{"jsonrpc":"2.0","id":"","result":{"genesis":{"genesis_time":"2026-11-13T06:37:55.480778076Z","chain_id":"moulstaging-1","consensus_params":{"Block":{"MaxTxBytes":"1000000","MaxDataBytes":"2000000","MaxBlockBytes":"0","MaxGas":"10000000000","TimeIotaMS":"100"},"Validator":{"PubKeyTypeURLs":["/tm.PubKeyEd25519"]}},"validators":[{"address":"g1cq9jked3586zf8q3fx52xfu8wr4lfcx94px85n","pub_key":{"@type":"/tm.PubKeyEd25519","value":"ojyQF2/7PrlXPQoI2OMYL+LIl1ijh/J+9efKakG6kJE="},"power":"10","name":"self"}],"app_hash":null,"app_state":{"@type":"/gno.GenesisState","balances":["g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5=10000000000000ugnot","g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u=10000000000000ugnot"],"txs":[{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"ufmt","path":"gno.land/p/nt/ufmt/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `ufmt` - String formatting\n\nGno port of a subset of Go's `fmt` package (micro-fmt). Provides `Printf`, `Sprintf`, `Errorf` and friends for formatting strings with verb-based templates.\n\n## Usage\n\n```go\nimport \"gno.land/p/nt/ufmt/v0\"\n\ns := ufmt.Sprintf(\"hello %s, you are %d years old\", \"alice\", 30)\n// \"hello alice, you are 30 years old\"\n\nerr := ufmt.Errorf(\"invalid id: %q\", input)\n\nvar buf bytes.Buffer\nufmt.Fprintf(\u0026buf, \"balance: %d\", amount)\n\nline := ufmt.Sprintln(\"token\", symbol, \"transferred\") // adds spaces + newline\n```\n\n## API\n\n```go\n// Format and return a string.\nfunc Sprint(a ...any) string\nfunc Sprintf(format string, a ...any) string\nfunc Sprintln(a ...any) string\n\n// Format and write to an io.Writer.\nfunc Fprint(w io.Writer, a ...any) (n int, err error)\nfunc Fprintf(w io.Writer, format string, a ...any) (n int, err error)\nfunc Fprintln(w io.Writer, a ...any) (n int, err error)\n\n// Format and print to standard output.\nfunc Print(a ...any) (n int, err error)\nfunc Printf(format string, a ...any) (n int, err error)\nfunc Println(a ...any) (n int, err error)\n\n// Format and append to a byte slice.\nfunc Append(b []byte, a ...any) []byte\nfunc Appendf(b []byte, format string, a ...any) []byte\nfunc Appendln(b []byte, a ...any) []byte\n\n// Format and return an error.\nfunc Errorf(format string, args ...any) error\n```\n\n## Supported verbs\n\n| Verb | Meaning                                                                |\n|------|------------------------------------------------------------------------|\n| `%s` | String. Uses `String()` or `Error()` if implemented.                   |\n| `%d` | Integer (signed and unsigned, all widths).                             |\n| `%c` | Unicode character from rune/int code point.                            |\n| `%t` | Boolean: `true` or `false`.                                            |\n| `%q` | Double-quoted, escaped string.                                         |\n| `%x` | Hexadecimal (uint8 only).                                              |\n| `%f` / `%F` | Decimal float; default precision 6.                             |\n| `%e` / `%E` | Scientific notation float; default precision 2.                 |\n| `%g` / `%G` | Float, compact representation.                                  |\n| `%T` | Type name of the argument (basic types only).                          |\n| `%v` | Default representation appropriate for the value's type.               |\n| `%%` | Literal `%`.                                                           |\n\nWidth (`%5s`) and precision (`%.2f`) are supported for the relevant verbs.\n\n## Notes\n\n- Verb/type mismatches produce `%!verb(type=value)` strings, matching Go's `fmt` behaviour.\n- Missing or extra arguments panic.\n- Not supported: `%b`, `%o`, `%U`, `%p`, `%+v`, `%#v`, argument indexing, flags like `-`, `+`, `#`, `0`.\n- `Print*` writes via the built-in `print` (stdout substitute) until `os.Stdout` is available.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package ufmt provides utility functions for formatting strings, similarly to\n// the Go package \"fmt\", of which only a subset is currently supported.\npackage ufmt\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/ufmt/v0\"\ngno = \"0.9\"\n"},{"name":"ufmt.gno","body":"// Package ufmt provides utility functions for formatting strings, similarly to\n// the Go package \"fmt\", of which only a subset is currently supported (hence\n// the name µfmt - micro fmt). It includes functions like Printf, Sprintf,\n// Fprintf, and Errorf.\n// Supported formatting verbs are documented in the Sprintf function.\npackage ufmt\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode/utf8\"\n)\n\n// buffer accumulates formatted output as a byte slice.\ntype buffer []byte\n\nfunc (b *buffer) write(p []byte) {\n\t*b = append(*b, p...)\n}\n\nfunc (b *buffer) writeString(s string) {\n\t*b = append(*b, s...)\n}\n\nfunc (b *buffer) writeByte(c byte) {\n\t*b = append(*b, c)\n}\n\nfunc (b *buffer) writeRune(r rune) {\n\t*b = utf8.AppendRune(*b, r)\n}\n\n// printer holds state for formatting operations.\ntype printer struct {\n\tbuf buffer\n}\n\nfunc newPrinter() *printer {\n\treturn \u0026printer{}\n}\n\n// Sprint formats using the default formats for its operands and returns the resulting string.\n// Sprint writes the given arguments with spaces between arguments.\nfunc Sprint(a ...any) string {\n\tp := newPrinter()\n\tp.doPrint(a)\n\treturn string(p.buf)\n}\n\n// doPrint formats arguments using default formats and writes to printer's buffer.\n// Spaces are added between arguments.\nfunc (p *printer) doPrint(args []any) {\n\tfor argNum, arg := range args {\n\t\tif argNum \u003e 0 {\n\t\t\tp.buf.writeRune(' ')\n\t\t}\n\n\t\tswitch v := arg.(type) {\n\t\tcase string:\n\t\t\tp.buf.writeString(v)\n\t\tcase (interface{ String() string }):\n\t\t\tp.buf.writeString(v.String())\n\t\tcase error:\n\t\t\tp.buf.writeString(v.Error())\n\t\tcase float64:\n\t\t\tp.buf.writeString(Sprintf(\"%f\", v))\n\t\tcase int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:\n\t\t\tp.buf.writeString(Sprintf(\"%d\", v))\n\t\tcase bool:\n\t\t\tif v {\n\t\t\t\tp.buf.writeString(\"true\")\n\t\t\t} else {\n\t\t\t\tp.buf.writeString(\"false\")\n\t\t\t}\n\t\tcase nil:\n\t\t\tp.buf.writeString(\"\u003cnil\u003e\")\n\t\tdefault:\n\t\t\tp.buf.writeString(\"(unhandled)\")\n\t\t}\n\t}\n}\n\n// doPrintln appends a newline after formatting arguments with doPrint.\nfunc (p *printer) doPrintln(a []any) {\n\tp.doPrint(a)\n\tp.buf.writeByte('\\n')\n}\n\n// Sprintf offers similar functionality to Go's fmt.Sprintf, or the sprintf\n// equivalent available in many languages, including C/C++.\n// The number of args passed must exactly match the arguments consumed by the format.\n// A limited number of formatting verbs and features are currently supported.\n//\n// Supported verbs:\n//\n//\t%s: Places a string value directly.\n//\t    If the value implements the interface interface{ String() string },\n//\t    the String() method is called to retrieve the value. Same about Error()\n//\t    string.\n//\t%c: Formats the character represented by Unicode code point\n//\t%d: Formats an integer value using package \"strconv\".\n//\t    Currently supports only uint, uint64, int, int64.\n//\t%f: Formats a float value, with a default precision of 6.\n//\t%e: Formats a float with scientific notation; 1.23456e+78\n//\t%E: Formats a float with scientific notation; 1.23456E+78\n//\t%F: The same as %f\n//\t%g: Formats a float value with %e for large exponents, and %f with full precision for smaller numbers\n//\t%G: Formats a float value with %G for large exponents, and %F with full precision for smaller numbers\n//\t%t: Formats a boolean value to \"true\" or \"false\".\n//\t%x: Formats an integer value as a hexadecimal string.\n//\t    Currently supports only uint8, []uint8, [32]uint8.\n//\t%c: Formats a rune value as a string.\n//\t    Currently supports only rune, int.\n//\t%q: Formats a string value as a quoted string.\n//\t%T: Formats the type of the value.\n//\t%v: Formats the value with a default representation appropriate for the value's type\n//\t    - nil: \u003cnil\u003e\n//\t    - bool: true/false\n//\t    - integers: base 10\n//\t    - float64: %g format\n//\t    - string: verbatim\n//\t    - types with String()/Error(): method result\n//\t    - others: (unhandled)\n//\t%%: Outputs a literal %. Does not consume an argument.\n//\n// Unsupported verbs or type mismatches produce error strings like \"%!d(string=foo)\".\nfunc Sprintf(format string, a ...any) string {\n\tp := newPrinter()\n\tp.doPrintf(format, a)\n\treturn string(p.buf)\n}\n\n// doPrintf parses the format string and writes formatted arguments to the buffer.\nfunc (p *printer) doPrintf(format string, args []any) {\n\tsTor := []rune(format)\n\tend := len(sTor)\n\targNum := 0\n\targLen := len(args)\n\n\tfor i := 0; i \u003c end; {\n\t\tisLast := i == end-1\n\t\tc := sTor[i]\n\n\t\tif isLast || c != '%' {\n\t\t\t// we don't check for invalid format like a one ending with \"%\"\n\t\t\tp.buf.writeRune(c)\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\n\t\tlength := -1\n\t\tprecision := -1\n\t\ti++ // skip '%'\n\n\t\tdigits := func() string {\n\t\t\tstart := i\n\t\t\tfor i \u003c end \u0026\u0026 sTor[i] \u003e= '0' \u0026\u0026 sTor[i] \u003c= '9' {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tif i \u003e start {\n\t\t\t\treturn string(sTor[start:i])\n\t\t\t}\n\t\t\treturn \"\"\n\t\t}\n\n\t\tif l := digits(); l != \"\" {\n\t\t\tvar err error\n\t\t\tlength, err = strconv.Atoi(l)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"ufmt: invalid length specification\")\n\t\t\t}\n\t\t}\n\n\t\tif i \u003c end \u0026\u0026 sTor[i] == '.' {\n\t\t\ti++ // skip '.'\n\t\t\tif l := digits(); l != \"\" {\n\t\t\t\tvar err error\n\t\t\t\tprecision, err = strconv.Atoi(l)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(\"ufmt: invalid precision specification\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif i \u003e= end {\n\t\t\tpanic(\"ufmt: invalid format string\")\n\t\t}\n\n\t\tverb := sTor[i]\n\t\tif verb == '%' {\n\t\t\tp.buf.writeRune('%')\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\n\t\tif argNum \u003e= argLen {\n\t\t\tpanic(\"ufmt: not enough arguments\")\n\t\t}\n\t\targ := args[argNum]\n\t\targNum++\n\n\t\tswitch verb {\n\t\tcase 'v':\n\t\t\twriteValue(p, verb, arg)\n\t\tcase 's':\n\t\t\twriteStringWithLength(p, verb, arg, length)\n\t\tcase 'c':\n\t\t\twriteChar(p, verb, arg)\n\t\tcase 'd':\n\t\t\twriteInt(p, verb, arg)\n\t\tcase 'e', 'E', 'f', 'F', 'g', 'G':\n\t\t\twriteFloatWithPrecision(p, verb, arg, precision)\n\t\tcase 't':\n\t\t\twriteBool(p, verb, arg)\n\t\tcase 'x':\n\t\t\twriteHex(p, verb, arg)\n\t\tcase 'q':\n\t\t\twriteQuotedString(p, verb, arg)\n\t\tcase 'T':\n\t\t\twriteType(p, arg)\n\t\t// % handled before, as it does not consume an argument\n\t\tdefault:\n\t\t\tp.buf.writeString(\"(unhandled verb: %\" + string(verb) + \")\")\n\t\t}\n\n\t\ti++\n\t}\n\n\tif argNum \u003c argLen {\n\t\tpanic(\"ufmt: too many arguments\")\n\t}\n}\n\n// writeValue handles %v formatting\nfunc writeValue(p *printer, verb rune, arg any) {\n\tswitch v := arg.(type) {\n\tcase nil:\n\t\tp.buf.writeString(\"\u003cnil\u003e\")\n\tcase bool:\n\t\twriteBool(p, verb, v)\n\tcase int:\n\t\tp.buf.writeString(strconv.Itoa(v))\n\tcase int8:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase int16:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase int32:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase int64:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase uint:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint8:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint16:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint32:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint64:\n\t\tp.buf.writeString(strconv.FormatUint(v, 10))\n\tcase float64:\n\t\tp.buf.writeString(strconv.FormatFloat(v, 'g', -1, 64))\n\tcase string:\n\t\tp.buf.writeString(v)\n\tcase []byte:\n\t\tp.buf.write(v)\n\tcase []rune:\n\t\tp.buf.writeString(string(v))\n\tcase (interface{ String() string }):\n\t\tp.buf.writeString(v.String())\n\tcase error:\n\t\tp.buf.writeString(v.Error())\n\tdefault:\n\t\tp.buf.writeString(fallback(verb, v))\n\t}\n}\n\n// writeStringWithLength handles %s formatting with length specification\nfunc writeStringWithLength(p *printer, verb rune, arg any, length int) {\n\tvar s string\n\tswitch v := arg.(type) {\n\tcase (interface{ String() string }):\n\t\ts = v.String()\n\tcase error:\n\t\ts = v.Error()\n\tcase string:\n\t\ts = v\n\tdefault:\n\t\ts = fallback(verb, v)\n\t}\n\n\tif length \u003e 0 \u0026\u0026 len(s) \u003c length {\n\t\ts = strings.Repeat(\" \", length-len(s)) + s\n\t}\n\tp.buf.writeString(s)\n}\n\n// writeChar handles %c formatting\nfunc writeChar(p *printer, verb rune, arg any) {\n\tswitch v := arg.(type) {\n\t// rune is int32. Exclude overflowing numeric types and dups (byte, int32):\n\tcase rune:\n\t\tp.buf.writeString(string(v))\n\tcase int:\n\t\tp.buf.writeRune(rune(v))\n\tcase int8:\n\t\tp.buf.writeRune(rune(v))\n\tcase int16:\n\t\tp.buf.writeRune(rune(v))\n\tcase uint:\n\t\tp.buf.writeRune(rune(v))\n\tcase uint8:\n\t\tp.buf.writeRune(rune(v))\n\tcase uint16:\n\t\tp.buf.writeRune(rune(v))\n\tdefault:\n\t\tp.buf.writeString(fallback(verb, v))\n\t}\n}\n\n// writeInt handles %d formatting\nfunc writeInt(p *printer, verb rune, arg any) {\n\tswitch v := arg.(type) {\n\tcase int:\n\t\tp.buf.writeString(strconv.Itoa(v))\n\tcase int8:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase int16:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase int32:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase int64:\n\t\tp.buf.writeString(strconv.Itoa(int(v)))\n\tcase uint:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint8:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint16:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint32:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 10))\n\tcase uint64:\n\t\tp.buf.writeString(strconv.FormatUint(v, 10))\n\tdefault:\n\t\tp.buf.writeString(fallback(verb, v))\n\t}\n}\n\n// writeFloatWithPrecision handles floating-point formatting with precision\nfunc writeFloatWithPrecision(p *printer, verb rune, arg any, precision int) {\n\tswitch v := arg.(type) {\n\tcase float64:\n\t\tformat := byte(verb)\n\t\tif format == 'F' {\n\t\t\tformat = 'f'\n\t\t}\n\t\tif precision \u003c 0 {\n\t\t\tswitch format {\n\t\t\tcase 'e', 'E':\n\t\t\t\tprecision = 2\n\t\t\tdefault:\n\t\t\t\tprecision = 6\n\t\t\t}\n\t\t}\n\t\tp.buf = strconv.AppendFloat(p.buf, v, format, precision, 64)\n\tdefault:\n\t\tp.buf.writeString(fallback(verb, v))\n\t}\n}\n\n// writeBool handles %t formatting\nfunc writeBool(p *printer, verb rune, arg any) {\n\tswitch v := arg.(type) {\n\tcase bool:\n\t\tif v {\n\t\t\tp.buf.writeString(\"true\")\n\t\t} else {\n\t\t\tp.buf.writeString(\"false\")\n\t\t}\n\tdefault:\n\t\tp.buf.writeString(fallback(verb, v))\n\t}\n}\n\n// writeHex handles %x formatting\nfunc writeHex(p *printer, verb rune, arg any) {\n\tswitch v := arg.(type) {\n\tcase uint8:\n\t\tp.buf.writeString(strconv.FormatUint(uint64(v), 16))\n\tdefault:\n\t\tp.buf.writeString(\"(unhandled)\")\n\t}\n}\n\n// writeQuotedString handles %q formatting\nfunc writeQuotedString(p *printer, verb rune, arg any) {\n\tswitch v := arg.(type) {\n\tcase string:\n\t\tp.buf.writeString(strconv.Quote(v))\n\tdefault:\n\t\tp.buf.writeString(\"(unhandled)\")\n\t}\n}\n\n// writeType handles %T formatting\nfunc writeType(p *printer, arg any) {\n\tswitch arg.(type) {\n\tcase bool:\n\t\tp.buf.writeString(\"bool\")\n\tcase int:\n\t\tp.buf.writeString(\"int\")\n\tcase int8:\n\t\tp.buf.writeString(\"int8\")\n\tcase int16:\n\t\tp.buf.writeString(\"int16\")\n\tcase int32:\n\t\tp.buf.writeString(\"int32\")\n\tcase int64:\n\t\tp.buf.writeString(\"int64\")\n\tcase uint:\n\t\tp.buf.writeString(\"uint\")\n\tcase uint8:\n\t\tp.buf.writeString(\"uint8\")\n\tcase uint16:\n\t\tp.buf.writeString(\"uint16\")\n\tcase uint32:\n\t\tp.buf.writeString(\"uint32\")\n\tcase uint64:\n\t\tp.buf.writeString(\"uint64\")\n\tcase string:\n\t\tp.buf.writeString(\"string\")\n\tcase []byte:\n\t\tp.buf.writeString(\"[]byte\")\n\tcase []rune:\n\t\tp.buf.writeString(\"[]rune\")\n\tdefault:\n\t\tp.buf.writeString(\"unknown\")\n\t}\n}\n\n// Fprintf formats according to a format specifier and writes to w.\n// Returns the number of bytes written and any write error encountered.\nfunc Fprintf(w io.Writer, format string, a ...any) (n int, err error) {\n\tp := newPrinter()\n\tp.doPrintf(format, a)\n\treturn w.Write(p.buf)\n}\n\n// Printf formats according to a format specifier and writes to standard output.\n// Returns the number of bytes written and any write error encountered.\n//\n// XXX: Replace with os.Stdout handling when available.\nfunc Printf(format string, a ...any) (n int, err error) {\n\tvar out strings.Builder\n\tn, err = Fprintf(\u0026out, format, a...)\n\tprint(out.String())\n\treturn n, err\n}\n\n// Appendf formats according to a format specifier, appends the result to the byte\n// slice, and returns the updated slice.\nfunc Appendf(b []byte, format string, a ...any) []byte {\n\tp := newPrinter()\n\tp.doPrintf(format, a)\n\treturn append(b, p.buf...)\n}\n\n// Fprint formats using default formats and writes to w.\n// Spaces are added between arguments.\n// Returns the number of bytes written and any write error encountered.\nfunc Fprint(w io.Writer, a ...any) (n int, err error) {\n\tp := newPrinter()\n\tp.doPrint(a)\n\treturn w.Write(p.buf)\n}\n\n// Print formats using default formats and writes to standard output.\n// Spaces are added between arguments.\n// Returns the number of bytes written and any write error encountered.\n//\n// XXX: Replace with os.Stdout handling when available.\nfunc Print(a ...any) (n int, err error) {\n\tvar out strings.Builder\n\tn, err = Fprint(\u0026out, a...)\n\tprint(out.String())\n\treturn n, err\n}\n\n// Append formats using default formats, appends to b, and returns the updated slice.\n// Spaces are added between arguments.\nfunc Append(b []byte, a ...any) []byte {\n\tp := newPrinter()\n\tp.doPrint(a)\n\treturn append(b, p.buf...)\n}\n\n// Fprintln formats using default formats and writes to w with newline.\n// Returns the number of bytes written and any write error encountered.\nfunc Fprintln(w io.Writer, a ...any) (n int, err error) {\n\tp := newPrinter()\n\tp.doPrintln(a)\n\treturn w.Write(p.buf)\n}\n\n// Println formats using default formats and writes to standard output with newline.\n// Returns the number of bytes written and any write error encountered.\n//\n// XXX: Replace with os.Stdout handling when available.\nfunc Println(a ...any) (n int, err error) {\n\tvar out strings.Builder\n\tn, err = Fprintln(\u0026out, a...)\n\tprint(out.String())\n\treturn n, err\n}\n\n// Sprintln formats using default formats and returns the string with newline.\n// Spaces are always added between arguments.\nfunc Sprintln(a ...any) string {\n\tp := newPrinter()\n\tp.doPrintln(a)\n\treturn string(p.buf)\n}\n\n// Appendln formats using default formats, appends to b, and returns the updated slice.\n// Appends a newline after the last argument.\nfunc Appendln(b []byte, a ...any) []byte {\n\tp := newPrinter()\n\tp.doPrintln(a)\n\treturn append(b, p.buf...)\n}\n\n// This function is used to mimic Go's fmt.Sprintf\n// specific behaviour of showing verb/type mismatches,\n// where for example:\n//\n//\tfmt.Sprintf(\"%d\", \"foo\") gives \"%!d(string=foo)\"\n//\n// Here:\n//\n//\tfallback(\"s\", 8) -\u003e \"%!s(int=8)\"\n//\tfallback(\"d\", nil) -\u003e \"%!d(\u003cnil\u003e)\", and so on.f\nfunc fallback(verb rune, arg any) string {\n\tvar s string\n\tswitch v := arg.(type) {\n\tcase string:\n\t\ts = \"string=\" + v\n\tcase (interface{ String() string }):\n\t\ts = \"string=\" + v.String()\n\tcase error:\n\t\t// note: also \"string=\" in Go fmt\n\t\ts = \"string=\" + v.Error()\n\tcase float64:\n\t\ts = \"float64=\" + Sprintf(\"%f\", v)\n\tcase int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:\n\t\t// note: rune, byte would be dups, being aliases\n\t\tif typename, e := typeToString(v); e == nil {\n\t\t\ts = typename + \"=\" + Sprintf(\"%d\", v)\n\t\t} else {\n\t\t\tpanic(\"ufmt: unexpected type error\")\n\t\t}\n\tcase bool:\n\t\ts = \"bool=\" + strconv.FormatBool(v)\n\tcase nil:\n\t\ts = \"\u003cnil\u003e\"\n\tdefault:\n\t\ts = \"(unhandled)\"\n\t}\n\treturn \"%!\" + string(verb) + \"(\" + s + \")\"\n}\n\n// typeToString returns the name of basic Go types as string.\nfunc typeToString(v any) (string, error) {\n\tswitch v.(type) {\n\tcase string:\n\t\treturn \"string\", nil\n\tcase int:\n\t\treturn \"int\", nil\n\tcase int8:\n\t\treturn \"int8\", nil\n\tcase int16:\n\t\treturn \"int16\", nil\n\tcase int32:\n\t\treturn \"int32\", nil\n\tcase int64:\n\t\treturn \"int64\", nil\n\tcase uint:\n\t\treturn \"uint\", nil\n\tcase uint8:\n\t\treturn \"uint8\", nil\n\tcase uint16:\n\t\treturn \"uint16\", nil\n\tcase uint32:\n\t\treturn \"uint32\", nil\n\tcase uint64:\n\t\treturn \"uint64\", nil\n\tcase float32:\n\t\treturn \"float32\", nil\n\tcase float64:\n\t\treturn \"float64\", nil\n\tcase bool:\n\t\treturn \"bool\", nil\n\tdefault:\n\t\treturn \"\", errors.New(\"unsupported type\")\n\t}\n}\n\n// errMsg implements the error interface for formatted error strings.\ntype errMsg struct {\n\tmsg string\n}\n\n// Error returns the formatted error message.\nfunc (e *errMsg) Error() string {\n\treturn e.msg\n}\n\n// Errorf formats according to a format specifier and returns an error value.\n// Supports the same verbs as Sprintf. See Sprintf documentation for details.\nfunc Errorf(format string, args ...any) error {\n\treturn \u0026errMsg{Sprintf(format, args...)}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"subtests","path":"gno.land/r/tests/vm/subtests","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/subtests\"\ngno = \"0.9\"\n"},{"name":"subtests.gno","body":"package subtests\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n)\n\nfunc GetCurrentRealm(cur realm) runtime.Realm {\n\treturn unsafe.CurrentRealm()\n}\n\nfunc GetPreviousRealm(cur realm) runtime.Realm {\n\treturn unsafe.PreviousRealm()\n}\n\nfunc Exec(fn func()) {\n\tfn()\n}\n\nfunc CallAssertOriginCall(cur realm) {\n\truntime.AssertOriginCall()\n}\n\nfunc CallIsOriginCall(cur realm) bool {\n\treturn unsafe.PreviousRealm().IsUser()\n}\n\nfunc BankerOriginSend(cur realm) string {\n\treturn unsafe.OriginSend().String()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"avl","path":"gno.land/p/nt/avl/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `avl` - Gas-efficient AVL tree\n\nA self-balancing AVL tree for storing key-value data in Gno realms. Each node is persisted as a separate object, so operations only load `O(log n)` nodes from storage instead of the entire collection.\n\n## Usage\n\n```go\npackage myrealm\n\nimport \"gno.land/p/nt/avl/v0\"\n\n// Persisted across transactions.\nvar tree avl.Tree\n\nfunc Set(key string, value int) {\n    tree.Set(key, value)\n}\n\nfunc Get(key string) int {\n    // Get returns nil for an absent key. A stored nil value looks the same,\n    // so use Has when you must tell absent from present-but-nil.\n    raw := tree.Get(key)\n    if raw == nil {\n        panic(\"not found\")\n    }\n    return raw.(int)\n}\n\n// Iterate a bounded key range, stopping early when possible. Iterating\n// the whole tree with (\"\", \"\") loads every node (O(n) storage reads);\n// for large or user-growable trees, paginate with the pager subpackage.\nfunc ListRange(start, end string) {\n    tree.Iterate(start, end, func(key string, value any) bool {\n        // return true to stop early\n        return false\n    })\n}\n```\n\n## API\n\n```go\ntype Tree struct{ /* unexported */ }\n\nfunc NewTree() *Tree\n\n// Read\nfunc (t *Tree) Size() int\nfunc (t *Tree) Has(key string) bool\nfunc (t *Tree) Get(key string) (value any) // nil if the key is absent\nfunc (t *Tree) GetByIndex(index int) (key string, value any)\nfunc (t *Tree) Iterate(start, end string, cb IterCbFn) bool\nfunc (t *Tree) ReverseIterate(start, end string, cb IterCbFn) bool\nfunc (t *Tree) IterateByOffset(offset, count int, cb IterCbFn) bool\nfunc (t *Tree) ReverseIterateByOffset(offset, count int, cb IterCbFn) bool\n\n// Write\nfunc (t *Tree) Set(key string, value any) (updated bool)\nfunc (t *Tree) Remove(key string) (value any, removed bool)\n\ntype IterCbFn func(key string, value any) bool\n\ntype ITree interface { /* same shape as Tree's methods */ }\n```\n\nThe zero value of `Tree` is a usable empty tree. `Get` returns `nil` for an absent key, so use `Has` to distinguish a stored `nil` value from a missing one. `Iterate` uses `[start, end)` (start inclusive, end exclusive); empty strings mean unbounded. Callbacks return `true` to stop early.\n\n## Notes\n\n- `avl.Tree` and `bptree` (`gno.land/p/nt/bptree/v0`) expose the same `ITree` interface; bptree swaps AVL balancing for a B+ layout with better cache locality. `seqid` (`gno.land/p/nt/seqid/v0`) generates ordered keys usable in either.\n- Never return the live `*Tree` from a realm getter: a caller can then call `Set`/`Remove` on it under your realm's authority (readonly taint does not block method dispatch). Return values, copies, or a read-only `rotree` view.\n\n## Subpackages\n\n- `gno.land/p/nt/avl/pager/v0` - pagination helper for trees and lists.\n- `gno.land/p/nt/avl/rotree/v0` - read-only view of a `Tree`.\n\n## Why AVL over Map?\n\nIn Gno, the choice between `avl.Tree` and `map` is about how data is persisted.\n\n**Maps** are stored as a single monolithic object. Accessing *any* value loads the *entire* map. A map with 1,000 entries loads all 1,000 on every read.\n\n**AVL trees** store each node as a separate object. Accessing a value loads only the nodes along the search path — `~log2(n)`. A tree with 1,000 entries loads ~10 nodes; a tree with 1,000,000 entries still loads only ~20.\n\n### Storage comparison (1,000 entries)\n\n**Map:**\n\n```\nObject :4 = map{\n  (\"0\" string):(\"123\" string),\n  (\"1\" string):(\"123\" string),\n  ...\n  (\"999\" string):(\"123\" string)\n}\n```\n- `map[\"100\"]` loads object `:4` — all 1,000 pairs.\n- Gas cost proportional to total map size.\n\n**AVL tree:**\n\n```\nObject :6  = Node{key=\"4\",   height=10, size=1000, left=:7,  right=...}\nObject :9  = Node{key=\"2\",   height=9,  size=334,  left=:10, right=...}\nObject :11 = Node{key=\"14\",  height=8,  size=112,  left=:12, right=...}\nObject :13 = Node{key=\"12\",  height=6,  size=46,   left=:14, right=...}\nObject :15 = Node{key=\"11\",  height=5,  size=24,   left=:16, right=...}\nObject :17 = Node{key=\"102\", height=4,  size=13,   left=:18, right=...}\nObject :19 = Node{key=\"100\", height=3,  size=5,    left=:30, right=...}\nObject :31 = Node{key=\"101\", height=1,  size=2,    left=:32, right=...}\nObject :33 = Node{key=\"100\", value=\"123\", height=0, size=1}\n```\n- `tree.Get(\"100\")` loads ~10 objects (the search path only).\n- Gas cost proportional to `log2(n)`.\n\n## Further reading\n\n- [Why should you use an AVL tree instead of a map?](https://howl.moe/posts/2024-09-19-gno-avl-over-maps/)\n- [Berty's AVL scalability report](https://github.com/gnolang/hackerspace/issues/67) - testing up to 20M entries\n- [Effective Gno - Choose storage types by access pattern](https://docs.gno.land/resources/effective-gno#choose-storage-types-by-access-pattern)\n- [Wikipedia - AVL tree](https://en.wikipedia.org/wiki/AVL_tree)\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package avl provides a gas-efficient AVL tree implementation for storing\n// key-value data in Gno realms.\npackage avl\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/avl/v0\"\ngno = \"0.9\"\n"},{"name":"node.gno","body":"package avl\n\n//----------------------------------------\n// Node\n\n// Node represents a node in an AVL tree.\ntype Node struct {\n\tkey       string // key is the unique identifier for the node.\n\tvalue     any    // value is the data stored in the node.\n\theight    int8   // height is the height of the node in the tree.\n\tsize      int    // size is the number of leaf nodes (key-value pairs) in the subtree rooted at this node.\n\tleftNode  *Node  // leftNode is the left child of the node.\n\trightNode *Node  // rightNode is the right child of the node.\n}\n\n// NewNode creates a new node with the given key and value.\nfunc NewNode(key string, value any) *Node {\n\treturn \u0026Node{\n\t\tkey:    key,\n\t\tvalue:  value,\n\t\theight: 0,\n\t\tsize:   1,\n\t}\n}\n\n// Size returns the size of the subtree rooted at the node.\nfunc (node *Node) Size() int {\n\tif node == nil {\n\t\treturn 0\n\t}\n\treturn node.size\n}\n\n// IsLeaf checks if the node is a leaf node (has no children).\nfunc (node *Node) IsLeaf() bool {\n\treturn node.height == 0\n}\n\n// Key returns the key of the node.\nfunc (node *Node) Key() string {\n\treturn node.key\n}\n\n// Value returns the value of the node.\nfunc (node *Node) Value() any {\n\treturn node.value\n}\n\nfunc (node *Node) _copy() *Node {\n\tif node.height == 0 {\n\t\tpanic(\"Why are you copying a value node?\")\n\t}\n\treturn \u0026Node{\n\t\tkey:       node.key,\n\t\theight:    node.height,\n\t\tsize:      node.size,\n\t\tleftNode:  node.leftNode,\n\t\trightNode: node.rightNode,\n\t}\n}\n\n// Has checks if a node with the given key exists in the subtree rooted at the node.\nfunc (node *Node) Has(key string) (has bool) {\n\tif node == nil {\n\t\treturn false\n\t}\n\tif node.key == key {\n\t\treturn true\n\t}\n\tif node.height == 0 {\n\t\treturn false\n\t} else {\n\t\tif key \u003c node.key {\n\t\t\treturn node.getLeftNode().Has(key)\n\t\t} else {\n\t\t\treturn node.getRightNode().Has(key)\n\t\t}\n\t}\n}\n\n// Get searches for a node with the given key in the subtree rooted at the node\n// and returns its index, value, and whether it exists.\nfunc (node *Node) Get(key string) (index int, value any, exists bool) {\n\tif node == nil {\n\t\treturn 0, nil, false\n\t}\n\n\tif node.height == 0 {\n\t\tif node.key == key {\n\t\t\treturn 0, node.value, true\n\t\t} else if node.key \u003c key {\n\t\t\treturn 1, nil, false\n\t\t} else {\n\t\t\treturn 0, nil, false\n\t\t}\n\t} else {\n\t\tif key \u003c node.key {\n\t\t\treturn node.getLeftNode().Get(key)\n\t\t} else {\n\t\t\trightNode := node.getRightNode()\n\t\t\tindex, value, exists = rightNode.Get(key)\n\t\t\tindex += node.size - rightNode.size\n\t\t\treturn index, value, exists\n\t\t}\n\t}\n}\n\n// GetByIndex retrieves the key-value pair of the node at the given index\n// in the subtree rooted at the node.\nfunc (node *Node) GetByIndex(index int) (key string, value any) {\n\tif index \u003c 0 {\n\t\tpanic(\"GetByIndex: negative index not allowed\")\n\t}\n\n\tif node.height == 0 {\n\t\tif index != 0 {\n\t\t\tpanic(\"GetByIndex asked for invalid index\")\n\t\t}\n\t\treturn node.key, node.value\n\t} else {\n\t\t// TODO: could improve this by storing the sizes\n\t\tleftNode := node.getLeftNode()\n\t\tif index \u003c leftNode.size {\n\t\t\treturn leftNode.GetByIndex(index)\n\t\t} else {\n\t\t\treturn node.getRightNode().GetByIndex(index - leftNode.size)\n\t\t}\n\t}\n}\n\n// Set inserts a new node with the given key-value pair into the subtree rooted at the node,\n// and returns the new root of the subtree and whether an existing node was updated.\n//\n// XXX consider a better way to do this... perhaps split Node from Node.\nfunc (node *Node) Set(key string, value any) (newSelf *Node, updated bool) {\n\tif node == nil {\n\t\treturn NewNode(key, value), false\n\t}\n\tif node.height == 0 {\n\t\tif key \u003c node.key {\n\t\t\treturn \u0026Node{\n\t\t\t\tkey:       node.key,\n\t\t\t\theight:    1,\n\t\t\t\tsize:      2,\n\t\t\t\tleftNode:  NewNode(key, value),\n\t\t\t\trightNode: node,\n\t\t\t}, false\n\t\t} else if key == node.key {\n\t\t\treturn NewNode(key, value), true\n\t\t} else {\n\t\t\treturn \u0026Node{\n\t\t\t\tkey:       key,\n\t\t\t\theight:    1,\n\t\t\t\tsize:      2,\n\t\t\t\tleftNode:  node,\n\t\t\t\trightNode: NewNode(key, value),\n\t\t\t}, false\n\t\t}\n\t} else {\n\t\tnode = node._copy()\n\t\tif key \u003c node.key {\n\t\t\tnode.leftNode, updated = node.getLeftNode().Set(key, value)\n\t\t} else {\n\t\t\tnode.rightNode, updated = node.getRightNode().Set(key, value)\n\t\t}\n\t\tif updated {\n\t\t\treturn node, updated\n\t\t} else {\n\t\t\tnode.calcHeightAndSize()\n\t\t\treturn node.balance(), updated\n\t\t}\n\t}\n}\n\n// Remove deletes the node with the given key from the subtree rooted at the node.\n// returns the new root of the subtree, the new leftmost leaf key (if changed),\n// the removed value and the removal was successful.\nfunc (node *Node) Remove(key string) (\n\tnewNode *Node, newKey string, value any, removed bool,\n) {\n\tif node == nil {\n\t\treturn nil, \"\", nil, false\n\t}\n\tif node.height == 0 {\n\t\tif key == node.key {\n\t\t\treturn nil, \"\", node.value, true\n\t\t} else {\n\t\t\treturn node, \"\", nil, false\n\t\t}\n\t} else {\n\t\tif key \u003c node.key {\n\t\t\tvar newLeftNode *Node\n\t\t\tnewLeftNode, newKey, value, removed = node.getLeftNode().Remove(key)\n\t\t\tif !removed {\n\t\t\t\treturn node, \"\", value, false\n\t\t\t} else if newLeftNode == nil { // left node held value, was removed\n\t\t\t\treturn node.rightNode, node.key, value, true\n\t\t\t}\n\t\t\tnode = node._copy()\n\t\t\tnode.leftNode = newLeftNode\n\t\t\tnode.calcHeightAndSize()\n\t\t\tnode = node.balance()\n\t\t\treturn node, newKey, value, true\n\t\t} else {\n\t\t\tvar newRightNode *Node\n\t\t\tnewRightNode, newKey, value, removed = node.getRightNode().Remove(key)\n\t\t\tif !removed {\n\t\t\t\treturn node, \"\", value, false\n\t\t\t} else if newRightNode == nil { // right node held value, was removed\n\t\t\t\treturn node.leftNode, \"\", value, true\n\t\t\t}\n\t\t\tnode = node._copy()\n\t\t\tnode.rightNode = newRightNode\n\t\t\tif newKey != \"\" {\n\t\t\t\tnode.key = newKey\n\t\t\t}\n\t\t\tnode.calcHeightAndSize()\n\t\t\tnode = node.balance()\n\t\t\treturn node, \"\", value, true\n\t\t}\n\t}\n}\n\nfunc (node *Node) getLeftNode() *Node {\n\treturn node.leftNode\n}\n\nfunc (node *Node) getRightNode() *Node {\n\treturn node.rightNode\n}\n\n// rotateRight performs a right rotation on the node and returns the new root.\n// NOTE: overwrites node\n// TODO: optimize balance \u0026 rotate\nfunc (node *Node) rotateRight() *Node {\n\tnode = node._copy()\n\tl := node.getLeftNode()\n\t_l := l._copy()\n\n\t_lrCached := _l.rightNode\n\t_l.rightNode = node\n\tnode.leftNode = _lrCached\n\n\tnode.calcHeightAndSize()\n\t_l.calcHeightAndSize()\n\n\treturn _l\n}\n\n// rotateLeft performs a left rotation on the node and returns the new root.\n// NOTE: overwrites node\n// TODO: optimize balance \u0026 rotate\nfunc (node *Node) rotateLeft() *Node {\n\tnode = node._copy()\n\tr := node.getRightNode()\n\t_r := r._copy()\n\n\t_rlCached := _r.leftNode\n\t_r.leftNode = node\n\tnode.rightNode = _rlCached\n\n\tnode.calcHeightAndSize()\n\t_r.calcHeightAndSize()\n\n\treturn _r\n}\n\n// calcHeightAndSize updates the height and size of the node based on its children.\n// NOTE: mutates height and size\nfunc (node *Node) calcHeightAndSize() {\n\tnode.height = maxInt8(node.getLeftNode().height, node.getRightNode().height) + 1\n\tnode.size = node.getLeftNode().size + node.getRightNode().size\n}\n\n// calcBalance calculates the balance factor of the node.\nfunc (node *Node) calcBalance() int {\n\treturn int(node.getLeftNode().height) - int(node.getRightNode().height)\n}\n\n// balance balances the subtree rooted at the node and returns the new root.\n// NOTE: assumes that node can be modified\n// TODO: optimize balance \u0026 rotate\nfunc (node *Node) balance() (newSelf *Node) {\n\tbalance := node.calcBalance()\n\tif balance \u003e 1 {\n\t\tif node.getLeftNode().calcBalance() \u003e= 0 {\n\t\t\t// Left Left Case\n\t\t\treturn node.rotateRight()\n\t\t} else {\n\t\t\t// Left Right Case\n\t\t\tleft := node.getLeftNode()\n\t\t\tnode.leftNode = left.rotateLeft()\n\t\t\treturn node.rotateRight()\n\t\t}\n\t}\n\tif balance \u003c -1 {\n\t\tif node.getRightNode().calcBalance() \u003c= 0 {\n\t\t\t// Right Right Case\n\t\t\treturn node.rotateLeft()\n\t\t} else {\n\t\t\t// Right Left Case\n\t\t\tright := node.getRightNode()\n\t\t\tnode.rightNode = right.rotateRight()\n\t\t\treturn node.rotateLeft()\n\t\t}\n\t}\n\t// Nothing changed\n\treturn node\n}\n\n// Shortcut for TraverseInRange.\nfunc (node *Node) Iterate(start, end string, cb func(*Node) bool) bool {\n\treturn node.TraverseInRange(start, end, true, true, cb)\n}\n\n// Shortcut for TraverseInRange.\nfunc (node *Node) ReverseIterate(start, end string, cb func(*Node) bool) bool {\n\treturn node.TraverseInRange(start, end, false, true, cb)\n}\n\n// TraverseInRange traverses all nodes, including inner nodes.\n// Start is inclusive and end is exclusive when ascending,\n// Start and end are inclusive when descending.\n// Empty start and empty end denote no start and no end.\n// If leavesOnly is true, only visit leaf nodes.\n// NOTE: To simulate an exclusive reverse traversal,\n// just append 0x00 to start.\nfunc (node *Node) TraverseInRange(start, end string, ascending bool, leavesOnly bool, cb func(*Node) bool) bool {\n\tif node == nil {\n\t\treturn false\n\t}\n\tafterStart := (start == \"\" || start \u003c node.key)\n\tstartOrAfter := (start == \"\" || start \u003c= node.key)\n\tbeforeEnd := false\n\tif ascending {\n\t\tbeforeEnd = (end == \"\" || node.key \u003c end)\n\t} else {\n\t\tbeforeEnd = (end == \"\" || node.key \u003c= end)\n\t}\n\n\t// Run callback per inner/leaf node.\n\tstop := false\n\tif (!node.IsLeaf() \u0026\u0026 !leavesOnly) ||\n\t\t(node.IsLeaf() \u0026\u0026 startOrAfter \u0026\u0026 beforeEnd) {\n\t\tstop = cb(node)\n\t\tif stop {\n\t\t\treturn stop\n\t\t}\n\t}\n\tif node.IsLeaf() {\n\t\treturn stop\n\t}\n\n\tif ascending {\n\t\t// check lower nodes, then higher\n\t\tif afterStart {\n\t\t\tstop = node.getLeftNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t\tif stop {\n\t\t\treturn stop\n\t\t}\n\t\tif beforeEnd {\n\t\t\tstop = node.getRightNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t} else {\n\t\t// check the higher nodes first\n\t\tif beforeEnd {\n\t\t\tstop = node.getRightNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t\tif stop {\n\t\t\treturn stop\n\t\t}\n\t\tif afterStart {\n\t\t\tstop = node.getLeftNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t}\n\n\treturn stop\n}\n\n// TraverseByOffset traverses all nodes, including inner nodes.\n// A limit of math.MaxInt means no limit.\nfunc (node *Node) TraverseByOffset(offset, limit int, ascending bool, leavesOnly bool, cb func(*Node) bool) bool {\n\tif node == nil {\n\t\treturn false\n\t}\n\n\t// Clamp negative offset to 0; otherwise `delta := first.size - offset`\n\t// over-counts and silently drops nodes.\n\tif offset \u003c 0 {\n\t\toffset = 0\n\t}\n\n\t// fast paths. these happen only if TraverseByOffset is called directly on a leaf.\n\tif limit \u003c= 0 || offset \u003e= node.size {\n\t\treturn false\n\t}\n\tif node.IsLeaf() {\n\t\tif offset \u003e 0 {\n\t\t\treturn false\n\t\t}\n\t\treturn cb(node)\n\t}\n\n\t// go to the actual recursive function.\n\treturn node.traverseByOffset(offset, limit, ascending, leavesOnly, cb)\n}\n\n// TraverseByOffset traverses the subtree rooted at the node by offset and limit,\n// in either ascending or descending order, and applies the callback function to each traversed node.\n// If leavesOnly is true, only leaf nodes are visited.\nfunc (node *Node) traverseByOffset(offset, limit int, ascending bool, leavesOnly bool, cb func(*Node) bool) bool {\n\t// caller guarantees: offset \u003c node.size; limit \u003e 0.\n\tif !leavesOnly {\n\t\tif cb(node) {\n\t\t\treturn true // Stop traversal if callback returns true\n\t\t}\n\t}\n\tfirst, second := node.getLeftNode(), node.getRightNode()\n\tif !ascending {\n\t\tfirst, second = second, first\n\t}\n\tif first.IsLeaf() {\n\t\t// either run or skip, based on offset\n\t\tif offset \u003e 0 {\n\t\t\toffset--\n\t\t} else {\n\t\t\tif cb(first) {\n\t\t\t\treturn true // Stop traversal if callback returns true\n\t\t\t}\n\t\t\tlimit--\n\t\t\tif limit \u003c= 0 {\n\t\t\t\treturn true // Stop traversal when limit is reached\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// possible cases:\n\t\t// 1 the offset given skips the first node entirely\n\t\t// 2 the offset skips none or part of the first node, but the limit requires some of the second node.\n\t\t// 3 the offset skips none or part of the first node, and the limit stops our search on the first node.\n\t\tif offset \u003e= first.size {\n\t\t\toffset -= first.size // 1\n\t\t} else {\n\t\t\tif first.traverseByOffset(offset, limit, ascending, leavesOnly, cb) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// number of leaves which could actually be called from inside\n\t\t\tdelta := first.size - offset\n\t\t\toffset = 0\n\t\t\tif delta \u003e= limit {\n\t\t\t\treturn true // 3\n\t\t\t}\n\t\t\tlimit -= delta // 2\n\t\t}\n\t}\n\n\t// because of the caller guarantees and the way we handle the first node,\n\t// at this point we know that limit \u003e 0 and there must be some values in\n\t// this second node that we include.\n\n\t// =\u003e if the second node is a leaf, it has to be included.\n\tif second.IsLeaf() {\n\t\treturn cb(second)\n\t}\n\t// =\u003e if it is not a leaf, it will still be enough to recursively call this\n\t// function with the updated offset and limit\n\treturn second.traverseByOffset(offset, limit, ascending, leavesOnly, cb)\n}\n\n// Only used in testing...\nfunc (node *Node) lmd() *Node {\n\tif node.height == 0 {\n\t\treturn node\n\t}\n\treturn node.getLeftNode().lmd()\n}\n\n// Only used in testing...\nfunc (node *Node) rmd() *Node {\n\tif node.height == 0 {\n\t\treturn node\n\t}\n\treturn node.getRightNode().rmd()\n}\n\nfunc maxInt8(a, b int8) int8 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n"},{"name":"tree.gno","body":"package avl\n\ntype ITree interface {\n\t// read operations\n\n\tSize() int\n\tHas(key string) bool\n\tGet(key string) any\n\tGetByIndex(index int) (key string, value any)\n\tIterate(start, end string, cb IterCbFn) bool\n\tReverseIterate(start, end string, cb IterCbFn) bool\n\tIterateByOffset(offset int, count int, cb IterCbFn) bool\n\tReverseIterateByOffset(offset int, count int, cb IterCbFn) bool\n\n\t// write operations\n\n\tSet(key string, value any) (updated bool)\n\tRemove(key string) (value any, removed bool)\n}\n\ntype IterCbFn func(key string, value any) bool\n\n//----------------------------------------\n// Tree\n\n// The zero struct can be used as an empty tree.\ntype Tree struct {\n\tnode *Node\n}\n\n// NewTree creates a new empty AVL tree.\nfunc NewTree() *Tree {\n\treturn \u0026Tree{\n\t\tnode: nil,\n\t}\n}\n\n// Size returns the number of key-value pair in the tree.\nfunc (tree *Tree) Size() int {\n\treturn tree.node.Size()\n}\n\n// Has checks whether a key exists in the tree.\n// It returns true if the key exists, otherwise false.\nfunc (tree *Tree) Has(key string) (has bool) {\n\treturn tree.node.Has(key)\n}\n\n// Get retrieves the value associated with the given key.\n// It returns the value if the key exists, or nil if it doesn't.\n// Note that a key stored with a nil value is indistinguishable\n// from an absent key; use Has to check for existence.\n// This allows for a simpler usage pattern with type assertions:\n//\n//\tif value, ok := tree.Get(\"key\").(MyType); ok {\n//\t    // use value\n//\t}\nfunc (tree *Tree) Get(key string) any {\n\t_, value, _ := tree.node.Get(key)\n\treturn value\n}\n\n// GetByIndex retrieves the key-value pair at the specified index in the tree.\n// It returns the key and value at the given index.\nfunc (tree *Tree) GetByIndex(index int) (key string, value any) {\n\treturn tree.node.GetByIndex(index)\n}\n\n// Set inserts a key-value pair into the tree.\n// If the key already exists, the value will be updated.\n// It returns a boolean indicating whether the key was newly inserted or updated.\nfunc (tree *Tree) Set(key string, value any) (updated bool) {\n\tnewnode, updated := tree.node.Set(key, value)\n\ttree.node = newnode\n\treturn updated\n}\n\n// Remove removes a key-value pair from the tree.\n// It returns the removed value and a boolean indicating whether the key was found and removed.\nfunc (tree *Tree) Remove(key string) (value any, removed bool) {\n\tnewnode, _, value, removed := tree.node.Remove(key)\n\ttree.node = newnode\n\treturn value, removed\n}\n\n// Iterate performs an in-order traversal of the tree within the specified key range.\n// It calls the provided callback function for each key-value pair encountered.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) Iterate(start, end string, cb IterCbFn) bool {\n\treturn tree.node.TraverseInRange(start, end, true, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// ReverseIterate performs a reverse in-order traversal of the tree within the specified key range.\n// It calls the provided callback function for each key-value pair encountered.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) ReverseIterate(start, end string, cb IterCbFn) bool {\n\treturn tree.node.TraverseInRange(start, end, false, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// IterateByOffset performs an in-order traversal of the tree starting from the specified offset.\n// It calls the provided callback function for each key-value pair encountered, up to the specified count.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) IterateByOffset(offset int, count int, cb IterCbFn) bool {\n\treturn tree.node.TraverseByOffset(offset, count, true, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// ReverseIterateByOffset performs a reverse in-order traversal of the tree starting from the specified offset.\n// It calls the provided callback function for each key-value pair encountered, up to the specified count.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) ReverseIterateByOffset(offset int, count int, cb IterCbFn) bool {\n\treturn tree.node.TraverseByOffset(offset, count, false, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// Verify that Tree implements TreeInterface\nvar _ ITree = (*Tree)(nil)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"addrset","path":"gno.land/p/moul/addrset/v0","files":[{"name":"addrset.gno","body":"// Package addrset provides a specialized set data structure for managing unique Gno addresses.\n//\n// It is built on top of an AVL tree for efficient operations and maintains addresses in sorted order.\n// This package is particularly useful when you need to:\n//   - Track a collection of unique addresses (e.g., for whitelists, participants, etc.)\n//   - Efficiently check address membership\n//   - Support pagination when displaying addresses\n//\n// Example usage:\n//\n//\timport (\n//\t    \"gno.land/p/moul/addrset/v0\"\n//\t)\n//\n//\tfunc MyHandler() {\n//\t    // Create a new address set\n//\t    var set addrset.Set\n//\n//\t    // Add some addresses\n//\t    addr1 := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n//\t    addr2 := address(\"g1sss5g0rkqr88k4u648yd5d3l9t4d8vvqwszqth\")\n//\n//\t    set.Add(addr1)  // returns true (newly added)\n//\t    set.Add(addr2)  // returns true (newly added)\n//\t    set.Add(addr1)  // returns false (already exists)\n//\n//\t    // Check membership\n//\t    if set.Has(addr1) {\n//\t        // addr1 is in the set\n//\t    }\n//\n//\t    // Get size\n//\t    size := set.Size()  // returns 2\n//\n//\t    // Iterate with pagination (10 items per page, starting at offset 0)\n//\t    set.IterateByOffset(0, 10, func(addr address) bool {\n//\t        // Process addr\n//\t        return false  // continue iteration\n//\t    })\n//\n//\t    // Remove an address\n//\t    set.Remove(addr1)  // returns true (was present)\n//\t    set.Remove(addr1)  // returns false (not present)\n//\t}\npackage addrset\n\nimport \"gno.land/p/nt/avl/v0\"\n\ntype Set struct {\n\ttree avl.Tree\n}\n\n// Add inserts an address into the set.\n// Returns true if the address was newly added, false if it already existed.\nfunc (s *Set) Add(addr address) bool {\n\treturn !s.tree.Set(string(addr), nil)\n}\n\n// Remove deletes an address from the set.\n// Returns true if the address was found and removed, false if it didn't exist.\nfunc (s *Set) Remove(addr address) bool {\n\t_, removed := s.tree.Remove(string(addr))\n\treturn removed\n}\n\n// Has checks if an address exists in the set.\nfunc (s *Set) Has(addr address) bool {\n\treturn s.tree.Has(string(addr))\n}\n\n// Size returns the number of addresses in the set.\nfunc (s *Set) Size() int {\n\treturn s.tree.Size()\n}\n\n// IterateByOffset walks through addresses starting at the given offset.\n// The callback should return true to stop iteration.\nfunc (s *Set) IterateByOffset(offset int, count int, cb func(addr address) bool) {\n\ts.tree.IterateByOffset(offset, count, func(key string, _ any) bool {\n\t\treturn cb(address(key))\n\t})\n}\n\n// ReverseIterateByOffset walks through addresses in reverse order starting at the given offset.\n// The callback should return true to stop iteration.\nfunc (s *Set) ReverseIterateByOffset(offset int, count int, cb func(addr address) bool) {\n\ts.tree.ReverseIterateByOffset(offset, count, func(key string, _ any) bool {\n\t\treturn cb(address(key))\n\t})\n}\n\n// Tree returns the underlying AVL tree for advanced usage.\nfunc (s *Set) Tree() avl.ITree {\n\treturn \u0026s.tree\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/addrset/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"readonly.gno","body":"package addrset\n\n// ReadonlySet is a read-only view of a *Set. Cross-package callers cannot\n// mutate the underlying set through this type: it exposes no mutator\n// methods and holds the *Set in an unexported field, so a foreign realm\n// can neither reach the set nor invoke Add/Remove on it.\n//\n// A ReadonlySet is a thin handle over the live Set (it does not copy or\n// snapshot), so reads through it always reflect the Set's current contents.\ntype ReadonlySet struct {\n\tset *Set\n}\n\n// NewReadonlySet returns a read-only view of s.\nfunc NewReadonlySet(s *Set) *ReadonlySet {\n\treturn \u0026ReadonlySet{set: s}\n}\n\n// Readonly returns a read-only view of the set.\nfunc (s *Set) Readonly() *ReadonlySet {\n\treturn NewReadonlySet(s)\n}\n\n// Has reports whether addr is in the underlying set.\nfunc (r ReadonlySet) Has(addr address) bool {\n\treturn r.set.Has(addr)\n}\n\n// Size returns the number of addresses in the underlying set.\nfunc (r ReadonlySet) Size() int {\n\treturn r.set.Size()\n}\n\n// IterateByOffset walks the underlying set in sorted order, starting at\n// offset and visiting up to count addresses. fn returns true to stop early;\n// IterateByOffset returns true if iteration was stopped that way.\n//\n// The wrapped Set.IterateByOffset has no return value, so the \"stopped\"\n// result is synthesized from the last callback return via a\n// closure-captured local.\nfunc (r ReadonlySet) IterateByOffset(offset, count int, fn func(addr address) bool) (stopped bool) {\n\tr.set.IterateByOffset(offset, count, func(a address) bool {\n\t\tstopped = fn(a)\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n\n// ReverseIterateByOffset is IterateByOffset in reverse (descending) order.\nfunc (r ReadonlySet) ReverseIterateByOffset(offset, count int, fn func(addr address) bool) (stopped bool) {\n\tr.set.ReverseIterateByOffset(offset, count, func(a address) bool {\n\t\tstopped = fn(a)\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"once","path":"gno.land/p/moul/once/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/once/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"once.gno","body":"// Package once provides utilities for one-time execution patterns.\n// It extends the concept of sync.Once with error handling and panic options.\npackage once\n\nimport (\n\t\"errors\"\n)\n\n// Once represents a one-time execution guard\ntype Once struct {\n\tdone    bool\n\terr     error\n\tpaniced bool\n\tvalue   any // stores the result of the execution\n}\n\n// New creates a new Once instance\nfunc New() *Once {\n\treturn \u0026Once{}\n}\n\n// Do executes fn only once and returns nil on subsequent calls\nfunc (o *Once) Do(fn func()) {\n\tif o.done {\n\t\treturn\n\t}\n\tdefer func() { o.done = true }()\n\tfn()\n}\n\n// DoErr executes fn only once and returns the same error on subsequent calls\nfunc (o *Once) DoErr(fn func() error) error {\n\tif o.done {\n\t\treturn o.err\n\t}\n\tdefer func() { o.done = true }()\n\to.err = fn()\n\treturn o.err\n}\n\n// DoOrPanic executes fn only once and panics on subsequent calls\nfunc (o *Once) DoOrPanic(fn func()) {\n\tif o.done {\n\t\tpanic(\"once: multiple execution attempted\")\n\t}\n\tdefer func() { o.done = true }()\n\tfn()\n}\n\n// DoValue executes fn only once and returns its value, subsequent calls return the cached value\nfunc (o *Once) DoValue(fn func() any) any {\n\tif o.done {\n\t\treturn o.value\n\t}\n\tdefer func() { o.done = true }()\n\to.value = fn()\n\treturn o.value\n}\n\n// DoValueErr executes fn only once and returns its value and error\n// Subsequent calls return the cached value and error\nfunc (o *Once) DoValueErr(fn func() (any, error)) (any, error) {\n\tif o.done {\n\t\treturn o.value, o.err\n\t}\n\tdefer func() { o.done = true }()\n\to.value, o.err = fn()\n\treturn o.value, o.err\n}\n\n// Reset resets the Once instance to its initial state\n// This is mainly useful for testing purposes\nfunc (o *Once) Reset() {\n\to.done = false\n\to.err = nil\n\to.paniced = false\n\to.value = nil\n}\n\n// IsDone returns whether the Once has been executed\nfunc (o *Once) IsDone() bool {\n\treturn o.done\n}\n\n// Error returns the error from the last execution if any\nfunc (o *Once) Error() error {\n\treturn o.err\n}\n\nvar (\n\tErrNotExecuted = errors.New(\"once: not executed yet\")\n)\n\n// Value returns the stored value and an error if not executed yet\nfunc (o *Once) Value() (any, error) {\n\tif !o.done {\n\t\treturn nil, ErrNotExecuted\n\t}\n\treturn o.value, nil\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"rotree","path":"gno.land/p/nt/avl/rotree/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/avl/rotree/v0\"\ngno = \"0.9\"\n"},{"name":"rotree.gno","body":"// Package rotree provides a read-only wrapper for avl.Tree with safe value transformation.\n//\n// It is useful when you want to expose a read-only view of a tree while ensuring that\n// the sensitive data cannot be modified.\n//\n// Example:\n//\n//\t// Define a user structure with sensitive data\n//\ttype User struct {\n//\t\tName     string\n//\t\tBalance  int\n//\t\tInternal string // sensitive field\n//\t}\n//\n//\t// Create and populate the original tree\n//\tprivateTree := avl.NewTree()\n//\tprivateTree.Set(\"alice\", \u0026User{\n//\t\tName:     \"Alice\",\n//\t\tBalance:  100,\n//\t\tInternal: \"sensitive\",\n//\t})\n//\n//\t// Create a safe transformation function that copies the struct\n//\t// while excluding sensitive data\n//\tmakeEntrySafeFn := func(v any) any {\n//\t\tu := v.(*User)\n//\t\treturn \u0026User{\n//\t\t\tName:     u.Name,\n//\t\t\tBalance:  u.Balance,\n//\t\t\tInternal: \"\", // omit sensitive data\n//\t\t}\n//\t}\n//\n//\t// Create a read-only view of the tree\n//\tPublicTree := rotree.Wrap(tree, makeEntrySafeFn)\n//\n//\t// Safely access the data\n//\tvalue := roTree.Get(\"alice\")\n//\tuser := value.(*User)\n//\t// user.Name == \"Alice\"\n//\t// user.Balance == 100\n//\t// user.Internal == \"\" (sensitive data is filtered)\npackage rotree\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Wrap creates a new ReadOnlyTree from an existing avl.Tree and a safety transformation function.\n// If makeEntrySafeFn is nil, values will be returned as-is without transformation.\n//\n// makeEntrySafeFn is a function that transforms a tree entry into a safe version that can be exposed to external users.\n// This function should be implemented based on the specific safety requirements of your use case:\n//\n//  1. No-op transformation: For primitive types (int, string, etc.) or already safe objects,\n//     simply pass nil as the makeEntrySafeFn to return values as-is.\n//\n//  2. Defensive copying: For mutable types like slices or maps, you should create a deep copy\n//     to prevent modification of the original data.\n//     Example: func(v any) any { return append([]int{}, v.([]int)...) }\n//\n//  3. Read-only wrapper: Return a read-only version of the object that implements\n//     a limited interface.\n//     Example: func(v any) any { return NewReadOnlyObject(v) }\n//\n//  4. DAO transformation: Transform the object into a data access object that\n//     controls how the underlying data can be accessed.\n//     Example: func(v any) any { return NewDAO(v) }\n//\n// The function ensures that the returned object is safe to expose to untrusted code,\n// preventing unauthorized modifications to the original data structure.\nfunc Wrap(tree *avl.Tree, makeEntrySafeFn func(any) any) *ReadOnlyTree {\n\treturn \u0026ReadOnlyTree{\n\t\ttree:            tree,\n\t\tmakeEntrySafeFn: makeEntrySafeFn,\n\t}\n}\n\n// ReadOnlyTree wraps an avl.Tree and provides read-only access.\ntype ReadOnlyTree struct {\n\ttree            *avl.Tree\n\tmakeEntrySafeFn func(any) any\n}\n\n// IReadOnlyTree defines the read-only operations available on a tree.\ntype IReadOnlyTree interface {\n\tSize() int\n\tHas(key string) bool\n\tGet(key string) any\n\tGetByIndex(index int) (string, any)\n\tIterate(start, end string, cb avl.IterCbFn) bool\n\tReverseIterate(start, end string, cb avl.IterCbFn) bool\n\tIterateByOffset(offset int, count int, cb avl.IterCbFn) bool\n\tReverseIterateByOffset(offset int, count int, cb avl.IterCbFn) bool\n}\n\n// Verify that ReadOnlyTree implements both ITree and IReadOnlyTree\nvar (\n\t_ avl.ITree     = (*ReadOnlyTree)(nil)\n\t_ IReadOnlyTree = (*ReadOnlyTree)(nil)\n)\n\n// getSafeValue applies the makeEntrySafeFn if it exists, otherwise returns the original value\nfunc (roTree *ReadOnlyTree) getSafeValue(value any) any {\n\tif roTree.makeEntrySafeFn == nil {\n\t\treturn value\n\t}\n\treturn roTree.makeEntrySafeFn(value)\n}\n\n// Size returns the number of key-value pairs in the tree.\nfunc (roTree *ReadOnlyTree) Size() int {\n\treturn roTree.tree.Size()\n}\n\n// Has checks whether a key exists in the tree.\nfunc (roTree *ReadOnlyTree) Has(key string) bool {\n\treturn roTree.tree.Has(key)\n}\n\n// Get retrieves the value associated with the given key, converted to a safe format.\n// It returns the value if the key exists, or nil if it doesn't.\n// Note that a key stored with a nil value is indistinguishable\n// from an absent key; use Has to check for existence.\nfunc (roTree *ReadOnlyTree) Get(key string) any {\n\tvalue := roTree.tree.Get(key)\n\tif value == nil {\n\t\treturn nil\n\t}\n\treturn roTree.getSafeValue(value)\n}\n\n// GetByIndex retrieves the key-value pair at the specified index in the tree, with the value converted to a safe format.\nfunc (roTree *ReadOnlyTree) GetByIndex(index int) (string, any) {\n\tkey, value := roTree.tree.GetByIndex(index)\n\treturn key, roTree.getSafeValue(value)\n}\n\n// Iterate performs an in-order traversal of the tree within the specified key range.\nfunc (roTree *ReadOnlyTree) Iterate(start, end string, cb avl.IterCbFn) bool {\n\treturn roTree.tree.Iterate(start, end, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// ReverseIterate performs a reverse in-order traversal of the tree within the specified key range.\nfunc (roTree *ReadOnlyTree) ReverseIterate(start, end string, cb avl.IterCbFn) bool {\n\treturn roTree.tree.ReverseIterate(start, end, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// IterateByOffset performs an in-order traversal of the tree starting from the specified offset.\nfunc (roTree *ReadOnlyTree) IterateByOffset(offset int, count int, cb avl.IterCbFn) bool {\n\treturn roTree.tree.IterateByOffset(offset, count, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// ReverseIterateByOffset performs a reverse in-order traversal of the tree starting from the specified offset.\nfunc (roTree *ReadOnlyTree) ReverseIterateByOffset(offset int, count int, cb avl.IterCbFn) bool {\n\treturn roTree.tree.ReverseIterateByOffset(offset, count, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// Set is not supported on ReadOnlyTree and will panic.\nfunc (roTree *ReadOnlyTree) Set(key string, value any) bool {\n\tpanic(\"Set operation not supported on ReadOnlyTree\")\n}\n\n// Remove is not supported on ReadOnlyTree and will panic.\nfunc (roTree *ReadOnlyTree) Remove(key string) (value any, removed bool) {\n\tpanic(\"Remove operation not supported on ReadOnlyTree\")\n}\n\n// RemoveByIndex is not supported on ReadOnlyTree and will panic.\nfunc (roTree *ReadOnlyTree) RemoveByIndex(index int) (key string, value any) {\n\tpanic(\"RemoveByIndex operation not supported on ReadOnlyTree\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"authz","path":"gno.land/p/moul/authz/v0","files":[{"name":"authz.gno","body":"// Package authz provides flexible authorization control for privileged actions.\n//\n// # Authorization Strategies\n//\n// The package supports multiple authorization strategies:\n//   - Member-based: Single user or team of users\n//   - Contract-based: The contract at a given path is itself the authority\n//   - Auto-accept: Allow all actions\n//   - Drop: Deny all actions\n//\n// Core Components\n//\n//   - Authority interface: Base interface implemented by all authorities\n//   - Authorizer: Main wrapper object for authority management\n//   - MemberAuthority: Manages authorized addresses\n//   - ContractAuthority: Makes the contract at a path its own authority\n//   - AutoAcceptAuthority: Accepts all actions\n//   - DroppedAuthority: Denies all actions\n//\n// Quick Start\n//\n//\t// Initialize with contract deployer as authority\n//\tvar member address(...)\n//\tvar auth = authz.NewWithMembers(member)\n//\n//\t// Create functions that require authorization\n//\tfunc UpdateConfig(cur realm, newValue string) error {\n//\t\treturn auth.DoByPrevious(0, cur, \"update_config\", func() error {\n//\t\t\tconfig = newValue\n//\t\t\treturn nil\n//\t\t})\n//\t}\n//\n// See example_test.gno for more usage examples.\npackage authz\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/addrset/v0\"\n\t\"gno.land/p/moul/once/v0\"\n\t\"gno.land/p/nt/avl/rotree/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Authorizer is the main wrapper object that handles authority management.\n// It is configured with a replaceable Authority implementation.\ntype Authorizer struct {\n\tauth Authority\n}\n\n// Authority represents an entity that can authorize privileged actions.\n// It is implemented by MemberAuthority, ContractAuthority, AutoAcceptAuthority,\n// and DroppedAuthority.\n//\n// Authority is the canonical safe shape for cross-package authority\n// interfaces: methods are address-typed (no realm/cur crosses the interface\n// boundary), and consumers correctly derive `caller` from\n// `cur.Previous().Address()` under `rlm.IsCurrent()` before invoking\n// Authorize. No cur-leak (class 1) is possible through this interface.\n//\n// However, two RESIDUAL RISKS apply:\n//\n//   - Class-3 impl-substitution: NewWithAuthority and Authorizer.Transfer\n//     accept any Authority impl. A malicious Authority can always-approve\n//     (silent privilege escalation) or always-deny (denial-of-service).\n//     Consumers should pass canonical impls from this package\n//     (MemberAuthority, ContractAuthority, AutoAcceptAuthority,\n//     DroppedAuthority) unless they have explicit reason to register a\n//     foreign impl. We do not expose an IsCanonicalAuthority allowlist\n//     because the package is intentionally extensible — third-party impls\n//     are the design intent.\n//\n//   - Class-4 closed-over-authority: NewContractAuthority and\n//     NewRestrictedContractAuthority capture a caller-supplied\n//     PrivilegedActionHandler closure. The handler runs synchronously\n//     inside Authorize with the consumer's authority. A hostile handler\n//     can swallow actions, log the caller, or execute arbitrary code\n//     under the consumer's frame. Register only trusted handler functions.\n//     See r/gnops/valopers/init.gno for the realistic registration shape.\n//\n//   - Caller- and title-forgery on the RAW interface: Authorize takes\n//     `caller` and `title` as ARGUMENTS, not from the frame. A consumer\n//     that exposes a bare Authority (rather than the *Authorizer that\n//     wraps it) therefore lets any holder present any caller and any\n//     title. Caller-forgery is contained — the only authority-mutating\n//     closure lives inside Authorizer.Transfer, so a forged caller on a\n//     raw Authorize runs the caller's own inert closure and cannot\n//     transfer; TestForgedCallerCannotTransfer pins that boundary.\n//     Title-forgery is NOT contained: the title is passed straight to the\n//     contractHandler, so a handler that branches on it (routing, quotas,\n//     audit trails) must not treat it as trusted. Keep the Authority\n//     unexported and hand out only what callers need; see\n//     r/gnops/valopers/admin.gno, which exports a description string.\n//\n// We do NOT seal Authority via an unexported marker method — that pattern\n// is bypassable via embedding in Gno; see\n// p/test/seal/filetests/z_seal_*_filetest.gno for the four bypass tests.\ntype Authority interface {\n\t// Authorize executes a privileged action if the caller is authorized\n\t// Additional args can be provided for context (e.g., for proposal creation)\n\tAuthorize(caller address, title string, action PrivilegedAction, args ...any) error\n\n\t// String returns a human-readable description of the authority\n\tString() string\n}\n\n// PrivilegedAction defines a function that performs a privileged action.\ntype PrivilegedAction func() error\n\n// PrivilegedActionHandler is called by contract-based authorities to handle\n// privileged actions.\ntype PrivilegedActionHandler func(title string, action PrivilegedAction) error\n\n// NewWithMembers creates a new Authorizer whose authority is a\n// MemberAuthority containing the given addresses. Callers express\n// authority intent at the call site:\n//\n//\t// \"auth realm is the authority\"\n//\ta := authz.NewWithMembers(cur.Address())\n//\n//\t// \"previous realm is the authority\" (from a crossing function)\n//\ta := authz.NewWithMembers(cur.Previous().Address())\n//\n//\t// \"EOA caller is the authority\" (from init(cur realm))\n//\tif !cur.Previous().IsUserCall() {\n//\t    panic(\"realm must be initialized by EOA\")\n//\t}\n//\ta := authz.NewWithMembers(cur.Previous().Address())\n//\n// This replaces the previous NewWithCurrent / NewWithPrevious /\n// NewWithOrigin sugar — those baked runtime.{Current,Previous,Origin}\n// reads into the constructor, which (a) prevented use from package-\n// level var initializers, (b) made the EOA-origin check inside\n// NewWithOrigin an indirect address comparison rather than the\n// straightforward IsUserCall predicate, and (c) coupled the\n// constructor to the runtime walks the rest of the migration is\n// moving away from.\nfunc NewWithMembers(addrs ...address) *Authorizer {\n\treturn \u0026Authorizer{\n\t\tauth: NewMemberAuthority(addrs...),\n\t}\n}\n\n// NewWithAuthority creates a new Authorizer with a specific authority.\n//\n// SECURITY: `authority` is an open-interface input — any value satisfying\n// Authority is accepted. A malicious impl can always-approve (privilege\n// escalation) or always-deny (DoS). Prefer canonical impls from this\n// package (NewMemberAuthority, NewContractAuthority, NewAutoAcceptAuthority,\n// NewDroppedAuthority) unless you specifically need a foreign impl.\nfunc NewWithAuthority(authority Authority) *Authorizer {\n\treturn \u0026Authorizer{\n\t\tauth: authority,\n\t}\n}\n\n// Authority returns the auth authority implementation\nfunc (a *Authorizer) Authority() Authority {\n\treturn a.auth\n}\n\n// Transfer changes the auth authority after validation. rlm must be the\n// caller's own captured cur (asserted via rlm.IsCurrent()); the\n// principal is rlm.Previous().Address(). Closes the address-parameter\n// forgery: an external realm cannot supply Owner() as `caller` to\n// bypass the underlying Authority's check.\n//\n// SECURITY (runtime substitution): once the current authority approves a\n// Transfer, the new authority is installed and effective on the next call.\n// If an attacker ever becomes the authority — even briefly — they can\n// install a permanent DroppedAuthority (DoS) or an AutoAcceptAuthority\n// (privilege escalation). Consumers concerned about this should wrap\n// Transfer with a one-shot guard or a quorum/cooldown check.\n//\n// `newAuthority` is also an open-interface input — see NewWithAuthority's\n// Class-3 caveat. Pass canonical impls.\nfunc (a *Authorizer) Transfer(_ int, rlm realm, newAuthority Authority) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.auth.Authorize(caller, \"transfer_authority\", func() error {\n\t\ta.auth = newAuthority\n\t\treturn nil\n\t})\n}\n\n// DoByCurrent executes a privileged action authorized as `rlm`. `rlm`\n// must be the caller's own live cur (asserted via rlm.IsCurrent());\n// the authorized principal is `rlm.Address()`. To authorize as the\n// realm that called your function, use `DoByPrevious`.\n//\n//\tauth.DoByCurrent(0, cur, \"update_config\", func() error { ... })    // current realm authorizes\n//\tauth.DoByPrevious(0, cur, \"update_config\", func() error { ... })   // calling realm authorizes\n//\n// The `_ int` first parameter is a deliberate sentinel that pushes\n// `rlm realm` past the first-arg position so DoByCurrent stays a\n// non-crossing method — otherwise it would be a crossing method and\n// rlm.Previous() inside would resolve one realm deeper than the caller\n// intended.\n//\n// SECURITY: the IsCurrent guard closes Class-2 designation forgery (see\n// docs/resources/gno-security.md). A realm value's .Address() is set\n// when the value is minted at a crossing frame; the value can in\n// principle be stored and replayed. Without IsCurrent, a hostile realm\n// could capture a high-privilege realm's cur.Previous() (e.g., when\n// that realm called into it) and later pass the stored value here to\n// authorize actions as that realm. IsCurrent rejects stale captures by\n// requiring the value to match the topmost live crossing frame's cur.\nfunc (a *Authorizer) DoByCurrent(_ int, rlm realm, title string, action PrivilegedAction, args ...any) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\treturn a.auth.Authorize(rlm.Address(), title, action, args...)\n}\n\n// DoByPrevious executes a privileged action authorized as the realm\n// that called the function invoking DoByPrevious. `rlm` must be the\n// caller's own live cur; the principal is derived as\n// `rlm.Previous().Address()`. Mirrors the Transfer/AddMember pattern:\n// always take live cur, derive the caller-of-caller internally rather\n// than accepting a stored/forwarded realm value.\nfunc (a *Authorizer) DoByPrevious(_ int, rlm realm, title string, action PrivilegedAction, args ...any) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\treturn a.auth.Authorize(rlm.Previous().Address(), title, action, args...)\n}\n\n// String returns a string representation of the auth authority.\n//\n// A non-canonical impl is wrapped as custom_authority[...] so that the\n// official \"dropped\" is distinguishable from a \"*custom*: dropped\"\n// (autoclaimed) one. Shared with ContractAuthority.String, which applies\n// the same rule to its nested proposer.\nfunc (a *Authorizer) String() string {\n\treturn canonicalAuthorityString(a.auth)\n}\n\n// MemberAuthority is the default implementation using addrset for member\n// management.\ntype MemberAuthority struct {\n\tmembers addrset.Set\n}\n\nfunc NewMemberAuthority(members ...address) *MemberAuthority {\n\tauth := \u0026MemberAuthority{}\n\tfor _, addr := range members {\n\t\tauth.members.Add(addr)\n\t}\n\treturn auth\n}\n\nfunc (a *MemberAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\tif !a.members.Has(caller) {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\n\tif err := action(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (a *MemberAuthority) String() string {\n\taddrs := []string{}\n\ta.members.Tree().Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\taddrs = append(addrs, key)\n\t\treturn false\n\t})\n\taddrsStr := strings.Join(addrs, \",\")\n\treturn ufmt.Sprintf(\"member_authority[%s]\", addrsStr)\n}\n\n// AddMember adds a new member to the authority. rlm must be the caller's\n// own captured cur; the principal is rlm.Previous().Address() and must\n// already be a member. The IsCurrent guard closes the forgery where an\n// external realm passes Owner() as caller to bypass members.Has(caller).\nfunc (a *MemberAuthority) AddMember(_ int, rlm realm, addr address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.Authorize(caller, \"add_member\", func() error {\n\t\ta.members.Add(addr)\n\t\treturn nil\n\t})\n}\n\n// AddMembers adds a list of members to the authority. Same rlm contract\n// as AddMember.\nfunc (a *MemberAuthority) AddMembers(_ int, rlm realm, addrs ...address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.Authorize(caller, \"add_members\", func() error {\n\t\tfor _, addr := range addrs {\n\t\t\ta.members.Add(addr)\n\t\t}\n\t\treturn nil\n\t})\n}\n\n// RemoveMember removes a member from the authority. Same rlm contract\n// as AddMember.\nfunc (a *MemberAuthority) RemoveMember(_ int, rlm realm, addr address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.Authorize(caller, \"remove_member\", func() error {\n\t\ta.members.Remove(addr)\n\t\treturn nil\n\t})\n}\n\n// Tree returns a read-only view of the members tree\nfunc (a *MemberAuthority) Tree() *rotree.ReadOnlyTree {\n\ttree := a.members.Tree().(*avl.Tree)\n\treturn rotree.Wrap(tree, nil)\n}\n\n// Has checks if the given address is a member of the authority\nfunc (a *MemberAuthority) Has(addr address) bool {\n\treturn a.members.Has(addr)\n}\n\n// ContractAuthority implements async contract-based authority\ntype ContractAuthority struct {\n\tcontractPath    string\n\tcontractAddr    address\n\tcontractHandler PrivilegedActionHandler\n\tproposer        Authority // controls who can create proposals\n}\n\n// NewContractAuthority makes the contract at `path` its OWN authority:\n// the default proposer accepts only chain.PackageAddress(path), so a\n// privileged action proceeds only when driven from that contract's own\n// frame.\n//\n// NewRestrictedContractAuthority does NOT widen this — it REPLACES it.\n// See its godoc; with an explicit proposer, `path` is a label and\n// contractAddr is never consulted.\n//\n// The `caller` compared against that address is established upstream by\n// Authorizer.DoByCurrent / DoByPrevious / Transfer under rlm.IsCurrent(),\n// so an external realm cannot present the contract address.\n//\n// BREAKING: the default proposer used to be\n// NewAutoAcceptAuthority (\"anyone can propose\"). Consumers that relied on\n// arbitrary callers driving a plain ContractAuthority will start getting\n// \"unauthorized\"; that is the fix, not a regression. Pass an explicit\n// proposer to NewRestrictedContractAuthority to opt back in.\n//\n// SECURITY — the gate binds the contract's IDENTITY, not its intent.\n// Inside any crossing frame of the contract, rlm.Address() is\n// unconditionally PackageAddress(path), so `DoByCurrent` from within the\n// contract is a tautology; only DoByPrevious and Transfer gain a real\n// check. Consequently ANY exported function of the contract that returns\n// a crossing closure (or anything else carrying its frame) hands this\n// authority to its caller. Keep privileged closures unexported.\n//\n// So DO NOT write NewContractAuthority(ownPath) + DoByCurrent. It reads\n// like \"only I may do this\" and compiles to \"anyone may do this\". Point\n// `path` at the principal you actually want to assert — usually the\n// governance realm that will drive the action — and use DoByPrevious, so\n// the comparison is against whoever crossed in:\n//\n//\t// in r/gnops/valopers/init.gno\n//\tauth = authz.NewWithAuthority(\n//\t    authz.NewContractAuthority(\"gno.land/r/gov/dao\", handler),\n//\t)\n//\t// in the privileged write\n//\tauth.DoByPrevious(0, rlm, \"update-instructions\", action)\n//\n// Own-path is right only when something OTHER than the contract's own\n// frame supplies the caller — i.e. you drive it via DoByPrevious from a\n// realm you have deliberately let call in, or via Transfer.\n//\n// SECURITY — a gate is only as good as the principal it names. Pointing\n// `path` at a realm whose frame ANY caller can mint buys nothing. Check,\n// for whatever principal you choose, that nothing exported by that realm\n// hands out its frame identity:\n//\n//   - `gno.land/r/gov/dao` is safe to assert ONLY because\n//     SimpleExecutor.Execute rejects invocation from outside the proxy\n//     (r/gov/dao/types.gno). Before that gate existed, dao's exported\n//     NewSimpleExecutor + Execute let any realm mint a frame whose\n//     Previous() was r/gov/dao, so this whole pairing authenticated\n//     nothing. Do not assume a governance path is unforgeable; verify it.\n//   - Whatever the principal, an exported function of YOUR realm whose\n//     signature is assignable to a callback type the principal invokes\n//     (for r/gov/dao: `func(realm) error`) is itself the leak — the\n//     principal will happily call it for an attacker. Keep privileged\n//     entrypoints out of that shape, or take extra parameters.\n//\n// Neither shape defends against re-exporting the privileged closure: its\n// holder picks the Previous() they present by wrapping it in an executor\n// of their own. Unexported closures remain the load-bearing rule.\n//\n// A syntactically valid but WRONG `path` is a permanent brick, not an\n// error: the authority accepts nobody, and Transfer routes through the\n// same gate, so it cannot be rotated out either. Construction rejects\n// malformed paths, but it cannot tell a wrong path from a right one —\n// e.g. \"gno.land/r/gov/dao/impl/v0\" (the path r/gov/dao's own\n// allowedDAOs list holds) is well-formed and permanently dead, because\n// an executor's Previous() is the PROXY path, never the impl. Give the\n// consumer a governance-gated rotation entrypoint before deploying; see\n// r/gnops/valopers/admin.gno's NewAuthorityRotationProposalRequest.\n//\n// SECURITY (Class-4 captured callback): `handler` is a caller-supplied\n// closure that runs SYNCHRONOUSLY inside Authorize, with the consumer's\n// authority. A hostile handler can swallow actions, log the caller, or\n// execute arbitrary code under the consumer's frame. The package-internal\n// wrappedAction enforces at-most-once invocation and NOTHING ELSE — in\n// particular it does not check the caller, and the handler may call it\n// however it likes (multiple times, never, out of order). Register only\n// trusted handler functions; treat handler registration as the trust\n// boundary.\n//\n// Panics if `path` is empty or malformed, or if `handler` is nil.\nfunc NewContractAuthority(path string, handler PrivilegedActionHandler) *ContractAuthority {\n\taddr := chain.PackageAddress(assertValidContractPath(path))\n\t// The default proposer is a real Authority, not an absent one. Encoding\n\t// the strictest policy as a nil field would mean the secure default is\n\t// what you get by leaving something OUT: a struct literal that skips\n\t// this constructor, a persisted value from an older build, or re-adding\n\t// `if proposer == nil { proposer = NewAutoAcceptAuthority() }` would all\n\t// silently be wide open again. A one-field struct costs the same as the\n\t// nil it replaces and cannot be reached by omission.\n\treturn newContractAuthority(path, addr, handler, \u0026contractIdentityAuthority{addr: addr})\n}\n\n// NewRestrictedContractAuthority creates a contract authority whose\n// proposer REPLACES the contract-identity gate.\n//\n// This is the escape hatch, not a second lock. `proposer` becomes the ONLY\n// authorization decision: contractAddr is not consulted on this path, so\n// `path` degrades to a label that appears in String() and asserts nothing.\n// NewRestrictedContractAuthority(p, h, NewAutoAcceptAuthority()) is exactly\n// the old default behaviour (\"anyone can propose\"), stated\n// explicitly rather than reached by default.\n//\n// In particular NewRestrictedContractAuthority(\"gno.land/r/gov/dao\", h,\n// NewMemberAuthority(alice)) does NOT mean \"GovDAO and alice\". It means\n// \"alice, and not GovDAO\".\n//\n// SECURITY:\n//   - `handler` is the same Class-4 captured-callback risk as\n//     NewContractAuthority — runs synchronously inside Authorize with the\n//     consumer's authority. Register only trusted handler functions.\n//   - `proposer` is an open-interface input (Class-3 impl-substitution).\n//     A hostile proposer Authority can always-approve creation of any\n//     proposal, defeating the restriction. Pass canonical impls only.\n//     String() renders a non-canonical proposer wrapped as\n//     custom_authority[...] so such a substitution is at least visible.\nfunc NewRestrictedContractAuthority(path string, handler PrivilegedActionHandler, proposer Authority) Authority {\n\tif proposer == nil {\n\t\tpanic(\"proposer cannot be nil\")\n\t}\n\taddr := chain.PackageAddress(assertValidContractPath(path))\n\treturn newContractAuthority(path, addr, handler, proposer)\n}\n\n// newContractAuthority is the single construction path: both exported\n// constructors validate, then land here, so a guard added once applies to\n// both. `handler` is rejected here rather than surfaced at Authorize time\n// because Authorize checks contractHandler == nil BEFORE consulting the\n// proposer, and Transfer routes through Authorize — so a nil-handler\n// authority could never be rotated out. It is a permanent brick with no\n// on-chain recovery for anyone: the same bricked-governance failure\n// mode, reached by accident.\nfunc newContractAuthority(path string, addr address, handler PrivilegedActionHandler, proposer Authority) *ContractAuthority {\n\tif handler == nil {\n\t\tpanic(\"contract handler cannot be nil\")\n\t}\n\treturn \u0026ContractAuthority{\n\t\tcontractPath:    path,\n\t\tcontractAddr:    addr,\n\t\tcontractHandler: handler,\n\t\tproposer:        proposer,\n\t}\n}\n\n// assertValidContractPath rejects paths that chain.PackageAddress would\n// hash happily but that no realm could ever present, which would brick the\n// authority permanently (nobody authorizes, and Transfer routes through the\n// same gate so nobody can rotate out). Returns `path` so it composes.\n//\n// The authoritative rule is gnolang.ReGnoUserPkgPath (\"all paths must be\n// lowercase ascii alphanumeric characters\", gnovm/pkg/gnolang/mempackage.go),\n// but no validator is exported to Gno code — chain's isValidSubpath /\n// assertValidSubpath are unexported, and there is no chain.IsValidPkgPath.\n// So this is a deliberately permissive superset: segment (\"/\" segment)*,\n// segment = [a-z0-9] ([a-z0-9_.-]* [a-z0-9])?. It accepts every real\n// package path and catches what actually gets typed wrong — trailing or\n// embedded whitespace, empty segments, uppercase, stray punctuation. It\n// CANNOT catch a well-formed path that is simply the wrong principal. See\n// NewContractAuthority's godoc on rotation.\nfunc assertValidContractPath(path string) string {\n\tif path == \"\" {\n\t\tpanic(\"contract path cannot be empty\")\n\t}\n\tif !strings.Contains(path, \"/\") {\n\t\tpanic(\"contract path must be a package path, e.g. gno.land/r/gov/dao\")\n\t}\n\tstart := 0\n\tfor i := 0; i \u003c= len(path); i++ {\n\t\tif i == len(path) || path[i] == '/' {\n\t\t\tif !isValidContractPathSegment(path[start:i]) {\n\t\t\t\tpanic(\"contract path must be '/'-separated segments of [a-z0-9] with '_.-' allowed inside a segment, e.g. gno.land/r/gov/dao\")\n\t\t\t}\n\t\t\tstart = i + 1\n\t\t}\n\t}\n\treturn path\n}\n\nfunc isValidContractPathSegment(seg string) bool {\n\tif seg == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(seg); i++ {\n\t\tswitch c := seg[i]; {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '_' || c == '.' || c == '-':\n\t\t\t// Allowed only strictly inside a segment.\n\t\t\tif i == 0 || i == len(seg)-1 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// contractIdentityAuthority is the default proposer installed by\n// NewContractAuthority: the contract at the bound path, and nobody else.\n// Unexported and unmutable by design — AddMember/RemoveMember are\n// meaningless for a fixed contract identity, which is why this is not a\n// MemberAuthority holding one address.\ntype contractIdentityAuthority struct {\n\taddr address\n}\n\nfunc (a *contractIdentityAuthority) Authorize(caller address, _ string, action PrivilegedAction, _ ...any) error {\n\tif caller != a.addr {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\treturn action()\n}\n\nfunc (a *contractIdentityAuthority) String() string { return \"contract-identity\" }\n\nfunc (a *ContractAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\tif a.contractHandler == nil {\n\t\treturn errors.New(\"contract handler is not set\")\n\t}\n\n\t// setup a once instance to ensure the action is executed only once\n\texecutionOnce := once.Once{}\n\n\t// wrappedAction enforces at-most-once invocation. The previous\n\t// gate `unsafe.CurrentRealm() == contractAddr` is removed: it\n\t// was .Title()-bypassable (runtime.CurrentRealm walks past\n\t// non-crossing frames to the most-recent crossing ancestor) and\n\t// the trust boundary is now upstream — Authorizer.DoByCurrent /\n\t// DoByPrevious require rlm.IsCurrent() and pass a non-forgeable\n\t// principal to Authorize, while the consumer realm's handler\n\t// closure is the Class-4 trust root by lexical capture at\n\t// registration time.\n\twrappedAction := func() error {\n\t\treturn executionOnce.DoErr(func() error {\n\t\t\treturn action()\n\t\t})\n\t}\n\n\thandle := func() error {\n\t\tif err := a.contractHandler(title, wrappedAction); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// The proposer IS the authorization decision. For an authority built by\n\t// NewContractAuthority it is a contractIdentityAuthority bound to\n\t// contractAddr — the contract itself and nobody else; for one built by\n\t// NewRestrictedContractAuthority it is whatever the consumer installed,\n\t// and contractAddr is deliberately not consulted (see that constructor's\n\t// godoc). `caller` is established upstream by Authorizer.DoByCurrent /\n\t// DoByPrevious / Transfer under rlm.IsCurrent(), so an external realm\n\t// cannot present an arbitrary principal here.\n\t//\n\t// A nil proposer is not a policy, it is a malformed value: both\n\t// constructors always install one, so nil means the struct was built by\n\t// a literal that bypassed them. Fail closed rather than dereference.\n\tif a.proposer == nil {\n\t\treturn errors.New(\"proposer is not set\")\n\t}\n\treturn a.proposer.Authorize(caller, title+\"_proposal\", handle, args...)\n}\n\n// String renders the contract path AND the proposer.\n//\n// The proposer half is security-relevant, not cosmetic: it is the only\n// thing distinguishing a gated authority from a wide-open one. Rendering\n// the path alone made\n//\n//\tNewContractAuthority(path, handler)                              // gated\n//\tNewRestrictedContractAuthority(path, handler, AutoAccept{})      // open to all\n//\n// byte-identical, so any consumer test asserting on this string — and\n// any on-chain reader inspecting it — was blind to the difference. A\n// consumer realm could have its authority swapped for a fully permissive\n// one and its assertions would stay green.\n//\n// \"contract-identity\" names the default installed by NewContractAuthority:\n// the contract at contractPath, and nobody else, may drive this authority.\n//\n// The proposer is rendered through canonicalAuthorityString, NOT by calling\n// a.proposer.String() directly. Authority is an open interface, so a foreign\n// impl can return any text it likes — including \"contract-identity\". That\n// made a fully permissive authority byte-identical to the gated default\n// again, defeating the very assertions this rendering exists to support.\n// Non-canonical impls are wrapped as custom_authority[...], mirroring what\n// Authorizer.String has always done at the outer level.\n//\n// Read the `contract=` half with care: it is load-bearing only for the\n// contract-identity default. With any other proposer it is a label —\n// see NewRestrictedContractAuthority.\nfunc (a *ContractAuthority) String() string {\n\treturn ufmt.Sprintf(\n\t\t\"contract_authority[contract=%s,proposer=%s]\",\n\t\ta.contractPath,\n\t\tcanonicalAuthorityString(a.proposer),\n\t)\n}\n\n// canonicalAuthorityString renders an Authority, wrapping any\n// implementation that is not one of this package's own as\n// custom_authority[...] so a foreign impl cannot impersonate a canonical\n// one by choosing its String() text. Shared by ContractAuthority.String\n// (for the nested proposer) and Authorizer.String (for the installed\n// authority).\nfunc canonicalAuthorityString(auth Authority) string {\n\tif auth == nil {\n\t\t// Only reachable via a struct literal that bypassed the\n\t\t// constructors; Authorize fails closed on the same condition.\n\t\treturn \"\u003cunset\u003e\"\n\t}\n\tswitch auth.(type) {\n\tcase *MemberAuthority, *ContractAuthority, *AutoAcceptAuthority,\n\t\t*droppedAuthority, *contractIdentityAuthority:\n\t\treturn auth.String()\n\tdefault:\n\t\treturn ufmt.Sprintf(\"custom_authority[%s]\", auth.String())\n\t}\n}\n\n// AutoAcceptAuthority implements an authority that accepts all actions\n// AutoAcceptAuthority is a simple authority that automatically accepts all\n// actions.\n// It can be used as a proposer authority to allow anyone to create proposals.\ntype AutoAcceptAuthority struct{}\n\nfunc NewAutoAcceptAuthority() *AutoAcceptAuthority {\n\treturn \u0026AutoAcceptAuthority{}\n}\n\nfunc (a *AutoAcceptAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\treturn action()\n}\n\nfunc (a *AutoAcceptAuthority) String() string {\n\treturn \"auto_accept_authority\"\n}\n\n// droppedAuthority implements an authority that denies all actions\ntype droppedAuthority struct{}\n\nfunc NewDroppedAuthority() Authority {\n\treturn \u0026droppedAuthority{}\n}\n\nfunc (a *droppedAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\treturn errors.New(\"dropped authority: all actions are denied\")\n}\n\nfunc (a *droppedAuthority) String() string {\n\treturn \"dropped_authority\"\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/authz/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"mdtable","path":"gno.land/p/moul/mdtable/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/mdtable/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"mdtable.gno","body":"// Package mdtable provides a simple way to create Markdown tables.\n//\n// Example usage:\n//\n//\timport \"gno.land/p/moul/mdtable/v0\"\n//\n//\tfunc Render(path string) string {\n//\t    table := mdtable.Table{\n//\t        Headers: []string{\"ID\", \"Title\", \"Status\", \"Date\"},\n//\t    }\n//\t    table.Append([]string{\"#1\", \"Add a new validator\", \"succeed\", \"2024-01-01\"})\n//\t    table.Append([]string{\"#2\", \"Change parameter\", \"timed out\", \"2024-01-02\"})\n//\t    return table.String()\n//\t}\n//\n// Output:\n//\n//\t| ID | Title | Status | Date |\n//\t| --- | --- | --- | --- |\n//\t| #1 | Add a new validator | succeed | 2024-01-01 |\n//\t| #2 | Change parameter | timed out | 2024-01-02 |\npackage mdtable\n\nimport (\n\t\"strings\"\n)\n\ntype Table struct {\n\tHeaders []string\n\tRows    [][]string\n\t// XXX: optional headers alignment.\n}\n\nfunc (t *Table) Append(row []string) {\n\tt.Rows = append(t.Rows, row)\n}\n\nfunc (t Table) String() string {\n\t// XXX: switch to using text/tabwriter when porting to Gno to support\n\t// better-formatted raw Markdown output.\n\n\tif len(t.Headers) == 0 \u0026\u0026 len(t.Rows) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar sb strings.Builder\n\n\tif len(t.Headers) == 0 {\n\t\tt.Headers = make([]string, len(t.Rows[0]))\n\t}\n\n\t// Print header.\n\tsb.WriteString(\"| \" + strings.Join(t.Headers, \" | \") + \" |\\n\")\n\tsb.WriteString(\"|\" + strings.Repeat(\" --- |\", len(t.Headers)) + \"\\n\")\n\n\t// Print rows.\n\tfor _, row := range t.Rows {\n\t\tescapedRow := make([]string, len(row))\n\t\tfor i, cell := range row {\n\t\t\tescapedRow[i] = strings.ReplaceAll(cell, \"|\", \"\u0026#124;\") // Escape pipe characters.\n\t\t}\n\t\tsb.WriteString(\"| \" + strings.Join(escapedRow, \" | \") + \" |\\n\")\n\t}\n\n\treturn sb.String()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"echo","path":"gno.land/r/archive/echo","files":[{"name":"echo.gno","body":"package echo\n\n/*\n * This realm echoes the `path` argument it received.\n * Can be used by developers as a simple endpoint to test\n * forbidden characters, for pentesting or simply to\n * test it works.\n *\n * See also r/demo/print (to print various thing like user address)\n */\nfunc Render(path string) string {\n\treturn path\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/archive/echo\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"txlink","path":"gno.land/p/moul/txlink/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/txlink/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"txlink.gno","body":"// Package txlink provides utilities for creating transaction-related links\n// compatible with Gnoweb, Gnobro, and other clients within the Gno ecosystem.\n//\n// This package is optimized for generating lightweight transaction links with\n// flexible arguments, allowing users to build dynamic links that integrate\n// seamlessly with various Gno clients.\n//\n// The package offers a way to generate clickable transaction MD links\n// for the current \"relative realm\":\n//\n//  Using a builder pattern for more structured URLs:\n//     txlink.NewLink(\"MyFunc\").\n//         AddArgs(\"k1\", \"v1\", \"k2\", \"v2\"). // or multiple at once\n//         SetSend(\"1000000ugnot\").\n//         URL()\n//\n// The builder pattern (TxBuilder) provides a fluent interface for constructing\n// transaction URLs in the current \"relative realm\". Like Call, it supports both\n// local realm paths and fully qualified paths through the underlying Call\n// implementation.\n//\n// The Call function remains the core implementation, used both directly and\n// internally by the builder pattern to generate the final URLs.\n//\n// This package is a streamlined alternative to helplink, providing similar\n// functionality for transaction links without the full feature set of helplink.\n\npackage txlink\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"net/url\"\n\t\"strings\"\n)\n\nvar chainDomain = runtime.ChainDomain()\n\n// Realm represents a specific realm for generating tx links.\ntype Realm string\n\n// TxBuilder provides a fluent interface for building transaction URLs\ntype TxBuilder struct {\n\tfn        string   // function name\n\targs      []string // key-value pairs\n\tsend      string   // optional send amount\n\trealm_XXX Realm    // realm for the URL\n}\n\n// NewLink creates a transaction link builder for the specified function in the current realm.\nfunc NewLink(fn string) *TxBuilder {\n\treturn Realm(\"\").NewLink(fn)\n}\n\n// NewLink creates a transaction link builder for the specified function in this realm.\nfunc (r Realm) NewLink(fn string) *TxBuilder {\n\tif fn == \"\" {\n\t\treturn nil\n\t}\n\treturn \u0026TxBuilder{fn: fn, realm_XXX: r}\n}\n\n// addArg adds a key-value argument pair. Returns the builder for chaining.\nfunc (b *TxBuilder) addArg(key, value string) *TxBuilder {\n\tif b == nil {\n\t\treturn nil\n\t}\n\tif key == \"\" {\n\t\treturn b\n\t}\n\n\t// Special case: \".\" prefix is for reserved keywords.\n\tif strings.HasPrefix(key, \".\") {\n\t\tpanic(\"invalid key\")\n\t}\n\n\tb.args = append(b.args, key, value)\n\treturn b\n}\n\n// AddArgs adds multiple key-value pairs at once. Arguments should be provided\n// as pairs: AddArgs(\"key1\", \"value1\", \"key2\", \"value2\").\nfunc (b *TxBuilder) AddArgs(args ...string) *TxBuilder {\n\tif b == nil {\n\t\treturn nil\n\t}\n\tif len(args)%2 != 0 {\n\t\tpanic(\"odd number of arguments\")\n\t}\n\t// Add key-value pairs\n\tfor i := 0; i \u003c len(args); i += 2 {\n\t\tkey := args[i]\n\t\tvalue := args[i+1]\n\t\tb.addArg(key, value)\n\t}\n\treturn b\n}\n\n// SetSend adds a send amount. (Only one send amount can be specified.)\nfunc (b *TxBuilder) SetSend(amount string) *TxBuilder {\n\tif b == nil {\n\t\treturn nil\n\t}\n\tif amount == \"\" {\n\t\treturn b\n\t}\n\tb.send = amount\n\treturn b\n}\n\n// URL generates the final URL using the standard $help\u0026func=name format.\nfunc (b *TxBuilder) URL() string {\n\tif b == nil || b.fn == \"\" {\n\t\treturn \"\"\n\t}\n\targs := b.args\n\tif b.send != \"\" {\n\t\targs = append(args, \".send\", b.send)\n\t}\n\treturn b.realm_XXX.Call(b.fn, args...)\n}\n\n// Call returns a URL for the specified function with optional key-value\n// arguments, for the current realm.\nfunc Call(fn string, args ...string) string {\n\treturn Realm(\"\").Call(fn, args...)\n}\n\n// prefix returns the URL prefix for the realm.\nfunc (r Realm) prefix() string {\n\t// relative\n\tif r == \"\" {\n\t\tcurPath := unsafe.CurrentRealm().PkgPath()\n\t\treturn strings.TrimPrefix(curPath, chainDomain)\n\t}\n\n\t// local realm -\u003e /realm\n\trlm := string(r)\n\tif strings.HasPrefix(rlm, chainDomain) {\n\t\treturn strings.TrimPrefix(rlm, chainDomain)\n\t}\n\n\t// remote realm -\u003e https://remote.land/realm\n\treturn \"https://\" + string(r)\n}\n\n// Call returns a URL for the specified function with optional key-value\n// arguments.\nfunc (r Realm) Call(fn string, args ...string) string {\n\tif len(args) == 0 {\n\t\treturn r.prefix() + \"$help\u0026func=\" + fn\n\t}\n\n\t// Create url.Values to properly encode parameters.\n\t// But manage \u0026func=fn as a special case to keep it as the first argument.\n\tvalues := url.Values{}\n\n\t// Check if args length is even\n\tif len(args)%2 != 0 {\n\t\tpanic(\"odd number of arguments\")\n\t}\n\t// Add key-value pairs to values\n\tfor i := 0; i \u003c len(args); i += 2 {\n\t\tkey := args[i]\n\t\tvalue := args[i+1]\n\t\tvalues.Add(key, value)\n\t}\n\n\t// Build the base URL and append encoded query parameters\n\treturn r.prefix() + \"$help\u0026func=\" + fn + \"\u0026\" + values.Encode()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"bptree","path":"gno.land/p/nt/bptree/v0","files":[{"name":"PLAN.md","body":"# Mutable B+ Tree for Gno\n\n## Goal\n\nA mutable (in-place) B+ tree with the same API as `gno.land/p/nt/avl/v0`.\nNo merkle hashing, no versioning, no persistence — just a simple, efficient\nordered map with configurable fanout.\n\n## API\n\n```go\n// Constructors\nfunc NewBPTreeN(fanout int) *BPTree   // arbitrary fanout (minimum 4)\nfunc NewBPTree32() *BPTree            // convenience: fanout 32\n\n// ITree interface (same as avl.ITree)\ntype ITree interface {\n    Size() int\n    Has(key string) bool\n    Get(key string) any\n    GetByIndex(index int) (key string, value any)\n    Iterate(start, end string, cb IterCbFn) bool\n    ReverseIterate(start, end string, cb IterCbFn) bool\n    IterateByOffset(offset int, count int, cb IterCbFn) bool\n    ReverseIterateByOffset(offset int, count int, cb IterCbFn) bool\n    Set(key string, value any) (updated bool)\n    Remove(key string) (value any, removed bool)\n}\n\ntype IterCbFn func(key string, value any) bool\n```\n\n`var _ ITree = (*BPTree)(nil)` enforces the interface at compile time.\n\n## Semantics (matching avl exactly)\n\n- `Set`: insert or update. Returns true if key already existed.\n- `Remove`: delete key. Returns (old value, true) if found.\n- `GetByIndex`: 0-based index into sorted keys. Panics on invalid index.\n- `Iterate(start, end, cb)`: ascending, start inclusive, end exclusive.\n  Empty string means no bound.\n- `ReverseIterate(start, end, cb)`: descending, start inclusive, end inclusive.\n  Empty string means no bound.\n- `IterateByOffset(offset, count, cb)`: ascending from the offset-th leaf entry\n  (0-indexed from the smallest key). Returns false if offset \u003e= size or count \u003c= 0.\n- `ReverseIterateByOffset(offset, count, cb)`: descending, where offset is\n  0-indexed from the largest key. offset=0 starts at the largest key,\n  offset=1 skips the largest and starts at the second-largest, etc.\n  Equivalent to: visit entries in descending order, skip `offset`, take `count`.\n- All iteration callbacks return true to stop early.\n\n## Node types\n\n### leafNode\n\n```go\ntype leafNode struct {\n    keys   []string  // sorted, len \u003c= fanout\n    values []*any    // parallel to keys\n}\n```\n\nLeaf nodes store all key-value data. No sibling pointers — iteration\nuses stack-based traversal to avoid ref-count \u003e= 2 (see\n[Ref-Count Safety](#ref-count-safety)).\n\nCapacity: up to `fanout` entries. Splits when full after insert.\nMinimum occupancy enforced during deletion: `fanout/2` (except the root leaf).\nNote: the 90/10 split optimization intentionally creates a right leaf with\nonly 2 entries, which may be below `fanout/2` for large fanouts. This is\nstandard B+ tree practice — if a subsequent Remove causes underflow, the\nnormal rebalance logic (redistribute or merge) handles it.\n\n### innerNode\n\n```go\ntype innerNode struct {\n    keys     []string // separator keys, len = len(children)-1\n    children []node   // child pointers, len \u003c= fanout\n    sizes    []int    // sizes[i] = total leaf count in children[i] subtree\n}\n```\n\n`keys[i]` = minimum key of `children[i+1]` (standard B+ tree convention).\nAn inner node with k separator keys has k+1 children.\n\nCapacity: up to `fanout` children (= `fanout-1` keys). Splits when full.\nMinimum occupancy: `fanout/2` children (except root, which may have as few as 2).\n\n### node interface\n\n```go\ntype node interface {\n    isLeaf() bool\n    nodeSize() int    // total leaf entries in subtree\n    minKey() string   // leftmost key in subtree\n}\n```\n\n`nodeSize()`: leafNode returns `len(keys)` (O(1)), innerNode sums `sizes[]` (O(fanout)).\n\nUsed internally so tree methods can handle both node types polymorphically.\nType assertions to `*leafNode` or `*innerNode` are used when accessing\ntype-specific fields (children, sizes).\n\n## BPTree struct\n\n```go\ntype BPTree struct {\n    root   node\n    size   int       // total number of key-value pairs\n    fanout int       // max children per inner node / max entries per leaf\n}\n```\n\nNo `first`/`last` pointers — they would create ref-count \u003e= 2 on leaves.\nFull-range iteration descends from the root (O(height) to find the first\nor last leaf, amortized O(1) per entry thereafter).\n\n## Key algorithms\n\n### Search (Get, Has)\n\nDescend from root. At each inner node, binary search `keys` to find the\nchild index. At the leaf, binary search `keys` for exact match.\n\n### Insert (Set)\n\n1. Descend root-to-leaf, recording the path (stack of `(innerNode, childIdx)` pairs).\n2. Binary search in the leaf for the key.\n3. If found: update value in place, return `updated=true`. No structural change.\n4. If not found: insert key-value at the sorted position.\n   - Increment `size` on the tree and all ancestor `sizes[childIdx]` entries.\n   - If the leaf now has `fanout+1` entries, **split**:\n     - **90/10 split** (append pattern): if the new key was inserted at\n       position `fanout` in the overflowed leaf (i.e., it is greater than\n       all pre-existing keys), split asymmetrically: left gets `fanout-1` entries, right\n       gets 2 entries (the last existing key + the new key). This keeps left\n       leaves ~97% full for sequential inserts.\n     - **50/50 split** (random pattern): otherwise, left gets `(fanout+1)/2`\n       (floor), right gets the rest.\n     - Create new right leaf node.\n     - Promote `right.keys[0]` as separator to the parent.\n     - Update parent's `sizes` for both children.\n     - If the parent now has `fanout+1` children, split the parent recursively.\n   - If the root splits, create a new inner root with 2 children.\n\n### Remove\n\n1. Descend root-to-leaf, recording the path.\n2. Binary search in the leaf for the key.\n3. If not found: return `(nil, false)`.\n4. If found: remove entry, decrement `size` and ancestor `sizes`.\n   - If the leaf is the root and now empty: set root to nil.\n   - If the leaf is the root and non-empty: done (root has no minimum).\n   - Otherwise, if leaf has fewer than `fanout/2` entries, **rebalance**:\n     - Try to **redistribute** from left sibling (if it has more than `fanout/2`).\n     - Try to **redistribute** from right sibling (if it has more than `fanout/2`).\n     - Otherwise **merge** with a sibling:\n       - Concatenate into the left node, remove the right child and its\n         separator from parent.\n       - Update parent's `sizes` and `size`.\n       - If parent is the root and drops to 1 child, replace root with that child.\n       - If parent is not the root and has fewer than `fanout/2` children,\n         rebalance recursively (the root is exempt — it may have as few as 2 children).\n   - If the minimum key was removed (pos == 0), update ancestor separator keys\n     before rebalancing. Rebalance operations also fix separators as needed.\n\n### Redistribute detail\n\n**Redistribute from left sibling to deficient child (both leaves):**\n1. Move left sibling's last key-value to the front of the deficient child.\n2. Update parent `keys[childIdx-1]` = deficient child's new `keys[0]` (its min key changed).\n3. Adjust parent `sizes`: decrement left's size, increment child's size.\n\n**Redistribute from right sibling to deficient child (both leaves):**\n1. Move right sibling's first key-value to the end of the deficient child.\n2. Update parent `keys[childIdx]` = right sibling's new `keys[0]` (its min key changed).\n3. Adjust parent `sizes`: decrement right's size, increment child's size.\n\n**Redistribute from left sibling to deficient child (both inner nodes):**\n1. Pull down parent's separator `keys[childIdx-1]` — **prepend** it to deficient child's keys\n   (insert at position 0, since the moved child goes to the front).\n2. Move left sibling's last child to the **front** of deficient child's children.\n   Move left sibling's last `sizes` entry to the front of deficient's sizes too.\n3. Push up left sibling's last key to replace parent's `keys[childIdx-1]`.\n4. Remove left sibling's last key, last child, and last size entry.\n5. Update parent's `sizes[childIdx-1]` and `sizes[childIdx]` to reflect\n   the new child sizes. (Parent's total size is unchanged since we just\n   moved entries between siblings.)\n\n**Redistribute from right sibling to deficient child (both inner nodes):**\n1. Pull down parent's separator `keys[childIdx]` — **append** it to deficient child's keys\n   (insert at the end, since the moved child goes to the end).\n2. Move right sibling's first child to the **end** of deficient child's children.\n   Move right sibling's first `sizes` entry to the end of deficient's sizes too.\n3. Push up right sibling's first key to replace parent's `keys[childIdx]`.\n4. Remove right sibling's first key, first child, and first size entry.\n5. Update parent's `sizes[childIdx]` and `sizes[childIdx+1]` to reflect\n   the new child sizes. (Parent's total size is unchanged.)\n\n**Merge two inner nodes:**\n1. Pull down the parent's separator between them into the left node's keys.\n2. Append all of right node's keys, children, and sizes to left node.\n3. Remove right child and its separator from parent.\n4. Update parent's `sizes` for the merged left child.\n\n### GetByIndex\n\nUse `sizes[]` at each inner node to find which child contains the i-th\nleaf entry, then descend. At the leaf, index directly into `keys[i]`/`values[i]`.\nPanics if index is out of range (matching avl behavior).\n\n### Stack-based iteration\n\nAll iteration uses a stack of `(innerNode, childIndex)` pairs representing\nthe path from root to the current leaf. When a leaf is exhausted, pop the\nstack, advance (or retreat) the child index, and descend to the next leaf.\nAmortized O(1) per entry — each node is pushed/popped at most once across\nthe full traversal.\n\nThe stack is a local slice built during iteration and discarded after —\nit creates no persistent references to nodes and does not affect ref-counts.\n\n### Iterate / ReverseIterate (key-range)\n\n**Ascending (Iterate):**\n1. Descend from root using separator keys to find the leaf containing `start`\n   (or descend to the leftmost leaf if start is \"\"), recording the path.\n2. Within the leaf, find the first key \u003e= start.\n3. Visit entries from that position forward.\n4. When the leaf is exhausted, advance to the next leaf via the stack:\n   pop the stack, increment childIdx. If childIdx is now past the last\n   child, pop again (repeat until a valid childIdx is found or the stack\n   is empty — if empty, iteration is done). Then descend to the leftmost\n   leaf of that child, pushing each inner node onto the stack.\n5. Stop when key \u003e= end (if end != \"\") or tree is exhausted.\n6. Call `cb(key, value)` for each entry; stop if cb returns true.\n\n**Descending (ReverseIterate):**\n1. Descend from root to find the leaf containing `end` (or the rightmost\n   leaf if end is \"\"), recording the path.\n2. Within the leaf, find the last key \u003c= end.\n3. Visit entries from that position backward.\n4. When the leaf is exhausted going backward, retreat to the previous leaf\n   via the stack: pop the stack, decrement childIdx. If childIdx \u003c 0, pop\n   again (repeat until a valid childIdx is found or the stack is empty —\n   if empty, iteration is done). Then descend to the rightmost leaf of\n   that child, pushing each inner node onto the stack.\n5. Stop when key \u003c start (if start != \"\") or tree is exhausted.\n6. Call `cb(key, value)` for each entry; stop if cb returns true.\n\n### IterateByOffset / ReverseIterateByOffset\n\n**Ascending:**\n1. Use `sizes[]` to descend to the leaf containing the offset-th entry,\n   recording the path. Maintain a running offset counter: at each inner node,\n   subtract `sizes[i]` for each skipped child. When `offset \u003c sizes[i]`,\n   descend into that child. Upon reaching a leaf, the remaining offset is\n   the position within the leaf.\n2. Visit entries from that position forward, advancing through leaves via\n   the stack (same as Iterate), counting up to `count`.\n\n**Descending:**\nThe descending view is: entries in reverse sorted order, 0-indexed from\nthe largest key. offset=0 is the largest, offset=1 is the second-largest, etc.\n\n1. Compute the ascending index of the starting entry:\n   `ascIdx = size - 1 - offset` (the entry at position `offset` in descending order).\n2. Use `sizes[]` to descend to the leaf containing entry `ascIdx`,\n   recording the path.\n3. Visit entries from that position backward, retreating through leaves via\n   the stack (same as ReverseIterate), counting up to `count`.\n4. If `ascIdx \u003c 0` or `offset \u003e= size` or `count \u003c= 0`, return false.\n\n## Split details\n\n### Leaf split\n\nGiven a leaf with `fanout+1` entries (one over capacity):\n\n**Detection:** after inserting the new key, if it ended up at position\n`fanout` in the overflowed `fanout+1`-entry leaf, it is an append-pattern\ninsert (the new key is greater than all pre-existing keys).\n\n**90/10 split (append pattern):**\n- `mid = fanout - 1`\n- Left leaf keeps entries `[0, fanout-1)` = `fanout-1` entries.\n- New right leaf gets entries `[fanout-1, fanout+1)` = 2 entries.\n- Left has `fanout-1` entries (~97% full), right has 2.\n- For large fanouts, the right leaf may be below the `fanout/2` deletion\n  threshold. This is intentional — the 90/10 split prioritizes fill factor\n  for append-heavy workloads. If a subsequent Remove causes the right leaf\n  to underflow, the standard rebalance logic handles it.\n\n**50/50 split (random pattern):**\n- `mid = (fanout + 1) / 2`\n- Left leaf keeps entries `[0, mid)`.\n- New right leaf gets entries `[mid, fanout+1)`.\n\nIn both cases:\n- Separator promoted to parent = `right.keys[0]`.\n- No linked list updates needed (no sibling pointers).\n\n### Inner split\n\nGiven an inner node with `fanout+1` children:\n- `mid = (fanout + 1) / 2`\n- Left keeps children `[0, mid)` with keys `[0, mid-1)` and sizes `[0, mid)`.\n- Right gets children `[mid, fanout+1)` with keys `[mid, fanout)` and sizes `[mid, fanout+1)`.\n- The separator at `keys[mid-1]` is **promoted** to the parent (not kept in either child).\n- Parent's sizes entry for the original child is replaced by the sum of left's sizes,\n  and a new entry is inserted for the right child with the sum of right's sizes.\n\n## Minimum fanout\n\nFanout must be \u003e= 4. With fanout 3, a leaf splits into (2, 2) and\nthe minimum occupancy is 1, which makes merge logic degenerate. Fanout 4\ngives minimum occupancy 2 and clean split/merge behavior.\n\n`NewBPTreeN` panics if fanout \u003c 4.\n\n## File structure\n\n```\nexamples/gno.land/p/nt/bptree/v0/\n  gnomod.toml\n  doc.gno          — package doc\n  node.gno         — leafNode, innerNode, node interface, binary search\n  tree.gno         — BPTree struct, constructors, ITree methods,\n                     insert/split, remove/merge/redistribute, iteration\n  tree_test.gno    — comprehensive tests (mirroring avl tests + B+ tree specifics)\n```\n\nTwo source files (`node.gno` + `tree.gno`) plus one test file. The node\ntypes and tree logic are tightly coupled, so fewer files is better than\nspreading thin.\n\n## Ref-count safety\n\nIn Gno's persistence model, objects with ref-count \u003e= 2 \"escape\" — they are\npersisted separately in an iavl tree rather than inlined in their parent's\nserialized form. Once escaped, they are forever escaped. This is expensive\nand should be avoided.\n\n**Design constraint: every node must have exactly one persistent reference.**\n\nThis means:\n- **No sibling pointers** on leaf nodes (a leaf would be referenced by both\n  its parent and its neighbor → ref-count \u003e= 2).\n- **No `first`/`last` pointers** on BPTree (a leaf would be referenced by\n  both BPTree and its parent inner node → ref-count \u003e= 2).\n- **No shared subtrees** (each child is owned by exactly one parent).\n\nThe tree structure is a pure tree (not a graph) — every node has exactly\none parent reference. The `BPTree.root` is the sole reference to the root\nnode. Each `innerNode.children[i]` is the sole reference to child `i`.\n\nIteration uses an ephemeral stack (local slice) that is built and discarded\nwithin a single method call. It does not create any persistent references.\n\n## Edge cases (must match avl behavior exactly)\n\n### Values and keys\n- `nil` is a valid value. `Set(\"foo\", nil)` stores it; `Get(\"foo\")` returns\n  `nil`; `Has(\"foo\")` returns `true`. `Remove(\"foo\")` returns `(nil, true)`.\n- `\"\"` is a valid key. Stored, retrieved, removed like any other key.\n- `Get` on missing key returns `nil` (use `Has` to distinguish from a stored\n  nil value).\n- `Remove` on missing key returns `(nil, false)`.\n- `Set` same key twice replaces value, returns `updated=true`.\n\n### Zero-value and structural\n- `var t BPTree` must work — zero-value tree is usable without a constructor.\n  All methods work on it immediately. This means `root == nil` must be handled\n  gracefully everywhere, and the default `fanout` (0) must be promoted to 32\n  on first use. `Set` promotes on first call: `if t.fanout == 0 { t.fanout = 32 }`.\n  All other methods that read `t.fanout` guard with `if t.root == nil` first, so\n  fanout is always initialized before it is read. Once set, fanout never resets\n  (even if tree becomes empty again).\n- Remove last key → tree returns to empty state (root = nil).\n- Insert after removing everything works normally.\n- `Size()` on empty tree returns 0.\n- `GetByIndex` on empty tree panics. Negative index or index \u003e= size also panics.\n- Single entry: root is a leafNode with 1 entry.\n- Root is a leaf: no inner nodes until first split.\n- Root inner node collapses: after merge leaves root with 1 child,\n  replace root with that child.\n\n### Separator key maintenance\n- When the minimum key of a subtree changes (deletion of leftmost key,\n  or redistribution), the parent's separator key must be updated.\n  After modifying a child, check if `keys[childIdx-1]` still equals\n  `children[childIdx].minKey()`.\n\n### Iteration — key range\n- All iteration on an empty tree returns `false` without calling cb.\n- `Iterate(\"\", \"\", cb)` visits ALL entries ascending (canonical pattern).\n- `ReverseIterate(\"\", \"\", cb)` visits ALL entries descending.\n- `Iterate(\"a\", \"a\", cb)` → empty. [a,a) = nothing (start inclusive, end exclusive).\n- `ReverseIterate(\"a\", \"a\", cb)` → visits \"a\". [a,a] = one entry (both inclusive).\n- `Iterate(\"z\", \"a\", cb)` → empty (no validation, logic just excludes everything).\n- `ReverseIterate(\"z\", \"a\", cb)` → empty (bounds don't swap).\n- `Iterate(\"\", \"a\", cb)` → visits all keys \u003c \"a\".\n- `ReverseIterate(\"a\", \"\", cb)` → visits all keys \u003e= \"a\", in descending order.\n- Return value = true if callback stopped iteration early, false otherwise.\n\n### Iteration — offset\n- `IterateByOffset(0, 0, cb)` → nothing (count \u003c= 0).\n- `IterateByOffset(size, 1, cb)` → nothing (offset \u003e= size).\n- `ReverseIterateByOffset(0, N, cb)` → starts at largest key, takes N descending.\n- `ReverseIterateByOffset(1, 2, cb)` on [a,b,c,d,e] → [d, c].\n- Negative count → treated as count \u003c= 0 (no iteration).\n- Negative offset → clamped to 0 (avl silently treats negative as 0; we do the same explicitly).\n"},{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `bptree` - Mutable B+ tree\n\nA mutable, in-place B+ tree for storing key-value data in Gno realms. Exposes the same `ITree` interface as `gno.land/p/nt/avl/v0` but uses a B+ tree internally — fewer pointer dereferences per operation and better cache locality, with a configurable fanout.\n\n## Usage\n\n```go\npackage myrealm\n\nimport \"gno.land/p/nt/bptree/v0\"\n\n// Zero value is usable (fanout 32). Persisted across transactions.\nvar tree bptree.BPTree\n\nfunc Set(key string, value int) {\n    tree.Set(key, value)\n}\n\nfunc Get(key string) int {\n    raw := tree.Get(key)\n    if raw == nil {\n        panic(\"not found\")\n    }\n    return raw.(int)\n}\n\nfunc RangeAsc(start, end string) {\n    tree.Iterate(start, end, func(key string, value any) bool {\n        // return true to stop early\n        return false\n    })\n}\n```\n\nFor a different fanout, use a constructor:\n\n```go\ntree := bptree.NewBPTreeN(64) // fanout 64\n```\n\n## API\n\n```go\ntype BPTree struct{ /* unexported */ }\n\nfunc NewBPTree32() *BPTree            // fanout 32\nfunc NewBPTreeN(fanout int) *BPTree   // panics if fanout \u003c 4\n\n// Read\nfunc (t *BPTree) Size() int\nfunc (t *BPTree) Has(key string) bool\nfunc (t *BPTree) Get(key string) (value any) // nil if the key is absent\nfunc (t *BPTree) GetByIndex(index int) (key string, value any)\nfunc (t *BPTree) Iterate(start, end string, cb IterCbFn) bool\nfunc (t *BPTree) ReverseIterate(start, end string, cb IterCbFn) bool\nfunc (t *BPTree) IterateByOffset(offset, count int, cb IterCbFn) bool\nfunc (t *BPTree) ReverseIterateByOffset(offset, count int, cb IterCbFn) bool\n\n// Write\nfunc (t *BPTree) Set(key string, value any) (updated bool)\nfunc (t *BPTree) Remove(key string) (value any, removed bool)\n\ntype IterCbFn func(key string, value any) bool\n\ntype ITree interface { /* same shape as BPTree's methods */ }\n```\n\nThe zero value of `BPTree` is a usable empty tree (fanout 32). `Iterate` uses `[start, end)` (start inclusive, end exclusive); `ReverseIterate` uses `[start, end]` (both inclusive). Empty strings mean unbounded. Callbacks return `true` to stop early. `GetByIndex` panics on out-of-range indices.\n\nThe tree must not be modified during iteration (no `Set` or `Remove` from the callback).\n\n## Subpackages\n\n- `gno.land/p/nt/bptree/list/v0` - ordered list built on top of `BPTree`.\n- `gno.land/p/nt/bptree/pager/v0` - pagination helper for trees and lists.\n- `gno.land/p/nt/bptree/rotree/v0` - read-only view of a `BPTree`.\n\n## Notes\n\n- API and semantics match `gno.land/p/nt/avl/v0` exactly — `\"\"` is a valid key, `Get` returns `nil` for a missing key (use `Has` to distinguish a stored `nil`), and `Remove` returns `(nil, false)`.\n- Never return the live `*BPTree` from a realm getter: a caller can then call `Set`/`Remove` on it under your realm's authority. Return values, copies, or a read-only `rotree` view.\n- Sequential keys from `seqid` (`gno.land/p/nt/seqid/v0`) pair well here: monotonic inserts hit the append-optimized split path.\n- Fanout must be `\u003e= 4`. Higher fanouts mean shallower trees and fewer object loads per lookup, at the cost of larger individual node objects.\n- Each node (leaf or inner) is persisted as a separate object, so reads only load the `O(log n)` nodes on the search path — same storage-efficiency benefit as `avl`.\n- No sibling pointers or `first`/`last` shortcuts: iteration uses an ephemeral stack to keep every persisted node at ref-count 1 (avoids Gno's object-escape penalty).\n"},{"name":"doc.gno","body":"// Package bptree provides a mutable B+ tree implementation for storing\n// key-value data in Gno realms. It implements the same ITree interface\n// as the avl package but uses a B+ tree internally for better cache\n// locality and fewer pointer dereferences per operation.\n//\n// The fanout (maximum number of children per inner node, and maximum\n// number of entries per leaf node) is configurable:\n//\n//\ttree := bptree.NewBPTree32()    // fanout 32\n//\ttree := bptree.NewBPTreeN(64)   // fanout 64\n//\n// The zero value is usable as an empty tree with fanout 32:\n//\n//\tvar tree bptree.BPTree\n//\ttree.Set(\"key\", \"value\")\npackage bptree\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bptree/v0\"\ngno = \"0.9\"\n"},{"name":"node.gno","body":"package bptree\n\n// node is the interface satisfied by both inner and leaf nodes.\ntype node interface {\n\tisLeaf() bool\n\tnodeSize() int // total leaf entries in subtree\n\tminKey() string\n}\n\n//----------------------------------------\n// leafNode\n\ntype leafNode struct {\n\tkeys   []string\n\tvalues []*any // each value is a separate object for lazy loading\n}\n\nfunc newLeafNode(fanout int) *leafNode {\n\treturn \u0026leafNode{\n\t\tkeys:   make([]string, 0, fanout),\n\t\tvalues: make([]*any, 0, fanout),\n\t}\n}\n\nfunc (n *leafNode) isLeaf() bool   { return true }\nfunc (n *leafNode) nodeSize() int  { return len(n.keys) }\nfunc (n *leafNode) minKey() string { return n.keys[0] }\n\n// find returns the index where key is or would be inserted,\n// and whether an exact match was found.\nfunc (n *leafNode) find(key string) (int, bool) {\n\tlo, hi := 0, len(n.keys)\n\tfor lo \u003c hi {\n\t\tmid := lo + (hi-lo)/2\n\t\tif n.keys[mid] \u003c key {\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid\n\t\t}\n\t}\n\tif lo \u003c len(n.keys) \u0026\u0026 n.keys[lo] == key {\n\t\treturn lo, true\n\t}\n\treturn lo, false\n}\n\n// insertAt inserts a key-value pair at the given position.\nfunc (n *leafNode) insertAt(pos int, key string, value *any) {\n\tn.keys = append(n.keys, \"\")\n\tcopy(n.keys[pos+1:], n.keys[pos:])\n\tn.keys[pos] = key\n\n\tn.values = append(n.values, nil)\n\tcopy(n.values[pos+1:], n.values[pos:])\n\tn.values[pos] = value\n}\n\n// removeAt removes the entry at the given position and returns the removed key and value.\nfunc (n *leafNode) removeAt(pos int) (string, *any) {\n\tkey := n.keys[pos]\n\tvalue := n.values[pos]\n\n\tcopy(n.keys[pos:], n.keys[pos+1:])\n\tn.keys[len(n.keys)-1] = \"\"\n\tn.keys = n.keys[:len(n.keys)-1]\n\n\tcopy(n.values[pos:], n.values[pos+1:])\n\tn.values[len(n.values)-1] = nil\n\tn.values = n.values[:len(n.values)-1]\n\n\treturn key, value\n}\n\n//----------------------------------------\n// innerNode\n\ntype innerNode struct {\n\tkeys     []string // separator keys; keys[i] = minKey of children[i+1]\n\tchildren []node\n\tsizes    []int // sizes[i] = total leaf entries in children[i]\n}\n\nfunc newInnerNode(fanout int) *innerNode {\n\treturn \u0026innerNode{\n\t\tkeys:     make([]string, 0, fanout-1),\n\t\tchildren: make([]node, 0, fanout),\n\t\tsizes:    make([]int, 0, fanout),\n\t}\n}\n\nfunc (n *innerNode) isLeaf() bool { return false }\nfunc (n *innerNode) nodeSize() int {\n\tsum := 0\n\tfor _, s := range n.sizes {\n\t\tsum += s\n\t}\n\treturn sum\n}\nfunc (n *innerNode) minKey() string { return n.children[0].minKey() }\n\n// findChild returns the child index for the given key.\nfunc (n *innerNode) findChild(key string) int {\n\t// Binary search: find the rightmost i where keys[i] \u003c= key.\n\tlo, hi := 0, len(n.keys)\n\tfor lo \u003c hi {\n\t\tmid := lo + (hi-lo)/2\n\t\tif n.keys[mid] \u003c= key {\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid\n\t\t}\n\t}\n\treturn lo\n}\n\n// insertChildAt inserts a new child with its separator key at the given position.\n// The separator key is placed at keys[pos-1] (since keys[i] = minKey of children[i+1]).\nfunc (n *innerNode) insertChildAt(pos int, sep string, child node, sz int) {\n\t// Insert separator at keys[pos-1].\n\tkeyPos := pos - 1\n\tn.keys = append(n.keys, \"\")\n\tcopy(n.keys[keyPos+1:], n.keys[keyPos:])\n\tn.keys[keyPos] = sep\n\n\t// Insert child at children[pos].\n\tn.children = append(n.children, nil)\n\tcopy(n.children[pos+1:], n.children[pos:])\n\tn.children[pos] = child\n\n\t// Insert size at sizes[pos].\n\tn.sizes = append(n.sizes, 0)\n\tcopy(n.sizes[pos+1:], n.sizes[pos:])\n\tn.sizes[pos] = sz\n}\n\n// removeChildAt removes the child at pos and its associated separator key.\nfunc (n *innerNode) removeChildAt(pos int) {\n\t// Determine which separator to remove.\n\t// keys[i] separates children[i] from children[i+1].\n\t// Removing children[pos]: if pos \u003e 0, remove keys[pos-1]; else remove keys[0].\n\tkeyPos := pos\n\tif pos \u003e 0 {\n\t\tkeyPos = pos - 1\n\t}\n\tif len(n.keys) \u003e 0 {\n\t\tcopy(n.keys[keyPos:], n.keys[keyPos+1:])\n\t\tn.keys[len(n.keys)-1] = \"\"\n\t\tn.keys = n.keys[:len(n.keys)-1]\n\t}\n\n\tcopy(n.children[pos:], n.children[pos+1:])\n\tn.children[len(n.children)-1] = nil\n\tn.children = n.children[:len(n.children)-1]\n\n\tcopy(n.sizes[pos:], n.sizes[pos+1:])\n\tn.sizes = n.sizes[:len(n.sizes)-1]\n}\n"},{"name":"tree.gno","body":"package bptree\n\ntype ITree interface {\n\tSize() int\n\tHas(key string) bool\n\tGet(key string) any\n\tGetByIndex(index int) (key string, value any)\n\tIterate(start, end string, cb IterCbFn) bool\n\tReverseIterate(start, end string, cb IterCbFn) bool\n\tIterateByOffset(offset int, count int, cb IterCbFn) bool\n\tReverseIterateByOffset(offset int, count int, cb IterCbFn) bool\n\tSet(key string, value any) (updated bool)\n\tRemove(key string) (value any, removed bool)\n}\n\ntype IterCbFn func(key string, value any) bool\n\n// Verify BPTree implements ITree.\nvar _ ITree = (*BPTree)(nil)\n\n// The zero value is usable as an empty tree with fanout 32.\ntype BPTree struct {\n\troot   node\n\tsize   int\n\tfanout int\n}\n\n// NewBPTreeN creates a new empty B+ tree with the given fanout.\n// It panics when fanout is lower than 4.\nfunc NewBPTreeN(fanout int) *BPTree {\n\tif fanout \u003c 4 {\n\t\tpanic(\"bptree: fanout must be \u003e= 4\")\n\t}\n\treturn \u0026BPTree{fanout: fanout}\n}\n\n// NewBPTree32 creates a new empty B+ tree with fanout 32.\nfunc NewBPTree32() *BPTree {\n\treturn NewBPTreeN(32)\n}\n\nfunc (t *BPTree) Size() int {\n\treturn t.size\n}\n\nfunc (t *BPTree) Has(key string) bool {\n\tif t.root == nil {\n\t\treturn false\n\t}\n\tn := t.root\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tidx := inner.findChild(key)\n\t\tn = inner.children[idx]\n\t}\n\tleaf := n.(*leafNode)\n\t_, found := leaf.find(key)\n\treturn found\n}\n\n// Get retrieves the value associated with the given key.\n// It returns the value if the key exists, or nil if it doesn't.\n// This allows for a simpler usage pattern with type assertions:\n//\n//\tif value, ok := tree.Get(\"key\").(MyType); ok {\n//\t    // use value\n//\t}\n//\n// Use Has to distinguish a stored nil value from a missing key.\nfunc (t *BPTree) Get(key string) any {\n\tif t.root == nil {\n\t\treturn nil\n\t}\n\tn := t.root\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tidx := inner.findChild(key)\n\t\tn = inner.children[idx]\n\t}\n\tleaf := n.(*leafNode)\n\tpos, found := leaf.find(key)\n\tif !found {\n\t\treturn nil\n\t}\n\treturn *leaf.values[pos]\n}\n\n// GetByIndex returns the key-value pair at the given 0-based index.\n// Panics if index is out of range.\nfunc (t *BPTree) GetByIndex(index int) (key string, value any) {\n\tif t.root == nil || index \u003c 0 || index \u003e= t.size {\n\t\tpanic(\"GetByIndex asked for invalid index\")\n\t}\n\tn := t.root\n\trem := index\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tfound := false\n\t\tfor i, s := range inner.sizes {\n\t\t\tif rem \u003c s {\n\t\t\t\tn = inner.children[i]\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\trem -= s\n\t\t}\n\t\tif !found {\n\t\t\tpanic(\"GetByIndex asked for invalid index\")\n\t\t}\n\t}\n\tleaf := n.(*leafNode)\n\treturn leaf.keys[rem], *leaf.values[rem]\n}\n\n//----------------------------------------\n// Set\n\n// pathEntry records a step in the root-to-leaf descent.\ntype pathEntry struct {\n\tinner    *innerNode\n\tchildIdx int\n}\n\n// Set inserts or updates a key-value pair. Returns true if the key already existed.\nfunc (t *BPTree) Set(key string, value any) (updated bool) {\n\tif t.fanout == 0 {\n\t\tt.fanout = 32\n\t}\n\tfanout := t.fanout\n\n\tvp := \u0026value // wrap value in *any for lazy loading\n\n\t// Empty tree: create a single leaf.\n\tif t.root == nil {\n\t\tleaf := newLeafNode(fanout)\n\t\tleaf.keys = append(leaf.keys, key)\n\t\tleaf.values = append(leaf.values, vp)\n\t\tt.root = leaf\n\t\tt.size = 1\n\t\treturn false\n\t}\n\n\t// Descend to the leaf, recording the path.\n\tvar path []pathEntry\n\tn := t.root\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tidx := inner.findChild(key)\n\t\tpath = append(path, pathEntry{inner, idx})\n\t\tn = inner.children[idx]\n\t}\n\tleaf := n.(*leafNode)\n\n\t// Check if key already exists.\n\tpos, found := leaf.find(key)\n\tif found {\n\t\t*leaf.values[pos] = value\n\t\treturn true\n\t}\n\n\t// Insert new key-value.\n\tleaf.insertAt(pos, key, vp)\n\tt.size++\n\n\t// Increment sizes up the path.\n\tfor i := range path {\n\t\tpath[i].inner.sizes[path[i].childIdx]++\n\t}\n\n\t// Split if leaf overflows.\n\tif len(leaf.keys) \u003e fanout {\n\t\tt.splitLeaf(leaf, pos, path)\n\t}\n\n\treturn false\n}\n\n// splitLeaf splits an overflowed leaf node. Uses 90/10 split for append\n// patterns (insertPos == fanout) and 50/50 otherwise.\nfunc (t *BPTree) splitLeaf(leaf *leafNode, insertPos int, path []pathEntry) {\n\tfanout := t.fanout\n\n\t// 90/10 split for append pattern: new key ended up at position fanout\n\t// (greater than all pre-existing keys).\n\tvar mid int\n\tif insertPos == fanout {\n\t\tmid = fanout - 1\n\t} else {\n\t\tmid = (fanout + 1) / 2\n\t}\n\n\t// Create right leaf with entries [mid, fanout+1).\n\tright := newLeafNode(fanout)\n\tright.keys = append(right.keys, leaf.keys[mid:]...)\n\tright.values = append(right.values, leaf.values[mid:]...)\n\n\t// Truncate left leaf to [0, mid).\n\tfor i := mid; i \u003c len(leaf.keys); i++ {\n\t\tleaf.keys[i] = \"\"\n\t\tleaf.values[i] = nil\n\t}\n\tleaf.keys = leaf.keys[:mid]\n\tleaf.values = leaf.values[:mid]\n\n\t// Promote separator to parent.\n\tsep := right.keys[0]\n\tleftSize := len(leaf.keys)\n\trightSize := len(right.keys)\n\n\tif len(path) == 0 {\n\t\t// Root was the leaf; create a new inner root.\n\t\tnewRoot := newInnerNode(fanout)\n\t\tnewRoot.keys = append(newRoot.keys, sep)\n\t\tnewRoot.children = append(newRoot.children, leaf, right)\n\t\tnewRoot.sizes = append(newRoot.sizes, leftSize, rightSize)\n\t\tt.root = newRoot\n\t\treturn\n\t}\n\n\t// Insert into parent.\n\tpe := path[len(path)-1]\n\tparent := pe.inner\n\tchildIdx := pe.childIdx\n\n\tparent.sizes[childIdx] = leftSize\n\tparent.insertChildAt(childIdx+1, sep, right, rightSize)\n\n\tif len(parent.children) \u003e fanout {\n\t\tt.splitInner(parent, path[:len(path)-1])\n\t}\n}\n\n// splitInner splits an overflowed inner node (always 50/50).\nfunc (t *BPTree) splitInner(inner *innerNode, path []pathEntry) {\n\tfanout := t.fanout\n\tmid := (fanout + 1) / 2\n\n\tpromotedKey := inner.keys[mid-1]\n\n\tright := newInnerNode(fanout)\n\tright.keys = append(right.keys, inner.keys[mid:]...)\n\tright.children = append(right.children, inner.children[mid:]...)\n\tright.sizes = append(right.sizes, inner.sizes[mid:]...)\n\n\tfor i := mid - 1; i \u003c len(inner.keys); i++ {\n\t\tinner.keys[i] = \"\"\n\t}\n\tfor i := mid; i \u003c len(inner.children); i++ {\n\t\tinner.children[i] = nil\n\t}\n\tinner.keys = inner.keys[:mid-1]\n\tinner.children = inner.children[:mid]\n\tinner.sizes = inner.sizes[:mid]\n\n\tif len(path) == 0 {\n\t\tnewRoot := newInnerNode(fanout)\n\t\tnewRoot.keys = append(newRoot.keys, promotedKey)\n\t\tnewRoot.children = append(newRoot.children, inner, right)\n\t\tnewRoot.sizes = append(newRoot.sizes, inner.nodeSize(), right.nodeSize())\n\t\tt.root = newRoot\n\t\treturn\n\t}\n\n\tpe := path[len(path)-1]\n\tparent := pe.inner\n\tchildIdx := pe.childIdx\n\n\tparent.sizes[childIdx] = inner.nodeSize()\n\tparent.insertChildAt(childIdx+1, promotedKey, right, right.nodeSize())\n\n\tif len(parent.children) \u003e fanout {\n\t\tt.splitInner(parent, path[:len(path)-1])\n\t}\n}\n\n//----------------------------------------\n// Remove\n\n// Remove deletes a key. Returns the old value and true if the key was found.\nfunc (t *BPTree) Remove(key string) (value any, removed bool) {\n\tif t.root == nil {\n\t\treturn nil, false\n\t}\n\tfanout := t.fanout\n\n\tvar path []pathEntry\n\tn := t.root\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tidx := inner.findChild(key)\n\t\tpath = append(path, pathEntry{inner, idx})\n\t\tn = inner.children[idx]\n\t}\n\tleaf := n.(*leafNode)\n\n\tpos, found := leaf.find(key)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\tvar vp *any\n\t_, vp = leaf.removeAt(pos)\n\tvalue = *vp\n\tt.size--\n\n\tfor i := range path {\n\t\tpath[i].inner.sizes[path[i].childIdx]--\n\t}\n\n\t// Handle root leaf.\n\tif len(path) == 0 {\n\t\tif len(leaf.keys) == 0 {\n\t\t\tt.root = nil\n\t\t}\n\t\treturn value, true\n\t}\n\n\t// Check underflow.\n\tminKeys := fanout / 2\n\tif len(leaf.keys) \u003e= minKeys {\n\t\tif pos == 0 {\n\t\t\tt.updateSeparator(path)\n\t\t}\n\t\treturn value, true\n\t}\n\n\t// If the minimum key was removed, fix ancestor separators before rebalancing.\n\tif pos == 0 {\n\t\tt.updateSeparator(path)\n\t}\n\n\t// Rebalance.\n\tt.rebalanceLeaf(leaf, path)\n\treturn value, true\n}\n\n// updateSeparator fixes the parent's separator key if the child's min key changed\n// (e.g., after removing the leftmost entry).\nfunc (t *BPTree) updateSeparator(path []pathEntry) {\n\tfor i := len(path) - 1; i \u003e= 0; i-- {\n\t\tpe := path[i]\n\t\tif pe.childIdx \u003e 0 {\n\t\t\tchild := pe.inner.children[pe.childIdx]\n\t\t\tpe.inner.keys[pe.childIdx-1] = child.minKey()\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// rebalanceLeaf handles a leaf that has underflowed (\u003c fanout/2 entries).\n// Tries redistribute from left, then right, then merges with a sibling.\nfunc (t *BPTree) rebalanceLeaf(leaf *leafNode, path []pathEntry) {\n\tfanout := t.fanout\n\tminKeys := fanout / 2\n\tpe := path[len(path)-1]\n\tparent := pe.inner\n\tchildIdx := pe.childIdx\n\n\t// Try redistribute from left sibling.\n\tif childIdx \u003e 0 {\n\t\tleftSib := parent.children[childIdx-1].(*leafNode)\n\t\tif len(leftSib.keys) \u003e minKeys {\n\t\t\tk, v := leftSib.removeAt(len(leftSib.keys) - 1)\n\t\t\tleaf.insertAt(0, k, v)\n\t\t\tparent.keys[childIdx-1] = leaf.keys[0]\n\t\t\tparent.sizes[childIdx-1] = len(leftSib.keys)\n\t\t\tparent.sizes[childIdx] = len(leaf.keys)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Try redistribute from right sibling.\n\tif childIdx \u003c len(parent.children)-1 {\n\t\trightSib := parent.children[childIdx+1].(*leafNode)\n\t\tif len(rightSib.keys) \u003e minKeys {\n\t\t\tk, v := rightSib.removeAt(0)\n\t\t\tleaf.insertAt(len(leaf.keys), k, v)\n\t\t\tparent.keys[childIdx] = rightSib.keys[0]\n\t\t\tparent.sizes[childIdx] = len(leaf.keys)\n\t\t\tparent.sizes[childIdx+1] = len(rightSib.keys)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Merge.\n\tif childIdx \u003e 0 {\n\t\tleftSib := parent.children[childIdx-1].(*leafNode)\n\t\tmergeLeaves(leftSib, leaf, parent, childIdx)\n\t} else {\n\t\trightSib := parent.children[childIdx+1].(*leafNode)\n\t\tmergeLeaves(leaf, rightSib, parent, childIdx+1)\n\t}\n\n\tt.rebalanceInner(path[:len(path)-1])\n}\n\n// mergeLeaves merges right leaf into left and removes right from parent.\nfunc mergeLeaves(left, right *leafNode, parent *innerNode, rightIdx int) {\n\tleft.keys = append(left.keys, right.keys...)\n\tleft.values = append(left.values, right.values...)\n\tparent.removeChildAt(rightIdx)\n\tparent.sizes[rightIdx-1] = len(left.keys)\n}\n\n// rebalanceInner handles an inner node that has underflowed after a child merge.\nfunc (t *BPTree) rebalanceInner(path []pathEntry) {\n\tif len(path) == 0 {\n\t\troot := t.root.(*innerNode)\n\t\tif len(root.children) == 1 {\n\t\t\tt.root = root.children[0]\n\t\t}\n\t\treturn\n\t}\n\n\tpe := path[len(path)-1]\n\tparent := pe.inner\n\tchildIdx := pe.childIdx\n\tchild := parent.children[childIdx].(*innerNode)\n\tfanout := t.fanout\n\tminChildren := fanout / 2\n\n\tif len(child.children) \u003e= minChildren {\n\t\tif childIdx \u003e 0 {\n\t\t\tparent.keys[childIdx-1] = child.minKey()\n\t\t}\n\t\treturn\n\t}\n\n\t// Try redistribute from left sibling.\n\tif childIdx \u003e 0 {\n\t\tleftSib := parent.children[childIdx-1].(*innerNode)\n\t\tif len(leftSib.children) \u003e minChildren {\n\t\t\tredistributeInnerLeft(parent, childIdx, leftSib, child)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Try redistribute from right sibling.\n\tif childIdx \u003c len(parent.children)-1 {\n\t\trightSib := parent.children[childIdx+1].(*innerNode)\n\t\tif len(rightSib.children) \u003e minChildren {\n\t\t\tredistributeInnerRight(parent, childIdx, child, rightSib)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Merge.\n\tif childIdx \u003e 0 {\n\t\tleftSib := parent.children[childIdx-1].(*innerNode)\n\t\tmergeInner(leftSib, child, parent, childIdx)\n\t} else {\n\t\trightSib := parent.children[childIdx+1].(*innerNode)\n\t\tmergeInner(child, rightSib, parent, childIdx+1)\n\t}\n\n\tgrandPath := path[:len(path)-1]\n\tif len(grandPath) == 0 {\n\t\troot := t.root.(*innerNode)\n\t\tif len(root.children) == 1 {\n\t\t\tt.root = root.children[0]\n\t\t}\n\t\treturn\n\t}\n\n\tgpe := grandPath[len(grandPath)-1]\n\tgparent := gpe.inner\n\tgchildIdx := gpe.childIdx\n\tgchild := gparent.children[gchildIdx].(*innerNode)\n\tminChildren = t.fanout / 2\n\n\tif len(gchild.children) \u003c minChildren {\n\t\tt.rebalanceInner(grandPath)\n\t} else if gchildIdx \u003e 0 {\n\t\tgparent.keys[gchildIdx-1] = gchild.minKey()\n\t}\n}\n\n// redistributeInnerLeft moves the last child from left sibling to the\n// deficient child, pulling down the parent separator and pushing up a new one.\nfunc redistributeInnerLeft(parent *innerNode, childIdx int, leftSib, child *innerNode) {\n\tsep := parent.keys[childIdx-1]\n\tchild.keys = append(child.keys, \"\")\n\tcopy(child.keys[1:], child.keys)\n\tchild.keys[0] = sep\n\n\tlastChild := leftSib.children[len(leftSib.children)-1]\n\tlastSize := leftSib.sizes[len(leftSib.sizes)-1]\n\tchild.children = append(child.children, nil)\n\tcopy(child.children[1:], child.children)\n\tchild.children[0] = lastChild\n\tchild.sizes = append(child.sizes, 0)\n\tcopy(child.sizes[1:], child.sizes)\n\tchild.sizes[0] = lastSize\n\n\tparent.keys[childIdx-1] = leftSib.keys[len(leftSib.keys)-1]\n\n\tleftSib.keys[len(leftSib.keys)-1] = \"\"\n\tleftSib.keys = leftSib.keys[:len(leftSib.keys)-1]\n\tleftSib.children[len(leftSib.children)-1] = nil\n\tleftSib.children = leftSib.children[:len(leftSib.children)-1]\n\tleftSib.sizes = leftSib.sizes[:len(leftSib.sizes)-1]\n\n\tparent.sizes[childIdx-1] = leftSib.nodeSize()\n\tparent.sizes[childIdx] = child.nodeSize()\n}\n\n// redistributeInnerRight moves the first child from right sibling to the\n// deficient child, pulling down the parent separator and pushing up a new one.\nfunc redistributeInnerRight(parent *innerNode, childIdx int, child, rightSib *innerNode) {\n\tsep := parent.keys[childIdx]\n\tchild.keys = append(child.keys, sep)\n\n\tfirstChild := rightSib.children[0]\n\tfirstSize := rightSib.sizes[0]\n\tchild.children = append(child.children, firstChild)\n\tchild.sizes = append(child.sizes, firstSize)\n\n\tparent.keys[childIdx] = rightSib.keys[0]\n\n\tcopy(rightSib.keys, rightSib.keys[1:])\n\trightSib.keys[len(rightSib.keys)-1] = \"\"\n\trightSib.keys = rightSib.keys[:len(rightSib.keys)-1]\n\tcopy(rightSib.children, rightSib.children[1:])\n\trightSib.children[len(rightSib.children)-1] = nil\n\trightSib.children = rightSib.children[:len(rightSib.children)-1]\n\tcopy(rightSib.sizes, rightSib.sizes[1:])\n\trightSib.sizes = rightSib.sizes[:len(rightSib.sizes)-1]\n\n\tparent.sizes[childIdx] = child.nodeSize()\n\tparent.sizes[childIdx+1] = rightSib.nodeSize()\n}\n\n// mergeInner merges right inner node into left, pulling down the parent\n// separator, and removes right from parent.\nfunc mergeInner(left, right *innerNode, parent *innerNode, rightIdx int) {\n\tsep := parent.keys[rightIdx-1]\n\tleft.keys = append(left.keys, sep)\n\tleft.keys = append(left.keys, right.keys...)\n\tleft.children = append(left.children, right.children...)\n\tleft.sizes = append(left.sizes, right.sizes...)\n\tparent.removeChildAt(rightIdx)\n\tparent.sizes[rightIdx-1] = left.nodeSize()\n}\n\n//----------------------------------------\n// Stack-based iteration\n\n// iterStack is a stack of (innerNode, childIdx) for traversal.\n// It is ephemeral — built during iteration, discarded after.\ntype iterStack []pathEntry\n\n// descendLeft descends to the leftmost leaf, pushing inner nodes onto the stack.\nfunc descendLeft(n node, stack *iterStack) *leafNode {\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\t*stack = append(*stack, pathEntry{inner, 0})\n\t\tn = inner.children[0]\n\t}\n\treturn n.(*leafNode)\n}\n\n// descendRight descends to the rightmost leaf, pushing inner nodes onto the stack.\nfunc descendRight(n node, stack *iterStack) *leafNode {\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tlast := len(inner.children) - 1\n\t\t*stack = append(*stack, pathEntry{inner, last})\n\t\tn = inner.children[last]\n\t}\n\treturn n.(*leafNode)\n}\n\n// advanceLeaf moves to the next leaf in ascending order via the stack.\n// Returns nil if there is no next leaf.\nfunc advanceLeaf(stack *iterStack) *leafNode {\n\tfor len(*stack) \u003e 0 {\n\t\ttop := \u0026(*stack)[len(*stack)-1]\n\t\ttop.childIdx++\n\t\tif top.childIdx \u003c len(top.inner.children) {\n\t\t\tn := top.inner.children[top.childIdx]\n\t\t\treturn descendLeft(n, stack)\n\t\t}\n\t\t*stack = (*stack)[:len(*stack)-1]\n\t}\n\treturn nil\n}\n\n// retreatLeaf moves to the previous leaf in descending order via the stack.\n// Returns nil if there is no previous leaf.\nfunc retreatLeaf(stack *iterStack) *leafNode {\n\tfor len(*stack) \u003e 0 {\n\t\ttop := \u0026(*stack)[len(*stack)-1]\n\t\ttop.childIdx--\n\t\tif top.childIdx \u003e= 0 {\n\t\t\tn := top.inner.children[top.childIdx]\n\t\t\treturn descendRight(n, stack)\n\t\t}\n\t\t*stack = (*stack)[:len(*stack)-1]\n\t}\n\treturn nil\n}\n\n//----------------------------------------\n// Iterate / ReverseIterate\n\n// Iterate calls cb for each key-value pair in [start, end) ascending order.\n// Empty start/end means no bound. Returns true if stopped early by cb.\n// The tree must not be modified during iteration (no Set or Remove from the callback).\nfunc (t *BPTree) Iterate(start, end string, cb IterCbFn) bool {\n\tif t.root == nil {\n\t\treturn false\n\t}\n\n\tvar stack iterStack\n\tvar leaf *leafNode\n\tvar pos int\n\n\tif start == \"\" {\n\t\tleaf = descendLeft(t.root, \u0026stack)\n\t\tpos = 0\n\t} else {\n\t\tleaf, pos, stack = t.descendToGE(start)\n\t\tif leaf == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfor leaf != nil {\n\t\tfor pos \u003c len(leaf.keys) {\n\t\t\tk := leaf.keys[pos]\n\t\t\tif end != \"\" \u0026\u0026 k \u003e= end {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif cb(k, *leaf.values[pos]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tpos++\n\t\t}\n\t\tleaf = advanceLeaf(\u0026stack)\n\t\tpos = 0\n\t}\n\treturn false\n}\n\n// ReverseIterate calls cb for each key-value pair in [start, end] descending order.\n// Empty start/end means no bound. Returns true if stopped early by cb.\n// The tree must not be modified during iteration (no Set or Remove from the callback).\nfunc (t *BPTree) ReverseIterate(start, end string, cb IterCbFn) bool {\n\tif t.root == nil {\n\t\treturn false\n\t}\n\n\tvar stack iterStack\n\tvar leaf *leafNode\n\tvar pos int\n\n\tif end == \"\" {\n\t\tleaf = descendRight(t.root, \u0026stack)\n\t\tpos = len(leaf.keys) - 1\n\t} else {\n\t\tleaf, pos, stack = t.descendToLE(end)\n\t\tif leaf == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfor leaf != nil {\n\t\tfor pos \u003e= 0 {\n\t\t\tk := leaf.keys[pos]\n\t\t\tif start != \"\" \u0026\u0026 k \u003c start {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif cb(k, *leaf.values[pos]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tpos--\n\t\t}\n\t\tleaf = retreatLeaf(\u0026stack)\n\t\tif leaf != nil {\n\t\t\tpos = len(leaf.keys) - 1\n\t\t}\n\t}\n\treturn false\n}\n\n// IterateByOffset calls cb for count entries starting at the offset-th entry\n// in ascending order. Returns true if stopped early by cb.\n// The tree must not be modified during iteration (no Set or Remove from the callback).\nfunc (t *BPTree) IterateByOffset(offset int, count int, cb IterCbFn) bool {\n\tif t.root == nil || offset \u003e= t.size || count \u003c= 0 {\n\t\treturn false\n\t}\n\tif offset \u003c 0 {\n\t\toffset = 0\n\t}\n\n\tleaf, pos, stack := t.descendToOffset(offset)\n\n\tvisited := 0\n\tfor leaf != nil \u0026\u0026 visited \u003c count {\n\t\tfor pos \u003c len(leaf.keys) \u0026\u0026 visited \u003c count {\n\t\t\tif cb(leaf.keys[pos], *leaf.values[pos]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tvisited++\n\t\t\tpos++\n\t\t}\n\t\tleaf = advanceLeaf(\u0026stack)\n\t\tpos = 0\n\t}\n\treturn false\n}\n\n// ReverseIterateByOffset calls cb for count entries starting at the offset-th\n// entry from the end, in descending order. Returns true if stopped early by cb.\n// The tree must not be modified during iteration (no Set or Remove from the callback).\nfunc (t *BPTree) ReverseIterateByOffset(offset int, count int, cb IterCbFn) bool {\n\tif t.root == nil || offset \u003e= t.size || count \u003c= 0 {\n\t\treturn false\n\t}\n\tif offset \u003c 0 {\n\t\toffset = 0\n\t}\n\n\tascIdx := t.size - 1 - offset\n\tleaf, pos, stack := t.descendToOffset(ascIdx)\n\n\tvisited := 0\n\tfor leaf != nil \u0026\u0026 visited \u003c count {\n\t\tfor pos \u003e= 0 \u0026\u0026 visited \u003c count {\n\t\t\tif cb(leaf.keys[pos], *leaf.values[pos]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tvisited++\n\t\t\tpos--\n\t\t}\n\t\tleaf = retreatLeaf(\u0026stack)\n\t\tif leaf != nil {\n\t\t\tpos = len(leaf.keys) - 1\n\t\t}\n\t}\n\treturn false\n}\n\n//----------------------------------------\n// Descent helpers for iteration\n\n// descendToGE descends to the first key \u003e= key, returning the leaf, position, and stack.\nfunc (t *BPTree) descendToGE(key string) (*leafNode, int, iterStack) {\n\tvar stack iterStack\n\tn := t.root\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tidx := inner.findChild(key)\n\t\tstack = append(stack, pathEntry{inner, idx})\n\t\tn = inner.children[idx]\n\t}\n\tleaf := n.(*leafNode)\n\tpos, _ := leaf.find(key)\n\tif pos \u003e= len(leaf.keys) {\n\t\tnext := advanceLeaf(\u0026stack)\n\t\tif next == nil {\n\t\t\treturn nil, 0, nil\n\t\t}\n\t\treturn next, 0, stack\n\t}\n\treturn leaf, pos, stack\n}\n\n// descendToLE descends to the last key \u003c= key, returning the leaf, position, and stack.\nfunc (t *BPTree) descendToLE(key string) (*leafNode, int, iterStack) {\n\tvar stack iterStack\n\tn := t.root\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tidx := inner.findChild(key)\n\t\tstack = append(stack, pathEntry{inner, idx})\n\t\tn = inner.children[idx]\n\t}\n\tleaf := n.(*leafNode)\n\tpos, found := leaf.find(key)\n\tif found {\n\t\treturn leaf, pos, stack\n\t}\n\tif pos \u003e 0 {\n\t\treturn leaf, pos - 1, stack\n\t}\n\tprev := retreatLeaf(\u0026stack)\n\tif prev == nil {\n\t\treturn nil, 0, nil\n\t}\n\treturn prev, len(prev.keys) - 1, stack\n}\n\n// descendToOffset descends to the offset-th entry using sizes[],\n// returning the leaf, position within leaf, and stack.\nfunc (t *BPTree) descendToOffset(offset int) (*leafNode, int, iterStack) {\n\tvar stack iterStack\n\tn := t.root\n\trem := offset\n\tfor !n.isLeaf() {\n\t\tinner := n.(*innerNode)\n\t\tfound := false\n\t\tfor i, s := range inner.sizes {\n\t\t\tif rem \u003c s {\n\t\t\t\tstack = append(stack, pathEntry{inner, i})\n\t\t\t\tn = inner.children[i]\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\trem -= s\n\t\t}\n\t\tif !found {\n\t\t\tpanic(\"descendToOffset: offset out of range\")\n\t\t}\n\t}\n\treturn n.(*leafNode), rem, stack\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"rotree","path":"gno.land/p/nt/bptree/rotree/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bptree/rotree/v0\"\ngno = \"0.9\"\n"},{"name":"rotree.gno","body":"// Package rotree provides a read-only wrapper for bptree.BPTree with safe value transformation.\n//\n// It is useful when you want to expose a read-only view of a tree while ensuring that\n// the sensitive data cannot be modified.\n//\n// Example:\n//\n//\t// Define a user structure with sensitive data\n//\ttype User struct {\n//\t\tName     string\n//\t\tBalance  int\n//\t\tInternal string // sensitive field\n//\t}\n//\n//\t// Create and populate the original tree\n//\tprivateTree := bptree.NewBPTree32()\n//\tprivateTree.Set(\"alice\", \u0026User{\n//\t\tName:     \"Alice\",\n//\t\tBalance:  100,\n//\t\tInternal: \"sensitive\",\n//\t})\n//\n//\t// Create a safe transformation function that copies the struct\n//\t// while excluding sensitive data\n//\tmakeEntrySafeFn := func(v any) any {\n//\t\tu := v.(*User)\n//\t\treturn \u0026User{\n//\t\t\tName:     u.Name,\n//\t\t\tBalance:  u.Balance,\n//\t\t\tInternal: \"\", // omit sensitive data\n//\t\t}\n//\t}\n//\n//\t// Create a read-only view of the tree\n//\tPublicTree := rotree.Wrap(tree, makeEntrySafeFn)\n//\n//\t// Safely access the data\n//\tvalue := roTree.Get(\"alice\")\n//\tuser := value.(*User)\n//\t// user.Name == \"Alice\"\n//\t// user.Balance == 100\n//\t// user.Internal == \"\" (sensitive data is filtered)\npackage rotree\n\nimport (\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\n// Wrap creates a new ReadOnlyTree from an existing bptree.BPTree and a safety transformation function.\n// If makeEntrySafeFn is nil, values will be returned as-is without transformation.\nfunc Wrap(tree *bptree.BPTree, makeEntrySafeFn func(any) any) *ReadOnlyTree {\n\treturn \u0026ReadOnlyTree{\n\t\ttree:            tree,\n\t\tmakeEntrySafeFn: makeEntrySafeFn,\n\t}\n}\n\n// ReadOnlyTree wraps a bptree.BPTree and provides read-only access.\ntype ReadOnlyTree struct {\n\ttree            *bptree.BPTree\n\tmakeEntrySafeFn func(any) any\n}\n\n// IReadOnlyTree defines the read-only operations available on a tree.\ntype IReadOnlyTree interface {\n\tSize() int\n\tHas(key string) bool\n\tGet(key string) any\n\tGetByIndex(index int) (string, any)\n\tIterate(start, end string, cb bptree.IterCbFn) bool\n\tReverseIterate(start, end string, cb bptree.IterCbFn) bool\n\tIterateByOffset(offset int, count int, cb bptree.IterCbFn) bool\n\tReverseIterateByOffset(offset int, count int, cb bptree.IterCbFn) bool\n}\n\n// Verify that ReadOnlyTree implements both ITree and IReadOnlyTree\nvar (\n\t_ bptree.ITree  = (*ReadOnlyTree)(nil)\n\t_ IReadOnlyTree = (*ReadOnlyTree)(nil)\n)\n\n// getSafeValue applies the makeEntrySafeFn if it exists, otherwise returns the original value\nfunc (roTree *ReadOnlyTree) getSafeValue(value any) any {\n\tif roTree.makeEntrySafeFn == nil {\n\t\treturn value\n\t}\n\treturn roTree.makeEntrySafeFn(value)\n}\n\n// Size returns the number of key-value pairs in the tree.\nfunc (roTree *ReadOnlyTree) Size() int {\n\treturn roTree.tree.Size()\n}\n\n// Has checks whether a key exists in the tree.\nfunc (roTree *ReadOnlyTree) Has(key string) bool {\n\treturn roTree.tree.Has(key)\n}\n\n// Get retrieves the value associated with the given key, converted to a safe format.\n// It returns the value if the key exists, or nil if it doesn't.\nfunc (roTree *ReadOnlyTree) Get(key string) any {\n\tvalue := roTree.tree.Get(key)\n\tif value == nil {\n\t\treturn nil\n\t}\n\treturn roTree.getSafeValue(value)\n}\n\n// GetByIndex retrieves the key-value pair at the specified index in the tree, with the value converted to a safe format.\nfunc (roTree *ReadOnlyTree) GetByIndex(index int) (string, any) {\n\tkey, value := roTree.tree.GetByIndex(index)\n\treturn key, roTree.getSafeValue(value)\n}\n\n// Iterate performs an in-order traversal of the tree within the specified key range.\nfunc (roTree *ReadOnlyTree) Iterate(start, end string, cb bptree.IterCbFn) bool {\n\treturn roTree.tree.Iterate(start, end, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// ReverseIterate performs a reverse in-order traversal of the tree within the specified key range.\nfunc (roTree *ReadOnlyTree) ReverseIterate(start, end string, cb bptree.IterCbFn) bool {\n\treturn roTree.tree.ReverseIterate(start, end, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// IterateByOffset performs an in-order traversal of the tree starting from the specified offset.\nfunc (roTree *ReadOnlyTree) IterateByOffset(offset int, count int, cb bptree.IterCbFn) bool {\n\treturn roTree.tree.IterateByOffset(offset, count, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// ReverseIterateByOffset performs a reverse in-order traversal of the tree starting from the specified offset.\nfunc (roTree *ReadOnlyTree) ReverseIterateByOffset(offset int, count int, cb bptree.IterCbFn) bool {\n\treturn roTree.tree.ReverseIterateByOffset(offset, count, func(key string, value any) bool {\n\t\treturn cb(key, roTree.getSafeValue(value))\n\t})\n}\n\n// Set is not supported on ReadOnlyTree and will panic.\nfunc (roTree *ReadOnlyTree) Set(key string, value any) bool {\n\tpanic(\"Set operation not supported on ReadOnlyTree\")\n}\n\n// Remove is not supported on ReadOnlyTree and will panic.\nfunc (roTree *ReadOnlyTree) Remove(key string) (value any, removed bool) {\n\tpanic(\"Remove operation not supported on ReadOnlyTree\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"cford32","path":"gno.land/p/nt/cford32/v0","files":[{"name":"LICENSE","body":"Copyright (c) 2009 The Go Authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n   * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n   * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n   * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `cford32` - Crockford Base32 encoding\n\nModified base32 encoding using the [Crockford alphabet](https://www.crockford.com/base32.html). Designed to be human-readable, error-resistant, and pronounceable: the ambiguous characters `I`, `L`, `O`, `U` are excluded from the encoding, and decoding accepts `I`/`L` as `1` and `O` as `0`. Output is never padded.\n\n## Usage\n\n```go\nimport \"gno.land/p/nt/cford32/v0\"\n\n// Byte slice encode/decode.\nencoded := cford32.EncodeToString([]byte(\"hello\"))  // uppercase, no padding\ndecoded, err := cford32.DecodeString(encoded)        // []byte(\"hello\")\n\n// Lowercase variant.\nlower := cford32.EncodeToStringLower([]byte(\"hello\"))\n\n// Compact uint64 encoding: 7 bytes for id \u003c 2^34, else 13 bytes.\nenc := cford32.PutCompact(42)\nback, _ := cford32.Uint64(enc) // 42\n\n// Full fixed-width uint64 encoding (always 13 bytes).\nfull := cford32.PutUint64(42)\n```\n\n## API\n\n```go\n// Errors.\ntype CorruptInputError int64\nfunc (e CorruptInputError) Error() string\n\n// Length helpers.\nfunc DecodedLen(n int) int\nfunc EncodedLen(n int) int\n\n// Byte slice encoding.\nfunc Encode(dst, src []byte)                          // uppercase\nfunc EncodeLower(dst, src []byte)                     // lowercase\nfunc EncodeToString(src []byte) string                // uppercase\nfunc EncodeToStringLower(src []byte) string           // lowercase\nfunc AppendEncode(dst, src []byte) []byte\nfunc AppendEncodeLower(dst, src []byte) []byte\n\n// Byte slice decoding. Case-insensitive; ignores \\r and \\n.\nfunc Decode(dst, src []byte) (n int, err error)\nfunc DecodeString(s string) ([]byte, error)\nfunc AppendDecode(dst, src []byte) ([]byte, error)\n\n// uint64 encoding.\nfunc PutUint64(id uint64) [13]byte                    // full, uppercase\nfunc PutUint64Lower(id uint64) [13]byte               // full, lowercase\nfunc PutCompact(id uint64) []byte                     // 7 bytes if id \u003c 2^34, else 13, lowercase\nfunc AppendCompact(id uint64, b []byte) []byte\nfunc Uint64(b []byte) (uint64, error)                 // accepts both compact (7) and full (13)\n\n// Streaming I/O.\nfunc NewEncoder(w io.Writer) io.WriteCloser\nfunc NewEncoderLower(w io.Writer) io.WriteCloser\nfunc NewDecoder(r io.Reader) io.Reader\n```\n\n## Notes\n\n- Alphabet: `0123456789ABCDEFGHJKMNPQRSTVWXYZ` (no `I`, `L`, `O`, `U`).\n- Decoding is case-insensitive; `I`/`i`/`L`/`l` decode as `1`, and `O`/`o` decode as `0`.\n- The compact uint64 encoding preserves lexicographic order with numeric order, making encoded IDs suitable as ordered keys.\n- The compact and full uint64 encodings are unambiguously distinguished by their first character: `0`-`f` indicates compact (7 bytes), `g`-`z` indicates full (13 bytes).\n- Values in `[0, 2^34)` have BOTH a compact and a full encoding. Pick one scheme per key space and stick to it: mixing both for the same value breaks the lexicographic-order property. `PutCompact` rolls over from compact to full at `2^34` automatically, which is safe as long as everything in that space is generated the same way.\n- For sequential IDs, see [`gno.land/p/nt/seqid/v0`](../../seqid/v0).\n"},{"name":"cford32.gno","body":"// Modified from the Go Source code for encoding/base32.\n// Copyright 2009 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Package cford32 implements a base32-like encoding/decoding package, with the\n// encoding scheme [specified by Douglas Crockford].\n//\n// From the website, the requirements of said encoding scheme are to:\n//\n//   - Be human readable and machine readable.\n//   - Be compact. Humans have difficulty in manipulating long strings of arbitrary symbols.\n//   - Be error resistant. Entering the symbols must not require keyboarding gymnastics.\n//   - Be pronounceable. Humans should be able to accurately transmit the symbols to other humans using a telephone.\n//\n// This is slightly different from a simple difference in encoding table from\n// the Go's stdlib `encoding/base32`, as when decoding the characters i I l L are\n// parsed as 1, and o O is parsed as 0.\n//\n// This package additionally provides ways to encode uint64's efficiently,\n// as well as efficient encoding to a lowercase variation of the encoding.\n// The encodings never use paddings.\n//\n// # Uint64 Encoding\n//\n// Aside from lower/uppercase encoding, there is a compact encoding, allowing\n// to encode all values in [0,2^34), and the full encoding, allowing all\n// values in [0,2^64). The compact encoding uses 7 characters, and the full\n// encoding uses 13 characters. Both are parsed unambiguously by the Uint64\n// decoder.\n//\n// The compact encodings have the first character between ['0','f'], while the\n// full encoding's first character ranges between ['g','z']. Practically, in\n// your usage of the package, you should consider which one to use and stick\n// with it, while considering that the compact encoding, once it reaches 2^34,\n// automatically switches to the full encoding. The properties of the generated\n// strings are still maintained: for instance, any two encoded uint64s x,y\n// consistently generated with the compact encoding, if the numeric value is\n// x \u003c y, will also be x \u003c y in lexical ordering. However, values [0,2^34) have a\n// \"double encoding\", which if mixed together lose the lexical ordering property.\n//\n// The Uint64 encoding is most useful for generating string versions of Uint64\n// IDs. Practically, it allows you to retain sleek and compact IDs for your\n// application for the first 2^34 (\u003e17 billion) entities, while seamlessly\n// rolling over to the full encoding should you exceed that. You are encouraged\n// to use it unless you have a requirement or preferences for IDs consistently\n// being always the same size.\n//\n// To use the cford32 encoding for IDs, you may want to consider using package\n// [gno.land/p/nt/seqid/v0].\n//\n// [specified by Douglas Crockford]: https://www.crockford.com/base32.html\npackage cford32\n\nimport (\n\t\"io\"\n\t\"strconv\"\n)\n\nconst (\n\tencTable      = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\"\n\tencTableLower = \"0123456789abcdefghjkmnpqrstvwxyz\"\n\n\t// each line is 16 bytes\n\tdecTable = \"\" +\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" + // 00-0f\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" + // 10-1f\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" + // 20-2f\n\t\t\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\xff\\xff\\xff\\xff\\xff\\xff\" + // 30-3f\n\t\t\"\\xff\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x10\\x11\\x01\\x12\\x13\\x01\\x14\\x15\\x00\" + // 40-4f\n\t\t\"\\x16\\x17\\x18\\x19\\x1a\\xff\\x1b\\x1c\\x1d\\x1e\\x1f\\xff\\xff\\xff\\xff\\xff\" + // 50-5f\n\t\t\"\\xff\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x10\\x11\\x01\\x12\\x13\\x01\\x14\\x15\\x00\" + // 60-6f\n\t\t\"\\x16\\x17\\x18\\x19\\x1a\\xff\\x1b\\x1c\\x1d\\x1e\\x1f\\xff\\xff\\xff\\xff\\xff\" + // 70-7f\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" + // 80-ff (not ASCII)\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" +\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" +\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" +\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" +\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" +\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\" +\n\t\t\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"\n)\n\n// CorruptInputError is returned by parsing functions when an invalid character\n// in the input is found. The integer value represents the byte index where\n// the error occurred.\n//\n// This is typically because the given character does not exist in the encoding.\ntype CorruptInputError int64\n\nfunc (e CorruptInputError) Error() string {\n\treturn \"illegal cford32 data at input byte \" + strconv.FormatInt(int64(e), 10)\n}\n\n// Uint64 parses a cford32-encoded byte slice into a uint64.\n//\n//   - The parser requires all provided character to be valid cford32 characters.\n//   - The parser disregards case.\n//   - If the first character is '0' \u003c= c \u003c= 'f', then the passed value is assumed\n//     encoded in the compact encoding, and must be 7 characters long.\n//   - If the first character is 'g' \u003c= c \u003c= 'z',  then the passed value is\n//     assumed encoded in the full encoding, and must be 13 characters long.\n//\n// If any of these requirements fail, a CorruptInputError will be returned.\nfunc Uint64(b []byte) (uint64, error) {\n\tif len(b) == 0 {\n\t\treturn 0, CorruptInputError(0)\n\t}\n\tb0 := decTable[b[0]]\n\tswitch {\n\tdefault:\n\t\treturn 0, CorruptInputError(0)\n\tcase len(b) == 7 \u0026\u0026 b0 \u003c 16:\n\t\tdecVals := [7]byte{\n\t\t\tdecTable[b[0]],\n\t\t\tdecTable[b[1]],\n\t\t\tdecTable[b[2]],\n\t\t\tdecTable[b[3]],\n\t\t\tdecTable[b[4]],\n\t\t\tdecTable[b[5]],\n\t\t\tdecTable[b[6]],\n\t\t}\n\t\tfor idx, v := range decVals {\n\t\t\tif v \u003e= 32 {\n\t\t\t\treturn 0, CorruptInputError(idx)\n\t\t\t}\n\t\t}\n\n\t\treturn 0 +\n\t\t\tuint64(decVals[0])\u003c\u003c30 |\n\t\t\tuint64(decVals[1])\u003c\u003c25 |\n\t\t\tuint64(decVals[2])\u003c\u003c20 |\n\t\t\tuint64(decVals[3])\u003c\u003c15 |\n\t\t\tuint64(decVals[4])\u003c\u003c10 |\n\t\t\tuint64(decVals[5])\u003c\u003c5 |\n\t\t\tuint64(decVals[6]), nil\n\tcase len(b) == 13 \u0026\u0026 b0 \u003e= 16 \u0026\u0026 b0 \u003c 32:\n\t\tdecVals := [13]byte{\n\t\t\tdecTable[b[0]] \u0026 0x0F, // disregard high bit\n\t\t\tdecTable[b[1]],\n\t\t\tdecTable[b[2]],\n\t\t\tdecTable[b[3]],\n\t\t\tdecTable[b[4]],\n\t\t\tdecTable[b[5]],\n\t\t\tdecTable[b[6]],\n\t\t\tdecTable[b[7]],\n\t\t\tdecTable[b[8]],\n\t\t\tdecTable[b[9]],\n\t\t\tdecTable[b[10]],\n\t\t\tdecTable[b[11]],\n\t\t\tdecTable[b[12]],\n\t\t}\n\t\tfor idx, v := range decVals {\n\t\t\tif v \u003e= 32 {\n\t\t\t\treturn 0, CorruptInputError(idx)\n\t\t\t}\n\t\t}\n\n\t\treturn 0 +\n\t\t\tuint64(decVals[0])\u003c\u003c60 |\n\t\t\tuint64(decVals[1])\u003c\u003c55 |\n\t\t\tuint64(decVals[2])\u003c\u003c50 |\n\t\t\tuint64(decVals[3])\u003c\u003c45 |\n\t\t\tuint64(decVals[4])\u003c\u003c40 |\n\t\t\tuint64(decVals[5])\u003c\u003c35 |\n\t\t\tuint64(decVals[6])\u003c\u003c30 |\n\t\t\tuint64(decVals[7])\u003c\u003c25 |\n\t\t\tuint64(decVals[8])\u003c\u003c20 |\n\t\t\tuint64(decVals[9])\u003c\u003c15 |\n\t\t\tuint64(decVals[10])\u003c\u003c10 |\n\t\t\tuint64(decVals[11])\u003c\u003c5 |\n\t\t\tuint64(decVals[12]), nil\n\t}\n}\n\nconst mask = 31\n\n// PutUint64 returns a cford32-encoded byte slice.\nfunc PutUint64(id uint64) [13]byte {\n\treturn [13]byte{\n\t\tencTable[id\u003e\u003e60\u0026mask|0x10], // specify full encoding\n\t\tencTable[id\u003e\u003e55\u0026mask],\n\t\tencTable[id\u003e\u003e50\u0026mask],\n\t\tencTable[id\u003e\u003e45\u0026mask],\n\t\tencTable[id\u003e\u003e40\u0026mask],\n\t\tencTable[id\u003e\u003e35\u0026mask],\n\t\tencTable[id\u003e\u003e30\u0026mask],\n\t\tencTable[id\u003e\u003e25\u0026mask],\n\t\tencTable[id\u003e\u003e20\u0026mask],\n\t\tencTable[id\u003e\u003e15\u0026mask],\n\t\tencTable[id\u003e\u003e10\u0026mask],\n\t\tencTable[id\u003e\u003e5\u0026mask],\n\t\tencTable[id\u0026mask],\n\t}\n}\n\n// PutUint64Lower returns a cford32-encoded byte array, swapping uppercase\n// letters with lowercase.\n//\n// For more information on how the value is encoded, see [Uint64].\nfunc PutUint64Lower(id uint64) [13]byte {\n\treturn [13]byte{\n\t\tencTableLower[id\u003e\u003e60\u0026mask|0x10],\n\t\tencTableLower[id\u003e\u003e55\u0026mask],\n\t\tencTableLower[id\u003e\u003e50\u0026mask],\n\t\tencTableLower[id\u003e\u003e45\u0026mask],\n\t\tencTableLower[id\u003e\u003e40\u0026mask],\n\t\tencTableLower[id\u003e\u003e35\u0026mask],\n\t\tencTableLower[id\u003e\u003e30\u0026mask],\n\t\tencTableLower[id\u003e\u003e25\u0026mask],\n\t\tencTableLower[id\u003e\u003e20\u0026mask],\n\t\tencTableLower[id\u003e\u003e15\u0026mask],\n\t\tencTableLower[id\u003e\u003e10\u0026mask],\n\t\tencTableLower[id\u003e\u003e5\u0026mask],\n\t\tencTableLower[id\u0026mask],\n\t}\n}\n\n// PutCompact returns a cford32-encoded byte slice, using the compact\n// representation of cford32 described in the package documentation where\n// possible (all values of id \u003c 1\u003c\u003c34). The lowercase encoding is used.\n//\n// The resulting byte slice will be 7 bytes long for all compact values,\n// and 13 bytes long for\nfunc PutCompact(id uint64) []byte {\n\treturn AppendCompact(id, nil)\n}\n\n// AppendCompact works like [PutCompact] but appends to the given byte slice\n// instead of allocating one anew.\nfunc AppendCompact(id uint64, b []byte) []byte {\n\tconst maxCompact = 1 \u003c\u003c 34\n\tif id \u003c maxCompact {\n\t\treturn append(b,\n\t\t\tencTableLower[id\u003e\u003e30\u0026mask],\n\t\t\tencTableLower[id\u003e\u003e25\u0026mask],\n\t\t\tencTableLower[id\u003e\u003e20\u0026mask],\n\t\t\tencTableLower[id\u003e\u003e15\u0026mask],\n\t\t\tencTableLower[id\u003e\u003e10\u0026mask],\n\t\t\tencTableLower[id\u003e\u003e5\u0026mask],\n\t\t\tencTableLower[id\u0026mask],\n\t\t)\n\t}\n\treturn append(b,\n\t\tencTableLower[id\u003e\u003e60\u0026mask|0x10],\n\t\tencTableLower[id\u003e\u003e55\u0026mask],\n\t\tencTableLower[id\u003e\u003e50\u0026mask],\n\t\tencTableLower[id\u003e\u003e45\u0026mask],\n\t\tencTableLower[id\u003e\u003e40\u0026mask],\n\t\tencTableLower[id\u003e\u003e35\u0026mask],\n\t\tencTableLower[id\u003e\u003e30\u0026mask],\n\t\tencTableLower[id\u003e\u003e25\u0026mask],\n\t\tencTableLower[id\u003e\u003e20\u0026mask],\n\t\tencTableLower[id\u003e\u003e15\u0026mask],\n\t\tencTableLower[id\u003e\u003e10\u0026mask],\n\t\tencTableLower[id\u003e\u003e5\u0026mask],\n\t\tencTableLower[id\u0026mask],\n\t)\n}\n\nfunc DecodedLen(n int) int {\n\treturn n/8*5 + n%8*5/8\n}\n\nfunc EncodedLen(n int) int {\n\treturn n/5*8 + (n%5*8+4)/5\n}\n\n// Encode encodes src using the encoding enc,\n// writing [EncodedLen](len(src)) bytes to dst.\n//\n// The encoding does not contain any padding, unlike Go's base32.\nfunc Encode(dst, src []byte) {\n\t// Copied from encoding/base32/base32.go (go1.22)\n\tif len(src) == 0 {\n\t\treturn\n\t}\n\n\tdi, si := 0, 0\n\tn := (len(src) / 5) * 5\n\tfor si \u003c n {\n\t\t// Combining two 32 bit loads allows the same code to be used\n\t\t// for 32 and 64 bit platforms.\n\t\thi := uint32(src[si+0])\u003c\u003c24 | uint32(src[si+1])\u003c\u003c16 | uint32(src[si+2])\u003c\u003c8 | uint32(src[si+3])\n\t\tlo := hi\u003c\u003c8 | uint32(src[si+4])\n\n\t\tdst[di+0] = encTable[(hi\u003e\u003e27)\u00260x1F]\n\t\tdst[di+1] = encTable[(hi\u003e\u003e22)\u00260x1F]\n\t\tdst[di+2] = encTable[(hi\u003e\u003e17)\u00260x1F]\n\t\tdst[di+3] = encTable[(hi\u003e\u003e12)\u00260x1F]\n\t\tdst[di+4] = encTable[(hi\u003e\u003e7)\u00260x1F]\n\t\tdst[di+5] = encTable[(hi\u003e\u003e2)\u00260x1F]\n\t\tdst[di+6] = encTable[(lo\u003e\u003e5)\u00260x1F]\n\t\tdst[di+7] = encTable[(lo)\u00260x1F]\n\n\t\tsi += 5\n\t\tdi += 8\n\t}\n\n\t// Add the remaining small block\n\tremain := len(src) - si\n\tif remain == 0 {\n\t\treturn\n\t}\n\n\t// Encode the remaining bytes in reverse order.\n\tval := uint32(0)\n\tswitch remain {\n\tcase 4:\n\t\tval |= uint32(src[si+3])\n\t\tdst[di+6] = encTable[val\u003c\u003c3\u00260x1F]\n\t\tdst[di+5] = encTable[val\u003e\u003e2\u00260x1F]\n\t\tfallthrough\n\tcase 3:\n\t\tval |= uint32(src[si+2]) \u003c\u003c 8\n\t\tdst[di+4] = encTable[val\u003e\u003e7\u00260x1F]\n\t\tfallthrough\n\tcase 2:\n\t\tval |= uint32(src[si+1]) \u003c\u003c 16\n\t\tdst[di+3] = encTable[val\u003e\u003e12\u00260x1F]\n\t\tdst[di+2] = encTable[val\u003e\u003e17\u00260x1F]\n\t\tfallthrough\n\tcase 1:\n\t\tval |= uint32(src[si+0]) \u003c\u003c 24\n\t\tdst[di+1] = encTable[val\u003e\u003e22\u00260x1F]\n\t\tdst[di+0] = encTable[val\u003e\u003e27\u00260x1F]\n\t}\n}\n\n// EncodeLower is like [Encode], but uses the lowercase\nfunc EncodeLower(dst, src []byte) {\n\t// Copied from encoding/base32/base32.go (go1.22)\n\tif len(src) == 0 {\n\t\treturn\n\t}\n\n\tdi, si := 0, 0\n\tn := (len(src) / 5) * 5\n\tfor si \u003c n {\n\t\t// Combining two 32 bit loads allows the same code to be used\n\t\t// for 32 and 64 bit platforms.\n\t\thi := uint32(src[si+0])\u003c\u003c24 | uint32(src[si+1])\u003c\u003c16 | uint32(src[si+2])\u003c\u003c8 | uint32(src[si+3])\n\t\tlo := hi\u003c\u003c8 | uint32(src[si+4])\n\n\t\tdst[di+0] = encTableLower[(hi\u003e\u003e27)\u00260x1F]\n\t\tdst[di+1] = encTableLower[(hi\u003e\u003e22)\u00260x1F]\n\t\tdst[di+2] = encTableLower[(hi\u003e\u003e17)\u00260x1F]\n\t\tdst[di+3] = encTableLower[(hi\u003e\u003e12)\u00260x1F]\n\t\tdst[di+4] = encTableLower[(hi\u003e\u003e7)\u00260x1F]\n\t\tdst[di+5] = encTableLower[(hi\u003e\u003e2)\u00260x1F]\n\t\tdst[di+6] = encTableLower[(lo\u003e\u003e5)\u00260x1F]\n\t\tdst[di+7] = encTableLower[(lo)\u00260x1F]\n\n\t\tsi += 5\n\t\tdi += 8\n\t}\n\n\t// Add the remaining small block\n\tremain := len(src) - si\n\tif remain == 0 {\n\t\treturn\n\t}\n\n\t// Encode the remaining bytes in reverse order.\n\tval := uint32(0)\n\tswitch remain {\n\tcase 4:\n\t\tval |= uint32(src[si+3])\n\t\tdst[di+6] = encTableLower[val\u003c\u003c3\u00260x1F]\n\t\tdst[di+5] = encTableLower[val\u003e\u003e2\u00260x1F]\n\t\tfallthrough\n\tcase 3:\n\t\tval |= uint32(src[si+2]) \u003c\u003c 8\n\t\tdst[di+4] = encTableLower[val\u003e\u003e7\u00260x1F]\n\t\tfallthrough\n\tcase 2:\n\t\tval |= uint32(src[si+1]) \u003c\u003c 16\n\t\tdst[di+3] = encTableLower[val\u003e\u003e12\u00260x1F]\n\t\tdst[di+2] = encTableLower[val\u003e\u003e17\u00260x1F]\n\t\tfallthrough\n\tcase 1:\n\t\tval |= uint32(src[si+0]) \u003c\u003c 24\n\t\tdst[di+1] = encTableLower[val\u003e\u003e22\u00260x1F]\n\t\tdst[di+0] = encTableLower[val\u003e\u003e27\u00260x1F]\n\t}\n}\n\n// AppendEncode appends the cford32 encoded src to dst\n// and returns the extended buffer.\nfunc AppendEncode(dst, src []byte) []byte {\n\tn := EncodedLen(len(src))\n\tdst = grow(dst, n)\n\tEncode(dst[len(dst):][:n], src)\n\treturn dst[:len(dst)+n]\n}\n\n// AppendEncodeLower appends the lowercase cford32 encoded src to dst\n// and returns the extended buffer.\nfunc AppendEncodeLower(dst, src []byte) []byte {\n\tn := EncodedLen(len(src))\n\tdst = grow(dst, n)\n\tEncodeLower(dst[len(dst):][:n], src)\n\treturn dst[:len(dst)+n]\n}\n\nfunc grow(s []byte, n int) []byte {\n\t// slices.Grow\n\tif n -= cap(s) - len(s); n \u003e 0 {\n\t\tnews := make([]byte, cap(s)+n)\n\t\tcopy(news[:cap(s)], s[:cap(s)])\n\t\treturn news[:len(s)]\n\t}\n\treturn s\n}\n\n// EncodeToString returns the cford32 encoding of src.\nfunc EncodeToString(src []byte) string {\n\tbuf := make([]byte, EncodedLen(len(src)))\n\tEncode(buf, src)\n\treturn string(buf)\n}\n\n// EncodeToStringLower returns the cford32 lowercase encoding of src.\nfunc EncodeToStringLower(src []byte) string {\n\tbuf := make([]byte, EncodedLen(len(src)))\n\tEncodeLower(buf, src)\n\treturn string(buf)\n}\n\nfunc decode(dst, src []byte) (n int, err error) {\n\tdsti := 0\n\tolen := len(src)\n\n\tfor len(src) \u003e 0 {\n\t\t// Decode quantum using the base32 alphabet\n\t\tvar dbuf [8]byte\n\t\tdlen := 8\n\n\t\tfor j := 0; j \u003c 8; {\n\t\t\tif len(src) == 0 {\n\t\t\t\t// We have reached the end and are not expecting any padding\n\t\t\t\tdlen = j\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tin := src[0]\n\t\t\tsrc = src[1:]\n\t\t\tdbuf[j] = decTable[in]\n\t\t\tif dbuf[j] == 0xFF {\n\t\t\t\treturn n, CorruptInputError(olen - len(src) - 1)\n\t\t\t}\n\t\t\tj++\n\t\t}\n\n\t\t// Pack 8x 5-bit source blocks into 5 byte destination\n\t\t// quantum\n\t\tswitch dlen {\n\t\tcase 8:\n\t\t\tdst[dsti+4] = dbuf[6]\u003c\u003c5 | dbuf[7]\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 7:\n\t\t\tdst[dsti+3] = dbuf[4]\u003c\u003c7 | dbuf[5]\u003c\u003c2 | dbuf[6]\u003e\u003e3\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 5:\n\t\t\tdst[dsti+2] = dbuf[3]\u003c\u003c4 | dbuf[4]\u003e\u003e1\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 4:\n\t\t\tdst[dsti+1] = dbuf[1]\u003c\u003c6 | dbuf[2]\u003c\u003c1 | dbuf[3]\u003e\u003e4\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 2:\n\t\t\tdst[dsti+0] = dbuf[0]\u003c\u003c3 | dbuf[1]\u003e\u003e2\n\t\t\tn++\n\t\t}\n\t\tdsti += 5\n\t}\n\treturn n, nil\n}\n\ntype encoder struct {\n\terr  error\n\tw    io.Writer\n\tenc  func(dst, src []byte)\n\tbuf  [5]byte    // buffered data waiting to be encoded\n\tnbuf int        // number of bytes in buf\n\tout  [1024]byte // output buffer\n}\n\nfunc NewEncoder(w io.Writer) io.WriteCloser {\n\treturn \u0026encoder{w: w, enc: Encode}\n}\n\nfunc NewEncoderLower(w io.Writer) io.WriteCloser {\n\treturn \u0026encoder{w: w, enc: EncodeLower}\n}\n\nfunc (e *encoder) Write(p []byte) (n int, err error) {\n\tif e.err != nil {\n\t\treturn 0, e.err\n\t}\n\n\t// Leading fringe.\n\tif e.nbuf \u003e 0 {\n\t\tvar i int\n\t\tfor i = 0; i \u003c len(p) \u0026\u0026 e.nbuf \u003c 5; i++ {\n\t\t\te.buf[e.nbuf] = p[i]\n\t\t\te.nbuf++\n\t\t}\n\t\tn += i\n\t\tp = p[i:]\n\t\tif e.nbuf \u003c 5 {\n\t\t\treturn\n\t\t}\n\t\te.enc(e.out[0:], e.buf[0:])\n\t\tif _, e.err = e.w.Write(e.out[0:8]); e.err != nil {\n\t\t\treturn n, e.err\n\t\t}\n\t\te.nbuf = 0\n\t}\n\n\t// Large interior chunks.\n\tfor len(p) \u003e= 5 {\n\t\tnn := len(e.out) / 8 * 5\n\t\tif nn \u003e len(p) {\n\t\t\tnn = len(p)\n\t\t\tnn -= nn % 5\n\t\t}\n\t\te.enc(e.out[0:], p[0:nn])\n\t\tif _, e.err = e.w.Write(e.out[0 : nn/5*8]); e.err != nil {\n\t\t\treturn n, e.err\n\t\t}\n\t\tn += nn\n\t\tp = p[nn:]\n\t}\n\n\t// Trailing fringe.\n\tcopy(e.buf[:], p)\n\te.nbuf = len(p)\n\tn += len(p)\n\treturn\n}\n\n// Close flushes any pending output from the encoder.\n// It is an error to call Write after calling Close.\nfunc (e *encoder) Close() error {\n\t// If there's anything left in the buffer, flush it out\n\tif e.err == nil \u0026\u0026 e.nbuf \u003e 0 {\n\t\te.enc(e.out[0:], e.buf[0:e.nbuf])\n\t\tencodedLen := EncodedLen(e.nbuf)\n\t\te.nbuf = 0\n\t\t_, e.err = e.w.Write(e.out[0:encodedLen])\n\t}\n\treturn e.err\n}\n\n// Decode decodes src using cford32. It writes at most\n// [DecodedLen](len(src)) bytes to dst and returns the number of bytes\n// written. If src contains invalid cford32 data, it will return the\n// number of bytes successfully written and [CorruptInputError].\n// Newline characters (\\r and \\n) are ignored.\nfunc Decode(dst, src []byte) (n int, err error) {\n\tbuf := make([]byte, len(src))\n\tl := stripNewlines(buf, src)\n\treturn decode(dst, buf[:l])\n}\n\n// AppendDecode appends the cford32 decoded src to dst\n// and returns the extended buffer.\n// If the input is malformed, it returns the partially decoded src and an error.\nfunc AppendDecode(dst, src []byte) ([]byte, error) {\n\tn := DecodedLen(len(src))\n\n\tdst = grow(dst, n)\n\tdstsl := dst[len(dst) : len(dst)+n]\n\tn, err := Decode(dstsl, src)\n\treturn dst[:len(dst)+n], err\n}\n\n// DecodeString returns the bytes represented by the cford32 string s.\nfunc DecodeString(s string) ([]byte, error) {\n\tbuf := []byte(s)\n\tl := stripNewlines(buf, buf)\n\tn, err := decode(buf, buf[:l])\n\treturn buf[:n], err\n}\n\n// stripNewlines removes newline characters and returns the number\n// of non-newline characters copied to dst.\nfunc stripNewlines(dst, src []byte) int {\n\toffset := 0\n\tfor _, b := range src {\n\t\tif b == '\\r' || b == '\\n' {\n\t\t\tcontinue\n\t\t}\n\t\tdst[offset] = b\n\t\toffset++\n\t}\n\treturn offset\n}\n\ntype decoder struct {\n\terr    error\n\tr      io.Reader\n\tbuf    [1024]byte // leftover input\n\tnbuf   int\n\tout    []byte // leftover decoded output\n\toutbuf [1024 / 8 * 5]byte\n}\n\n// NewDecoder constructs a new base32 stream decoder.\nfunc NewDecoder(r io.Reader) io.Reader {\n\treturn \u0026decoder{r: \u0026newlineFilteringReader{r}}\n}\n\nfunc readEncodedData(r io.Reader, buf []byte) (n int, err error) {\n\tfor n \u003c 1 \u0026\u0026 err == nil {\n\t\tvar nn int\n\t\tnn, err = r.Read(buf[n:])\n\t\tn += nn\n\t}\n\treturn\n}\n\nfunc (d *decoder) Read(p []byte) (n int, err error) {\n\t// Use leftover decoded output from last read.\n\tif len(d.out) \u003e 0 {\n\t\tn = copy(p, d.out)\n\t\td.out = d.out[n:]\n\t\tif len(d.out) == 0 {\n\t\t\treturn n, d.err\n\t\t}\n\t\treturn n, nil\n\t}\n\n\tif d.err != nil {\n\t\treturn 0, d.err\n\t}\n\n\t// Read nn bytes from input, bounded [8,len(d.buf)]\n\tnn := (len(p)/5 + 1) * 8\n\tif nn \u003e len(d.buf) {\n\t\tnn = len(d.buf)\n\t}\n\n\tnn, d.err = readEncodedData(d.r, d.buf[d.nbuf:nn])\n\td.nbuf += nn\n\tif d.nbuf \u003c 1 {\n\t\treturn 0, d.err\n\t}\n\n\t// Decode chunk into p, or d.out and then p if p is too small.\n\tnr := d.nbuf\n\tif d.err != io.EOF \u0026\u0026 nr%8 != 0 {\n\t\tnr -= nr % 8\n\t}\n\tnw := DecodedLen(d.nbuf)\n\n\tif nw \u003e len(p) {\n\t\tnw, err = decode(d.outbuf[0:], d.buf[0:nr])\n\t\td.out = d.outbuf[0:nw]\n\t\tn = copy(p, d.out)\n\t\td.out = d.out[n:]\n\t} else {\n\t\tn, err = decode(p, d.buf[0:nr])\n\t}\n\td.nbuf -= nr\n\tfor i := 0; i \u003c d.nbuf; i++ {\n\t\td.buf[i] = d.buf[i+nr]\n\t}\n\n\tif err != nil \u0026\u0026 (d.err == nil || d.err == io.EOF) {\n\t\td.err = err\n\t}\n\n\tif len(d.out) \u003e 0 {\n\t\t// We cannot return all the decoded bytes to the caller in this\n\t\t// invocation of Read, so we return a nil error to ensure that Read\n\t\t// will be called again.  The error stored in d.err, if any, will be\n\t\t// returned with the last set of decoded bytes.\n\t\treturn n, nil\n\t}\n\n\treturn n, d.err\n}\n\ntype newlineFilteringReader struct {\n\twrapped io.Reader\n}\n\nfunc (r *newlineFilteringReader) Read(p []byte) (int, error) {\n\tn, err := r.wrapped.Read(p)\n\tfor n \u003e 0 {\n\t\ts := p[0:n]\n\t\toffset := stripNewlines(s, s)\n\t\tif err != nil || offset \u003e 0 {\n\t\t\treturn offset, err\n\t\t}\n\t\t// Previous buffer entirely whitespace, read again\n\t\tn, err = r.wrapped.Read(p)\n\t}\n\treturn n, err\n}\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package cford32 implements a modified base32 encoding based on Douglas\n// Crockford's base32 encoding.\npackage cford32\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/cford32/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"seqid","path":"gno.land/p/nt/seqid/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `seqid` - Sequential IDs\n\nSequential ID generator producing ordered binary and string representations suitable for use as AVL tree keys. String IDs use [cford32](../../cford32/v0)'s compact encoding and preserve lexicographic ordering.\n\n## Usage\n\n```go\nimport (\n    \"gno.land/p/nt/avl/v0\"\n    \"gno.land/p/nt/seqid/v0\"\n)\n\nvar (\n    id    seqid.ID\n    users avl.Tree\n)\n\nfunc NewUser(name string) {\n    user := \u0026User{Name: name}\n\n    // String() is human-friendly and preserves ordering.\n    users.Set(id.Next().String(), user)\n\n    // Or persist the binary form as a fixed-width 8-byte AVL key.\n    users.Set(id.Next().Binary(), user)\n}\n\n// Recover an ID from user input (case-insensitive, sanitized).\nfunc Lookup(raw string) (seqid.ID, error) {\n    return seqid.FromString(raw)\n}\n```\n\n## API\n\n```go\n// An ID is a sequential ID. The zero value is valid; the first\n// Next() call returns 1.\ntype ID uint64\n\n// Next advances the ID and returns the new value. Panics on overflow.\nfunc (i *ID) Next() ID\n\n// TryNext is like Next but returns false instead of panicking on overflow.\nfunc (i *ID) TryNext() (ID, bool)\n\n// Binary returns a fixed 8-byte big-endian encoding of the ID, suitable\n// as an AVL key. Lexicographic order matches numeric order.\nfunc (i ID) Binary() string\n\n// String returns the cford32 compact encoding of the ID: 7 bytes for\n// IDs in [0, 2^34), 13 bytes after that. Lexicographic order matches\n// numeric order across the rollover.\nfunc (i ID) String() string\n\n// FromBinary parses a value produced by Binary.\nfunc FromBinary(b string) (ID, bool)\n\n// FromString parses a cford32-encoded ID. Case-insensitive; maps\n// I/L to 1 and O to 0. Always re-encode user input via FromString\n// then String() before using it as a key.\nfunc FromString(b string) (ID, error)\n```\n\n## Notes\n\n- `Binary()` is the cheapest and most compact key (8 bytes, fixed width). Prefer it for internal storage. The keys work with any `ITree` (`gno.land/p/nt/avl/v0` or `gno.land/p/nt/bptree/v0`); their monotonic order suits bptree's append path especially well.\n- `String()` is human-friendly and URL-safe; use it for IDs surfaced to users.\n- Because cford32 accepts multiple spellings for the same value, always normalize external input through `FromString` then `String()` before using it as a lookup key.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package seqid provides a simple way to have sequential IDs which will be\n// ordered correctly when inserted in an AVL tree.\npackage seqid\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/seqid/v0\"\ngno = \"0.9\"\n"},{"name":"seqid.gno","body":"// Package seqid provides a simple way to have sequential IDs which will be\n// ordered correctly when inserted in an AVL tree.\n//\n// Sample usage:\n//\n//\tvar id seqid.ID\n//\tvar users avl.Tree\n//\n//\tfunc NewUser() {\n//\t\tusers.Set(id.Next().String(), \u0026User{ ... })\n//\t}\npackage seqid\n\nimport (\n\t\"encoding/binary\"\n\n\t\"gno.land/p/nt/cford32/v0\"\n)\n\n// An ID is a simple sequential ID generator.\ntype ID uint64\n\n// Next advances the ID i.\n// It will panic if increasing ID would overflow.\nfunc (i *ID) Next() ID {\n\tnext, ok := i.TryNext()\n\tif !ok {\n\t\tpanic(\"seqid: next ID overflows uint64\")\n\t}\n\treturn next\n}\n\nconst maxID ID = 1\u003c\u003c64 - 1\n\n// TryNext increases i by 1 and returns its value.\n// It returns true if successful, or false if the increment would result in\n// an overflow.\nfunc (i *ID) TryNext() (ID, bool) {\n\tif *i == maxID {\n\t\t// Addition will overflow.\n\t\treturn 0, false\n\t}\n\t*i++\n\treturn *i, true\n}\n\n// Binary returns a big-endian binary representation of the ID,\n// suitable to be used as an AVL key.\nfunc (i ID) Binary() string {\n\tbuf := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(buf, uint64(i))\n\treturn string(buf)\n}\n\n// String encodes i using cford32's compact encoding. For more information,\n// see the documentation for package [gno.land/p/nt/cford32/v0].\n//\n// The result of String will be a 7-byte string for IDs [0,2^34), and a\n// 13-byte string for all values following that. All generated string IDs\n// follow the same lexicographic order as their number values; that is, for any\n// two IDs (x, y) such that x \u003c y, x.String() \u003c y.String().\n// As such, this string representation is suitable to be used as an AVL key.\nfunc (i ID) String() string {\n\treturn string(cford32.PutCompact(uint64(i)))\n}\n\n// FromBinary creates a new ID from the given string, expected to be a binary\n// big-endian encoding of an ID (such as that of [ID.Binary]).\n// The second return value is true if the conversion was successful.\nfunc FromBinary(b string) (ID, bool) {\n\tif len(b) != 8 {\n\t\treturn 0, false\n\t}\n\treturn ID(binary.BigEndian.Uint64([]byte(b))), true\n}\n\n// FromString creates a new ID from the given string, expected to be a string\n// representation using cford32, such as that returned by [ID.String].\n//\n// The encoding scheme used by cford32 allows the same ID to have many\n// different representations (though the one returned by [ID.String] is only\n// one, deterministic and safe to be used in AVL). The encoding scheme is\n// \"human-centric\" and is thus case insensitive, and maps some ambiguous\n// characters to be the same, ie. L = I = 1, O = 0. For this reason, when\n// parsing user input to retrieve a key (encoded as a string), always sanitize\n// it first using FromString, then run String(), instead of using the user's\n// input directly.\nfunc FromString(b string) (ID, error) {\n\tn, err := cford32.Uint64([]byte(b))\n\treturn ID(n), err\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"dao","path":"gno.land/r/gov/dao","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da\"\n"},{"name":"proxy.gno","body":"package dao\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// dao is the actual govDAO implementation, having all the needed business logic\nvar dao DAO\n\n// allowedDAOs contains realms that can be used to update the actual govDAO implementation,\n// and validate Proposals.\n// This is like that to be able to rollback using a previous govDAO implementation in case\n// the latest implementation has a breaking bug. After a test period, a proposal can be\n// executed to remove all previous govDAOs implementations and leave the last one.\nvar allowedDAOs []string\n\n// proposals contains all the proposals in history.\nvar proposals *Proposals = NewProposals()\n\n// Render calls directly to Render's DAO implementation.\n// This allows to have this realm as the main entry point for everything.\nfunc Render(cur realm, p string) string {\n\tif dao == nil {\n\t\treturn \"DAO not initialized\"\n\t}\n\treturn dao.Render(cross(cur), cur.PkgPath(), p)\n}\n\n// MustCreateProposal is an utility method that does the same as CreateProposal,\n// but instead of erroing if something happens, it panics.\nfunc MustCreateProposal(cur realm, r ProposalRequest) ProposalID {\n\tpid, err := CreateProposal(cur, r)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn pid\n}\n\n// ExecuteProposal will try to execute the proposal with the provided ProposalID.\n// If the proposal was denied, it will return false. If the proposal is correctly\n// executed, it will return true. If something happens this function will panic.\nfunc ExecuteProposal(cur realm, pid ProposalID) bool {\n\treturn executeProposal(cur, pid, false)\n}\n\n// ExecuteOrRejectProposal executes the proposal with the provided ProposalID or rejects\n// it when there is an execution error.\n// If the proposal was denied, it will return false. If the proposal is correctly\n// executed, it will return true, unless execution fails with an error, in which case\n// proposal is rejected with the error as the reason.\n// This function allows to finish proposals by rejecting them when there is a state\n// change or an error in the proposal parameters that makes execution fail, potentially\n// leaving the proposal active forever because it can't be successfully executed.\nfunc ExecuteOrRejectProposal(cur realm, pid ProposalID) bool {\n\treturn executeProposal(cur, pid, true)\n}\n\n// CreateProposal will try to create a new proposal, that will be validated by the actual\n// govDAO implementation. If the proposal cannot be created, an error will be returned.\nfunc CreateProposal(cur realm, r ProposalRequest) (ProposalID, error) {\n\tif dao == nil {\n\t\treturn -1, errors.New(\"DAO not initialized\")\n\t}\n\tauthor, err := dao.PreCreateProposal(0, cur, r)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tp := \u0026Proposal{\n\t\tauthor:      author,\n\t\ttitle:       r.title,\n\t\tdescription: r.description,\n\t\texecutor:    r.executor,\n\t\tallowedDAOs: allowedDAOs[:],\n\t}\n\n\tpid := proposals.SetProposal(p)\n\tdao.PostCreateProposal(0, cur, r, pid)\n\n\tchain.Emit(\"ProposalCreated\",\n\t\t\"id\", strconv.FormatInt(int64(pid), 10),\n\t)\n\n\treturn pid, nil\n}\n\nfunc MustVoteOnProposal(cur realm, r VoteRequest) {\n\tif err := VoteOnProposal(cur, r); err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\n// VoteOnProposal sends a vote to the actual govDAO implementation.\n// If the voter cannot vote the specified proposal, this method will return an error\n// with the explanation of why.\nfunc VoteOnProposal(cur realm, r VoteRequest) error {\n\tif dao == nil {\n\t\treturn errors.New(\"DAO not initialized\")\n\t}\n\treturn dao.VoteOnProposal(0, cur, r)\n}\n\n// MustVoteOnProposalSimple is like MustVoteOnProposal but intended to be used through gnokey with basic types.\nfunc MustVoteOnProposalSimple(cur realm, pid int64, option string) {\n\tMustVoteOnProposal(cur, VoteRequest{\n\t\tOption:     VoteOption(option),\n\t\tProposalID: ProposalID(pid),\n\t})\n}\n\nfunc MustGetProposal(pid ProposalID) *Proposal {\n\tp, err := GetProposal(pid)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn p\n}\n\n// GetProposal gets created proposal by its ID. Non-crossing pure read:\n// looks up the proposal in this realm's package var. Callable directly\n// from any realm without cross-call syntax.\nfunc GetProposal(pid ProposalID) (*Proposal, error) {\n\tif dao == nil {\n\t\treturn nil, errors.New(\"DAO not initialized\")\n\t}\n\tprop := proposals.GetProposal(pid)\n\tif prop == nil {\n\t\treturn nil, errors.New(ufmt.Sprintf(\"Proposal %v does not exist.\", int64(pid)))\n\t}\n\treturn prop, nil\n}\n\n// UpdateImpl is a method intended to be used on a proposal.\n// This method will update the current govDAO implementation\n// to a new one. AllowedDAOs are a list of realms that can\n// call this method, in case the new DAO implementation had\n// a breaking bug. A nil DAO is ignored.\n// If AllowedDAOs field is not set correctly, the actual DAO\n// implementation wont be able to execute new Proposals!\n//\n// An empty AllowedDAOs is ignored rather than stored. An empty list makes\n// InAllowedDAOs() return true for every caller — the bootstrap-only state that\n// lets the genesis MsgRun seed the member set. Since this is the only site that\n// assigns allowedDAOs, ignoring empty here makes the transition\n// empty -\u003e non-empty one-way: once locked down the DAO cannot be reopened,\n// whether the empty value arrives as a literal []string{} or from\n// NewUpdateRequest(d, nil), which copies nil into a non-nil empty slice.\n// Individual entries must be non-blank realm paths; an empty entry would match\n// a user realm's empty PkgPath() and is rejected.\nfunc UpdateImpl(cur realm, r UpdateRequest) {\n\t// AGENTS.md: in a crossing function, always check IsCurrent() before\n\t// deriving caller identity from cur.Previous(). Redundant under the\n\t// crossing-frame guarantee, but mandated, and this is the single most\n\t// powerful entrypoint (it rewrites the allowlist and swaps the impl).\n\tif !cur.IsCurrent() {\n\t\tpanic(\"UpdateImpl: realm value is not the caller's live cur\")\n\t}\n\tgRealm := cur.Previous().PkgPath()\n\n\tif !InAllowedDAOs(gRealm) {\n\t\tpanic(\"permission denied for prev realm: \" + gRealm)\n\t}\n\n\tif len(r.AllowedDAOs) != 0 {\n\t\t// Every entry must be a real realm path. len() != 0 alone is the wrong\n\t\t// invariant: InAllowedDAOs compares by exact string, and a user realm's\n\t\t// PkgPath() is \"\", so a single \"\" entry admits any caller whose previous\n\t\t// frame is a user realm -- the same fail-open outcome this guard exists\n\t\t// to prevent, just spelled differently. An empty entry can only be a\n\t\t// drafting mistake, so reject the whole request rather than silently\n\t\t// dropping it and storing a list the proposal did not describe.\n\t\tfor i, d := range r.AllowedDAOs {\n\t\t\ttrimmed := strings.TrimSpace(d)\n\t\t\tif trimmed == \"\" {\n\t\t\t\tpanic(\"AllowedDAOs entries must be realm paths; got an empty one\")\n\t\t\t}\n\t\t\t// Entries are stored exactly as given, and InAllowedDAOs compares\n\t\t\t// whole strings, so an entry with surrounding spaces matches no\n\t\t\t// caller at all. A non-empty list also closes the bootstrap\n\t\t\t// window, so a list of only padded entries is locked shut against\n\t\t\t// everyone, the DAO included, with no way to reopen it.\n\t\t\t//\n\t\t\t// This does not make the list typo-proof, and is not meant to be:\n\t\t\t// any wrong path locks the DAO out exactly the same way, and no\n\t\t\t// check here can tell a typo from a realm that does not exist yet.\n\t\t\t// Whitespace is worth rejecting because it is the one spelling a\n\t\t\t// human reviewing the proposal cannot see. Rejected rather than\n\t\t\t// trimmed, so what gets stored is what the proposal said.\n\t\t\t// Reported by position, not by value. A panic message becomes the\n\t\t\t// proposal's DeniedReason, which is stored, and the entry is\n\t\t\t// caller-supplied and unbounded — echoing it would put an\n\t\t\t// arbitrary amount of someone else's text into this realm's\n\t\t\t// storage. The index is enough to find it in a list the proposal\n\t\t\t// author wrote.\n\t\t\tif d != trimmed {\n\t\t\t\tpanic(\"AllowedDAOs entries must not have leading or trailing spaces; entry \" + strconv.Itoa(i))\n\t\t\t}\n\t\t}\n\t\t// Stored as given. A defensive copy here looks prudent but would\n\t\t// guard a write no outside realm can perform, which was checked from\n\t\t// a separate realm rather than assumed:\n\t\t//\n\t\t//   - Building this request as a literal fails outright, with\n\t\t//     \"cannot allocate gno.land/r/gov/dao.UpdateRequest in realm ...\".\n\t\t//   - Writing through a request obtained from NewUpdateRequest fails\n\t\t//     with \"cannot directly modify readonly tainted object\".\n\t\t//\n\t\t// So the only way in is NewUpdateRequest, which copies already. Both\n\t\t// checks are language guarantees, not conventions.\n\t\tallowedDAOs = r.AllowedDAOs\n\t}\n\n\tif r.DAO != nil {\n\t\tdao = r.DAO\n\t}\n}\n\nfunc AllowedDAOs() []string {\n\tdup := make([]string, len(allowedDAOs))\n\tcopy(dup, allowedDAOs)\n\treturn dup\n}\n\nfunc InAllowedDAOs(pkg string) bool {\n\tif len(allowedDAOs) == 0 {\n\t\treturn true // corner case for initialization\n\t}\n\tfor _, d := range allowedDAOs {\n\t\tif pkg == d {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc executeProposal(cur realm, pid ProposalID, execErrorRejects bool) bool {\n\tif dao == nil {\n\t\treturn false\n\t}\n\texecute, err := dao.PreExecuteProposal(0, cur, pid)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tif !execute {\n\t\treturn false\n\t}\n\tprop, err := GetProposal(pid)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\terr = dao.ExecuteProposal(0, cur, pid, prop.executor)\n\tif err != nil {\n\t\tif execErrorRejects {\n\t\t\treturn false\n\t\t}\n\n\t\tpanic(err.Error())\n\t}\n\treturn true\n}\n"},{"name":"types.gno","body":"package dao\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\ntype ProposalID int64\n\nfunc (pid ProposalID) String() string {\n\treturn seqid.ID(pid).String()\n}\n\n// VoteOption is the limited voting option for a DAO proposal\n// New govDAOs can create their own VoteOptions if needed in the\n// future.\ntype VoteOption string\n\nconst (\n\tAbstainVote VoteOption = \"ABSTAIN\" // Side is not chosen\n\tYesVote     VoteOption = \"YES\"     // Proposal should be accepted\n\tNoVote      VoteOption = \"NO\"      // Proposal should be rejected\n)\n\ntype VoteRequest struct {\n\tOption     VoteOption\n\tProposalID ProposalID\n\tMetadata   interface{}\n}\n\nfunc NewVoteRequest(option VoteOption, proposalID ProposalID) VoteRequest {\n\treturn VoteRequest{\n\t\tOption:     option,\n\t\tProposalID: proposalID,\n\t}\n}\n\nfunc NewVoteRequestWithMetadata(option VoteOption, proposalID ProposalID, metadata interface{}) VoteRequest {\n\treturn VoteRequest{\n\t\tOption:     option,\n\t\tProposalID: proposalID,\n\t\tMetadata:   metadata,\n\t}\n}\n\nfunc NewProposalRequest(title string, description string, executor Executor) ProposalRequest {\n\treturn ProposalRequest{\n\t\ttitle:       title,\n\t\tdescription: description,\n\t\texecutor:    executor,\n\t}\n}\n\nfunc NewProposalRequestWithFilter(title string, description string, executor Executor, filter Filter) ProposalRequest {\n\treturn ProposalRequest{\n\t\ttitle:       title,\n\t\tdescription: description,\n\t\texecutor:    executor,\n\t\tfilter:      filter,\n\t}\n}\n\ntype Filter interface{}\n\ntype ProposalRequest struct {\n\ttitle       string\n\tdescription string\n\texecutor    Executor\n\tfilter      Filter\n}\n\nfunc (p *ProposalRequest) Title() string {\n\treturn p.title\n}\n\nfunc (p *ProposalRequest) Description() string {\n\treturn p.description\n}\n\nfunc (p *ProposalRequest) Filter() Filter {\n\treturn p.filter\n}\n\ntype Proposal struct {\n\tauthor address\n\n\ttitle       string\n\tdescription string\n\n\texecutor    Executor\n\tallowedDAOs []string\n}\n\nfunc (p *Proposal) Author() address {\n\treturn p.author\n}\n\nfunc (p *Proposal) Title() string {\n\treturn p.title\n}\n\nfunc (p *Proposal) Description() string {\n\treturn p.description\n}\n\nfunc (p *Proposal) ExecutorString() string {\n\tif p.executor != nil {\n\t\treturn p.executor.String()\n\t}\n\n\treturn \"\"\n}\n\nfunc (p *Proposal) ExecutorCreationRealm() string {\n\tif p.executor != nil {\n\t\treturn p.executor.CreationRealm()\n\t}\n\n\treturn \"\"\n}\n\nfunc (p *Proposal) AllowedDAOs() []string {\n\treturn append([]string(nil), p.allowedDAOs...)\n}\n\ntype Proposals struct {\n\tseq            seqid.ID\n\t*bptree.BPTree // *bptree.BPTree[ProposalID]*Proposal\n}\n\nfunc NewProposals() *Proposals {\n\treturn \u0026Proposals{BPTree: bptree.NewBPTree32()}\n}\n\nfunc (ps *Proposals) SetProposal(p *Proposal) ProposalID {\n\tpid := ProposalID(int64(ps.seq))\n\tupdated := ps.Set(pid.String(), p)\n\tif updated {\n\t\tpanic(\"fatal error: Override proposals is not allowed\")\n\t}\n\tps.seq = ps.seq.Next()\n\treturn pid\n}\n\nfunc (ps *Proposals) GetProposal(pid ProposalID) *Proposal {\n\tpv := ps.Get(pid.String())\n\tif pv == nil {\n\t\treturn nil\n\t}\n\n\treturn pv.(*Proposal)\n}\n\ntype Executor interface {\n\tExecute(cur realm) error\n\tString() string\n\tCreationRealm() string\n}\n\n// NewSimpleExecutor constructs an Executor whose creationRealm is captured\n// from rlm.PkgPath() at construction time. The IsCurrent() check rejects\n// stale or stashed realm values so the captured value is the authentic\n// caller realm. creationRealm is display-only (rendered as \"Executor\n// created in: ...\" in proposal listings) — no auth gate downstream.\nfunc NewSimpleExecutor(_ int, rlm realm, callback func(realm) error, description string) *SimpleExecutor {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"NewSimpleExecutor: rlm is not the caller's live cur (stale capture or sibling frame)\")\n\t}\n\tif callback == nil {\n\t\tpanic(\"executor callback must not be nil\")\n\t}\n\n\treturn \u0026SimpleExecutor{\n\t\tcallback:      callback,\n\t\tdesc:          description,\n\t\tcreationRealm: rlm.PkgPath(),\n\t}\n}\n\n// SimpleExecutor implements the Executor interface using\n// a callback function and a description string.\ntype SimpleExecutor struct {\n\tcallback      func(realm) error\n\tdesc          string\n\tcreationRealm string\n}\n\n// proxyPkgPath is this package: the realm whose frame Execute mints for a\n// callback, and therefore the only realm entitled to invoke one.\nconst proxyPkgPath = \"gno.land/r/gov/dao\"\n\n// Execute runs the proposal's callback. Invocable only from this proxy.\n//\n// SECURITY: Execute is a CROSSING method declared here, so invoking it mints\n// a gno.land/r/gov/dao frame for the callback — `cur.Previous()` inside the\n// callback is this path whoever called. That is a capability: realms gate on\n// it (authz.NewContractAuthority(\"gno.land/r/gov/dao\") + DoByPrevious,\n// ownable, anything reading Previous().Address()). Ungated, any realm could\n// wrap a reachable `func(realm) error` — including an ordinary exported\n// entrypoint of the victim — and run it with governance's identity, with no\n// proposal id minted, so nothing to render, audit or deny afterwards.\n//\n// NOT InAllowedDAOs: that is SafeExecutor's bug. It holds the impl path while\n// an executor's caller is the proxy, so it rejects the approved route and\n// fails open while empty. Exact path plus subpackages, because\n// impl.ExecuteProposal is non-crossing (Previous() is the proxy exactly), so\n// a bare prefix would reject every real proposal.\n//\n// Gates the executor object's INVOCATION only. Keeping a privileged closure,\n// or an exported entrypoint shaped like `func(realm) error`, out of reach\n// stays the consumer's job — see r/gnops/valopers/admin.gno\n// and p/moul/authz's NewContractAuthority godoc.\nfunc (e *SimpleExecutor) Execute(cur realm) error {\n\t// IsCurrent first, as every other gate here does: otherwise Previous() is\n\t// read from whatever realm value the caller threaded in.\n\tif !cur.IsCurrent() {\n\t\treturn errors.New(\"execution denied: cur is not the caller's live realm\")\n\t}\n\tif prev := cur.Previous().PkgPath(); prev != proxyPkgPath \u0026\u0026\n\t\t!strings.HasPrefix(prev, proxyPkgPath+\"/\") {\n\t\treturn errors.New(\"execution denied: executors are only invocable by \" + proxyPkgPath)\n\t}\n\n\t// Check if executor was created using the constructor func\n\tif e.callback == nil {\n\t\treturn nil\n\t}\n\n\treturn e.callback(cross(cur))\n}\n\nfunc (e *SimpleExecutor) String() string {\n\treturn e.desc\n}\n\nfunc (e *SimpleExecutor) CreationRealm() string {\n\treturn e.creationRealm\n}\n\nfunc NewSafeExecutor(e Executor) *SafeExecutor {\n\treturn \u0026SafeExecutor{\n\t\te: e,\n\t}\n}\n\n// SafeExecutor wraps an Executor to only allow its execution\n// by allowed govDAOs.\ntype SafeExecutor struct {\n\te Executor\n}\n\nfunc (e *SafeExecutor) Execute(cur realm) error {\n\t// IsCurrent first, matching every other allowlist gate in this tree\n\t// (proxy.go's UpdateImpl, treasury, memberstore). Without it this method\n\t// trusts whatever realm value it is handed, so a caller threading a stale\n\t// or sibling-frame cur would have its Previous() read from that value\n\t// rather than from the live frame.\n\t//\n\t// NewSafeExecutor has no call sites, so this type is currently dead code.\n\t// Live proposal execution goes through the Executor interface to\n\t// SimpleExecutor.Execute, which now gates on the invoking realm being the\n\t// proxy -- deliberately NOT on InAllowedDAOs, which holds the impl path\n\t// and therefore rejects the approved route and fails open while empty.\n\t// That is this method's bug; see SimpleExecutor.Execute.\n\tif !cur.IsCurrent() {\n\t\treturn errors.New(\"execution denied: cur is not the caller's live realm\")\n\t}\n\t// Verify the caller is an adequate Realm\n\tif !InAllowedDAOs(cur.Previous().PkgPath()) {\n\t\treturn errors.New(\"execution only allowed by validated govDAOs\")\n\t}\n\n\treturn e.e.Execute(cross(cur))\n}\n\nfunc (e *SafeExecutor) String() string {\n\treturn e.e.String()\n}\n\nfunc (e *SafeExecutor) CreationRealm() string {\n\treturn e.e.CreationRealm()\n}\n\n// DAO is the govDAO implementation interface. All mutating/auth-gated\n// methods take rlm as their realm-typed parameter in the second position\n// (the `_ int, rlm realm` non-crossing form): callers thread the proxy's\n// cur as data without forcing a realm transition, so the impl's existing\n// unsafe.CurrentRealm()-based auth gates (isValidCall, memberstore.Get)\n// continue to see the proxy realm. Render stays unchanged.\ntype DAO interface {\n\t// PreCreateProposal is called just before creating a new Proposal\n\t// It is intended to be used to get the address of the proposal, that\n\t// may vary depending on the DAO implementation, and to validate that\n\t// the requester is allowed to do a proposal\n\tPreCreateProposal(_ int, rlm realm, r ProposalRequest) (address, error)\n\n\t// PostCreateProposal is called after creating the Proposal. It is\n\t// intended to be used as a way to store a new proposal status, that\n\t// depends on the actuall govDAO implementation\n\tPostCreateProposal(_ int, rlm realm, r ProposalRequest, pid ProposalID)\n\n\t// VoteOnProposal will send a petition to vote for a specific proposal\n\t// to the actual govDAO implementation\n\tVoteOnProposal(_ int, rlm realm, r VoteRequest) error\n\n\t// PreExecuteProposal is called when someone is trying to execute a proposal by ID.\n\t// Is intended to be used to validate who can trigger the proposal execution.\n\tPreExecuteProposal(_ int, rlm realm, pid ProposalID) (bool, error)\n\n\t// ExecuteProposal executes the proposal executor and on error changes proposal\n\t// status to denied with the error message being the denial reason.\n\t// It returns the executor error when it fails.\n\tExecuteProposal(_ int, rlm realm, pid ProposalID, e Executor) error\n\n\t// Render will return a human-readable string in markdown format that\n\t// will be used to show new data through the dao proxy entrypoint.\n\t// Crossing: the chain query layer auto-injects .cur, and\n\t// implementations forward cur to internal rlm-aware helpers (mux\n\t// RenderRlm + downstream cross(rlm) reads).\n\tRender(cur realm, pkgpath string, path string) string\n}\n\ntype UpdateRequest struct {\n\tDAO         DAO\n\tAllowedDAOs []string\n}\n\n// NewUpdateRequest copies allowedDAOs into a fresh slice owned by\n// /r/gov/dao. Under the storage=authority model, if we stored the\n// caller-passed slice directly, the base ArrayValue would retain\n// PkgID = caller_realm: storage rent would attribute to caller, and\n// /r/gov/dao could not mutate (e.g. append to) its own copy without\n// a DidUpdate panic. The internal copy ensures the UpdateRequest\n// and its AllowedDAOs both live entirely in /r/gov/dao's authority.\nfunc NewUpdateRequest(d DAO, allowedDAOs []string) UpdateRequest {\n\tcp := make([]string, len(allowedDAOs))\n\tcopy(cp, allowedDAOs)\n\treturn UpdateRequest{\n\t\tDAO:         d,\n\t\tAllowedDAOs: cp,\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"users","path":"gno.land/r/sys/users","files":[{"name":"README.md","body":"# `r/sys/users`\n\nThe system realm that owns the (name → address, address → user) registry for\ngno.land. It is intentionally minimal: it stores `UserData` records, exposes\nresolve/update/delete primitives, and gates writes through a controller\nwhitelist managed by GovDAO (`ProposeNewController` /\n`ProposeControllerRemoval` / `ProposeControllerAdditionAndRemoval`).\n\nThis realm does **not** define what a \"name\" is, what registration costs, or\nwhether names can be transferred. Those policies live in *controller realms*\nthat the DAO whitelists. See `r/sys/namereg/v0` for one such controller, and\nthe `examples/gno.land/r/sys/names` realm for the related namespace verifier\nthat gates package deployment under `gno.land/r/\u003cnamespace\u003e/...`.\n\n## Trust boundary at genesis (height 0)\n\nThe whitelist check in `RegisterUser` (and the sibling\n`AddControllerAtGenesis`) **short-circuits at chain height 0**:\n\n```go\n// store.gno\nif runtime.ChainHeight() \u003e 0 \u0026\u0026 !controllers.Has(runtime.PreviousRealm().Address()) {\n    return NewErrNotWhitelisted()\n}\n```\n\nThis is **intentional**, not a bug. Genesis is the bootstrap window where:\n\n1. The controller whitelist is empty (it can't be populated until *after* it\n   exists).\n2. System realms (`r/sys/users/init`, `r/sys/namereg/v0`, etc.) need to\n   pre-seed users and add themselves as controllers.\n3. Any realm whose `init()` runs at genesis can therefore call `RegisterUser`\n   without authorization.\n\nThe protection model is **out-of-band trust**: chain operators control which\nrealms ship in genesis (via the contents of `examples/gno.land/r/...`), and\nthose realms are vouched for at chain-binary build time. The realm code does\nnot — and intentionally does not try to — enforce who is \"allowed\" to\npre-register at height 0.\n\n### Audit reference\n\nThis bypass was flagged as audit finding #4 (\"Genesis bypass — any caller can\nregister at height 0\"). After review, it is treated as **WON'T FIX, working\nas intended**:\n\n- Removing the bypass breaks every legitimate genesis pre-registration use\n  case (including this realm's own bootstrap and `r/sys/namereg/v0`'s\n  preregister loop of system names).\n- A hardcoded genesis-allowlist (a la \"only `r/sys/*` realms may bypass\")\n  shifts the trust to a literal in source — a chain upgrade is required to\n  add a new genesis-bootstrap realm. This trades flexibility for the same\n  amount of trust.\n- Path-prefix gating (e.g. \"only `gno.land/r/sys/*`\") couples this realm to\n  the namespace verifier remaining locked-down, an implicit dependency that\n  makes future refactors fragile.\n\nIf chain operators want post-deployment auditing of who pre-registered what\nat genesis, the `RegisterUserEvent` is emitted on every successful\nregistration regardless of height, and the source of each registration can be\nrecovered by walking genesis-block events alongside the `examples/` tree.\n\n### Sibling bypass: `AddControllerAtGenesis`\n\nThe same height-0 trust model applies to `AddControllerAtGenesis` in\n`admin.gno`:\n\n```go\nfunc AddControllerAtGenesis(_ realm, addr address) {\n    height := runtime.ChainHeight()\n    if height \u003e 0 {\n        panic(\"AddControllerAtGenesis can only be called at genesis (height 0)\")\n    }\n    if !addr.IsValid() {\n        panic(ErrInvalidAddress)\n    }\n    controllers.Add(addr)\n}\n```\n\nThis was audit finding #7 (\"AddControllerAtGenesis has no caller check\"). It\nis the **same intentional design** as #4 and is likewise treated as **WON'T\nFIX**:\n\n- Any realm whose `init()` runs at genesis can whitelist any address as a\n  controller, without authorization.\n- This is how the registry bootstraps itself: `r/sys/users/init.Bootstrap`\n  adds its own package address, and `r/sys/namereg/v0/init.gno` likewise\n  auto-whitelists `gno.land/r/sys/namereg/v0`. Removing the bypass would\n  break the bootstrap pattern.\n- After genesis (height \u003e 0) the function hard-panics, so the privilege\n  window is strictly one-time at chain birth.\n- The trust model is identical: chain operators vouch for whatever realms\n  ship in `examples/` at chain-binary build time.\n\nIf you need to add a new controller post-genesis, the supported path is a\nGovDAO proposal via `ProposeNewController` — the same channel that rotates\nevery controller going forward.\n\n### What the audit DID flag that's worth fixing\n\n- #5: `ufmt.Sprint` used instead of `Sprintf` in controller-swap proposal\n  description (governance-vote readability).\n- #6: Add+Remove proposal silently no-ops if `add` fails on an already-listed\n  controller — voted-on swap doesn't actually swap.\n- #7: `AddControllerAtGenesis` shares the height-0 bypass; same trust model\n  applies, same intentional design.\n\nSee `NAMEREG_AUDIT.md` for the full set and `NAMEREG_TODO.md` for tracked\n\"won't fix / accepted risk\" items.\n"},{"name":"admin.gno","body":"package users\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/addrset/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\t\"gno.land/r/gov/dao\"\n)\n\nconst initControllerPath = \"gno.land/r/sys/users/init\"\n\nvar controllers = addrset.Set{} // caller whitelist\n\nfunc init() {\n\t// auto-whitelist the init controller for bootstrapping for testing chain.\n\tif chainID := runtime.ChainID(); chainID == \"dev\" {\n\t\tcontrollers.Add(chain.PackageAddress(initControllerPath))\n\t}\n}\n\n// AddControllerAtGenesis allows adding a controller during chain genesis (height 0).\n// This is mostly useful for testing.\nfunc AddControllerAtGenesis(_ realm, addr address) {\n\theight := runtime.ChainHeight()\n\tif height \u003e 0 {\n\t\tpanic(\"AddControllerAtGenesis can only be called at genesis (height 0)\")\n\t}\n\n\tif !addr.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\n\tcontrollers.Add(addr)\n}\n\n// ProposeNewController allows GovDAO to add a whitelisted caller\nfunc ProposeNewController(cur realm, addr address) dao.ProposalRequest {\n\tif !addr.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\n\tcb := func(cur realm) error {\n\t\treturn addToWhitelist(addr)\n\t}\n\n\tdesc := \"This proposal adds \" + addr.String() + \" to `sys/users` realm's callers whitelist.\"\n\treturn dao.NewProposalRequest(\"Add Whitelisted Caller to \\\"sys/users\\\" Realm\", desc, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// ProposeControllerRemoval allows GovDAO to add a whitelisted caller\nfunc ProposeControllerRemoval(cur realm, addr address) dao.ProposalRequest {\n\tif !addr.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\n\tcb := func(cur realm) error {\n\t\treturn deleteFromWhitelist(addr)\n\t}\n\n\tdesc := \"This proposal removes \" + addr.String() + \" from `sys/users` realm's callers whitelist.\"\n\treturn dao.NewProposalRequest(\"Remove Whitelisted Caller From \\\"sys/users\\\" Realm\", desc, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// ProposeControllerAdditionAndRemoval allows GovDAO to add a new caller and remove an old caller in the same proposal.\nfunc ProposeControllerAdditionAndRemoval(cur realm, toAdd, toRemove address) dao.ProposalRequest {\n\tif !toAdd.IsValid() || !toRemove.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\n\tcb := func(cur realm) error {\n\t\treturn applyControllerSwap(toAdd, toRemove)\n\t}\n\n\tdesc := ufmt.Sprintf(\n\t\t\"This proposal adds %s and removes %s from `sys/users` realm's callers whitelist.\",\n\t\ttoAdd,\n\t\ttoRemove,\n\t)\n\treturn dao.NewProposalRequest(\"Add and Remove Whitelisted Callers From \\\"sys/users\\\" Realm\", desc, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// applyControllerSwap is the callback body of ProposeControllerAdditionAndRemoval,\n// extracted so it can be unit-tested without driving the full GovDAO flow.\n//\n// The desired end state is \"toAdd is in the whitelist AND toRemove is out\".\n// Both operations are made idempotent so the swap doesn't silently no-op when\n// the chain state has drifted between proposal creation and execution:\n//\n//   - If toAdd is already whitelisted, treat addToWhitelist's\n//     ErrAlreadyWhitelisted as benign and continue to the remove step.\n//   - If toRemove is already absent, treat deleteFromWhitelist's\n//     ErrNotWhitelisted as benign and return success.\n//\n// Without this idempotency, the original code returned early on an \"already\n// whitelisted\" toAdd and skipped the remove entirely — a swap proposal could\n// pass governance and silently leave the old controller active. (audit\n// finding #6)\nfunc applyControllerSwap(toAdd, toRemove address) error {\n\tif err := addToWhitelist(toAdd); err != nil \u0026\u0026 err != ErrAlreadyWhitelisted {\n\t\treturn err\n\t}\n\tif err := deleteFromWhitelist(toRemove); err != nil {\n\t\tif _, alreadyOut := err.(ErrNotWhitelisted); !alreadyOut {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// ProposeRegisterUser allows GovDAO to register a name without checking\n// controllers. The executor closure runs with ignoreCanonical=true (decision\n// #3): DAO grants always bypass canonical-collision detection. Voters see\n// any collision in the proposal description and can vote NO if unintended.\nfunc ProposeRegisterUser(cur realm, name string, addr address) dao.ProposalRequest {\n\t// Validate the name and address now, even though registerUser will validate again\n\tif err := validateName(name); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tif !addr.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\n\tdesc := \"This proposal registers \" + name + \" with address \" + addr.String() + \" in `sys/users`.\"\n\tif existing, taken := IsCanonicalTaken(name); taken \u0026\u0026 existing != name {\n\t\tdesc += \"\\n\\nCANONICAL COLLISION: this name's canonical form matches the existing registration of `\" +\n\t\t\texisting + \"`. DAO grants bypass canonical-collision detection — the proposal will succeed if voted in. \" +\n\t\t\t\"If the collision is unintended, vote NO.\"\n\t}\n\n\tcb := func(cur realm) error {\n\t\treturn registerUser(cur, name, addr, true) // bypass canonical (decision #3)\n\t}\n\n\treturn dao.NewProposalRequest(\"Register User to \\\"sys/users\\\" Realm\", desc, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// ProposeUpdateName allows GovDAO to update a name with an alias without\n// checking controllers. Like ProposeRegisterUser, the executor runs with\n// ignoreCanonical=true (decision #3).\nfunc ProposeUpdateName(cur realm, addr address, newName string) dao.ProposalRequest {\n\tif !addr.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\tif err := validateName(newName); err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tdesc := \"This proposal updates address \" + addr.String() + \" with alias \" + newName + \" in `sys/users`.\"\n\tif existing, taken := IsCanonicalTaken(newName); taken \u0026\u0026 existing != newName {\n\t\tdesc += \"\\n\\nCANONICAL COLLISION: the new alias's canonical form matches the existing registration of `\" +\n\t\t\texisting + \"`. DAO grants bypass canonical-collision detection — the proposal will succeed if voted in. \" +\n\t\t\t\"If the collision is unintended, vote NO.\"\n\t}\n\n\tcb := func(cur realm) error {\n\t\tdata := ResolveAddress(addr)\n\t\tif data == nil {\n\t\t\treturn ErrUserNotExistOrDeleted\n\t\t}\n\t\treturn data.updateName(newName, true) // bypass canonical (decision #3)\n\t}\n\n\treturn dao.NewProposalRequest(\"Update Name Alias in \\\"sys/users\\\" Realm\", desc, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// ProposeDeleteUser allows GovDAO to delete a user without checking controllers\nfunc ProposeDeleteUser(cur realm, addr address) dao.ProposalRequest {\n\tif !addr.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\n\tcb := func(cur realm) error {\n\t\tdata := ResolveAddress(addr)\n\t\tif data == nil {\n\t\t\treturn ErrUserNotExistOrDeleted\n\t\t}\n\t\treturn data.delete()\n\t}\n\n\tdesc := \"This proposal deletes the user with address \" + addr.String() + \" in `sys/users`.\"\n\treturn dao.NewProposalRequest(\"Delete User in \\\"sys/users\\\" Realm\", desc, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// IsController reports whether the given address is currently in the\n// controller whitelist. Returns the same boolean that gating checks\n// (RegisterUser, UpdateName, Delete) use internally — useful for\n// off-chain monitoring and for governance proposals to inspect state\n// before voting.\nfunc IsController(addr address) bool {\n\treturn controllers.Has(addr)\n}\n\n// Controllers returns a snapshot of the current controller whitelist.\n// The returned slice is a fresh copy; mutating it does not affect realm\n// state. Order is the iteration order of the underlying address set.\n//\n// Audit finding #20: without this getter, the controller whitelist was\n// opaque from outside the package — operators had to read source or\n// replay every governance proposal to know who could write to the\n// registry. This is the read-only API that closes that gap.\nfunc Controllers() []address {\n\tout := make([]address, 0, controllers.Size())\n\tcontrollers.IterateByOffset(0, controllers.Size(), func(a address) bool {\n\t\tout = append(out, a)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Helpers\n\nfunc deleteFromWhitelist(addr address) error {\n\tif !controllers.Has(addr) {\n\t\treturn ErrNotWhitelisted{Caller: \"UserRealm{ \" + addr.String() + \" }\"}\n\t}\n\n\tif ok := controllers.Remove(addr); !ok {\n\t\treturn ErrWhitelistRemoveFailed\n\t}\n\n\treturn nil\n}\n\nfunc addToWhitelist(newCaller address) error {\n\tif !controllers.Add(newCaller) {\n\t\treturn ErrAlreadyWhitelisted\n\t}\n\n\treturn nil\n}\n"},{"name":"api.gno","body":"package users\n\n// IsNameTaken reports whether the exact-string name exists in nameStore.\n// Returns true for any name ever registered, including:\n//\n//   - active registrations\n//   - tombstoned (deleted) users' names — Delete() sets `deleted=true`\n//     but does not remove the nameStore entry (anti-revival policy)\n//   - old aliases from renames — UpdateName inserts the new name\n//     alongside the old; the old key stays (anti-rename-squat policy)\n//\n// In short: IsNameTaken(name) answers \"would RegisterUser(name, _)\n// fail with ErrNameTaken?\" — same answer for active, deleted, or\n// aliased-away names. Pairs with IsCanonicalTaken (canonical-match)\n// and ResolveName (active-current-user lookup with full UserData).\n//\n// No canonicalization is applied. For controllers that want exact-\n// match uniqueness without pulling in canonical-collision logic.\nfunc IsNameTaken(name string) bool {\n\treturn nameStore.Has(name)\n}\n\n// IsCanonicalTaken reports whether the given name's canonical form is\n// already registered. Pass the raw name; canonicalization is applied\n// internally. The first return is the original (non-canonical) name\n// that owns the canonical key, for UX in collision messages.\n//\n// When a bypass write (RegisterUserIgnoreCanonical or the bypass path\n// through ProposeRegisterUser/ProposeUpdateName) overwrites a prior\n// canonical entry, this returns the most-recently-written original.\nfunc IsCanonicalTaken(name string) (existing string, taken bool) {\n\tv := canonicalStore.Get(Canonicalize(name))\n\tif v == nil {\n\t\treturn \"\", false\n\t}\n\treturn v.(string), true\n}\n"},{"name":"canonical.gno","body":"package users\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\n// canonicalStore maps canonicalized full names to the original name\n// that was registered. Keyed by the result of Canonicalize.\n//\n// Multiple controllers (namereg/v0, future registries, governance,\n// genesis bootstrapping) all share this single store via RegisterUser\n// and the bypass variant RegisterUserIgnoreCanonical. Cross-controller\n// canonical-collision detection is uniform and atomic with the\n// nameStore write.\nvar canonicalStore = bptree.NewBPTree32()\n\n// Canonicalize returns the canonical form of a name. The substitutions\n// collapse single-character visual confusables that arise across the\n// allowed [a-z0-9] character set, and strip the three separators that\n// can sneak between identical alphanumeric runs.\n//\n//   - {l, i, 1} → i\n//   - {0, o}    → o\n//   - {-, ., _} → stripped\n//   - all other characters unchanged\n//\n// CONTRACT: stable. Future controllers that want to share this\n// canonical namespace MUST use this exact function — do not roll your\n// own. Adding new substitutions later is a breaking change because it\n// would silently re-key existing entries in canonicalStore.\n//\n// Input contract: ASCII-only. r/sys/users.validateName already rejects\n// non-ASCII at the registration boundary, so by the time a name reaches\n// Canonicalize through the standard write path it is guaranteed to be\n// ASCII. Direct callers from other realms must honor this contract;\n// non-ASCII bytes are passed through as-is and will produce undefined\n// collision behavior.\n//\n// Multi-char confusables (m↔rn, nn↔m, cl↔d) are NOT canonicalized.\n// They require fixed-point substring substitution rounds, which is out\n// of scope for the unified store.\n//\n// Pure: no state access. Safe to call from anywhere.\nfunc Canonicalize(name string) string {\n\tvar b strings.Builder\n\tb.Grow(len(name))\n\tfor i := 0; i \u003c len(name); i++ {\n\t\tc := name[i]\n\t\tswitch c {\n\t\tcase 'l', '1':\n\t\t\tb.WriteByte('i')\n\t\tcase '0':\n\t\t\tb.WriteByte('o')\n\t\tcase '-', '.', '_':\n\t\t\t// strip\n\t\tdefault:\n\t\t\tb.WriteByte(c)\n\t\t}\n\t}\n\treturn b.String()\n}\n"},{"name":"errors.gno","body":"package users\n\nimport (\n\t\"errors\"\n)\n\nconst prefix = \"r/sys/users: \"\n\nvar (\n\tErrAlreadyWhitelisted    = errors.New(prefix + \"already whitelisted\")\n\tErrWhitelistRemoveFailed = errors.New(prefix + \"failed to remove address from whitelist\")\n\n\tErrNameTaken          = errors.New(prefix + \"name/Alias already taken\")\n\tErrCanonicalCollision = errors.New(prefix + \"name collides with a confusable variant of an existing name\")\n\tErrInvalidAddress     = errors.New(prefix + \"invalid address\")\n\n\tErrEmptyUsername   = errors.New(prefix + \"empty username provided\")\n\tErrNameLikeAddress = errors.New(prefix + \"username resembles a gno.land address\")\n\tErrInvalidUsername = errors.New(prefix + \"username must match ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ (max 64 chars)\")\n\n\tErrAlreadyHasName = errors.New(prefix + \"username for this address already registered - try creating an Alias\")\n\tErrDeletedUser    = errors.New(prefix + \"cannot register a new username after deleting\")\n\n\tErrUserNotExistOrDeleted = errors.New(prefix + \"this user does not exist or was deleted\")\n\n\t// ErrInvalidRealm is returned by controller-gated *UserData mutators\n\t// when the supplied rlm is not the caller's live cur (i.e.\n\t// rlm.IsCurrent() is false). Closes Class-2 designation forgery via\n\t// a stored stale realm value whose .Address() resolves to a\n\t// whitelisted controller. See docs/resources/gno-security.md.\n\tErrInvalidRealm = errors.New(prefix + \"rlm is not the caller's live cur\")\n)\n\n// ErrNotWhitelisted stores the failing caller's realm identity as a\n// plain string so the error is a pure data record (no live realm values\n// in its fields).\ntype ErrNotWhitelisted struct {\n\tCaller string // \"CodeRealm{ \u003caddr\u003e, \u003cpkgPath\u003e }\" or \"UserRealm{ \u003caddr\u003e }\" — failed the whitelist check\n}\n\n// NewErrNotWhitelisted constructs the error with the caller's realm\n// identity captured as a string at construction time. The _ int\n// discriminator keeps this non-crossing (a non-crossing function can't\n// take a `realm`-named-`cur` first param, so we use the standard\n// _ int, rlm realm shape).\nfunc NewErrNotWhitelisted(_ int, caller realm) ErrNotWhitelisted {\n\treturn ErrNotWhitelisted{\n\t\tCaller: caller.String(),\n\t}\n}\n\nfunc (e ErrNotWhitelisted) Error() string {\n\treturn prefix + \"caller realm/user does not exist in whitelist: \" + e.Caller\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/users\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"render.gno","body":"package users\n\nimport \"gno.land/p/nt/ufmt/v0\"\n\nfunc Render(_ string) string {\n\tout := \"# r/sys/users\\n\\n\"\n\n\tout += \"`r/sys/users` is a system realm for managing user registrations.\\n\\n\"\n\tout += \"User registration is managed through whitelisted controller realms.\\n\\n\"\n\tout += \"---\\n\\n\"\n\n\tout += \"## Stats\\n\\n\"\n\tout += ufmt.Sprintf(\"Total unique addresses registered: **%d**\\n\\n\", addressStore.Size())\n\tout += ufmt.Sprintf(\"Total unique names registered: **%d**\\n\\n\", nameStore.Size())\n\treturn out\n}\n"},{"name":"store.gno","body":"package users\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"regexp\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar (\n\tnameStore    = bptree.NewBPTree32() // name/aliases \u003e *UserData\n\taddressStore = bptree.NewBPTree32() // address \u003e *UserData\n\n\treAddressLookalike = regexp.MustCompile(`^g1[a-z0-9]{20,38}$`)\n\n\t// reName mirrors gno's package-name shape (gnovm/pkg/gnolang/mempackage.go\n\t// `Re_name`): start with a lowercase letter, optional alphanumeric body,\n\t// then any number of (separator + alphanumeric run) — so single hyphens\n\t// or underscores are allowed BETWEEN alphanumerics, but consecutive\n\t// separators (`--`, `__`, `-_`, `_-`) are rejected, and so are leading\n\t// or trailing separators. Lowercase-only — closes the case-confusable\n\t// squatting concern (Alice vs alice were two distinct names under the\n\t// previous case-preserving regex). Length cap of 64 enforced separately\n\t// in validateName.\n\treName = regexp.MustCompile(`^[a-z][a-z0-9]*([_-][a-z0-9]+)*$`)\n)\n\nconst maxNameLen = 64\n\nconst (\n\tRegisterUserEvent = \"Registered\"\n\tUpdateNameEvent   = \"Updated\"\n\tDeleteUserEvent   = \"Deleted\"\n)\n\ntype UserData struct {\n\taddr     address\n\tusername string // contains the latest name of a user\n\tdeleted  bool\n}\n\nfunc (u UserData) Name() string {\n\treturn u.username\n}\n\nfunc (u UserData) Addr() address {\n\treturn u.addr\n}\n\n// IsDeleted reports whether this user record is missing or marked deleted.\n// A nil receiver returns true — \"the user does not exist\" is semantically\n// indistinguishable from \"the user was deleted\" for callers that need to\n// gate further state changes. This lets call sites collapse the nil check\n// and the deleted check into a single guard:\n//\n//\tif u.IsDeleted() {\n//\t    return ErrUserNotExistOrDeleted\n//\t}\nfunc (u *UserData) IsDeleted() bool {\n\tif u == nil {\n\t\treturn true\n\t}\n\treturn u.deleted\n}\n\n// RenderLink provides a render link to the user page on gnoweb\n// `linkText` is optional\nfunc (u UserData) RenderLink(linkText string) string {\n\tif linkText == \"\" {\n\t\treturn ufmt.Sprintf(\"[@%s](/u/%s)\", u.username, u.username)\n\t}\n\n\treturn ufmt.Sprintf(\"[%s](/u/%s)\", linkText, u.username)\n}\n\n// registerUser adds a new user to the system without checking controllers.\n// The ignoreCanonical flag suppresses ErrCanonicalCollision; the canonical\n// store is written either way (decision #14: later-wins on bypass).\nfunc registerUser(cur realm, name string, address_XXX address, ignoreCanonical bool) error {\n\t// Validate name\n\tif err := validateName(name); err != nil {\n\t\treturn err\n\t}\n\n\t// Validate address\n\tif !address_XXX.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\t// Check if name is taken (exact-string match precedes canonical check)\n\tif nameStore.Has(name) {\n\t\treturn ErrNameTaken\n\t}\n\n\tcanonical := Canonicalize(name)\n\tif !ignoreCanonical {\n\t\tif canonicalStore.Has(canonical) {\n\t\t\treturn ErrCanonicalCollision\n\t\t}\n\t}\n\n\traw := addressStore.Get(address_XXX.String())\n\tif raw != nil {\n\t\t// Cannot re-register after deletion\n\t\tif raw.(*UserData).IsDeleted() {\n\t\t\treturn ErrDeletedUser\n\t\t}\n\n\t\t// For a second name, use UpdateName\n\t\treturn ErrAlreadyHasName\n\t}\n\n\t// Create UserData\n\tdata := \u0026UserData{\n\t\taddr:     address_XXX,\n\t\tusername: name,\n\t\tdeleted:  false,\n\t}\n\n\t// Set corresponding stores\n\tnameStore.Set(name, data)\n\taddressStore.Set(address_XXX.String(), data)\n\tcanonicalStore.Set(canonical, name)\n\n\tchain.Emit(RegisterUserEvent,\n\t\t\"name\", name,\n\t\t\"address\", address_XXX.String(),\n\t)\n\treturn nil\n}\n\n// RegisterUser adds a new user to the system. Enforces canonical-\n// collision detection: a name whose Canonicalize-form matches a prior\n// registration returns ErrCanonicalCollision.\nfunc RegisterUser(cur realm, name string, address_XXX address) error {\n\t// IsCurrent before Previous, as UpdateName/Delete below already do. The\n\t// file was inconsistent: those three checked it, these two did not.\n\tif !cur.IsCurrent() {\n\t\treturn NewErrNotWhitelisted(0, cur.Previous())\n\t}\n\t// At genesis (height 0), allow any caller to register users.\n\t// After genesis, only whitelisted controllers can register.\n\tif runtime.ChainHeight() \u003e 0 \u0026\u0026 !controllers.Has(cur.Previous().Address()) {\n\t\treturn NewErrNotWhitelisted(0, cur.Previous())\n\t}\n\n\treturn registerUser(cur, name, address_XXX, false)\n}\n\n// RegisterUserIgnoreCanonical is the bypass path: same controller-\n// whitelist gate, but ErrCanonicalCollision is suppressed. The canonical\n// store is still written; a prior entry with the same canonical key is\n// silently overwritten (decision #14, later-wins). Use sparingly — names\n// registered here can canonical-collide with existing ones, weakening\n// confusable protection for everyone.\nfunc RegisterUserIgnoreCanonical(cur realm, name string, address_XXX address) error {\n\t// IsCurrent before Previous, as UpdateName/Delete below already do. The\n\t// file was inconsistent: those three checked it, these two did not.\n\tif !cur.IsCurrent() {\n\t\treturn NewErrNotWhitelisted(0, cur.Previous())\n\t}\n\tif runtime.ChainHeight() \u003e 0 \u0026\u0026 !controllers.Has(cur.Previous().Address()) {\n\t\treturn NewErrNotWhitelisted(0, cur.Previous())\n\t}\n\n\treturn registerUser(cur, name, address_XXX, true)\n}\n\n// updateName adds a name that is associated with a specific address without\n// checking controllers. The ignoreCanonical flag suppresses\n// ErrCanonicalCollision; the canonical store is written either way (decision\n// #14: later-wins on bypass).\n//\n// All previous names are preserved and resolvable.\n// The new name is the default value returned for address lookups.\nfunc (u *UserData) updateName(newName string, ignoreCanonical bool) error {\n\t// IsDeleted handles both branches: nil receiver (user never existed)\n\t// AND a non-nil receiver whose .deleted is true (a controller cached\n\t// the *UserData pointer before the user was deleted by a separate\n\t// controller or governance proposal). Without the deleted-flag branch,\n\t// nameStore.Set(newName, u) would insert an alias pointing at a\n\t// deleted user — Has(newName) returns true forever but Resolve(newName)\n\t// returns nil (Resolve* APIs filter deleted), so the name is squatted\n\t// with no recovery path. (audit finding #3)\n\tif u.IsDeleted() {\n\t\treturn ErrUserNotExistOrDeleted\n\t}\n\n\t// Validate name\n\tif err := validateName(newName); err != nil {\n\t\treturn err\n\t}\n\n\t// Check if the requested Alias is already taken (exact-string match)\n\tif nameStore.Has(newName) {\n\t\treturn ErrNameTaken\n\t}\n\n\tcanonical := Canonicalize(newName)\n\tif !ignoreCanonical {\n\t\t// No self-collision filter (decision #15): even the user's OWN\n\t\t// prior canonical claim blocks the rename. Prevents accumulating\n\t\t// confusable aliases of one's own name through free renames. The\n\t\t// only path to a self-confusable rename is DAO governance via\n\t\t// ProposeUpdateName.\n\t\tif canonicalStore.Has(canonical) {\n\t\t\treturn ErrCanonicalCollision\n\t\t}\n\t}\n\n\tu.username = newName\n\tnameStore.Set(newName, u)\n\tcanonicalStore.Set(canonical, newName)\n\n\tchain.Emit(UpdateNameEvent,\n\t\t\"alias\", newName,\n\t\t\"address\", u.addr.String(),\n\t)\n\treturn nil\n}\n\n// UpdateName adds a name that is associated with a specific address.\n// Enforces canonical-collision detection.\n// All previous names are preserved and resolvable.\n// The new name is the default value returned for address lookups.\n//\n// rlm is the cur of the caller's enclosing crossing function (passed as\n// data via the `_ int, rlm realm` non-crossing form). rlm.Address() is\n// the calling realm against which we authorize.\nfunc (u *UserData) UpdateName(_ int, rlm realm, newName string) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrInvalidRealm\n\t}\n\tif u.IsDeleted() {\n\t\treturn ErrUserNotExistOrDeleted\n\t}\n\n\t// Validate caller\n\tif !controllers.Has(rlm.Address()) {\n\t\treturn NewErrNotWhitelisted(0, rlm)\n\t}\n\n\treturn u.updateName(newName, false)\n}\n\n// UpdateNameIgnoreCanonical is the bypass path: same controller-\n// whitelist gate, but ErrCanonicalCollision is suppressed. The canonical\n// store is still written; a prior entry with the same canonical key is\n// silently overwritten (decision #14, later-wins).\nfunc (u *UserData) UpdateNameIgnoreCanonical(_ int, rlm realm, newName string) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrInvalidRealm\n\t}\n\tif u.IsDeleted() {\n\t\treturn ErrUserNotExistOrDeleted\n\t}\n\n\tif !controllers.Has(rlm.Address()) {\n\t\treturn NewErrNotWhitelisted(0, rlm)\n\t}\n\n\treturn u.updateName(newName, true)\n}\n\n// delete marks a user and all their aliases as deleted without checking controllers.\nfunc (u *UserData) delete() error {\n\tif u.IsDeleted() {\n\t\treturn ErrUserNotExistOrDeleted\n\t}\n\n\tu.deleted = true\n\n\tchain.Emit(DeleteUserEvent, \"address\", u.addr.String())\n\treturn nil\n}\n\n// Delete marks a user and all their aliases as deleted.\n// rlm is the cur of the caller's enclosing crossing function; see UpdateName.\nfunc (u *UserData) Delete(_ int, rlm realm) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrInvalidRealm\n\t}\n\tif u.IsDeleted() {\n\t\treturn ErrUserNotExistOrDeleted\n\t}\n\n\t// Validate caller\n\tif !controllers.Has(rlm.Address()) {\n\t\treturn NewErrNotWhitelisted(0, rlm)\n\t}\n\n\treturn u.delete()\n}\n\n// Validate validates username and address passed in\n// Most of the validation is done in the controllers\n// This provides more flexibility down the line\nfunc validateName(username string) error {\n\tif username == \"\" {\n\t\treturn ErrEmptyUsername\n\t}\n\n\tif len(username) \u003e maxNameLen {\n\t\treturn ErrInvalidUsername\n\t}\n\n\tif !reName.MatchString(username) {\n\t\treturn ErrInvalidUsername\n\t}\n\n\t// Check if the username can be decoded or looks like a valid address\n\tif address(username).IsValid() || reAddressLookalike.MatchString(username) {\n\t\treturn ErrNameLikeAddress\n\t}\n\n\treturn nil\n}\n"},{"name":"users.gno","body":"package users\n\nimport \"gno.land/p/nt/bptree/rotree/v0\"\n\n// ResolveName returns the latest UserData of a specific user by name or alias\nfunc ResolveName(name string) (data *UserData, isCurrent bool) {\n\traw := nameStore.Get(name)\n\tif raw == nil {\n\t\treturn nil, false\n\t}\n\n\tdata = raw.(*UserData)\n\tif data.deleted {\n\t\treturn nil, false\n\t}\n\n\treturn data, name == data.username\n}\n\n// ResolveAddress returns the latest UserData of a specific user by address\nfunc ResolveAddress(addr address) *UserData {\n\traw := addressStore.Get(addr.String())\n\tif raw == nil {\n\t\treturn nil\n\t}\n\n\tdata := raw.(*UserData)\n\tif data.deleted {\n\t\treturn nil\n\t}\n\n\treturn data\n}\n\n// ResolveAny tries to resolve any given string to *UserData\n// If the input is not found in the registry in any form, nil is returned\nfunc ResolveAny(input string) (*UserData, bool) {\n\taddr := address(input)\n\tif addr.IsValid() {\n\t\treturn ResolveAddress(addr), true\n\t}\n\n\treturn ResolveName(input)\n}\n\n// GetReadonlyAddrStore exposes the address store in readonly mode\nfunc GetReadonlyAddrStore() *rotree.ReadOnlyTree {\n\treturn rotree.Wrap(addressStore, makeUserDataSafe)\n}\n\n// GetReadOnlyNameStore exposes the name store in readonly mode\nfunc GetReadOnlyNameStore() *rotree.ReadOnlyTree {\n\treturn rotree.Wrap(nameStore, makeUserDataSafe)\n}\n\nfunc makeUserDataSafe(data any) any {\n\tcpy := new(UserData)\n\t*cpy = *(data.(*UserData))\n\tif cpy.deleted {\n\t\treturn nil\n\t}\n\n\t// Note: when requesting data from this AVL tree, (exists bool) will be true\n\t// Even if the data is \"deleted\". This is currently unavoidable\n\treturn cpy\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"boards","path":"gno.land/r/archive/boards","files":[{"name":"board.gno","body":"package boards\n\nimport (\n\t\"strconv\"\n\t\"time\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n//----------------------------------------\n// Board\n\ntype BoardID uint64\n\nfunc (bid BoardID) String() string {\n\treturn strconv.Itoa(int(bid))\n}\n\ntype Board struct {\n\tid        BoardID // only set for public boards.\n\turl       string\n\tname      string\n\tcreator   address\n\tthreads   avl.Tree // Post.id -\u003e *Post\n\tpostsCtr  uint64   // increments Post.id\n\tcreatedAt time.Time\n\tdeleted   avl.Tree // TODO reserved for fast-delete.\n}\n\nfunc newBoard(id BoardID, url string, name string, creator address) *Board {\n\tif !reName.MatchString(name) {\n\t\tpanic(\"invalid name: \" + name)\n\t}\n\texists := gBoardsByName.Has(name)\n\tif exists {\n\t\tpanic(\"board already exists\")\n\t}\n\treturn \u0026Board{\n\t\tid:        id,\n\t\turl:       url,\n\t\tname:      name,\n\t\tcreator:   creator,\n\t\tthreads:   avl.Tree{},\n\t\tcreatedAt: time.Now(),\n\t\tdeleted:   avl.Tree{},\n\t}\n}\n\n/* TODO support this once we figure out how to ensure URL correctness.\n// A private board is not tracked by gBoards*,\n// but must be persisted by the caller's realm.\n// Private boards have 0 id and does not ping\n// back the remote board on reposts.\nfunc NewPrivateBoard(_ realm, url string, name string, creator address) *Board {\n\treturn newBoard(0, url, name, creator)\n}\n*/\n\nfunc (board *Board) IsPrivate() bool {\n\treturn board.id == 0\n}\n\nfunc (board *Board) GetThread(pid PostID) *Post {\n\tpidkey := postIDKey(pid)\n\tpostI := board.threads.Get(pidkey)\n\tif postI == nil {\n\t\treturn nil\n\t}\n\treturn postI.(*Post)\n}\n\nfunc (board *Board) AddThread(creator address, title string, body string) *Post {\n\tpid := board.incGetPostID()\n\tpidkey := postIDKey(pid)\n\tthread := newPost(board, pid, creator, title, body, pid, 0, 0)\n\tboard.threads.Set(pidkey, thread)\n\treturn thread\n}\n\n// NOTE: this can be potentially very expensive for threads with many replies.\n// TODO: implement optional fast-delete where thread is simply moved.\nfunc (board *Board) DeleteThread(pid PostID) {\n\tpidkey := postIDKey(pid)\n\t_, removed := board.threads.Remove(pidkey)\n\tif !removed {\n\t\tpanic(\"thread does not exist with id \" + pid.String())\n\t}\n}\n\nfunc (board *Board) HasPermission(addr address, perm Permission) bool {\n\tif board.creator == addr {\n\t\tswitch perm {\n\t\tcase EditPermission:\n\t\t\treturn true\n\t\tcase DeletePermission:\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}\n\n// Renders the board for display suitable as plaintext in\n// console.  This is suitable for demonstration or tests,\n// but not for prod.\nfunc (board *Board) RenderBoard() string {\n\tstr := \"\"\n\tstr += \"\\\\[[post](\" + board.GetPostFormURL() + \")]\\n\\n\"\n\tif board.threads.Size() \u003e 0 {\n\t\tboard.threads.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\tif str != \"\" {\n\t\t\t\tstr += \"----------------------------------------\\n\"\n\t\t\t}\n\t\t\tstr += value.(*Post).RenderSummary() + \"\\n\"\n\t\t\treturn false\n\t\t})\n\t}\n\treturn str\n}\n\nfunc (board *Board) incGetPostID() PostID {\n\tboard.postsCtr++\n\treturn PostID(board.postsCtr)\n}\n\nfunc (board *Board) GetURLFromThreadAndReplyID(threadID, replyID PostID) string {\n\tif replyID == 0 {\n\t\treturn board.url + \"/\" + threadID.String()\n\t} else {\n\t\treturn board.url + \"/\" + threadID.String() + \"/\" + replyID.String()\n\t}\n}\n\nfunc (board *Board) GetPostFormURL() string {\n\treturn gRealmLink.Call(\"CreateThread\", \"bid\", board.id.String())\n}\n"},{"name":"boards.gno","body":"package boards\n\nimport (\n\t\"regexp\"\n\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n//----------------------------------------\n// Realm (package) state\n\nvar (\n\tgRealmLink      = txlink.Realm(\"gno.land/r/archive/boards\")\n\tgBoards         avl.Tree    // id -\u003e *Board\n\tgBoardsCtr      int         // increments Board.id\n\tgBoardsByName   avl.Tree    // name -\u003e *Board\n\tgDefaultAnonFee = 100000000 // minimum fee required if anonymous\n)\n\n//----------------------------------------\n// Constants\n\nvar reName = regexp.MustCompile(`^[a-z]+[_a-z0-9]{2,29}$`)\n"},{"name":"example_post.md","body":"Hey all! 👋\n\nThis is my first post in this land!\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/archive/boards\"\ngno = \"0.9\"\n"},{"name":"misc.gno","body":"package boards\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/r/sys/users\"\n)\n\n//----------------------------------------\n// private utility methods\n// XXX ensure these cannot be called from public.\n\nfunc getBoard(bid BoardID) *Board {\n\tbidkey := boardIDKey(bid)\n\tboard_ := gBoards.Get(bidkey)\n\tif board_ == nil {\n\t\treturn nil\n\t}\n\tboard := board_.(*Board)\n\treturn board\n}\n\nfunc incGetBoardID() BoardID {\n\tgBoardsCtr++\n\treturn BoardID(gBoardsCtr)\n}\n\nfunc padLeft(str string, length int) string {\n\tif len(str) \u003e= length {\n\t\treturn str\n\t} else {\n\t\treturn strings.Repeat(\" \", length-len(str)) + str\n\t}\n}\n\nfunc padZero(u64 uint64, length int) string {\n\tstr := strconv.Itoa(int(u64))\n\tif len(str) \u003e= length {\n\t\treturn str\n\t} else {\n\t\treturn strings.Repeat(\"0\", length-len(str)) + str\n\t}\n}\n\nfunc boardIDKey(bid BoardID) string {\n\treturn padZero(uint64(bid), 10)\n}\n\nfunc postIDKey(pid PostID) string {\n\treturn padZero(uint64(pid), 10)\n}\n\nfunc indentBody(indent string, body string) string {\n\tlines := strings.Split(body, \"\\n\")\n\tres := \"\"\n\tfor i, line := range lines {\n\t\tif i \u003e 0 {\n\t\t\tres += \"\\n\"\n\t\t}\n\t\tres += indent + line\n\t}\n\treturn res\n}\n\n// NOTE: length must be greater than 3.\nfunc summaryOf(str string, length int) string {\n\tlines := strings.SplitN(str, \"\\n\", 2)\n\tline := lines[0]\n\tif len(line) \u003e length {\n\t\tline = line[:(length-3)] + \"...\"\n\t} else if len(lines) \u003e 1 {\n\t\t// len(line) \u003c= 80\n\t\tline = line + \"...\"\n\t}\n\treturn line\n}\n\nfunc displayAddressMD(addr address) string {\n\tuser := users.ResolveAddress(addr)\n\tif user == nil {\n\t\treturn \"[\" + addr.String() + \"](/u/\" + addr.String() + \")\"\n\t} else {\n\t\treturn \"[@\" + user.Name() + \"](/u/\" + user.Name() + \")\"\n\t}\n}\n\nfunc usernameOf(addr address) string {\n\tuser := users.ResolveAddress(addr)\n\tif user == nil {\n\t\treturn \"\"\n\t}\n\treturn user.Name()\n}\n"},{"name":"post.gno","body":"package boards\n\nimport (\n\t\"strconv\"\n\t\"time\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n//----------------------------------------\n// Post\n\n// NOTE: a PostID is relative to the board.\ntype PostID uint64\n\nfunc (pid PostID) String() string {\n\treturn strconv.Itoa(int(pid))\n}\n\n// A Post is a \"thread\" or a \"reply\" depending on context.\n// A thread is a Post of a Board that holds other replies.\ntype Post struct {\n\tboard       *Board\n\tid          PostID\n\tcreator     address\n\ttitle       string // optional\n\tbody        string\n\treplies     avl.Tree // Post.id -\u003e *Post\n\trepliesAll  avl.Tree // Post.id -\u003e *Post (all replies, for top-level posts)\n\treposts     avl.Tree // Board.id -\u003e Post.id\n\tthreadID    PostID   // original Post.id\n\tparentID    PostID   // parent Post.id (if reply or repost)\n\trepostBoard BoardID  // original Board.id (if repost)\n\tcreatedAt   time.Time\n\tupdatedAt   time.Time\n}\n\nfunc newPost(board *Board, id PostID, creator address, title, body string, threadID, parentID PostID, repostBoard BoardID) *Post {\n\treturn \u0026Post{\n\t\tboard:       board,\n\t\tid:          id,\n\t\tcreator:     creator,\n\t\ttitle:       title,\n\t\tbody:        body,\n\t\treplies:     avl.Tree{},\n\t\trepliesAll:  avl.Tree{},\n\t\treposts:     avl.Tree{},\n\t\tthreadID:    threadID,\n\t\tparentID:    parentID,\n\t\trepostBoard: repostBoard,\n\t\tcreatedAt:   time.Now(),\n\t}\n}\n\nfunc (post *Post) IsThread() bool {\n\treturn post.parentID == 0\n}\n\nfunc (post *Post) GetPostID() PostID {\n\treturn post.id\n}\n\nfunc (post *Post) AddReply(creator address, body string) *Post {\n\tboard := post.board\n\tpid := board.incGetPostID()\n\tpidkey := postIDKey(pid)\n\treply := newPost(board, pid, creator, \"\", body, post.threadID, post.id, 0)\n\tpost.replies.Set(pidkey, reply)\n\tif post.threadID == post.id {\n\t\tpost.repliesAll.Set(pidkey, reply)\n\t} else {\n\t\tthread := board.GetThread(post.threadID)\n\t\tthread.repliesAll.Set(pidkey, reply)\n\t}\n\treturn reply\n}\n\nfunc (post *Post) Update(title string, body string) {\n\tpost.title = title\n\tpost.body = body\n\tpost.updatedAt = time.Now()\n}\n\nfunc (thread *Post) GetReply(pid PostID) *Post {\n\tpidkey := postIDKey(pid)\n\treplyI := thread.repliesAll.Get(pidkey)\n\tif replyI == nil {\n\t\treturn nil\n\t} else {\n\t\treturn replyI.(*Post)\n\t}\n}\n\nfunc (post *Post) AddRepostTo(creator address, title, body string, dst *Board) *Post {\n\tif !post.IsThread() {\n\t\tpanic(\"cannot repost non-thread post\")\n\t}\n\tpid := dst.incGetPostID()\n\tpidkey := postIDKey(pid)\n\trepost := newPost(dst, pid, creator, title, body, pid, post.id, post.board.id)\n\tdst.threads.Set(pidkey, repost)\n\tif !dst.IsPrivate() {\n\t\tbidkey := boardIDKey(dst.id)\n\t\tpost.reposts.Set(bidkey, pid)\n\t}\n\treturn repost\n}\n\nfunc (thread *Post) DeletePost(pid PostID) {\n\tif thread.id == pid {\n\t\tpanic(\"should not happen\")\n\t}\n\tpidkey := postIDKey(pid)\n\tpostI, removed := thread.repliesAll.Remove(pidkey)\n\tif !removed {\n\t\tpanic(\"post not found in thread\")\n\t}\n\tpost := postI.(*Post)\n\tif post.parentID != thread.id {\n\t\tparent := thread.GetReply(post.parentID)\n\t\tparent.replies.Remove(pidkey)\n\t} else {\n\t\tthread.replies.Remove(pidkey)\n\t}\n}\n\nfunc (post *Post) HasPermission(addr address, perm Permission) bool {\n\tif post.creator == addr {\n\t\tswitch perm {\n\t\tcase EditPermission:\n\t\t\treturn true\n\t\tcase DeletePermission:\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\t// post notes inherit permissions of the board.\n\treturn post.board.HasPermission(addr, perm)\n}\n\nfunc (post *Post) GetSummary() string {\n\treturn summaryOf(post.body, 80)\n}\n\nfunc (post *Post) GetURL() string {\n\tif post.IsThread() {\n\t\treturn post.board.GetURLFromThreadAndReplyID(\n\t\t\tpost.id, 0)\n\t} else {\n\t\treturn post.board.GetURLFromThreadAndReplyID(\n\t\t\tpost.threadID, post.id)\n\t}\n}\n\nfunc (post *Post) GetReplyFormURL() string {\n\treturn gRealmLink.Call(\"CreateReply\",\n\t\t\"bid\", post.board.id.String(),\n\t\t\"threadid\", post.threadID.String(),\n\t\t\"postid\", post.id.String(),\n\t)\n}\n\nfunc (post *Post) GetRepostFormURL() string {\n\treturn gRealmLink.Call(\"CreateRepost\",\n\t\t\"bid\", post.board.id.String(),\n\t\t\"postid\", post.id.String(),\n\t)\n}\n\nfunc (post *Post) GetDeleteFormURL() string {\n\treturn gRealmLink.Call(\"DeletePost\",\n\t\t\"bid\", post.board.id.String(),\n\t\t\"threadid\", post.threadID.String(),\n\t\t\"postid\", post.id.String(),\n\t)\n}\n\nfunc (post *Post) RenderSummary() string {\n\tif post.repostBoard != 0 {\n\t\tdstBoard := getBoard(post.repostBoard)\n\t\tif dstBoard == nil {\n\t\t\tpanic(\"repostBoard does not exist\")\n\t\t}\n\t\tthread := dstBoard.GetThread(PostID(post.parentID))\n\t\tif thread == nil {\n\t\t\treturn \"reposted post does not exist\"\n\t\t}\n\t\treturn \"Repost: \" + post.GetSummary() + \"\\n\" + thread.RenderSummary()\n\t}\n\tstr := \"\"\n\tif post.title != \"\" {\n\t\tstr += \"## [\" + summaryOf(post.title, 80) + \"](\" + post.GetURL() + \")\\n\"\n\t\tstr += \"\\n\"\n\t}\n\tstr += post.GetSummary() + \"\\n\"\n\tstr += \"\\\\- \" + displayAddressMD(post.creator) + \",\"\n\tstr += \" [\" + post.createdAt.Format(\"2006-01-02 3:04pm MST\") + \"](\" + post.GetURL() + \")\"\n\tstr += \" \\\\[[x](\" + post.GetDeleteFormURL() + \")]\"\n\tstr += \" (\" + strconv.Itoa(post.replies.Size()) + \" replies)\"\n\tstr += \" (\" + strconv.Itoa(post.reposts.Size()) + \" reposts)\" + \"\\n\"\n\treturn str\n}\n\nfunc (post *Post) RenderPost(indent string, levels int) string {\n\tif post == nil {\n\t\treturn \"nil post\"\n\t}\n\tstr := \"\"\n\tif post.title != \"\" {\n\t\tstr += indent + \"# \" + post.title + \"\\n\"\n\t\tstr += indent + \"\\n\"\n\t}\n\tstr += indentBody(indent, post.body) + \"\\n\" // TODO: indent body lines.\n\tstr += indent + \"\\\\- \" + displayAddressMD(post.creator) + \", \"\n\tstr += \"[\" + post.createdAt.Format(\"2006-01-02 3:04pm (MST)\") + \"](\" + post.GetURL() + \")\"\n\tstr += \" \\\\[[reply](\" + post.GetReplyFormURL() + \")]\"\n\tif post.IsThread() {\n\t\tstr += \" \\\\[[repost](\" + post.GetRepostFormURL() + \")]\"\n\t}\n\tstr += \" \\\\[[x](\" + post.GetDeleteFormURL() + \")]\\n\"\n\tif levels \u003e 0 {\n\t\tif post.replies.Size() \u003e 0 {\n\t\t\tpost.replies.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\t\tstr += indent + \"\\n\"\n\t\t\t\tstr += value.(*Post).RenderPost(indent+\"\u003e \", levels-1)\n\t\t\t\treturn false\n\t\t\t})\n\t\t}\n\t} else {\n\t\tif post.replies.Size() \u003e 0 {\n\t\t\tstr += indent + \"\\n\"\n\t\t\tstr += indent + \"_[see all \" + strconv.Itoa(post.replies.Size()) + \" replies](\" + post.GetURL() + \")_\\n\"\n\t\t}\n\t}\n\treturn str\n}\n\n// render reply and link to context thread\nfunc (post *Post) RenderInner() string {\n\tif post.IsThread() {\n\t\tpanic(\"unexpected thread\")\n\t}\n\tthreadID := post.threadID\n\t// replyID := post.id\n\tparentID := post.parentID\n\tstr := \"\"\n\tstr += \"_[see thread](\" + post.board.GetURLFromThreadAndReplyID(\n\t\tthreadID, 0) + \")_\\n\\n\"\n\tthread := post.board.GetThread(post.threadID)\n\tvar parent *Post\n\tif thread.id == parentID {\n\t\tparent = thread\n\t} else {\n\t\tparent = thread.GetReply(parentID)\n\t}\n\tstr += parent.RenderPost(\"\", 0)\n\tstr += \"\\n\"\n\tstr += post.RenderPost(\"\u003e \", 5)\n\treturn str\n}\n"},{"name":"public.gno","body":"package boards\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n)\n\n//----------------------------------------\n// Public facing functions\n\nfunc GetBoardIDFromName(name string) (BoardID, bool) {\n\tboardI := gBoardsByName.Get(name)\n\tif boardI == nil {\n\t\treturn 0, false\n\t}\n\treturn boardI.(*Board).id, true\n}\n\nfunc CreateBoard(cur realm, name string) BoardID {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"invalid non-user call\")\n\t}\n\n\tbid := incGetBoardID()\n\tcaller := unsafe.OriginCaller()\n\tif usernameOf(caller) == \"\" {\n\t\tpanic(\"unauthorized\")\n\t}\n\turl := \"/r/archive/boards:\" + name\n\tboard := newBoard(bid, url, name, caller)\n\tbidkey := boardIDKey(bid)\n\tgBoards.Set(bidkey, board)\n\tgBoardsByName.Set(name, board)\n\treturn board.id\n}\n\n// checkAnonFee reads unsafe.OriginSend() to verify the anonymous-posting\n// fee was attached to the tx. Callers MUST also assert\n// cur.Previous().IsUserCall() before calling — see\n// docs/resources/effective-gno.md#verifying-inbound-coin-payments.\nfunc checkAnonFee() bool {\n\tsent := unsafe.OriginSend()\n\tanonFeeCoin := chain.NewCoin(\"ugnot\", int64(gDefaultAnonFee))\n\tif len(sent) == 1 \u0026\u0026 sent[0].IsGTE(anonFeeCoin) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc CreateThread(cur realm, bid BoardID, title string, body string) PostID {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"invalid non-user call\")\n\t}\n\n\tcaller := unsafe.OriginCaller()\n\tif usernameOf(caller) == \"\" {\n\t\tif !checkAnonFee() {\n\t\t\tpanic(\"please register, otherwise minimum fee \" + strconv.Itoa(gDefaultAnonFee) + \" is required if anonymous\")\n\t\t}\n\t}\n\tboard := getBoard(bid)\n\tif board == nil {\n\t\tpanic(\"board not exist\")\n\t}\n\tthread := board.AddThread(caller, title, body)\n\treturn thread.id\n}\n\nfunc CreateReply(cur realm, bid BoardID, threadid, postid PostID, body string) PostID {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"invalid non-user call\")\n\t}\n\n\tcaller := unsafe.OriginCaller()\n\tif usernameOf(caller) == \"\" {\n\t\tif !checkAnonFee() {\n\t\t\tpanic(\"please register, otherwise minimum fee \" + strconv.Itoa(gDefaultAnonFee) + \" is required if anonymous\")\n\t\t}\n\t}\n\tboard := getBoard(bid)\n\tif board == nil {\n\t\tpanic(\"board not exist\")\n\t}\n\tthread := board.GetThread(threadid)\n\tif thread == nil {\n\t\tpanic(\"thread not exist\")\n\t}\n\tif postid == threadid {\n\t\treply := thread.AddReply(caller, body)\n\t\treturn reply.id\n\t} else {\n\t\tpost := thread.GetReply(postid)\n\t\treply := post.AddReply(caller, body)\n\t\treturn reply.id\n\t}\n}\n\n// If dstBoard is private, does not ping back.\n// If board specified by bid is private, panics.\nfunc CreateRepost(cur realm, bid BoardID, postid PostID, title string, body string, dstBoardID BoardID) PostID {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"invalid non-user call\")\n\t}\n\n\tcaller := unsafe.OriginCaller()\n\tif usernameOf(caller) == \"\" {\n\t\t// TODO: allow with gDefaultAnonFee payment.\n\t\tif !checkAnonFee() {\n\t\t\tpanic(\"please register, otherwise minimum fee \" + strconv.Itoa(gDefaultAnonFee) + \" is required if anonymous\")\n\t\t}\n\t}\n\tboard := getBoard(bid)\n\tif board == nil {\n\t\tpanic(\"src board not exist\")\n\t}\n\tif board.IsPrivate() {\n\t\tpanic(\"cannot repost from a private board\")\n\t}\n\tdst := getBoard(dstBoardID)\n\tif dst == nil {\n\t\tpanic(\"dst board not exist\")\n\t}\n\tthread := board.GetThread(postid)\n\tif thread == nil {\n\t\tpanic(\"thread not exist\")\n\t}\n\trepost := thread.AddRepostTo(caller, title, body, dst)\n\treturn repost.id\n}\n\nfunc DeletePost(cur realm, bid BoardID, threadid, postid PostID, reason string) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"invalid non-user call\")\n\t}\n\n\tcaller := unsafe.OriginCaller()\n\tboard := getBoard(bid)\n\tif board == nil {\n\t\tpanic(\"board not exist\")\n\t}\n\tthread := board.GetThread(threadid)\n\tif thread == nil {\n\t\tpanic(\"thread not exist\")\n\t}\n\tif postid == threadid {\n\t\t// delete thread\n\t\tif !thread.HasPermission(caller, DeletePermission) {\n\t\t\tpanic(\"unauthorized\")\n\t\t}\n\t\tboard.DeleteThread(threadid)\n\t} else {\n\t\t// delete thread's post\n\t\tpost := thread.GetReply(postid)\n\t\tif post == nil {\n\t\t\tpanic(\"post not exist\")\n\t\t}\n\t\tif !post.HasPermission(caller, DeletePermission) {\n\t\t\tpanic(\"unauthorized\")\n\t\t}\n\t\tthread.DeletePost(postid)\n\t}\n}\n\nfunc EditPost(cur realm, bid BoardID, threadid, postid PostID, title, body string) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"invalid non-user call\")\n\t}\n\n\tcaller := unsafe.OriginCaller()\n\tboard := getBoard(bid)\n\tif board == nil {\n\t\tpanic(\"board not exist\")\n\t}\n\tthread := board.GetThread(threadid)\n\tif thread == nil {\n\t\tpanic(\"thread not exist\")\n\t}\n\tif postid == threadid {\n\t\t// edit thread\n\t\tif !thread.HasPermission(caller, EditPermission) {\n\t\t\tpanic(\"unauthorized\")\n\t\t}\n\t\tthread.Update(title, body)\n\t} else {\n\t\t// edit thread's post\n\t\tpost := thread.GetReply(postid)\n\t\tif post == nil {\n\t\t\tpanic(\"post not exist\")\n\t\t}\n\t\tif !post.HasPermission(caller, EditPermission) {\n\t\t\tpanic(\"unauthorized\")\n\t\t}\n\t\tpost.Update(title, body)\n\t}\n}\n"},{"name":"render.gno","body":"package boards\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n//----------------------------------------\n// Render functions\n\nfunc RenderBoard(bid BoardID) string {\n\tboard := getBoard(bid)\n\tif board == nil {\n\t\treturn \"missing board\"\n\t}\n\treturn board.RenderBoard()\n}\n\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\tstr := \"These are all the boards of this realm:\\n\\n\"\n\t\tgBoards.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\tboard := value.(*Board)\n\t\t\tstr += \" * [\" + board.url + \"](\" + board.url + \")\\n\"\n\t\t\treturn false\n\t\t})\n\t\treturn str\n\t}\n\tparts := strings.Split(path, \"/\")\n\tif len(parts) == 1 {\n\t\t// /r/archive/boards:BOARD_NAME\n\t\tname := parts[0]\n\t\tboardI := gBoardsByName.Get(name)\n\t\tif boardI == nil {\n\t\t\treturn \"board does not exist: \" + name\n\t\t}\n\t\treturn boardI.(*Board).RenderBoard()\n\t} else if len(parts) == 2 {\n\t\t// /r/archive/boards:BOARD_NAME/THREAD_ID\n\t\tname := parts[0]\n\t\tboardI := gBoardsByName.Get(name)\n\t\tif boardI == nil {\n\t\t\treturn \"board does not exist: \" + name\n\t\t}\n\t\tpid, err := strconv.Atoi(parts[1])\n\t\tif err != nil {\n\t\t\treturn \"invalid thread id: \" + parts[1]\n\t\t}\n\t\tboard := boardI.(*Board)\n\t\tthread := board.GetThread(PostID(pid))\n\t\tif thread == nil {\n\t\t\treturn \"thread does not exist with id: \" + parts[1]\n\t\t}\n\t\treturn thread.RenderPost(\"\", 5)\n\t} else if len(parts) == 3 {\n\t\t// /r/archive/boards:BOARD_NAME/THREAD_ID/REPLY_ID\n\t\tname := parts[0]\n\t\tboardI := gBoardsByName.Get(name)\n\t\tif boardI == nil {\n\t\t\treturn \"board does not exist: \" + name\n\t\t}\n\t\tpid, err := strconv.Atoi(parts[1])\n\t\tif err != nil {\n\t\t\treturn \"invalid thread id: \" + parts[1]\n\t\t}\n\t\tboard := boardI.(*Board)\n\t\tthread := board.GetThread(PostID(pid))\n\t\tif thread == nil {\n\t\t\treturn \"thread does not exist with id: \" + parts[1]\n\t\t}\n\t\trid, err := strconv.Atoi(parts[2])\n\t\tif err != nil {\n\t\t\treturn \"invalid reply id: \" + parts[2]\n\t\t}\n\t\treply := thread.GetReply(PostID(rid))\n\t\tif reply == nil {\n\t\t\treturn \"reply does not exist with id: \" + parts[2]\n\t\t}\n\t\treturn reply.RenderInner()\n\t} else {\n\t\treturn \"unrecognized path \" + path\n\t}\n}\n"},{"name":"role.gno","body":"package boards\n\ntype Permission string\n\nconst (\n\tDeletePermission Permission = \"role:delete\"\n\tEditPermission   Permission = \"role:edit\"\n)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"panictoerr","path":"gno.land/p/aeddi/panictoerr/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/aeddi/panictoerr/v0\"\ngno = \"0.9\"\n"},{"name":"panictoerr.gno","body":"package panictoerr\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// PanicToError executes a function that might panic and, if it does,\n// recovers the panic and converts it to an error.\nfunc PanicToError(mightPanic func()) (err error) {\n\t// Catch any panic that might occur and convert it to an error.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = anyToError(r)\n\t\t}\n\t}()\n\n\t// Execute the function that might panic.\n\tmightPanic()\n\n\treturn nil\n}\n\n// AbortToError executes a function that might abort, and if it does,\n// revives the abort and converts it to an error.\nfunc AbortToError(mightAbort func()) error {\n\t// Catch any abort that might occur and convert it to an error.\n\tif r := revive(mightAbort); r != nil {\n\t\treturn anyToError(r)\n\t}\n\n\treturn nil\n}\n\n// PanicAbortToError executes a function that might either panic or abort,\n// and if it does, it recovers the panic or revives the abort and converts\n// it to an error.\nfunc PanicAbortToError(mightPanicOrAbort func()) error {\n\tvar panicErr error\n\n\t// Catch any panic or abort that might occur and convert it to an error.\n\tif abortErr := AbortToError(func() {\n\t\tpanicErr = PanicToError(mightPanicOrAbort)\n\t}); abortErr != nil {\n\t\treturn abortErr\n\t}\n\n\treturn panicErr\n}\n\n// anyToError converts any value to an error.\nfunc anyToError(v any) error {\n\tswitch v := v.(type) {\n\tcase string:\n\t\treturn errors.New(v)\n\tcase error:\n\t\treturn v\n\tdefault:\n\t\treturn errors.New(ufmt.Sprint(v))\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"helplink","path":"gno.land/p/moul/helplink/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/helplink/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"helplink.gno","body":"// Package helplink provides utilities for creating help page links compatible\n// with Gnoweb, Gnobro, and other clients that support the Gno contracts'\n// flavored Markdown format.\n//\n// This package simplifies the generation of dynamic, context-sensitive help\n// links, enabling users to navigate relevant documentation seamlessly within\n// the Gno ecosystem.\n//\n// For a more lightweight alternative, consider using p/moul/txlink.\n//\n// The primary functions — Func, FuncURL, and Home — are intended for use with\n// the \"relative realm\". When specifying a custom Realm, you can create links\n// that utilize either the current realm path or a fully qualified path to\n// another realm.\npackage helplink\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/txlink/v0\"\n)\n\nvar chainDomain = runtime.ChainDomain()\n\n// Func returns a markdown link for the specific function with optional\n// key-value arguments, for the current realm.\nfunc Func(title string, fn string, args ...string) string {\n\treturn Realm(\"\").Func(title, fn, args...)\n}\n\n// FuncURL returns a URL for the specified function with optional key-value\n// arguments, for the current realm.\nfunc FuncURL(fn string, args ...string) string {\n\treturn Realm(\"\").FuncURL(fn, args...)\n}\n\n// Home returns the URL for the help homepage of the current realm.\nfunc Home() string {\n\treturn Realm(\"\").Home()\n}\n\n// Realm represents a specific realm for generating help links.\ntype Realm string\n\n// prefix returns the URL prefix for the realm.\nfunc (r Realm) prefix() string {\n\t// relative\n\tif r == \"\" {\n\t\tcurPath := unsafe.CurrentRealm().PkgPath()\n\t\treturn strings.TrimPrefix(curPath, chainDomain)\n\t}\n\n\t// local realm -\u003e /realm\n\trlmstr := string(r)\n\tif strings.HasPrefix(rlmstr, chainDomain) {\n\t\treturn strings.TrimPrefix(rlmstr, chainDomain)\n\t}\n\n\t// remote realm -\u003e https://remote.land/realm\n\treturn \"https://\" + rlmstr\n}\n\n// Func returns a markdown link for the specified function with optional\n// key-value arguments.\nfunc (r Realm) Func(title string, fn string, args ...string) string {\n\t// XXX: escape title\n\treturn \"[\" + title + \"](\" + r.FuncURL(fn, args...) + \")\"\n}\n\n// FuncURL returns a URL for the specified function with optional key-value\n// arguments.\nfunc (r Realm) FuncURL(fn string, args ...string) string {\n\ttlr := txlink.Realm(r)\n\treturn tlr.Call(fn, args...)\n}\n\n// Home returns the base help URL for the specified realm.\nfunc (r Realm) Home() string {\n\treturn r.prefix() + \"$help\"\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"sanitize","path":"gno.land/p/nt/markdown/sanitize/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `sanitize` - Markdown input sanitizers\n\nInput-cleaning primitives and safe-emit builders, one per markdown lexical slot. Wrap a user-supplied string with the matching helper before flowing it into rendered markdown, so user content cannot break out of its slot or inject new top-level structure (a heading, table, code fence, link-reference definition, HTML block, or invisible bidi/zero-width spoof).\n\n## Usage\n\n```go\nimport \"gno.land/p/nt/markdown/sanitize/v0\"\n\nout := \"# \" + sanitize.InlineText(userTitle) + \"\\n\\n\" +\n    sanitize.Block(userBody)\nout += sanitize.Blockquote(userQuote)\nout += sanitize.LanguageCodeBlock(realmLang, userCode)\n```\n\n## Two rules\n\n1. **Wrap once.** Most helpers are *not* idempotent: a second pass re-escapes the bytes the first added (`\\*` becomes `\\\\\\*`, `\u0026amp;` becomes `\u0026amp;amp;`, a fenced block gets re-fenced). Wrap each user-derived string with at most one `sanitize.*` call. If a builder package (e.g. `p/moul/md`) already sanitizes an argument, pass the raw input, do not pre-wrap.\n2. **Right helper per slot.** Match the helper to the slot the content lands in.\n\n## Picking the right helper\n\n| Slot | Helper |\n|---|---|\n| `[text](url)`, `# Heading`, `**bold**`, `![alt]`, alert title | `InlineText` |\n| Multi-paragraph body (paragraph-only) | `Block` |\n| Multi-paragraph body with rich structure (headings, lists, tables) | `BlockRich` |\n| Multi-line blockquote | `Blockquote` / `BlockquoteRich` |\n| `[text](url \"title\")` | `LinkTitle` |\n| Table cell | `TableCell` |\n| Inside an HTML tag/attribute (`\u003cgno-card caption=\"X\"\u003e`) | `HTMLEscape` |\n| Any link URL / image src | `URL` / `ImageURL` |\n| Inline / fenced code, with or without a language tag | `InlineCode` / `CodeBlock` / `LanguageCodeBlock` |\n| Footnote body / link-reference definition | `FootnoteDefinition` / `LinkReferenceDefinition` |\n| Validate a handle / bech32 address / label / language / nest prefix | `UserName` / `BechString` / `FootnoteLabel` / `LanguageName` / `NestedPrefix` |\n\n## Escapers vs validators\n\n- **Escapers** always return a transformed, safe string and never reject: any input is acceptable because the transformation makes it safe.\n- **Validators** (`UserName`, `BechString`, `FootnoteLabel`, `LanguageName`, `NestedPrefix`) return the cleaned input verbatim on accept, or `\"\"` on reject. They never half-process, so `\"\"` unambiguously means rejected (or empty input).\n\n## `Block` vs `BlockRich`\n\nBoth run identical realm-binding defenses; they differ in what user structure survives.\n\n- **`Block`** — paragraph-shaped only. Escapes `#`, `\u003e`, list markers, thematic breaks, and setext underlines. Use for leaf slots and any content that must not visually impersonate realm chrome.\n- **`BlockRich`** — preserves user headings, lists, quotes, and tables. Use for content the realm intends to render with full block structure, typically inside a sandbox container (`\u003cgno-card\u003e`, [`\u003cgno-foreign\u003e`](../../foreign/v0)). Inner-heading visual containment is the realm's CSS responsibility.\n\nDo not compose the two in either direction; pick one at the right level.\n\n## API\n\nEscapers (always return a safe, transformed string; never reject):\n\n```go\nfunc InlineText(s string) string\nfunc Block(s string) string\nfunc BlockRich(s string) string\nfunc Blockquote(text string) string\nfunc BlockquoteRich(text string) string\nfunc LinkTitle(s string) string\nfunc TableCell(s string) string\nfunc HTMLEscape(s string) string\nfunc URL(s string) string\nfunc ImageURL(s string) string\nfunc InlineCode(content string) string\nfunc CodeBlock(content string) string\nfunc LanguageCodeBlock(language, content string) string\nfunc CodeFence(content string, minCount int) string // raw fence builder for custom emitters\nfunc FootnoteDefinition(name, text string) string\nfunc LinkReferenceDefinition(label, url, title string) string\n```\n\nValidators (return the cleaned input verbatim, or `\"\"` on reject):\n\n```go\nfunc UserName(s string) string\nfunc BechString(s, prefix string) string\nfunc FootnoteLabel(s string) string\nfunc LanguageName(s string) string\nfunc NestedPrefix(s string) string\n```\n\nLow-level normalizers (rarely needed directly; the helpers above call them):\n\n```go\nfunc StripBidiAndZeroWidth(s string) string\nfunc NormalizeBreaks(s string) string\n```\n\n## Threat model\n\nHelpers defend against bidi/zero-width injection, line-ending homoglyphs, markdown-structure injection, CommonMark HTML-block absorption (types 1-5 that do not close on a blank line), footnote / link-reference namespace pollution, URL scheme abuse (`javascript:`, `data:text/html`, protocol-relative), unclosed code-fence leakage, and table-alignment drift.\n\nOut of scope: no state, no URL reputation, no CSS containment, and no structural sandboxing of opaque foreign blobs (use [`foreign`](../../foreign/v0) for that).\n\n## Notes\n\n- Every helper is a pure function, panic-free for any string input, and runs in `O(len(input))` with bounded allocation.\n- Every text-shaped helper strips bidi/zero-width characters (`Block` and `BlockRich` normalize line breaks first, then strip), so displayed text always matches stored bytes.\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/markdown/sanitize/v0\"\ngno = \"0.9\"\n"},{"name":"sanitize.gno","body":"// Package sanitize provides input-cleaning primitives and safe-emit\n// builders for each markdown lexical slot. Realm authors wrap user-\n// supplied strings with these helpers before flowing them into rendered\n// markdown output. Each helper targets one specific slot (link text,\n// heading text, URL href, table cell, HTML attribute, fenced code block,\n// blockquote, footnote definition, link-reference definition, etc.) and\n// neutralizes the bytes that would otherwise let user content break out\n// of that slot or inject new top-level structure.\n//\n// Pick the right helper from the table under \"Picking the right helper\"\n// below, then wrap each user-supplied argument exactly once at the call\n// site (see \"The audit rule\").\n//\n// # Wrap once\n//\n// Most escapers and safe-emit builders in this package are NOT\n// idempotent — applying them twice re-escapes bytes the first pass\n// added (`\\*` becomes `\\\\\\*`, `\u0026amp;` becomes `\u0026amp;amp;`, a fenced\n// block gets re-fenced). Wrap each user-derived string with at most\n// one sanitize.* call. Block and BlockRich are exceptions —\n// idempotent by design — but the at-most-once rule is still the\n// safest default. See the \"Idempotence classes\" enumeration below\n// for the full breakdown.\n//\n// Some markdown-builder packages (e.g. p/moul/md) sanitize the args of\n// specific helpers internally — see each builder's package doc for the\n// per-helper contract. If the builder sanitizes for you, pass the raw\n// user input; if it doesn't, wrap the input with the right sanitize.*\n// helper at the call site.\n//\n// # Picking the right helper\n//\n// Match the helper to the slot the user content lands in:\n//\n//\tslot                                       helper\n//\t-------------------------------------------------------------\n//\t[text](url)                                InlineText (text)\n//\t# Heading text                             InlineText\n//\t**bold** _italic_                          InlineText\n//\t![alt](src)                                InlineText (alt)\n//\t\u003e [!NOTE] one-line title                   InlineText\n//\tmulti-paragraph post body                  Block\n//\tmulti-paragraph post body w/ rich block    BlockRich\n//\t  structure (headings, lists, tables, etc.)\n//\tmulti-line blockquote (`\u003e ` prefixed)      Blockquote\n//\tmulti-line blockquote w/ rich block body   BlockquoteRich\n//\t[text](url \"title\")                        LinkTitle (title)\n//\t| cell |                                   TableCell\n//\t\u003cgno-card caption=\"X\"\u003e                     HTMLEscape\n//\t\u003ch5\u003eX\u003c/h5\u003e                                 HTMLEscape\n//\tany URL going into ](X)                    URL\n//\tany image src going into (X)               ImageURL\n//\t`inline code` inside running prose         InlineCode\n//\tmulti-line fenced code block               CodeBlock\n//\tmulti-line fenced code with language tag   LanguageCodeBlock\n//\t[^name]: footnote body                     FootnoteDefinition\n//\t[label]: url \"title\" reference def         LinkReferenceDefinition\n//\tr/sys/users handle                         UserName       (validator)\n//\tg1.../gpub1... etc.                        BechString     (validator)\n//\tfootnote / LRD label / {#id} anchor name   FootnoteLabel  (validator)\n//\tfenced-code language tag                   LanguageName   (validator)\n//\tprefix arg to md.Nested                    NestedPrefix   (validator)\n//\n// # Invariants\n//\n// All helpers in this package are panic-free for any string input and\n// run in O(len(input)) time with bounded allocation.\n//\n// Idempotence classes:\n//\n//\tIdempotent (calling twice == calling once):\n//\t  StripBidiAndZeroWidth, NormalizeBreaks\n//\t  UserName, BechString, FootnoteLabel, LanguageName, NestedPrefix\n//\t  URL, ImageURL              (accept→identity; reject→\"\")\n//\t  Block                      (bracket walker treats \\[/\\] as ordinary;\n//\t                              line-leader escapes don't re-fire on\n//\t                              already-escaped `\\#` etc.)\n//\t  BlockRich                  (TrimLeft/TrimRight + \"\\n\\n\" wrap is stable)\n//\n//\tNOT idempotent — never wrap an already-sanitized string:\n//\t  InlineText, LinkTitle, TableCell   (re-escape backslashes)\n//\t  HTMLEscape                         (re-escapes `\u0026` → `\u0026amp;`)\n//\t  Blockquote, BlockquoteRich         (re-prefixes `\u003e `, nesting the quote each pass)\n//\t  InlineCode, CodeBlock,\n//\t  LanguageCodeBlock                  (wrap with a fence — calling twice double-wraps)\n//\t  FootnoteDefinition,\n//\t  LinkReferenceDefinition            (compose Block/InlineText/URL internally —\n//\t                                      passing already-sanitized strings double-escapes)\n//\n//\tCodeFence is pure: same inputs always give the same output.\n//\n// Validators (UserName / BechString / FootnoteLabel / LanguageName /\n// NestedPrefix) return either the cleaned input verbatim or \"\". They\n// never partially-sanitize: if the input doesn't match the slot's\n// charset/shape, the answer is rejection.\n//\n// # Composition rules\n//\n// Direct sanitize use (when emitting markdown without a builder package):\n//\n//\tout := \"# \" + sanitize.InlineText(userTitle) + \"\\n\\n\" +\n//\t       sanitize.Block(userBody)\n//\tout += sanitize.Blockquote(userQuote)\n//\tout += sanitize.LanguageCodeBlock(realmLang, userCode)\n//\n// Use with a builder package (e.g. p/moul/md): pass raw user input to\n// the builder helpers that sanitize internally — do NOT pre-wrap with\n// sanitize.*, or the input gets double-escaped (escapers are not\n// idempotent). See the builder's package doc for the per-helper\n// contract. For example, with p/moul/md:\n//\n//\tmd.Blockquote(userProse)                 // good — md.Blockquote sanitizes\n//\tmd.LanguageCodeBlock(realmLang, userCode) // good — sanitizes both args\n//\tmd.Link(userText, userURL)               // good — sanitizes both slots\n//\n//\tmd.Blockquote(sanitize.Block(userProse))         // BAD: double-wrap\n//\tmd.Link(sanitize.InlineText(t), sanitize.URL(u)) // BAD: double-wrap\n//\n// Wrong (across all callers):\n//\n//\tsanitize.InlineText(sanitize.InlineText(s))   double-wrap (re-escape)\n//\tsanitize.TableCell(sanitize.InlineText(s))    TableCell already calls InlineText\n//\tsanitize.URL(sanitize.InlineText(href))       inline-escape backslash-escapes `.` `-` `_`\n//\t                                              inside the URL, corrupting the host/path\n//\tsanitize.Blockquote(sanitize.Blockquote(s))   double-wrap — outer would escape the\n//\t                                              inner `\u003e ` prefixes\n//\tsanitize.Block(sanitize.BlockRich(s))         double-sanitize — strict Block re-escapes\n//\t                                              the markers BlockRich preserved (headings,\n//\t                                              lists, tables); BlockRich's rich structure\n//\t                                              renders as literal text after Block escapes\n//\t                                              its line-leaders\n//\tsanitize.BlockRich(sanitize.Block(s))         pointless double-sanitize — Block already\n//\t                                              escaped every line-leader to `\\#`/`\\\u003e`/etc.;\n//\t                                              BlockRich preserves the backslash escapes\n//\t                                              as visible artifacts in user prose\n//\tsanitize.Blockquote(sanitize.BlockRich(s))    double-sanitize — Blockquote's Block step\n//\t                                              re-escapes the markers BlockRich preserved\n//\tsanitize.BlockRich(sanitize.Blockquote(s))    nonsense — Blockquote already line-prefixed\n//\t                                              with `\u003e `; BlockRich expects raw user content\n//\tsanitize.BlockquoteRich(sanitize.BlockRich(s)) double-wrap — Rich + Rich nests twice\n//\tsanitize.BlockRich(sanitize.TableCell(s))     wrong slot — use TableCell for cell content,\n//\t                                              BlockRich for multi-paragraph block content\n//\tsanitize.TableCell(multiParagraphProse)       newlines fold to space silently; use a\n//\t                                              non-table layout for multi-paragraph text\n//\n// # Threat model\n//\n// Sanitizers in this package defend against:\n//\n//   - bidi/zero-width injection: invisible characters that make\n//     displayed text disagree with stored bytes (e.g. an address `g1abc...`\n//     that renders as `g1xyz...`, or a username that visually collides\n//     with another). Stripped by StripBidiAndZeroWidth, which runs as\n//     the first step of every text-shaped helper.\n//   - line-ending homoglyphs: CR-only and Unicode separators\n//     (U+0085 NEL, U+2028, U+2029) that some renderers treat as line\n//     breaks. Folded uniformly.\n//   - markdown-structure injection: user content opening a heading,\n//     blockquote, list, code fence, link-reference def, setext underline,\n//     gnoweb extension delimiter, or GFM table row at document level.\n//     Strict Block escapes the line-leading `|` of any GFM table row so\n//     user content cannot inject `\u003ctable\u003e`-shaped structure; permissive\n//     BlockRich preserves table rows so authors can compose `\u003ctable\u003e`\n//     elements (gnoweb loads extension.Table per render_config.go).\n//   - HTML block type 1-5 absorption: CommonMark §4.6 HTML block types 1\n//     (`\u003cscript\u003e`, `\u003cpre\u003e`, `\u003cstyle\u003e`, `\u003ctextarea\u003e`), 2 (`\u003c!--`), 3\n//     (`\u003c?`), 4 (`\u003c!UPPER`), and 5 (`\u003c![CDATA[`) do NOT close on a blank\n//     line — they only close on a type-specific token (`\u003c/tag\u003e`, `--\u003e`,\n//     `?\u003e`, `\u003e`, `]]\u003e`) or EOF. Without a defense, user content opening\n//     any of these would swallow realm chrome appended afterward. Both\n//     Block and BlockRich line-escape the openers (prepend `\\`) so the\n//     block never opens; this defense is unconditional in both modes.\n//     Types 6 and 7 close on a blank line, so BlockRich's `\\n\\n`\n//     paragraph envelope already bounds them and no escape is needed.\n//   - realm-discipline boundary (caller's responsibility, not enforced):\n//     callers should emit realm chrome at flush-left column 0 around\n//     `BlockRich(user)`. Indented chrome (4+ leading spaces, list-item\n//     continuations, footnote-definition body, or an unclosed Type 1\n//     HTML tag in realm chrome before the call) can extend across blank\n//     lines into user content or vice versa. The sanitizer cannot\n//     defend against malformed realm chrome — only against user input.\n//   - footnote / link-reference namespace pollution: user content\n//     containing `[^name]` or `[text][label]` syntax that would otherwise\n//     resolve against realm-defined footnote definitions or link\n//     reference definitions elsewhere on the page. Block escapes the\n//     opening `[` in both shapes.\n//   - reference-link / footnote-ref / shortcut-ref collisions:\n//     `[text][label]`, `[^name]`, and bare `[label]` shortcut forms\n//     are ALL neutralized by Block's bracket walk, which preserves\n//     only inline `[text](url)` and `![alt](src)` syntax — everything\n//     else has both `[` and `]` backslash-escaped, so the parser sees\n//     literal text and can't resolve against realm-defined LRDs or\n//     footnote definitions.\n//   - multi-line LRD evasion: Block's walker recognises `[lab\\nel]: url`\n//     across newlines (single `\\n` OK, blank line aborts) and strips\n//     the whole region. `\\]` inside the label is honored as an escaped\n//     literal, so `[label\\]: url` is NOT treated as an LRD (renders as\n//     literal text).\n//   - URL scheme abuse: javascript:, data:text/html, vbscript:, blob:,\n//     protocol-relative //, mailto: with prefill phishing parameters.\n//     Allowlist-only (URL / ImageURL).\n//   - HTML attribute / element breakout: `\"`, `\u003c`, `\u003e`, `\u0026`, `'` inside\n//     HTML lexical slots. Handled by HTMLEscape.\n//   - CommonMark §2.3 NUL: replaced with U+FFFD by Block, InlineText,\n//     LinkTitle, TableCell, HTMLEscape, InlineCode, CodeBlock, and\n//     LanguageCodeBlock.\n//   - code-fence leakage: a user-opened ``` ``` ``` fence that runs to EOF\n//     with no closing fence, which would otherwise swallow every realm-\n//     emitted line that follows. Block auto-closes any open fence at EOF.\n//   - table-alignment drift: tabs inside table cells expanding to variable\n//     widths (1-4 spaces depending on column position) and shifting cell\n//     boundaries unpredictably. TableCell replaces tabs with single spaces.\n//\n// What this package does NOT do:\n//\n//   - It does not store state. Every helper is a pure function.\n//   - It does not validate semantic correctness. sanitize.URL accepts\n//     a syntactically valid https:// URL even if the host is malicious;\n//     URL reputation is a separate layer.\n//   - It does not enforce CSS containment. ImageURL admits data:image/*\n//     URIs on the assumption that the deploying gnoweb instance caps\n//     rendered image dimensions via CSS. Without that cap, a malicious\n//     image can blow out the page layout or exhaust memory.\n//   - It does not perform structural sandboxing of foreign markdown.\n//     If a realm concatenates an opaque markdown blob returned from a\n//     polymorphic interface (`someThing.Render()`), it needs a structural\n//     sandbox primitive (e.g. a `\u003cgno-card\u003e` extension), not just leaf\n//     sanitization.\n//\n// # When to use Block vs BlockRich\n//\n// Both are safe sanitizers; both run identical realm-binding defenses.\n// They differ in what user-authored block structure survives:\n//\n//   - Block — paragraph-shaped only. Escapes `#`, `\u003e`, list markers,\n//     `---`/`***`/`___` thematic breaks, and `===`/`---` setext\n//     underlines. Use for leaf slots — footnote definition bodies,\n//     table cells, blockquote bodies (Blockquote uses Block), single-\n//     paragraph prose, any slot where richer structure has no benefit\n//     or where richer structure could visually impersonate realm chrome.\n//\n//   - BlockRich — full-richness. Preserves user-authored headings,\n//     lists, quotes, HR, setext. Use for user content the realm intends\n//     to compose with full block-level structure, typically inside a\n//     sandbox container (`\u003cgno-card\u003e`, `\u003cgno-foreign\u003e`) or a CSS-demoted\n//     region. BlockRich's qualifying-setext defense prevents the\n//     cross-boundary attack (user content reaching back to promote\n//     realm chrome to a heading), but inner-heading visual containment\n//     is the realm's CSS responsibility. gnoweb does not yet ship CSS\n//     rules that demote headings inside sandbox containers — until they\n//     land, BlockRich + sandbox renders inner headings at literal size.\n//\n// Do NOT compose Block and BlockRich in either direction. Pick one\n// helper at the right level.\n//\n// # Extending\n//\n// A new helper added to this package MUST:\n//\n//  1. Be panic-free for any string input.\n//  2. Strip bidi+zero-width before any other transform (so display\n//     equals storage end-to-end).\n//  3. Declare its idempotence class in the table above.\n//  4. Document the markdown / HTML lexical slot it targets.\n//  5. Reject rather than partially-sanitize when input is structurally\n//     invalid (return \"\" — never half-process an address or URL).\n//  6. Pick exactly one of the two return-value contracts and stick to\n//     it: escapers always return a transformed string and never reject\n//     (any input is OK — the transformation makes it safe); validators\n//     return the cleaned input verbatim on accept or \"\" on reject and\n//     never half-process. Mixing the contracts within one helper is a\n//     bug — callers can't reason about whether \"\" means \"input was\n//     already empty\" or \"input was rejected\".\npackage sanitize\n\nimport (\n\t\"chain/markdown\"\n\t\"html\"\n\t\"strings\"\n)\n\n// ----- Re-exports of the public chain/markdown natives -----\n//\n// These are general-purpose data-hygiene primitives, not markdown-specific.\n// The other helpers in this package call them internally, so realms emitting\n// markdown rarely need to call them directly. Reach for these when you have\n// a non-markdown use case — e.g. normalizing a username before storage,\n// canonicalizing a search query, or stripping invisible characters from\n// any user string that will be displayed or compared.\n\n// StripBidiAndZeroWidth removes Unicode bidi controls and zero-width\n// characters (U+200B-D, U+200E-F, U+202A-E, U+2066-9, U+FEFF) from s.\n// Use it when storing or comparing user-supplied strings outside of a\n// markdown context — for example, before saving a display name to state,\n// or before hashing a search query. Idempotent: calling twice gives the\n// same result.\n//\n// Thin wrapper over chain/markdown.StripBidiAndZeroWidth.\nfunc StripBidiAndZeroWidth(s string) string {\n\treturn markdown.StripBidiAndZeroWidth(s)\n}\n\n// NormalizeBreaks unifies CR-LF and lone CR to LF (CommonMark §2.2 line\n// endings only — does NOT touch U+2028/U+2029). Use it when comparing\n// or hashing user input that may have been authored on different\n// platforms (Windows CRLF vs. Unix LF), so equivalent strings normalize\n// to the same bytes. Idempotent.\n//\n// Thin wrapper over chain/markdown.NormalizeBreaks.\nfunc NormalizeBreaks(s string) string {\n\treturn markdown.NormalizeBreaks(s)\n}\n\n// ----- Escapers -----\n\n// InlineText prepares an arbitrary user string for an INLINE markdown\n// slot — anywhere the rendered output stays on a single line and lives\n// inside a larger markdown construct.\n//\n// Use for:\n//   - link text:        [InlineText(label)](url)\n//   - heading text:     # InlineText(title)\n//   - bold/italic body: **InlineText(name)**\n//   - image alt text:   ![InlineText(alt)](src)\n//   - single-line block-context slots:\n//     \u003e [!NOTE] InlineText(title)\n//     \u003e Author: InlineText(name)\n//\n// Multi-paragraph prose belongs in Block, not InlineText. InlineText\n// folds every newline to a single space (so paragraph structure is\n// erased) and escapes inline-active CommonMark punctuation:\n//\n//\t\\ * _ [ ] ( ) ~ \u003e - + . ! ` # \u003c \u0026\n//\n// Two characters are intentionally NOT escaped:\n//\n//   - `|` — only meaningful in GFM table rows. Leaving it literal here\n//     lets TableCell (which calls InlineText then escapes `|` itself)\n//     avoid double-escaping pipes into `\\\\|`.\n//   - `=` — only meaningful as a setext heading underline, which is a\n//     line-level construct. Escaping `=` inline would mangle expressions\n//     like `x = 1` for no benefit.\n//\n// Not idempotent (see package doc).\nfunc InlineText(s string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\ts = markdown.NormalizeBreaks(s)       // CM §2.2 \\r\\n / \\r → \\n\n\ts = foldNewlinesAndSeparators(s, ' ') // \\n + NEL + U+2028/U+2029 → space\n\treturn markdown.EscapeInline(s)\n}\n\n// Block prepares user content for a top-level BLOCK markdown context\n// where paragraphs, line breaks, code blocks, and other block structure\n// should survive — but where the content must NOT be able to inject\n// new top-level constructs (headings, lists, blockquotes,\n// link-reference definitions, setext underlines, gnoweb extension\n// delimiters, GFM table rows).\n//\n// Output shape: every non-empty result begins AND ends with \"\\n\\n\" —\n// CM §4.8 blank lines on both sides — so user content is guaranteed\n// to occupy its own paragraph(s), isolated from any realm chrome that\n// precedes OR follows it. This bounds CM §4.6 HTML block types 6 and\n// 7 (`\u003cdiv\u003e`, `\u003ctable\u003e`, `\u003cform\u003e`, arbitrary `\u003cfoo\u003e` tags) which\n// close on a blank line and are NOT escaped in any mode, and it\n// defeats first-line setext promotion (`===`/`---`) that strict-mode\n// escapes miss when the previous line is blank in the user input but\n// non-blank in the concatenated realm output. Empty input (or input\n// that strips entirely, e.g. a lone LRD) returns \"\" — no envelope is\n// emitted.\n//\n// Use for any multi-paragraph user-supplied prose that the realm\n// concatenates into its rendered output:\n//   - post bodies, comments, replies\n//   - profile bios, About sections\n//   - proposal descriptions, governance motions\n//   - changelog entries, release notes\n//\n// What Block does with each kind of attacker input:\n//\n//\tUser attempt                                          | Block's response\n//\t------------------------------------------------------|----------------------------------------------------\n//\t  --- preserved verbatim ---                          |\n//\t[text](url) inline link, ![alt](src) image            | preserved verbatim\n//\t------------------------------------------------------|----------------------------------------------------\n//\t  --- escaped / stripped / folded ---                 |\n//\t# heading at line-start                               | escaped → literal `# heading`\n//\t\u003e quoted at line-start                                | escaped → literal `\u003e`\n//\t- item, * item, + item, 1. item at line-start         | escaped\n//\t---, ***, ___ (3+) at line-start                      | escaped\n//\t=== or --- on its own line after non-blank text       | escaped (no setext promotion of the line above)\n//\t\u003cgno-card\u003e, \u003cgno-columns\u003e, any \u003cgno-…\u003e/\u003c/gno-…\u003e at    | escaped (wildcard match) → literal text\n//\t  line-start                                          |\n//\t| a | b | GFM table row (line-leading `|`)            | escaped → literal `| a | b |`\n//\t\u003c!--, \u003cscript\u003e, \u003cpre\u003e, \u003cstyle\u003e, \u003ctextarea\u003e, \u003c?…?\u003e,    | escaped (\\\u003c…) → literal text;\n//\t  \u003c!DOCTYPE…\u003e, \u003c![CDATA[…]]\u003e at line-start            |   blocks goldmark from opening a\n//\t  (CM §4.6 HTML block types 1-5)                      |   blank-line-NON-terminating HTML block\n//\t[text][realm-label] ref-link USE                      | both bracket pairs escaped → \\[text\\]\\[realm-label\\]\n//\t[^name] footnote-ref                                  | both brackets escaped → \\[^name\\]\n//\t[label] bare shortcut-ref                             | both brackets escaped → \\[label\\]\n//\t[label]: url link-reference definition                | whole region stripped (incl. multi-line label\n//\t  (incl. [lab\\nel]: url multi-line)                   |   `[lab\\nel]: url` and any title continuation)\n//\t[label\\]: url (backslash-escaped `]`)                 | NOT stripped; brackets escaped → paragraph text\n//\tcode fence opened without close                       | autoclosed at end of input\n//\tNUL byte (\\x00)                                       | replaced with U+FFFD\n//\tU+2028 / U+2029 / U+0085 (NEL)                        | folded to `\\n`\n//\tbidi/zero-width controls                              | stripped\n//\n// COMPOSITION GOTCHA: Block's EOF fence-autoclose appends a final\n// fence line. If you wrap Block's output with a line-prefixing\n// builder like md.Blockquote (which prepends `\u003e ` per line) or\n// md.Nested, that closing fence becomes a prefixed line. The output\n// is still safe (the fence still closes correctly) but may render\n// awkwardly. If pixel-perfect output matters, strip a trailing blank\n// fence line after Block.\n//\n// Why backslash and not a space for `\u003cgno-…\u003e` lines: gnoweb's\n// extension parsers call `util.TrimLeftSpace` on the line before tag\n// matching, which would strip a leading space and let the tag match\n// anyway. A leading `\\` survives the trim (only ASCII whitespace +\n// form-feed are stripped) and is consumed by the inline escape phase\n// before Type-7 HTML block detection can fire (Type-7 requires the\n// first non-whitespace char to be `\u003c`).\n//\n// Inline emphasis, code spans, inline links, and soft line breaks\n// within a paragraph are PRESERVED — users can format. Pipes that\n// are NOT at line-start stay literal so prose can still write things\n// like `a | b`.\n//\n// Idempotent: Block(Block(s)) is byte-identical to Block(s). The\n// bracket walker strips LRDs on the first pass; remaining `[`/`]`\n// outside inline-link/image spans are escaped to `\\[`/`\\]`, and\n// already-escaped brackets are preserved on subsequent passes\n// (pass-2 backslash-parity tracking). Still, wrap each user-supplied\n// string exactly once — chained sanitization adds no value and\n// burns gas.\nfunc Block(s string) string {\n\ts = markdown.NormalizeBreaks(s)\n\ts = markdown.StripBidiAndZeroWidth(s)\n\ts = replaceNULWithFFFD(s)\n\ts = markdown.EscapeBlockHazards(s)\n\t// Symmetric \"\\n\\n\" envelope — same pattern BlockRich uses for the\n\t// same reasons (see BlockRich docstring \"Cross-paragraph safety\").\n\t// Strict mode escapes most line-leading hazards (setext, GFM table\n\t// row, CM §4.6 HTML types 1-5, list/heading/HR markers), but two\n\t// hazards remain that only a blank-line break can close:\n\t//\n\t//   - CM §4.6 HTML block types 6 and 7 (`\u003cdiv\u003e`, `\u003ctable\u003e`,\n\t//     `\u003cform\u003e`, arbitrary `\u003cfoo\u003e` tags) are NOT escaped in any mode\n\t//     — they close on a blank line per CM. Without a trailing\n\t//     \"\\n\\n\", a `\u003cdiv\u003e` at the end of user content extends into\n\t//     appended realm chrome.\n\t//\n\t//   - First-line setext: strict mode's setext escape only fires\n\t//     when the previous line is non-blank IN THE USER'S INPUT.\n\t//     A user whose first line is `===` slips past, and concatenated\n\t//     after `chrome\\n` would promote chrome to H1. The leading\n\t//     \"\\n\\n\" forces a paragraph break so chrome cannot be merged.\n\t//\n\t// TrimLeft/TrimRight + fixed wrap is idempotent: Block(Block(s)) is\n\t// byte-identical to Block(s). Empty post-escape result short-\n\t// circuits to \"\" so realm concatenation doesn't leak stray blank\n\t// lines for trivially empty inputs (e.g. lone LRD that strips\n\t// entirely).\n\ts = strings.TrimLeft(s, \"\\n\")\n\ts = strings.TrimRight(s, \"\\n\")\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\treturn \"\\n\\n\" + s + \"\\n\\n\"\n}\n\n// BlockRich is the permissive counterpart of Block. Both are safe\n// sanitizers — the distinction is what markdown structure survives:\n//\n//   - Block escapes line-leading block markers (`#`, `\u003e`, `-`, `*`,\n//     `+`, `1.`), thematic breaks (`---`/`***`/`___`), and setext\n//     underlines (`===`/`---`). User content becomes paragraph-shaped.\n//   - BlockRich PRESERVES all of those, so user content can compose\n//     headings, lists, quotes, horizontal rules, and setext-styled\n//     headings. Realm-binding defenses stay on (extension delimiters\n//     `\u003cgno-…\u003e`, the bracket walker for link / LRD / ref /\n//     footnote / shortcut, fence autoclose, NUL / bidi /\n//     Unicode-separator folding). GFM table-row openers are\n//     PRESERVED (see \"Tables\" below).\n//\n// Cross-paragraph safety: BlockRich's output begins with \"\\n\\n\"\n// AND ends with \"\\n\\n\" — CM §4.8 blank lines on both sides — so\n// user content is guaranteed to occupy its own paragraph(s),\n// isolated from anything the realm emits before OR after. Symmetric\n// isolation closes four distinct attacks:\n//\n//   - Cross-paragraph setext promotion (backward). User content\n//     `body\\n===\\nmore` concatenated after realm chrome (no\n//     trailing `\\n`) would, without paragraph isolation, place\n//     \"chrome\\nbody\" in one paragraph; the `===` setext underline\n//     would then promote that merged paragraph to H1, hijacking\n//     realm chrome. The leading \"\\n\\n\" forces a paragraph break.\n//\n//   - Cross-paragraph GFM table promotion (backward). User content\n//     beginning with `|---|---|` (a table delimiter row) would,\n//     without a blank-line break, retroactively turn the preceding\n//     realm line into a `\u003cthead\u003e`. Paragraph isolation prevents\n//     the table-detection scan from crossing the boundary.\n//\n//   - Cross-paragraph GFM table promotion (forward). Realm chrome\n//     appended immediately after BlockRich(user) that begins with\n//     `|---|` would, without a trailing blank line, extend user's\n//     last line into a table header and pull realm chrome into the\n//     body row. The trailing \"\\n\\n\" prevents the merge.\n//\n//   - Lazy paragraph continuation (forward). Paragraph-shaped realm\n//     chrome appended immediately after BlockRich(user) would, via\n//     CM §5.2, merge into user's trailing paragraph and inherit any\n//     block-level decoration it carries.\n//\n// First-line qualifying-setext escape (the\n// `neuterLeadingSetextIfQualifying` pre-pass) remains in place as\n// belt-and-suspenders: if the first non-blank line of user input\n// matches the CM §4.3 setext-underline pattern (run of `=` or `-`\n// with 0-3 leading spaces and only trailing whitespace), BlockRich\n// inserts `\\` before the first `=`/`-`. This is redundant given\n// paragraph isolation but harmless and inexpensive.\n//\n// # Tables\n//\n// BlockRich preserves line-leading `|` so user content can\n// compose GFM tables:\n//\n//\t| Header A | Header B |\n//\t|----------|----------|\n//\t| cell a   | cell b   |\n//\n// renders as a real `\u003ctable\u003e` element. Strict Block continues to\n// escape line-leading `|` (each row becomes literal `\\| a | b |`\n// text). When the realm authors the table itself and inserts user\n// content into a specific cell, use TableCell — NOT BlockRich —\n// to sanitize that cell value.\n//\n// What attacker input produces what (full table, same rows as Block\n// except where marked CHANGED):\n//\n//\tUser attempt                                  | BlockRich response\n//\t----------------------------------------------|--------------------------------------------------\n//\t  --- preserved (compose freely) ---          |\n//\t# heading at line-start                       | preserved [CHANGED from Block]\n//\t\u003e quoted at line-start                        | preserved [CHANGED]\n//\t- item, * item, + item, 1. item               | preserved [CHANGED]\n//\t---, ***, ___ thematic break                  | preserved [CHANGED]\n//\t=== or --- setext underline                   | preserved when preceded by user text;\n//\t                                              | escaped (\\===/\\---) if the first non-blank\n//\t                                              | line of input [CHANGED]\n//\t| a | b | GFM table row (line-leading |)      | preserved → renders as \u003ctable\u003e when followed by\n//\t                                              | a delimiter row [CHANGED]\n//\t[text](url), ![alt](src)                      | preserved verbatim [SAME]\n//\t----------------------------------------------|--------------------------------------------------\n//\t  --- escaped / stripped / folded ---         |\n//\t\u003cgno-card\u003e, any \u003cgno-…\u003e/\u003c/gno-…\u003e at line-start| escaped (wildcard match) [SAME]\n//\t\u003c!--, \u003cscript\u003e, \u003cpre\u003e, \u003cstyle\u003e, \u003ctextarea\u003e,   | escaped (\\\u003c…) [SAME] — Types 1-5 don't close\n//\t  \u003c?…?\u003e, \u003c!DOCTYPE…\u003e, \u003c![CDATA[…]]\u003e           |   on blank lines, so `\\n\\n` envelope\n//\t  at line-start (CM §4.6 HTML block types 1-5)|   doesn't isolate them; explicit escape\n//\t[text][realm-label] ref-link USE              | both pairs escaped [SAME]\n//\t[^name] footnote-ref                          | both brackets escaped [SAME]\n//\t[label] bare shortcut-ref                     | both brackets escaped [SAME]\n//\t[label]: url link-reference definition        | whole region stripped [SAME]\n//\t[label\\]: url (escaped `]`)                   | not stripped; brackets escaped [SAME]\n//\tcode fence opened without close               | autoclosed at end of input [SAME]\n//\tNUL byte (\\x00)                               | replaced with U+FFFD [SAME]\n//\tU+2028 / U+2029 / U+0085 (NEL)                | folded to `\\n` [SAME]\n//\tbidi/zero-width controls                      | stripped [SAME]\n//\n// Use BlockRich for user content the realm intends to compose with\n// full block-level richness — typically inside a sandbox container\n// (`\u003cgno-card\u003e`, `\u003cgno-foreign\u003e`) or a CSS-demoted region where inner\n// headings render visually distinct from realm chrome. The realm\n// must own the visual containment: concatenating BlockRich's output\n// directly into a top-level page still lets the user write `# heading`\n// at document level. BlockRich's cross-boundary setext defense prevents\n// the worst case (reaching backwards into realm bytes), but visual\n// containment of inner headings is the realm's CSS responsibility.\n// gnoweb does not yet ship CSS rules that demote inner headings inside\n// `\u003cgno-card\u003e` / `\u003cgno-foreign\u003e` — until those rules land, realms\n// using BlockRich + a sandbox should be aware that inner headings\n// render at their literal level.\n//\n// Idempotent: BlockRich(BlockRich(s)) is byte-identical to\n// BlockRich(s). The TrimLeft-then-\"\\n\\n\"-prepend pattern strips\n// any leading newlines and reapplies exactly two, so the leading\n// shape is stable across passes; the qualifying-setext escape is\n// stable (a line beginning with `\\` no longer matches the setext\n// pattern); and the bracket walker treats already-escaped\n// `\\[`/`\\]` as ordinary bytes. Empty input (or input that strips\n// to empty, e.g. a lone link-reference definition) returns \"\" —\n// realm concatenation doesn't get a stray blank line.\n// Still, wrap each user-supplied string exactly once — chained\n// sanitization adds no value and burns gas.\n//\n// Realm-discipline boundary: BlockRich defends user input against\n// every cross-paragraph attack listed above, but it CANNOT defend\n// against malformed REALM chrome. Specifically, callers should emit\n// realm chrome at flush-left column 0 around `BlockRich(user)`. If\n// the realm chrome BEFORE the call contains an unclosed CM §4.6\n// Type 1 HTML tag (`\u003cscript\u003e`, `\u003cpre\u003e`, `\u003cstyle\u003e`, `\u003ctextarea\u003e`),\n// the `\\n\\n` envelope does NOT close it (Type 1 closes only on the\n// matching close tag), and user-controlled `\u003c/tag\u003e` content can\n// then prematurely terminate it. Indented chrome (4+ leading\n// spaces, list-item continuations, footnote-definition body) can\n// likewise extend across the envelope into user content. Keep\n// chrome flush-left and Type 1 tags closed within the chrome.\n//\n// PREVIEW: BlockquoteRich is currently the only in-tree caller of\n// BlockRich; the API and the `\"\\n\\n\"` output shape may evolve once\n// direct callers emerge.\nfunc BlockRich(s string) string {\n\ts = markdown.NormalizeBreaks(s)\n\ts = markdown.StripBidiAndZeroWidth(s)\n\ts = replaceNULWithFFFD(s)\n\t// Fold Unicode separators (U+2028, U+2029, U+0085 NEL) to '\\n'\n\t// BEFORE the setext-qualifying check. The native\n\t// EscapeBlockHazardsRich also folds them internally, but the Gno\n\t// helper below needs to see the folded form to correctly identify\n\t// the first non-blank line — otherwise an attacker can hide the\n\t// `===` setext underline behind a U+2028 / U+2029 / U+0085 and\n\t// reach back to promote realm chrome above it.\n\ts = foldSeparatorsToNewline(s)\n\ts = neuterLeadingSetextIfQualifying(s)\n\ts = markdown.EscapeBlockHazardsRich(s)\n\t// Ensure the output BOTH starts AND ends with \"\\n\\n\" — CM §4.8\n\t// blank lines on each side — so user content is GUARANTEED to\n\t// occupy its own paragraph(s), isolated from anything the realm\n\t// emits before OR after. Symmetric isolation closes four attacks:\n\t//\n\t//  Backward (closed by leading \"\\n\\n\"):\n\t//   1. Deeper-setext: user content `body\\n===\\nmore` concatenated\n\t//      after realm chrome (no trailing `\\n`) would otherwise place\n\t//      \"chrome\\nbody\" in one paragraph; the `===` setext underline\n\t//      would then promote that merged paragraph to H1, hijacking\n\t//      realm chrome.\n\t//   2. GFM table-row promotion: user content beginning with\n\t//      `|---|---|` (a table delimiter row) would, without a blank-\n\t//      line break, retroactively promote the preceding realm line\n\t//      into a `\u003cthead\u003e` cell.\n\t//\n\t//  Forward (closed by trailing \"\\n\\n\"):\n\t//   3. GFM table-row promotion in reverse: realm appending its own\n\t//      chrome immediately after BlockRich(user), where chrome\n\t//      starts with `|---|`, would extend user's last line into a\n\t//      table header and pull realm chrome into the body row.\n\t//   4. Lazy paragraph continuation: realm appending paragraph-\n\t//      shaped chrome immediately after BlockRich(user) would, via\n\t//      CM §5.2 lazy-continuation, merge into user's trailing\n\t//      paragraph and inherit any block-level decoration it carries.\n\t//\n\t// `neuterLeadingSetextIfQualifying` above is now belt-and-\n\t// suspenders for the first-line setext case: even if the blank-\n\t// line guarantee were somehow defeated by an exotic CM consumer,\n\t// the first-line escape still blocks the simplest setext shape.\n\t//\n\t// Empty post-escape result short-circuits to \"\" so realm\n\t// concatenation doesn't leak stray blank lines for trivially empty\n\t// inputs (e.g. a lone link-reference definition that strips\n\t// entirely).\n\t//\n\t// Idempotency: TrimLeft and TrimRight strip ALL leading/trailing\n\t// \"\\n\"s, then the wrap adds exactly two on each side. Stable\n\t// across passes.\n\ts = strings.TrimLeft(s, \"\\n\")\n\ts = strings.TrimRight(s, \"\\n\")\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\treturn \"\\n\\n\" + s + \"\\n\\n\"\n}\n\n// foldSeparatorsToNewline replaces U+0085 NEL (0xC2 0x85),\n// U+2028 (0xE2 0x80 0xA8), and U+2029 (0xE2 0x80 0xA9) with '\\n'.\n// Leaves '\\n' bytes alone. Used by BlockRich so the qualifying-setext\n// pre-pass and the native both see the same line structure.\nfunc foldSeparatorsToNewline(s string) string {\n\t// Cheap pre-check: only the 0xC2 / 0xE2 lead bytes can trigger.\n\tif !containsAnyByteForFold(s) {\n\t\treturn s\n\t}\n\tout := make([]byte, 0, len(s))\n\tfor i := 0; i \u003c len(s); {\n\t\tc := s[i]\n\t\tif c == 0xC2 \u0026\u0026 i+1 \u003c len(s) \u0026\u0026 s[i+1] == 0x85 {\n\t\t\tout = append(out, '\\n')\n\t\t\ti += 2\n\t\t\tcontinue\n\t\t}\n\t\tif c == 0xE2 \u0026\u0026 i+2 \u003c len(s) \u0026\u0026 s[i+1] == 0x80 \u0026\u0026 (s[i+2] == 0xA8 || s[i+2] == 0xA9) {\n\t\t\tout = append(out, '\\n')\n\t\t\ti += 3\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, c)\n\t\ti++\n\t}\n\treturn string(out)\n}\n\nfunc containsAnyByteForFold(s string) bool {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif s[i] == 0xC2 || s[i] == 0xE2 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// neuterLeadingSetextIfQualifying scans s for the first non-blank\n// line. If that line matches the CommonMark §4.3 setext-underline\n// pattern (0-3 leading spaces, then a run of all `=` or all `-`,\n// then optional trailing whitespace, then `\\n` or EOF), the function\n// returns s with a `\\` inserted before the first `=`/`-`. Otherwise\n// returns s unchanged. The escape prevents a realm-emitted line above\n// BlockRich's output from being retroactively promoted to a heading.\nfunc neuterLeadingSetextIfQualifying(s string) string {\n\tpos := 0\n\tfor pos \u003c len(s) {\n\t\t// Walk to the first non-whitespace byte of the current line.\n\t\tlineStart := pos\n\t\ti := pos\n\t\tfor i \u003c len(s) \u0026\u0026 (s[i] == ' ' || s[i] == '\\t') {\n\t\t\ti++\n\t\t}\n\t\tif i \u003e= len(s) || s[i] == '\\n' {\n\t\t\t// Blank line; advance to next line.\n\t\t\tif i \u003e= len(s) {\n\t\t\t\treturn s\n\t\t\t}\n\t\t\tpos = i + 1\n\t\t\tcontinue\n\t\t}\n\t\t// First non-blank line. Check setext-underline shape.\n\t\tif i-lineStart \u003e 3 {\n\t\t\treturn s // 4+ leading spaces = indented code, not setext\n\t\t}\n\t\tc := s[i]\n\t\tif c != '=' \u0026\u0026 c != '-' {\n\t\t\treturn s // not a setext underline candidate\n\t\t}\n\t\tj := i + 1\n\t\tfor j \u003c len(s) \u0026\u0026 s[j] == c {\n\t\t\tj++\n\t\t}\n\t\tfor j \u003c len(s) \u0026\u0026 (s[j] == ' ' || s[j] == '\\t') {\n\t\t\tj++\n\t\t}\n\t\tif j \u003c len(s) \u0026\u0026 s[j] != '\\n' {\n\t\t\treturn s // mixed content on the line — not setext\n\t\t}\n\t\treturn s[:i] + \"\\\\\" + s[i:]\n\t}\n\treturn s\n}\n\n// Blockquote wraps user content as a CommonMark blockquote: each line\n// of the cleaned content gets a \"\u003e \" prefix so the renderer displays\n// it inside a `\u003cblockquote\u003e` element.\n//\n// Use for any multi-paragraph user-supplied text that the realm wants\n// to render as a quotation: cited posts, attached responses, error\n// snapshots that should visually stand out.\n//\n// The content is first cleaned by Block (bidi-strip, line-ending\n// normalize, NUL→U+FFFD, bracket walker for link/image/LRD spans,\n// block-marker escape, code-fence auto-close at EOF, Unicode-separator\n// fold). Block's \"\\n\\n\" cross-paragraph envelope is then stripped —\n// the `\u003e ` marker creates the container boundary, so the envelope\n// would only line-prefix to empty `\u003e ` lines top and bottom — and\n// every remaining line is prefixed with \"\u003e \". The user content can\n// still use inline emphasis, code spans, and nested fenced code blocks\n// inside the quote; what it cannot do is open new top-level structure\n// (heading, list, blockquote, GFM table row, etc.) or escape the\n// quote.\n//\n// Output shape — every non-empty result begins with \"\\n\" and ends\n// with \"\\n\\n\" (same shape as BlockquoteRich):\n//\n//   - Leading \"\\n\" guarantees a clean blockquote opener even when the\n//     realm concatenates `chrome + Blockquote(user)` without its own\n//     newline separator.\n//   - Trailing \"\\n\\n\" (blank line) cleanly ends the blockquote so a\n//     realm appending `Blockquote(user) + chrome` cannot pull chrome\n//     bytes into the quote via CommonMark §5.2 lazy continuation.\n//\n// Empty input (or input that strips entirely, e.g. a lone LRD)\n// returns \"\" — no blockquote is emitted.\n//\n// Composition gotcha: Block's EOF code-fence auto-close (added when\n// user content opens a ``` ``` ``` fence without closing it) becomes a\n// \"\u003e ```\" line at the end of the blockquote. Goldmark parses this\n// correctly as the close of a fenced block inside the quote — the\n// output is structurally safe — but the markdown source looks unusual\n// to a human reviewer. If aesthetic output matters, ensure user\n// content closes its own fences.\n//\n// Not idempotent (see package doc): wraps with `\u003e ` per line, so\n// calling twice double-wraps and the outer call's Block step escapes\n// the inner `\u003e` prefixes.\n//\n// Do NOT compose with BlockRich in either direction:\n//   - Blockquote(BlockRich(s)) double-sanitizes: BlockRich preserves\n//     `#`/`\u003e`/etc., then Blockquote's Block step escapes them again.\n//   - BlockRich(Blockquote(s)) doesn't make sense: Blockquote already\n//     line-prefixed with `\u003e `; BlockRich expects raw user content.\n//\n// For a quoted body that can contain headings, lists, nested quotes,\n// or thematic breaks, use BlockquoteRich.\nfunc Blockquote(text string) string {\n\ttext = Block(text)\n\t// Block wraps its output with \"\\n\\n\" on each side for cross-\n\t// paragraph isolation. Inside a blockquote both wraps are redundant\n\t// — the `\u003e ` marker creates the container boundary — and they\n\t// would line-prefix to two useless `\u003e ` empty quoted lines top and\n\t// bottom. Strip ALL leading and trailing \"\\n\"s so the body starts\n\t// and ends clean; this helper re-wraps with `\\n` + body + `\\n\\n`\n\t// below (same shape as BlockquoteRich).\n\ttext = strings.TrimLeft(text, \"\\n\")\n\tif text == \"\" {\n\t\treturn \"\"\n\t}\n\ttext = strings.TrimRight(text, \"\\n\")\n\tif text == \"\" {\n\t\treturn \"\"\n\t}\n\tvar sb strings.Builder\n\tsb.WriteByte('\\n')\n\tfor _, line := range strings.Split(text, \"\\n\") {\n\t\tsb.WriteString(\"\u003e \")\n\t\tsb.WriteString(line)\n\t\tsb.WriteByte('\\n')\n\t}\n\tsb.WriteByte('\\n')\n\treturn sb.String()\n}\n\n// BlockquoteRich is the permissive counterpart of Blockquote. Both\n// wrap user content as a CommonMark blockquote (each line prefixed\n// with `\u003e `), but they differ in what block-level structure inside\n// the quote survives:\n//\n//   - Blockquote escapes line-leading block markers, so the quoted\n//     body is paragraph-shaped — `# x` inside a Blockquote stays a\n//     literal `#`.\n//   - BlockquoteRich PRESERVES line-leading block markers, so the\n//     quoted body can compose ATX headings, lists, thematic breaks,\n//     nested blockquotes (`\u003e \u003e nested`), and other block-level\n//     structure. Realm-binding defenses stay on (extension delimiters,\n//     GFM table-row openers, bracket walker, fence autoclose,\n//     NUL / bidi / Unicode-separator folding).\n//\n// Output shape — every non-empty result begins with \"\\n\" and ends\n// with \"\\n\\n\":\n//\n//   - Leading \"\\n\" guarantees a clean blockquote opener even when the\n//     realm concatenates `chrome + BlockquoteRich(user)` without its\n//     own newline separator. Without the leading \"\\n\", chrome ending\n//     mid-line followed by \"\u003e quoted\" would render `\u003e` as literal\n//     paragraph text instead of opening a blockquote.\n//   - Trailing \"\\n\\n\" (blank line) cleanly ends the blockquote so a\n//     realm appending `BlockquoteRich(user) + chrome` cannot pull\n//     chrome bytes into the quote via CommonMark §5.2 lazy\n//     continuation. Without the trailing blank line, paragraph chrome\n//     immediately after BlockquoteRich would render inside the quote.\n//   - BlockRich's own leading \"\\n\\n\" (paragraph-isolation blank line)\n//     is stripped before line-prefixing — otherwise the output would\n//     carry one or two redundant empty `\u003e ` quoted lines at the top.\n//     A single \"\\n\" is then re-prepended at the BlockquoteRich\n//     boundary so `chrome + BlockquoteRich(user)` still lands the\n//     first `\u003e` at column 0.\n//   - The cross-boundary setext defense BlockRich provides is\n//     redundant inside a blockquote: a setext underline inside `\u003e `\n//     content can only promote a line in the same blockquote, never\n//     reach realm bytes (different CM container). BlockRich still\n//     applies it, harmlessly.\n//\n// What attacker input produces what (rows that differ from\n// Blockquote are marked CHANGED):\n//\n//\tUser attempt                                  | BlockquoteRich response\n//\t----------------------------------------------|------------------------------------------------\n//\t  --- preserved inside `\u003e ` quote ---         |\n//\t# heading                                     | preserved as `\u003e # heading` [CHANGED]\n//\t\u003e nested quote                                | preserved as `\u003e \u003e nested quote` [CHANGED]\n//\t- item, * item, + item, 1. item               | preserved as `\u003e - item` etc. [CHANGED]\n//\t---, ***, ___ thematic break                  | preserved [CHANGED]\n//\t=== or --- setext underline                   | preserved when preceded by user text;\n//\t                                              | escaped (\\===/\\---) if first non-blank\n//\t                                              | line of input [CHANGED]\n//\t| a | b | GFM table row (line-leading |)      | preserved → renders as \u003ctable\u003e inside the\n//\t                                              | blockquote when followed by a delimiter row [CHANGED]\n//\t[text](url), ![alt](src)                      | preserved verbatim [SAME]\n//\t----------------------------------------------|------------------------------------------------\n//\t  --- escaped / stripped / folded ---         |\n//\t\u003cgno-card\u003e, any \u003cgno-…\u003e/\u003c/gno-…\u003e at line-start| escaped (wildcard match) [SAME]\n//\t\u003c!--, \u003cscript\u003e, \u003cpre\u003e, \u003cstyle\u003e, \u003ctextarea\u003e,   | escaped (\\\u003c…) [SAME] — CM §4.6 Types 1-5\n//\t  \u003c?…?\u003e, \u003c!DOCTYPE…\u003e, \u003c![CDATA[…]]\u003e           |   don't close on blank lines; without escape\n//\t  at line-start                               |   they would swallow chrome past the `\u003e ` quote\n//\t[text][realm-label] ref-link USE              | both pairs escaped [SAME]\n//\t[^name] footnote-ref                          | both brackets escaped [SAME]\n//\t[label] bare shortcut-ref                     | both brackets escaped [SAME]\n//\t[label]: url link-reference definition        | whole region stripped [SAME]\n//\tcode fence opened without close               | autoclosed at end of input [SAME]\n//\tNUL byte (\\x00)                               | replaced with U+FFFD [SAME]\n//\tU+2028 / U+2029 / U+0085 (NEL)                | folded to `\\n` [SAME]\n//\tbidi/zero-width controls                      | stripped [SAME]\n//\n// Use BlockquoteRich when the realm wants to render user content as\n// a quotation that itself reads like authored markdown — the visual\n// CSS containment of `\u003cblockquote\u003e` already demotes inner headings\n// relative to realm chrome, so the \"inner headings need a sandbox\"\n// caveat that applies to BlockRich at top level does not apply here.\n//\n// Not idempotent: like Blockquote, calling twice double-wraps —\n// `BlockquoteRich(BlockquoteRich(s))` produces `\u003e \u003e content`,\n// nesting the quote a level deeper each pass.\n//\n// Empty input (or input that reduces to nothing after BlockRich,\n// e.g. a lone link-reference definition) returns \"\" — no blockquote\n// is emitted and neither the leading \"\\n\" nor the trailing \"\\n\\n\"\n// shape applies.\nfunc BlockquoteRich(text string) string {\n\ttext = BlockRich(text)\n\t// BlockRich wraps user content with \"\\n\\n\" on each side for\n\t// cross-paragraph isolation. Inside a blockquote both wraps are\n\t// redundant — the `\u003e ` marker creates the container boundary —\n\t// and they would line-prefix to two useless `\u003e ` empty quoted\n\t// lines top and bottom. Strip ALL leading and trailing \"\\n\"s so\n\t// the body starts and ends clean; this helper re-wraps with `\\n`\n\t// + body + `\\n\\n` below.\n\ttext = strings.TrimLeft(text, \"\\n\")\n\tif text == \"\" {\n\t\treturn \"\"\n\t}\n\t// Strip ALL trailing newlines so the loop produces exactly one\n\t// `\u003e line` per content line, then append `\\n\\n` at the end so the\n\t// blockquote terminates cleanly (see \"Output shape\" above).\n\ttext = strings.TrimRight(text, \"\\n\")\n\tif text == \"\" {\n\t\treturn \"\"\n\t}\n\tvar sb strings.Builder\n\t// Leading \"\\n\" so `chrome + BlockquoteRich(user)` cannot land the\n\t// first `\u003e` mid-line.\n\tsb.WriteByte('\\n')\n\tfor _, line := range strings.Split(text, \"\\n\") {\n\t\tsb.WriteString(\"\u003e \")\n\t\tsb.WriteString(line)\n\t\tsb.WriteByte('\\n')\n\t}\n\t// Trailing blank line so `BlockquoteRich(user) + chrome` cannot\n\t// pull chrome into the quote via lazy continuation.\n\tsb.WriteByte('\\n')\n\treturn sb.String()\n}\n\n// LinkTitle prepares user content for a CommonMark link-title or\n// image-title slot — the optional quoted text after the URL in any of\n// these forms:\n//\n//\t[text](url \"TITLE\")\n//\t![alt](src \"TITLE\")\n//\t[label]: url \"TITLE\"\n//\n// Escapes the inline-active set plus `\"` and `'` (the title delimiters\n// that aren't already in the inline set; `(` and `)` are), so the\n// caller can choose any of the three title-quote styles safely.\n//\n// Pick the right helper for the slot — markdown title and HTML\n// attribute share the look but use different escape rules:\n//\n//\t[text](url \"X\")              → LinkTitle      (markdown title)\n//\t\u003ca title=\"X\"\u003e                → HTMLEscape     (HTML attribute)\n//\t\u003ch5\u003eX\u003c/h5\u003e                   → HTMLEscape     (HTML element body)\n//\n// Swapping HTMLEscape for LinkTitle is wrong: HTML's `\u0026amp;` written\n// inside a markdown title renders as the literal characters `\u0026amp;`.\n// Swapping LinkTitle for HTMLEscape is wrong: markdown's `\\\"` survives\n// into the rendered HTML as a literal backslash-quote.\n//\n// Not idempotent (see package doc).\nfunc LinkTitle(s string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\ts = markdown.NormalizeBreaks(s)\n\ts = foldNewlinesAndSeparators(s, ' ')\n\treturn markdown.EscapeTitle(s)\n}\n\n// TableCell prepares user content for a GFM table cell — the bytes\n// between two `|` column delimiters in a table row like\n// `| cell-a | cell-b | cell-c |`. An unescaped `|` inside cell\n// content would open a new column, letting a malicious user shift\n// every column to its right.\n//\n// On top of InlineText's behavior, TableCell:\n//   - escapes `|` to `\\|` so user content can't end the cell early.\n//   - replaces tabs with single spaces. CommonMark expands tabs to\n//     the next multiple-of-4 column boundary (variable 1-4 spaces),\n//     which would shift the displayed cell-content width unpredictably\n//     and confuse table alignment.\n//\n// Not idempotent (see package doc).\nfunc TableCell(s string) string {\n\ts = InlineText(s)\n\ts = strings.ReplaceAll(s, \"\\t\", \" \")\n\ts = strings.ReplaceAll(s, \"|\", `\\|`)\n\treturn s\n}\n\n// HTMLEscape prepares user content for an HTML lexical slot inside\n// markdown — covers attribute values, element bodies, and HTML\n// comment bodies:\n//\n//\t\u003cgno-card type=\"...\" caption=\"X\"\u003e         attribute value\n//\t\u003cgno-alert title=\"X\"\u003e                     attribute value\n//\t\u003ch5\u003eX\u003c/h5\u003e                                element body\n//\t\u003cdetails\u003e\u003csummary\u003eX\u003c/summary\u003e...          element body\n//\t\u003c!-- X --\u003e                                comment body (safe: `\u003e`\n//\t                                          becomes `\u0026gt;`, so user\n//\t                                          cannot inject `--\u003e`)\n//\n// HTMLEscape escapes the union of attribute-breaking and body-breaking\n// characters (`\u003c`, `\u003e`, `\u0026`, `\"`, `'`), so one function safely serves\n// every HTML lexical context. Callers don't have to remember which\n// subset to use for which slot.\n//\n// Pick the right helper — markdown title and HTML attribute share\n// the look but use different escape rules:\n//\n//\t[text](url \"X\")              → LinkTitle      (markdown title)\n//\t\u003cspan title=\"X\"\u003e             → HTMLEscape     (HTML attribute)\n//\t\u003ch5\u003eX\u003c/h5\u003e                   → HTMLEscape     (HTML element body)\n//\n// Swapping InlineText for HTMLEscape is wrong: markdown's backslash\n// escapes survive into the rendered HTML as literal `\\*`. Swapping\n// LinkTitle for HTMLEscape is also wrong: `\u0026amp;` written inside a\n// markdown title renders as the literal characters `\u0026amp;`.\n//\n// Not idempotent (see package doc): calling twice produces\n// `\u0026amp;` → `\u0026amp;amp;`.\nfunc HTMLEscape(s string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\ts = markdown.NormalizeBreaks(s)\n\ts = foldNewlinesAndSeparators(s, ' ')\n\ts = replaceNULWithFFFD(s)\n\treturn html.EscapeString(s)\n}\n\n// ----- URL filters -----\n\n// URL validates a URL for use as a link href, percent-encodes unsafe\n// bytes, and rejects anything outside the allowlist of schemes.\n//\n// Allowlist:\n//   - http, https\n//   - mailto (rejected if it carries any query: prefill phishing via\n//     body, subject, cc, etc. Both '?' and '\u0026' are rejected; see\n//     linkSchemeAllowed for why '\u0026' counts.)\n//   - any URL WITHOUT a scheme — relative paths (`/path`, `./rel`,\n//     `bare-path`), query-only (`?q=v`), fragment-only (`#anchor`).\n//     A `:` appearing inside the URL (e.g. `/path:foo`, `?q=a:b`) is\n//     NOT a scheme separator per RFC 3986 — only `:` immediately after\n//     a leading `[a-zA-Z][a-zA-Z0-9+.-]*` counts.\n//\n// Rejected (have an unknown scheme):\n//   - javascript:, data:, vbscript:, blob:, file:, etc.\n//   - `//host/...` (protocol-relative — tracking-pixel vector)\n//\n// Returns \"\" if the URL is empty after trim or fails the allowlist.\nfunc URL(s string) string {\n\ts = strings.TrimSpace(s)\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\tif !linkSchemeAllowed(s) {\n\t\treturn \"\"\n\t}\n\treturn markdown.PercentEncodeURL(s)\n}\n\n// ImageURL validates a URL for use as an image src. Kept separate from\n// URL — not a parameterized variant — because the allowlist shapes\n// differ qualitatively (data:image/* vs. mailto:) and a single boolean\n// flag would invite callers to pass the wrong default.\n//\n// Allowlist:\n//   - http, https\n//   - schemeless relative URLs starting with /, ./, or ..\n//     (rejects // protocol-relative — tracking-pixel vector)\n//   - data:image/svg+xml, data:image/png, data:image/jpeg,\n//     data:image/gif, data:image/webp\n//\n// Any other data: subtype is rejected — data:text/html etc. would\n// render as inline HTML and execute embedded scripts.\n//\n// DEPLOYMENT PRECONDITION: data: URIs encode the bytes of the image\n// directly into the markup, so a malicious sender can construct an\n// image whose pixel dimensions are arbitrarily large at minimal byte\n// cost. The deploying gnoweb instance MUST clamp rendered image\n// dimensions via CSS (e.g. `max-width: 100%; max-height: \u003cbound\u003e`).\n// Without that cap, a single image can blow out the page layout or\n// exhaust the browser's memory.\n//\n// Returns \"\" if the URL is empty after trim or fails the allowlist.\nfunc ImageURL(s string) string {\n\ts = strings.TrimSpace(s)\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\tif !imageSchemeAllowed(s) {\n\t\treturn \"\"\n\t}\n\treturn markdown.PercentEncodeURL(s)\n}\n\n// ----- Validators -----\n\n// userNameCharsets builds the [2]uint64 bitmaps for the r/sys/users\n// charset: first [a-z], rest [a-z0-9_-]. Initialized once at package\n// init.\nvar (\n\tuserNameFirstLo, userNameFirstHi           uint64\n\tuserNameRestLo, userNameRestHi             uint64\n\tfootnoteLabelFirstLo, footnoteLabelFirstHi uint64\n\tfootnoteLabelRestLo, footnoteLabelRestHi   uint64\n\tlangFirstLo, langFirstHi                   uint64\n\tlangRestLo, langRestHi                     uint64\n\tbechHrpFirstLo, bechHrpFirstHi             uint64\n\tbechHrpRestLo, bechHrpRestHi               uint64\n\tbechDataFirstLo, bechDataFirstHi           uint64\n\tbechDataRestLo, bechDataRestHi             uint64\n)\n\nfunc init() {\n\t// UserName: first [a-z], rest [a-z0-9_-].\n\tfor c := byte('a'); c \u003c= 'z'; c++ {\n\t\tsetBit(\u0026userNameFirstLo, \u0026userNameFirstHi, c)\n\t\tsetBit(\u0026userNameRestLo, \u0026userNameRestHi, c)\n\t}\n\tfor c := byte('0'); c \u003c= '9'; c++ {\n\t\tsetBit(\u0026userNameRestLo, \u0026userNameRestHi, c)\n\t}\n\tsetBit(\u0026userNameRestLo, \u0026userNameRestHi, '_')\n\tsetBit(\u0026userNameRestLo, \u0026userNameRestHi, '-')\n\n\t// FootnoteLabel: [A-Za-z0-9_-] for both first and rest.\n\tfor c := byte('A'); c \u003c= 'Z'; c++ {\n\t\tsetBit(\u0026footnoteLabelFirstLo, \u0026footnoteLabelFirstHi, c)\n\t\tsetBit(\u0026footnoteLabelRestLo, \u0026footnoteLabelRestHi, c)\n\t}\n\tfor c := byte('a'); c \u003c= 'z'; c++ {\n\t\tsetBit(\u0026footnoteLabelFirstLo, \u0026footnoteLabelFirstHi, c)\n\t\tsetBit(\u0026footnoteLabelRestLo, \u0026footnoteLabelRestHi, c)\n\t}\n\tfor c := byte('0'); c \u003c= '9'; c++ {\n\t\tsetBit(\u0026footnoteLabelFirstLo, \u0026footnoteLabelFirstHi, c)\n\t\tsetBit(\u0026footnoteLabelRestLo, \u0026footnoteLabelRestHi, c)\n\t}\n\tfor _, c := range []byte{'_', '-'} {\n\t\tsetBit(\u0026footnoteLabelFirstLo, \u0026footnoteLabelFirstHi, c)\n\t\tsetBit(\u0026footnoteLabelRestLo, \u0026footnoteLabelRestHi, c)\n\t}\n\n\t// LanguageName: [a-zA-Z0-9_+-] for both first and rest.\n\tfor c := byte('A'); c \u003c= 'Z'; c++ {\n\t\tsetBit(\u0026langFirstLo, \u0026langFirstHi, c)\n\t\tsetBit(\u0026langRestLo, \u0026langRestHi, c)\n\t}\n\tfor c := byte('a'); c \u003c= 'z'; c++ {\n\t\tsetBit(\u0026langFirstLo, \u0026langFirstHi, c)\n\t\tsetBit(\u0026langRestLo, \u0026langRestHi, c)\n\t}\n\tfor c := byte('0'); c \u003c= '9'; c++ {\n\t\tsetBit(\u0026langFirstLo, \u0026langFirstHi, c)\n\t\tsetBit(\u0026langRestLo, \u0026langRestHi, c)\n\t}\n\tfor _, c := range []byte{'_', '+', '-'} {\n\t\tsetBit(\u0026langFirstLo, \u0026langFirstHi, c)\n\t\tsetBit(\u0026langRestLo, \u0026langRestHi, c)\n\t}\n\n\t// Bech HRP (when prefix==\"\"): [a-z], 1-16 chars.\n\tfor c := byte('a'); c \u003c= 'z'; c++ {\n\t\tsetBit(\u0026bechHrpFirstLo, \u0026bechHrpFirstHi, c)\n\t\tsetBit(\u0026bechHrpRestLo, \u0026bechHrpRestHi, c)\n\t}\n\n\t// Bech data part: [a-z0-9], 6-90 chars.\n\tfor c := byte('a'); c \u003c= 'z'; c++ {\n\t\tsetBit(\u0026bechDataFirstLo, \u0026bechDataFirstHi, c)\n\t\tsetBit(\u0026bechDataRestLo, \u0026bechDataRestHi, c)\n\t}\n\tfor c := byte('0'); c \u003c= '9'; c++ {\n\t\tsetBit(\u0026bechDataFirstLo, \u0026bechDataFirstHi, c)\n\t\tsetBit(\u0026bechDataRestLo, \u0026bechDataRestHi, c)\n\t}\n}\n\nfunc setBit(lo, hi *uint64, c byte) {\n\tif c \u003c 64 {\n\t\t*lo |= 1 \u003c\u003c c\n\t} else {\n\t\t*hi |= 1 \u003c\u003c (c - 64)\n\t}\n}\n\n// UserName validates the r/sys/users-registration charset:\n// ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ length ≤ 64.\n//\n// The native MatchCharsetN enforces the leading-letter + tail-charset\n// shape and length bound; this helper also performs the bidi-strip\n// pre-pass. The \"no consecutive [_-]\" rule from r/sys/users is NOT\n// enforced here (it's a registration-policy rule, not a sanitization\n// concern — registrations go through r/sys/users itself).\n//\n// Returns the (bidi-stripped) input if valid, \"\" otherwise. On a \"\"\n// return, do not emit the user-mention markup at all (e.g. skip the\n// `[@user](/u/user)` link); falling back to the raw user-supplied\n// string would defeat the validation.\nfunc UserName(s string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\tif markdown.MatchCharsetN(s, userNameFirstLo, userNameFirstHi, userNameRestLo, userNameRestHi, 1, 64) {\n\t\treturn s\n\t}\n\treturn \"\"\n}\n\n// BechString validates a bech32-style address-like string.\n//\n// A bech32 string has the shape `\u003chrp\u003e1\u003cdata\u003e`: a human-readable\n// prefix (HRP) that names the family (e.g. `g` for gno addresses,\n// `gpub` for gno pubkeys, `cosmos` for cosmos addresses), the\n// separator character `1`, then a data part carrying the encoded\n// payload as lowercase alphanumerics.\n//\n// If prefix != \"\", requires s to start with prefix+\"1\" exactly, and the\n// data part to match ^[a-z0-9]{6,90}$. Use this when you know the\n// expected family:\n//\n//\tsanitize.BechString(addr, \"g\")     // only g1...     (addresses)\n//\tsanitize.BechString(pk,   \"gpub\")  // only gpub1...  (pubkeys)\n//\n// If prefix == \"\", accepts any reasonable bech32 shape:\n// ^[a-z]{1,16}1[a-z0-9]{6,90}$.\n//\n// Syntactic only — does NOT verify the bech32 checksum. Use a true\n// bech32 decoder if you need that. Returns the cleaned input on\n// accept, \"\" on reject; on \"\" return, do not emit the address-link\n// markup (the user-supplied bytes have failed shape validation and\n// should not appear unmodified in output).\nfunc BechString(s, prefix string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\tif prefix != \"\" {\n\t\t// HRP must be lowercase ASCII letters.\n\t\tfor i := 0; i \u003c len(prefix); i++ {\n\t\t\tc := prefix[i]\n\t\t\tif c \u003c 'a' || c \u003e 'z' {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t}\n\t\tneed := prefix + \"1\"\n\t\tif !strings.HasPrefix(s, need) {\n\t\t\treturn \"\"\n\t\t}\n\t\tdata := s[len(need):]\n\t\tif markdown.MatchCharsetN(data, bechDataFirstLo, bechDataFirstHi, bechDataRestLo, bechDataRestHi, 6, 90) {\n\t\t\treturn s\n\t\t}\n\t\treturn \"\"\n\t}\n\t// prefix == \"\" — accept any 1-16 char lowercase HRP, then '1', then data.\n\tsep := strings.IndexByte(s, '1')\n\tif sep \u003c 1 || sep \u003e 16 {\n\t\treturn \"\"\n\t}\n\thrp := s[:sep]\n\tif !markdown.MatchCharsetN(hrp, bechHrpFirstLo, bechHrpFirstHi, bechHrpRestLo, bechHrpRestHi, 1, 16) {\n\t\treturn \"\"\n\t}\n\tdata := s[sep+1:]\n\tif markdown.MatchCharsetN(data, bechDataFirstLo, bechDataFirstHi, bechDataRestLo, bechDataRestHi, 6, 90) {\n\t\treturn s\n\t}\n\treturn \"\"\n}\n\n// FootnoteLabel validates an identifier used as a footnote name, link-\n// reference-definition label, or {#id} anchor: ^[A-Za-z0-9_-]{1,64}$.\n// Strips bidi/zero-width first. Returns s if valid, \"\" otherwise.\n//\n// Use for every shape where a markdown identifier is treated as an\n// opaque key by the parser:\n//\n//   - footnote-definition labels:        [^FootnoteLabel(name)]: body\n//   - footnote-reference labels:         see [^FootnoteLabel(name)]\n//   - link-reference-definition labels:  [FootnoteLabel(label)]: url\n//   - reference-link USE labels:         [text][FootnoteLabel(label)]\n//   - goldmark auto-anchor {#id}:        # Heading {#FootnoteLabel(id)}\n//\n// The shared validator name reflects the shared charset and shared\n// security goal — keep untrusted bytes out of any parser-managed\n// identifier slot.\n//\n// On \"\" return, omit the footnote / LRD / anchor entirely rather than\n// emitting it with raw user bytes.\nfunc FootnoteLabel(s string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\tif markdown.MatchCharsetN(s, footnoteLabelFirstLo, footnoteLabelFirstHi, footnoteLabelRestLo, footnoteLabelRestHi, 1, 64) {\n\t\treturn s\n\t}\n\treturn \"\"\n}\n\n// LanguageName validates the language tag (a.k.a. \"info string\") for\n// a fenced code block — the `go` in:\n//\n//\t```go\n//\tfmt.Println(\"hi\")\n//\t```\n//\n// Charset: ^[a-zA-Z0-9_+-]{1,32}$ — letters, digits, `_`, `+`, `-`,\n// up to 32 bytes. Strips bidi/zero-width first.\n//\n// Returns the cleaned input if valid, \"\" otherwise. A \"\" return means\n// the caller should emit a language-less fence (``` without a tag)\n// rather than letting the user pick the syntax highlighter — which\n// could otherwise be used to inject newlines or block markers into\n// what becomes the opening fence line.\nfunc LanguageName(s string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\tif markdown.MatchCharsetN(s, langFirstLo, langFirstHi, langRestLo, langRestHi, 1, 32) {\n\t\treturn s\n\t}\n\treturn \"\"\n}\n\n// NestedPrefix validates a prefix string for line-prefixing builders\n// like md.Nested, which prepends `prefix` to every line of content\n// to render the content as a nested/indented sub-block.\n//\n// Allowed: any string matching `^[ \\t\u003e]*$` — spaces, tabs, blockquote\n// `\u003e` chars only. Anything else (a `#`, a `-`, a letter) would let a\n// caller turn benign sub-content into a heading, list, or paragraph\n// at the wrong nesting level.\n//\n// Returns s if valid, \"\" otherwise. Strips bidi/zero-width first —\n// otherwise an invisible character hidden inside a `\u003e` prefix would\n// be replicated on every nested content line, producing per-line\n// display-vs-storage divergence.\n//\n// On \"\" return, fall back to a known-safe prefix literal (e.g.\n// `\"\u003e \"`) or skip the nesting entirely. Do not emit the raw\n// user-supplied prefix.\nfunc NestedPrefix(s string) string {\n\ts = markdown.StripBidiAndZeroWidth(s)\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c != ' ' \u0026\u0026 c != '\\t' \u0026\u0026 c != '\u003e' {\n\t\t\treturn \"\"\n\t\t}\n\t}\n\treturn s\n}\n\n// ----- Primitive -----\n\n// CodeFence returns a string of backticks long enough to wrap content\n// as a CommonMark fenced code block without the content's own backticks\n// closing the fence prematurely.\n//\n// Returned length N = max(minCount, longestBacktickRunInContent + 1).\n// Use N backticks both before and after the content:\n//\n//\tfence := sanitize.CodeFence(userCode, 3)\n//\tout += fence + \"\\n\" + userCode + \"\\n\" + fence + \"\\n\"\n//\n// Typical minCount values:\n//   - 1 for inline code spans (`x`)\n//   - 3 for block fenced code (CommonMark §4.5 requires ≥3)\n//\n// `minCount \u003c 1` is clamped to 1. Empty content returns\n// strings.Repeat(\"`\", max(minCount, 1)). Never panics.\n//\n// Most realms should reach for InlineCode / CodeBlock /\n// LanguageCodeBlock below, which call CodeFence internally and emit\n// the full code block for you. Call CodeFence directly only when\n// you're rolling a custom fence emitter (e.g. a renderer that needs\n// the fence length but emits the body differently).\nfunc CodeFence(content string, minCount int) string {\n\treturn markdown.CodeFence(content, minCount)\n}\n\n// InlineCode wraps user content as a CommonMark inline code span — the\n// `code` in “ `code` “. Use for any user-derived token, identifier,\n// or short literal that should render in monospace inside running\n// prose: variable names, hashes, hex addresses, token symbols, error\n// codes, package paths, transaction IDs.\n//\n// Inline code spans cannot span lines (a `\\n` inside the content would\n// end the span and leave the surrounding backticks as literal text),\n// so all line breaks — CR / CRLF / LF, NEL (U+0085), U+2028, U+2029 —\n// are folded to a single space. If you want each line of user content\n// on its own row, use CodeBlock instead.\n//\n// Behavior:\n//   - Bidi/zero-width controls are stripped (browsers honor bidi marks\n//     inside `\u003ccode\u003e`, so leaving them would let stored bytes display\n//     as something different).\n//   - NUL is replaced with U+FFFD.\n//   - The wrapping fence is one backtick longer than the longest\n//     backtick run in the content, so internal backticks can never\n//     close the span prematurely.\n//   - A single space pad is added on each side when content starts or\n//     ends with “ ` “ or space, so leading/trailing backticks render\n//     literally rather than fusing with the fence (the renderer\n//     strips one space from each side per CommonMark spec).\n//\n// Empty input returns \"\" rather than a literal two-backtick string\n// (which CommonMark parses as text, not as an empty code span). If\n// you use InlineCode as link text and it returns \"\", omit the link\n// entirely.\n//\n// Not idempotent (see package doc): wraps with a fence, so calling\n// twice double-wraps.\nfunc InlineCode(content string) string {\n\tcontent = markdown.StripBidiAndZeroWidth(content)\n\tcontent = markdown.NormalizeBreaks(content)\n\tcontent = foldNewlinesAndSeparators(content, ' ')\n\tcontent = replaceNULWithFFFD(content)\n\tif content == \"\" {\n\t\treturn \"\"\n\t}\n\tfence := markdown.CodeFence(content, 1)\n\tpad := \"\"\n\tif content[0] == '`' || content[0] == ' ' ||\n\t\tcontent[len(content)-1] == '`' || content[len(content)-1] == ' ' {\n\t\tpad = \" \"\n\t}\n\treturn fence + pad + content + pad + fence\n}\n\n// CodeBlock wraps user content as a CommonMark fenced code block.\n// Use for any user-derived multi-line snippet that should render as a\n// code block: log excerpts, JSON dumps, error backtraces, config\n// snippets, posted code samples.\n//\n// Behavior:\n//   - Bidi/zero-width controls are stripped.\n//   - CR/CRLF line endings are normalized to LF; Unicode separators\n//     (NEL U+0085, U+2028, U+2029) are folded to LF for line-count\n//     consistency.\n//   - NUL is replaced with U+FFFD per CM §2.3.\n//   - The wrapping fence is at least 3 backticks (CM §4.5 minimum) and\n//     sized to outscan internal backticks — an attacker cannot embed\n//     a closing fence in the content.\n//\n// Empty content emits an empty fenced block (\"```\\n\\n```\\n\"), which is\n// valid CommonMark and renders as an empty `\u003cpre\u003e\u003ccode\u003e\u003c/code\u003e\u003c/pre\u003e`.\n//\n// Not idempotent (see package doc).\nfunc CodeBlock(content string) string {\n\tcontent = markdown.StripBidiAndZeroWidth(content)\n\tcontent = markdown.NormalizeBreaks(content)\n\tcontent = foldNewlinesAndSeparators(content, '\\n')\n\tcontent = replaceNULWithFFFD(content)\n\tfence := markdown.CodeFence(content, 3)\n\treturn fence + \"\\n\" + content + \"\\n\" + fence + \"\\n\"\n}\n\n// LanguageCodeBlock wraps user content as a fenced code block tagged\n// with a programming-language hint (the \"info string\" after the\n// opening fence, e.g. `go` in ```` ```go ````) so the renderer can\n// apply syntax highlighting.\n//\n// An invalid `language` tag silently falls back to a tagless fence —\n// the helper never returns an error or panics. If a realm author is\n// debugging \"why is my Go highlighting gone?\", the input failed the\n// language validator (charset ^[a-zA-Z0-9_+-]{1,32}$ after bidi-strip).\n// This fallback exists because an unvalidated tag could contain a\n// newline that injects content (e.g. a heading) onto what becomes the\n// opening fence line.\n//\n// Content is cleaned exactly as in CodeBlock (bidi-strip, CR/CRLF\n// normalize to LF, NEL/U+2028/U+2029 fold to LF, NUL→U+FFFD, fence\n// sized to outscan internal backticks).\n//\n// Not idempotent (see package doc).\nfunc LanguageCodeBlock(language, content string) string {\n\tcontent = markdown.StripBidiAndZeroWidth(content)\n\tcontent = markdown.NormalizeBreaks(content)\n\tcontent = foldNewlinesAndSeparators(content, '\\n')\n\tcontent = replaceNULWithFFFD(content)\n\tfence := markdown.CodeFence(content, 3)\n\tlang := LanguageName(language) // \"\" on reject\n\treturn fence + lang + \"\\n\" + content + \"\\n\" + fence + \"\\n\"\n}\n\n// ----- Reference-style definitions -----\n\n// FootnoteDefinition emits a GFM footnote definition — the\n// `[^name]: body` form that introduces a footnote whose body is rendered\n// in the page footer (or wherever the renderer chooses to place it).\n// Other parts of the markdown reference the footnote by writing\n// `[^name]` inline.\n//\n// Use for any realm-rendered footnote where the body text comes from\n// user input. The realm picks the footnote name (passed as `name`,\n// validated by FootnoteLabel — failure here returns \"\"); the user's\n// content goes in `text`, which is sanitized via Block.\n//\n// Contract:\n//   - `name`: passed raw, validated as a FootnoteLabel\n//     (^[A-Za-z0-9_-]{1,64}$). Reject → return \"\".\n//   - `text`: passed raw multi-paragraph user prose, cleaned via Block\n//     (bidi-strip, line-ending normalize, LRD strip, block-marker\n//     escape, ref-link USE escape, fence auto-close).\n//\n// Empty body → returns \"\" (a label without body is not a valid\n// footnote definition; the markdown would parse as a paragraph\n// containing the label).\n//\n// Output shape:\n//\n//\t[^name]:\n//\t    line 1 of body\n//\t    line 2 of body\n//\t    ...\n//\n// The label sits on its own line and each body line gets a 4-space\n// indent — the GFM continuation rule that keeps multi-paragraph body\n// text bound to the footnote rather than detaching as a new paragraph.\n//\n// Not idempotent (see package doc): composes Block internally; passing\n// already-sanitized body text double-escapes.\nfunc FootnoteDefinition(name, text string) string {\n\tlabel := FootnoteLabel(name)\n\tif label == \"\" {\n\t\treturn \"\"\n\t}\n\t// Block now wraps with \"\\n\\n\" on both sides for cross-paragraph\n\t// isolation; inside a footnote-definition's 4-space-indented body\n\t// the wrap would line-prefix to blank padding lines, so strip ALL\n\t// leading and trailing \"\\n\"s before continuation-indenting.\n\tbody := strings.Trim(Block(text), \"\\n\")\n\tif body == \"\" {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"[^\")\n\tb.WriteString(label)\n\tb.WriteString(\"]:\\n\")\n\tfor _, line := range strings.Split(body, \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tb.WriteByte('\\n')\n\t\t} else {\n\t\t\tb.WriteString(\"    \")\n\t\t\tb.WriteString(line)\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// LinkReferenceDefinition emits a CommonMark link reference definition\n// (CM §4.7) — the `[label]: url \"title\"` form that other parts of the\n// markdown reference by writing `[text][label]` or `[label]` (shortcut).\n//\n// Use for any realm-rendered LRD where the realm owns the label but\n// any of the URL or title come from user input. The user content for\n// the URL goes through URL (allowlist-based — reject → \"\"); the title\n// goes through LinkTitle (escape).\n//\n// Contract:\n//   - `label`: passed raw, validated as a FootnoteLabel\n//     (^[A-Za-z0-9_-]{1,64}$). Realms should choose a namespaced label\n//     using dashes (e.g. `r-myrealm-help`) so shortcut-reference\n//     invocations from user content can't collide with bare prose\n//     (`[help]`, `[click here]`). `/` is not in the FootnoteLabel\n//     charset; reject → return \"\".\n//   - `url`: passed raw, sanitized via URL. If URL rejects, the LRD is\n//     skipped (return \"\").\n//   - `title`: passed raw, sanitized via LinkTitle. Empty title → no\n//     title clause emitted.\n//\n// The output is framed with leading and trailing blank lines so that\n// the definition cannot accidentally fuse with adjacent paragraph\n// content into a setext underline or a continuation line.\n//\n// Not idempotent (see package doc).\nfunc LinkReferenceDefinition(label, url, title string) string {\n\tlbl := FootnoteLabel(label)\n\tif lbl == \"\" {\n\t\treturn \"\"\n\t}\n\tsafeURL := URL(url)\n\tif safeURL == \"\" {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"\\n\\n[\")\n\tb.WriteString(lbl)\n\tb.WriteString(\"]: \")\n\tb.WriteString(safeURL)\n\tif title != \"\" {\n\t\tb.WriteString(\" \\\"\")\n\t\tb.WriteString(LinkTitle(title))\n\t\tb.WriteString(\"\\\"\")\n\t}\n\tb.WriteString(\"\\n\\n\")\n\treturn b.String()\n}\n\n// ----- internal helpers -----\n\n// linkSchemeAllowed returns true if s passes the URL helper's scheme\n// allowlist. See URL's doc for the policy.\nfunc linkSchemeAllowed(s string) bool {\n\tif strings.HasPrefix(s, \"http://\") || strings.HasPrefix(s, \"https://\") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"mailto:\") {\n\t\t// Reject any query: RFC 6068 headers (body, subject, cc, bcc, ...)\n\t\t// prefill the composed message and are a phishing vector. '?' opens\n\t\t// the header section (covering percent-encoded names like ?%62ody=).\n\t\t// '\u0026' is rejected because gnoweb's renderer decodes HTML character\n\t\t// references ('\u0026#63;', '\u0026#x3f;', '\u0026quest;') back into '?' after this\n\t\t// check, reconstituting a query. Percent-encoded '%3f' stays encoded\n\t\t// and reads as a literal '?' in the address, so it's allowed.\n\t\tif strings.ContainsAny(s, \"?\u0026\") {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"//\") {\n\t\t// Protocol-relative — reject (tracking-pixel vector).\n\t\treturn false\n\t}\n\t// Any URL with an unknown scheme (RFC 3986: `^[a-zA-Z][a-zA-Z0-9+.-]*:`)\n\t// is rejected — this blocks `javascript:`, `data:`, `vbscript:`, `blob:`,\n\t// and anything else not handled above. URLs without a scheme are\n\t// treated as relative and accepted (bare path, query-only, fragment).\n\tif hasURLScheme(s) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n// hasURLScheme reports whether s begins with a scheme followed by ':'\n// per RFC 3986 (^[a-zA-Z][a-zA-Z0-9+.-]*:). A `:` appearing later in\n// the URL (e.g. `/path:foo` or `?q=a:b`) does not count.\nfunc hasURLScheme(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tc := s[0]\n\tif !((c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z')) {\n\t\treturn false\n\t}\n\tfor i := 1; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == ':' {\n\t\t\treturn true\n\t\t}\n\t\tif !((c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') ||\n\t\t\t(c \u003e= '0' \u0026\u0026 c \u003c= '9') || c == '+' || c == '.' || c == '-') {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}\n\n// imageSchemeAllowed returns true if s passes the ImageURL helper's\n// scheme allowlist. Tighter than linkSchemeAllowed: no mailto/tel,\n// only data:image/\u003csubset\u003e.\nfunc imageSchemeAllowed(s string) bool {\n\tif strings.HasPrefix(s, \"http://\") || strings.HasPrefix(s, \"https://\") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"//\") {\n\t\treturn false\n\t}\n\tif strings.HasPrefix(s, \"/\") || strings.HasPrefix(s, \"./\") || strings.HasPrefix(s, \"../\") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"data:\") {\n\t\t// Only the curated image/* subset. CSS must enforce sizing.\n\t\tfor _, p := range []string{\n\t\t\t\"data:image/svg+xml\",\n\t\t\t\"data:image/png\",\n\t\t\t\"data:image/jpeg\",\n\t\t\t\"data:image/gif\",\n\t\t\t\"data:image/webp\",\n\t\t} {\n\t\t\tif strings.HasPrefix(s, p) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}\n\n// foldNewlinesAndSeparators replaces \\n, U+0085 NEL, U+2028 LINE SEPARATOR,\n// U+2029 PARAGRAPH SEPARATOR with the given replacement byte (typically\n// space for inline-context helpers).\n//\n// NormalizeBreaks has already folded \\r\\n and \\r to \\n before this runs,\n// so \\n is the canonical break byte to substitute.\nfunc foldNewlinesAndSeparators(s string, replacement byte) string {\n\tif !needsSeparatorFold(s) {\n\t\treturn s\n\t}\n\tout := make([]byte, 0, len(s))\n\tfor i := 0; i \u003c len(s); {\n\t\tc := s[i]\n\t\tif c == '\\n' {\n\t\t\tout = append(out, replacement)\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\t// U+0085 NEL: 0xC2 0x85\n\t\tif c == 0xC2 \u0026\u0026 i+1 \u003c len(s) \u0026\u0026 s[i+1] == 0x85 {\n\t\t\tout = append(out, replacement)\n\t\t\ti += 2\n\t\t\tcontinue\n\t\t}\n\t\t// U+2028 (0xE2 0x80 0xA8) or U+2029 (0xE2 0x80 0xA9)\n\t\tif c == 0xE2 \u0026\u0026 i+2 \u003c len(s) \u0026\u0026 s[i+1] == 0x80 \u0026\u0026 (s[i+2] == 0xA8 || s[i+2] == 0xA9) {\n\t\t\tout = append(out, replacement)\n\t\t\ti += 3\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, c)\n\t\ti++\n\t}\n\treturn string(out)\n}\n\nfunc needsSeparatorFold(s string) bool {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == '\\n' || c == 0xC2 || c == 0xE2 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// replaceNULWithFFFD substitutes any NUL byte with the UTF-8 encoding\n// of U+FFFD REPLACEMENT CHARACTER per CM §2.3.\nfunc replaceNULWithFFFD(s string) string {\n\tif !strings.ContainsRune(s, 0) {\n\t\treturn s\n\t}\n\treturn strings.ReplaceAll(s, \"\\x00\", \"\\ufffd\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"md","path":"gno.land/p/moul/md/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/md/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"md.gno","body":"// Package md provides helper functions for generating Markdown content programmatically.\n//\n// It includes utilities for text formatting, creating lists, blockquotes, code blocks,\n// links, images, and more.\n//\n// Highlights:\n// - Supports basic Markdown syntax such as bold, italic, strikethrough, headers, and lists.\n// - Manages multiline support in lists (e.g., bullet, ordered, and todo lists).\n// - Includes advanced helpers like inline images with links and nested list prefixes.\n//\n// For a comprehensive example of how to use these helpers, see:\n// https://gno.land/r/docs/moul_md\n//\n// # Sanitization contract\n//\n// Some helpers in this package sanitize their user-derived arguments\n// INTERNALLY (via p/nt/markdown/sanitize/v0). When using these, pass\n// raw user input — do NOT pre-wrap with sanitize.*, or you will\n// double-wrap (the escapers are not idempotent and double-wrap is a\n// bug):\n//\n//\tLink, UserLink, Image, InlineImageWithLink, FootnoteDefinition,\n//\tLinkReferenceDefinition, CollapsibleSection (title only),\n//\tInlineCode, CodeBlock, LanguageCodeBlock, Blockquote\n//\n// The other helpers DO NOT sanitize — they are pure builders that\n// wrap their input in markdown chrome. User-derived input reaches\n// the output unmodified, so callers MUST wrap with sanitize.* at the\n// call site:\n//\n//\tBold, Italic, Strikethrough, H1-H6, BulletList, BulletItem,\n//\tOrderedList, TodoList, TodoItem, Nested, Paragraph, Columns,\n//\tColumnsN, HorizontalRule\n//\n// Examples:\n//\n//\t// Sanitizing helper — pass raw:\n//\tout += md.Link(post.Title, post.URL)                                 // good\n//\tout += md.Link(sanitize.InlineText(post.Title), sanitize.URL(post.URL)) // BAD: double-wrap\n//\n//\t// Non-sanitizing helper — wrap once:\n//\tout += md.H2(sanitize.InlineText(post.Title))                        // good\n//\tout += md.H2(post.Title)                                             // BAD: raw user input\n//\tout += md.H2(sanitize.InlineText(sanitize.InlineText(post.Title)))   // BAD: double-wrap\n//\n// Composition: outputs of sanitizing helpers are safe markdown chrome\n// and can be embedded inside non-sanitizing helpers freely:\n//\n//\tout += md.H2(md.Link(post.Title, post.URL))   // good — H2 doesn't re-escape Link's output\n//\n// The reverse is unsafe: do NOT embed a non-sanitizing helper's\n// markdown chrome inside a sanitizing helper's arg, or the inner\n// markdown gets re-escaped:\n//\n//\tout += md.Link(md.Bold(post.Title), post.URL) // BAD: Link's internal sanitize\n//\t                                              // escapes the ** chars from md.Bold\npackage md\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Bold returns bold text for markdown.\n// Example: Bold(\"foo\") =\u003e \"**foo**\"\nfunc Bold(text string) string {\n\treturn \"**\" + text + \"**\"\n}\n\n// Italic returns italicized text for markdown.\n// Example: Italic(\"foo\") =\u003e \"*foo*\"\nfunc Italic(text string) string {\n\treturn \"*\" + text + \"*\"\n}\n\n// Strikethrough returns strikethrough text for markdown.\n// Example: Strikethrough(\"foo\") =\u003e \"~~foo~~\"\nfunc Strikethrough(text string) string {\n\treturn \"~~\" + text + \"~~\"\n}\n\n// H1 returns a level 1 header for markdown.\n// Example: H1(\"foo\") =\u003e \"# foo\\n\"\nfunc H1(text string) string {\n\treturn \"# \" + text + \"\\n\"\n}\n\n// H2 returns a level 2 header for markdown.\n// Example: H2(\"foo\") =\u003e \"## foo\\n\"\nfunc H2(text string) string {\n\treturn \"## \" + text + \"\\n\"\n}\n\n// H3 returns a level 3 header for markdown.\n// Example: H3(\"foo\") =\u003e \"### foo\\n\"\nfunc H3(text string) string {\n\treturn \"### \" + text + \"\\n\"\n}\n\n// H4 returns a level 4 header for markdown.\n// Example: H4(\"foo\") =\u003e \"#### foo\\n\"\nfunc H4(text string) string {\n\treturn \"#### \" + text + \"\\n\"\n}\n\n// H5 returns a level 5 header for markdown.\n// Example: H5(\"foo\") =\u003e \"##### foo\\n\"\nfunc H5(text string) string {\n\treturn \"##### \" + text + \"\\n\"\n}\n\n// H6 returns a level 6 header for markdown.\n// Example: H6(\"foo\") =\u003e \"###### foo\\n\"\nfunc H6(text string) string {\n\treturn \"###### \" + text + \"\\n\"\n}\n\n// BulletList returns a bullet list for markdown.\n// Example: BulletList([]string{\"foo\", \"bar\"}) =\u003e \"- foo\\n- bar\\n\"\nfunc BulletList(items []string) string {\n\tvar sb strings.Builder\n\tfor _, item := range items {\n\t\tsb.WriteString(BulletItem(item))\n\t}\n\treturn sb.String()\n}\n\n// BulletItem returns a bullet item for markdown.\n// Example: BulletItem(\"foo\") =\u003e \"- foo\\n\"\nfunc BulletItem(item string) string {\n\tvar sb strings.Builder\n\tlines := strings.Split(item, \"\\n\")\n\tsb.WriteString(\"- \" + lines[0] + \"\\n\")\n\tfor _, line := range lines[1:] {\n\t\tsb.WriteString(\"  \" + line + \"\\n\")\n\t}\n\treturn sb.String()\n}\n\n// OrderedList returns an ordered list for markdown.\n// Example: OrderedList([]string{\"foo\", \"bar\"}) =\u003e \"1. foo\\n2. bar\\n\"\nfunc OrderedList(items []string) string {\n\tvar sb strings.Builder\n\tfor i, item := range items {\n\t\tlines := strings.Split(item, \"\\n\")\n\t\tsb.WriteString(strconv.Itoa(i+1) + \". \" + lines[0] + \"\\n\")\n\t\tfor _, line := range lines[1:] {\n\t\t\tsb.WriteString(\"   \" + line + \"\\n\")\n\t\t}\n\t}\n\treturn sb.String()\n}\n\n// TodoList returns a list of todo items with checkboxes for markdown.\n// Example: TodoList([]string{\"foo\", \"bar\\nmore bar\"}, []bool{true, false}) =\u003e \"- [x] foo\\n- [ ] bar\\n  more bar\\n\"\nfunc TodoList(items []string, done []bool) string {\n\tvar sb strings.Builder\n\tfor i, item := range items {\n\t\tsb.WriteString(TodoItem(item, done[i]))\n\t}\n\treturn sb.String()\n}\n\n// TodoItem returns a todo item with checkbox for markdown.\n// Example: TodoItem(\"foo\", true) =\u003e \"- [x] foo\\n\"\nfunc TodoItem(item string, done bool) string {\n\tvar sb strings.Builder\n\tcheckbox := \" \"\n\tif done {\n\t\tcheckbox = \"x\"\n\t}\n\tlines := strings.Split(item, \"\\n\")\n\tsb.WriteString(\"- [\" + checkbox + \"] \" + lines[0] + \"\\n\")\n\tfor _, line := range lines[1:] {\n\t\tsb.WriteString(\"  \" + line + \"\\n\")\n\t}\n\treturn sb.String()\n}\n\n// Nested prefixes each line with a given prefix, enabling nested lists.\n// Example: Nested(\"- foo\\n- bar\", \"  \") =\u003e \"  - foo\\n  - bar\\n\"\nfunc Nested(content, prefix string) string {\n\tlines := strings.Split(content, \"\\n\")\n\tfor i := range lines {\n\t\tif strings.TrimSpace(lines[i]) != \"\" {\n\t\t\tlines[i] = prefix + lines[i]\n\t\t}\n\t}\n\treturn strings.Join(lines, \"\\n\")\n}\n\n// Blockquote returns the text as a CommonMark blockquote.\n// Example: Blockquote(\"foo\\nbar\") =\u003e \"\\n\u003e foo\\n\u003e bar\\n\\n\"\n//\n// Delegates to sanitize.Blockquote, which cleans the content (bidi-strip,\n// CR/CRLF/U+2028/U+2029/NEL line-ending normalize, LRD strip, ref-link\n// escape, block-marker escape, fence auto-close), line-prefixes each\n// line with \"\u003e \", and wraps with \"\\n\" / \"\\n\\n\" so the quote opens\n// cleanly and cannot pull appended chrome into the quote via CM §5.2\n// lazy continuation. Callers do NOT need to pre-wrap the input.\nfunc Blockquote(text string) string {\n\treturn sanitize.Blockquote(text)\n}\n\n// InlineCode wraps the given text as a CommonMark inline code span.\n// Example: InlineCode(\"foo\") =\u003e \"`foo`\"\n//\n// Delegates to sanitize.InlineCode, which cleans the input (bidi-strip,\n// CR/CRLF + NEL + U+2028/U+2029 folded to single space, NUL→U+FFFD)\n// and picks a backtick-run length that outscans any internal backticks.\n// Callers do NOT need to pre-wrap the input.\nfunc InlineCode(code string) string {\n\treturn sanitize.InlineCode(code)\n}\n\n// CodeBlock creates a markdown code block.\n// Example: CodeBlock(\"foo\") =\u003e \"```\\nfoo\\n```\"\n//\n// Delegates to sanitize.CodeBlock, which cleans the content (bidi-strip,\n// CR/CRLF normalize, NEL/U+2028/U+2029 fold, NUL→U+FFFD) and picks a\n// fence wide enough to outscan any backticks in content. Callers do NOT\n// need to pre-wrap content with another sanitize helper.\nfunc CodeBlock(content string) string {\n\treturn sanitize.CodeBlock(content)\n}\n\n// LanguageCodeBlock creates a markdown code block with language-specific syntax highlighting.\n// Example: LanguageCodeBlock(\"go\", \"foo\") =\u003e \"```go\\nfoo\\n```\"\n//\n// Delegates to sanitize.LanguageCodeBlock, which validates the language\n// tag (charset ^[a-zA-Z0-9_+-]{1,32}$, falling back to a tagless fence\n// if invalid) and cleans the content as CodeBlock does. Callers do NOT\n// need to pre-wrap either argument.\nfunc LanguageCodeBlock(language, content string) string {\n\treturn sanitize.LanguageCodeBlock(language, content)\n}\n\n// HorizontalRule returns a horizontal rule for markdown.\n// Example: HorizontalRule() =\u003e \"---\\n\"\nfunc HorizontalRule() string {\n\treturn \"---\\n\"\n}\n\n// Link returns a hyperlink for markdown.\n// Example: Link(\"foo\", \"http://example.com\") =\u003e \"[foo](http://example.com)\"\n//\n// The text and url args are sanitized internally — text via\n// sanitize.InlineText, url via sanitize.URL (allowlists http/https/\n// mailto/relative/fragment; rejects javascript:, data:, blob:, etc.).\n// Callers do NOT need to pre-wrap either argument; double-wrapping is\n// a bug (the inline-text escaper is non-idempotent).\n//\n// If the URL fails the scheme allowlist, the href is rendered empty —\n// the link becomes inert rather than carrying a malicious destination.\nfunc Link(text, url string) string {\n\treturn \"[\" + sanitize.InlineText(text) + \"](\" + sanitize.URL(url) + \")\"\n}\n\n// UserLink returns a user profile link for markdown.\n// Example: UserLink(\"moul\") =\u003e \"[@moul](/u/moul)\"\n// Example: UserLink(\"g1blah...\") =\u003e \"[g1blah...](/u/g1blah...)\"\n//\n// Validates the user identifier — if it matches the gno bech32 address\n// pattern (g1...), produces an address-style link; otherwise tries the\n// r/sys/users-charset username and produces an @-style link. Returns\n// \"\" if the identifier matches neither — callers should treat \"\" as\n// \"skip the user mention\" rather than emit a broken link.\nfunc UserLink(user string) string {\n\tif addr := sanitize.BechString(user, \"g\"); addr != \"\" {\n\t\treturn \"[\" + addr + \"](/u/\" + addr + \")\"\n\t}\n\tif name := sanitize.UserName(user); name != \"\" {\n\t\treturn \"[@\" + name + \"](/u/\" + name + \")\"\n\t}\n\treturn \"\"\n}\n\n// InlineImageWithLink creates an inline image wrapped in a hyperlink for markdown.\n// Example: InlineImageWithLink(\"alt text\", \"image-url\", \"link-url\") =\u003e \"[![alt text](image-url)](link-url)\"\n//\n// altText and imageUrl are sanitized via Image (sanitize.InlineText +\n// sanitize.ImageURL); linkUrl is sanitized via sanitize.URL. Callers\n// do NOT need to pre-wrap any argument.\nfunc InlineImageWithLink(altText, imageUrl, linkUrl string) string {\n\treturn \"[\" + Image(altText, imageUrl) + \"](\" + sanitize.URL(linkUrl) + \")\"\n}\n\n// Image returns an image for markdown.\n// Example: Image(\"foo\", \"http://example.com\") =\u003e \"![foo](http://example.com)\"\n//\n// altText is sanitized via sanitize.InlineText, url via\n// sanitize.ImageURL (allowlists http/https/relative + data:image/*;\n// rejects mailto:, javascript:, data:text/html, etc.). Callers do NOT\n// need to pre-wrap either argument.\nfunc Image(altText, url string) string {\n\treturn \"![\" + sanitize.InlineText(altText) + \"](\" + sanitize.ImageURL(url) + \")\"\n}\n\n// FootnoteDefinition emits a GFM footnote definition — `[^name]: body` —\n// for a footnote that is referenced elsewhere in the document by\n// `[^name]`.\n//\n// Example: FootnoteDefinition(\"note1\", \"Long form of the citation.\")\n// renders as:\n//\n//\t[^note1]:\n//\t    Long form of the citation.\n//\n// The `name` is validated as a FootnoteLabel (^[A-Za-z0-9_-]{1,64}$);\n// `text` is user-supplied multi-paragraph prose, sanitized via Block.\n// An invalid name or empty body returns \"\".\n//\n// Delegates to sanitize.FootnoteDefinition. Callers do NOT need to\n// pre-wrap either argument.\nfunc FootnoteDefinition(name, text string) string {\n\treturn sanitize.FootnoteDefinition(name, text)\n}\n\n// LinkReferenceDefinition emits a CommonMark link reference definition\n// (CM §4.7) — `[label]: url \"title\"` — for a reference link that is\n// invoked elsewhere by `[text][label]` or by the shortcut form\n// `[label]`.\n//\n// Example: LinkReferenceDefinition(\"r/docs/help\", \"/r/docs/help\", \"\")\n// renders as:\n//\n//\t[r/docs/help]: /r/docs/help\n//\n// The `label` is validated as a FootnoteLabel (^[A-Za-z0-9_-]{1,64}$);\n// `url` is sanitized via URL (allowlist); `title` is sanitized via\n// LinkTitle. An invalid label or rejected URL returns \"\".\n//\n// Realms should choose a namespaced label using dashes\n// (e.g. `r-myrealm-help`) so that shortcut-reference invocations from\n// user content can't collide with bare words a user is likely to write.\n// `/` is not in the FootnoteLabel charset.\n//\n// Delegates to sanitize.LinkReferenceDefinition. Callers do NOT need to\n// pre-wrap any argument.\nfunc LinkReferenceDefinition(label, url, title string) string {\n\treturn sanitize.LinkReferenceDefinition(label, url, title)\n}\n\n// Paragraph wraps the given text in a Markdown paragraph.\n// Example: Paragraph(\"foo\") =\u003e \"foo\\n\"\nfunc Paragraph(content string) string {\n\treturn content + \"\\n\\n\"\n}\n\n// CollapsibleSection creates a collapsible section for markdown using\n// HTML \u003cdetails\u003e and \u003csummary\u003e tags.\n// Example:\n// CollapsibleSection(\"Click to expand\", \"Hidden content\")\n// =\u003e\n// \u003cdetails\u003e\u003csummary\u003eClick to expand\u003c/summary\u003e\n//\n// Hidden content\n// \u003c/details\u003e\n//\n// The title argument is sanitized via sanitize.HTMLEscape (it lands in\n// an HTML element body inside \u003csummary\u003e, not a markdown context — so\n// HTML entity escaping is the correct policy, not markdown backslash\n// escaping). The content argument is passed through unchanged because\n// \u003cdetails\u003e with a blank-line-separated body allows markdown inside\n// (CM §4.6); callers must pre-wrap content with sanitize.Block if it\n// derives from user input.\nfunc CollapsibleSection(title, content string) string {\n\treturn \"\u003cdetails\u003e\u003csummary\u003e\" + sanitize.HTMLEscape(title) + \"\u003c/summary\u003e\\n\\n\" + content + \"\\n\u003c/details\u003e\\n\"\n}\n\n// EscapeURL escapes characters in a URL for use in markdown link syntax.\n//\n// Deprecated: use sanitize.URL (for link href) or sanitize.ImageURL\n// (for image src) directly. EscapeURL previously only percent-encoded\n// ( and ) and did not validate the URL scheme — a security footgun\n// (EscapeURL(\"javascript:alert(1)\") returned a working XSS payload).\n// It now delegates to sanitize.URL, which allowlists schemes (rejects\n// javascript:, data:text/html, vbscript:, blob:, etc.) and\n// percent-encodes all unsafe bytes (including the ( ) this function\n// handled). The other helpers in this package (Link, UserLink, Image,\n// InlineImageWithLink) sanitize their URL args internally now, so you\n// rarely need to call any URL-escape helper directly.\n//\n// Behavior change vs. the original implementation: invalid schemes\n// now return \"\" instead of passing through with ( ) escaped. Non-ASCII\n// bytes get percent-encoded to standard RFC 3986 wire form instead of\n// passing through as raw UTF-8.\nfunc EscapeURL(url string) string {\n\treturn sanitize.URL(url)\n}\n\n// EscapeText escapes special Markdown characters in regular text for\n// use in inline contexts.\n//\n// Deprecated: use sanitize.InlineText directly. EscapeText was\n// INCOMPLETE — it missed \\, #, \u003c, \u0026 and did not strip bidi/zero-width\n// characters, replace NUL with U+FFFD, or normalize line endings.\n// User input could inject backslash escapes (\\* cancels neighboring\n// escapes), autolinks (\u003chttps://x\u003e), raw HTML (\u003cscript\u003e), HTML entity\n// references (\u0026amp;), and bidi spoofing (RLO before an address). It\n// now delegates to sanitize.InlineText. The other helpers in this\n// package (Link, UserLink, Image, InlineImageWithLink, CollapsibleSection)\n// sanitize their text args internally now, so you rarely need to call\n// any inline-text-escape helper directly.\n//\n// Behavior change vs. the original implementation: \\, #, \u003c, \u0026 are now\n// escaped; | is no longer escaped (the original was over-escaping —\n// outside GFM table-cell context, | is markdown-inert; for table\n// cells use sanitize.TableCell which adds the | escape on top of the\n// inline-text set). Bidi controls are stripped, NUL becomes U+FFFD,\n// and line endings normalize.\nfunc EscapeText(text string) string {\n\treturn sanitize.InlineText(text)\n}\n\n// Columns returns a formatted row of columns using the Gno syntax.\n// If you want a specific number of columns per row (\u003c=4), use ColumnsN.\n// Check /r/docs/markdown#columns for more info.\n// If padded=true \u0026 the final \u003cgno-columns\u003e tag is missing column content, an empty\n// column element will be placed to keep the cols per row constant.\n// Padding works only with colsPerRow \u003e 0.\n//\n// Example:\n//\n//\tColumns([]string{\"A\", \"B\"}, false)\n//\t// Returns:\n//\t// \u003cgno-columns\u003e\n//\t// A\n//\t// \u003cgno-columns-sep\u003e\n//\t// B\n//\t// \u003c/gno-columns\u003e\nfunc Columns(contentByColumn []string, padded bool) string {\n\tif len(contentByColumn) == 0 {\n\t\treturn \"\"\n\t}\n\tmaxCols := 4\n\tif padded \u0026\u0026 len(contentByColumn)%maxCols != 0 {\n\t\tmissing := maxCols - len(contentByColumn)%maxCols\n\t\tcontentByColumn = append(contentByColumn, make([]string, missing)...)\n\t}\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"\u003cgno-columns\u003e\\n\")\n\n\tfor i, column := range contentByColumn {\n\t\tif i \u003e 0 {\n\t\t\tsb.WriteString(\"\u003cgno-columns-sep\u003e\\n\")\n\t\t}\n\t\tsb.WriteString(column + \"\\n\")\n\t}\n\n\tsb.WriteString(\"\u003c/gno-columns\u003e\\n\")\n\treturn sb.String()\n}\n\nconst maxColumnsPerRow = 4\n\n// ColumnsN splits content into multiple rows of N columns each and formats them.\n// If colsPerRow \u003c= 0, all items are placed in one \u003cgno-columns\u003e block.\n// If padded=true \u0026 the final \u003cgno-columns\u003e tag is missing column content, an empty\n// column element will be placed to keep the cols per row constant.\n// Padding works only with colsPerRow \u003e 0.\n// Note: On standard-size screens, gnoweb handles a max of 4 cols per row.\n//\n// Example:\n//\n//\tColumnsN([]string{\"A\", \"B\", \"C\"}, 2, false)\n//\t// Returns:\n//\t// \u003cgno-columns\u003e\n//\t// A\n//\t// \u003cgno-columns-sep\u003e\n//\t// B\n//\t// \u003c/gno-columns\u003e\n//\t// \u003cgno-columns\u003e\n//\t// C\n//\t// \u003c/gno-columns\u003e\nfunc ColumnsN(content []string, colsPerRow int, padded bool) string {\n\tif len(content) == 0 {\n\t\treturn \"\"\n\t}\n\tif colsPerRow \u003c= 0 {\n\t\treturn Columns(content, padded)\n\t}\n\n\tvar sb strings.Builder\n\t// Case 2: Multiple blocks with max 4 columns\n\tfor i := 0; i \u003c len(content); i += colsPerRow {\n\t\tend := i + colsPerRow\n\t\tif end \u003e len(content) {\n\t\t\tend = len(content)\n\t\t}\n\t\trow := content[i:end]\n\n\t\t// Add padding if needed\n\t\tif padded \u0026\u0026 len(row) \u003c colsPerRow {\n\t\t\trow = append(row, make([]string, colsPerRow-len(row))...)\n\t\t}\n\n\t\tsb.WriteString(Columns(row, false))\n\t}\n\treturn sb.String()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"pager","path":"gno.land/p/nt/bptree/pager/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bptree/pager/v0\"\ngno = \"0.9\"\n"},{"name":"pager.gno","body":"package pager\n\nimport (\n\t\"math\"\n\t\"net/url\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/bptree/rotree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Pager is a struct that holds the B+ tree and pagination parameters.\ntype Pager struct {\n\tTree            rotree.IReadOnlyTree\n\tPageQueryParam  string\n\tSizeQueryParam  string\n\tDefaultPageSize int\n\tReversed        bool\n}\n\n// Page represents a single page of results.\ntype Page struct {\n\tItems      []Item\n\tPageNumber int\n\tPageSize   int\n\tTotalItems int\n\tTotalPages int\n\tHasPrev    bool\n\tHasNext    bool\n\tPager      *Pager // Reference to the parent Pager\n}\n\n// Item represents a key-value pair in the B+ tree.\ntype Item struct {\n\tKey   string\n\tValue any\n}\n\n// NewPager creates a new Pager with default values.\nfunc NewPager(tree rotree.IReadOnlyTree, defaultPageSize int, reversed bool) *Pager {\n\treturn \u0026Pager{\n\t\tTree:            tree,\n\t\tPageQueryParam:  \"page\",\n\t\tSizeQueryParam:  \"size\",\n\t\tDefaultPageSize: defaultPageSize,\n\t\tReversed:        reversed,\n\t}\n}\n\n// GetPage retrieves a page of results from the B+ tree.\nfunc (p *Pager) GetPage(pageNumber int) *Page {\n\treturn p.GetPageWithSize(pageNumber, p.DefaultPageSize)\n}\n\nfunc (p *Pager) GetPageWithSize(pageNumber, pageSize int) *Page {\n\ttotalItems := p.Tree.Size()\n\ttotalPages := int(math.Ceil(float64(totalItems) / float64(pageSize)))\n\n\tpage := \u0026Page{\n\t\tTotalItems: totalItems,\n\t\tTotalPages: totalPages,\n\t\tPageSize:   pageSize,\n\t\tPager:      p,\n\t}\n\n\t// pages without content\n\tif pageSize \u003c 1 {\n\t\treturn page\n\t}\n\n\t// page number provided is not available\n\tif pageNumber \u003c 1 {\n\t\tpage.HasNext = totalPages \u003e 0\n\t\treturn page\n\t}\n\n\t// page number provided is outside the range of total pages\n\tif pageNumber \u003e totalPages {\n\t\tpage.PageNumber = pageNumber\n\t\tpage.HasPrev = pageNumber \u003e 0\n\t\treturn page\n\t}\n\n\tstartIndex := (pageNumber - 1) * pageSize\n\tendIndex := startIndex + pageSize\n\tif endIndex \u003e totalItems {\n\t\tendIndex = totalItems\n\t}\n\n\titems := []Item{}\n\n\tif p.Reversed {\n\t\tp.Tree.ReverseIterateByOffset(startIndex, endIndex-startIndex, func(key string, value any) bool {\n\t\t\titems = append(items, Item{Key: key, Value: value})\n\t\t\treturn false\n\t\t})\n\t} else {\n\t\tp.Tree.IterateByOffset(startIndex, endIndex-startIndex, func(key string, value any) bool {\n\t\t\titems = append(items, Item{Key: key, Value: value})\n\t\t\treturn false\n\t\t})\n\t}\n\n\tpage.Items = items\n\tpage.PageNumber = pageNumber\n\tpage.HasPrev = pageNumber \u003e 1\n\tpage.HasNext = pageNumber \u003c totalPages\n\treturn page\n}\n\nfunc (p *Pager) MustGetPageByPath(rawURL string) *Page {\n\tpage, err := p.GetPageByPath(rawURL)\n\tif err != nil {\n\t\tpanic(\"invalid path\")\n\t}\n\treturn page\n}\n\n// GetPageByPath retrieves a page of results based on the query parameters in the URL path.\nfunc (p *Pager) GetPageByPath(rawURL string) (*Page, error) {\n\tpageNumber, pageSize, err := p.ParseQuery(rawURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.GetPageWithSize(pageNumber, pageSize), nil\n}\n\n// Picker generates the Markdown UI for the page Picker\nfunc (p *Page) Picker(path string) string {\n\tpageNumber := p.PageNumber\n\tpageNumber = max(pageNumber, 1)\n\n\tif p.TotalPages \u003c= 1 {\n\t\treturn \"\"\n\t}\n\n\tu, _ := url.Parse(path)\n\tquery := u.Query()\n\n\t// Remove existing page query parameter\n\tquery.Del(p.Pager.PageQueryParam)\n\n\t// Encode remaining query parameters\n\tbaseQuery := query.Encode()\n\tif baseQuery != \"\" {\n\t\tbaseQuery = \"\u0026\" + baseQuery\n\t}\n\tmd := \"\"\n\n\tif p.HasPrev {\n\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", 1, p.Pager.PageQueryParam, 1, baseQuery)\n\n\t\tif p.PageNumber \u003e 4 {\n\t\t\tmd += \"… | \"\n\t\t}\n\n\t\tif p.PageNumber \u003e 3 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber-2, p.Pager.PageQueryParam, p.PageNumber-2, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003e 2 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber-1, p.Pager.PageQueryParam, p.PageNumber-1, baseQuery)\n\t\t}\n\t}\n\n\tif p.PageNumber \u003e 0 \u0026\u0026 p.PageNumber \u003c= p.TotalPages {\n\t\tmd += ufmt.Sprintf(\"**%d**\", p.PageNumber)\n\t} else {\n\t\tmd += ufmt.Sprintf(\"_%d_\", p.PageNumber)\n\t}\n\n\tif p.HasNext {\n\t\tif p.PageNumber \u003c p.TotalPages-1 {\n\t\t\tmd += ufmt.Sprintf(\" | [%d](?%s=%d%s)\", p.PageNumber+1, p.Pager.PageQueryParam, p.PageNumber+1, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003c p.TotalPages-2 {\n\t\t\tmd += ufmt.Sprintf(\" | [%d](?%s=%d%s)\", p.PageNumber+2, p.Pager.PageQueryParam, p.PageNumber+2, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003c p.TotalPages-3 {\n\t\t\tmd += \" | …\"\n\t\t}\n\n\t\tmd += ufmt.Sprintf(\" | [%d](?%s=%d%s)\", p.TotalPages, p.Pager.PageQueryParam, p.TotalPages, baseQuery)\n\t}\n\n\treturn md\n}\n\n// ParseQuery parses the URL to extract the page number and page size.\nfunc (p *Pager) ParseQuery(rawURL string) (int, int, error) {\n\tu, err := url.Parse(rawURL)\n\tif err != nil {\n\t\treturn 1, p.DefaultPageSize, err\n\t}\n\n\tquery := u.Query()\n\tpageNumber := 1\n\tpageSize := p.DefaultPageSize\n\n\tif p.PageQueryParam != \"\" {\n\t\tif pageStr := query.Get(p.PageQueryParam); pageStr != \"\" {\n\t\t\tpageNumber, err = strconv.Atoi(pageStr)\n\t\t\tif err != nil || pageNumber \u003c 1 {\n\t\t\t\tpageNumber = 1\n\t\t\t}\n\t\t}\n\t}\n\n\tif p.SizeQueryParam != \"\" {\n\t\tif sizeStr := query.Get(p.SizeQueryParam); sizeStr != \"\" {\n\t\t\tpageSize, err = strconv.Atoi(sizeStr)\n\t\t\tif err != nil || pageSize \u003c 1 {\n\t\t\t\tpageSize = p.DefaultPageSize\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pageNumber, pageSize, nil\n}\n\nfunc max(a, b int) int {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"mux","path":"gno.land/p/nt/mux/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `mux` - Path router for Render\n\nSimple routing and rendering library for `Render(path)` requests in Gno realms. Similar in spirit to `http.ServeMux`, with support for path variables (`{name}`), wildcards (`*`), and query strings.\n\n## Usage\n\n```go\npackage myrealm\n\nimport \"gno.land/p/nt/mux/v0\"\n\nvar router *mux.Router\n\nfunc init() {\n    router = mux.NewRouter()\n\n    // Static route.\n    router.HandleFunc(\"\", func(res *mux.ResponseWriter, req *mux.Request) {\n        res.Write(\"# Home\\n\")\n    })\n\n    // Named parameter.\n    router.HandleFunc(\"hello/{name}\", func(res *mux.ResponseWriter, req *mux.Request) {\n        name := req.GetVar(\"name\")\n        res.Write(\"Hello, \" + name + \"!\")\n    })\n\n    // Query string.\n    router.HandleFunc(\"search\", func(res *mux.ResponseWriter, req *mux.Request) {\n        q := req.Query.Get(\"q\")\n        res.Write(\"Searching for: \" + q)\n    })\n\n    // Wildcard - matches the rest of the path.\n    router.HandleFunc(\"files/*\", func(res *mux.ResponseWriter, req *mux.Request) {\n        res.Write(\"File path: \" + req.GetVar(\"*\"))\n    })\n}\n\n// Realm entry point.\nfunc Render(path string) string {\n    return router.Render(path)\n}\n```\n\n## API\n\n```go\ntype Router struct {\n    NotFoundHandler NotFoundHandler\n    // unexported\n}\n\nfunc NewRouter() *Router\n\nfunc (r *Router) HandleFunc(pattern string, fn HandlerFunc)\nfunc (r *Router) HandleFuncRlm(pattern string, fn HandlerFuncRlm) // rlm-aware handler\nfunc (r *Router) HandleErrFunc(pattern string, fn ErrHandlerFunc)\nfunc (r *Router) SetNotFoundHandler(handler NotFoundHandler)\nfunc (r *Router) Render(reqPath string) string\nfunc (r *Router) RenderRlm(_ int, rlm realm, reqPath string) string // dispatches rlm-aware routes\n\ntype Request struct {\n    Path        string     // path without query string\n    RawPath     string     // path including \"?...\" query string\n    HandlerPath string     // pattern that matched this request\n    Query       url.Values // parsed query parameters\n}\n\nfunc (r *Request) GetVar(key string) string\n\ntype ResponseWriter struct{ /* unexported */ }\n\nfunc (rw *ResponseWriter) Write(data string)\nfunc (rw *ResponseWriter) Output() string\n\ntype Handler struct {\n    Pattern string\n    Fn      HandlerFunc    // set by HandleFunc\n    FnRlm   HandlerFuncRlm // set by HandleFuncRlm\n}\n\ntype HandlerFunc     func(*ResponseWriter, *Request)\ntype HandlerFuncRlm  func(_ int, rlm realm, res *ResponseWriter, req *Request)\ntype ErrHandlerFunc  func(*ResponseWriter, *Request) error\ntype NotFoundHandler func(*ResponseWriter, *Request)\n```\n\n## Route patterns\n\n- `users` - static, matches exactly `users`.\n- `users/{id}` - named parameter, extracted with `req.GetVar(\"id\")`.\n- `files/*` - wildcard, captures all remaining segments. Extract with `req.GetVar(\"*\")`.\n\nRoutes are matched in registration order; the first match wins. If no route matches, `NotFoundHandler` runs (default writes `\"404\"`).\n\n## Notes\n\n- `HandleErrFunc` wraps an error-returning handler: a non-nil error is written as `\"Error: \" + err.Error()` to the response.\n- Query strings are parsed off `reqPath` (`?foo=bar`); access via `req.Query` (a `net/url.Values`).\n- `req.RawPath` keeps the original path including the query string; `req.Path` strips it.\n- `req.GetVar(...)` and `req.Query.Get(...)` return attacker-controlled path/query input. Wrap it with `sanitize.InlineText` from [`gno.land/p/nt/markdown/sanitize/v0`](../../markdown/sanitize/v0) before writing it into the response, or user input can inject Markdown structure.\n- Register realm-aware handlers with `HandleFuncRlm` and dispatch them with `RenderRlm(0, cur, path)`. The plain `Render` path only invokes non-rlm `Fn` handlers.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package mux provides a simple routing and rendering library for handling dynamic path-based requests in Gno contracts.\n//\n// The `mux` package aims to offer similar functionality to `http.ServeMux` in Go, but for Gno's Render() requests.\n// It allows you to define routes with dynamic parts and associate them with corresponding handler functions for rendering outputs.\n//\n// Usage:\n// 1. Create a new Router instance using `NewRouter()` to handle routing and rendering logic.\n// 2. Register routes and their associated handler functions using the `Handle(route, handler)` method.\n// 3. Implement the rendering logic within the handler functions, utilizing the `Request` and `ResponseWriter` types.\n// 4. Use the `Render(path)` method to process a given path and execute the corresponding handler function to obtain the rendered output.\n//\n// Route Patterns:\n// Routes can include dynamic parts enclosed in braces, such as \"users/{id}\" or \"hello/{name}\". The `Request` object's `GetVar(key)`\n// method allows you to extract the value of a specific variable from the path based on routing rules.\n//\n// Example:\n//\n//\trouter := mux.NewRouter()\n//\n//\t// Define a route with a variable and associated handler function\n//\trouter.HandleFunc(\"hello/{name}\", func(res *mux.ResponseWriter, req *mux.Request) {\n//\t\tname := req.GetVar(\"name\")\n//\t\tif name != \"\" {\n//\t\t\tres.Write(\"Hello, \" + name + \"!\")\n//\t\t} else {\n//\t\t\tres.Write(\"Hello, world!\")\n//\t\t}\n//\t})\n//\n//\t// Render the output for the \"/hello/Alice\" path\n//\toutput := router.Render(\"hello/Alice\")\n//\t// Output: \"Hello, Alice!\"\n//\n// Note: The `mux` package provides a basic routing and rendering mechanism for simple use cases. For more advanced routing features,\n// consider using more specialized libraries or frameworks.\npackage mux\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/mux/v0\"\ngno = \"0.9\"\n"},{"name":"handler.gno","body":"package mux\n\n// Handler stores a route pattern with one of two handler shapes.\n// Fn (HandlerFunc, no rlm) is set by HandleFunc; FnRlm (HandlerFuncRlm,\n// rlm-aware non-crossing) is set by HandleFuncRlm. Exactly one is set\n// per route. RenderRlm dispatches FnRlm with the supplied rlm; Render\n// dispatches Fn and panics if the matched route was registered with\n// HandleFuncRlm (caller used the wrong dispatch method).\ntype Handler struct {\n\tPattern string\n\tFn      HandlerFunc\n\tFnRlm   HandlerFuncRlm\n}\n\ntype HandlerFunc func(*ResponseWriter, *Request)\n\n// HandlerFuncRlm is the rlm-aware handler shape — non-crossing\n// (`_ int, rlm realm` first params) so callers thread cur as data\n// for the handler to forward to downstream crossing functions.\ntype HandlerFuncRlm func(_ int, rlm realm, res *ResponseWriter, req *Request)\n\ntype ErrHandlerFunc func(*ResponseWriter, *Request) error\n\ntype NotFoundHandler func(*ResponseWriter, *Request)\n\n// TODO: AutomaticIndex\n"},{"name":"helpers.gno","body":"package mux\n\nfunc defaultNotFoundHandler(res *ResponseWriter, req *Request) {\n\tres.Write(\"404\")\n}\n"},{"name":"request.gno","body":"package mux\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n)\n\n// Request represents an incoming request.\ntype Request struct {\n\t// Path is request path name.\n\t//\n\t// Note: use RawPath to obtain a raw path with query string.\n\tPath string\n\n\t// RawPath contains a whole request path, including query string.\n\tRawPath string\n\n\t// HandlerPath is handler rule that matches a request.\n\tHandlerPath string\n\n\t// Query contains the parsed URL query parameters.\n\tQuery url.Values\n}\n\n// GetVar retrieves a variable from the path based on routing rules.\nfunc (r *Request) GetVar(key string) string {\n\thandlerParts := strings.Split(r.HandlerPath, \"/\")\n\treqParts := strings.Split(r.Path, \"/\")\n\treqIndex := 0\n\tfor handlerIndex := 0; handlerIndex \u003c len(handlerParts); handlerIndex++ {\n\t\thandlerPart := handlerParts[handlerIndex]\n\t\tswitch {\n\t\tcase handlerPart == \"*\":\n\t\t\t// If a wildcard \"*\" is found, consume all remaining segments\n\t\t\twildcardParts := reqParts[reqIndex:]\n\t\t\treqIndex = len(reqParts)                // Consume all remaining segments\n\t\t\treturn strings.Join(wildcardParts, \"/\") // Return all remaining segments as a string\n\t\tcase strings.HasPrefix(handlerPart, \"{\") \u0026\u0026 strings.HasSuffix(handlerPart, \"}\"):\n\t\t\t// If a variable of the form {param} is found we compare it with the key\n\t\t\tparameter := handlerPart[1 : len(handlerPart)-1]\n\t\t\tif parameter == key {\n\t\t\t\treturn reqParts[reqIndex]\n\t\t\t}\n\t\t\treqIndex++\n\t\tdefault:\n\t\t\tif reqIndex \u003e= len(reqParts) || handlerPart != reqParts[reqIndex] {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treqIndex++\n\t\t}\n\t}\n\n\treturn \"\"\n}\n"},{"name":"response.gno","body":"package mux\n\nimport \"strings\"\n\n// ResponseWriter represents the response writer.\ntype ResponseWriter struct {\n\toutput strings.Builder\n}\n\n// Write appends data to the response output.\nfunc (rw *ResponseWriter) Write(data string) {\n\trw.output.WriteString(data)\n}\n\n// Output returns the final response output.\nfunc (rw *ResponseWriter) Output() string {\n\treturn rw.output.String()\n}\n\n// TODO: func (rw *ResponseWriter) Header()...\n"},{"name":"router.gno","body":"package mux\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n)\n\n// Router handles the routing and rendering logic.\ntype Router struct {\n\troutes          []Handler\n\tNotFoundHandler NotFoundHandler\n}\n\n// NewRouter creates a new Router instance.\nfunc NewRouter() *Router {\n\treturn \u0026Router{\n\t\troutes:          make([]Handler, 0),\n\t\tNotFoundHandler: defaultNotFoundHandler,\n\t}\n}\n\n// Render renders the output for the given path using the registered route handler.\nfunc (r *Router) Render(reqPath string) string {\n\tclearPath, rawQuery, _ := strings.Cut(reqPath, \"?\")\n\tquery, _ := url.ParseQuery(rawQuery)\n\treqParts := strings.Split(clearPath, \"/\")\n\n\tfor _, route := range r.routes {\n\t\tpatParts := strings.Split(route.Pattern, \"/\")\n\t\twildcard := false\n\t\tfor _, part := range patParts {\n\t\t\tif part == \"*\" {\n\t\t\t\twildcard = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !wildcard \u0026\u0026 len(patParts) != len(reqParts) {\n\t\t\tcontinue\n\t\t}\n\n\t\tmatch := true\n\t\tfor i := 0; i \u003c len(patParts); i++ {\n\t\t\tpatPart := patParts[i]\n\t\t\treqPart := reqParts[i]\n\n\t\t\tif patPart == \"*\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif strings.HasPrefix(patPart, \"{\") \u0026\u0026 strings.HasSuffix(patPart, \"}\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif patPart != reqPart {\n\t\t\t\tmatch = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif match {\n\t\t\treq := \u0026Request{\n\t\t\t\tPath:        clearPath,\n\t\t\t\tRawPath:     reqPath,\n\t\t\t\tHandlerPath: route.Pattern,\n\t\t\t\tQuery:       query,\n\t\t\t}\n\t\t\tres := \u0026ResponseWriter{}\n\t\t\tif route.Fn == nil {\n\t\t\t\tpanic(\"Router.Render: route \" + route.Pattern + \" was registered via HandleFuncRlm; use RenderRlm to dispatch\")\n\t\t\t}\n\t\t\troute.Fn(res, req)\n\t\t\treturn res.Output()\n\t\t}\n\t}\n\n\t// not found\n\treq := \u0026Request{Path: reqPath, Query: query}\n\tres := \u0026ResponseWriter{}\n\tr.NotFoundHandler(res, req)\n\treturn res.Output()\n}\n\n// RenderRlm is the rlm-aware counterpart of Render. Dispatches matched\n// routes registered via HandleFuncRlm with the supplied rlm; routes\n// registered via the legacy HandleFunc still work — rlm is ignored.\n// Use this when the router carries any rlm-aware handlers.\nfunc (r *Router) RenderRlm(_ int, rlm realm, reqPath string) string {\n\tclearPath, rawQuery, _ := strings.Cut(reqPath, \"?\")\n\tquery, _ := url.ParseQuery(rawQuery)\n\treqParts := strings.Split(clearPath, \"/\")\n\n\tfor _, route := range r.routes {\n\t\tpatParts := strings.Split(route.Pattern, \"/\")\n\t\twildcard := false\n\t\tfor _, part := range patParts {\n\t\t\tif part == \"*\" {\n\t\t\t\twildcard = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !wildcard \u0026\u0026 len(patParts) != len(reqParts) {\n\t\t\tcontinue\n\t\t}\n\n\t\tmatch := true\n\t\tfor i := 0; i \u003c len(patParts); i++ {\n\t\t\tpatPart := patParts[i]\n\t\t\treqPart := reqParts[i]\n\n\t\t\tif patPart == \"*\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif strings.HasPrefix(patPart, \"{\") \u0026\u0026 strings.HasSuffix(patPart, \"}\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif patPart != reqPart {\n\t\t\t\tmatch = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif match {\n\t\t\treq := \u0026Request{\n\t\t\t\tPath:        clearPath,\n\t\t\t\tRawPath:     reqPath,\n\t\t\t\tHandlerPath: route.Pattern,\n\t\t\t\tQuery:       query,\n\t\t\t}\n\t\t\tres := \u0026ResponseWriter{}\n\t\t\tif route.FnRlm != nil {\n\t\t\t\troute.FnRlm(0, rlm, res, req)\n\t\t\t} else {\n\t\t\t\troute.Fn(res, req)\n\t\t\t}\n\t\t\treturn res.Output()\n\t\t}\n\t}\n\n\t// not found\n\treq := \u0026Request{Path: reqPath, Query: query}\n\tres := \u0026ResponseWriter{}\n\tr.NotFoundHandler(res, req)\n\treturn res.Output()\n}\n\n// HandleFunc registers a route and its handler function.\nfunc (r *Router) HandleFunc(pattern string, fn HandlerFunc) {\n\troute := Handler{Pattern: pattern, Fn: fn}\n\tr.routes = append(r.routes, route)\n}\n\n// HandleFuncRlm registers a route with a rlm-aware handler. Dispatch\n// must use Router.RenderRlm — calling Router.Render on a route registered\n// via HandleFuncRlm panics (no rlm to supply).\nfunc (r *Router) HandleFuncRlm(pattern string, fn HandlerFuncRlm) {\n\troute := Handler{Pattern: pattern, FnRlm: fn}\n\tr.routes = append(r.routes, route)\n}\n\n// HandleErrFunc registers a route and its error handler function.\nfunc (r *Router) HandleErrFunc(pattern string, fn ErrHandlerFunc) {\n\t// Convert ErrHandlerFunc to regular HandlerFunc\n\thandler := func(res *ResponseWriter, req *Request) {\n\t\tif err := fn(res, req); err != nil {\n\t\t\tres.Write(\"Error: \" + err.Error())\n\t\t}\n\t}\n\n\tr.HandleFunc(pattern, handler)\n}\n\n// SetNotFoundHandler sets custom message for 404 defaultNotFoundHandler.\nfunc (r *Router) SetNotFoundHandler(handler NotFoundHandler) {\n\tr.NotFoundHandler = handler\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"list","path":"gno.land/p/nt/bptree/list/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bptree/list/v0\"\ngno = \"0.9\"\n"},{"name":"list.gno","body":"// Package list implements a dynamic list data structure backed by a B+ tree.\n// It provides O(log n) operations for most list operations while maintaining\n// order stability.\n//\n// The list supports various operations including append, get, set, delete,\n// range queries, and iteration. It can store values of any type.\n//\n// Example usage:\n//\n//\t// Create a new list and add elements\n//\tvar l list.List\n//\tl.Append(1, 2, 3)\n//\n//\t// Get and set elements\n//\tvalue, _ := l.Get(1)  // returns 2\n//\tl.Set(1, 42)      // updates index 1 to 42\n//\n//\t// Delete elements\n//\tl.Delete(0)       // removes first element\n//\n//\t// Iterate over elements\n//\tl.ForEach(func(index int, value any) bool {\n//\t    ufmt.Printf(\"index %d: %v\\n\", index, value)\n//\t    return false  // continue iteration\n//\t})\n//\t// Output:\n//\t// index 0: 42\n//\t// index 1: 3\n//\n//\t// Create a list using a variable declaration\n//\tvar l2 list.List\n//\tl2.Append(4, 5, 6)\n//\tprintln(l2.Len())  // Output: 3\npackage list\n\nimport (\n\t\"gno.land/p/nt/bptree/rotree/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\n// IList defines the interface for list operations\ntype IList interface {\n\tLen() int\n\tAppend(values ...any)\n\tGet(index int) (any, bool)\n\tSet(index int, value any) bool\n\tDelete(index int) (any, bool)\n\tSlice(startIndex, endIndex int) []any\n\tForEach(fn func(index int, value any) bool)\n\tClone() *List\n\tDeleteRange(startIndex, endIndex int) int\n}\n\n// Verify List implements IList interface\nvar _ IList = (*List)(nil)\n\n// List represents an ordered sequence of items backed by a B+ tree\ntype List struct {\n\ttree  bptree.BPTree\n\tidGen seqid.ID\n}\n\n// Len returns the number of elements in the list.\nfunc (l *List) Len() int {\n\treturn l.tree.Size()\n}\n\n// Append adds one or more values to the end of the list.\nfunc (l *List) Append(values ...any) {\n\tfor _, v := range values {\n\t\tl.tree.Set(l.idGen.Next().String(), v)\n\t}\n}\n\n// Get returns the value at the specified index and true if the index is valid.\n// Returns (nil, false) if index is out of bounds.\nfunc (l *List) Get(index int) (any, bool) {\n\tif index \u003c 0 || index \u003e= l.tree.Size() {\n\t\treturn nil, false\n\t}\n\t_, value := l.tree.GetByIndex(index)\n\treturn value, true\n}\n\n// Set updates or appends a value at the specified index.\n// Returns true if the operation was successful, false otherwise.\n// For empty lists, only index 0 is valid (append case).\nfunc (l *List) Set(index int, value any) bool {\n\tsize := l.tree.Size()\n\n\t// Handle empty list case - only allow index 0\n\tif size == 0 {\n\t\tif index == 0 {\n\t\t\tl.Append(value)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tif index \u003c 0 || index \u003e size {\n\t\treturn false\n\t}\n\n\t// If setting at the end (append case)\n\tif index == size {\n\t\tl.Append(value)\n\t\treturn true\n\t}\n\n\t// Get the key at the specified index\n\tkey, _ := l.tree.GetByIndex(index)\n\tif key == \"\" {\n\t\treturn false\n\t}\n\n\t// Update the value at the existing key\n\tl.tree.Set(key, value)\n\treturn true\n}\n\n// Delete removes the element at the specified index.\n// Returns the deleted value and true if successful, nil and false otherwise.\nfunc (l *List) Delete(index int) (any, bool) {\n\tsize := l.tree.Size()\n\t// Always return nil, false for empty list\n\tif size == 0 {\n\t\treturn nil, false\n\t}\n\n\tif index \u003c 0 || index \u003e= size {\n\t\treturn nil, false\n\t}\n\n\tkey, value := l.tree.GetByIndex(index)\n\tif key == \"\" {\n\t\treturn nil, false\n\t}\n\n\tl.tree.Remove(key)\n\treturn value, true\n}\n\n// Slice returns a slice of values from startIndex (inclusive) to endIndex (exclusive).\n// Returns nil if the range is invalid.\nfunc (l *List) Slice(startIndex, endIndex int) []any {\n\tsize := l.tree.Size()\n\n\t// Normalize bounds\n\tif startIndex \u003c 0 {\n\t\tstartIndex = 0\n\t}\n\tif endIndex \u003e size {\n\t\tendIndex = size\n\t}\n\tif startIndex \u003e= endIndex {\n\t\treturn nil\n\t}\n\n\tcount := endIndex - startIndex\n\tresult := make([]any, count)\n\n\ti := 0\n\tl.tree.IterateByOffset(startIndex, count, func(_ string, value any) bool {\n\t\tresult[i] = value\n\t\ti++\n\t\treturn false\n\t})\n\treturn result\n}\n\n// ForEach iterates through all elements in the list.\nfunc (l *List) ForEach(fn func(index int, value any) bool) {\n\tif l.tree.Size() == 0 {\n\t\treturn\n\t}\n\n\tindex := 0\n\tl.tree.IterateByOffset(0, l.tree.Size(), func(_ string, value any) bool {\n\t\tresult := fn(index, value)\n\t\tindex++\n\t\treturn result\n\t})\n}\n\n// Clone creates a shallow copy of the list.\nfunc (l *List) Clone() *List {\n\tnewList := \u0026List{\n\t\ttree:  bptree.BPTree{},\n\t\tidGen: l.idGen,\n\t}\n\n\tsize := l.tree.Size()\n\tif size == 0 {\n\t\treturn newList\n\t}\n\n\tl.tree.IterateByOffset(0, size, func(_ string, value any) bool {\n\t\tnewList.Append(value)\n\t\treturn false\n\t})\n\n\treturn newList\n}\n\n// DeleteRange removes elements from startIndex (inclusive) to endIndex (exclusive).\n// Returns the number of elements deleted.\nfunc (l *List) DeleteRange(startIndex, endIndex int) int {\n\tsize := l.tree.Size()\n\n\t// Normalize bounds\n\tif startIndex \u003c 0 {\n\t\tstartIndex = 0\n\t}\n\tif endIndex \u003e size {\n\t\tendIndex = size\n\t}\n\tif startIndex \u003e= endIndex {\n\t\treturn 0\n\t}\n\n\t// Collect keys to delete\n\tkeysToDelete := make([]string, 0, endIndex-startIndex)\n\tl.tree.IterateByOffset(startIndex, endIndex-startIndex, func(key string, _ any) bool {\n\t\tkeysToDelete = append(keysToDelete, key)\n\t\treturn false\n\t})\n\n\t// Delete collected keys\n\tfor _, key := range keysToDelete {\n\t\tl.tree.Remove(key)\n\t}\n\n\treturn len(keysToDelete)\n}\n\n// Tree returns a read-only pointer to the underlying B+ tree.\nfunc (l *List) Tree() *rotree.ReadOnlyTree {\n\treturn rotree.Wrap(\u0026l.tree, nil)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"grc20","path":"gno.land/p/nt/grc20/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/grc20/v0\"\ngno = \"0.9\"\n"},{"name":"mock.gno","body":"package grc20\n\n// XXX: func Mock(t *Token)\n"},{"name":"tellers.gno","body":"package grc20\n\nimport (\n\t\"chain\"\n)\n\n// CallerTeller returns a GRC20 compatible teller that, at each write call,\n// resolves the caller as rlm.Previous() — the realm that crossed into the\n// caller. rlm must be the caller's own captured cur (asserted via\n// rlm.IsCurrent() inside the Teller methods).\n//\n// SECURITY: this accessor hangs off *PrivateLedger, not *Token, and that is\n// load-bearing. A frame-relative teller debits whoever crossed into the realm\n// holding it, so it is only ever meaningful inside the token's own realm,\n// whose wrappers act for a caller who knowingly invoked the token. Anywhere\n// else it is a confused deputy. The *Token pointer is published (exported\n// vars, grc20factory, grc20reg) but the ledger is not — NewToken hands it to\n// the creating realm and nowhere else — so a foreign realm cannot mint one.\n//\n// Construction privacy alone is not enough: a realm may legally build a teller\n// and then export the VALUE. The write methods therefore also verify that the\n// invoking realm is the token's own (see guardHome), which makes a leaked\n// teller inert everywhere but home.\nfunc (ledger *PrivateLedger) CallerTeller() Teller {\n\tif ledger == nil {\n\t\tpanic(\"Ledger cannot be nil\")\n\t}\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, rlm realm) address {\n\t\t\treturn rlm.Previous().Address()\n\t\t},\n\t\thomeGuard: true,\n\t\tToken:     ledger.token,\n\t}\n}\n\n// ReadonlyTeller is a GRC20 compatible teller that panics for any write operation.\nfunc (tok *Token) ReadonlyTeller() Teller {\n\tif tok == nil {\n\t\tpanic(\"Token cannot be nil\")\n\t}\n\n\treturn \u0026fnTeller{\n\t\taccountFn: nil,\n\t\tToken:     tok,\n\t}\n}\n\n// RealmTeller returns a GRC20 compatible teller that will store the\n// caller realm permanently. Calling anything through this teller will\n// result in allowance or balance changes for the realm that initialized the teller.\n// The initializer of this teller should usually never share the resulting Teller from\n// this method except maybe for advanced delegation flows such as a DAO treasury\n// management.\n//\n// rlm must be the caller's own captured cur (asserted via rlm.IsCurrent()).\n// The address is frozen eagerly at construction.\nfunc (tok *Token) RealmTeller(_ int, rlm realm) Teller {\n\tif tok == nil {\n\t\tpanic(\"Token cannot be nil\")\n\t}\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrSpoofedRealm)\n\t}\n\n\tcaller := rlm.Address()\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, _ realm) address {\n\t\t\treturn caller\n\t\t},\n\t\tToken: tok,\n\t}\n}\n\n// RealmSubTeller is like RealmTeller but uses the provided slug to derive a\n// subaccount.\n//\n// rlm must be the caller's own captured cur (asserted via rlm.IsCurrent()).\n// The subaccount address is frozen eagerly at construction.\nfunc (tok *Token) RealmSubTeller(_ int, rlm realm, slug string) Teller {\n\tif tok == nil {\n\t\tpanic(\"Token cannot be nil\")\n\t}\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrSpoofedRealm)\n\t}\n\n\taccount := accountSlugAddr(rlm.Address(), slug)\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, _ realm) address {\n\t\t\treturn account\n\t\t},\n\t\tToken: tok,\n\t}\n}\n\n// ImpersonateTeller returns a GRC20 compatible teller that impersonates as a\n// specified address. This allows operations to be performed as if they were\n// executed by the given address, enabling the caller to manipulate tokens on\n// behalf of that address.\n//\n// It is particularly useful in scenarios where a contract needs to perform\n// actions on behalf of a user or another account, without exposing the\n// underlying logic or requiring direct access to the user's account. The\n// returned teller will use the provided address for all operations, effectively\n// masking the original caller.\n//\n// This method should be used with caution, as it allows for potentially\n// sensitive operations to be performed under the guise of another address.\nfunc (ledger *PrivateLedger) ImpersonateTeller(addr address) Teller {\n\tif ledger == nil {\n\t\tpanic(\"Ledger cannot be nil\")\n\t}\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, _ realm) address {\n\t\t\treturn addr\n\t\t},\n\t\tToken: ledger.token,\n\t}\n}\n\n// generic tellers methods.\n//\n\n// guardHome confines a frame-relative (homeGuard) teller to the token's own\n// realm. Construction privacy stops a foreign realm from minting one;\n// this stops a minted one from travelling, which is what happens when a realm\n// legally builds a teller and then exports the value.\n//\n// The check is on the invoking realm's path alone — deliberately NOT on\n// whether the resolved actor is an end user. Keying on the actor only blocks\n// the case where the debited party is the signing user, which leaves two doors\n// open: a realm can be charged by a realm it calls, and TransferFrom resolves\n// the *spender* from the frame, so a realm reached from an honest hub spends\n// that hub's allowance against any owner who granted one. Both are the same\n// defect as the original one level up — frame-relative resolution means\n// whoever you call can act as you — and neither is reachable once the teller\n// only works at home.\n//\n// The host is compared after stripping any \"#subpath\" synthesized by\n// realm.Sub, so the token's own sub-realms are not falsely rejected.\n//\n// A foreign realm that needs to move a user's funds uses the ordinary route:\n// Approve, then RealmTeller().TransferFrom, which is eagerly bound to that\n// realm's own address and allowance-gated.\n//\n// The leading int keeps this a plain method.\nfunc (ft *fnTeller) guardHome(_ int, rlm realm) error {\n\tif !ft.homeGuard {\n\t\treturn nil\n\t}\n\thost, _, _ := chain.SplitPkgSubPath(rlm.PkgPath())\n\tif host != ft.Token.origRealm {\n\t\treturn ErrForeignCallerTeller\n\t}\n\treturn nil\n}\n\nfunc (ft *fnTeller) Transfer(_ int, rlm realm, to address, amount int64) error {\n\tif ft.accountFn == nil {\n\t\treturn ErrReadonly\n\t}\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\tif err := ft.guardHome(0, rlm); err != nil {\n\t\treturn err\n\t}\n\tcaller := ft.accountFn(0, rlm)\n\treturn ft.Token.ledger.Transfer(caller, to, amount)\n}\n\nfunc (ft *fnTeller) Approve(_ int, rlm realm, spender address, amount int64) error {\n\tif ft.accountFn == nil {\n\t\treturn ErrReadonly\n\t}\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\tif err := ft.guardHome(0, rlm); err != nil {\n\t\treturn err\n\t}\n\tcaller := ft.accountFn(0, rlm)\n\treturn ft.Token.ledger.Approve(caller, spender, amount)\n}\n\nfunc (ft *fnTeller) TransferFrom(_ int, rlm realm, owner, to address, amount int64) error {\n\tif ft.accountFn == nil {\n\t\treturn ErrReadonly\n\t}\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\tif err := ft.guardHome(0, rlm); err != nil {\n\t\treturn err\n\t}\n\tspender := ft.accountFn(0, rlm)\n\treturn ft.Token.ledger.TransferFrom(owner, spender, to, amount)\n}\n\n// helpers\n//\n\n// accountSlugAddr returns the address derived from the specified address and slug.\nfunc accountSlugAddr(addr address, slug string) address {\n\t// XXX: use a new `std.XXX` call for this.\n\tif slug == \"\" {\n\t\treturn addr\n\t}\n\tkey := addr.String() + \"/\" + slug\n\treturn chain.PackageAddress(key) // temporarily using this helper\n}\n"},{"name":"token.gno","body":"package grc20\n\nimport (\n\t\"chain\"\n\t\"math\"\n\t\"math/overflow\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewToken creates a Token whose origRealm is bound to the calling realm.\n// rlm must be the caller's own captured cur (asserted via rlm.IsCurrent()),\n// and rlm.PkgPath() — the calling realm itself, with any realm.Sub subpath\n// stripped — becomes the Token's origRealm. Token.ID() keeps the raw\n// rlm.PkgPath(), and returns it + \".\" + symbol + \".\" + id.\n//\n// Because IsCurrent runtime-validates that rlm came from the live\n// crossing frame, origRealm is unforgeable: an external realm cannot\n// fabricate a Token claiming to belong to a different package.\n//\n// Realms that create multiple tokens should allocate id from one persistent\n// seqid.ID, shared by every creation path, to avoid conflicting identifiers:\n//\n//\tvar nextTokenID seqid.ID\n//\tToken, ledger := grc20.NewToken(\"Foo\", \"FOO\", 4, nextTokenID.Next(), cur)\n//\n// A realm that creates only a single token can pass 0 directly, since no\n// other token of that realm can collide with it.\n//\n// If the Token should be discoverable, follow up with\n// grc20reg.Register(cross(cur), Token, slug). The registry key is the\n// rlmPath.symbol prefix of Token.ID(), without its trailing id.\n//\n// Every successful call emits a NewToken event carrying the resulting\n// Token.ID(). Because Token's fields are unexported, NewToken is the only way a\n// Token can come into existence, so this event makes token creation fully\n// observable: an indexer that sees the same Token.ID() announced twice knows the\n// realm built two independent ledgers behind one identifier, and that every\n// later Mint/Burn/Transfer/Approval carrying that id is ambiguous. Such a realm\n// is emitting untrustworthy events and should be flagged or ignored wholesale.\nfunc NewToken(name, symbol string, decimals int, id seqid.ID, rlm realm) (*Token, *PrivateLedger) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrSpoofedRealm)\n\t}\n\tpkgPath := rlm.PkgPath()\n\tif pkgPath == \"\" {\n\t\tpanic(ErrNotRealm)\n\t}\n\tif !validName(name) {\n\t\tpanic(ErrInvalidName)\n\t}\n\tif !validSymbol(symbol) {\n\t\tpanic(ErrInvalidSymbol)\n\t}\n\tif decimals \u003c 0 || decimals \u003e MaxDecimals {\n\t\tpanic(ErrInvalidDecimals)\n\t}\n\t// origRealm drops any realm.Sub subpath: a token created while its realm\n\t// operates under a sub identity still belongs to the host realm. guardHome\n\t// resolves the invoking host the same way, so storing the raw path here\n\t// would pin the token to that sub and lock its own realm out for good.\n\torigRealm, _, _ := chain.SplitPkgSubPath(pkgPath)\n\tledger := \u0026PrivateLedger{}\n\ttoken := \u0026Token{\n\t\tid:        pkgPath + \".\" + symbol + \".\" + id.String(),\n\t\tname:      name,\n\t\tsymbol:    symbol,\n\t\tdecimals:  decimals,\n\t\tledger:    ledger,\n\t\torigRealm: origRealm,\n\t}\n\tledger.token = token\n\n\tchain.Emit(\n\t\tNewTokenEvent,\n\t\t\"token\", token.id,\n\t\t\"name\", name,\n\t\t\"symbol\", symbol,\n\t\t\"decimals\", strconv.Itoa(decimals),\n\t)\n\n\treturn token, ledger\n}\n\n// validName reports whether name is a valid display name: non-empty,\n// within MaxNameLen, and contains no control characters (any rune\n// below 0x20 or 0x7f). Permits Unicode letters, digits, punctuation,\n// and spaces — name is purely a display field.\nfunc validName(name string) bool {\n\tif name == \"\" || len(name) \u003e MaxNameLen {\n\t\treturn false\n\t}\n\tfor _, c := range name {\n\t\tif c \u003c 0x20 || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// validSymbol reports whether s is valid slug-compatible metadata: non-empty,\n// within MaxSymbolLen, and consists only of [A-Za-z0-9_-].\nfunc validSymbol(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxSymbolLen {\n\t\treturn false\n\t}\n\tfor _, c := range s {\n\t\tif !isAlnum(c) \u0026\u0026 c != '_' \u0026\u0026 c != '-' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc isAlnum(c rune) bool {\n\treturn (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9')\n}\n\n// GetName returns the name of the token.\nfunc (tok Token) GetName() string { return tok.name }\n\n// GetSymbol returns the symbol of the token.\nfunc (tok Token) GetSymbol() string { return tok.symbol }\n\n// GetDecimals returns the number of decimals used to get the token's precision.\nfunc (tok Token) GetDecimals() int { return tok.decimals }\n\n// TotalSupply returns the total supply of the token.\nfunc (tok Token) TotalSupply() int64 { return tok.ledger.totalSupply }\n\n// KnownAccounts returns the number of known accounts in the bank.\nfunc (tok Token) KnownAccounts() int { return tok.ledger.balances.Size() }\n\n// ID returns the Identifier of the token.\n// It is composed of the creating realm's raw pkgpath — including any\n// realm.Sub subpath, unlike origRealm — the symbol, and the provided id.\nfunc (tok *Token) ID() string {\n\treturn tok.id\n}\n\n// HasAddr checks if the specified address is a known account in the bank.\nfunc (tok Token) HasAddr(addr address) bool {\n\treturn tok.ledger.hasAddr(addr)\n}\n\n// BalanceOf returns the balance of the specified address.\nfunc (tok Token) BalanceOf(addr address) int64 {\n\treturn tok.ledger.balanceOf(addr)\n}\n\n// Allowance returns the allowance of the specified owner and spender.\nfunc (tok Token) Allowance(owner, spender address) int64 {\n\treturn tok.ledger.allowance(owner, spender)\n}\n\nfunc (tok Token) RenderHome() string {\n\tstr := \"\"\n\tstr += ufmt.Sprintf(\"# %s ($%s)\\n\\n\", tok.name, tok.symbol)\n\tstr += ufmt.Sprintf(\"* **Decimals**: %d\\n\", tok.decimals)\n\tstr += ufmt.Sprintf(\"* **Total supply**: %d\\n\", tok.ledger.totalSupply)\n\tstr += ufmt.Sprintf(\"* **Known accounts**: %d\\n\", tok.KnownAccounts())\n\treturn str\n}\n\n// SpendAllowance decreases the allowance of the specified owner and spender.\nfunc (led *PrivateLedger) SpendAllowance(owner, spender address, amount int64) error {\n\tif !owner.IsValid() || !spender.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\tif amount \u003c 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\t// do nothing\n\tif amount == 0 {\n\t\treturn nil\n\t}\n\n\tcurrentAllowance := led.allowance(owner, spender)\n\tif currentAllowance \u003c amount {\n\t\treturn ErrInsufficientAllowance\n\t}\n\n\tkey := allowanceKey(owner, spender)\n\tnewAllowance := overflow.Sub64p(currentAllowance, amount)\n\n\tif newAllowance == 0 {\n\t\tled.allowances.Remove(key)\n\t} else {\n\t\tled.allowances.Set(key, newAllowance)\n\t}\n\n\treturn nil\n}\n\n// Transfer transfers tokens from the specified from address to the specified to address.\nfunc (led *PrivateLedger) Transfer(from, to address, amount int64) error {\n\tif !from.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\tif !to.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\tif from == to {\n\t\treturn ErrCannotTransferToSelf\n\t}\n\tif amount \u003c 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\n\tvar (\n\t\ttoBalance   = led.balanceOf(to)\n\t\tfromBalance = led.balanceOf(from)\n\t)\n\n\tif fromBalance \u003c amount {\n\t\treturn ErrInsufficientBalance\n\t}\n\n\tvar (\n\t\tnewToBalance   = overflow.Add64p(toBalance, amount)\n\t\tnewFromBalance = overflow.Sub64p(fromBalance, amount)\n\t)\n\n\tled.balances.Set(string(to), newToBalance)\n\n\tif newFromBalance == 0 {\n\t\tled.balances.Remove(string(from))\n\t} else {\n\t\tled.balances.Set(string(from), newFromBalance)\n\t}\n\n\tchain.Emit(\n\t\tTransferEvent,\n\t\t\"token\", led.token.ID(),\n\t\t\"from\", from.String(),\n\t\t\"to\", to.String(),\n\t\t\"value\", strconv.Itoa(int(amount)),\n\t)\n\n\treturn nil\n}\n\n// TransferFrom transfers tokens from the specified owner to the specified to address.\n// It first checks if the owner has sufficient balance and then decreases the allowance.\nfunc (led *PrivateLedger) TransferFrom(owner, spender, to address, amount int64) error {\n\tif amount \u003c 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\n\tif !owner.IsValid() || !to.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\tif owner == to {\n\t\treturn ErrCannotTransferToSelf\n\t}\n\n\tif led.balanceOf(owner) \u003c amount {\n\t\treturn ErrInsufficientBalance\n\t}\n\n\t// The check above guarantees that Transfer will succeed, ensuring\n\t// atomicity for the subsequent operations.\n\tif err := led.SpendAllowance(owner, spender, amount); err != nil {\n\t\treturn err\n\t}\n\n\tif err := led.Transfer(owner, to, amount); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// Approve sets the allowance of the specified owner and spender.\nfunc (led *PrivateLedger) Approve(owner, spender address, amount int64) error {\n\tif !owner.IsValid() || !spender.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\tif amount \u003c 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\n\tled.allowances.Set(allowanceKey(owner, spender), amount)\n\n\tchain.Emit(\n\t\tApprovalEvent,\n\t\t\"token\", led.token.ID(),\n\t\t\"owner\", string(owner),\n\t\t\"spender\", string(spender),\n\t\t\"value\", strconv.Itoa(int(amount)),\n\t)\n\n\treturn nil\n}\n\n// Mint increases the total supply of the token and adds the specified amount to the specified address.\nfunc (led *PrivateLedger) Mint(addr address, amount int64) error {\n\tif !addr.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\tif amount \u003c 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\n\t// limit amount to MaxInt64 - totalSupply\n\tif amount \u003e overflow.Sub64p(math.MaxInt64, led.totalSupply) {\n\t\treturn ErrMintOverflow\n\t}\n\n\tled.totalSupply += amount\n\tcurrentBalance := led.balanceOf(addr)\n\tnewBalance := overflow.Add64p(currentBalance, amount)\n\n\tled.balances.Set(string(addr), newBalance)\n\n\tchain.Emit(\n\t\tTransferEvent,\n\t\t\"token\", led.token.ID(),\n\t\t\"from\", \"\",\n\t\t\"to\", string(addr),\n\t\t\"value\", strconv.Itoa(int(amount)),\n\t)\n\n\treturn nil\n}\n\n// Burn decreases the total supply of the token and subtracts the specified amount from the specified address.\nfunc (led *PrivateLedger) Burn(addr address, amount int64) error {\n\tif !addr.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\tif amount \u003c 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\n\tcurrentBalance := led.balanceOf(addr)\n\tif currentBalance \u003c amount {\n\t\treturn ErrInsufficientBalance\n\t}\n\n\tled.totalSupply = overflow.Sub64p(led.totalSupply, amount)\n\tnewBalance := overflow.Sub64p(currentBalance, amount)\n\n\tif newBalance == 0 {\n\t\tled.balances.Remove(string(addr))\n\t} else {\n\t\tled.balances.Set(string(addr), newBalance)\n\t}\n\n\tchain.Emit(\n\t\tTransferEvent,\n\t\t\"token\", led.token.ID(),\n\t\t\"from\", string(addr),\n\t\t\"to\", \"\",\n\t\t\"value\", strconv.Itoa(int(amount)),\n\t)\n\n\treturn nil\n}\n\n// hasAddr checks if the specified address is a known account in the ledger.\nfunc (led PrivateLedger) hasAddr(addr address) bool {\n\treturn led.balances.Has(addr.String())\n}\n\n// balanceOf returns the balance of the specified address.\nfunc (led PrivateLedger) balanceOf(addr address) int64 {\n\tbalance := led.balances.Get(addr.String())\n\tif balance == nil {\n\t\treturn 0\n\t}\n\treturn balance.(int64)\n}\n\n// allowance returns the allowance of the specified owner and spender.\nfunc (led PrivateLedger) allowance(owner, spender address) int64 {\n\tallowance := led.allowances.Get(allowanceKey(owner, spender))\n\tif allowance == nil {\n\t\treturn 0\n\t}\n\treturn allowance.(int64)\n}\n\n// allowanceKey returns the key for the allowance of the specified owner and spender.\nfunc allowanceKey(owner, spender address) string {\n\treturn owner.String() + \":\" + spender.String()\n}\n"},{"name":"types.gno","body":"package grc20\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Teller interface defines the methods that a GRC20 token must implement. It\n// extends the TokenMetadata interface to include methods for managing token\n// transfers, allowances, and querying balances.\n//\n// The Teller interface is designed to ensure that any token adhering to this\n// standard provides a consistent API for interacting with fungible tokens.\n//\n// SECURITY: Transfer/Approve/TransferFrom take (_ int, rlm realm, ...), so\n// handing a Teller value to untrusted code yields a capability token to\n// whatever Transfer/Approve/TransferFrom impl that code dispatches into.\n// Any /p/ or /r/ function that accepts a Teller as a parameter from external\n// callers MUST type-assert against the canonical concrete type (*fnTeller)\n// via IsCanonicalTeller and reject otherwise. An unexported-marker \"seal\"\n// does NOT defend against this — see\n// p/test/seal/filetests/z_seal_iface_embedding_filetest.gno\n// for the realistic embedding-bypass attack. Reference impl for the\n// canonical-allowlist pattern: p/jaekwon/allowancesender.\ntype Teller interface {\n\t// Returns the name of the token.\n\tGetName() string\n\n\t// Returns the symbol of the token, usually a shorter version of the\n\t// name.\n\tGetSymbol() string\n\n\t// Returns the decimals places of the token.\n\tGetDecimals() int\n\n\t// Returns the amount of tokens in existence.\n\tTotalSupply() int64\n\n\t// Returns the amount of tokens owned by `account`.\n\tBalanceOf(account address) int64\n\n\t// Moves `amount` tokens from the caller's account to `to`. rlm must\n\t// be the caller's own captured cur — verified via rlm.IsCurrent().\n\t//\n\t// Returns an error if the operation failed.\n\tTransfer(_ int, rlm realm, to address, amount int64) error\n\n\t// Returns the remaining number of tokens that `spender` will be\n\t// allowed to spend on behalf of `owner` through {transferFrom}. This is\n\t// zero by default.\n\t//\n\t// This value changes when {approve} or {transferFrom} are called.\n\tAllowance(owner, spender address) int64\n\n\t// Sets `amount` as the allowance of `spender` over the caller's tokens.\n\t//\n\t// Returns an error if the operation failed.\n\t//\n\t// IMPORTANT: Beware that changing an allowance with this method brings\n\t// the risk that someone may use both the old and the new allowance by\n\t// unfortunate transaction ordering. One possible solution to mitigate\n\t// this race condition is to first reduce the spender's allowance to 0\n\t// and set the desired value afterwards:\n\t// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n\tApprove(_ int, rlm realm, spender address, amount int64) error\n\n\t// Moves `amount` tokens from `from` to `to` using the\n\t// allowance mechanism. `amount` is then deducted from the caller's\n\t// allowance.\n\t//\n\t// Returns an error if the operation failed.\n\tTransferFrom(_ int, rlm realm, from, to address, amount int64) error\n}\n\n// Token represents a fungible token with an ID, name, symbol, and a certain\n// number of decimal places. It maintains a ledger for tracking balances and\n// allowances of addresses.\n//\n// The Token struct provides methods for retrieving token metadata, such as the\n// name, symbol, and decimals, as well as methods for interacting with the\n// ledger, including checking balances and allowances.\ntype Token struct {\n\t// Identifier precomputed in NewToken to make ID() a cheap field read.\n\tid string\n\t// Name of the token (e.g., \"Dummy Token\").\n\tname string\n\t// Symbol of the token (e.g., \"DUMMY\").\n\tsymbol string\n\t// Number of decimal places used for the token's precision.\n\tdecimals int\n\t// Pointer to the PrivateLedger that manages balances and allowances.\n\tledger *PrivateLedger\n\t// origRealm is the PkgPath of the realm that created the token, captured\n\t// unforgeably in NewToken. A frame-relative teller only works there.\n\torigRealm string\n}\n\n// PrivateLedger is a struct that holds the balances and allowances for the\n// token. It provides administrative functions for minting, burning,\n// transferring tokens, and managing allowances.\n//\n// The PrivateLedger is not safe to expose publicly, as it contains sensitive\n// information regarding token balances and allowances, and allows direct,\n// unrestricted access to all administrative functions.\ntype PrivateLedger struct {\n\t// Total supply of the token managed by this ledger.\n\ttotalSupply int64\n\t// chain.Address -\u003e int64\n\tbalances avl.Tree\n\t// owner.(chain.Address)+\":\"+spender.(chain.Address)) -\u003e int64\n\tallowances avl.Tree\n\t// Pointer to the associated Token struct\n\ttoken *Token\n}\n\nvar (\n\tErrInsufficientBalance   = errors.New(\"insufficient balance\")\n\tErrInsufficientAllowance = errors.New(\"insufficient allowance\")\n\tErrInvalidAddress        = errors.New(\"invalid address\")\n\tErrCannotTransferToSelf  = errors.New(\"cannot send transfer to self\")\n\tErrReadonly              = errors.New(\"banker is readonly\")\n\tErrRestrictedTokenOwner  = errors.New(\"restricted to bank owner\")\n\tErrMintOverflow          = errors.New(\"mint overflow\")\n\tErrInvalidAmount         = errors.New(\"invalid amount\")\n\tErrSpoofedRealm          = errors.New(\"rlm does not match the current crossing frame\")\n\tErrForeignCallerTeller   = errors.New(\"caller teller is confined to the token's own realm\")\n\tErrNotRealm              = errors.New(\"rlm must be a realm (got EOA/origin)\")\n\tErrInvalidName           = errors.New(\"invalid token name (empty, too long, or contains control chars)\")\n\tErrInvalidSymbol         = errors.New(\"invalid token symbol (empty, too long, or contains chars outside [A-Za-z0-9_-])\")\n\tErrInvalidDecimals       = errors.New(\"invalid decimals (must be 0..18)\")\n)\n\n// Construction limits. Symbol is restricted to the same charset as\n// grc20reg.validateSlug because it is included in Token.ID(), which is\n// emitted in events and frequently used as a registry slug; banning `.` `/`\n// and whitespace here prevents downstream parsers from being fooled by\n// ambiguous IDs. Name is for display only and allows any valid UTF-8 except\n// control characters.\nconst (\n\tMaxNameLen   = 64\n\tMaxSymbolLen = 11\n\tMaxDecimals  = 18\n)\n\nconst (\n\tNewTokenEvent = \"NewToken\"\n\tMintEvent     = \"Mint\"\n\tBurnEvent     = \"Burn\"\n\tTransferEvent = \"Transfer\"\n\tApprovalEvent = \"Approval\"\n)\n\ntype fnTeller struct {\n\taccountFn func(_ int, rlm realm) address\n\t// homeGuard marks a frame-relative teller (PrivateLedger.CallerTeller),\n\t// whose actor is resolved from the invoking frame. Such a teller is only\n\t// meaningful in the token's own realm and is refused anywhere else, so\n\t// exporting the value cannot hand out a spend capability.\n\thomeGuard bool\n\t*Token\n}\n\nvar _ Teller = (*fnTeller)(nil)\n\n// IsCanonicalTeller reports whether t is the canonical *fnTeller produced by\n// Token.CallerTeller / RealmTeller / RealmSubTeller / ReadonlyTeller /\n// ImpersonateTeller. Use this at any public entry point that accepts a\n// Teller from an external caller before invoking its methods.\n//\n// Foreign types — including embedding-based wrappers like\n// `type Evil struct { grc20.Teller }` — are rejected because type\n// assertions are nominal: *Evil is not *fnTeller, regardless of method\n// promotion. This is the reliable defense; the unexported-marker \"seal\"\n// pattern is bypassable via embedding (see\n// p/test/seal/filetests/z_seal_iface_embedding_filetest.gno).\n//\n// Mirrors the precedent of chain/banker.IsCanonical and\n// p/jaekwon/allowancesender's canonical-impl check.\nfunc IsCanonicalTeller(t Teller) bool {\n\t_, ok := t.(*fnTeller)\n\treturn ok\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"treasury","path":"gno.land/p/nt/treasury/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `treasury` - Coin and GRC20 treasury management\n\nTreasury management for coin and GRC20 token transfers in Gno realms. A `Treasury` holds a set of `Banker`s, each responsible for sending a specific asset type, and records the payment history per banker.\n\n# 1. Concepts\n\n- **Treasury**: container that registers one or more `Banker`s and exposes a unified `Send`/`History`/`Balances` API. Also provides a `Render` router for gnoweb pages.\n- **Banker**: handler for a single asset type. Built-ins are `CoinsBanker` (native chain coins) and `GRC20Banker` (any number of GRC20 tokens, resolved through a user-supplied `TokenListerFunc`).\n- **Payment**: opaque value produced by a banker-specific helper (`NewCoinsPayment`, `NewGRC20Payment`). Each `Payment` is bound to a `BankerID()`, which is how the treasury routes it.\n\n# 2. Usage\n\n```go\nimport (\n    \"chain\"\n    \"chain/banker\"\n    \"chain/runtime\"\n\n    \"gno.land/p/nt/grc20/v0\"\n    \"gno.land/p/nt/treasury/v0\"\n)\n\nvar (\n    tokens = map[string]*grc20.Token{}\n    tr     *treasury.Treasury\n)\n\nfunc init() {\n    owner := runtime.CurrentRealm().Address() // this realm holds and sends the funds\n\n    // Coins banker owned by this realm.\n    coinsBanker, err := treasury.NewCoinsBankerWithOwner(\n        owner,\n        banker.NewBanker(banker.BankerTypeRealmSend),\n    )\n    if err != nil {\n        panic(err)\n    }\n\n    // GRC20 banker that resolves tokens through a lister.\n    grc20Banker, err := treasury.NewGRC20BankerWithOwner(owner, func() map[string]*grc20.Token {\n        return tokens\n    })\n    if err != nil {\n        panic(err)\n    }\n\n    tr, err = treasury.New(\n        []treasury.Banker{coinsBanker, grc20Banker},\n        runtime.CurrentRealm().PkgPath(),\n    )\n    if err != nil {\n        panic(err)\n    }\n}\n\n// SendUgnot transfers ugnot from the realm to `to`.\nfunc SendUgnot(cur realm, to address, amount int64) {\n    p := treasury.NewCoinsPayment(chain.Coins{{Denom: \"ugnot\", Amount: amount}}, to)\n    if err := tr.Send(0, cur, p); err != nil {\n        panic(err)\n    }\n}\n\n// Render exposes the treasury under the realm's render path.\nfunc Render(path string) string {\n    return tr.Render(path)\n}\n```\n\n# 3. API\n\n## 3.1 Treasury\n\n```go\n// Builds a treasury with the provided bankers (at least one required, IDs must be unique).\n// pkgPath is the realm's package path, used as the base for the Render router.\nfunc New(bankers []Banker, pkgPath string) (*Treasury, error)\n\nfunc (t *Treasury) Send(_ int, rlm realm, p Payment) error\nfunc (t *Treasury) History(bankerID string, pageNumber, pageSize int) ([]Payment, error)\nfunc (t *Treasury) Balances(bankerID string) ([]Balance, error)\nfunc (t *Treasury) Address(bankerID string) (string, error)\nfunc (t *Treasury) HasBanker(bankerID string) bool\nfunc (t *Treasury) ListBankerIDs() []string\n\n// Render entry points (a mux router is initialized by `New`).\nfunc (t *Treasury) Render(path string) string\nfunc (t *Treasury) RenderLanding(path string) string\nfunc (t *Treasury) RenderBanker(bankerID, path string) string\nfunc (t *Treasury) RenderBankerHistory(bankerID, path string) string\n```\n\nRender routes:\n- `\"\"` — landing page, lists each banker.\n- `{banker}` — banker details (address, balances, last N payments).\n- `{banker}/history` — paginated payment history.\n\nThe `history_size` query parameter on `{banker}` controls the preview size (default `5`, `0` hides the preview).\n\n## 3.2 Banker and Payment interfaces\n\n```go\ntype Banker interface {\n    ID() string                     // unique banker ID used for routing\n    Send(int, realm, Payment) error // thread the caller's cur; pass 0 as the first arg\n    Balances() []Balance\n    Address() string                // address used to receive payments\n}\n\ntype Payment interface {\n    BankerID() string    // routes the payment to a banker\n    String() string\n}\n\ntype Balance struct {\n    Denom  string\n    Amount int64\n}\n\n// Capability guard: any entry point that accepts a Banker from an external\n// caller MUST verify it before invoking its methods. Validates dynamic type\n// only (embedding-based wrappers are rejected), not captured state.\nfunc IsCanonicalBanker(b Banker) bool\n```\n\n## 3.3 CoinsBanker\n\n`Banker` for native chain coins. Owns an address and an inner `chain/banker.Banker` (must be the canonical one returned by `banker.NewBanker` — fake implementations are rejected).\n\n```go\nfunc NewCoinsBankerWithOwner(owner address, banker_ banker.Banker) (*CoinsBanker, error)\n\nfunc NewCoinsPayment(coins chain.Coins, toAddress address) Payment\n```\n\n`CoinsBanker.ID()` returns `\"Coins\"`.\n\n## 3.4 GRC20Banker\n\n`Banker` for GRC20 tokens. Tokens are resolved at send time through a `TokenListerFunc`, so the set of supported tokens can change without rebuilding the banker.\n\n```go\ntype TokenListerFunc func() map[string]*grc20.Token\n\nfunc NewGRC20BankerWithOwner(owner address, lister TokenListerFunc) (*GRC20Banker, error)\n\nfunc NewGRC20Payment(tokenKey string, amount int64, toAddress address) Payment\n```\n\n`GRC20Banker.ID()` returns `\"GRC20\"`. `tokenKey` must be a key in the map returned by the lister.\n\n## 3.5 Errors\n\n```go\nErrNoBankerProvided       // New called with empty bankers slice\nErrDuplicateBanker        // two bankers share the same ID\nErrBankerNotFound         // Send/History/... called with an unknown banker ID\nErrSendPaymentFailed      // wraps the underlying banker error\nErrCurrentRealmIsNotOwner // banker called from a realm other than its owner\nErrNoOwnerProvided\nErrInvalidPaymentType     // payment routed to the wrong banker type\nErrNonCanonicalBanker     // CoinsBanker built from a non-canonical std banker\nErrNonCanonicalBankerImpl // New given a Banker of a non-canonical type\nErrSpoofedRealm           // Send called with a non-current rlm\nErrNoListerProvided\nErrGRC20TokenNotFound\n```\n\n# 4. Security\n\nThe `Banker` capability model rests on three rules:\n\n- **Construct your own bankers.** Never accept a pre-built `Banker` (including a `*WithOwner` value) from an external realm. A hostile `Balances`/`Address` can report data tied to an attacker address. `New` calls `IsCanonicalBanker` on each banker and rejects foreign types with `ErrNonCanonicalBankerImpl`.\n- **`IsCanonicalBanker` checks dynamic TYPE only, not captured state.** Embedding-based wrappers (`type Evil struct { *CoinsBanker }`) are rejected because type assertions are nominal. Any public entry point that takes a `Banker` from a caller must call it before invoking the banker's methods.\n- **Owner must match the acting realm.** `Send` asserts `rlm.IsCurrent()` (else `ErrSpoofedRealm`) and the banker rejects a caller that is not its owner (`ErrCurrentRealmIsNotOwner`). Set the owner to the realm that will actually send.\n"},{"name":"banker_coins.gno","body":"package treasury\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"errors\"\n\n\t\"gno.land/p/aeddi/panictoerr/v0\"\n)\n\nvar ErrNonCanonicalBanker = errors.New(\"inner banker is not the canonical chain/banker.Banker\")\n\n// CoinsBanker is a Banker that sends banker.Coins.\ntype CoinsBanker struct {\n\towner  address       // The address of this coins banker owner.\n\tbanker banker.Banker // The underlying std banker, must be a BankerTypeRealmSend.\n}\n\nvar _ Banker = (*CoinsBanker)(nil)\n\n// ID implements Banker.\nfunc (CoinsBanker) ID() string {\n\treturn \"Coins\"\n}\n\n// Send implements Banker.\n//\n// rlm must be the caller's own captured cur (i.e. the cur of the\n// immediate crossing-function caller). Sending with rlm = cur.Previous()\n// or any other realm value is rejected: rlm.IsCurrent() asserts pointer\n// identity against the topmost crossing frame. Combined with the\n// rlm.Address() == cb.owner check, this restricts Send to the owning\n// realm acting in its own frame.\nfunc (cb *CoinsBanker) Send(_ int, rlm realm, p Payment) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\tif rlm.Address() != cb.owner {\n\t\treturn ErrCurrentRealmIsNotOwner\n\t}\n\t// Check if payment is of type coinsPayment.\n\tpayment, ok := p.(coinsPayment)\n\tif !ok {\n\t\treturn ErrInvalidPaymentType\n\t}\n\n\t// Send the coins.\n\treturn panictoerr.PanicToError(func() {\n\t\tcb.banker.SendCoins(cb.owner, payment.toAddress, payment.coins)\n\t})\n}\n\n// Balances implements Banker.\nfunc (cb *CoinsBanker) Balances() []Balance {\n\t// Get the coins from the banker.\n\tcoins := cb.banker.GetCoins(cb.owner)\n\n\t// Convert banker.Coins to []Balance.\n\tbalances := make([]Balance, len(coins))\n\tfor i := range coins {\n\t\tbalances[i] = Balance{\n\t\t\tDenom:  coins[i].Denom,\n\t\t\tAmount: coins[i].Amount,\n\t\t}\n\t}\n\n\treturn balances\n}\n\n// Address implements Banker.\nfunc (cb *CoinsBanker) Address() string {\n\treturn cb.owner.String()\n}\n\n// NewCoinsBankerWithOwner creates a new CoinsBanker with the given address.\n//\n// banker_ must be the canonical Banker produced by banker.NewBanker;\n// hand-rolled Banker implementations (no-op fakes, decorators) are\n// rejected via banker.IsCanonical. Without this check, a callee\n// receiving a *CoinsBanker constructed from a fake banker would not\n// be able to tell that Send is a no-op (no real coins move). The\n// pkgAddr-vs-owner mismatch is still surfaced lazily by the inner\n// banker's own SendCoins check.\nfunc NewCoinsBankerWithOwner(owner address, banker_ banker.Banker) (*CoinsBanker, error) {\n\tif owner == \"\" {\n\t\treturn nil, ErrNoOwnerProvided\n\t}\n\n\tif !banker.IsCanonical(banker_) {\n\t\treturn nil, ErrNonCanonicalBanker\n\t}\n\n\treturn \u0026CoinsBanker{\n\t\towner:  owner,\n\t\tbanker: banker_,\n\t}, nil\n}\n\n// coinsPayment represents a payment that is issued by a CoinsBanker.\ntype coinsPayment struct {\n\tcoins     chain.Coins // The coins being sent.\n\ttoAddress address     // The recipient of the payment.\n}\n\nvar _ Payment = (*coinsPayment)(nil)\n\n// BankerID implements Payment.\nfunc (coinsPayment) BankerID() string {\n\treturn CoinsBanker{}.ID()\n}\n\n// String implements Payment.\nfunc (cp coinsPayment) String() string {\n\treturn cp.coins.String() + \" to \" + cp.toAddress.String()\n}\n\n// NewCoinsPayment creates a new coinsPayment.\n//\n// The coins are copied, so the caller cannot change the amount after the\n// payment exists, and sorted and joined, so String() renders the set that will\n// actually be paid. A non-positive amount is rejected here rather than by the\n// bank keeper at execution, after a vote. A malformed denom is still only\n// caught by the keeper.\nfunc NewCoinsPayment(coins chain.Coins, toAddress address) Payment {\n\tcz := chain.Coins{}.Add(coins)\n\n\tfor _, c := range cz {\n\t\tif !c.IsPositive() {\n\t\t\tpanic(\"coins payment amounts must be positive, got \" + c.String())\n\t\t}\n\t}\n\n\treturn coinsPayment{\n\t\tcoins:     cz,\n\t\ttoAddress: toAddress,\n\t}\n}\n"},{"name":"banker_grc20.gno","body":"package treasury\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar (\n\tErrNoListerProvided   = errors.New(\"no lister provided\")\n\tErrGRC20TokenNotFound = errors.New(\"GRC20 token not found\")\n)\n\n// GRC20Banker is a Banker that sends GRC20 tokens listed using a getter\n// set during initialization.\ntype GRC20Banker struct {\n\towner  address         // The address of this GRC20 banker owner.\n\tlister TokenListerFunc // Allows to list tokens from methods that require it.\n}\n\n// TokenListerFunc is a function type that returns a map of GRC20 tokens.\ntype TokenListerFunc func() map[string]*grc20.Token\n\nvar _ Banker = (*GRC20Banker)(nil)\n\n// ID implements Banker.\nfunc (GRC20Banker) ID() string {\n\treturn \"GRC20\"\n}\n\n// Send implements Banker.\n//\n// rlm must be the caller's own captured cur (i.e. the cur of the\n// immediate crossing-function caller). Sending with rlm = cur.Previous()\n// or any other realm value is rejected: rlm.IsCurrent() asserts pointer\n// identity against the topmost crossing frame. Combined with the\n// rlm.Address() == gb.owner check, this restricts Send to the owning\n// realm acting in its own frame.\nfunc (gb *GRC20Banker) Send(_ int, rlm realm, p Payment) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\tif rlm.Address() != gb.owner {\n\t\treturn ErrCurrentRealmIsNotOwner\n\t}\n\n\tpayment, ok := p.(grc20Payment)\n\tif !ok {\n\t\treturn ErrInvalidPaymentType\n\t}\n\n\t// Get the GRC20 tokens using the lister.\n\ttokens := gb.lister()\n\n\t// Look for the token corresponding to the payment tokenKey.\n\ttoken, ok := tokens[payment.tokenKey]\n\tif !ok {\n\t\treturn ufmt.Errorf(\"%v: %s\", ErrGRC20TokenNotFound, payment.tokenKey)\n\t}\n\n\t// Send the token from the owner's balance.\n\treturn token.RealmTeller(0, rlm).Transfer(0, rlm, payment.toAddress, payment.amount)\n}\n\n// Balances implements Banker.\nfunc (gb *GRC20Banker) Balances() []Balance {\n\t// Get the GRC20 tokens from the lister.\n\ttokens := gb.lister()\n\n\t// Convert GRC20 tokens to []Balance.\n\tvar balances []Balance\n\tfor key, token := range tokens {\n\t\tbalances = append(balances, Balance{\n\t\t\tDenom:  key,\n\t\t\tAmount: token.BalanceOf(gb.owner),\n\t\t})\n\t}\n\treturn balances\n}\n\n// Address implements Banker.\nfunc (gb *GRC20Banker) Address() string {\n\treturn gb.owner.String()\n}\n\n// NewGRC20BankerWithOwner creates a new GRC20Banker with the given address.\nfunc NewGRC20BankerWithOwner(owner address, lister TokenListerFunc) (*GRC20Banker, error) {\n\tif owner == \"\" {\n\t\treturn nil, ErrNoOwnerProvided\n\t}\n\n\tif lister == nil {\n\t\treturn nil, ErrNoListerProvided\n\t}\n\n\treturn \u0026GRC20Banker{\n\t\towner:  owner,\n\t\tlister: lister,\n\t}, nil\n}\n\n// grc20Payment represents a payment that is issued by a GRC20Banker.\ntype grc20Payment struct {\n\ttokenKey  string  // The key associated with the GRC20 token.\n\tamount    int64   // The amount of token to send.\n\ttoAddress address // The recipient of the payment.\n}\n\nvar _ Payment = (*grc20Payment)(nil)\n\n// BankerID implements Payment.\nfunc (grc20Payment) BankerID() string {\n\treturn GRC20Banker{}.ID()\n}\n\n// String implements Payment.\nfunc (gp grc20Payment) String() string {\n\tamount := strconv.Itoa(int(gp.amount))\n\treturn amount + gp.tokenKey + \" to \" + gp.toAddress.String()\n}\n\n// NewGRC20Payment creates a new grc20Payment.\nfunc NewGRC20Payment(tokenKey string, amount int64, toAddress address) Payment {\n\treturn grc20Payment{\n\t\ttokenKey:  tokenKey,\n\t\tamount:    amount,\n\t\ttoAddress: toAddress,\n\t}\n}\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package treasury provides treasury management for handling coin and GRC20\n// token transfers in Gno realms.\npackage treasury\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/treasury/v0\"\ngno = \"0.9\"\n"},{"name":"render.gno","body":"package treasury\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/nt/bptree/pager/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\tDefaultHistoryPreviewSize = 5  // Number of payments in the history preview.\n\tDefaultHistoryPageSize    = 20 // Number of payments per page in the history.\n)\n\n// Render renders content based on the given path.\nfunc (t *Treasury) Render(path string) string {\n\treturn t.router.Render(path)\n}\n\n// RenderLanding renders the landing page of the treasury.\nfunc (t *Treasury) RenderLanding(path string) string {\n\tvar out string\n\n\t// Render each banker.\n\tfor _, bankerID := range t.ListBankerIDs() {\n\t\tout += t.RenderBanker(bankerID, path)\n\t}\n\n\treturn out\n}\n\n// RenderBanker renders the details of a specific banker.\nfunc (t *Treasury) RenderBanker(bankerID string, path string) string {\n\t// Get the banker associated to this ID.\n\tbr := t.bankers.Get(bankerID)\n\tif br == nil {\n\t\treturn md.Paragraph(\"Banker not found: \" + md.EscapeText(bankerID))\n\t}\n\tbanker := br.(*bankerRecord).banker\n\n\t// Render banker title.\n\tout := md.H2(md.EscapeText(bankerID) + \" Banker\")\n\n\t// Render address section.\n\tout += md.H3(\"Address\")\n\tout += md.Paragraph(banker.Address())\n\n\t// Render balances section.\n\tout += md.H3(\"Balances\")\n\tbalances := banker.Balances()\n\tif len(balances) == 0 {\n\t\tout += md.Paragraph(\"No balances found.\")\n\t} else {\n\t\ttable := mdtable.Table{Headers: []string{\"Denom\", \"Amount\"}}\n\t\tfor _, balance := range balances {\n\t\t\ttable.Append([]string{balance.Denom, strconv.FormatInt(balance.Amount, 10)})\n\t\t}\n\t\tout += table.String()\n\t}\n\n\thistorySize := DefaultHistoryPreviewSize\n\n\t// Check if the query parameter \"history_size\" is present and parse it.\n\tif req, err := url.Parse(path); err == nil \u0026\u0026 req.Query() != nil {\n\t\tsize, err := strconv.Atoi(req.Query().Get(\"history_size\"))\n\t\tif err == nil \u0026\u0026 size \u003e= 0 {\n\t\t\thistorySize = size\n\t\t}\n\t}\n\n\t// Skip history rendering if historySize is 0.\n\tif historySize == 0 {\n\t\treturn out\n\t}\n\n\t// Render history section.\n\tout += md.H3(\"History\")\n\thistory, _ := t.History(bankerID, 1, historySize)\n\tif len(history) == 0 {\n\t\tout += md.Paragraph(\"No payments sent yet.\")\n\t} else {\n\t\tif len(history) == 1 {\n\t\t\tout += md.Paragraph(\"Last payment:\")\n\t\t} else {\n\t\t\tcount := strconv.FormatInt(int64(len(history)), 10)\n\t\t\tout += md.Paragraph(\"Last \" + count + \" payments:\")\n\t\t}\n\n\t\t// Render each payment in the history.\n\t\tfor _, payment := range history {\n\t\t\tout += md.BulletItem(payment.String())\n\t\t}\n\t\tout += \"\\n\"\n\n\t\t// Build the \"See full history\" link from the owning realm's\n\t\t// path captured at New() time. Skipped if no path was supplied\n\t\t// (e.g. /p/ filetests that don't exercise rendering).\n\t\tif from := strings.IndexRune(t.realmPath, '/'); from \u003e= 0 {\n\t\t\tout += md.Link(\n\t\t\t\t\"See full history\",\n\t\t\t\tufmt.Sprintf(\"%s:%s/history\", t.realmPath[from:], bankerID),\n\t\t\t)\n\t\t}\n\t}\n\n\treturn out\n}\n\n// RenderBankerHistory renders the payment history of a specific banker.\nfunc (t *Treasury) RenderBankerHistory(bankerID string, path string) string {\n\t// Get the banker record corresponding to this ID if it exists.\n\tbr := t.bankers.Get(bankerID)\n\tif br == nil {\n\t\treturn md.Paragraph(\"Banker not found: \" + md.EscapeText(bankerID))\n\t}\n\thistory := br.(*bankerRecord).history\n\n\t// Render banker history title.\n\tout := md.H2(md.EscapeText(bankerID) + \" Banker History\")\n\n\t// Get the current page of tokens based on the request path.\n\tp := pager.NewPager(history.Tree(), DefaultHistoryPageSize, true)\n\tpage, err := p.GetPageByPath(path)\n\tif err != nil {\n\t\treturn md.Paragraph(\"Error retrieving page: \" + md.EscapeText(err.Error()))\n\t}\n\n\t// Render full history section.\n\tif history.Len() == 0 {\n\t\tout += md.Paragraph(\"No payments sent yet.\")\n\t} else {\n\t\tif history.Len() == 1 {\n\t\t\tout += md.Paragraph(\"1 payment:\")\n\t\t} else {\n\t\t\tcount := strconv.FormatInt(int64(history.Len()), 10)\n\t\t\tout += md.Paragraph(count + \" payments (sorted by latest, descending):\")\n\t\t}\n\t\tfor _, item := range page.Items {\n\t\t\tout += md.BulletItem(item.Value.(Payment).String())\n\t\t}\n\t}\n\tout += \"\\n\"\n\n\t// Add the page picker.\n\tout += md.Paragraph(page.Picker(path))\n\n\treturn out\n}\n\n// initRenderRouter registers the routes for rendering the treasury pages.\nfunc (t *Treasury) initRenderRouter() {\n\tt.router = mux.NewRouter()\n\n\t// Landing page.\n\tt.router.HandleFunc(\"\", func(res *mux.ResponseWriter, req *mux.Request) {\n\t\tres.Write(t.RenderLanding(req.RawPath))\n\t})\n\n\t// Banker details.\n\tt.router.HandleFunc(\"{banker}\", func(res *mux.ResponseWriter, req *mux.Request) {\n\t\tres.Write(t.RenderBanker(req.GetVar(\"banker\"), req.RawPath))\n\t})\n\n\t// Banker full history.\n\tt.router.HandleFunc(\"{banker}/history\", func(res *mux.ResponseWriter, req *mux.Request) {\n\t\tres.Write(t.RenderBankerHistory(req.GetVar(\"banker\"), req.RawPath))\n\t})\n}\n"},{"name":"treasury.gno","body":"package treasury\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/pager/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar (\n\tErrNoBankerProvided       = errors.New(\"no banker provided\")\n\tErrDuplicateBanker        = errors.New(\"duplicate banker\")\n\tErrBankerNotFound         = errors.New(\"banker not found\")\n\tErrSendPaymentFailed      = errors.New(\"failed to send payment\")\n\tErrNonCanonicalBankerImpl = errors.New(\"non-canonical Banker impl: only *CoinsBanker / *GRC20Banker accepted\")\n)\n\n// New creates a new Treasury instance with the given bankers.\n//\n// pkgPath should be the package path of the owning realm. It is\n// captured on the Treasury and used to build the \"See full history\"\n// link in RenderBanker. Pass `cur.PkgPath()` from the owning realm's\n// init (or another live-cur context). Passing \"\" disables the link.\n//\n// The path is stored as plain data — no IsCurrent guard inside this\n// /p/ constructor. The caller is the trust boundary; it must derive\n// the value from a real `cur realm` rather than accept it from\n// untrusted input. The captured path is consumed only for render\n// output (Class-2 designation-forgery shape, accepted as\n// display-only — see docs/resources/gno-security.md).\n//\n// Each banker must be one of treasury's canonical concrete impls\n// (*CoinsBanker, *GRC20Banker) per IsCanonicalBanker. Foreign-realm impls\n// (including embedded wrappers around canonical types) are rejected: a\n// malicious Send impl would receive a capability token via its rlm\n// parameter when treasury.Send dispatches into it.\n//\n// The allowlist validates type only, not captured state. Treasury operators\n// must construct their own bankers; never accept a pre-built *Banker value\n// from an external realm.\nfunc New(bankers []Banker, pkgPath string) (*Treasury, error) {\n\tif len(bankers) == 0 {\n\t\treturn nil, ErrNoBankerProvided\n\t}\n\n\t// Canonical-impl allowlist: reject foreign types (embedding-based\n\t// bypasses fail here because type assertions are nominal).\n\tfor _, b := range bankers {\n\t\tif !IsCanonicalBanker(b) {\n\t\t\treturn nil, ErrNonCanonicalBankerImpl\n\t\t}\n\t}\n\n\t// Create a new Treasury instance.\n\ttreasury := \u0026Treasury{bankers: bptree.NewBPTree32(), realmPath: pkgPath}\n\n\t// Register the bankers.\n\tfor _, banker := range bankers {\n\t\tif treasury.bankers.Has(banker.ID()) {\n\t\t\treturn nil, ufmt.Errorf(\"%v: %s\", ErrDuplicateBanker, banker.ID())\n\t\t}\n\n\t\ttreasury.bankers.Set(\n\t\t\tbanker.ID(),\n\t\t\t\u0026bankerRecord{banker: banker},\n\t\t)\n\t}\n\n\t// Register the Render routes.\n\ttreasury.initRenderRouter()\n\n\treturn treasury, nil\n}\n\n// Send sends a payment using the corresponding banker. rlm is threaded\n// to the banker's Send for IsCurrent + owner validation.\nfunc (t *Treasury) Send(_ int, rlm realm, p Payment) error {\n\t// Get the banker record corresponding to this Payment.\n\tbr := t.bankers.Get(p.BankerID())\n\tif br == nil {\n\t\treturn ufmt.Errorf(\"%v: %s\", ErrBankerNotFound, p.BankerID())\n\t}\n\trecord := br.(*bankerRecord)\n\n\t// Send the payment using the corresponding banker.\n\tif err := record.banker.Send(0, rlm, p); err != nil {\n\t\treturn ufmt.Errorf(\"%v: %s\", ErrSendPaymentFailed, err)\n\t}\n\n\t// Add the payment to the history of the banker.\n\trecord.history.Append(p)\n\n\treturn nil\n}\n\n// History returns the payment history sent by the banker with the given ID.\n// Payments are paginated, with the most recent payments first.\nfunc (t *Treasury) History(\n\tbankerID string,\n\tpageNumber int,\n\tpageSize int,\n) ([]Payment, error) {\n\t// Get the banker record corresponding to this ID.\n\tbr := t.bankers.Get(bankerID)\n\tif br == nil {\n\t\treturn nil, ufmt.Errorf(\"%v: %s\", ErrBankerNotFound, bankerID)\n\t}\n\thistory := br.(*bankerRecord).history\n\n\t// Get the page of payments from the history.\n\tp := pager.NewPager(history.Tree(), pageSize, true)\n\tpage := p.GetPage(pageNumber)\n\n\t// Convert the items in the page to a slice of Payments.\n\tpayments := make([]Payment, len(page.Items))\n\tfor i := range page.Items {\n\t\tpayments[i] = page.Items[i].Value.(Payment)\n\t}\n\n\treturn payments, nil\n}\n\n// Balances returns the balances of the banker with the given ID.\nfunc (t *Treasury) Balances(bankerID string) ([]Balance, error) {\n\t// Get the banker record corresponding to this ID.\n\tbr := t.bankers.Get(bankerID)\n\tif br == nil {\n\t\treturn nil, ufmt.Errorf(\"%v: %s\", ErrBankerNotFound, bankerID)\n\t}\n\n\t// Get the balances from the banker.\n\treturn br.(*bankerRecord).banker.Balances(), nil\n}\n\n// Address returns the address of the banker with the given ID.\nfunc (t *Treasury) Address(bankerID string) (string, error) {\n\t// Get the banker record corresponding to this ID.\n\tbr := t.bankers.Get(bankerID)\n\tif br == nil {\n\t\treturn \"\", ufmt.Errorf(\"%v: %s\", ErrBankerNotFound, bankerID)\n\t}\n\n\t// Get the address from the banker.\n\treturn br.(*bankerRecord).banker.Address(), nil\n}\n\n// HasBanker checks if a banker with the given ID is registered.\nfunc (t *Treasury) HasBanker(bankerID string) bool {\n\treturn t.bankers.Has(bankerID)\n}\n\n// ListBankerIDs returns a list of all registered banker IDs.\nfunc (t *Treasury) ListBankerIDs() []string {\n\tvar bankerIDs []string\n\n\tt.bankers.Iterate(\"\", \"\", func(bankerID string, _ any) bool {\n\t\tbankerIDs = append(bankerIDs, bankerID)\n\t\treturn false\n\t})\n\n\treturn bankerIDs\n}\n"},{"name":"types.gno","body":"package treasury\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/list/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n)\n\n// Treasury is the main structure that holds all bankers and their payment\n// history. It also provides a router for rendering the treasury pages.\ntype Treasury struct {\n\tbankers   *bptree.BPTree // string -\u003e *bankerRecord\n\trouter    *mux.Router\n\trealmPath string // owning realm's PkgPath, captured at New() (used for render links)\n}\n\n// bankerRecord holds a Banker and its payment history.\ntype bankerRecord struct {\n\tbanker  Banker\n\thistory list.List // List of Payment.\n}\n\n// Banker is an interface that allows for banking operations.\n//\n// SECURITY: Send takes (int, realm, Payment), so handing a Banker value to\n// untrusted code yields a capability token to whatever Send impl that code\n// dispatches into. The set of canonical impls is closed (*CoinsBanker,\n// *GRC20Banker); any public function that accepts a Banker as a parameter\n// from external callers MUST verify it via IsCanonicalBanker and reject\n// otherwise. treasury.New enforces this for its own intake; future\n// Banker-accepting APIs must do the same. An unexported-marker \"seal\" does\n// NOT defend against this — see\n// p/test/seal/filetests/z_seal_iface_embedding_filetest.gno.\n//\n// Note that IsCanonicalBanker validates dynamic TYPE only, not captured\n// STATE: a canonical *CoinsBanker constructed via NewCoinsBankerWithOwner\n// with a hostile owner argument passes the allowlist but its read methods\n// (Balances, Address) report data tied to that hostile address. Treasury\n// operators must construct their own bankers and NEVER accept pre-built\n// *Banker values from external realms.\ntype Banker interface {\n\tID() string                     // Get the ID of the banker.\n\tSend(int, realm, Payment) error // Send a payment to a recipient.\n\tBalances() []Balance            // Get the balances of the banker.\n\tAddress() string                // Get the address of the banker to receive payments.\n}\n\n// IsCanonicalBanker reports whether b is one of treasury's canonical\n// concrete Banker impls. Use this at any public entry point in /p/ or /r/\n// that accepts a Banker from an external caller before invoking its methods.\n//\n// Foreign types — including embedding-based wrappers like\n// `type Evil struct { *CoinsBanker }` — are rejected because type assertions\n// are nominal: *Evil is not *CoinsBanker, regardless of method promotion.\n//\n// To add a new canonical type: extend the switch below AND add a regression\n// test (under filetests/ in this package) that an embedded-impl bypass is\n// rejected.\n//\n// Mirrors the precedent of chain/banker.IsCanonical and\n// p/jaekwon/allowancesender's canonical-impl check.\nfunc IsCanonicalBanker(b Banker) bool {\n\tswitch b.(type) {\n\tcase *CoinsBanker, *GRC20Banker:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// Payment is an interface that allows getting details about a payment.\ntype Payment interface {\n\tBankerID() string // Get the ID of the banker that can process this payment.\n\tString() string   // Get a string representation of the payment.\n}\n\n// IsCanonicalPayment reports whether p is one of treasury's canonical concrete\n// Payment impls. Use this at any public entry point that accepts a Payment\n// from an external caller and shows it to a human before it is processed.\n//\n// The immutability the constructors provide is a property of these two types,\n// not of the interface: a foreign impl's String() says whatever its realm\n// likes, and no Banker will process it, because Banker.Send type-asserts and\n// so fails only at execution — after a vote has been spent on it.\n//\n// Only the value types are listed, deliberately. Banker.Send asserting\n// p.(coinsPayment) is what makes this check meaningful, so accepting\n// *coinsPayment would pass a payment that still fails at execution.\n//\n// To add a new canonical type: extend the switch below AND add a regression\n// test (under filetests/ in this package) that a foreign impl is rejected.\n//\n// Mirrors IsCanonicalBanker above.\nfunc IsCanonicalPayment(p Payment) bool {\n\tswitch p.(type) {\n\tcase coinsPayment, grc20Payment:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// Balance represents the balance of an asset held by a Banker.\ntype Balance struct {\n\tDenom  string // The denomination of the asset\n\tAmount int64  // The amount of the asset\n}\n\n// Common Banker errors.\nvar (\n\tErrCurrentRealmIsNotOwner = errors.New(\"current realm is not the owner of the banker\")\n\tErrNoOwnerProvided        = errors.New(\"no owner provided\")\n\tErrInvalidPaymentType     = errors.New(\"invalid payment type\")\n\tErrSpoofedRealm           = errors.New(\"rlm does not match the current crossing frame\")\n)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"svg","path":"gno.land/p/nt/svg/v0","files":[{"name":"doc.gno","body":"/*\nPackage svg is a minimalist and extensible SVG generation library for Gno.\n\nIt provides a structured way to create and compose SVG elements such as rectangles, circles, text, paths, and more. The package is designed to be modular and developer-friendly, enabling optional attributes and method chaining for ease of use.\n\nEach SVG element embeds a BaseAttrs struct, which supports common SVG attributes like `id`, `class`, `style`, `fill`, `stroke`, and `transform`.\n\nCanvas objects represent the root SVG container and support global dimensions, viewBox configuration, embedded styles, and element composition.\n\nExample:\n\n\timport \"gno.land/p/nt/svg/v0\"\n\n\tfunc Foo() string {\n\t\tcanvas := svg.NewCanvas(200, 200).WithViewBox(0, 0, 200, 200)\n\t\tcanvas.AddStyle(\".my-rect\", \"stroke:black;stroke-width:2\")\n\t\tcanvas.Append(\n\t\t\tsvg.NewRectangle(60, 40, 100, 50, \"red\").WithClass(\"my-rect\"),\n\t\t\tsvg.NewCircle(50, 80, 40, \"blue\"),\n\t\t\t\u0026svg.Path{D: `M 10,30\n\t\t\tA 20,20 0,0,1 50,30\n\t\t\t\tA 20,20 0,0,1  90,30\n\t\t\t\tQ 90,60 50,90\n\t\t\t\tQ 10,60 10,30 z`, Fill: \"magenta\"},\n\t\t\tsvg.NewText(20, 50, \"Hello SVG\", \"black\"),\n\t\t)\n\t\tmysvg := canvas.Base64()\n\t}\n*/\npackage svg // import \"gno.land/p/nt/svg/v0\"\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/svg/v0\"\ngno = \"0.9\"\n"},{"name":"svg.gno","body":"package svg\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype Canvas struct {\n\tWidth, Height int\n\tViewBox       string\n\tElems         []Elem\n\tStyle         *avl.Tree\n}\n\ntype Elem interface{ String() string }\n\nfunc NewCanvas(width, height int) *Canvas {\n\treturn \u0026Canvas{\n\t\tWidth:  width,\n\t\tHeight: height,\n\t\tStyle:  nil,\n\t}\n}\n\nfunc (c *Canvas) AddStyle(key, value string) *Canvas {\n\tif c.Style == nil {\n\t\tc.Style = avl.NewTree()\n\t}\n\tc.Style.Set(key, value)\n\treturn c\n}\n\nfunc (c *Canvas) WithViewBox(x, y, width, height int) *Canvas {\n\tc.ViewBox = ufmt.Sprintf(\"%d %d %d %d\", x, y, width, height)\n\treturn c\n}\n\n// Render renders your canvas\nfunc (c Canvas) Render(alt string) string {\n\tbase64SVG := base64.StdEncoding.EncodeToString([]byte(c.String()))\n\treturn ufmt.Sprintf(\"![%s](data:image/svg+xml;base64,%s)\", alt, base64SVG)\n}\n\nfunc (c Canvas) String() string {\n\tout := \"\"\n\tout += ufmt.Sprintf(`\u003csvg xmlns=\"http://www.w3.org/2000/svg\" width=\"%d\" height=\"%d\" viewBox=\"%s\"\u003e`, c.Width, c.Height, c.ViewBox)\n\tif c.Style != nil {\n\t\tout += \"\u003cstyle\u003e\"\n\t\tc.Style.Iterate(\"\", \"\", func(k string, val interface{}) bool {\n\t\t\tv := val.(string)\n\t\t\tout += ufmt.Sprintf(\"%s{%s}\", k, v)\n\t\t\treturn false\n\t\t})\n\t\tout += \"\u003c/style\u003e\"\n\t}\n\tfor _, elem := range c.Elems {\n\t\tout += elem.String()\n\t}\n\tout += \"\u003c/svg\u003e\"\n\treturn out\n}\n\nfunc (c Canvas) Base64() string {\n\tout := c.String()\n\treturn base64.StdEncoding.EncodeToString([]byte(out))\n}\n\nfunc (c *Canvas) Append(elem ...Elem) {\n\tc.Elems = append(c.Elems, elem...)\n}\n\ntype BaseAttrs struct {\n\tID          string\n\tClass       string\n\tStyle       string\n\tStroke      string\n\tStrokeWidth string\n\tOpacity     string\n\tTransform   string\n\tVisibility  string\n}\n\nfunc (b BaseAttrs) String() string {\n\tvar elems []string\n\n\tif b.ID != \"\" {\n\t\telems = append(elems, `id=\"`+b.ID+`\"`)\n\t}\n\tif b.Class != \"\" {\n\t\telems = append(elems, `class=\"`+b.Class+`\"`)\n\t}\n\tif b.Style != \"\" {\n\t\telems = append(elems, `style=\"`+b.Style+`\"`)\n\t}\n\tif b.Stroke != \"\" {\n\t\telems = append(elems, `stroke=\"`+b.Stroke+`\"`)\n\t}\n\tif b.StrokeWidth != \"\" {\n\t\telems = append(elems, `stroke-width=\"`+b.StrokeWidth+`\"`)\n\t}\n\tif b.Opacity != \"\" {\n\t\telems = append(elems, `opacity=\"`+b.Opacity+`\"`)\n\t}\n\tif b.Transform != \"\" {\n\t\telems = append(elems, `transform=\"`+b.Transform+`\"`)\n\t}\n\tif b.Visibility != \"\" {\n\t\telems = append(elems, `visibility=\"`+b.Visibility+`\"`)\n\t}\n\tif len(elems) == 0 {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(elems, \" \")\n}\n\ntype Circle struct {\n\tCX   int // center X\n\tCY   int // center Y\n\tR    int // radius\n\tFill string\n\tAttr BaseAttrs\n}\n\nfunc (c Circle) String() string {\n\treturn ufmt.Sprintf(`\u003ccircle cx=\"%d\" cy=\"%d\" r=\"%d\" fill=\"%s\" %s/\u003e`, c.CX, c.CY, c.R, c.Fill, c.Attr.String())\n}\n\nfunc NewCircle(cx, cy, r int, fill string) *Circle {\n\treturn \u0026Circle{\n\t\tCX:   cx,\n\t\tCY:   cy,\n\t\tR:    r,\n\t\tFill: fill,\n\t}\n}\n\nfunc (c *Circle) WithClass(class string) *Circle {\n\tc.Attr.Class = class\n\treturn c\n}\n\ntype Ellipse struct {\n\tCX   int // center X\n\tCY   int // center Y\n\tRX   int // radius X\n\tRY   int // radius Y\n\tFill string\n\tAttr BaseAttrs\n}\n\nfunc (e Ellipse) String() string {\n\treturn ufmt.Sprintf(`\u003cellipse cx=\"%d\" cy=\"%d\" rx=\"%d\" ry=\"%d\" fill=\"%s\" %s/\u003e`, e.CX, e.CY, e.RX, e.RY, e.Fill, e.Attr.String())\n}\n\nfunc NewEllipse(cx, cy int, fill string) *Ellipse {\n\treturn \u0026Ellipse{\n\t\tCX:   cx,\n\t\tCY:   cy,\n\t\tFill: fill,\n\t}\n}\n\nfunc (e *Ellipse) WithClass(class string) *Ellipse {\n\te.Attr.Class = class\n\treturn e\n}\n\ntype Rectangle struct {\n\tX, Y, Width, Height int\n\tRX, RY              int // corner radiuses\n\tFill                string\n\tAttr                BaseAttrs\n}\n\nfunc (r Rectangle) String() string {\n\treturn ufmt.Sprintf(`\u003crect x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" rx=\"%d\" ry=\"%d\" fill=\"%s\" %s/\u003e`, r.X, r.Y, r.Width, r.Height, r.RX, r.RY, r.Fill, r.Attr.String())\n}\n\nfunc NewRectangle(x, y, width, height int, fill string) *Rectangle {\n\treturn \u0026Rectangle{\n\t\tX:      x,\n\t\tY:      y,\n\t\tWidth:  width,\n\t\tHeight: height,\n\t\tFill:   fill,\n\t}\n}\n\nfunc (r *Rectangle) WithClass(class string) *Rectangle {\n\tr.Attr.Class = class\n\treturn r\n}\n\ntype Path struct {\n\tD    string\n\tFill string\n\tAttr BaseAttrs\n}\n\nfunc (p Path) String() string {\n\treturn ufmt.Sprintf(`\u003cpath d=\"%s\" fill=\"%s\" %s/\u003e`, p.D, p.Fill, p.Attr.String())\n}\n\nfunc NewPath(d, fill string) *Path {\n\treturn \u0026Path{\n\t\tD:    d,\n\t\tFill: fill,\n\t}\n}\n\nfunc (p *Path) WithClass(class string) *Path {\n\tp.Attr.Class = class\n\treturn p\n}\n\ntype Polygon struct { // closed shape\n\tPoints string\n\tFill   string\n\tAttr   BaseAttrs\n}\n\nfunc (p Polygon) String() string {\n\treturn ufmt.Sprintf(`\u003cpolygon points=\"%s\" fill=\"%s\" %s/\u003e`, p.Points, p.Fill, p.Attr.String())\n}\n\nfunc NewPolygon(points, fill string) *Polygon {\n\treturn \u0026Polygon{\n\t\tPoints: points,\n\t\tFill:   fill,\n\t}\n}\n\nfunc (p *Polygon) WithClass(class string) *Polygon {\n\tp.Attr.Class = class\n\treturn p\n}\n\ntype Polyline struct { // polygon but not necessarily closed\n\tPoints string\n\tFill   string\n\tAttr   BaseAttrs\n}\n\nfunc (p Polyline) String() string {\n\treturn ufmt.Sprintf(`\u003cpolyline points=\"%s\" fill=\"%s\" %s/\u003e`, p.Points, p.Fill, p.Attr.String())\n}\n\nfunc NewPolyline(points, fill string) *Polyline {\n\treturn \u0026Polyline{\n\t\tPoints: points,\n\t\tFill:   fill,\n\t}\n}\n\nfunc (p *Polyline) WithClass(class string) *Polyline {\n\tp.Attr.Class = class\n\treturn p\n}\n\ntype Text struct {\n\tX, Y       int\n\tDX, DY     int // shift text pos horizontally/ vertically\n\tRotate     string\n\tText, Fill string\n\tAttr       BaseAttrs\n}\n\nfunc (c Text) String() string {\n\treturn ufmt.Sprintf(`\u003ctext x=\"%d\" y=\"%d\" dx=\"%d\" dy=\"%d\" rotate=\"%s\" fill=\"%s\" %s\u003e%s\u003c/text\u003e`, c.X, c.Y, c.DX, c.DY, c.Rotate, c.Fill, c.Attr.String(), c.Text)\n}\n\nfunc NewText(x, y int, text, fill string) *Text {\n\treturn \u0026Text{\n\t\tX:    x,\n\t\tY:    y,\n\t\tText: text,\n\t\tFill: fill,\n\t}\n}\n\nfunc (c *Text) WithClass(class string) *Text {\n\tc.Attr.Class = class\n\treturn c\n}\n\ntype Group struct {\n\tElems []Elem\n\tFill  string\n\tAttr  BaseAttrs\n}\n\nfunc (g Group) String() string {\n\tout := \"\"\n\tfor _, e := range g.Elems {\n\t\tout += e.String()\n\t}\n\treturn ufmt.Sprintf(`\u003cg fill=\"%s\" %s\u003e%s\u003c/g\u003e`, g.Fill, g.Attr.String(), out)\n}\n\nfunc NewGroup(fill string) *Group {\n\treturn \u0026Group{\n\t\tFill: fill,\n\t}\n}\n\nfunc (g *Group) Append(elem ...Elem) {\n\tg.Elems = append(g.Elems, elem...)\n}\n\nfunc (g *Group) WithClass(class string) *Group {\n\tg.Attr.Class = class\n\treturn g\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"md","path":"gno.land/p/sunspirit/md/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/sunspirit/md/v0\"\ngno = \"0.9\"\n"},{"name":"md.gno","body":"package md\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Builder helps to build a Markdown string from individual elements\ntype Builder struct {\n\telements []string\n}\n\n// NewBuilder creates a new Builder instance\nfunc NewBuilder() *Builder {\n\treturn \u0026Builder{}\n}\n\n// Add adds a Markdown element to the builder\nfunc (m *Builder) Add(md ...string) *Builder {\n\tm.elements = append(m.elements, md...)\n\treturn m\n}\n\n// Render returns the final Markdown string joined with the specified separator\nfunc (m *Builder) Render(separator string) string {\n\treturn strings.Join(m.elements, separator)\n}\n\n// Bold returns bold text for markdown\nfunc Bold(text string) string {\n\treturn ufmt.Sprintf(\"**%s**\", text)\n}\n\n// Italic returns italicized text for markdown\nfunc Italic(text string) string {\n\treturn ufmt.Sprintf(\"*%s*\", text)\n}\n\n// Strikethrough returns strikethrough text for markdown\nfunc Strikethrough(text string) string {\n\treturn ufmt.Sprintf(\"~~%s~~\", text)\n}\n\n// H1 returns a level 1 header for markdown\nfunc H1(text string) string {\n\treturn ufmt.Sprintf(\"# %s\\n\", text)\n}\n\n// H2 returns a level 2 header for markdown\nfunc H2(text string) string {\n\treturn ufmt.Sprintf(\"## %s\\n\", text)\n}\n\n// H3 returns a level 3 header for markdown\nfunc H3(text string) string {\n\treturn ufmt.Sprintf(\"### %s\\n\", text)\n}\n\n// H4 returns a level 4 header for markdown\nfunc H4(text string) string {\n\treturn ufmt.Sprintf(\"#### %s\\n\", text)\n}\n\n// H5 returns a level 5 header for markdown\nfunc H5(text string) string {\n\treturn ufmt.Sprintf(\"##### %s\\n\", text)\n}\n\n// H6 returns a level 6 header for markdown\nfunc H6(text string) string {\n\treturn ufmt.Sprintf(\"###### %s\\n\", text)\n}\n\n// BulletList returns an bullet list for markdown\nfunc BulletList(items []string) string {\n\tvar sb strings.Builder\n\tfor _, item := range items {\n\t\tsb.WriteString(ufmt.Sprintf(\"- %s\\n\", item))\n\t}\n\treturn sb.String()\n}\n\n// OrderedList returns an ordered list for markdown\nfunc OrderedList(items []string) string {\n\tvar sb strings.Builder\n\tfor i, item := range items {\n\t\tsb.WriteString(ufmt.Sprintf(\"%d. %s\\n\", i+1, item))\n\t}\n\treturn sb.String()\n}\n\n// TodoList returns a list of todo items with checkboxes for markdown\nfunc TodoList(items []string, done []bool) string {\n\tvar sb strings.Builder\n\n\tfor i, item := range items {\n\t\tcheckbox := \" \"\n\t\tif done[i] {\n\t\t\tcheckbox = \"x\"\n\t\t}\n\t\tsb.WriteString(ufmt.Sprintf(\"- [%s] %s\\n\", checkbox, item))\n\t}\n\treturn sb.String()\n}\n\n// Blockquote returns a blockquote for markdown\nfunc Blockquote(text string) string {\n\tlines := strings.Split(text, \"\\n\")\n\tvar sb strings.Builder\n\tfor _, line := range lines {\n\t\tsb.WriteString(ufmt.Sprintf(\"\u003e %s\\n\", line))\n\t}\n\n\treturn sb.String()\n}\n\n// InlineCode returns inline code for markdown\nfunc InlineCode(code string) string {\n\treturn ufmt.Sprintf(\"`%s`\", code)\n}\n\n// CodeBlock creates a markdown code block\nfunc CodeBlock(content string) string {\n\treturn ufmt.Sprintf(\"```\\n%s\\n```\", content)\n}\n\n// LanguageCodeBlock creates a markdown code block with language-specific syntax highlighting\nfunc LanguageCodeBlock(language, content string) string {\n\treturn ufmt.Sprintf(\"```%s\\n%s\\n```\", language, content)\n}\n\n// LineBreak returns the specified number of line breaks for markdown\nfunc LineBreak(count uint) string {\n\tif count \u003e 0 {\n\t\treturn strings.Repeat(\"\\n\", int(count)+1)\n\t}\n\treturn \"\"\n}\n\n// HorizontalRule returns a horizontal rule for markdown\nfunc HorizontalRule() string {\n\treturn \"---\\n\"\n}\n\n// Link returns a hyperlink for markdown\nfunc Link(text, url string) string {\n\treturn ufmt.Sprintf(\"[%s](%s)\", text, url)\n}\n\n// Image returns an image for markdown\nfunc Image(altText, url string) string {\n\treturn ufmt.Sprintf(\"![%s](%s)\", altText, url)\n}\n\n// Footnote returns a footnote for markdown\nfunc Footnote(reference, text string) string {\n\treturn ufmt.Sprintf(\"[%s]: %s\", reference, text)\n}\n\n// Paragraph wraps the given text in a Markdown paragraph\nfunc Paragraph(content string) string {\n\treturn ufmt.Sprintf(\"%s\\n\", content)\n}\n\n// MdTable is an interface for table types that can be converted to Markdown format\ntype MdTable interface {\n\tString() string\n}\n\n// Table takes any MdTable implementation and returns its markdown representation\nfunc Table(table MdTable) string {\n\treturn table.String()\n}\n\n// EscapeMarkdown escapes special markdown characters in a string\nfunc EscapeMarkdown(text string) string {\n\treturn ufmt.Sprintf(\"``%s``\", text)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"piechart","path":"gno.land/p/samcrew/piechart/v0","files":[{"name":"README.md","body":"# `piechart` - SVG pie charts \n\nGenerate pie charts with legends as SVG markup for gnoweb rendering.\n\n## Usage\n\n```go\nslices := []piechart.PieSlice{\n    {Value: 30, Color: \"#ff6b6b\", Label: \"Frontend\"},\n    {Value: 25, Color: \"#4ecdc4\", Label: \"Backend\"},\n    {Value: 20, Color: \"#45b7d1\", Label: \"DevOps\"},\n    {Value: 15, Color: \"#96ceb4\", Label: \"Mobile\"},\n    {Value: 10, Color: \"#ffeaa7\", Label: \"Other\"},\n}\n\n// With title\ntitledChart := piechart.Render(slices, \"Team Distribution\")\n\n// Without title  \nuntitledChart := piechart.Render(slices, \"\")\n```\n\n## API Reference\n\n```go\ntype PieSlice struct {\n    Value float64 // Numeric value for the slice\n    Color string  // Hex color code (e.g., \"#ff6b6b\")\n    Label string  // Display label for the slice\n}\n\n// slices: Array of PieSlice structs containing the data\n// title: Chart title (empty string for no title)\n// Returns: SVG markup as a string\nfunc Render(slices []PieSlice, title string) string\n```\n\n## Live Example\n\n- [/r/docs/charts:piechart](/r/docs/charts:piechart)\n- [/r/samcrew/daodemo/custom_condition:members](/r/samcrew/daodemo/custom_condition:members)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/samcrew/piechart/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1kfd9f5zlvcvy6aammcmqswa7cyjpu2nyt9qfen\"\n"},{"name":"piechart.gno","body":"// Package piechart provides functionality to render a pie chart as an SVG image.\n// It takes a list of PieSlice objects, each representing a slice of the pie with a value,\n// color, and label, and generates an SVG representation of the pie chart.\npackage piechart\n\nimport (\n\t\"math\"\n\n\t\"gno.land/p/nt/svg/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/sunspirit/md/v0\"\n)\n\ntype PieSlice struct {\n\tValue float64\n\tColor string\n\tLabel string\n}\n\n// Render creates an SVG pie chart from given slices (value, color and label).\n// It returns an img svg markup as a string, including a markdown header if a non-empty title is provided.\nfunc Render(slices []PieSlice, title string) string {\n\t// Validate input slices length\n\tif len(slices) == 0 {\n\t\treturn \"\\npiechart fails: no data provided\"\n\t}\n\n\tconst (\n\t\tcanvasWidth  = 500\n\t\tcanvasHeight = 200\n\t\tcenterX      = 100.0\n\t\tcenterY      = 100.0\n\t\tradius       = 80.0\n\t\tlegendX      = 210\n\t\tlegendStartY = 30\n\t\tlineHeight   = 26\n\t\tsquareSize   = 16\n\t\tfontSize     = 16\n\t)\n\n\tcanvas := svg.NewCanvas(canvasWidth, canvasHeight)\n\n\t// Sum all values to compute slices proportions\n\tvar total float64\n\tfor _, s := range slices {\n\t\ttotal += s.Value\n\t}\n\n\t// Draw pie slices and legend in one pass\n\tstartAngle := -math.Pi / 2\n\tfor i, s := range slices {\n\t\tif s.Value \u003e 0 {\n\t\t\t// --- PIE SLICE ---\n\t\t\t// Calculate angle span for current slice\n\t\t\tangle := (s.Value / total) * 2 * math.Pi\n\t\t\tendAngle := startAngle + angle\n\n\t\t\t// Compute start and end points on the circle circumference\n\t\t\tcosStart, sinStart := math.Cos(startAngle), math.Sin(startAngle)\n\t\t\tcosEnd, sinEnd := math.Cos(endAngle), math.Sin(endAngle)\n\t\t\tx1 := centerX + radius*cosStart\n\t\t\ty1 := centerY + radius*sinStart\n\t\t\tx2 := centerX + radius*cosEnd\n\t\t\ty2 := centerY + radius*sinEnd\n\n\t\t\t// Determine if the arc should be a large arc (\u003e 180 degrees) (Arc direction)\n\t\t\tlargeArcFlag := 0\n\t\t\tif angle \u003e math.Pi {\n\t\t\t\tlargeArcFlag = 1\n\t\t\t}\n\n\t\t\t// Build the SVG path for the pie slice\n\t\t\tpath := ufmt.Sprintf(\n\t\t\t\t\"M%.2f,%.2f L%.2f,%.2f A%.2f,%.2f 0 %d 1 %.2f,%.2f Z\",\n\t\t\t\tcenterX, centerY, x1, y1, radius, radius, largeArcFlag, x2, y2,\n\t\t\t)\n\n\t\t\t// Colored slice\n\t\t\tcanvas.Append(svg.Path{\n\t\t\t\tD:    path,\n\t\t\t\tFill: s.Color,\n\t\t\t})\n\n\t\t\tstartAngle = endAngle\n\t\t}\n\n\t\t// --- LEGEND ---\n\t\ty := legendStartY + i*lineHeight\n\t\t// Colored square representing slice color\n\t\tcanvas.Append(svg.Rectangle{\n\t\t\tX:      legendX,\n\t\t\tY:      y - squareSize/2,\n\t\t\tWidth:  squareSize,\n\t\t\tHeight: squareSize,\n\t\t\tFill:   s.Color,\n\t\t})\n\n\t\t// Legend text showing label, value and percentage\n\t\ttext := ufmt.Sprintf(\"%s: %.0f (%.1f%%)\", s.Label, s.Value, s.Value*100/total)\n\t\tcanvas.Append(svg.Text{\n\t\t\tX:    legendX + squareSize + 8,\n\t\t\tY:    y + fontSize/3,\n\t\t\tText: text,\n\t\t\tFill: \"#54595D\",\n\t\t\tAttr: svg.BaseAttrs{\n\t\t\t\tStyle: ufmt.Sprintf(\"font-family:'Inter var',sans-serif;font-size:%dpx;\", fontSize),\n\t\t\t},\n\t\t})\n\t}\n\n\tif title == \"\" {\n\t\treturn canvas.Render(\"Pie Chart\")\n\t}\n\treturn md.H2(title) + canvas.Render(\"Pie Chart \"+title)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"md","path":"gno.land/p/mason/md/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/mason/md/v0\"\ngno = \"0.9\"\n"},{"name":"md.gno","body":"package md\n\nimport (\n\t\"strings\"\n)\n\ntype MD struct {\n\telements []string\n}\n\nfunc New() *MD {\n\treturn \u0026MD{elements: []string{}}\n}\n\nfunc (m *MD) H1(text string) {\n\tm.elements = append(m.elements, \"# \"+text)\n}\n\nfunc (m *MD) H3(text string) {\n\tm.elements = append(m.elements, \"### \"+text)\n}\n\nfunc (m *MD) P(text string) {\n\tm.elements = append(m.elements, text)\n}\n\nfunc (m *MD) Code(text string) {\n\tm.elements = append(m.elements, \"  ```\\n\"+text+\"\\n```\\n\")\n}\n\nfunc (m *MD) Im(path string, caption string) {\n\tm.elements = append(m.elements, \"![\"+caption+\"](\"+path+\" \\\"\"+caption+\"\\\")\")\n}\n\nfunc (m *MD) Bullet(point string) {\n\tm.elements = append(m.elements, \"- \"+point)\n}\n\nfunc Link(text, url string, title ...string) string {\n\tif len(title) \u003e 0 \u0026\u0026 title[0] != \"\" {\n\t\treturn \"[\" + text + \"](\" + url + \" \\\"\" + title[0] + \"\\\")\"\n\t}\n\treturn \"[\" + text + \"](\" + url + \")\"\n}\n\nfunc (m *MD) Render() string {\n\treturn strings.Join(m.elements, \"\\n\\n\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"tablesort","path":"gno.land/p/samcrew/tablesort/v0","files":[{"name":"README.md","body":"# `tablesort` - Sortable markdown tables\n\nGenerate sortable markdown tables with clickable column headers. Sorting state is managed via URL query parameters.\n\n## Usage\n\n```go\nimport \"gno.land/p/samcrew/tablesort/v0\"\n\ntable := \u0026tablesort.Table{\n    Headings: []string{\"Name\", \"Age\", \"City\"},\n    Rows: [][]string{\n        {\"Alice\", \"25\", \"New York\"},\n        {\"Bob\", \"30\", \"London\"},\n        {\"Charlie\", \"22\", \"Paris\"},\n    },\n}\n\n// Basic usage\nu, _ := url.Parse(\"/users\")\nmarkdown := tablesort.Render(u, table, \"\")\n\n// Multiple tables on same page (use prefix to avoid conflicts)\nmarkdown1 := tablesort.Render(u, table, \"table1-\")\nmarkdown2 := tablesort.Render(u, table, \"table2-\")\n```\n\n## On-chain Example\n\n- [/r/gov/dao/memberstore/v0:members?filter=T1](/r/gov/dao/memberstore/v0:members?filter=T1)\n\n## API\n\n```go\ntype Table struct {\n    Headings []string   // Column headers\n    Rows     [][]string // Table data rows\n}\n\n// `u`: Current URL for generating sort links\n// `table`: Table data structure\n// `paramPrefix`: Prefix for URL params (use for multiple tables)\nfunc Render(u *url.URL, table *Table, paramPrefix string) string\n```\n\n**URL Parameters:**\n- `{prefix}sort-asc={column}`: Sort column ascending\n- `{prefix}sort-desc={column}`: Sort column descending\n\n**URL Examples:**\n- `/users?sort-desc=Name` - Sort by Name descending\n- `/page?users-sort-asc=Age\u0026orders-sort-desc=Total` - Multiple tables\n\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/samcrew/tablesort/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1kfd9f5zlvcvy6aammcmqswa7cyjpu2nyt9qfen\"\n"},{"name":"render.gno","body":"package tablesort\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gno.land/p/mason/md/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Table holds the headings and rows for rendering.\n// Each row must have the same number of cells as there are headings.\ntype Table struct {\n\tHeadings []string   // [\"A\", \"B\", \"C\"]\n\tRows     [][]string // [[\"a1\",\"b1\",\"c1\"], [\"a2\",\"b2\",\"c2\"], ...]\n}\n\n// Render generates a Markdown table from a Table struct with sortable columns based on URL params.\n// paramPrefix is an optional prefix for in the URL to identify the tablesort Renders (e.g. \"members-\").\nfunc Render(u *url.URL, table *Table, paramPrefix string) string {\n\tdirection := \"\"\n\tcurrentHeading := \"\"\n\tif h := u.Query().Get(paramPrefix + \"sort-asc\"); h != \"\" {\n\t\tdirection = \"asc\"\n\t\tcurrentHeading = h\n\t} else if h := u.Query().Get(paramPrefix + \"sort-desc\"); h != \"\" {\n\t\tdirection = \"desc\"\n\t\tcurrentHeading = h\n\t}\n\n\tvar sb strings.Builder\n\n\t// Find the index of the column to sort\n\tcolIndex := -1\n\tfor i, h := range table.Headings {\n\t\tif h == currentHeading {\n\t\t\tcolIndex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Sort rows if necessary\n\tif colIndex != -1 {\n\t\tSortRows(table.Rows, colIndex, direction == \"asc\")\n\t}\n\n\t// Build header\n\tsb.WriteString(buildHeader(u, table.Headings, currentHeading, direction, paramPrefix))\n\tsb.WriteString(\"\\n\")\n\n\tnumCols := len(table.Headings)\n\n\t// Build rows\n\tfor i, row := range table.Rows {\n\t\t// Validate row length\n\t\tif len(row) != numCols {\n\t\t\treturn \"tablesort fails: row \" + ufmt.Sprintf(\"%d\", i+1) + \" has \" +\n\t\t\t\tufmt.Sprintf(\"%d\", len(row)) + \" cells, expected \" +\n\t\t\t\tufmt.Sprintf(\"%d\", numCols) + \", because there are \" + ufmt.Sprintf(\"%d\", numCols) + \" columns.\\n\"\n\t\t}\n\n\t\tsb.WriteString(\"|\")\n\t\tfor _, cell := range row {\n\t\t\tsb.WriteString(\" \" + cell + \" |\")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\n\treturn sb.String()\n}\n\n// buildHeader builds the Markdown header row with clickable links and arrows\nfunc buildHeader(u *url.URL, headings []string, currentHeading, direction string, paramPrefix string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"|\")\n\tfor _, h := range headings {\n\t\tarrow := \"\"\n\t\tif h == currentHeading {\n\t\t\tif direction == \"asc\" {\n\t\t\t\tarrow = \" ↑\"\n\t\t\t} else if direction == \"desc\" {\n\t\t\t\tarrow = \" ↓\"\n\t\t\t}\n\t\t}\n\n\t\t// Build URL for the header link with toggle logic\n\t\tnewURL := *u\n\t\tq := newURL.Query()\n\t\tif h == currentHeading {\n\t\t\t// Toggle sort direction\n\t\t\tif direction == \"asc\" {\n\t\t\t\tq.Del(paramPrefix + \"sort-asc\")\n\t\t\t\tq.Set(paramPrefix+\"sort-desc\", h)\n\t\t\t} else {\n\t\t\t\tq.Del(paramPrefix + \"sort-desc\")\n\t\t\t\tq.Set(paramPrefix+\"sort-asc\", h)\n\t\t\t}\n\t\t} else {\n\t\t\t// First click defaults to descending\n\t\t\tq.Del(paramPrefix + \"sort-asc\")\n\t\t\tq.Set(paramPrefix+\"sort-desc\", h)\n\t\t}\n\t\tnewURL.RawQuery = q.Encode()\n\t\tlink := md.Link(h+arrow, newURL.String())\n\t\tsb.WriteString(\" \" + link + \" |\")\n\t}\n\n\tsb.WriteString(\"\\n|\")\n\tfor range headings {\n\t\tsb.WriteString(\" --- |\")\n\t}\n\treturn sb.String()\n}\n"},{"name":"tablesort.gno","body":"// Package tablesort provides functionality to render a Markdown table with sortable columns.\n// It allows users to click on column headers to sort the table in ascending or descending sort direction.\n// The sorting state is managed via URL query parameters.\n// It displays an error if the table is malformed (e.g. rows with missing cells).\n// Multiple tablesort can be rendered on the same page by using a paramPrefix for each Render (See the Render function).\npackage tablesort\n\nimport (\n\t\"sort\"\n)\n\n// rowSorter implements sort.Interface for sorting rows by a specific column.\ntype rowSorter struct {\n\trows      [][]string\n\tcolIndex  int\n\tascending bool\n}\n\nfunc (rs rowSorter) Len() int {\n\treturn len(rs.rows)\n}\n\nfunc (rs rowSorter) Less(i, j int) bool {\n\tiCell := rs.rows[i][rs.colIndex]\n\tjCell := rs.rows[j][rs.colIndex]\n\tif rs.ascending {\n\t\treturn iCell \u003c jCell\n\t}\n\treturn iCell \u003e jCell\n}\n\nfunc (rs rowSorter) Swap(i, j int) {\n\trs.rows[i], rs.rows[j] = rs.rows[j], rs.rows[i]\n}\n\n// SortRows sorts the rows slice by a given column index and direction\nfunc SortRows(rows [][]string, colIndex int, ascending bool) {\n\tsort.Sort(rowSorter{rows, colIndex, ascending})\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"urlfilter","path":"gno.land/p/samcrew/urlfilter/v0","files":[{"name":"README.md","body":"# `urlfilter` - URL-based filtering\n\nFilter items using URL query parameters with toggleable markdown links. Works with AVL tree structures where each filter contains its associated items.\n\nGiven filters `[\"T1\", \"T2\", \"size:XL\"]` and URL `/shop?filter=T1,size:XL`, it generates toggle links:\n\n- **T1** _(active, click to remove)_\n- ~~T2~~ _(inactive, click to add)_  \n- **size:XL** _(active, click to remove)_\n\n**Markdown output:**\n```markdown\n[**T1**](/p/samcrew/urlfilter/v0?filter=size:XL) - [~~T2~~](/p/samcrew/urlfilter/v0=T1,T2,size:XL) - [**size:XL**](/p/samcrew/urlfilter/v0?filter=T1)\n```\n\n**Rendered as:**\n[**T1**](/p/samcrew/urlfilter/v0?filter=size:XL) - [~~T2~~](/p/samcrew/urlfilter/v0=T1,T2,size:XL) - [**size:XL**](/p/samcrew/urlfilter/v0?filter=T1)\n\n## Usage\n\nThe package expects a two-level AVL tree structure:\n- **Top level**: Filter names as keys (e.g., \"T1\", \"size:XL\", \"on_sale\")  \n- **Second level**: Item trees containing the actual items for each filter\n\n```go\n// Build the main filters tree\nfilters := avl.NewTree()\n\n// Subtree for filter \"T1\" \nt1Items := avl.NewTree()\nt1Items.Set(\"key1\", \"item1\")\nt1Items.Set(\"key2\", \"item2\")\nfilters.Set(\"T1\", t1Items)\n\n// Subtree for filter \"size:XL\"\nt2Items := avl.NewTree()\nt2Items.Set(\"key3\", \"item3\")\nfilters.Set(\"T2\", t2Items)\n\n// URL with active filter \"T1\"\nu, _ := url.Parse(\"/shop?filter=T1\")\n\n// Apply filtering\nmdLinks, filteredItems := urlfilter.ApplyFilters(u, filters, \"filter\") // \"filter\" for /shop?*filter*=T1\n\n// mdLinks    → Markdown links for toggling filters  \n// filteredItems → AVL tree containing only filtered items\n```\n\n## API\n\n```go\nfunc ApplyFilters(u *url.URL, items *avl.Tree, paramName string) (string, *avl.Tree)\n```\n\n**Parameters:**\n- `u`: URL containing query parameters\n- `items`: Two-level AVL tree (filters → item trees)\n- `paramName`: Query parameter name (e.g., \"filter\" for /shop?filter=T1)\n\n**URL Format:**\n- Single filter: `?filter=T1`\n- Multiple filters: `?filter=T1,size:XL,on_sale`\n- Filter names are comma-separated\n\n**Returns:**\n- **Markdown links**: Toggleable filter links with formatting\n- **Filtered items**: AVL tree containing items from active filters\n  - If no filters active: returns all items\n  - Item keys are preserved, values show which filter matched\n\n# Example\n\n- [/r/gov/dao/memberstore/v0:members?filter=T1](/r/gov/dao/memberstore/v0:members?filter=T1)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/samcrew/urlfilter/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1kfd9f5zlvcvy6aammcmqswa7cyjpu2nyt9qfen\"\n"},{"name":"urlfilter.gno","body":"// Package urlfilter provides functionality to filter items based on URL query parameters.\n// It is designed to work with an avl.Tree structure where each key represents a filter\n// and each value is an avl.Tree containing items associated with that filter.\npackage urlfilter\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/sunspirit/md/v0\"\n)\n\n// ApplyFilters filters items based on the \"filter\" query parameter in the given URL\n// and generates a Markdown representation of all available filters.\n//\n// Expected `items` structure:\n//   - `items` is an *bptree.BPTree where each key is a filter name (e.g., \"T1\", \"size:XL\", \"on_sale\")\n//     and each value is an *bptree.BPTree containing the items for that filter.\n//   - Each item tree uses:\n//     Key   (string): Unique item identifier\n//     Value (any)   : Optional associated item data\n//\n// Example:\n//\n//\t// Build the main filters tree\n//\tfilters := bptree.NewBPTree32()\n//\n//\t// Subtree for filter \"T1\"\n//\tt1Items := bptree.NewBPTree32()\n//\tt1Items.Set(\"item1\", nil)\n//\tt1Items.Set(\"item2\", nil)\n//\tfilters.Set(\"T1\", t1Items)\n//\n//\t// URL with active filter \"T1\"\n//\tu, _ := url.Parse(\"/shop?filter=T1\")\n//\n//\tmdFilters, items := ApplyFilters(u, filters, \"filter\")\n//\n//\t// mdFilters\t→ Markdown links for toggling filters\n//\t// items    \t→ AVL tree containing the filtered items\nfunc ApplyFilters(u *url.URL, items *bptree.BPTree, paramName string) (string, *bptree.BPTree) {\n\tactive := parseFilterMap(u.Query(), paramName)\n\tallFilters := make([]string, 0)\n\tresultTree := bptree.NewBPTree32()\n\n\t// Iterate over each filter group in the items tree\n\titems.Iterate(\"\", \"\", func(filterKey string, subtree interface{}) bool {\n\t\tallFilters = append(allFilters, filterKey)\n\n\t\ttree, ok := subtree.(*bptree.BPTree)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\t// Add items to result if there are no active filters\n\t\t// or if the current filter is active\n\t\ttree.Iterate(\"\", \"\", func(itemKey string, _ interface{}) bool {\n\t\t\tif len(active) == 0 || active[filterKey] {\n\t\t\t\tresultTree.Set(itemKey, filterKey)\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\treturn false\n\t})\n\n\t// Build Markdown links for toggling each filter\n\tvar sb strings.Builder\n\tfor _, f := range allFilters {\n\t\tq := toggleFilterQuery(active, f, allFilters, paramName)\n\t\turlStr := buildURL(u.Path, q)\n\t\tsb.WriteString(ufmt.Sprintf(\" | %v \", md.Link(formatLabel(f, active[f]), urlStr)))\n\t}\n\n\treturn sb.String(), resultTree\n}\n\n// buildURL returns a path + query string, omitting the \"?\" if no query exists.\nfunc buildURL(path string, query url.Values) string {\n\tif enc := query.Encode(); enc != \"\" {\n\t\treturn path + \"?\" + enc\n\t}\n\treturn path\n}\n\n// parseFilterMap reads the \"filter\" query parameter and converts it into a map\n// where keys are filter names and values are true for active filters.\n//\n// Example:\n//\n//\t\"filter=T1,T2\" -\u003e map[string]bool{\"T1\": true, \"T2\": true}\nfunc parseFilterMap(query url.Values, paramName string) map[string]bool {\n\tfilterStr := strings.TrimSpace(query.Get(paramName))\n\tif filterStr == \"\" {\n\t\treturn map[string]bool{}\n\t}\n\tm := make(map[string]bool)\n\tfor _, f := range strings.Split(filterStr, \",\") {\n\t\tif f = strings.TrimSpace(f); f != \"\" {\n\t\t\tm[f] = true\n\t\t}\n\t}\n\treturn m\n}\n\n// toggleFilterQuery returns a new query string with the given filter toggled.\n// - If the filter is currently active, it will be removed.\n// - If it is inactive, it will be added.\n// The order of filters follows the `all` list for consistency.\nfunc toggleFilterQuery(active map[string]bool, toggled string, all []string, paramName string) url.Values {\n\tnewFilters := []string{}\n\tfor _, f := range all {\n\t\tif f == toggled {\n\t\t\tif !active[f] { // Add if it was inactive\n\t\t\t\tnewFilters = append(newFilters, f)\n\t\t\t}\n\t\t} else if active[f] { // Keep other active filters\n\t\t\tnewFilters = append(newFilters, f)\n\t\t}\n\t}\n\tq := url.Values{}\n\tif len(newFilters) \u003e 0 {\n\t\tq.Set(paramName, strings.Join(newFilters, \",\"))\n\t}\n\treturn q\n}\n\n// formatLabel returns the Markdown-formatted label for a filter,\n// showing active filters in bold (**filter**) and inactive filters\n// with strikethrough (~~filter~~).\nfunc formatLabel(name string, active bool) string {\n\tif active {\n\t\treturn md.Bold(name)\n\t}\n\treturn md.Strikethrough(name)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"memberstore","path":"gno.land/r/gov/dao/memberstore/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/memberstore/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da\"\n"},{"name":"memberstore.gno","body":"package memberstore\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/svg/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\nvar (\n\tmembers MembersByTier\n\ttiers   TiersByName // private to prevent external modification\n\trouter  *mux.Router\n)\n\nconst (\n\tT1 = \"T1\"\n\tT2 = \"T2\"\n\tT3 = \"T3\"\n)\n\nfunc init() {\n\tmembers = NewMembersByTier()\n\n\ttiers = TiersByName{bptree.NewBPTree32()}\n\ttiers.Set(T1, Tier{\n\t\tInvitationPoints: 3,\n\t\tMinSize: func(membersByTier MembersByTier, tiersByName TiersByName) int {\n\t\t\treturn 70\n\t\t},\n\t\tMaxSize: func(membersByTier MembersByTier, tiersByName TiersByName) int {\n\t\t\treturn 0\n\t\t},\n\t\tBasePower: 3,\n\t\tPowerHandler: func(membersByTier MembersByTier, tiersByName TiersByName) float64 {\n\t\t\treturn 3\n\t\t},\n\t})\n\n\ttiers.Set(T2, Tier{\n\t\tInvitationPoints: 2,\n\t\tMaxSize: func(membersByTier MembersByTier, tiersByName TiersByName) int {\n\t\t\treturn membersByTier.GetTierSize(T1) * 2\n\t\t},\n\t\tMinSize: func(membersByTier MembersByTier, tiersByName TiersByName) int {\n\t\t\treturn membersByTier.GetTierSize(T1) / 4\n\t\t},\n\t\tBasePower: 2,\n\t\tPowerHandler: func(membersByTier MembersByTier, tiersByName TiersByName) float64 {\n\t\t\tt1ms := float64(membersByTier.GetTierSize(T1))\n\t\t\tt1, _ := tiersByName.GetTier(T1)\n\t\t\tt2ms := float64(membersByTier.GetTierSize(T2))\n\t\t\tt2, _ := tiersByName.GetTier(T2)\n\n\t\t\tt1p := t1.BasePower * t1ms\n\t\t\tt2p := t2.BasePower * t2ms\n\n\t\t\t// capped to 2/3 of tier 1\n\t\t\tt1ptreshold := t1p * (2.0 / 3.0)\n\t\t\tif t2p \u003e t1ptreshold {\n\t\t\t\treturn t1ptreshold / t2ms\n\t\t\t}\n\n\t\t\treturn t2.BasePower\n\t\t},\n\t})\n\n\ttiers.Set(T3, Tier{\n\t\tInvitationPoints: 1,\n\t\tMaxSize: func(membersByTier MembersByTier, tiersByName TiersByName) int {\n\t\t\treturn 0\n\t\t},\n\t\tMinSize: func(membersByTier MembersByTier, tiersByName TiersByName) int {\n\t\t\treturn 0\n\t\t},\n\t\tBasePower: 1,\n\t\tPowerHandler: func(membersByTier MembersByTier, tiersByName TiersByName) float64 {\n\t\t\tt1ms := float64(membersByTier.GetTierSize(T1))\n\t\t\tt1, _ := tiersByName.GetTier(T1)\n\t\t\tt3ms := float64(membersByTier.GetTierSize(T3))\n\t\t\tt3, _ := tiersByName.GetTier(T3)\n\n\t\t\tt1p := t1.BasePower * t1ms\n\t\t\tt3p := t3.BasePower * t3ms\n\n\t\t\t// capped to 1/3 of tier 1\n\t\t\tt1ptreshold := t1p * (1.0 / 3.0)\n\t\t\tif t3p \u003e t1ptreshold {\n\t\t\t\treturn t1ptreshold / t3ms\n\t\t\t}\n\n\t\t\treturn t3.BasePower\n\t\t},\n\t})\n\n\tinitRouter()\n}\n\n// initRouter initializes the router for the memberstore.\nfunc initRouter() {\n\trouter = mux.NewRouter()\n\trouter.HandleFunc(\"\", renderHome)\n\trouter.HandleFunc(\"members\", renderMembers)\n\trouter.NotFoundHandler = renderNotFound\n}\n\n// renderHome displays the tiers data (Number of members and powers) and tiers charts.\nfunc renderHome(res *mux.ResponseWriter, req *mux.Request) {\n\tvar sb strings.Builder\n\tsb.WriteString(md.Link(\"\u003e Go to Members list \u003c\", \"/r/gov/dao/memberstore/v0:members\") + \"\\n\")\n\n\tmembers.Iterate(\"\", \"\", func(tn string, ti interface{}) bool {\n\t\ttree, ok := ti.(*bptree.BPTree)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\ttier, ok := tiers.GetTier(tn)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\ttp := (tier.PowerHandler(members, tiers) * float64(members.GetTierSize(tn)))\n\n\t\tsb.WriteString(ufmt.Sprintf(\"- %v Tier %v contains %v members with power: %v\\n\", tierColoredChip(tn), tn, tree.Size(), tp))\n\n\t\treturn false\n\t})\n\n\tsb.WriteString(\"\\n\" + RenderCharts(members))\n\tres.Write(sb.String())\n}\n\n// renderMembers displays the members list.\nfunc renderMembers(res *mux.ResponseWriter, req *mux.Request) {\n\tpath := strings.Replace(req.RawPath, \"members\", \"\", 1) // We have to clean the path\n\tres.Write(RenderMembers(path, members))\n}\n\nfunc renderNotFound(res *mux.ResponseWriter, req *mux.Request) {\n\tres.Write(\"# 404\\n\\nThat page was not found. Would you like to [**go home**?](/r/gov/dao/memberstore/v0)\")\n}\n\nfunc tierColor(tn string) string {\n\tswitch tn {\n\tcase T1:\n\t\treturn \"#329175\"\n\tcase T2:\n\t\treturn \"#21577A\"\n\tcase T3:\n\t\treturn \"#F3D3BC\"\n\tdefault:\n\t\treturn \"#FFF\"\n\t}\n}\n\n// tierColoredChip returns a colored chip svg for the given tier name.\nfunc tierColoredChip(tn string) string {\n\tcanvas := svg.NewCanvas(16, 16)\n\tcanvas.Append(svg.NewRectangle(0, 0, 16, 16, tierColor(tn)))\n\treturn canvas.Render(tn + \" colored chip\")\n}\n\nfunc Render(path string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(md.H1(\"Memberstore Govdao v0\"))\n\tsb.WriteString(router.Render(path))\n\treturn sb.String()\n}\n\n// Get gets the Members store.\n//\n// rlm is the cur of an in-scope crossing frame, threaded by the caller.\n// The IsCurrent() check rejects stale or stashed realm values — a\n// malicious realm cannot replay an old cur to claim allowed-DAO\n// identity. After the check, rlm.PkgPath() is the authentic immediate\n// caller's realm.\nfunc Get(_ int, rlm realm) MembersByTier {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"memberstore.Get: rlm is not the caller's live cur (stale capture or sibling frame)\")\n\t}\n\tcurrealm := rlm.PkgPath()\n\tif !dao.InAllowedDAOs(currealm) {\n\t\tpanic(\"this Realm is not allowed to get the Members data: \" + currealm)\n\t}\n\n\treturn members\n}\n\n// GetTier returns a tier by name. This is a read-only accessor.\nfunc GetTier(name string) (Tier, bool) {\n\treturn tiers.GetTier(name)\n}\n\n// IterateTiers iterates over all tiers in order. This is a read-only accessor.\n// The callback receives the tier name and tier data.\n// Return true from the callback to stop iteration.\nfunc IterateTiers(fn func(name string, tier Tier) bool) {\n\ttiers.Iterate(\"\", \"\", func(name string, value interface{}) bool {\n\t\ttier, ok := value.(Tier)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn fn(name, tier)\n\t})\n}\n\n// setTiers replaces the tiers configuration.\n// This is internal and should only be called via governance proposal execution.\nfunc setTiers(newTiers TiersByName) {\n\ttiers = newTiers\n}\n\n// GetTierPower calculates the effective voting power for a tier given the current members.\n// This is a safe accessor that uses the internal tiers configuration.\nfunc GetTierPower(tierName string, members MembersByTier) float64 {\n\ttier, ok := tiers.GetTier(tierName)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn tier.PowerHandler(members, tiers)\n}\n"},{"name":"prop_requests.gno","body":"package memberstore\n\nimport (\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\n\t\"gno.land/r/gov/dao\"\n)\n\nfunc NewChangeTiersRequest(cur realm, tiers map[string]Tier) dao.ProposalRequest {\n\tif len(tiers) == 0 {\n\t\tpanic(\"tiers list is empty\")\n\t}\n\n\tmember, _ := Get(0, cur).GetMember(unsafe.OriginCaller())\n\tif member == nil {\n\t\tpanic(\"proposer is not a member\")\n\t}\n\n\tnewTiers := TiersByName{bptree.NewBPTree32()}\n\tfor name, tier := range tiers {\n\t\tnewTiers.Set(name, tier)\n\t}\n\n\tcallback := func(cur realm) error {\n\t\tsetTiers(newTiers)\n\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, callback, \"New set of tiers proposed.\")\n\n\treturn dao.NewProposalRequest(\"Change Tiers Proposal\", \"This proposal is looking to change the existing Tiers in memberstore\", e)\n}\n"},{"name":"rendercharts.gno","body":"package memberstore\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/samcrew/piechart/v0\"\n)\n\n// RenderCharts generates two pie charts for member tiers:\n// 1) distribution of member counts per tier\n// 2) distribution of power per tier\nfunc RenderCharts(members MembersByTier) string {\n\tvar sb strings.Builder\n\n\ttierNames := []string{T1, T2, T3}\n\tpieSlicesTs := make([]piechart.PieSlice, 0, len(tierNames))\n\tpieSlicesTp := make([]piechart.PieSlice, 0, len(tierNames))\n\n\tfor _, tn := range tierNames {\n\t\ttier, ok := tiers.GetTier(tn)\n\t\tif !ok {\n\t\t\treturn \"\"\n\t\t}\n\n\t\tts := float64(members.GetTierSize(tn))\n\t\ttp := tier.PowerHandler(members, tiers) * ts\n\n\t\tpieSlicesTs = append(pieSlicesTs, piechart.PieSlice{\n\t\t\tValue: ts,\n\t\t\tColor: tierColor(tn),\n\t\t\tLabel: tn,\n\t\t})\n\t\tpieSlicesTp = append(pieSlicesTp, piechart.PieSlice{\n\t\t\tValue: tp,\n\t\t\tColor: tierColor(tn),\n\t\t\tLabel: tn,\n\t\t})\n\t}\n\n\t// Render pie charts for members count and power distribution\n\tresultPieChartTs := piechart.Render(pieSlicesTs, \"Members distribution:\")\n\tresultPieChartTp := piechart.Render(pieSlicesTp, \"Power distribution:\")\n\n\tsb.WriteString(resultPieChartTs + \"\\n\")\n\tsb.WriteString(resultPieChartTp + \"\\n\")\n\n\treturn sb.String()\n}\n"},{"name":"rendermembers.gno","body":"package memberstore\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/bptree/pager/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/samcrew/tablesort/v0\"\n\t\"gno.land/p/samcrew/urlfilter/v0\"\n)\n\n// RenderMembers returns the members list with tier filters and pagination.\nfunc RenderMembers(path string, members MembersByTier) string {\n\tu, err := url.Parse(path)\n\tif err != nil {\n\t\t// A path url.Parse rejects (e.g. a control byte) is the caller's own\n\t\t// malformed input. Degrade to the unfiltered first page instead of\n\t\t// nil-derefing in ApplyFilters or panicking in MustGetPageByPath below\n\t\t// — this is a read-only, unauthenticated render.\n\t\tu, _ = url.Parse(\"\")\n\t\tpath = \"\"\n\t}\n\tmdFilters, items := urlfilter.ApplyFilters(u, members.BPTree, \"filter\")\n\tvar sb strings.Builder\n\n\tsb.WriteString(md.Link(\"\u003e Go to Tiers summary \u003c\", \"/r/gov/dao/memberstore/v0\") + \"\\n\\n\")\n\tsb.WriteString(md.Bold(\"Filter members by tiers:\"))\n\tsb.WriteString(mdFilters + \"\\n\")\n\n\tconst pageSize = 14\n\tpager := pager.NewPager(items, pageSize, false)\n\tpage := pager.MustGetPageByPath(path)\n\n\tsb.WriteString(renderMembersPages(u, page, items) + \"\\n\")\n\tsb.WriteString(renderPagination(u, page))\n\n\treturn sb.String()\n}\n\n// renderMembersPages returns the members of each page.\nfunc renderMembersPages(u *url.URL, page *pager.Page, members *bptree.BPTree) string {\n\tvar sb strings.Builder\n\n\ttable := \u0026tablesort.Table{\n\t\tHeadings: []string{\"Tier\", \"Address\"},\n\t\tRows:     [][]string{},\n\t}\n\n\tfor _, item := range page.Items {\n\t\taddr := item.Key\n\t\ttn := members.Get(addr)\n\t\ttnStr, _ := tn.(string)\n\t\ttierCell := ufmt.Sprintf(\"%s %s\", tierColoredChip(tnStr), tn)\n\t\ttable.Rows = append(table.Rows, []string{tierCell, addr})\n\t}\n\n\tsb.WriteString(tablesort.Render(u, table, \"\"))\n\n\treturn sb.String()\n}\n\n// renderPagination returns the pagination UI for the current page.\nfunc renderPagination(u *url.URL, page *pager.Page) string {\n\tq := u.Query()\n\tq.Del(\"page\")\n\tu.RawQuery = q.Encode()\n\n\tvar sb strings.Builder\n\tsb.WriteString(page.Picker(u.String()))\n\n\treturn sb.String()\n}\n"},{"name":"types.gno","body":"package memberstore\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\ntype ErrMemberAlreadyExists struct {\n\tTier string\n}\n\nfunc (e *ErrMemberAlreadyExists) Error() string {\n\treturn \"member already exists on tier \" + e.Tier\n}\n\ntype Member struct {\n\tInvitationPoints int\n}\n\nfunc NewMember(invitationPoints int) *Member {\n\treturn \u0026Member{InvitationPoints: invitationPoints}\n}\n\nfunc (m *Member) RemoveInvitationPoint() {\n\tif m.InvitationPoints \u003c= 0 {\n\t\tpanic(\"not enough invitation points\")\n\t}\n\n\tm.InvitationPoints = m.InvitationPoints - 1\n}\n\n// MembersByTier contains all `Member`s indexed by their Address.\ntype MembersByTier struct {\n\t*bptree.BPTree // tier name -\u003e address -\u003e member\n}\n\nfunc NewMembersByTier() MembersByTier {\n\treturn MembersByTier{BPTree: bptree.NewBPTree32()}\n}\n\nfunc (mbt MembersByTier) DeleteAll() {\n\tmbt.Iterate(\"\", \"\", func(tn string, msv interface{}) bool {\n\t\tmbt.Remove(tn)\n\t\treturn false\n\t})\n}\n\nfunc (mbt MembersByTier) SetTier(tier string) error {\n\tif ok := mbt.Has(tier); ok {\n\t\treturn errors.New(\"tier already exist: \" + tier)\n\t}\n\n\tmbt.Set(tier, bptree.NewBPTree32())\n\n\treturn nil\n}\n\n// GetTierSize tries to get how many members are on the specified tier. If the tier does not exists, it returns 0.\nfunc (mbt MembersByTier) GetTierSize(tn string) int {\n\ttv := mbt.Get(tn)\n\tif tv == nil {\n\t\treturn 0\n\t}\n\n\ttree, ok := tv.(*bptree.BPTree)\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn tree.Size()\n}\n\n// SetMember adds a new member to the specified tier. The tier index is created on the fly if it does not exists.\nfunc (mbt MembersByTier) SetMember(tier string, addr address, member *Member) error {\n\t_, t := mbt.GetMember(addr)\n\tif t != \"\" {\n\t\treturn \u0026ErrMemberAlreadyExists{Tier: t}\n\t}\n\n\tif ok := mbt.Has(tier); !ok {\n\t\treturn errors.New(\"tier does not exist: \" + tier)\n\t}\n\n\tms := mbt.Get(tier)\n\tmst := ms.(*bptree.BPTree)\n\n\tmst.Set(string(addr), member)\n\n\treturn nil\n}\n\n// GetMember iterate over all tiers to try to find a member by its address. The tier ID is also returned if the Member is found.\nfunc (mbt MembersByTier) GetMember(addr address) (m *Member, t string) {\n\tmbt.Iterate(\"\", \"\", func(tn string, msv interface{}) bool {\n\t\tmst, ok := msv.(*bptree.BPTree)\n\t\tif !ok {\n\t\t\tpanic(\"MembersByTier values can only be bptree.BPTree\")\n\t\t}\n\n\t\tmv := mst.Get(string(addr))\n\t\tif mv == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tmm, ok := mv.(*Member)\n\t\tif !ok {\n\t\t\tpanic(\"MembersByTier values can only be *Member\")\n\t\t}\n\n\t\tm = mm\n\t\tt = tn\n\n\t\treturn true\n\t})\n\n\treturn\n}\n\n// RemoveMember removes a member from any tier\nfunc (mbt MembersByTier) RemoveMember(addr address) (t string) {\n\tmbt.Iterate(\"\", \"\", func(tn string, msv interface{}) bool {\n\t\tmst, ok := msv.(*bptree.BPTree)\n\t\tif !ok {\n\t\t\tpanic(\"MembersByTier values can only be bptree.BPTree\")\n\t\t}\n\n\t\t_, removed := mst.Remove(string(addr))\n\t\tif removed {\n\t\t\tt = tn\n\t\t}\n\t\treturn removed\n\t})\n\n\treturn\n}\n\n// GetTotalPower obtains the total voting power from all the specified tiers.\nfunc (mbt MembersByTier) GetTotalPower() float64 {\n\tvar out float64\n\tmbt.Iterate(\"\", \"\", func(tn string, msv interface{}) bool {\n\t\ttier, ok := tiers.GetTier(tn)\n\t\tif !ok {\n\t\t\t// tier does not exists, so we cannot count power from this tier\n\t\t\treturn false\n\t\t}\n\n\t\tout = out + (tier.PowerHandler(mbt, tiers) * float64(mbt.GetTierSize(tn)))\n\n\t\treturn false\n\t})\n\n\treturn out\n}\n\ntype Tier struct {\n\t// BasePower defines the standard voting power for the members on this tier.\n\tBasePower float64\n\n\t// InvitationPoints defines how many invitation points users on that tier will receive.\n\tInvitationPoints int\n\n\t// MaxSize calculates the max amount of members expected to be on this tier.\n\tMaxSize func(membersByTier MembersByTier, tiersByName TiersByName) int\n\n\t// MinSize calculates the min amount of members expected to be on this tier.\n\tMinSize func(membersByTier MembersByTier, tiersByName TiersByName) int\n\n\t// PowerHandler calculates what is the final power of this tier after taking into account Members by other tiers.\n\tPowerHandler func(membersByTier MembersByTier, tiersByName TiersByName) float64\n}\n\n// TiersByName contains all tier objects indexed by its name.\ntype TiersByName struct {\n\t*bptree.BPTree // *bptree.BPTree[string]Tier\n}\n\n// GetTier obtains a Tier struct by its name. It returns false if the Tier is not found.\nfunc (tbn TiersByName) GetTier(tn string) (Tier, bool) {\n\tval := tbn.Get(tn)\n\tif val == nil {\n\t\treturn Tier{}, false\n\t}\n\n\tt, ok := val.(Tier)\n\tif !ok {\n\t\tpanic(\"TiersByName must contains only Tier types\")\n\t}\n\n\treturn t, true\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"fqname","path":"gno.land/p/nt/fqname/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `fqname` - Fully qualified identifiers\n\nParse, construct, and link fully qualified Gno identifiers of the form `\u003cpkgpath\u003e.\u003cname\u003e` (e.g. `gno.land/p/nt/avl/v0.Tree`).\n\n## Usage\n\n```go\nimport \"gno.land/p/nt/fqname/v0\"\n\n// Split a fully qualified name\npkgpath, name := fqname.Parse(\"gno.land/p/nt/avl/v0.Tree\")\n// pkgpath == \"gno.land/p/nt/avl/v0\", name == \"Tree\"\n\n// Rebuild one from its parts\nid := fqname.Construct(\"gno.land/r/demo/foo20\", \"Token\")\n// id == \"gno.land/r/demo/foo20.Token\"\n\n// Render as a Markdown link (gno.land paths become clickable)\nlink := fqname.RenderLink(\"gno.land/r/demo/foo20\", \"Token\")\n// link == \"[gno.land/r/demo/foo20](/r/demo/foo20).Token\"\n```\n\n## API\n\n```go\n// Parse splits a fully qualified identifier into (pkgpath, name).\n// If no name is present (no dot after the last slash), name is \"\".\nfunc Parse(fqname string) (pkgpath, name string)\n\n// Construct joins pkgpath and name with a dot. If name is empty, returns pkgpath.\nfunc Construct(pkgpath, name string) string\n\n// RenderLink formats a fully qualified identifier as Markdown.\n// Paths starting with \"gno.land\" are turned into a link to the package;\n// other paths are returned as plain text. The slug is dot-appended and\n// markdown-escaped.\nfunc RenderLink(pkgPath, slug string) string\n```\n\n## Notes\n\n- `Parse` treats everything after the dot following the last slash as the name, so nested selectors like `Pkg.Type.Method` round-trip as a single name.\n- `RenderLink` only links `gno.land`-rooted paths; foreign domains (e.g. `github.com/...`) are returned unmodified except for the dot-joined slug.\n- `RenderLink` markdown-escapes the `slug`, but NOT `pkgPath`: a `]` or `)` in an untrusted `pkgPath` breaks out of the link. Pass validated package paths, or sanitize with [`gno.land/p/nt/markdown/sanitize/v0`](../../markdown/sanitize/v0) before rendering untrusted input.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package fqname provides utilities for handling fully qualified identifiers\n// in Gno, typically a package path followed by a dot and a symbol name.\npackage fqname\n"},{"name":"fqname.gno","body":"// Package fqname provides utilities for handling fully qualified identifiers in\n// Gno. A fully qualified identifier typically includes a package path followed\n// by a dot (.) and then the name of a variable, function, type, or other\n// package-level declaration.\npackage fqname\n\nimport (\n\t\"strings\"\n)\n\n// Parse splits a fully qualified identifier into its package path and name\n// components. It handles cases with and without slashes in the package path.\n//\n//\tpkgpath, name := fqname.Parse(\"gno.land/p/nt/avl/v0.Tree\")\n//\tufmt.Sprintf(\"Package: %s, Name: %s\\n\", id.Package, id.Name)\n//\t// Output: Package: gno.land/p/nt/avl/v0, Name: Tree\nfunc Parse(fqname string) (pkgpath, name string) {\n\t// Find the index of the last slash.\n\tlastSlashIndex := strings.LastIndex(fqname, \"/\")\n\tif lastSlashIndex == -1 {\n\t\t// No slash found, handle it as a simple package name with dot notation.\n\t\tdotIndex := strings.LastIndex(fqname, \".\")\n\t\tif dotIndex == -1 {\n\t\t\treturn fqname, \"\"\n\t\t}\n\t\treturn fqname[:dotIndex], fqname[dotIndex+1:]\n\t}\n\n\t// Get the part after the last slash.\n\tafterSlash := fqname[lastSlashIndex+1:]\n\n\t// Check for a dot in the substring after the last slash.\n\tdotIndex := strings.Index(afterSlash, \".\")\n\tif dotIndex == -1 {\n\t\t// No dot found after the last slash\n\t\treturn fqname, \"\"\n\t}\n\n\t// Split at the dot to separate the base and the suffix.\n\tbase := fqname[:lastSlashIndex+1+dotIndex]\n\tsuffix := afterSlash[dotIndex+1:]\n\n\treturn base, suffix\n}\n\n// Construct a qualified identifier.\n//\n//\tfqName := fqname.Construct(\"gno.land/r/demo/foo20\", \"Token\")\n//\tfmt.Println(\"Fully Qualified Name:\", fqName)\n//\t// Output: gno.land/r/demo/foo20.Token\nfunc Construct(pkgpath, name string) string {\n\t// TODO: ensure pkgpath is valid - and as such last part does not contain a dot.\n\tif name == \"\" {\n\t\treturn pkgpath\n\t}\n\treturn pkgpath + \".\" + name\n}\n\n// RenderLink creates a formatted link for a fully qualified identifier.\n// If the package path starts with \"gno.land\", it converts it to a markdown link.\n// If the domain is different or missing, it returns the input as is.\nfunc RenderLink(pkgPath, slug string) string {\n\tif strings.HasPrefix(pkgPath, \"gno.land\") {\n\t\tpkgLink := strings.TrimPrefix(pkgPath, \"gno.land\")\n\t\tif slug != \"\" {\n\t\t\tsafeSlug := escapeMarkdown(slug)\n\t\t\treturn \"[\" + pkgPath + \"](\" + pkgLink + \").\" + safeSlug\n\t\t}\n\n\t\treturn \"[\" + pkgPath + \"](\" + pkgLink + \")\"\n\t}\n\n\tif slug != \"\" {\n\t\tsafeSlug := escapeMarkdown(slug)\n\t\treturn pkgPath + \".\" + safeSlug\n\t}\n\n\treturn pkgPath\n}\n\n// escapeMarkdown escapes characters that could break markdown link syntax.\nfunc escapeMarkdown(s string) string {\n\tr := strings.NewReplacer(\n\t\t\"[\", `\\[`,\n\t\t\"]\", `\\]`,\n\t\t\"(\", `\\(`,\n\t\t\")\", `\\)`,\n\t)\n\treturn r.Replace(s)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/fqname/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"grc20reg","path":"gno.land/r/nt/grc20reg/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/nt/grc20reg/v0\"\ngno = \"0.9\"\n"},{"name":"grc20reg.gno","body":"package grc20reg\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/avl/rotree/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/fqname/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar registry = avl.NewTree() // rlmPath.symbol -\u003e *Token\n\n// Construction lives in grc20.NewToken — it takes rlm realm last\n// and binds origRealm from rlm.PkgPath() under an IsCurrent assertion.\n// The registry key is the canonical fqname rlmPath.symbol (one token per\n// realm+symbol), independent of Token.ID()'s trailing sequence id, so\n// callers can look a token up from the (realm, symbol) pair they already\n// know:\n//\n//\tToken, ledger := grc20.NewToken(name, symbol, decimals, id, cur)\n//\tkey := grc20reg.Register(cross(cur), Token, \"\")\n\n// Register records token under its rlmPath.symbol key and returns that key.\n// Token.ID() carries a trailing sequence id (rlmPath.symbol.\u003cid\u003e) that keeps\n// token identities/events unique, but the registry deliberately keys by\n// rlmPath.symbol so lookups don't need to know the id, and so a realm cannot\n// register two tokens under the same symbol (overwrite/alias guard).\nfunc Register(cur realm, token *grc20.Token, slug string) string {\n\tif token == nil {\n\t\tpanic(\"grc20reg: nil token\")\n\t}\n\tif slug != \"\" {\n\t\tvalidateSlug(slug)\n\t}\n\trlmPath := cur.Previous().PkgPath()\n\tkey := fqname.Construct(rlmPath, token.GetSymbol())\n\t// Token.ID() == key + \".\" + \u003cid\u003e; verify the token originates from the\n\t// registering realm and symbol.\n\tif !strings.HasPrefix(token.ID(), key+\".\") {\n\t\tpanic(\"grc20reg: token must be registered from its own realm\")\n\t}\n\tif registry.Has(key) {\n\t\tpanic(\"grc20reg: token already registered\")\n\t}\n\tregistry.Set(key, token)\n\tchain.Emit(\n\t\tregisterEvent,\n\t\t\"token_path\", key,\n\t\t\"pkgpath\", rlmPath,\n\t\t\"slug\", slug,\n\t\t\"symbol\", token.GetSymbol(),\n\t)\n\treturn key\n}\n\nfunc Get(key string) *grc20.Token {\n\ttoken := registry.Get(key)\n\tif token == nil {\n\t\treturn nil\n\t}\n\treturn token.(*grc20.Token)\n}\n\nfunc MustGet(key string) *grc20.Token {\n\ttoken := Get(key)\n\tif token == nil {\n\t\tpanic(\"unknown token: \" + key)\n\t}\n\treturn token\n}\n\n// Write wrappers: a registered token can be moved through the registry without\n// importing the token's realm, which is the point of a registry. What makes\n// that safe is the calling convention, so it is worth stating once here rather\n// than three times below.\n//\n// These are NOT crossing functions. `_ int, rlm realm` is the only shape that\n// gives a non-crossing realm parameter — a realm parameter in first position\n// must be named `cur`, which makes the function crossing — and the distinction\n// is load-bearing, not stylistic:\n//\n//   - Crossing (`func Transfer(cur realm, …)`) mints a fresh `cur` for THIS\n//     realm. RealmTeller would then bind the actor to the registry's own\n//     address and the registry would spend its own balance. Useless at best.\n//   - Non-crossing (`func Transfer(_ int, rlm realm, …)`) declaring-borrows to\n//     the registry without a realm-context change, so `rlm` is still the\n//     caller's own live token and the actor is the caller.\n//\n// The safety comes from RealmTeller's IsCurrent() assertion. The actor is\n// rlm.Address() on a token that must be the live crossing frame, so it is\n// provably the immediate caller: a stale or foreign token is refused with\n// ErrSpoofedRealm. Debiting anyone else would mean holding their live `cur`,\n// which means executing inside their frame — authority they handed over\n// deliberately, and the same trust model RealmTeller already carries.\n//\n// This is deliberately not grc20.CallerTeller. \"Act as whoever called me\" is\n// the confused deputy: the debited account ends up chosen by whoever the hub\n// can be induced to serve, and an intermediate realm frame silently changes who\n// pays. CallerTeller is confined to the token's own realm for that reason and\n// is not reachable from a *Token. \"Act as the realm that called me, verified\n// current\" has nothing to induce — the caller cannot name a victim, only\n// itself.\n//\n// Realm-only by construction: MsgCall cannot build a realm argument\n// (convertArgToGno rejects non-primitive parameter types), so a signing user\n// cannot reach these at all and there is no in-band case to guard against.\n// Users move their own tokens through the token realm's own entry points\n// (wugnot.Transfer, foo20.Transfer, …).\n\n// Transfer moves `amount` out of the CALLING REALM's own balance.\n//\n// Call it non-crossing, forwarding your own `cur`:\n//\n//\tgrc20reg.Transfer(0, cur, \"gno.land/r/demo/defi/foo20.FOO\", to, 100)\nfunc Transfer(_ int, rlm realm, tokenKey string, to address, amount int64) {\n\tcheckErr(MustGet(tokenKey).RealmTeller(0, rlm).Transfer(0, rlm, to, amount))\n}\n\n// Approve sets an allowance owned by the CALLING REALM, letting `spender` draw\n// on the calling realm's balance. It does not touch the signing user's\n// allowances.\nfunc Approve(_ int, rlm realm, tokenKey string, spender address, amount int64) {\n\tcheckErr(MustGet(tokenKey).RealmTeller(0, rlm).Approve(0, rlm, spender, amount))\n}\n\n// TransferFrom spends an allowance with the CALLING REALM as the spender.\n//\n// Note the allowance direction this implies: `from` must have approved the\n// calling realm, not the signing user. That is the supported way for a realm to\n// move a user's funds — the user grants the realm an allowance, and the realm\n// draws on it as itself, so every debit is one the owner authorized against\n// that specific realm.\nfunc TransferFrom(_ int, rlm realm, tokenKey string, from, to address, amount int64) {\n\tcheckErr(MustGet(tokenKey).RealmTeller(0, rlm).TransferFrom(0, rlm, from, to, amount))\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Render(path string) string {\n\tswitch {\n\tcase path == \"\": // home\n\t\t// TODO: add pagination\n\t\ts := \"\"\n\t\tcount := 0\n\t\tregistry.Iterate(\"\", \"\", func(key string, tokenI any) bool {\n\t\t\tcount++\n\t\t\ttoken := tokenI.(*grc20.Token)\n\t\t\trlmPath, tokenID := fqname.Parse(key)\n\t\t\trlmLink := fqname.RenderLink(rlmPath, tokenID)\n\t\t\tinfoLink := \"/r/nt/grc20reg/v0:\" + key\n\t\t\ts += \"- \" + md.Bold(md.EscapeText(token.GetName())) + \" - \" + rlmLink + \" - \" + md.Link(\"info\", infoLink) + \"\\n\"\n\t\t\treturn false\n\t\t})\n\t\tif count == 0 {\n\t\t\treturn \"No registered token.\"\n\t\t}\n\t\treturn s\n\tdefault: // specific token\n\t\tkey := path\n\t\ttoken := MustGet(key)\n\t\trlmPath, tokenID := fqname.Parse(key)\n\t\trlmLink := fqname.RenderLink(rlmPath, tokenID)\n\t\ts := ufmt.Sprintf(\"# %s\\n\", md.EscapeText(token.GetName()))\n\t\ts += \"- symbol: \" + md.Bold(md.EscapeText(token.GetSymbol())) + \"\\n\"\n\t\ts += ufmt.Sprintf(\"- realm: %s\\n\", rlmLink)\n\t\ts += ufmt.Sprintf(\"- decimals: %d\\n\", token.GetDecimals())\n\t\ts += ufmt.Sprintf(\"- total supply: %d\\n\", token.TotalSupply())\n\t\treturn s\n\t}\n}\n\nconst (\n\tregisterEvent = \"register\"\n\tmaxSlugLen    = 128\n)\n\nfunc GetRegistry() *rotree.ReadOnlyTree {\n\treturn rotree.Wrap(registry, nil)\n}\n\n// validateSlug panics if the slug is too long or contains non-alphanumeric characters.\n// Only letters, digits, dashes, and underscores are allowed.\nfunc validateSlug(slug string) {\n\tif len(slug) \u003e maxSlugLen {\n\t\tpanic(\"grc20reg: slug too long\")\n\t}\n\tfor _, c := range slug {\n\t\tif !isAlphanumeric(c) \u0026\u0026 c != '_' \u0026\u0026 c != '-' {\n\t\t\tpanic(\"grc20reg: invalid slug character: \" + string(c))\n\t\t}\n\t}\n}\n\nfunc isAlphanumeric(c rune) bool {\n\treturn (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9')\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"treasury","path":"gno.land/r/gov/dao/treasury/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/treasury/v0\"\ngno = \"0.9\"\n"},{"name":"treasury.gno","body":"package treasury\n\nimport (\n\t\"chain/banker\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\tt \"gno.land/p/nt/treasury/v0\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nvar (\n\ttreasury  *t.Treasury\n\ttokenKeys = []string{\n\t\t// TODO: Add the default GRC20 tokens we want to support here.\n\t}\n)\n\nfunc init(cur realm) {\n\t// Define a token lister for the GRC20Banker.\n\t// For now, GovDAO uses a static list of tokens.\n\tgrc20Lister := func() map[string]*grc20.Token {\n\t\t// Get the GRC20 tokens from the registry.\n\t\ttokens := map[string]*grc20.Token{}\n\t\tfor _, key := range tokenKeys {\n\t\t\t// Get the token by its key.\n\t\t\ttoken := grc20reg.Get(key)\n\t\t\tif token != nil {\n\t\t\t\ttokens[key] = token\n\t\t\t}\n\t\t}\n\n\t\treturn tokens\n\t}\n\n\t// Init the treasury bankers.\n\tcoinsBanker, err := t.NewCoinsBankerWithOwner(cur.Address(), banker.NewBanker(banker.BankerTypeRealmSend, cur))\n\tif err != nil {\n\t\tpanic(\"failed to create CoinsBanker: \" + err.Error())\n\t}\n\tgrc20Banker, err := t.NewGRC20BankerWithOwner(cur.Address(), grc20Lister)\n\tif err != nil {\n\t\tpanic(\"failed to create GRC20Banker: \" + err.Error())\n\t}\n\tbankers := []t.Banker{\n\t\tcoinsBanker,\n\t\tgrc20Banker,\n\t}\n\n\t// Create the treasury instance with the bankers. cur.PkgPath() is\n\t// captured for render-link construction (See full history → /r/gov/dao/treasury/v0:.../history).\n\ttreasury, err = t.New(bankers, cur.PkgPath())\n\tif err != nil {\n\t\tpanic(\"failed to create treasury: \" + err.Error())\n\t}\n}\n\n// SetTokenKeys sets the GRC20 token registry keys that the treasury will use.\nfunc SetTokenKeys(cur realm, keys []string) {\n\t// Crossing function, so cur is a live minted cur and this is redundant\n\t// today; kept to match the documented rule that caller identity is\n\t// derived from cur.Previous() only under an IsCurrent() guard.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"realm value is not the caller's live cur\")\n\t}\n\tcaller := cur.Previous().PkgPath()\n\n\t// Check if the caller realm is allowed to set token keys.\n\tif !dao.InAllowedDAOs(caller) {\n\t\tpanic(\"this Realm is not allowed to send payment: \" + caller)\n\t}\n\n\t// Copied, not aliased: the grc20Lister closure re-reads tokenKeys on every\n\t// Balances() and every GRC20 payment, so storing the caller's array as\n\t// given would leave it a permanent write handle on this realm's token set.\n\ttokenKeys = make([]string, len(keys))\n\tcopy(tokenKeys, keys)\n}\n\n// Send sends a payment using the treasury instance.\nfunc Send(cur realm, payment t.Payment) {\n\t// See SetTokenKeys: redundant under the crossing-function guarantee, kept\n\t// for conformance with the IsCurrent()-before-Previous() rule.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"realm value is not the caller's live cur\")\n\t}\n\tcaller := cur.Previous().PkgPath()\n\n\t// Check if the caller realm is allowed to send payments.\n\tif !dao.InAllowedDAOs(caller) {\n\t\tpanic(\"this Realm is not allowed to send payment: \" + caller)\n\t}\n\n\t// Send the payment using the treasury instance. cur is this realm's\n\t// captured cur — passes IsCurrent inside Banker.Send and matches the\n\t// banker's owner (this realm's address) registered at init.\n\tif err := treasury.Send(0, cur, payment); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// History returns the payment history sent by the banker with the given ID.\n// Payments are paginated, with the most recent payments first.\nfunc History(bankerID string, pageNumber int, pageSize int) []t.Payment {\n\thistory, err := treasury.History(bankerID, pageNumber, pageSize)\n\tif err != nil {\n\t\tpanic(\"failed to get history: \" + err.Error())\n\t}\n\n\treturn history\n}\n\n// Balances returns the balances of the banker with the given ID.\nfunc Balances(bankerID string) []t.Balance {\n\tbalances, err := treasury.Balances(bankerID)\n\tif err != nil {\n\t\tpanic(\"failed to get balances: \" + err.Error())\n\t}\n\n\treturn balances\n}\n\n// Address returns the address of the banker with the given ID.\nfunc Address(bankerID string) string {\n\taddr, err := treasury.Address(bankerID)\n\tif err != nil {\n\t\tpanic(\"failed to get address: \" + err.Error())\n\t}\n\n\treturn addr\n}\n\n// HasBanker checks if a banker with the given ID is registered.\nfunc HasBanker(bankerID string) bool {\n\treturn treasury.HasBanker(bankerID)\n}\n\n// ListBankerIDs returns a list of all registered banker IDs.\nfunc ListBankerIDs() []string {\n\treturn treasury.ListBankerIDs()\n}\n\nfunc Render(path string) string {\n\treturn treasury.Render(path)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"impl","path":"gno.land/r/gov/dao/impl/v0","files":[{"name":"clamp.gno","body":"package impl\n\n// Attacker-controlled strings are clamped before they reach the sanitizer, so\n// escaping costs a bounded constant rather than scaling with input.\n//\n// Sanitizing runs ~11,310 gas/byte (InlineCode) against ~31 for the raw\n// concatenation it replaced, and Render is reachable unauthenticated through\n// vm/qrender under maxGasQuery = 3_000_000_000. ExecutorCreationRealm is\n// dispatched through the public dao.Executor interface, so a hostile executor\n// computes it per call while storing almost nothing. Measured on the real\n// render path: a 250KB value costs 2,839,117,770 gas unclamped against\n// 18,749,984 clamped. 250KB is just under the cap; about 265KB crosses it\n// (3,008,818,394), and past that the page cannot be rendered at all by\n// anyone. Choosing the larger number costs the attacker nothing, since the\n// value is computed per call and almost nothing is stored. Removing that\n// amplification is the point of this file.\n//\n// It does NOT make the page safe, and nothing here should be read as claiming\n// so. The executor's method body runs inside the same query and is unbounded:\n// an executor that simply burns CPU before returning a short string still\n// renders the proposal page permanently un-queryable, for a few hundred bytes\n// of on-chain storage. That predates this change — Render has always called\n// ExecutorString() and ExecutorCreationRealm() through the public interface —\n// and bounding it needs a gas budget around executor dispatch, not a clamp.\nconst (\n\t// A realm path. The longest deployable realm path in examples/ is 35 bytes\n\t// (gno.land/r/gov/dao/treasury/test/v0), so this leaves about seven times\n\t// the room anything real needs. A hostile executor returns any length it\n\t// likes, which is the reason to clamp at all. It is headroom, not a\n\t// guarantee: the package-path grammar puts no ceiling on how many segments\n\t// a path may have, so a deeply nested realm could still be cut. That costs\n\t// a truncation marker on the page and nothing else.\n\tmaxRenderedRealm = 256\n\t// \"execution failed: \" plus an executor's error message. Also bounds what\n\t// govdao.gno stores, so the realm never holds a reason it cannot show.\n\tmaxRenderedReason = 1024\n\t// A strconv error that echoes the caller's own path segment. Everything in\n\t// it is fixed text except the quoted segment, whose length the caller picks.\n\tmaxRenderedError = 256\n\t// A proposal title. The longest in examples/ is about 40 bytes, so this is\n\t// roughly nine times anything real, and long for a heading. Titles are\n\t// escaped on both the proposal page and the list page, and the list page\n\t// escapes one per proposal shown, so this is the bound that keeps a single\n\t// oversized title from pricing the whole list out of the query cap.\n\tmaxRenderedTitle = 512\n\t// A Payment's String(). The canonical impls render a coin set or an\n\t// amount plus a token key, then \" to \" and a bech32 address; a coin set\n\t// is bounded by the number of denoms a proposer cares to list and each\n\t// denom's length is unbounded, which is the reason to clamp at all.\n\tmaxRenderedPayment = 512\n)\n\n// Always clamp first — before escaping, and before any other pass over the\n// value. Trimming used to run before the clamp, which meant it walked every\n// byte the executor returned: 250KB of spaces cost 1,368,719,824 gas to render\n// nothing, and 560KB cost 3,048,904,520, past the query cap. Clamping first\n// bounds that scan and brought the same 560KB down to 16,657,792.\n//\n// Never clamp after escaping either. The escapers size their wrapper\n// from the string they are handed — InlineCode picks a fence long enough to\n// outscan the backticks it can see. Cutting a value that has already been\n// escaped can slice the closing fence off and leave the span hanging open,\n// which is worse than not clamping at all. Both call sites read\n// InlineCode(clampField(...)) for that reason, and the enormous-value case in\n// filetests/executor_disclosure_filetest.gno fails if the two are swapped.\n//\n// clampField cuts s to at most max bytes, backing off to a rune boundary so a\n// well-formed multi-byte character is not split, and marks the result so a\n// reader can tell it was cut. Input that is already invalid UTF-8 can still\n// leave a dangling lead byte; the sanitizer tolerates that. The marker avoids markdown punctuation:\n// these values are escaped downstream, and parentheses would come back as\n// \"\\(truncated\\)\".\nfunc clampField(s string, max int) string {\n\tif len(s) \u003c= max {\n\t\treturn s\n\t}\n\n\tend := max\n\t// UTF-8 continuation bytes are 0b10xxxxxx.\n\tfor end \u003e 0 \u0026\u0026 s[end]\u00260xC0 == 0x80 {\n\t\tend--\n\t}\n\n\treturn s[:end] + \"… truncated\"\n}\n"},{"name":"filter.gno","body":"package impl\n\ntype FilterByTier struct {\n\tTier string\n}\n\nfunc NewFilterByTier(tier string) FilterByTier {\n\treturn FilterByTier{Tier: tier}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/impl/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da\"\n"},{"name":"govdao.gno","body":"package impl\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"errors\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/memberstore/v0\"\n)\n\nvar ErrMemberNotFound = errors.New(\"member not found\")\n\ntype GovDAO struct {\n\tpss    ProposalsStatuses\n\trender *render\n}\n\nfunc NewGovDAO() *GovDAO {\n\tpss := NewProposalsStatuses()\n\td := \u0026GovDAO{\n\t\tpss: pss,\n\t}\n\n\td.render = NewRender(d)\n\n\t// Attach to package var (impl owns _govdao). Plain assignment is\n\t// fine — we're in impl's package, no realm transition needed.\n\t// TODO: replace with future attach().\n\t_govdao = d\n\n\treturn d\n}\n\n// Setting this to a global variable forces attaching the GovDAO struct to this\n// realm. TODO replace with future `attach()`.\nvar _govdao *GovDAO\n\nfunc (g *GovDAO) PreCreateProposal(_ int, rlm realm, r dao.ProposalRequest) (address, error) {\n\tif !g.isValidCall(0, rlm) {\n\t\treturn \"\", errors.New(ufmt.Sprintf(\"proposal creation must be done directly by a user or through the r/gov/dao proxy. caller realm: %v; caller's previous: %v\",\n\t\t\trlm, rlm.Previous()))\n\t}\n\n\t// Verify that the one creating the proposal is a member.\n\tcaller := unsafe.OriginCaller()\n\tmem, _ := getMembers(cross(rlm)).GetMember(caller)\n\tif mem == nil {\n\t\treturn caller, errors.New(\"only members can create new proposals\")\n\t}\n\n\treturn caller, nil\n}\n\nfunc (g *GovDAO) PostCreateProposal(_ int, rlm realm, r dao.ProposalRequest, pid dao.ProposalID) {\n\t// Tiers Allowed to Vote\n\ttatv := []string{memberstore.T1, memberstore.T2, memberstore.T3}\n\tswitch v := r.Filter().(type) {\n\tcase FilterByTier:\n\t\t// only members from T1 are allowed to vote when adding new members to T1\n\t\tif v.Tier == memberstore.T1 {\n\t\t\ttatv = []string{memberstore.T1}\n\t\t}\n\t\t// only members from T1 and T2 are allowed to vote when adding new members to T2\n\t\tif v.Tier == memberstore.T2 {\n\t\t\ttatv = []string{memberstore.T1, memberstore.T2}\n\t\t}\n\t}\n\tg.pss.Set(pid.String(), newProposalStatus(tatv))\n}\n\nfunc (g *GovDAO) VoteOnProposal(_ int, rlm realm, r dao.VoteRequest) error {\n\tif !g.isValidCall(0, rlm) {\n\t\treturn errors.New(\"proposal voting must be done directly by a user\")\n\t}\n\n\tcaller := unsafe.OriginCaller()\n\tmem, tie := getMembers(cross(rlm)).GetMember(caller)\n\tif mem == nil {\n\t\treturn ErrMemberNotFound\n\t}\n\n\tstatus := g.pss.GetStatus(r.ProposalID)\n\tif status == nil {\n\t\treturn errors.New(\"proposal not found\")\n\t}\n\n\tif status.Denied || status.Accepted {\n\t\treturn errors.New(ufmt.Sprintf(\"proposal closed. Accepted: %v\", status.Accepted))\n\t}\n\n\tif !status.IsAllowed(tie) {\n\t\treturn errors.New(\"member on specified tier is not allowed to vote on this proposal\")\n\t}\n\n\tmVoted, _ := status.AllVotes.GetMember(caller)\n\tif mVoted != nil {\n\t\treturn errors.New(\"already voted on proposal\")\n\t}\n\n\tswitch r.Option {\n\tcase dao.YesVote:\n\t\tstatus.AllVotes.SetMember(tie, caller, mem)\n\t\tstatus.YesVotes.SetMember(tie, caller, mem)\n\tcase dao.NoVote:\n\t\tstatus.AllVotes.SetMember(tie, caller, mem)\n\t\tstatus.NoVotes.SetMember(tie, caller, mem)\n\tcase dao.AbstainVote:\n\t\tstatus.AllVotes.SetMember(tie, caller, mem)\n\t\tstatus.AbstainVotes.SetMember(tie, caller, mem)\n\tdefault:\n\t\treturn errors.New(\"voting can only be YES, NO, or ABSTAIN\")\n\t}\n\n\treturn nil\n}\n\nfunc (g *GovDAO) PreExecuteProposal(_ int, rlm realm, pid dao.ProposalID) (bool, error) {\n\tif !g.isValidCall(0, rlm) {\n\t\treturn false, errors.New(\"proposal execution must be done directly by a user\")\n\t}\n\tstatus := g.pss.GetStatus(pid)\n\tif status == nil {\n\t\t// Unknown to this implementation: either an unknown id, or a\n\t\t// proposal created before a DAO upgrade replaced this GovDAO\n\t\t// (statuses live on the instance, so a fresh instance has none).\n\t\t// Mirrors VoteOnProposal above, which returns this same error for\n\t\t// the same lookup. Without it the nil deref panics with an opaque\n\t\t// \"runtime error: nil pointer dereference\" that reads like a VM\n\t\t// fault. It reports the condition only — see the ADR for why the\n\t\t// proposal still cannot be resolved.\n\t\treturn false, errors.New(\"proposal not found\")\n\t}\n\tif status.Denied || status.Accepted {\n\t\treturn false, errors.New(ufmt.Sprintf(\"proposal already executed. Accepted: %v\", status.Accepted))\n\t}\n\n\tif status.YesPercent(0, rlm) \u003e= law.Supermajority {\n\t\tstatus.Accepted = true\n\t\treturn true, nil\n\t}\n\n\tif status.NoPercent(0, rlm) \u003e= law.Supermajority {\n\t\tstatus.Denied = true\n\t\treturn false, nil\n\t}\n\n\treturn false, errors.New(ufmt.Sprintf(\"proposal didn't reach supermajority yet: %v\", law.Supermajority))\n}\n\nfunc (g *GovDAO) ExecuteProposal(_ int, rlm realm, pid dao.ProposalID, e dao.Executor) error {\n\tif e == nil {\n\t\tpanic(\"an executor is required to execute the proposal\")\n\t}\n\n\tstatus := g.pss.GetStatus(pid)\n\tif status == nil {\n\t\tpanic(\"proposal not found\")\n\t}\n\n\terr := e.Execute(cross(rlm))\n\tif err != nil {\n\t\tstatus.Accepted = false\n\t\tstatus.Denied = true\n\t\t// Clamped on the way in, not just on the way out. The error comes from\n\t\t// the proposal's executor — third-party code — and this assignment is a\n\t\t// write to realm storage, paid for by whoever executes the proposal\n\t\t// rather than by whoever wrote the executor. Bounding it here means the\n\t\t// realm never stores a reason larger than it can display. The clamp at\n\t\t// the render site stays, because reasons stored before this change are\n\t\t// still unbounded.\n\t\tstatus.DeniedReason = \"execution failed: \" + clampField(err.Error(), maxRenderedReason)\n\t}\n\treturn err\n}\n\nfunc (g *GovDAO) Render(cur realm, pkgPath string, path string) string {\n\t// Same-realm dispatch: pass cur through as data (non-crossing).\n\treturn g.render.Render(0, cur, pkgPath, path)\n}\n\n// isValidCall verifies that the impl method is being invoked from the\n// r/gov/dao proxy via a legitimate user transaction (MsgCall or MsgRun).\n//\n// The proxy passes its own crossing-frame Cur as rlm when calling the\n// impl methods. rlm.IsCurrent() rejects stale or stashed realm values —\n// a malicious realm cannot replay a captured proxy cur to impersonate\n// the proxy. After the IsCurrent() check:\n//   - rlm.PkgPath() == \"gno.land/r/gov/dao\" identifies the proxy\n//     unforgeably (pkg path is set at mint time by installCrossingCur).\n//   - rlm.Previous() is the caller of the proxy.\n//\n// The proxy is the only legitimate entrypoint. The impl methods are\n// non-crossing and take rlm as a regular argument, so a direct user\n// MsgCall to them cannot supply a valid rlm: the IsCurrent() check\n// rejects any forged or stashed realm value.\n//\n// This is also what makes the unsafe.OriginCaller()-based membership\n// checks safe. Those key on the transaction origin (an EOA), which is\n// correct only if the origin is the immediate caller. isValidCall\n// guarantees exactly that: it admits prev only when prev.IsUser() (a\n// direct EOA call or the origin's own ephemeral run realm) or when\n// prev's package address equals the origin — never a third-party realm\n// in the middle. Relaxing this to allow realm intermediaries would let\n// one member's vote be cast under another origin: keep the two in sync.\nfunc (g *GovDAO) isValidCall(_ int, rlm realm) bool {\n\tif !rlm.IsCurrent() {\n\t\treturn false\n\t}\n\tif rlm.PkgPath() != \"gno.land/r/gov/dao\" {\n\t\treturn false\n\t}\n\tprev := rlm.Previous()\n\t// MsgCall: proxy was called directly by an EOA (UserRealm).\n\tif prev.IsUser() {\n\t\treturn true\n\t}\n\t// MsgRun: proxy was called from the ephemeral run realm; that\n\t// realm's package address equals the EOA OriginCaller.\n\treturn chain.PackageAddress(prev.PkgPath()) == unsafe.OriginCaller()\n}\n"},{"name":"impl.gno","body":"package impl\n\nimport (\n\t\"gno.land/r/gov/dao/memberstore/v0\"\n)\n\nvar (\n\tlaw    *Law\n\tgovDAO *GovDAO = NewGovDAO()\n)\n\nfunc init() {\n\tlaw = \u0026Law{\n\t\tSupermajority: 66.66, // Two thirds\n\t}\n}\n\nfunc Render(cur realm, in string) string {\n\t// Same-realm: pass cur to govDAO.Render (also crossing, but same realm\n\t// so use the literal cur form rather than cross(cur)).\n\treturn govDAO.Render(cur, cur.PkgPath(), in)\n}\n\n// AddMember allows T1 and T2 members to freely add T3 members using their invitation points.\nfunc AddMember(cur realm, addr address) {\n\t// AGENTS.md: check IsCurrent() before cur.Previous() in a crossing function.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"AddMember: realm value is not the caller's live cur\")\n\t}\n\t// address args are not VM-validated (the raw MsgCall string is stored), so\n\t// reject a non-bech32 addr here — matching InitWithUsers. This keeps the\n\t// member store free of unauthenticable keys and of markdown/pipe/HTML\n\t// metachars that would otherwise inject into the members render table.\n\tif !addr.IsValid() {\n\t\tpanic(\"invalid member address: \" + addr.String())\n\t}\n\tcaller := cur.Previous()\n\tif !caller.IsUser() {\n\t\tpanic(\"this function must be called by an EOA through msg call or msg run\")\n\t}\n\tm, t := memberstore.Get(0, cur).GetMember(caller.Address())\n\tif m == nil {\n\t\tpanic(\"caller is not a member\")\n\t}\n\n\tif t != memberstore.T1 \u0026\u0026 t != memberstore.T2 {\n\t\tpanic(\"caller is not on T1 or T2. To add members, propose them through proposals\")\n\t}\n\n\tm.RemoveInvitationPoint()\n\n\tif err := memberstore.Get(0, cur).SetMember(memberstore.T3, addr, memberByTier(memberstore.T3)); err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\n// GetInstance returns the singleton *GovDAO. Only the loader realm may\n// call it (used during the bootstrap UpdateImpl handoff). The\n// IsCurrent() check rejects stale or stashed realm values; PkgPath()\n// after the check is the authentic immediate caller.\nfunc GetInstance(_ int, rlm realm) *GovDAO {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"GetInstance: rlm is not the caller's live cur (stale capture or sibling frame)\")\n\t}\n\tif rlm.PkgPath() != \"gno.land/r/gov/dao/loader/v0\" {\n\t\tpanic(\"not allowed\")\n\t}\n\n\treturn govDAO\n}\n"},{"name":"prop_requests.gno","body":"package impl\n\nimport (\n\t\"chain/runtime/unsafe\"\n\t\"strings\"\n\n\t\"gno.land/p/aeddi/panictoerr/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n\ttrs_pkg \"gno.land/p/nt/treasury/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/memberstore/v0\"\n\t\"gno.land/r/gov/dao/treasury/v0\"\n)\n\nfunc NewChangeLawRequest(cur realm, newLaw Law) dao.ProposalRequest {\n\tmember, _ := memberstore.Get(0, cur).GetMember(unsafe.OriginCaller())\n\tif member == nil {\n\t\tpanic(\"proposer is not a member\")\n\t}\n\n\tcb := func(cur realm) error {\n\t\tlaw = \u0026newLaw\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf(\"A new Law is proposed:\\n %v\", newLaw))\n\n\treturn dao.NewProposalRequest(\"Change Law Proposal\", \"This proposal is looking to change the actual govDAO Law\", e)\n}\n\nfunc NewUpgradeDaoImplRequest(cur realm, newDao dao.DAO, realmPkg, reason string) dao.ProposalRequest {\n\t// Rejected here as well as in UpdateImpl so the mistake surfaces when the\n\t// proposal is written, not when it executes. An empty realmPkg would be\n\t// stored as an allowlist entry matching every user realm's empty\n\t// PkgPath(), and would render as a blank name in the grant sentence below.\n\tif strings.TrimSpace(realmPkg) == \"\" {\n\t\tpanic(\"realmPkg must be the realm path being granted govDAO authority\")\n\t}\n\t// Padding is rejected for the same reason UpdateImpl rejects it: the entry\n\t// is stored as given and matched whole, so a padded path grants nobody\n\t// anything. Caught here so the author sees it, not the voters.\n\tif realmPkg != strings.TrimSpace(realmPkg) {\n\t\tpanic(\"realmPkg must not have leading or trailing spaces\")\n\t}\n\n\tmember, _ := memberstore.Get(0, cur).GetMember(unsafe.OriginCaller())\n\tif member == nil {\n\t\tpanic(\"proposer is not a member\")\n\t}\n\n\tcb := func(cur realm) error {\n\t\t// dao.UpdateImpl() must be cross-called from v0/impl but\n\t\t// what calls this cb function is r/gov/dao.\n\t\t// therefore we must cross back into v0/impl and then\n\t\t// cross call dao.UpdateRequest().\n\t\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(newDao, []string{\"gno.land/r/gov/dao/impl/v0\", realmPkg}))\n\t\treturn nil\n\t}\n\n\t// State the grant: this executor rewrites AllowedDAOs, and previously\n\t// rendered nothing at all. realmPkg is caller-supplied and lands in a code\n\t// span, so it is wrapped with sanitize.InlineCode — which emits its own\n\t// fence, so do not add backticks around it. (md.EscapeText is wrong here:\n\t// CommonMark 6.1 does not process backslash escapes inside code spans.)\n\t// Nothing ties realmPkg to newDao, which is why the text says so.\n\te := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf(\n\t\t\"Replaces the govDAO implementation with the DAO carried by this proposal.\\n\\n\"+\n\t\t\t\"After execution, only `gno.land/r/gov/dao/impl/v0` and %s may replace the \"+\n\t\t\t\"implementation, mutate the member store, or move treasury funds.\\n\\n\"+\n\t\t\t\"This grant is stated by the proposer: the incoming implementation is passed \"+\n\t\t\t\"as a value and is not verified to belong to the realm named above.\",\n\t\tsanitize.InlineCode(realmPkg)))\n\n\treturn dao.NewProposalRequest(\"Change DAO implementation\", \"This proposal is looking to change the actual govDAO implementation. Reason: \"+reason, e)\n}\n\nfunc NewAddMemberRequest(cur realm, addr address, tier string, portfolio string) dao.ProposalRequest {\n\t// Reject a non-bech32 address at proposal-build time (see AddMember): keeps\n\t// an unauthenticable / injection-bearing key out of the member store.\n\tif !addr.IsValid() {\n\t\tpanic(\"invalid member address: \" + addr.String())\n\t}\n\t_, ok := memberstore.GetTier(tier)\n\tif !ok {\n\t\tpanic(\"provided tier does not exists\")\n\t}\n\n\tif tier != memberstore.T1 \u0026\u0026 tier != memberstore.T2 {\n\t\tpanic(\"Only T1 and T2 members can be added by proposal. To add a T3 member use AddMember function directly.\")\n\t}\n\n\tif portfolio == \"\" {\n\t\tpanic(\"A portfolio for the proposed member is required\")\n\t}\n\n\tmember, _ := memberstore.Get(0, cur).GetMember(unsafe.OriginCaller())\n\tif member == nil {\n\t\tpanic(\"proposer is not a member\")\n\t}\n\n\tif member.InvitationPoints \u003c= 0 {\n\t\tpanic(\"proposer does not have enough invitation points for inviting new people to the board\")\n\t}\n\n\tcb := func(cur realm) error {\n\t\t// Add the member first, spend the proposer's invitation point second.\n\t\t//\n\t\t// SetMember RETURNS an error when the address is already a member --\n\t\t// easy to reach, since AddMember enrols T3 members directly. A returned\n\t\t// executor error does not revert: ExecuteOrRejectProposal marks the\n\t\t// proposal rejected and the transaction still commits. So with the old\n\t\t// order the point was spent and the member was not added.\n\t\t//\n\t\t// RemoveInvitationPoint can still fail, despite the build-time check\n\t\t// above: it panics at zero, and AddMember spends points from this same\n\t\t// captured member, so a proposer can drain their own between creation\n\t\t// and execution. That panics and reverts, which loses nothing.\n\t\tif err := memberstore.Get(0, cur).SetMember(tier, addr, memberByTier(tier)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmember.RemoveInvitationPoint()\n\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf(\"A new member with address %v is proposed to be on tier %v. Provided Portfolio information:\\n\\n%v\", addr, tier, portfolio))\n\n\tname := tryResolveAddr(addr)\n\treturn dao.NewProposalRequestWithFilter(\n\t\tufmt.Sprintf(\"New %s Member Proposal\", tier),\n\t\tufmt.Sprintf(\"This is a proposal to add `%s` to **%s**.\\n#### `%s`'s Portfolio:\\n\\n%s\\n\", name, tier, name, portfolio),\n\t\te,\n\t\tFilterByTier{Tier: tier},\n\t)\n}\n\nfunc NewWithdrawMemberRequest(cur realm, addr address, reason string) dao.ProposalRequest {\n\tmember, tier := memberstore.Get(0, cur).GetMember(addr)\n\tif member == nil {\n\t\tpanic(\"user we want to remove not found\")\n\t}\n\n\treason = strings.TrimSpace(reason)\n\tif tier == memberstore.T1 \u0026\u0026 reason == \"\" {\n\t\tpanic(\"T1 user removals must contains a reason.\")\n\t}\n\n\tcb := func(cur realm) error {\n\t\tmemberstore.Get(0, cur).RemoveMember(addr)\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf(\"Member with address %v will be withdrawn.\\n\\n REASON: %v.\", addr, reason))\n\n\treturn dao.NewProposalRequest(\n\t\t\"Member Withdrawal Proposal\",\n\t\tufmt.Sprintf(\"This is a proposal to remove %s from the GovDAO\", tryResolveAddr(addr)),\n\t\te,\n\t)\n}\n\nfunc NewPromoteMemberRequest(cur realm, addr address, fromTier string, toTier string) dao.ProposalRequest {\n\tcb := func(cur realm) error {\n\t\t// Fail on an unknown destination tier before touching the member.\n\t\t//\n\t\t// Everything that can be checked before a write is checked here, and\n\t\t// RETURNS. A returned executor error rejects the proposal and closes it,\n\t\t// and since nothing has been mutated yet that commits nothing.\n\t\t//\n\t\t// After RemoveMember the policy inverts: a return would commit a member\n\t\t// who was removed and not re-added, so everything below panics instead,\n\t\t// which reverts the whole transaction.\n\t\t// A tier dropped from the global table. NewChangeTiersRequest replaces\n\t\t// that table wholesale, so a proposal listing only T1 and T2 removes T3\n\t\t// for good. memberByTier would not notice: it switches on the constant\n\t\t// and ignores GetTier's ok, so the promotion would succeed and hand the\n\t\t// member zero invitation points. Untested -- reaching it needs a passed\n\t\t// tier-change proposal, which rewrites state every other test shares.\n\t\tif _, ok := memberstore.GetTier(toTier); !ok {\n\t\t\treturn ufmt.Errorf(\"unknown destination tier: %s\", toTier)\n\t\t}\n\n\t\tmbt := memberstore.Get(0, cur)\n\n\t\t// SetMember consults the store's own index, not the global tier table\n\t\t// above: DeleteAll empties the buckets and leaves the definitions.\n\t\tif !mbt.Has(toTier) {\n\t\t\treturn ufmt.Errorf(\"destination tier is missing from the member store: %s\", toTier)\n\t\t}\n\n\t\tprevTier := mbt.RemoveMember(addr)\n\t\tif prevTier == \"\" {\n\t\t\tpanic(\"member not found, so cannot be promoted\")\n\t\t}\n\n\t\tif prevTier != fromTier {\n\t\t\tpanic(\"previous tier changed from the one indicated in the proposal\")\n\t\t}\n\n\t\tif err := mbt.SetMember(toTier, addr, memberByTier(toTier)); err != nil {\n\t\t\t// Unreachable: both of SetMember's failures are ruled out above.\n\t\t\t// Panicking is what makes it safe to be wrong about that.\n\t\t\tpanic(\"promotion failed after removal: \" + err.Error())\n\t\t}\n\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, ufmt.Sprintf(\"A new member with address %v will be promoted from tier %v to tier %v.\", addr, fromTier, toTier))\n\n\treturn dao.NewProposalRequestWithFilter(\n\t\t\"Member Promotion Proposal\",\n\t\tufmt.Sprintf(\"This is a proposal to promote %s from **%s** to **%s**.\", tryResolveAddr(addr), fromTier, toTier),\n\t\te,\n\t\tFilterByTier{Tier: toTier},\n\t)\n}\n\nfunc NewTreasuryPaymentRequest(cur realm, payment trs_pkg.Payment, reason string) dao.ProposalRequest {\n\t// A foreign impl renders a Payment line no Banker will process, so it would\n\t// fail only at execution, after the vote. Rejected here so the proposer\n\t// sees it, not the voters. See IsCanonicalPayment.\n\tif !trs_pkg.IsCanonicalPayment(payment) {\n\t\tpanic(\"payment must be built by treasury.NewCoinsPayment or treasury.NewGRC20Payment\")\n\t}\n\tif !treasury.HasBanker(payment.BankerID()) {\n\t\tpanic(\"banker not registered in treasury with ID: \" + payment.BankerID())\n\t}\n\n\treason = strings.TrimSpace(reason)\n\tif reason == \"\" {\n\t\tpanic(\"treasury payment request requires a reason\")\n\t}\n\n\tcb := func(cur realm) error {\n\t\treturn panictoerr.PanicToError(func() {\n\t\t\ttreasury.Send(cross(cur), payment)\n\t\t})\n\t}\n\n\t// Both are caller-supplied and land in the same body as the Payment line a\n\t// member votes on, which render.gno emits raw. InlineText folds newlines to\n\t// spaces, so neither can start a line of its own and forge that label.\n\t// Clamp before escaping, per clamp.gno.\n\tsafeReason := sanitize.InlineText(clampField(reason, maxRenderedReason))\n\tsafePayment := sanitize.InlineText(clampField(payment.String(), maxRenderedPayment))\n\n\te := dao.NewSimpleExecutor(0, cur,\n\t\tcb,\n\t\tufmt.Sprintf(\n\t\t\t\"A payment will be sent by the GovDAO treasury.\\n\\nReason: %s\\n\\nPayment: %s.\",\n\t\t\tsafeReason,\n\t\t\tsafePayment,\n\t\t),\n\t)\n\n\treturn dao.NewProposalRequest(\n\t\t\"Treasury Payment\",\n\t\tufmt.Sprintf(\n\t\t\t\"This proposal is looking to send a payment using the treasury.\\n\\nReason: %s\\n\\nPayment: %s\",\n\t\t\tsafeReason,\n\t\t\tsafePayment,\n\t\t),\n\t\te,\n\t)\n}\n\n// NewTreasuryGRC20TokensUpdate creates a proposal request to update the list of GRC20 tokens registry\n// keys used by the treasury. The new list, if voted and accepted, will overwrite the current one.\nfunc NewTreasuryGRC20TokensUpdate(cur realm, newTokenKeys []string) dao.ProposalRequest {\n\tif len(newTokenKeys) == 0 {\n\t\tpanic(\"the list of new tokens is empty\")\n\t}\n\n\t// Copied for the same reason NewCoinsPayment copies its coins: the bullet\n\t// list below is rendered once at creation, but the executor closure\n\t// re-reads the slice at execution, so the caller could otherwise install a\n\t// token set the board never saw.\n\tkeys := make([]string, len(newTokenKeys))\n\tcopy(keys, newTokenKeys)\n\n\tcb := func(cur realm) error {\n\t\treturn panictoerr.PanicToError(func() {\n\t\t\t// NOTE:: Consider checking if the keys are already registered\n\t\t\t// in the grc20reg before updating the treasury tokens keys.\n\t\t\ttreasury.SetTokenKeys(cross(cur), keys)\n\t\t})\n\t}\n\n\tbulletList := md.BulletList(keys)\n\n\te := dao.NewSimpleExecutor(0, cur,\n\t\tcb,\n\t\tufmt.Sprintf(\n\t\t\t\"The list of GRC20 tokens used by the treasury will be updated.\\n\\nNew Token Keys:\\n%s.\\n\",\n\t\t\tbulletList,\n\t\t),\n\t)\n\n\treturn dao.NewProposalRequest(\n\t\t\"Treasury GRC20 Tokens Update\",\n\t\tufmt.Sprintf(\n\t\t\t\"This proposal is looking to update the list of GRC20 tokens used by the treasury.\\n\\nNew Token Keys:\\n%s\",\n\t\t\tbulletList,\n\t\t),\n\t\te,\n\t)\n}\n\nfunc memberByTier(tier string) *memberstore.Member {\n\tswitch tier {\n\tcase memberstore.T1:\n\t\tt, _ := memberstore.GetTier(memberstore.T1)\n\t\treturn memberstore.NewMember(t.InvitationPoints)\n\tcase memberstore.T2:\n\t\tt, _ := memberstore.GetTier(memberstore.T2)\n\t\treturn memberstore.NewMember(t.InvitationPoints)\n\tcase memberstore.T3:\n\t\tt, _ := memberstore.GetTier(memberstore.T3)\n\t\treturn memberstore.NewMember(t.InvitationPoints)\n\tdefault:\n\t\tpanic(\"member not found by the specified tier\")\n\t}\n}\n"},{"name":"render.gno","body":"package impl\n\nimport (\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/helplink/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/bptree/pager/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/sys/users\"\n)\n\ntype render struct {\n\trelativeRealmPath string\n\trouter            *mux.Router\n\tpssPager          *pager.Pager\n}\n\nfunc NewRender(d *GovDAO) *render {\n\tren := \u0026render{\n\t\tpssPager: pager.NewPager(d.pss.BPTree, 5, true),\n\t}\n\n\tr := mux.NewRouter()\n\n\t// Handlers use mux's rlm-aware shape: rlm is supplied at RenderRlm\n\t// dispatch time rather than captured at NewRender time. This lets\n\t// downstream crossing reads (dao.GetProposal etc.) use cross(rlm)\n\t// without relying on bare cross or restructuring the router.\n\tr.HandleFuncRlm(\"\", func(_ int, rlm realm, rw *mux.ResponseWriter, req *mux.Request) {\n\t\trw.Write(ren.renderActiveProposals(0, rlm, req.RawPath, d))\n\t})\n\n\tr.HandleFuncRlm(\"{pid}\", func(_ int, rlm realm, rw *mux.ResponseWriter, req *mux.Request) {\n\t\trw.Write(ren.renderProposalPage(0, rlm, req.GetVar(\"pid\"), d))\n\t})\n\n\tr.HandleFuncRlm(\"{pid}/votes\", func(_ int, rlm realm, rw *mux.ResponseWriter, req *mux.Request) {\n\t\trw.Write(ren.renderVotesForProposal(0, rlm, req.GetVar(\"pid\"), d))\n\t})\n\n\tren.router = r\n\n\treturn ren\n}\n\nfunc (ren *render) Render(_ int, rlm realm, pkgPath string, path string) string {\n\trelativePath, found := strings.CutPrefix(pkgPath, runtime.ChainDomain())\n\tif !found {\n\t\tpanic(ufmt.Sprintf(\n\t\t\t\"realm package with unexpected name found: %v in chain domain %v\",\n\t\t\tpkgPath, runtime.ChainDomain()))\n\t}\n\tren.relativeRealmPath = relativePath\n\treturn ren.router.RenderRlm(0, rlm, path)\n}\n\nfunc (ren *render) renderActiveProposals(_ int, rlm realm, url string, d *GovDAO) string {\n\tout := \"# GovDAO\\n\"\n\tout += \"## Members\\n\"\n\tout += \"[\u003e Go to Memberstore \u003c](/r/gov/dao/memberstore/v0)\\n\"\n\tout += \"## Proposals\\n\"\n\tpage, perr := ren.pssPager.GetPageByPath(url)\n\tif perr != nil {\n\t\t// A query url.Parse rejects (e.g. a control byte) is the caller's own\n\t\t// malformed input; render the default first page instead of aborting\n\t\t// this read-only render. ParseQuery already tolerates bad page/size\n\t\t// values, so every currently-working input is unaffected.\n\t\tpage = ren.pssPager.GetPage(1)\n\t}\n\tif len(page.Items) == 0 {\n\t\tout += \"\\nNo proposals yet.\\n\\n\"\n\t\treturn out\n\t}\n\n\tfor _, item := range page.Items {\n\t\tseqpid, err := seqid.FromString(item.Key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tout += ren.renderProposalListItem(0, rlm, ufmt.Sprintf(\"%v\", int64(seqpid)), d)\n\t\tout += \"---\\n\\n\"\n\t}\n\n\tout += page.Picker(\"\")\n\n\treturn out\n}\n\nfunc (ren *render) renderProposalPage(_ int, rlm realm, sPid string, d *GovDAO) string {\n\tpid, err := strconv.ParseInt(sPid, 10, 64)\n\tif err != nil {\n\t\t// err echoes the caller's raw pid segment (strconv quotes it but leaves\n\t\t// markdown/HTML metachars); escape+clamp it like every other untrusted\n\t\t// slot on this page, since Render is reachable unauthenticated.\n\t\treturn ufmt.Sprintf(\"# Error: Invalid proposal ID format.\\n\\n\\n%s\\n\\n\", md.EscapeText(clampField(err.Error(), maxRenderedError)))\n\t}\n\n\tp, err := dao.GetProposal(dao.ProposalID(pid))\n\tif err != nil {\n\t\treturn ufmt.Sprintf(\"# Proposal not found\\n\\n%s\", err.Error())\n\t}\n\n\t// pid is user-supplied and the proposal itself lives on the proxy, so\n\t// GetProposal can succeed for a proposal this implementation has no status\n\t// for — the same post-upgrade case PreExecuteProposal guards (statuses live\n\t// on the instance, so a fresh instance has none). Without this the page\n\t// panics at ps.String below. renderProposalListItem needs no such guard:\n\t// its pids are iterated out of pss itself, so a status always exists.\n\tps := d.pss.GetStatus(dao.ProposalID(pid))\n\tif ps == nil {\n\t\treturn ufmt.Sprintf(\"# Proposal #%v not available\\n\\nThis proposal was not created by the current govDAO implementation, so it has no voting status here.\", pid)\n\t}\n\n\tout := ufmt.Sprintf(\"## Prop #%v - %v\\n\", pid, md.EscapeText(clampField(p.Title(), maxRenderedTitle)))\n\tout += \"Author: \" + tryResolveAddr(p.Author()) + \"\\n\\n\"\n\n\tout += p.Description()\n\tout += \"\\n\\n\"\n\n\t// Add executor metadata if available\n\tif p.ExecutorString() != \"\" {\n\t\tout += ufmt.Sprintf(`This proposal contains the following metadata:\n\n%s\n\n`, p.ExecutorString())\n\t}\n\n\t// Disclosed independently of the description: this names the realm whose\n\t// code runs if the proposal passes. Sharing the gate above hid it for every\n\t// proposal built with an empty executor description — 16 call sites across\n\t// 7 production realms, nearly all r/sys/* governance actions.\n\t//\n\t// Escaped, not trusted: CreationRealm() is dispatched through the public\n\t// dao.Executor interface, so only SimpleExecutor's value is VM-captured;\n\t// a third-party executor returns any string it likes.\n\t// Guarded on the sanitized value, not the raw one: InlineCode returns \"\"\n\t// for input that strips to nothing (bidi/zero-width only), and TrimSpace\n\t// catches plain whitespace, so neither prints a label with nothing after\n\t// it. This is tidiness, not a boundary: a zero-width/space mixture still\n\t// renders an empty-looking span, and a hostile executor can always return\n\t// a plausible-looking lie. The security property is the escaping below.\n\tif cr := sanitize.InlineCode(strings.TrimSpace(clampField(p.ExecutorCreationRealm(), maxRenderedRealm))); cr != \"\" {\n\t\tout += ufmt.Sprintf(\"Executor created in: %s\\n\", cr)\n\t\tout += \"\\n\\n\"\n\t}\n\n\tout += \"\\n\\n---\\n\\n\"\n\tout += ps.String(0, rlm)\n\tout += \"\\n\"\n\tout += ufmt.Sprintf(\"[Detailed voting list](%v:%v/votes)\", ren.relativeRealmPath, pid)\n\tout += \"\\n\\n---\\n\\n\"\n\n\tout += renderActionBar(ufmt.Sprintf(\"%v\", pid))\n\n\treturn out\n}\n\nfunc (ren *render) renderProposalListItem(_ int, rlm realm, sPid string, d *GovDAO) string {\n\tpid, err := strconv.ParseInt(sPid, 10, 64)\n\tif err != nil {\n\t\t// err echoes the caller's raw pid segment (strconv quotes it but leaves\n\t\t// markdown/HTML metachars); escape+clamp it like every other untrusted\n\t\t// slot on this page, since Render is reachable unauthenticated.\n\t\treturn ufmt.Sprintf(\"# Error: Invalid proposal ID format.\\n\\n\\n%s\\n\\n\", md.EscapeText(clampField(err.Error(), maxRenderedError)))\n\t}\n\n\tp, err := dao.GetProposal(dao.ProposalID(pid))\n\tif err != nil {\n\t\treturn ufmt.Sprintf(\"# Proposal not found\\n\\n%s\\n\\n\", err.Error())\n\t}\n\n\tps := d.pss.GetStatus(dao.ProposalID(pid))\n\tout := ufmt.Sprintf(\"### [Prop #%v - %v](%v:%v)\\n\", pid, md.EscapeText(clampField(p.Title(), maxRenderedTitle)), ren.relativeRealmPath, pid)\n\tout += ufmt.Sprintf(\"Author: %s\\n\\n\", tryResolveAddr(p.Author()))\n\n\tout += \"Status: \" + getPropStatus(ps)\n\tout += \"\\n\\n\"\n\n\tout += \"Tiers eligible to vote: \"\n\tout += strings.Join(ps.TiersAllowedToVote, \", \")\n\n\tout += \"\\n\\n\"\n\treturn out\n}\n\nfunc (ren *render) renderVotesForProposal(_ int, rlm realm, sPid string, d *GovDAO) string {\n\tpid, err := strconv.ParseInt(sPid, 10, 64)\n\tif err != nil {\n\t\t// err echoes the caller's raw pid segment (strconv quotes it but leaves\n\t\t// markdown/HTML metachars); escape+clamp it like every other untrusted\n\t\t// slot on this page, since Render is reachable unauthenticated.\n\t\treturn ufmt.Sprintf(\"# Error: Invalid proposal ID format.\\n\\n\\n%s\\n\\n\", md.EscapeText(clampField(err.Error(), maxRenderedError)))\n\t}\n\n\tps := d.pss.GetStatus(dao.ProposalID(pid))\n\tif ps == nil {\n\t\treturn ufmt.Sprintf(\"# Proposal not found\\n\\nProposal %v does not exist.\", pid)\n\t}\n\n\tout := \"\"\n\tout += ufmt.Sprintf(\"# Proposal #%v - Vote List\\n\\n\", pid)\n\tout += StringifyVotes(0, rlm, ps)\n\n\treturn out\n}\n\nfunc isPropActive(ps *proposalStatus) bool {\n\treturn !ps.Accepted \u0026\u0026 !ps.Denied\n}\n\nfunc getPropStatus(ps *proposalStatus) string {\n\tif ps == nil {\n\t\treturn \"UNKNOWN\"\n\t}\n\tif ps.Accepted {\n\t\treturn \"ACCEPTED\"\n\t} else if ps.Denied {\n\t\treturn \"REJECTED\"\n\t}\n\treturn \"ACTIVE\"\n}\n\nfunc renderActionBar(sPid string) string {\n\tout := \"### Actions\\n\"\n\n\tproxy := helplink.Realm(\"gno.land/r/gov/dao\")\n\tout += proxy.Func(\"Vote YES\", \"MustVoteOnProposalSimple\", \"pid\", sPid, \"option\", \"YES\") + \" | \"\n\tout += proxy.Func(\"Vote NO\", \"MustVoteOnProposalSimple\", \"pid\", sPid, \"option\", \"NO\") + \" | \"\n\tout += proxy.Func(\"Vote ABSTAIN\", \"MustVoteOnProposalSimple\", \"pid\", sPid, \"option\", \"ABSTAIN\")\n\n\tout += \"\\n\\n\"\n\tout += \"WARNING: Please double check transaction data before voting.\"\n\treturn out\n}\n\n// tryResolveAddr renders the author/voter as a username link. RenderLink\n// interpolates the username raw into \"[@name](/u/name)\" (r/sys/users), so this\n// is markdown-safe ONLY because r/sys/users validateName restricts names to\n// ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ (max 64) — no markdown/HTML metachar. If that\n// charset ever loosens, this line and writeVotes in types.gno need escaping.\nfunc tryResolveAddr(addr address) string {\n\tuserData := users.ResolveAddress(addr)\n\tif userData == nil {\n\t\treturn addr.String()\n\t}\n\treturn userData.RenderLink(\"\")\n}\n"},{"name":"types.gno","body":"package impl\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/memberstore/v0\"\n)\n\ntype Law struct {\n\tSupermajority float64\n}\n\nfunc NewLaw(supermajority float64) Law {\n\treturn Law{Supermajority: supermajority}\n}\n\nfunc (l *Law) String() string {\n\treturn ufmt.Sprintf(\"This law contains the following data:\\n\\n- Supermajority: %v%%\", l.Supermajority)\n}\n\n// ProposalsStatuses contains the status of all the proposals indexed by the proposal ID.\ntype ProposalsStatuses struct {\n\t*bptree.BPTree // map[int]*proposalStatus\n}\n\nfunc NewProposalsStatuses() ProposalsStatuses {\n\treturn ProposalsStatuses{bptree.NewBPTree32()}\n}\n\nfunc (pss ProposalsStatuses) GetStatus(id dao.ProposalID) *proposalStatus {\n\tif pss.BPTree == nil {\n\t\treturn nil\n\t}\n\n\tpids := id.String()\n\tpsv := pss.Get(pids)\n\tif psv == nil {\n\t\treturn nil\n\t}\n\n\tps, ok := psv.(*proposalStatus)\n\tif !ok {\n\t\tpanic(\"ProposalsStatuses must contains only proposalStatus types\")\n\t}\n\n\treturn ps\n}\n\ntype proposalStatus struct {\n\tYesVotes     memberstore.MembersByTier\n\tNoVotes      memberstore.MembersByTier\n\tAbstainVotes memberstore.MembersByTier\n\tAllVotes     memberstore.MembersByTier\n\n\tAccepted bool\n\tDenied   bool\n\n\tDeniedReason string\n\n\tTiersAllowedToVote []string\n}\n\nfunc getMembers(cur realm) memberstore.MembersByTier {\n\treturn memberstore.Get(0, cur)\n}\n\nfunc newEmptyVoteStore() memberstore.MembersByTier {\n\tmbt := memberstore.NewMembersByTier()\n\tmbt.SetTier(memberstore.T1)\n\tmbt.SetTier(memberstore.T2)\n\tmbt.SetTier(memberstore.T3)\n\treturn mbt\n}\n\nfunc newProposalStatus(allowedToVote []string) *proposalStatus {\n\treturn \u0026proposalStatus{\n\t\tYesVotes:           newEmptyVoteStore(),\n\t\tNoVotes:            newEmptyVoteStore(),\n\t\tAbstainVotes:       newEmptyVoteStore(),\n\t\tAllVotes:           newEmptyVoteStore(),\n\t\tTiersAllowedToVote: allowedToVote,\n\t}\n}\n\n// totalPower computes the total voting power dynamically from current members\n// rather than using a snapshot. See https://github.com/gnolang/gno/pull/5271#discussion_r2952523023\n//\n// Non-crossing: rlm is threaded into the crossing getMembers(cross(rlm))\n// call. The proposalStatus methods that compose this (votePowerPercent,\n// YesPercent etc., String) all take `_ int, rlm realm` for the same reason.\nfunc (ps *proposalStatus) totalPower(_ int, rlm realm) float64 {\n\tmembers := getMembers(cross(rlm))\n\tvar tp float64\n\tfor _, tn := range ps.TiersAllowedToVote {\n\t\tpower := memberstore.GetTierPower(tn, members)\n\t\ttp += power * float64(members.GetTierSize(tn))\n\t}\n\treturn tp\n}\n\nfunc (ps *proposalStatus) votePowerPercent(_ int, rlm realm, votes memberstore.MembersByTier) float64 {\n\tmembers := getMembers(cross(rlm))\n\tvar vp float64\n\tmemberstore.IterateTiers(func(tn string, tier memberstore.Tier) bool {\n\t\tpower := memberstore.GetTierPower(tn, members)\n\t\tts := votes.GetTierSize(tn)\n\t\tvp = vp + (power * float64(ts))\n\t\treturn false\n\t})\n\ttp := ps.totalPower(0, rlm)\n\tif tp == 0 {\n\t\treturn 0\n\t}\n\treturn (vp / tp) * 100\n}\n\nfunc (ps *proposalStatus) YesPercent(_ int, rlm realm) float64 {\n\treturn ps.votePowerPercent(0, rlm, ps.YesVotes)\n}\n\nfunc (ps *proposalStatus) NoPercent(_ int, rlm realm) float64 {\n\treturn ps.votePowerPercent(0, rlm, ps.NoVotes)\n}\n\nfunc (ps *proposalStatus) AbstainPercent(_ int, rlm realm) float64 {\n\treturn ps.votePowerPercent(0, rlm, ps.AbstainVotes)\n}\n\nfunc (ps *proposalStatus) IsAllowed(tier string) bool {\n\tfor _, ta := range ps.TiersAllowedToVote {\n\t\tif ta == tier {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n// XXX: can be optimized by passing down total power to Yes/No/Abstain percent fn to avoid re-computing\nfunc (ps *proposalStatus) String(_ int, rlm realm) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"### Stats\\n\")\n\n\tif ps.Accepted {\n\t\tsb.WriteString(\"- **PROPOSAL HAS BEEN ACCEPTED**\\n\")\n\t} else if ps.Denied {\n\t\tsb.WriteString(\"- **PROPOSAL HAS BEEN DENIED**\\n\")\n\t\tif ps.DeniedReason != \"\" {\n\t\t\tsb.WriteString(\"REASON: \")\n\t\t\t// DeniedReason is \"execution failed: \" + err.Error() from the\n\t\t\t// proposal's executor callback, which any third-party realm can\n\t\t\t// supply. Raw, it wrote attacker-controlled markdown directly beneath\n\t\t\t// the \"PROPOSAL HAS BEEN DENIED\" line. InlineText folds newlines, so\n\t\t\t// the reason cannot leave the REASON: line, and escapes emphasis and\n\t\t\t// raw HTML.\n\t\t\tsb.WriteString(sanitize.InlineText(clampField(ps.DeniedReason, maxRenderedReason)))\n\t\t\tsb.WriteString(\"\\n\")\n\t\t}\n\t} else {\n\t\tsb.WriteString(\"- **Proposal is open for votes**\\n\")\n\t}\n\n\tsb.WriteString(\"- Tiers eligible to vote: \")\n\tsb.WriteString(strings.Join(ps.TiersAllowedToVote, \", \"))\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(ufmt.Sprintf(\"- YES PERCENT: %v%%\\n\", ps.YesPercent(0, rlm)))\n\tsb.WriteString(ufmt.Sprintf(\"- NO PERCENT: %v%%\\n\", ps.NoPercent(0, rlm)))\n\tsb.WriteString(ufmt.Sprintf(\"- ABSTAIN PERCENT: %v%%\\n\", ps.AbstainPercent(0, rlm)))\n\n\treturn sb.String()\n}\n\nfunc StringifyVotes(_ int, rlm realm, ps *proposalStatus) string {\n\tvar sb strings.Builder\n\n\twriteVotes(0, rlm, \u0026sb, ps.YesVotes, \"YES\")\n\twriteVotes(0, rlm, \u0026sb, ps.NoVotes, \"NO\")\n\twriteVotes(0, rlm, \u0026sb, ps.AbstainVotes, \"ABSTAIN\")\n\n\tif sb.String() == \"\" {\n\t\treturn \"No one voted yet.\"\n\t}\n\n\treturn sb.String()\n}\n\nfunc writeVotes(_ int, rlm realm, sb *strings.Builder, t memberstore.MembersByTier, title string) {\n\tif t.Size() == 0 {\n\t\treturn\n\t}\n\tmembers := getMembers(cross(rlm))\n\tt.Iterate(\"\", \"\", func(tn string, value interface{}) bool {\n\t\t_, ok := memberstore.GetTier(tn)\n\t\tif !ok {\n\t\t\tpanic(\"tier not found\")\n\t\t}\n\n\t\tpower := memberstore.GetTierPower(tn, members)\n\n\t\tsb.WriteString(ufmt.Sprintf(\"%v from %v (VPPM %v):\\n\\n\", title, tn, power))\n\t\tms, _ := value.(*bptree.BPTree)\n\t\tms.Iterate(\"\", \"\", func(addr string, _ interface{}) bool {\n\t\t\tsb.WriteString(\"- \" + tryResolveAddr(address(addr)) + \"\\n\")\n\t\t\treturn false\n\t\t})\n\n\t\tsb.WriteString(\"\\n\")\n\n\t\treturn false\n\t})\n}\n\nfunc StringifyProposal(p *dao.Proposal) string {\n\tout := ufmt.Sprintf(`\n### Title: %s\n\n### Proposed by: %s\n\n%s\n`, p.Title(), p.Author(), p.Description())\n\n\tif p.ExecutorString() != \"\" {\n\t\tout += ufmt.Sprintf(`\nThis proposal contains the following metadata:\n\n%s\n`, p.ExecutorString())\n\t}\n\n\t// Disclosed independently of the metadata string, and escaped, for the\n\t// same reasons as render.renderProposalPage.\n\tif cr := sanitize.InlineCode(strings.TrimSpace(clampField(p.ExecutorCreationRealm(), maxRenderedRealm))); cr != \"\" {\n\t\tout += ufmt.Sprintf(\"\\nExecutor created in: %s\\n\", cr)\n\t}\n\n\treturn out\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"loader","path":"gno.land/r/gov/dao/loader/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/loader/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da\"\n"},{"name":"loader.gno","body":"// loader.gno initialises the govDAO v0 implementation and tier structure.\n//\n// It intentionally does NOT add any members or set AllowedDAOs.  When the\n// allowedDAOs list in the DAO proxy is empty, InAllowedDAOs() returns true\n// for any caller (see r/gov/dao/proxy.gno), which lets a subsequent MsgRun\n// bootstrap the member set and then lock things down.\n//\n// Bootstrap flow (official network genesis or local dev):\n//\n//  1. All packages — including this loader — are deployed via MsgAddPackage.\n//     The loader sets up tier entries and the DAO implementation.\n//  2. A MsgRun executes a setup script (e.g. govdao_prop1.gno) which:\n//     a. Adds a temporary deployer as T1 member (for supermajority).\n//     b. Creates a governance proposal to register validators, votes YES,\n//     and executes it.\n//     c. Adds the real govDAO members directly via memberstore.Get().\n//     d. Removes the temporary deployer.\n//     e. Calls dao.UpdateImpl to set AllowedDAOs, locking down access.\n//\n// See misc/deployments/ for concrete genesis generation examples.\npackage loader\n\nimport (\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/impl/v0\"\n\t\"gno.land/r/gov/dao/memberstore/v0\"\n)\n\nfunc init(cur realm) {\n\t// Create tier entries in the members tree (required before any SetMember).\n\tmemberstore.Get(0, cur).SetTier(memberstore.T1)\n\tmemberstore.Get(0, cur).SetTier(memberstore.T2)\n\tmemberstore.Get(0, cur).SetTier(memberstore.T3)\n\n\t// Set the DAO implementation.  AllowedDAOs is intentionally left empty\n\t// so that the genesis MsgRun can manipulate the memberstore directly.\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.GetInstance(0, cur), nil))\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"mdform","path":"gno.land/p/jeronimoalbi/mdform/v0","files":[{"name":"README.md","body":"# Markdown Form Package\n\nThe package provides a very simplistic [Gno-Flavored Markdown form](/r/docs/markdown#forms) generator.\n\nForms can be created by sequentially calling form methods to create each one of the form fields.\n\nExample usage:\n\n```go\nimport \"gno.land/p/jeronimoalbi/mdform/v0\"\n\nfunc Render(string) string {\n    form := mdform.New()\n\n    // Add a text input field\n    form.Input(\n        \"name\",\n        \"placeholder\", \"Name\",\n        \"value\", \"John Doe\",\n    )\n\n    // Add a select field with three possible values\n    form.Select(\n        \"country\",\n        \"United States\",\n        \"description\", \"Select your country\",\n    )\n    form.Select(\n        \"country\",\n        \"Spain\",\n    )\n    form.Select(\n        \"country\",\n        \"Germany\",\n    )\n\n    // Add a checkbox group with two possible values\n    form.Checkbox(\n        \"interests\",\n        \"music\",\n        \"description\", \"What do you like to do?\",\n    )\n    form.Checkbox(\n        \"interests\",\n        \"tech\",\n        \"checked\", \"true\",\n    )\n\n    return form.String()\n}\n```\n\nForm output:\n\n```html\n\u003cgno-form exec=\"FunctionName\"\u003e\n    \u003cgno-input name=\"name\" placeholder=\"Name\" value=\"John Doe\" /\u003e\n    \u003cgno-select name=\"country\" value=\"United States\" description=\"Select your country\" /\u003e\n    \u003cgno-select name=\"country\" value=\"Spain\" /\u003e\n    \u003cgno-select name=\"country\" value=\"Germany\" /\u003e\n    \u003cgno-input type=\"checkbox\" name=\"interests\" value=\"music\" description=\"What do you like to do?\" /\u003e\n    \u003cgno-input type=\"checkbox\" name=\"interests\" value=\"tech\" checked=\"true\" /\u003e\n\u003c/gno-form\u003e\n```\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jeronimoalbi/mdform/v0\"\ngno = \"0.9\"\n"},{"name":"mdform.gno","body":"package mdform\n\nimport (\n\t\"html\"\n\t\"strings\"\n)\n\nconst (\n\tInputTypeText     = \"text\"\n\tInputTypeNumber   = \"number\"\n\tInputTypeEmail    = \"email\"\n\tInputTypePhone    = \"tel\"\n\tInputTypePassword = \"password\"\n\tInputTypeRadio    = \"radio\"\n\tInputTypeCheckbox = \"checkbox\"\n)\n\nvar (\n\tformAttributes     = []string{\"exec\", \"path\"}\n\tinputAttributes    = []string{\"checked\", \"description\", \"placeholder\", \"readonly\", \"required\", \"type\", \"value\"}\n\ttextareaAttributes = []string{\"placeholder\", \"readonly\", \"required\", \"rows\", \"value\"}\n\tselectAttributes   = []string{\"description\", \"readonly\", \"required\", \"selected\"}\n)\n\n// New creates a new form.\nfunc New(attributes ...string) *Form {\n\tassertEvenAttributes(attributes)\n\n\tform := \u0026Form{}\n\tfor i := 0; i \u003c len(attributes); i += 2 {\n\t\tname, value := attributes[i], attributes[i+1]\n\n\t\tassertIsValidAttribute(name, formAttributes)\n\n\t\tform.attrs = append(form.attrs, formatAttribute(name, value))\n\t}\n\treturn form\n}\n\n// Form is a form that can be rendered to Gno-Flavored Markdown.\ntype Form struct {\n\tattrs  []string\n\tfields []string\n}\n\n// Input appends a new input to form fields.\n// Use `Form.Radio()` or `Form.Checkbox()` to append those types of inputs to the form.\n// Method panics when appending inputs of type radio or checkbox, or when attributes are not valid.\nfunc (f *Form) Input(name string, attributes ...string) *Form {\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tpanic(\"form input name is required\")\n\t}\n\n\tassertEvenAttributes(attributes)\n\n\tattrs := []string{formatAttribute(\"name\", name)}\n\tfor i := 0; i \u003c len(attributes); i += 2 {\n\t\tname, value := attributes[i], attributes[i+1]\n\t\tif name == \"type\" {\n\t\t\tswitch value {\n\t\t\tcase InputTypeRadio:\n\t\t\t\tpanic(\"use form.Radio() to create inputs of type radio\")\n\t\t\tcase InputTypeCheckbox:\n\t\t\t\tpanic(\"use form.Checkbox() to create inputs of type checkbox\")\n\t\t\t}\n\t\t}\n\n\t\tassertIsValidAttribute(name, inputAttributes)\n\n\t\tattrs = append(attrs, formatAttribute(name, value))\n\t}\n\n\tf.fields = append(f.fields, \"\u003cgno-input \"+strings.Join(attrs, \" \")+\" /\u003e\")\n\treturn f\n}\n\n// Radio appends a new input of type radio to form fields.\n// Method panics when attributes are not valid.\nfunc (f *Form) Radio(name, value string, attributes ...string) *Form {\n\treturn f.appendInputType(InputTypeRadio, name, value, attributes...)\n}\n\n// Checkbox appends a new input of type checkbox to form fields.\n// Method panics when attributes are not valid.\nfunc (f *Form) Checkbox(name, value string, attributes ...string) *Form {\n\treturn f.appendInputType(InputTypeCheckbox, name, value, attributes...)\n}\n\n// Textarea appends a new textarea to form fields.\n// Method panics when attributes are not valid.\nfunc (f *Form) Textarea(name string, attributes ...string) *Form {\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tpanic(\"form textarea name is required\")\n\t}\n\n\tassertEvenAttributes(attributes)\n\n\tattrs := []string{formatAttribute(\"name\", name)}\n\tfor i := 0; i \u003c len(attributes); i += 2 {\n\t\tname, value := attributes[i], attributes[i+1]\n\n\t\tassertIsValidAttribute(name, textareaAttributes)\n\n\t\tattrs = append(attrs, formatAttribute(name, value))\n\t}\n\n\tf.fields = append(f.fields, \"\u003cgno-textarea \"+strings.Join(attrs, \" \")+\" /\u003e\")\n\treturn f\n}\n\n// Select appends a new select to form fields.\n// Method panics when attributes are not valid.\nfunc (f *Form) Select(name, value string, attributes ...string) *Form {\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tpanic(\"form select name is required\")\n\t}\n\n\tassertEvenAttributes(attributes)\n\n\tattrs := []string{\n\t\tformatAttribute(\"name\", name),\n\t\tformatAttribute(\"value\", value),\n\t}\n\n\tfor i := 0; i \u003c len(attributes); i += 2 {\n\t\tname, value := attributes[i], attributes[i+1]\n\n\t\tassertIsValidAttribute(name, selectAttributes)\n\n\t\tattrs = append(attrs, formatAttribute(name, value))\n\t}\n\n\tf.fields = append(f.fields, \"\u003cgno-select \"+strings.Join(attrs, \" \")+\" /\u003e\")\n\treturn f\n}\n\n// String returns the form as Gno-Flavored Markdown.\nfunc (f Form) String() string {\n\tfields := strings.Join(f.fields, \"\\n\")\n\tattrs := strings.Join(f.attrs, \" \")\n\tif len(attrs) \u003e 0 {\n\t\tattrs = \" \" + attrs\n\t}\n\n\treturn \"\u003cgno-form\" + attrs + \"\u003e\\n\" + fields + \"\\n\u003c/gno-form\u003e\\n\"\n}\n\nfunc (f *Form) appendInputType(typeName, name, value string, attributes ...string) *Form {\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tpanic(\"form \" + typeName + \" input name is required\")\n\t}\n\n\tassertEvenAttributes(attributes)\n\n\tattrs := []string{\n\t\tformatAttribute(\"type\", typeName),\n\t\tformatAttribute(\"name\", name),\n\t\tformatAttribute(\"value\", value),\n\t}\n\n\tfor i := 0; i \u003c len(attributes); i += 2 {\n\t\tname, value := attributes[i], attributes[i+1]\n\t\tif name == \"type\" || name == \"value\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tassertIsValidAttribute(name, inputAttributes)\n\n\t\tattrs = append(attrs, formatAttribute(name, value))\n\t}\n\n\tf.fields = append(f.fields, \"\u003cgno-input \"+strings.Join(attrs, \" \")+\" /\u003e\")\n\treturn f\n}\n\nfunc formatAttribute(name, value string) string {\n\treturn name + `=\"` + html.EscapeString(value) + `\"`\n}\n\nfunc assertEvenAttributes(attrs []string) {\n\tif len(attrs)%2 != 0 {\n\t\tpanic(\"expected an even number of attribute arguments\")\n\t}\n}\n\nfunc assertIsValidAttribute(attr string, attrs []string) {\n\tfor _, name := range attrs {\n\t\tif name == attr {\n\t\t\treturn\n\t\t}\n\t}\n\n\tpanic(\"invalid attribute: \" + attr)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"expect","path":"gno.land/p/jeronimoalbi/expect/v0","files":[{"name":"boolean.gno","body":"package expect\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewBooleanChecker creates a new checker of boolean values\nfunc NewBooleanChecker(ctx Context, value bool) BooleanChecker {\n\treturn BooleanChecker{ctx, value}\n}\n\n// BooleanChecker asserts boolean values.\ntype BooleanChecker struct {\n\tctx   Context\n\tvalue bool\n}\n\n// Not negates the next called expectation.\nfunc (c BooleanChecker) Not() BooleanChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// ToEqual asserts that current value is equal to an expected value.\nfunc (c BooleanChecker) ToEqual(v bool) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value == v, func(ctx Context) string {\n\t\tgot := formatBoolean(c.value)\n\t\tif !ctx.IsNegated() {\n\t\t\twant := formatBoolean(v)\n\t\t\treturn ufmt.Sprintf(\"Expected values to match\\nGot: %s\\nWant: %s\", got, want)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected values to be different\\nGot: %s\", got)\n\t})\n}\n\n// ToBeFalsy asserts that current value is falsy.\nfunc (c BooleanChecker) ToBeFalsy() {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(!c.value, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn \"Expected value to be falsy\"\n\t\t}\n\t\treturn \"Expected value not to be falsy\"\n\t})\n}\n\n// ToBeTruthy asserts that current value is truthy.\nfunc (c BooleanChecker) ToBeTruthy() {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn \"Expected value to be truthy\"\n\t\t}\n\t\treturn \"Expected value not to be truthy\"\n\t})\n}\n\nfunc asBoolean(value any) (bool, error) {\n\tif value == nil {\n\t\treturn false, nil\n\t}\n\n\tvar s string\n\tswitch v := value.(type) {\n\tcase bool:\n\t\treturn v, nil\n\tcase string:\n\t\ts = v\n\tcase []byte:\n\t\ts = string(v)\n\tcase Stringer:\n\t\ts = v.String()\n\tdefault:\n\t\treturn false, ErrIncompatibleType\n\t}\n\n\tif s != \"\" {\n\t\treturn strconv.ParseBool(s)\n\t}\n\treturn false, nil\n}\n\nfunc formatBoolean(value bool) string {\n\treturn strconv.FormatBool(value)\n}\n"},{"name":"context.gno","body":"package expect\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst defaultAssertFailMsg = \"assert expectation failed\"\n\n// NewContext creates a new testing context.\nfunc NewContext(t TestingT) Context {\n\treturn Context{t: t}\n}\n\n// Context preserves the current testing context.\ntype Context struct {\n\tt       TestingT\n\tnegated bool\n\tprefix  string\n}\n\n// T returns context's testing T instance.\nfunc (c Context) T() TestingT {\n\tif c.t == nil {\n\t\tpanic(\"expect: context is not initialized\")\n\t}\n\treturn c.t\n}\n\n// Prefix returns context's error prefix.\nfunc (c Context) Prefix() string {\n\treturn c.prefix\n}\n\n// IsNegated checks if current context negates current assert expectations.\nfunc (c Context) IsNegated() bool {\n\treturn c.negated\n}\n\n// CheckExpectation checks an assert expectation and calls a callback on fail.\n// It returns true when the asserted expectation fails.\n// Callback is called when a negated assertion succeeds or when non negated assertion fails.\nfunc (c Context) CheckExpectation(success bool, cb func(Context) string) bool {\n\tfailed := (c.negated \u0026\u0026 success) || (!c.negated \u0026\u0026 !success)\n\tif failed {\n\t\tmsg := cb(c)\n\t\tif strings.TrimSpace(msg) == \"\" {\n\t\t\tmsg = defaultAssertFailMsg\n\t\t}\n\n\t\tc.Fail(msg)\n\t}\n\treturn failed\n}\n\n// Fail makes the current test fail with a custom message.\nfunc (c Context) Fail(msg string, args ...any) {\n\tif c.prefix != \"\" {\n\t\tmsg = c.prefix + \" - \" + msg\n\t}\n\n\tc.t.Fatalf(msg, args...)\n}\n\n// TestingT defines a minimal interface for `testing.T` instances.\ntype TestingT interface {\n\tHelper()\n\tFatal(args ...any)\n\tFatalf(format string, args ...any)\n}\n\n// MockTestingT creates a new testing mock that writes testing output to a string builder.\nfunc MockTestingT(output *strings.Builder) TestingT {\n\treturn \u0026testingT{output}\n}\n\ntype testingT struct{ buf *strings.Builder }\n\nfunc (testingT) Helper()                          {}\nfunc (t testingT) Fatal(args ...any)              { t.buf.WriteString(ufmt.Sprintln(args...)) }\nfunc (t testingT) Fatalf(fmt string, args ...any) { t.buf.WriteString(ufmt.Sprintf(fmt+\"\\n\", args...)) }\n"},{"name":"doc.gno","body":"// Package expect provides testing support for packages and realms.\n//\n// The opinionated approach taken on this package for testing is to use function chaining and\n// semanthics to hopefully make unit and file testing fun. Focus is not on speed as there are\n// other packages that would run tests faster like the official `uassert` or `urequire` packages.\n//\n// Values can be asserted using the `Value()` function, for example:\n//\n//\tfunc TestFoo(t *testing.T) {\n//\t  got := 42\n//\t  expect.Value(t, got).ToEqual(42)\n//\t  expect.Value(t, got).Not().ToEqual(0)\n//\n//\t  expect.Value(t, \"foo\").ToEqual(\"foo\")\n//\t  expect.Value(t, 42).AsInt().Not().ToBeGreaterThan(50)\n//\t  expect.Value(t, \"TRUE\").AsBoolean().ToBeTruthy()\n//\t}\n//\n// Functions can also be used to assert returned values, errors or panics.\n//\n// Package supports four type of functions:\n//\n//   - func()\n//   - func() any\n//   - func() error\n//   - func() (any, error)\n//\n// Functions can be asserted using the `Func()` function, for example:\n//\n//\tfunc TestFoo(t *testing.T) {\n//\t  expect.Func(t, func() {\n//\t    panic(\"Boom!\")\n//\t  }).ToPanic().WithMessage(\"Boom!\")\n//\n//\t  wantErr := errors.New(\"Boom!\")\n//\t  expect.Func(t, func() error {\n//\t    return wantErr\n//\t  }).ToFail().WithMessage(\"Boom!\")\n//\n//\t  expect.Func(t, func() error {\n//\t    return wantErr\n//\t  }).ToFail().WithError(wantErr)\n//\t}\npackage expect\n"},{"name":"error.gno","body":"package expect\n\nimport \"gno.land/p/nt/ufmt/v0\"\n\n// NewErrorChecker creates a new checker of errors.\nfunc NewErrorChecker(ctx Context, err error) ErrorChecker {\n\treturn ErrorChecker{ctx, err}\n}\n\n// ErrorChecker asserts error values.\ntype ErrorChecker struct {\n\tctx Context\n\terr error\n}\n\n// Not negates the next called expectation.\nfunc (c ErrorChecker) Not() ErrorChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// WithMessage asserts that current error contains an expected message.\nfunc (c ErrorChecker) WithMessage(msg string) {\n\tc.ctx.T().Helper()\n\n\tif c.err == nil {\n\t\tc.ctx.Fail(\"Expected an error with message\\nGot: nil\\nWant: %s\", msg)\n\t\treturn\n\t}\n\n\tNewMessageChecker(c.ctx, c.err.Error(), MessageTypeError).WithMessage(msg)\n}\n\n// WithError asserts that current error message is the same as an expected error.\nfunc (c ErrorChecker) WithError(err error) {\n\tc.ctx.T().Helper()\n\n\tif c.err == nil {\n\t\tif err != nil {\n\t\t\tc.ctx.Fail(\"Expected an error\\nGot: nil\\nWant: %s\", err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tgot := c.err.Error()\n\tc.ctx.CheckExpectation(got == err.Error(), func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected errors to match\\nGot: %s\\nWant: %s\", got, err.Error())\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected errors to be different\\nGot: %s\", got)\n\t})\n}\n"},{"name":"float.gno","body":"package expect\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewFloatChecker creates a new checker of float64 values.\nfunc NewFloatChecker(ctx Context, value float64) FloatChecker {\n\treturn FloatChecker{ctx, value}\n}\n\n// FloatChecker asserts float64 values.\ntype FloatChecker struct {\n\tctx   Context\n\tvalue float64\n}\n\n// Not negates the next called expectation.\nfunc (c FloatChecker) Not() FloatChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// ToEqual asserts that current value is equal to an expected value.\nfunc (c FloatChecker) ToEqual(value float64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value == value, func(ctx Context) string {\n\t\tgot := formatFloat(c.value)\n\t\tif !ctx.IsNegated() {\n\t\t\twant := formatFloat(value)\n\t\t\treturn ufmt.Sprintf(\"Expected values to match\\nGot: %s\\nWant: %s\", got, want)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to be different\\nGot: %s\", got)\n\t})\n}\n\n// ToBeGreaterThan asserts that current value is greater than an expected value.\nfunc (c FloatChecker) ToBeGreaterThan(value float64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003e value, func(ctx Context) string {\n\t\tgot := formatFloat(c.value)\n\t\twant := formatFloat(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be gerater than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be greater than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeGreaterOrEqualThan asserts that current value is greater or equal than an expected value.\nfunc (c FloatChecker) ToBeGreaterOrEqualThan(value float64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003e= value, func(ctx Context) string {\n\t\tgot := formatFloat(c.value)\n\t\twant := formatFloat(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be greater or equal than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be greater or equal than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeLowerThan asserts that current value is lower than an expected value.\nfunc (c FloatChecker) ToBeLowerThan(value float64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003c value, func(ctx Context) string {\n\t\tgot := formatFloat(c.value)\n\t\twant := formatFloat(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be lower than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be lower than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeLowerOrEqualThan asserts that current value is lower or equal than an expected value.\nfunc (c FloatChecker) ToBeLowerOrEqualThan(value float64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003c= value, func(ctx Context) string {\n\t\tgot := formatFloat(c.value)\n\t\twant := formatFloat(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be lower or equal than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be lower or equal than %s\\nGot: %s\", want, got)\n\t})\n}\n\nfunc formatFloat(value float64) string {\n\treturn strconv.FormatFloat(value, 'g', -1, 64)\n}\n\nfunc asFloat(value any) (float64, error) {\n\tswitch v := value.(type) {\n\tcase float32:\n\t\treturn float64(v), nil\n\tcase float64:\n\t\treturn v, nil\n\tdefault:\n\t\treturn 0, ErrIncompatibleType\n\t}\n}\n"},{"name":"func.gno","body":"package expect\n\nimport \"gno.land/p/nt/ufmt/v0\"\n\ntype (\n\t// Fn defines a type for generic functions.\n\tFn = func()\n\n\t// ErrorFn defines a type for generic functions that return an error.\n\tErrorFn = func() error\n\n\t// AnyFn defines a type for generic functions that returns a value.\n\tAnyFn = func() any\n\n\t// AnyErrorFn defines a type for generic functions that return a value and an error.\n\tAnyErrorFn = func() (any, error)\n)\n\n// Func creates a new checker for functions.\nfunc Func(t TestingT, fn any) FuncChecker {\n\treturn FuncChecker{\n\t\tctx: NewContext(t),\n\t\tfn:  fn,\n\t}\n}\n\n// FuncChecker asserts function panics, errors and returned value.\ntype FuncChecker struct {\n\tctx Context\n\tfn  any\n}\n\n// WithFailPrefix assigns a prefix that will be prefixed to testing errors when an assertion fails.\nfunc (c FuncChecker) WithFailPrefix(prefix string) FuncChecker {\n\tc.ctx.prefix = prefix\n\treturn c\n}\n\n// Not negates the next called expectation.\nfunc (c FuncChecker) Not() FuncChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// ToFail return an error checker to assert if current function returns an error.\nfunc (c FuncChecker) ToFail() ErrorChecker {\n\tc.ctx.T().Helper()\n\n\tvar err error\n\tswitch fn := c.fn.(type) {\n\tcase ErrorFn:\n\t\terr = fn()\n\tcase AnyErrorFn:\n\t\t_, err = fn()\n\tdefault:\n\t\tc.ctx.Fail(\"Unsupported error func type\\nGot: %T\", c.fn)\n\t\treturn ErrorChecker{}\n\t}\n\n\tc.ctx.CheckExpectation(err != nil, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn \"Expected func to return an error\"\n\t\t}\n\t\treturn ufmt.Sprintf(\"Func failed with error\\nGot: %s\", err.Error())\n\t})\n\n\treturn NewErrorChecker(c.ctx, err)\n}\n\n// ToPanic return an message checker to assert if current function panicked.\n// This assertion is handled within the same realm, to assert panics when crossing\n// to another realm use the `ToAbort()` assertion.\n//\n// Example usage:\n//\n//\tfunc TestFoo(t *testing.T) {\n//\t  expect.Func(t, func() {\n//\t    Foo(cross)\n//\t  }).Not().ToCrossPanic()\n//\t}\nfunc (c FuncChecker) ToPanic() MessageChecker {\n\tc.ctx.T().Helper()\n\n\tvar (\n\t\tmsg      string\n\t\tpanicked bool\n\t)\n\n\t// TODO: Can't use a switch because it triggers the following VM error:\n\t// \"panic: should not happen, should be heapItemType: fn\u003c()~VPBlock(1,0)\u003e\"\n\t//\n\t// switch fn := c.fn.(type) {\n\t// case Fn:\n\t// \tmsg, panicked = handlePanic(fn)\n\t// case ErrorFn:\n\t// \tmsg, panicked = handlePanic(func() { _ = fn() })\n\t// case AnyFn:\n\t// \tmsg, panicked = handlePanic(func() { _ = fn() })\n\t// case AnyErrorFn:\n\t// \tmsg, panicked = handlePanic(func() { _, _ = fn() })\n\t// default:\n\t// \tc.ctx.Fail(\"Unsupported func type\\nGot: %T\", c.fn)\n\t// \treturn MessageChecker{}\n\t// }\n\n\tif fn, ok := c.fn.(Fn); ok {\n\t\tmsg, panicked = handlePanic(fn)\n\t} else if fn, ok := c.fn.(ErrorFn); ok {\n\t\tmsg, panicked = handlePanic(func() { _ = fn() })\n\t} else if fn, ok := c.fn.(AnyFn); ok {\n\t\tmsg, panicked = handlePanic(func() { _ = fn() })\n\t} else if fn, ok := c.fn.(AnyErrorFn); ok {\n\t\tmsg, panicked = handlePanic(func() { _, _ = fn() })\n\t} else {\n\t\tc.ctx.Fail(\"Unsupported func type\\nGot: %T\", c.fn)\n\t\treturn MessageChecker{}\n\t}\n\n\tc.ctx.CheckExpectation(panicked, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn \"Expected function to panic\"\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected func not to panic\\nGot: %s\", msg)\n\t})\n\n\treturn NewMessageChecker(c.ctx, msg, MessageTypePanic)\n}\n\n// ToCrossPanic return an message checker to assert if current function panicked when crossing.\n// This assertion is handled only when making a crossing call to another realm, when asserting\n// within the same realm use `ToPanic()`.\nfunc (c FuncChecker) ToCrossPanic() MessageChecker {\n\tc.ctx.T().Helper()\n\n\tvar (\n\t\tmsg      string\n\t\tpanicked bool\n\t)\n\n\t// TODO: Can't use a switch because it triggers the following VM error:\n\t// \"panic: should not happen, should be heapItemType: fn\u003c()~VPBlock(1,0)\u003e\"\n\t//\n\t// switch fn := c.fn.(type) {\n\t// case Fn:\n\t// \tmsg, panicked = handleCrossPanic(fn)\n\t// case ErrorFn:\n\t// \tmsg, panicked = handleCrossPanic(func() { _ = fn() })\n\t// case AnyFn:\n\t// \tmsg, panicked = handleCrossPanic(func() { _ = fn() })\n\t// case AnyErrorFn:\n\t// \tmsg, panicked = handleCrossPanic(func() { _, _ = fn() })\n\t// default:\n\t// \tc.ctx.Fail(\"Unsupported func type\\nGot: %T\", c.fn)\n\t// \treturn MessageChecker{}\n\t// }\n\n\tif fn, ok := c.fn.(Fn); ok {\n\t\tmsg, panicked = handleCrossPanic(fn)\n\t} else if fn, ok := c.fn.(ErrorFn); ok {\n\t\tmsg, panicked = handleCrossPanic(func() { _ = fn() })\n\t} else if fn, ok := c.fn.(AnyFn); ok {\n\t\tmsg, panicked = handleCrossPanic(func() { _ = fn() })\n\t} else if fn, ok := c.fn.(AnyErrorFn); ok {\n\t\tmsg, panicked = handleCrossPanic(func() { _, _ = fn() })\n\t} else {\n\t\tc.ctx.Fail(\"Unsupported func type\\nGot: %T\", c.fn)\n\t\treturn MessageChecker{}\n\t}\n\n\tc.ctx.CheckExpectation(panicked, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn \"Expected function to cross panic\"\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected func not to cross panic\\nGot: %s\", msg)\n\t})\n\n\treturn NewMessageChecker(c.ctx, msg, MessageTypeCrossPanic)\n}\n\n// ToReturn asserts that current function returned a value equal to an expected value.\nfunc (c FuncChecker) ToReturn(value any) {\n\tc.ctx.T().Helper()\n\n\tvar (\n\t\terr error\n\t\tv   any\n\t)\n\n\tif fn, ok := c.fn.(AnyFn); ok {\n\t\tv = fn()\n\t} else if fn, ok := c.fn.(AnyErrorFn); ok {\n\t\tv, err = fn()\n\t} else {\n\t\tc.ctx.Fail(\"Unsupported func type\\nGot: %T\", c.fn)\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tc.ctx.Fail(\"Function returned unexpected error\\nGot: %s\", err.Error())\n\t\treturn\n\t}\n\n\tif c.ctx.negated {\n\t\tValue(c.ctx.T(), v).Not().ToEqual(value)\n\t} else {\n\t\tValue(c.ctx.T(), v).ToEqual(value)\n\t}\n}\n\nfunc handlePanic(fn func()) (msg string, panicked bool) {\n\tdefer func() {\n\t\tr := recover()\n\t\tif r == nil {\n\t\t\treturn\n\t\t}\n\n\t\tpanicked = true\n\n\t\tif err, ok := r.(error); ok {\n\t\t\tmsg = err.Error()\n\t\t\treturn\n\t\t}\n\n\t\tif s, ok := r.(string); ok {\n\t\t\tmsg = s\n\t\t\treturn\n\t\t}\n\n\t\tmsg = \"unsupported panic type\"\n\t}()\n\n\tfn()\n\treturn\n}\n\nfunc handleCrossPanic(fn func()) (string, bool) {\n\tr := revive(fn)\n\tif r == nil {\n\t\treturn \"\", false\n\t}\n\n\tif err, ok := r.(error); ok {\n\t\treturn err.Error(), true\n\t}\n\n\tif s, ok := r.(string); ok {\n\t\treturn s, true\n\t}\n\n\treturn \"unsupported panic type\", true\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jeronimoalbi/expect/v0\"\ngno = \"0.9\"\n"},{"name":"int.gno","body":"package expect\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewIntChecker creates a new checker of int64 values.\nfunc NewIntChecker(ctx Context, value int64) IntChecker {\n\treturn IntChecker{ctx, value}\n}\n\n// IntChecker asserts int64 values.\ntype IntChecker struct {\n\tctx   Context\n\tvalue int64\n}\n\n// Not negates the next called expectation.\nfunc (c IntChecker) Not() IntChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// ToEqual asserts that current value is equal to an expected value.\nfunc (c IntChecker) ToEqual(value int64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value == value, func(ctx Context) string {\n\t\tgot := formatInt(c.value)\n\t\tif !ctx.IsNegated() {\n\t\t\twant := formatInt(value)\n\t\t\treturn ufmt.Sprintf(\"Expected values to match\\nGot: %s\\nWant: %s\", got, want)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to be different\\nGot: %s\", got)\n\t})\n}\n\n// ToBeGreaterThan asserts that current value is greater than an expected value.\nfunc (c IntChecker) ToBeGreaterThan(value int64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003e value, func(ctx Context) string {\n\t\tgot := formatInt(c.value)\n\t\twant := formatInt(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be gerater than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be greater than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeGreaterOrEqualThan asserts that current value is greater or equal than an expected value.\nfunc (c IntChecker) ToBeGreaterOrEqualThan(value int64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003e= value, func(ctx Context) string {\n\t\tgot := formatInt(c.value)\n\t\twant := formatInt(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be greater or equal than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be greater or equal than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeLowerThan asserts that current value is lower than an expected value.\nfunc (c IntChecker) ToBeLowerThan(value int64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003c value, func(ctx Context) string {\n\t\tgot := formatInt(c.value)\n\t\twant := formatInt(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be lower than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be lower than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeLowerOrEqualThan asserts that current value is lower or equal than an expected value.\nfunc (c IntChecker) ToBeLowerOrEqualThan(value int64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003c= value, func(ctx Context) string {\n\t\tgot := formatInt(c.value)\n\t\twant := formatInt(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be lower or equal than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be lower or equal than %s\\nGot: %s\", want, got)\n\t})\n}\n\nfunc formatInt(value int64) string {\n\treturn strconv.FormatInt(value, 10)\n}\n\nfunc asInt(value any) (int64, error) {\n\tswitch v := value.(type) {\n\tcase int:\n\t\treturn int64(v), nil\n\tcase int8:\n\t\treturn int64(v), nil\n\tcase int16:\n\t\treturn int64(v), nil\n\tcase int32:\n\t\treturn int64(v), nil\n\tcase int64:\n\t\treturn v, nil\n\tdefault:\n\t\treturn 0, ErrIncompatibleType\n\t}\n}\n"},{"name":"message.gno","body":"package expect\n\nimport \"gno.land/p/nt/ufmt/v0\"\n\nconst (\n\tMessageTypeCrossPanic MessageType = \"cross panic\"\n\tMessageTypeError                  = \"error\"\n\tMessageTypePanic                  = \"panic\"\n)\n\n// MessageType defines a type for message checker errors.\ntype MessageType string\n\n// NewMessageChecker creates a new checker for text messages.\nfunc NewMessageChecker(ctx Context, msg string, t MessageType) MessageChecker {\n\treturn MessageChecker{ctx, msg, t}\n}\n\n// MessageChecker asserts text messages.\ntype MessageChecker struct {\n\tctx     Context\n\tmsg     string\n\tmsgType MessageType\n}\n\n// Not negates the next called expectation.\nfunc (c MessageChecker) Not() MessageChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// WithMessage asserts that a message is equal to an expected message.\nfunc (c MessageChecker) WithMessage(msg string) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.msg == msg, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected %s message to match\\nGot: %s\\nWant: %s\", string(c.msgType), c.msg, msg)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected %s message to be different\\nGot: %s\", string(c.msgType), c.msg)\n\t})\n}\n"},{"name":"string.gno","body":"package expect\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// ErrIncompatibleType indicates that a value can't be casted to a different type.\nvar ErrIncompatibleType = errors.New(\"incompatible type\")\n\n// NewStringChecker creates a new checker of string values.\nfunc NewStringChecker(ctx Context, value string) StringChecker {\n\treturn StringChecker{ctx, value}\n}\n\n// StringChecker asserts string values.\ntype StringChecker struct {\n\tctx   Context\n\tvalue string\n}\n\n// Not negates the next called expectation.\nfunc (c StringChecker) Not() StringChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// ToEqual asserts that current value is equal to an expected value.\nfunc (c StringChecker) ToEqual(v string) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value == v, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to match\\nGot: %s\\nWant: %s\", c.value, v)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected values to be different\\nGot: %s\", c.value)\n\t})\n}\n\n// ToBeEmpty asserts that current value is an empty string.\nfunc (c StringChecker) ToBeEmpty() {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value == \"\", func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected string to be empty\\nGot: %s\", c.value)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Unexpected empty string\")\n\t})\n}\n\n// ToHaveLength asserts that current value has an expected length.\nfunc (c StringChecker) ToHaveLength(length int) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(len(c.value) == length, func(ctx Context) string {\n\t\tgot := len(c.value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected string length to match\\nGot: %d\\nWant: %d\", got, length)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected string lengths to be different\\nGot: %d\", got)\n\t})\n}\n\n// Stringer defines an interface for values that has a String method.\ntype Stringer interface {\n\tString() string\n}\n\nfunc asString(value any) (string, error) {\n\tswitch v := value.(type) {\n\tcase string:\n\t\treturn v, nil\n\tcase []byte:\n\t\treturn string(v), nil\n\tcase Stringer:\n\t\treturn v.String(), nil\n\tcase address:\n\t\treturn v.String(), nil\n\tdefault:\n\t\treturn \"\", ErrIncompatibleType\n\t}\n}\n"},{"name":"uint.gno","body":"package expect\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewUintChecker creates a new checker of uint64 values.\nfunc NewUintChecker(ctx Context, value uint64) UintChecker {\n\treturn UintChecker{ctx, value}\n}\n\n// UintChecker asserts uint64 values.\ntype UintChecker struct {\n\tctx   Context\n\tvalue uint64\n}\n\n// Not negates the next called expectation.\nfunc (c UintChecker) Not() UintChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// ToEqual asserts that current value is equal to an expected value.\nfunc (c UintChecker) ToEqual(value uint64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value == value, func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\tgot := formatUint(c.value)\n\t\t\twant := formatUint(value)\n\t\t\treturn ufmt.Sprintf(\"Expected values to match\\nGot: %s\\nWant: %s\", got, want)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to be different\\nGot: %s\", formatUint(c.value))\n\t})\n}\n\n// ToBeGreaterThan asserts that current value is greater than an expected value.\nfunc (c UintChecker) ToBeGreaterThan(value uint64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003e value, func(ctx Context) string {\n\t\tgot := formatUint(c.value)\n\t\twant := formatUint(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be gerater than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be greater than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeGreaterOrEqualThan asserts that current value is greater or equal than an expected value.\nfunc (c UintChecker) ToBeGreaterOrEqualThan(value uint64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003e= value, func(ctx Context) string {\n\t\tgot := formatUint(c.value)\n\t\twant := formatUint(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be greater or equal than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be greater or equal than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeLowerThan asserts that current value is lower than an expected value.\nfunc (c UintChecker) ToBeLowerThan(value uint64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003c value, func(ctx Context) string {\n\t\tgot := formatUint(c.value)\n\t\twant := formatUint(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be lower than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be lower than %s\\nGot: %s\", want, got)\n\t})\n}\n\n// ToBeLowerOrEqualThan asserts that current value is lower or equal than an expected value.\nfunc (c UintChecker) ToBeLowerOrEqualThan(value uint64) {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value \u003c= value, func(ctx Context) string {\n\t\tgot := formatUint(c.value)\n\t\twant := formatUint(value)\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected values to be lower or equal than %s\\nGot: %s\", want, got)\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected value to not to be lower or equal than %s\\nGot: %s\", want, got)\n\t})\n}\n\nfunc formatUint(value uint64) string {\n\treturn strconv.FormatUint(value, 10)\n}\n\nfunc asUint(value any) (uint64, error) {\n\tswitch v := value.(type) {\n\tcase uint:\n\t\treturn uint64(v), nil\n\tcase uint8:\n\t\treturn uint64(v), nil\n\tcase uint16:\n\t\treturn uint64(v), nil\n\tcase uint32:\n\t\treturn uint64(v), nil\n\tcase uint64:\n\t\treturn v, nil\n\tcase int:\n\t\tif v \u003c 0 {\n\t\t\treturn 0, ErrIncompatibleType\n\t\t}\n\t\treturn uint64(v), nil\n\tdefault:\n\t\treturn 0, ErrIncompatibleType\n\t}\n}\n"},{"name":"value.gno","body":"package expect\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Value creates a new checker values of different types.\nfunc Value(t TestingT, value any) ValueChecker {\n\treturn ValueChecker{\n\t\tctx:   NewContext(t),\n\t\tvalue: value,\n\t}\n}\n\n// ValueChecker asserts values of different types.\ntype ValueChecker struct {\n\tctx   Context\n\tvalue any\n}\n\n// WithFailPrefix assigns a prefix that will be prefixed to testing errors when an assertion fails.\nfunc (c ValueChecker) WithFailPrefix(prefix string) ValueChecker {\n\tc.ctx.prefix = prefix\n\treturn c\n}\n\n// Not negates the next called expectation.\nfunc (c ValueChecker) Not() ValueChecker {\n\tc.ctx.negated = !c.ctx.negated\n\treturn c\n}\n\n// ToBeNil asserts that current value is nil.\nfunc (c ValueChecker) ToBeNil() {\n\tc.ctx.T().Helper()\n\tc.ctx.CheckExpectation(c.value == nil || istypednil(c.value), func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected value to be nil\\nGot: %v\", c.value)\n\t\t}\n\t\treturn \"Expected a non nil value\"\n\t})\n}\n\n// ToEqual asserts that current value is equal to an expected value.\nfunc (c ValueChecker) ToEqual(value any) {\n\tc.ctx.T().Helper()\n\n\t// Assert error values first to allow comparing errors to string values\n\tif err, ok := c.value.(error); ok {\n\t\twant, ok := value.(error)\n\t\tif !ok {\n\t\t\tc.ctx.Fail(\"Failed: expected an error value\\nGot: %T\", value)\n\t\t\treturn\n\t\t}\n\n\t\tc.ctx.CheckExpectation(err.Error() == want.Error(), func(ctx Context) string {\n\t\t\tif !ctx.IsNegated() {\n\t\t\t\treturn ufmt.Sprintf(\"Expected errors to match\\nGot: %s\\nWant: %s\", err.Error(), want.Error())\n\t\t\t}\n\t\t\treturn ufmt.Sprintf(\"Expected errors to be different\\nGot: %s\", err.Error())\n\t\t})\n\n\t\treturn\n\t}\n\n\tswitch v := value.(type) {\n\tcase string:\n\t\tc.AsString().ToEqual(v)\n\tcase []byte:\n\t\tc.AsString().ToEqual(string(v))\n\tcase Stringer:\n\t\tc.AsString().ToEqual(v.String())\n\tcase bool:\n\t\tc.AsBoolean().ToEqual(v)\n\tcase float32:\n\t\tc.AsFloat().ToEqual(float64(v))\n\tcase float64:\n\t\tc.AsFloat().ToEqual(v)\n\tcase uint:\n\t\tc.AsUint().ToEqual(uint64(v))\n\tcase uint8:\n\t\tc.AsUint().ToEqual(uint64(v))\n\tcase uint16:\n\t\tc.AsUint().ToEqual(uint64(v))\n\tcase uint32:\n\t\tc.AsUint().ToEqual(uint64(v))\n\tcase uint64:\n\t\tc.AsUint().ToEqual(v)\n\tcase int:\n\t\tc.AsInt().ToEqual(int64(v))\n\tcase int8:\n\t\tc.AsInt().ToEqual(int64(v))\n\tcase int16:\n\t\tc.AsInt().ToEqual(int64(v))\n\tcase int32:\n\t\tc.AsInt().ToEqual(int64(v))\n\tcase int64:\n\t\tc.AsInt().ToEqual(v)\n\tcase error:\n\t\tc.ctx.Fail(\"Error is not equal to value\\nGot: %s\", v.Error())\n\tdefault:\n\t\tc.ctx.Fail(\"Unsupported type: %T\", value)\n\t}\n}\n\n// ToContainErrorString asserts that current error value contains an error string.\nfunc (c ValueChecker) ToContainErrorString(msg string) {\n\tc.ctx.T().Helper()\n\n\terr, ok := c.value.(error)\n\tif !ok {\n\t\tc.ctx.Fail(\"Failed: expected an error value\\nGot: %T\", c.value)\n\t\treturn\n\t}\n\n\tc.ctx.CheckExpectation(strings.Contains(err.Error(), msg), func(ctx Context) string {\n\t\tif !ctx.IsNegated() {\n\t\t\treturn ufmt.Sprintf(\"Expected error message to contain: %s\\nGot: %s\", msg, err.Error())\n\t\t}\n\t\treturn ufmt.Sprintf(\"Expected error message not to contain: %s\\nGot: %s\", msg, err.Error())\n\t})\n}\n\n// AsString returns a checker to assert current value as a string.\nfunc (c ValueChecker) AsString() StringChecker {\n\tc.ctx.T().Helper()\n\n\tv, err := asString(c.value)\n\tif err != nil {\n\t\tc.ctx.Fail(\"Failed: %s: expected a string value\\nGot: %T\", err.Error(), c.value)\n\t\treturn StringChecker{}\n\t}\n\n\treturn NewStringChecker(c.ctx, v)\n}\n\n// AsBoolean returns a checker to assert current value as a boolean.\nfunc (c ValueChecker) AsBoolean() BooleanChecker {\n\tc.ctx.T().Helper()\n\n\tv, err := asBoolean(c.value)\n\tif err != nil {\n\t\tc.ctx.Fail(\"Failed: %s: expected a boolean value\\nGot: %T\", err.Error(), c.value)\n\t\treturn BooleanChecker{}\n\t}\n\n\treturn NewBooleanChecker(c.ctx, v)\n}\n\n// AsFloat returns a checker to assert current value as a float64.\nfunc (c ValueChecker) AsFloat() FloatChecker {\n\tc.ctx.T().Helper()\n\n\tv, err := asFloat(c.value)\n\tif err != nil {\n\t\tc.ctx.Fail(\"%s: expected a float value\\nGot: %T\", err.Error(), c.value)\n\t\treturn FloatChecker{}\n\t}\n\n\treturn NewFloatChecker(c.ctx, v)\n}\n\n// AsUint returns a checker to assert current value as a uint64.\nfunc (c ValueChecker) AsUint() UintChecker {\n\tc.ctx.T().Helper()\n\n\tv, err := asUint(c.value)\n\tif err != nil {\n\t\tc.ctx.Fail(\"Failed: %s: expected a uint value\\nGot: %T\", err.Error(), c.value)\n\t\treturn UintChecker{}\n\t}\n\n\treturn NewUintChecker(c.ctx, v)\n}\n\n// AsInt returns a checker to assert current value as a int64.\nfunc (c ValueChecker) AsInt() IntChecker {\n\tc.ctx.T().Helper()\n\n\tv, err := asInt(c.value)\n\tif err != nil {\n\t\tc.ctx.Fail(\"Failed: %s: expected an int value\\nGot: %T\", err.Error(), c.value)\n\t\treturn IntChecker{}\n\t}\n\n\treturn NewIntChecker(c.ctx, v)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"diff","path":"gno.land/p/onbloc/diff/v0","files":[{"name":"diff.gno","body":"// The diff package implements the Myers diff algorithm to compute the edit distance\n// and generate a minimal edit script between two strings.\n//\n// Edit distance, also known as Levenshtein distance, is a measure of the similarity\n// between two strings. It is defined as the minimum number of single-character edits (insertions,\n// deletions, or substitutions) required to change one string into the other.\npackage diff\n\nimport (\n\t\"strings\"\n)\n\n// EditType represents the type of edit operation in a diff.\ntype EditType uint8\n\nconst (\n\t// EditKeep indicates that a character is unchanged in both strings.\n\tEditKeep EditType = iota\n\n\t// EditInsert indicates that a character was inserted in the new string.\n\tEditInsert\n\n\t// EditDelete indicates that a character was deleted from the old string.\n\tEditDelete\n)\n\n// Edit represent a single edit operation in a diff.\ntype Edit struct {\n\t// Type is the kind of edit operation.\n\tType EditType\n\n\t// Char is the character involved in the edit operation.\n\tChar rune\n}\n\n// MyersDiff computes the difference between two strings using Myers' diff algorithm.\n// It returns a slice of Edit operations that transform the old string into the new string.\n// This implementation finds the shortest edit script (SES) that represents the minimal\n// set of operations to transform one string into the other.\n//\n// The function handles both ASCII and non-ASCII characters correctly.\n//\n// Time complexity: O((N+M)D), where N and M are the lengths of the input strings,\n// and D is the size of the minimum edit script.\n//\n// Space complexity: O((N+M)D)\n//\n// In the worst case, where the strings are completely different, D can be as large as N+M,\n// leading to a time and space complexity of O((N+M)^2). However, for strings with many\n// common substrings, the performance is much better, often closer to O(N+M).\n//\n// Parameters:\n//   - old: the original string.\n//   - new: the modified string.\n//\n// Returns:\n//   - A slice of Edit operations representing the minimum difference between the two strings.\nfunc MyersDiff(old, new string) []Edit {\n\toldRunes, newRunes := []rune(old), []rune(new)\n\tn, m := len(oldRunes), len(newRunes)\n\n\tif n == 0 \u0026\u0026 m == 0 {\n\t\treturn []Edit{}\n\t}\n\n\t// old is empty\n\tif n == 0 {\n\t\tedits := make([]Edit, m)\n\t\tfor i, r := range newRunes {\n\t\t\tedits[i] = Edit{Type: EditInsert, Char: r}\n\t\t}\n\t\treturn edits\n\t}\n\n\tif m == 0 {\n\t\tedits := make([]Edit, n)\n\t\tfor i, r := range oldRunes {\n\t\t\tedits[i] = Edit{Type: EditDelete, Char: r}\n\t\t}\n\t\treturn edits\n\t}\n\n\tmax := n + m\n\tv := make([]int, 2*max+1)\n\tvar trace [][]int\nsearch:\n\tfor d := 0; d \u003c= max; d++ {\n\t\t// iterate through diagonals\n\t\tfor k := -d; k \u003c= d; k += 2 {\n\t\t\tvar x int\n\t\t\tif k == -d || (k != d \u0026\u0026 v[max+k-1] \u003c v[max+k+1]) {\n\t\t\t\tx = v[max+k+1] // move down\n\t\t\t} else {\n\t\t\t\tx = v[max+k-1] + 1 // move right\n\t\t\t}\n\t\t\ty := x - k\n\n\t\t\t// extend the path as far as possible with matching characters\n\t\t\tfor x \u003c n \u0026\u0026 y \u003c m \u0026\u0026 oldRunes[x] == newRunes[y] {\n\t\t\t\tx++\n\t\t\t\ty++\n\t\t\t}\n\n\t\t\tv[max+k] = x\n\n\t\t\t// check if we've reached the end of both strings\n\t\t\tif x == n \u0026\u0026 y == m {\n\t\t\t\ttrace = append(trace, append([]int(nil), v...))\n\t\t\t\tbreak search\n\t\t\t}\n\t\t}\n\t\ttrace = append(trace, append([]int(nil), v...))\n\t}\n\n\t// backtrack to construct the edit script\n\tedits := make([]Edit, 0, n+m)\n\tx, y := n, m\n\tfor d := len(trace) - 1; d \u003e= 0; d-- {\n\t\tvPrev := trace[d]\n\t\tk := x - y\n\t\tvar prevK int\n\t\tif k == -d || (k != d \u0026\u0026 vPrev[max+k-1] \u003c vPrev[max+k+1]) {\n\t\t\tprevK = k + 1\n\t\t} else {\n\t\t\tprevK = k - 1\n\t\t}\n\t\tprevX := vPrev[max+prevK]\n\t\tprevY := prevX - prevK\n\n\t\t// add keep edits for matching characters\n\t\tfor x \u003e prevX \u0026\u0026 y \u003e prevY {\n\t\t\tif x \u003e 0 \u0026\u0026 y \u003e 0 {\n\t\t\t\tedits = append([]Edit{{Type: EditKeep, Char: oldRunes[x-1]}}, edits...)\n\t\t\t}\n\t\t\tx--\n\t\t\ty--\n\t\t}\n\t\tif y \u003e prevY {\n\t\t\tif y \u003e 0 {\n\t\t\t\tedits = append([]Edit{{Type: EditInsert, Char: newRunes[y-1]}}, edits...)\n\t\t\t}\n\t\t\ty--\n\t\t} else if x \u003e prevX {\n\t\t\tif x \u003e 0 {\n\t\t\t\tedits = append([]Edit{{Type: EditDelete, Char: oldRunes[x-1]}}, edits...)\n\t\t\t}\n\t\t\tx--\n\t\t}\n\t}\n\n\treturn edits\n}\n\n// Format converts a slice of Edit operations into a human-readable string representation.\n// It groups consecutive edits of the same type and formats them as follows:\n//   - Unchanged characters are left as-is\n//   - Inserted characters are wrapped in [+...]\n//   - Deleted characters are wrapped in [-...]\n//\n// This function is useful for visualizing the differences between two strings\n// in a compact and intuitive format.\n//\n// Parameters:\n//   - edits: A slice of Edit operations, typically produced by MyersDiff\n//\n// Returns:\n//   - A formatted string representing the diff\n//\n// Example output:\n//\n//\tFor the diff between \"abcd\" and \"acbd\", the output might be:\n//\t\"a[-b]c[+b]d\"\n//\n// Note:\n//\n//\tThe function assumes that the input slice of edits is in the correct order.\n//\tAn empty input slice will result in an empty string.\nfunc Format(edits []Edit) string {\n\tif len(edits) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar (\n\t\tresult       strings.Builder\n\t\tcurrentType  EditType\n\t\tcurrentChars strings.Builder\n\t)\n\n\tflushCurrent := func() {\n\t\tif currentChars.Len() \u003e 0 {\n\t\t\tswitch currentType {\n\t\t\tcase EditKeep:\n\t\t\t\tresult.WriteString(currentChars.String())\n\t\t\tcase EditInsert:\n\t\t\t\tresult.WriteString(\"[+\")\n\t\t\t\tresult.WriteString(currentChars.String())\n\t\t\t\tresult.WriteByte(']')\n\t\t\tcase EditDelete:\n\t\t\t\tresult.WriteString(\"[-\")\n\t\t\t\tresult.WriteString(currentChars.String())\n\t\t\t\tresult.WriteByte(']')\n\t\t\t}\n\t\t\tcurrentChars.Reset()\n\t\t}\n\t}\n\n\tfor _, edit := range edits {\n\t\tif edit.Type != currentType {\n\t\t\tflushCurrent()\n\t\t\tcurrentType = edit.Type\n\t\t}\n\t\tcurrentChars.WriteRune(edit.Char)\n\t}\n\tflushCurrent()\n\n\treturn result.String()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/onbloc/diff/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"uassert","path":"gno.land/p/nt/uassert/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `uassert` - test assertions\n\nAssertion helpers for writing Gno tests, in both `_test.gno` and `_filetest.gno` files. Adapted, lighter port of `stretchr/testify/assert`. Each helper takes a `TestingT`, reports the failure via `t.Errorf`, and lets the test keep running.\n\n## Usage\n\n```go\nimport (\n    \"testing\"\n\n    \"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestAdd(cur realm, t *testing.T) {\n    got, err := Add(2, 3)\n    uassert.NoError(t, err)\n    uassert.Equal(t, 5, got)\n    uassert.True(t, got \u003e 0, \"result must be positive\")\n\n    uassert.PanicsWithMessage(t, cur, \"div by zero\", func() {\n        Div(1, 0)\n    })\n}\n```\n\nEvery helper returns a `bool` (`true` on success) so they can be chained or used in conditionals.\n\n## API\n\n```go\ntype TestingT interface {\n    Helper()\n    Skip(args ...any)\n    Fatalf(fmt string, args ...any)\n    Errorf(fmt string, args ...any)\n    Logf(fmt string, args ...any)\n    Fail()\n    FailNow()\n}\n```\n\nEquality and emptiness (supports `string`, `address`, `bool`, all int/uint widths, `float32/64`):\n\n```go\nfunc Equal(t TestingT, expected, actual any, msgs ...string) bool\nfunc NotEqual(t TestingT, expected, actual any, msgs ...string) bool\nfunc Empty(t TestingT, obj any, msgs ...string) bool\nfunc NotEmpty(t TestingT, obj any, msgs ...string) bool\n```\n\nTruthiness and nil:\n\n```go\nfunc True(t TestingT, value bool, msgs ...string) bool\nfunc False(t TestingT, value bool, msgs ...string) bool\nfunc Nil(t TestingT, value any, msgs ...string) bool\nfunc NotNil(t TestingT, value any, msgs ...string) bool\nfunc TypedNil(t TestingT, value any, msgs ...string) bool\nfunc NotTypedNil(t TestingT, value any, msgs ...string) bool\n```\n\nErrors:\n\n```go\nfunc NoError(t TestingT, err error, msgs ...string) bool\nfunc Error(t TestingT, err error, msgs ...string) bool\nfunc ErrorContains(t TestingT, err error, contains string, msgs ...string) bool\nfunc ErrorIs(t TestingT, err, target error, msgs ...string) bool\n```\n\nPanics and aborts (`f` may be `func()` or `func(realm)`; pass the test's own `cur` as `rlm`):\n\n```go\nfunc PanicsWithMessage(t TestingT, rlm realm, msg string, f any, msgs ...string) bool\nfunc PanicsContains(t TestingT, rlm realm, substr string, f any, msgs ...string) bool\nfunc NotPanics(t TestingT, rlm realm, f any, msgs ...string) bool\nfunc AbortsWithMessage(t TestingT, rlm realm, msg string, f any, msgs ...string) bool\nfunc AbortsContains(t TestingT, rlm realm, substr string, f any, msgs ...string) bool\nfunc NotAborts(t TestingT, rlm realm, f any, msgs ...string) bool\n```\n\n## Notes\n\n- A *panic* is a same-realm runtime failure caught with `recover`. An *abort* is a panic that crosses a realm boundary, caught with gno's `revive`. Use the right variant: `PanicsX` for same-realm, `AbortsX` for cross-realm. `NotPanics` covers both.\n- `uassert` reports the failure but lets the test continue. Use `gno.land/p/nt/urequire/v0` when subsequent assertions wouldn't be meaningful after a failure.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\npackage uassert // import \"gno.land/p/nt/uassert/v0\"\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/uassert/v0\"\ngno = \"0.9\"\n"},{"name":"helpers.gno","body":"package uassert\n\nimport \"strings\"\n\nfunc fail(t TestingT, customMsgs []string, failureMessage string, args ...any) bool {\n\tcustomMsg := \"\"\n\tif len(customMsgs) \u003e 0 {\n\t\tcustomMsg = strings.Join(customMsgs, \" \")\n\t}\n\tif customMsg != \"\" {\n\t\tfailureMessage += \" - \" + customMsg\n\t}\n\tt.Errorf(failureMessage, args...)\n\treturn false\n}\n\nfunc checkDidPanic(f any, rlm realm) (didPanic bool, message string) {\n\tdidPanic = true\n\tdefer func() {\n\t\tr := recover()\n\n\t\tif r == nil {\n\t\t\tmessage = \"nil\"\n\t\t\treturn\n\t\t}\n\n\t\terr, ok := r.(error)\n\t\tif ok {\n\t\t\tmessage = err.Error()\n\t\t\treturn\n\t\t}\n\n\t\terrStr, ok := r.(string)\n\t\tif ok {\n\t\t\tmessage = errStr\n\t\t\treturn\n\t\t}\n\n\t\tmessage = \"recover: unsupported type\"\n\t}()\n\tswitch f := f.(type) {\n\tcase func():\n\t\tf()\n\tcase func(realm):\n\t\tf(cross(rlm))\n\tdefault:\n\t\tpanic(\"f must be of type func() or func(realm)\")\n\t}\n\tdidPanic = false\n\treturn\n}\n"},{"name":"types.gno","body":"package uassert\n\ntype TestingT interface {\n\tHelper()\n\tSkip(args ...any)\n\tFatalf(fmt string, args ...any)\n\tErrorf(fmt string, args ...any)\n\tLogf(fmt string, args ...any)\n\tFail()\n\tFailNow()\n}\n"},{"name":"uassert.gno","body":"// uassert is an adapted lighter version of https://github.com/stretchr/testify/assert.\npackage uassert\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/onbloc/diff/v0\"\n)\n\n// NoError asserts that a function returned no error (i.e. `nil`).\nfunc NoError(t TestingT, err error, msgs ...string) bool {\n\tt.Helper()\n\tif err != nil {\n\t\treturn fail(t, msgs, \"unexpected error: %s\", err.Error())\n\t}\n\treturn true\n}\n\n// Error asserts that a function returned an error (i.e. not `nil`).\nfunc Error(t TestingT, err error, msgs ...string) bool {\n\tt.Helper()\n\tif err == nil {\n\t\treturn fail(t, msgs, \"an error is expected but got nil\")\n\t}\n\treturn true\n}\n\n// ErrorContains asserts that a function returned an error (i.e. not `nil`)\n// and that the error contains the specified substring.\nfunc ErrorContains(t TestingT, err error, contains string, msgs ...string) bool {\n\tt.Helper()\n\n\tif !Error(t, err, msgs...) {\n\t\treturn false\n\t}\n\n\tactual := err.Error()\n\tif !strings.Contains(actual, contains) {\n\t\treturn fail(t, msgs, \"error %q does not contain %q\", actual, contains)\n\t}\n\n\treturn true\n}\n\n// True asserts that the specified value is true.\nfunc True(t TestingT, value bool, msgs ...string) bool {\n\tt.Helper()\n\tif !value {\n\t\treturn fail(t, msgs, \"should be true\")\n\t}\n\treturn true\n}\n\n// False asserts that the specified value is false.\nfunc False(t TestingT, value bool, msgs ...string) bool {\n\tt.Helper()\n\tif value {\n\t\treturn fail(t, msgs, \"should be false\")\n\t}\n\treturn true\n}\n\n// ErrorIs asserts the given error matches the target error using errors.Is,\n// which traverses the error chain looking for a match.\nfunc ErrorIs(t TestingT, err, target error, msgs ...string) bool {\n\tt.Helper()\n\n\tif !errors.Is(err, target) {\n\t\treturn fail(t, msgs, \"error mismatch, expected %s, got %s\", target, err)\n\t}\n\n\treturn true\n}\n\n// AbortsWithMessage asserts that the code inside the specified func aborts\n// (panics when crossing another realm).\n// Use PanicsWithMessage for asserting local panics within the same realm.\n//\n// `rlm` is threaded into the callback via cross(rlm) when f is func(realm).\n// It is ignored for func() callbacks. /p/ production code cannot declare\n// crossing functions, so rlm is taken as the second (non-first) parameter\n// — callers pass `cur` directly.\n//\n// NOTE: This relies on gno's `revive` mechanism to catch aborts.\nfunc AbortsWithMessage(t TestingT, rlm realm, msg string, f any, msgs ...string) bool {\n\tt.Helper()\n\n\tvar didAbort bool\n\tvar abortValue any\n\tvar r any\n\n\tswitch f := f.(type) {\n\tcase func():\n\t\tr = revive(f) // revive() captures the value passed to panic()\n\tcase func(realm):\n\t\tr = revive(func() { f(cross(rlm)) })\n\tdefault:\n\t\tpanic(\"f must be of type func() or func(realm)\")\n\t}\n\tif r != nil {\n\t\tdidAbort = true\n\t\tabortValue = r\n\t}\n\n\tif !didAbort {\n\t\t// If the function didn't abort as expected\n\t\treturn fail(t, msgs, \"func should abort\")\n\t}\n\n\t// Check if the abort value matches the expected message string\n\tabortStr := ufmt.Sprintf(\"%v\", abortValue)\n\tif abortStr != msg {\n\t\treturn fail(t, msgs, \"func should abort with message:\\t%q\\n\\tActual abort value:\\t%q\", msg, abortStr)\n\t}\n\n\t// Success: function aborted with the expected message\n\treturn true\n}\n\n// AbortsContains asserts that the code inside the specified func aborts\n// (panics when crossing another realm) and the abort message contains the specified substring.\n// See AbortsWithMessage for `rlm` semantics.\nfunc AbortsContains(t TestingT, rlm realm, substr string, f any, msgs ...string) bool {\n\tt.Helper()\n\n\tvar didAbort bool\n\tvar abortValue any\n\tvar r any\n\n\tif fn, ok := f.(func()); ok {\n\t\tr = revive(fn)\n\t} else if fn, ok := f.(func(realm)); ok {\n\t\tr = revive(func() { fn(cross(rlm)) })\n\t} else {\n\t\tpanic(\"f must be of type func() or func(realm)\")\n\t}\n\tif r != nil {\n\t\tdidAbort = true\n\t\tabortValue = r\n\t}\n\n\tif !didAbort {\n\t\treturn fail(t, msgs, \"func should abort\")\n\t}\n\n\tabortStr := ufmt.Sprintf(\"%v\", abortValue)\n\tif !strings.Contains(abortStr, substr) {\n\t\treturn fail(t, msgs, \"func should abort with message containing:\\t%q\\n\\tActual abort value:\\t%q\", substr, abortStr)\n\t}\n\n\treturn true\n}\n\n// NotAborts asserts that the code inside the specified func does NOT abort\n// when crossing an execution boundary.\n// Note: Consider using NotPanics which checks for both panics and aborts.\n// See AbortsWithMessage for `rlm` semantics.\nfunc NotAborts(t TestingT, rlm realm, f any, msgs ...string) bool {\n\tt.Helper()\n\n\tvar didAbort bool\n\tvar abortValue any\n\tvar r any\n\n\tswitch f := f.(type) {\n\tcase func():\n\t\tr = revive(f) // revive() captures the value passed to panic()\n\tcase func(realm):\n\t\tr = revive(func() { f(cross(rlm)) })\n\tdefault:\n\t\tpanic(\"f must be of type func() or func(realm)\")\n\t}\n\tif r != nil {\n\t\tdidAbort = true\n\t\tabortValue = r\n\t}\n\n\tif didAbort {\n\t\t// Fail if the function aborted when it shouldn't have\n\t\t// Attempt to format the abort value in the error message\n\t\treturn fail(t, msgs, \"func should not abort\\\\n\\\\tAbort value:\\\\t%v\", abortValue)\n\t}\n\n\t// Success: function did not abort\n\treturn true\n}\n\n// PanicsWithMessage asserts that the code inside the specified func panics\n// locally within the same execution realm.\n// Use AbortsWithMessage for asserting panics that cross execution boundaries (aborts).\n// See AbortsWithMessage for `rlm` semantics.\nfunc PanicsWithMessage(t TestingT, rlm realm, msg string, f any, msgs ...string) bool {\n\tt.Helper()\n\n\tdidPanic, panicValue := checkDidPanic(f, rlm)\n\tif !didPanic {\n\t\treturn fail(t, msgs, \"func should panic\\n\\tPanic value:\\t%v\", panicValue)\n\t}\n\n\t// Check if the abort value matches the expected message string\n\tpanicStr := ufmt.Sprintf(\"%v\", panicValue)\n\tif panicStr != msg {\n\t\treturn fail(t, msgs, \"func should panic with message:\\t%q\\n\\tActual panic value:\\t%q\", msg, panicStr)\n\t}\n\treturn true\n}\n\n// PanicsContains asserts that the code inside the specified func panics\n// locally within the same execution realm and the panic message contains the specified substring.\n// See AbortsWithMessage for `rlm` semantics.\nfunc PanicsContains(t TestingT, rlm realm, substr string, f any, msgs ...string) bool {\n\tt.Helper()\n\n\tdidPanic, panicValue := checkDidPanic(f, rlm)\n\tif !didPanic {\n\t\treturn fail(t, msgs, \"func should panic\\n\\tPanic value:\\t%v\", panicValue)\n\t}\n\n\tpanicStr := ufmt.Sprintf(\"%v\", panicValue)\n\tif !strings.Contains(panicStr, substr) {\n\t\treturn fail(t, msgs, \"func should panic with message containing:\\t%q\\n\\tActual panic value:\\t%q\", substr, panicStr)\n\t}\n\treturn true\n}\n\n// NotPanics asserts that the code inside the specified func does NOT panic\n// (within the same realm) or abort (due to a cross-realm panic).\n// See AbortsWithMessage for `rlm` semantics.\nfunc NotPanics(t TestingT, rlm realm, f any, msgs ...string) bool {\n\tt.Helper()\n\n\tvar panicVal any\n\tvar didPanic bool\n\tvar abortVal any\n\n\t// Use revive to catch cross-realm aborts\n\tabortVal = revive(func() {\n\t\t// Use defer+recover to catch same-realm panics\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tdidPanic = true\n\t\t\t\tpanicVal = r\n\t\t\t}\n\t\t}()\n\t\t// Execute the function\n\t\tswitch f := f.(type) {\n\t\tcase func():\n\t\t\tf()\n\t\tcase func(realm):\n\t\t\tf(cross(rlm))\n\t\tdefault:\n\t\t\tpanic(\"f must be of type func() or func(realm)\")\n\t\t}\n\t})\n\n\t// Check if revive caught an abort\n\tif abortVal != nil {\n\t\treturn fail(t, msgs, \"func should not abort\\n\\tAbort value:\\t%+v\", abortVal)\n\t}\n\n\t// Check if recover caught a panic\n\tif didPanic {\n\t\t// Format panic value for message\n\t\tpanicMsg := \"\"\n\t\tif panicVal == nil {\n\t\t\tpanicMsg = \"nil\"\n\t\t} else if err, ok := panicVal.(error); ok {\n\t\t\tpanicMsg = err.Error()\n\t\t} else if str, ok := panicVal.(string); ok {\n\t\t\tpanicMsg = str\n\t\t} else {\n\t\t\t// Fallback for other types\n\t\t\tpanicMsg = \"panic: unsupported type\"\n\t\t}\n\t\treturn fail(t, msgs, \"func should not panic\\n\\tPanic value:\\t%s\", panicMsg)\n\t}\n\n\treturn true // No panic or abort occurred\n}\n\n// Equal asserts that two objects are equal.\nfunc Equal(t TestingT, expected, actual any, msgs ...string) bool {\n\tt.Helper()\n\n\tif expected == nil || actual == nil {\n\t\treturn expected == actual\n\t}\n\n\t// XXX: errors\n\t// XXX: slices\n\t// XXX: pointers\n\n\tequal := false\n\tok_ := false\n\tes, as := \"unsupported type\", \"unsupported type\"\n\n\tswitch ev := expected.(type) {\n\tcase string:\n\t\tif av, ok := actual.(string); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = ev, av\n\t\t\tif !equal {\n\t\t\t\tdif := diff.MyersDiff(ev, av)\n\t\t\t\treturn fail(t, msgs, \"uassert.Equal: strings are different\\n\\tDiff: %s\", diff.Format(dif))\n\t\t\t}\n\t\t}\n\tcase address:\n\t\tif av, ok := actual.(address); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = string(ev), string(av)\n\t\t}\n\tcase int:\n\t\tif av, ok := actual.(int); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(ev), strconv.Itoa(av)\n\t\t}\n\tcase int8:\n\t\tif av, ok := actual.(int8); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase int16:\n\t\tif av, ok := actual.(int16); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase int32:\n\t\tif av, ok := actual.(int32); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase int64:\n\t\tif av, ok := actual.(int64); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase uint:\n\t\tif av, ok := actual.(uint); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint8:\n\t\tif av, ok := actual.(uint8); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint16:\n\t\tif av, ok := actual.(uint16); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint32:\n\t\tif av, ok := actual.(uint32); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint64:\n\t\tif av, ok := actual.(uint64); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(ev, 10), strconv.FormatUint(av, 10)\n\t\t}\n\tcase bool:\n\t\tif av, ok := actual.(bool); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t\tif ev {\n\t\t\t\tes, as = \"true\", \"false\"\n\t\t\t} else {\n\t\t\t\tes, as = \"false\", \"true\"\n\t\t\t}\n\t\t}\n\tcase float32:\n\t\tif av, ok := actual.(float32); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t}\n\tcase float64:\n\t\tif av, ok := actual.(float64); ok {\n\t\t\tequal = ev == av\n\t\t\tok_ = true\n\t\t}\n\tdefault:\n\t\treturn fail(t, msgs, \"uassert.Equal: unsupported type\")\n\t}\n\n\t/*\n\t\t// XXX: implement stringer and other well known similar interfaces\n\t\ttype stringer interface{ String() string }\n\t\tif ev, ok := expected.(stringer); ok {\n\t\t\tif av, ok := actual.(stringer); ok {\n\t\t\t\tequal = ev.String() == av.String()\n\t\t\t\tok_ = true\n\t\t\t}\n\t\t}\n\t*/\n\n\tif !ok_ {\n\t\treturn fail(t, msgs, \"uassert.Equal: different types\") // XXX: display the types\n\t}\n\tif !equal {\n\t\treturn fail(t, msgs, \"uassert.Equal: same type but different value\\n\\texpected: %s\\n\\tactual:   %s\", es, as)\n\t}\n\n\treturn true\n}\n\n// NotEqual asserts that two objects are not equal.\nfunc NotEqual(t TestingT, expected, actual any, msgs ...string) bool {\n\tt.Helper()\n\n\tif expected == nil || actual == nil {\n\t\treturn expected != actual\n\t}\n\n\t// XXX: errors\n\t// XXX: slices\n\t// XXX: pointers\n\n\tnotEqual := false\n\tok_ := false\n\tes, as := \"unsupported type\", \"unsupported type\"\n\n\tswitch ev := expected.(type) {\n\tcase string:\n\t\tif av, ok := actual.(string); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = ev, av\n\t\t}\n\tcase address:\n\t\tif av, ok := actual.(address); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = string(ev), string(av)\n\t\t}\n\tcase int:\n\t\tif av, ok := actual.(int); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(ev), strconv.Itoa(av)\n\t\t}\n\tcase int8:\n\t\tif av, ok := actual.(int8); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase int16:\n\t\tif av, ok := actual.(int16); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase int32:\n\t\tif av, ok := actual.(int32); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase int64:\n\t\tif av, ok := actual.(int64); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))\n\t\t}\n\tcase uint:\n\t\tif av, ok := actual.(uint); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint8:\n\t\tif av, ok := actual.(uint8); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint16:\n\t\tif av, ok := actual.(uint16); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint32:\n\t\tif av, ok := actual.(uint32); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)\n\t\t}\n\tcase uint64:\n\t\tif av, ok := actual.(uint64); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tes, as = strconv.FormatUint(ev, 10), strconv.FormatUint(av, 10)\n\t\t}\n\tcase bool:\n\t\tif av, ok := actual.(bool); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t\tif ev {\n\t\t\t\tes, as = \"true\", \"false\"\n\t\t\t} else {\n\t\t\t\tes, as = \"false\", \"true\"\n\t\t\t}\n\t\t}\n\tcase float32:\n\t\tif av, ok := actual.(float32); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t}\n\tcase float64:\n\t\tif av, ok := actual.(float64); ok {\n\t\t\tnotEqual = ev != av\n\t\t\tok_ = true\n\t\t}\n\tdefault:\n\t\treturn fail(t, msgs, \"uassert.NotEqual: unsupported type\")\n\t}\n\n\t/*\n\t\t// XXX: implement stringer and other well known similar interfaces\n\t\ttype stringer interface{ String() string }\n\t\tif ev, ok := expected.(stringer); ok {\n\t\t\tif av, ok := actual.(stringer); ok {\n\t\t\t\tnotEqual = ev.String() != av.String()\n\t\t\t\tok_ = true\n\t\t\t}\n\t\t}\n\t*/\n\n\tif !ok_ {\n\t\treturn fail(t, msgs, \"uassert.NotEqual: different types\") // XXX: display the types\n\t}\n\tif !notEqual {\n\t\treturn fail(t, msgs, \"uassert.NotEqual: same type and same value\\n\\texpected: %s\\n\\tactual:   %s\", es, as)\n\t}\n\n\treturn true\n}\n\nfunc isNumberEmpty(n any) (isNumber, isEmpty bool) {\n\tswitch n := n.(type) {\n\t// NOTE: the cases are split individually, so that n becomes of the\n\t// asserted type; the type of '0' was correctly inferred and converted\n\t// to the corresponding type, int, int8, etc.\n\tcase int:\n\t\treturn true, n == 0\n\tcase int8:\n\t\treturn true, n == 0\n\tcase int16:\n\t\treturn true, n == 0\n\tcase int32:\n\t\treturn true, n == 0\n\tcase int64:\n\t\treturn true, n == 0\n\tcase uint:\n\t\treturn true, n == 0\n\tcase uint8:\n\t\treturn true, n == 0\n\tcase uint16:\n\t\treturn true, n == 0\n\tcase uint32:\n\t\treturn true, n == 0\n\tcase uint64:\n\t\treturn true, n == 0\n\tcase float32:\n\t\treturn true, n == 0\n\tcase float64:\n\t\treturn true, n == 0\n\t}\n\treturn false, false\n}\n\nfunc Empty(t TestingT, obj any, msgs ...string) bool {\n\tt.Helper()\n\n\tisNumber, isEmpty := isNumberEmpty(obj)\n\tif isNumber {\n\t\tif !isEmpty {\n\t\t\treturn fail(t, msgs, \"uassert.Empty: not empty number: %d\", obj)\n\t\t}\n\t} else {\n\t\tswitch val := obj.(type) {\n\t\tcase string:\n\t\t\tif val != \"\" {\n\t\t\t\treturn fail(t, msgs, \"uassert.Empty: not empty string: %s\", val)\n\t\t\t}\n\t\tcase address:\n\t\t\tvar zeroAddr address\n\t\t\tif val != zeroAddr {\n\t\t\t\treturn fail(t, msgs, \"uassert.Empty: not empty address: %s\", string(val))\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fail(t, msgs, \"uassert.Empty: unsupported type\")\n\t\t}\n\t}\n\treturn true\n}\n\nfunc NotEmpty(t TestingT, obj any, msgs ...string) bool {\n\tt.Helper()\n\tisNumber, isEmpty := isNumberEmpty(obj)\n\tif isNumber {\n\t\tif isEmpty {\n\t\t\treturn fail(t, msgs, \"uassert.NotEmpty: empty number: %d\", obj)\n\t\t}\n\t} else {\n\t\tswitch val := obj.(type) {\n\t\tcase string:\n\t\t\tif val == \"\" {\n\t\t\t\treturn fail(t, msgs, \"uassert.NotEmpty: empty string: %s\", val)\n\t\t\t}\n\t\tcase address:\n\t\t\tvar zeroAddr address\n\t\t\tif val == zeroAddr {\n\t\t\t\treturn fail(t, msgs, \"uassert.NotEmpty: empty address: %s\", string(val))\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fail(t, msgs, \"uassert.NotEmpty: unsupported type\")\n\t\t}\n\t}\n\treturn true\n}\n\n// Nil asserts that the value is nil.\nfunc Nil(t TestingT, value any, msgs ...string) bool {\n\tt.Helper()\n\tif value != nil {\n\t\treturn fail(t, msgs, \"should be nil\")\n\t}\n\treturn true\n}\n\n// NotNil asserts that the value is not nil.\nfunc NotNil(t TestingT, value any, msgs ...string) bool {\n\tt.Helper()\n\tif value == nil {\n\t\treturn fail(t, msgs, \"should not be nil\")\n\t}\n\treturn true\n}\n\n// TypedNil asserts that the value is a typed-nil (nil pointer) value.\nfunc TypedNil(t TestingT, value any, msgs ...string) bool {\n\tt.Helper()\n\tif value == nil {\n\t\treturn fail(t, msgs, \"should be typed-nil but got nil instead\")\n\t}\n\tif !istypednil(value) {\n\t\treturn fail(t, msgs, \"should be typed-nil\")\n\t}\n\treturn true\n}\n\n// NotTypedNil asserts that the value is not a typed-nil (nil pointer) value.\nfunc NotTypedNil(t TestingT, value any, msgs ...string) bool {\n\tt.Helper()\n\tif istypednil(value) {\n\t\treturn fail(t, msgs, \"should not be typed-nil\")\n\t}\n\treturn true\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"launderpkg","path":"gno.land/p/demo/tests/launderpkg/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/launderpkg/v0\"\ngno = \"0.9\"\n"},{"name":"launderpkg.gno","body":"// Package launderpkg defines a struct type that the laundervictim\n// realm uses as the type of its package-level state. The Set method\n// is the \"innocent /p/-helper\" that an attacker tries to weaponize\n// via the receiver-borrow rule (PushFrameCall borrow rule 2):\n// when the receiver is owned by /r/X, calling Set borrows m.Realm to\n// /r/X, and the write inside Set runs with /r/X authority.\npackage launderpkg\n\ntype Object struct {\n\tField string\n}\n\n// PInitData is a /p/-init-allocated package-level data var. Its\n// StructValue carries ObjectInfo.PkgID = /p/demo/tests/launderpkg/v0.\n// Used by zrealm_launder_pdata_* filetests to probe the /p/-source\n// read patterns that the existing 62 /r/-source launder filetests\n// don't cover. Empirically, direct value-read and pointer-deref of\n// PInitData from a /r/-caller both panic readonly tainted — the\n// /p/-source bytes are not adoptable into /r/-authority via these\n// patterns.\nvar PInitData = Object{Field: \"p-init\"}\n\n// Set is the canonical \"/p/ helper that mutates /r/-owned state\"\n// pattern. Looks benign — like list.Set, avl.Set, etc. — but if a\n// foreign caller obtains a pointer to a victim realm's Object, they\n// can invoke Set on it and the borrow rule grants them victim\n// authority for the call. Exposing a *Object out of a realm is\n// equivalent to consenting to mutation by any caller that holds the\n// pointer.\nfunc (o *Object) Set(s string) {\n\to.Field = s\n}\n\n// Read is a read-only accessor.\nfunc (o *Object) Read() string {\n\treturn o.Field\n}\n\n// Mutator is an interface — callers can pass any implementation. A\n// realistic pattern: /p/orig defines a hook interface and exposes a\n// method that lets callers register an impl for some operation.\ntype Mutator interface {\n\tRun(*Immutable)\n}\n\n// UseMutator is a /p/-method on *Object that dispatches an interface\n// method (Mutator.Run) with target as the argument. This is the\n// realistic shape — a /p/-library invoking a user-supplied hook on\n// /r/-owned data.\nfunc (o *Object) UseMutator(target *Immutable, m Mutator) {\n\tm.Run(target)\n}\n\n// SliceMutator's Run takes a SLICE of pointers — exercises the\n// \"non-pointer parameter that still conveys writable foreign data\"\n// shape that Attack K explores.\ntype SliceMutator interface {\n\tRun([]*Immutable)\n}\n\n// UseSliceMutator dispatches a SliceMutator on a single-element\n// slice carrying target.\nfunc (o *Object) UseSliceMutator(target *Immutable, m SliceMutator) {\n\tm.Run([]*Immutable{target})\n}\n\n// AnyMutator's Run takes `any` — interface-typed parameter. The\n// caller can box a *Immutable into the interface and an attacker\n// impl can type-assert back to write. Tests whether the predicate\n// needs to treat interface-typed params as potentially foreign.\ntype AnyMutator interface {\n\tRun(any)\n}\n\n// UseAnyMutator boxes target into `any` before dispatching.\nfunc (o *Object) UseAnyMutator(target *Immutable, m AnyMutator) {\n\tm.Run(target)\n}\n\n// Bare is a /p/-declared struct type with NO methods. Used to test\n// whether embedding/fielding a methods-less /p/-type inside an\n// /r/-declared container exposes any laundering vector through\n// DIRECT field writes (no method dispatch, no Apply callback). The\n// expectation: readonly taint on the /r/-container propagates to\n// inner /p/-typed fields and direct writes panic.\ntype Bare struct {\n\tField string\n}\n\n// Immutable is a deliberately read-only /p/ type: same struct layout\n// as Object, but no mutator method. A realm using Immutable as the\n// type of an exposed field intends \"read-only API.\" The launder game\n// variation explores whether an attacker /p/ package can convert\n// *Immutable to a type with a mutator method declared elsewhere.\ntype Immutable struct {\n\tField string\n}\n\n// Read is a read-only accessor.\nfunc (i *Immutable) Read() string {\n\treturn i.Field\n}\n\n// Apply is a higher-order helper that hands the *Immutable to a\n// caller-supplied callback. The signature looks read-only (no\n// mutator method on *Immutable itself), but Apply hands out an\n// addressable pointer to victim-owned memory while m.Realm is\n// borrowed to the victim. A /p/-declared callback substituted by\n// the caller therefore runs with victim authority. This is the\n// avl.Tree.Iterate / list.ForEach shape — common in /p/ libraries.\nfunc (i *Immutable) Apply(fn func(*Immutable)) {\n\tfn(i)\n}\n\n// BumpToPwn is a no-arg, no-return /p/-method that mutates the\n// receiver. Used by stored-bound-method-value laundering probes:\n// `mv := victimImmPtr.BumpToPwn` has type `func()`, which fits\n// PlainHook = func(). When the bound method value is stored and\n// invoked later from /r/-victim context, recv-borrow borrow rule #2 fires on\n// the /r/-victim-stamped recv → m.Realm = /r/-victim → write\n// commits.\nfunc (i *Immutable) BumpToPwn() {\n\ti.Field = \"pwnd-via-bound-mv\"\n}\n\n// DeferApply is the defer-variant of Apply: schedules fn(i) as a\n// defer instead of calling synchronously. Used to probe whether\n// the borrow rules apply the same when a callback is invoked from\n// inside a /p/-function's defer queue.\nfunc (i *Immutable) DeferApply(fn func(*Immutable)) {\n\tdefer fn(i)\n}\n\n// PanicAfterApply: invokes fn(i) synchronously, then panics after\n// return. If fn ran without panicking (write succeeded), the panic\n// here is /p/-realm panic propagating up.\nfunc (i *Immutable) PanicAfterApply(fn func(*Immutable)) {\n\tfn(i)\n\tpanic(\"post-apply panic\")\n}\n\n// RecoverApply: defers a recover(), then calls fn(i). If fn panics\n// with readonly, recover catches it (within the same /p/-pkg\n// frame). Returns the recovered value.\nfunc (i *Immutable) RecoverApply(fn func(*Immutable)) (rec any) {\n\tdefer func() {\n\t\trec = recover()\n\t}()\n\tfn(i)\n\treturn\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"launderrvictim","path":"gno.land/r/tests/vm/launderrvictim","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/launderrvictim\"\ngno = \"0.9\"\n"},{"name":"launderrvictim.gno","body":"// Package launderrvictim is the /r/-DATA-DECLARED variant of the\n// launder-game victim. Its Immutable type is declared HERE (in /r/),\n// not in /p/launderpkg. This is the recommended inter-realm pattern:\n// realms declare their own logic data types.\n//\n// The hypothesis under test: with /r/-declared logic data, the\n// Attack H/I/J/K/L laundering shapes are structurally impossible.\n// Tests against this victim should all fail to mutate gImm.\npackage launderrvictim\n\nimport \"gno.land/p/demo/tests/launderpkg/v0\"\n\n// Immutable is /r/-declared (the key difference from /r/laundervictim,\n// which uses /p/launderpkg.Immutable).\ntype Immutable struct {\n\tField string\n}\n\n// Read is /r/launderrvictim-declared, so calling it borrow rule #1 borrows\n// m.Realm to launderrvictim.\nfunc (i *Immutable) Read() string { return i.Field }\n\nvar gImm *Immutable\n\nfunc init() {\n\tgImm = \u0026Immutable{Field: \"rdata-original\"}\n}\n\n// GetImm hands out a pointer to gImm. Standard \"victim exposes a\n// pointer to its state\" antipattern — but with /r/-declared data,\n// the attacker should still be unable to write through it.\nfunc GetImm() *Immutable { return gImm }\n\n// ReadImm reads the current field for after-attack verification.\nfunc ReadImm() string { return gImm.Field }\n\n// UseAnyMutator boxes gImm as any and dispatches a /p/-declared\n// AnyMutator. This is the dangerous shape from Attack L: victim\n// boxes its own /r/-declared data through a /p/-defined interface\n// that the attacker can implement.\nfunc UseAnyMutator(m launderpkg.AnyMutator) {\n\tm.Run(gImm)\n}\n\n// ApplyHook dispatches a caller-supplied callback on gImm. The\n// callback's parameter type is /r/launderrvictim-declared, so /p/\n// packages can't supply this hook — only /r/ realms can.\nfunc ApplyHook(h func(*Immutable)) {\n\th(gImm)\n}\n\n// --- /p/-type embedded / fielded inside /r/-declared types ---\n//\n// The three shapes below mix /r/-declared containers with /p/-typed\n// inner state. Even though the container types are /r/-declared,\n// the inner /p/-typed values inherit /p/'s methods — including\n// Apply-style higher-order methods that take /p/-typed callbacks.\n// /p/-attacker code can supply such callbacks. The attacker reaches\n// the inner /p/-value (read access works), then invokes Apply with\n// a /p/-declared function pointer. Inside Apply (borrow rule #2ed\n// to /r/launderrvictim), the callback runs without any borrow rule #1 or #2\n// shift (top-level /p/ fn), so the write commits under victim\n// authority.\n\n// WithEmbed embeds launderpkg.Immutable by VALUE (method promotion\n// gives WithEmbed an .Apply method).\ntype WithEmbed struct {\n\tlaunderpkg.Immutable\n}\n\n// WithPtr has a POINTER FIELD to launderpkg.Immutable.\ntype WithPtr struct {\n\tInner *launderpkg.Immutable\n}\n\n// WithVal has a VALUE FIELD of launderpkg.Immutable (not embedded;\n// the field is named, no method promotion — but the value is still\n// addressable through c.Inner).\ntype WithVal struct {\n\tInner launderpkg.Immutable\n}\n\nvar (\n\tgWithEmbed *WithEmbed\n\tgWithPtr   *WithPtr\n\tgWithVal   *WithVal\n)\n\nfunc init() {\n\tgWithEmbed = \u0026WithEmbed{Immutable: launderpkg.Immutable{Field: \"embed-orig\"}}\n\tgWithPtr = \u0026WithPtr{Inner: \u0026launderpkg.Immutable{Field: \"ptr-orig\"}}\n\tgWithVal = \u0026WithVal{Inner: launderpkg.Immutable{Field: \"val-orig\"}}\n}\n\nfunc GetWithEmbed() *WithEmbed { return gWithEmbed }\nfunc GetWithPtr() *WithPtr     { return gWithPtr }\nfunc GetWithVal() *WithVal     { return gWithVal }\n\nfunc ReadEmbed() string { return gWithEmbed.Field }\nfunc ReadPtr() string   { return gWithPtr.Inner.Field }\nfunc ReadVal() string   { return gWithVal.Inner.Field }\n\n// --- Methods-less /p/-type inner state ---\n// launderpkg.Bare has no methods. These containers wrap Bare in\n// the three field shapes. The question: does readonly taint catch\n// a direct field write through the /r/-container's getter?\n\ntype WithBareEmbed struct {\n\tlaunderpkg.Bare\n}\n\ntype WithBarePtr struct {\n\tInner *launderpkg.Bare\n}\n\ntype WithBareVal struct {\n\tInner launderpkg.Bare\n}\n\nvar (\n\tgWithBareEmbed *WithBareEmbed\n\tgWithBarePtr   *WithBarePtr\n\tgWithBareVal   *WithBareVal\n)\n\nfunc init() {\n\tgWithBareEmbed = \u0026WithBareEmbed{Bare: launderpkg.Bare{Field: \"bare-embed-orig\"}}\n\tgWithBarePtr = \u0026WithBarePtr{Inner: \u0026launderpkg.Bare{Field: \"bare-ptr-orig\"}}\n\tgWithBareVal = \u0026WithBareVal{Inner: launderpkg.Bare{Field: \"bare-val-orig\"}}\n}\n\nfunc GetWithBareEmbed() *WithBareEmbed { return gWithBareEmbed }\nfunc GetWithBarePtr() *WithBarePtr     { return gWithBarePtr }\nfunc GetWithBareVal() *WithBareVal     { return gWithBareVal }\n\nfunc ReadBareEmbed() string { return gWithBareEmbed.Field }\nfunc ReadBarePtr() string   { return gWithBarePtr.Inner.Field }\nfunc ReadBareVal() string   { return gWithBareVal.Inner.Field }\n\n// --- Composite containers holding /p/-typed elements ---\n// Slices, arrays, maps of methods-less /p/-Bare values and pointers.\n\nvar (\n\tgBareSlice    []launderpkg.Bare\n\tgBarePtrSlice []*launderpkg.Bare\n\tgBareArr      [3]launderpkg.Bare\n\tgBarePtrArr   [3]*launderpkg.Bare\n\tgBareMap      map[string]launderpkg.Bare\n\tgBarePtrMap   map[string]*launderpkg.Bare\n)\n\nfunc init() {\n\tgBareSlice = []launderpkg.Bare{\n\t\t{Field: \"slice0\"}, {Field: \"slice1\"},\n\t}\n\tgBarePtrSlice = []*launderpkg.Bare{\n\t\t{Field: \"ptrslice0\"}, {Field: \"ptrslice1\"},\n\t}\n\tgBareArr = [3]launderpkg.Bare{\n\t\t{Field: \"arr0\"}, {Field: \"arr1\"}, {Field: \"arr2\"},\n\t}\n\tgBarePtrArr = [3]*launderpkg.Bare{\n\t\t{Field: \"ptrarr0\"}, {Field: \"ptrarr1\"}, {Field: \"ptrarr2\"},\n\t}\n\tgBareMap = map[string]launderpkg.Bare{\n\t\t\"a\": {Field: \"mapA\"}, \"b\": {Field: \"mapB\"},\n\t}\n\tgBarePtrMap = map[string]*launderpkg.Bare{\n\t\t\"a\": {Field: \"ptrmapA\"}, \"b\": {Field: \"ptrmapB\"},\n\t}\n}\n\nfunc GetBareSlice() []launderpkg.Bare            { return gBareSlice }\nfunc GetBarePtrSlice() []*launderpkg.Bare        { return gBarePtrSlice }\nfunc GetBareArr() *[3]launderpkg.Bare            { return \u0026gBareArr }\nfunc GetBarePtrArr() *[3]*launderpkg.Bare        { return \u0026gBarePtrArr }\nfunc GetBareMap() map[string]launderpkg.Bare     { return gBareMap }\nfunc GetBarePtrMap() map[string]*launderpkg.Bare { return gBarePtrMap }\n\nfunc ReadBareSlice0() string      { return gBareSlice[0].Field }\nfunc ReadBareSlice0Then1() string { return gBareSlice[1].Field }\nfunc ReadBarePtrSlice0() string   { return gBarePtrSlice[0].Field }\nfunc ReadBareArr0() string        { return gBareArr[0].Field }\nfunc ReadBarePtrArr0() string     { return gBarePtrArr[0].Field }\nfunc ReadBareMapA() string        { return gBareMap[\"a\"].Field }\nfunc ReadBarePtrMapA() string     { return gBarePtrMap[\"a\"].Field }\n\n// --- Panic/defer/recover helpers ---\n// These victim-side helpers expose scenarios where the m.Realm\n// borrow can interact with deferred calls, recover(), and panics\n// in unusual control-flow shapes.\n\n// DeferCallback installs h as a defer inside an /r/launderrvictim\n// frame, then returns. h runs at frame pop. The question: at the\n// time h is invoked, m.Realm has just been restored to caller's\n// realm by PopFrameAndReturn — but wait, defers run BEFORE\n// PopFrameAndReturn. So m.Realm should still be victim's. Does\n// the deferred h then run under victim authority?\nfunc DeferCallback(h func(*Immutable)) {\n\tdefer h(gImm)\n}\n\n// PanicAfterPushDefer pushes a defer and then panics, so the defer\n// runs as part of panic unwinding. Tests that m.Realm is correctly\n// borrowed when the defer body invokes a foreign function.\nfunc PanicAfterPushDefer(h func(*Immutable)) {\n\tdefer h(gImm)\n\tpanic(\"victim-induced panic\")\n}\n\n// DeferApplyHook defers an ApplyHook call. The deferred ApplyHook\n// itself runs borrow rule #1 to /r/launderrvictim, and inside the\n// callback runs as borrow rule #1 of the attacker's realm — the standard\n// known-open Apply pattern, but now triggered via defer.\nfunc DeferApplyHook(h func(*Immutable)) {\n\tdefer ApplyHook(h)\n}\n\n// RecoverAndRetry: inside a victim method, defer a recover, write\n// something to gImm, then panic. After the recover, the function\n// returns normally. Tests that internal panic/recover doesn't leak\n// state.\nfunc RecoverAndRetry(h func(*Immutable)) (recovered any) {\n\tdefer func() {\n\t\trecovered = recover()\n\t}()\n\th(gImm)\n\treturn\n}\n\n// CallThenPanic invokes h synchronously and then panics. If h is\n// attacker-supplied and writes via captured pointer, this is just\n// a re-shape of ApplyHook.\nfunc CallThenPanic(h func(*Immutable)) {\n\th(gImm)\n\tpanic(\"victim panic after callback\")\n}\n\n// CallPDeferApply: multi-level defer chain. Victim invokes a\n// /p/-method (DeferApply) on a victim-owned *launderpkg.Immutable;\n// the /p/-method defers the attacker callback. Three frames at\n// callback time: attacker.main → victim.CallPDeferApply →\n// /p/.DeferApply (deferred fn dispatches here).\nfunc CallPDeferApply(fn func(*launderpkg.Immutable)) {\n\tgWithPtr.Inner.DeferApply(fn)\n}\n\n// --- Stored-hook plumbing ---\n//\n// Victim accepts caller-registered callbacks and dispatches them\n// LATER, from inside a /r/-victim method body. If the registered\n// callback is /p/-declared and writes through a captured /r/-stamped\n// pointer, the laundering shape is: stored callback rather than\n// callback-arg.\n\ntype ImmHook func(*Immutable)\n\nvar gHooks []ImmHook\n\nfunc RegisterHook(h ImmHook) { gHooks = append(gHooks, h) }\nfunc RunHooks() {\n\tfor _, h := range gHooks {\n\t\th(gImm)\n\t}\n}\n\ntype PlainHook func()\n\nvar gPlainHooks []PlainHook\n\nfunc RegisterPlainHook(h PlainHook) { gPlainHooks = append(gPlainHooks, h) }\nfunc RunPlainHooks() {\n\tfor _, h := range gPlainHooks {\n\t\th()\n\t}\n}\n\nfunc ClearHooks() {\n\tgHooks = nil\n\tgPlainHooks = nil\n}\n\n// MakeWriterClosure constructs a /r/-victim-declared closure that\n// captures gImm and writes through it. The closure body is /r/-victim-\n// declared, so borrow rule #1 fires at invocation → m.Realm = /r/-victim →\n// write commits with victim authority. Returning this closure to an\n// attacker is \"consenting to write\" by the victim.\nfunc MakeWriterClosure(value string) func() {\n\treturn func() {\n\t\tgImm.Field = value\n\t}\n}\n\n// MakeApplyTrampoline returns a closure that captures \u0026gImm.Field\n// indirectly: it captures *Immutable, and dispatches a caller-supplied\n// callback fn on it. /r/-victim-declared body → borrow rule #1 → m.Realm =\n// /r/-victim. If `fn` is /p/-declared (e.g. EvilWrite), it inherits\n// victim authority. This is \"victim returns a closure that's itself\n// an Apply-style trampoline\" — a packaged Apply.\nfunc MakeApplyTrampoline() func(func(*Immutable)) {\n\treturn func(fn func(*Immutable)) {\n\t\tfn(gImm)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"p_closurecap","path":"gno.land/p/demo/tests/p_closurecap/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/p_closurecap/v0\"\ngno = \"0.9\"\n"},{"name":"p_closurecap.gno","body":"// Package p_closurecap exercises the \"var stopped bool in\n// memberStorage.IterateByOffset\" pattern from boards2/commondao:\n// a method declares a local var that an inline closure captures and\n// writes to. Without the unreal-HIV exception in the readonly check,\n// this failed across borrow-realm transitions because the HIV's PkgID\n// stamp records the alloc-site realm, but the closure body may run\n// under a different borrowed realm — the check would fire on a write\n// the closure itself made to its own captured slot.\npackage p_closurecap\n\n// Inner is the receiver of loop(). When Inner lives in a different\n// realm than the Outer-method's caller realm, PushFrameCall's borrow\n// rule 2 shifts m.Realm to Inner's realm for the entire body of loop()\n// (and the synchronously-invoked closure). That shift is what makes\n// HIV.PkgID (stamped at var stopped's alloc) differ from m.Realm at\n// the closure's write site.\ntype Inner struct {\n\tN int\n}\n\n// Outer is the var-stopped pattern. The inline closure captures\n// `stopped` and writes to it. Returns true if `fn` ever returned true.\n//\n// The key shape: Outer is a top-level /p/ func (no receiver, so no\n// borrow on entry — HIV stamps with caller's realm), but it delegates\n// to `inn.loop(...)`, where `inn` is supplied by the caller and may\n// live in a different realm. inn.loop's borrow flips m.Realm to inn's\n// realm; the inline closure then writes to `stopped` under that\n// borrowed realm.\nfunc Outer(inn *Inner, count int, fn func(i int) bool) bool {\n\tvar stopped bool\n\tinn.loop(count, func(i int) bool {\n\t\tstopped = fn(i)\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n\n// loop is a /p/ method on *Inner. As a receiver-method on a /p/ type,\n// PushFrameCall's borrow rule 2 fires here: m.Realm becomes\n// Inner.PkgID's realm for the duration of loop().\nfunc (in *Inner) loop(count int, cb func(i int) bool) {\n\tfor i := 0; i \u003c count; i++ {\n\t\tif cb(i) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// MakeCounter returns a closure that captures a local int. The\n// returned closure can be stored in /r/ state — verifying that a\n// persisted closure-capture HIV (whose FuncLit lives in /p/) is still\n// writable when invoked from a foreign realm context.\nfunc MakeCounter(start int) func() int {\n\tc := start\n\treturn func() int {\n\t\tc++\n\t\treturn c\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"pager","path":"gno.land/p/nt/avl/pager/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/avl/pager/v0\"\ngno = \"0.9\"\n"},{"name":"pager.gno","body":"package pager\n\nimport (\n\t\"math\"\n\t\"net/url\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/avl/rotree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Pager is a struct that holds the AVL tree and pagination parameters.\ntype Pager struct {\n\tTree            rotree.IReadOnlyTree\n\tPageQueryParam  string\n\tSizeQueryParam  string\n\tDefaultPageSize int\n\tReversed        bool\n}\n\n// Page represents a single page of results.\ntype Page struct {\n\tItems      []Item\n\tPageNumber int\n\tPageSize   int\n\tTotalItems int\n\tTotalPages int\n\tHasPrev    bool\n\tHasNext    bool\n\tPager      *Pager // Reference to the parent Pager\n}\n\n// Item represents a key-value pair in the AVL tree.\ntype Item struct {\n\tKey   string\n\tValue any\n}\n\n// NewPager creates a new Pager with default values.\nfunc NewPager(tree rotree.IReadOnlyTree, defaultPageSize int, reversed bool) *Pager {\n\treturn \u0026Pager{\n\t\tTree:            tree,\n\t\tPageQueryParam:  \"page\",\n\t\tSizeQueryParam:  \"size\",\n\t\tDefaultPageSize: defaultPageSize,\n\t\tReversed:        reversed,\n\t}\n}\n\n// GetPage retrieves a page of results from the AVL tree.\nfunc (p *Pager) GetPage(pageNumber int) *Page {\n\treturn p.GetPageWithSize(pageNumber, p.DefaultPageSize)\n}\n\nfunc (p *Pager) GetPageWithSize(pageNumber, pageSize int) *Page {\n\tif pageSize \u003c= 0 {\n\t\tpanic(\"GetPageWithSize: invalid page size\")\n\t}\n\n\ttotalItems := p.Tree.Size()\n\ttotalPages := int(math.Ceil(float64(totalItems) / float64(pageSize)))\n\n\tpage := \u0026Page{\n\t\tTotalItems: totalItems,\n\t\tTotalPages: totalPages,\n\t\tPageSize:   pageSize,\n\t\tPager:      p,\n\t}\n\n\t// page number provided is not available\n\tif pageNumber \u003c 1 {\n\t\tpage.HasNext = totalPages \u003e 0\n\t\treturn page\n\t}\n\n\t// page number provided is outside the range of total pages\n\tif pageNumber \u003e totalPages {\n\t\tpage.PageNumber = pageNumber\n\t\tpage.HasPrev = pageNumber \u003e 0\n\t\treturn page\n\t}\n\n\tstartIndex := (pageNumber - 1) * pageSize\n\tendIndex := startIndex + pageSize\n\tif endIndex \u003e totalItems {\n\t\tendIndex = totalItems\n\t}\n\n\titems := []Item{}\n\n\tif p.Reversed {\n\t\tp.Tree.ReverseIterateByOffset(startIndex, endIndex-startIndex, func(key string, value any) bool {\n\t\t\titems = append(items, Item{Key: key, Value: value})\n\t\t\treturn false\n\t\t})\n\t} else {\n\t\tp.Tree.IterateByOffset(startIndex, endIndex-startIndex, func(key string, value any) bool {\n\t\t\titems = append(items, Item{Key: key, Value: value})\n\t\t\treturn false\n\t\t})\n\t}\n\n\tpage.Items = items\n\tpage.PageNumber = pageNumber\n\tpage.HasPrev = pageNumber \u003e 1\n\tpage.HasNext = pageNumber \u003c totalPages\n\treturn page\n}\n\nfunc (p *Pager) MustGetPageByPath(rawURL string) *Page {\n\tpage, err := p.GetPageByPath(rawURL)\n\tif err != nil {\n\t\tpanic(\"invalid path\")\n\t}\n\treturn page\n}\n\n// GetPageByPath retrieves a page of results based on the query parameters in the URL path.\nfunc (p *Pager) GetPageByPath(rawURL string) (*Page, error) {\n\tpageNumber, pageSize, err := p.ParseQuery(rawURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.GetPageWithSize(pageNumber, pageSize), nil\n}\n\n// Picker generates the Markdown UI for the page Picker\nfunc (p *Page) Picker(path string) string {\n\tpageNumber := p.PageNumber\n\tpageNumber = max(pageNumber, 1)\n\n\tif p.TotalPages \u003c= 1 {\n\t\treturn \"\"\n\t}\n\n\tu, _ := url.Parse(path)\n\tquery := u.Query()\n\n\t// Remove existing page query parameter\n\tquery.Del(p.Pager.PageQueryParam)\n\n\t// Encode remaining query parameters\n\tbaseQuery := query.Encode()\n\tif baseQuery != \"\" {\n\t\tbaseQuery = \"\u0026\" + baseQuery\n\t}\n\tmd := \"\"\n\n\tif p.HasPrev {\n\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", 1, p.Pager.PageQueryParam, 1, baseQuery)\n\n\t\tif p.PageNumber \u003e 4 {\n\t\t\tmd += \"… | \"\n\t\t}\n\n\t\tif p.PageNumber \u003e 3 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber-2, p.Pager.PageQueryParam, p.PageNumber-2, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003e 2 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber-1, p.Pager.PageQueryParam, p.PageNumber-1, baseQuery)\n\t\t}\n\t}\n\n\tif p.PageNumber \u003e 0 \u0026\u0026 p.PageNumber \u003c= p.TotalPages {\n\t\tmd += ufmt.Sprintf(\"**%d**\", p.PageNumber)\n\t} else {\n\t\tmd += ufmt.Sprintf(\"_%d_\", p.PageNumber)\n\t}\n\n\tif p.HasNext {\n\t\tif p.PageNumber \u003c p.TotalPages-1 {\n\t\t\tmd += ufmt.Sprintf(\" | [%d](?%s=%d%s)\", p.PageNumber+1, p.Pager.PageQueryParam, p.PageNumber+1, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003c p.TotalPages-2 {\n\t\t\tmd += ufmt.Sprintf(\" | [%d](?%s=%d%s)\", p.PageNumber+2, p.Pager.PageQueryParam, p.PageNumber+2, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003c p.TotalPages-3 {\n\t\t\tmd += \" | …\"\n\t\t}\n\n\t\tmd += ufmt.Sprintf(\" | [%d](?%s=%d%s)\", p.TotalPages, p.Pager.PageQueryParam, p.TotalPages, baseQuery)\n\t}\n\n\treturn md\n}\n\n// ParseQuery parses the URL to extract the page number and page size.\nfunc (p *Pager) ParseQuery(rawURL string) (int, int, error) {\n\tu, err := url.Parse(rawURL)\n\tif err != nil {\n\t\treturn 1, p.DefaultPageSize, err\n\t}\n\n\tquery := u.Query()\n\tpageNumber := 1\n\tpageSize := p.DefaultPageSize\n\n\tif p.PageQueryParam != \"\" {\n\t\tif pageStr := query.Get(p.PageQueryParam); pageStr != \"\" {\n\t\t\tpageNumber, err = strconv.Atoi(pageStr)\n\t\t\tif err != nil || pageNumber \u003c 1 {\n\t\t\t\tpageNumber = 1\n\t\t\t}\n\t\t}\n\t}\n\n\tif p.SizeQueryParam != \"\" {\n\t\tif sizeStr := query.Get(p.SizeQueryParam); sizeStr != \"\" {\n\t\t\tpageSize, err = strconv.Atoi(sizeStr)\n\t\t\tif err != nil || pageSize \u003c 1 {\n\t\t\t\tpageSize = p.DefaultPageSize\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pageNumber, pageSize, nil\n}\n\nfunc max(a, b int) int {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"grc721","path":"gno.land/p/nt/grc721/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/grc721/v0\"\ngno = \"0.9\"\n"},{"name":"tellers.gno","body":"package grc721\n\nimport (\n\t\"chain\"\n)\n\n// CallerTeller resolves the acting account at each write as rlm.Previous() —\n// the realm that crossed into the realm holding the teller.\n//\n// SECURITY: this accessor hangs off *PrivateLedger, not *Token, and that is\n// load-bearing. A frame-relative teller acts as whoever crossed into its\n// holder, so it is only meaningful inside the token's own realm, where the\n// wrappers act for a caller who knowingly invoked the collection. Anywhere\n// else it is a confused deputy: a realm a user merely calls could move that\n// user's tokens. The *Token pointer is published — exported vars, the\n// collection facade, grc721reg — while the ledger is not, since NewToken hands\n// it to the creating realm and nowhere else. So a foreign realm cannot mint\n// one.\n//\n// Construction privacy alone is not enough: a realm may legally build a teller\n// and then export the VALUE. The write methods therefore also verify that the\n// invoking realm is the token's own (see guardHome), which leaves a leaked\n// teller inert everywhere but home.\nfunc (led *PrivateLedger) CallerTeller() Teller {\n\tif led == nil {\n\t\tpanic(\"Ledger cannot be nil\")\n\t}\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, rlm realm) address {\n\t\t\treturn rlm.Previous().Address()\n\t\t},\n\t\thomeGuard: true,\n\t\tToken:     led.token,\n\t}\n}\n\n// Write methods return ErrReadonly.\nfunc (tok *Token) ReadonlyTeller() Teller {\n\tif tok == nil {\n\t\tpanic(\"Token cannot be nil\")\n\t}\n\n\treturn \u0026fnTeller{\n\t\taccountFn: nil,\n\t\tToken:     tok,\n\t}\n}\n\n// Permanently acts as the calling realm (verified via IsCurrent).\nfunc (tok *Token) RealmTeller(_ int, rlm realm) Teller {\n\tif tok == nil {\n\t\tpanic(\"Token cannot be nil\")\n\t}\n\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrSpoofedRealm)\n\t}\n\n\tcaller := rlm.Address()\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, _ realm) address {\n\t\t\treturn caller\n\t\t},\n\t\tToken: tok,\n\t}\n}\n\n// Like RealmTeller but acts as a sub-account derived from slug.\nfunc (tok *Token) RealmSubTeller(_ int, rlm realm, slug string) Teller {\n\tif tok == nil {\n\t\tpanic(\"Token cannot be nil\")\n\t}\n\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrSpoofedRealm)\n\t}\n\n\taccount := accountSlugAddr(rlm.Address(), slug)\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, _ realm) address {\n\t\t\treturn account\n\t\t},\n\t\tToken: tok,\n\t}\n}\n\n// Admin-grade: issuer-only (holds the PrivateLedger). Panics on invalid addr to close the empty-sentinel hole.\nfunc (led *PrivateLedger) ImpersonateTeller(addr address) Teller {\n\tif led == nil {\n\t\tpanic(\"Ledger cannot be nil\")\n\t}\n\n\tif !addr.IsValid() {\n\t\tpanic(ErrInvalidAddress)\n\t}\n\n\treturn \u0026fnTeller{\n\t\taccountFn: func(_ int, _ realm) address {\n\t\t\treturn addr\n\t\t},\n\t\tToken: led.token,\n\t}\n}\n\n// guardHome confines a frame-relative teller to the token's own realm.\n// Construction privacy stops a foreign realm from minting one; this stops a\n// minted one from travelling, which is what happens when a realm legally builds\n// a teller and then exports the value.\n//\n// The check is on the invoking realm's path alone — deliberately NOT on whether\n// the resolved actor is an end user. Keying on the actor only blocks the case\n// where the debited party is the signing user, and leaves two doors open: a\n// realm can be charged by a realm it calls, and TransferFrom resolves the\n// *spender* from the frame, so a realm reached from an honest hub spends that\n// hub's approvals against any owner who granted one. Both are the same defect\n// as the original one level up — frame-relative resolution means whoever you\n// call can act as you — and neither is reachable once the teller only works at\n// home.\n//\n// The host is compared after stripping any \"#subpath\" synthesized by realm.Sub,\n// so the token's own sub-realms are not falsely rejected.\n//\n// A foreign realm that needs to move a user's tokens uses the ordinary route:\n// the owner Approves it, and it spends as itself through RealmTeller, which is\n// eagerly bound to its own address and approval-gated.\n//\n// The leading int keeps this a plain method.\nfunc (ft *fnTeller) guardHome(_ int, rlm realm) error {\n\tif !ft.homeGuard {\n\t\treturn nil\n\t}\n\n\thost, _, _ := chain.SplitPkgSubPath(rlm.PkgPath())\n\tif host != ft.Token.origRealm {\n\t\treturn ErrForeignCallerTeller\n\t}\n\n\treturn nil\n}\n\nfunc (ft *fnTeller) Approve(_ int, rlm realm, to address, tid TokenID) error {\n\tif ft.accountFn == nil {\n\t\treturn ErrReadonly\n\t}\n\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\n\tif err := ft.guardHome(0, rlm); err != nil {\n\t\treturn err\n\t}\n\n\tcaller := ft.accountFn(0, rlm)\n\n\treturn ft.Token.ledger.Approve(caller, to, tid)\n}\n\nfunc (ft *fnTeller) SetApprovalForAll(_ int, rlm realm, operator address, approved bool) error {\n\tif ft.accountFn == nil {\n\t\treturn ErrReadonly\n\t}\n\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\n\tif err := ft.guardHome(0, rlm); err != nil {\n\t\treturn err\n\t}\n\n\tcaller := ft.accountFn(0, rlm)\n\n\treturn ft.Token.ledger.SetApprovalForAll(caller, operator, approved)\n}\n\nfunc (ft *fnTeller) TransferFrom(_ int, rlm realm, from, to address, tid TokenID) error {\n\tif ft.accountFn == nil {\n\t\treturn ErrReadonly\n\t}\n\n\tif !rlm.IsCurrent() {\n\t\treturn ErrSpoofedRealm\n\t}\n\n\tif err := ft.guardHome(0, rlm); err != nil {\n\t\treturn err\n\t}\n\n\tspender := ft.accountFn(0, rlm)\n\n\treturn ft.Token.ledger.TransferFrom(spender, from, to, tid)\n}\n\nfunc accountSlugAddr(addr address, slug string) address {\n\tif slug == \"\" {\n\t\treturn addr\n\t}\n\n\tkey := addr.String() + \"/\" + slug\n\n\treturn chain.PackageAddress(key)\n}\n"},{"name":"token.gno","body":"package grc721\n\nimport (\n\t\"chain\"\n\t\"math/overflow\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewToken creates a core token and its ledger.\n// rlm must be the caller's own captured cur (IsCurrent); its PkgPath becomes the unforgeable origRealm.\n//\n// Every successful call emits a NewToken event carrying the resulting Token.ID().\n// Because Token's fields are unexported, NewToken is the only way a Token can come\n// into existence, so this event makes token creation fully observable: an indexer\n// that sees the same Token.ID() announced twice knows the realm built two\n// independent ledgers behind one identifier, and that every later\n// Mint/Burn/Transfer/Approval carrying that id is ambiguous. Such a realm is\n// emitting untrustworthy events and should be flagged or ignored wholesale.\nfunc NewToken(name, symbol string, id seqid.ID, rlm realm) (*Token, *PrivateLedger) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrSpoofedRealm)\n\t}\n\n\tpkgPath := rlm.PkgPath()\n\tif pkgPath == \"\" {\n\t\tpanic(ErrNotRealm)\n\t}\n\n\tif !validName(name) {\n\t\tpanic(ErrInvalidName)\n\t}\n\n\tif !validSymbol(symbol) {\n\t\tpanic(ErrInvalidSymbol)\n\t}\n\n\t// origRealm is the host path, with any \"#subpath\" synthesized by realm.Sub\n\t// stripped. guardHome strips the invoking path the same way, so a token\n\t// created from a sub frame is not locked out of its own host realm, and a\n\t// host's sub-realms are not falsely rejected. Token.ID() keeps the raw\n\t// pkgPath, so identities and the NewToken event are unaffected.\n\torigRealm, _, _ := chain.SplitPkgSubPath(pkgPath)\n\n\tledger := \u0026PrivateLedger{}\n\ttoken := \u0026Token{\n\t\tid:        pkgPath + \".\" + symbol + \".\" + id.String(),\n\t\tname:      name,\n\t\tsymbol:    symbol,\n\t\tledger:    ledger,\n\t\torigRealm: origRealm,\n\t}\n\tledger.token = token\n\n\tchain.Emit(\n\t\tNewTokenEvent,\n\t\t\"token\", token.id,\n\t\t\"name\", name,\n\t\t\"symbol\", symbol,\n\t)\n\n\treturn token, ledger\n}\n\nfunc validName(name string) bool {\n\tif name == \"\" || len(name) \u003e MaxNameLen {\n\t\treturn false\n\t}\n\n\tfor _, c := range name {\n\t\tif c \u003c 0x20 || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc validSymbol(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxSymbolLen {\n\t\treturn false\n\t}\n\n\tfor _, c := range s {\n\t\tif !isAlnum(c) \u0026\u0026 c != '_' \u0026\u0026 c != '-' {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc isAlnum(c rune) bool {\n\treturn (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9')\n}\n\nfunc (tok *Token) GetName() string { return tok.name }\n\nfunc (tok *Token) GetSymbol() string { return tok.symbol }\n\nfunc (tok *Token) ID() string { return tok.id }\n\nfunc (tok *Token) TotalSupply() int64 { return tok.ledger.totalSupply }\n\nfunc (tok *Token) KnownAccounts() int { return tok.ledger.balances.Size() }\n\n// EIP-721: balanceOf throws for queries about the zero address,\n// since NFTs assigned to it are considered invalid.\nfunc (tok *Token) BalanceOf(addr address) (int64, error) {\n\tif !addr.IsValid() {\n\t\treturn 0, ErrInvalidAddress\n\t}\n\n\treturn tok.ledger.balanceOf(addr), nil\n}\n\nfunc (tok *Token) OwnerOf(tid TokenID) (address, error) { return tok.ledger.ownerOf(tid) }\n\n// EIP-721: getApproved throws for a token that is not a valid NFT, so a missing\n// token is ErrInvalidTokenId and a live but unapproved one is ErrTokenIdNotApproved.\nfunc (tok *Token) GetApproved(tid TokenID) (address, error) {\n\tif !tok.ledger.exists(tid) {\n\t\treturn zeroAddress, ErrInvalidTokenId\n\t}\n\n\taddr := tok.ledger.tokenApprovals.Get(tid.String())\n\tif addr == nil {\n\t\treturn zeroAddress, ErrTokenIdNotApproved\n\t}\n\n\treturn addr.(address), nil\n}\n\nfunc (tok *Token) IsApprovedForAll(owner, operator address) bool {\n\treturn tok.ledger.isApprovedForAll(owner, operator)\n}\n\nfunc (tok *Token) RenderHome() string {\n\tstr := \"\"\n\tstr += ufmt.Sprintf(\"# %s ($%s)\\n\\n\", tok.name, tok.symbol)\n\tstr += ufmt.Sprintf(\"* **Total supply**: %d\\n\", tok.ledger.totalSupply)\n\tstr += ufmt.Sprintf(\"* **Known accounts**: %d\\n\", tok.KnownAccounts())\n\n\treturn str\n}\n\n// RegisterExtension attaches an issuer-supplied hook set. Issuer-only (holds the\n// PrivateLedger), which keeps the surface from being attacker-attachable — but the\n// attachment is still a privilege: per the Extension doc, an attached hook can veto\n// transfers (a panic aborts the transaction before the Transfer event is emitted) and\n// adds gas to every movement.\n// One extension per kind; a second registration of an attached kind panics.\nfunc (led *PrivateLedger) RegisterExtension(ext Extension) {\n\tif ext == nil {\n\t\tpanic(\"grc721: nil extension\")\n\t}\n\n\tkind := ext.ExtensionKind()\n\tfor _, e := range led.extensions {\n\t\tif e.ExtensionKind() == kind {\n\t\t\tpanic(\"grc721: extension kind already registered: \" + kind)\n\t\t}\n\t}\n\n\tled.extensions = append(led.extensions, ext)\n}\n\nfunc (led *PrivateLedger) ReadToken() *Token { return led.token }\n\nfunc (led *PrivateLedger) Mint(to address, tid TokenID) error {\n\tif !to.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\tif tid == \"\" {\n\t\treturn ErrInvalidTokenId\n\t}\n\n\tif led.exists(tid) {\n\t\treturn ErrTokenIdAlreadyExists\n\t}\n\n\tled.balances.Set(to.String(), overflow.Add64p(led.balanceOf(to), 1))\n\tled.owners.Set(tid.String(), to)\n\tled.totalSupply = overflow.Add64p(led.totalSupply, 1)\n\n\tfor _, ext := range led.extensions {\n\t\text.OnMint(to, tid)\n\t}\n\n\t// Mint emits Transfer from the empty address (EIP-721); indexers reconstruct ownership from Transfer alone.\n\tchain.Emit(\n\t\tTransferEvent,\n\t\t\"token\", led.token.id,\n\t\t\"from\", \"\",\n\t\t\"to\", to.String(),\n\t\t\"tokenId\", tid.String(),\n\t)\n\n\treturn nil\n}\n\n// Fans OnBurn out to every extension so per-token state cannot resurface if tid is re-minted.\nfunc (led *PrivateLedger) Burn(tid TokenID) error {\n\towner, err := led.ownerOf(tid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttidStr := tid.String()\n\tled.tokenApprovals.Remove(tidStr)\n\tled.setBalance(owner, overflow.Sub64p(led.balanceOf(owner), 1))\n\tled.owners.Remove(tidStr)\n\tled.totalSupply = overflow.Sub64p(led.totalSupply, 1)\n\n\tfor _, ext := range led.extensions {\n\t\text.OnBurn(tid)\n\t}\n\n\t// Burn emits Transfer to the empty address (EIP-721).\n\tchain.Emit(\n\t\tTransferEvent,\n\t\t\"token\", led.token.id,\n\t\t\"from\", owner.String(),\n\t\t\"to\", \"\",\n\t\t\"tokenId\", tidStr,\n\t)\n\n\treturn nil\n}\n\n// spender must own or be approved for tid; callers derive it from a trusted per-frame identity.\nfunc (led *PrivateLedger) TransferFrom(spender, from, to address, tid TokenID) error {\n\tif !led.isApprovedOrOwner(spender, tid) {\n\t\treturn ErrCallerIsNotOwnerOrApproved\n\t}\n\n\treturn led.transfer(from, to, tid)\n}\n\n// caller must own tid or be an approved operator of the owner.\n// EIP-721: approving the zero address clears (revokes) any single-token approval.\nfunc (led *PrivateLedger) Approve(caller, to address, tid TokenID) error {\n\trevoke := to == zeroAddress\n\tif !revoke \u0026\u0026 !to.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\towner, err := led.ownerOf(tid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif owner == to {\n\t\treturn ErrApprovalToCurrentOwner\n\t}\n\n\tif caller != owner \u0026\u0026 !led.isApprovedForAll(owner, caller) {\n\t\treturn ErrCallerIsNotOwnerOrApproved\n\t}\n\n\tif revoke {\n\t\tled.tokenApprovals.Remove(tid.String())\n\t} else {\n\t\tled.tokenApprovals.Set(tid.String(), to)\n\t}\n\n\tchain.Emit(\n\t\tApprovalEvent,\n\t\t\"token\", led.token.id,\n\t\t\"owner\", owner.String(),\n\t\t\"to\", to.String(), // empty for a revoke\n\t\t\"tokenId\", tid.String(),\n\t)\n\n\treturn nil\n}\n\nfunc (led *PrivateLedger) SetApprovalForAll(owner, operator address, approved bool) error {\n\tif !owner.IsValid() || !operator.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\tif owner == operator {\n\t\treturn ErrApprovalToCurrentOwner\n\t}\n\n\tkey := operatorKey(owner, operator)\n\tif approved {\n\t\tled.operatorApprovals.Set(key, approved)\n\t} else {\n\t\tled.operatorApprovals.Remove(key)\n\t}\n\n\tchain.Emit(\n\t\tApprovalForAllEvent,\n\t\t\"token\", led.token.id,\n\t\t\"owner\", owner.String(),\n\t\t\"to\", operator.String(),\n\t\t\"approved\", strconv.FormatBool(approved),\n\t)\n\n\treturn nil\n}\n\nfunc (led *PrivateLedger) transfer(from, to address, tid TokenID) error {\n\tif !from.IsValid() || !to.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\tif from == to {\n\t\treturn ErrCannotTransferToSelf\n\t}\n\n\towner, err := led.ownerOf(tid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif owner != from {\n\t\treturn ErrTransferFromIncorrectOwner\n\t}\n\n\ttidStr := tid.String()\n\tled.tokenApprovals.Remove(tidStr)\n\tled.setBalance(from, overflow.Sub64p(led.balanceOf(from), 1))\n\tled.setBalance(to, overflow.Add64p(led.balanceOf(to), 1))\n\tled.owners.Set(tidStr, to)\n\n\tfor _, ext := range led.extensions {\n\t\text.OnTransfer(from, to, tid)\n\t}\n\n\tchain.Emit(\n\t\tTransferEvent,\n\t\t\"token\", led.token.id,\n\t\t\"from\", from.String(),\n\t\t\"to\", to.String(),\n\t\t\"tokenId\", tidStr,\n\t)\n\n\treturn nil\n}\n\nfunc (led *PrivateLedger) ownerOf(tid TokenID) (address, error) {\n\towner := led.owners.Get(tid.String())\n\tif owner == nil {\n\t\treturn zeroAddress, ErrInvalidTokenId\n\t}\n\n\treturn owner.(address), nil\n}\n\nfunc (led *PrivateLedger) balanceOf(addr address) int64 {\n\tbalance := led.balances.Get(addr.String())\n\tif balance == nil {\n\t\treturn 0\n\t}\n\n\treturn balance.(int64)\n}\n\nfunc (led *PrivateLedger) setBalance(addr address, balance int64) {\n\tif balance == 0 {\n\t\tled.balances.Remove(addr.String())\n\n\t\treturn\n\t}\n\n\tled.balances.Set(addr.String(), balance)\n}\n\nfunc (led *PrivateLedger) isApprovedForAll(owner, operator address) bool {\n\tapproved := led.operatorApprovals.Get(operatorKey(owner, operator))\n\tif approved == nil {\n\t\treturn false\n\t}\n\n\treturn approved.(bool)\n}\n\nfunc (led *PrivateLedger) isApprovedOrOwner(addr address, tid TokenID) bool {\n\towner := led.owners.Get(tid.String())\n\tif owner == nil {\n\t\treturn false\n\t}\n\n\townerAddr := owner.(address)\n\tif addr == ownerAddr || led.isApprovedForAll(ownerAddr, addr) {\n\t\treturn true\n\t}\n\n\tapproved := led.tokenApprovals.Get(tid.String())\n\n\treturn approved != nil \u0026\u0026 approved.(address) == addr\n}\n\nfunc (led *PrivateLedger) exists(tid TokenID) bool {\n\treturn led.owners.Has(tid.String())\n}\n\nfunc operatorKey(owner, operator address) string {\n\treturn owner.String() + \":\" + operator.String()\n}\n"},{"name":"types.gno","body":"package grc721\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\ntype TokenID string\n\nfunc (t TokenID) String() string { return string(t) }\n\n// A Teller is a capability that acts as some account whenever it writes.\n// IsCanonicalTeller confirms a Teller was minted by this package — an embedding\n// forgery fails the check — but it does NOT reveal which account the Teller acts\n// as: a caller-scoped CallerTeller and the admin-grade ImpersonateTeller (which\n// acts as an arbitrary address) are both canonical. So it is an authenticity\n// check on the implementation, not an authorization guard on the acting account;\n// a caller accepting a Teller from outside must still establish, out of band, what\n// account that Teller is entitled to act as.\n// safeTransferFrom is omitted: EIP-721's receiver check needs a registry, and aliasing it would imply false safety.\ntype Teller interface {\n\tGetName() string\n\tGetSymbol() string\n\tID() string\n\tTotalSupply() int64\n\tBalanceOf(owner address) (int64, error)\n\tOwnerOf(tid TokenID) (address, error)\n\tGetApproved(tid TokenID) (address, error)\n\tIsApprovedForAll(owner, operator address) bool\n\n\tApprove(_ int, rlm realm, to address, tid TokenID) error\n\tSetApprovalForAll(_ int, rlm realm, operator address, approved bool) error\n\tTransferFrom(_ int, rlm realm, from, to address, tid TokenID) error\n}\n\n// Extension hooks fire on every mint/transfer/burn. This is a trust grant to the\n// issuer, not an EIP-721 feature: only the issuer can attach one (RegisterExtension\n// holds the PrivateLedger), but once attached the hook runs arbitrary issuer code on\n// every movement, a panic in OnMint/OnTransfer/OnBurn aborts the transaction before\n// the movement is announced — an implicit veto over transfers — and gas scales\n// linearly with the extension count. Hooks run after the ledger write so they observe\n// the post-movement state; only a caller that recovers from the panic keeps that write.\n// Holders of a collection's tokens are therefore trusting the issuer not to freeze or\n// tax movement through this surface. Hooks take no rlm params (they cannot capture cur);\n// attach only via RegisterExtension.\ntype Extension interface {\n\tExtensionKind() string // unique; duplicates rejected at register\n\tOnMint(to address, tid TokenID)\n\tOnTransfer(from, to address, tid TokenID)\n\tOnBurn(tid TokenID)\n}\n\ntype ExtensionView interface {\n\tExtensionKind() string\n\tTokenID() string // core Token.ID\n}\n\ntype Token struct {\n\tid     string // raw creation pkgpath + \".\" + symbol + \".\" + id\n\tname   string\n\tsymbol string\n\tledger *PrivateLedger\n\t// origRealm is the PkgPath of the realm that created the token, captured\n\t// unforgeably in NewToken. A frame-relative teller only works there.\n\torigRealm string\n}\n\ntype PrivateLedger struct {\n\ttoken             *Token\n\ttotalSupply       int64\n\towners            avl.Tree // TokenID -\u003e owner address\n\tbalances          avl.Tree // owner address -\u003e int64\n\ttokenApprovals    avl.Tree // TokenID -\u003e approved address\n\toperatorApprovals avl.Tree // \"owner:operator\" -\u003e bool\n\textensions        []Extension\n}\n\nvar (\n\tErrInvalidTokenId             = errors.New(\"invalid token id\")\n\tErrInvalidAddress             = errors.New(\"invalid address\")\n\tErrTokenIdNotApproved         = errors.New(\"token id not approved for anyone\")\n\tErrApprovalToCurrentOwner     = errors.New(\"approval to current owner\")\n\tErrCallerIsNotOwner           = errors.New(\"caller is not token owner\")\n\tErrCannotTransferToSelf       = errors.New(\"cannot send transfer to self\")\n\tErrTransferFromIncorrectOwner = errors.New(\"transfer from incorrect owner\")\n\tErrCallerIsNotOwnerOrApproved = errors.New(\"caller is not token owner or approved\")\n\tErrTokenIdAlreadyExists       = errors.New(\"token id already exists\")\n\tErrReadonly                   = errors.New(\"teller is readonly\")\n\tErrSpoofedRealm               = errors.New(\"rlm does not match the current crossing frame\")\n\tErrForeignCallerTeller        = errors.New(\"frame-relative teller used outside the token's realm\")\n\tErrNotRealm                   = errors.New(\"rlm must be a realm (got EOA/origin)\")\n\tErrInvalidName                = errors.New(\"invalid token name (empty, too long, or contains control chars)\")\n\tErrInvalidSymbol              = errors.New(\"invalid token symbol (empty, too long, or contains chars outside [A-Za-z0-9_-])\")\n)\n\n// Symbol charset matches grc20reg slug (embedded in Token.ID / events).\nconst (\n\tMaxNameLen   = 64\n\tMaxSymbolLen = 11\n)\n\nconst (\n\t// NewToken announces every token creation; see NewToken for why it is a\n\t// complete provenance signal.\n\tNewTokenEvent = \"NewToken\"\n\t// Mint emits from empty addr; burn emits to empty addr (EIP-721).\n\tTransferEvent       = \"Transfer\"\n\tApprovalEvent       = \"Approval\"\n\tApprovalForAllEvent = \"ApprovalForAll\"\n)\n\nvar zeroAddress = address(\"\")\n\ntype fnTeller struct {\n\taccountFn func(_ int, rlm realm) address\n\t// homeGuard marks a frame-relative teller, whose writes are confined to\n\t// the token's own realm. See fnTeller.guardHome.\n\thomeGuard bool\n\t*Token\n}\n\nvar _ Teller = (*fnTeller)(nil)\n\n// IsCanonicalTeller reports whether t was minted by this package, rejecting Tellers\n// forged by embedding *fnTeller in a wrapper. It does NOT discriminate by capability\n// grade: CallerTeller, ReadonlyTeller, RealmTeller, RealmSubTeller and the admin-grade\n// ImpersonateTeller all return true. Do not treat a true result as proof that a Teller\n// is a caller-scoped capability — establish the acting account separately.\nfunc IsCanonicalTeller(t Teller) bool {\n\t_, ok := t.(*fnTeller)\n\treturn ok\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"enumerable","path":"gno.land/p/nt/grc721/enumerable/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/grc721/enumerable/v0\"\ngno = \"0.9\"\n"},{"name":"token.gno","body":"package enumerable\n\nimport (\n\t\"gno.land/p/nt/grc721/v0\"\n)\n\nconst Kind = \"enumerable\"\n\n// NewEnumerable attaches an enumerable extension and registers it as a core\n// Extension. Attach it before the first mint so every token is indexed.\nfunc NewEnumerable(coreLedger *grc721.PrivateLedger) (*Enumerable, *Ledger) {\n\tif coreLedger == nil {\n\t\tpanic(\"enumerable: nil core ledger\")\n\t}\n\n\tst := \u0026storage{}\n\tcore := coreLedger.ReadToken()\n\tled := \u0026Ledger{core: core, st: st}\n\tcoreLedger.RegisterExtension(led)\n\n\treturn \u0026Enumerable{core: core, st: st}, led\n}\n\nfunc (e *Enumerable) ExtensionKind() string {\n\treturn Kind\n}\n\nfunc (e *Enumerable) TokenID() string {\n\treturn e.core.ID()\n}\n\nfunc (e *Enumerable) TotalSupply() int64 {\n\treturn int64(len(e.st.allTokens))\n}\n\nfunc (e *Enumerable) TokenByIndex(index int64) (grc721.TokenID, error) {\n\tif index \u003c 0 || index \u003e= int64(len(e.st.allTokens)) {\n\t\treturn \"\", ErrIndexOutOfRange\n\t}\n\n\treturn e.st.allTokens[index], nil\n}\n\nfunc (e *Enumerable) TokenOfOwnerByIndex(owner address, index int64) (grc721.TokenID, error) {\n\tlist := e.ownedList(owner)\n\tif list == nil || index \u003c 0 || index \u003e= int64(len(list.ids)) {\n\t\treturn \"\", ErrIndexOutOfRange\n\t}\n\n\treturn list.ids[index], nil\n}\n\nfunc (e *Enumerable) ownedList(owner address) *tokenList {\n\tv := e.st.owned.Get(owner.String())\n\tif v == nil {\n\t\treturn nil\n\t}\n\n\treturn v.(*tokenList)\n}\n\nfunc (led *Ledger) ExtensionKind() string { return Kind }\n\nfunc (led *Ledger) OnMint(to address, tid grc721.TokenID) {\n\tled.addToAll(tid)\n\tled.addToOwner(to, tid)\n}\n\nfunc (led *Ledger) OnTransfer(from, to address, tid grc721.TokenID) {\n\tled.removeFromOwner(from, tid)\n\tled.addToOwner(to, tid)\n}\n\nfunc (led *Ledger) OnBurn(tid grc721.TokenID) {\n\tif v := led.st.owner.Get(tid.String()); v != nil {\n\t\tled.removeFromOwner(v.(address), tid)\n\t}\n\n\tled.removeFromAll(tid)\n}\n\nfunc (led *Ledger) addToAll(tid grc721.TokenID) {\n\tled.st.allIndex.Set(tid.String(), len(led.st.allTokens))\n\tled.st.allTokens = append(led.st.allTokens, tid)\n}\n\n// Swap-and-pop: move the last id into the freed slot, then truncate.\nfunc (led *Ledger) removeFromAll(tid grc721.TokenID) {\n\ttidStr := tid.String()\n\n\tv := led.st.allIndex.Get(tidStr)\n\tif v == nil {\n\t\treturn\n\t}\n\n\tidx := v.(int)\n\n\tlast := len(led.st.allTokens) - 1\n\tif idx != last {\n\t\tmoved := led.st.allTokens[last]\n\t\tled.st.allTokens[idx] = moved\n\t\tled.st.allIndex.Set(moved.String(), idx)\n\t}\n\n\tled.st.allTokens = led.st.allTokens[:last]\n\n\tled.st.allIndex.Remove(tidStr)\n}\n\nfunc (led *Ledger) addToOwner(owner address, tid grc721.TokenID) {\n\townerStr := owner.String()\n\n\tvar list *tokenList\n\tif v := led.st.owned.Get(ownerStr); v != nil {\n\t\tlist = v.(*tokenList)\n\t} else {\n\t\tlist = \u0026tokenList{}\n\t\tled.st.owned.Set(ownerStr, list)\n\t}\n\n\tled.st.ownedIndex.Set(tid.String(), len(list.ids))\n\tlist.ids = append(list.ids, tid)\n\tled.st.owner.Set(tid.String(), owner)\n}\n\n// Swap-and-pop within the owner list; drops the owner entry when it empties.\nfunc (led *Ledger) removeFromOwner(owner address, tid grc721.TokenID) {\n\townerStr := owner.String()\n\n\tv := led.st.owned.Get(ownerStr)\n\tif v == nil {\n\t\treturn\n\t}\n\n\tlist := v.(*tokenList)\n\ttidStr := tid.String()\n\n\tiv := led.st.ownedIndex.Get(tidStr)\n\tif iv == nil {\n\t\treturn\n\t}\n\n\tidx := iv.(int)\n\n\tlast := len(list.ids) - 1\n\tif idx != last {\n\t\tmoved := list.ids[last]\n\t\tlist.ids[idx] = moved\n\t\tled.st.ownedIndex.Set(moved.String(), idx)\n\t}\n\n\tlist.ids = list.ids[:last]\n\n\tled.st.ownedIndex.Remove(tidStr)\n\n\tif len(list.ids) == 0 {\n\t\tled.st.owned.Remove(ownerStr)\n\t}\n\n\tled.st.owner.Remove(tidStr)\n}\n"},{"name":"types.gno","body":"// Package enumerable is a stackable GRC721 extension implementing\n// EIP-721Enumerable. Attach it via NewEnumerable before the first mint.\npackage enumerable\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc721/v0\"\n)\n\nvar ErrIndexOutOfRange = errors.New(\"index out of range\")\n\n// Stored by pointer so in-place swap-and-pop updates persist.\ntype tokenList struct {\n\tids []grc721.TokenID\n}\n\ntype storage struct {\n\tallTokens  []grc721.TokenID\n\tallIndex   avl.Tree // grc721.TokenID -\u003e int (position in allTokens)\n\towned      avl.Tree // owner address -\u003e *tokenList\n\townedIndex avl.Tree // grc721.TokenID -\u003e int (position within its owner list)\n\towner      avl.Tree // grc721.TokenID -\u003e owner address\n}\n\ntype Enumerable struct {\n\tcore *grc721.Token\n\tst   *storage\n}\n\ntype Ledger struct {\n\tcore *grc721.Token\n\tst   *storage\n}\n\nvar _ grc721.Extension = (*Ledger)(nil)\n\nvar _ grc721.ExtensionView = (*Enumerable)(nil)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"curchain_b","path":"gno.land/r/tests/vm/curchain_b","files":[{"name":"curchain_b.gno","body":"// Package curchain_b is the terminal hop in the multi-level cross-call\n// chain test helpers. It prints the full captured chain visible from this\n// realm, and asserts parity with unsafe.CurrentRealm() /\n// unsafe.PreviousRealm() at the cross-callee position.\npackage curchain_b\n\nimport (\n\t\"chain/runtime/unsafe\"\n)\n\n// B is a crossing function that prints the captured chain reached via\n// .Previous() walks and asserts parity with unsafe.CurrentRealm() /\n// unsafe.PreviousRealm() at the cross-callee position. The chain-root\n// case is covered separately by zrealm_cur_parity.\n//\n// Chain layout for callsite main -\u003e curchain_a.A -\u003e curchain_b.B:\n//\n//\tcur                  = B\n//\tcur.Previous()       = A\n//\tcur.Previous()^2     = main\n//\tcur.Previous()^3     = EOA origin (PkgPath() == \"\")\n//\tcur.Previous()^4     = panics (origin has no further previous)\nfunc B(cur realm) {\n\tprintln(\"B cur.PkgPath:\", cur.PkgPath())\n\tp1 := cur.Previous()\n\tprintln(\"B Previous().PkgPath:\", p1.PkgPath())\n\tp2 := p1.Previous()\n\tprintln(\"B Previous().Previous().PkgPath:\", p2.PkgPath())\n\tp3 := p2.Previous()\n\tprintln(\"B Previous()^3 PkgPath empty (EOA origin):\", p3.PkgPath() == \"\")\n\tfunc() {\n\t\tdefer func() {\n\t\t\tr := recover()\n\t\t\tprintln(\"B Previous()^4 panics past origin:\", r != nil)\n\t\t}()\n\t\t_ = p3.Previous()\n\t}()\n\n\t// Parity at cross-callee position: cur agrees with\n\t// unsafe.CurrentRealm(), and cur.Previous() (the caller realm\n\t// A) agrees with unsafe.PreviousRealm().\n\trc := unsafe.CurrentRealm()\n\trp := unsafe.PreviousRealm()\n\tprintln(\"B parity cur==Current:\",\n\t\tstring(cur.Address()) == string(rc.Address()) \u0026\u0026\n\t\t\tcur.PkgPath() == rc.PkgPath())\n\tprintln(\"B parity prev==Previous:\",\n\t\tstring(p1.Address()) == string(rp.Address()) \u0026\u0026\n\t\t\tp1.PkgPath() == rp.PkgPath())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/curchain_b\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"curchain_a","path":"gno.land/r/tests/vm/curchain_a","files":[{"name":"curchain_a.gno","body":"// Package curchain_a is a test helper for multi-level cross-call chain tests.\n// A is the middle hop: when called via cross, it cross-calls into curchain_b.\npackage curchain_a\n\nimport (\n\t\"gno.land/r/tests/vm/curchain_b\"\n)\n\n// A is a crossing function that cross-calls curchain_b.B(cross).\n// Use from a filetest as: curchain_a.A(cross) to set up a 3-level chain\n// caller → A → B with the filetest's main as the chain root.\nfunc A(cur realm) {\n\tprintln(\"A cur.PkgPath:\", cur.PkgPath())\n\tprintln(\"A prev.PkgPath:\", cur.Previous().PkgPath())\n\tcurchain_b.B(cross(cur))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/curchain_a\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"test20","path":"gno.land/r/tests/vm/test20","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/test20\"\ngno = \"0.9\"\n"},{"name":"test20.gno","body":"// Package test20 implements a deliberately insecure ERC20 token for testing purposes.\n// The Test20 token allows anyone to mint any amount of tokens to any address, making\n// it unsuitable for production use. The primary goal of this package is to facilitate\n// testing and experimentation without any security measures or restrictions.\n//\n//\tWARNING: This token is highly insecure and should not be used in any\n//\t production environment. It is intended solely for testing and\n//\t educational purposes.\npackage test20\n\nimport (\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nvar (\n\tToken         *grc20.Token\n\tPrivateLedger *grc20.PrivateLedger\n)\n\nfunc init(cur realm) {\n\t// test20 only ever creates this one token, so id 0 can't collide.\n\tToken, PrivateLedger = grc20.NewToken(\"Test20\", \"TST\", 4, 0, cur)\n\tgrc20reg.Register(cross(cur), Token, \"\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"variadic","path":"gno.land/r/tests/vm/variadic","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/variadic\"\ngno = \"0.9\"\n"},{"name":"main.gno","body":"package variadic\n\nimport \"strings\"\n\nfunc Echo(cur realm, vals ...string) string {\n\treturn strings.Join(vals, \" \")\n}\n\nfunc Add(cur realm, nums ...int) int {\n\tres := 0\n\n\tfor _, num := range nums {\n\t\tres += num\n\t}\n\n\treturn res\n}\n\nfunc And(cur realm, booleans ...bool) bool {\n\n\tfor _, boolean := range booleans {\n\t\tif !boolean {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"subtests","path":"gno.land/p/demo/tests/subtests/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/subtests/v0\"\ngno = \"0.9\"\n"},{"name":"subtests.gno","body":"package subtests\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n)\n\nfunc GetCurrentRealm() runtime.Realm {\n\treturn unsafe.CurrentRealm()\n}\n\nfunc GetPreviousRealm() runtime.Realm {\n\treturn unsafe.PreviousRealm()\n}\n\nfunc Exec(fn func()) {\n\tfn()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"tests","path":"gno.land/p/demo/tests/v0","files":[{"name":"README.md","body":"Modules here are only useful for file realm tests.\nThey can be safely ignored for other purposes.\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/v0\"\ngno = \"0.9\"\n"},{"name":"tests.gno","body":"package tests\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\tpsubtests \"gno.land/p/demo/tests/subtests/v0\"\n)\n\nconst World = \"world\"\n\nfunc CurrentRealmPath() string {\n\treturn unsafe.CurrentRealm().PkgPath()\n}\n\n//----------------------------------------\n// cross realm test vars\n\ntype TestRealmObject2 struct {\n\tField string\n}\n\nfunc (o2 *TestRealmObject2) Modify() {\n\to2.Field = \"modified\"\n}\n\n// Value-receiver mutator. By Go/Gno semantics this only mutates the\n// method's local copy. Used by readonly-taint filetests to probe\n// whether a receiver carrying the sticky N_Readonly bit propagates\n// the bit onto the method-frame copy.\nfunc (o2 TestRealmObject2) ModifyVal() {\n\to2.Field = \"modified-val\"\n}\n\n// Unexported mutator. Used by the method-expression visibility filetest:\n// `(*tests.TestRealmObject2).clearField` from outside this package must\n// be rejected at preprocess time.\nfunc (o2 *TestRealmObject2) clearField() {\n\to2.Field = \"\"\n}\n\nvar (\n\tsomevalue1 TestRealmObject2\n\tSomeValue2 TestRealmObject2\n\tSomeValue3 *TestRealmObject2\n)\n\nfunc init() {\n\tsomevalue1 = TestRealmObject2{Field: \"init\"}\n\tSomeValue2 = TestRealmObject2{Field: \"init\"}\n\tSomeValue3 = \u0026TestRealmObject2{Field: \"init\"}\n}\n\nfunc ModifyTestRealmObject2a() {\n\tsomevalue1.Field = \"modified\"\n}\n\nfunc ModifyTestRealmObject2b() {\n\tSomeValue2.Field = \"modified\"\n}\n\nfunc ModifyTestRealmObject2c() {\n\tSomeValue3.Field = \"modified\"\n}\n\nfunc GetPreviousRealm() runtime.Realm {\n\treturn unsafe.PreviousRealm()\n}\n\nfunc GetPSubtestsPreviousRealm() runtime.Realm {\n\treturn psubtests.GetPreviousRealm()\n}\n\n// Warning: unsafe pattern.\nfunc Exec(fn func()) {\n\tfn()\n}\n\n// ExecRlm mirrors Exec but threads the caller's rlm into the callback\n// so the callback can use `cross(rlm)` instead of bare `cross`.\nfunc ExecRlm(_ int, rlm realm, fn func(_ int, rlm realm)) {\n\tfn(0, rlm)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"boards","path":"gno.land/p/gnoland/boards/v0","files":[{"name":"board.gno","body":"package boards\n\nimport \"time\"\n\n// Board defines a type for boards.\ntype Board struct {\n\t// ID is the unique identifier of the board.\n\tID ID\n\n\t// Name is the current name of the board.\n\tName string\n\n\t// Aliases contains a list of alternative names for the board.\n\tAliases []string\n\n\t// Readonly indicates that the board is readonly.\n\tReadonly bool\n\n\t// Threads contains board threads.\n\tThreads PostStorage\n\n\t// ThreadsSequence generates sequential ID for new threads.\n\tThreadsSequence IdentifierGenerator\n\n\t// Permissions enables support for permissioned boards.\n\t// This type of boards allows managing members with roles and permissions.\n\t// It also enables the implementation of permissioned execution of board related features.\n\tPermissions Permissions\n\n\t// Creator is the account address that created the board.\n\tCreator address\n\n\t// Meta allows storing board metadata.\n\tMeta any\n\n\t// CreatedAt is the board's creation time.\n\tCreatedAt time.Time\n\n\t// UpdatedAt is the board's update time.\n\tUpdatedAt time.Time\n}\n\n// New creates a new basic non permissioned board.\nfunc New(id ID) *Board {\n\treturn \u0026Board{\n\t\tID:              id,\n\t\tThreads:         NewPostStorage(),\n\t\tThreadsSequence: NewIdentifierGenerator(),\n\t\tCreatedAt:       time.Now(),\n\t}\n}\n\n// SetID sets board ID value.\nfunc (board *Board) SetID(v ID) {\n\tboard.ID = v\n}\n\n// SetName sets name value.\nfunc (board *Board) SetName(v string) {\n\tboard.Name = v\n}\n\n// SetAliases sets board name aliases.\nfunc (board *Board) SetAliases(v []string) {\n\tboard.Aliases = v\n}\n\n// SetReadonly sets readonly value.\nfunc (board *Board) SetReadonly(v bool) {\n\tboard.Readonly = v\n}\n\n// SetThreadStorage sets the storage where board threads are stored.\nfunc (board *Board) SetThreadStorage(v PostStorage) {\n\tboard.Threads = v\n}\n\n// SetThreadsSequence sets the sequential thread ID generator.\nfunc (board *Board) SetThreadsSequence(v IdentifierGenerator) {\n\tboard.ThreadsSequence = v\n}\n\n// SetPermissions sets permissions value.\nfunc (board *Board) SetPermissions(v Permissions) {\n\tboard.Permissions = v\n}\n\n// SetCreator sets the address of the account that created the board.\nfunc (board *Board) SetCreator(v address) {\n\tboard.Creator = v\n}\n\n// SetCreatedAt sets the time when board was created.\nfunc (board *Board) SetCreatedAt(v time.Time) {\n\tboard.CreatedAt = v\n}\n\n// SetUpdatedAt sets the time when a board value was updated.\nfunc (board *Board) SetUpdatedAt(v time.Time) {\n\tboard.UpdatedAt = v\n}\n\n// SetMeta sets board metadata.\nfunc (board *Board) SetMeta(v any) {\n\tboard.Meta = v\n}\n"},{"name":"flag_storage.gno","body":"package boards\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype (\n\t// Flag defines a type for post flags\n\tFlag struct {\n\t\t// User is the user that flagged the post.\n\t\tUser address\n\n\t\t// Reason is the reason that describes why post is flagged.\n\t\tReason string\n\t}\n\n\t// FlagIterFn defines a function type to iterate post flags.\n\tFlagIterFn func(Flag) bool\n\n\t// FlagStorage defines an interface for storing posts flagging information.\n\tFlagStorage interface {\n\t\t// Exists checks if a flag from a user exists\n\t\tExists(address) bool\n\n\t\t// Add adds a new flag from a user.\n\t\tAdd(Flag) error\n\n\t\t// Remove removes a user flag.\n\t\tRemove(address) (removed bool)\n\n\t\t// Size returns the number of flags in the storage.\n\t\tSize() int\n\n\t\t// Iterate iterates post flags.\n\t\t// To reverse iterate flags use a negative count.\n\t\t// If the callback returns true, the iteration is stopped.\n\t\tIterate(start, count int, fn FlagIterFn) bool\n\t}\n)\n\n// NewFlagStorage creates a new storage for post flags.\n// The new storage uses an AVL tree to store flagging info.\nfunc NewFlagStorage() FlagStorage {\n\treturn \u0026flagStorage{bptree.NewBPTree32()}\n}\n\ntype flagStorage struct {\n\tflags *bptree.BPTree // address -\u003e string(reason)\n}\n\n// Exists checks if a flag from a user exists\nfunc (s flagStorage) Exists(addr address) bool {\n\treturn s.flags.Has(addr.String())\n}\n\n// Add adds a new flag from a user.\n// It fails if a flag from the same user exists.\nfunc (s *flagStorage) Add(f Flag) error {\n\tif !f.User.IsValid() {\n\t\treturn ufmt.Errorf(\"post flagging error, invalid user address: %s\", f.User)\n\t}\n\n\tk := f.User.String()\n\tif s.flags.Has(k) {\n\t\treturn ufmt.Errorf(\"flag from user already exists: %s\", f.User)\n\t}\n\n\ts.flags.Set(k, strings.TrimSpace(f.Reason))\n\treturn nil\n}\n\n// Remove removes a user flag.\nfunc (s *flagStorage) Remove(addr address) bool {\n\t_, removed := s.flags.Remove(addr.String())\n\treturn removed\n}\n\n// Size returns the number of flags in the storage.\nfunc (s flagStorage) Size() int {\n\treturn s.flags.Size()\n}\n\n// Iterate iterates post flags.\n// To reverse iterate flags use a negative count.\n// If the callback returns true, the iteration is stopped.\nfunc (s flagStorage) Iterate(start, count int, fn FlagIterFn) bool {\n\tif count \u003c 0 {\n\t\treturn s.flags.ReverseIterateByOffset(start, -count, func(k string, v any) bool {\n\t\t\treturn fn(Flag{\n\t\t\t\tUser:   address(k),\n\t\t\t\tReason: v.(string),\n\t\t\t})\n\t\t})\n\t}\n\n\treturn s.flags.IterateByOffset(start, count, func(k string, v any) bool {\n\t\treturn fn(Flag{\n\t\t\tUser:   address(k),\n\t\t\tReason: v.(string),\n\t\t})\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/gnoland/boards/v0\"\ngno = \"0.9\"\n"},{"name":"id.gno","body":"package boards\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\nconst paddedStringLen = 10\n\n// ID defines a type for unique identifiers.\ntype ID uint64\n\n// String returns the ID as a string.\nfunc (id ID) String() string {\n\treturn strconv.FormatUint(uint64(id), 10)\n}\n\n// PaddedString returns the ID as a 10 character string padded with zeroes.\n// This value can be used for indexing by ID.\nfunc (id ID) PaddedString() string {\n\ts := id.String()\n\treturn strings.Repeat(\"0\", paddedStringLen-len(s)) + s\n}\n\n// Key returns the ID as a string which can be used to index by ID.\nfunc (id ID) Key() string {\n\treturn seqid.ID(id).String()\n}\n\n// IdentifierGenerator defines an interface for sequential unique identifier generators.\ntype IdentifierGenerator interface {\n\t// Current returns the last generated ID.\n\tLast() ID\n\n\t// Next generates a new ID or panics if increasing ID overflows.\n\tNext() ID\n}\n\n// NewIdentifierGenerator creates a new sequential unique identifier generator.\nfunc NewIdentifierGenerator() IdentifierGenerator {\n\treturn \u0026idGenerator{}\n}\n\ntype idGenerator struct {\n\tlast seqid.ID\n}\n\n// Current returns the last generated ID.\nfunc (g idGenerator) Last() ID {\n\treturn ID(g.last)\n}\n\n// Next generates a new ID or panics if increasing ID overflows.\nfunc (g *idGenerator) Next() ID {\n\treturn ID(g.last.Next())\n}\n"},{"name":"permission_set.gno","body":"package boards\n\n// PermissionSet defines a type to store any number of permissions.\ntype PermissionSet []uint64\n\n// NewPermissionSet creates a new PermissionSet containing the given permissions.\nfunc NewPermissionSet(perms ...Permission) PermissionSet {\n\tif len(perms) == 0 {\n\t\treturn nil\n\t}\n\n\t// Find max permission value to calculate slice size.\n\t// This allows any number of permissions to be assigned in any order.\n\tvar max Permission\n\tfor _, p := range perms {\n\t\tif p \u003e max {\n\t\t\tmax = p\n\t\t}\n\t}\n\n\ts := make(PermissionSet, int(max)/64+1)\n\tfor _, p := range perms {\n\t\t// Calculate the index within the set where the permission should be defined.\n\t\t// Each item in the set can contain 64 permissions, for example:\n\t\t// - Item 0: permissions 0 to 63\n\t\t// - Item 1: permissions 64 to 127\n\t\tidx := int(p) / 64\n\n\t\t// Turn on the bit that matches the permission, ranging from bit 0 to 63\n\t\ts[idx] |= 1 \u003c\u003c (uint(p) % 64)\n\t}\n\treturn s\n}\n\n// Has checks if a permission is in the set.\nfunc (s PermissionSet) Has(p Permission) bool {\n\tidx := int(p) / 64\n\tif idx \u003e= len(s) {\n\t\treturn false\n\t}\n\n\t// Check if the bit for the current permission is on\n\treturn s[idx]\u0026(1\u003c\u003c(uint(p)%64)) != 0\n}\n\n// IsEmpty reports whether the set contains no permissions.\nfunc (s PermissionSet) IsEmpty() bool {\n\tfor _, v := range s {\n\t\tif v != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"},{"name":"permissions.gno","body":"package boards\n\nimport \"strconv\"\n\ntype (\n\t// Role defines the type for user roles.\n\tRole string\n\n\t// Args is a list of generic arguments.\n\tArgs []interface{}\n\n\t// User contains user info.\n\tUser struct {\n\t\tAddress address\n\t\tRoles   []Role\n\t}\n\n\t// UsersIterFn defines a function type to iterate users.\n\tUsersIterFn func(User) bool\n\n\t// Permissions define an interface to for permissioned execution.\n\tPermissions interface {\n\t\t// HasRole checks if a user has a specific role assigned.\n\t\tHasRole(address, Role) bool\n\n\t\t// HasPermission checks if a user has a specific permission.\n\t\tHasPermission(address, Permission) bool\n\n\t\t// WithPermission calls a callback when a user has a specific permission.\n\t\t// It panics on error.\n\t\t//\n\t\t// An inline crossing function call can be used by the implementation if\n\t\t// crossing is required to update its internal state, for example to create\n\t\t// proposals that when approved execute the callback:\n\t\t//\n\t\t//  func(realm) {\n\t\t//    // Update internal realm state\n\t\t//    // ...\n\t\t//  }(cross)\n\t\tWithPermission(address, Permission, Args, func())\n\n\t\t// SetUserRoles adds a new user when it doesn't exist and sets its roles.\n\t\t// Method can also be called to change the roles of an existing user.\n\t\t// It panics on error.\n\t\tSetUserRoles(address, ...Role)\n\n\t\t// RemoveUser removes a user from the permissioner.\n\t\t// It panics on error.\n\t\tRemoveUser(address) (removed bool)\n\n\t\t// HasUser checks if a user exists.\n\t\tHasUser(address) bool\n\n\t\t// UsersCount returns the total number of users the permissioner contains.\n\t\tUsersCount() int\n\n\t\t// IterateUsers iterates permissions' users.\n\t\tIterateUsers(start, count int, fn UsersIterFn) bool\n\t}\n)\n\n// Permission defines the type for permissions.\ntype Permission uint16\n\n// String returns the string representation of a permission value.\nfunc (p Permission) String() string {\n\treturn strconv.FormatUint(uint64(p), 10)\n}\n"},{"name":"post.gno","body":"package boards\n\nimport (\n\t\"strings\"\n\t\"time\"\n)\n\n// Post defines a generic type for posts.\n// A post can be either a thread or a reply.\ntype Post struct {\n\t// ID is the unique identifier of the post.\n\tID ID\n\n\t// ParentID is the ID of the parent post.\n\tParentID ID\n\n\t// ThreadID contains the post ID of the thread where current post is created.\n\t// If current post is a thread it contains post's ID.\n\t// It should be used when current post is a thread or reply.\n\tThreadID ID\n\n\t// OriginalBoardID contains the board ID of the original post when current post is a repost.\n\tOriginalBoardID ID\n\n\t// Board contains the board where post is created.\n\tBoard *Board\n\n\t// Title contains the post's title.\n\tTitle string\n\n\t// Body contains content of the post.\n\tBody string\n\n\t// Hidden indicates that the post is hidden.\n\tHidden bool\n\n\t// Readonly indicates that the post is readonly.\n\tReadonly bool\n\n\t// Replies stores post replies.\n\tReplies PostStorage\n\n\t// Reposts stores reposts of the current post.\n\t// It should be used when post is a thread.\n\tReposts RepostStorage\n\n\t// Flags stores users flags for the current post.\n\tFlags FlagStorage\n\n\t// Creator is the account address that created the post.\n\tCreator address\n\n\t// Meta allows storing post metadata.\n\tMeta any\n\n\t// CreatedAt is the post's creation time.\n\tCreatedAt time.Time\n\n\t// UpdatedAt is the post's update time.\n\tUpdatedAt time.Time\n}\n\n// Summary return a summary of the post's body.\n// It returns the body making sure that the length is limited to 80 characters.\nfunc (post Post) Summary() string {\n\treturn SummaryOf(post.Body, 80)\n}\n\n// SetID sets post ID value.\nfunc (post *Post) SetID(v ID) {\n\tpost.ID = v\n}\n\n// SetParentID sets post's parent ID value.\nfunc (post *Post) SetParentID(v ID) {\n\tpost.ParentID = v\n}\n\n// SetThreadID sets thread ID value.\nfunc (post *Post) SetThreadID(v ID) {\n\tpost.ThreadID = v\n}\n\n// SetOriginalBoardID sets the board ID of the original post when current post is a repost.\nfunc (post *Post) SetOriginalBoardID(v ID) {\n\tpost.OriginalBoardID = v\n}\n\n// SetBoard sets the board where post was created.\nfunc (post *Post) SetBoard(v *Board) {\n\tpost.Board = v\n}\n\n// SetTitle sets title value.\nfunc (post *Post) SetTitle(v string) {\n\tpost.Title = v\n}\n\n// SetBody sets post's content.\nfunc (post *Post) SetBody(v string) {\n\tpost.Body = v\n}\n\n// SetHidden sets hidden value.\nfunc (post *Post) SetHidden(v bool) {\n\tpost.Hidden = v\n}\n\n// SetReadonly sets readonly value.\nfunc (post *Post) SetReadonly(v bool) {\n\tpost.Readonly = v\n}\n\n// SetReplyStorage sets the storage where post replies are stored.\nfunc (post *Post) SetReplyStorage(v PostStorage) {\n\tpost.Replies = v\n}\n\n// SetRepostStorage sets the storage where thread reposts are stored.\nfunc (post *Post) SetRepostStorage(v RepostStorage) {\n\tpost.Reposts = v\n}\n\n// SetFlagStorage sets the storage where post flags are stored.\nfunc (post *Post) SetFlagStorage(v FlagStorage) {\n\tpost.Flags = v\n}\n\n// SetCreator sets the address of the account that created the post.\nfunc (post *Post) SetCreator(v address) {\n\tpost.Creator = v\n}\n\n// SetCreatedAt sets the time when post was created.\nfunc (post *Post) SetCreatedAt(v time.Time) {\n\tpost.CreatedAt = v\n}\n\n// SetUpdatedAt sets the time when a post value was updated.\nfunc (post *Post) SetUpdatedAt(v time.Time) {\n\tpost.UpdatedAt = v\n}\n\n// IsThread checks if a post is a thread.\n// When a post is not a thread it's considered a thread's reply/comment.\nfunc IsThread(p *Post) bool {\n\tif p == nil {\n\t\treturn false\n\t}\n\treturn p.ThreadID == p.ID\n}\n\n// IsRepost checks if a thread is a repost.\nfunc IsRepost(thread *Post) bool {\n\tif thread == nil {\n\t\treturn false\n\t}\n\treturn thread.OriginalBoardID != 0\n}\n\n// SummaryOf returns a summary of a text.\nfunc SummaryOf(text string, length int) string {\n\ttext = strings.TrimSpace(text)\n\tif text == \"\" {\n\t\treturn \"\"\n\t}\n\n\tlines := strings.SplitN(text, \"\\n\", 2)\n\tline := lines[0]\n\tif len(line) \u003e length {\n\t\tline = line[:(length-3)] + \"...\"\n\t} else if len(lines) \u003e 1 {\n\t\tline = line + \"...\"\n\t}\n\treturn line\n}\n"},{"name":"post_storage.gno","body":"package boards\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\ntype (\n\t// PostIterFn defines a function type to iterate posts.\n\tPostIterFn func(*Post) bool\n\n\t// PostStorage defines an interface for posts storage.\n\tPostStorage interface {\n\t\t// Get retruns a post that matches an ID.\n\t\tGet(ID) (_ *Post, found bool)\n\n\t\t// Remove removes a post from the storage.\n\t\tRemove(ID) (_ *Post, removed bool)\n\n\t\t// Add adds a post in the storage.\n\t\tAdd(*Post) error\n\n\t\t// Size returns the number of posts in the storage.\n\t\tSize() int\n\n\t\t// Iterate iterates posts.\n\t\t// To reverse iterate posts use a negative count.\n\t\t// If the callback returns true, the iteration is stopped.\n\t\tIterate(start, count int, fn PostIterFn) bool\n\t}\n)\n\n// NewPostStorage creates a new storage for posts.\n// The new storage uses an AVL tree to store posts.\nfunc NewPostStorage() PostStorage {\n\treturn \u0026postStorage{bptree.NewBPTree32()}\n}\n\ntype postStorage struct {\n\tposts *bptree.BPTree // string(Post.ID) -\u003e *Post\n}\n\n// Get retruns a post that matches an ID.\nfunc (s postStorage) Get(id ID) (*Post, bool) {\n\tk := makePostKey(id)\n\tv := s.posts.Get(k)\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*Post), true\n}\n\n// Remove removes a post from the storage.\nfunc (s *postStorage) Remove(id ID) (*Post, bool) {\n\tk := makePostKey(id)\n\tv, removed := s.posts.Remove(k)\n\tif !removed {\n\t\treturn nil, false\n\t}\n\treturn v.(*Post), true\n}\n\n// Add adds a post in the storage.\n// It updates existing posts when storage contains one with the same ID.\nfunc (s *postStorage) Add(p *Post) error {\n\tif p == nil {\n\t\treturn errors.New(\"saving nil posts is not allowed\")\n\t}\n\n\ts.posts.Set(makePostKey(p.ID), p)\n\treturn nil\n}\n\n// Size returns the number of posts in the storage.\nfunc (s postStorage) Size() int {\n\treturn s.posts.Size()\n}\n\n// Iterate iterates posts.\n// To reverse iterate posts use a negative count.\n// If the callback returns true, the iteration is stopped.\nfunc (s postStorage) Iterate(start, count int, fn PostIterFn) bool {\n\tif count \u003c 0 {\n\t\treturn s.posts.ReverseIterateByOffset(start, -count, func(_ string, v any) bool {\n\t\t\treturn fn(v.(*Post))\n\t\t})\n\t}\n\n\treturn s.posts.IterateByOffset(start, count, func(_ string, v any) bool {\n\t\treturn fn(v.(*Post))\n\t})\n}\n\nfunc makePostKey(postID ID) string {\n\treturn postID.PaddedString()\n}\n"},{"name":"reply.gno","body":"package boards\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewReply creates a new reply to a thread or another reply.\nfunc NewReply(parent *Post, creator address, body string) (*Post, error) {\n\tif parent == nil {\n\t\treturn nil, errors.New(\"reply requires a parent thread or reply\")\n\t}\n\n\tif parent.ThreadID == 0 {\n\t\treturn nil, errors.New(\"parent has no thread ID assigned\")\n\t}\n\n\tif parent.Board == nil {\n\t\treturn nil, errors.New(\"parent has no board assigned\")\n\t}\n\n\tif !creator.IsValid() {\n\t\treturn nil, ufmt.Errorf(\"invalid reply creator address: %s\", creator)\n\t}\n\n\tbody = strings.TrimSpace(body)\n\tif body == \"\" {\n\t\treturn nil, errors.New(\"reply body is required\")\n\t}\n\n\tid := parent.Board.ThreadsSequence.Next()\n\treturn \u0026Post{\n\t\tID:        id,\n\t\tParentID:  parent.ID,\n\t\tThreadID:  parent.ThreadID,\n\t\tBoard:     parent.Board,\n\t\tBody:      body,\n\t\tReplies:   NewPostStorage(),\n\t\tFlags:     NewFlagStorage(),\n\t\tCreator:   creator,\n\t\tCreatedAt: time.Now(),\n\t}, nil\n}\n\n// MustNewReply creates a new reply or panics on error.\nfunc MustNewReply(parent *Post, creator address, body string) *Post {\n\tp, err := NewReply(parent, creator, body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn p\n}\n"},{"name":"repost_storage.gno","body":"package boards\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\ntype (\n\t// RepostIterFn defines a function type to iterate reposts.\n\tRepostIterFn func(board, repost ID) bool\n\n\t// RepostStorage defines an interface for storing reposts.\n\tRepostStorage interface {\n\t\t// Get returns the repost ID for a board.\n\t\tGet(board ID) (repost ID, found bool)\n\n\t\t// Add adds a new repost to the storage.\n\t\tAdd(repost *Post) error\n\n\t\t// Remove removes repost for a board.\n\t\tRemove(board ID) (removed bool)\n\n\t\t// Size returns the number of reposts in the storage.\n\t\tSize() int\n\n\t\t// Iterate iterates reposts.\n\t\t// To reverse iterate reposts use a negative count.\n\t\t// If the callback returns true, the iteration is stopped.\n\t\tIterate(start, count int, fn RepostIterFn) bool\n\t}\n)\n\n// NewRepostStorage creates a new storage for reposts.\n// The new storage uses an AVL tree to store reposts.\nfunc NewRepostStorage() RepostStorage {\n\treturn \u0026repostStorage{bptree.NewBPTree32()}\n}\n\ntype repostStorage struct {\n\treposts *bptree.BPTree // string(Board.ID) -\u003e Post.ID\n}\n\n// Get returns the repost ID for a board.\nfunc (s repostStorage) Get(boardID ID) (ID, bool) {\n\tv := s.reposts.Get(boardID.Key())\n\tif v == nil {\n\t\treturn 0, false\n\t}\n\treturn v.(ID), true\n}\n\n// Add adds a new repost to the storage.\nfunc (s *repostStorage) Add(repost *Post) error {\n\tif repost == nil {\n\t\treturn errors.New(\"saving nil reposts is not allowed\")\n\t}\n\n\ts.reposts.Set(repost.Board.ID.Key(), repost.ID)\n\treturn nil\n}\n\n// Remove removes repost for a board.\nfunc (s *repostStorage) Remove(boardID ID) bool {\n\t_, removed := s.reposts.Remove(boardID.Key())\n\treturn removed\n}\n\n// Size returns the number of reposts in the storage.\nfunc (s repostStorage) Size() int {\n\treturn s.reposts.Size()\n}\n\n// Iterate iterates reposts.\n// To reverse iterate reposts use a negative count.\n// If the callback returns true, the iteration is stopped.\nfunc (s repostStorage) Iterate(start, count int, fn RepostIterFn) bool {\n\tif count \u003c 0 {\n\t\treturn s.reposts.ReverseIterateByOffset(start, -count, func(k string, v any) bool {\n\t\t\tid, err := seqid.FromString(k)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\treturn fn(ID(id), v.(ID))\n\t\t})\n\t}\n\n\treturn s.reposts.IterateByOffset(start, count, func(k string, v any) bool {\n\t\tid, err := seqid.FromString(k)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\treturn fn(ID(id), v.(ID))\n\t})\n}\n"},{"name":"storage.gno","body":"package boards\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\ntype (\n\t// BoardIterFn defines a function type to iterate boards.\n\tBoardIterFn func(*Board) bool\n\n\t// Storage defines an interface for boards storage.\n\tStorage interface {\n\t\t// Get retruns a boards that matches an ID.\n\t\tGet(ID) (_ *Board, found bool)\n\n\t\t// GetByName retruns a boards that matches a name.\n\t\tGetByName(name string) (_ *Board, found bool)\n\n\t\t// Remove removes a board from the storage.\n\t\tRemove(ID) (_ *Board, removed bool)\n\n\t\t// Add adds a board to the storage.\n\t\tAdd(*Board) error\n\n\t\t// Size returns the number of boards in the storage.\n\t\tSize() int\n\n\t\t// Iterate iterates boards.\n\t\t// To reverse iterate boards use a negative count.\n\t\t// If the callback returns true, the iteration is stopped.\n\t\tIterate(start, count int, fn BoardIterFn) bool\n\t}\n)\n\n// NewStorage creates a new boards storage.\nfunc NewStorage() Storage {\n\treturn \u0026storage{\n\t\tbyID:   bptree.NewBPTree32(),\n\t\tbyName: bptree.NewBPTree32(),\n\t}\n}\n\ntype storage struct {\n\tbyID   *bptree.BPTree // string(Board.ID) -\u003e *Board\n\tbyName *bptree.BPTree // Board.Name -\u003e Board.ID\n}\n\n// Get returns a board for a specific ID.\nfunc (s storage) Get(boardID ID) (*Board, bool) {\n\tkey := makeBoardKey(boardID)\n\tv := s.byID.Get(key)\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*Board), true\n}\n\n// Get returns a board for a specific name.\nfunc (s storage) GetByName(name string) (*Board, bool) {\n\tkey := makeBoardNameKey(name)\n\tv := s.byName.Get(key)\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn s.Get(v.(ID))\n}\n\n// Remove removes a board from the storage.\n// It returns false when board is not found.\nfunc (s *storage) Remove(boardID ID) (*Board, bool) {\n\tboard, found := s.Get(boardID)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\t// Remove indexes for current and previous board names\n\tnames := append([]string{board.Name}, board.Aliases...)\n\tfor _, name := range names {\n\t\tkey := makeBoardNameKey(name)\n\n\t\t// Make sure that name is indexed to the board being removed\n\t\tv := s.byName.Get(key)\n\t\tif v != nil \u0026\u0026 v.(ID) == boardID {\n\t\t\ts.byName.Remove(key)\n\t\t}\n\t}\n\n\tkey := makeBoardKey(board.ID)\n\t_, removed := s.byID.Remove(key)\n\treturn board, removed\n}\n\n// Add adds a board to the storage.\n// If board already exists it updates storage by reindexing the board by ID and name.\n// When board name changes it's indexed so it can be found with the new and previous names.\nfunc (s *storage) Add(board *Board) error {\n\tif board == nil {\n\t\treturn errors.New(\"adding nil boards to the storage is not allowed\")\n\t}\n\n\tkey := makeBoardKey(board.ID)\n\ts.byID.Set(key, board)\n\n\t// Index by name when the optional board name is not empty\n\tif key = makeBoardNameKey(board.Name); key != \"\" {\n\t\ts.byName.Set(key, board.ID)\n\t}\n\treturn nil\n}\n\n// Size returns the number of boards in the storage.\nfunc (s storage) Size() int {\n\treturn s.byID.Size()\n}\n\n// Iterate iterates boards.\n// To reverse iterate boards use a negative count.\n// If the callback returns true, the iteration is stopped.\nfunc (s storage) Iterate(start, count int, fn BoardIterFn) bool {\n\tif count \u003c 0 {\n\t\treturn s.byID.ReverseIterateByOffset(start, -count, func(_ string, v any) bool {\n\t\t\treturn fn(v.(*Board))\n\t\t})\n\t}\n\n\treturn s.byID.IterateByOffset(start, count, func(_ string, v any) bool {\n\t\treturn fn(v.(*Board))\n\t})\n}\n\nfunc makeBoardKey(boardID ID) string {\n\treturn boardID.Key()\n}\n\nfunc makeBoardNameKey(name string) string {\n\tname = strings.TrimSpace(name)\n\treturn strings.ToLower(name)\n}\n"},{"name":"thread.gno","body":"package boards\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// NewThread creates a new board thread.\nfunc NewThread(b *Board, creator address, title, body string) (*Post, error) {\n\tif b == nil {\n\t\treturn nil, errors.New(\"thread requires a parent board\")\n\t}\n\n\tif !creator.IsValid() {\n\t\treturn nil, ufmt.Errorf(\"invalid thread creator address: %s\", creator)\n\t}\n\n\ttitle = strings.TrimSpace(title)\n\tif title == \"\" {\n\t\treturn nil, errors.New(\"thread title is required\")\n\t}\n\n\tbody = strings.TrimSpace(body)\n\tif body == \"\" {\n\t\treturn nil, errors.New(\"thread body is required\")\n\t}\n\n\tid := b.ThreadsSequence.Next()\n\treturn \u0026Post{\n\t\tID:        id,\n\t\tThreadID:  id,\n\t\tBoard:     b,\n\t\tTitle:     title,\n\t\tBody:      body,\n\t\tReplies:   NewPostStorage(),\n\t\tReposts:   NewRepostStorage(),\n\t\tFlags:     NewFlagStorage(),\n\t\tCreator:   creator,\n\t\tCreatedAt: time.Now(),\n\t}, nil\n}\n\n// MustNewThread creates a new thread or panics on error.\nfunc MustNewThread(b *Board, creator address, title, body string) *Post {\n\tt, err := NewThread(b, creator, title, body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn t\n}\n\n// NewRepost creates a new thread that is a repost of a thread from another board.\nfunc NewRepost(thread *Post, dst *Board, creator address) (*Post, error) {\n\tif thread == nil {\n\t\treturn nil, errors.New(\"thread to repost is required\")\n\t}\n\n\tif thread.Board == nil {\n\t\treturn nil, errors.New(\"original thread has no board assigned\")\n\t}\n\n\tif dst == nil {\n\t\treturn nil, errors.New(\"thread repost requires a destination board\")\n\t}\n\n\tif IsRepost(thread) {\n\t\treturn nil, errors.New(\"reposting a thread that is a repost is not allowed\")\n\t}\n\n\tif !IsThread(thread) {\n\t\treturn nil, errors.New(\"post must be a thread to be reposted to another board\")\n\t}\n\n\tif !creator.IsValid() {\n\t\treturn nil, ufmt.Errorf(\"invalid thread repost creator address: %s\", creator)\n\t}\n\n\tid := dst.ThreadsSequence.Next()\n\treturn \u0026Post{\n\t\tID:              id,\n\t\tThreadID:        id,\n\t\tParentID:        thread.ID,\n\t\tOriginalBoardID: thread.Board.ID,\n\t\tBoard:           dst,\n\t\tReplies:         NewPostStorage(),\n\t\tReposts:         NewRepostStorage(),\n\t\tFlags:           NewFlagStorage(),\n\t\tCreator:         creator,\n\t\tCreatedAt:       time.Now(),\n\t}, nil\n}\n\n// MustNewRepost creates a new thread that is a repost of a thread from another board or panics on error.\nfunc MustNewRepost(thread *Post, dst *Board, creator address) *Post {\n\tr, err := NewRepost(thread, dst, creator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn r\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"hub","path":"gno.land/p/gnoland/boards/exts/hub/v0","files":[{"name":"README.md","body":"# hub\n\nSimplified, read-only view types over `gno.land/p/gnoland/boards/v0` data:\n`Board`, `Thread`, `Comment`, `Flag` and `Member`.\n\nRealms use these to expose board contents through a query API without\nhanding callers access to their own persistent state.\n\n## Invariant\n\n**A safe type is a snapshot, never a live reference.**\n\nEach `NewSafe*` constructor reads the fields it needs off the `boards`\nvalue and copies them. It keeps no pointer to the source, so a value\nreturned to a caller cannot be used to reach — let alone mutate — the\nrealm data it was built from. Counts (`ThreadCount`, `FlagCount`, …) are\nresolved at construction time and do not track later changes.\n\nKeep it that way when adding fields:\n\n- Copy scalars. Never store the `*boards.Board` / `*boards.Post` the\n  constructor was handed, and never expose a `boards.PostStorage`,\n  `boards.FlagStorage` or `boards.Permissions` — those are handles onto\n  live realm state.\n- Deep-copy slices and maps, as `NewSafeBoard` does for `Aliases` and\n  `NewSafeMember` does for `Roles`. Copy on the way out too: a getter\n  that returns the stored slice lets a caller mutate the snapshot and\n  change what the same value reports on the next call, so `Aliases()`\n  and `Roles()` each return a fresh slice.\n- Convert `boards` types to plain ones where practical, the way `Member`\n  flattens `[]boards.Role` to `[]string`.\n\nAn earlier version of these types carried a `ref` field plus `Iterate*`\nmethods that walked realm storage through it. That is the thing this\npackage exists to not do.\n\n## Usage\n\n```go\nimport (\n    \"gno.land/p/gnoland/boards/v0\"\n    hubexts \"gno.land/p/gnoland/boards/exts/hub/v0\"\n)\n\nfunc GetBoard(id uint64) (hubexts.Board, bool) {\n    b, found := gBoards.Get(boards.ID(id))\n    if !found {\n        return hubexts.Board{}, false\n    }\n    return hubexts.NewSafeBoard(b), true\n}\n```\n\nThe constructors panic on a nil reference, and on a post whose kind does\nnot match (`NewSafeThread` on a comment, or `NewSafeComment` on a\nthread). Resolve and check existence before calling them.\n"},{"name":"board.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Board defines a safe type for boards.\ntype Board struct {\n\t// id is the unique identifier of the board.\n\tid uint64\n\n\t// name is the current name of the board.\n\tname string\n\n\t// aliases contains a list of alternative names for the board.\n\taliases []string\n\n\t// readonly indicates that the board is readonly.\n\treadonly bool\n\n\t// threadCount contains the number of threads within the board.\n\tthreadCount int\n\n\t// memberCount contains the number of members of the board.\n\tmemberCount int\n\n\t// creator is the account address that created the board.\n\tcreator address\n\n\t// createdAt is the board's creation time as Unix time.\n\tcreatedAt int64\n\n\t// updatedAt is the board's update time as Unix time.\n\tupdatedAt int64\n}\n\n// ID returns the unique identifier of the board.\nfunc (b Board) ID() uint64 { return b.id }\n\n// Name returns the current name of the board.\nfunc (b Board) Name() string { return b.name }\n\n// Aliases returns the list of alternative names for the board.\nfunc (b Board) Aliases() []string { return append([]string(nil), b.aliases...) }\n\n// Readonly indicates that the board is readonly.\nfunc (b Board) Readonly() bool { return b.readonly }\n\n// ThreadCount returns the number of threads within the board.\nfunc (b Board) ThreadCount() int { return b.threadCount }\n\n// MemberCount returns the number of members of the board.\nfunc (b Board) MemberCount() int { return b.memberCount }\n\n// Creator returns the account address that created the board.\nfunc (b Board) Creator() address { return b.creator }\n\n// CreatedAt returns the board's creation time as Unix time.\nfunc (b Board) CreatedAt() int64 { return b.createdAt }\n\n// UpdatedAt returns the board's update time as Unix time.\nfunc (b Board) UpdatedAt() int64 { return b.updatedAt }\n\n// NewSafeBoard creates a safe board.\nfunc NewSafeBoard(ref *boards.Board) Board {\n\tif ref == nil {\n\t\tpanic(\"board reference is nil\")\n\t}\n\n\tvar usersCount int\n\tif ref.Permissions != nil {\n\t\tusersCount = ref.Permissions.UsersCount()\n\t}\n\n\tvar threadCount int\n\tif ref.Threads != nil {\n\t\tthreadCount = ref.Threads.Size()\n\t}\n\n\treturn Board{\n\t\tid:          uint64(ref.ID),\n\t\tname:        ref.Name,\n\t\taliases:     append([]string(nil), ref.Aliases...),\n\t\treadonly:    ref.Readonly,\n\t\tthreadCount: threadCount,\n\t\tmemberCount: usersCount,\n\t\tcreator:     ref.Creator,\n\t\tcreatedAt:   timeToUnix(ref.CreatedAt),\n\t\tupdatedAt:   timeToUnix(ref.UpdatedAt),\n\t}\n}\n"},{"name":"comment.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Comment defines a type for threads comment/replies.\ntype Comment struct {\n\t// id is the unique identifier of the comment.\n\tid uint64\n\n\t// boardID is the board ID where comment is created.\n\tboardID uint64\n\n\t// threadID is the ID of the thread where comment is created.\n\tthreadID uint64\n\n\t// parentID is the ID of the parent comment or reply.\n\tparentID uint64\n\n\t// body contains the comment's content.\n\tbody string\n\n\t// hidden indicates that comment is hidden.\n\thidden bool\n\n\t// replyCount contains the number of comments replies.\n\t// Count only includes top level replies, sub-replies are not included.\n\treplyCount int\n\n\t// flagCount contains the number of flags that comment has.\n\tflagCount int\n\n\t// creator is the account address that created the comment or reply.\n\tcreator address\n\n\t// createdAt is thread's creation time as Unix time.\n\tcreatedAt int64\n\n\t// updatedAt is thread's update time as Unix time.\n\tupdatedAt int64\n}\n\n// ID returns the unique identifier of the comment.\nfunc (c Comment) ID() uint64 { return c.id }\n\n// BoardID returns the board ID where the comment is created.\nfunc (c Comment) BoardID() uint64 { return c.boardID }\n\n// ThreadID returns the ID of the thread where the comment is created.\nfunc (c Comment) ThreadID() uint64 { return c.threadID }\n\n// ParentID returns the ID of the parent comment or reply.\nfunc (c Comment) ParentID() uint64 { return c.parentID }\n\n// Body returns the comment's content.\nfunc (c Comment) Body() string { return c.body }\n\n// Hidden indicates that the comment is hidden.\nfunc (c Comment) Hidden() bool { return c.hidden }\n\n// ReplyCount returns the number of comment replies.\n// Count only includes top level replies, sub-replies are not included.\nfunc (c Comment) ReplyCount() int { return c.replyCount }\n\n// FlagCount returns the number of flags that the comment has.\nfunc (c Comment) FlagCount() int { return c.flagCount }\n\n// Creator returns the account address that created the comment or reply.\nfunc (c Comment) Creator() address { return c.creator }\n\n// CreatedAt returns the comment's creation time as Unix time.\nfunc (c Comment) CreatedAt() int64 { return c.createdAt }\n\n// UpdatedAt returns the comment's update time as Unix time.\nfunc (c Comment) UpdatedAt() int64 { return c.updatedAt }\n\n// NewSafeComment creates a safe comment.\nfunc NewSafeComment(ref *boards.Post) Comment {\n\tif ref == nil {\n\t\tpanic(\"post reference is nil\")\n\t}\n\tif boards.IsThread(ref) {\n\t\tpanic(\"post is not a comment or reply\")\n\t}\n\n\tvar replyCount int\n\tif ref.Replies != nil {\n\t\treplyCount = ref.Replies.Size()\n\t}\n\n\tvar flagCount int\n\tif ref.Flags != nil {\n\t\tflagCount = ref.Flags.Size()\n\t}\n\n\treturn Comment{\n\t\tid:         uint64(ref.ID),\n\t\tboardID:    uint64(ref.Board.ID),\n\t\tthreadID:   uint64(ref.ThreadID),\n\t\tparentID:   uint64(ref.ParentID),\n\t\tbody:       ref.Body,\n\t\thidden:     ref.Hidden,\n\t\treplyCount: replyCount,\n\t\tflagCount:  flagCount,\n\t\tcreator:    ref.Creator,\n\t\tcreatedAt:  timeToUnix(ref.CreatedAt),\n\t\tupdatedAt:  timeToUnix(ref.UpdatedAt),\n\t}\n}\n"},{"name":"flag.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Flag defines a type for thread and comment flags.\ntype Flag struct {\n\t// user is the user that flagged.\n\tuser address\n\n\t// reason is the reason for flagging.\n\treason string\n}\n\n// User returns the user that flagged.\nfunc (f Flag) User() address { return f.user }\n\n// Reason returns the reason for flagging.\nfunc (f Flag) Reason() string { return f.reason }\n\n// NewSafeFlag creates a safe flag.\nfunc NewSafeFlag(ref boards.Flag) Flag {\n\treturn Flag{\n\t\tuser:   ref.User,\n\t\treason: ref.Reason,\n\t}\n}\n"},{"name":"format.gno","body":"package hub\n\nimport \"time\"\n\n// timeToUnix converts time to Unix epoch.\nfunc timeToUnix(t time.Time) int64 {\n\tif t.IsZero() {\n\t\treturn 0\n\t}\n\treturn t.Unix()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/gnoland/boards/exts/hub/v0\"\ngno = \"0.9\"\n"},{"name":"member.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Member defines a safe type for board members.\ntype Member struct {\n\t// address is the account address of the member.\n\taddress address\n\n\t// roles contains the names of the roles assigned to the member.\n\troles []string\n}\n\n// Address returns the account address of the member.\nfunc (m Member) Address() address { return m.address }\n\n// Roles returns the names of the roles assigned to the member.\nfunc (m Member) Roles() []string { return append([]string(nil), m.roles...) }\n\n// NewSafeMember creates a safe board member.\nfunc NewSafeMember(ref boards.User) Member {\n\troles := make([]string, len(ref.Roles))\n\tfor i, r := range ref.Roles {\n\t\troles[i] = string(r)\n\t}\n\n\treturn Member{\n\t\taddress: ref.Address,\n\t\troles:   roles,\n\t}\n}\n"},{"name":"thread.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Thread defines a type for board threads.\ntype Thread struct {\n\t// id is the unique identifier of the thread.\n\tid uint64\n\n\t// originalBoardID contains the board ID of the original thread when current is a repost.\n\toriginalBoardID uint64\n\n\t// originalThreadID contains the ID of the original thread when current is a repost.\n\toriginalThreadID uint64\n\n\t// boardID is the board ID where thread is created.\n\tboardID uint64\n\n\t// title contains thread's title.\n\ttitle string\n\n\t// body contains content of the thread.\n\tbody string\n\n\t// hidden indicates that thread is hidden.\n\thidden bool\n\n\t// readonly indicates that thread is readonly.\n\treadonly bool\n\n\t// commentCount contains the number of thread comments.\n\t// Count only includes top level comment, replies are not included.\n\tcommentCount int\n\n\t// repostCount contains the number of times thread has been reposted.\n\trepostCount int\n\n\t// flagCount contains the number of flags that thread has.\n\tflagCount int\n\n\t// creator is the account address that created the thread.\n\tcreator address\n\n\t// createdAt is thread's creation time as Unix time.\n\tcreatedAt int64\n\n\t// updatedAt is thread's update time as unix time.\n\tupdatedAt int64\n}\n\n// ID returns the unique identifier of the thread.\nfunc (t Thread) ID() uint64 { return t.id }\n\n// OriginalBoardID returns the board ID of the original thread when current is a repost.\nfunc (t Thread) OriginalBoardID() uint64 { return t.originalBoardID }\n\n// OriginalThreadID returns the ID of the original thread when current is a repost.\nfunc (t Thread) OriginalThreadID() uint64 { return t.originalThreadID }\n\n// BoardID returns the board ID where the thread is created.\nfunc (t Thread) BoardID() uint64 { return t.boardID }\n\n// Title returns the thread's title.\nfunc (t Thread) Title() string { return t.title }\n\n// Body returns the content of the thread.\nfunc (t Thread) Body() string { return t.body }\n\n// Hidden indicates that the thread is hidden.\nfunc (t Thread) Hidden() bool { return t.hidden }\n\n// Readonly indicates that the thread is readonly.\nfunc (t Thread) Readonly() bool { return t.readonly }\n\n// CommentCount returns the number of thread comments.\n// Count only includes top level comment, replies are not included.\nfunc (t Thread) CommentCount() int { return t.commentCount }\n\n// RepostCount returns the number of times the thread has been reposted.\nfunc (t Thread) RepostCount() int { return t.repostCount }\n\n// FlagCount returns the number of flags that the thread has.\nfunc (t Thread) FlagCount() int { return t.flagCount }\n\n// Creator returns the account address that created the thread.\nfunc (t Thread) Creator() address { return t.creator }\n\n// CreatedAt returns the thread's creation time as Unix time.\nfunc (t Thread) CreatedAt() int64 { return t.createdAt }\n\n// UpdatedAt returns the thread's update time as Unix time.\nfunc (t Thread) UpdatedAt() int64 { return t.updatedAt }\n\n// NewSafeThread creates a safe thread.\nfunc NewSafeThread(ref *boards.Post) Thread {\n\tif ref == nil {\n\t\tpanic(\"post reference is nil\")\n\t}\n\tif !boards.IsThread(ref) {\n\t\tpanic(\"post is not a thread\")\n\t}\n\n\tvar commentCount int\n\tif ref.Replies != nil {\n\t\tcommentCount = ref.Replies.Size()\n\t}\n\n\tvar repostCount int\n\tif ref.Reposts != nil {\n\t\trepostCount = ref.Reposts.Size()\n\t}\n\n\tvar flagCount int\n\tif ref.Flags != nil {\n\t\tflagCount = ref.Flags.Size()\n\t}\n\n\treturn Thread{\n\t\tid:               uint64(ref.ID),\n\t\toriginalBoardID:  uint64(ref.OriginalBoardID),\n\t\toriginalThreadID: uint64(ref.ParentID),\n\t\tboardID:          uint64(ref.Board.ID),\n\t\ttitle:            ref.Title,\n\t\tbody:             ref.Body,\n\t\thidden:           ref.Hidden,\n\t\treadonly:         ref.Readonly,\n\t\tcommentCount:     commentCount,\n\t\trepostCount:      repostCount,\n\t\tflagCount:        flagCount,\n\t\tcreator:          ref.Creator,\n\t\tcreatedAt:        timeToUnix(ref.CreatedAt),\n\t\tupdatedAt:        timeToUnix(ref.UpdatedAt),\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"realmpath","path":"gno.land/p/moul/realmpath/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/realmpath/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"realmpath.gno","body":"// Package realmpath is a lightweight Render.path parsing and link generation\n// library with an idiomatic API, closely resembling that of net/url.\n//\n// This package provides utilities for parsing request paths and query\n// parameters, allowing you to extract path segments and manipulate query\n// values.\n//\n// Example usage:\n//\n//\timport \"gno.land/p/moul/realmpath/v0\"\n//\n//\tfunc Render(path string) string {\n//\t    // Parsing a sample path with query parameters\n//\t    path = \"hello/world?foo=bar\u0026baz=foobar\"\n//\t    req := realmpath.Parse(path)\n//\n//\t    // Accessing parsed path and query parameters\n//\t    println(req.Path)             // Output: hello/world\n//\t    println(req.PathPart(0))      // Output: hello\n//\t    println(req.PathPart(1))      // Output: world\n//\t    println(req.Query.Get(\"foo\")) // Output: bar\n//\t    println(req.Query.Get(\"baz\")) // Output: foobar\n//\n//\t    // Rebuilding the URL\n//\t    println(req.String())         // Output: /r/current/realm:hello/world?baz=foobar\u0026foo=bar\n//\t}\npackage realmpath\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"net/url\"\n\t\"strings\"\n)\n\nvar chainDomain = runtime.ChainDomain()\n\n// Request represents a parsed request.\ntype Request struct {\n\tPath  string     // The path of the request\n\tQuery url.Values // The parsed query parameters\n\tRealm string     // The realm associated with the request\n}\n\n// Parse takes a raw path string and returns a Request object.\n// It splits the path into its components and parses any query parameters.\nfunc Parse(rawPath string) *Request {\n\t// Split the raw path into path and query components\n\tpath, query := splitPathAndQuery(rawPath)\n\n\t// Parse the query string into url.Values\n\tqueryValues, _ := url.ParseQuery(query)\n\n\treturn \u0026Request{\n\t\tPath:  path,        // Set the path\n\t\tQuery: queryValues, // Set the parsed query values\n\t}\n}\n\n// PathParts returns the segments of the path as a slice of strings.\n// It trims leading and trailing slashes and splits the path by slashes.\nfunc (r *Request) PathParts() []string {\n\treturn strings.Split(strings.Trim(r.Path, \"/\"), \"/\")\n}\n\n// PathPart returns the specified part of the path.\n// If the index is out of bounds, it returns an empty string.\nfunc (r *Request) PathPart(index int) string {\n\tparts := r.PathParts() // Get the path segments\n\tif index \u003c 0 || index \u003e= len(parts) {\n\t\treturn \"\" // Return empty if index is out of bounds\n\t}\n\treturn parts[index] // Return the specified path part\n}\n\n// String rebuilds the URL from the path and query values.\n// If the Realm is not set, it automatically retrieves the current realm path.\n//\n// SECURITY (Class-2-shaped, intentionally accepted): unsafe.CurrentRealm()\n// inside a non-crossing /p/ method is .Title()-vulnerable — it walks past\n// non-crossing frames to the most-recent crossing ancestor, not the\n// immediate caller. The lazily-captured r.Realm is therefore NOT a reliable\n// identity claim under a contrived call chain.\n//\n// This is acceptable here because r.Realm is consumed only as a URL string\n// for rendering (the line below builds reconstructedPath for display); no\n// caller in /examples uses it for authorization. If you add a new consumer\n// that gates writes/auth on r.Realm, replace the lazy fill with an explicit\n// `req.Realm = cur.PkgPath()` set by the caller under rlm.IsCurrent(), or\n// switch to a sibling method that takes a realm parameter — see\n// docs/resources/gno-security.md for the threat-class taxonomy.\nfunc (r *Request) String() string {\n\t// Automatically set the Realm if it is not already defined\n\tif r.Realm == \"\" {\n\t\tr.Realm = unsafe.CurrentRealm().PkgPath() // Get the current realm path\n\t}\n\n\t// Rebuild the path using the realm and path parts\n\trelativePkgPath := strings.TrimPrefix(r.Realm, chainDomain) // Trim the chain domain prefix\n\treconstructedPath := relativePkgPath + \":\" + strings.Join(r.PathParts(), \"/\")\n\n\t// Rebuild the query string\n\tqueryString := r.Query.Encode() // Encode the query parameters\n\tif queryString != \"\" {\n\t\treturn reconstructedPath + \"?\" + queryString // Return the full URL with query\n\t}\n\treturn reconstructedPath // Return the path without query parameters\n}\n\nfunc splitPathAndQuery(rawPath string) (string, string) {\n\tif idx := strings.Index(rawPath, \"?\"); idx != -1 {\n\t\treturn rawPath[:idx], rawPath[idx+1:] // Split at the first '?' found\n\t}\n\treturn rawPath, \"\" // No query string present\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"ulist","path":"gno.land/p/moul/ulist/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/ulist/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"ulist.gno","body":"// Package ulist provides an append-only list implementation using a binary tree structure,\n// optimized for scenarios requiring sequential inserts with auto-incrementing indices.\n//\n// The implementation uses a binary tree where new elements are added by following a path\n// determined by the binary representation of the index. This provides automatic balancing\n// for append operations without requiring any balancing logic.\n//\n// Unlike the AVL tree-based list implementation (p/demo/avl/list), ulist is specifically\n// designed for append-only operations and does not require rebalancing. This makes it more\n// efficient for sequential inserts but less flexible for general-purpose list operations.\n//\n// Key differences from AVL list:\n// * Append-only design (no arbitrary inserts)\n// * No tree rebalancing needed\n// * Simpler implementation\n// * More memory efficient for sequential operations\n// * Less flexible than AVL (no arbitrary inserts/reordering)\n//\n// Key characteristics:\n// * O(log n) append and access operations\n// * Perfect balance for power-of-2 sizes\n// * No balancing needed\n// * Memory efficient\n// * Natural support for range queries\n// * Support for soft deletion of elements\n// * Forward and reverse iteration capabilities\n// * Offset-based iteration with count control\npackage ulist\n\n// TODO: Make avl/pager compatible in some way. Explain the limitations (not always 10 items because of nil ones).\n// TODO: Use this ulist in moul/collection for the primary index.\n// TODO: Consider adding a \"compact\" method that removes nil nodes.\n// TODO: Benchmarks.\n\nimport (\n\t\"errors\"\n)\n\n// List represents an append-only binary tree list\ntype List struct {\n\troot       *treeNode\n\ttotalSize  int\n\tactiveSize int\n}\n\n// Entry represents a key-value pair in the list, where Index is the position\n// and Value is the stored data\ntype Entry struct {\n\tIndex int\n\tValue any\n}\n\n// treeNode represents a node in the binary tree\ntype treeNode struct {\n\tdata  any\n\tleft  *treeNode\n\tright *treeNode\n}\n\n// Error variables\nvar (\n\tErrOutOfBounds = errors.New(\"index out of bounds\")\n\tErrDeleted     = errors.New(\"element already deleted\")\n)\n\n// New creates a new empty List instance\nfunc New() *List {\n\treturn \u0026List{}\n}\n\n// Append adds one or more values to the end of the list.\n// Values are added sequentially, and the list grows automatically.\nfunc (l *List) Append(values ...any) {\n\tfor _, value := range values {\n\t\tindex := l.totalSize\n\t\tnode := l.findNode(index, true)\n\t\tnode.data = value\n\t\tl.totalSize++\n\t\tl.activeSize++\n\t}\n}\n\n// Get retrieves the value at the specified index.\n// Returns nil if the index is out of bounds or if the element was deleted.\nfunc (l *List) Get(index int) any {\n\tnode := l.findNode(index, false)\n\tif node == nil {\n\t\treturn nil\n\t}\n\treturn node.data\n}\n\n// Delete marks the elements at the specified indices as deleted.\n// Returns ErrOutOfBounds if any index is invalid or ErrDeleted if\n// the element was already deleted.\nfunc (l *List) Delete(indices ...int) error {\n\tif len(indices) == 0 {\n\t\treturn nil\n\t}\n\tif l == nil || l.totalSize == 0 {\n\t\treturn ErrOutOfBounds\n\t}\n\n\tfor _, index := range indices {\n\t\tif index \u003c 0 || index \u003e= l.totalSize {\n\t\t\treturn ErrOutOfBounds\n\t\t}\n\n\t\tnode := l.findNode(index, false)\n\t\tif node == nil || node.data == nil {\n\t\t\treturn ErrDeleted\n\t\t}\n\t\tnode.data = nil\n\t\tl.activeSize--\n\t}\n\n\treturn nil\n}\n\n// Set updates or restores a value at the specified index if within bounds\n// Returns ErrOutOfBounds if the index is invalid\nfunc (l *List) Set(index int, value any) error {\n\tif l == nil || index \u003c 0 || index \u003e= l.totalSize {\n\t\treturn ErrOutOfBounds\n\t}\n\n\tnode := l.findNode(index, false)\n\tif node == nil {\n\t\treturn ErrOutOfBounds\n\t}\n\n\t// If this is restoring a deleted element\n\tif value != nil \u0026\u0026 node.data == nil {\n\t\tl.activeSize++\n\t}\n\n\t// If this is deleting an element\n\tif value == nil \u0026\u0026 node.data != nil {\n\t\tl.activeSize--\n\t}\n\n\tnode.data = value\n\treturn nil\n}\n\n// Size returns the number of active (non-deleted) elements in the list\nfunc (l *List) Size() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn l.activeSize\n}\n\n// TotalSize returns the total number of elements ever added to the list,\n// including deleted elements\nfunc (l *List) TotalSize() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn l.totalSize\n}\n\n// IterCbFn is a callback function type used in iteration methods.\n// Return true to stop iteration, false to continue.\ntype IterCbFn func(index int, value any) bool\n\n// Iterator performs iteration between start and end indices, calling cb for each entry.\n// If start \u003e end, iteration is performed in reverse order.\n// Returns true if iteration was stopped early by the callback returning true.\n// Skips deleted elements.\nfunc (l *List) Iterator(start, end int, cb IterCbFn) bool {\n\t// For empty list or invalid range\n\tif l == nil || l.totalSize == 0 {\n\t\treturn false\n\t}\n\tif start \u003c 0 \u0026\u0026 end \u003c 0 {\n\t\treturn false\n\t}\n\tif start \u003e= l.totalSize \u0026\u0026 end \u003e= l.totalSize {\n\t\treturn false\n\t}\n\n\t// Normalize indices\n\tif start \u003c 0 {\n\t\tstart = 0\n\t}\n\tif end \u003c 0 {\n\t\tend = 0\n\t}\n\tif end \u003e= l.totalSize {\n\t\tend = l.totalSize - 1\n\t}\n\tif start \u003e= l.totalSize {\n\t\tstart = l.totalSize - 1\n\t}\n\n\t// Handle reverse iteration\n\tif start \u003e end {\n\t\tfor i := start; i \u003e= end; i-- {\n\t\t\tval := l.Get(i)\n\t\t\tif val != nil {\n\t\t\t\tif cb(i, val) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// Handle forward iteration\n\tfor i := start; i \u003c= end; i++ {\n\t\tval := l.Get(i)\n\t\tif val != nil {\n\t\t\tif cb(i, val) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n// IteratorByOffset performs iteration starting from offset for count elements.\n// If count is positive, iterates forward; if negative, iterates backward.\n// The iteration stops after abs(count) elements or when reaching list bounds.\n// Skips deleted elements.\nfunc (l *List) IteratorByOffset(offset int, count int, cb IterCbFn) bool {\n\tif count == 0 || l == nil || l.totalSize == 0 {\n\t\treturn false\n\t}\n\n\t// Normalize offset\n\tif offset \u003c 0 {\n\t\toffset = 0\n\t}\n\tif offset \u003e= l.totalSize {\n\t\toffset = l.totalSize - 1\n\t}\n\n\t// Determine end based on count direction\n\tvar end int\n\tif count \u003e 0 {\n\t\tend = l.totalSize - 1\n\t} else {\n\t\tend = 0\n\t}\n\n\twrapperReturned := false\n\n\t// Wrap the callback to limit iterations\n\tremaining := abs(count)\n\twrapper := func(index int, value any) bool {\n\t\tif remaining \u003c= 0 {\n\t\t\twrapperReturned = true\n\t\t\treturn true\n\t\t}\n\t\tremaining--\n\t\treturn cb(index, value)\n\t}\n\tret := l.Iterator(offset, end, wrapper)\n\tif wrapperReturned {\n\t\treturn false\n\t}\n\treturn ret\n}\n\n// abs returns the absolute value of x\nfunc abs(x int) int {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\n// findNode locates or creates a node at the given index in the binary tree.\n// The tree is structured such that the path to a node is determined by the binary\n// representation of the index. For example, a tree with 15 elements would look like:\n//\n//\t          0\n//\t       /      \\\n//\t     1         2\n//\t   /   \\     /   \\\n//\t  3    4    5     6\n//\t / \\  / \\  / \\   / \\\n//\t7  8 9 10 11 12 13 14\n//\n// To find index 13 (binary 1101):\n// 1. Start at root (0)\n// 2. Calculate bits needed (4 bits for index 13)\n// 3. Skip the highest bit position and start from bits-2\n// 4. Read bits from left to right:\n//   - 1 -\u003e go right to 2\n//   - 1 -\u003e go right to 6\n//   - 0 -\u003e go left to 13\n//\n// Special cases:\n// - Index 0 always returns the root node\n// - For create=true, missing nodes are created along the path\n// - For create=false, returns nil if any node is missing\nfunc (l *List) findNode(index int, create bool) *treeNode {\n\t// For read operations, check bounds strictly\n\tif !create \u0026\u0026 (l == nil || index \u003c 0 || index \u003e= l.totalSize) {\n\t\treturn nil\n\t}\n\n\t// For create operations, allow index == totalSize for append\n\tif create \u0026\u0026 (l == nil || index \u003c 0 || index \u003e l.totalSize) {\n\t\treturn nil\n\t}\n\n\t// Initialize root if needed\n\tif l.root == nil {\n\t\tif !create {\n\t\t\treturn nil\n\t\t}\n\t\tl.root = \u0026treeNode{}\n\t\treturn l.root\n\t}\n\n\tnode := l.root\n\n\t// Special case for root node\n\tif index == 0 {\n\t\treturn node\n\t}\n\n\t// Calculate the number of bits needed (inline highestBit logic)\n\tbits := 0\n\tn := index + 1\n\tfor n \u003e 0 {\n\t\tn \u003e\u003e= 1\n\t\tbits++\n\t}\n\n\t// Start from the second highest bit\n\tfor level := bits - 2; level \u003e= 0; level-- {\n\t\tbit := (index \u0026 (1 \u003c\u003c uint(level))) != 0\n\n\t\tif bit {\n\t\t\tif node.right == nil {\n\t\t\t\tif !create {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tnode.right = \u0026treeNode{}\n\t\t\t}\n\t\t\tnode = node.right\n\t\t} else {\n\t\t\tif node.left == nil {\n\t\t\t\tif !create {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tnode.left = \u0026treeNode{}\n\t\t\t}\n\t\t\tnode = node.left\n\t\t}\n\t}\n\n\treturn node\n}\n\n// MustDelete deletes elements at the specified indices.\n// Panics if any index is invalid or if any element was already deleted.\nfunc (l *List) MustDelete(indices ...int) {\n\tif err := l.Delete(indices...); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// MustGet retrieves the value at the specified index.\n// Panics if the index is out of bounds or if the element was deleted.\nfunc (l *List) MustGet(index int) any {\n\tif l == nil || index \u003c 0 || index \u003e= l.totalSize {\n\t\tpanic(ErrOutOfBounds)\n\t}\n\tvalue := l.Get(index)\n\tif value == nil {\n\t\tpanic(ErrDeleted)\n\t}\n\treturn value\n}\n\n// MustSet updates or restores a value at the specified index.\n// Panics if the index is out of bounds.\nfunc (l *List) MustSet(index int, value any) {\n\tif err := l.Set(index, value); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// GetRange returns a slice of Entry containing elements between start and end indices.\n// If start \u003e end, elements are returned in reverse order.\n// Deleted elements are skipped.\nfunc (l *List) GetRange(start, end int) []Entry {\n\tvar entries []Entry\n\tl.Iterator(start, end, func(index int, value any) bool {\n\t\tentries = append(entries, Entry{Index: index, Value: value})\n\t\treturn false\n\t})\n\treturn entries\n}\n\n// GetByOffset returns a slice of Entry starting from offset for count elements.\n// If count is positive, returns elements forward; if negative, returns elements backward.\n// The operation stops after abs(count) elements or when reaching list bounds.\n// Deleted elements are skipped.\nfunc (l *List) GetByOffset(offset int, count int) []Entry {\n\tvar entries []Entry\n\tl.IteratorByOffset(offset, count, func(index int, value any) bool {\n\t\tentries = append(entries, Entry{Index: index, Value: value})\n\t\treturn false\n\t})\n\treturn entries\n}\n\n// IList defines the interface for an ulist.List compatible structure.\ntype IList interface {\n\t// Basic operations\n\tAppend(values ...any)\n\tGet(index int) any\n\tDelete(indices ...int) error\n\tSize() int\n\tTotalSize() int\n\tSet(index int, value any) error\n\n\t// Must variants that panic instead of returning errors\n\tMustDelete(indices ...int)\n\tMustGet(index int) any\n\tMustSet(index int, value any)\n\n\t// Range operations\n\tGetRange(start, end int) []Entry\n\tGetByOffset(offset int, count int) []Entry\n\n\t// Iterator operations\n\tIterator(start, end int, cb IterCbFn) bool\n\tIteratorByOffset(offset int, count int, cb IterCbFn) bool\n}\n\n// Verify that List implements IList\nvar _ IList = (*List)(nil)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"royalty","path":"gno.land/p/nt/grc721/royalty/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/grc721/royalty/v0\"\ngno = \"0.9\"\n"},{"name":"token.gno","body":"package royalty\n\nimport (\n\t\"chain\"\n\t\"math\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/grc721/v0\"\n)\n\nconst Kind = \"royalty\"\n\n// NewRoyalty attaches a royalty extension; maxBps caps every rate and must be 0..10000.\nfunc NewRoyalty(coreLedger *grc721.PrivateLedger, maxBps int64) (*Royalty, *Ledger) {\n\tif coreLedger == nil {\n\t\tpanic(\"royalty: nil core ledger\")\n\t}\n\n\tif maxBps \u003c 0 || maxBps \u003e FeeDenominator {\n\t\tpanic(ErrMaxBpsRange)\n\t}\n\n\tst := \u0026storage{maxBps: maxBps}\n\tcore := coreLedger.ReadToken()\n\tled := \u0026Ledger{core: core, st: st}\n\n\tcoreLedger.RegisterExtension(led)\n\n\treturn \u0026Royalty{core: core, st: st}, led\n}\n\nfunc (r *Royalty) ExtensionKind() string { return Kind }\n\nfunc (r *Royalty) TokenID() string { return r.core.ID() }\n\nfunc (r *Royalty) MaxBps() int64 { return r.st.maxBps }\n\n// RoyaltyInfo implements EIP-2981; per-token override takes precedence over the\n// default, and no royalty returns (zeroAddress, 0) — the \"no royalty\" signal.\nfunc (r *Royalty) RoyaltyInfo(tid grc721.TokenID, salePrice int64) (address, int64, error) {\n\tif salePrice \u003c 0 {\n\t\treturn zeroAddress, 0, ErrInvalidSalePrice\n\t}\n\n\tinfo, ok := r.resolve(tid)\n\tif !ok {\n\t\treturn zeroAddress, 0, nil\n\t}\n\n\tif info.Bps != 0 \u0026\u0026 salePrice \u003e math.MaxInt64/info.Bps {\n\t\treturn zeroAddress, 0, ErrInvalidSalePrice\n\t}\n\n\tamount := salePrice * info.Bps / FeeDenominator\n\n\treturn info.Receiver, amount, nil\n}\n\nfunc (r *Royalty) DefaultRoyalty() (RoyaltyInfo, bool) {\n\tif !r.st.hasDefault {\n\t\treturn RoyaltyInfo{}, false\n\t}\n\n\treturn r.st.def, true\n}\n\nfunc (r *Royalty) TokenRoyalty(tid grc721.TokenID) (RoyaltyInfo, bool) {\n\tv := r.st.perToken.Get(tid.String())\n\tif v == nil {\n\t\treturn RoyaltyInfo{}, false\n\t}\n\n\treturn v.(RoyaltyInfo), true\n}\n\n// resolve returns the effective royalty: per-token override first, then default.\nfunc (r *Royalty) resolve(tid grc721.TokenID) (RoyaltyInfo, bool) {\n\tif v := r.st.perToken.Get(tid.String()); v != nil {\n\t\treturn v.(RoyaltyInfo), true\n\t}\n\n\tif r.st.hasDefault {\n\t\treturn r.st.def, true\n\t}\n\n\treturn RoyaltyInfo{}, false\n}\n\n// SetDefaultRoyalty sets the collection default for tokens without an override; issuer-only.\nfunc (led *Ledger) SetDefaultRoyalty(receiver address, bps int64) error {\n\tif err := led.validate(receiver, bps); err != nil {\n\t\treturn err\n\t}\n\n\tled.st.def = RoyaltyInfo{Receiver: receiver, Bps: bps}\n\tled.st.hasDefault = true\n\n\tled.emitRoyaltyUpdate(\"default\", \"\", receiver, bps)\n\treturn nil\n}\n\nfunc (led *Ledger) DeleteDefaultRoyalty() {\n\tled.st.hasDefault = false\n\tled.st.def = RoyaltyInfo{}\n\n\tled.emitRoyaltyUpdate(\"default\", \"\", zeroAddress, 0)\n}\n\n// SetTokenRoyalty sets a per-token override for tid; issuer-only.\nfunc (led *Ledger) SetTokenRoyalty(tid grc721.TokenID, receiver address, bps int64) error {\n\tif _, err := led.core.OwnerOf(tid); err != nil {\n\t\treturn ErrTokenNotMinted\n\t}\n\n\tif err := led.validate(receiver, bps); err != nil {\n\t\treturn err\n\t}\n\n\tled.st.perToken.Set(tid.String(), RoyaltyInfo{Receiver: receiver, Bps: bps})\n\n\tled.emitRoyaltyUpdate(\"token\", tid.String(), receiver, bps)\n\treturn nil\n}\n\n// DeleteTokenRoyalty clears the per-token override, falling back to the default.\nfunc (led *Ledger) DeleteTokenRoyalty(tid grc721.TokenID) {\n\tled.st.perToken.Remove(tid.String())\n\n\tled.emitRoyaltyUpdate(\"token\", tid.String(), zeroAddress, 0)\n}\n\n// emitRoyaltyUpdate signals a royalty change (EIP-2981 defines no events); a\n// cleared royalty is reported as an empty receiver and bps 0.\nfunc (led *Ledger) emitRoyaltyUpdate(scope, tokenID string, receiver address, bps int64) {\n\tchain.Emit(\n\t\tRoyaltyUpdateEvent,\n\t\t\"token\", led.core.ID(),\n\t\t\"scope\", scope,\n\t\t\"tokenId\", tokenID,\n\t\t\"receiver\", receiver.String(),\n\t\t\"bps\", strconv.FormatInt(bps, 10),\n\t)\n}\n\nfunc (led *Ledger) validate(receiver address, bps int64) error {\n\tif !receiver.IsValid() {\n\t\treturn ErrInvalidReceiver\n\t}\n\n\tif bps \u003c 0 || bps \u003e led.st.maxBps {\n\t\treturn ErrInvalidBps\n\t}\n\n\treturn nil\n}\n\nfunc (led *Ledger) ExtensionKind() string { return Kind }\n\nfunc (led *Ledger) OnMint(to address, tid grc721.TokenID)           {}\nfunc (led *Ledger) OnTransfer(from, to address, tid grc721.TokenID) {}\n\n// OnBurn clears the per-token override (cannot resurface on re-mint) but keeps\n// the default, which is collection-level policy, not per-token state.\nfunc (led *Ledger) OnBurn(tid grc721.TokenID) {\n\tled.st.perToken.Remove(tid.String())\n}\n"},{"name":"types.gno","body":"// Package royalty is a stackable GRC721 extension implementing EIP-2981 in basis\n// points. Writes are issuer-only so a holder cannot zero out a royalty on a\n// token they just received.\npackage royalty\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc721/v0\"\n)\n\n// FeeDenominator is the EIP-2981 basis-point denominator: bps/10000, 10000 == 100%.\nconst FeeDenominator = 10000\n\nconst RoyaltyUpdateEvent = \"RoyaltyUpdate\"\n\nvar (\n\tErrInvalidReceiver  = errors.New(\"invalid royalty receiver\")\n\tErrInvalidBps       = errors.New(\"royalty bps out of range\")\n\tErrTokenNotMinted   = errors.New(\"token is not minted\")\n\tErrMaxBpsRange      = errors.New(\"maxBps out of range (0..10000)\")\n\tErrInvalidSalePrice = errors.New(\"invalid sale price (negative or would overflow)\")\n)\n\nvar zeroAddress = address(\"\")\n\n// RoyaltyInfo is a royalty policy: send Bps/10000 of a sale to Receiver.\ntype RoyaltyInfo struct {\n\tReceiver address\n\tBps      int64\n}\n\ntype storage struct {\n\tmaxBps     int64\n\thasDefault bool\n\tdef        RoyaltyInfo\n\tperToken   avl.Tree // grc721.TokenID -\u003e RoyaltyInfo\n}\n\ntype Royalty struct {\n\tcore *grc721.Token\n\tst   *storage\n}\n\ntype Ledger struct {\n\tcore *grc721.Token\n\tst   *storage\n}\n\nvar _ grc721.Extension = (*Ledger)(nil)\n\nvar _ grc721.ExtensionView = (*Royalty)(nil)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"foreign","path":"gno.land/p/nt/markdown/foreign/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `foreign` - Foreign markdown sandbox\n\nRealm-side helper that wraps externally-built markdown in a `\u003cgno-foreign\u003e` sandbox block. gnoweb renders the wrapped body inside its own goldmark sub-instance, so markdown you did not author cannot reach out and alter the surrounding page. Use it when flowing in markdown returned by another realm's interface method, fetched from chain storage owned by another realm, or otherwise outside your control.\n\n## Usage\n\n```go\npackage myrealm\n\nimport \"gno.land/p/nt/markdown/foreign/v0\"\n\nfunc Render(path string) string {\n    body := otherRealm.Render(path) // markdown you did not author\n    return \"## Included content\\n\\n\" + foreign.Foreign(body)\n}\n```\n\nWith a caller-supplied label shown as a strip above the body:\n\n```go\nforeign.ForeignWithLabel(\"Pulled from /r/foo\", body)\n```\n\n## API\n\n```go\nfunc Foreign(body string) string\nfunc ForeignWithLabel(label, body string) string\nfunc MaxBlocksPerRender() int\n```\n\n## Notes\n\n- `body` is normalized before wrapping: `\\r\\n` and bare `\\r` become `\\n`, and any line that looks like a `gno-foreign` opener or closer (bare, attribute-bearing, or any case) has its leading `\u003c` escaped to `\u0026lt;`. Foreign content therefore cannot terminate the sandbox early or open a nested one.\n- `ForeignWithLabel` sanitizes the label: bidi/zero-width characters are stripped, NUL is dropped, other control characters and the Unicode line separators (U+2028/U+2029/U+0085) become spaces, `\u0026` `\u003c` `\u003e` `\"` become HTML entities, and surrounding whitespace is trimmed. A label that is empty after sanitization behaves exactly like `Foreign` (no label strip, no default text).\n- `MaxBlocksPerRender()` re-exports gnoweb's per-render cap on `\u003cgno-foreign\u003e` blocks (the same value the renderer reads). Past the cap, later blocks fall through to raw HTML and are dropped, so keep a page's foreign total under it.\n- The renderer-side contract lives in `gno.land/pkg/gnoweb/markdown/ext_foreign.go`.\n- To clean user-supplied (rather than realm-supplied) markdown at the leaf level, see [`sanitize`](../../sanitize/v0).\n"},{"name":"foreign.gno","body":"// Package foreign provides the realm-side helper for emitting the\n// gno-foreign sandbox block. Realm authors wrap externally-built\n// markdown (markdown returned by an interface method on a foreign\n// realm, fetched from chain storage owned by another realm, etc.) in\n// Foreign before flowing it into rendered output, so gnoweb renders\n// the body inside its own goldmark sub-instance with structural\n// extensions selectively loaded.\n//\n// The renderer-side contract lives in\n// gno.land/pkg/gnoweb/markdown/ext_foreign.go. This helper produces\n// bytes that satisfy the parser's opener requirements (CommonMark\n// §4.6 Type-7 HTML block, no attribute fall-through) and neutralizes\n// any literal sentinel lines in the body so the foreign markdown\n// cannot terminate the outer block prematurely.\npackage foreign\n\nimport (\n\t\"chain/markdown\"\n\t\"strings\"\n)\n\n// Foreign wraps body in a `\u003cgno-foreign\u003e` ... `\u003c/gno-foreign\u003e` sandbox\n// block. The returned string is ready to concatenate into a larger\n// markdown document.\n//\n// Three normalization steps apply to body:\n//\n//  1. \\r\\n and bare \\r line endings are normalized to \\n. The parser\n//     uses byte-equal matching against the sentinel close tag, so\n//     mixed line endings would otherwise change the match boundary.\n//\n//  2. Any line whose trimmed content looks like a gno-foreign tag\n//     opener OR closer — bare (`\u003cgno-foreign\u003e`, `\u003c/gno-foreign\u003e`) or\n//     attribute-bearing (`\u003cgno-foreign label=\"x\"\u003e`, `\u003c/gno-foreign\n//     attr=\"…\"\u003e`, etc.) — is neutralized by HTML-escaping the leading\n//     `\u003c` to `\u0026lt;`. The parser tokenizes line bytes literally, so the\n//     escaped form is seen as text and cannot terminate the outer\n//     block or open an unintended inner block.\n//\n//     Crucially, BOTH open-tag and close-tag attribute-bearing forms\n//     are neutralized. The parser recognizes a bare `\u003cgno-foreign\u003e`\n//     opener, a labeled `\u003cgno-foreign label=\"x\"\u003e` opener, and ANY\n//     `\u003c/gno-foreign…\u003e` closer (golang.org/x/net/html drops attrs on\n//     end tags before our recognizer sees them, so attr-bearing\n//     closers are sentinel-equivalent). Leaving any of those forms\n//     un-neutralized in body bytes would let attacker-supplied\n//     markdown adjust the parser's framing-depth counter and either\n//     consume the helper's own close (capturing trailing realm\n//     content into the sandbox) or close the outer block early\n//     (escaping the sandbox entirely).\n//\n//     There is therefore NO nesting via the helper: Foreign(Foreign(x))\n//     escapes the inner call's own `\u003cgno-foreign\u003e`/`\u003c/gno-foreign\u003e`\n//     lines, so the inner block renders as visible literal text inside\n//     one sandbox, not as a nested sandbox. This is intended — wrapping\n//     foreign-built markdown that itself contains gno-foreign sentinels\n//     must neutralize them, not honor them.\n//\n//  3. A leading and trailing blank line are emitted around the\n//     opener / closer. CommonMark §4.6 forbids Type-7 HTML blocks\n//     from interrupting a paragraph; without the blank line, an\n//     opener following a non-blank line is absorbed into the\n//     preceding paragraph instead of opening a sandbox.\n//\n// The renderer caps cross-family nesting at 4 levels and per-Convert\n// foreign blocks at 256. Beyond those caps, the opener falls through\n// to raw HTML and is stripped by the renderer's safe mode.\nfunc Foreign(body string) string {\n\treturn wrapForeign(\"\", body)\n}\n\n// ForeignWithLabel wraps body like Foreign but emits an explicit\n// `label=\"…\"` attribute on the opener so the rendered sandbox carries\n// a caller-supplied label (e.g., \"Pulled from /r/foo\") shown as a\n// strip above the body. The label is sanitized so it cannot inject\n// HTML or break out of the attribute value:\n//\n//   - NUL bytes are dropped.\n//   - Other control characters (U+0000–U+001F, U+007F) become spaces.\n//   - `\u0026`, `\u003c`, `\u003e`, and `\"` are replaced with their HTML entities.\n//   - Leading/trailing whitespace is trimmed.\n//\n// A label that is empty after sanitization behaves identically to\n// Foreign: no attribute is emitted, and the renderer shows the sandbox\n// box with NO label strip (there is no default label text).\nfunc ForeignWithLabel(label, body string) string {\n\treturn wrapForeign(label, body)\n}\n\n// MaxBlocksPerRender is gnoweb's per-render cap on the number of\n// \u003cgno-foreign\u003e blocks a single page render admits; beyond it, later\n// blocks fall through to raw HTML and are dropped. A realm emitting\n// many foreign blocks (e.g. one per comment) should keep its rendered\n// total under this. Re-exports chain/markdown.MaxForeignBlocksPerConvert\n// — the single source of truth the gnoweb renderer also reads — so\n// callers get the cap without importing chain/markdown directly.\nfunc MaxBlocksPerRender() int {\n\treturn markdown.MaxForeignBlocksPerConvert()\n}\n\nfunc wrapForeign(rawLabel, body string) string {\n\tlabel := sanitizeLabel(rawLabel)\n\n\t// Normalize line endings (CR/CRLF → LF). The parser matches the\n\t// sentinel close against \\n-delimited lines, so mixed line endings\n\t// would otherwise shift the match boundary. CR/CRLF → LF ONLY: do\n\t// not fold Unicode separators here — they must stay verbatim in the\n\t// body so the inner renderer sees the foreign markdown unaltered.\n\tbody = markdown.NormalizeBreaks(body)\n\n\t// Mangle any line that would terminate the outer block or open\n\t// an inner one. Covers bare and attribute-bearing forms of both\n\t// the opener and the closer (see step 2 in the package doc).\n\tvar b strings.Builder\n\t// b accumulates only the body lines (the opener/closer envelope is\n\t// concatenated separately below), so len(body) is the exact size in\n\t// the common case. Sentinel lines that expand `\u003c`→`\u0026lt;` may force\n\t// one growth — rare enough not to pre-size for.\n\tb.Grow(len(body))\n\tlines := strings.Split(body, \"\\n\")\n\tfor i, line := range lines {\n\t\tif isForeignSentinelLine(trimSentinel(line)) {\n\t\t\t// Escape just the leading `\u003c` so the html tokenizer\n\t\t\t// sees this as text instead of a tag. Preserve any 0-3\n\t\t\t// leading spaces the parser's trim would have stripped.\n\t\t\tidx := strings.Index(line, \"\u003c\")\n\t\t\tif idx \u003e= 0 {\n\t\t\t\tline = line[:idx] + \"\u0026lt;\" + line[idx+1:]\n\t\t\t}\n\t\t}\n\t\tb.WriteString(line)\n\t\tif i \u003c len(lines)-1 {\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\t}\n\n\topener := \"\u003cgno-foreign\u003e\"\n\tif label != \"\" {\n\t\topener = `\u003cgno-foreign label=\"` + label + `\"\u003e`\n\t}\n\treturn \"\\n\\n\" + opener + \"\\n\" + b.String() + \"\\n\u003c/gno-foreign\u003e\\n\\n\"\n}\n\n// sanitizeLabel makes a user-supplied label safe to splice into an\n// HTML attribute value on the gno-foreign opener line.\nfunc sanitizeLabel(s string) string {\n\t// Strip bidi-override and zero-width controls FIRST — same ordering\n\t// as the sanitize package's HTMLEscape — so invisible reordering or\n\t// zero-width payloads can't survive into the rendered label.\n\ts = markdown.StripBidiAndZeroWidth(s)\n\t// Drop NUL; map other ASCII controls AND the Unicode line/paragraph\n\t// separators (U+2028, U+2029, U+0085 NEL) to spaces. The opener is a\n\t// single line, so any of these surviving in the label would either\n\t// add a control payload or, for the separators, render as a stray\n\t// line break inside the attribute.\n\ts = strings.Map(func(r rune) rune {\n\t\tif r == 0 {\n\t\t\treturn -1\n\t\t}\n\t\tif r \u003c 0x20 || r == 0x7f || r == 0x2028 || r == 0x2029 || r == 0x0085 {\n\t\t\treturn ' '\n\t\t}\n\t\treturn r\n\t}, s)\n\t// Escape `\u0026` first so subsequent entity bytes don't get\n\t// re-escaped.\n\ts = strings.ReplaceAll(s, \"\u0026\", \"\u0026amp;\")\n\ts = strings.ReplaceAll(s, `\"`, \"\u0026quot;\")\n\ts = strings.ReplaceAll(s, \"\u003c\", \"\u0026lt;\")\n\ts = strings.ReplaceAll(s, \"\u003e\", \"\u0026gt;\")\n\treturn strings.TrimSpace(s)\n}\n\n// isForeignSentinelLine reports whether s (already trimmed via\n// trimSentinel) begins with the gno-foreign tag prefix and so must be\n// neutralized before it can reach the renderer-side parser.\n//\n// Deliberately OVER-INCLUSIVE: it matches any line whose trimmed form\n// starts (case-INSENSITIVELY) with `\u003cgno-foreign` or `\u003c/gno-foreign`,\n// regardless of what follows. This is a strict superset of every line\n// goldmark's html.Tokenizer can recognize as a \u003cgno-foreign\u003e opener or\n// closer, which is what makes it safe:\n//\n//   - The tokenizer lowercases tag names, so `\u003cGNO-FOREIGN\u003e` etc. are\n//     sentinels; the prefix match is case-folded to mirror that.\n//   - The tokenizer ends a tag name at ANY of several terminators\n//     (`\u003e`, space, tab, form-feed, `/`). A precise check that\n//     enumerates terminators keeps missing variants — e.g.\n//     `\u003c/gno-foreign/\u003e` and `\u003c/gno-foreign\\f\u003e` are both recognized as\n//     closers by the parser. Matching on the prefix alone cannot miss\n//     one: if a body line could be parsed as a sentinel, it starts with\n//     this prefix and is escaped here.\n//\n// The only cost is that an unrelated longer tag like `\u003cgno-foreignx\u003e`\n// (a different tag name, not a sentinel) is also escaped — rendered as\n// visible literal text instead of being raw-HTML-stripped — which is\n// harmless for foreign body bytes.\nfunc isForeignSentinelLine(s string) bool {\n\treturn hasASCIIFoldPrefix(s, \"\u003c/gno-foreign\") || hasASCIIFoldPrefix(s, \"\u003cgno-foreign\")\n}\n\n// hasASCIIFoldPrefix reports whether s begins with prefix, comparing\n// ASCII letters case-insensitively. prefix must be lowercase ASCII;\n// folding is ASCII-only on purpose (Unicode case folding would\n// over-match, and the sentinel envelope is pure ASCII anyway).\nfunc hasASCIIFoldPrefix(s, prefix string) bool {\n\tif len(s) \u003c len(prefix) {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(prefix); i++ {\n\t\tc := s[i]\n\t\tif c \u003e= 'A' \u0026\u0026 c \u003c= 'Z' {\n\t\t\tc += 'a' - 'A'\n\t\t}\n\t\tif c != prefix[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// trimSentinel returns line with the leading 0-3 spaces and trailing\n// ASCII whitespace that the parser's trimForeignLine strips. Mirrors\n// the byte-level trim the parser performs so this helper detects the\n// same sentinel match the parser would.\nfunc trimSentinel(s string) string {\n\ti := 0\n\tfor i \u003c len(s) \u0026\u0026 i \u003c 3 \u0026\u0026 s[i] == ' ' {\n\t\ti++\n\t}\n\ts = s[i:]\n\tfor len(s) \u003e 0 {\n\t\tc := s[len(s)-1]\n\t\tif c == ' ' || c == '\\t' || c == '\\n' || c == '\\v' || c == '\\f' || c == '\\r' {\n\t\t\ts = s[:len(s)-1]\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn s\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/markdown/foreign/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"counter","path":"gno.land/r/demo/counter","files":[{"name":"counter.gno","body":"package counter\n\nimport \"strconv\"\n\nvar counter int\n\nfunc Increment(_ realm) int {\n\tcounter++\n\treturn counter\n}\n\nfunc Render(_ string) string {\n\treturn strconv.Itoa(counter)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/counter\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"ingester","path":"gno.land/p/demo/gnorkle/ingester/v0","files":[{"name":"errors.gno","body":"package ingester\n\nimport \"errors\"\n\nvar ErrUndefined = errors.New(\"ingester undefined\")\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/ingester/v0\"\ngno = \"0.9\"\n"},{"name":"type.gno","body":"package ingester\n\n// Type indicates an ingester type.\ntype Type int\n\nconst (\n\t// TypeSingle indicates an ingester that can only ingest a single within a given period or no period.\n\tTypeSingle Type = iota\n\t// TypeMulti indicates an ingester that can ingest multiple within a given period or no period\n\tTypeMulti\n)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"profile","path":"gno.land/r/demo/profile","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/profile\"\ngno = \"0.9\"\n"},{"name":"profile.gno","body":"package profile\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar (\n\tfields = avl.NewTree()\n\trouter = mux.NewRouter()\n)\n\n// Standard fields\nconst (\n\tDisplayName        = \"DisplayName\"\n\tHomepage           = \"Homepage\"\n\tBio                = \"Bio\"\n\tAge                = \"Age\"\n\tLocation           = \"Location\"\n\tAvatar             = \"Avatar\"\n\tGravatarEmail      = \"GravatarEmail\"\n\tAvailableForHiring = \"AvailableForHiring\"\n\tInvalidField       = \"InvalidField\"\n)\n\n// Events\nconst (\n\tProfileFieldCreated = \"ProfileFieldCreated\"\n\tProfileFieldUpdated = \"ProfileFieldUpdated\"\n)\n\n// Field types used when emitting event\nconst FieldType = \"FieldType\"\n\nconst (\n\tBoolField   = \"BoolField\"\n\tStringField = \"StringField\"\n\tIntField    = \"IntField\"\n)\n\nfunc init() {\n\trouter.HandleFunc(\"\", homeHandler)\n\trouter.HandleFunc(\"u/{addr}\", profileHandler)\n\trouter.HandleFunc(\"f/{addr}/{field}\", fieldHandler)\n}\n\n// List of supported string fields\nvar stringFields = map[string]bool{\n\tDisplayName:   true,\n\tHomepage:      true,\n\tBio:           true,\n\tLocation:      true,\n\tAvatar:        true,\n\tGravatarEmail: true,\n}\n\n// List of support int fields\nvar intFields = map[string]bool{\n\tAge: true,\n}\n\n// List of support bool fields\nvar boolFields = map[string]bool{\n\tAvailableForHiring: true,\n}\n\n// Setters\n\nfunc SetStringField(cur realm, field, value string) bool {\n\taddr := cur.Previous().Address()\n\tkey := addr.String() + \":\" + field\n\tupdated := fields.Set(key, value)\n\n\tevent := ProfileFieldCreated\n\tif updated {\n\t\tevent = ProfileFieldUpdated\n\t}\n\n\tchain.Emit(event, FieldType, StringField, field, value)\n\n\treturn updated\n}\n\nfunc SetIntField(cur realm, field string, value int) bool {\n\taddr := cur.Previous().Address()\n\tkey := addr.String() + \":\" + field\n\tupdated := fields.Set(key, value)\n\n\tevent := ProfileFieldCreated\n\tif updated {\n\t\tevent = ProfileFieldUpdated\n\t}\n\n\tchain.Emit(event, FieldType, IntField, field, string(value))\n\n\treturn updated\n}\n\nfunc SetBoolField(cur realm, field string, value bool) bool {\n\taddr := cur.Previous().Address()\n\tkey := addr.String() + \":\" + field\n\tupdated := fields.Set(key, value)\n\n\tevent := ProfileFieldCreated\n\tif updated {\n\t\tevent = ProfileFieldUpdated\n\t}\n\n\tchain.Emit(event, FieldType, BoolField, field, ufmt.Sprintf(\"%t\", value))\n\n\treturn updated\n}\n\n// Getters\n\nfunc GetStringField(addr address, field, def string) string {\n\tkey := addr.String() + \":\" + field\n\tif value := fields.Get(key); value != nil {\n\t\treturn value.(string)\n\t}\n\n\treturn def\n}\n\nfunc GetBoolField(addr address, field string, def bool) bool {\n\tkey := addr.String() + \":\" + field\n\tif value := fields.Get(key); value != nil {\n\t\treturn value.(bool)\n\t}\n\n\treturn def\n}\n\nfunc GetIntField(addr address, field string, def int) int {\n\tkey := addr.String() + \":\" + field\n\tif value := fields.Get(key); value != nil {\n\t\treturn value.(int)\n\t}\n\n\treturn def\n}\n"},{"name":"render.gno","body":"package profile\n\nimport (\n\t\"bytes\"\n\t\"net/url\"\n\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\tBaseURL           = \"/r/demo/profile\"\n\tSetStringFieldURL = BaseURL + \"$help\u0026func=SetStringField\u0026field=%s\"\n\tSetIntFieldURL    = BaseURL + \"$help\u0026func=SetIntField\u0026field=%s\"\n\tSetBoolFieldURL   = BaseURL + \"$help\u0026func=SetBoolField\u0026field=%s\"\n\tViewAllFieldsURL  = BaseURL + \":u/%s\"\n\tViewFieldURL      = BaseURL + \":f/%s/%s\"\n)\n\nfunc homeHandler(res *mux.ResponseWriter, req *mux.Request) {\n\tvar b bytes.Buffer\n\n\tb.WriteString(\"## Setters\\n\")\n\tfor field := range stringFields {\n\t\tlink := ufmt.Sprintf(SetStringFieldURL, field)\n\t\tb.WriteString(ufmt.Sprintf(\"- [Set %s](%s)\\n\", field, link))\n\t}\n\n\tfor field := range intFields {\n\t\tlink := ufmt.Sprintf(SetIntFieldURL, field)\n\t\tb.WriteString(ufmt.Sprintf(\"- [Set %s](%s)\\n\", field, link))\n\t}\n\n\tfor field := range boolFields {\n\t\tlink := ufmt.Sprintf(SetBoolFieldURL, field)\n\t\tb.WriteString(ufmt.Sprintf(\"- [Set %s Field](%s)\\n\", field, link))\n\t}\n\n\tb.WriteString(\"\\n---\\n\\n\")\n\n\tres.Write(b.String())\n}\n\nfunc profileHandler(res *mux.ResponseWriter, req *mux.Request) {\n\tvar b bytes.Buffer\n\taddr := req.GetVar(\"addr\")\n\n\tb.WriteString(ufmt.Sprintf(\"# Profile %s\\n\", addr))\n\n\taddress_XXX := address(addr)\n\n\tfor field := range stringFields {\n\t\tvalue := GetStringField(address_XXX, field, \"n/a\")\n\t\tlink := ufmt.Sprintf(SetStringFieldURL, field)\n\t\tb.WriteString(ufmt.Sprintf(\"- %s: %s [Edit](%s)\\n\", field, value, link))\n\t}\n\n\tfor field := range intFields {\n\t\tvalue := GetIntField(address_XXX, field, 0)\n\t\tlink := ufmt.Sprintf(SetIntFieldURL, field)\n\t\tb.WriteString(ufmt.Sprintf(\"- %s: %d [Edit](%s)\\n\", field, value, link))\n\t}\n\n\tfor field := range boolFields {\n\t\tvalue := GetBoolField(address_XXX, field, false)\n\t\tlink := ufmt.Sprintf(SetBoolFieldURL, field)\n\t\tb.WriteString(ufmt.Sprintf(\"- %s: %t [Edit](%s)\\n\", field, value, link))\n\t}\n\n\tres.Write(b.String())\n}\n\nfunc fieldHandler(res *mux.ResponseWriter, req *mux.Request) {\n\tvar b bytes.Buffer\n\taddr := req.GetVar(\"addr\")\n\tfield := req.GetVar(\"field\")\n\n\tb.WriteString(ufmt.Sprintf(\"# Field %s for %s\\n\", field, addr))\n\n\taddress_XXX := address(addr)\n\tvalue := \"n/a\"\n\tvar editLink string\n\n\tif _, ok := stringFields[field]; ok {\n\t\tvalue = ufmt.Sprintf(\"%s\", GetStringField(address_XXX, field, \"n/a\"))\n\t\teditLink = ufmt.Sprintf(SetStringFieldURL+\"\u0026addr=%s\u0026value=%s\", field, addr, url.QueryEscape(value))\n\t} else if _, ok := intFields[field]; ok {\n\t\tvalue = ufmt.Sprintf(\"%d\", GetIntField(address_XXX, field, 0))\n\t\teditLink = ufmt.Sprintf(SetIntFieldURL+\"\u0026addr=%s\u0026value=%s\", field, addr, value)\n\t} else if _, ok := boolFields[field]; ok {\n\t\tvalue = ufmt.Sprintf(\"%t\", GetBoolField(address_XXX, field, false))\n\t\teditLink = ufmt.Sprintf(SetBoolFieldURL+\"\u0026addr=%s\u0026value=%s\", field, addr, value)\n\t}\n\n\tb.WriteString(ufmt.Sprintf(\"- %s: %s [Edit](%s)\\n\", field, value, editLink))\n\n\tres.Write(b.String())\n}\n\nfunc Render(path string) string {\n\treturn router.Render(path)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"groups","path":"gno.land/p/nt/groups/v0","files":[{"name":"README.md","body":"# groups\n\nA `Group` is a set of addresses (the **base set**) plus any number of named\n**Roles**, each with its own member set and optional metadata. One `Group`\nper DAO, per board, per permissions instance — whatever your realm manages.\n\n```\nGroup\n├── base set:        the plain members (guests, users, council — you decide)\n└── roles\n    ├── \"admin\":     member set + meta\n    └── \"moderator\": member set + meta\n```\n\n## Quick start\n\n```go\nimport \"gno.land/p/nt/groups/v0\"\n\nvar group = groups.NewGroup()\n\nfunc init() {\n    // Base members.\n    group.Add(address(\"g1alice...\"))\n    group.Add(address(\"g1bob...\"))\n\n    // A role with its own members.\n    admins, _ := group.AddRole(\"admin\")\n    admins.Members().Add(address(\"g1carol...\"))\n}\n```\n\n## Three kinds of operations\n\nEvery membership operation belongs to exactly one family, so a call site\nalways says which semantic it means — checking the base set and checking\n\"anywhere in the group\" are different questions with different methods.\n\n| Family | Methods | Looks at |\n|---|---|---|\n| Base set | `Add`, `Remove`, `Has`, `Size`, `Iterate` | base set only |\n| Role registry | `AddRole`, `GetRole`, `HasRole`, `RemoveRole`, `RoleCount`, `IterateRoles` | the named roles |\n| Aggregated | `HasAny`, `TotalSize`, `IterateAll`, `RemoveFromAll` | base + every role, deduplicated |\n| Aggregated | `RolesContaining` | every role — base membership is not a role |\n\n(`NewGroup` and the `Readonly()` views sit outside the families; views are\ncovered below.)\n\nSo with alice in the base set only and dave in the \"council\" role only:\n\n```go\ngroup.Has(alice)  // true  — alice is a base member\ngroup.Has(dave)   // false — Has never consults roles\ngroup.HasAny(dave) // true — dave is somewhere in the group\ngroup.RolesContaining(dave) // [\"council\"]\n```\n\nAn address may appear in the base set and several roles at once;\n`TotalSize` and `IterateAll` count and yield it once. All iterators take\n`offset, count` for pagination, and the callback returns `true` to stop.\n\n`RemoveRole` discards only the role itself — its members stay wherever\nelse they appear. `RemoveFromAll` is the opposite: it purges one address\nfrom the base set and every role.\n\n## Sharing across realms: readonly views\n\nA `*Group` or `*Role` is a **mutable handle**: anyone holding it can change\nyour data (method calls run with the allocating realm's storage authority).\n`Readonly()` returns a view that structurally cannot mutate — no mutator\nmethods exist on it at all.\n\nThree rules at realm boundaries:\n\n1. **Never accept** a `*Group`/`*Role` from an untrusted caller.\n2. **Never return** a `*Group`/`*Role` to one — return\n   `group.Readonly()` (a `*ReadonlyGroup`) or `role.Readonly()` instead.\n3. **Never trust** a readonly view someone else hands you: it is a live\n   window onto *their* data, which they can change between your reads.\n\n## The `meta` slot\n\n`Role.SetMeta(meta any)` stores arbitrary per-role data — permission bits,\na description, a quorum. Store **value types only** (strings, ints, value\nstructs/slices). Do not store pointers to types with mutator methods (such\nas `*avl.Tree` or `*addrset.Set`): `Meta()` returns the value as-is, so a\nreader holding a readonly view could call those mutators on it.\n\nSee `doc.gno` for the precise security model, and\n`filetests/z_readme_filetest.gno` for this README as a running example.\n"},{"name":"doc.gno","body":"// Package groups provides Groups containing a base address set plus named\n// Roles, each with their own member set and metadata.\n//\n// A Group is the top-level container — one per DAO, one per permissions\n// instance, etc. A Role is a named subset within a Group with arbitrary\n// per-role metadata.\n//\n// The API separates three concerns explicitly, so each call site picks the\n// right semantic:\n//\n//   - base-only operations: Add, Remove, Has, Size, Iterate;\n//   - role registry operations: AddRole, GetRole, HasRole, RemoveRole,\n//     RoleCount, IterateRoles;\n//   - aggregated operations across base + all roles: HasAny, TotalSize,\n//     IterateAll, RolesContaining, RemoveFromAll.\n//\n// # Security model\n//\n// A Group, and the *Role values it hands out, are meant to be allocated and\n// held by the consuming realm. Three rules apply at realm boundaries:\n//\n//  1. Do not ACCEPT a *Group or *Role from an external/untrusted caller —\n//     subsequent mutations would route to the allocating (attacker)\n//     realm's authority, and a poisoned Group could cause DoS or\n//     unexpected state.\n//\n//  2. Do not RETURN a *Group or *Role from any method or function callable\n//     by untrusted realms. Return *ReadonlyGroup or *ReadonlyRole instead.\n//     Exposing a mutable handle is exactly as dangerous as accepting one.\n//\n//  3. Do not TRUST a *ReadonlyGroup or *ReadonlyRole received from an\n//     untrusted caller. A readonly view is a live handle over its creator's\n//     data, not a snapshot: the sender controls the contents and can mutate\n//     them between reads. Base authorization and accounting decisions only\n//     on views derived from a Group you allocated yourself.\n//\n// The Readonly() views are the only safe handles to cross a realm boundary —\n// safe to hand out, per rule 3 not blindly safe to consume.\n//\n// # Metadata: do not store mutable pointers\n//\n// Each Role has a free-form \"meta any\" slot. Meta() returns the stored\n// value as-is, so a pointer stored in meta can be retrieved by an untrusted\n// reader holding a Readonly() view. A direct field write through that\n// pointer is still blocked by the realm-ownership\n// gate, but invoking a MUTATOR METHOD on it (or passing it into a function\n// that mutates by argument) runs under whatever realm allocated it (borrow\n// rule #2) and commits the write. This includes common /p/ types such as\n// *addrset.Set and *avl.Tree — they are mutable pointers, not \"just data\".\n// Therefore store only:\n//\n//   - value types (ints, strings, value structs/slices with NO internal\n//     pointer reaching a mutator-bearing type), or\n//   - a wrapper whose only exported methods are read-only and which holds no\n//     externally-mutable pointer.\n//\n// # Readonly views\n//\n// Group and Role each expose a Readonly() method returning a typed\n// read-only view (ReadonlyGroup, ReadonlyRole; role member sets surface as\n// *addrset.ReadonlySet). The views are concrete structs with unexported\n// fields and only read-side exported methods, so cross-package callers\n// cannot mutate through them.\npackage groups\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/groups/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l\"\n"},{"name":"group.gno","body":"package groups\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/moul/addrset/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\nvar (\n\tErrRoleExists = errors.New(\"role already exists\")\n\tErrEmptyName  = errors.New(\"role name is required\")\n)\n\n// Group is a container with a base address set plus a registry of named\n// Roles. The zero value is not usable; construct with NewGroup.\n//\n// # Security\n//\n// A Group, and the *Role values it hands out, are meant to be allocated and\n// held by the consuming realm. Three rules apply at realm boundaries:\n//\n//  1. Do not ACCEPT a *Group or *Role from an external/untrusted caller —\n//     subsequent mutations would route to the allocating (attacker)\n//     realm's authority, and a poisoned Group could cause DoS or\n//     unexpected state.\n//\n//  2. Do not RETURN a *Group or *Role from any method or function callable\n//     by untrusted realms. Return *ReadonlyGroup or *ReadonlyRole instead.\n//\n//  3. Do not TRUST a *ReadonlyGroup or *ReadonlyRole received from an\n//     untrusted caller — it is a live handle over the sender's data, not a\n//     snapshot; the contents are attacker-controlled and can change between\n//     reads.\n//\n// Both directions matter: exposing a *Group to attacker code is as\n// dangerous as accepting one. The Readonly() views are the only safe\n// handles to cross a realm boundary.\ntype Group struct {\n\tbase  *addrset.Set\n\troles *bptree.BPTree // name -\u003e *Role\n}\n\n// NewGroup constructs an empty group.\nfunc NewGroup() *Group {\n\treturn \u0026Group{\n\t\tbase:  \u0026addrset.Set{},\n\t\troles: bptree.NewBPTree32(),\n\t}\n}\n\n// --- Base set ---\n//\n// All base methods operate ONLY on the base set; roles are never consulted.\n// Use the aggregated forms (HasAny, TotalSize, IterateAll, RemoveFromAll)\n// for views across base + roles.\n\n// Add inserts addr into the base set. Returns true if newly added.\nfunc (g *Group) Add(addr address) (added bool) {\n\treturn g.base.Add(addr)\n}\n\n// Remove deletes addr from the base set. Returns true if it was present.\nfunc (g *Group) Remove(addr address) (removed bool) {\n\treturn g.base.Remove(addr)\n}\n\n// Has reports whether addr is in the base set. It does NOT consult roles;\n// use HasAny for an aggregated check.\nfunc (g *Group) Has(addr address) bool {\n\treturn g.base.Has(addr)\n}\n\n// Size returns the number of addresses in the base set only.\nfunc (g *Group) Size() int {\n\treturn g.base.Size()\n}\n\n// Iterate walks the base set (only) in sorted order, starting at offset.\n// fn returns true to stop; Iterate returns true if stopped early.\nfunc (g *Group) Iterate(offset, count int, fn func(addr address) bool) (stopped bool) {\n\tg.base.IterateByOffset(offset, count, func(a address) bool {\n\t\tstopped = fn(a)\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n\n// --- Role registry ---\n\n// AddRole registers a new empty role. Returns ErrEmptyName if name is\n// empty, ErrRoleExists if a role of that name already exists.\nfunc (g *Group) AddRole(name string) (*Role, error) {\n\tif name == \"\" {\n\t\treturn nil, ErrEmptyName\n\t}\n\tif g.roles.Has(name) {\n\t\treturn nil, ErrRoleExists\n\t}\n\tr := newRole(name)\n\tg.roles.Set(name, r)\n\treturn r, nil\n}\n\n// GetRole returns the mutable role if it exists.\n//\n// SECURITY: the returned *Role exposes mutators (Members().Add/Remove,\n// SetMeta). Do not pass it to untrusted callers — use GetRole on a\n// *ReadonlyGroup for cross-realm exposure.\nfunc (g *Group) GetRole(name string) (r *Role, found bool) {\n\tr, found = g.roles.Get(name).(*Role)\n\treturn r, found\n}\n\n// HasRole reports whether a role with the given name exists.\nfunc (g *Group) HasRole(name string) bool {\n\treturn g.roles.Has(name)\n}\n\n// RemoveRole removes the named role and its membership records. Members of\n// the removed role are NOT removed from the base set or from any other\n// role; only this role's own data is discarded. Returns false if no such\n// role exists.\nfunc (g *Group) RemoveRole(name string) (removed bool) {\n\t_, removed = g.roles.Remove(name)\n\treturn removed\n}\n\n// RoleCount returns the number of registered roles.\nfunc (g *Group) RoleCount() int {\n\treturn g.roles.Size()\n}\n\n// IterateRoles walks roles in lexicographic name order, starting at offset\n// and visiting up to count roles. The callback receives a *ReadonlyRole —\n// deliberately not a *Role, so that plumbing an untrusted callback into the\n// iteration cannot escalate into role mutation under this realm's authority.\n// To mutate, capture names during iteration and revisit via GetRole from a\n// trusted context after iteration returns; registry mutation (AddRole,\n// RemoveRole) mid-iteration can panic and abort the transaction. fn returns\n// true to stop; IterateRoles returns true if stopped early.\nfunc (g *Group) IterateRoles(offset, count int, fn func(*ReadonlyRole) bool) (stopped bool) {\n\treturn g.roles.IterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn fn(value.(*Role).Readonly())\n\t})\n}\n\n// --- Aggregations across base + all roles ---\n\n// HasAny reports whether addr is in the base set OR in any role.\nfunc (g *Group) HasAny(addr address) bool {\n\tif g.base.Has(addr) {\n\t\treturn true\n\t}\n\tfound := false\n\tg.roles.IterateByOffset(0, g.roles.Size(), func(_ string, value any) bool {\n\t\tif value.(*Role).members.Has(addr) {\n\t\t\tfound = true\n\t\t\treturn true // stop\n\t\t}\n\t\treturn false\n\t})\n\treturn found\n}\n\n// TotalSize returns the count of distinct addresses across the base set and\n// all roles, deduplicated. A caller may place the same address in base and\n// in multiple roles; TotalSize counts it once.\n//\n// Implementation note: dedup tracks seen addresses in an internal addrset,\n// costing O(N) memory in the total membership.\nfunc (g *Group) TotalSize() int {\n\tn := 0\n\tg.visitDistinct(func(address) bool {\n\t\tn++\n\t\treturn false\n\t})\n\treturn n\n}\n\n// IterateAll walks every distinct address across base + all roles,\n// deduplicated. Order: base first (in addrset order), then roles in name\n// order, skipping addresses already yielded. offset and count apply to the\n// deduplicated output, not the pre-dedup items; a negative offset counts as\n// zero. fn returns true to stop; IterateAll returns true if stopped early.\n//\n// The walk is live: do not mutate the group (base set, member sets, or the\n// role registry) from within fn — registry mutation mid-iteration can panic\n// and abort the transaction. Collect addresses first, mutate after\n// IterateAll returns.\n//\n// Implementation note: dedup tracks seen addresses in an internal addrset\n// (O(N) memory in the addresses scanned); scanning stops as soon as the\n// requested window has been served. For paginating a large Group without\n// dedup, use Iterate (base only) or IterateRoles.\nfunc (g *Group) IterateAll(offset, count int, fn func(addr address) bool) (stopped bool) {\n\tif count \u003c= 0 {\n\t\treturn false\n\t}\n\tif offset \u003c 0 {\n\t\toffset = 0\n\t}\n\tseen := 0\n\tg.visitDistinct(func(a address) bool {\n\t\tif seen \u003c offset {\n\t\t\tseen++\n\t\t\treturn false\n\t\t}\n\t\tif fn(a) {\n\t\t\tstopped = true\n\t\t\treturn true\n\t\t}\n\t\tseen++\n\t\treturn seen-offset \u003e= count\n\t})\n\treturn stopped\n}\n\n// visitDistinct walks the base set then every role (in name order), calling\n// visit once per distinct address the first time it is seen. visit returns\n// true to stop the walk early.\nfunc (g *Group) visitDistinct(visit func(addr address) bool) {\n\tseen := \u0026addrset.Set{}\n\tdone := false\n\trecord := func(a address) bool {\n\t\tif !seen.Add(a) { // Add returns false when already seen\n\t\t\treturn false\n\t\t}\n\t\tdone = visit(a)\n\t\treturn done\n\t}\n\tg.base.IterateByOffset(0, g.base.Size(), record)\n\tif done {\n\t\treturn\n\t}\n\tg.roles.IterateByOffset(0, g.roles.Size(), func(_ string, value any) bool {\n\t\tr := value.(*Role)\n\t\tr.members.IterateByOffset(0, r.members.Size(), record)\n\t\treturn done\n\t})\n}\n\n// RolesContaining returns the names of all roles containing addr, in\n// lexicographic name order. The base set is not consulted (base membership\n// is not a \"role\"). Returns nil if addr is in no roles.\nfunc (g *Group) RolesContaining(addr address) []string {\n\tvar names []string\n\tg.roles.IterateByOffset(0, g.roles.Size(), func(name string, value any) bool {\n\t\tif value.(*Role).members.Has(addr) {\n\t\t\tnames = append(names, name)\n\t\t}\n\t\treturn false\n\t})\n\treturn names\n}\n\n// RemoveFromAll removes addr from the base set and from every role. Returns\n// true if it was removed from at least one location.\nfunc (g *Group) RemoveFromAll(addr address) (removed bool) {\n\tif g.base.Remove(addr) {\n\t\tremoved = true\n\t}\n\tg.roles.IterateByOffset(0, g.roles.Size(), func(_ string, value any) bool {\n\t\tif value.(*Role).members.Remove(addr) {\n\t\t\tremoved = true\n\t\t}\n\t\treturn false\n\t})\n\treturn removed\n}\n\n// Readonly returns a read-only view of the group.\nfunc (g *Group) Readonly() *ReadonlyGroup {\n\treturn \u0026ReadonlyGroup{group: g}\n}\n"},{"name":"readonly.gno","body":"package groups\n\nimport \"gno.land/p/moul/addrset/v0\"\n\n// ReadonlyRole is a read-only view of a Role. It exposes only read-side\n// methods and holds the *Role in an unexported field, so cross-package\n// callers cannot mutate the role through this type.\ntype ReadonlyRole struct {\n\trole *Role\n}\n\n// Name returns the role's name.\nfunc (rr ReadonlyRole) Name() string {\n\treturn rr.role.name\n}\n\n// Members returns a read-only view of the role's member set.\nfunc (rr ReadonlyRole) Members() *addrset.ReadonlySet {\n\treturn rr.role.members.Readonly()\n}\n\n// Meta returns the role's metadata slot.\n//\n// NOTE: a mutable pointer stored in meta is NOT protected by this readonly\n// view — the pointee remains mutable by anyone who retrieves it. See the\n// package doc.\nfunc (rr ReadonlyRole) Meta() any {\n\treturn rr.role.meta\n}\n\n// ReadonlyGroup is a read-only view of a Group. Every method mirrors the\n// read-side of Group; mutators are absent. It holds the *Group in an\n// unexported field, so cross-package callers cannot mutate through it.\ntype ReadonlyGroup struct {\n\tgroup *Group\n}\n\n// --- Base set (base only) ---\n\n// Has reports whether addr is in the base set (roles not consulted).\nfunc (rg ReadonlyGroup) Has(addr address) bool {\n\treturn rg.group.Has(addr)\n}\n\n// Size returns the number of addresses in the base set only.\nfunc (rg ReadonlyGroup) Size() int {\n\treturn rg.group.Size()\n}\n\n// Iterate walks the base set (only); see Group.Iterate.\nfunc (rg ReadonlyGroup) Iterate(offset, count int, fn func(addr address) bool) (stopped bool) {\n\treturn rg.group.Iterate(offset, count, fn)\n}\n\n// --- Role registry ---\n\n// GetRole returns a read-only view of the named role if it exists.\nfunc (rg ReadonlyGroup) GetRole(name string) (rr *ReadonlyRole, found bool) {\n\tr, ok := rg.group.GetRole(name)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn r.Readonly(), true\n}\n\n// HasRole reports whether a role with the given name exists.\nfunc (rg ReadonlyGroup) HasRole(name string) bool {\n\treturn rg.group.HasRole(name)\n}\n\n// RoleCount returns the number of registered roles.\nfunc (rg ReadonlyGroup) RoleCount() int {\n\treturn rg.group.RoleCount()\n}\n\n// IterateRoles walks roles in name order; see Group.IterateRoles.\nfunc (rg ReadonlyGroup) IterateRoles(offset, count int, fn func(*ReadonlyRole) bool) (stopped bool) {\n\treturn rg.group.IterateRoles(offset, count, fn)\n}\n\n// --- Aggregations ---\n\n// HasAny reports whether addr is in the base set OR in any role.\nfunc (rg ReadonlyGroup) HasAny(addr address) bool {\n\treturn rg.group.HasAny(addr)\n}\n\n// TotalSize returns the deduplicated count across base + all roles.\nfunc (rg ReadonlyGroup) TotalSize() int {\n\treturn rg.group.TotalSize()\n}\n\n// IterateAll walks every distinct address across base + all roles; see\n// Group.IterateAll.\nfunc (rg ReadonlyGroup) IterateAll(offset, count int, fn func(addr address) bool) (stopped bool) {\n\treturn rg.group.IterateAll(offset, count, fn)\n}\n\n// RolesContaining returns the names of all roles containing addr, in name\n// order; see Group.RolesContaining.\nfunc (rg ReadonlyGroup) RolesContaining(addr address) []string {\n\treturn rg.group.RolesContaining(addr)\n}\n"},{"name":"role.gno","body":"package groups\n\nimport \"gno.land/p/moul/addrset/v0\"\n\n// Role is a named bucket of addresses with optional metadata.\n//\n// A Role is always owned by a parent Group; the only way to obtain a *Role\n// is Group.AddRole or Group.GetRole. See the Group doc for the realm-\n// boundary rules that govern passing *Role values around.\ntype Role struct {\n\tname    string\n\tmembers *addrset.Set\n\tmeta    any\n}\n\n// newRole constructs a new empty role with the given name. Unexported: the\n// only valid path to a *Role is via Group.AddRole, which registers it in\n// the parent Group's role registry. A detached Role has no useful API.\nfunc newRole(name string) *Role {\n\treturn \u0026Role{\n\t\tname:    name,\n\t\tmembers: \u0026addrset.Set{},\n\t}\n}\n\n// Name returns the role's registry name.\nfunc (r *Role) Name() string {\n\treturn r.name\n}\n\n// Members returns a mutable reference to the role's member set; mutations\n// through the returned pointer affect the role.\n//\n// SECURITY: the returned *addrset.Set is mutable. Do not expose it to\n// untrusted callers — use Role.Readonly().Members() for a\n// cross-realm-safe view.\nfunc (r *Role) Members() *addrset.Set {\n\treturn r.members\n}\n\n// Meta returns the role's metadata slot. See the package doc for the rule\n// against storing mutable pointers in meta.\nfunc (r *Role) Meta() any {\n\treturn r.meta\n}\n\n// SetMeta sets the role's metadata slot. Passing nil clears it.\n//\n// SECURITY: do NOT store a pointer whose type has a mutator method (this\n// includes common /p/ types like *addrset.Set or *avl.Tree) if untrusted\n// realms may hold a Readonly() view of this Group. Meta() returns the stored\n// value as-is, so a foreign reader can invoke that method and borrow rule #2\n// commits the write under this (the allocating) realm's authority. A direct\n// field write through the pointer is still blocked by the realm-ownership\n// gate — the leak is specifically mutator-method dispatch. Prefer value types\n// with no internal pointers. See the package doc.\nfunc (r *Role) SetMeta(meta any) {\n\tr.meta = meta\n}\n\n// Readonly returns a read-only view of the role.\nfunc (r *Role) Readonly() *ReadonlyRole {\n\treturn \u0026ReadonlyRole{role: r}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"permissions","path":"gno.land/p/gnoland/boards/exts/permissions/v0","files":[{"name":"README.md","body":"# Boards Permissions Extension\n\nThis is a `gno.land/p/gnoland/boards/v0` package extension that provides a custom\n`Permissions` implementation that uses an underlying `gno.land/p/nt/groups`\ngroup to manage users and roles.\n\nIt also supports optionally setting validation functions to be triggered by the\n`WithPermission()` method before a callback is called. Validators allows adding\ncustom checks and requirements before the callback is called.\n\nUsage Example:\n\n[embedmd]:# (example_test.gno go)\n```go\npackage permissions\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Example user account\nconst user address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\n// Define a role\nconst RoleExample boards.Role = \"example\"\n\n// Define a permission\nconst PermissionFoo boards.Permission = 42\n\nfunc ExamplePermission() {\n\t// Define a custom foo permission validation function\n\tvalidateFoo := func(_ boards.Permissions, args boards.Args) error {\n\t\t// Check that the first argument is the string \"bob\"\n\t\tif name, ok := args[0].(string); !ok || name != \"bob\" {\n\t\t\treturn errors.New(\"unauthorized\")\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Create a permissions instance and assign the custom validator to it\n\tperms := New()\n\tperms.ValidateFunc(PermissionFoo, validateFoo)\n\n\t// Add foo permission to example role\n\tperms.AddRole(RoleExample, PermissionFoo)\n\n\t// Add a guest user\n\tperms.SetUserRoles(user, RoleExample)\n\n\t// Call a permissioned callback\n\targs := boards.Args{\"bob\"}\n\tperms.WithPermission(user, PermissionFoo, args, func() {\n\t\tprintln(\"Hello Bob!\")\n\t})\n\n\t// Output:\n\t// Hello Bob!\n}\n```\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/gnoland/boards/exts/permissions/v0\"\ngno = \"0.9\"\n"},{"name":"options.gno","body":"package permissions\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Option configures permissions.\ntype Option func(*Permissions)\n\n// UseSingleUserRole configures permissions to only allow one role per user.\nfunc UseSingleUserRole() Option {\n\treturn func(p *Permissions) {\n\t\tp.singleUserRole = true\n\t}\n}\n\n// WithSuperRole configures permissions to have a super role.\n// A super role is the one that have all permissions.\n// This type of role doesn't need to be mapped to any permission.\nfunc WithSuperRole(r boards.Role) Option {\n\treturn func(p *Permissions) {\n\t\tif p.superRole != \"\" {\n\t\t\tpanic(\"permissions super role can be assigned only once\")\n\t\t}\n\n\t\tname := string(r)\n\t\tif strings.TrimSpace(name) == \"\" {\n\t\t\tpanic(\"permissions super role name is required\")\n\t\t}\n\n\t\tif _, err := p.group.AddRole(name); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tp.superRole = r\n\t}\n}\n"},{"name":"permissions.gno","body":"package permissions\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/groups/v0\"\n)\n\n// ValidatorFunc defines a function type for permissions validators.\n//\n// SECURITY: validators run inside WithPermission holding the live\n// Permissions value, with full mutation access (SetUserRoles, RemoveUser,\n// AddRole, ...) under the owning realm's authority. Register only functions\n// the owning realm controls, and never expose ValidateFunc or the\n// *Permissions value across a realm boundary.\ntype ValidatorFunc func(boards.Permissions, boards.Args) error\n\n// Permissions manages users, roles and permissions.\n//\n// This type is a default `gno.land/p/gnoland/boards/v0` package `Permissions`\n// implementation that handles boards users, roles and permissions using an\n// underlying groups.Group: the base set holds every user (guests included),\n// and each boards role is a group Role whose member set is kept a subset of\n// the base set, with the role's boards.PermissionSet stored in the role meta\n// (a value type, per the groups meta rule). It also supports optionally\n// setting validation functions to be triggered within `WithPermission()`\n// method before a permissioned callback is called.\n//\n// No permissions validation is done by default.\n//\n// Users are allowed to have multiple roles at the same time by default, but\n// permissions can be configured to only allow one role per user.\ntype Permissions struct {\n\tsuperRole      boards.Role\n\tgroup          *groups.Group\n\tpublic         boards.PermissionSet\n\tvalidators     *bptree.BPTree // string(boards.Permission) -\u003e ValidatorFunc\n\tsingleUserRole bool\n}\n\n// New creates a new permissions type.\nfunc New(options ...Option) *Permissions {\n\tps := \u0026Permissions{\n\t\tvalidators: bptree.NewBPTree32(),\n\t\tgroup:      groups.NewGroup(),\n\t}\n\n\tfor _, apply := range options {\n\t\tapply(ps)\n\t}\n\treturn ps\n}\n\n// ValidateFunc adds a custom permission validator function.\n// If an existing permission function exists it's overwritten by the new one.\nfunc (ps *Permissions) ValidateFunc(p boards.Permission, fn ValidatorFunc) {\n\tps.validators.Set(p.String(), fn)\n}\n\n// SetPublicPermissions assigns permissions that are available to anyone.\n// It removes previous public permissions and assigns the new ones.\n// By default there are no public permissions.\nfunc (ps *Permissions) SetPublicPermissions(permissions ...boards.Permission) {\n\tps.public = boards.NewPermissionSet(permissions...)\n}\n\n// AddRole adds a role with one or more assigned permissions.\n// If role exists its permissions are overwritten with the new ones.\nfunc (ps *Permissions) AddRole(r boards.Role, p boards.Permission, extra ...boards.Permission) {\n\tname := string(r)\n\tif strings.TrimSpace(name) == \"\" {\n\t\tpanic(\"role name is required\")\n\t}\n\n\t// If role is the super role it already has all permissions\n\tif ps.superRole == r {\n\t\treturn\n\t}\n\n\t// Get the role if it exists or otherwise register a new one\n\trole, found := ps.group.GetRole(name)\n\tif !found {\n\t\tvar err error\n\t\trole, err = ps.group.AddRole(name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Save permissions within the role meta overwriting any existing permissions\n\tpermissions := append([]boards.Permission{p}, extra...)\n\trole.SetMeta(boards.NewPermissionSet(permissions...))\n}\n\n// RoleExists checks if a role exists.\nfunc (ps Permissions) RoleExists(r boards.Role) bool {\n\treturn r == ps.superRole || ps.group.HasRole(string(r))\n}\n\n// GetUserRoles returns the list of roles assigned to a user.\nfunc (ps Permissions) GetUserRoles(user address) []boards.Role {\n\tnames := ps.group.RolesContaining(user)\n\tif names == nil {\n\t\treturn nil\n\t}\n\n\troles := make([]boards.Role, len(names))\n\tfor i, name := range names {\n\t\troles[i] = boards.Role(name)\n\t}\n\treturn roles\n}\n\n// HasRole checks if a user has a specific role assigned.\nfunc (ps Permissions) HasRole(user address, r boards.Role) bool {\n\trole, found := ps.group.GetRole(string(r))\n\tif !found {\n\t\treturn false\n\t}\n\treturn role.Members().Has(user)\n}\n\n// HasPermission checks if a user has a specific permission.\nfunc (ps Permissions) HasPermission(user address, perm boards.Permission) bool {\n\tif ps.public.Has(perm) {\n\t\treturn true\n\t}\n\n\tfor _, name := range ps.group.RolesContaining(user) {\n\t\tif ps.superRole == boards.Role(name) {\n\t\t\treturn true\n\t\t}\n\n\t\trole, found := ps.group.GetRole(name)\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\tif perms, ok := role.Meta().(boards.PermissionSet); ok \u0026\u0026 perms.Has(perm) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// SetUserRoles adds a new user when it doesn't exist and sets its roles.\n// Method can also be called to change the roles of an existing user.\n// It removes any existing user roles before assigning new ones.\n// All user's roles can be removed by calling this method without roles.\nfunc (ps *Permissions) SetUserRoles(user address, roles ...boards.Role) {\n\tif len(roles) \u003e 1 \u0026\u0026 ps.singleUserRole {\n\t\tpanic(\"user can only have one role\")\n\t}\n\n\t// Resolve every role name upfront so an invalid name panics before any\n\t// state is mutated.\n\tnewRoles := make([]*groups.Role, len(roles))\n\tfor i, r := range roles {\n\t\trole, found := ps.group.GetRole(string(r))\n\t\tif !found {\n\t\t\tpanic(\"invalid role: \" + string(r))\n\t\t}\n\t\tnewRoles[i] = role\n\t}\n\n\t// Clear current user roles\n\tfor _, name := range ps.group.RolesContaining(user) {\n\t\tif role, found := ps.group.GetRole(name); found {\n\t\t\trole.Members().Remove(user)\n\t\t}\n\t}\n\n\t// Every user is a base set member, with or without roles; role member\n\t// sets are kept subsets of the base set.\n\tps.group.Add(user)\n\n\t// Add user to role member sets\n\tfor _, role := range newRoles {\n\t\trole.Members().Add(user)\n\t}\n}\n\n// RemoveUser removes a user from permissions.\nfunc (ps *Permissions) RemoveUser(user address) bool {\n\treturn ps.group.RemoveFromAll(user)\n}\n\n// HasUser checks if a user exists.\nfunc (ps Permissions) HasUser(user address) bool {\n\treturn ps.group.Has(user)\n}\n\n// UsersCount returns the total number of users the permissioner contains.\nfunc (ps Permissions) UsersCount() int {\n\treturn ps.group.Size()\n}\n\n// IterateUsers iterates permissions' users.\nfunc (ps Permissions) IterateUsers(start, count int, fn boards.UsersIterFn) (stopped bool) {\n\treturn ps.group.Iterate(start, count, func(addr address) bool {\n\t\treturn fn(boards.User{\n\t\t\tAddress: addr,\n\t\t\tRoles:   ps.GetUserRoles(addr),\n\t\t})\n\t})\n}\n\n// WithPermission calls a callback when a user has a specific permission.\n// It panics on error or when a permission validator fails.\n// Callbacks are by default called when there is no validator function registered for the permission.\n// If a permission validation function exists it's called before calling the callback.\nfunc (ps *Permissions) WithPermission(user address, p boards.Permission, args boards.Args, cb func()) {\n\tif !ps.HasPermission(user, p) {\n\t\tpanic(\"unauthorized, user \" + user.String() + \" doesn't have the required permission\")\n\t}\n\n\t// Execute custom validation before calling the callback\n\tif v := ps.validators.Get(p.String()); v != nil {\n\t\terr := v.(ValidatorFunc)(ps, args)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tcb()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"pager","path":"gno.land/p/jeronimoalbi/pager/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/jeronimoalbi/pager/v0\"\ngno = \"0.9\"\n"},{"name":"pager.gno","body":"// Package pager provides pagination functionality through a generic pager implementation.\n//\n// Example usage:\n//\n//\timport (\n//\t    \"strconv\"\n//\t    \"strings\"\n//\n//\t    \"gno.land/p/jeronimoalbi/pager/v0\"\n//\t)\n//\n//\tfunc Render(path string) string {\n//\t    // Define the items to paginate\n//\t    items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n//\n//\t    // Create a pager that paginates 4 items at a time\n//\t    p, err := pager.New(path, len(items), pager.WithPageSize(4))\n//\t    if err != nil {\n//\t        panic(err)\n//\t    }\n//\n//\t    // Render items for the current page\n//\t    var output strings.Builder\n//\t    p.Iterate(func(i int) bool {\n//\t        output.WriteString(\"- \" + strconv.Itoa(items[i]) + \"\\n\")\n//\t        return false\n//\t    })\n//\n//\t    // Render page picker\n//\t    if p.HasPages() {\n//\t        output.WriteString(\"\\n\" + pager.Picker(p))\n//\t    }\n//\n//\t    return output.String()\n//\t}\npackage pager\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar ErrInvalidPageNumber = errors.New(\"invalid page number\")\n\n// PagerIterFn defines a callback to iterate page items.\ntype PagerIterFn func(index int) (stop bool)\n\n// New creates a new pager.\nfunc New(rawURL string, totalItems int, options ...PagerOption) (Pager, error) {\n\tu, err := url.Parse(rawURL)\n\tif err != nil {\n\t\treturn Pager{}, err\n\t}\n\n\tp := Pager{\n\t\tquery:          u.RawQuery,\n\t\tpageQueryParam: DefaultPageQueryParam,\n\t\tpageSize:       DefaultPageSize,\n\t\tpage:           1,\n\t\ttotalItems:     totalItems,\n\t}\n\tfor _, apply := range options {\n\t\tapply(\u0026p)\n\t}\n\n\tp.pageCount = int(math.Ceil(float64(p.totalItems) / float64(p.pageSize)))\n\n\trawPage := u.Query().Get(p.pageQueryParam)\n\tif rawPage != \"\" {\n\t\tp.page, _ = strconv.Atoi(rawPage)\n\t\tif p.page == 0 || p.page \u003e p.pageCount {\n\t\t\treturn Pager{}, ErrInvalidPageNumber\n\t\t}\n\t}\n\n\treturn p, nil\n}\n\n// MustNew creates a new pager or panics if there is an error.\nfunc MustNew(rawURL string, totalItems int, options ...PagerOption) Pager {\n\tp, err := New(rawURL, totalItems, options...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn p\n}\n\n// Pager allows paging items.\ntype Pager struct {\n\tquery, pageQueryParam                 string\n\tpageSize, page, pageCount, totalItems int\n}\n\n// TotalItems returns the total number of items to paginate.\nfunc (p Pager) TotalItems() int {\n\treturn p.totalItems\n}\n\n// PageSize returns the size of each page.\nfunc (p Pager) PageSize() int {\n\treturn p.pageSize\n}\n\n// Page returns the current page number.\nfunc (p Pager) Page() int {\n\treturn p.page\n}\n\n// PageCount returns the number pages.\nfunc (p Pager) PageCount() int {\n\treturn p.pageCount\n}\n\n// Offset returns the index of the first page item.\nfunc (p Pager) Offset() int {\n\treturn (p.page - 1) * p.pageSize\n}\n\n// HasPages checks if pager has more than one page.\nfunc (p Pager) HasPages() bool {\n\treturn p.pageCount \u003e 1\n}\n\n// GetPageURI returns the URI for a page.\n// An empty string is returned when page doesn't exist.\nfunc (p Pager) GetPageURI(page int) string {\n\tif page \u003c 1 || page \u003e p.PageCount() {\n\t\treturn \"\"\n\t}\n\n\tvalues, _ := url.ParseQuery(p.query)\n\tvalues.Set(p.pageQueryParam, strconv.Itoa(page))\n\treturn \"?\" + values.Encode()\n}\n\n// PrevPageURI returns the URI path to the previous page.\n// An empty string is returned when current page is the first page.\nfunc (p Pager) PrevPageURI() string {\n\tif p.page == 1 || !p.HasPages() {\n\t\treturn \"\"\n\t}\n\treturn p.GetPageURI(p.page - 1)\n}\n\n// NextPageURI returns the URI path to the next page.\n// An empty string is returned when current page is the last page.\nfunc (p Pager) NextPageURI() string {\n\tif p.page == p.pageCount {\n\t\t// Current page is the last page\n\t\treturn \"\"\n\t}\n\treturn p.GetPageURI(p.page + 1)\n}\n\n// Iterate allows iterating page items.\nfunc (p Pager) Iterate(fn PagerIterFn) bool {\n\tif p.totalItems == 0 {\n\t\treturn true\n\t}\n\n\tstart := p.Offset()\n\tend := start + p.PageSize()\n\tif end \u003e p.totalItems {\n\t\tend = p.totalItems\n\t}\n\n\tfor i := start; i \u003c end; i++ {\n\t\tif fn(i) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// TODO: Support different types of pickers (ex. with clickable page numbers)\n\n// Picker returns a string with the pager as Markdown.\n// An empty string is returned when the pager has no pages.\nfunc Picker(p Pager) string {\n\tif !p.HasPages() {\n\t\treturn \"\"\n\t}\n\n\tvar out strings.Builder\n\n\tif s := p.PrevPageURI(); s != \"\" {\n\t\tout.WriteString(\"[«](\" + s + \") | \")\n\t} else {\n\t\tout.WriteString(\"\\\\- | \")\n\t}\n\n\tout.WriteString(\"page \" + strconv.Itoa(p.Page()) + \" of \" + strconv.Itoa(p.PageCount()))\n\n\tif s := p.NextPageURI(); s != \"\" {\n\t\tout.WriteString(\" | [»](\" + s + \")\")\n\t} else {\n\t\tout.WriteString(\" | \\\\-\")\n\t}\n\n\treturn out.String()\n}\n"},{"name":"pager_options.gno","body":"package pager\n\nimport \"strings\"\n\nconst (\n\tDefaultPageSize       = 50\n\tDefaultPageQueryParam = \"page\"\n)\n\n// PagerOption configures the pager.\ntype PagerOption func(*Pager)\n\n// WithPageSize assigns a page size to a pager.\nfunc WithPageSize(size int) PagerOption {\n\treturn func(p *Pager) {\n\t\tif size \u003c 1 {\n\t\t\tp.pageSize = DefaultPageSize\n\t\t} else {\n\t\t\tp.pageSize = size\n\t\t}\n\t}\n}\n\n// WithPageQueryParam assigns the name of the URL query param for the page value.\nfunc WithPageQueryParam(name string) PagerOption {\n\treturn func(p *Pager) {\n\t\tname = strings.TrimSpace(name)\n\t\tif name == \"\" {\n\t\t\tname = DefaultPageQueryParam\n\t\t}\n\t\tp.pageQueryParam = name\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"svgbtn","path":"gno.land/p/leon/svgbtn/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/leon/svgbtn/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\"\n"},{"name":"svgbtn.gno","body":"// Package svgbtn provides utilities for generating SVG-styled buttons as Markdown image links.\n//\n// Buttons are rendered as SVG images with customizable size, colors, labels, and links.\n// This package includes preconfigured styles such as Primary, Danger, Success, Small, Wide,\n// Text-like, and Icon buttons, as well as a factory method for dynamic button creation.\n//\n// Example usage:\n//\n//\tfunc Render(_ string) string {\n//\t\tbtn := svgbtn.PrimaryButton(120, 40, \"Click Me\", \"https://example.com\")\n//\t\treturn btn\n//\t}\n//\n// See more examples at gno.land/r/leon:buttons\n//\n// All buttons are returned as Markdown-compatible strings: [svg_data](link).\npackage svgbtn\n\nimport (\n\t\"gno.land/p/nt/svg/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Button creates a base SVG button with given size, colors, label, and link.\n// - `width`, `height`: size in pixels\n// - `btnColor`: background color (e.g. \"#007BFF\")\n// - `textColor`: label color (e.g. \"#FFFFFF\")\n// - `text`: visible button label\n// - `link`: URL to wrap the image in markdown-style [svg](link)\nfunc Button(width, height int, btnColor, textColor, text, link string) string {\n\treturn ButtonWithRadius(width, height, height/5, btnColor, textColor, text, link)\n}\n\n// ButtonWithRadius creates a base SVG button with custom border radius.\n// - `width`, `height`: size in pixels\n// - `radius`: border radius in pixels\n// - `btnColor`: background color (e.g. \"#007BFF\")\n// - `textColor`: label color (e.g. \"#FFFFFF\")\n// - `text`: visible button label\n// - `link`: URL to wrap the image in markdown-style [svg](link)\nfunc ButtonWithRadius(width, height, radius int, btnColor, textColor, text, link string) string {\n\tcanvas := svg.NewCanvas(width, height).\n\t\tWithViewBox(0, 0, width, height).\n\t\tAddStyle(\"text\", \"font-family:sans-serif;font-size:14px;text-anchor:middle;dominant-baseline:middle;\")\n\n\tbg := svg.NewRectangle(0, 0, width, height, btnColor)\n\tbg.RX = radius\n\tbg.RY = radius\n\n\tlabel := svg.NewText(width/2, height/2, text, textColor)\n\n\tcanvas.Append(bg, label)\n\n\treturn ufmt.Sprintf(\"[%s](%s)\", canvas.Render(text), link)\n}\n\n// PrimaryButton renders a blue button with white text.\nfunc PrimaryButton(width, height int, text, link string) string {\n\treturn Button(width, height, \"#007BFF\", \"#ffffff\", text, link)\n}\n\n// DangerButton renders a red button with white text.\nfunc DangerButton(width, height int, text, link string) string {\n\treturn Button(width, height, \"#DC3545\", \"#ffffff\", text, link)\n}\n\n// SuccessButton renders a green button with white text.\nfunc SuccessButton(width, height int, text, link string) string {\n\treturn Button(width, height, \"#28A745\", \"#ffffff\", text, link)\n}\n\n// SmallButton renders a compact gray button with white text.\nfunc SmallButton(width, height int, text, link string) string {\n\treturn Button(width, height, \"#6C757D\", \"#ffffff\", text, link)\n}\n\n// WideButton renders a wider cyan button with white text.\nfunc WideButton(width, height int, text, link string) string {\n\treturn Button(width, height, \"#17A2B8\", \"#ffffff\", text, link)\n}\n\n// TextButton renders a white button with colored text, like a hyperlink.\nfunc TextButton(width, height int, text, link string) string {\n\treturn Button(width, height, \"#ffffff\", \"#007BFF\", text, link)\n}\n\n// IconButton renders a square button with an icon character (e.g. emoji).\nfunc IconButton(width, height int, icon, link string) string {\n\treturn Button(width, height, \"#E0E0E0\", \"#000000\", icon, link)\n}\n\n// ButtonFactory provides a named-style constructor for buttons.\n// Supported kinds: \"primary\", \"danger\", \"success\", \"small\", \"wide\", \"text\", \"icon\".\nfunc ButtonFactory(kind string, width, height int, text, link string) string {\n\tswitch kind {\n\tcase \"primary\":\n\t\treturn PrimaryButton(width, height, text, link)\n\tcase \"danger\":\n\t\treturn DangerButton(width, height, text, link)\n\tcase \"success\":\n\t\treturn SuccessButton(width, height, text, link)\n\tcase \"small\":\n\t\treturn SmallButton(width, height, text, link)\n\tcase \"wide\":\n\t\treturn WideButton(width, height, text, link)\n\tcase \"text\":\n\t\treturn TextButton(width, height, text, link)\n\tcase \"icon\":\n\t\treturn IconButton(width, height, text, link)\n\tdefault:\n\t\treturn PrimaryButton(width, height, text, link)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"mdalert","path":"gno.land/p/nt/mdalert/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `mdalert` - Markdown alerts\n\nRender gnoweb-flavored Markdown alert blocks (note, tip, info, success, warning, caution) with optional title and folded mode.\n\n## Usage\n\n```go\nimport \"gno.land/p/nt/mdalert/v0\"\n\n// One-liner helpers per type\nmd := mdalert.Warning(\"Heads up\", \"Disk almost full\")\n\n// Formatted variants accept ufmt-style args\nmd = mdalert.Infof(\"Stats\", \"%d users online\", n)\n\n// Full control via the Alert struct (e.g. folded by default)\na := mdalert.New(mdalert.TypeTip, \"Click to expand\", \"Hidden details here\", true)\nmd = a.String()\n```\n\nRendered output (for the warning above):\n\n```\n\u003e [!WARNING] Heads up\n\u003e Disk almost full\n```\n\n## API\n\n```go\n// Type identifies an alert variant.\ntype Type string\n\nconst (\n    TypeCaution Type = \"CAUTION\"\n    TypeInfo         = \"INFO\"\n    TypeNote         = \"NOTE\"\n    TypeSuccess      = \"SUCCESS\"\n    TypeTip          = \"TIP\"\n    TypeWarning      = \"WARNING\"\n)\n\n// Alert is a Markdown alert block.\ntype Alert struct {\n    Type    Type   // Alert variant\n    Title   string // Optional title (header line)\n    Message string // Body; may contain newlines\n    Folded  bool   // If true, render collapsed (only title visible)\n}\n\n// String renders the alert as Markdown. Returns \"\" if Type is empty or Message is blank (whitespace only).\nfunc (a Alert) String() string\n\n// New builds an Alert.\nfunc New(t Type, title, msg string, folded bool) Alert\n\n// Per-type helpers (unfolded). The *f variants format msg with ufmt.Sprintf.\nfunc Caution(title, msg string) string\nfunc Cautionf(title, format string, a ...any) string\nfunc Info(title, msg string) string\nfunc Infof(title, format string, a ...any) string\nfunc Note(title, msg string) string\nfunc Notef(title, format string, a ...any) string\nfunc Success(title, msg string) string\nfunc Successf(title, format string, a ...any) string\nfunc Tip(title, msg string) string\nfunc Tipf(title, format string, a ...any) string\nfunc Warning(title, msg string) string\nfunc Warningf(title, format string, a ...any) string\n```\n\n## Notes\n\n- Alert types are documented in the Markdown docs realm: [/r/docs/markdown#alerts](/r/docs/markdown#alerts).\n- Per-type helpers always render unfolded. For folded alerts use `New(...)` with `folded=true`.\n- `title` and `msg` are emitted into Markdown as-is. When either carries untrusted input (a `Render(path)` segment, user text), wrap it with `sanitize.InlineText` from [`gno.land/p/nt/markdown/sanitize/v0`](../../markdown/sanitize/v0) first, or it can inject structure into the rendered page. The `*f` variants format via `ufmt.Sprintf`, which supports only ufmt's verb subset (no `%b`, `%o`, `%w`, `%+v`).\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package mdalert provides support for creating Markdown alerts.\npackage mdalert\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/mdalert/v0\"\ngno = \"0.9\"\n"},{"name":"mdalert.gno","body":"// Package mdalert provides support for creating Markdown alerts.\n//\n// It defines supported alert types and helper functions that can be\n// called to generate Markdown for different alert types.\n//\n// The different alert types are documented in the Markdown docs realm:\n// https://gno.land/r/docs/markdown#alerts\npackage mdalert\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Types of alerts.\nconst (\n\tTypeCaution Type = \"CAUTION\"\n\tTypeInfo         = \"INFO\"\n\tTypeNote         = \"NOTE\"\n\tTypeSuccess      = \"SUCCESS\"\n\tTypeTip          = \"TIP\"\n\tTypeWarning      = \"WARNING\"\n)\n\ntype (\n\t// Type defines a type for the alert types.\n\tType string\n\n\t// Alert defines a type for alerts.\n\tAlert struct {\n\t\t// Type defines the type of alert.\n\t\tType Type\n\n\t\t// Title contains an optional title for the alert.\n\t\tTitle string\n\n\t\t// Message contains alerts's message.\n\t\tMessage string\n\n\t\t// Folded indicates that the alert must be folded on render.\n\t\t// Message is not initially visible when folded, only title is visible.\n\t\tFolded bool\n\t}\n)\n\n// String returns the alert as a Markdown string.\nfunc (a Alert) String() string {\n\talertType := string(a.Type)\n\tmsg := strings.TrimSpace(a.Message)\n\tif msg == \"\" || alertType == \"\" {\n\t\treturn \"\"\n\t}\n\n\t// Init alert fold marker\n\tvar fold string\n\tif a.Folded {\n\t\tfold = \"-\"\n\t}\n\n\t// Write alert header\n\tvar b strings.Builder\n\theader := ufmt.Sprintf(\"\u003e [!%s]%s %s\", alertType, fold, a.Title)\n\tb.WriteString(strings.TrimSpace(header) + \"\\n\")\n\n\t// Write alert message\n\tlines := strings.Split(msg, \"\\n\")\n\tfor _, line := range lines {\n\t\tb.WriteString(\"\u003e \" + line + \"\\n\")\n\t}\n\treturn b.String()\n}\n\n// New creates a new alert.\nfunc New(t Type, title, msg string, folded bool) Alert {\n\treturn Alert{\n\t\tType:    t,\n\t\tTitle:   title,\n\t\tMessage: msg,\n\t\tFolded:  folded,\n\t}\n}\n\n// Caution returns an alert Markdown of type caution.\nfunc Caution(title, msg string) string {\n\treturn New(TypeCaution, title, msg, false).String()\n}\n\n// Cautionf returns an alert Markdown of type caution with a formatted message.\nfunc Cautionf(title, format string, a ...any) string {\n\treturn New(TypeCaution, title, ufmt.Sprintf(format, a...), false).String()\n}\n\n// Info returns an alert Markdown of type info.\nfunc Info(title, msg string) string {\n\treturn New(TypeInfo, title, msg, false).String()\n}\n\n// Infof returns an alert Markdown of type info with a formatted message.\nfunc Infof(title, format string, a ...any) string {\n\treturn New(TypeInfo, title, ufmt.Sprintf(format, a...), false).String()\n}\n\n// Note returns an alert Markdown of type note.\nfunc Note(title, msg string) string {\n\treturn New(TypeNote, title, msg, false).String()\n}\n\n// Notef returns an alert Markdown of type note with a formatted message.\nfunc Notef(title, format string, a ...any) string {\n\treturn New(TypeNote, title, ufmt.Sprintf(format, a...), false).String()\n}\n\n// Success returns an alert Markdown of type success.\nfunc Success(title, msg string) string {\n\treturn New(TypeSuccess, title, msg, false).String()\n}\n\n// Notef returns an alert Markdown of type success with a formatted message.\nfunc Successf(title, format string, a ...any) string {\n\treturn New(TypeSuccess, title, ufmt.Sprintf(format, a...), false).String()\n}\n\n// Tip returns an alert Markdown of type tip.\nfunc Tip(title, msg string) string {\n\treturn New(TypeTip, title, msg, false).String()\n}\n\n// Tipf returns an alert Markdown of type tip with a formatted message.\nfunc Tipf(title, format string, a ...any) string {\n\treturn New(TypeTip, title, ufmt.Sprintf(format, a...), false).String()\n}\n\n// Warning returns an alert Markdown of type warning.\nfunc Warning(title, msg string) string {\n\treturn New(TypeWarning, title, msg, false).String()\n}\n\n// Warningf returns an alert Markdown of type warning with a formatted message.\nfunc Warningf(title, format string, a ...any) string {\n\treturn New(TypeWarning, title, ufmt.Sprintf(format, a...), false).String()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"boards2","path":"gno.land/r/gnoland/boards2/v0","files":[{"name":"README.md","body":"# Boards2\n\nBoards2 is a social discussion forum for open communication and community-driven conversations.\n\nUsers can start discussions by creating or reposting threads and then submitting comments or replies to\nother user comments.\n\nDiscussions happen within different boards, where each board is an independent self managed community.\n\nBoards2 allows users to create two types of boards, one is the invite only board where only invited users\ncan create threads and comment, and where non invited users can only read the content and discussions; The\nother type of board is the open board where any user with a specific amount of GNOT in their account can\ncreate threads, repost and comment.\n\n## Open Boards Quick Start\n\nIf you are new to Gno.land in general, the quick start guide below can help you get started.\n\nWhat you need to create threads and start commenting within open boards is having a specific amount of GNOT\nin your Gno.land user account, which by default initially is 3000 GNOT. This initial GNOT amount could be\nchanged over time to a different amount, so this requirement can change.\n\n### How To Get a Gno.land Address\n\nTo use Boards2 you'll need a Gno.land address. You can quickly setup your account using [Adena] or any\nGno.land compatible wallet by following these steps:\n\n- Download [Adena], or a Gno.land compatible wallet\n- Once installed, you have to create a new account or add an existing one following wallet's instructions\n- If you don't have GNOT you will need to use a faucet to get some, if the network allows it\n\nFor testing networks you can use the official [Faucet Hub] to receive GNOT in your account.\n\n### How to Start Using Open Boards\n\nOnce you have the required GNOT amount in your account you can start commenting, creating and reposting\nthreads within any open board.\n\nTo comment and engage on an open board discussion visit a thread and click on the \"Comment\" link. You can\nalso reply to any of the thread's comments by clicking on the \"Reply\" link.\n\nTo create threads, visit an open board and then click on the \"Create Thread\" link, there you will have to\nenter a title and some content for the thread body.\n\nThread and comments content can be written as plaintext, or Markdown if you want to format the content so\nit's rendered as rich text.\n\nYou can also repost any thread, even the ones from invite only boards, into any open board. To do so visit\nthe thread you want to repost and click on the \"Repost\" link at the bottom of the thread, there you will have\nto enter the open board where you want the repost to be created, a title for the thread repost and optionally\nalso some content to render at the top of the repost. The optional content can also be written as plaintext\nor Markdown, like threads.\n\nAfter your thread, repost or comment is created, you can easily share the link with others so they can join\nthe discussion!\n\n## Boards\n\nBoards2 realm enables the creation of different communities though independent boards.\n\nWhen a board is created, and independetly of the board type, it initially has a single \"owner\" member\nassigned by default, which is the user that creates it. The member is called \"owner\" because by default it\nhas the `owner` role, which grants all permissions within that board.\n\nMembers of a board with the `owner` or `admin` role, independently of the board type, can invite other\nmembers, or otherwise users can request being invited to be a member by visiting the board and clicking the\n\"Request Invite\" link. Requested invites can be accepted or revoked though the board's \"Invite Requests\" view\nor using these public realm functions:\n\n```go\n// AcceptInvite accepts a board invite request.\nfunc AcceptInvite(_ realm, boardID boards.ID, user address)\n\n// RevokeInvite revokes a board invite request\nfunc RevokeInvite(_ realm, boardID boards.ID, user address)\n```\n\nThere are four possible roles that invited users can have when they are members of a board:\n- `owner`: Grants all available permissions\n- `admin`: Grants basic, moderator and advanced permissions, like being able to rename boards, add or remove\n   members, or change their role.\n- `moderator`: Grants basic and moderation related permissions, like being able to ban or unban users, or\n  flag content.\n- `guest`: Grants basic permissions that allow creating threads, reposting and commenting.\n\nDefault board configuration, permissions and roles are defined in the [permissions file].\n\nNo roles or number of members is enforced for boards, so technically a board can be updated to have no\nmembers, or for example, boards could exists without any \"owner\" if all members with `owner` role are removed\nfrom it.\n\nOther custom user defined roles can exists on top of the default ones though [custom board] implementations.\n\n### Custom Boards\n\nBoards2 realm allows users to customize the mechanics of their boards when the default ones doesn't make\nsense to that community, or when users want to integrate a board with their realms.\n\nAn example of this would be a case where thread creation should be allowed only though a new `publisher`\nrole, or a case where a community have their own DAO realm and governance implementation and are looking to\nintegrate it into their board mechanics by creating threads though proposals that must be approved for the\nthread to be published.\n\nEach board can customize the way it works by implementing the [Permissions] interface that is defined in the\n[gno.land/p/gnoland/boards/v0] package. It is though the implementation of that interface within a new realm\nthat the default board mechanics can be customized. The new realm can then be used to create an instance of\na custom `Permissions` implementation to replace the one assigned by default to a board.\n\nRight now only Boards2 realm `owner` members are allowed to change default board permissions using a public\nrealm function:\n\n```go\n// SetPermissions sets a permissions implementation for boards2 realm or a board\nfunc SetPermissions(_ realm, boardID boards.ID, p boards.Permissions)\n```\n\n\u003e This function will be replaced by a proposal that would need to pass for the custom permissions to be\n\u003e applied to a board once Boards2 governance is implemented.\n\n`Permissions` implementation allow communities to customize the way they want to manage users and roles,\nwhere or how they should be stored, and the requirements or effects different board actions have.\n\nBoards2 provides a custom `Permissions` implementation in [gno.land/r/gnoland/boards2/v0/permissions] that\ncan be imported by realms and used to implement custom boards.\n\n### Boards Governance\n\nBy default boards are created with an undelying DAO, so each new board is linked to an independent DAO which\nis used to organize members by role, and can also be used to update boards in a permissionless manner.\n\nRight now is possible to integrate with the underlying DAO and change the default board mechanics to rely on\nproposals using a [custom board] implementation, by creating a new realm that imports and uses the\n[gno.land/r/gnoland/boards2/v0/permissions] realm, which exposes the underlying DAO.\n\n\u003e Current Boards2 realm implementation doesn't run proposals, but some of the current mechanics will rely on\n\u003e DAO proposals to actually execute changes.\n\n## Moderation\n\n### Flagging\n\nThreads and comments are moderated by flagging, which requires the `moderator`, `admin` or `owner` roles.\n\nA reason is required each time content is flagged by a member. Content is replaced by a feedback message\nand a link to the list of flagging reasons given by moderators when a moderation flagging threshold is\nreached. By default the threshold is of a single flag.\n\n\u003e Right now is not possible to show the content of a thread or comment that has been hidden because of\n\u003e moderation, but future Boards2 versions might implement a way to handle moderation disputes and allow\n\u003e restoring the thread or comment content.\n\n\u003e Boards2 realm `owners` are allowed to moderate content with a single flag within any board at this point,\n\u003e but this might be changed to work though a DAO proposal.\n\nEach board's `owner` or `admin` members are free to change the flagging threshold within a single board to a\ngreater value using a public realm function:\n\n```go\n// SetFlaggingThreshold sets the number of flags required to hide a thread or comment\nfunc SetFlaggingThreshold(_ realm, boardID boards.ID, threshold int)\n```\n\n### Banning\n\nMembers with the `moderator`, `admin` or `owner` roles are the only ones that are allowed to ban or unban\na user within a board.\n\nUsers can be banned with a reason for any number of hours. Within this period banned users are not allowed\nto interact or make any changes.\n\nOnly invited `guest` members and open board users can be banned, banning board owners, admins and moderators\nis not allowed.\n\nBanning and unbanning can be done by calling these public realm functions:\n\n```go\n// Ban bans a user from a board for a period of time\nfunc Ban(_ realm, boardID boards.ID, user address, hours uint, reason string)\n\n// Unban unbans a user from a board\nfunc Unban(_ realm, boardID boards.ID, user address, reason string)\n```\n\n## Freezing\n\nBoards2 realm allows `owner` or `admin` members of a board to freeze the board or any of its threads.\nFreezing makes the board or thread readonly, disallowing any changes or additions until unfrozen.\n\nThe following public realm function can be called for freezing:\n\n```go\n// FreezeBoard freezes a board so no more threads and comments can be created or modified\nfunc FreezeBoard(_ realm, boardID boards.ID)\n\n// UnfreezeBoard removes frozen status from a board\nfunc UnfreezeBoard(_ realm, boardID boards.ID)\n\n// FreezeThread freezes a thread so thread cannot be replied, modified or deleted\nfunc FreezeThread(_ realm, boardID, threadID boards.ID)\n\n// UnfreezeThread removes frozen status from a thread\nfunc UnfreezeThread(_ realm, boardID, threadID boards.ID)\n```\n\n\n[permissions file]: https://gno.land/r/gnoland/boards2/v0$source\u0026file=permissions.gno\n[gno.land/r/gnoland/boards2/v0/permissions]: https://gno.land/r/gnoland/boards2/v0/permissions/\n[custom board]: #custom-boards\n[Adena]: https://www.adena.app/\n[Faucet Hub]: https://faucet.gno.land/\n[gno.land/p/gnoland/boards/v0]: https://gno.land/p/gnoland/boards/v0\n[Permissions]: https://gno.land/p/gnoland/boards/v0$source\u0026file=permissions.gno#L23\n"},{"name":"boards.gno","body":"package boards2\n\nimport (\n\t\"gno.land/p/gnoland/boards/exts/permissions/v0\"\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\nconst (\n\trealmPkgPath         = \"gno.land/r/gnoland/boards2/v0\"\n\tgRealmPath           = \"/r/gnoland/boards2/v0\"\n\tinitialOwner address = \"g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx\" // GovDAO T1 multisig\n)\n\nvar (\n\t// RealmLink contains Boards2 realm link.\n\t// It can be used to generate board TX links from other realms.\n\tRealmLink = txlink.Realm(realmPkgPath)\n\n\t// RequiredAccountAmount contains the required account amount for open board interactions.\n\t// The amount requirement is not applied to members that were invited to an open board.\n\t// Amount is defined as ugnot.\n\tRequiredAccountAmount = int64(3_000_000_000)\n\n\t// Notice contains an optional message that is displayed globally within the realm.\n\tNotice string\n\n\t// Help contains optional Markdown with Boards2 realm help.\n\tHelp string\n)\n\n// TODO: Refactor globals in favor of a cleaner pattern\nvar (\n\tgListedBoardsByID bptree.BPTree // string(id) -\u003e *boards.Board\n\tgInviteRequests   bptree.BPTree // string(board id) -\u003e *bptree.BPTree(address -\u003e time.Time)\n\tgBannedUsers      bptree.BPTree // string(board id) -\u003e *bptree.BPTree(address -\u003e time.Time)\n\tgLocked           struct {\n\t\trealm        bool\n\t\trealmMembers bool\n\t}\n)\n\nvar (\n\tgBoards         = boards.NewStorage()\n\tgBoardsSequence = boards.NewIdentifierGenerator()\n\tgPerms          = initRealmPermissions(initialOwner)\n)\n\n// initRealmPermissions returns the default realm permissions.\nfunc initRealmPermissions(owners ...address) boards.Permissions {\n\tperms := permissions.New(\n\t\tpermissions.UseSingleUserRole(),\n\t\tpermissions.WithSuperRole(RoleOwner),\n\t)\n\tperms.AddRole(RoleAdmin, PermissionBoardCreate)\n\tfor _, owner := range owners {\n\t\tperms.SetUserRoles(owner, RoleOwner)\n\t}\n\n\tperms.ValidateFunc(PermissionBoardCreate, validateBasicBoardCreate)\n\tperms.ValidateFunc(PermissionMemberInvite, validateBasicMemberInvite)\n\tperms.ValidateFunc(PermissionRoleChange, validateBasicRoleChange)\n\treturn perms\n}\n\nfunc init() {\n\taddBoard(gBoardsSequence.Next(), initialOwner, \"OpenDiscussions\", true, true)\n}\n\n// getInviteRequests returns invite requests for a board.\nfunc getInviteRequests(boardID boards.ID) (_ *bptree.BPTree, found bool) {\n\tv := gInviteRequests.Get(boardID.Key())\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*bptree.BPTree), true\n}\n\n// getBannedUsers returns banned users within a board.\nfunc getBannedUsers(boardID boards.ID) (_ *bptree.BPTree, found bool) {\n\tv := gBannedUsers.Get(boardID.Key())\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*bptree.BPTree), true\n}\n\n// mustGetBoardByName returns a board or panics when it's not found.\nfunc mustGetBoardByName(name string) *boards.Board {\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tpanic(\"board does not exist with name: \" + name)\n\t}\n\treturn board\n}\n\n// mustGetBoard returns a board or panics when it's not found.\nfunc mustGetBoard(id boards.ID) *boards.Board {\n\tboard, found := gBoards.Get(id)\n\tif !found {\n\t\tpanic(\"board does not exist with ID: \" + id.String())\n\t}\n\treturn board\n}\n\n// getThread returns a board thread.\nfunc getThread(board *boards.Board, threadID boards.ID) (*boards.Post, bool) {\n\tthread, found := board.Threads.Get(threadID)\n\tif !found {\n\t\t// When thread is not found search it within hidden threads\n\t\tmeta := board.Meta.(*BoardMeta)\n\t\tthread, found = meta.HiddenThreads.Get(threadID)\n\t}\n\treturn thread, found\n}\n\n// getReply returns a thread comment or reply.\nfunc getReply(thread *boards.Post, replyID boards.ID) (*boards.Post, bool) {\n\tmeta := thread.Meta.(*ThreadMeta)\n\treturn meta.AllReplies.Get(replyID)\n}\n\n// mustGetThread returns a thread or panics when it's not found.\nfunc mustGetThread(board *boards.Board, threadID boards.ID) *boards.Post {\n\tthread, found := getThread(board, threadID)\n\tif !found {\n\t\tpanic(\"thread does not exist with ID: \" + threadID.String())\n\t}\n\treturn thread\n}\n\n// mustGetReply returns a reply or panics when it's not found.\nfunc mustGetReply(thread *boards.Post, replyID boards.ID) *boards.Post {\n\treply, found := getReply(thread, replyID)\n\tif !found {\n\t\tpanic(\"reply does not exist with ID: \" + replyID.String())\n\t}\n\treturn reply\n}\n\nfunc mustGetPermissions(bid boards.ID) boards.Permissions {\n\tif bid != 0 {\n\t\tboard := mustGetBoard(bid)\n\t\treturn board.Permissions\n\t}\n\treturn gPerms\n}\n\nfunc parseRealmPath(path string) *realmpath.Request {\n\t// Make sure request is using current realm path so paths can be parsed during Render\n\tr := realmpath.Parse(path)\n\tr.Realm = string(RealmLink)\n\treturn r\n}\n"},{"name":"doc.gno","body":"// Boards2 is a social discussion forum for open communication and community-driven conversations.\n//\n// Users can start discussions by creating or reposting threads and then submitting comments or replies\n// to other user comments.\n//\n// Discussions happen within different boards, where each board is an independent self managed community.\n//\n// Boards2 allows users to create two types of boards:\n// - Invite Only: Only invited users (members) can create threads, reposts and comments.\n// - Open: Anyone with a specific amount of GNOT in their account can create threads, reposts and comments.\npackage boards2\n"},{"name":"flag.gno","body":"package boards2\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\n// DefaultFlaggingThreshold defines the default number of flags that hides flaggable items.\nconst DefaultFlaggingThreshold = 1\n\nvar gFlaggingThresholds bptree.BPTree // string(board ID) -\u003e int\n\n// flagItem adds a flag to a post.\n// Returns whether flag count threshold is reached and post can be hidden.\n// Panics if flag count threshold was already reached.\nfunc flagItem(post *boards.Post, user address, reason string, threshold int) bool {\n\tif post.Flags.Size() \u003e= threshold {\n\t\tpanic(\"flag count threshold exceeded: \" + strconv.Itoa(threshold))\n\t}\n\n\tif post.Flags.Exists(user) {\n\t\tpanic(\"post has been already flagged by \" + user.String())\n\t}\n\n\tpost.Flags.Add(boards.Flag{\n\t\tUser:   user,\n\t\tReason: reason,\n\t})\n\n\treturn post.Flags.Size() == threshold\n}\n\nfunc getFlaggingThreshold(bid boards.ID) int {\n\tif v := gFlaggingThresholds.Get(bid.String()); v != nil {\n\t\treturn v.(int)\n\t}\n\treturn DefaultFlaggingThreshold\n}\n"},{"name":"format.gno","body":"package boards2\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/markdown/foreign/v0\"\n\n\t\"gno.land/r/sys/users\"\n)\n\nconst dateFormat = \"2006-01-02 3:04pm MST\"\n\nfunc padLeft(s string, length int) string {\n\tif len(s) \u003e= length {\n\t\treturn s\n\t}\n\treturn strings.Repeat(\" \", length-len(s)) + s\n}\n\nfunc padZero(u64 uint64, length int) string {\n\ts := strconv.Itoa(int(u64))\n\tif len(s) \u003e= length {\n\t\treturn s\n\t}\n\treturn strings.Repeat(\"0\", length-len(s)) + s\n}\n\nfunc indentBody(indent string, body string) string {\n\tvar (\n\t\tres   string\n\t\tlines = strings.Split(body, \"\\n\")\n\t)\n\tfor i, line := range lines {\n\t\tif i \u003e 0 {\n\t\t\t// Add two spaces to keep newlines within Markdown\n\t\t\tres += \"  \\n\"\n\t\t}\n\t\tres += indent + line\n\t}\n\treturn res\n}\n\n// indentForeignBody is the single \"render a user body\" operation: it\n// sandboxes the body in a \u003cgno-foreign\u003e block, indents it like\n// indentBody, AND charges one unit against the per-render budget — so\n// wrapping and budget-accounting can't drift apart (the *int signals\n// the mutation). The body renders inside the sandbox: its block\n// structure (headings, blockquotes, lists, columns, alerts) is\n// contained and cannot hijack realm chrome, so boards no longer needs\n// the write-time markdown blacklist. The opener survives the \"\u003e \"\n// comment indentation at any depth (goldmark strips the \"\u003e \" prefix\n// before the block parser runs).\nfunc indentForeignBody(indent, body string, budget *int) string {\n\t*budget-- // one \u003cgno-foreign\u003e block\n\treturn indentBody(indent, foreign.Foreign(body))\n}\n\nfunc summaryOf(text string, length int) string {\n\tlines := strings.SplitN(text, \"\\n\", 2)\n\tline := lines[0]\n\tif len(line) \u003e length {\n\t\tline = line[:(length-3)] + \"...\"\n\t} else if len(lines) \u003e 1 {\n\t\tline = line + \"...\"\n\t}\n\treturn line\n}\n\nfunc userLink(addr address) string {\n\tif u := users.ResolveAddress(addr); u != nil {\n\t\treturn md.UserLink(u.Name())\n\t}\n\treturn md.UserLink(addr.String())\n}\n\nfunc getRoleBadge(post *boards.Post) string {\n\tif post == nil || post.Board == nil || post.Board.Permissions == nil {\n\t\treturn \"\"\n\t}\n\n\tperms := post.Board.Permissions\n\tcreator := post.Creator\n\n\t// Check roles in order of priority\n\tif perms.HasRole(creator, RoleOwner) {\n\t\treturn \" `owner`\"\n\t}\n\tif perms.HasRole(creator, RoleAdmin) {\n\t\treturn \" `admin`\"\n\t}\n\tif perms.HasRole(creator, RoleModerator) {\n\t\treturn \" `mod`\"\n\t}\n\treturn \"\"\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/gnoland/boards2/v0\"\ngno = \"0.9\"\n"},{"name":"hub.gno","body":"// The `hub.gno` file exposes safe, read-only views over the realm's\n// persistent state.\n//\n// Note for future maintainers: these reads perform no caller\n// authorization, so do not graft user-identity gating onto them.\n\npackage boards2\n\nimport (\n\thubexts \"gno.land/p/gnoland/boards/exts/hub/v0\"\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// Safe view types are defined in the hub extensions package and\n// re-exported here so callers can keep using them via this realm.\ntype (\n\tBoard   = hubexts.Board\n\tComment = hubexts.Comment\n\tFlag    = hubexts.Flag\n\tMember  = hubexts.Member\n\tThread  = hubexts.Thread\n)\n\n// GetBoard returns a safe board.\nfunc GetBoard(id uint64) (Board, bool) {\n\tb, found := gBoards.Get(boards.ID(id))\n\tif !found {\n\t\treturn Board{}, false\n\t}\n\treturn hubexts.NewSafeBoard(b), true\n}\n\n// GetThread returns a safe board thread.\nfunc GetThread(boardID, threadID uint64) (Thread, bool) {\n\tt, found := getBoardThread(boardID, threadID)\n\tif !found {\n\t\treturn Thread{}, false\n\t}\n\treturn hubexts.NewSafeThread(t), true\n}\n\n// GetComment returns a safe thread comment or reply.\n// `commentID` can be the ID of a top level comment or of a nested reply.\nfunc GetComment(boardID, threadID, commentID uint64) (Comment, bool) {\n\tc, found := getComment(boardID, threadID, commentID)\n\tif !found {\n\t\treturn Comment{}, false\n\t}\n\treturn hubexts.NewSafeComment(c), true\n}\n\n// GetBoards returns a list with all boards.\n// To reverse iterate use a negative count.\nfunc GetBoards(start, count int) []Board {\n\tvar boards_ []Board\n\tgBoards.Iterate(start, count, func(b *boards.Board) bool {\n\t\tboards_ = append(boards_, hubexts.NewSafeBoard(b))\n\t\treturn false\n\t})\n\treturn boards_\n}\n\n// GetThreads returns a list with threads of a board.\n// To reverse iterate use a negative count.\n// A board without thread storage has no threads, so nil is returned.\nfunc GetThreads(boardID uint64, start, count int) []Thread {\n\tb, found := gBoards.Get(boards.ID(boardID))\n\tif !found || b.Threads == nil {\n\t\treturn nil\n\t}\n\n\tvar threads []Thread\n\tb.Threads.Iterate(start, count, func(thread *boards.Post) bool {\n\t\tthreads = append(threads, hubexts.NewSafeThread(thread))\n\t\treturn false\n\t})\n\treturn threads\n}\n\n// GetMembers returns a list with the members of a board.\n// A zero `boardID` refers to the realm, so the realm admin users are returned.\n// A non permissioned board has no members, so nil is returned.\nfunc GetMembers(boardID uint64, start, count int) []Member {\n\tperms := gPerms\n\tif boardID != 0 {\n\t\tb, found := gBoards.Get(boards.ID(boardID))\n\t\tif !found {\n\t\t\treturn nil\n\t\t}\n\t\tperms = b.Permissions\n\t}\n\n\tif perms == nil {\n\t\treturn nil\n\t}\n\n\tvar members []Member\n\tperms.IterateUsers(start, count, func(u boards.User) bool {\n\t\tmembers = append(members, hubexts.NewSafeMember(u))\n\t\treturn false\n\t})\n\treturn members\n}\n\n// GetReposts returns a list with repost of a board thread.\n// To reverse iterate use a negative count.\n// A repost is not included when its destination thread has been deleted,\n// so the total accessible results can be shorter than the thread's RepostCount(),\n// and a single call can return fewer than count results.\n// (The reason for the discrepancy is that the start index can be large,\n// and this function cannot scan all reposts up to the start index to\n// resolve the discrepancy.)\nfunc GetReposts(boardID, threadID uint64, start, count int) []Thread {\n\tt, found := getBoardThread(boardID, threadID)\n\tif !found {\n\t\treturn nil\n\t}\n\n\tvar reposts []Thread\n\tt.Reposts.Iterate(start, count, func(rBoardID, rRepostID boards.ID) bool {\n\t\tr, found := getBoardThread(uint64(rBoardID), uint64(rRepostID))\n\t\tif found {\n\t\t\treposts = append(reposts, hubexts.NewSafeThread(r))\n\t\t}\n\t\treturn false\n\t})\n\treturn reposts\n}\n\n// GetFlags returns a list with thread or comment moderation flags.\n// To reverse iterate use a negative count.\n// Thread flags are returned when `commentID` is zero, or the flags of the\n// comment or reply with that ID are returned otherwise.\nfunc GetFlags(boardID, threadID, commentID uint64, start, count int) []Flag {\n\tvar storage boards.FlagStorage\n\tif commentID == 0 {\n\t\tt, found := getBoardThread(boardID, threadID)\n\t\tif !found {\n\t\t\treturn nil\n\t\t}\n\n\t\tstorage = t.Flags\n\t} else {\n\t\tc, found := getComment(boardID, threadID, commentID)\n\t\tif !found {\n\t\t\treturn nil\n\t\t}\n\n\t\tstorage = c.Flags\n\t}\n\n\tvar flags []Flag\n\tstorage.Iterate(start, count, func(f boards.Flag) bool {\n\t\tflags = append(flags, hubexts.NewSafeFlag(f))\n\t\treturn false\n\t})\n\treturn flags\n}\n\n// GetComments returns a list with top-level comments of a thread.\n// To reverse iterate use a negative count.\nfunc GetComments(boardID, threadID uint64, start, count int) []Comment {\n\tt, found := getBoardThread(boardID, threadID)\n\tif !found {\n\t\treturn nil\n\t}\n\n\tvar comments []Comment\n\t// Replies only has direct replies.\n\tt.Replies.Iterate(start, count, func(comment *boards.Post) bool {\n\t\tcomments = append(comments, hubexts.NewSafeComment(comment))\n\t\treturn false\n\t})\n\treturn comments\n}\n\n// GetReplies returns a list with the direct replies of a comment or reply.\n// To reverse iterate use a negative count.\n// `commentID` can be the ID of a top level comment or of a nested reply.\nfunc GetReplies(boardID, threadID, commentID uint64, start, count int) []Comment {\n\tc, found := getComment(boardID, threadID, commentID)\n\tif !found {\n\t\treturn nil\n\t}\n\n\tvar replies []Comment\n\tc.Replies.Iterate(start, count, func(comment *boards.Post) bool {\n\t\treplies = append(replies, hubexts.NewSafeComment(comment))\n\t\treturn false\n\t})\n\treturn replies\n}\n\n// getBoardThread returns a board thread from their IDs.\nfunc getBoardThread(boardID, threadID uint64) (*boards.Post, bool) {\n\tb, found := gBoards.Get(boards.ID(boardID))\n\tif !found {\n\t\treturn nil, false\n\t}\n\treturn getThread(b, boards.ID(threadID))\n}\n\n// getComment returns a thread comment or reply from their IDs.\n// It searches the thread's flat index of all comments and replies, so\n// nested replies are addressable by ID and not only top level comments.\nfunc getComment(boardID, threadID, commentID uint64) (*boards.Post, bool) {\n\tt, found := getBoardThread(boardID, threadID)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\treturn getReply(t, boards.ID(commentID))\n}\n"},{"name":"meta.gno","body":"package boards2\n\nimport \"gno.land/p/gnoland/boards/v0\"\n\n// BoardMeta defines a type for board metadata.\ntype BoardMeta struct {\n\t// HiddenThreads contains hidden board threads.\n\tHiddenThreads boards.PostStorage\n}\n\n// ThreadMeta defines a type for thread metadata.\ntype ThreadMeta struct {\n\t// AllReplies contains all existing thread comments and replies.\n\tAllReplies boards.PostStorage\n}\n"},{"name":"permissions.gno","body":"package boards2\n\nimport (\n\t\"gno.land/p/gnoland/boards/exts/permissions/v0\"\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// List of Boards2 member roles.\nconst (\n\tRoleOwner     boards.Role = \"owner\"\n\tRoleAdmin                 = \"admin\"\n\tRoleModerator             = \"moderator\"\n\tRoleGuest                 = \"guest\"\n)\n\n// PermissionCustom defines an initial value for custom board permissions.\n// When a board defines custom permissions it must starts from a value\n// greater or equal than PermissionCustom.\n//\n// Custom permissions definition example:\n//\n//\tconst (\n//\t  PermissionCustom1 boards.Permission = iota + boards2.PermissionCustom\n//\t  PermissionCustom2\n//\t  PermissionCustom3\n//\t)\nconst PermissionCustom boards.Permission = 200\n\n// List of Boards2 permissions.\nconst (\n\tPermissionBoardCreate boards.Permission = iota\n\tPermissionBoardFlaggingUpdate\n\tPermissionBoardFreeze\n\tPermissionBoardRename\n\tPermissionMemberInvite\n\tPermissionMemberInviteRevoke\n\tPermissionMemberRemove\n\tPermissionPermissionsUpdate\n\tPermissionRealmHelpChange\n\tPermissionRealmLock\n\tPermissionRealmNotice\n\tPermissionAccountRequiredAmountChange\n\tPermissionReplyCreate\n\tPermissionReplyDelete\n\tPermissionReplyFlag\n\tPermissionRoleChange\n\tPermissionThreadCreate\n\tPermissionThreadDelete\n\tPermissionThreadEdit\n\tPermissionThreadFlag\n\tPermissionThreadFreeze\n\tPermissionThreadRepost\n\tPermissionUserBan\n\tPermissionUserUnban\n)\n\nfunc createBasicBoardPermissions(owner address) *permissions.Permissions {\n\tperms := permissions.New(\n\t\tpermissions.UseSingleUserRole(),\n\t\tpermissions.WithSuperRole(RoleOwner),\n\t)\n\tperms.AddRole(\n\t\tRoleAdmin,\n\t\tPermissionBoardRename,\n\t\tPermissionBoardFlaggingUpdate,\n\t\tPermissionMemberInvite,\n\t\tPermissionMemberInviteRevoke,\n\t\tPermissionMemberRemove,\n\t\tPermissionThreadCreate,\n\t\tPermissionThreadEdit,\n\t\tPermissionThreadDelete,\n\t\tPermissionThreadRepost,\n\t\tPermissionThreadFlag,\n\t\tPermissionThreadFreeze,\n\t\tPermissionReplyCreate,\n\t\tPermissionReplyDelete,\n\t\tPermissionReplyFlag,\n\t\tPermissionRoleChange,\n\t\tPermissionUserBan,\n\t\tPermissionUserUnban,\n\t)\n\tperms.AddRole(\n\t\tRoleModerator,\n\t\tPermissionThreadCreate,\n\t\tPermissionThreadEdit,\n\t\tPermissionThreadRepost,\n\t\tPermissionThreadFlag,\n\t\tPermissionReplyCreate,\n\t\tPermissionReplyFlag,\n\t\tPermissionUserBan,\n\t\tPermissionUserUnban,\n\t)\n\tperms.AddRole(\n\t\tRoleGuest,\n\t\tPermissionThreadCreate,\n\t\tPermissionThreadRepost,\n\t\tPermissionReplyCreate,\n\t)\n\tperms.SetUserRoles(owner, RoleOwner)\n\tperms.ValidateFunc(PermissionBoardRename, validateBasicBoardRename)\n\tperms.ValidateFunc(PermissionMemberInvite, validateBasicMemberInvite)\n\tperms.ValidateFunc(PermissionRoleChange, validateBasicRoleChange)\n\treturn perms\n}\n\nfunc createOpenBoardPermissions(owner address) *permissions.Permissions {\n\tperms := permissions.New(\n\t\tpermissions.UseSingleUserRole(),\n\t\tpermissions.WithSuperRole(RoleOwner),\n\t)\n\tperms.SetPublicPermissions(\n\t\tPermissionThreadCreate,\n\t\tPermissionThreadRepost,\n\t\tPermissionReplyCreate,\n\t)\n\tperms.AddRole(\n\t\tRoleAdmin,\n\t\tPermissionBoardRename,\n\t\tPermissionBoardFlaggingUpdate,\n\t\tPermissionMemberInvite,\n\t\tPermissionMemberInviteRevoke,\n\t\tPermissionMemberRemove,\n\t\tPermissionThreadCreate,\n\t\tPermissionThreadEdit,\n\t\tPermissionThreadDelete,\n\t\tPermissionThreadRepost,\n\t\tPermissionThreadFlag,\n\t\tPermissionThreadFreeze,\n\t\tPermissionReplyCreate,\n\t\tPermissionReplyDelete,\n\t\tPermissionReplyFlag,\n\t\tPermissionRoleChange,\n\t\tPermissionUserBan,\n\t\tPermissionUserUnban,\n\t)\n\tperms.AddRole(\n\t\tRoleModerator,\n\t\tPermissionThreadCreate,\n\t\tPermissionThreadEdit,\n\t\tPermissionThreadRepost,\n\t\tPermissionThreadFlag,\n\t\tPermissionReplyCreate,\n\t\tPermissionReplyFlag,\n\t\tPermissionUserBan,\n\t\tPermissionUserUnban,\n\t)\n\tperms.AddRole(\n\t\tRoleGuest,\n\t\tPermissionThreadCreate,\n\t\tPermissionThreadRepost,\n\t\tPermissionReplyCreate,\n\t)\n\tperms.SetUserRoles(owner, RoleOwner)\n\tperms.ValidateFunc(PermissionBoardRename, validateOpenBoardRename)\n\tperms.ValidateFunc(PermissionMemberInvite, validateOpenMemberInvite)\n\tperms.ValidateFunc(PermissionRoleChange, validateOpenRoleChange)\n\tperms.ValidateFunc(PermissionThreadCreate, validateOpenThreadCreate)\n\tperms.ValidateFunc(PermissionThreadRepost, validateOpenThreadRepost)\n\tperms.ValidateFunc(PermissionReplyCreate, validateOpenReplyCreate)\n\treturn perms\n}\n"},{"name":"permissions_validators_basic.gno","body":"package boards2\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\n\t\"gno.land/r/sys/users\"\n)\n\n// validateBasicBoardCreate validates PermissionBoardCreate.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board name\n// 3. Board ID\n// 4. Is board listed\n// 5. Is board open\nfunc validateBasicBoardCreate(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\tname, ok := args[1].(string)\n\tif !ok {\n\t\treturn errors.New(\"expected board name to be a string\")\n\t}\n\n\topen, ok := args[4].(bool)\n\tif !ok {\n\t\treturn errors.New(\"expected board open flag to be a boolean\")\n\t}\n\n\tif open \u0026\u0026 !perms.HasRole(caller, RoleOwner) {\n\t\treturn errors.New(\"only owners can create open boards\")\n\t}\n\n\tif err := checkBoardNameIsNotAddress(name); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkBoardNameBelongsToAddress(caller, name); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// validateBasicBoardRename validates PermissionBoardRename.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Current board name\n// 4. New board name\nfunc validateBasicBoardRename(_ boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\tnewName, ok := args[3].(string)\n\tif !ok {\n\t\treturn errors.New(\"expected new board name to be a string\")\n\t}\n\n\tif err := checkBoardNameIsNotAddress(newName); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkBoardNameBelongsToAddress(caller, newName); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// validateBasicMemberInvite validates PermissionMemberInvite.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Invites\nfunc validateBasicMemberInvite(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\tinvites, ok := args[2].([]Invite)\n\tif !ok {\n\t\treturn errors.New(\"expected valid user invites\")\n\t}\n\n\t// Make sure that only owners invite other owners\n\tcallerIsOwner := perms.HasRole(caller, RoleOwner)\n\tfor _, v := range invites {\n\t\tif v.Role == RoleOwner \u0026\u0026 !callerIsOwner {\n\t\t\treturn errors.New(\"only owners are allowed to invite other owners\")\n\t\t}\n\t}\n\treturn nil\n}\n\n// validateBasicRoleChange validates PermissionRoleChange.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Member address\n// 4. Role\nfunc validateBasicRoleChange(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\t// Owners and Admins can change roles.\n\t// Admins should not be able to assign or remove the Owner role from members.\n\tif perms.HasRole(caller, RoleAdmin) {\n\t\trole, ok := args[3].(boards.Role)\n\t\tif !ok {\n\t\t\treturn errors.New(\"expected a valid member role\")\n\t\t}\n\n\t\tif role == RoleOwner {\n\t\t\treturn errors.New(\"admins are not allowed to promote members to Owner\")\n\t\t} else {\n\t\t\tmember, ok := args[2].(address)\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"expected a valid member address\")\n\t\t\t}\n\n\t\t\tif perms.HasRole(member, RoleOwner) {\n\t\t\t\treturn errors.New(\"admins are not allowed to remove the Owner role\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc checkBoardNameIsNotAddress(s string) error {\n\tif address(s).IsValid() {\n\t\treturn errors.New(\"addresses are not allowed as board name\")\n\t}\n\treturn nil\n}\n\nfunc checkBoardNameBelongsToAddress(owner address, name string) error {\n\t// When the board name is the name of a registered user\n\t// check that caller is the owner of the name.\n\tuser, _ := users.ResolveName(name)\n\tif user != nil \u0026\u0026 user.Addr() != owner {\n\t\treturn errors.New(\"board name is a user name registered to a different user\")\n\t}\n\treturn nil\n}\n"},{"name":"permissions_validators_open.gno","body":"package boards2\n\nimport (\n\t\"chain/banker\"\n\t\"errors\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// validateOpenBoardRename validates PermissionBoardRename.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Current board name\n// 4. New board name\nfunc validateOpenBoardRename(_ boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\tnewName, ok := args[3].(string)\n\tif !ok {\n\t\treturn errors.New(\"expected new board name to be a string\")\n\t}\n\n\tif err := checkBoardNameIsNotAddress(newName); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkBoardNameBelongsToAddress(caller, newName); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// validateOpenMemberInvite validates PermissionMemberInvite.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Invites\nfunc validateOpenMemberInvite(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\tinvites, ok := args[2].([]Invite)\n\tif !ok {\n\t\treturn errors.New(\"expected valid user invites\")\n\t}\n\n\t// Make sure that only owners invite other owners\n\tcallerIsOwner := perms.HasRole(caller, RoleOwner)\n\tfor _, v := range invites {\n\t\tif v.Role == RoleOwner \u0026\u0026 !callerIsOwner {\n\t\t\treturn errors.New(\"only owners are allowed to invite other owners\")\n\t\t}\n\t}\n\treturn nil\n}\n\n// validateOpenRoleChange validates PermissionRoleChange.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Member address\n// 4. Role\nfunc validateOpenRoleChange(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\t// Owners and Admins can change roles.\n\t// Admins should not be able to assign or remove the Owner role from members.\n\tif perms.HasRole(caller, RoleAdmin) {\n\t\trole, ok := args[3].(boards.Role)\n\t\tif !ok {\n\t\t\treturn errors.New(\"expected a valid member role\")\n\t\t}\n\n\t\tif role == RoleOwner {\n\t\t\treturn errors.New(\"admins are not allowed to promote members to Owner\")\n\t\t} else {\n\t\t\tmember, ok := args[2].(address)\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"expected a valid member address\")\n\t\t\t}\n\n\t\t\tif perms.HasRole(member, RoleOwner) {\n\t\t\t\treturn errors.New(\"admins are not allowed to remove the Owner role\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// validateOpenThreadCreate validates PermissionThreadCreate.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Thread ID\n// 4. Title\n// 5. Body\nfunc validateOpenThreadCreate(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\t// Owners and admins can create threads without special requirements\n\tif perms.HasRole(caller, RoleOwner) || perms.HasRole(caller, RoleAdmin) {\n\t\treturn nil\n\t}\n\n\t// Require non members to have some GNOT in their accounts\n\tif err := checkAccountHasAmount(caller, RequiredAccountAmount); err != nil {\n\t\treturn ufmt.Errorf(\"caller is not allowed to create threads: %s\", err)\n\t}\n\treturn nil\n}\n\n// validateOpenThreadRepost validates PermissionThreadRepost.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Thread ID\n// 4. Destination board ID\n// 5. Repost ID\n// 6. Title\n// 7. Body\nfunc validateOpenThreadRepost(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\t// Owners and admins can repost threads without special requirements\n\tif perms.HasRole(caller, RoleOwner) || perms.HasRole(caller, RoleAdmin) {\n\t\treturn nil\n\t}\n\n\t// Require non members to have some GNOT in their accounts\n\tif err := checkAccountHasAmount(caller, RequiredAccountAmount); err != nil {\n\t\treturn ufmt.Errorf(\"caller is not allowed to repost threads: %s\", err)\n\t}\n\treturn nil\n}\n\n// validateOpenReplyCreate validates PermissionReplyCreate.\n//\n// Expected `args` values:\n// 1. Caller address\n// 2. Board ID\n// 3. Thread ID\n// 4. Parent ID\n// 5. Reply ID\n// 6. Body\nfunc validateOpenReplyCreate(perms boards.Permissions, args boards.Args) error {\n\tcaller, ok := args[0].(address)\n\tif !ok {\n\t\treturn errors.New(\"expected a valid caller address\")\n\t}\n\n\t// All board members can reply\n\tif perms.HasUser(caller) {\n\t\treturn nil\n\t}\n\n\t// Require non members to have some GNOT in their accounts\n\tif err := checkAccountHasAmount(caller, RequiredAccountAmount); err != nil {\n\t\treturn ufmt.Errorf(\"caller is not allowed to comment: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc checkAccountHasAmount(addr address, amount int64) error {\n\tbnk := banker.NewReadonlyBanker()\n\tif bnk.GetCoin(addr, \"ugnot\") \u003c RequiredAccountAmount {\n\t\tamount = amount / 1_000_000 // ugnot -\u003e GNOT\n\t\treturn ufmt.Errorf(\"account amount is lower than %d GNOT\", amount)\n\t}\n\treturn nil\n}\n"},{"name":"public.gno","body":"package boards2\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\nconst (\n\t// MaxBoardNameLength defines the maximum length allowed for board names.\n\tMaxBoardNameLength = 50\n\n\t// MaxThreadTitleLength defines the maximum length allowed for thread titles.\n\tMaxThreadTitleLength = 100\n\n\t// MaxThreadBodyLength defines the maximum length allowed for thread bodies.\n\t// 40,000 mirrors Reddit's self-post body cap.\n\tMaxThreadBodyLength = 40000\n\n\t// MaxReplyLength defines the maximum length allowed for replies.\n\t// 10,000 mirrors Reddit's comment cap.\n\tMaxReplyLength = 10000\n)\n\nvar reBoardName = regexp.MustCompile(`(?i)^[a-z]+[a-z0-9_\\-]{2,50}$`)\n\n// SetHelp sets or updates boards realm help content.\nfunc SetHelp(cur realm, content string) {\n\tcontent = strings.TrimSpace(content)\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{content}\n\tgPerms.WithPermission(caller, PermissionRealmHelpChange, args, func() {\n\t\tHelp = content\n\t})\n}\n\n// SetRequiredAccountAmount sets the required account amount to interact as a non member with open boards.\n// Amount must be given as ugnot.\n// The amount requirement is not applied to members that were invited to an open board.\nfunc SetRequiredAccountAmount(cur realm, amount int64) {\n\tif amount \u003c 0 {\n\t\tpanic(\"invalid amount\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{amount}\n\tgPerms.WithPermission(caller, PermissionAccountRequiredAmountChange, args, func() {\n\t\tRequiredAccountAmount = amount\n\n\t\tchain.Emit(\n\t\t\t\"RequiredAccountAmountChanged\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t\t)\n\t})\n}\n\n// SetPermissions sets a permissions implementation for boards2 realm or a board.\nfunc SetPermissions(cur realm, boardID boards.ID, p boards.Permissions) {\n\tassertRealmIsNotLocked()\n\tassertBoardExists(boardID)\n\n\tif p == nil {\n\t\tpanic(\"permissions is required\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{boardID}\n\tgPerms.WithPermission(caller, PermissionPermissionsUpdate, args, func() {\n\t\tassertRealmIsNotLocked()\n\n\t\t// When board ID is zero it means that realm permissions are being updated\n\t\tif boardID == 0 {\n\t\t\tgPerms = p\n\n\t\t\tchain.Emit(\n\t\t\t\t\"RealmPermissionsChanged\",\n\t\t\t\t\"caller\", caller.String(),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\t// Otherwise update the permissions of a single board\n\t\tboard := mustGetBoard(boardID)\n\t\tboard.Permissions = p\n\n\t\tchain.Emit(\n\t\t\t\"BoardPermissionsChanged\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t)\n\t})\n}\n\n// SetRealmNotice sets a notice to be displayed globally within the realm.\n// An empty message removes the realm notice.\nfunc SetRealmNotice(cur realm, message string) {\n\tmessage = strings.TrimSpace(message)\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{message}\n\tgPerms.WithPermission(caller, PermissionRealmNotice, args, func() {\n\t\tNotice = message\n\n\t\tchain.Emit(\n\t\t\t\"RealmNoticeChanged\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"message\", message,\n\t\t)\n\t})\n}\n\n// GetBoardIDFromName searches a board by name and returns its ID.\nfunc GetBoardIDFromName(_ realm, name string) (_ boards.ID, found bool) {\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\treturn 0, false\n\t}\n\treturn board.ID, true\n}\n\n// BoardCount returns the total number of boards.\nfunc BoardCount() int {\n\treturn gBoards.Size()\n}\n\n// CreateBoard creates a new board.\n//\n// Listed boards are included in the realm's list of boards.\n// Open boards allow anyone to create threads and comment.\nfunc CreateBoard(cur realm, name string, listed, open bool) boards.ID {\n\tassertRealmIsNotLocked()\n\n\tname = strings.TrimSpace(name)\n\tassertIsValidBoardName(name)\n\tassertBoardNameNotExists(name)\n\n\tcaller := cur.Previous().Address()\n\tid := gBoardsSequence.Next()\n\targs := boards.Args{caller, name, id, listed, open}\n\tgPerms.WithPermission(caller, PermissionBoardCreate, args, func() {\n\t\tassertRealmIsNotLocked()\n\t\tassertBoardNameNotExists(name)\n\t\taddBoard(id, caller, name, listed, open)\n\t})\n\treturn id\n}\n\n// addBoard creates a board and adds it to the realm storage.\n// It performs no permission or validation checks, so callers are responsible\n// for doing their own.\nfunc addBoard(id boards.ID, caller address, name string, listed, open bool) {\n\tboard := boards.New(id)\n\tboard.Name = name\n\tboard.Creator = caller\n\tboard.Meta = \u0026BoardMeta{\n\t\tHiddenThreads: boards.NewPostStorage(),\n\t}\n\n\tif open {\n\t\tboard.Permissions = createOpenBoardPermissions(caller)\n\t} else {\n\t\tboard.Permissions = createBasicBoardPermissions(caller)\n\t}\n\n\tif err := gBoards.Add(board); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Listed boards are also indexed separately for easier iteration and pagination\n\tif listed {\n\t\tgListedBoardsByID.Set(board.ID.Key(), board)\n\t}\n\n\tchain.Emit(\n\t\t\"BoardCreated\",\n\t\t\"caller\", caller.String(),\n\t\t\"boardID\", board.ID.String(),\n\t\t\"name\", name,\n\t)\n}\n\n// RenameBoard changes the name of an existing board.\n//\n// A history of previous board names is kept when boards are renamed.\n// Because of that boards are also accessible using previous name(s).\nfunc RenameBoard(cur realm, name, newName string) {\n\tassertRealmIsNotLocked()\n\n\tnewName = strings.TrimSpace(newName)\n\tassertIsValidBoardName(newName)\n\tassertBoardNameNotExists(newName)\n\n\tboard := mustGetBoardByName(name)\n\tassertBoardIsNotFrozen(board)\n\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{caller, board.ID, name, newName}\n\tboard.Permissions.WithPermission(caller, PermissionBoardRename, args, func() {\n\t\tassertRealmIsNotLocked()\n\t\tassertBoardNameNotExists(newName)\n\n\t\tboard.Aliases = append(board.Aliases, board.Name)\n\t\tboard.Name = newName\n\t\tboard.UpdatedAt = time.Now()\n\n\t\t// Index board for the new name keeping previous indexes for older names\n\t\tgBoards.Add(board)\n\n\t\tchain.Emit(\n\t\t\t\"BoardRenamed\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"name\", name,\n\t\t\t\"newName\", newName,\n\t\t)\n\t})\n}\n\n// CreateThread creates a new thread within a board.\nfunc CreateThread(cur realm, boardID boards.ID, title, body string) boards.ID {\n\tassertRealmIsNotLocked()\n\n\ttitle = strings.TrimSpace(title)\n\tassertTitleIsValid(title)\n\tassertThreadBodyIsValid(body)\n\n\tcaller := cur.Previous().Address()\n\tassertUserIsNotBanned(boardID, caller)\n\n\tboard := mustGetBoard(boardID)\n\tassertBoardIsNotFrozen(board)\n\n\tthread := boards.MustNewThread(board, caller, title, body)\n\targs := boards.Args{caller, board.ID, thread.ID, title, body}\n\tboard.Permissions.WithPermission(caller, PermissionThreadCreate, args, func() {\n\t\tassertRealmIsNotLocked()\n\t\tassertUserIsNotBanned(board.ID, caller)\n\n\t\tthread.Meta = \u0026ThreadMeta{\n\t\t\tAllReplies: boards.NewPostStorage(),\n\t\t}\n\n\t\tif err := board.Threads.Add(thread); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"ThreadCreated\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"title\", title,\n\t\t)\n\t})\n\treturn thread.ID\n}\n\n// CreateReply creates a new comment or reply within a thread.\n//\n// The value of `replyID` is only required when creating a reply of another reply.\nfunc CreateReply(cur realm, boardID, threadID, replyID boards.ID, body string) boards.ID {\n\tassertRealmIsNotLocked()\n\n\tbody = strings.TrimSpace(body)\n\tassertReplyBodyIsValid(body)\n\n\tcaller := cur.Previous().Address()\n\tassertUserIsNotBanned(boardID, caller)\n\n\tboard := mustGetBoard(boardID)\n\tassertBoardIsNotFrozen(board)\n\n\tthread := mustGetThread(board, threadID)\n\tassertThreadIsVisible(thread)\n\tassertThreadIsNotFrozen(thread)\n\n\t// By default consider that reply's parent is the thread.\n\t// Or when replyID is assigned use that reply as the parent.\n\tparent := thread\n\tif replyID \u003e 0 {\n\t\tparent = mustGetReply(thread, replyID)\n\t\tif parent.Hidden || parent.Readonly {\n\t\t\tpanic(\"replying to a hidden or frozen reply is not allowed\")\n\t\t}\n\t}\n\n\treply := boards.MustNewReply(parent, caller, body)\n\targs := boards.Args{caller, board.ID, thread.ID, parent.ID, reply.ID, body}\n\tboard.Permissions.WithPermission(caller, PermissionReplyCreate, args, func() {\n\t\tassertRealmIsNotLocked()\n\n\t\t// Add reply to its parent\n\t\tif err := parent.Replies.Add(reply); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Always add reply to the thread so it contains all comments and replies.\n\t\t// Comment and reply only contains direct replies.\n\t\tmeta := thread.Meta.(*ThreadMeta)\n\t\tif err := meta.AllReplies.Add(reply); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"ReplyCreate\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"replyID\", reply.ID.String(),\n\t\t)\n\t})\n\treturn reply.ID\n}\n\n// CreateRepost reposts a thread into another board.\nfunc CreateRepost(cur realm, boardID, threadID, destinationBoardID boards.ID, title, body string) boards.ID {\n\tassertRealmIsNotLocked()\n\n\ttitle = strings.TrimSpace(title)\n\tassertTitleIsValid(title)\n\tassertThreadBodyIsValid(body)\n\n\tcaller := cur.Previous().Address()\n\tassertUserIsNotBanned(destinationBoardID, caller)\n\n\tdst := mustGetBoard(destinationBoardID)\n\tassertBoardIsNotFrozen(dst)\n\n\tboard := mustGetBoard(boardID)\n\tthread := mustGetThread(board, threadID)\n\tassertThreadIsVisible(thread)\n\n\trepost := boards.MustNewRepost(thread, dst, caller)\n\targs := boards.Args{caller, board.ID, thread.ID, dst.ID, repost.ID, title, body}\n\tdst.Permissions.WithPermission(caller, PermissionThreadRepost, args, func() {\n\t\tassertRealmIsNotLocked()\n\n\t\trepost.Title = title\n\t\trepost.Body = strings.TrimSpace(body)\n\t\trepost.Meta = \u0026ThreadMeta{\n\t\t\tAllReplies: boards.NewPostStorage(),\n\t\t}\n\n\t\tif err := dst.Threads.Add(repost); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif err := thread.Reposts.Add(repost); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"Repost\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"destinationBoardID\", dst.ID.String(),\n\t\t\t\"repostID\", repost.ID.String(),\n\t\t\t\"title\", title,\n\t\t)\n\t})\n\treturn repost.ID\n}\n\n// DeleteThread deletes a thread from a board.\n//\n// Threads can be deleted by the users who created them or otherwise by users with special permissions.\nfunc DeleteThread(cur realm, boardID, threadID boards.ID) {\n\tassertRealmIsNotLocked()\n\n\tcaller := cur.Previous().Address()\n\tboard := mustGetBoard(boardID)\n\tassertUserIsNotBanned(boardID, caller)\n\n\tisRealmOwner := gPerms.HasRole(caller, RoleOwner) // TODO: Add DeleteThread filetest cases for realm owners\n\tif !isRealmOwner {\n\t\tassertBoardIsNotFrozen(board)\n\t}\n\n\tthread := mustGetThread(board, threadID)\n\tdeleteThread := func() {\n\t\tboard.Threads.Remove(thread.ID)\n\n\t\tchain.Emit(\n\t\t\t\"ThreadDeleted\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t)\n\t}\n\n\t// Thread can be directly deleted by user that created it.\n\t// It can also be deleted by realm owners, to be able to delete inappropriate content.\n\t// TODO: Discuss and decide if realm owners should be able to delete threads.\n\tif isRealmOwner || caller == thread.Creator {\n\t\tdeleteThread()\n\t\treturn\n\t}\n\n\targs := boards.Args{caller, board.ID, thread.ID}\n\tboard.Permissions.WithPermission(caller, PermissionThreadDelete, args, func() {\n\t\tassertRealmIsNotLocked()\n\t\tdeleteThread()\n\t})\n}\n\n// DeleteReply deletes a reply from a thread.\n//\n// Replies can be deleted by the users who created them or otherwise by users with special permissions.\n// Soft deletion is used when the deleted reply contains sub replies, in which case the reply content\n// is replaced by a text informing that reply has been deleted to avoid deleting sub-replies.\nfunc DeleteReply(cur realm, boardID, threadID, replyID boards.ID) {\n\tassertRealmIsNotLocked()\n\n\tcaller := cur.Previous().Address()\n\tboard := mustGetBoard(boardID)\n\tassertUserIsNotBanned(boardID, caller)\n\n\tthread := mustGetThread(board, threadID)\n\treply := mustGetReply(thread, replyID)\n\tisRealmOwner := gPerms.HasRole(caller, RoleOwner) // TODO: Add DeleteReply filetest cases for realm owners\n\tif !isRealmOwner {\n\t\tassertBoardIsNotFrozen(board)\n\t\tassertThreadIsNotFrozen(thread)\n\t\tassertReplyIsVisible(reply)\n\t}\n\n\tdeleteReply := func() {\n\t\t// Soft delete comment/reply by changing its body when\n\t\t// it contains replies, otherwise hard delete it.\n\t\tif reply.Replies.Size() \u003e 0 {\n\t\t\treply.Body = \"⚠ This comment has been deleted\"\n\t\t\treply.UpdatedAt = time.Now()\n\t\t} else {\n\t\t\t// Remove reply from the flat thread index.\n\t\t\tmeta := thread.Meta.(*ThreadMeta)\n\t\t\treply, removed := meta.AllReplies.Remove(replyID)\n\t\t\tif !removed {\n\t\t\t\tpanic(\"reply not found\")\n\t\t\t}\n\n\t\t\t// Remove reply from its parent's direct-children list too. A\n\t\t\t// direct thread reply's parent is the thread itself; a nested\n\t\t\t// reply's parent is another reply (resolved via the flat index).\n\t\t\t// Missing the thread-parent case left a ghost in thread.Replies\n\t\t\t// (rendered in the threaded view, with a stale reply count).\n\t\t\tif reply.ParentID == thread.ID {\n\t\t\t\tthread.Replies.Remove(replyID)\n\t\t\t} else if parent, found := meta.AllReplies.Get(reply.ParentID); found {\n\t\t\t\tparent.Replies.Remove(replyID)\n\t\t\t}\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"ReplyDeleted\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"replyID\", reply.ID.String(),\n\t\t)\n\t}\n\n\t// Reply can be directly deleted by user that created it.\n\t// It can also be deleted by realm owners, to be able to delete inappropriate content.\n\t// TODO: Discuss and decide if realm owners should be able to delete replies.\n\tif isRealmOwner || caller == reply.Creator {\n\t\tdeleteReply()\n\t\treturn\n\t}\n\n\targs := boards.Args{caller, board.ID, thread.ID, reply.ID}\n\tboard.Permissions.WithPermission(caller, PermissionReplyDelete, args, func() {\n\t\tassertRealmIsNotLocked()\n\t\tdeleteReply()\n\t})\n}\n\n// EditThread updates the title and body of a thread.\n//\n// Threads can be updated by the users who created them or otherwise by users with special permissions.\nfunc EditThread(cur realm, boardID, threadID boards.ID, title, body string) {\n\tassertRealmIsNotLocked()\n\n\ttitle = strings.TrimSpace(title)\n\tassertTitleIsValid(title)\n\tassertThreadBodyIsValid(body)\n\n\tboard := mustGetBoard(boardID)\n\tassertBoardIsNotFrozen(board)\n\n\tcaller := cur.Previous().Address()\n\tassertUserIsNotBanned(boardID, caller)\n\n\tthread := mustGetThread(board, threadID)\n\tassertThreadIsNotFrozen(thread)\n\n\tbody = strings.TrimSpace(body)\n\tif !boards.IsRepost(thread) {\n\t\tassertBodyIsNotEmpty(body)\n\t}\n\n\teditThread := func() {\n\t\tthread.Title = title\n\t\tthread.Body = body\n\t\tthread.UpdatedAt = time.Now()\n\n\t\tchain.Emit(\n\t\t\t\"ThreadEdited\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"title\", title,\n\t\t)\n\t}\n\n\tif caller == thread.Creator {\n\t\teditThread()\n\t\treturn\n\t}\n\n\targs := boards.Args{caller, board.ID, thread.ID, title, body}\n\tboard.Permissions.WithPermission(caller, PermissionThreadEdit, args, func() {\n\t\tassertRealmIsNotLocked()\n\t\teditThread()\n\t})\n}\n\n// EditReply updates the body of a comment or reply.\n//\n// Replies can be updated only by the users who created them.\nfunc EditReply(cur realm, boardID, threadID, replyID boards.ID, body string) {\n\tassertRealmIsNotLocked()\n\n\tbody = strings.TrimSpace(body)\n\tassertReplyBodyIsValid(body)\n\n\tboard := mustGetBoard(boardID)\n\tassertBoardIsNotFrozen(board)\n\n\tcaller := cur.Previous().Address()\n\tassertUserIsNotBanned(boardID, caller)\n\n\tthread := mustGetThread(board, threadID)\n\tassertThreadIsNotFrozen(thread)\n\n\treply := mustGetReply(thread, replyID)\n\tassertReplyIsVisible(reply)\n\n\tif caller != reply.Creator {\n\t\tpanic(\"only the reply creator is allowed to edit it\")\n\t}\n\n\treply.Body = body\n\treply.UpdatedAt = time.Now()\n\n\tchain.Emit(\n\t\t\"ReplyEdited\",\n\t\t\"caller\", caller.String(),\n\t\t\"boardID\", board.ID.String(),\n\t\t\"threadID\", thread.ID.String(),\n\t\t\"replyID\", reply.ID.String(),\n\t\t\"body\", body,\n\t)\n}\n\n// RemoveMember removes a member from the realm or a board.\n//\n// Board ID is only required when removing a member from board.\nfunc RemoveMember(cur realm, boardID boards.ID, member address) {\n\tassertMembersUpdateIsEnabled(boardID)\n\tassertMemberAddressIsValid(member)\n\n\tperms := mustGetPermissions(boardID)\n\torigin := unsafe.OriginCaller()\n\tcaller := cur.Previous().Address()\n\tremoveMember := func() {\n\t\tif !perms.RemoveUser(member) {\n\t\t\tpanic(\"member not found\")\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"MemberRemoved\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"origin\", origin.String(), // When origin and caller match it means self removal\n\t\t\t\"boardID\", boardID.String(),\n\t\t\t\"member\", member.String(),\n\t\t)\n\t}\n\n\t// Members can remove themselves without permission\n\tif origin == member {\n\t\tremoveMember()\n\t\treturn\n\t}\n\n\targs := boards.Args{boardID, member}\n\tperms.WithPermission(caller, PermissionMemberRemove, args, func() {\n\t\tassertMembersUpdateIsEnabled(boardID)\n\t\tremoveMember()\n\t})\n}\n\n// IsMember checks if a user is a member of the realm or a board.\n//\n// Board ID is only required when checking if a user is a member of a board.\nfunc IsMember(boardID boards.ID, user address) bool {\n\tassertUserAddressIsValid(user)\n\n\tif boardID != 0 {\n\t\tboard := mustGetBoard(boardID)\n\t\tassertBoardIsNotFrozen(board)\n\t}\n\n\tperms := mustGetPermissions(boardID)\n\treturn perms.HasUser(user)\n}\n\n// HasMemberRole checks if a realm or board member has a specific role assigned.\n//\n// Board ID is only required when checking a member of a board.\nfunc HasMemberRole(boardID boards.ID, member address, role boards.Role) bool {\n\tassertMemberAddressIsValid(member)\n\n\tif boardID != 0 {\n\t\tboard := mustGetBoard(boardID)\n\t\tassertBoardIsNotFrozen(board)\n\t}\n\n\tperms := mustGetPermissions(boardID)\n\treturn perms.HasRole(member, role)\n}\n\n// ChangeMemberRole changes the role of a realm or board member.\n//\n// Board ID is only required when changing the role for a member of a board.\nfunc ChangeMemberRole(cur realm, boardID boards.ID, member address, role boards.Role) {\n\tassertMemberAddressIsValid(member)\n\tassertMembersUpdateIsEnabled(boardID)\n\n\tif role == \"\" {\n\t\trole = RoleGuest\n\t}\n\n\tperms := mustGetPermissions(boardID)\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{caller, boardID, member, role}\n\tperms.WithPermission(caller, PermissionRoleChange, args, func() {\n\t\tassertMembersUpdateIsEnabled(boardID)\n\n\t\tperms.SetUserRoles(member, role)\n\n\t\tchain.Emit(\n\t\t\t\"RoleChanged\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", boardID.String(),\n\t\t\t\"member\", member.String(),\n\t\t\t\"newRole\", string(role),\n\t\t)\n\t})\n}\n\nfunc assertMemberAddressIsValid(member address) {\n\tif !member.IsValid() {\n\t\tpanic(\"invalid member address: \" + member.String())\n\t}\n}\n\nfunc assertUserAddressIsValid(user address) {\n\tif !user.IsValid() {\n\t\tpanic(\"invalid user address: \" + user.String())\n\t}\n}\n\nfunc assertBoardExists(id boards.ID) {\n\tif id == 0 { // ID zero is used to refer to the realm\n\t\treturn\n\t}\n\n\tif _, found := gBoards.Get(id); !found {\n\t\tpanic(\"board not found: \" + id.String())\n\t}\n}\n\nfunc assertBoardIsNotFrozen(b *boards.Board) {\n\tif b.Readonly {\n\t\tpanic(\"board is frozen\")\n\t}\n}\n\nfunc assertIsValidBoardName(name string) {\n\tsize := len(name)\n\tif size == 0 {\n\t\tpanic(\"board name is empty\")\n\t}\n\n\tif size \u003c 3 {\n\t\tpanic(\"board name is too short, minimum length is 3 characters\")\n\t}\n\n\tif size \u003e MaxBoardNameLength {\n\t\tn := strconv.Itoa(MaxBoardNameLength)\n\t\tpanic(\"board name is too long, maximum allowed is \" + n + \" characters\")\n\t}\n\n\tif !reBoardName.MatchString(name) {\n\t\tpanic(\"board name must start with a letter and have letters, numbers, \\\"-\\\" and \\\"_\\\"\")\n\t}\n}\n\nfunc assertThreadIsNotFrozen(t *boards.Post) {\n\tif t.Readonly {\n\t\tpanic(\"thread is frozen\")\n\t}\n}\n\nfunc assertNameIsNotEmpty(name string) {\n\tif name == \"\" {\n\t\tpanic(\"name is empty\")\n\t}\n}\n\nfunc assertTitleIsValid(title string) {\n\tif title == \"\" {\n\t\tpanic(\"title is empty\")\n\t}\n\n\tif len(title) \u003e MaxThreadTitleLength {\n\t\tn := strconv.Itoa(MaxThreadTitleLength)\n\t\tpanic(\"title is too long, maximum allowed is \" + n + \" characters\")\n\t}\n}\n\nfunc assertBodyIsNotEmpty(body string) {\n\tif body == \"\" {\n\t\tpanic(\"body is empty\")\n\t}\n}\n\nfunc assertBoardNameNotExists(name string) {\n\tname = strings.ToLower(name)\n\tif _, found := gBoards.GetByName(name); found {\n\t\tpanic(\"board already exists\")\n\t}\n}\n\nfunc assertThreadExists(b *boards.Board, threadID boards.ID) {\n\tif _, found := getThread(b, threadID); !found {\n\t\tpanic(\"thread not found: \" + threadID.String())\n\t}\n}\n\nfunc assertReplyExists(thread *boards.Post, replyID boards.ID) {\n\tif _, found := getReply(thread, replyID); !found {\n\t\tpanic(\"reply not found: \" + replyID.String())\n\t}\n}\n\nfunc assertThreadIsVisible(thread *boards.Post) {\n\tif thread.Hidden {\n\t\tpanic(\"thread is hidden\")\n\t}\n}\n\nfunc assertReplyIsVisible(thread *boards.Post) {\n\tif thread.Hidden {\n\t\tpanic(\"reply is hidden\")\n\t}\n}\n\nfunc assertThreadBodyIsValid(body string) {\n\tif len(body) \u003e MaxThreadBodyLength {\n\t\tn := strconv.Itoa(MaxThreadBodyLength)\n\t\tpanic(\"thread body is too long, maximum allowed is \" + n + \" characters\")\n\t}\n}\n\nfunc assertReplyBodyIsValid(body string) {\n\tassertBodyIsNotEmpty(body)\n\n\tif len(body) \u003e MaxReplyLength {\n\t\tn := strconv.Itoa(MaxReplyLength)\n\t\tpanic(\"reply is too long, maximum allowed is \" + n + \" characters\")\n\t}\n\n\t// No markdown-structure or gno-form blacklist here: reply bodies\n\t// render inside a \u003cgno-foreign\u003e sandbox (see indentForeignBody),\n\t// which contains block structure and omits forms at render time.\n}\n\nfunc assertMembersUpdateIsEnabled(boardID boards.ID) {\n\tif boardID != 0 {\n\t\tassertRealmIsNotLocked()\n\t} else {\n\t\tassertRealmMembersAreNotLocked()\n\t}\n}\n"},{"name":"public_ban.gno","body":"package boards2\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\n// Constants for different banning periods.\nconst (\n\tBanDay  = uint(24)\n\tBanWeek = BanDay * 7\n\tBanYear = BanDay * 365\n)\n\n// Ban bans a user from a board for a period of time.\n// Only invited guest members and external users can be banned.\n// Banning board owners, admins and moderators is not allowed.\nfunc Ban(cur realm, boardID boards.ID, user address, hours uint, reason string) {\n\tassertAddressIsValid(user)\n\n\tif hours == 0 {\n\t\tpanic(\"ban period in hours is required\")\n\t}\n\n\treason = strings.TrimSpace(reason)\n\tif reason == \"\" {\n\t\tpanic(\"ban reason is required\")\n\t}\n\n\tboard := mustGetBoard(boardID)\n\tcaller := cur.Previous().Address()\n\tuntil := time.Now().Add(time.Minute * 60 * time.Duration(hours))\n\targs := boards.Args{boardID, user, until, reason}\n\tboard.Permissions.WithPermission(caller, PermissionUserBan, args, func() {\n\t\t// When banning invited members make sure they are guests, otherwise\n\t\t// disallow banning. Only guest or external users can be banned.\n\t\tif board.Permissions.HasUser(user) \u0026\u0026 !board.Permissions.HasRole(user, RoleGuest) {\n\t\t\tpanic(\"owner, admin and moderator banning is not allowed\")\n\t\t}\n\n\t\tbanned, found := getBannedUsers(boardID)\n\t\tif !found {\n\t\t\tbanned = bptree.NewBPTree32()\n\t\t\tgBannedUsers.Set(boardID.Key(), banned)\n\t\t}\n\n\t\tbanned.Set(user.String(), until)\n\n\t\tchain.Emit(\n\t\t\t\"UserBanned\",\n\t\t\t\"bannedBy\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"user\", user.String(),\n\t\t\t\"until\", until.Format(time.RFC3339),\n\t\t\t\"reason\", reason,\n\t\t)\n\t})\n}\n\n// Unban unbans a user from a board.\nfunc Unban(cur realm, boardID boards.ID, user address, reason string) {\n\tassertAddressIsValid(user)\n\n\tboard := mustGetBoard(boardID)\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{boardID, user, reason}\n\tboard.Permissions.WithPermission(caller, PermissionUserUnban, args, func() {\n\t\tbanned, found := getBannedUsers(boardID)\n\t\tif !found || !banned.Has(user.String()) {\n\t\t\tpanic(\"user is not banned\")\n\t\t}\n\n\t\tbanned.Remove(user.String())\n\n\t\tchain.Emit(\n\t\t\t\"UserUnbanned\",\n\t\t\t\"bannedBy\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"user\", user.String(),\n\t\t\t\"reason\", reason,\n\t\t)\n\t})\n}\n\n// IsBanned checks if a user is banned from a board.\nfunc IsBanned(boardID boards.ID, user address) bool {\n\tbanned, found := getBannedUsers(boardID)\n\treturn found \u0026\u0026 banned.Has(user.String())\n}\n\nfunc assertAddressIsValid(addr address) {\n\tif !addr.IsValid() {\n\t\tpanic(\"invalid address: \" + addr.String())\n\t}\n}\n\nfunc assertUserIsNotBanned(boardID boards.ID, user address) {\n\tbanned, found := getBannedUsers(boardID)\n\tif !found {\n\t\treturn\n\t}\n\n\tv := banned.Get(user.String())\n\tif v == nil {\n\t\treturn\n\t}\n\n\tuntil := v.(time.Time)\n\tif time.Now().Before(until) {\n\t\tpanic(user.String() + \" is banned until \" + until.Format(dateFormat))\n\t}\n}\n"},{"name":"public_flag.gno","body":"package boards2\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// SetFlaggingThreshold sets the number of flags required to hide a thread or comment.\n//\n// Threshold is only applicable within the board where it's setted.\nfunc SetFlaggingThreshold(cur realm, boardID boards.ID, threshold int) {\n\tif threshold \u003c 1 {\n\t\tpanic(\"invalid flagging threshold\")\n\t}\n\n\tassertRealmIsNotLocked()\n\n\tboard := mustGetBoard(boardID)\n\tassertBoardIsNotFrozen(board)\n\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{board.ID, threshold}\n\tboard.Permissions.WithPermission(caller, PermissionBoardFlaggingUpdate, args, func() {\n\t\tassertRealmIsNotLocked()\n\n\t\tgFlaggingThresholds.Set(boardID.String(), threshold)\n\n\t\tchain.Emit(\n\t\t\t\"FlaggingThresholdUpdated\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threshold\", strconv.Itoa(threshold),\n\t\t)\n\t})\n}\n\n// GetFlaggingThreshold returns the number of flags required to hide a thread or comment within a board.\nfunc GetFlaggingThreshold(boardID boards.ID) int {\n\tassertBoardExists(boardID)\n\treturn getFlaggingThreshold(boardID)\n}\n\n// FlagThread adds a new flag to a thread.\n//\n// Flagging requires special permissions and hides the thread when\n// the number of flags reaches a pre-defined flagging threshold.\nfunc FlagThread(cur realm, boardID, threadID boards.ID, reason string) {\n\treason = strings.TrimSpace(reason)\n\tif reason == \"\" {\n\t\tpanic(\"flagging reason is required\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\tboard := mustGetBoard(boardID)\n\tisRealmOwner := gPerms.HasRole(caller, RoleOwner)\n\tif !isRealmOwner {\n\t\tassertRealmIsNotLocked()\n\t\tassertBoardIsNotFrozen(board)\n\t}\n\n\tthread, found := getThread(board, threadID)\n\tif !found {\n\t\tpanic(\"thread not found\")\n\t}\n\n\tif thread.Hidden {\n\t\tpanic(\"flagging hidden threads is not allowed\")\n\t}\n\n\tflagThread := func() {\n\t\tif thread.Hidden {\n\t\t\tpanic(\"flagged thread is already hidden\")\n\t\t}\n\n\t\t// Hide thread when flagging threshold is reached.\n\t\t// Realm owners can hide with a single flag.\n\t\thide := flagItem(thread, caller, reason, getFlaggingThreshold(board.ID))\n\t\tif hide || isRealmOwner {\n\t\t\t// Remove thread from the list of visible threads\n\t\t\tthread, removed := board.Threads.Remove(threadID)\n\t\t\tif !removed {\n\t\t\t\tpanic(\"thread not found\")\n\t\t\t}\n\n\t\t\t// Mark thread as hidden to avoid rendering content\n\t\t\tthread.Hidden = true\n\n\t\t\t// Keep track of hidden the thread to be able to restore it after moderation disputes\n\t\t\tmeta := board.Meta.(*BoardMeta)\n\t\t\tmeta.HiddenThreads.Add(thread)\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"ThreadFlagged\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"reason\", reason,\n\t\t)\n\t}\n\n\t// Realm owners should be able to flag without permissions even when board is frozen\n\tif isRealmOwner {\n\t\tflagThread()\n\t\treturn\n\t}\n\n\targs := boards.Args{caller, board.ID, thread.ID, reason}\n\tboard.Permissions.WithPermission(caller, PermissionThreadFlag, args, func() {\n\t\tflagThread()\n\t})\n}\n\n// FlagReply adds a new flag to a comment or reply.\n//\n// Flagging requires special permissions and hides the comment or reply\n// when the number of flags reaches a pre-defined flagging threshold.\nfunc FlagReply(cur realm, boardID, threadID, replyID boards.ID, reason string) {\n\treason = strings.TrimSpace(reason)\n\tif reason == \"\" {\n\t\tpanic(\"flagging reason is required\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\tboard := mustGetBoard(boardID)\n\tisRealmOwner := gPerms.HasRole(caller, RoleOwner)\n\tif !isRealmOwner {\n\t\tassertRealmIsNotLocked()\n\t\tassertBoardIsNotFrozen(board)\n\t}\n\n\tthread := mustGetThread(board, threadID)\n\treply := mustGetReply(thread, replyID)\n\tif reply.Hidden {\n\t\tpanic(\"flagging hidden comments or replies is not allowed\")\n\t}\n\n\tflagReply := func() {\n\t\tif reply.Hidden {\n\t\t\tpanic(\"flagged comment or reply is already hidden\")\n\t\t}\n\n\t\thide := flagItem(reply, caller, reason, getFlaggingThreshold(board.ID))\n\t\tif hide || isRealmOwner {\n\t\t\treply.Hidden = true\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"ReplyFlagged\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"replyID\", reply.ID.String(),\n\t\t\t\"reason\", reason,\n\t\t)\n\t}\n\n\t// Realm owners should be able to flag without permissions even when board is frozen\n\tif isRealmOwner {\n\t\tflagReply()\n\t\treturn\n\t}\n\n\targs := boards.Args{caller, board.ID, thread.ID, reply.ID, reason}\n\tboard.Permissions.WithPermission(caller, PermissionReplyFlag, args, func() {\n\t\tflagReply()\n\t})\n}\n"},{"name":"public_freeze.gno","body":"package boards2\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// FreezeBoard freezes a board so no more threads and comments can be created or modified.\nfunc FreezeBoard(cur realm, boardID boards.ID) {\n\tsetBoardReadonly(0, cur, boardID, true)\n}\n\n// UnfreezeBoard removes frozen status from a board.\nfunc UnfreezeBoard(cur realm, boardID boards.ID) {\n\tsetBoardReadonly(0, cur, boardID, false)\n}\n\n// IsBoardFrozen checks if a board has been frozen.\nfunc IsBoardFrozen(boardID boards.ID) bool {\n\tboard := mustGetBoard(boardID)\n\treturn board.Readonly\n}\n\n// FreezeThread freezes a thread so thread cannot be replied, modified or deleted.\n//\n// Fails if board is frozen.\nfunc FreezeThread(cur realm, boardID, threadID boards.ID) {\n\tsetThreadReadonly(0, cur, boardID, threadID, true)\n}\n\n// UnfreezeThread removes frozen status from a thread.\n//\n// Fails if board is frozen.\nfunc UnfreezeThread(cur realm, boardID, threadID boards.ID) {\n\tsetThreadReadonly(0, cur, boardID, threadID, false)\n}\n\n// IsThreadFrozen checks if a thread has been frozen.\n//\n// Returns true if board is frozen.\nfunc IsThreadFrozen(boardID, threadID boards.ID) bool {\n\tboard := mustGetBoard(boardID)\n\tthread := mustGetThread(board, threadID)\n\treturn board.Readonly || thread.Readonly\n}\n\nfunc setBoardReadonly(_ int, rlm realm, boardID boards.ID, readonly bool) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tassertRealmIsNotLocked()\n\n\tboard := mustGetBoard(boardID)\n\tif readonly {\n\t\tassertBoardIsNotFrozen(board)\n\t}\n\n\tcaller := rlm.Previous().Address()\n\targs := boards.Args{caller, board.ID, readonly}\n\tboard.Permissions.WithPermission(caller, PermissionBoardFreeze, args, func() {\n\t\tassertRealmIsNotLocked()\n\n\t\tboard.Readonly = readonly\n\n\t\tchain.Emit(\n\t\t\t\"BoardFreeze\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"frozen\", strconv.FormatBool(readonly),\n\t\t)\n\t})\n}\n\nfunc setThreadReadonly(_ int, rlm realm, boardID, threadID boards.ID, readonly bool) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tassertRealmIsNotLocked()\n\n\tboard := mustGetBoard(boardID)\n\tassertBoardIsNotFrozen(board)\n\n\tthread := mustGetThread(board, threadID)\n\tif readonly {\n\t\tassertThreadIsNotFrozen(thread)\n\t}\n\n\tcaller := rlm.Previous().Address()\n\targs := boards.Args{caller, board.ID, thread.ID, readonly}\n\tboard.Permissions.WithPermission(caller, PermissionThreadFreeze, args, func() {\n\t\tassertRealmIsNotLocked()\n\n\t\tthread.Readonly = readonly\n\n\t\tchain.Emit(\n\t\t\t\"ThreadFreeze\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"threadID\", thread.ID.String(),\n\t\t\t\"frozen\", strconv.FormatBool(readonly),\n\t\t)\n\t})\n}\n"},{"name":"public_invite.gno","body":"package boards2\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\n// Invite contains a user invitation.\ntype Invite struct {\n\t// User is the user to invite.\n\tUser address\n\n\t// Role is the optional role to assign to the user.\n\tRole boards.Role\n}\n\n// InviteMember adds a member to the realm or to a board.\n//\n// A role can optionally be specified to be assigned to the new member.\nfunc InviteMember(cur realm, boardID boards.ID, user address, role boards.Role) {\n\tinviteMembers(0, cur, boardID, Invite{\n\t\tUser: user,\n\t\tRole: role,\n\t})\n}\n\n// InviteMembers adds one or more members to the realm or to a board.\n//\n// Board ID is only required when inviting a member to a specific board.\nfunc InviteMembers(cur realm, boardID boards.ID, invites ...Invite) {\n\tinviteMembers(0, cur, boardID, invites...)\n}\n\n// RequestInvite request to be invited to a board.\nfunc RequestInvite(cur realm, boardID boards.ID) {\n\tassertMembersUpdateIsEnabled(boardID)\n\n\tif !cur.Previous().IsUser() {\n\t\tpanic(\"caller must be user\")\n\t}\n\n\t// TODO: Request a fee (returned on accept) or registered user to avoid spam?\n\t//   WARNING: if a fee is added via unsafe.OriginSend(), the guard above\n\t//   must be tightened to IsUserCall() — IsUser() accepts maketx-run\n\t//   ephemeral realms which can consume the origin-send envelope before\n\t//   calling us, bypassing the fee. See\n\t//   docs/resources/effective-gno.md#verifying-inbound-coin-payments.\n\t// TODO: Make open invite requests optional (per board)\n\n\tboard := mustGetBoard(boardID)\n\tuser := cur.Previous().Address()\n\tif board.Permissions.HasUser(user) {\n\t\tpanic(\"caller is already a member\")\n\t}\n\n\tinvitee := user.String()\n\trequests, found := getInviteRequests(boardID)\n\tif !found {\n\t\trequests = bptree.NewBPTree32()\n\t\trequests.Set(invitee, time.Now())\n\t\tgInviteRequests.Set(boardID.Key(), requests)\n\t\treturn\n\t}\n\n\tif requests.Has(invitee) {\n\t\tpanic(\"invite request already exists\")\n\t}\n\n\trequests.Set(invitee, time.Now())\n}\n\n// AcceptInvite accepts a board invite request.\nfunc AcceptInvite(cur realm, boardID boards.ID, user address) {\n\tassertMembersUpdateIsEnabled(boardID)\n\tassertInviteRequestExists(boardID, user)\n\n\tboard := mustGetBoard(boardID)\n\tif board.Permissions.HasUser(user) {\n\t\tpanic(\"user is already a member\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\tinvite := Invite{\n\t\tUser: user,\n\t\tRole: RoleGuest,\n\t}\n\targs := boards.Args{caller, boardID, []Invite{invite}}\n\tboard.Permissions.WithPermission(caller, PermissionMemberInvite, args, func() {\n\t\tassertMembersUpdateIsEnabled(boardID)\n\n\t\tinvitee := user.String()\n\t\trequests, found := getInviteRequests(boardID)\n\t\tif !found || !requests.Has(invitee) {\n\t\t\tpanic(\"invite request not found\")\n\t\t}\n\n\t\tif board.Permissions.HasUser(user) {\n\t\t\tpanic(\"user is already a member\")\n\t\t}\n\n\t\tboard.Permissions.SetUserRoles(user)\n\t\trequests.Remove(invitee)\n\n\t\tchain.Emit(\n\t\t\t\"MembersInvited\",\n\t\t\t\"invitedBy\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"members\", user.String()+\":\"+string(RoleGuest), // TODO: Support optional role assign\n\t\t)\n\t})\n}\n\n// RevokeInvite revokes a board invite request.\nfunc RevokeInvite(cur realm, boardID boards.ID, user address) {\n\tassertInviteRequestExists(boardID, user)\n\n\tboard := mustGetBoard(boardID)\n\tcaller := cur.Previous().Address()\n\targs := boards.Args{boardID, user, RoleGuest}\n\tboard.Permissions.WithPermission(caller, PermissionMemberInviteRevoke, args, func() {\n\t\tinvitee := user.String()\n\t\trequests, found := getInviteRequests(boardID)\n\t\tif !found || !requests.Has(invitee) {\n\t\t\tpanic(\"invite request not found\")\n\t\t}\n\n\t\trequests.Remove(invitee)\n\n\t\tchain.Emit(\n\t\t\t\"InviteRevoked\",\n\t\t\t\"revokedBy\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"user\", user.String(),\n\t\t)\n\t})\n}\n\nfunc inviteMembers(_ int, rlm realm, boardID boards.ID, invites ...Invite) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tif len(invites) == 0 {\n\t\tpanic(\"one or more user invites are required\")\n\t}\n\n\tassertMembersUpdateIsEnabled(boardID)\n\tassertNoDuplicatedInvites(invites)\n\n\tperms := mustGetPermissions(boardID)\n\tcaller := rlm.Previous().Address()\n\targs := boards.Args{caller, boardID, invites}\n\tperms.WithPermission(caller, PermissionMemberInvite, args, func() {\n\t\tassertMembersUpdateIsEnabled(boardID)\n\n\t\tusers := make([]string, len(invites))\n\t\tfor _, v := range invites {\n\t\t\tassertMemberAddressIsValid(v.User)\n\n\t\t\tif perms.HasUser(v.User) {\n\t\t\t\tpanic(\"user is already a member: \" + v.User.String())\n\t\t\t}\n\n\t\t\t// NOTE: Permissions implementation should check that role is valid\n\t\t\tperms.SetUserRoles(v.User, v.Role)\n\t\t\tusers = append(users, v.User.String()+\":\"+string(v.Role))\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"MembersInvited\",\n\t\t\t\"invitedBy\", caller.String(),\n\t\t\t\"boardID\", boardID.String(),\n\t\t\t\"members\", strings.Join(users, \",\"),\n\t\t)\n\t})\n}\n\nfunc assertInviteRequestExists(boardID boards.ID, user address) {\n\tinvitee := user.String()\n\trequests, found := getInviteRequests(boardID)\n\tif !found || !requests.Has(invitee) {\n\t\tpanic(\"invite request not found\")\n\t}\n}\n\nfunc assertNoDuplicatedInvites(invites []Invite) {\n\tif len(invites) == 1 {\n\t\treturn\n\t}\n\n\tseen := make(map[address]struct{}, len(invites))\n\tfor _, v := range invites {\n\t\tif _, found := seen[v.User]; found {\n\t\t\tpanic(\"duplicated invite: \" + v.User.String())\n\t\t}\n\n\t\tseen[v.User] = struct{}{}\n\t}\n}\n"},{"name":"public_lock.gno","body":"package boards2\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\n// LockRealm locks the realm making it readonly.\n//\n// WARNING: Realm can't be unlocked once locked.\n//\n// Realm can also be locked without locking realm members.\n// Realm members can be locked when locking the realm or afterwards.\n// This is relevant for two reasons, one so that members can be modified after the lock.\n// The other is for realm owners, who can delete threads and comments after the lock.\nfunc LockRealm(cur realm, lockRealmMembers bool) {\n\tassertRealmMembersAreNotLocked()\n\n\t// If realm members are not being locked assert that realm is not locked.\n\t// Members can be locked after locking the realm, in a second `LockRealm` call.\n\tif !lockRealmMembers {\n\t\tassertRealmIsNotLocked()\n\t}\n\n\tcaller := cur.Previous().Address()\n\tgPerms.WithPermission(caller, PermissionRealmLock, boards.Args{}, func() {\n\t\tgLocked.realm = true\n\t\tgLocked.realmMembers = lockRealmMembers\n\n\t\tchain.Emit(\n\t\t\t\"RealmLocked\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"lockRealmMembers\", strconv.FormatBool(lockRealmMembers),\n\t\t)\n\t})\n}\n\n// IsRealmLocked checks if boards realm has been locked.\nfunc IsRealmLocked() bool {\n\treturn gLocked.realm\n}\n\n// AreRealmMembersLocked checks if realm members have been locked.\nfunc AreRealmMembersLocked() bool {\n\treturn gLocked.realmMembers\n}\n\nfunc assertRealmIsNotLocked() { // TODO: Add filtests for locked realm case to all public functions\n\tif gLocked.realm {\n\t\tpanic(\"realm is locked\")\n\t}\n}\n\nfunc assertRealmMembersAreNotLocked() { // TODO: Add filtests for locked members case to all public member functions\n\tif gLocked.realmMembers {\n\t\tpanic(\"realm and members are locked\")\n\t}\n}\n"},{"name":"render.gno","body":"package boards2\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/jeronimoalbi/mdform/v0\"\n\t\"gno.land/p/jeronimoalbi/pager/v0\"\n\t\"gno.land/p/leon/svgbtn/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/nt/markdown/foreign/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n)\n\nconst (\n\tpageSizeDefault = 6\n\tpageSizeReplies = 10\n\t// pageSizeFlat is the page size of the flat \"all comments\" view (?flat=1).\n\t// Each comment renders exactly one \u003cgno-foreign\u003e block (no recursion); with\n\t// the OP (and any repost-source body) the per-page total stays well under\n\t// maxRenderedBodies, so a flat page can't hit the render cap.\n\tpageSizeFlat = 50\n)\n\n// maxRenderedBodies caps user bodies wrapped in \u003cgno-foreign\u003e per page\n// render, kept a margin under gnoweb's per-render foreign-block cap\n// (foreign.MaxBlocksPerRender, sourced from chain/markdown so it can't\n// drift from the renderer). On reaching it the tree stops descending\n// and shows a truncation notice instead of letting the renderer blank\n// comments past the cap. The margin absorbs the OP, repost source\n// bodies, and chrome.\n//\n// Computed lazily (a func, not a package-level var) so it tracks the\n// native cap across chain upgrades: a var initializer runs once at\n// realm-init and persists, freezing a stale value if the underlying\n// MaxBlocksPerRender ever changes; recomputing per render re-reads it.\nfunc maxRenderedBodies() int {\n\treturn foreign.MaxBlocksPerRender() - 10\n}\n\n// sortToggleLink builds the asc/desc sort-toggle link for path. The label\n// names the DESTINATION order (what you get by clicking), not the order you're\n// currently viewing, and ?page= is reset since page N of one order is a\n// different slice in the other. It reports whether the CURRENT order is\n// descending, so callers can drive their own (signed-count or reverse-iterate)\n// pagination. Other query params (e.g. flat=1) are preserved.\nfunc sortToggleLink(path string) (link string, desc bool) {\n\tr := parseRealmPath(path)\n\tdesc = r.Query.Get(\"order\") == \"desc\"\n\tr.Query.Del(\"page\")\n\tif desc {\n\t\tr.Query.Set(\"order\", \"asc\")\n\t\treturn md.Link(\"oldest first\", r.String()), true\n\t}\n\tr.Query.Set(\"order\", \"desc\")\n\treturn md.Link(\"newest first\", r.String()), false\n}\n\nconst menuManageBoard = \"manageBoard\"\n\nvar (\n\tcreateBoardURI = gRealmPath + \":create-board\"\n\tadminUsersURI  = gRealmPath + \":admin-users\"\n\thelpURI        = gRealmPath + \":help\"\n)\n\nfunc Render(path string) string {\n\tvar (\n\t\tb      strings.Builder\n\t\trouter = mux.NewRouter()\n\t)\n\n\trouter.HandleFunc(\"\", renderBoardsList)\n\trouter.HandleFunc(\"help\", renderHelp)\n\trouter.HandleFunc(\"admin-users\", renderMembers)\n\trouter.HandleFunc(\"create-board\", renderCreateBoard)\n\trouter.HandleFunc(\"{board}\", renderBoard)\n\trouter.HandleFunc(\"{board}/members\", renderMembers)\n\trouter.HandleFunc(\"{board}/invites\", renderInvites)\n\trouter.HandleFunc(\"{board}/banned-users\", renderBannedUsers)\n\trouter.HandleFunc(\"{board}/create-thread\", renderCreateThread)\n\trouter.HandleFunc(\"{board}/invite-member\", renderInviteMember)\n\trouter.HandleFunc(\"{board}/{thread}\", renderThread)\n\trouter.HandleFunc(\"{board}/{thread}/flag\", renderFlagPost)\n\trouter.HandleFunc(\"{board}/{thread}/flagging-reasons\", renderFlaggingReasonsPost)\n\trouter.HandleFunc(\"{board}/{thread}/reply\", renderReplyPost)\n\trouter.HandleFunc(\"{board}/{thread}/edit\", renderEditThread)\n\trouter.HandleFunc(\"{board}/{thread}/repost\", renderRepostThread)\n\trouter.HandleFunc(\"{board}/{thread}/{reply}\", renderReply)\n\trouter.HandleFunc(\"{board}/{thread}/{reply}/flag\", renderFlagPost)\n\trouter.HandleFunc(\"{board}/{thread}/{reply}/flagging-reasons\", renderFlaggingReasonsPost)\n\trouter.HandleFunc(\"{board}/{thread}/{reply}/reply\", renderReplyPost)\n\trouter.HandleFunc(\"{board}/{thread}/{reply}/edit\", renderEditReply)\n\n\trouter.NotFoundHandler = func(res *mux.ResponseWriter, _ *mux.Request) {\n\t\tres.Write(md.Blockquote(\"Path not found\"))\n\t}\n\n\t// Render common realm header before resolving render path\n\tif Notice != \"\" {\n\t\tb.WriteString(infoAlert(\"Notice\", Notice))\n\t}\n\n\t// Render view for current path\n\tb.WriteString(router.Render(path))\n\n\treturn b.String()\n}\n\nfunc renderHelp(res *mux.ResponseWriter, _ *mux.Request) {\n\tres.Write(md.H1(\"Boards Help\"))\n\tif Help != \"\" {\n\t\tres.Write(Help)\n\t\treturn\n\t}\n\n\tlink := RealmLink.Call(\"SetHelp\", \"content\", \"\")\n\tres.Write(md.H3(\"Help content has not been uploaded\"))\n\tres.Write(\"Do you want to \" + md.Link(\"upload boards help\", link) + \"?\")\n}\n\nfunc renderBoardsList(res *mux.ResponseWriter, req *mux.Request) {\n\tres.Write(md.H1(\"Boards\"))\n\trenderBoardListMenu(res, req)\n\tres.Write(md.HorizontalRule())\n\n\tp := newClampedPager(req.RawPath, gListedBoardsByID.Size(), pageSizeDefault)\n\n\trender := func(_ string, v any) bool {\n\t\tboard := v.(*boards.Board)\n\t\tuserLink := userLink(board.Creator)\n\t\tdate := board.CreatedAt.Format(dateFormat)\n\n\t\tres.Write(md.H6(md.Link(board.Name, makeBoardURI(board))))\n\t\tres.Write(\"Created by \" + userLink + \" on \" + date + \", #\" + board.ID.String() + \"  \\n\")\n\n\t\tstatus := strconv.Itoa(board.Threads.Size()) + \" threads\"\n\t\tif board.Readonly {\n\t\t\tstatus += \", read-only\"\n\t\t}\n\n\t\tres.Write(md.Bold(status) + \"\\n\\n\")\n\t\treturn false\n\t}\n\n\tres.Write(\"Sort by: \")\n\tlink, desc := sortToggleLink(req.RawPath)\n\tres.Write(link + \"\\n\\n\")\n\tif desc {\n\t\tgListedBoardsByID.ReverseIterateByOffset(p.Offset(), p.PageSize(), render)\n\t} else {\n\t\tgListedBoardsByID.IterateByOffset(p.Offset(), p.PageSize(), render)\n\t}\n\n\tif p.HasPages() {\n\t\tres.Write(md.HorizontalRule())\n\t\tres.Write(pager.Picker(p))\n\t}\n}\n\nfunc renderBoardListMenu(res *mux.ResponseWriter, req *mux.Request) {\n\tres.Write(md.Link(\"Create Board\", createBoardURI))\n\tres.Write(\" • \")\n\tres.Write(md.Link(\"List Admin Users\", adminUsersURI))\n\tres.Write(\" • \")\n\tres.Write(md.Link(\"Help\", helpURI))\n\tres.Write(\"\\n\\n\")\n}\n\nfunc renderCreateBoard(res *mux.ResponseWriter, _ *mux.Request) {\n\tform := mdform.New(\"exec\", \"CreateBoard\")\n\tform.Input(\n\t\t\"name\",\n\t\t\"placeholder\", \"Board name\",\n\t\t\"required\", \"true\",\n\t)\n\tform.Radio(\n\t\t\"listed\",\n\t\t\"true\",\n\t\t\"checked\", \"true\",\n\t\t\"description\", \"Should board be publicly listed?\",\n\t)\n\tform.Radio(\n\t\t\"listed\",\n\t\t\"false\",\n\t)\n\tform.Radio(\n\t\t\"open\",\n\t\t\"true\",\n\t\t\"description\", \"Should anyone be allowed to create threads and comments?\",\n\t)\n\tform.Radio(\n\t\t\"open\",\n\t\t\"false\",\n\t\t\"checked\", \"true\",\n\t)\n\n\tres.Write(md.H1(\"Boards: Create Board\"))\n\tres.Write(md.Link(\"← Back to boards\", gRealmPath) + \"\\n\\n\")\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\t\"Boards are by default listed by the realm but they can optionally \" +\n\t\t\t\t\"be created so they are only found by their URL.\",\n\t\t),\n\t)\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\t\"They can also be created to be open so anyone is allowed to create \" +\n\t\t\t\t\"new threads and also to comment on any thread within the open board.\",\n\t\t),\n\t)\n\tres.Write(form.String())\n\tres.Write(\"\\n\\n**Done?** \" + svgbtn.ButtonWithRadius(136, 32, 4, \"#E2E2E2\", \"#54595D\", \"Return to boards\", gRealmPath) + \"\\n\")\n}\n\nfunc renderMembers(res *mux.ResponseWriter, req *mux.Request) {\n\tboardID := boards.ID(0)\n\tperms := gPerms\n\tname := req.GetVar(\"board\")\n\tif name != \"\" {\n\t\tboard, found := gBoards.GetByName(name)\n\t\tif !found {\n\t\t\tres.Write(md.H3(\"Board not found\"))\n\t\t\treturn\n\t\t}\n\n\t\tboardID = board.ID\n\t\tperms = board.Permissions\n\n\t\tres.Write(md.H1(board.Name + \" Members\"))\n\t\tres.Write(md.H3(\"These are the board members\"))\n\t} else {\n\t\tres.Write(md.H1(\"Admin Users\"))\n\t\tres.Write(md.H3(\"These are the admin users of the realm\"))\n\t}\n\n\t// Create a pager with a small page size to reduce\n\t// the number of username lookups per page.\n\tp := newClampedPager(req.RawPath, perms.UsersCount(), pageSizeDefault)\n\n\ttable := mdtable.Table{\n\t\tHeaders: []string{\"Member\", \"Role\", \"Actions\"},\n\t}\n\n\tperms.IterateUsers(p.Offset(), p.PageSize(), func(u boards.User) bool {\n\t\tactions := []string{\n\t\t\tmd.Link(\"remove\", RealmLink.Call(\n\t\t\t\t\"RemoveMember\",\n\t\t\t\t\"boardID\", boardID.String(),\n\t\t\t\t\"member\", u.Address.String(),\n\t\t\t)),\n\t\t\tmd.Link(\"change role\", RealmLink.Call(\n\t\t\t\t\"ChangeMemberRole\",\n\t\t\t\t\"boardID\", boardID.String(),\n\t\t\t\t\"member\", u.Address.String(),\n\t\t\t\t\"role\", \"\",\n\t\t\t)),\n\t\t}\n\n\t\ttable.Append([]string{\n\t\t\tuserLink(u.Address),\n\t\t\trolesToString(u.Roles),\n\t\t\tstrings.Join(actions, \" • \"),\n\t\t})\n\t\treturn false\n\t})\n\tres.Write(table.String())\n\n\tif p.HasPages() {\n\t\tres.Write(\"\\n\" + pager.Picker(p))\n\t}\n}\n\nfunc renderInvites(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(md.H3(\"Board not found\"))\n\t\treturn\n\t}\n\n\tres.Write(md.H1(board.Name + \" Invite Requests\"))\n\n\trequests, found := getInviteRequests(board.ID)\n\tif !found || requests.Size() == 0 {\n\t\tres.Write(md.H3(\"Board has no invite requests\"))\n\t\treturn\n\t}\n\n\tp := newClampedPager(req.RawPath, requests.Size(), pageSizeDefault)\n\n\ttable := mdtable.Table{\n\t\tHeaders: []string{\"User\", \"Request Date\", \"Actions\"},\n\t}\n\n\tres.Write(md.H3(\"These users have requested to be invited to the board\"))\n\trequests.ReverseIterateByOffset(p.Offset(), p.PageSize(), func(addr string, v any) bool {\n\t\tactions := []string{\n\t\t\tmd.Link(\"accept\", RealmLink.Call(\n\t\t\t\t\"AcceptInvite\",\n\t\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\t\"user\", addr,\n\t\t\t)),\n\t\t\tmd.Link(\"revoke\", RealmLink.Call(\n\t\t\t\t\"RevokeInvite\",\n\t\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\t\"user\", addr,\n\t\t\t)),\n\t\t}\n\n\t\ttable.Append([]string{\n\t\t\tuserLink(address(addr)),\n\t\t\tv.(time.Time).Format(dateFormat),\n\t\t\tstrings.Join(actions, \" • \"),\n\t\t})\n\t\treturn false\n\t})\n\n\tres.Write(table.String())\n\n\tif p.HasPages() {\n\t\tres.Write(\"\\n\" + pager.Picker(p))\n\t}\n}\n\nfunc renderBannedUsers(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(md.H3(\"Board not found\"))\n\t\treturn\n\t}\n\n\tres.Write(md.H1(board.Name + \" Banned Users\"))\n\n\tbanned, found := getBannedUsers(board.ID)\n\tif !found || banned.Size() == 0 {\n\t\tres.Write(md.H3(\"Board has no banned users\"))\n\t\treturn\n\t}\n\n\tp := newClampedPager(req.RawPath, banned.Size(), pageSizeDefault)\n\n\ttable := mdtable.Table{\n\t\tHeaders: []string{\"User\", \"Banned Until\", \"Actions\"},\n\t}\n\n\tres.Write(md.H3(\"These users have been banned from the board\"))\n\tbanned.ReverseIterateByOffset(p.Offset(), p.PageSize(), func(addr string, v any) bool {\n\t\ttable.Append([]string{\n\t\t\tuserLink(address(addr)),\n\t\t\tv.(time.Time).Format(dateFormat),\n\t\t\tmd.Link(\"unban\", RealmLink.Call(\n\t\t\t\t\"Unban\",\n\t\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\t\"user\", addr,\n\t\t\t\t\"reason\", \"\",\n\t\t\t)),\n\t\t})\n\t\treturn false\n\t})\n\n\tres.Write(table.String())\n\n\tif p.HasPages() {\n\t\tres.Write(\"\\n\" + pager.Picker(p))\n\t}\n}\n\nfunc infoAlert(title, msg string) string {\n\theader := strings.TrimSpace(\"[!INFO] \" + title)\n\treturn md.Blockquote(header + \"\\n\" + msg)\n}\n\nfunc rolesToString(roles []boards.Role) string {\n\tif len(roles) == 0 {\n\t\treturn \"\"\n\t}\n\n\tnames := make([]string, len(roles))\n\tfor i, r := range roles {\n\t\tnames[i] = string(r)\n\t}\n\treturn strings.Join(names, \", \")\n}\n\nfunc menuURL(name string) string {\n\t// TODO: Menu URL works because no other GET arguments are being used\n\treturn \"?menu=\" + name\n}\n\nfunc getCurrentMenu(rawURL string) string {\n\t_, rawQuery, found := strings.Cut(rawURL, \"?\")\n\tif !found {\n\t\treturn \"\"\n\t}\n\n\tquery, _ := url.ParseQuery(rawQuery)\n\treturn query.Get(\"menu\")\n}\n"},{"name":"render_board.gno","body":"package boards2\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/jeronimoalbi/mdform/v0\"\n\t\"gno.land/p/jeronimoalbi/pager/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/mdalert/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n)\n\nfunc renderBoard(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(md.H3(\"The board you are looking for does not exist\"))\n\t\tres.Write(\"Do you want to \" + md.Link(\"create a new board\", createBoardURI) + \"?\")\n\t\treturn\n\t}\n\n\tcreatorLink := userLink(board.Creator)\n\tdate := board.CreatedAt.Format(dateFormat)\n\n\tres.Write(md.H1(md.Link(\"Boards\", gRealmPath) + \" › \" + board.Name))\n\tif board.Readonly {\n\t\tres.Write(\n\t\t\tmdalert.Warning(\"Info\", \"Creating new threads and commenting are disabled within this board\") + \"\\n\",\n\t\t)\n\t}\n\n\tres.Write(\"Created by \" + creatorLink + \" on \" + date + \", #\" + board.ID.String())\n\tres.Write(\"  \\n\" + renderBoardMenu(board, req))\n\tres.Write(md.HorizontalRule())\n\n\tif board.Threads.Size() == 0 {\n\t\tres.Write(md.H3(\"This board doesn't have any threads\"))\n\t\tif !board.Readonly {\n\t\t\tstartConversationLink := md.Link(\"start a new conversation\", makeCreateThreadURI(board))\n\t\t\tres.Write(\"Do you want to \" + startConversationLink + \" in this board?\")\n\t\t}\n\t\treturn\n\t}\n\n\tp := newClampedPager(req.RawPath, board.Threads.Size(), pageSizeDefault)\n\n\trender := func(thread *boards.Post) bool {\n\t\tres.Write(renderThreadSummary(thread) + \"\\n\")\n\t\treturn false\n\t}\n\n\tres.Write(\"Sort by: \")\n\n\tlink, desc := sortToggleLink(req.RawPath)\n\tres.Write(link + \"\\n\\n\")\n\n\tcount := p.PageSize()\n\tif desc {\n\t\tcount = -count // Reverse iterate\n\t}\n\n\tboard.Threads.Iterate(p.Offset(), count, render)\n\n\tif p.HasPages() {\n\t\tres.Write(md.HorizontalRule())\n\t\tres.Write(pager.Picker(p))\n\t}\n}\n\n// renderSubMenu renders a sub-menu with a distinct visual pattern.\nfunc renderSubMenu(items []string) string {\n\tif len(items) == 0 {\n\t\treturn \"\"\n\t}\n\treturn \"└─ \" + strings.Join(items, \" • \") + \"\\n\"\n}\n\nfunc renderBoardMenu(board *boards.Board, req *mux.Request) string {\n\tvar (\n\t\tb               strings.Builder\n\t\tboardMembersURL = makeBoardURI(board) + \"/members\"\n\t)\n\n\tif board.Readonly {\n\t\tb.WriteString(md.Link(\"List Members\", boardMembersURL))\n\t\tb.WriteString(\" • \")\n\t\tb.WriteString(md.Link(\"Unfreeze Board\", makeUnfreezeBoardURI(board)))\n\t\tb.WriteString(\"\\n\")\n\t} else {\n\t\tb.WriteString(\"↳ \")\n\t\tb.WriteString(md.Link(\"Create Thread\", makeCreateThreadURI(board)))\n\t\tb.WriteString(\" • \")\n\t\tb.WriteString(md.Link(\"Request Invite\", makeRequestInviteURI(board)))\n\t\tb.WriteString(\" • \")\n\n\t\tmenu := getCurrentMenu(req.RawPath)\n\t\tif menu == menuManageBoard {\n\t\t\tb.WriteString(md.Bold(\"Manage Board\"))\n\t\t} else {\n\t\t\tb.WriteString(md.Link(\"Manage Board\", menuURL(menuManageBoard)))\n\t\t}\n\n\t\tb.WriteString(\"  \\n\")\n\n\t\tif menu == menuManageBoard {\n\t\t\tsubMenuItems := []string{\n\t\t\t\tmd.Link(\"Invite Member\", makeInviteMemberURI(board)),\n\t\t\t\tmd.Link(\"List Invite Requests\", makeBoardURI(board)+\"/invites\"),\n\t\t\t\tmd.Link(\"List Members\", boardMembersURL),\n\t\t\t\tmd.Link(\"List Banned Users\", makeBoardURI(board)+\"/banned-users\"),\n\t\t\t\tmd.Link(\"Freeze Board\", makeFreezeBoardURI(board)),\n\t\t\t}\n\t\t\tb.WriteString(renderSubMenu(subMenuItems))\n\t\t}\n\t}\n\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\nfunc renderInviteMember(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\tform := mdform.New(\"exec\", \"InviteMember\")\n\tform.Input(\n\t\t\"boardID\",\n\t\t\"placeholder\", \"Board ID\",\n\t\t\"value\", board.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"user\",\n\t\t\"placeholder\", \"Address\",\n\t\t\"required\", \"true\",\n\t)\n\tform.Select(\n\t\t\"role\",\n\t\tstring(RoleOwner),\n\t)\n\tform.Select(\n\t\t\"role\",\n\t\tstring(RoleAdmin),\n\t)\n\tform.Select(\n\t\t\"role\",\n\t\tstring(RoleModerator),\n\t)\n\tform.Select(\n\t\t\"role\",\n\t\tstring(RoleGuest),\n\t\t\"selected\", \"true\",\n\t)\n\n\tres.Write(md.H1(board.Name + \": Invite Member\"))\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\t\"Both open and invite only boards can have multiple members with different roles within a \"+\n\t\t\t\t\"board, where members can have a single role at a time.\",\n\t\t) +\n\t\t\tmd.Paragraph(\n\t\t\t\t\"Boards are independent communities which could apply different permissions per role than \"+\n\t\t\t\t\t\"other boards, but generally Boards2 supports four roles, _owner_, _admin_, _moderator_ \"+\n\t\t\t\t\t\"and _guest_.\",\n\t\t\t) +\n\t\t\tmd.Paragraph(\n\t\t\t\t\"Member will be added to \"+md.Link(board.Name, makeBoardURI(board))+\" board.\",\n\t\t\t),\n\t)\n\tres.Write(form.String())\n}\n"},{"name":"render_post.gno","body":"package boards2\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/jeronimoalbi/mdform/v0\"\n\t\"gno.land/p/leon/svgbtn/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/nt/markdown/foreign/v0\"\n\t\"gno.land/p/nt/mdalert/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// renderPost renders a post and (unless it's a leaf or capped) its replies.\n// desc is the page's sort order, forwarded so a comment's nested inline\n// children (renderSubReplies) match the order of the view they appear in. It\n// is unused for the top-level/re-root call (path != \"\" routes to\n// renderTopLevelReplies, which derives the order from the path); those\n// callers pass false.\nfunc renderPost(post *boards.Post, path, indent string, levels int, budget *int, desc bool) string {\n\tvar b strings.Builder\n\n\t// Thread reposts might not have a title, if so get title from source thread\n\ttitle := post.Title\n\tif boards.IsRepost(post) \u0026\u0026 title == \"\" {\n\t\tif board, ok := gBoards.Get(post.OriginalBoardID); ok {\n\t\t\tif src, ok := getThread(board, post.ParentID); ok {\n\t\t\t\ttitle = src.Title\n\t\t\t}\n\t\t}\n\t}\n\n\tif title != \"\" { // Replies don't have a title\n\t\tb.WriteString(md.H2(md.EscapeText(title)))\n\t}\n\n\tb.WriteString(indent + \"\\n\")\n\tb.WriteString(renderPostContent(post, indent, levels, budget))\n\n\tif post.Replies.Size() == 0 {\n\t\treturn b.String()\n\t}\n\n\t// In practice this only fires for the re-rooted view's context-parent,\n\t// which renderPostInner renders with an explicit levels==0. The thread\n\t// recursion does levels-1 in BOTH renderPost and renderTopLevelReplies/\n\t// renderSubReplies, so levels drops by 2 per nesting level and skips 0 —\n\t// i.e. levels does NOT bound depth in the thread view; the render budget\n\t// and the per-node breadth cap (renderSubReplies) are the real bounds.\n\tif levels == 0 {\n\t\tb.WriteString(indent + \"\\n\")\n\t\treturn b.String()\n\t}\n\n\tif path != \"\" {\n\t\tb.WriteString(renderTopLevelReplies(post, path, indent, levels-1, budget))\n\t} else {\n\t\tb.WriteString(renderSubReplies(post, indent, levels-1, budget, desc))\n\t}\n\treturn b.String()\n}\n\nfunc renderPostContent(post *boards.Post, indent string, levels int, budget *int) string {\n\tvar b strings.Builder\n\n\t// Author and date header\n\tcreatorLink := userLink(post.Creator)\n\troleBadge := getRoleBadge(post)\n\tdate := post.CreatedAt.Format(dateFormat)\n\tb.WriteString(indent)\n\tb.WriteString(md.Bold(creatorLink) + roleBadge + \" · \" + date)\n\tif !boards.IsThread(post) {\n\t\tb.WriteString(\" \" + md.Link(\"#\"+post.ID.String(), makeReplyURI(post)))\n\t}\n\tb.WriteString(\"  \\n\")\n\n\t// Flagged comment should be hidden, but replies still visible (see: #3480)\n\t// Flagged threads will be hidden by render function caller.\n\tif post.Hidden {\n\t\tlink := md.Link(\"inappropriate\", makeFlaggingReasonsURI(post))\n\t\tb.WriteString(indentBody(indent, \"⚠ Reply is hidden as it has been flagged as \"+link))\n\t\tb.WriteString(\"\\n\")\n\t\treturn b.String()\n\t}\n\n\tsrcContent, srcPost := renderSourcePost(post, indent, budget)\n\tif boards.IsRepost(post) \u0026\u0026 srcPost != nil {\n\t\tmsg := ufmt.Sprintf(\n\t\t\t\"Original thread is %s  \\nCreated by %s on %s\",\n\t\t\tmd.Link(srcPost.Title, makeThreadURI(srcPost)),\n\t\t\tuserLink(srcPost.Creator),\n\t\t\tsrcPost.CreatedAt.Format(dateFormat),\n\t\t)\n\n\t\tb.WriteString(mdalert.New(mdalert.TypeInfo, \"Thread Repost\", msg, true).String())\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\t// Render repost body before original thread's body\n\tif post.Body != \"\" {\n\t\tb.WriteString(indentForeignBody(indent, post.Body, budget) + \"\\n\")\n\t\tif srcContent != \"\" {\n\t\t\t// Add extra line to separate repost content from original thread content\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\tb.WriteString(srcContent)\n\n\t// Add a newline to separate source deleted message from repost body content\n\tif boards.IsRepost(post) \u0026\u0026 srcPost == nil \u0026\u0026 len(post.Body) \u003e 0 {\n\t\tb.WriteString(\"\\n\\n\")\n\t}\n\n\t// Split thread content and actions\n\tif boards.IsThread(post) \u0026\u0026 !boards.IsRepost(post) {\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\t// Action buttons\n\tb.WriteString(indent)\n\tif !boards.IsThread(post) { // is comment\n\t\tb.WriteString(\"  \\n\")\n\t\tb.WriteString(indent)\n\t}\n\n\tactions := []string{\n\t\tmd.Link(\"Flag\", makeFlagURI(post)),\n\t}\n\n\tif boards.IsThread(post) {\n\t\trepostAction := md.Link(\"Repost\", makeCreateRepostURI(post))\n\t\tif post.Reposts.Size() \u003e 0 {\n\t\t\trepostAction += \" [\" + strconv.Itoa(post.Reposts.Size()) + \"]\"\n\t\t}\n\t\tactions = append(actions, repostAction)\n\t}\n\n\tisReadonly := post.Readonly || post.Board.Readonly\n\t// A reply doesn't carry the thread's frozen flag (FreezeThread sets\n\t// Readonly on the thread post only), so check the enclosing thread too —\n\t// otherwise a frozen thread's replies show Reply/Edit/Delete links that\n\t// the backend rejects. Mirrors the IsReadonly helper (board || thread).\n\tif !isReadonly \u0026\u0026 !boards.IsThread(post) {\n\t\tif t, ok := getThread(post.Board, post.ThreadID); ok {\n\t\t\tisReadonly = t.Readonly\n\t\t}\n\t}\n\tif !isReadonly {\n\t\treplyLabel := \"Reply\"\n\t\tif boards.IsThread(post) {\n\t\t\treplyLabel = \"Comment\"\n\t\t}\n\t\treplyAction := md.Link(replyLabel, makeCreateReplyURI(post))\n\t\t// Add reply count if any\n\t\tif post.Replies.Size() \u003e 0 {\n\t\t\treplyAction += \" [\" + strconv.Itoa(post.Replies.Size()) + \"]\"\n\t\t}\n\n\t\tactions = append(\n\t\t\tactions,\n\t\t\treplyAction,\n\t\t\tmd.Link(\"Edit\", makeEditPostURI(post)),\n\t\t\tmd.Link(\"Delete\", makeDeletePostURI(post)),\n\t\t)\n\t}\n\n\tif levels == 0 {\n\t\tswitch {\n\t\tcase boards.IsThread(post):\n\t\t\tactions = append(actions, md.Link(\"Show all Replies\", makeThreadURI(post)))\n\t\tcase post.Replies.Size() \u003e 0:\n\t\t\t// Reached at levels==0 — in practice the re-rooted view's\n\t\t\t// context-parent (see renderPost). It still has replies below, so\n\t\t\t// re-root here (Reddit/HN \"continue this thread\") to keep the\n\t\t\t// subtree drillable instead of bouncing to the thread root.\n\t\t\tactions = append(actions, md.Link(\"Continue this thread →\", makeReplyURI(post)))\n\t\t}\n\t}\n\n\tb.WriteString(\"↳ \" + strings.Join(actions, \" • \") + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderPostInner(post *boards.Post, path string) string {\n\tif boards.IsThread(post) {\n\t\treturn \"\"\n\t}\n\n\tvar (\n\t\ts         string\n\t\tthreadID  = post.ThreadID\n\t\tthread, _ = getThread(post.Board, threadID)\n\t\tbudget    = maxRenderedBodies()\n\t)\n\n\t// Fully render parent if it's not a repost.\n\tif !boards.IsRepost(post) {\n\t\tparentID := post.ParentID\n\t\tparent := thread\n\n\t\tif thread.ID != parentID {\n\t\t\tparent, _ = getReply(thread, parentID)\n\t\t}\n\n\t\ts += renderPost(parent, \"\", \"\", 0, \u0026budget, false) + \"\\n\"\n\t}\n\n\t// Pass the reply's own path so renderPost routes to renderTopLevelReplies\n\t// and paginates this comment's direct replies (the re-root has its own\n\t// ?page= — no collision with the thread view, which is a different path).\n\t// desc=false: order is derived from path by renderTopLevelReplies.\n\ts += renderPost(post, path, \"\u003e \", 5, \u0026budget, false)\n\treturn s\n}\n\nfunc renderSourcePost(post *boards.Post, indent string, budget *int) (string, *boards.Post) {\n\tif !boards.IsRepost(post) {\n\t\treturn \"\", nil\n\t}\n\n\tindent += \"\u003e \"\n\n\t// TODO: figure out a way to decouple posts from a global storage.\n\tboard, ok := gBoards.Get(post.OriginalBoardID)\n\tif !ok {\n\t\t// TODO: Boards can't be deleted so this might be redundant\n\t\treturn indentBody(indent, \"⚠ Source board has been deleted\"), nil\n\t}\n\n\tsrcPost, ok := getThread(board, post.ParentID)\n\tif !ok {\n\t\treturn indentBody(indent, \"⚠ Source post has been deleted\"), nil\n\t}\n\n\tif srcPost.Hidden {\n\t\treturn indentBody(indent, \"⚠ Source post has been flagged as inappropriate\"), nil\n\t}\n\n\treturn indentForeignBody(indent, srcPost.Body, budget) + \"\\n\\n\", srcPost\n}\n\nfunc renderFlagPost(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\t// Thread ID must always be available\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := getThread(board, boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\t// Parse reply ID when post is a reply\n\tvar reply *boards.Post\n\trawID = req.GetVar(\"reply\")\n\tisReply := rawID != \"\"\n\tif isReply {\n\t\treplyID, err := strconv.Atoi(rawID)\n\t\tif err != nil {\n\t\t\tres.Write(\"Invalid reply ID: \" + md.EscapeText(rawID))\n\t\t\treturn\n\t\t}\n\n\t\treply, _ = getReply(thread, boards.ID(replyID))\n\t\tif reply == nil {\n\t\t\tres.Write(\"Reply not found\")\n\t\t\treturn\n\t\t}\n\t}\n\n\texec := \"FlagThread\"\n\tif isReply {\n\t\texec = \"FlagReply\"\n\t}\n\n\tform := mdform.New(\"exec\", exec)\n\tform.Input(\n\t\t\"boardID\",\n\t\t\"placeholder\", \"Board ID\",\n\t\t\"value\", board.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"threadID\",\n\t\t\"placeholder\", \"Thread ID\",\n\t\t\"value\", thread.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\n\tif isReply {\n\t\tform.Input(\n\t\t\t\"replyID\",\n\t\t\t\"placeholder\", \"Reply ID\",\n\t\t\t\"value\", reply.ID.String(),\n\t\t\t\"readonly\", \"true\",\n\t\t)\n\t}\n\n\tform.Input(\n\t\t\"reason\",\n\t\t\"placeholder\", \"Flagging Reason\",\n\t)\n\n\t// Breadcrumb navigation\n\tbackLink := md.Link(\"← Back to thread\", makeThreadURI(thread))\n\n\tif isReply {\n\t\tres.Write(md.H1(board.Name + \": Flag Comment\"))\n\t} else {\n\t\tres.Write(md.H1(board.Name + \": Flag Thread\"))\n\t}\n\tres.Write(backLink + \"\\n\\n\")\n\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\t\"Thread or comment moderation is done through flagging, which is usually done \"+\n\t\t\t\t\"by board members with the moderator role, though other roles could also potentially flag.\",\n\t\t) +\n\t\t\tmd.Paragraph(\n\t\t\t\t\"Flagging relies on a configurable threshold, which by default is of one flag, that when \"+\n\t\t\t\t\t\"reached leads to the flagged thread or comment to be hidden.\",\n\t\t\t) +\n\t\t\tmd.Paragraph(\n\t\t\t\t\"Flagging thresholds can be different within each board.\",\n\t\t\t),\n\t)\n\n\tif isReply {\n\t\tres.Write(\n\t\t\tmd.Paragraph(\n\t\t\t\tufmt.Sprintf(\n\t\t\t\t\t\"⚠ You are flagging a %s from %s ⚠\",\n\t\t\t\t\tmd.Link(\"comment\", makeReplyURI(reply)),\n\t\t\t\t\tuserLink(reply.Creator),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t} else {\n\t\tres.Write(\n\t\t\tmd.Paragraph(\n\t\t\t\tufmt.Sprintf(\n\t\t\t\t\t\"⚠ You are flagging the thread: %s ⚠\",\n\t\t\t\t\tmd.Link(thread.Title, makeThreadURI(thread)),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t}\n\n\tres.Write(form.String())\n\tres.Write(\"\\n\\n**Done?** \" + svgbtn.ButtonWithRadius(136, 32, 4, \"#E2E2E2\", \"#54595D\", \"Return to thread\", makeThreadURI(thread)) + \"\\n\")\n}\n\nfunc renderFlaggingReasonsPost(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\t// Thread ID must always be available\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := getThread(board, boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\tflags := thread.Flags\n\n\t// Parse reply ID when post is a reply\n\tvar reply *boards.Post\n\trawID = req.GetVar(\"reply\")\n\tisReply := rawID != \"\"\n\tif isReply {\n\t\treplyID, err := strconv.Atoi(rawID)\n\t\tif err != nil {\n\t\t\tres.Write(\"Invalid reply ID: \" + md.EscapeText(rawID))\n\t\t\treturn\n\t\t}\n\n\t\treply, found = getReply(thread, boards.ID(replyID))\n\t\tif !found {\n\t\t\tres.Write(\"Reply not found\")\n\t\t\treturn\n\t\t}\n\n\t\tflags = reply.Flags\n\t}\n\n\ttable := mdtable.Table{\n\t\tHeaders: []string{\"Moderator\", \"Reason\"},\n\t}\n\n\tflags.Iterate(0, flags.Size(), func(f boards.Flag) bool {\n\t\t// f.Reason is user-supplied (only trimmed at write); escape it so a\n\t\t// flag reason can't inject markdown (links/images) or HTML into the\n\t\t// reasons table. md.EscapeText leaves '|' for mdtable to escape.\n\t\ttable.Append([]string{userLink(f.User), md.EscapeText(f.Reason)})\n\t\treturn false\n\t})\n\n\t// Breadcrumb navigation\n\tbackLink := md.Link(\"← Back to thread\", makeThreadURI(thread))\n\n\tres.Write(md.H1(\"Flagging Reasons\"))\n\tres.Write(backLink + \"\\n\\n\")\n\tif isReply {\n\t\tres.Write(\n\t\t\tmd.Paragraph(\n\t\t\t\tufmt.Sprintf(\n\t\t\t\t\t\"Moderation flags for a %s submitted by %s\",\n\t\t\t\t\tmd.Link(\"comment\", makeReplyURI(reply)),\n\t\t\t\t\tuserLink(reply.Creator),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t} else {\n\t\tres.Write(\n\t\t\tmd.Paragraph(\n\t\t\t\t// Intentionally hide flagged thread title\n\t\t\t\tufmt.Sprintf(\"Moderation flags for %s\", md.Link(\"thread\", makeThreadURI(thread))),\n\t\t\t),\n\t\t)\n\t}\n\tres.Write(table.String())\n}\n\nfunc renderReplyPost(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\t// Thread ID must always be available\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := board.Threads.Get(boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\t// Parse reply ID when post is a reply\n\tvar reply *boards.Post\n\trawID = req.GetVar(\"reply\")\n\tisReply := rawID != \"\"\n\tif isReply {\n\t\treplyID, err := strconv.Atoi(rawID)\n\t\tif err != nil {\n\t\t\tres.Write(\"Invalid reply ID: \" + md.EscapeText(rawID))\n\t\t\treturn\n\t\t}\n\n\t\treply, _ = getReply(thread, boards.ID(replyID))\n\t\tif reply == nil {\n\t\t\tres.Write(\"Reply not found\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tform := mdform.New(\"exec\", \"CreateReply\")\n\tform.Input(\n\t\t\"boardID\",\n\t\t\"placeholder\", \"Board ID\",\n\t\t\"value\", board.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"threadID\",\n\t\t\"placeholder\", \"Thread ID\",\n\t\t\"value\", thread.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\n\tif isReply {\n\t\tform.Input(\n\t\t\t\"replyID\",\n\t\t\t\"placeholder\", \"Reply ID\",\n\t\t\t\"value\", reply.ID.String(),\n\t\t\t\"readonly\", \"true\",\n\t\t)\n\t} else {\n\t\tform.Input(\n\t\t\t\"replyID\",\n\t\t\t\"placeholder\", \"Reply ID\",\n\t\t\t\"value\", \"0\",\n\t\t\t\"readonly\", \"true\",\n\t\t)\n\t}\n\n\tform.Textarea(\n\t\t\"body\",\n\t\t\"placeholder\", \"Comment\",\n\t\t\"required\", \"true\",\n\t)\n\n\t// Breadcrumb navigation\n\tbackLink := md.Link(\"← Back to thread\", makeThreadURI(thread))\n\n\tif isReply {\n\t\tres.Write(md.H1(board.Name + \": Reply\"))\n\t\tres.Write(backLink + \"\\n\\n\")\n\t\tres.Write(\n\t\t\tmd.Paragraph(ufmt.Sprintf(\"Replying to a comment posted by %s:\", userLink(reply.Creator))) +\n\t\t\t\tforeign.ForeignWithLabel(\"Quoted comment\", reply.Body),\n\t\t)\n\t} else {\n\t\tres.Write(md.H1(board.Name + \": Comment\"))\n\t\tres.Write(backLink + \"\\n\\n\")\n\t\tres.Write(\n\t\t\tmd.Paragraph(\n\t\t\t\tufmt.Sprintf(\"Commenting on the thread: %s\", md.Link(thread.Title, makeThreadURI(thread))),\n\t\t\t),\n\t\t)\n\t}\n\n\tres.Write(form.String())\n\tres.Write(\"\\n\\n**Done?** \" + svgbtn.ButtonWithRadius(136, 32, 4, \"#E2E2E2\", \"#54595D\", \"Return to thread\", makeThreadURI(thread)) + \"\\n\")\n}\n"},{"name":"render_reply.gno","body":"package boards2\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/jeronimoalbi/mdform/v0\"\n\t\"gno.land/p/jeronimoalbi/pager/v0\"\n\t\"gno.land/p/leon/svgbtn/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc renderReply(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\trawID = req.GetVar(\"reply\")\n\treplyID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid reply ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := getThread(board, boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\treply, found := getReply(thread, boards.ID(replyID))\n\tif !found {\n\t\tres.Write(\"Reply not found\")\n\t\treturn\n\t}\n\n\t// Call render even for hidden replies to display children.\n\t// Original comment content will be hidden under the hood.\n\t// See: #3480\n\tres.Write(renderPostInner(reply, req.RawPath))\n}\n\n// newClampedPager builds a pager, clamping an out-of-range, zero, negative,\n// or malformed ?page= to the last valid page instead of erroring. pager.New\n// rejects page==0, page\u003epageCount, and non-numeric pages with\n// ErrInvalidPageNumber, which the callers would otherwise surface as a panic\n// (aborting the whole render) or an error page in place of the list. A\n// NEGATIVE page is not rejected by pager.New (it only checks ==0 and\n// \u003epageCount), so it must be caught here too — otherwise it renders a broken\n// \"page -N of M\" picker with both arrows disabled. Triggers on a stale deep\n// link after deletions, or a hand-edited URL.\nfunc newClampedPager(path string, size, pageSize int) pager.Pager {\n\tp, err := pager.New(path, size, pager.WithPageSize(pageSize))\n\tif err == nil \u0026\u0026 p.Page() \u003e= 1 {\n\t\treturn p\n\t}\n\t// Re-parse without ?page= to get a valid page-1 pager and read the real\n\t// page count, then jump to the last page when there is more than one.\n\tr := parseRealmPath(path)\n\tr.Query.Del(\"page\")\n\tfirst, ferr := pager.New(r.String(), size, pager.WithPageSize(pageSize))\n\tif ferr != nil {\n\t\t// A page-less path is valid for every current route, so this is\n\t\t// unreachable today; fall back to the original pager rather than\n\t\t// asserting the invariant with a panic that would abort the render.\n\t\treturn p\n\t}\n\tif last := first.PageCount(); last \u003e 1 {\n\t\tr.Query.Set(\"page\", strconv.Itoa(last))\n\t\tif clamped, e := pager.New(r.String(), size, pager.WithPageSize(pageSize)); e == nil {\n\t\t\treturn clamped\n\t\t}\n\t}\n\treturn first\n}\n\nfunc renderTopLevelReplies(post *boards.Post, path, indent string, levels int, budget *int) string {\n\tp := newClampedPager(path, post.Replies.Size(), pageSizeReplies)\n\tlink, desc := sortToggleLink(path)\n\n\tvar (\n\t\tb              strings.Builder\n\t\tcommentsIndent = indent + \"\u003e \"\n\t\ttruncated      bool\n\t)\n\n\trender := func(reply *boards.Post) bool {\n\t\tif *budget \u003c= 0 {\n\t\t\ttruncated = true\n\t\t\treturn true // stop: render budget exhausted (see maxRenderedBodies)\n\t\t}\n\t\t// Forward the page order so this reply's nested children match it.\n\t\tb.WriteString(indent + \"\\n\" + renderPost(reply, \"\", commentsIndent, levels-1, budget, desc))\n\t\treturn false\n\t}\n\n\tb.WriteString(\"\\n\" + md.HorizontalRule() + \"Sort by: \" + link + \"\\n\")\n\n\tcount := p.PageSize()\n\tif desc {\n\t\tcount = -count // Reverse iterate\n\t}\n\n\tpost.Replies.Iterate(p.Offset(), count, render)\n\n\tif truncated {\n\t\tb.WriteString(indent + \"\\n\" + commentsIndent + \"_Some replies not shown — \" +\n\t\t\tmd.Link(\"view all comments\", makeThreadFlatURI(post)) + \"._\\n\")\n\t}\n\n\t// Suppress the page picker when the budget truncated this page: later\n\t// replies in the page were skipped, so the offset-based \"next page\" would\n\t// jump past them. The flat link above is the complete, reachable view.\n\tif !truncated \u0026\u0026 p.HasPages() {\n\t\tb.WriteString(md.HorizontalRule())\n\t\tb.WriteString(pager.Picker(p))\n\t}\n\treturn b.String()\n}\n\nfunc renderSubReplies(post *boards.Post, indent string, levels int, budget *int, desc bool) string {\n\tvar (\n\t\tb              strings.Builder\n\t\tcommentsIndent = indent + \"\u003e \"\n\t\ttruncated      bool\n\t)\n\n\t// Cap inline children at pageSizeReplies. A nested reply list can't have\n\t// its own pager (it would collide with the page's ?page=), so instead of\n\t// dumping every child here a comment with more links to its own re-rooted\n\t// view, which paginates them. Keeps every view bounded to \u003c=pageSizeReplies\n\t// children per post. count's sign follows the page order so the inline\n\t// children match the view they appear in (desc → the newest ones).\n\tcount := pageSizeReplies\n\tif desc {\n\t\tcount = -count\n\t}\n\tpost.Replies.Iterate(0, count, func(reply *boards.Post) bool {\n\t\tif *budget \u003c= 0 {\n\t\t\ttruncated = true\n\t\t\treturn true // stop: render budget exhausted (see maxRenderedBodies)\n\t\t}\n\t\tb.WriteString(indent + \"\\n\" + renderPost(reply, \"\", commentsIndent, levels-1, budget, desc))\n\t\treturn false\n\t})\n\n\tnotice := func(text, uri string) {\n\t\tb.WriteString(indent + \"\\n\" + commentsIndent + md.Link(text, uri) + \"\\n\")\n\t}\n\tswitch {\n\tcase truncated:\n\t\t// Budget exhausted: the whole-thread flat view is the reachable backstop.\n\t\tnotice(\"More replies — view all comments\", makeThreadFlatURI(post))\n\tcase post.Replies.Size() \u003e pageSizeReplies:\n\t\t// Breadth cap hit: re-root at this comment to page the rest, carrying\n\t\t// the page's sort order so the re-root opens the same way (its first\n\t\t// page then matches the newest-first children shown inline here).\n\t\turi := makeReplyURI(post)\n\t\tif desc {\n\t\t\turi += \"?order=desc\"\n\t\t}\n\t\tnotice(\"View all \"+strconv.Itoa(post.Replies.Size())+\" replies\", uri)\n\t}\n\treturn b.String()\n}\n\nfunc renderEditReply(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\trawID = req.GetVar(\"reply\")\n\treplyID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid reply ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := getThread(board, boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\treply, found := getReply(thread, boards.ID(replyID))\n\tif !found {\n\t\tres.Write(\"Reply not found\")\n\t\treturn\n\t}\n\n\tform := mdform.New(\"exec\", \"EditReply\")\n\tform.Input(\n\t\t\"boardID\",\n\t\t\"placeholder\", \"Board ID\",\n\t\t\"value\", board.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"threadID\",\n\t\t\"placeholder\", \"Thread ID\",\n\t\t\"value\", thread.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"replyID\",\n\t\t\"placeholder\", \"Reply ID\",\n\t\t\"value\", reply.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Textarea(\n\t\t\"body\",\n\t\t\"placeholder\", \"Comment\",\n\t\t\"value\", reply.Body,\n\t\t\"required\", \"true\",\n\t)\n\n\tres.Write(md.H1(board.Name + \": Edit Comment\"))\n\tres.Write(md.Link(\"← Back to thread\", makeThreadURI(thread)) + \"\\n\\n\")\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\tufmt.Sprintf(\"Editing a comment from the thread: %s\", md.Link(thread.Title, makeThreadURI(thread))),\n\t\t),\n\t)\n\tres.Write(form.String())\n\tres.Write(\"\\n\\n**Done?** \" + svgbtn.ButtonWithRadius(136, 32, 4, \"#E2E2E2\", \"#54595D\", \"Return to thread\", makeThreadURI(thread)) + \"\\n\")\n}\n"},{"name":"render_thread.gno","body":"package boards2\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n\t\"gno.land/p/jeronimoalbi/mdform/v0\"\n\t\"gno.land/p/jeronimoalbi/pager/v0\"\n\t\"gno.land/p/leon/svgbtn/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// maxFlatIndentDepth caps the blockquote nesting in the flat comment view so\n// deep reply chains stay readable; comments deeper than this still render,\n// just at the capped indent.\nconst maxFlatIndentDepth = 6\n\nfunc renderThread(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := getThread(board, boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\tif thread.Hidden {\n\t\tlink := md.Link(\"inappropriate\", makeFlaggingReasonsURI(thread))\n\t\tres.Write(\"⚠ Thread has been flagged as \" + link)\n\t\treturn\n\t}\n\n\tres.Write(md.H1(md.Link(\"Boards\", gRealmPath) + \" › \" + md.Link(board.Name, makeBoardURI(board))))\n\tbudget := maxRenderedBodies()\n\tif parseRealmPath(req.RawPath).Query.Get(\"flat\") != \"\" {\n\t\tres.Write(renderThreadFlat(thread, req.RawPath, \u0026budget))\n\t\treturn\n\t}\n\tres.Write(renderPost(thread, req.RawPath, \"\", 5, \u0026budget, false))\n}\n\n// renderThreadFlat renders every comment in the thread as a single flat,\n// depth-indented, paginated list backed by ThreadMeta.AllReplies (the index\n// that already holds every reply at every depth). Unlike the recursive\n// threaded view — which bounds work with the render budget and truncates a\n// large subtree — this view is reachable to the very last comment: each\n// comment renders one \u003cgno-foreign\u003e block (no recursion), so a fixed page\n// size (pageSizeFlat) plus the OP stays well under the budget regardless of\n// nesting, and the pager always advances. ?order=desc shows newest first, so\n// its page 1 is the latest comments.\nfunc renderThreadFlat(thread *boards.Post, path string, budget *int) string {\n\tvar b strings.Builder\n\n\t// The OP for context (its body only; no replies — levels 0).\n\tb.WriteString(renderPost(thread, \"\", \"\", 0, budget, false))\n\n\tmeta, ok := thread.Meta.(*ThreadMeta)\n\tif !ok || meta.AllReplies.Size() == 0 {\n\t\treturn b.String()\n\t}\n\tall := meta.AllReplies\n\tp := newClampedPager(path, all.Size(), pageSizeFlat)\n\n\tb.WriteString(\"\\n\" + md.HorizontalRule())\n\tb.WriteString(md.Link(\"← Threaded view\", makeThreadURI(thread)) + \" · All \" +\n\t\tstrconv.Itoa(all.Size()) + \" comments — sort by: \")\n\n\t// sortToggleLink preserves flat=1, so the toggle stays in the flat view.\n\tlink, desc := sortToggleLink(path)\n\tb.WriteString(link + \"\\n\")\n\n\tcount := p.PageSize()\n\tif desc {\n\t\tcount = -count // reverse iterate: newest first\n\t}\n\tall.Iterate(p.Offset(), count, func(reply *boards.Post) bool {\n\t\tif *budget \u003c= 0 {\n\t\t\t// Unreachable while pageSizeFlat \u003c\u003c maxRenderedBodies; a backstop\n\t\t\t// in case a chain upgrade drops the native cap below one page.\n\t\t\treturn true\n\t\t}\n\t\tindent := flatIndent(thread, reply)\n\t\tb.WriteString(indent + \"\\n\" + renderPost(reply, \"\", indent, 0, budget, false))\n\t\treturn false\n\t})\n\n\tif p.HasPages() {\n\t\tb.WriteString(md.HorizontalRule())\n\t\tb.WriteString(pager.Picker(p))\n\t}\n\treturn b.String()\n}\n\n// flatIndent returns the blockquote indent for a reply in the flat view,\n// derived from its depth below the thread root (depth 1 = a direct reply to\n// the thread), capped at maxFlatIndentDepth.\nfunc flatIndent(thread *boards.Post, reply *boards.Post) string {\n\tdepth := 1\n\tpid := reply.ParentID\n\tfor pid != thread.ID \u0026\u0026 pid != 0 \u0026\u0026 depth \u003c maxFlatIndentDepth {\n\t\tparent, ok := getReply(thread, pid)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tdepth++\n\t\tpid = parent.ParentID\n\t}\n\treturn strings.Repeat(\"\u003e \", depth)\n}\n\nfunc renderThreadSummary(thread *boards.Post) string {\n\tvar (\n\t\tb           strings.Builder\n\t\tpostURI     = makeThreadURI(thread)\n\t\tsummary     = summaryOf(thread.Title, 80)\n\t\tcreatorLink = userLink(thread.Creator)\n\t\troleBadge   = getRoleBadge(thread)\n\t\tdate        = thread.CreatedAt.Format(dateFormat)\n\t)\n\n\tbyline := \"Created by \"\n\tif boards.IsRepost(thread) {\n\t\tsummary += ` ⟳`\n\t\tbyline = \"Reposted by \"\n\t}\n\n\tb.WriteString(md.H6(md.Link(summary, postURI)))\n\tb.WriteString(byline + creatorLink + roleBadge + \" on \" + date + \"  \\n\")\n\n\tstatus := []string{\n\t\tstrconv.Itoa(thread.Replies.Size()) + \" replies\",\n\t\tstrconv.Itoa(thread.Reposts.Size()) + \" reposts\",\n\t}\n\tb.WriteString(md.Bold(strings.Join(status, \" • \")) + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderCreateThread(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\tform := mdform.New(\"exec\", \"CreateThread\")\n\tform.Input(\n\t\t\"boardID\",\n\t\t\"placeholder\", \"Board ID\",\n\t\t\"value\", board.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"title\",\n\t\t\"placeholder\", \"Title\",\n\t\t\"required\", \"true\",\n\t)\n\tform.Textarea(\n\t\t\"body\",\n\t\t\"placeholder\", \"Content\",\n\t\t\"rows\", \"10\",\n\t\t\"required\", \"true\",\n\t)\n\n\tres.Write(md.H1(board.Name + \": Create Thread\"))\n\tres.Write(md.Link(\"← Back to board\", makeBoardURI(board)) + \"\\n\\n\")\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\tufmt.Sprintf(\"Thread will be created in the board: %s\", md.Link(board.Name, makeBoardURI(board))),\n\t\t),\n\t)\n\tres.Write(form.String())\n\tres.Write(\"\\n\\n**Done?** \" + svgbtn.ButtonWithRadius(136, 32, 4, \"#E2E2E2\", \"#54595D\", \"Return to board\", makeBoardURI(board)) + \"\\n\")\n}\n\nfunc renderEditThread(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := getThread(board, boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\tform := mdform.New(\"exec\", \"EditThread\")\n\tform.Input(\n\t\t\"boardID\",\n\t\t\"placeholder\", \"Board ID\",\n\t\t\"value\", board.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"threadID\",\n\t\t\"placeholder\", \"Thread ID\",\n\t\t\"value\", thread.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"title\",\n\t\t\"placeholder\", \"Title\",\n\t\t\"value\", thread.Title,\n\t\t\"required\", \"true\",\n\t)\n\tform.Textarea(\n\t\t\"body\",\n\t\t\"placeholder\", \"Content\",\n\t\t\"rows\", \"10\",\n\t\t\"value\", thread.Body,\n\t\t\"required\", \"true\",\n\t)\n\n\tres.Write(md.H1(board.Name + \": Edit Thread\"))\n\tres.Write(md.Link(\"← Back to thread\", makeThreadURI(thread)) + \"\\n\\n\")\n\tres.Write(\n\t\tmd.Paragraph(\"Editing \" + md.Link(thread.Title, makeThreadURI(thread))),\n\t)\n\tres.Write(form.String())\n\tres.Write(\"\\n\\n**Done?** \" + svgbtn.ButtonWithRadius(136, 32, 4, \"#E2E2E2\", \"#54595D\", \"Return to thread\", makeThreadURI(thread)) + \"\\n\")\n}\n\nfunc renderRepostThread(res *mux.ResponseWriter, req *mux.Request) {\n\tname := req.GetVar(\"board\")\n\tboard, found := gBoards.GetByName(name)\n\tif !found {\n\t\tres.Write(\"Board not found\")\n\t\treturn\n\t}\n\n\trawID := req.GetVar(\"thread\")\n\tthreadID, err := strconv.Atoi(rawID)\n\tif err != nil {\n\t\tres.Write(\"Invalid thread ID: \" + md.EscapeText(rawID))\n\t\treturn\n\t}\n\n\tthread, found := getThread(board, boards.ID(threadID))\n\tif !found {\n\t\tres.Write(\"Thread not found\")\n\t\treturn\n\t}\n\n\tform := mdform.New(\"exec\", \"CreateRepost\")\n\tform.Input(\n\t\t\"boardID\",\n\t\t\"placeholder\", \"Board ID\",\n\t\t\"value\", board.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"threadID\",\n\t\t\"placeholder\", \"Thread ID\",\n\t\t\"value\", thread.ID.String(),\n\t\t\"readonly\", \"true\",\n\t)\n\tform.Input(\n\t\t\"destinationBoardID\",\n\t\t\"type\", mdform.InputTypeNumber,\n\t\t\"placeholder\", \"Board ID where to repost\",\n\t\t\"required\", \"true\",\n\t)\n\tform.Input(\n\t\t\"title\",\n\t\t\"value\", thread.Title,\n\t\t\"placeholder\", \"Title\",\n\t\t\"required\", \"true\",\n\t)\n\tform.Textarea(\n\t\t\"body\",\n\t\t\"placeholder\", \"Content\",\n\t\t\"rows\", \"10\",\n\t)\n\n\tres.Write(md.H1(board.Name + \": Repost Thread\"))\n\tres.Write(md.Link(\"← Back to thread\", makeThreadURI(thread)) + \"\\n\\n\")\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\t\"Threads can be reposted to other open boards or boards where you are a member \" +\n\t\t\t\t\"and are allowed to create new threads.\",\n\t\t),\n\t)\n\tres.Write(\n\t\tmd.Paragraph(\n\t\t\tufmt.Sprintf(\"Reposting the thread: %s.\", md.Link(thread.Title, makeThreadURI(thread))),\n\t\t),\n\t)\n\tres.Write(form.String())\n\tres.Write(\"\\n\\n**Done?** \" + svgbtn.ButtonWithRadius(136, 32, 4, \"#E2E2E2\", \"#54595D\", \"Return to thread\", makeThreadURI(thread)) + \"\\n\")\n}\n"},{"name":"uris_board.gno","body":"package boards2\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\nfunc makeBoardURI(b *boards.Board) string {\n\tpath := strings.TrimPrefix(string(RealmLink), \"gno.land\")\n\treturn path + \":\" + url.PathEscape(b.Name)\n}\n\nfunc makeFreezeBoardURI(b *boards.Board) string {\n\treturn RealmLink.Call(\n\t\t\"FreezeBoard\",\n\t\t\"boardID\", b.ID.String(),\n\t)\n}\n\nfunc makeUnfreezeBoardURI(b *boards.Board) string {\n\treturn RealmLink.Call(\n\t\t\"UnfreezeBoard\",\n\t\t\"boardID\", b.ID.String(),\n\t\t\"threadID\", \"\",\n\t\t\"replyID\", \"\",\n\t)\n}\n\nfunc makeInviteMemberURI(b *boards.Board) string {\n\treturn makeBoardURI(b) + \"/invite-member\"\n}\n\nfunc makeCreateThreadURI(b *boards.Board) string {\n\treturn makeBoardURI(b) + \"/create-thread\"\n}\n\nfunc makeRequestInviteURI(b *boards.Board) string {\n\treturn RealmLink.Call(\n\t\t\"RequestInvite\",\n\t\t\"boardID\", b.ID.String(),\n\t)\n}\n"},{"name":"uris_post.gno","body":"package boards2\n\nimport (\n\t\"gno.land/p/gnoland/boards/v0\"\n)\n\nfunc makeThreadURI(p *boards.Post) string {\n\tif boards.IsThread(p) {\n\t\treturn makeBoardURI(p.Board) + \"/\" + p.ID.String()\n\t}\n\n\t// When post is a reply use the parent thread ID\n\treturn makeBoardURI(p.Board) + \"/\" + p.ThreadID.String()\n}\n\n// makeThreadFlatURI links to the thread's flat \"all comments\" view. Works for\n// a thread or any reply within it (makeThreadURI resolves to the thread).\nfunc makeThreadFlatURI(p *boards.Post) string {\n\treturn makeThreadURI(p) + \"?flat=1\"\n}\n\nfunc makeReplyURI(p *boards.Post) string {\n\treturn makeBoardURI(p.Board) + \"/\" + p.ThreadID.String() + \"/\" + p.ID.String()\n}\n\nfunc makeCreateReplyURI(p *boards.Post) string {\n\tif boards.IsThread(p) {\n\t\treturn makeThreadURI(p) + \"/reply\"\n\t}\n\treturn makeReplyURI(p) + \"/reply\"\n}\n\nfunc makeCreateRepostURI(p *boards.Post) string {\n\treturn makeThreadURI(p) + \"/repost\"\n}\n\nfunc makeDeletePostURI(p *boards.Post) string {\n\tif boards.IsThread(p) {\n\t\treturn RealmLink.Call(\n\t\t\t\"DeleteThread\",\n\t\t\t\"boardID\", p.Board.ID.String(),\n\t\t\t\"threadID\", p.ThreadID.String(),\n\t\t)\n\t}\n\treturn RealmLink.Call(\n\t\t\"DeleteReply\",\n\t\t\"boardID\", p.Board.ID.String(),\n\t\t\"threadID\", p.ThreadID.String(),\n\t\t\"replyID\", p.ID.String(),\n\t)\n}\n\nfunc makeEditPostURI(p *boards.Post) string {\n\tif boards.IsThread(p) {\n\t\treturn makeThreadURI(p) + \"/edit\"\n\t}\n\treturn makeReplyURI(p) + \"/edit\"\n}\n\nfunc makeFlagURI(p *boards.Post) string {\n\tif boards.IsThread(p) {\n\t\treturn makeThreadURI(p) + \"/flag\"\n\t}\n\treturn makeReplyURI(p) + \"/flag\"\n}\n\nfunc makeFlaggingReasonsURI(p *boards.Post) string {\n\tif boards.IsThread(p) {\n\t\treturn makeThreadURI(p) + \"/flagging-reasons\"\n\t}\n\treturn makeReplyURI(p) + \"/flagging-reasons\"\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"test","path":"gno.land/r/gov/dao/treasury/test/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/treasury/test/v0\"\ngno = \"0.9\"\n"},{"name":"workaround.gno","body":"package test\n\n// This package exists solely to circumvent a limitation associated with the\n// suffixed test package (a test package sharing the same folder as the main\n// package to be tested but having the suffix _test in its name).\n// Currently, the GnoVM no longer differentiates between the dependencies of a\n// package and its test package, which causes circular dependencies issues.\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"coinsort","path":"gno.land/p/leon/coinsort/v0","files":[{"name":"coinsort.gno","body":"// Package coinsort provides helpers to sort a slice of banker.Coins using the\n// classic sort.Sort API (without relying on sort.Slice).\n//\n// Usage examples:\n//\n//\tcoins := banker.GetCoins(\"g1....\")\n//\n//\t// Ascending by balance\n//\tcoinsort.SortByBalance(coins)\n//\n//\t// Custom order – largest balance first\n//\tcoinsort.SortBy(coins, func(a, b chain.Coin) bool {\n//\t    return a.Amount \u003e b.Amount // descending\n//\t})\n//\n// Note: when getting banker.Coins from the banker, it's sorted by denom by default.\npackage coinsort\n\nimport (\n\t\"chain\"\n\t\"sort\"\n)\n\ntype ByAmount struct{ chain.Coins }\n\nfunc (b ByAmount) Len() int           { return len(b.Coins) }\nfunc (b ByAmount) Swap(i, j int)      { b.Coins[i], b.Coins[j] = b.Coins[j], b.Coins[i] }\nfunc (b ByAmount) Less(i, j int) bool { return b.Coins[i].Amount \u003c b.Coins[j].Amount }\n\n// SortByBalance sorts c in ascending order by Amount.\n//\n//\tcoinsort.SortByBalance(myCoins)\nfunc SortByBalance(c chain.Coins) {\n\tsort.Sort(ByAmount{c})\n}\n\n// LessFunc defines the comparison function for SortBy. It must return true if\n// 'a' should come before 'b'.\n\ntype LessFunc func(a, b chain.Coin) bool\n\n// customSorter adapts a LessFunc to sort.Interface so we can keep using\n// sort.Sort (rather than sort.Slice).\n\ntype customSorter struct {\n\tcoins chain.Coins\n\tless  LessFunc\n}\n\nfunc (cs customSorter) Len() int      { return len(cs.coins) }\nfunc (cs customSorter) Swap(i, j int) { cs.coins[i], cs.coins[j] = cs.coins[j], cs.coins[i] }\nfunc (cs customSorter) Less(i, j int) bool {\n\treturn cs.less(cs.coins[i], cs.coins[j])\n}\n\n// SortBy sorts c in place using the provided LessFunc.\n//\n// Example – descending by Amount:\n//\n//\tcoinsort.SortBy(coins, func(a, b banker.Coin) bool {\n//\t    return a.Amount \u003e b.Amount\n//\t})\nfunc SortBy(c chain.Coins, less LessFunc) {\n\tif less == nil {\n\t\treturn // nothing to do; keep original order\n\t}\n\tsort.Sort(customSorter{coins: c, less: less})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/leon/coinsort/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"ownable","path":"gno.land/p/nt/ownable/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `ownable` - Ownership pattern for realms\n\nProvides an `Ownable` object that gates privileged operations behind a single owner address. Embed it in a realm (or any struct) to restrict actions like configuration changes, withdrawals, or upgrades.\n\n## Usage\n\n```go\npackage myrealm\n\nimport (\n    \"chain/runtime\"\n\n    \"gno.land/p/nt/ownable/v0\"\n)\n\n// The owner address is chosen explicitly at construction. A common\n// choice is the deployer, captured in init after confirming it is a\n// real user call.\nvar owner *ownable.Ownable\n\nfunc init() {\n    caller := runtime.PreviousRealm()\n    if !caller.IsUserCall() {\n        panic(\"must be deployed by a user\")\n    }\n    owner = ownable.NewWithAddress(caller.Address())\n}\n\n// SetFee is gated: only the current owner may call it.\nfunc SetFee(cur realm, newFee int64) {\n    if !cur.IsCurrent() {\n        panic(\"spoofed realm\")\n    }\n    owner.AssertOwnedBy(cur.Previous().Address())\n    fee = newFee\n}\n\n// Hand the realm over. TransferOwnership itself verifies the caller is owner.\nfunc TransferOwner(cur realm, to address) error {\n    return owner.TransferOwnership(0, cur, to)\n}\n```\n\nThere is no auth-mode flag. The single `NewWithAddress` constructor replaced the\nold `New` / `NewWithOrigin` / `NewWithAddressByPrevious` sugar: the realm now picks\nthe owner address explicitly rather than baking a runtime walk into the struct.\n\n## API\n\n```go\ntype Ownable struct{ /* unexported */ }\n\nconst OwnershipTransferEvent = \"OwnershipTransfer\"\n\nvar (\n    ErrUnauthorized   = errors.New(\"ownable: caller is not owner\")\n    ErrInvalidAddress = errors.New(\"ownable: new owner address is invalid\")\n)\n\n// NewWithAddress is the only constructor: the realm picks the owner\n// address explicitly (e.g. cur.Previous().Address() after checking\n// cur.Previous().IsUserCall() in init).\nfunc NewWithAddress(addr address) *Ownable\n\n// Queries (caller supplies the address to check).\nfunc (o *Ownable) Owner() address             // \"\" if o is nil or ownership was dropped\nfunc (o *Ownable) OwnedBy(addr address) bool  // true if addr is the current owner\nfunc (o *Ownable) AssertOwnedBy(addr address) // panics with ErrUnauthorized if addr is not the owner\n\n// Authority mutation (thread the caller's own cur; pass 0 as the first arg).\nfunc (o *Ownable) TransferOwnership(_ int, rlm realm, newOwner address) error\nfunc (o *Ownable) DropOwnership(_ int, rlm realm) error // sets owner to \"\" — irreversible\n```\n\n## Notes\n\n- Authority-mutating methods assert `rlm.IsCurrent()` and identify the caller as `rlm.Previous().Address()`, which must equal the current owner. The principal is therefore unforgeable: an attacker cannot supply an arbitrary caller address. Pass `0` as the placeholder first arg and your own `cur` as `rlm`.\n- Read helpers (`OwnedBy`, `AssertOwnedBy`) take a bare address; the caller extracts it, guarding with `cur.IsCurrent()` before reading `cur.Previous().Address()`.\n- `TransferOwnership` rejects an invalid `newOwner` with `ErrInvalidAddress`. Both mutators emit `OwnershipTransferEvent` with `from` and `to` fields.\n- `DropOwnership` is permanent: `owner` becomes `\"\"`, so every owner-gated action becomes unreachable.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package ownable provides an ownership pattern for Gno realms, allowing\n// contracts to restrict access to privileged operations to a designated owner.\npackage ownable\n"},{"name":"errors.gno","body":"package ownable\n\nimport \"errors\"\n\nvar (\n\tErrUnauthorized   = errors.New(\"ownable: caller is not owner\")\n\tErrInvalidAddress = errors.New(\"ownable: new owner address is invalid\")\n)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/ownable/v0\"\ngno = \"0.9\"\n"},{"name":"ownable.gno","body":"package ownable\n\nimport \"chain\"\n\nconst OwnershipTransferEvent = \"OwnershipTransfer\"\n\n// Ownable is meant to be used as a top-level object to make your contract\n// ownable OR being embedded in a Gno object to manage per-object ownership.\n// Ownable is safe to export as a top-level object.\n//\n// Authority-mutating methods (TransferOwnership, DropOwnership) take\n// (_ int, rlm realm). The caller threads its own cur; the method\n// asserts rlm.IsCurrent() and identifies the principal as\n// rlm.Previous().Address() — which must equal the current owner.\n//\n//\to.TransferOwnership(0, cur, newOwner)\n//\to.DropOwnership(0, cur)\n//\n// Read methods (OwnedBy, AssertOwnedBy) keep the bare-address shape;\n// callers extract the address themselves (e.g. cur.Previous().Address()).\ntype Ownable struct {\n\towner address\n}\n\n// NewWithAddress creates an Ownable with the given address as owner.\n// This is the only constructor — the previous New/NewWithOrigin/\n// NewWithAddressByPrevious sugar baked runtime walks and an auth-mode\n// flag into the struct; the realm using this package now picks the\n// owner address explicitly (e.g. cur.Previous().Address() after\n// verifying cur.Previous().IsUserCall() in init).\nfunc NewWithAddress(addr address) *Ownable {\n\treturn \u0026Ownable{\n\t\towner: addr,\n\t}\n}\n\n// OwnedBy reports whether addr is the current owner.\nfunc (o *Ownable) OwnedBy(addr address) bool {\n\tif o == nil {\n\t\treturn false\n\t}\n\treturn addr == o.owner\n}\n\n// AssertOwnedBy panics with ErrUnauthorized if addr is not the owner.\nfunc (o *Ownable) AssertOwnedBy(addr address) {\n\tif !o.OwnedBy(addr) {\n\t\tpanic(ErrUnauthorized)\n\t}\n}\n\n// TransferOwnership transfers ownership of the Ownable to newOwner. rlm\n// must be the caller's own captured cur (asserted via rlm.IsCurrent()).\n// The principal is rlm.Previous().Address() — the realm that crossed\n// into the caller — which must equal the current owner.\n//\n// IsCurrent + rlm.Previous() makes the principal unforgeable: an\n// attacker calling TransferOwnership on a foreign Ownable cannot supply\n// an arbitrary caller address; rlm comes from a runtime-validated\n// crossing frame.\nfunc (o *Ownable) TransferOwnership(_ int, rlm realm, newOwner address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrUnauthorized\n\t}\n\tcaller := rlm.Previous().Address()\n\tif !o.OwnedBy(caller) {\n\t\treturn ErrUnauthorized\n\t}\n\tif !newOwner.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\tprevOwner := o.owner\n\to.owner = newOwner\n\tchain.Emit(\n\t\tOwnershipTransferEvent,\n\t\t\"from\", prevOwner.String(),\n\t\t\"to\", newOwner.String(),\n\t)\n\treturn nil\n}\n\n// DropOwnership removes the owner, disabling any owner-related actions.\n// rlm must be the caller's own captured cur; rlm.Previous().Address()\n// must equal the current owner.\nfunc (o *Ownable) DropOwnership(_ int, rlm realm) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrUnauthorized\n\t}\n\tcaller := rlm.Previous().Address()\n\tif !o.OwnedBy(caller) {\n\t\treturn ErrUnauthorized\n\t}\n\tprevOwner := o.owner\n\to.owner = \"\"\n\tchain.Emit(\n\t\tOwnershipTransferEvent,\n\t\t\"from\", prevOwner.String(),\n\t\t\"to\", \"\",\n\t)\n\treturn nil\n}\n\n// Owner returns the owner address.\nfunc (o *Ownable) Owner() address {\n\tif o == nil {\n\t\treturn address(\"\")\n\t}\n\treturn o.owner\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"foo20","path":"gno.land/r/demo/defi/foo20","files":[{"name":"foo20.gno","body":"// foo20 is a GRC20 token contract where all the grc20.Teller methods are\n// proxified with top-level functions. see also gno.land/r/demo/bar20.\npackage foo20\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nvar (\n\tToken         *grc20.Token\n\tprivateLedger *grc20.PrivateLedger\n\tuserTeller    grc20.Teller\n\tOwnable       = ownable.NewWithAddress(\"g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx\") // govdao t1 multisig\n)\n\nfunc init(cur realm) {\n\t// foo20 only ever creates this one token, so id 0 can't collide.\n\tToken, privateLedger = grc20.NewToken(\"Foo\", \"FOO\", 4, 0, cur)\n\tuserTeller = privateLedger.CallerTeller()\n\tprivateLedger.Mint(Ownable.Owner(), 1_000_000*10_000) // @privateLedgeristrator (1M)\n\tgrc20reg.Register(cross(cur), Token, \"\")\n}\n\nfunc TotalSupply() int64 {\n\treturn userTeller.TotalSupply()\n}\n\nfunc BalanceOf(owner address) int64 {\n\treturn userTeller.BalanceOf(owner)\n}\n\nfunc Allowance(owner, spender address) int64 {\n\treturn userTeller.Allowance(owner, spender)\n}\n\nfunc Transfer(cur realm, to address, amount int64) {\n\tcheckErr(userTeller.Transfer(0, cur, to, amount))\n}\n\nfunc Approve(cur realm, spender address, amount int64) {\n\tcheckErr(userTeller.Approve(0, cur, spender, amount))\n}\n\nfunc TransferFrom(cur realm, from, to address, amount int64) {\n\tcheckErr(userTeller.TransferFrom(0, cur, from, to, amount))\n}\n\n// Faucet is distributing foo20 tokens without restriction (unsafe).\n// For a real token faucet, you should take care of setting limits are asking payment.\nfunc Faucet(cur realm) {\n\tcaller := cur.Previous().Address()\n\tamount := int64(1_000 * 10_000) // 1k\n\tcheckErr(privateLedger.Mint(caller, amount))\n}\n\nfunc Mint(cur realm, to address, amount int64) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tcheckErr(privateLedger.Mint(to, amount))\n}\n\nfunc Burn(cur realm, from address, amount int64) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tcheckErr(privateLedger.Burn(from, amount))\n}\n\nfunc Render(path string) string {\n\tparts := strings.Split(path, \"/\")\n\tc := len(parts)\n\n\tswitch {\n\tcase path == \"\":\n\t\treturn Token.RenderHome()\n\tcase c == 2 \u0026\u0026 parts[0] == \"balance\":\n\t\towner := address(parts[1])\n\t\tbalance := userTeller.BalanceOf(owner)\n\t\treturn ufmt.Sprintf(\"%d\\n\", balance)\n\tdefault:\n\t\treturn \"404\\n\"\n\t}\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/defi/foo20\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"fifo","path":"gno.land/p/moul/fifo/v0","files":[{"name":"fifo.gno","body":"// Package fifo implements a fixed-size FIFO (First-In-First-Out) list data structure\n// using a singly-linked list. The implementation prioritizes storage efficiency by minimizing\n// storage operations - each add/remove operation only updates 1-2 pointers, regardless of\n// list size.\n//\n// Key features:\n// - Fixed-size with automatic removal of oldest entries when full\n// - Support for both prepend (add at start) and append (add at end) operations\n// - Constant storage usage through automatic pruning\n// - O(1) append operations and latest element access\n// - Iterator support for sequential access\n// - Dynamic size adjustment via SetMaxSize\n//\n// This implementation is optimized for frequent updates, as insertions and deletions only\n// require updating 1-2 pointers. However, random access operations are O(n) as they require\n// traversing the list. For use cases where writes are rare, a slice-based\n// implementation might be more suitable.\n//\n// The linked list structure is equally efficient for storing both small values (like pointers)\n// and larger data structures, as each node maintains a single next-pointer regardless of the\n// stored value's size.\n//\n// Example usage:\n//\n//\tlist := fifo.New(3)        // Create a new list with max size 3\n//\tlist.Append(\"a\")           // List: [a]\n//\tlist.Append(\"b\")           // List: [a b]\n//\tlist.Append(\"c\")           // List: [a b c]\n//\tlist.Append(\"d\")           // List: [b c d] (oldest element \"a\" was removed)\n//\tlatest := list.Latest()    // Returns \"d\"\n//\tall := list.Entries()      // Returns [\"b\", \"c\", \"d\"]\npackage fifo\n\n// node represents a single element in the linked list\ntype node struct {\n\tvalue any\n\tnext  *node\n}\n\n// List represents a fixed-size FIFO list\ntype List struct {\n\thead    *node\n\ttail    *node\n\tsize    int\n\tmaxSize int\n}\n\n// New creates a new FIFO list with the specified maximum size\nfunc New(maxSize int) *List {\n\treturn \u0026List{\n\t\tmaxSize: maxSize,\n\t}\n}\n\n// Prepend adds a new entry at the start of the list. If the list exceeds maxSize,\n// the last entry is automatically removed.\nfunc (l *List) Prepend(entry any) {\n\tif l.maxSize == 0 {\n\t\treturn\n\t}\n\n\tnewNode := \u0026node{value: entry}\n\n\tif l.head == nil {\n\t\tl.head = newNode\n\t\tl.tail = newNode\n\t\tl.size = 1\n\t\treturn\n\t}\n\n\tnewNode.next = l.head\n\tl.head = newNode\n\n\tif l.size \u003c l.maxSize {\n\t\tl.size++\n\t\treturn\n\t}\n\n\t// Remove last element by traversing to second-to-last\n\tif l.size == 1 {\n\t\t// Special case: if size is 1, just update both pointers\n\t\tl.head = newNode\n\t\tl.tail = newNode\n\t\tnewNode.next = nil\n\t\treturn\n\n\t}\n\n\t// Find second-to-last node\n\tcurrent := l.head\n\tfor current.next != l.tail {\n\t\tcurrent = current.next\n\t}\n\tcurrent.next = nil\n\tl.tail = current\n\n}\n\n// Append adds a new entry at the end of the list. If the list exceeds maxSize,\n// the first entry is automatically removed.\nfunc (l *List) Append(entry any) {\n\tif l.maxSize == 0 {\n\t\treturn\n\t}\n\n\tnewNode := \u0026node{value: entry}\n\n\tif l.head == nil {\n\t\tl.head = newNode\n\t\tl.tail = newNode\n\t\tl.size = 1\n\t\treturn\n\t}\n\n\tl.tail.next = newNode\n\tl.tail = newNode\n\n\tif l.size \u003c l.maxSize {\n\t\tl.size++\n\t} else {\n\t\tl.head = l.head.next\n\t}\n}\n\n// Get returns the entry at the specified index.\n// Index 0 is the oldest entry, Size()-1 is the newest.\nfunc (l *List) Get(index int) any {\n\tif index \u003c 0 || index \u003e= l.size {\n\t\treturn nil\n\t}\n\n\tcurrent := l.head\n\tfor i := 0; i \u003c index; i++ {\n\t\tcurrent = current.next\n\t}\n\treturn current.value\n}\n\n// Size returns the current number of entries in the list\nfunc (l *List) Size() int {\n\treturn l.size\n}\n\n// MaxSize returns the maximum size configured for this list\nfunc (l *List) MaxSize() int {\n\treturn l.maxSize\n}\n\n// Entries returns all current entries as a slice\nfunc (l *List) Entries() []any {\n\tentries := make([]any, l.size)\n\tcurrent := l.head\n\tfor i := 0; i \u003c l.size; i++ {\n\t\tentries[i] = current.value\n\t\tcurrent = current.next\n\t}\n\treturn entries\n}\n\n// Iterator returns a function that can be used to iterate over the entries\n// from oldest to newest. Returns nil when there are no more entries.\nfunc (l *List) Iterator() func() any {\n\tcurrent := l.head\n\treturn func() any {\n\t\tif current == nil {\n\t\t\treturn nil\n\t\t}\n\t\tvalue := current.value\n\t\tcurrent = current.next\n\t\treturn value\n\t}\n}\n\n// Latest returns the most recent entry.\n// Returns nil if the list is empty.\nfunc (l *List) Latest() any {\n\tif l.tail == nil {\n\t\treturn nil\n\t}\n\treturn l.tail.value\n}\n\n// SetMaxSize updates the maximum size of the list.\n// If the new maxSize is smaller than the current size,\n// the oldest entries are removed to fit the new size.\nfunc (l *List) SetMaxSize(maxSize int) {\n\tif maxSize \u003c 0 {\n\t\tmaxSize = 0\n\t}\n\n\t// If new maxSize is smaller than current size,\n\t// remove oldest entries until we fit\n\tif maxSize \u003c l.size {\n\t\t// Special case: if new maxSize is 0, clear the list\n\t\tif maxSize == 0 {\n\t\t\tl.head = nil\n\t\t\tl.tail = nil\n\t\t\tl.size = 0\n\t\t} else {\n\t\t\t// Keep the newest entries by moving head forward\n\t\t\tdiff := l.size - maxSize\n\t\t\tfor i := 0; i \u003c diff; i++ {\n\t\t\t\tl.head = l.head.next\n\t\t\t}\n\t\t\tl.size = maxSize\n\t\t}\n\t}\n\n\tl.maxSize = maxSize\n}\n\n// Delete removes the element at the specified index.\n// Returns true if an element was removed, false if the index was invalid.\nfunc (l *List) Delete(index int) bool {\n\tif index \u003c 0 || index \u003e= l.size {\n\t\treturn false\n\t}\n\n\t// Special case: deleting the only element\n\tif l.size == 1 {\n\t\tl.head = nil\n\t\tl.tail = nil\n\t\tl.size = 0\n\t\treturn true\n\t}\n\n\t// Special case: deleting first element\n\tif index == 0 {\n\t\tl.head = l.head.next\n\t\tl.size--\n\t\treturn true\n\t}\n\n\t// Find the node before the one to delete\n\tcurrent := l.head\n\tfor i := 0; i \u003c index-1; i++ {\n\t\tcurrent = current.next\n\t}\n\n\t// Special case: deleting last element\n\tif index == l.size-1 {\n\t\tl.tail = current\n\t\tcurrent.next = nil\n\t} else {\n\t\tcurrent.next = current.next.next\n\t}\n\n\tl.size--\n\treturn true\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/fifo/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"namereg","path":"gno.land/r/sys/namereg/v0","files":[{"name":"admin.gno","body":"package namereg\n\nimport (\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/gov/dao\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\nvar paused = false // XXX: replace with p/moul/authz\n\n//----------------------------------------\n// Privileged mutators.\n\nfunc setPaused(cur realm, newPausedValue bool) {\n\tpaused = newPausedValue\n}\n\nfunc updateUsername(cur realm, userData *susers.UserData, newName string) error {\n\t// UpdateName must be called from this realm.\n\treturn userData.UpdateName(0, cur, newName)\n}\n\nfunc deleteUserdata(cur realm, userData *susers.UserData) error {\n\t// Delete must be called from this realm.\n\treturn userData.Delete(0, cur)\n}\n\nfunc setRegisterPrice(cur realm, newPrice int64) {\n\tregisterPrice = newPrice\n}\n\n//----------------------------------------\n// Public API\n\n// NewSetPausedExecutor allows GovDAO to pause or unpause this realm\nfunc NewSetPausedExecutor(cur realm, newPausedValue bool) dao.ProposalRequest {\n\tcb := func(cur realm) error {\n\t\tsetPaused(cur, newPausedValue)\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, \"\")\n\n\tif newPausedValue {\n\t\treturn dao.NewProposalRequest(\"User Registry V0: Pause\", \"\", e)\n\t}\n\n\treturn dao.NewProposalRequest(\"User Registry V0: Unpause\", \"\", e)\n}\n\n// ProposeNewName allows GovDAO to propose a new name for an existing user.\n// The associated address and all previous names of a user that changes a\n// name are preserved, and all resolve to the new name.\n//\n// Governance renames bypass the Open Nym Tier `nym-...\\d{3}` format intentionally.\n// The DAO is the trust root for this realm; if voters approve a rename to\n// `vitalik` (e.g. for trademark dispute resolution or system reservations),\n// the validation here imposes no further opinion. The new name is still\n// subject to the base shape enforced by `r/sys/users.validateName`\n// (`^[a-z][a-z0-9]*([_-][a-z0-9]+)*$`, max 64 chars), which runs inside\n// the updateUsername callback below.\nfunc ProposeNewName(cur realm, addr address, newName string) dao.ProposalRequest {\n\tuserData := susers.ResolveAddress(addr)\n\tif userData == nil {\n\t\tpanic(susers.ErrUserNotExistOrDeleted)\n\t}\n\n\tcb := func(cur realm) error {\n\t\terr := updateUsername(cur, userData, newName)\n\t\treturn err\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, \"\")\n\n\treturn dao.NewProposalRequest(\n\t\tufmt.Sprintf(\"User Registry V0: Rename user `%s` to `%s`\", userData.Name(), newName),\n\t\t\"\",\n\t\te,\n\t)\n}\n\n// ProposeDeleteUser allows GovDAO to propose deletion of a user\n// This will make the associated address and names unresolvable.\n// WARN: After deletion, the same address WILL NOT be able to register a new name.\nfunc ProposeDeleteUser(cur realm, addr address, reason string) dao.ProposalRequest {\n\tuserData := susers.ResolveAddress(addr)\n\tif userData == nil {\n\t\tpanic(susers.ErrUserNotExistOrDeleted)\n\t}\n\n\tcb := func(cur realm) error {\n\t\treturn deleteUserdata(cur, userData)\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, \"\")\n\n\treturn dao.NewProposalRequest(\n\t\tufmt.Sprintf(\"User Registry V0: Delete user `%s`\", userData.Name()),\n\t\treason,\n\t\te,\n\t)\n}\n\n// ProposeNewRegisterPrice allows GovDAO to update the price of registration.\n// Rejects prices below MinRegisterPrice (currently 0) at proposal-creation\n// time. (audit finding #14: original code only rejected negative values,\n// which would have been arithmetically nonsensical.)\nfunc ProposeNewRegisterPrice(cur realm, newPrice int64) dao.ProposalRequest {\n\tif newPrice \u003c MinRegisterPrice {\n\t\tpanic(ufmt.Sprintf(\"price below floor: %d ugnot \u003c %d ugnot (MinRegisterPrice)\",\n\t\t\tnewPrice, MinRegisterPrice))\n\t}\n\n\tcb := func(cur realm) error {\n\t\tsetRegisterPrice(cur, newPrice)\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, cb, \"\")\n\n\treturn dao.NewProposalRequest(\n\t\tufmt.Sprintf(\"User Registry V0: Update registration price to `%d`\", newPrice),\n\t\t\"\",\n\t\te,\n\t)\n}\n"},{"name":"api.gno","body":"package namereg\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n// Open Nym Tier username format. Anchored.\n//   - literal `nym-` prefix (4 chars)\n//   - 5-13 lowercase ASCII letters (the alpha stem)\n//   - exactly 3 trailing decimal digits\n//\n// Total length 12-20 chars. Distinct by length from `g1...` addresses\n// which are always 40 chars.\nconst reNymFormat = `^nym-[a-z]{5,13}\\d{3}$`\n\nvar reNym = regexp.MustCompile(reNymFormat)\n\n// Reserved alpha-stem prefixes. Names whose stem starts with one of\n// these are rejected at format-validation time with ErrReservedPrefix\n// (clearer than ErrCanonicalCollision after the fact).\n//\n// `gi` is intentionally NOT listed: in most rendering targets `i` is\n// visually distinct enough from `1`/`l` that legitimate `gi*` names\n// (giggles, gimbal, gift, etc.) should remain registerable. Phishing\n// protection for the visual class is still enforced by canonical-\n// collision detection in r/sys/users — once any `gi*` or `gl*` name\n// is registered, all variants under the {l,i,1}→i canonicalization\n// collide.\n//\n// `gl` and `g1` remain listed because they're more visually\n// confusable with the bech32 address prefix `g1`. `g1` itself is\n// unreachable through the alpha-only stem regex; defense-in-depth\n// for any future regex relaxation.\nvar reservedPrefixes = []string{\"gl\", \"g1\", \"gno\", \"atom\", \"atone\", \"photon\", \"cosmos\"}\n\n// Exported error sentinels returned by ValidateNymFormat. Use\n// errors.Is or direct equality; do not string-match.\n//\n// ErrReservedPrefix's message is built from reservedPrefixes at package\n// init time so the surfaced list never drifts from the actual policy.\n//\n// Canonical-collision detection moved to r/sys/users in Option B.\n// Consumers that previously caught namereg.ErrCanonicalCollision\n// should switch to susers.ErrCanonicalCollision.\nvar (\n\tErrInvalidFormat  = errors.New(\"namereg: name must match nym-[a-z]{5,13}\\\\d{3}\")\n\tErrReservedPrefix = errors.New(\"namereg: stem starts with a reserved prefix (\" + strings.Join(reservedPrefixes, \"/\") + \")\")\n\tErrBlacklisted    = errors.New(\"namereg: stem matches a reserved role name\")\n)\n\n// IsReserved reports whether the given alpha stem matches a reserved\n// role name (with implicit `s`-suffix expansion). The check is\n// canonicalized — so `vital1k`-style l-substituted variants of a\n// reserved name are also caught. O(1) backed by `reservedSet` built\n// in init().\nfunc IsReserved(stem string) bool {\n\t_, found := reservedSet[Canonicalize(stem)]\n\treturn found\n}\n\n// ValidateNymFormat checks the regex, prefix-exclusion, and reserved-\n// name rules in that order. Returns one of the exported sentinel\n// errors per failure mode, or nil on success.\n//\n// Does NOT run the canonical-collision check — that lives in r/sys/users\n// (susers.IsCanonicalTaken or, atomically with the write, inside\n// susers.RegisterUser).\nfunc ValidateNymFormat(username string) error {\n\tif !reNym.MatchString(username) {\n\t\treturn ErrInvalidFormat\n\t}\n\n\t// Stem is everything between `nym-` (4 chars) and the trailing\n\t// 3 digits. Regex guarantees 5..13 alpha chars in this slice.\n\tstem := username[4 : len(username)-3]\n\n\tfor _, p := range reservedPrefixes {\n\t\tif strings.HasPrefix(stem, p) {\n\t\t\treturn ErrReservedPrefix\n\t\t}\n\t}\n\n\tif IsReserved(stem) {\n\t\treturn ErrBlacklisted\n\t}\n\n\treturn nil\n}\n\n// IsPaused exposes the realm's pause flag for cross-controller\n// coordination.\nfunc IsPaused() bool {\n\treturn paused\n}\n"},{"name":"blacklist.gno","body":"package namereg\n\n// reservedNames lists role/system identifiers that must never be allocated\n// as a registered name. The intent is to prevent Open Nym Tier\n// auto-registrations like \"nym-admin000\" from impersonating system roles.\n//\n// Sources merged here:\n//   - Common role names already covered by Handshake's valid.json (the 90k\n//     curated trademark/gTLD-application list) — admin, help, support, etc.\n//   - Common role names NOT covered by Handshake — administrator, root,\n//     sysadmin, owner, staff, api, etc.\n//   - RFC 2606 / RFC 6761 reserved labels — example, invalid, localhost,\n//     local, test.\n//\n// Plural rule: every entry below is ALSO reserved with the literal \"s\"\n// suffix appended. So \"doc\" reserves both \"doc\" and \"docs\"; \"setting\"\n// reserves both \"setting\" and \"settings\"; \"new\" covers \"news\", and so on.\n// Entries are stored in the singular here and the validator appends \"s\"\n// at check time. This halves list maintenance and avoids the temptation\n// to add `name+\"s\"` after every singular entry.\n//\n// Note on length: the Open Nym Tier regex restricts the [a-z]{5,13}\n// middle to 5–13 chars, so entries shorter than 5 (mod, api, bot, god,\n// gno, ...) and longer than 13 (administrator, jesuschrist,\n// newtendermint, ...) cannot appear in Register() even without this list.\n// They are kept anyway because:\n//\n//\t(a) cross-reference value — a single canonical list is easier to audit\n//\t    than two scope-specific lists with overlapping intent; and\n//\t(b) future controllers (e.g. a hypothetical DAO-allocated path) can\n//\t    opt in to the same blacklist by querying IsReserved, providing\n//\t    defense-in-depth across the registration ecosystem.\n//\n// IMPORTANT: this list is NOT consulted by `ProposeNewName` — governance\n// renames are gated by GovDAO vote alone, not by this blacklist. Voters\n// reviewing a rename proposal are responsible for catching collisions\n// with reserved names.\n//\n// Sortedness: entries must be sorted lexicographically (Go's \u003c on strings,\n// which is byte-wise ASCII). TestReservedNamesSorted enforces this.\nvar reservedNames = []string{\n\t\"about\",\n\t\"abuse\",\n\t\"account\",\n\t\"admin\",\n\t\"administrator\",\n\t\"aib\",\n\t\"aibinc\",\n\t\"allinbits\",\n\t\"allinbitsinc\",\n\t\"anonymous\",\n\t\"api\",\n\t\"atom\",\n\t\"atomone\",\n\t\"atomonehub\",\n\t\"atone\",\n\t\"atonehub\",\n\t\"bitcoin\",\n\t\"blockchain\",\n\t\"blog\",\n\t\"bot\",\n\t\"chain\",\n\t\"coin\",\n\t\"community\",\n\t\"contact\",\n\t\"cosmos\",\n\t\"cosmoshub\",\n\t\"crypto\",\n\t\"daemon\",\n\t\"dashboard\",\n\t\"default\",\n\t\"demo\",\n\t\"doc\",\n\t\"domain\",\n\t\"email\",\n\t\"ether\",\n\t\"ethereum\",\n\t\"everyone\",\n\t\"example\",\n\t\"gno\",\n\t\"gnoland\",\n\t\"gnolang\",\n\t\"gnome\",\n\t\"gnot\",\n\t\"gnoworld\",\n\t\"god\",\n\t\"gov\",\n\t\"govdao\",\n\t\"governance\",\n\t\"guest\",\n\t\"help\",\n\t\"home\",\n\t\"host\",\n\t\"info\",\n\t\"invalid\",\n\t\"jaekwon\",\n\t\"jesus\",\n\t\"jesuschrist\",\n\t\"local\",\n\t\"localhost\",\n\t\"login\",\n\t\"mail\",\n\t\"mod\",\n\t\"moderator\",\n\t\"new\",\n\t\"newtendermint\",\n\t\"newtendermintllc\",\n\t\"nt\",\n\t\"ntllc\",\n\t\"null\",\n\t\"owner\",\n\t\"photon\",\n\t\"profile\",\n\t\"register\",\n\t\"registry\",\n\t\"resolution\",\n\t\"resolve\",\n\t\"resolver\",\n\t\"root\",\n\t\"security\",\n\t\"service\",\n\t\"setting\",\n\t\"shop\",\n\t\"signup\",\n\t\"staff\",\n\t\"store\",\n\t\"support\",\n\t\"sys\",\n\t\"sysadmin\",\n\t\"system\",\n\t\"team\",\n\t\"tendermint\",\n\t\"test\",\n\t\"user\",\n}\n"},{"name":"canonical.gno","body":"package namereg\n\nimport (\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// reservedSet is the runtime O(1) lookup for the role-name blacklist.\n// Built in init() from reservedNames in blacklist.gno: each source\n// entry contributes BOTH `Canonicalize(n)` and `Canonicalize(n+\"s\")`\n// as keys, implementing the \"implicit `s` suffix\" rule documented on\n// reservedNames.\n//\n// Why canonicalize the blacklist itself: validation canonicalizes the\n// candidate stem before checking, so the comparison set must also be\n// in canonical form. Otherwise a candidate like \"vital1k\" would\n// canonicalize to \"vitaiik\" but the blacklist would contain only\n// \"vitalik\" — the comparison would miss the match. Keeping both sides\n// in canonical form makes the lookup exact.\n//\n// The blacklist remains namereg/v0-local because it is policy specific\n// to the Open Nym Tier. Other controllers may have entirely different\n// reserved-name policies, or none at all.\nvar reservedSet map[string]struct{}\n\nfunc init() {\n\treservedSet = make(map[string]struct{}, len(reservedNames)*2)\n\tfor _, n := range reservedNames {\n\t\treservedSet[Canonicalize(n)] = struct{}{}\n\t\treservedSet[Canonicalize(n+\"s\")] = struct{}{}\n\t}\n}\n\n// Canonicalize is a delegating shim to r/sys/users.Canonicalize.\n//\n// HISTORY: namereg/v0 used to host its own per-stem canonical store and\n// its own Canonicalize (l→i only). Option B unified the canonical lookup\n// into r/sys/users keyed by full canonical name with broader\n// substitutions ({l,i,1}→i, {0,o}→o, {-,.,_} stripped). This shim\n// preserves the call-site name for local consumers (blacklist init,\n// IsReserved) and any external consumer that imported the function\n// from namereg/v0 before Option B.\n//\n// New code should call susers.Canonicalize directly.\nfunc Canonicalize(s string) string {\n\treturn susers.Canonicalize(s)\n}\n"},{"name":"errors.gno","body":"package namereg\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar (\n\tErrNonUserCall     = errors.New(\"r/gnoland/users: non-user call\")\n\tErrPaused          = errors.New(\"r/gnoland/users: paused\")\n\tErrInvalidUsername = errors.New(\"r/gnoland/users: invalid username\")\n\n\t// ErrInvalidPayment is the sentinel for \"OriginSend amount didn't\n\t// match registerPrice.\" It deliberately omits the price from its\n\t// message — the price is read at panic time via errInvalidPayment()\n\t// below, so users see the CURRENT price even after governance has\n\t// changed it. Tests that match against this error use it as a\n\t// substring check via uassert.AbortsWithMessage. (audit finding #13)\n\tErrInvalidPayment = errors.New(\"r/gnoland/users: invalid payment amount\")\n)\n\n// errInvalidPayment returns the panic value for an OriginSend mismatch.\n// Constructed lazily so the formatted price reflects the current value\n// of registerPrice rather than the value frozen at package init time.\n// Replaces the old `ErrInvalidPayment = ufmt.Errorf(...)` package var\n// (audit finding #13) which captured registerPrice once and silently\n// drifted out of date after every ProposeNewRegisterPrice execution.\nfunc errInvalidPayment() error {\n\treturn ufmt.Errorf(\"%s: must send exactly %d ugnot\",\n\t\tErrInvalidPayment.Error(), registerPrice)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/namereg/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"init.gno","body":"package namereg\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\n\tsusers \"gno.land/r/sys/users\"\n)\n\nfunc init(cur realm) {\n\tif runtime.ChainHeight() == 0 {\n\t\tsusers.AddControllerAtGenesis(cross(cur), chain.PackageAddress(\"gno.land/r/sys/namereg/v0\"))\n\t}\n}\n"},{"name":"preregister.gno","body":"package namereg\n\nimport (\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// Pre-registered names bypass the Open Nym Tier `nym-...\\d{3}` format\n// intentionally. They are bootstrap names allocated at genesis and are\n// not subject to the auto-registration regex. They DO appear in\n// reservedNames as a defense-in-depth (so a future governance-bypass\n// path can't accidentally reallocate them either), but at this layer\n// they are written directly via susers.RegisterUserIgnoreCanonical.\n//\n// Uses the bypass path so curated confusables in the seed (e.g.\n// `gnoland` and `gnolang` both canonicalize distinctly today, but a\n// future addition that collides must not abort chain bring-up).\n// Matches the genesis posture in r/sys/users/init.gno.\n\n// pre-registered users\nvar preRegisteredUsers = []struct {\n\tName    string\n\tAddress address\n}{\n\t// system names.\n\t// the goal is to make them either team/DAO-owned or ownerless.\n\t{\"archive\", \"g1xlnyjrnf03ju82v0f98ruhpgnquk28knmjfe5k\"}, // -\u003e @archive\n\t{\"demo\", \"g13ek2zz9qurzynzvssyc4sthwppnruhnp0gdz8n\"},    // -\u003e @demo\n\t{\"gno\", \"g19602kd9tfxrfd60sgreadt9zvdyyuudcyxsz8a\"},     // -\u003e @gno\n\t{\"gnoland\", \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"}, // -\u003e @gnoland\n\t{\"gnolang\", \"g1yjlnm3z2630gg5mryjd79907e0zx658wxs9hnd\"}, // -\u003e @gnolang\n\t{\"gov\", \"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da\"},     // -\u003e @gov\n\t{\"nt\", \"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l\"},      // -\u003e @nt\n\t{\"sys\", \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"},     // -\u003e @sys\n\t{\"x\", \"g164sdpew3c2t3rvxj3kmfv7c7ujlvcw2punzzuz\"},       // -\u003e @x\n\n\t// test1 user\n\t{\"test1\", \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"}, // -\u003e @test1\n}\n\nfunc init(cur realm) {\n\t// add pre-registered users via the bypass path (genesis posture).\n\t// Errors are intentionally discarded; the seed is curated and any\n\t// duplicate-address / already-deleted entries (re-init across test\n\t// realm reuse) just no-op.\n\tfor _, res := range preRegisteredUsers {\n\t\tsusers.RegisterUserIgnoreCanonical(cross(cur), res.Name, res.Address)\n\t}\n}\n"},{"name":"render.gno","body":"package namereg\n\nimport (\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\t\"gno.land/r/demo/profile\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tif req.Path == \"\" {\n\t\treturn renderHomePage()\n\t}\n\n\t// Otherwise, render the user page\n\treturn renderUserPage(req.Path)\n}\n\nfunc renderHomePage() string {\n\tvar out string\n\n\tout += \"# Gno.land User Registry\\n\"\n\n\tif paused {\n\t\tout += md.HorizontalRule()\n\t\tout += md.H2(\"This realm is paused.\")\n\t\tout += md.Paragraph(\"Check out [`gno.land/r/sys/users`](/r/sys/users) for the current user registry.\")\n\t\tout += md.HorizontalRule()\n\t}\n\n\tout += renderIntroParagraph()\n\n\tout += md.H2(\"Latest registrations\")\n\tout += RenderLatestUsersWidget(-1)\n\n\treturn out\n}\n\nfunc renderIntroParagraph() string {\n\tout := md.Paragraph(\"Welcome to the Gno.land User Registry (v0). Please register a username.\")\n\tout += md.Paragraph(`Registering a username grants the registering address the right to deploy packages and realms\nunder that username’s namespace. For example, if an address registers the username ` + md.InlineCode(\"nym-alice123\") + `, it\nwill gain permission to deploy packages and realms to package paths with the pattern ` + md.InlineCode(\"gno.land/{p,r}/nym-alice123/*\") + `.`)\n\n\tout += md.Paragraph(\"In V0, usernames must match `nym-\u003cstem\u003e\u003cdigits\u003e`, where:\")\n\titems := []string{\n\t\t\"`\u003cstem\u003e` is 5 to 13 lowercase ASCII letters\",\n\t\t\"`\u003cdigits\u003e` is exactly 3 decimal digits\",\n\t\t\"The stem must NOT start with `gno`, `gl`, `atom`, `atone`, `photon`, or `cosmos` (reserved prefixes)\",\n\t\t\"The stem must NOT match a reserved role name (admin, root, support, ...)\",\n\t\t\"Confusable variants (e.g. `vitaiik` vs `vitalik` via `l↔i`) are blocked via canonical-form collision detection\",\n\t\t\"Total username length: 12–20 chars (distinct from `g1...` addresses, which are always 40 chars)\",\n\t}\n\tout += md.BulletList(items)\n\n\tout += \"\\n\\n\"\n\tout += md.Paragraph(\"Vanity names outside this format may be allocated by GovDAO governance through `ProposeNewName`.\")\n\n\tif !paused {\n\t\tamount := ufmt.Sprintf(\"%dugnot\", registerPrice)\n\t\tlink := txlink.NewLink(\"Register\")\n\t\tif registerPrice \u003e 0 {\n\t\t\tlink = link.SetSend(amount)\n\t\t}\n\n\t\tout += md.H3(ufmt.Sprintf(\" [[Click here to register]](%s)\", link.URL()))\n\t\t// XXX: Display registration price adjusting for dynamic GNOT price when it becomes possible.\n\t\tout += ufmt.Sprintf(\"Registration price: %f GNOT (%s)\\n\\n\", float64(registerPrice)/1_000_000, amount)\n\t}\n\n\tout += md.HorizontalRule()\n\tout += \"\\n\\n\"\n\n\treturn out\n}\n\n// resolveUser resolves the user based on the path, determining if it's a name or address\nfunc resolveUser(path string) (*susers.UserData, bool, bool) {\n\tif address(path).IsValid() {\n\t\treturn susers.ResolveAddress(address(path)), false, false\n\t}\n\n\tdata, isLatest := susers.ResolveName(path)\n\treturn data, isLatest, true\n}\n\n// renderUserPage generates the user page based on user data and path\nfunc renderUserPage(path string) string {\n\tvar out string\n\n\t// Render single user page\n\tdata, isLatest, isName := resolveUser(path)\n\tif data == nil {\n\t\tout += md.H1(\"User not found.\")\n\t\tout += \"This user does not exist or has been deleted.\\n\"\n\t\treturn out\n\t}\n\n\tout += md.H1(\"User - \" + md.InlineCode(data.Name()))\n\n\tif isName \u0026\u0026 !isLatest {\n\t\tout += md.Paragraph(ufmt.Sprintf(\n\t\t\t\"Note: You searched for `%s`, which is a previous name of [`%s`](/u/%s).\",\n\t\t\tpath, data.Name(), data.Name()))\n\t} else {\n\t\tout += ufmt.Sprintf(\"Address: %s\\n\\n\", data.Addr().String())\n\n\t\tout += md.H2(\"Bio\")\n\t\tout += profile.GetStringField(data.Addr(), \"Bio\", \"No bio defined.\")\n\t\tout += \"\\n\\n\"\n\t\tout += ufmt.Sprintf(\"[Update bio](%s)\", txlink.Realm(\"gno.land/r/demo/profile\").Call(\"SetStringField\", \"field\", \"Bio\"))\n\t\tout += \"\\n\\n\"\n\t}\n\n\treturn out\n}\n\n// RenderLatestUsersWidget renders the latest num registered users.\n// For num = -1, the maximum number (100) will be displayed.\nfunc RenderLatestUsersWidget(num int) string {\n\tsize := latestUsers.Size()\n\tif size == 0 {\n\t\treturn \"No registered users.\"\n\t}\n\n\tif num \u003e size || num \u003c 0 {\n\t\tnum = size\n\t}\n\n\tentries := latestUsers.Entries()\n\tvar out string\n\n\tfor i := size - 1; i \u003e= size-num; i-- {\n\t\tuser := entries[i].(string)\n\t\tout += md.BulletItem(md.UserLink(user))\n\t}\n\n\treturn out\n}\n"},{"name":"users.gno","body":"package namereg\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/fifo/v0\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// MinRegisterPrice is the lowest price (in ugnot) that\n// ProposeNewRegisterPrice will accept. Set to 0 — registration is free\n// by default; governance can raise the price via ProposeNewRegisterPrice\n// without a floor.\nconst MinRegisterPrice = int64(0)\n\nvar (\n\tregisterPrice = int64(0)      // free by default; governance can raise via ProposeNewRegisterPrice\n\tlatestUsers   = fifo.New(100) // Save the latest 100 users for rendering purposes\n)\n\n// Register registers a new username for the caller.\n//\n// Valid usernames match `nym-[a-z]{5,13}\\d{3}`:\n//   - literal `nym-` prefix (4 chars)\n//   - 5-13 lowercase letters (the alpha stem)\n//   - exactly 3 trailing decimal digits\n//\n// Total length 12-20 chars. The alpha stem additionally must NOT start\n// with `gno`/`gi`/`gl` and must not match a reserved role name (with\n// implicit `s`-suffix expansion). See ValidateNymFormat for the\n// format/blacklist check.\n//\n// Canonical-collision detection is enforced atomically by\n// susers.RegisterUser via the unified canonical store in r/sys/users\n// (decision: per Option B, every controller participates in the same\n// canonical-form lookup keyed by full canonical name).\n//\n// Only direct EOA (maketx call) invocations are supported.\nfunc Register(cur realm, username string) {\n\t// Anti-squatting payment check, two paired guards:\n\t//\n\t//   (a) PreviousRealm must be a pure EOA (IsUserCall: pkgPath == \"\").\n\t//       This excludes intermediate code realms AND user-run ephemeral\n\t//       realms (\"maketx run\" scripts). Both can attach -send to the\n\t//       tx but spend the coins on something other than forwarding to\n\t//       this realm, leaving OriginSend() describing a phantom payment.\n\t//       IsUserCall is the only PreviousRealm shape where the tx-send\n\t//       envelope is guaranteed to have landed at this realm's address.\n\t//\n\t//   (b) OriginSend amount must exactly equal registerPrice. Verifies\n\t//       the tx actually attached the expected amount.\n\t//\n\t// Both checks MUST run together. Removing (a) alone makes (b) meaningless\n\t// because OriginSend() describes tx intent, not realm receipt.\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(ErrNonUserCall)\n\t}\n\n\tif paused {\n\t\tpanic(ErrPaused)\n\t}\n\n\tif unsafe.OriginSend().AmountOf(\"ugnot\") != registerPrice {\n\t\tpanic(errInvalidPayment())\n\t}\n\n\t// Format + prefix + reserved-name check. ValidateNymFormat returns\n\t// one of ErrInvalidFormat, ErrReservedPrefix, ErrBlacklisted.\n\tif err := ValidateNymFormat(username); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Delegate the canonical-collision check + nameStore write atomically\n\t// to r/sys/users. Returns susers.ErrCanonicalCollision if the\n\t// canonical form clashes with an existing registration in any\n\t// controller.\n\tregistrant := cur.Previous().Address()\n\tif err := susers.RegisterUser(cross(cur), username, registrant); err != nil {\n\t\tpanic(err)\n\t}\n\n\tlatestUsers.Append(username)\n\tchain.Emit(\"Registration\", \"address\", registrant.String(), \"name\", username)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"laundervictim","path":"gno.land/r/tests/vm/laundervictim","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/laundervictim\"\ngno = \"0.9\"\n"},{"name":"laundervictim.gno","body":"// Package laundervictim is the \"victim\" realm in the launder-game\n// tests. It exposes a package-level g that an attacker tries to\n// mutate by various means. Two shapes are exposed:\n//\n//   - gVal is `launderpkg.Object` (value type).\n//   - gPtr is `*launderpkg.Object` (pointer to a fresh Object).\n//\n// Both are allocated at init under this realm's context, so their\n// PkgID stamp is /r/.../laundervictim. The attacker's job is to make\n// the stamp not match m.Realm at the write site — by laundering the\n// stamp, capturing the value, or exploiting a borrow-rule shift.\npackage laundervictim\n\nimport \"gno.land/p/demo/tests/launderpkg/v0\"\n\nvar (\n\tgVal launderpkg.Object\n\tgPtr *launderpkg.Object\n\t// gImm is an Immutable: same layout as Object but no mutator\n\t// method in /p/launderpkg. Victim exposes a pointer to it,\n\t// intending \"callers can read but not write.\"\n\tgImm *launderpkg.Immutable\n\t// gBuf is a victim-owned byte buffer (real, /r/laundervictim-stamped\n\t// after init). Used to probe whether a stdlib method (e.g.\n\t// base64.Encode) can be tricked into writing the victim's own buffer\n\t// when an attacker passes it as an out-parameter.\n\tgBuf []byte\n)\n\nfunc init() {\n\tgVal = launderpkg.Object{Field: \"original-val\"}\n\tgPtr = \u0026launderpkg.Object{Field: \"original-ptr\"}\n\tgImm = \u0026launderpkg.Immutable{Field: \"original-imm\"}\n\tgBuf = []byte(\"original-buffer!\")\n}\n\n// GetVal returns g by VALUE (caller gets a copy).\nfunc GetVal() launderpkg.Object { return gVal }\n\n// GetPtr returns the pointer to gPtr's underlying Object. The\n// returned pointer aliases the victim's persisted state.\nfunc GetPtr() *launderpkg.Object { return gPtr }\n\n// GetValAddr returns \u0026gVal — a pointer to the value-typed slot.\n// The returned pointer aliases the victim's persisted state.\nfunc GetValAddr() *launderpkg.Object { return \u0026gVal }\n\n// GetImm returns the pointer to gImm — a *Immutable, which has no\n// mutator method in /p/launderpkg. Victim's intent: callers can read\n// but not write.\nfunc GetImm() *launderpkg.Immutable { return gImm }\n\n// GetBuf returns the victim's own byte buffer. The returned slice\n// aliases the victim's persisted backing array (/r/laundervictim-stamped).\nfunc GetBuf() []byte { return gBuf }\n\n// ReadVal / ReadPtr / ReadImm / ReadBuf report the current values for\n// after-attack verification.\nfunc ReadVal() string { return gVal.Field }\nfunc ReadPtr() string { return gPtr.Field }\nfunc ReadImm() string { return gImm.Field }\nfunc ReadBuf() string { return string(gBuf) }\n\n// Exploiter is the interface the victim accepts. The attacker\n// supplies an implementation; the victim invokes Something(g)\n// passing its own g. This is the \"victim hands attacker the data\"\n// vector.\ntype Exploiter interface {\n\tSomething(launderpkg.Object)\n\tSomethingPtr(*launderpkg.Object)\n}\n\n// Invoke calls the attacker's methods passing the victim's g by both\n// value and by pointer.\nfunc Invoke(e Exploiter) {\n\te.Something(gVal)\n\te.SomethingPtr(gPtr)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"grc20factory","path":"gno.land/r/demo/defi/grc20factory","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/defi/grc20factory\"\ngno = \"0.9\"\n"},{"name":"grc20factory.gno","body":"package grc20factory\n\nimport (\n\t\"gno.land/p/moul/md/v0\"\n\tp \"gno.land/p/nt/avl/pager/v0\"\n\t\"gno.land/p/nt/avl/rotree/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nvar (\n\tinstances   avl.Tree // symbol -\u003e *instance\n\tnextTokenID seqid.ID\n\tpager       = p.NewPager(rotree.Wrap(\u0026instances, nil), 20, false)\n)\n\ntype instance struct {\n\ttoken  *grc20.Token\n\tledger *grc20.PrivateLedger\n\tadmin  *ownable.Ownable\n\tfaucet int64 // per-request amount. disabled if 0.\n}\n\nfunc New(cur realm, name, symbol string, decimals int, initialMint, faucet int64) {\n\tcaller := cur.Previous().Address()\n\tNewWithAdmin(cur, name, symbol, decimals, initialMint, faucet, caller)\n}\n\nfunc NewWithAdmin(cur realm, name, symbol string, decimals int, initialMint, faucet int64, admin address) {\n\texists := instances.Has(symbol)\n\tif exists {\n\t\tpanic(\"token already exists\")\n\t}\n\n\ttoken, ledger := grc20.NewToken(name, symbol, decimals, nextTokenID.Next(), cur)\n\tif initialMint \u003e 0 {\n\t\tledger.Mint(admin, initialMint)\n\t}\n\n\tinst := instance{\n\t\ttoken:  token,\n\t\tledger: ledger,\n\t\tadmin:  ownable.NewWithAddress(admin),\n\t\tfaucet: faucet,\n\t}\n\tinstances.Set(symbol, \u0026inst)\n\n\tgrc20reg.Register(cross(cur), token, symbol)\n}\n\nfunc Bank(symbol string) *grc20.Token {\n\tinst := mustGetInstance(symbol)\n\treturn inst.token\n}\n\nfunc TotalSupply(symbol string) int64 {\n\tinst := mustGetInstance(symbol)\n\treturn inst.token.ReadonlyTeller().TotalSupply()\n}\n\nfunc HasAddr(symbol string, owner address) bool {\n\tinst := mustGetInstance(symbol)\n\treturn inst.token.HasAddr(owner)\n}\n\nfunc BalanceOf(symbol string, owner address) int64 {\n\tinst := mustGetInstance(symbol)\n\treturn inst.token.ReadonlyTeller().BalanceOf(owner)\n}\n\nfunc Allowance(symbol string, owner, spender address) int64 {\n\tinst := mustGetInstance(symbol)\n\treturn inst.token.ReadonlyTeller().Allowance(owner, spender)\n}\n\nfunc Transfer(cur realm, symbol string, to address, amount int64) {\n\tinst := mustGetInstance(symbol)\n\tcaller := cur.Previous().Address()\n\tteller := inst.ledger.ImpersonateTeller(caller)\n\tcheckErr(teller.Transfer(0, cur, to, amount))\n}\n\nfunc Approve(cur realm, symbol string, spender address, amount int64) {\n\tinst := mustGetInstance(symbol)\n\tcaller := cur.Previous().Address()\n\tteller := inst.ledger.ImpersonateTeller(caller)\n\tcheckErr(teller.Approve(0, cur, spender, amount))\n}\n\nfunc TransferFrom(cur realm, symbol string, from, to address, amount int64) {\n\tinst := mustGetInstance(symbol)\n\tcaller := cur.Previous().Address()\n\tteller := inst.ledger.ImpersonateTeller(caller)\n\tcheckErr(teller.TransferFrom(0, cur, from, to, amount))\n}\n\n// faucet.\nfunc Faucet(cur realm, symbol string) {\n\tinst := mustGetInstance(symbol)\n\tif inst.faucet == 0 {\n\t\tpanic(\"faucet disabled for this token\")\n\t}\n\t// FIXME: add limits?\n\t// FIXME: add payment in gnot?\n\tcaller := cur.Previous().Address()\n\tcheckErr(inst.ledger.Mint(caller, inst.faucet))\n}\n\nfunc Mint(cur realm, symbol string, to address, amount int64) {\n\tinst := mustGetInstance(symbol)\n\tinst.admin.AssertOwnedBy(cur.Previous().Address())\n\tcheckErr(inst.ledger.Mint(to, amount))\n}\n\nfunc Burn(cur realm, symbol string, from address, amount int64) {\n\tinst := mustGetInstance(symbol)\n\tinst.admin.AssertOwnedBy(cur.Previous().Address())\n\tcheckErr(inst.ledger.Burn(from, amount))\n}\n\n// instance admin functionality\nfunc DropInstanceOwnership(cur realm, symbol string) {\n\tinst := mustGetInstance(symbol)\n\tcheckErr(inst.admin.DropOwnership(0, cur))\n}\n\nfunc TransferInstanceOwnership(cur realm, symbol string, newOwner address) {\n\tinst := mustGetInstance(symbol)\n\tcheckErr(inst.admin.TransferOwnership(0, cur, newOwner))\n}\n\nfunc ListTokens(pageNumber, pageSize int) []*grc20.Token {\n\tpage := pager.GetPageWithSize(pageNumber, pageSize)\n\n\ttokens := make([]*grc20.Token, len(page.Items))\n\tfor i := range page.Items {\n\t\ttokens[i] = page.Items[i].Value.(*instance).token\n\t}\n\n\treturn tokens\n}\n\nfunc Render(path string) string {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"\", renderHome)\n\trouter.HandleFunc(\"{symbol}\", renderToken)\n\trouter.HandleFunc(\"{symbol}/balance/{address}\", renderBalance)\n\treturn router.Render(path)\n}\n\nfunc renderHome(res *mux.ResponseWriter, req *mux.Request) {\n\tout := md.H1(ufmt.Sprintf(\"GRC20 Tokens (%d)\", instances.Size()))\n\n\t// Get the current page of tokens based on the request path.\n\tpage := pager.MustGetPageByPath(req.RawPath)\n\n\t// Render the list of tokens.\n\tfor _, item := range page.Items {\n\t\ttoken := item.Value.(*instance).token\n\t\tout += md.BulletItem(\n\t\t\tmd.Link(\n\t\t\t\tufmt.Sprintf(\"%s ($%s)\", token.GetName(), token.GetSymbol()),\n\t\t\t\tufmt.Sprintf(\"/r/demo/grc20factory:%s\", token.GetSymbol()),\n\t\t\t),\n\t\t)\n\t}\n\tout += \"\\n\"\n\n\t// Add the page picker.\n\tout += md.Paragraph(page.Picker(req.Path))\n\n\tres.Write(out)\n}\n\nfunc renderToken(res *mux.ResponseWriter, req *mux.Request) {\n\t// Get the token symbol from the request.\n\tsymbol := req.GetVar(\"symbol\")\n\tinst := mustGetInstance(symbol)\n\n\t// Render the token details.\n\tout := inst.token.RenderHome()\n\tout += md.BulletItem(\n\t\tufmt.Sprintf(\"%s: %s\", md.Bold(\"Admin\"), inst.admin.Owner()),\n\t)\n\n\tres.Write(out)\n}\n\nfunc renderBalance(res *mux.ResponseWriter, req *mux.Request) {\n\tvar (\n\t\tsymbol = req.GetVar(\"symbol\")\n\t\taddr   = req.GetVar(\"address\")\n\t)\n\n\t// Get the balance of the specified address for the token.\n\tinst := mustGetInstance(symbol)\n\tbalance := inst.token.BalanceOf(address(addr))\n\n\t// Render the balance information.\n\tout := md.Paragraph(\n\t\tufmt.Sprintf(\"%s balance: %d\", md.Bold(addr), balance),\n\t)\n\n\tres.Write(out)\n}\n\nfunc mustGetInstance(symbol string) *instance {\n\tt := instances.Get(symbol)\n\tif t == nil {\n\t\tpanic(\"token instance does not exist\")\n\t}\n\treturn t.(*instance)\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"addrset","path":"gno.land/p/nt/addrset/v0","files":[{"name":"addrset.gno","body":"// Package addrset provides a set of blockchain addresses backed by a\n// B+ tree, with a read-only view type for safe cross-realm exposure.\n//\n// It mirrors the gno.land/p/moul/addrset/v0 API on a\n// gno.land/p/nt/bptree/v0 backing: a B+ tree packs many entries per\n// persisted node, so a stored address costs ~0.9 KB vs the\n// one-node-per-entry AVL backing's ~2.0 KB (2.2x asymptotically, 1.6x\n// at 10 entries; insert gas ~2.1x less). Prefer this package when sets\n// are part of persisted realm state; the omitted Tree() escape hatch is\n// deliberate, so the backing store never leaks.\n//\n// Two behavioral differences from the AVL-backed moul package, both\n// consequences of the in-place-mutating backing:\n//\n//   - the set must NOT be mutated (Add/Remove) from inside an iteration\n//     callback — the AVL backing's copy-on-write tolerated it, this one\n//     does not;\n//   - do not copy a non-zero Set by value — the copies share live tree\n//     nodes while their roots and sizes diverge (the AVL backing's\n//     copies were independent snapshots).\n//\n// Example:\n//\n//\tvar set addrset.Set // the zero value is an empty, usable set\n//\n//\tset.Add(addr)   // true (newly added)\n//\tset.Has(addr)   // true\n//\tset.Remove(addr) // true (was present)\npackage addrset\n\nimport \"gno.land/p/nt/bptree/v0\"\n\n// Set stores a set of addresses in sorted order. The zero value is an\n// empty, usable set.\ntype Set struct {\n\ttree bptree.BPTree\n}\n\n// Add inserts an address into the set.\n// Returns true if the address was newly added, false if it already existed.\nfunc (s *Set) Add(addr address) bool {\n\treturn !s.tree.Set(string(addr), nil)\n}\n\n// Remove deletes an address from the set.\n// Returns true if the address was found and removed, false if it didn't exist.\nfunc (s *Set) Remove(addr address) bool {\n\t_, removed := s.tree.Remove(string(addr))\n\treturn removed\n}\n\n// Has checks if an address exists in the set.\nfunc (s *Set) Has(addr address) bool {\n\treturn s.tree.Has(string(addr))\n}\n\n// Size returns the number of addresses in the set.\nfunc (s *Set) Size() int {\n\treturn s.tree.Size()\n}\n\n// IterateByOffset walks through addresses in sorted order, starting at\n// the given offset and visiting up to count addresses. The callback\n// returns true to stop iteration. The set must not be modified during\n// iteration (no Add or Remove from the callback).\nfunc (s *Set) IterateByOffset(offset int, count int, cb func(addr address) bool) {\n\ts.tree.IterateByOffset(offset, count, func(key string, _ any) bool {\n\t\treturn cb(address(key))\n\t})\n}\n\n// ReverseIterateByOffset walks through addresses in reverse (descending)\n// order, starting at the given offset (counted from the end) and\n// visiting up to count addresses. The callback returns true to stop\n// iteration. The set must not be modified during iteration (no Add or\n// Remove from the callback).\nfunc (s *Set) ReverseIterateByOffset(offset int, count int, cb func(addr address) bool) {\n\ts.tree.ReverseIterateByOffset(offset, count, func(key string, _ any) bool {\n\t\treturn cb(address(key))\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/addrset/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l\"\n"},{"name":"readonly.gno","body":"package addrset\n\n// ReadonlySet is a read-only view of a *Set. Cross-package callers cannot\n// mutate the underlying set through this type: it exposes no mutator\n// methods and holds the *Set in an unexported field, so a foreign realm\n// can neither reach the set nor invoke Add/Remove on it.\n//\n// A ReadonlySet is a thin handle over the live Set (it does not copy or\n// snapshot), so reads through it always reflect the Set's current contents.\ntype ReadonlySet struct {\n\tset *Set\n}\n\n// NewReadonlySet returns a read-only view of s.\nfunc NewReadonlySet(s *Set) *ReadonlySet {\n\treturn \u0026ReadonlySet{set: s}\n}\n\n// Readonly returns a read-only view of the set.\nfunc (s *Set) Readonly() *ReadonlySet {\n\treturn NewReadonlySet(s)\n}\n\n// Has reports whether addr is in the underlying set.\nfunc (r ReadonlySet) Has(addr address) bool {\n\treturn r.set.Has(addr)\n}\n\n// Size returns the number of addresses in the underlying set.\nfunc (r ReadonlySet) Size() int {\n\treturn r.set.Size()\n}\n\n// IterateByOffset walks the underlying set in sorted order, starting at\n// offset and visiting up to count addresses. fn returns true to stop early;\n// IterateByOffset returns true if iteration was stopped that way.\n//\n// The wrapped Set.IterateByOffset has no return value, so the \"stopped\"\n// result is synthesized from the last callback return via a\n// closure-captured local.\nfunc (r ReadonlySet) IterateByOffset(offset, count int, fn func(addr address) bool) (stopped bool) {\n\tr.set.IterateByOffset(offset, count, func(a address) bool {\n\t\tstopped = fn(a)\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n\n// ReverseIterateByOffset is IterateByOffset in reverse (descending) order.\nfunc (r ReadonlySet) ReverseIterateByOffset(offset, count int, fn func(addr address) bool) (stopped bool) {\n\tr.set.ReverseIterateByOffset(offset, count, func(a address) bool {\n\t\tstopped = fn(a)\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"bylaws","path":"gno.land/p/nt/bylaws/v0","files":[{"name":"bylaws.gno","body":"// Package bylaws stores a DAO's governing documents — bylaws and\n// mandates — as named plaintext files and amends them with verifiable\n// diff patches.\n//\n// Documents are keyed by a slash-separated path (\"mandates/treasury.md\");\n// folders are a naming convention over the path, not stored objects — a\n// folder exists exactly when a document path has it as a prefix. The only\n// mutation is Apply: a Patch carries the sha256 of the document text it\n// was diffed against plus the edit script that transforms that text into\n// the proposed one. Apply rejects the patch when the document has changed\n// since (optimistic concurrency, no clobbering) and otherwise replays the\n// script. An amendment whose result is empty removes the document, so a\n// stored document is never empty.\n//\n// The package is governance-agnostic: it decides nothing about WHO may\n// amend. A consuming realm (e.g. a DAO) gates Apply behind its own vote\n// and keeps the *Bylaws handle private — Apply mutates, so the handle\n// must never be exposed to untrusted callers.\npackage bylaws\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\nconst (\n\t// MaxPathLen bounds a document path's byte length.\n\tMaxPathLen = 200\n\n\t// MaxDocLen bounds a document's byte length. Bylaws are human-written\n\t// prose; the cap keeps documents renderable and patch replay bounded.\n\tMaxDocLen = 64 * 1024\n)\n\nvar (\n\tErrInvalidPath  = errors.New(\"bylaws: invalid document path\")\n\tErrInvalidPatch = errors.New(\"bylaws: invalid patch\")\n\tErrInvalidText  = errors.New(\"bylaws: text is not valid UTF-8\")\n\tErrStalePatch   = errors.New(\"bylaws: document changed since the patch base\")\n\tErrDocTooLarge  = errors.New(\"bylaws: document exceeds the maximum size\")\n)\n\n// Bylaws is one DAO's set of governing documents, keyed by path.\ntype Bylaws struct {\n\tdocs *bptree.BPTree // path (string) -\u003e document text (string, never empty)\n}\n\n// New creates an empty document set.\nfunc New() *Bylaws {\n\treturn \u0026Bylaws{docs: bptree.NewBPTree32()}\n}\n\n// Get returns a document's text and whether it exists.\nfunc (b *Bylaws) Get(path string) (string, bool) {\n\tif v := b.docs.Get(path); v != nil {\n\t\treturn v.(string), true\n\t}\n\treturn \"\", false\n}\n\n// Has reports whether a document exists.\nfunc (b *Bylaws) Has(path string) bool {\n\treturn b.docs.Has(path)\n}\n\n// Size returns the number of documents.\nfunc (b *Bylaws) Size() int {\n\treturn b.docs.Size()\n}\n\n// Hash returns the hex sha256 of a document's text, or an empty string\n// when the document does not exist. It is the base a Patch must pin to\n// amend the document (an empty hash pins \"the document must not exist\").\nfunc (b *Bylaws) Hash(path string) string {\n\tif text, ok := b.Get(path); ok {\n\t\treturn HashText(text)\n\t}\n\treturn \"\"\n}\n\n// List returns the sorted document paths under a prefix. An empty prefix\n// lists every document. The prefix is a raw path prefix: include the\n// trailing slash to scope to a folder (e.g. \"mandates/\"), or \"mandates\"\n// also matches a sibling file like \"mandates-old.md\".\nfunc (b *Bylaws) List(prefix string) []string {\n\tpaths := []string{}\n\tb.Iterate(prefix, func(path, _ string) bool {\n\t\tpaths = append(paths, path)\n\t\treturn false\n\t})\n\treturn paths\n}\n\n// Iterate walks the documents under a prefix in sorted path order until\n// fn returns true. It returns true when the walk was stopped by fn. The\n// set must not be amended during iteration (no Apply from fn).\nfunc (b *Bylaws) Iterate(prefix string, fn func(path, text string) bool) bool {\n\tend := \"\"\n\tif prefix != \"\" {\n\t\t// Path bytes are all \u003c 0x7f (see IsValidPath), so every key with\n\t\t// the prefix sorts before prefix+\"\\x7f\". The tree iterates the\n\t\t// half-open range [start, end) in sorted key order.\n\t\tend = prefix + \"\\x7f\"\n\t}\n\treturn b.docs.Iterate(prefix, end, func(key string, value any) bool {\n\t\treturn fn(key, value.(string))\n\t})\n}\n\n// HashText returns the hex sha256 of a text.\nfunc HashText(text string) string {\n\tsum := sha256.Sum256([]byte(text))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// IsValidPath reports whether a path names a document: one or more\n// non-empty \"/\"-separated segments of [a-zA-Z0-9._-] characters, where no\n// segment is \".\" or \"..\". The restricted charset keeps paths render- and\n// link-safe and the patch encoding delimiter-free.\nfunc IsValidPath(path string) bool {\n\tif path == \"\" || len(path) \u003e MaxPathLen {\n\t\treturn false\n\t}\n\tsegStart := 0\n\tfor i := 0; i \u003c= len(path); i++ {\n\t\tif i == len(path) || path[i] == '/' {\n\t\t\tseg := path[segStart:i]\n\t\t\tif seg == \"\" || seg == \".\" || seg == \"..\" {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tsegStart = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tif !isPathChar(path[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc isPathChar(c byte) bool {\n\treturn c \u003e= 'a' \u0026\u0026 c \u003c= 'z' ||\n\t\tc \u003e= 'A' \u0026\u0026 c \u003c= 'Z' ||\n\t\tc \u003e= '0' \u0026\u0026 c \u003c= '9' ||\n\t\tc == '.' || c == '_' || c == '-'\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bylaws/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l\"\n"},{"name":"patch.gno","body":"package bylaws\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode/utf8\"\n\n\t\"gno.land/p/onbloc/diff/v0\"\n)\n\n// MaxOps bounds the number of ops a decoded patch may carry. DiffTexts\n// output always stays far below it (see maxMyersRunes), so the cap only\n// rejects hand-built pathological payloads at the wire boundary.\nconst MaxOps = 16 * 1024\n\n// maxMyersRunes bounds the combined rune length of the texts handed to\n// MyersDiff, whose memory is O((N+M)·D): past the budget, DiffTexts\n// falls back to replacing the whole changed region in one delete+insert\n// (payload ~ proposed size; replay stays linear). The common prefix and\n// suffix are trimmed first, so ordinary human edits — small changes in a\n// large document — stay within budget and get a minimal script.\nconst maxMyersRunes = 1024\n\n// OpType is the kind of a patch operation.\ntype OpType byte\n\nconst (\n\tOpKeep   OpType = 'K' // keep the next N runes of the base text\n\tOpDelete OpType = 'D' // delete the next N runes of the base text\n\tOpInsert OpType = 'I' // insert literal text\n)\n\n// Op is one run of a patch's edit script. Keep and Delete address the\n// base text positionally (a rune count), so only Insert carries bytes —\n// a small edit to a large document stays a small patch.\ntype Op struct {\n\tType OpType\n\tN    int    // rune count (Keep and Delete only)\n\tText string // inserted literal (Insert only)\n}\n\n// Patch is a verifiable amendment to one document: the edit script that\n// transforms the document's base text into the proposed text, pinned to\n// that base by hash. Apply rejects the patch unless the target currently\n// hashes to Base, so a patch can never be applied to text it was not\n// diffed against.\ntype Patch struct {\n\tPath string // target document path\n\tBase string // hex sha256 of the base text; \"\" pins \"document absent\" (create)\n\tOps  []Op   // edit script, replayed in order against the base text\n}\n\n// IsCreate reports whether the patch creates the document (its base pins\n// \"document absent\").\nfunc (p Patch) IsCreate() bool {\n\treturn p.Base == \"\"\n}\n\n// IsRemove reports whether applying the patch removes the document (the\n// script deletes the whole base text and inserts nothing).\nfunc (p Patch) IsRemove() bool {\n\tif len(p.Ops) == 0 {\n\t\treturn false\n\t}\n\tfor _, op := range p.Ops {\n\t\tif op.Type != OpDelete {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// IsNoop reports whether applying the patch leaves the document set\n// unchanged (the script only keeps text, or creates an empty document).\n// The check is shape-based: a hand-built script that deletes and\n// reinserts identical text is not detected (Diff never produces one).\nfunc (p Patch) IsNoop() bool {\n\tfor _, op := range p.Ops {\n\t\tif op.Type != OpKeep {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Diff builds the patch that changes the document at path to the\n// proposed text: it diffs against the document's current text and pins\n// its hash. A new path yields a create patch; empty proposed text yields\n// a remove patch.\nfunc (b *Bylaws) Diff(path, proposed string) (Patch, error) {\n\tcur, exists := b.Get(path)\n\treturn DiffTexts(path, cur, proposed, exists)\n}\n\n// DiffTexts builds the patch transforming base into proposed for the\n// document at path. exists reports whether the document currently exists\n// (base must be \"\" when it does not); a patch built with exists=false\n// creates the document. Both texts must be valid UTF-8 — documents are\n// plaintext, and the invariant keeps Keep/Delete rune math byte-faithful.\nfunc DiffTexts(path, base, proposed string, exists bool) (Patch, error) {\n\tif !IsValidPath(path) {\n\t\treturn Patch{}, ErrInvalidPath\n\t}\n\tif len(proposed) \u003e MaxDocLen {\n\t\treturn Patch{}, ErrDocTooLarge\n\t}\n\tif !utf8.ValidString(base) || !utf8.ValidString(proposed) {\n\t\treturn Patch{}, ErrInvalidText\n\t}\n\tbaseHash := \"\"\n\tif exists {\n\t\tbaseHash = HashText(base)\n\t}\n\treturn Patch{\n\t\tPath: path,\n\t\tBase: baseHash,\n\t\tOps:  diffOps(base, proposed),\n\t}, nil\n}\n\n// diffOps builds the coalesced edit script from base to proposed: trim\n// the common prefix and suffix, Myers-diff the differing middles, and\n// past the maxMyersRunes budget replace the whole middle instead. The\n// trimmed middles differ at both ends (or are empty), so the pieces\n// never need merging with the surrounding Keep ops.\nfunc diffOps(base, proposed string) []Op {\n\tb, p := []rune(base), []rune(proposed)\n\n\tpre := 0\n\tfor pre \u003c len(b) \u0026\u0026 pre \u003c len(p) \u0026\u0026 b[pre] == p[pre] {\n\t\tpre++\n\t}\n\tsuf := 0\n\tfor suf \u003c len(b)-pre \u0026\u0026 suf \u003c len(p)-pre \u0026\u0026 b[len(b)-1-suf] == p[len(p)-1-suf] {\n\t\tsuf++\n\t}\n\tbMid, pMid := b[pre:len(b)-suf], p[pre:len(p)-suf]\n\n\tops := []Op{}\n\tif pre \u003e 0 {\n\t\tops = append(ops, Op{Type: OpKeep, N: pre})\n\t}\n\tif len(bMid)+len(pMid) \u003e maxMyersRunes {\n\t\tif len(bMid) \u003e 0 {\n\t\t\tops = append(ops, Op{Type: OpDelete, N: len(bMid)})\n\t\t}\n\t\tif len(pMid) \u003e 0 {\n\t\t\tops = append(ops, Op{Type: OpInsert, Text: string(pMid)})\n\t\t}\n\t} else {\n\t\tops = append(ops, coalesce(diff.MyersDiff(string(bMid), string(pMid)))...)\n\t}\n\tif suf \u003e 0 {\n\t\tops = append(ops, Op{Type: OpKeep, N: suf})\n\t}\n\treturn ops\n}\n\n// coalesce collapses a per-rune Myers edit script into run-length ops:\n// runs of Keep/Delete become counts, runs of Insert carry their literal.\nfunc coalesce(edits []diff.Edit) []Op {\n\tops := []Op{}\n\tvar (\n\t\tlit     strings.Builder\n\t\tcount   int\n\t\tcurType OpType\n\t\thave    bool\n\t)\n\tflush := func() {\n\t\tif !have {\n\t\t\treturn\n\t\t}\n\t\tif curType == OpInsert {\n\t\t\tops = append(ops, Op{Type: OpInsert, Text: lit.String()})\n\t\t} else {\n\t\t\tops = append(ops, Op{Type: curType, N: count})\n\t\t}\n\t\tlit.Reset()\n\t\tcount = 0\n\t\thave = false\n\t}\n\tfor _, e := range edits {\n\t\tvar t OpType\n\t\tswitch e.Type {\n\t\tcase diff.EditKeep:\n\t\t\tt = OpKeep\n\t\tcase diff.EditInsert:\n\t\t\tt = OpInsert\n\t\tdefault:\n\t\t\tt = OpDelete\n\t\t}\n\t\tif !have || t != curType {\n\t\t\tflush()\n\t\t\tcurType = t\n\t\t\thave = true\n\t\t}\n\t\tif t == OpInsert {\n\t\t\tlit.WriteRune(e.Char)\n\t\t} else {\n\t\t\tcount++\n\t\t}\n\t}\n\tflush()\n\treturn ops\n}\n\n// Apply verifies the patch and amends the document set: the target's\n// current text must hash to the patch base (\"\" base means the document\n// must not exist), and the edit script must consume exactly that text.\n// An empty result removes the document. Apply is the package's only\n// mutation; on any error the set is unchanged.\nfunc (b *Bylaws) Apply(p Patch) error {\n\tif !IsValidPath(p.Path) {\n\t\treturn ErrInvalidPath\n\t}\n\tcur, exists := b.Get(p.Path)\n\tcurHash := \"\"\n\tif exists {\n\t\tcurHash = HashText(cur)\n\t}\n\tif p.Base != curHash {\n\t\treturn ErrStalePatch\n\t}\n\tout, err := replay(cur, p.Ops)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(out) \u003e MaxDocLen {\n\t\treturn ErrDocTooLarge\n\t}\n\tif out == \"\" {\n\t\tb.docs.Remove(p.Path)\n\t\treturn nil\n\t}\n\tb.docs.Set(p.Path, out)\n\treturn nil\n}\n\n// replay runs the edit script against the base text: Keep emits base\n// runes and advances, Delete advances, Insert emits its literal. The\n// script must consume the base exactly, so a script that does not fit\n// the text it runs against fails instead of producing garbage.\nfunc replay(base string, ops []Op) (string, error) {\n\tr := []rune(base)\n\tvar (\n\t\tsb strings.Builder\n\t\ti  int\n\t)\n\tfor _, op := range ops {\n\t\tswitch op.Type {\n\t\tcase OpKeep:\n\t\t\tif op.N \u003c= 0 || op.N \u003e len(r)-i {\n\t\t\t\treturn \"\", ErrInvalidPatch\n\t\t\t}\n\t\t\tsb.WriteString(string(r[i : i+op.N]))\n\t\t\ti += op.N\n\t\tcase OpDelete:\n\t\t\tif op.N \u003c= 0 || op.N \u003e len(r)-i {\n\t\t\t\treturn \"\", ErrInvalidPatch\n\t\t\t}\n\t\t\ti += op.N\n\t\tcase OpInsert:\n\t\t\tif op.Text == \"\" {\n\t\t\t\treturn \"\", ErrInvalidPatch\n\t\t\t}\n\t\t\tsb.WriteString(op.Text)\n\t\tdefault:\n\t\t\treturn \"\", ErrInvalidPatch\n\t\t}\n\t}\n\tif i != len(r) {\n\t\treturn \"\", ErrInvalidPatch\n\t}\n\treturn sb.String(), nil\n}\n\n// Format renders the patch against its base text as a plain-text change\n// summary: kept runs collapse to a marker, deleted and inserted text is\n// shown literally with every line marker-prefixed (\"- \"/\"+ \"), so a\n// multi-line literal cannot masquerade as the summary's own markers (an\n// insertion containing \"\\n- fake\" renders as \"+ …\" and \"+ - fake\"). It\n// fails like replay when the script does not fit the base. The output is\n// raw text — callers rendering markdown must escape it (the content is\n// document text, and insertions are proposer-controlled).\nfunc (p Patch) Format(base string) (string, error) {\n\tr := []rune(base)\n\tvar (\n\t\tsb strings.Builder\n\t\ti  int\n\t)\n\tfor _, op := range p.Ops {\n\t\tswitch op.Type {\n\t\tcase OpKeep:\n\t\t\tif op.N \u003c= 0 || op.N \u003e len(r)-i {\n\t\t\t\treturn \"\", ErrInvalidPatch\n\t\t\t}\n\t\t\tsb.WriteString(\"= \" + strconv.Itoa(op.N) + \" unchanged\\n\")\n\t\t\ti += op.N\n\t\tcase OpDelete:\n\t\t\tif op.N \u003c= 0 || op.N \u003e len(r)-i {\n\t\t\t\treturn \"\", ErrInvalidPatch\n\t\t\t}\n\t\t\twriteMarked(\u0026sb, \"- \", string(r[i:i+op.N]))\n\t\t\ti += op.N\n\t\tcase OpInsert:\n\t\t\tif op.Text == \"\" {\n\t\t\t\treturn \"\", ErrInvalidPatch\n\t\t\t}\n\t\t\twriteMarked(\u0026sb, \"+ \", op.Text)\n\t\tdefault:\n\t\t\treturn \"\", ErrInvalidPatch\n\t\t}\n\t}\n\tif i != len(r) {\n\t\treturn \"\", ErrInvalidPatch\n\t}\n\treturn sb.String(), nil\n}\n\n// writeMarked writes text with every line prefixed by marker.\nfunc writeMarked(sb *strings.Builder, marker, text string) {\n\tfor _, line := range strings.Split(text, \"\\n\") {\n\t\tsb.WriteString(marker)\n\t\tsb.WriteString(line)\n\t\tsb.WriteByte('\\n')\n\t}\n}\n\n// Encode serializes the patch to a compact single-string payload fit for\n// a transaction argument: \"v0:\u003cpath\u003e:\u003cbase\u003e:\" followed by one segment\n// per op — \"K\u003cn\u003e;\" and \"D\u003cn\u003e;\" carry rune counts, \"I\u003clen\u003e:\u003cbytes\u003e;\"\n// carries the inserted literal length-prefixed by its byte length (no\n// escaping needed). DecodePatch is the exact inverse.\nfunc (p Patch) Encode() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"v0:\")\n\tsb.WriteString(p.Path)\n\tsb.WriteByte(':')\n\tsb.WriteString(p.Base)\n\tsb.WriteByte(':')\n\tfor _, op := range p.Ops {\n\t\tswitch op.Type {\n\t\tcase OpKeep, OpDelete:\n\t\t\tsb.WriteByte(byte(op.Type))\n\t\t\tsb.WriteString(strconv.Itoa(op.N))\n\t\tcase OpInsert:\n\t\t\tsb.WriteByte(byte(OpInsert))\n\t\t\tsb.WriteString(strconv.Itoa(len(op.Text)))\n\t\t\tsb.WriteByte(':')\n\t\t\tsb.WriteString(op.Text)\n\t\t}\n\t\tsb.WriteByte(';')\n\t}\n\treturn sb.String()\n}\n\n// DecodePatch parses an Encode payload back into a Patch, validating the\n// path, the base hash shape, and every op (counts must be canonical, so\n// DecodePatch accepts exactly Encode's output shape; insert literals\n// must be valid UTF-8, keeping documents plaintext and Keep's rune math\n// byte-faithful). Replay validity against the actual document is Apply's\n// job; DecodePatch only guarantees the patch is well-formed.\nfunc DecodePatch(s string) (Patch, error) {\n\tif !strings.HasPrefix(s, \"v0:\") {\n\t\treturn Patch{}, ErrInvalidPatch\n\t}\n\trest := s[len(\"v0:\"):]\n\ti := strings.IndexByte(rest, ':')\n\tif i \u003c 0 {\n\t\treturn Patch{}, ErrInvalidPatch\n\t}\n\tpath := rest[:i]\n\trest = rest[i+1:]\n\tif !IsValidPath(path) {\n\t\treturn Patch{}, ErrInvalidPath\n\t}\n\tj := strings.IndexByte(rest, ':')\n\tif j \u003c 0 {\n\t\treturn Patch{}, ErrInvalidPatch\n\t}\n\tbase := rest[:j]\n\trest = rest[j+1:]\n\tif !isValidBase(base) {\n\t\treturn Patch{}, ErrInvalidPatch\n\t}\n\tops := []Op{}\n\tfor len(rest) \u003e 0 {\n\t\tif len(ops) == MaxOps {\n\t\t\treturn Patch{}, ErrInvalidPatch\n\t\t}\n\t\tt := OpType(rest[0])\n\t\trest = rest[1:]\n\t\tswitch t {\n\t\tcase OpKeep, OpDelete:\n\t\t\tk := strings.IndexByte(rest, ';')\n\t\t\tif k \u003c 0 {\n\t\t\t\treturn Patch{}, ErrInvalidPatch\n\t\t\t}\n\t\t\tn, ok := parseCount(rest[:k])\n\t\t\tif !ok {\n\t\t\t\treturn Patch{}, ErrInvalidPatch\n\t\t\t}\n\t\t\tops = append(ops, Op{Type: t, N: n})\n\t\t\trest = rest[k+1:]\n\t\tcase OpInsert:\n\t\t\tk := strings.IndexByte(rest, ':')\n\t\t\tif k \u003c 0 {\n\t\t\t\treturn Patch{}, ErrInvalidPatch\n\t\t\t}\n\t\t\tn, ok := parseCount(rest[:k])\n\t\t\tif !ok {\n\t\t\t\treturn Patch{}, ErrInvalidPatch\n\t\t\t}\n\t\t\trest = rest[k+1:]\n\t\t\tif len(rest) \u003c n+1 || rest[n] != ';' {\n\t\t\t\treturn Patch{}, ErrInvalidPatch\n\t\t\t}\n\t\t\ttext := rest[:n]\n\t\t\tif !utf8.ValidString(text) {\n\t\t\t\treturn Patch{}, ErrInvalidText\n\t\t\t}\n\t\t\tops = append(ops, Op{Type: OpInsert, Text: text})\n\t\t\trest = rest[n+1:]\n\t\tdefault:\n\t\t\treturn Patch{}, ErrInvalidPatch\n\t\t}\n\t}\n\treturn Patch{Path: path, Base: base, Ops: ops}, nil\n}\n\n// parseCount parses a strictly canonical op count: decimal digits with\n// no sign and no leading zero (so Encode∘DecodePatch is the identity on\n// accepted payloads), in (0, MaxDocLen].\nfunc parseCount(s string) (int, bool) {\n\tif s == \"\" || s[0] == '0' || len(s) \u003e 6 {\n\t\treturn 0, false\n\t}\n\tn := 0\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c \u003c '0' || c \u003e '9' {\n\t\t\treturn 0, false\n\t\t}\n\t\tn = n*10 + int(c-'0')\n\t}\n\tif n \u003e MaxDocLen {\n\t\treturn 0, false\n\t}\n\treturn n, true\n}\n\n// isValidBase reports whether a base is the empty sentinel (create) or a\n// 64-char lowercase hex sha256.\nfunc isValidBase(base string) bool {\n\tif base == \"\" {\n\t\treturn true\n\t}\n\tif len(base) != 64 {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(base); i++ {\n\t\tc := base[i]\n\t\tif !(c \u003e= '0' \u0026\u0026 c \u003c= '9' || c \u003e= 'a' \u0026\u0026 c \u003c= 'f') {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"commondao","path":"gno.land/p/nt/commondao/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# commondao\n\nGovernance primitives following the Common DAO Spec\n(`docs/CONSTITUTION.md`, Appendix): a `CommonDAO` is a **Council** (a\nset of addresses with equal voting power), a proposal lifecycle, and an\noptional sub-DAO tree.\n\n```\nCommonDAO\n├── council:            *addrset.Set — who may vote\n├── kinds:              registered ProposalKind factories — what may be\n│                       proposed (name → New(readonly dao, args))\n├── active proposals:   active + early passed, each with an electorate\n│                       snapshot and voting record\n├── finished proposals: dismissed / executed / failed / withdrawn\n├── treasury:           a derived address + frozen flag (funds moved by\n│                       the hosting realm, never by this package)\n└── children:           sub-DAOs (each a CommonDAO with a parent pointer)\n```\n\n## Quick start\n\n```go\nimport \"gno.land/p/nt/commondao/v0\"\n\n// A proposal kind names one proposal type and builds its definitions.\ntype textKind struct{}\n\nfunc (textKind) Name() string { return \"text\" }\nfunc (textKind) New(dao commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n    text, ok := args.(string) // validate args, build the definition\n    if !ok || text == \"\" {\n        return nil, errors.New(\"a proposal text is required\")\n    }\n    return textDefinition{text}, nil\n}\n\nvar dao = commondao.New(\n    commondao.WithName(\"My DAO\"),\n    commondao.WithCouncilMember(founder),\n    commondao.WithProposalKind(textKind{}), // a type is proposable iff registered\n)\n\n// Propose looks the kind up in the DAO's registry and calls its New\n// factory with a readonly view of the host DAO and args to build the\n// frozen definition. The council snapshot taken at Propose is the\n// proposal's electorate. (The package does not gate who proposes —\n// hosting realms do.)\np, _ := dao.Propose(founder, \"text\", \"hello world\")\n\n// Electorate members vote; default rule proposals can be decided the\n// moment the outcome is settled.\ndao.Vote(founder, p.ID(), commondao.ChoiceYes, \"\")\n\n// Execute runs passed proposals (early passed ones immediately, active\n// ones once their voting deadline passes). The host mints a DAO-scoped\n// sub-identity and passes it as the executor's value-movement authority.\ndao.Execute(p.ID(), sub)\n```\n\n## Voting rules (the constitutional defaults)\n\nEvery proposal definition returns a `Threshold()`; proposals are decided\nby `TallyDefault` with integer math over the proposal's **electorate\nsnapshot** E (the council at `Propose` time):\n\n```\nD = |E| - abstains                 // the tally denominator\nsupermajority:   pass ⇔ D \u003e 0 \u0026\u0026 3*yes \u003e= 2*D   (\"two thirds or more\")\nsimple majority: pass ⇔ D \u003e 0 \u0026\u0026 2*yes \u003e D       (\"more than half\")\ndismiss (both):       ⇔ 2*no \u003e D\nundecided at deadline ⇒ dismissed\n```\n\nAbstaining shrinks the denominator (deference); not voting counts\nagainst passage (silence is opposition). Votes are re-evaluated after\nevery ballot — including changed votes — so a proposal **passes or is\ndismissed the moment the outcome is mathematically settled** and an\nearly-passed proposal may be executed before its deadline.\n\nVote choices are fixed at YES/NO/ABSTAIN.\n\n## Council changes\n\n`UpdateCouncil(add, remove)` applies idempotent set operations: the\nfinal set is `(council ∪ add) \\ remove`, duplicate adds and absent\nremoves are no-ops (so concurrently passed updates merge in execution\norder), full replacement in one call is legal, and an update that\nwould empty a non-empty council returns `ErrEmptyCouncil` — executors\npropagate the error to fail the proposal cleanly.\n\n## Proposal kinds\n\nProposal types are registered on the DAO, not passed per proposal: a\n`ProposalKind` couples a registry name with a\n`New(dao ReadonlyCommonDAO, args)` factory, and\n`Propose(creator, kind, args)` accepts exactly the kinds registered\n(`WithProposalKind` at construction; `RegisterKind`/`DeregisterKind`\nafterwards, typically from a governance proposal executor). The registry\nis read only at `Propose`: deregistering a kind blocks new proposals but\nnever touches in-flight ones, whose definitions were frozen at creation.\n`HasKind`/`KindNames` expose the registry, also on the readonly view.\n\n`New` receives only a **`ReadonlyCommonDAO`**, so a kind — including an\nexternally-authored or user-registered one — cannot mutate the host DAO\n(or its tree) at `Propose` time, before the vote. A kind that must mutate\nstate on execution takes the target `*CommonDAO` through `args`, which\nonly a trusted caller can populate (an external proposer cannot obtain a\n`*CommonDAO`), captures it in the definition, and mutates in its\n`Executor` — which runs only after the vote passes.\n\n### The `ExecutionKind` concrete kind\n\nThe package ships exactly one concrete kind, `/p/`-typed so any realm can\nseed it with `WithProposalKind(ExecutionKind{})` or register it later\nwith `RegisterKind`:\n\n- **`ExecutionKind`** (`\"execution\"`) runs an arbitrary `ExecFunc`\n  supplied by the proposer (`ExecutionArgs{Title, Body, Fn}`) on\n  approval, under a default policy (7-day voting period, supermajority\n  threshold) and no check on the closure beyond a non-nil `Fn`. The `Fn`\n  closure is frozen at `Propose` (vote-integrity), so it **must be\n  authored in a persistent realm** — a closure created by a `maketx run`\n  script does not persist to `Execute` and cannot run.\n\n  Because it applies no policy to the closure, a realm with treasury\n  constraints (e.g. a freeze flag) should **not** catalog `ExecutionKind`\n  directly: it should author its own execution kind whose definition wraps\n  the closure with a `Validable` check enforcing those constraints, so\n  arbitrary execution cannot bypass them. The reference realm does this to\n  keep a frozen DAO from draining its own treasury via an execution\n  proposal.\n\nA registered foreign-realm kind runs under its **defining** realm's\nauthority — registering one is a governance trust grant, not a sandbox.\n\nThe package ships **no** governance meta-kinds. `RegisterKind` /\n`DeregisterKind` are plain registry primitives with no reserved names:\nany registered kind can be removed. Managing a DAO's kind set through\ngovernance — and keeping a managing kind un-removable so a DAO can always\nrecover — is the consuming realm's policy, built on these primitives (see\nthe reference realm's `manage-kinds` kind).\n\n## Extending commondao in your own realm\n\nThe package is mostly mechanism: it ships the `ExecutionKind` concrete\nkind (with a default voting policy) and the registry primitives, and\nleaves the rest of governance policy — which kinds a DAO accepts, how it\nmanages them, and any per-kind constraints such as a treasury freeze — to\nthe consuming realm. To add your own proposal type:\n\n1. **Author a `ProposalKind`** — `Name()` plus\n   `New(dao ReadonlyCommonDAO, args any) (ProposalDefinition, error)`. Make\n   the definition `Executable` if it mutates on approval. If its executor\n   moves funds from a DAO other than the host, have the **host** realm\n   consume a `Funded`-style contract (`FundingDAOID() uint64`): minting a\n   DAO sub needs the host's `cur`, so it is host-consumed, not\n   package-dispatched — define it in your realm.\n2. **Seed it** — the owning realm holds the handle, so no proposal is\n   needed: `commondao.New(WithProposalKind(YourKind{}), …)` at\n   construction, or `dao.RegisterKind(YourKind{})` directly.\n3. **Author a typed, CLI-friendly wrapper**\n   `CreateYourProposal(cur realm, daoID uint64, …params…)` that\n   council-gates the caller, builds the args, and calls `Propose`.\n4. **Optionally add a governance toggle** — a `manage-kinds`-style kind\n   whose executor calls `RegisterKind`/`DeregisterKind`, kept itself\n   un-deregisterable, if the council should manage kinds at runtime.\n\n**Trust boundary:** `New` gets only a `ReadonlyCommonDAO`; the mutable\n`*CommonDAO` reaches a definition only via args your trusted wrapper\npopulates; the executor gets the DAO's terminal, RealmSend-only sub. See\nthe reference realm for a worked example.\n\n## Proposal lifecycle\n\n`Propose` (kind-gated as above; capped via `SetMaxActiveProposals`;\n`CapExempt` definitions such as council updates bypass the cap, bounded\nto one active proposal per creator) → `Vote` (electorate-gated,\ndeadline-gated, rejects non-active proposals) → `Execute`\n(early-passed: immediately, still validating; active: after the\ndeadline, dismissing undecided proposals) or `Withdraw` (active, zero\nvotes). `Dissolve` dismisses every in-flight proposal and soft deletes\nthe DAO; deleted DAOs reject proposals, votes, and executions.\n\n## Treasury\n\nThe package stores a treasury `address` (`WithAddress`, `Address()`) and\na frozen flag (`SetTreasuryFrozen`, `IsTreasuryFrozen`) but never moves\nfunds — hosting realms derive the address (typically a realm\nsub-identity via `chain.DerivePkgSubAddr`) and enforce the frozen flag.\n`Execute` runs the executor with the DAO-scoped sub-identity the host\npasses as its value-movement authority: a fund-moving definition builds\nits banker from that `sub`, so value moves are structurally bounded to\nthat one DAO address. Which DAO's sub the host mints is the host's\ndecision — minting a sub needs the host realm's `cur`, so the package\ncannot make it — typically the proposal's own DAO, but a fund-moving\ndefinition may direct the host to a different DAO (e.g. clawback sweeps\nthe target, not the host). See the reference realm's treasury proposals\nand its host-side `Funded` contract for the constitutional pattern.\n\n## Realm boundaries\n\nA `*CommonDAO` is a mutable handle for the realm that owns it:\n\n1. Do not ACCEPT a `*CommonDAO` from an untrusted caller.\n2. Do not RETURN a `*CommonDAO` — return `dao.Readonly()`, a\n   `ReadonlyCommonDAO` view whose whole reachable graph is read-only\n   (`ReadonlyProposal` flattens `Title()`/`Body()` and never exposes\n   the `ProposalDefinition`, whose executor would otherwise be\n   callable under your realm's authority).\n3. Do not TRUST a readonly view received from an untrusted caller —\n   it is a live handle over the sender's data.\n\nSee `gno.land/r/nt/commondao/v0` for the reference realm hosting many\nDAOs with invitations, council governance, treasuries, and rendering.\n"},{"name":"commondao.gno","body":"package commondao\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/addrset/v0\"\n\t\"gno.land/p/nt/bptree/list/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\n// DefaultMaxActiveProposals is the default cap for simultaneously active\n// proposals per DAO. Every active proposal stores a council snapshot, so\n// the cap bounds storage. It is applied at construction; a hosting realm\n// may override it per DAO via SetMaxActiveProposals (the reference realm\n// keeps this default).\nconst DefaultMaxActiveProposals = 32\n\nvar (\n\tErrCouncilUpdateOverlap  = errors.New(\"council update adds and removes the same address\")\n\tErrDAOIsDeleted          = errors.New(\"DAO is deleted\")\n\tErrEmptyCouncil          = errors.New(\"council update would remove every council member\")\n\tErrExecutionNotAllowed   = errors.New(\"proposal must be active or passed to be executed\")\n\tErrInvalidVoteChoice     = errors.New(\"invalid vote choice\")\n\tErrMaxActiveProposals    = errors.New(\"max number of active proposals reached\")\n\tErrMaxCapExemptProposals = errors.New(\"creator already has an active cap exempt proposal\")\n\tErrNotElectorateMember   = errors.New(\"account is not a member of the proposal's electorate\")\n\tErrOverflow              = errors.New(\"next ID overflows uint64\")\n\tErrProposalKindExists    = errors.New(\"proposal kind already registered\")\n\tErrProposalKindNotFound  = errors.New(\"proposal kind not found\")\n\tErrProposalKindRequired  = errors.New(\"proposal kind is required\")\n\tErrProposalNotFound      = errors.New(\"proposal not found\")\n\tErrVotingDeadlineNotMet  = errors.New(\"voting deadline not met\")\n\tErrVotingDeadlinePassed  = errors.New(\"voting deadline has passed\")\n\tErrWithdrawalNotAllowed  = errors.New(\"withdrawal not allowed for proposals with votes\")\n)\n\n// CommonDAO defines a DAO.\n//\n// # Security\n//\n// A *CommonDAO is a mutable handle: its exported mutators (UpdateCouncil,\n// Dissolve, Propose, Vote, Execute, Withdraw, SetTreasuryFrozen,\n// SetMaxActiveProposals, RegisterKind, DeregisterKind) are meant for the\n// realm that owns the DAO.\n// Three rules apply at realm boundaries:\n//\n//  1. Do not ACCEPT a *CommonDAO from an external/untrusted caller.\n//  2. Do not RETURN a *CommonDAO from any function callable by untrusted\n//     realms — return dao.Readonly() (a ReadonlyCommonDAO view) instead.\n//  3. Do not TRUST a readonly view received from an untrusted caller: it\n//     is a live handle over the sender's data.\ntype CommonDAO struct {\n\tid                 uint64\n\tname               string\n\tdescription        string\n\tpurpose            string\n\taddr               address // derived treasury address, empty when unset\n\tparent             *CommonDAO\n\tchildren           list.IList\n\tcouncil            *addrset.Set\n\tgenID              seqid.ID\n\tkinds              *bptree.BPTree // proposal kind name -\u003e ProposalKind\n\tactiveProposals    *proposalStorage\n\tfinishedProposals  *proposalStorage\n\tdeleted            bool // Soft delete\n\ttreasuryFrozen     bool\n\tmaxActiveProposals int\n\tproposing          bool // re-entrancy latch around a kind's New in Propose\n\texecuting          bool // re-entrancy latch around Execute\n}\n\n// New creates a new common DAO.\nfunc New(options ...Option) *CommonDAO {\n\tdao := \u0026CommonDAO{\n\t\tchildren:           \u0026list.List{},\n\t\tcouncil:            \u0026addrset.Set{},\n\t\tkinds:              bptree.NewBPTree32(),\n\t\tactiveProposals:    newProposalStorage(),\n\t\tfinishedProposals:  newProposalStorage(),\n\t\tmaxActiveProposals: DefaultMaxActiveProposals,\n\t}\n\tfor _, apply := range options {\n\t\tapply(dao)\n\t}\n\treturn dao\n}\n\n// ID returns DAO's unique identifier.\nfunc (dao CommonDAO) ID() uint64 {\n\treturn dao.id\n}\n\n// Name returns DAO's name.\nfunc (dao CommonDAO) Name() string {\n\treturn dao.name\n}\n\n// Purpose returns the DAO's purpose. Together with the description it\n// forms the DAO's Charter (docs/CONSTITUTION.md :1485).\nfunc (dao CommonDAO) Purpose() string {\n\treturn dao.purpose\n}\n\n// Description returns DAO's description.\nfunc (dao CommonDAO) Description() string {\n\treturn dao.description\n}\n\n// Address returns the DAO's treasury address, assigned at creation with\n// WithAddress. The package never derives or uses the address itself:\n// hosting realms derive it (e.g. from a realm sub-identity) and operate\n// its funds through their own banker. Empty when unset.\nfunc (dao CommonDAO) Address() address {\n\treturn dao.addr\n}\n\n// IsTreasuryFrozen checks if the DAO's treasury is frozen. The package\n// stores the flag only; hosting realms enforce it when moving funds.\nfunc (dao CommonDAO) IsTreasuryFrozen() bool {\n\treturn dao.treasuryFrozen\n}\n\n// SetTreasuryFrozen freezes or unfreezes the DAO's treasury.\nfunc (dao *CommonDAO) SetTreasuryFrozen(frozen bool) {\n\tdao.treasuryFrozen = frozen\n}\n\n// Parent returns the parent DAO.\n// Null can be returned when DAO has no parent assigned.\nfunc (dao CommonDAO) Parent() *CommonDAO {\n\treturn dao.parent\n}\n\n// ChildrenCount returns the number of direct children DAOs.\nfunc (dao CommonDAO) ChildrenCount() int {\n\treturn dao.children.Len()\n}\n\n// IterateChildren iterates the direct children DAOs.\nfunc (dao CommonDAO) IterateChildren(fn func(*CommonDAO) bool) (stopped bool) {\n\tdao.children.ForEach(func(_ int, v any) bool {\n\t\tstopped = fn(v.(*CommonDAO))\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n\n// Council returns a read only view of the DAO council.\n//\n// The council is the set of addresses entitled to vote. It changes only\n// through UpdateCouncil (normally called by a council update proposal\n// executor) or constructor options.\nfunc (dao CommonDAO) Council() *addrset.ReadonlySet {\n\treturn dao.council.Readonly()\n}\n\n// UpdateCouncil adds and removes council members as idempotent set\n// operations: adding an existing member or removing an absent one is a\n// no-op, so concurrently passed council updates merge deterministically in\n// execution order, and a full council replacement in a single update is\n// legal.\n//\n// The final set is (council ∪ add) \\ remove. An update that adds and\n// removes the same address is rejected, and an update whose final set\n// would empty a non-empty council returns ErrEmptyCouncil: executors must\n// propagate the error (failing the proposal) instead of panicking, which\n// would revert the transaction and leave the proposal stuck.\nfunc (dao *CommonDAO) UpdateCouncil(add, remove []address) error {\n\tfor _, a := range add {\n\t\tfor _, r := range remove {\n\t\t\tif a == r {\n\t\t\t\treturn ErrCouncilUpdateOverlap\n\t\t\t}\n\t\t}\n\t}\n\n\t// The final set can only be empty when nothing is added: overlap is\n\t// rejected above, so any added address survives its own update.\n\tif dao.council.Size() \u003e 0 \u0026\u0026 len(add) == 0 {\n\t\tempty := true\n\t\tdao.council.IterateByOffset(0, dao.council.Size(), func(member address) bool {\n\t\t\tfor _, r := range remove {\n\t\t\t\tif r == member {\n\t\t\t\t\treturn false // removed: keep looking for a survivor\n\t\t\t\t}\n\t\t\t}\n\t\t\tempty = false\n\t\t\treturn true\n\t\t})\n\t\tif empty {\n\t\t\treturn ErrEmptyCouncil\n\t\t}\n\t}\n\n\tfor _, a := range add {\n\t\tdao.council.Add(a)\n\t}\n\tfor _, r := range remove {\n\t\tdao.council.Remove(r)\n\t}\n\treturn nil\n}\n\n// ActiveProposalsSize returns the number of active proposals, including\n// early passed proposals that were not executed yet.\nfunc (dao CommonDAO) ActiveProposalsSize() int {\n\treturn dao.activeProposals.Size()\n}\n\n// IterateActiveProposals iterates active proposals ordered by ID.\nfunc (dao CommonDAO) IterateActiveProposals(offset, count int, reverse bool, fn func(*Proposal) bool) bool {\n\treturn dao.activeProposals.Iterate(offset, count, reverse, fn)\n}\n\n// FinishedProposalsSize returns the number of finished proposals.\nfunc (dao CommonDAO) FinishedProposalsSize() int {\n\treturn dao.finishedProposals.Size()\n}\n\n// IterateFinishedProposals iterates finished proposals ordered by ID.\nfunc (dao CommonDAO) IterateFinishedProposals(offset, count int, reverse bool, fn func(*Proposal) bool) bool {\n\treturn dao.finishedProposals.Iterate(offset, count, reverse, fn)\n}\n\n// IsDeleted returns true when DAO has been soft deleted.\nfunc (dao CommonDAO) IsDeleted() bool {\n\treturn dao.deleted\n}\n\n// MaxActiveProposals returns the cap for simultaneously active proposals.\nfunc (dao CommonDAO) MaxActiveProposals() int {\n\treturn dao.maxActiveProposals\n}\n\n// SetMaxActiveProposals changes the cap for simultaneously active\n// proposals. Values below one are ignored: a DAO must always be able to\n// propose.\nfunc (dao *CommonDAO) SetMaxActiveProposals(max int) {\n\tif max \u003e= 1 {\n\t\tdao.maxActiveProposals = max\n\t}\n}\n\n// RegisterKind registers a proposal kind by its name.\n//\n// Registered kinds are the only way to create proposals: Propose looks\n// kinds up by name and calls their New factory, so a proposal type is\n// proposable iff its kind is registered. Like SetTreasuryFrozen, this\n// mutator is meant for the realm that owns the DAO (typically called at\n// DAO creation and by governance proposal executors).\nfunc (dao *CommonDAO) RegisterKind(k ProposalKind) error {\n\tif k == nil || k.Name() == \"\" {\n\t\treturn ErrProposalKindRequired\n\t}\n\tif dao.kinds.Has(k.Name()) {\n\t\treturn ErrProposalKindExists\n\t}\n\tdao.kinds.Set(k.Name(), k)\n\treturn nil\n}\n\n// DeregisterKind removes a proposal kind by name.\n//\n// Deregistering only blocks new proposals: the registry is read at\n// Propose time only, so in-flight proposals of the kind keep their\n// frozen definition and still vote and execute.\n//\n// This is a plain registry primitive with no reserved names: any\n// registered kind can be removed. A consuming realm that must keep a\n// kind un-removable (e.g. a governance kind that manages the kind set)\n// enforces that as its own policy, not through this package.\nfunc (dao *CommonDAO) DeregisterKind(name string) error {\n\tif _, removed := dao.kinds.Remove(name); !removed {\n\t\treturn ErrProposalKindNotFound\n\t}\n\treturn nil\n}\n\n// HasKind checks if a proposal kind is registered.\nfunc (dao CommonDAO) HasKind(name string) bool {\n\treturn dao.kinds.Has(name)\n}\n\n// KindNames returns the names of the registered proposal kinds, sorted.\nfunc (dao CommonDAO) KindNames() []string {\n\tnames := make([]string, 0, dao.kinds.Size())\n\tdao.kinds.IterateByOffset(0, dao.kinds.Size(), func(name string, _ any) bool {\n\t\tnames = append(names, name)\n\t\treturn false\n\t})\n\treturn names\n}\n\n// Propose creates a new DAO proposal.\n//\n// Proposals are created through registered proposal kinds: the kind is\n// looked up by name in the DAO's registry and its New factory builds the\n// proposal definition from args. The registry is read only here and the\n// definition is frozen once the proposal is created, so deregistering a\n// kind later never touches in-flight proposals.\n//\n// The proposal's electorate is the council snapshot taken now: members\n// added later vote on the next proposal; members removed later remain in\n// the electorate, where their silence counts against passage.\n//\n// The number of simultaneously active proposals is capped. Definitions\n// implementing CapExempt (e.g. council updates, which must never be\n// blockable by a full cap) are exempt but bounded to one active proposal\n// per creator.\nfunc (dao *CommonDAO) Propose(creator address, kind string, args any) (*Proposal, error) {\n\tif dao.deleted {\n\t\treturn nil, ErrDAOIsDeleted\n\t}\n\n\tv := dao.kinds.Get(kind)\n\tif v == nil {\n\t\treturn nil, ErrProposalKindNotFound\n\t}\n\n\t// Re-entrancy latch: a kind's New must not trigger another Propose on\n\t// this DAO (e.g. via a captured handle), which could nest factory\n\t// calls or grow active storage unboundedly before the first returns.\n\tif dao.proposing {\n\t\tpanic(\"commondao: re-entrant Propose is not allowed\")\n\t}\n\tdao.proposing = true\n\t// Deferred so a panicking New cannot leave the latch stuck (which would\n\t// brick every future Propose on this DAO for a consumer that recovers\n\t// the panic within the transaction); mirrors the executing latch.\n\tdefer func() { dao.proposing = false }()\n\td, err := v.(ProposalKind).New(dao.Readonly(), args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif d == nil {\n\t\treturn nil, ErrProposalDefinitionRequired\n\t}\n\n\tif _, exempt := d.(CapExempt); exempt {\n\t\tvar found bool\n\t\tdao.activeProposals.Iterate(0, dao.activeProposals.Size(), false, func(p *Proposal) bool {\n\t\t\tif _, ok := p.definition.(CapExempt); ok \u0026\u0026 p.creator == creator {\n\t\t\t\tfound = true\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tif found {\n\t\t\treturn nil, ErrMaxCapExemptProposals\n\t\t}\n\t} else if dao.activeProposals.Size() \u003e= dao.maxActiveProposals {\n\t\treturn nil, ErrMaxActiveProposals\n\t}\n\n\tid, ok := dao.genID.TryNext()\n\tif !ok {\n\t\treturn nil, ErrOverflow\n\t}\n\n\tp, err := newProposal(uint64(id), creator, d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Snapshot the current council as the proposal's electorate\n\tdao.council.IterateByOffset(0, dao.council.Size(), func(member address) bool {\n\t\tp.electorate.Add(member)\n\t\treturn false\n\t})\n\n\tdao.activeProposals.Add(p)\n\treturn p, nil\n}\n\n// GetProposal returns a proposal or nil when proposal is not found.\nfunc (dao CommonDAO) GetProposal(proposalID uint64) *Proposal {\n\tp := dao.activeProposals.Get(proposalID)\n\tif p != nil {\n\t\treturn p\n\t}\n\treturn dao.finishedProposals.Get(proposalID)\n}\n\n// Withdraw withdraws a proposal that has no votes.\n// Only active proposals without votes can be withdrawn, and once\n// withdrawn they are considered finished.\nfunc (dao *CommonDAO) Withdraw(proposalID uint64) error {\n\tp := dao.activeProposals.Get(proposalID)\n\tif p == nil {\n\t\treturn ErrProposalNotFound\n\t}\n\n\tif p.status != StatusActive {\n\t\treturn ErrStatusIsNotActive\n\t}\n\n\tif p.record.Size() \u003e 0 {\n\t\treturn ErrWithdrawalNotAllowed\n\t}\n\n\tp.status = StatusWithdrawn\n\tdao.activeProposals.Remove(p.id)\n\tdao.finishedProposals.Add(p)\n\treturn nil\n}\n\n// Vote submits a new vote for a proposal.\n//\n// Votes are only allowed to members of the proposal's electorate while the\n// proposal is active and within the voting period. A member may change\n// their vote by voting again.\n//\n// Proposals are re-evaluated after every recorded vote: a YES tally at\n// the definition's threshold decides the proposal immediately, and a\n// simple majority of NO dismisses it immediately.\nfunc (dao *CommonDAO) Vote(member address, proposalID uint64, c VoteChoice, reason string) error {\n\tif dao.deleted {\n\t\treturn ErrDAOIsDeleted\n\t}\n\n\tp := dao.activeProposals.Get(proposalID)\n\tif p == nil {\n\t\treturn ErrProposalNotFound\n\t}\n\n\tif p.status != StatusActive {\n\t\treturn ErrStatusIsNotActive\n\t}\n\n\tif !p.electorate.Has(member) {\n\t\treturn ErrNotElectorateMember\n\t}\n\n\tif p.HasVotingDeadlinePassed() {\n\t\treturn ErrVotingDeadlinePassed\n\t}\n\n\tif c != ChoiceYes \u0026\u0026 c != ChoiceNo \u0026\u0026 c != ChoiceAbstain {\n\t\treturn ErrInvalidVoteChoice\n\t}\n\n\tp.record.AddVote(Vote{\n\t\taddr:   member,\n\t\tchoice: c,\n\t\treason: reason,\n\t})\n\n\t// Early termination: proposals are decided the moment the outcome is\n\t// mathematically settled. A passed proposal stays in the active\n\t// storage until executed; a dismissed one is finished.\n\tswitch TallyDefault(p.record.Readonly(), p.Electorate(), p.definition.Threshold()) {\n\tcase OutcomePassed:\n\t\tp.status = StatusPassed\n\tcase OutcomeDismissed:\n\t\tdao.dismiss(p)\n\t}\n\treturn nil\n}\n\n// Execute executes a proposal.\n//\n// Proposals that already passed (decided early by the default Council\n// rules) execute immediately. Active proposals are tallied once their\n// voting deadline passes and are dismissed unless passed.\n//\n// sub is the DAO-scoped sub-identity that the host mints and passes into\n// the executor as its value-movement authority (see ExecFunc). The\n// executor is non-crossing, so it is called directly. Execute itself is\n// not a crossing function (sub sits in a non-first parameter slot)\n// because /p/ production code cannot declare crossing functions.\nfunc (dao *CommonDAO) Execute(proposalID uint64, sub realm) error {\n\tif dao.deleted {\n\t\treturn ErrDAOIsDeleted\n\t}\n\n\t// Re-entrancy latch: an executor must not re-enter Execute on this\n\t// DAO. Remove-before-run already stops the same proposal from running\n\t// twice; this additionally blocks an executor from executing a\n\t// different proposal of the same DAO mid-execution.\n\tif dao.executing {\n\t\tpanic(\"commondao: re-entrant Execute is not allowed\")\n\t}\n\tdao.executing = true\n\tdefer func() { dao.executing = false }()\n\n\tp := dao.activeProposals.Get(proposalID)\n\tif p == nil {\n\t\treturn ErrProposalNotFound\n\t}\n\n\tswitch p.status {\n\tcase StatusPassed:\n\t\t// Decided early: execute now, before the voting deadline\n\tcase StatusActive:\n\t\tif !p.HasVotingDeadlinePassed() {\n\t\t\treturn ErrVotingDeadlineNotMet\n\t\t}\n\tdefault:\n\t\treturn ErrExecutionNotAllowed\n\t}\n\n\t// The proposal leaves active storage before any definition code\n\t// (Validate, the executor) runs, so a re-entrant Execute call\n\t// cannot run it twice.\n\tdao.activeProposals.Remove(p.id)\n\n\t// Tally proposals that are still active after their deadline;\n\t// undecided proposals are dismissed. Vote already decides settled\n\t// outcomes, so this re-tally only matters for definitions whose\n\t// Threshold is not constant.\n\tif p.status == StatusActive {\n\t\tif TallyDefault(p.record.Readonly(), p.Electorate(), p.definition.Threshold()) == OutcomePassed {\n\t\t\tp.status = StatusPassed\n\t\t} else {\n\t\t\tp.status = StatusDismissed\n\t\t\tdao.finishedProposals.Add(p)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// IMPORTANT, from this point on, any error is going to result\n\t// in a proposal failure and execute will succeed.\n\n\t// Validate the passed proposal before execution\n\terr := p.Validate()\n\n\t// Execute proposal only if it's executable\n\tif err == nil {\n\t\tif e, ok := p.Definition().(Executable); ok {\n\t\t\tif fn := e.Executor(); fn != nil {\n\t\t\t\terr = fn(0, sub)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Proposal fails if there is any error during validation and execution process\n\tif err != nil {\n\t\tp.status = StatusFailed\n\t\tp.statusReason = err.Error()\n\t} else {\n\t\tp.status = StatusExecuted\n\t\tp.statusReason = \"\"\n\t}\n\n\t// Whichever the outcome of the validation, tallying\n\t// and execution consider the proposal finished.\n\tdao.finishedProposals.Add(p)\n\treturn nil\n}\n\n// dismiss finishes a proposal as dismissed.\nfunc (dao *CommonDAO) dismiss(p *Proposal) {\n\tp.status = StatusDismissed\n\tdao.activeProposals.Remove(p.id)\n\tdao.finishedProposals.Add(p)\n}\n\n// Dissolve soft deletes the DAO after dismissing every in-flight proposal\n// (both still-active and passed-but-unexecuted ones). Dissolution is\n// terminal: a deleted DAO rejects proposals, votes and executions, so\n// nothing may remain pending.\nfunc (dao *CommonDAO) Dissolve(reason string) {\n\tvar pending []*Proposal\n\tdao.activeProposals.Iterate(0, dao.activeProposals.Size(), false, func(p *Proposal) bool {\n\t\tpending = append(pending, p)\n\t\treturn false\n\t})\n\n\tfor _, p := range pending {\n\t\tp.statusReason = reason\n\t\tdao.dismiss(p)\n\t}\n\tdao.deleted = true\n}\n"},{"name":"commondao_options.gno","body":"package commondao\n\n// Option configures the CommonDAO.\ntype Option func(*CommonDAO)\n\n// WithID assigns a unique identifier to the DAO.\nfunc WithID(id uint64) Option {\n\treturn func(dao *CommonDAO) {\n\t\tdao.id = id\n\t}\n}\n\n// WithName assigns a name to the DAO.\nfunc WithName(name string) Option {\n\treturn func(dao *CommonDAO) {\n\t\tdao.name = name\n\t}\n}\n\n// WithPurpose assigns a purpose to the DAO. Purpose and description\n// together form the DAO's Charter (docs/CONSTITUTION.md :1485).\nfunc WithPurpose(purpose string) Option {\n\treturn func(dao *CommonDAO) {\n\t\tdao.purpose = purpose\n\t}\n}\n\n// WithDescription assigns a description to the DAO.\nfunc WithDescription(description string) Option {\n\treturn func(dao *CommonDAO) {\n\t\tdao.description = description\n\t}\n}\n\n// WithAddress assigns a treasury address to the DAO. Hosting realms\n// derive it, typically as a realm sub-identity address\n// (chain.DerivePkgSubAddr) so each DAO owns a distinct account.\nfunc WithAddress(addr address) Option {\n\treturn func(dao *CommonDAO) {\n\t\tdao.addr = addr\n\t}\n}\n\n// WithParent assigns a parent DAO and registers the DAO as one of the\n// parent's children, keeping both sides of the tree wired in one step.\nfunc WithParent(p *CommonDAO) Option {\n\treturn func(dao *CommonDAO) {\n\t\tdao.parent = p\n\t\tif p != nil {\n\t\t\tp.children.Append(dao)\n\t\t}\n\t}\n}\n\n// WithCouncilMember assigns a council member to the DAO.\nfunc WithCouncilMember(addr address) Option {\n\treturn func(dao *CommonDAO) {\n\t\tdao.council.Add(addr)\n\t}\n}\n\n// WithProposalKind registers a proposal kind on the DAO.\n// It panics when the kind is nil, has an empty name, or its name is\n// already registered.\n//\n// The package ships one concrete kind, ExecutionKind; seed it with\n// WithProposalKind(ExecutionKind{}).\nfunc WithProposalKind(k ProposalKind) Option {\n\treturn func(dao *CommonDAO) {\n\t\tif err := dao.RegisterKind(k); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package commondao provides governance primitives following the Common\n// DAO Spec (docs/CONSTITUTION.md, Appendix): a CommonDAO is a Council (a\n// set of addresses with equal voting power), a proposal lifecycle decided\n// by the constitution's default voting rules, and an optional sub-DAO\n// tree.\n//\n// Proposal types are registered per DAO: a ProposalKind couples a\n// registry name with a definition factory New(dao ReadonlyCommonDAO,\n// args), and Propose(creator, kind, args) accepts exactly the kinds\n// registered on the DAO. New receives only a readonly view, so it cannot\n// mutate the DAO before the vote; a kind that must mutate state on\n// execution captures its target *CommonDAO from args (populated only by\n// trusted callers) and mutates in its executor. RegisterKind /\n// DeregisterKind / HasKind / KindNames and the WithProposalKind option\n// are the registry primitives; the package ships one concrete kind,\n// ExecutionKind (arbitrary execution), and no governance meta-kinds —\n// managing a DAO's kind set through governance is the consuming realm's\n// job.\n//\n// Proposals snapshot the council as their electorate at creation and\n// are decided the moment the outcome is mathematically settled: with\n// integer math over D = |electorate| - abstains, a supermajority\n// (3*yes \u003e= 2*D) passes, a NO majority (2*no \u003e D) dismisses, and\n// proposals still undecided at their voting deadline are dismissed.\n//\n// A DAO may carry a treasury address and frozen flag; the package only\n// stores them - hosting realms derive the address and move the funds.\n//\n// A *CommonDAO is a mutable handle for the realm that owns it: never\n// accept one from, or return one to, an untrusted realm - readonly views\n// (CommonDAO.Readonly) are the only safe handles to cross a realm\n// boundary. See the package README for details.\n//\n// # Extending commondao in your own realm\n//\n// This package is mostly mechanism: it ships the ExecutionKind concrete kind\n// (with a default voting policy) and the registry primitives, and leaves the\n// rest of governance policy — which kinds a DAO accepts, how it manages them,\n// and any per-kind constraints such as a treasury freeze — to the consuming\n// realm. To add a proposal type of your own:\n//\n//   - Author a ProposalKind: a type with Name() string and\n//     New(dao ReadonlyCommonDAO, args any) (ProposalDefinition, error). Make\n//     the definition Executable (Executor() returns an ExecFunc) if it\n//     mutates state on approval. If its executor moves funds from a DAO other\n//     than the proposal's host, have the HOST realm consume a Funded-style\n//     contract (FundingDAOID() uint64) — minting a DAO sub needs the host's\n//     cur, so this contract is host-consumed, not package-dispatched; define\n//     it in your realm, as the reference realm does.\n//   - Apply your own policy. ExecutionKind runs the closure as-is (no check\n//     beyond a non-nil Fn), so if your realm has treasury constraints (e.g. a\n//     freeze flag) do NOT catalog ExecutionKind directly: author your own\n//     execution kind whose definition wraps the closure with a Validable\n//     check (Validate() error) enforcing those constraints, so arbitrary\n//     execution cannot bypass them. The reference realm does this so a frozen\n//     DAO cannot drain its own treasury through an execution proposal.\n//   - Seed it. The owning realm holds the DAO handle, so no proposal is\n//     needed: pass commondao.New(WithProposalKind(YourKind{}), …) at\n//     construction, or call dao.RegisterKind(YourKind{}) directly.\n//   - Author a typed, CLI-friendly wrapper\n//     CreateYourProposal(cur realm, daoID uint64, …params…): council-gate the\n//     caller, build the args struct, and call Propose. This is the only\n//     public entry, so the args-capture trust boundary holds.\n//   - Optionally add a runtime governance toggle. If the council should\n//     register/deregister kinds by vote (rather than only at construction),\n//     author a manage-kinds-style ProposalKind whose executor calls\n//     RegisterKind/DeregisterKind, and keep that managing kind itself\n//     un-deregisterable so the DAO can always recover.\n//\n// Trust boundary: New receives only a ReadonlyCommonDAO, so a kind — even an\n// externally authored one — cannot mutate the host at Propose time. The\n// mutable *CommonDAO reaches a definition only through args, which your\n// trusted wrapper populates (an external proposer cannot obtain one). On\n// execution the host passes the DAO's terminal, RealmSend-only sub, so a\n// fund-moving executor is bounded to that one DAO address. See the reference\n// realm gno.land/r/nt/commondao/v0 for a full worked example.\npackage commondao\n"},{"name":"execution_kind.gno","body":"package commondao\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n// executionKindName is the name of the arbitrary-execution kind.\nconst executionKindName = \"execution\"\n\nvar ErrExecutionFuncRequired = errors.New(\"execution proposal requires a non-nil Fn\")\n\n// defaultExecutionVotingPeriod is the voting period of execution proposals.\nconst defaultExecutionVotingPeriod = 7 * 24 * time.Hour\n\n// ExecutionArgs are the args for the execution kind (ExecutionKind): a\n// title, a body, and the ExecFunc to run on approval. The closure must be\n// authored in a persistent realm so it survives Propose→Execute; a\n// closure created by a `maketx run` script does not persist and cannot be\n// executed later.\ntype ExecutionArgs struct {\n\tTitle string\n\tBody  string\n\tFn    ExecFunc\n}\n\n// ExecutionKind is the package's one concrete proposal kind: a stateless,\n// reusable arbitrary-execution kind that runs an ExecFunc supplied by the\n// proposer on approval. It is /p/-typed so any realm can register it with\n// WithProposalKind(ExecutionKind{}) or RegisterKind without defining its\n// own execution kind.\n//\n// The executor moves value only through the DAO-scoped sub the host\n// passes (see ExecFunc): the host mints and passes that sub, so the\n// executor receives whichever DAO's sub the host decides (its own DAO's by\n// default). The closure is frozen at Propose (vote-integrity: the exact\n// code is fixed before the vote).\n//\n// This kind applies NO policy check to the closure beyond a non-nil Fn: it\n// runs the arbitrary code as-is. A realm that has treasury constraints (e.g.\n// a freeze flag) should NOT catalog this kind directly; instead it should\n// author its own execution kind whose definition wraps the closure with a\n// Validable check that enforces those constraints (blocking execution while\n// frozen, etc.), so arbitrary execution cannot bypass them. The reference\n// realm gno.land/r/nt/commondao/v0 does exactly this.\ntype ExecutionKind struct{}\n\n// Name returns the execution kind's registry name.\nfunc (ExecutionKind) Name() string { return executionKindName }\n\n// New validates ExecutionArgs and builds an execution definition. It is a\n// pure factory: it receives only a readonly view and captures no mutable\n// handle.\nfunc (ExecutionKind) New(_ ReadonlyCommonDAO, args any) (ProposalDefinition, error) {\n\ta, ok := args.(ExecutionArgs)\n\tif !ok || a.Fn == nil {\n\t\treturn nil, ErrExecutionFuncRequired\n\t}\n\treturn executionDef{title: a.Title, body: a.Body, fn: a.Fn}, nil\n}\n\n// executionDef is the definition produced by ExecutionKind.\ntype executionDef struct {\n\ttitle string\n\tbody  string\n\tfn    ExecFunc\n}\n\nfunc (d executionDef) Title() string             { return d.title }\nfunc (d executionDef) Body() string              { return d.body }\nfunc (executionDef) VotingPeriod() time.Duration { return defaultExecutionVotingPeriod }\nfunc (executionDef) Threshold() Threshold        { return ThresholdSupermajority }\nfunc (d executionDef) Executor() ExecFunc        { return d.fn }\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/commondao/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l\"\n"},{"name":"proposal.gno","body":"package commondao\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"gno.land/p/nt/addrset/v0\"\n)\n\nconst (\n\tStatusActive    ProposalStatus = \"active\"\n\tStatusPassed    ProposalStatus = \"passed\"\n\tStatusDismissed ProposalStatus = \"dismissed\"\n\tStatusExecuted  ProposalStatus = \"executed\"\n\tStatusFailed    ProposalStatus = \"failed\"\n\tStatusWithdrawn ProposalStatus = \"withdrawn\"\n)\n\n// Vote choices, fixed by the Common DAO Spec's default voting rules.\nconst (\n\tChoiceYes     VoteChoice = \"YES\"\n\tChoiceNo      VoteChoice = \"NO\"\n\tChoiceAbstain VoteChoice = \"ABSTAIN\"\n)\n\n// Thresholds for the constitution's default Council voting rules.\nconst (\n\t// ThresholdSupermajority passes with \"two thirds or more\" of the\n\t// tally denominator. The default for Council decisions.\n\tThresholdSupermajority Threshold = iota\n\n\t// ThresholdSimpleMajority passes with \"more than half\" of the\n\t// tally denominator. The Constitution assigns it to specific\n\t// decisions, e.g. sub-DAO creation.\n\tThresholdSimpleMajority\n)\n\n// Outcomes of tallying a proposal under the default Council rules.\nconst (\n\tOutcomePending Outcome = iota\n\tOutcomePassed\n\tOutcomeDismissed\n)\n\nvar (\n\tErrInvalidCreatorAddress      = errors.New(\"invalid proposal creator address\")\n\tErrInvalidVoterAddress        = errors.New(\"invalid voter address\")\n\tErrProposalDefinitionRequired = errors.New(\"proposal definition is required\")\n\tErrStatusIsNotActive          = errors.New(\"proposal status is not active\")\n)\n\ntype (\n\t// ProposalStatus defines a type for different proposal states.\n\tProposalStatus string\n\n\t// VoteChoice defines a type for proposal vote choices.\n\tVoteChoice string\n\n\t// Threshold defines a type for the default tally thresholds.\n\tThreshold int\n\n\t// Outcome defines a type for default tally outcomes.\n\tOutcome int\n\n\t// ExecFunc defines a type for functions that execute proposals.\n\t//\n\t// The leading int makes ExecFunc non-crossing: the host calls it\n\t// directly (no cross), so the executor holds no realm cur of its own —\n\t// only the realm argument, a DAO-scoped sub-identity the host mints and\n\t// passes. Fund-moving executors send through that sub (e.g. banker\n\t// RealmSend), which is terminal and bounded to one DAO address;\n\t// executors that move no funds ignore it. The int is unused.\n\t//\n\t// Authority note: the sub is a least-authority DEFAULT, not a sandbox.\n\t// An executor is trusted realm code; because the sub is the executor's\n\t// only current realm value, it could regain the host realm's primary\n\t// authority via an explicit cross(sub) into a crossing function. That is\n\t// a visible, auditable call the reference realm's executors never make,\n\t// so their blast radius is one treasury — but a realm that runs\n\t// untrusted or user-registered executors gets no such guarantee. See ADR\n\t// pr6012_commondao_exec_scope.\n\t//\n\t// The sharper hazard for such a realm is not cross(sub) but the banker:\n\t// an executor can mint banker.NewBanker(BankerTypeRealmSend, sub) and\n\t// simply RETAIN it. Authorization happens at construction only, and the\n\t// banker holds no realm reference, so it persists across transactions\n\t// even though the sub itself cannot — a permanent, unrevocable\n\t// capability over that DAO's address, spendable later with no proposal.\n\t// It also bypasses any check the host performs before spending (a\n\t// frozen flag, a pause switch), because it reaches the bank keeper\n\t// without re-entering host code. Passing the sub to an executor whose\n\t// code the DAO has not vetted is therefore an irrevocable grant of that\n\t// DAO's treasury, not a scoped loan of it.\n\tExecFunc func(int, realm) error\n\n\t// Proposal defines a DAO proposal.\n\tProposal struct {\n\t\tid             uint64\n\t\tstatus         ProposalStatus\n\t\tdefinition     ProposalDefinition\n\t\tcreator        address\n\t\trecord         *VotingRecord\n\t\telectorate     *addrset.Set // council snapshot taken at Propose\n\t\tstatusReason   string\n\t\tvotingDeadline time.Time\n\t\tcreatedAt      time.Time\n\t}\n\n\t// ProposalDefinition defines an interface for custom proposal definitions.\n\t// These definitions define proposal content and behavior, essentially\n\t// allowing the definition of different proposal types.\n\tProposalDefinition interface {\n\t\t// Title returns the proposal title.\n\t\tTitle() string\n\n\t\t// Body returns proposal's body.\n\t\t// It usually contains description or values that are specific to the proposal,\n\t\t// like a description of the proposal's motivation or the list of values that\n\t\t// would be applied when the proposal is approved.\n\t\tBody() string\n\n\t\t// VotingPeriod returns the period where votes are allowed after proposal creation.\n\t\t// It is used to calculate the voting deadline from the proposal's creation date.\n\t\tVotingPeriod() time.Duration\n\n\t\t// Threshold returns the tally threshold for passing the proposal.\n\t\t// Proposals are decided by the constitution's default Council voting\n\t\t// rules: re-evaluated after every recorded vote, they can pass or be\n\t\t// dismissed before their voting deadline.\n\t\t//\n\t\t// Threshold is read on every Vote (for early passage) AND again in\n\t\t// the post-deadline re-tally inside Execute. Return a CONSTANT value:\n\t\t// a threshold that loosens over a proposal's lifetime can let the\n\t\t// deadline re-tally pass with fewer YES votes than voters faced when\n\t\t// they cast under the stricter earlier value. A changing threshold is\n\t\t// honored, but the definition author owns that consequence.\n\t\tThreshold() Threshold\n\t}\n\n\t// ProposalKind defines an interface for proposal kinds: named factories\n\t// for proposal definitions, registered per DAO. A kind is both the\n\t// registry key (Name) and the factory (New) for one proposal type, and\n\t// a DAO accepts proposals of exactly the kinds registered on it\n\t// (CommonDAO.RegisterKind).\n\tProposalKind interface {\n\t\t// Name returns the kind name used as registry key, e.g. \"treasury-spend\".\n\t\tName() string\n\n\t\t// New validates args and builds the proposal definition. Propose\n\t\t// passes a ReadonlyCommonDAO view of the host DAO, so New is a\n\t\t// pure factory that cannot mutate the host or its tree before the\n\t\t// vote; proposal targets and parameters come via args. A kind that\n\t\t// must mutate state on execution receives the target *CommonDAO\n\t\t// through args (which only trusted callers can populate), captures\n\t\t// it, and mutates in its Executor. The returned definition's\n\t\t// instance data is frozen at Propose like any proposal definition.\n\t\tNew(dao ReadonlyCommonDAO, args any) (ProposalDefinition, error)\n\t}\n\n\t// CapExempt defines an interface for proposal definitions that are not\n\t// counted against the DAO's active proposals cap. Exempt definitions are\n\t// instead bounded to one active proposal per creator, so that proposals\n\t// which remove members (and therefore must never be blockable by a full\n\t// cap) stay bounded.\n\tCapExempt interface {\n\t\t// CapExempt marks the definition as exempt.\n\t\tCapExempt()\n\t}\n\n\t// Validable defines an interface for proposal definitions that require state validation.\n\t// Validation is done before execution and normally also during proposal rendering.\n\tValidable interface {\n\t\t// Validate validates that the proposal is valid for the current state.\n\t\tValidate() error\n\t}\n\n\t// Executable defines an interface for proposal definitions that modify state on approval.\n\t// Once proposals are executed they are archived and considered finished.\n\tExecutable interface {\n\t\t// Executor returns a function to execute the proposal.\n\t\tExecutor() ExecFunc\n\t}\n)\n\n// newProposal creates a new DAO proposal.\n//\n// The proposal is created with an empty electorate; Propose populates it\n// with the council snapshot.\nfunc newProposal(id uint64, creator address, d ProposalDefinition) (*Proposal, error) {\n\tif !creator.IsValid() {\n\t\treturn nil, ErrInvalidCreatorAddress\n\t}\n\n\tnow := time.Now()\n\treturn \u0026Proposal{\n\t\tid:             id,\n\t\tstatus:         StatusActive,\n\t\tdefinition:     d,\n\t\tcreator:        creator,\n\t\trecord:         \u0026VotingRecord{},\n\t\telectorate:     \u0026addrset.Set{},\n\t\tvotingDeadline: now.Add(d.VotingPeriod()),\n\t\tcreatedAt:      now,\n\t}, nil\n}\n\n// ID returns the unique proposal identifier.\nfunc (p Proposal) ID() uint64 {\n\treturn p.id\n}\n\n// Definition returns the proposal definition.\n// Proposal definitions define proposal content and behavior.\nfunc (p Proposal) Definition() ProposalDefinition {\n\treturn p.definition\n}\n\n// Status returns the current proposal status.\nfunc (p Proposal) Status() ProposalStatus {\n\treturn p.status\n}\n\n// Creator returns the address of the account that created the proposal.\nfunc (p Proposal) Creator() address {\n\treturn p.creator\n}\n\n// CreatedAt returns the time that proposal was created.\nfunc (p Proposal) CreatedAt() time.Time {\n\treturn p.createdAt\n}\n\n// VotingRecord returns a read only record with the votes submitted for\n// the proposal. Votes are recorded through CommonDAO.Vote only.\nfunc (p Proposal) VotingRecord() ReadonlyVotingRecord {\n\treturn p.record.Readonly()\n}\n\n// Electorate returns the proposal's electorate: a read only view of the\n// council snapshot taken when the proposal was created. Members added to\n// the council afterwards vote on the next proposal; members removed or\n// resigned afterwards remain in the electorate (their silence counts\n// against passage).\nfunc (p Proposal) Electorate() *addrset.ReadonlySet {\n\treturn p.electorate.Readonly()\n}\n\n// StatusReason returns an optional reason that led to the current proposal status.\n// Reason is mostly useful when a proposal fails.\nfunc (p Proposal) StatusReason() string {\n\treturn p.statusReason\n}\n\n// VotingDeadline returns the deadline after which no more votes should be allowed.\nfunc (p Proposal) VotingDeadline() time.Time {\n\treturn p.votingDeadline\n}\n\n// HasVotingDeadlinePassed checks if the voting deadline has been met.\nfunc (p Proposal) HasVotingDeadlinePassed() bool {\n\treturn !time.Now().Before(p.VotingDeadline())\n}\n\n// Validate validates that a proposal is valid for the current state.\n// Validation is done when the proposal can still be executed (status is\n// active or passed) and when the definition supports validation.\nfunc (p Proposal) Validate() error {\n\tif p.status != StatusActive \u0026\u0026 p.status != StatusPassed {\n\t\treturn nil\n\t}\n\n\tif v, ok := p.definition.(Validable); ok {\n\t\treturn v.Validate()\n\t}\n\treturn nil\n}\n\n// ExpectedOutcome returns the outcome the proposal would have if it were\n// decided with the votes submitted so far. Useful for rendering.\nfunc (p Proposal) ExpectedOutcome() Outcome {\n\treturn TallyDefault(p.record.Readonly(), p.Electorate(), p.definition.Threshold())\n}\n"},{"name":"proposal_storage.gno","body":"package commondao\n\nimport (\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\n// newProposalStorage creates a new proposal storage.\nfunc newProposalStorage() *proposalStorage {\n\treturn \u0026proposalStorage{bptree.NewBPTree32()}\n}\n\n// proposalStorage stores proposals indexed by ID.\ntype proposalStorage struct {\n\tstorage *bptree.BPTree // string(proposal ID) -\u003e *Proposal\n}\n\n// Get returns a proposal or nil when proposal doesn't exist.\nfunc (s proposalStorage) Get(id uint64) *Proposal {\n\tif v := s.storage.Get(makeProposalKey(id)); v != nil {\n\t\treturn v.(*Proposal)\n\t}\n\treturn nil\n}\n\n// Add adds a proposal to the storage.\nfunc (s *proposalStorage) Add(p *Proposal) {\n\tif p == nil {\n\t\treturn\n\t}\n\n\ts.storage.Set(makeProposalKey(p.ID()), p)\n}\n\n// Remove removes a proposal from the storage.\nfunc (s *proposalStorage) Remove(id uint64) {\n\ts.storage.Remove(makeProposalKey(id))\n}\n\n// Size returns the number of proposals that the storage contains.\nfunc (s proposalStorage) Size() int {\n\treturn s.storage.Size()\n}\n\n// Iterate iterates proposals.\nfunc (s proposalStorage) Iterate(offset, count int, reverse bool, fn func(*Proposal) bool) bool {\n\tcb := func(_ string, v any) bool { return fn(v.(*Proposal)) }\n\n\tif reverse {\n\t\treturn s.storage.ReverseIterateByOffset(offset, count, cb)\n\t}\n\treturn s.storage.IterateByOffset(offset, count, cb)\n}\n\nfunc makeProposalKey(id uint64) string {\n\treturn seqid.ID(id).String()\n}\n"},{"name":"readonly.gno","body":"package commondao\n\nimport (\n\t\"time\"\n\n\t\"gno.land/p/nt/addrset/v0\"\n)\n\n// ReadonlyCommonDAO is a read only view of a CommonDAO. It exposes only\n// read side methods, holds the *CommonDAO in an unexported field, and every\n// reachable value is itself readonly or a copy — so cross-realm holders\n// cannot mutate the DAO through it. Views are live handles, not snapshots.\n//\n// This is the only safe handle to a DAO across a realm boundary: hosting\n// realms must never return the *CommonDAO itself.\ntype ReadonlyCommonDAO struct {\n\tdao *CommonDAO\n}\n\n// Readonly returns a read only view of the DAO.\nfunc (dao *CommonDAO) Readonly() ReadonlyCommonDAO {\n\treturn ReadonlyCommonDAO{dao}\n}\n\n// ID returns DAO's unique identifier.\nfunc (r ReadonlyCommonDAO) ID() uint64 {\n\treturn r.dao.id\n}\n\n// Name returns DAO's name.\nfunc (r ReadonlyCommonDAO) Name() string {\n\treturn r.dao.name\n}\n\n// Purpose returns DAO's purpose (part of the Charter).\nfunc (r ReadonlyCommonDAO) Purpose() string {\n\treturn r.dao.purpose\n}\n\n// Description returns DAO's description.\nfunc (r ReadonlyCommonDAO) Description() string {\n\treturn r.dao.description\n}\n\n// Address returns the DAO's treasury address, or empty when unset.\nfunc (r ReadonlyCommonDAO) Address() address {\n\treturn r.dao.addr\n}\n\n// IsDeleted returns true when DAO has been soft deleted.\nfunc (r ReadonlyCommonDAO) IsDeleted() bool {\n\treturn r.dao.deleted\n}\n\n// IsTreasuryFrozen checks if the DAO's treasury is frozen.\nfunc (r ReadonlyCommonDAO) IsTreasuryFrozen() bool {\n\treturn r.dao.treasuryFrozen\n}\n\n// Council returns a read only view of the DAO council.\nfunc (r ReadonlyCommonDAO) Council() *addrset.ReadonlySet {\n\treturn r.dao.council.Readonly()\n}\n\n// HasKind checks if a proposal kind is registered on the DAO.\nfunc (r ReadonlyCommonDAO) HasKind(name string) bool {\n\treturn r.dao.HasKind(name)\n}\n\n// KindNames returns the names of the registered proposal kinds, sorted.\nfunc (r ReadonlyCommonDAO) KindNames() []string {\n\treturn r.dao.KindNames()\n}\n\n// Parent returns a read only view of the parent DAO when there is one.\nfunc (r ReadonlyCommonDAO) Parent() (_ ReadonlyCommonDAO, found bool) {\n\tif r.dao.parent == nil {\n\t\treturn ReadonlyCommonDAO{}, false\n\t}\n\treturn r.dao.parent.Readonly(), true\n}\n\n// ChildrenCount returns the number of direct children DAOs.\nfunc (r ReadonlyCommonDAO) ChildrenCount() int {\n\treturn r.dao.children.Len()\n}\n\n// IterateChildren iterates the direct children DAOs.\n// The callback can return true to stop iteration.\nfunc (r ReadonlyCommonDAO) IterateChildren(fn func(ReadonlyCommonDAO) bool) (stopped bool) {\n\tr.dao.children.ForEach(func(_ int, v any) bool {\n\t\tstopped = fn(v.(*CommonDAO).Readonly())\n\t\treturn stopped\n\t})\n\treturn stopped\n}\n\n// GetProposal returns a read only view of a proposal when it exists.\nfunc (r ReadonlyCommonDAO) GetProposal(proposalID uint64) (_ ReadonlyProposal, found bool) {\n\tp := r.dao.GetProposal(proposalID)\n\tif p == nil {\n\t\treturn ReadonlyProposal{}, false\n\t}\n\treturn p.Readonly(), true\n}\n\n// ActiveProposalsSize returns the number of active proposals.\nfunc (r ReadonlyCommonDAO) ActiveProposalsSize() int {\n\treturn r.dao.activeProposals.Size()\n}\n\n// FinishedProposalsSize returns the number of finished proposals.\nfunc (r ReadonlyCommonDAO) FinishedProposalsSize() int {\n\treturn r.dao.finishedProposals.Size()\n}\n\n// IterateActiveProposals iterates read only views of the active proposals.\n// The callback can return true to stop iteration.\nfunc (r ReadonlyCommonDAO) IterateActiveProposals(offset, count int, reverse bool, fn func(ReadonlyProposal) bool) bool {\n\treturn r.dao.activeProposals.Iterate(offset, count, reverse, func(p *Proposal) bool {\n\t\treturn fn(p.Readonly())\n\t})\n}\n\n// IterateFinishedProposals iterates read only views of the finished proposals.\n// The callback can return true to stop iteration.\nfunc (r ReadonlyCommonDAO) IterateFinishedProposals(offset, count int, reverse bool, fn func(ReadonlyProposal) bool) bool {\n\treturn r.dao.finishedProposals.Iterate(offset, count, reverse, func(p *Proposal) bool {\n\t\treturn fn(p.Readonly())\n\t})\n}\n\n// ReadonlyProposal is a read only view of a Proposal. Proposal content is\n// exposed flattened (Title, Body): the view never exposes the underlying\n// ProposalDefinition, whose Executor would otherwise be callable by any\n// holder with the hosting realm's authority.\ntype ReadonlyProposal struct {\n\tp *Proposal\n}\n\n// Readonly returns a read only view of the proposal.\nfunc (p *Proposal) Readonly() ReadonlyProposal {\n\treturn ReadonlyProposal{p}\n}\n\n// ID returns the unique proposal identifier.\nfunc (r ReadonlyProposal) ID() uint64 {\n\treturn r.p.id\n}\n\n// Status returns the current proposal status.\nfunc (r ReadonlyProposal) Status() ProposalStatus {\n\treturn r.p.status\n}\n\n// StatusReason returns an optional reason that led to the current proposal status.\nfunc (r ReadonlyProposal) StatusReason() string {\n\treturn r.p.statusReason\n}\n\n// Creator returns the address of the account that created the proposal.\nfunc (r ReadonlyProposal) Creator() address {\n\treturn r.p.creator\n}\n\n// CreatedAt returns the time that proposal was created.\nfunc (r ReadonlyProposal) CreatedAt() time.Time {\n\treturn r.p.createdAt\n}\n\n// VotingDeadline returns the deadline after which no more votes are allowed.\nfunc (r ReadonlyProposal) VotingDeadline() time.Time {\n\treturn r.p.votingDeadline\n}\n\n// Title returns the proposal definition's title.\nfunc (r ReadonlyProposal) Title() string {\n\treturn r.p.definition.Title()\n}\n\n// Body returns the proposal definition's body.\nfunc (r ReadonlyProposal) Body() string {\n\treturn r.p.definition.Body()\n}\n\n// VotingRecord returns a read only record with the submitted votes.\nfunc (r ReadonlyProposal) VotingRecord() ReadonlyVotingRecord {\n\treturn r.p.record.Readonly()\n}\n\n// Electorate returns a read only view of the proposal's electorate.\nfunc (r ReadonlyProposal) Electorate() *addrset.ReadonlySet {\n\treturn r.p.Electorate()\n}\n"},{"name":"record.gno","body":"package commondao\n\nimport (\n\t\"gno.land/p/nt/addrset/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\ntype (\n\t// VoteIterFn defines a callback to iterate votes.\n\tVoteIterFn func(Vote) (stop bool)\n\n\t// VotesCountIterFn defines a callback to iterate voted choices.\n\tVotesCountIterFn func(_ VoteChoice, voteCount int) (stop bool)\n\n\t// Vote defines a single vote. Its fields are unexported so instances\n\t// cannot be forged or reshaped outside the package: votes enter a\n\t// record only through CommonDAO.Vote's gates.\n\tVote struct {\n\t\taddr   address\n\t\tchoice VoteChoice\n\t\treason string\n\t}\n)\n\n// NewVote creates a vote, validating the address and choice. It exists\n// so external code can build records to independently re-verify a tally\n// with TallyDefault; votes reach a DAO's own records only through\n// CommonDAO.Vote.\nfunc NewVote(addr address, choice VoteChoice, reason string) (Vote, error) {\n\tif !addr.IsValid() {\n\t\treturn Vote{}, ErrInvalidVoterAddress\n\t}\n\n\tif choice != ChoiceYes \u0026\u0026 choice != ChoiceNo \u0026\u0026 choice != ChoiceAbstain {\n\t\treturn Vote{}, ErrInvalidVoteChoice\n\t}\n\n\treturn Vote{addr: addr, choice: choice, reason: reason}, nil\n}\n\n// Address returns the address of the account that submitted the vote.\nfunc (v Vote) Address() address {\n\treturn v.addr\n}\n\n// Choice returns the voted choice.\nfunc (v Vote) Choice() VoteChoice {\n\treturn v.choice\n}\n\n// Reason returns the optional reason for the vote.\nfunc (v Vote) Reason() string {\n\treturn v.reason\n}\n\n// ReadonlyVotingRecord defines a read only voting record. The copy\n// captures the live record's tree roots by value, so a held value can go\n// stale in surprising ways: fetch it, read it, and re-fetch rather than\n// holding it across votes.\ntype ReadonlyVotingRecord struct {\n\tvotes bptree.BPTree // string(address) -\u003e Vote\n\tcount bptree.BPTree // string(choice) -\u003e int\n}\n\n// Size returns the total number of votes that record contains.\nfunc (r ReadonlyVotingRecord) Size() int {\n\treturn r.votes.Size()\n}\n\n// Iterate iterates voting record votes.\nfunc (r ReadonlyVotingRecord) Iterate(offset, count int, reverse bool, fn VoteIterFn) bool {\n\tcb := func(_ string, v any) bool { return fn(v.(Vote)) }\n\tif reverse {\n\t\treturn r.votes.ReverseIterateByOffset(offset, count, cb)\n\t}\n\treturn r.votes.IterateByOffset(offset, count, cb)\n}\n\n// IterateVotesCount iterates voted choices with the amount of votes submitted for each.\nfunc (r ReadonlyVotingRecord) IterateVotesCount(fn VotesCountIterFn) bool {\n\treturn r.count.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\treturn fn(VoteChoice(k), v.(int))\n\t})\n}\n\n// VoteCount returns the number of votes for a single voting choice.\nfunc (r ReadonlyVotingRecord) VoteCount(c VoteChoice) int {\n\tif v := r.count.Get(string(c)); v != nil {\n\t\treturn v.(int)\n\t}\n\treturn 0\n}\n\n// HasVoted checks if an account already voted.\nfunc (r ReadonlyVotingRecord) HasVoted(user address) bool {\n\treturn r.votes.Has(user.String())\n}\n\n// GetVote returns a vote.\nfunc (r ReadonlyVotingRecord) GetVote(user address) (_ Vote, found bool) {\n\tif v := r.votes.Get(user.String()); v != nil {\n\t\treturn v.(Vote), true\n\t}\n\treturn Vote{}, false\n}\n\n// VotingRecord stores accounts that voted and vote choices.\ntype VotingRecord struct {\n\tReadonlyVotingRecord\n}\n\n// Readonly returns a read only voting record.\nfunc (r VotingRecord) Readonly() ReadonlyVotingRecord {\n\treturn r.ReadonlyVotingRecord\n}\n\n// AddVote adds a vote to the voting record.\n// If a vote for the same user already exists is overwritten.\nfunc (r *VotingRecord) AddVote(vote Vote) (updated bool) {\n\t// Get previous member vote if it exists\n\tv := r.votes.Get(vote.addr.String())\n\n\t// When a previous vote exists update counter for the previous choice\n\tupdated = r.votes.Set(vote.addr.String(), vote)\n\tif updated {\n\t\tprev := v.(Vote)\n\t\tr.count.Set(string(prev.choice), r.VoteCount(prev.choice)-1)\n\t}\n\n\tr.count.Set(string(vote.choice), r.VoteCount(vote.choice)+1)\n\treturn\n}\n\n// TallyDefault applies the constitution's default Council voting rules\n// over a proposal's electorate.\n//\n// Only votes cast by electorate members are counted. The tally denominator\n// D is the electorate size minus the number of ABSTAIN votes: abstaining\n// shrinks the denominator (deference), while not voting counts against\n// passage (silence is opposition). With integer math:\n//\n//\tD = |electorate| - abstains\n//\tsupermajority:   passed    ⇔ D \u003e 0 \u0026\u0026 3*yes \u003e= 2*D\n//\tsimple majority: passed    ⇔ D \u003e 0 \u0026\u0026 2*yes \u003e D\n//\tboth:            dismissed ⇔ 2*no \u003e D\n//\n// Passing is checked before dismissal; within one electorate both can never\n// hold at once (yes+no \u003c= D makes each pair contradictory). When D is zero\n// or negative (an empty electorate, or every member abstained) the outcome\n// stays pending: nothing can pass with zero YES votes.\nfunc TallyDefault(r ReadonlyVotingRecord, electorate *addrset.ReadonlySet, t Threshold) Outcome {\n\tvar yes, no, abstain int\n\tr.Iterate(0, r.Size(), false, func(v Vote) bool {\n\t\tif !electorate.Has(v.addr) {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch v.choice {\n\t\tcase ChoiceYes:\n\t\t\tyes++\n\t\tcase ChoiceNo:\n\t\t\tno++\n\t\tcase ChoiceAbstain:\n\t\t\tabstain++\n\t\t}\n\t\treturn false\n\t})\n\n\td := electorate.Size() - abstain\n\tif d \u003c= 0 {\n\t\treturn OutcomePending\n\t}\n\n\tswitch t {\n\tcase ThresholdSimpleMajority:\n\t\tif 2*yes \u003e d {\n\t\t\treturn OutcomePassed\n\t\t}\n\tdefault:\n\t\tif 3*yes \u003e= 2*d {\n\t\t\treturn OutcomePassed\n\t\t}\n\t}\n\n\tif 2*no \u003e d {\n\t\treturn OutcomeDismissed\n\t}\n\treturn OutcomePending\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"commondao","path":"gno.land/r/nt/commondao/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this realm that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# commondao (realm)\n\nReference realm implementation of the `gno.land/p/nt/commondao/v0` package for\nmanaging Decentralized Autonomous Organizations per the Common DAO Spec\n(`docs/CONSTITUTION.md`, Appendix).\n\nWhat it hosts:\n\n- **DAOs and sub-DAO trees** with a Charter (purpose + description), a\n  council, and per-DAO treasury addresses derived as realm sub-identities\n  (`cur.Sub(\"dao/\u003cid\u003e\")`).\n- **Proposals** through a per-DAO registry of proposal kinds. Ten default\n  kinds are seeded at creation (text, council updates, sub-DAO creation,\n  dissolution, treasury spend/clawback/freeze, manage-kinds, amend-bylaws);\n  the arbitrary-execution kind is opt-in by governance. The kind set itself\n  is governable (`manage-kinds`), and manage-kinds can never be deregistered.\n- **Treasuries**: spends from a DAO's own sub-identity; ancestor clawback and\n  freeze; dissolution sweeps. Freeze blocks every self-initiated movement,\n  including arbitrary execution.\n- **Bylaws \u0026 Mandates** as named plaintext documents amended by verifiable\n  diff patches (`gno.land/p/nt/bylaws/v0`); the `mandates/` folder is\n  reserved for the (deferred) ancestor amendment power.\n- **Render** pages for DAOs, settings, bylaws, proposals and votes.\n\nDesign records live in `gno.land/adr/pr6012_commondao_*.md`; the extension\nguide for building your own realm on the `/p/` package is in\n`gno.land/p/nt/commondao/v0`'s README.\n"},{"name":"commondao.gno","body":"package commondao\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\n// pkgPath is this realm's package path, fixed regardless of quarantine\n// location. DAO treasury addresses derive from it, so they are stable\n// across a SAME-PATH redeploy. Moving to a different package path (e.g.\n// .../v1) changes cur.Sub derivation and would strand existing treasuries\n// unless a drain executor ran first (see gnovm/adr/pr5890_realm_sub.md\n// §Cross-host identity); this realm ships no such migration executor.\nconst pkgPath = \"gno.land/r/nt/commondao/v0\"\n\n// CommonDAOID is the ID of the realm's DAO.\nconst CommonDAOID uint64 = 1\n\nvar (\n\tdaoID     seqid.ID\n\trealmLink = txlink.Realm(pkgPath)\n\tdaos      = bptree.NewBPTree32() // string(ID) -\u003e *commondao.CommonDAO\n\tinvites   = bptree.NewBPTree32() // string(address) -\u003e address(inviter)\n\tcreators  = bptree.NewBPTree32() // string(address) -\u003e struct{}; consumed-invite marker\n\tlisted    = bptree.NewBPTree32() // string(ID) -\u003e uint64(ID); home-index opt-in\n)\n\nfunc getDAO(daoID uint64) *commondao.CommonDAO {\n\tkey := makeIDKey(daoID)\n\tif v := daos.Get(key); v != nil {\n\t\treturn v.(*commondao.CommonDAO)\n\t}\n\treturn nil\n}\n\nfunc mustGetDAO(daoID uint64) *commondao.CommonDAO {\n\tdao := getDAO(daoID)\n\tif dao == nil {\n\t\tpanic(\"DAO not found\")\n\t}\n\treturn dao\n}\n\nfunc makeIDKey(daoID uint64) string {\n\treturn seqid.ID(daoID).String()\n}\n\n// isCreator reports whether an address has already consumed an invite and\n// may create further DAOs without another one.\nfunc isCreator(addr address) bool {\n\treturn creators.Has(addr.String())\n}\n\n// isListed reports whether a DAO opted into the realm's public home index.\nfunc isListed(daoID uint64) bool {\n\treturn listed.Has(makeIDKey(daoID))\n}\n\n// setListed adds or removes a DAO from the realm's public home index.\nfunc setListed(daoID uint64, v bool) {\n\tkey := makeIDKey(daoID)\n\tif v {\n\t\t// Store the ID as the value so renderHome can paginate over the\n\t\t// listed set directly (keys are cford32-encoded, order-preserving).\n\t\tlisted.Set(key, daoID)\n\t} else {\n\t\tlisted.Remove(key)\n\t}\n}\n\n// subpathOf returns the realm sub-identity subpath that acts for a DAO.\nfunc subpathOf(daoID uint64) string {\n\treturn \"dao/\" + strconv.FormatUint(daoID, 10)\n}\n\n// daoAddress derives a DAO's treasury address: the address of the realm\n// sub-identity cur.Sub(subpathOf(daoID)) that executors mint to move its\n// funds. Pure derivation; DAO IDs are never reused, so the address is\n// collision free and stable.\nfunc daoAddress(daoID uint64) address {\n\treturn chain.DerivePkgSubAddr(pkgPath, subpathOf(daoID))\n}\n\nfunc createDAO(name, purpose, description string, members ...address) *commondao.CommonDAO {\n\tif len(members) == 0 {\n\t\tpanic(\"a DAO requires at least one initial council member\")\n\t}\n\n\tid := daoID.Next()\n\tdao := commondao.New(newDAOOptions(uint64(id), name, purpose, description, nil, members)...)\n\tdaos.Set(id.String(), dao)\n\treturn dao\n}\n\nfunc createSubDAO(parent *commondao.CommonDAO, name, purpose, description string, members ...address) *commondao.CommonDAO {\n\tif len(members) == 0 {\n\t\tpanic(\"a SubDAO requires at least one initial council member\")\n\t}\n\n\t// WithParent also registers the new DAO as one of parent's children\n\tid := daoID.Next()\n\tdao := commondao.New(newDAOOptions(uint64(id), name, purpose, description, parent, members)...)\n\tdaos.Set(id.String(), dao)\n\treturn dao\n}\n\nfunc newDAOOptions(id uint64, name, purpose, description string, parent *commondao.CommonDAO, members []address) []commondao.Option {\n\topts := []commondao.Option{\n\t\tcommondao.WithID(id),\n\t\tcommondao.WithName(name),\n\t\tcommondao.WithPurpose(purpose),\n\t\tcommondao.WithDescription(description),\n\t\tcommondao.WithAddress(daoAddress(id)),\n\t}\n\tif parent != nil {\n\t\topts = append(opts, commondao.WithParent(parent))\n\t}\n\tfor _, m := range members {\n\t\topts = append(opts, commondao.WithCouncilMember(m))\n\t}\n\n\t// Seed the default proposal kinds: every new DAO (genesis, user-created\n\t// or sub-DAO) starts with these registered. The opt-in catalog kind\n\t// (execution) is deliberately NOT seeded — a DAO gains it only after a\n\t// supermajority CreateRegisterKindProposal.\n\tfor _, k := range defaultProposalKinds {\n\t\topts = append(opts, commondao.WithProposalKind(k))\n\t}\n\treturn opts\n}\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package commondao provides a reference realm implementation of the\n// gno.land/p/nt/commondao/v0 package for managing Decentralized Autonomous\n// Organizations per the Common DAO Spec: DAO and sub-DAO trees with\n// councils and charters, a governable registry of proposal kinds (ten\n// defaults plus an opt-in arbitrary-execution kind), per-DAO treasuries on\n// derived sub-identity addresses with ancestor clawback/freeze powers, and\n// bylaws documents amended by verifiable diff patches. See README.md and\n// the ADRs under gno.land/adr/ for the design record.\npackage commondao\n"},{"name":"genesis.gno","body":"package commondao\n\nfunc init() {\n\t// Fail closed if deployed off the package path treasury addresses\n\t// derive from (see assertRunningPath).\n\tassertRunningPath()\n\n\t// Create the realm's own DAO, governed by its maintainers. There is no\n\t// owner: the realm administers nothing about a DAO except its home-index\n\t// listing, which the realm DAO sets for itself here.\n\tdao := createDAO(\n\t\t\"Common DAO\",\n\t\t\"Govern and maintain the commondao reference realm.\",\n\t\t\"This DAO is responsible for managing `commondao` realm functionalities.\",\n\t\t\"g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx\", // govdao t1 multisig\n\t\t\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\", // @moul\n\t)\n\tsetListed(dao.ID(), true)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/nt/commondao/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l\"\n"},{"name":"proposal_bylaws.gno","body":"package commondao\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/bylaws/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// bylawsSets stores each DAO's governing documents (bylaws and\n// mandates), keyed like daos. A set is created lazily on a DAO's first\n// amendment proposal; a DAO with no documents has no entry. The\n// *bylaws.Bylaws handle is mutable (Apply amends it), so it never leaves\n// the realm — public reads return strings.\nvar bylawsSets = bptree.NewBPTree32() // string(ID) -\u003e *bylaws.Bylaws\n\n// bylawsView returns a DAO's document set or nil when it has none. Read\n// paths (render, public getters, payload building) use this — it never\n// writes realm state, so it is safe under read-only query evaluation.\nfunc bylawsView(daoID uint64) *bylaws.Bylaws {\n\tif v := bylawsSets.Get(makeIDKey(daoID)); v != nil {\n\t\treturn v.(*bylaws.Bylaws)\n\t}\n\treturn nil\n}\n\n// bylawsOf returns a DAO's document set, creating an empty one on first\n// use. Only proposal creation calls it; an empty set left behind by a\n// failed proposal is harmless.\nfunc bylawsOf(daoID uint64) *bylaws.Bylaws {\n\tif b := bylawsView(daoID); b != nil {\n\t\treturn b\n\t}\n\tb := bylaws.New()\n\tbylawsSets.Set(makeIDKey(daoID), b)\n\treturn b\n}\n\n// isMandatesPath reports whether a document path is in the reserved\n// mandates/ folder (or is the bare \"mandates\" file). Mandates are not\n// council-self-amendable; see amendBylawsKind.New.\nfunc isMandatesPath(path string) bool {\n\treturn path == \"mandates\" || strings.HasPrefix(path, \"mandates/\")\n}\n\n// amendBylawsProposal is both the amend-bylaws args struct and the\n// proposal definition it produces (one type serves both roles, like\n// manageKindsProposal). set is the host DAO's document set the executor\n// patches: New receives only a readonly view, so the trusted wrapper\n// passes the mutable set through args (from its own bylawsOf) together\n// with the host daoID for the identity pin. display is the human-readable\n// change, rendered at New against the then-current document.\ntype amendBylawsProposal struct {\n\tdaoID   uint64\n\tset     *bylaws.Bylaws\n\tpatch   bylaws.Patch\n\tdisplay string\n}\n\n// amendBylawsKind creates proposals that add, amend or remove one of the\n// host DAO's bylaws/mandates documents with a verifiable diff patch. The\n// patch pins the sha256 of the document text it was diffed against, so a\n// passed amendment that raced a concurrent change to the same document\n// fails cleanly (StatusFailed) instead of clobbering it. Decided by\n// supermajority: this is the council amending its OWN governing\n// documents, which the Constitution grants with no special threshold, so\n// the default council rule applies. (The Constitution's simple-majority\n// clause for charter/bylaws/mandate changes is an ANCESTOR power — a\n// parent amending a descendant's documents — which this realm does not\n// implement yet.)\ntype amendBylawsKind struct{}\n\nfunc (amendBylawsKind) Name() string { return kindAmendBylaws }\n\nfunc (amendBylawsKind) New(dao commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\tp, ok := args.(amendBylawsProposal)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\t// Defense in depth: pin the proposal to the readonly host Propose\n\t// passed here AND pin the args-captured document set to that host's\n\t// canonical set, so a future wrapper can never validate against one\n\t// DAO's documents and amend another's (the trusted wrapper always\n\t// passes matching handles today).\n\tif p.daoID != dao.ID() || p.set == nil || p.set != bylawsView(p.daoID) {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\tif !bylaws.IsValidPath(p.patch.Path) {\n\t\treturn nil, bylaws.ErrInvalidPath\n\t}\n\t// The Constitution grants a council self-power over its BYLAWS only;\n\t// Mandates are changed from above (creation or an ancestor's Simple\n\t// Majority — the ancestor amendment path, not implemented yet). Reserve\n\t// the mandates/ folder so self-amendment cannot author what only an\n\t// ancestor may.\n\tif isMandatesPath(p.patch.Path) {\n\t\treturn nil, errors.New(\"mandates are not council-amendable: they are set at creation or by an ancestor (ancestor amendment is not implemented yet)\")\n\t}\n\n\t// Freshness fail-fast: reject a patch that is already stale at\n\t// creation (Validate re-checks at execution).\n\tcur, exists := p.set.Get(p.patch.Path)\n\tcurHash := \"\"\n\tif exists {\n\t\tcurHash = bylaws.HashText(cur)\n\t}\n\tif p.patch.Base != curHash {\n\t\treturn nil, bylaws.ErrStalePatch\n\t}\n\n\t// Rendering the change also validates the edit script against the\n\t// current text, so a malformed patch never becomes a proposal; only\n\t// then reject the well-formed do-nothing shapes.\n\tdisplay, err := p.patch.Format(cur)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif p.patch.IsNoop() {\n\t\treturn nil, errors.New(\"bylaws amendment must change the document\")\n\t}\n\tp.display = display\n\treturn p, nil\n}\n\n// Title returns the proposal title as raw text: the renderer escapes\n// every definition title.\nfunc (p amendBylawsProposal) Title() string {\n\tverb := \"Amend\"\n\tswitch {\n\tcase p.patch.IsCreate():\n\t\tverb = \"Add\"\n\tcase p.patch.IsRemove():\n\t\tverb = \"Remove\"\n\t}\n\treturn verb + \" Bylaws Document: \" + p.patch.Path\n}\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown: the path\n// is escaped inline and the change summary is emitted as a fenced code\n// block.\nfunc (amendBylawsProposal) isTrustedMarkdownBody() {}\n\nfunc (p amendBylawsProposal) Body() string {\n\t// A code block, not sanitize.Block: the summary's \"+\" lines are the\n\t// proposer's inserted literal text, and Block deliberately preserves\n\t// inline formatting AND inline links — which would render a live\n\t// attacker-controlled link on the page councils read before voting\n\t// (the same reason renderProposal escapes untrusted bodies inline).\n\t// A fence keeps the diff's line structure, which an inline escape\n\t// would fold away, and neutralizes markup; md.CodeBlock widens the\n\t// fence to outscan any backticks in the content.\n\treturn md.Paragraph(md.Bold(\"Document:\")+\" \"+md.EscapeText(p.patch.Path)) +\n\t\tmd.CodeBlock(p.display)\n}\n\nfunc (amendBylawsProposal) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// Threshold returns the tally threshold: amending the DAO's own\n// governing documents is a council decision with no special\n// constitutional threshold, so the supermajority default applies (the\n// Constitution's simple-majority clause covers ancestor-initiated\n// amendment, not implemented here).\nfunc (amendBylawsProposal) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\n// Validate re-asserts patch freshness at execution (Validate reruns\n// inside Execute): a document amended after this proposal passed fails\n// it cleanly (StatusFailed) instead of clobbering the newer text.\nfunc (p amendBylawsProposal) Validate() error {\n\tif p.set.Hash(p.patch.Path) != p.patch.Base {\n\t\treturn bylaws.ErrStalePatch\n\t}\n\treturn nil\n}\n\nfunc (p amendBylawsProposal) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\n// execute applies the patch, returning any bylaws error unchanged so a\n// race between two passed amendments fails the later one cleanly\n// (StatusFailed) instead of panicking the transaction. It moves no\n// funds, so the definition is not Funded and ignores sub.\nfunc (p amendBylawsProposal) execute(_ int, _ realm) error {\n\treturn p.set.Apply(p.patch)\n}\n"},{"name":"proposal_council.gno","body":"package commondao\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// newCouncilUpdatePropDefinition creates a new proposal definition for\n// adding/removing council members.\nfunc newCouncilUpdatePropDefinition(dao *commondao.CommonDAO, add, remove []address) councilUpdatePropDefinition {\n\tif dao == nil {\n\t\tpanic(\"DAO is required\")\n\t}\n\n\tif len(add) == 0 \u0026\u0026 len(remove) == 0 {\n\t\tpanic(\"no council members were specified to be added or removed\")\n\t}\n\n\treturn councilUpdatePropDefinition{\n\t\tdao:      dao,\n\t\ttoAdd:    add,\n\t\ttoRemove: remove,\n\t}\n}\n\n// councilUpdatePropDefinition defines a proposal type for adding/removing\n// council members. Adds and removes apply as idempotent set operations, so\n// concurrently passed updates merge in execution order; an update whose\n// final set would empty a non-empty council fails at execution.\ntype councilUpdatePropDefinition struct {\n\tdao             *commondao.CommonDAO\n\ttoAdd, toRemove []address\n}\n\nfunc (councilUpdatePropDefinition) Title() string               { return \"Council Update\" }\nfunc (councilUpdatePropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown; the renderer\n// renders it verbatim (embedded addresses are formatted by md helpers).\nfunc (councilUpdatePropDefinition) isTrustedMarkdownBody() {}\n\n// CapExempt exempts council updates from the active proposals cap: a\n// council member who fills the cap must never be able to block their own\n// removal. Exempt proposals are bounded to one active one per creator.\nfunc (councilUpdatePropDefinition) CapExempt() {}\n\n// Threshold returns the tally threshold: council self-mutation requires a\n// supermajority.\nfunc (councilUpdatePropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\nfunc (p councilUpdatePropDefinition) Body() string {\n\tvar b strings.Builder\n\n\tif len(p.toAdd) \u003e 0 {\n\t\tb.WriteString(md.Paragraph(\n\t\t\tmd.Bold(\"Council Members to Add:\") + \"\\n\" + md.BulletList(addrStrings(p.toAdd)),\n\t\t))\n\t}\n\n\tif len(p.toRemove) \u003e 0 {\n\t\tb.WriteString(md.Paragraph(\n\t\t\tmd.Bold(\"Council Members to Remove:\") + \"\\n\" + md.BulletList(addrStrings(p.toRemove)),\n\t\t))\n\t}\n\n\treturn b.String()\n}\n\nfunc (p councilUpdatePropDefinition) Validate() error {\n\t// Membership is intentionally not validated: adds and removes are\n\t// idempotent, so updates passed concurrently merge cleanly instead of\n\t// failing on addresses that another update already added or removed.\n\tfor _, a := range p.toAdd {\n\t\tfor _, r := range p.toRemove {\n\t\t\tif a == r {\n\t\t\t\treturn errors.New(\"address is added and removed at once: \" + a.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (p councilUpdatePropDefinition) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\nfunc (p councilUpdatePropDefinition) execute(_ int, sub realm) error {\n\treturn p.dao.UpdateCouncil(p.toAdd, p.toRemove)\n}\n\n// newAncestorCouncilUpdatePropDefinition creates a proposal definition for\n// an ancestor DAO to modify a descendant's council membership\n// (docs/CONSTITUTION.md :1531-1532). It is hosted and voted in the\n// ancestor; ancestry is verified at proposal validation.\nfunc newAncestorCouncilUpdatePropDefinition(dao, target *commondao.CommonDAO, add, remove []address) ancestorCouncilUpdatePropDefinition {\n\tif dao == nil {\n\t\tpanic(\"DAO is required\")\n\t}\n\tif target == nil {\n\t\tpanic(\"target DAO is required\")\n\t}\n\tif len(add) == 0 \u0026\u0026 len(remove) == 0 {\n\t\tpanic(\"no council members were specified to be added or removed\")\n\t}\n\n\treturn ancestorCouncilUpdatePropDefinition{\n\t\tdao:      dao,\n\t\ttarget:   target,\n\t\ttoAdd:    add,\n\t\ttoRemove: remove,\n\t}\n}\n\n// ancestorCouncilUpdatePropDefinition defines a proposal type for an\n// ancestor DAO to add and/or remove members of a descendant's council.\n// This is the spec's rescue path for a stuck or empty descendant council\n// (:1531-1532): decided by the ancestor's own supermajority, validated as\n// strictly proper ancestry so a DAO can never mutate its own council\n// through this path (that is the self-mutating councilUpdate).\ntype ancestorCouncilUpdatePropDefinition struct {\n\tdao             *commondao.CommonDAO // proposing DAO, must be a proper ancestor\n\ttarget          *commondao.CommonDAO\n\ttoAdd, toRemove []address\n}\n\nfunc (ancestorCouncilUpdatePropDefinition) Title() string               { return \"Ancestor Council Update\" }\nfunc (ancestorCouncilUpdatePropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown.\nfunc (ancestorCouncilUpdatePropDefinition) isTrustedMarkdownBody() {}\n\n// Threshold returns the tally threshold: ancestor council modification\n// requires a supermajority (:1531-1532).\nfunc (ancestorCouncilUpdatePropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\nfunc (p ancestorCouncilUpdatePropDefinition) Body() string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.Paragraph(md.Bold(\"Target DAO:\") + \"\\n\" + daoMDLink(p.target)))\n\n\tif len(p.toAdd) \u003e 0 {\n\t\tb.WriteString(md.Paragraph(\n\t\t\tmd.Bold(\"Council Members to Add:\") + \"\\n\" + md.BulletList(addrStrings(p.toAdd)),\n\t\t))\n\t}\n\n\tif len(p.toRemove) \u003e 0 {\n\t\tb.WriteString(md.Paragraph(\n\t\t\tmd.Bold(\"Council Members to Remove:\") + \"\\n\" + md.BulletList(addrStrings(p.toRemove)),\n\t\t))\n\t}\n\n\treturn b.String()\n}\n\nfunc (p ancestorCouncilUpdatePropDefinition) Validate() error {\n\tif err := assertIsProperAncestor(p.dao, p.target); err != nil {\n\t\treturn err\n\t}\n\n\t// Same overlap check as the self-mutating update: adds and removes are\n\t// idempotent, so only a contradictory same-address add+remove is rejected.\n\tfor _, a := range p.toAdd {\n\t\tfor _, r := range p.toRemove {\n\t\t\tif a == r {\n\t\t\t\treturn errors.New(\"address is added and removed at once: \" + a.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (p ancestorCouncilUpdatePropDefinition) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\nfunc (p ancestorCouncilUpdatePropDefinition) execute(_ int, sub realm) error {\n\treturn p.target.UpdateCouncil(p.toAdd, p.toRemove)\n}\n\n// addrStrings converts addresses for markdown list rendering.\nfunc addrStrings(addrs []address) []string {\n\titems := make([]string, 0, len(addrs))\n\tfor _, a := range addrs {\n\t\titems = append(items, a.String())\n\t}\n\treturn items\n}\n"},{"name":"proposal_kinds.gno","body":"package commondao\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// Proposal kind names: the per-DAO registry keys for every proposal type\n// this realm can host. A DAO accepts proposals of exactly the kinds\n// registered on it. The default kinds are registered at DAO creation and\n// the kind set is managed afterwards through the manage-kinds kind\n// (CreateRegisterKindProposal / CreateDeregisterKindProposal).\nconst (\n\tkindText                  = \"text\"\n\tkindCouncilUpdate         = \"council-update\"\n\tkindAncestorCouncilUpdate = \"ancestor-council-update\"\n\tkindSubDAO                = \"subdao\"\n\tkindDissolve              = \"dissolve\"\n\tkindTreasurySpend         = \"treasury-spend\"\n\tkindTreasuryClawback      = \"treasury-clawback\"\n\tkindTreasuryFreeze        = \"treasury-freeze\"\n\tkindManageKinds           = \"manage-kinds\"\n\tkindAmendBylaws           = \"amend-bylaws\"\n\n\t// Opt-in kind. It is part of the catalog (so catalogKind resolves it and\n\t// manage-kinds can register it by name) but is NOT default-seeded: a DAO\n\t// gains it only after a supermajority register.\n\t//\n\t// It is a realm-side kind (executionKind), not the bare /p/\n\t// commondao.ExecutionKind: the realm wraps the arbitrary-exec closure with\n\t// its own Validable freeze policy so a frozen DAO cannot drain its own\n\t// treasury through an execution proposal (the /p/ kind carries no such\n\t// policy). The name still matches the /p/ kind's name.\n\tkindExecution = \"execution\"\n)\n\n// errInvalidProposalArgs reports a proposal kind invoked with the wrong\n// args type. Wrappers and kinds live in the same package, so this only\n// fires on a realm bug, never on user input.\nvar errInvalidProposalArgs = errors.New(\"invalid proposal arguments\")\n\n// defaultProposalKinds lists the proposal kinds seeded on every new DAO\n// (genesis, user-created or sub-DAO). Kinds are stateless singletons that\n// wrap the definition constructors. This is the DAO's starting governance\n// surface; the kind set is managed afterwards through the manage-kinds kind.\n// Ordering here is immaterial — render.gno owns the presentation order.\nvar defaultProposalKinds = []commondao.ProposalKind{\n\ttextKind{},\n\tcouncilUpdateKind{},\n\tancestorCouncilUpdateKind{},\n\tsubDAOKind{},\n\tdissolveKind{},\n\ttreasurySpendKind{},\n\ttreasuryClawbackKind{},\n\ttreasuryFreezeKind{},\n\tmanageKindsKind{},\n\tamendBylawsKind{},\n}\n\n// optInProposalKinds lists the opt-in proposal kinds: they are part of the\n// catalog but NOT default-seeded, so a DAO gains them only after a\n// supermajority manage-kinds register. The execution kind is realm-side\n// (executionKind), not the bare /p/ ExecutionKind, so it can carry the\n// realm's freeze policy (see kindExecution).\nvar optInProposalKinds = []commondao.ProposalKind{\n\texecutionKind{},\n}\n\n// proposalKindCatalog lists every proposal kind this realm can host: the\n// default-seeded kinds plus the opt-in kind (execution). catalogKind\n// resolves against this list, so manage-kinds can register an opt-in kind by\n// name that is not seeded. The executor set stays closed because only catalog\n// kinds are ever registered on a DAO by name. Ordering here is immaterial —\n// render.gno owns the presentation order.\nvar proposalKindCatalog = append(\n\tappend([]commondao.ProposalKind{}, defaultProposalKinds...),\n\toptInProposalKinds...,\n)\n\n// catalogKind returns a catalog kind by name, or nil when the name is not\n// part of the catalog.\nfunc catalogKind(name string) commondao.ProposalKind {\n\tfor _, k := range proposalKindCatalog {\n\t\tif k.Name() == name {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn nil\n}\n\n// HasProposalKind reports whether a proposal kind is registered on a DAO.\nfunc HasProposalKind(daoID uint64, name string) bool {\n\treturn mustGetDAO(daoID).HasKind(name)\n}\n\n// textArgs carries CreateTextProposal parameters to the text kind.\ntype textArgs struct {\n\ttitle        string\n\tbody         string\n\tvotingPeriod time.Duration\n}\n\n// textKind creates general text proposals.\ntype textKind struct{}\n\nfunc (textKind) Name() string { return kindText }\n\nfunc (textKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(textArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newTextPropDefinition(a.title, a.body, a.votingPeriod), nil\n}\n\n// councilUpdateArgs carries CreateCouncilUpdateProposal parameters to the\n// council-update kind. dao is the host DAO whose own council the executor\n// mutates: New receives only a readonly view, so the trusted wrapper passes\n// the mutable host handle through args (captured from its own mustGetDAO).\ntype councilUpdateArgs struct {\n\tdao    *commondao.CommonDAO\n\tadd    []address\n\tremove []address\n}\n\n// councilUpdateKind creates proposals that add and/or remove members of\n// the host DAO's own council.\ntype councilUpdateKind struct{}\n\nfunc (councilUpdateKind) Name() string { return kindCouncilUpdate }\n\nfunc (councilUpdateKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(councilUpdateArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newCouncilUpdatePropDefinition(a.dao, a.add, a.remove), nil\n}\n\n// ancestorCouncilUpdateArgs carries CreateAncestorCouncilUpdateProposal\n// parameters to the ancestor-council-update kind. host is the proposing\n// ancestor DAO (read for the ancestry check); target is the descendant\n// whose council the executor mutates. Both handles come from the trusted\n// wrapper via args, since New receives only a readonly view.\ntype ancestorCouncilUpdateArgs struct {\n\thost   *commondao.CommonDAO\n\ttarget *commondao.CommonDAO\n\tadd    []address\n\tremove []address\n}\n\n// ancestorCouncilUpdateKind creates proposals for the host DAO, as an\n// ancestor, to add and/or remove members of a descendant's council.\ntype ancestorCouncilUpdateKind struct{}\n\nfunc (ancestorCouncilUpdateKind) Name() string { return kindAncestorCouncilUpdate }\n\nfunc (ancestorCouncilUpdateKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(ancestorCouncilUpdateArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newAncestorCouncilUpdatePropDefinition(a.host, a.target, a.add, a.remove), nil\n}\n\n// subDAOArgs carries CreateSubDAOProposal parameters to the subdao kind.\n// parent is the host DAO the new SubDAO is created under; the executor\n// mutates it (wiring the child in), so the trusted wrapper passes the\n// mutable host handle through args, since New receives only a readonly view.\ntype subDAOArgs struct {\n\tparent      *commondao.CommonDAO\n\tname        string\n\tpurpose     string\n\tdescription string\n\tmembers     []address\n}\n\n// subDAOKind creates proposals that add a SubDAO under the host DAO.\ntype subDAOKind struct{}\n\nfunc (subDAOKind) Name() string { return kindSubDAO }\n\nfunc (subDAOKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(subDAOArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newSubDAOPropDefinition(a.parent, a.name, a.purpose, a.description, a.members), nil\n}\n\n// dissolveArgs carries CreateDissolutionProposal parameters to the\n// dissolve kind, including the DAO being dissolved: the proposal is hosted\n// in the nearest live ancestor (the host DAO that Propose passes to New),\n// so the definition must operate on the dissolved descendant carried here,\n// never on the host.\ntype dissolveArgs struct {\n\tdissolveDAO *commondao.CommonDAO\n\tdestination address // sweep destination, root DAOs only\n}\n\n// dissolveKind creates proposals that dissolve a DAO or SubDAO.\ntype dissolveKind struct{}\n\nfunc (dissolveKind) Name() string { return kindDissolve }\n\nfunc (dissolveKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(dissolveArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newDissolvePropDefinition(a.dissolveDAO, a.destination), nil\n}\n\n// treasurySpendArgs carries CreateTreasurySpendProposal parameters to the\n// treasury-spend kind. dao is the host DAO whose own treasury funds the\n// spend (its sub is the funding source, see FundingDAOID); the trusted\n// wrapper passes the mutable host handle through args, since New receives\n// only a readonly view.\ntype treasurySpendArgs struct {\n\tdao  *commondao.CommonDAO\n\tto   address\n\tcoin chain.Coin\n}\n\n// treasurySpendKind creates proposals that send coins from the host DAO's\n// own treasury.\ntype treasurySpendKind struct{}\n\nfunc (treasurySpendKind) Name() string { return kindTreasurySpend }\n\nfunc (treasurySpendKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(treasurySpendArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newTreasurySpendPropDefinition(a.dao, a.to, a.coin), nil\n}\n\n// treasuryClawbackArgs carries CreateTreasuryClawbackProposal parameters\n// to the treasury-clawback kind. host is the proposing ancestor DAO (read\n// for the ancestry check); target is the descendant whose treasury the\n// executor sweeps (its sub is the funding source, see FundingDAOID). Both\n// handles come from the trusted wrapper via args, since New receives only\n// a readonly view.\ntype treasuryClawbackArgs struct {\n\thost   *commondao.CommonDAO\n\ttarget *commondao.CommonDAO\n}\n\n// treasuryClawbackKind creates proposals for the host DAO, as an ancestor,\n// to sweep a descendant DAO's treasury to the descendant's parent.\ntype treasuryClawbackKind struct{}\n\nfunc (treasuryClawbackKind) Name() string { return kindTreasuryClawback }\n\nfunc (treasuryClawbackKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(treasuryClawbackArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newTreasuryClawbackPropDefinition(a.host, a.target), nil\n}\n\n// treasuryFreezeArgs carries CreateTreasuryFreezeProposal parameters to\n// the treasury-freeze kind. host is the proposing ancestor DAO (read for\n// the ancestry / orphan-rescue check); target is the descendant whose\n// treasury the executor freezes or unfreezes. Both handles come from the\n// trusted wrapper via args, since New receives only a readonly view.\ntype treasuryFreezeArgs struct {\n\thost   *commondao.CommonDAO\n\ttarget *commondao.CommonDAO\n\tfrozen bool\n}\n\n// treasuryFreezeKind creates proposals for the host DAO, as an ancestor,\n// to freeze or unfreeze a descendant DAO's treasury.\ntype treasuryFreezeKind struct{}\n\nfunc (treasuryFreezeKind) Name() string { return kindTreasuryFreeze }\n\nfunc (treasuryFreezeKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(treasuryFreezeArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\treturn newTreasuryFreezePropDefinition(a.host, a.target, a.frozen), nil\n}\n\n// errTreasuryFrozen reports an execution proposal blocked because the host\n// DAO's treasury is frozen. It is a sentinel so the freeze gate is greppable\n// and testable (the create-time panic and the Validate-time failure share\n// this one message).\nvar errTreasuryFrozen = errors.New(\"commondao: treasury is frozen\")\n\n// executionArgs carries CreateExecutionProposal parameters to the execution\n// kind: a title, a body, and the closure executed on approval. Unlike the\n// governance kinds, the execution kind captures no mutable handle — its only\n// use of the DAO is a freeze-flag read, so its definition holds the readonly\n// host view Propose passes to New rather than a *CommonDAO from args.\ntype executionArgs struct {\n\ttitle string\n\tbody  string\n\tfn    commondao.ExecFunc\n}\n\n// executionKind creates proposals that run an arbitrary ExecFunc as the host\n// DAO's own sub on approval. It is the realm-side counterpart of the /p/\n// commondao.ExecutionKind: identical arbitrary-exec mechanism, but wrapped\n// with the realm's Validable freeze policy (executionPropDefinition.Validate)\n// so a frozen DAO cannot drain its own treasury through it — the /p/ kind\n// carries no such policy. This is the pattern the /p/ extension docs\n// recommend for an arbitrary-exec closure: wrap it with your realm's own\n// checks.\ntype executionKind struct{}\n\nfunc (executionKind) Name() string { return kindExecution }\n\nfunc (executionKind) New(dao commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\ta, ok := args.(executionArgs)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\tif a.fn == nil {\n\t\treturn nil, commondao.ErrExecutionFuncRequired\n\t}\n\t// The definition captures the readonly host view Propose passed here, not a\n\t// handle from args: its only use of the DAO is the Validate freeze read. No\n\t// mutable handle means no host-identity pin is needed — the view is the\n\t// host by construction.\n\treturn executionPropDefinition{dao: dao, title: a.title, body: a.body, fn: a.fn}, nil\n}\n\n// executionPropDefinition defines a proposal that runs an arbitrary ExecFunc\n// as the host DAO's own sub on approval. Its Validate blocks execution while\n// the host treasury is frozen, so an execution proposal can never move funds\n// out of a frozen DAO — matching the treasury-spend freeze gate.\ntype executionPropDefinition struct {\n\tdao   commondao.ReadonlyCommonDAO\n\ttitle string\n\tbody  string\n\tfn    commondao.ExecFunc\n}\n\n// Title returns raw, user-supplied text; the renderer escapes every\n// definition title.\nfunc (p executionPropDefinition) Title() string { return p.title }\n\n// isTrustedMarkdownBody marks Body as self-assembled: it prepends the\n// realm's own standing warning and escapes the proposer's text itself.\nfunc (executionPropDefinition) isTrustedMarkdownBody() {}\n\n// Body prefixes the proposer's description with a disclosure. The closure\n// is frozen at Propose, so what executes cannot change after voting starts\n// — but it also cannot be shown: a function value has no rendering, and\n// the title and description are whatever the proposer chose to write. A\n// council voting on this kind is approving code it cannot read, so say so\n// rather than let prose stand alone.\nfunc (p executionPropDefinition) Body() string {\n\treturn md.Blockquote(\"⚠ This proposal runs arbitrary code with the DAO's own authority, \"+\n\t\t\"including its treasury. The code is fixed when the proposal is created but cannot be \"+\n\t\t\"displayed here — verify the proposing realm before voting.\") +\n\t\tmd.Paragraph(md.EscapeText(p.body))\n}\n\nfunc (executionPropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// Threshold returns the tally threshold: arbitrary execution runs code under\n// the DAO's authority, so the supermajority default applies.\nfunc (executionPropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\n// Validate runs at proposal creation and again inside Execute: a treasury\n// frozen after the proposal passed still blocks it cleanly (StatusFailed, no\n// funds leave) instead of letting the closure run against a frozen DAO. Freeze\n// = no self-initiated treasury movement, spend and execution alike.\nfunc (p executionPropDefinition) Validate() error {\n\tif p.dao.IsTreasuryFrozen() {\n\t\treturn errTreasuryFrozen\n\t}\n\treturn nil\n}\n\nfunc (p executionPropDefinition) Executor() commondao.ExecFunc {\n\treturn p.fn\n}\n\n// manageKindsProposal is both the manage-kinds args struct and the proposal\n// definition it produces: manageKindsKind.New validates it and returns it\n// unchanged (one type serves both the args and definition roles). dao is the\n// host DAO whose registry the executor\n// mutates: New receives only a readonly view, so the trusted wrapper passes\n// the mutable host handle through args (captured from its own mustGetDAO).\n//\n// A proposal is one of two shapes, both populated only by a trusted\n// wrapper and both by name (the name resolves against the realm catalog):\n//   - register:   remove=false, name set;\n//   - deregister: remove=true,  name set.\n//\n// Registering a foreign kind by value is intentionally not offered here: on\n// this realm such a kind would be inert (no propose path). The by-value\n// capability stays available in /p/ (WithProposalKind / RegisterKind) for a\n// downstream realm that authors its own propose wrapper (see /p/ doc.gno,\n// \"Extending commondao in your own realm\").\ntype manageKindsProposal struct {\n\tdao    *commondao.CommonDAO\n\tremove bool\n\tname   string\n}\n\n// manageKindsKind creates governance proposals that register or deregister\n// a catalog proposal kind on the host DAO by name — the DAO's one permanent\n// capability to manage which kinds it accepts. Registering adds a kind;\n// deregistering removes one, which blocks new proposals of that kind while\n// in-flight ones still vote and execute. It is decided by supermajority and\n// cannot itself be deregistered (the self-brick guard below), so a DAO\n// always keeps the ability to manage its kind set.\ntype manageKindsKind struct{}\n\nfunc (manageKindsKind) Name() string { return kindManageKinds }\n\nfunc (manageKindsKind) New(dao commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\tp, ok := args.(manageKindsProposal)\n\tif !ok {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\t// Defense in depth: this kind captures a mutable host handle from args (it\n\t// must, to register/deregister on Execute) while the checks below read the\n\t// readonly host Propose passed here. Pin them to the same DAO so a future\n\t// wrapper can never validate against one registry and mutate another (the\n\t// trusted wrapper always passes matching handles today).\n\tif p.dao.ID() != dao.ID() {\n\t\treturn nil, errInvalidProposalArgs\n\t}\n\n\tif p.remove {\n\t\t// Deregister by name. Reject no-ops so a council vote is always\n\t\t// about an actual change, and reject the self-brick: manage-kinds\n\t\t// is the only un-deregisterable kind, so a DAO can never lose the\n\t\t// ability to manage its kind set.\n\t\tif !dao.HasKind(p.name) {\n\t\t\treturn nil, errors.New(\"proposal kind is not registered: \" + p.name)\n\t\t}\n\t\tif p.name == kindManageKinds {\n\t\t\treturn nil, errors.New(\"the manage-kinds kind cannot be deregistered\")\n\t\t}\n\t\treturn p, nil\n\t}\n\n\t// Register by name: the name must resolve against the realm catalog, and\n\t// reject a no-op (already registered) so a council vote is always about\n\t// an actual change.\n\tif catalogKind(p.name) == nil {\n\t\treturn nil, errors.New(\"unknown proposal kind\")\n\t}\n\tif dao.HasKind(p.name) {\n\t\treturn nil, errors.New(\"proposal kind is already registered\")\n\t}\n\n\treturn p, nil\n}\n\n// Title returns the proposal title as raw text: the renderer escapes\n// every definition title, so escaping the kind name here (unlike in Body,\n// which the renderer trusts as markdown) would double-escape it.\nfunc (p manageKindsProposal) Title() string {\n\tif p.remove {\n\t\treturn \"Deregister Proposal Kind: \" + p.name\n\t}\n\treturn \"Register Proposal Kind: \" + p.name\n}\n\nfunc (manageKindsProposal) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown; the embedded\n// kind name is escaped in Body itself (defense in depth).\nfunc (manageKindsProposal) isTrustedMarkdownBody() {}\n\n// Threshold returns the tally threshold: changing which proposal kinds a\n// DAO accepts alters its governance surface, so the supermajority default\n// applies.\nfunc (manageKindsProposal) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\n// Validate re-asserts the self-brick at Execute time (Validate reruns\n// inside Execute): the manage-kinds kind can never be deregistered, so a\n// DAO always keeps the ability to manage its kind set. This is a\n// defense-in-depth second layer behind the New check.\nfunc (p manageKindsProposal) Validate() error {\n\tif p.remove \u0026\u0026 p.name == kindManageKinds {\n\t\treturn errors.New(\"the manage-kinds kind cannot be deregistered\")\n\t}\n\treturn nil\n}\n\nfunc (p manageKindsProposal) Body() string {\n\tvar b strings.Builder\n\n\t// The kind name is validated against the catalog; it is escaped anyway\n\t// as defense in depth.\n\tb.WriteString(md.Paragraph(md.Bold(\"Proposal Kind:\") + \"\\n\" + md.EscapeText(p.name)))\n\n\taction := \"registered: new proposals of this kind can be created.\"\n\tif p.remove {\n\t\taction = \"deregistered: no new proposal of this kind can be created. \" +\n\t\t\t\"In-flight proposals of the kind still vote and execute.\"\n\t}\n\tb.WriteString(md.Paragraph(md.Bold(\"Effect:\") + \"\\nThe proposal kind is \" + action))\n\n\treturn b.String()\n}\n\nfunc (p manageKindsProposal) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\n// execute registers or deregisters the catalog kind, returning any registry\n// error unchanged so a race between two concurrently passed manage-kinds\n// proposals fails the later one cleanly (StatusFailed) instead of panicking\n// the transaction. catalogKind is a process-global immutable lookup, so a\n// name valid at New still resolves here; the executor does not re-resolve\n// or re-validate beyond the Validate self-brick. It moves no funds, so the\n// definition is not Funded and ignores sub.\nfunc (p manageKindsProposal) execute(_ int, sub realm) error {\n\tif p.remove {\n\t\treturn p.dao.DeregisterKind(p.name)\n\t}\n\treturn p.dao.RegisterKind(catalogKind(p.name))\n}\n"},{"name":"proposal_subdao.gno","body":"package commondao\n\nimport (\n\t\"chain/banker\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// newSubDAOPropDefinition creates a new proposal definition for adding a SubDAO.\nfunc newSubDAOPropDefinition(parent *commondao.CommonDAO, name, purpose, description string, members []address) subDAOPropDefinition {\n\tif parent == nil {\n\t\tpanic(\"parent DAO is required\")\n\t}\n\n\tname = strings.TrimSpace(name)\n\tassertDAONameIsValid(name)\n\n\tpurpose = strings.TrimSpace(purpose)\n\tassertDAOPurposeIsValid(purpose)\n\n\tdescription = strings.TrimSpace(description)\n\tassertDAODescriptionIsValid(description)\n\n\tif len(members) == 0 {\n\t\tpanic(\"a SubDAO requires at least one initial council member\")\n\t}\n\n\treturn subDAOPropDefinition{\n\t\tparent:      parent,\n\t\tname:        name,\n\t\tpurpose:     purpose,\n\t\tdescription: description,\n\t\tmembers:     members,\n\t}\n}\n\n// subDAOPropDefinition defines a proposal type for adding a SubDAO.\ntype subDAOPropDefinition struct {\n\tparent      *commondao.CommonDAO\n\tname        string\n\tpurpose     string\n\tdescription string\n\tmembers     []address\n}\n\nfunc (p subDAOPropDefinition) Title() string             { return \"New SubDAO: \" + p.name }\nfunc (subDAOPropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown; the embedded\n// user fields (name, purpose, description) are escaped in Body itself.\nfunc (subDAOPropDefinition) isTrustedMarkdownBody() {}\n\n// Threshold returns the tally threshold: the constitution grants SubDAO\n// creation at a simple majority of the Council.\nfunc (subDAOPropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSimpleMajority\n}\n\nfunc (p subDAOPropDefinition) Body() string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.Paragraph(\n\t\tmd.Bold(\"Parent DAO:\") + \"\\n\" + daoMDLink(p.parent),\n\t))\n\n\tb.WriteString(md.Paragraph(\n\t\tmd.Bold(\"SubDAO Name:\") + \"\\n\" + md.EscapeText(p.name),\n\t))\n\n\tb.WriteString(md.Paragraph(\n\t\tmd.Bold(\"SubDAO Purpose:\") + \"\\n\" + md.EscapeText(p.purpose),\n\t))\n\n\tif p.description != \"\" {\n\t\tb.WriteString(md.Paragraph(\n\t\t\tmd.Bold(\"SubDAO Description:\") + \"\\n\" + md.EscapeText(p.description),\n\t\t))\n\t}\n\n\tb.WriteString(md.Paragraph(\n\t\tmd.Bold(\"Council Members:\") + \"\\n\" + md.BulletList(addrStrings(p.members)),\n\t))\n\n\treturn b.String()\n}\n\nfunc (p subDAOPropDefinition) Validate() (err error) {\n\tp.parent.IterateChildren(func(subDAO *commondao.CommonDAO) bool {\n\t\tif subDAO.Name() == p.name {\n\t\t\terr = errors.New(\"a SubDAO with the same name already exists\")\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn err\n}\n\nfunc (p subDAOPropDefinition) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\nfunc (p subDAOPropDefinition) execute(_ int, sub realm) error {\n\tcreateSubDAO(p.parent, p.name, p.purpose, p.description, p.members...)\n\treturn nil\n}\n\n// newDissolvePropDefinition creates a new proposal definition for\n// dissolving a DAO. Dissolution sweeps any remaining treasury balance:\n// sub-DAO sweeps go to the parent (fixed, not nameable — the same place\n// a clawback would put the funds); a root DAO has no parent, so its\n// dissolution requires an explicit destination. Both rules are\n// state-independent: parent pointers never change after construction.\nfunc newDissolvePropDefinition(dao *commondao.CommonDAO, destination address) dissolvePropDefinition {\n\tif dao == nil {\n\t\tpanic(\"SubDAO is required\")\n\t}\n\tif dao.Parent() != nil {\n\t\tif destination != \"\" {\n\t\t\tpanic(\"sub-DAO dissolution sweeps to the parent DAO; destination must be empty\")\n\t\t}\n\t} else {\n\t\tif !destination.IsValid() {\n\t\t\tpanic(\"root DAO dissolution requires a valid sweep destination\")\n\t\t}\n\t}\n\n\treturn dissolvePropDefinition{dao, destination}\n}\n\n// dissolvePropDefinition defines a proposal type for dissolving a SubDAO.\ntype dissolvePropDefinition struct {\n\tdao         *commondao.CommonDAO\n\tdestination address // sweep destination, root DAOs only\n}\n\nfunc (p dissolvePropDefinition) Title() string             { return \"Dissolve DAO: \" + p.dao.Name() }\nfunc (dissolvePropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown (a DAO link).\nfunc (dissolvePropDefinition) isTrustedMarkdownBody() {}\n\n// Threshold returns the tally threshold: the constitution is silent on\n// dissolution, so the supermajority default applies.\nfunc (dissolvePropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\nfunc (p dissolvePropDefinition) Body() string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.Paragraph(md.Bold(\"DAO:\") + \"\\n\" + daoMDLink(p.dao)))\n\n\t// A root dissolution sweeps the entire treasury to an address named at\n\t// proposal creation. Show it — it is the one dissolution shape with a\n\t// free-form destination, and voters cannot judge the proposal without\n\t// it (a spend renders its recipient for the same reason). Sub-DAO\n\t// dissolution has no destination: it always sweeps up the tree.\n\tif p.destination != \"\" {\n\t\tb.WriteString(md.Paragraph(md.Bold(\"Sweep destination:\") + \"\\n\" + userLink(p.destination)))\n\t}\n\n\treturn b.String()\n}\n\nfunc (p dissolvePropDefinition) Validate() (err error) {\n\tif p.dao.IsDeleted() {\n\t\treturn errors.New(\"DAO has already been dissolved\")\n\t}\n\treturn nil\n}\n\nfunc (p dissolvePropDefinition) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\n// FundingDAOID returns the ID of the DAO whose treasury the dissolution\n// sweeps: the DAO being dissolved. For a sub-DAO the proposal is hosted in\n// an ancestor, so the operative DAO differs from the host.\nfunc (p dissolvePropDefinition) FundingDAOID() uint64 {\n\treturn p.dao.ID()\n}\n\nfunc (p dissolvePropDefinition) execute(_ int, sub realm) error {\n\t// Sweep any remaining treasury before soft deleting: no council\n\t// remains afterwards to pass a spend. Sub-DAO funds go to the parent;\n\t// root funds go to the destination named at proposal creation. A\n\t// frozen treasury does not block dissolution — the sweep sends the\n\t// funds where a clawback would. sub is the dissolved DAO's sub-identity,\n\t// minted by the host. Full-balance send: cost is O(denoms); a\n\t// denom-flooded DAO can push this past block gas, blocking dissolution\n\t// (known limitation — see the treasury ADR §Sweep gas-bomb).\n\tif balance := treasuryBalance(p.dao); !balance.IsZero() {\n\t\tdest := p.destination\n\t\tif parent := p.dao.Parent(); parent != nil {\n\t\t\t// Sweep to the nearest LIVE ancestor, mirroring the walk\n\t\t\t// CreateDissolutionProposal uses to pick the host. Sending to a\n\t\t\t// dissolved intermediate would deposit the balance on a dead\n\t\t\t// DAO: only a further clawback could rescue it, and once the\n\t\t\t// whole chain is dissolved it is lost outright. A dissolution\n\t\t\t// proposal can only be hosted by a live ancestor (a deleted DAO\n\t\t\t// rejects Propose), so one always exists.\n\t\t\tfor parent.IsDeleted() \u0026\u0026 parent.Parent() != nil {\n\t\t\t\tparent = parent.Parent()\n\t\t\t}\n\t\t\tdest = parent.Address()\n\t\t}\n\n\t\tb := banker.NewBanker(banker.BankerTypeRealmSend, sub)\n\t\tb.SendCoins(sub.Address(), dest, balance)\n\t}\n\n\t// Drop the DAO from the home index: a dissolved DAO can no longer be\n\t// unlisted through SetListed (it rejects deleted DAOs), so unlist it\n\t// here rather than leave it stuck in the listing.\n\tsetListed(p.dao.ID(), false)\n\n\t// Dissolution voids the DAO's in-flight proposals before soft deleting\n\t// it, so nothing remains pending on a DAO that rejects execution.\n\tp.dao.Dissolve(\"DAO dissolved\")\n\treturn nil\n}\n"},{"name":"proposal_text.gno","body":"package commondao\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\nconst (\n\tmaxTextBody         = 15_000\n\tmaxTextTitle        = 255\n\tminTextVotingPeriod = time.Hour * 24\n)\n\n// newTextPropDefinition creates a new general text proposal definition.\nfunc newTextPropDefinition(title, body string, votingPeriod time.Duration) textPropDefinition {\n\ttitle = strings.TrimSpace(title)\n\tif title == \"\" {\n\t\tpanic(\"proposal title is empty\")\n\t}\n\n\tif len(title) \u003e maxTextTitle {\n\t\tpanic(\"proposal title is too long, max length is 255 chars\")\n\t}\n\n\tbody = strings.TrimSpace(body)\n\tif body == \"\" {\n\t\tpanic(\"proposal body is empty\")\n\t}\n\n\tif len(body) \u003e maxTextBody {\n\t\tpanic(\"proposal body is too long, max length is 15000 chars\")\n\t}\n\n\tif votingPeriod \u003c minTextVotingPeriod {\n\t\tpanic(\"minimum proposal voting period is one day\")\n\t}\n\n\treturn textPropDefinition{\n\t\ttitle:        title,\n\t\tbody:         body,\n\t\tvotingPeriod: votingPeriod,\n\t}\n}\n\n// textPropDefinition defines a proposal type for general text proposals.\n// These type of proposals are not executable so nothing happens when they pass.\ntype textPropDefinition struct {\n\ttitle, body  string\n\tvotingPeriod time.Duration\n}\n\nfunc (p textPropDefinition) Title() string               { return p.title }\nfunc (p textPropDefinition) Body() string                { return p.body }\nfunc (p textPropDefinition) VotingPeriod() time.Duration { return p.votingPeriod }\n\n// Threshold returns the tally threshold: text proposals are decided by the\n// constitution's default supermajority rule.\nfunc (textPropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n"},{"name":"proposal_treasury.gno","body":"package commondao\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// hasLiveProperAncestor checks if any proper ancestor of dao is not\n// dissolved.\nfunc hasLiveProperAncestor(dao *commondao.CommonDAO) bool {\n\tfor p := dao.Parent(); p != nil; p = p.Parent() {\n\t\tif !p.IsDeleted() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// isProperAncestor checks if dao is a proper ancestor of target.\n// Parent pointers are set only at construction and no re-parenting path\n// exists, so ancestry is stable for the lifetime of a proposal.\nfunc isProperAncestor(dao, target *commondao.CommonDAO) bool {\n\tfor p := target.Parent(); p != nil; p = p.Parent() {\n\t\tif p.ID() == dao.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// assertIsProperAncestor validates the ancestor relation that authorizes\n// treasury controls over a descendant (docs/CONSTITUTION.md :1507). The\n// relation is strictly proper: a DAO can never claw back or unfreeze\n// itself.\nfunc assertIsProperAncestor(dao, target *commondao.CommonDAO) error {\n\tif target.ID() == dao.ID() {\n\t\treturn errors.New(\"a DAO cannot target itself\")\n\t}\n\tif !isProperAncestor(dao, target) {\n\t\treturn errors.New(\"DAO is not an ancestor of the target DAO\")\n\t}\n\treturn nil\n}\n\n// treasuryBalance returns the current balance of a DAO's treasury address.\nfunc treasuryBalance(dao *commondao.CommonDAO) chain.Coins {\n\treturn banker.NewReadonlyBanker().GetCoins(dao.Address())\n}\n\n// newTreasurySpendPropDefinition creates a proposal definition that sends\n// coins from the DAO's own treasury.\nfunc newTreasurySpendPropDefinition(dao *commondao.CommonDAO, to address, coin chain.Coin) treasurySpendPropDefinition {\n\tif dao == nil {\n\t\tpanic(\"DAO is required\")\n\t}\n\tif !to.IsValid() {\n\t\tpanic(\"invalid recipient address\")\n\t}\n\tif coin.Denom == \"\" {\n\t\tpanic(\"coin denomination is empty\")\n\t}\n\tif !coin.IsPositive() {\n\t\tpanic(\"spend amount must be positive\")\n\t}\n\n\treturn treasurySpendPropDefinition{dao, to, coin}\n}\n\n// treasurySpendPropDefinition defines a proposal type for spending funds\n// from the DAO's own treasury (docs/CONSTITUTION.md :1542-1543).\ntype treasurySpendPropDefinition struct {\n\tdao  *commondao.CommonDAO\n\tto   address\n\tcoin chain.Coin\n}\n\nfunc (treasurySpendPropDefinition) Title() string               { return \"Treasury Spend\" }\nfunc (treasurySpendPropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown; the embedded\n// recipient and amount are formatted by md helpers / EscapeText in Body.\nfunc (treasurySpendPropDefinition) isTrustedMarkdownBody() {}\n\n// Threshold returns the tally threshold: the constitution attaches no\n// spend-specific rule, so the supermajority default applies.\nfunc (treasurySpendPropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\nfunc (p treasurySpendPropDefinition) Body() string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.Paragraph(md.Bold(\"Recipient:\") + \"\\n\" + userLink(p.to)))\n\tb.WriteString(md.Paragraph(md.Bold(\"Amount:\") + \"\\n\" + md.EscapeText(p.coin.String())))\n\n\treturn b.String()\n}\n\n// Validate runs at proposal creation and again at execution, so a\n// treasury frozen or drained after the proposal passed still fails it\n// cleanly (StatusFailed, coins untouched) instead of panicking the tx.\nfunc (p treasurySpendPropDefinition) Validate() error {\n\tif p.dao.IsDeleted() {\n\t\treturn errors.New(\"DAO has already been dissolved\")\n\t}\n\tif p.dao.IsTreasuryFrozen() {\n\t\treturn errors.New(\"DAO treasury is frozen\")\n\t}\n\tif treasuryBalance(p.dao).AmountOf(p.coin.Denom) \u003c p.coin.Amount {\n\t\treturn errors.New(\"insufficient treasury balance\")\n\t}\n\treturn nil\n}\n\nfunc (p treasurySpendPropDefinition) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\n// FundingDAOID returns the ID of the DAO whose treasury funds the spend:\n// its own (the host).\nfunc (p treasurySpendPropDefinition) FundingDAOID() uint64 {\n\treturn p.dao.ID()\n}\n\nfunc (p treasurySpendPropDefinition) execute(_ int, sub realm) error {\n\t// sub is this DAO's sub-identity, minted by the host: send from it.\n\t// Banker sends move bank balances without invoking recipient code, so\n\t// there is no reentrancy vector. Validate ran in this same Execute\n\t// call, so the balance check is current.\n\tb := banker.NewBanker(banker.BankerTypeRealmSend, sub)\n\tb.SendCoins(sub.Address(), p.to, chain.NewCoins(p.coin))\n\treturn nil\n}\n\n// newTreasuryClawbackPropDefinition creates a proposal definition that\n// sweeps a descendant DAO's treasury one step up the tree.\nfunc newTreasuryClawbackPropDefinition(dao, target *commondao.CommonDAO) treasuryClawbackPropDefinition {\n\tif dao == nil {\n\t\tpanic(\"DAO is required\")\n\t}\n\tif target == nil {\n\t\tpanic(\"target DAO is required\")\n\t}\n\n\treturn treasuryClawbackPropDefinition{dao, target}\n}\n\n// treasuryClawbackPropDefinition defines a proposal type for an ancestor\n// DAO to reclaim a descendant's treasury. The destination is fixed — the\n// target's parent — so funds move one step up the tree toward their\n// origin and can never be drained out of the tree entirely. Clawback\n// remains valid against soft-deleted and frozen descendants.\ntype treasuryClawbackPropDefinition struct {\n\tdao    *commondao.CommonDAO // proposing DAO, must be a proper ancestor\n\ttarget *commondao.CommonDAO\n}\n\nfunc (treasuryClawbackPropDefinition) Title() string               { return \"Treasury Clawback\" }\nfunc (treasuryClawbackPropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown (a DAO link).\nfunc (treasuryClawbackPropDefinition) isTrustedMarkdownBody() {}\n\n// Threshold returns the tally threshold: simple majority, the\n// constitutional wording for this ancestor power.\nfunc (treasuryClawbackPropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSimpleMajority\n}\n\nfunc (p treasuryClawbackPropDefinition) Body() string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.Paragraph(md.Bold(\"Target DAO:\") + \"\\n\" + daoMDLink(p.target)))\n\tb.WriteString(md.Paragraph(\n\t\tmd.Bold(\"Destination:\") + \"\\n\" +\n\t\t\t\"The target's parent DAO receives the target's full balance at execution time.\",\n\t))\n\n\treturn b.String()\n}\n\nfunc (p treasuryClawbackPropDefinition) Validate() error {\n\treturn assertIsProperAncestor(p.dao, p.target)\n}\n\nfunc (p treasuryClawbackPropDefinition) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\n// FundingDAOID returns the ID of the DAO whose treasury the clawback\n// sweeps: the target, not the proposing ancestor that hosts the proposal.\nfunc (p treasuryClawbackPropDefinition) FundingDAOID() uint64 {\n\treturn p.target.ID()\n}\n\nfunc (p treasuryClawbackPropDefinition) execute(_ int, sub realm) error {\n\tbalance := treasuryBalance(p.target)\n\tif balance.IsZero() {\n\t\treturn nil\n\t}\n\n\t// sub is the target's sub-identity, minted by the host. A proper\n\t// ancestor exists, so the target always has a parent. Full-balance\n\t// send: cost is O(number of denoms held). A target dusted with many\n\t// realm-minted denoms can push this past block gas (known limitation —\n\t// see the treasury ADR §Sweep gas-bomb).\n\tb := banker.NewBanker(banker.BankerTypeRealmSend, sub)\n\tb.SendCoins(sub.Address(), p.target.Parent().Address(), balance)\n\treturn nil\n}\n\n// newTreasuryFreezePropDefinition creates a proposal definition that\n// freezes or unfreezes a descendant DAO's treasury.\nfunc newTreasuryFreezePropDefinition(dao, target *commondao.CommonDAO, frozen bool) treasuryFreezePropDefinition {\n\tif dao == nil {\n\t\tpanic(\"DAO is required\")\n\t}\n\tif target == nil {\n\t\tpanic(\"target DAO is required\")\n\t}\n\n\treturn treasuryFreezePropDefinition{dao, target, frozen}\n}\n\n// treasuryFreezePropDefinition defines a proposal type for an ancestor\n// DAO to freeze or unfreeze a descendant's treasury. Freezing does not\n// cascade: ancestors freeze each descendant explicitly. Only a proper\n// ancestor can unfreeze — the frozen DAO's own council cannot.\ntype treasuryFreezePropDefinition struct {\n\tdao    *commondao.CommonDAO // proposing DAO, must be a proper ancestor\n\ttarget *commondao.CommonDAO\n\tfrozen bool\n}\n\nfunc (p treasuryFreezePropDefinition) Title() string {\n\tif p.frozen {\n\t\treturn \"Treasury Freeze\"\n\t}\n\treturn \"Treasury Unfreeze\"\n}\n\nfunc (treasuryFreezePropDefinition) VotingPeriod() time.Duration { return time.Hour * 24 * 7 }\n\n// isTrustedMarkdownBody marks Body as self-assembled markdown (a DAO link).\nfunc (treasuryFreezePropDefinition) isTrustedMarkdownBody() {}\n\n// Threshold returns the tally threshold: simple majority, matching the\n// clawback power it safeguards.\nfunc (treasuryFreezePropDefinition) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSimpleMajority\n}\n\nfunc (p treasuryFreezePropDefinition) Body() string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.Paragraph(md.Bold(\"Target DAO:\") + \"\\n\" + daoMDLink(p.target)))\n\n\taction := \"frozen: no funds can leave the treasury until a proper ancestor unfreezes it.\"\n\tif !p.frozen {\n\t\taction = \"unfrozen: funds can leave the treasury again.\"\n\t}\n\tb.WriteString(md.Paragraph(md.Bold(\"Effect:\") + \"\\nThe target's treasury is \" + action))\n\n\treturn b.String()\n}\n\nfunc (p treasuryFreezePropDefinition) Validate() error {\n\t// Orphan rescue: when every proper ancestor is dissolved, the freezing\n\t// authority class is extinct, so the target's own council may restore\n\t// the constitutional default by unfreezing itself. Without this, a\n\t// frozen DAO orphaned by its ancestors' dissolution would hold its\n\t// funds locked forever. Freezing - and any self-targeting while a\n\t// live ancestor exists - stays ancestor-only.\n\tif !p.frozen \u0026\u0026 p.dao.ID() == p.target.ID() \u0026\u0026 !hasLiveProperAncestor(p.target) {\n\t\treturn nil\n\t}\n\treturn assertIsProperAncestor(p.dao, p.target)\n}\n\nfunc (p treasuryFreezePropDefinition) Executor() commondao.ExecFunc {\n\treturn p.execute\n}\n\nfunc (p treasuryFreezePropDefinition) execute(_ int, sub realm) error {\n\tp.target.SetTreasuryFrozen(p.frozen)\n\treturn nil\n}\n\n// daoMDLink returns a markdown link to a DAO's page.\nfunc daoMDLink(dao *commondao.CommonDAO) string {\n\treturn md.Link(dao.Name(), daoURL(dao.ID()))\n}\n"},{"name":"public.gno","body":"package commondao\n\nimport (\n\t// unsafe is used only for the CurrentRealm call in assertRunningPath when\n\t// checking the deployment path. Caller authentication uses cur.Previous().\n\t\"chain/runtime/unsafe\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// assertCurrent guards every public crossing entry. Authentication reads\n// cur.Previous() and Execute mints cur.Sub(...) for the executor; both\n// require cur to be the live top-of-frame realm (AGENTS.md / interrealm-v2).\n// Every entry is only reachable via a cross today, so this is\n// defense-in-depth against a future non-crossing caller.\nfunc assertCurrent(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"commondao: cur realm is not current\")\n\t}\n}\n\n// assertRunningPath fails closed if this realm is deployed at a package\n// path other than pkgPath. Treasury addresses derive from the pkgPath\n// const (daoAddress), while Execute mints the DAO sub under the running\n// realm's own path (cur.Sub). Those agree only when the running path is\n// pkgPath; a copy deployed elsewhere would read balances at one address\n// and send from another, turning a clean StatusFailed into a mismatch. We\n// reject that at genesis rather than silently diverge.\nfunc assertRunningPath() {\n\tif got := unsafe.CurrentRealm().PkgPath(); got != pkgPath {\n\t\tpanic(\"commondao: realm deployed at \" + got + \", expected \" + pkgPath)\n\t}\n}\n\n// assertCallerIsUser rejects a code realm creating a DAO on someone's\n// behalf. New keys the invite and the creators set on the caller, and\n// invites are granted to people, so the caller must be the user itself:\n// either a direct MsgCall (IsUserCall) or that user's own MsgRun frame\n// (IsUserRun, whose address is the signer's own). Both are IsUser; a\n// published realm is neither.\n//\n// Relaying is what this excludes. If a realm could redeem an invite, one\n// invited realm would become a DAO factory for un-invited callers — the\n// vector pr6012_commondao_ownership_rescope.md closed by keying on the\n// transaction origin. Keying on the caller closes it too, but only while\n// the caller cannot be a realm.\n//\n// It bounds who may *create* a DAO, not who may sit on one: the members\n// argument may still name realm addresses, and sub-DAO councils are set\n// by proposal (see CreateSubDAOProposal). Handing a DAO to a realm is a\n// council decision, not a creation-time one.\nfunc assertCallerIsUser(cur realm) {\n\tif !cur.Previous().IsUser() {\n\t\tpanic(\"only a user can create a DAO\")\n\t}\n}\n\n// Invite invites a user to the realm.\n// A user invitation is required to start creating new DAOs.\nfunc Invite(cur realm, invitee address) {\n\tassertCurrent(cur)\n\n\tif !invitee.IsValid() {\n\t\tpanic(\"invalid address\")\n\t}\n\n\tdao := mustGetDAO(CommonDAOID)\n\tcaller := cur.Previous().Address()\n\tif !dao.Council().Has(caller) {\n\t\tpanic(\"unauthorized\")\n\t}\n\n\tinvites.Set(invitee.String(), caller.String())\n}\n\n// IsInvited checks if an address has an invitation to the realm.\nfunc IsInvited(addr address) bool {\n\treturn isInvited(addr)\n}\n\n// New creates a new CommonDAO and returns its ID.\n// The caller must be a user, not a realm (see assertCallerIsUser), and must\n// hold an invite. The invite is consumed when that caller creates a DAO for\n// the first time, after which the caller may create further DAOs freely.\n// The caller becomes a council member along with any additional member\n// addresses listed on separate lines; those may be realm addresses, so a\n// DAO can be handed to a realm by seating it here and resigning. DAOs with\n// a parent are created through proposals (see CreateSubDAOProposal).\nfunc New(cur realm, name, purpose, description, members string) uint64 {\n\tassertCurrent(cur)\n\tassertCallerIsUser(cur)\n\tcaller := cur.Previous().Address()\n\n\tname = strings.TrimSpace(name)\n\tassertDAONameIsValid(name)\n\n\tpurpose = strings.TrimSpace(purpose)\n\tassertDAOPurposeIsValid(purpose)\n\n\tdescription = strings.TrimSpace(description)\n\tassertDAODescriptionIsValid(description)\n\n\t// The invite is consumed once. The direct user caller is then recorded and\n\t// can create further DAOs without another invite.\n\tif !isCreator(caller) {\n\t\tassertIsInvited(caller)\n\t\tinvites.Remove(caller.String())\n\t\tcreators.Set(caller.String(), struct{}{})\n\t}\n\n\tdao := createDAO(name, purpose, description, parseInitialMembers(caller, members)...)\n\treturn dao.ID()\n}\n\n// parseInitialMembers returns the caller plus the parsed additional\n// members, deduplicated.\nfunc parseInitialMembers(caller address, members string) []address {\n\taddrs := parseAddresses(members)\n\tif containsAddress(addrs, caller) {\n\t\treturn addrs\n\t}\n\treturn append(addrs, caller)\n}\n\n// SetListed adds or removes a DAO from the realm's public home index.\n// Listing is cosmetic — it affects only how this realm presents the DAO\n// in its own UI — so any single council member of the DAO may toggle it,\n// like Resign. It defaults to off.\nfunc SetListed(cur realm, daoID uint64, listed bool) {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tif dao.IsDeleted() {\n\t\tpanic(commondao.ErrDAOIsDeleted)\n\t}\n\n\tassertCallerIsCouncilMember(cur.Previous().Address(), dao)\n\tsetListed(daoID, listed)\n}\n\n// IsListed reports whether a DAO appears in the realm's public home index.\nfunc IsListed(daoID uint64) bool {\n\treturn isListed(daoID)\n}\n\n// GetView returns a read only view of a common DAO searched by ID.\nfunc GetView(daoID uint64) commondao.ReadonlyCommonDAO {\n\treturn mustGetDAO(daoID).Readonly()\n}\n\n// GetBylawsDoc returns the text of a DAO's bylaws/mandates document, or\n// an empty string when the document does not exist (a stored document is\n// never empty).\nfunc GetBylawsDoc(daoID uint64, path string) string {\n\tmustGetDAO(daoID)\n\n\tif set := bylawsView(daoID); set != nil {\n\t\ttext, _ := set.Get(path)\n\t\treturn text\n\t}\n\treturn \"\"\n}\n\n// ListBylawsDocs returns the sorted paths of a DAO's bylaws/mandates\n// documents under a prefix (empty prefix lists all).\nfunc ListBylawsDocs(daoID uint64, prefix string) []string {\n\tmustGetDAO(daoID)\n\n\tif set := bylawsView(daoID); set != nil {\n\t\treturn set.List(prefix)\n\t}\n\treturn nil\n}\n\n// Vote submits a vote for a DAO proposal.\n// Voting is allowed to the members of the proposal's electorate: the\n// council snapshot taken when the proposal was created.\nfunc Vote(cur realm, daoID, proposalID uint64, vote commondao.VoteChoice, reason string) {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\terr := dao.Vote(caller, proposalID, vote, reason)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Funded is the optional contract a proposal definition implements when its\n// executor moves funds from a DAO other than the proposal's host: it names,\n// by ID, the DAO whose sub-identity address funds the executor. Execute\n// resolves that DAO, mints its terminal RealmSend-only sub and passes it to\n// the ExecFunc; a definition that does not implement Funded receives the\n// host DAO's own sub by default. The returned ID must identify the DAO the\n// definition validates its fund movement against (e.g. the DAO being spent,\n// swept or dissolved).\n//\n// It lives realm-side, not in /p/: minting a DAO sub needs the host realm's\n// cur (cur.Sub), so only the host — never the package — can honor it. /p/\n// dispatches CapExempt/Executable/Validable itself, but Execute (the host)\n// is the sole consumer of Funded, so the package has no reason to know it.\ntype Funded interface {\n\t// FundingDAOID returns the ID of the DAO whose sub-address funds the\n\t// executor.\n\tFundingDAOID() uint64\n}\n\n// Execute executes a DAO proposal.\n//\n// Executing a proposal that passed early (decided by the default Council\n// rules before its voting deadline) requires the caller to be a council\n// member. Once the voting deadline has passed execution is permissionless:\n// the tally is deterministic, so anyone can finalize the proposal.\nfunc Execute(cur realm, daoID, proposalID uint64) {\n\tassertCurrent(cur)\n\n\t// Re-entrancy latch: a proposal executor must not trigger another\n\t// Execute. Without this, an executor could finalize a second proposal\n\t// mid-run — e.g. dissolve its own DAO and leave this frame finalizing on\n\t// a deleted DAO. The latch is global (one executor per tx); it does not\n\t// block Vote/Create*, so an executor may still act as its DAO elsewhere.\n\tenterExecute()\n\tdefer leaveExecute()\n\n\tdao := mustGetDAO(daoID)\n\tp := dao.GetProposal(proposalID)\n\tif p == nil {\n\t\tpanic(commondao.ErrProposalNotFound)\n\t}\n\n\t// Before the deadline, only a council member may execute an\n\t// early-passed proposal. Once the deadline passes the tally is\n\t// deterministic, so finalization is permissionless.\n\tif !p.HasVotingDeadlinePassed() {\n\t\tassertCallerIsCouncilMember(cur.Previous().Address(), dao)\n\t}\n\n\t// Mint the sub-identity that funds the executor and pass it in. The\n\t// operative DAO is the host by default; a fund-moving definition\n\t// (Funded) may name a different DAO by ID (e.g. clawback sweeps the\n\t// target, sub-DAO dissolution sweeps the dissolved descendant). Non-fund\n\t// executors ignore the sub. The sub is terminal and RealmSend-only, so\n\t// the executor can move value only from this one DAO address.\n\top := daoID\n\tif f, ok := p.Definition().(Funded); ok {\n\t\top = f.FundingDAOID()\n\t}\n\tsub := cur.Sub(subpathOf(op))\n\n\terr := dao.Execute(proposalID, sub)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Withdraw withdraws an active DAO proposal that has no votes.\n// Only the proposal creator can withdraw it.\nfunc Withdraw(cur realm, daoID, proposalID uint64) {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tp := dao.GetProposal(proposalID)\n\tif p == nil {\n\t\tpanic(commondao.ErrProposalNotFound)\n\t}\n\n\tif p.Creator() != cur.Previous().Address() {\n\t\tpanic(\"only the proposal creator can withdraw it\")\n\t}\n\n\tif err := dao.Withdraw(proposalID); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Resign removes the caller from a DAO council.\n// The last remaining council member cannot resign.\nfunc Resign(cur realm, daoID uint64) {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tif dao.IsDeleted() {\n\t\tpanic(commondao.ErrDAOIsDeleted)\n\t}\n\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\tif err := dao.UpdateCouncil(nil, []address{caller}); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc isInvited(addr address) bool {\n\treturn invites.Has(addr.String())\n}\n\nfunc assertIsInvited(addr address) {\n\tif !isInvited(addr) {\n\t\tpanic(\"unauthorized\")\n\t}\n}\n\nfunc assertDAONameIsValid(name string) {\n\tif name == \"\" {\n\t\tpanic(\"DAO name is empty\")\n\t}\n\n\tif len(name) \u003e 60 {\n\t\tpanic(\"DAO name is too long, max length is 60 characters\")\n\t}\n}\n\nfunc assertDAOPurposeIsValid(purpose string) {\n\tif purpose == \"\" {\n\t\tpanic(\"DAO purpose is empty\")\n\t}\n\n\tif len(purpose) \u003e 250 {\n\t\tpanic(\"DAO purpose is too long, max length is 250 characters\")\n\t}\n}\n\nfunc assertDAODescriptionIsValid(description string) {\n\tif len(description) \u003e 250 {\n\t\tpanic(\"DAO description is too long, max length is 250 characters\")\n\t}\n}\n\nfunc assertCallerIsCouncilMember(caller address, dao *commondao.CommonDAO) {\n\tif !dao.Council().Has(caller) {\n\t\tpanic(\"caller is not a council member\")\n\t}\n}\n"},{"name":"public_proposals.gno","body":"package commondao\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/nt/bylaws/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// CreateTextProposal creates a new general text proposal.\n//\n// Parameters:\n// - daoID: ID of the DAO (required)\n// - title: Title of the proposal (required)\n// - body: Body of the proposal (required)\n// - votingDays: The number of days where proposal accepts votes.\n//\n// The default voting period is 7 days.\nfunc CreateTextProposal(cur realm, daoID uint64, title, body string, votingDays uint8) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tif votingDays \u003e 30 {\n\t\tpanic(\"maximum proposal voting period is 30 days\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\tvar votingPeriod time.Duration\n\tif votingDays == 0 {\n\t\tvotingPeriod = time.Hour * 24 * 7\n\t} else {\n\t\tvotingPeriod = time.Hour * 24 * time.Duration(votingDays)\n\t}\n\n\treturn mustPropose(dao, caller, kindText, textArgs{title, body, votingPeriod})\n}\n\n// CreateCouncilUpdateProposal creates a new proposal to add and/or remove\n// council members.\n//\n// Parameters:\n// - daoID: ID of the DAO (required)\n// - newMembers: Newline separated list of addresses to add to the council\n// - removeMembers: Newline separated list of council addresses to remove\nfunc CreateCouncilUpdateProposal(cur realm, daoID uint64, newMembers, removeMembers string) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\targs := councilUpdateArgs{dao, parseAddresses(newMembers), parseAddresses(removeMembers)}\n\treturn mustPropose(dao, caller, kindCouncilUpdate, args)\n}\n\n// CreateAncestorCouncilUpdateProposal creates a proposal for an ancestor\n// DAO to add and/or remove members of a descendant's council\n// (docs/CONSTITUTION.md :1531-1532) — the rescue path for a stuck or\n// empty descendant council. It is hosted and voted in the ancestor\n// (daoID) and decided by supermajority; the proposing DAO must be a\n// proper ancestor of the target, verified at proposal validation.\n//\n// Parameters:\n// - daoID: ID of the proposing ancestor DAO (required)\n// - targetID: ID of the descendant DAO whose council changes (required)\n// - newMembers: Newline separated list of addresses to add to the council\n// - removeMembers: Newline separated list of council addresses to remove\nfunc CreateAncestorCouncilUpdateProposal(cur realm, daoID, targetID uint64, newMembers, removeMembers string) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\ttarget := mustGetDAO(targetID)\n\targs := ancestorCouncilUpdateArgs{dao, target, parseAddresses(newMembers), parseAddresses(removeMembers)}\n\treturn mustPropose(dao, caller, kindAncestorCouncilUpdate, args)\n}\n\n// CreateSubDAOProposal creates a new proposal to create a new SubDAO.\n//\n// Parameters:\n// - daoID: ID of the parent DAO (required)\n// - name: A name for the SubDAO (required)\n// - purpose: A purpose for the SubDAO (required)\n// - description: A description for the SubDAO\n// - members: Newline separated list of initial SubDAO council addresses (required)\nfunc CreateSubDAOProposal(cur realm, daoID uint64, name, purpose, description, members string) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\targs := subDAOArgs{dao, name, purpose, description, parseAddresses(members)}\n\treturn mustPropose(dao, caller, kindSubDAO, args)\n}\n\n// CreateDissolutionProposal creates a new proposal to dissolve a DAO or SubDAO.\n//\n// SubDAOs can only be dissolved by the parent DAO, which owns and\n// controls its sub-DAOs (docs/CONSTITUTION.md :1507). When the parent is\n// itself already dissolved, the proposal is hosted in the nearest\n// non-dissolved ancestor, so orphans below a dissolved middle DAO remain\n// dissolvable.\n//\n// Dissolution sweeps any remaining treasury balance. A sub-DAO's sweep\n// goes to its parent and destination must be empty; a root DAO has no\n// parent, so a valid destination address is required.\n//\n// Parameters:\n// - daoID: ID of the DAO to dissolve (required)\n// - destination: sweep destination, root DAOs only\nfunc CreateDissolutionProposal(cur realm, daoID uint64, destination address) uint64 {\n\tassertCurrent(cur)\n\n\t// When DAO to dissolve is a SubDAO make sure that proposal is created\n\t// in the parent DAO, or in the nearest non-dissolved ancestor when\n\t// parents were dissolved first.\n\tdao := mustGetDAO(daoID)\n\tdissolveDAO := dao\n\tif parent := dao.Parent(); parent != nil {\n\t\tfor parent.IsDeleted() \u0026\u0026 parent.Parent() != nil {\n\t\t\tparent = parent.Parent()\n\t\t}\n\t\tdao = parent\n\t}\n\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\t// The host (nearest live ancestor) gates and votes the proposal, while\n\t// the definition operates on the dissolved descendant carried in args.\n\treturn mustPropose(dao, caller, kindDissolve, dissolveArgs{dissolveDAO, destination})\n}\n\n// CreateTreasurySpendProposal creates a new proposal to send coins from\n// the DAO's own treasury (docs/CONSTITUTION.md :1542-1543).\n//\n// Parameters:\n// - daoID: ID of the DAO whose treasury is spent (required)\n// - to: recipient address (required)\n// - denom: coin denomination, e.g. \"ugnot\" (required)\n// - amount: coin amount, must be positive (required)\nfunc CreateTreasurySpendProposal(cur realm, daoID uint64, to address, denom string, amount int64) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\targs := treasurySpendArgs{dao, to, chain.NewCoin(denom, amount)}\n\treturn mustPropose(dao, caller, kindTreasurySpend, args)\n}\n\n// CreateTreasuryClawbackProposal creates a new proposal for an ancestor\n// DAO to sweep a descendant DAO's full treasury balance to the target's\n// parent (docs/CONSTITUTION.md :1507). The proposing DAO must be a\n// proper ancestor of the target; a target's own options can never block\n// an ancestor's clawback.\n//\n// Parameters:\n// - daoID: ID of the proposing ancestor DAO (required)\n// - targetID: ID of the descendant DAO to claw back (required)\nfunc CreateTreasuryClawbackProposal(cur realm, daoID, targetID uint64) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\ttarget := mustGetDAO(targetID)\n\treturn mustPropose(dao, caller, kindTreasuryClawback, treasuryClawbackArgs{dao, target})\n}\n\n// CreateTreasuryFreezeProposal creates a new proposal for an ancestor DAO\n// to freeze or unfreeze a descendant DAO's treasury. While frozen, no\n// treasury spend can execute. Only a proper ancestor can unfreeze — the\n// frozen DAO's own council cannot.\n//\n// Parameters:\n// - daoID: ID of the proposing ancestor DAO (required)\n// - targetID: ID of the descendant DAO to freeze or unfreeze (required)\n// - frozen: true to freeze the target's treasury, false to unfreeze\nfunc CreateTreasuryFreezeProposal(cur realm, daoID, targetID uint64, frozen bool) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\ttarget := mustGetDAO(targetID)\n\treturn mustPropose(dao, caller, kindTreasuryFreeze, treasuryFreezeArgs{dao, target, frozen})\n}\n\n// CreateExecutionProposal creates a proposal that runs an arbitrary\n// ExecFunc as the DAO's own sub on approval, through the realm's execution\n// kind.\n//\n// The execution kind is opt-in: it is not seeded on new DAOs and must be\n// registered first through a supermajority CreateRegisterKindProposal.\n//\n// Freeze policy: an execution proposal moves value under the DAO's own\n// authority, so it is subject to the treasury freeze exactly like a spend.\n// This wrapper fails fast when the treasury is already frozen, and the\n// definition re-checks at Execute (so a freeze landing after the proposal\n// passed fails it cleanly, StatusFailed, no funds leaving). An ancestor's\n// clawback/dissolution is a separate power and is not blocked by freeze.\n//\n// Sharp edges (known limitations):\n//   - The fn closure cannot be encoded in a CLI transaction, so this wrapper\n//     is reachable only from a PERSISTENT realm that imports this one and is\n//     a council member of the DAO (a realm-in-council). The closure must be\n//     authored in that realm so it survives Propose→Execute; a `maketx run`\n//     script's closure does not persist and cannot execute later.\n//   - A closure that panics or runs out of gas aborts the whole Execute tx, so\n//     the proposal is stuck Active (every retry re-aborts) and can never\n//     finalize. The only recovery is dissolving the DAO (Dissolve dismisses\n//     in-flight proposals). Author closures that return an error instead of\n//     panicking so a bad execution fails cleanly (StatusFailed) and releases.\n//\n// Parameters:\n// - daoID: ID of the DAO (required)\n// - title: proposal title (raw text, escaped when rendered)\n// - body: proposal body (raw text, escaped when rendered)\n// - fn: the closure executed on approval (required, non-nil)\nfunc CreateExecutionProposal(cur realm, daoID uint64, title, body string, fn commondao.ExecFunc) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\t// Opt-in gate: refuse unless the DAO registered the execution kind.\n\t// Without this, arbitrary code execution would ride on a name a DAO\n\t// never opted into. Propose also rejects an unregistered kind, but this\n\t// fails fast with a clear message before any definition is built.\n\tassertKindRegistered(dao, kindExecution)\n\n\t// Freeze gate (intentional defense in depth): a frozen DAO cannot initiate\n\t// any treasury movement, so refuse up front here even though the\n\t// definition's Validate re-checks the same flag at create and at execute.\n\t// Redundant on purpose — two independent layers on the \"no funds leave a\n\t// frozen DAO\" invariant. Without it an execution proposal could drain a\n\t// frozen DAO's own treasury, defeating an ancestor's freeze.\n\tif dao.IsTreasuryFrozen() {\n\t\tpanic(errTreasuryFrozen)\n\t}\n\n\treturn mustPropose(dao, caller, kindExecution, executionArgs{title: title, body: body, fn: fn})\n}\n\n// CreateRegisterKindProposal creates a proposal to register one of the\n// realm's catalog proposal kinds on a DAO by name, through the permanent\n// manage-kinds kind (e.g. register \"execution\").\n//\n// The proposal is hosted and voted in the DAO itself and decided by\n// supermajority; on approval the named catalog kind is registered, so new\n// proposals of that kind can be created. The manage-kinds kind is seeded\n// on every DAO, so this path is always available.\n//\n// Parameters:\n// - daoID: ID of the DAO (required)\n// - kindName: name of the catalog proposal kind to register (required)\nfunc CreateRegisterKindProposal(cur realm, daoID uint64, kindName string) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\treturn mustPropose(dao, caller, kindManageKinds, manageKindsProposal{dao: dao, name: kindName})\n}\n\n// CreateDeregisterKindProposal creates a proposal to deregister a proposal\n// kind from a DAO by name, through the permanent manage-kinds kind.\n//\n// The proposal is hosted and voted in the DAO itself and decided by\n// supermajority; on approval the kind is deregistered, which blocks new\n// proposals of that kind while in-flight ones still vote and execute. The\n// manage-kinds kind itself cannot be deregistered, so a DAO always keeps\n// the ability to manage its kind set (and to re-register a catalog kind by\n// name).\n//\n// Parameters:\n// - daoID: ID of the DAO (required)\n// - kindName: name of the proposal kind to deregister (required)\nfunc CreateDeregisterKindProposal(cur realm, daoID uint64, kindName string) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\treturn mustPropose(dao, caller, kindManageKinds, manageKindsProposal{dao: dao, remove: true, name: kindName})\n}\n\n// CreateAmendBylawsProposal creates a proposal to add, amend or remove one\n// of the DAO's bylaws documents with a verifiable diff patch (see\n// gno.land/p/nt/bylaws/v0). The mandates/ folder is reserved: the\n// Constitution grants a council self-power over its Bylaws only, so\n// mandates change from above (creation or an ancestor's amendment — not\n// implemented yet), never through this proposal.\n// The payload is an encoded patch — build it with\n// AmendBylawsPayload (e.g. through a vm/qeval query) or with\n// bylaws.Diff(...).Encode() from a realm. The patch pins the sha256 of the\n// document text it was diffed against, so an amendment racing a concurrent\n// change to the same document fails cleanly instead of clobbering it; a\n// patch already stale at creation is rejected here. Amendments are decided\n// by supermajority — the default council rule; the Constitution names no\n// special threshold for a council amending its own documents.\n//\n// Parameters:\n// - daoID: ID of the DAO (required)\n// - payload: encoded bylaws patch (required)\nfunc CreateAmendBylawsProposal(cur realm, daoID uint64, payload string) uint64 {\n\tassertCurrent(cur)\n\n\tdao := mustGetDAO(daoID)\n\tcaller := cur.Previous().Address()\n\tassertCallerIsCouncilMember(caller, dao)\n\n\tpatch, err := bylaws.DecodePatch(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn mustPropose(dao, caller, kindAmendBylaws, amendBylawsProposal{\n\t\tdaoID: daoID,\n\t\tset:   bylawsOf(daoID),\n\t\tpatch: patch,\n\t})\n}\n\n// AmendBylawsPayload builds the CreateAmendBylawsProposal payload that\n// changes a DAO's document at path to the proposed text: a new path adds a\n// document, empty proposed text removes one. It diffs against the\n// document's current text and pins its hash, so build the payload fresh\n// (e.g. through a vm/qeval query) and propose promptly — a payload built\n// against superseded text is rejected. Read-only.\nfunc AmendBylawsPayload(daoID uint64, path, proposed string) string {\n\tmustGetDAO(daoID)\n\n\tvar (\n\t\tcur    string\n\t\texists bool\n\t)\n\tif set := bylawsView(daoID); set != nil {\n\t\tcur, exists = set.Get(path)\n\t}\n\n\tp, err := bylaws.DiffTexts(path, cur, proposed, exists)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn p.Encode()\n}\n\n// assertKindRegistered panics unless a proposal kind is registered on the\n// DAO. Used to gate the opt-in propose paths so they work only after the DAO\n// registered the kind through governance.\nfunc assertKindRegistered(dao *commondao.CommonDAO, name string) {\n\tif !dao.HasKind(name) {\n\t\tpanic(\"proposal kind is not registered: \" + name)\n\t}\n}\n\n// mustPropose submits a proposal through one of the DAO's registered\n// proposal kinds and validates it for the current state, panicking on any\n// error. Validation also reruns inside Execute, so this only fails fast at\n// creation.\nfunc mustPropose(dao *commondao.CommonDAO, caller address, kind string, args any) uint64 {\n\tp, err := dao.Propose(caller, kind, args)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = p.Validate(); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn p.ID()\n}\n\n// parseAddresses parses a newline separated list of addresses,\n// deduplicated, panicking on invalid entries.\nfunc parseAddresses(s string) []address {\n\tvar addrs []address\n\tfor _, raw := range strings.Split(s, \"\\n\") {\n\t\traw = strings.TrimSpace(raw)\n\t\tif raw == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\taddr := address(raw)\n\t\tif !addr.IsValid() {\n\t\t\tpanic(\"invalid address: \" + addr.String())\n\t\t}\n\n\t\tif !containsAddress(addrs, addr) {\n\t\t\taddrs = append(addrs, addr)\n\t\t}\n\t}\n\treturn addrs\n}\n\n// containsAddress checks if an address is present in a list.\nfunc containsAddress(addrs []address, addr address) bool {\n\tfor _, a := range addrs {\n\t\tif a == addr {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"},{"name":"reentrancy.gno","body":"package commondao\n\n// executing is this realm's GLOBAL re-entrancy latch, the outer of two\n// complementary layers. It is set while a proposal executor is running\n// (inside the public Execute) and rejects any nested Execute — an executor\n// must never trigger another execution, whether of the same DAO or a\n// different one, directly or by crossing back in as its DAO.\n//\n// The two layers guard different invariants and neither subsumes the other:\n//\n//   - The /p/ CommonDAO carries per-DAO `executing` / `proposing` FIELDS\n//     (see the package's commondao.gno). Being fields on the owning DAO\n//     object, they are writable where a mutable /p/ global is not, so they\n//     travel with a standalone /p/ consumer that never wrote a realm-global\n//     latch: they give every consumer same-DAO re-entrancy protection (a\n//     nested Execute or Propose on the SAME DAO).\n//   - This realm-global bool adds what a per-DAO field structurally cannot:\n//     it enforces one-executor-per-transaction across ALL DAOs, closing the\n//     cross-DAO straddle a per-DAO latch misses — the ancestor-hosted\n//     dissolution/clawback case, where an executor running under DAO A's\n//     Execute nests an Execute that deletes a DIFFERENT DAO out from under\n//     A. A latch keyed on the executing DAO never fires there; a target\n//     latch would demand a scattered check at every DAO-mutating executor.\n//     The single global bool makes \"one executor per tx\" a local,\n//     unforgettable invariant instead, and also shuts the conditional-\n//     execution \"free option\" (nest a different DAO's Execute, observe\n//     in-tx, panic to revert).\n//\n// It is realm module state: a mutable /p/ package global is forbidden\n// (writing one panics the borrow/stamping rule), and the latch must be\n// writable. This global is the realm's, complementing — not replacing — the\n// /p/ per-DAO fields.\n//\n// Vote / Create* / Withdraw / Resign are deliberately NOT latched: no executor\n// re-enters them, legitimate executors need them (sub-DAO creation, the\n// dissolution sweep), and a proposal executor acting as its DAO in ANOTHER DAO\n// (e.g. casting a council vote) rides those paths.\n//\n// A rejected nested Execute panics. Thrown across the cross() boundary the\n// re-entrant call arrived through, that aborts the whole transaction.\n//\n// The deferred leaveExecute lowers the flag on normal returns (and on any\n// same-transaction recovered panic). Cross-transaction safety does NOT rely on\n// that defer — a rejected re-entry aborts the transaction, and the aborted\n// transaction's realm writes (including this flag) are never committed, so a\n// later transaction can never observe it stuck true.\nvar executing bool\n\n// enterExecute raises the re-entrancy latch, panicking if it is already raised\n// (i.e. this Execute is nested inside another). Pair with a deferred\n// leaveExecute.\nfunc enterExecute() {\n\tif executing {\n\t\tpanic(\"commondao: re-entrant Execute is not allowed\")\n\t}\n\texecuting = true\n}\n\n// leaveExecute lowers the re-entrancy latch.\nfunc leaveExecute() {\n\texecuting = false\n}\n"},{"name":"render.gno","body":"package commondao\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/jeronimoalbi/pager/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/nt/addrset/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\t\"gno.land/r/sys/users\"\n)\n\nconst dateFormat = \"Mon, 02 Jan 2006 03:04pm MST\"\n\n// trustedMarkdownBody marks proposal definitions whose Body returns\n// markdown the definition assembled itself (escaping any embedded user\n// fields with md.EscapeText). Those bodies are rendered verbatim. Every\n// other body — including the execution kind, whose Body is the proposer's\n// raw text — is treated as user-supplied and escaped by the renderer. A\n// definition from an imported package cannot implement this realm-local\n// marker either, so it is escaped too. The render layer is the single escape\n// point: definitions return raw text and opt out only when they render their\n// own markup.\ntype trustedMarkdownBody interface {\n\tisTrustedMarkdownBody()\n}\n\nfunc Render(path string) string {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"\", renderHome)\n\trouter.HandleFunc(\"{daoID}\", renderDAO)\n\trouter.HandleFunc(\"{daoID}/settings\", renderSettings)\n\trouter.HandleFunc(\"{daoID}/bylaws\", renderBylaws)\n\trouter.HandleFunc(\"{daoID}/proposals\", renderProposalsList)\n\trouter.HandleFunc(\"{daoID}/proposals/{proposalID}\", renderProposal)\n\trouter.HandleFunc(\"{daoID}/proposals/{proposalID}/vote/{address}\", renderProposalVote)\n\treturn router.Render(path)\n}\n\nfunc renderHome(res *mux.ResponseWriter, req *mux.Request) {\n\tres.Write(md.H1(\"Common DAO\"))\n\tres.Write(md.HorizontalRule())\n\tres.Write(ufmt.Sprintf(\n\t\tmd.Paragraph(\"This realm can be used to create CommonDAO instances based on %s package.\"),\n\t\tmd.Link(\"commondao\", \"/p/nt/commondao/v0/\"),\n\t))\n\n\t// Nothing listed: render just the header. pager.New reports a total of\n\t// zero as \"invalid page number\" for every page including page 1, which\n\t// its own Picker links to.\n\tif listed.Size() == 0 {\n\t\treturn\n\t}\n\n\t// Paginate over the LISTED set, not every DAO: listing is opt-in and\n\t// off by default, so a window over all DAOs could be entirely unlisted\n\t// — rendering an empty page that also drops the pager (the len==0 guard\n\t// below), stranding the listed DAOs on unreachable later pages.\n\tpages, err := pager.New(req.RawPath, listed.Size(), pager.WithPageSize(10))\n\tif err != nil {\n\t\t// Its own block: an unterminated error line glues itself onto\n\t\t// whatever is written next (renderCouncil returns into renderDAO,\n\t\t// which goes straight on to write the Treasury heading).\n\t\tres.Write(md.Paragraph(md.EscapeText(err.Error())))\n\t\treturn\n\t}\n\n\tvar items []string\n\tlisted.ReverseIterateByOffset(pages.Offset(), pages.PageSize(), func(_ string, v any) bool {\n\t\tif dao := getDAO(v.(uint64)); dao != nil {\n\t\t\titems = append(items, md.Link(dao.Name(), daoURL(dao.ID())))\n\t\t}\n\t\treturn false\n\t})\n\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\n\tres.Write(md.Paragraph(\"Here is a list of some of the DAOs that were created:\"))\n\tres.Write(md.Paragraph(md.BulletList(items)))\n\n\tif pages.HasPages() {\n\t\tres.Write(md.Paragraph(pager.Picker(pages)))\n\t}\n}\n\nfunc renderDAO(res *mux.ResponseWriter, req *mux.Request) {\n\tdao := mustGetDAOFromRequest(req)\n\n\t// Render header messages\n\tif dao.IsDeleted() {\n\t\tres.Write(md.Blockquote(\"⚠ This DAO has been dissolved\"))\n\t\t// A dissolved DAO with no live proper ancestor can never move funds\n\t\t// again (its own council is gone and no ancestor can claw back), so\n\t\t// warn that late deposits to its treasury address are unrecoverable.\n\t\tif !hasLiveProperAncestor(dao) {\n\t\t\tres.Write(md.Blockquote(\"⚠ No live ancestor DAO remains: coins sent to this treasury address can no longer be recovered.\"))\n\t\t}\n\t}\n\n\t// Render header (Charter: purpose is required, description optional)\n\tres.Write(md.H1(md.EscapeText(dao.Name())))\n\tres.Write(md.Paragraph(md.Bold(\"Purpose:\") + \" \" + md.EscapeText(dao.Purpose())))\n\tif desc := dao.Description(); desc != \"\" {\n\t\tres.Write(md.Paragraph(md.EscapeText(desc)))\n\t}\n\n\t// Render main menu\n\tmenu := []string{\n\t\tmd.Link(\"View Proposals\", daoProposalsURL(dao.ID())),\n\t\tmd.Link(\"View Settings\", settingsURL(dao.ID())),\n\t}\n\n\tif set := bylawsView(dao.ID()); set != nil \u0026\u0026 set.Size() \u003e 0 {\n\t\tmenu = append(menu, md.Link(\"View Bylaws \u0026 Mandates\", bylawsURL(dao.ID())))\n\t}\n\n\tif parentDAO := dao.Parent(); parentDAO != nil {\n\t\tmenu = append(menu, md.Link(\"Go to Parent DAO\", daoURL(parentDAO.ID())))\n\t}\n\n\tres.Write(md.Paragraph(strings.Join(menu, \" • \")))\n\tres.Write(md.HorizontalRule())\n\n\t// Render council\n\tcouncil := dao.Council()\n\tif council.Size() == 0 {\n\t\tres.Write(md.Paragraph(md.Bold(\"⚠ The DAO has no council members\")))\n\t} else {\n\t\trenderCouncil(res, req.RawPath, council)\n\t}\n\n\trenderTreasury(res, dao)\n\n\t// Render organization tree\n\tif dao.ChildrenCount() \u003e 0 {\n\t\tr := parseRealmPath(req.RawPath)\n\t\tdissolvedVisible := r.Query.Has(\"dissolved\") || dao.IsDeleted()\n\t\tres.Write(md.H2(\"Tree\"))\n\n\t\t// Render toggle only when DAO is not dissolved,\n\t\t// otherwise render the whole tree when DAO is dissolved\n\t\tif !dao.IsDeleted() {\n\t\t\tvar toggleLink string\n\t\t\tif dissolvedVisible {\n\t\t\t\tr.Query.Del(\"dissolved\")\n\t\t\t\ttoggleLink = md.Link(\"hide\", r.String())\n\t\t\t} else {\n\t\t\t\tr.Query.Add(\"dissolved\", \"\")\n\t\t\t\ttoggleLink = md.Link(\"show\", r.String())\n\t\t\t}\n\n\t\t\tres.Write(md.Paragraph(\"Dissolved: \" + toggleLink))\n\t\t}\n\n\t\trenderTree(res, dao, \"\", dissolvedVisible)\n\t}\n\n\t// Render latest proposals\n\tif dao.ActiveProposalsSize() \u003e 0 {\n\t\tres.Write(md.H2(\"Latest Proposals\"))\n\t\tdao.IterateActiveProposals(0, 3, true, func(p *commondao.Proposal) bool {\n\t\t\trenderProposalsListItem(res, dao, p)\n\t\t\treturn false\n\t\t})\n\t}\n\n\t// Render proposal creation links\n\tif !dao.IsDeleted() {\n\t\trenderCreateProposalSection(dao, res)\n\t}\n}\n\nfunc renderCreateProposalSection(dao *commondao.CommonDAO, res *mux.ResponseWriter) {\n\tdaoID := dao.ID()\n\n\t// One entry per link-encodable catalog kind, in display order (the\n\t// execution kind has no entry: its closure cannot be encoded in a\n\t// help link). Only the kinds registered on the DAO are rendered.\n\tentries := []struct {\n\t\tkind string\n\t\ttext string\n\t}{\n\t\t{\n\t\t\tkindText,\n\t\t\tmd.Paragraph(textProposalLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal is also known as text proposal which can be used for example \"+\n\t\t\t\t\t\t\"to get consensus on initiatives without actually making any change on-chain.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindCouncilUpdate,\n\t\t\tmd.Paragraph(updateCouncilLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal can be used to add new council members to this DAO \"+\n\t\t\t\t\t\t\"and also to remove existing ones.\",\n\t\t\t\t) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"A single proposal allows new council members to be added and any number of existing ones \"+\n\t\t\t\t\t\t\"removed within the same proposal.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindAncestorCouncilUpdate,\n\t\t\tmd.Paragraph(ancestorCouncilUpdateLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal lets this DAO, as an ancestor, add or \"+\n\t\t\t\t\t\t\"remove council members of one of its descendant DAOs — the \"+\n\t\t\t\t\t\t\"rescue path for a descendant whose council is stuck or empty.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindDissolve,\n\t\t\tmd.Paragraph(dissolveSubDAOLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal can be used to dissolve DAOs and SubDAOs.\",\n\t\t\t\t) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"Dissolving a DAO can't be undone, once the dissolution proposal passes \"+\n\t\t\t\t\t\t\"and is executed DAO will be readonly.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindTreasurySpend,\n\t\t\tmd.Paragraph(treasurySpendLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal sends coins from the DAO's own treasury \"+\n\t\t\t\t\t\t\"when it passes and is executed.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindTreasuryClawback,\n\t\t\tmd.Paragraph(treasuryClawbackLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal sweeps a descendant DAO's treasury to \"+\n\t\t\t\t\t\t\"the descendant's parent DAO.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindTreasuryFreeze,\n\t\t\tmd.Paragraph(treasuryFreezeLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal freezes or unfreezes a descendant DAO's \"+\n\t\t\t\t\t\t\"treasury. While frozen, no funds can leave the treasury.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindSubDAO,\n\t\t\tmd.Paragraph(newSubDAOLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal is used to create SubDAOs, \"+\n\t\t\t\t\t\t\"which are used to create tree based DAOs.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindManageKinds,\n\t\t\tmd.Paragraph(registerKindLink(daoID)+\" • \"+deregisterKindLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal registers one of the realm's catalog \"+\n\t\t\t\t\t\t\"proposal kinds on this DAO by name, or deregisters a kind. \"+\n\t\t\t\t\t\t\"Deregistering a kind blocks new proposals of that kind while \"+\n\t\t\t\t\t\t\"in-flight ones still vote and execute. The manage-kinds kind \"+\n\t\t\t\t\t\t\"itself cannot be deregistered.\",\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tkindAmendBylaws,\n\t\t\tmd.Paragraph(amendBylawsLink(daoID)) +\n\t\t\t\tmd.Paragraph(\n\t\t\t\t\t\"This type of proposal adds, amends or removes one of the DAO's \"+\n\t\t\t\t\t\t\"bylaws documents with a diff patch pinned to the current \"+\n\t\t\t\t\t\t\"document text (the mandates folder is reserved: mandates are \"+\n\t\t\t\t\t\t\"set from above, not by the council). Build the payload with \"+\n\t\t\t\t\t\t\"the AmendBylawsPayload query function.\",\n\t\t\t\t),\n\t\t},\n\t}\n\n\tvar cols []string\n\tfor _, e := range entries {\n\t\tif dao.HasKind(e.kind) {\n\t\t\tcols = append(cols, e.text)\n\t\t}\n\t}\n\n\tif len(cols) == 0 {\n\t\treturn\n\t}\n\n\tres.Write(md.H2(\"Create Proposal\"))\n\tres.Write(md.Paragraph(\"These are the proposal supported by this DAO:\"))\n\t// Wrap at 3 per row: gnoweb renders at most 4 columns per row, and a\n\t// DAO with every kind registered has up to ten cards.\n\tres.Write(md.ColumnsN(cols, 3, false))\n}\n\nfunc renderTreasury(res *mux.ResponseWriter, dao *commondao.CommonDAO) {\n\tres.Write(md.H2(\"Treasury\"))\n\tres.Write(md.BulletItem(\"Address: \" + md.EscapeText(string(dao.Address()))))\n\n\tbalance := treasuryBalance(dao)\n\tif balance.IsZero() {\n\t\tres.Write(md.BulletItem(\"Balance: (empty)\"))\n\t} else {\n\t\tres.Write(md.BulletItem(\"Balance: \" + md.EscapeText(balance.String())))\n\t}\n\n\tif dao.IsTreasuryFrozen() {\n\t\t// Blockquote, not a bold paragraph: a paragraph directly after the\n\t\t// balance bullet is a lazy continuation of that list item, so the\n\t\t// warning would render inside the bullet instead of as its own\n\t\t// block. Matches the dissolved-DAO banners.\n\t\tfrozen := \"⚠ The treasury is frozen: no proposal can move funds until a proper ancestor DAO unfreezes it.\"\n\t\tif dao.HasKind(kindExecution) {\n\t\t\t// Freeze gates the realm's own spending paths. A closure from a\n\t\t\t// past execution proposal may hold a retained banker, which\n\t\t\t// reaches the bank keeper without passing through them.\n\t\t\tfrozen += \" This DAO has the execution kind registered, so a\" +\n\t\t\t\t\" capability retained by an earlier execution proposal could\" +\n\t\t\t\t\" still move funds; freeze alone is not containment here.\"\n\t\t}\n\t\tres.Write(md.Blockquote(frozen))\n\t}\n}\n\nfunc renderCouncil(res *mux.ResponseWriter, path string, council *addrset.ReadonlySet) {\n\tpages, err := pager.New(path, council.Size(), pager.WithPageQueryParam(\"members\"), pager.WithPageSize(8))\n\tif err != nil {\n\t\t// Its own block: an unterminated error line glues itself onto\n\t\t// whatever is written next (renderCouncil returns into renderDAO,\n\t\t// which goes straight on to write the Treasury heading).\n\t\tres.Write(md.Paragraph(md.EscapeText(err.Error())))\n\t\treturn\n\t}\n\n\ttable := mdtable.Table{Headers: []string{\"Council\"}}\n\tcouncil.IterateByOffset(pages.Offset(), pages.PageSize(), func(addr address) bool {\n\t\ttable.Append([]string{userLink(addr)})\n\t\treturn false\n\t})\n\n\tres.Write(md.Paragraph(table.String()))\n\n\tif pages.HasPages() {\n\t\tres.Write(md.Paragraph(pager.Picker(pages)))\n\t}\n}\n\nfunc renderTree(res *mux.ResponseWriter, dao *commondao.CommonDAO, indent string, showDissolved bool) {\n\tdaoLink := md.Link(dao.Name(), daoURL(dao.ID()))\n\tif dao.IsDeleted() {\n\t\t// Strikethough dissolved DAO names\n\t\tdaoLink = md.Strikethrough(daoLink)\n\t}\n\n\tres.Write(indent + md.BulletItem(daoLink))\n\n\tindent += \"  \"\n\tdao.IterateChildren(func(subDAO *commondao.CommonDAO) bool {\n\t\tif showDissolved || !subDAO.IsDeleted() {\n\t\t\trenderTree(res, subDAO, indent, showDissolved)\n\t\t}\n\t\treturn false\n\t})\n}\n\nfunc renderSettings(res *mux.ResponseWriter, req *mux.Request) {\n\tdao := mustGetDAOFromRequest(req)\n\n\t// Render header\n\tres.Write(md.H1(md.EscapeText(dao.Name()) + \": Settings\"))\n\n\t// Render main menu\n\tres.Write(md.Paragraph(goToDAOLink(dao.ID())))\n\tres.Write(md.HorizontalRule())\n\n\t// Render info\n\ttable := mdtable.Table{Headers: []string{\"Setting\", \"Value\"}}\n\ttable.Append([]string{\"Listed\", strconv.FormatBool(isListed(dao.ID()))})\n\ttable.Append([]string{\"Max active proposals\", strconv.Itoa(dao.MaxActiveProposals())})\n\ttable.Append([]string{\"Proposal kinds\", md.EscapeText(strings.Join(dao.KindNames(), \", \"))})\n\n\tres.Write(md.H2(\"Info\"))\n\tres.Write(table.String())\n}\n\nfunc renderBylaws(res *mux.ResponseWriter, req *mux.Request) {\n\tdao := mustGetDAOFromRequest(req)\n\n\t// Render header\n\tres.Write(md.H1(md.EscapeText(dao.Name()) + \": Bylaws \u0026 Mandates\"))\n\n\t// Render main menu\n\tres.Write(md.Paragraph(goToDAOLink(dao.ID())))\n\tres.Write(md.HorizontalRule())\n\n\tset := bylawsView(dao.ID())\n\tif set == nil || set.Size() == 0 {\n\t\tres.Write(md.Paragraph(\"This DAO has no bylaws or mandates documents.\"))\n\t\treturn\n\t}\n\n\tpaths := set.List(\"\")\n\tpages, err := pager.New(req.RawPath, len(paths), pager.WithPageSize(5))\n\tif err != nil {\n\t\t// Its own block: an unterminated error line glues itself onto\n\t\t// whatever is written next (renderCouncil returns into renderDAO,\n\t\t// which goes straight on to write the Treasury heading).\n\t\tres.Write(md.Paragraph(md.EscapeText(err.Error())))\n\t\treturn\n\t}\n\n\t// Documents are multi-line plaintext with council-controlled content:\n\t// the path is escaped inline and the text goes through sanitize.Block,\n\t// which preserves paragraph structure (an inline escape would fold the\n\t// whole document to one line) while escaping block-level hazards. The\n\t// hash is what an amendment payload must pin (AmendBylawsPayload reads\n\t// it for you).\n\t// Clamp the offset: pager.New rejects page 0 and pages past the end but\n\t// accepts a negative page, and unlike the tree-backed pagers this one\n\t// indexes a slice — a raw negative offset panics the whole render.\n\tstart := pages.Offset()\n\tif start \u003c 0 {\n\t\tstart = 0\n\t}\n\tfor i := start; i \u003c len(paths) \u0026\u0026 i \u003c start+pages.PageSize(); i++ {\n\t\tpath := paths[i]\n\t\ttext, _ := set.Get(path)\n\t\tres.Write(md.H2(md.EscapeText(path)))\n\t\tres.Write(md.Paragraph(\"sha256: \" + set.Hash(path)))\n\t\tres.Write(sanitize.Block(text))\n\t}\n\n\tif pages.HasPages() {\n\t\tres.Write(md.Paragraph(pager.Picker(pages)))\n\t}\n}\n\nfunc renderProposalsList(res *mux.ResponseWriter, req *mux.Request) {\n\tdao := mustGetDAOFromRequest(req)\n\n\t// Render header\n\tres.Write(md.H1(md.EscapeText(dao.Name()) + \": Proposals\"))\n\n\t// Render main menu\n\tres.Write(md.Paragraph(goToDAOLink(dao.ID())))\n\tres.Write(md.HorizontalRule())\n\n\t// Render proposals\n\tif dao.ActiveProposalsSize() == 0 \u0026\u0026 dao.FinishedProposalsSize() == 0 {\n\t\tres.Write(md.Paragraph(md.Bold(\"⚠ The DAO has no proposals\")))\n\t\treturn\n\t}\n\n\tsize := dao.ActiveProposalsSize()\n\titerate := dao.IterateActiveProposals\n\trenderFinished := req.Query.Has(\"finished\")\n\tif renderFinished {\n\t\tsize = dao.FinishedProposalsSize()\n\t\titerate = dao.IterateFinishedProposals\n\t}\n\n\tvar viewLink, sortLink string\n\n\tr := parseRealmPath(req.RawPath)\n\tr.Query.Del(\"page\") // a view switch resets to page 1 (the other view may have fewer pages)\n\tif renderFinished {\n\t\tr.Query.Del(\"finished\")\n\t\tviewLink = md.Link(\"active\", r.String())\n\t} else {\n\t\tr.Query.Add(\"finished\", \"\")\n\t\tviewLink = md.Link(\"finished\", r.String())\n\t}\n\n\tr = parseRealmPath(req.RawPath)\n\tr.Query.Del(\"page\") // a sort switch resets to page 1\n\treverseSort := r.Query.Get(\"order\") != \"asc\"\n\tif reverseSort {\n\t\tr.Query.Set(\"order\", \"asc\")\n\t\tsortLink = md.Link(\"oldest\", r.String())\n\t} else {\n\t\tr.Query.Set(\"order\", \"desc\")\n\t\tsortLink = md.Link(\"newest\", r.String())\n\t}\n\n\tres.Write(md.Paragraph(\"View: \" + viewLink + \" • Sort by: \" + sortLink))\n\n\t// The empty view is handled before the pager: pager.New reports a total\n\t// of zero as \"invalid page number\" for every page including page 1,\n\t// which the other view's Picker links to — so switching into an empty\n\t// view would answer with an error instead of the empty-state message.\n\tif size == 0 {\n\t\tif renderFinished {\n\t\t\tres.Write(md.Paragraph(\"Currently there are no finished proposals\"))\n\t\t} else {\n\t\t\tres.Write(md.Paragraph(\"Currently there are no active proposals\"))\n\t\t}\n\t\treturn\n\t}\n\n\tpages, err := pager.New(req.RawPath, size, pager.WithPageSize(8))\n\tif err != nil {\n\t\tres.Write(md.Paragraph(md.EscapeText(err.Error())))\n\t\treturn\n\t}\n\n\titerate(pages.Offset(), pages.PageSize(), reverseSort, func(p *commondao.Proposal) bool {\n\t\trenderProposalsListItem(res, dao, p)\n\t\treturn false\n\t})\n\n\t// Render pager\n\tif pages.HasPages() {\n\t\tres.Write(md.HorizontalRule())\n\t\tres.Write(pager.Picker(pages))\n\t}\n}\n\nfunc renderProposalsListItem(res *mux.ResponseWriter, dao *commondao.CommonDAO, p *commondao.Proposal) {\n\tdef := p.Definition()\n\trecord := p.VotingRecord()\n\n\t// Render title\n\tres.Write(ufmt.Sprintf(\"**[#%d %s](%s)**  \\n\", p.ID(), md.EscapeText(def.Title()), proposalURL(dao.ID(), p.ID())))\n\n\t// Render details\n\tres.Write(ufmt.Sprintf(\"Created by %s  \\n\", userLink(p.Creator())))\n\tres.Write(ufmt.Sprintf(\"Voting ends on %s  \\n\", p.VotingDeadline().UTC().Format(dateFormat)))\n\n\t// Render status\n\tstatus := []string{\n\t\tufmt.Sprintf(\"Votes: **%d**\", record.Size()),\n\t\tufmt.Sprintf(\"Status: **%s**\", string(p.Status())),\n\t}\n\n\t// Render actions\n\tif isVotingPeriodActive(p) {\n\t\tstatus = append(status, voteLink(dao.ID(), p.ID()))\n\t}\n\n\tif isExecutionAllowed(p) {\n\t\tstatus = append(status, executeLink(dao.ID(), p.ID()))\n\t}\n\n\tres.Write(md.Paragraph(strings.Join(status, \" • \")))\n}\n\nfunc renderProposal(res *mux.ResponseWriter, req *mux.Request) {\n\tdao := mustGetDAOFromRequest(req)\n\tp := mustGetProposalFromRequest(req, dao)\n\n\t// Check that proposal has no issues\n\tif err := p.Validate(); err != nil {\n\t\t// Escape the error text (the bold label is ours): a definition's\n\t\t// Validate may embed user-supplied values in its message.\n\t\tres.Write(md.Blockquote(\"⚠ **ERROR**: \" + md.EscapeText(err.Error())))\n\t}\n\n\tvotingActive := isVotingPeriodActive(p)\n\tif votingActive {\n\t\tres.Write(\n\t\t\tmd.Blockquote(\"Voting ends on \" + md.Bold(p.VotingDeadline().UTC().Format(dateFormat))),\n\t\t)\n\t}\n\n\tdef := p.Definition()\n\n\t// Render header\n\tres.Write(md.H1(\"#\" + strconv.FormatUint(p.ID(), 10) + \" \" + md.EscapeText(def.Title())))\n\n\t// Render main menu\n\titems := []string{goToDAOLink(dao.ID())}\n\tif votingActive {\n\t\titems = append(items, voteLink(dao.ID(), p.ID()))\n\t}\n\n\tif isExecutionAllowed(p) {\n\t\titems = append(items, executeLink(dao.ID(), p.ID()))\n\t}\n\n\tres.Write(md.Paragraph(strings.Join(items, \" • \")))\n\tres.Write(md.HorizontalRule())\n\n\t// Render details\n\tres.Write(md.H2(\"Details\"))\n\tres.Write(md.BulletItem(\"Proposer: \" + userLink(p.Creator())))\n\tres.Write(md.BulletItem(\"Submit Time: \" + p.CreatedAt().UTC().Format(time.RFC1123)))\n\n\trecord := p.VotingRecord()\n\tif p.Status() == commondao.StatusActive {\n\t\t// Vote settles the outcome early — it flips a proposal to passed or\n\t\t// dismissed the moment the tally allows — so while voting is open a\n\t\t// still-active proposal is undecided, and \"pending\" is the honest\n\t\t// label (\"fail\" would read as a prediction of defeat on a proposal\n\t\t// nobody has voted on yet). Once the deadline has passed no further\n\t\t// vote is accepted and Execute's re-tally dismisses an undecided\n\t\t// proposal, so there \"pending\" would be the misleading one.\n\t\t//\n\t\t// The decided arms are reachable in principle: /p/ honors a\n\t\t// non-constant Threshold (see ProposalDefinition.Threshold), though\n\t\t// every definition in this realm returns a constant.\n\t\tswitch p.ExpectedOutcome() {\n\t\tcase commondao.OutcomePassed:\n\t\t\tres.Write(md.BulletItem(\"Expected Outcome: **pass** ☑\"))\n\t\tcase commondao.OutcomeDismissed:\n\t\t\tres.Write(md.BulletItem(\"Expected Outcome: **dismiss** ☒\"))\n\t\tdefault:\n\t\t\tif votingActive {\n\t\t\t\tres.Write(md.BulletItem(\"Expected Outcome: **pending** ⏳\"))\n\t\t\t} else {\n\t\t\t\tres.Write(md.BulletItem(\"Expected Outcome: **dismiss** ☒\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tstatusItem := \"Status: \" + md.Bold(string(p.Status()))\n\tif reason := p.StatusReason(); reason != \"\" {\n\t\tstatusItem += \" • \" + md.Italic(md.EscapeText(reason))\n\t}\n\tres.Write(md.BulletItem(statusItem))\n\n\t// Render proposal body. Bodies are raw user text and escaped here by\n\t// default; only definitions that assemble their own markdown (marked\n\t// trustedMarkdownBody) are rendered verbatim.\n\tif body := def.Body(); body != \"\" {\n\t\tres.Write(md.H2(\"Description\"))\n\t\tif _, trusted := def.(trustedMarkdownBody); !trusted {\n\t\t\t// Inline escape, deliberately: it neutralizes inline markup and\n\t\t\t// links in proposer-supplied text. sanitize.Block would preserve\n\t\t\t// the body's line structure but also its inline links — a\n\t\t\t// phishing vector on a page councils read before voting. The\n\t\t\t// cost is that a multi-line body renders as one line; a\n\t\t\t// structure-preserving fix must escape inline per line rather\n\t\t\t// than switch to Block (see z_10_b, which pins the escaping).\n\t\t\tbody = md.EscapeText(body)\n\t\t}\n\t\tres.Write(md.Paragraph(body))\n\t}\n\n\t// Render voting stats and votes\n\tif record.Size() \u003e 0 {\n\t\trenderProposalStats(res, record)\n\t\trenderProposalVotes(res, req.RawPath, dao, p)\n\t}\n}\n\nfunc renderProposalStats(res *mux.ResponseWriter, record commondao.ReadonlyVotingRecord) {\n\ttotalCount := float64(record.Size())\n\ttable := mdtable.Table{Headers: []string{\"Vote Choices\", \"Percentage of Votes\"}}\n\n\trecord.IterateVotesCount(func(c commondao.VoteChoice, voteCount int) bool {\n\t\t// A changed vote leaves a zeroed counter behind; skip it so the\n\t\t// table shows only choices with live votes.\n\t\tif voteCount == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\tpercentage := float64(voteCount*100) / totalCount\n\t\ttable.Append([]string{md.EscapeText(string(c)), strconv.FormatFloat(percentage, 'f', 2, 64) + \"%\"})\n\t\treturn false\n\t})\n\n\tres.Write(md.H2(\"Stats\"))\n\tres.Write(md.Paragraph(table.String()))\n}\n\nfunc renderProposalVotes(res *mux.ResponseWriter, path string, dao *commondao.CommonDAO, p *commondao.Proposal) {\n\tres.Write(md.H2(\"Votes\")) // Render title here so it appears before any pager errors\n\n\trecord := p.VotingRecord()\n\tpages, err := pager.New(path, record.Size(), pager.WithPageQueryParam(\"votes\"), pager.WithPageSize(5))\n\tif err != nil {\n\t\t// Its own block: an unterminated error line glues itself onto\n\t\t// whatever is written next (renderCouncil returns into renderDAO,\n\t\t// which goes straight on to write the Treasury heading).\n\t\tres.Write(md.Paragraph(md.EscapeText(err.Error())))\n\t\treturn\n\t}\n\n\ttable := mdtable.Table{Headers: []string{\"Users\", \"Votes\"}}\n\trecord.Iterate(pages.Offset(), pages.PageSize(), false, func(v commondao.Vote) bool {\n\t\tvoteDetails := md.Link(string(v.Choice()), voteURL(dao.ID(), p.ID(), v.Address()))\n\t\tif v.Reason() != \"\" {\n\t\t\tvoteDetails += \" with a reason\"\n\t\t}\n\n\t\ttable.Append([]string{userLink(v.Address()), voteDetails})\n\t\treturn false\n\t})\n\n\tres.Write(ufmt.Sprintf(\"Total number of votes: **%d**\\n\", record.Size()))\n\tres.Write(md.Paragraph(table.String()))\n\n\tif pages.HasPages() {\n\t\tres.Write(md.Paragraph(pager.Picker(pages)))\n\t}\n}\n\nfunc renderProposalVote(res *mux.ResponseWriter, req *mux.Request) {\n\t// Resolve the DAO and proposal before validating the address, so a bad\n\t// daoID is reported as such instead of being blamed on the address, and\n\t// write the header first so every branch below is a navigable page\n\t// rather than a bare dead-end string.\n\tdao := mustGetDAOFromRequest(req)\n\tp := mustGetProposalFromRequest(req, dao)\n\n\tlinks := []string{\n\t\tgoToDAOLink(dao.ID()),\n\t\tgoToProposalLink(dao.ID(), p.ID()),\n\t}\n\n\tres.Write(md.H1(ufmt.Sprintf(\"Vote: Proposal #%d\", p.ID())))\n\tres.Write(md.Paragraph(strings.Join(links, \" • \")))\n\tres.Write(md.HorizontalRule())\n\n\tmember := address(req.GetVar(\"address\"))\n\tif !member.IsValid() {\n\t\tres.Write(md.Paragraph(\"Invalid address.\"))\n\t\treturn\n\t}\n\n\tv, found := p.VotingRecord().GetVote(member)\n\tif !found {\n\t\t// Distinguish the two ways a vote can be absent: a member who has\n\t\t// not voted yet is an ordinary state, an outsider is not.\n\t\tif p.Electorate().Has(member) {\n\t\t\tres.Write(md.Paragraph(\"This council member has not voted on this proposal yet.\"))\n\t\t} else {\n\t\t\tres.Write(md.Paragraph(\"This account is not a member of the proposal's electorate.\"))\n\t\t}\n\t\treturn\n\t}\n\n\tres.Write(md.H2(\"Details\"))\n\tres.Write(md.BulletItem(\"User: \" + userLink(v.Address())))\n\tres.Write(md.BulletItem(\"Vote: \" + md.EscapeText(string(v.Choice()))))\n\n\tif v.Reason() != \"\" {\n\t\tres.Write(md.H2(\"Reason\"))\n\t\t// Inline escape for the same reason as a proposal body: a voter's\n\t\t// reason is untrusted text, so its inline links must not render.\n\t\tres.Write(md.Paragraph(md.EscapeText(v.Reason())))\n\t}\n}\n\nfunc mustGetDAOFromRequest(req *mux.Request) *commondao.CommonDAO {\n\trawID := req.GetVar(\"daoID\")\n\tdaoID, err := strconv.ParseUint(rawID, 10, 64)\n\tif err != nil {\n\t\tpanic(\"invalid DAO ID\")\n\t}\n\n\treturn mustGetDAO(daoID)\n}\n\nfunc mustGetProposalFromRequest(req *mux.Request, dao *commondao.CommonDAO) *commondao.Proposal {\n\trawID := req.GetVar(\"proposalID\")\n\tproposalID, err := strconv.ParseUint(rawID, 10, 64)\n\tif err != nil {\n\t\tpanic(\"invalid proposal ID\")\n\t}\n\n\tp := dao.GetProposal(proposalID)\n\tif p == nil {\n\t\tpanic(\"proposal not found\")\n\t}\n\treturn p\n}\n\nfunc parseRealmPath(path string) *realmpath.Request {\n\tr := realmpath.Parse(path)\n\tr.Realm = string(realmLink)\n\treturn r\n}\n\nfunc voteLink(daoID, proposalID uint64) string {\n\treturn md.Link(\"Vote\", realmLink.Call(\n\t\t\"Vote\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"proposalID\", strconv.FormatUint(proposalID, 10),\n\t\t\"vote\", \"\",\n\t\t\"reason\", \"\",\n\t))\n}\n\nfunc executeLink(daoID, proposalID uint64) string {\n\treturn md.Link(\"Execute\", realmLink.Call(\n\t\t\"Execute\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"proposalID\", strconv.FormatUint(proposalID, 10),\n\t))\n}\n\nfunc textProposalLink(daoID uint64) string {\n\treturn ufmt.Sprintf(\"[General Proposal](%s)\", realmLink.Call(\n\t\t\"CreateTextProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"title\", \"\",\n\t\t\"body\", \"\",\n\t\t\"votingDays\", \"7\",\n\t))\n}\n\nfunc updateCouncilLink(daoID uint64) string {\n\treturn md.Link(\"Update Council\", realmLink.Call(\n\t\t\"CreateCouncilUpdateProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"newMembers\", \"\",\n\t\t\"removeMembers\", \"\",\n\t))\n}\n\nfunc ancestorCouncilUpdateLink(daoID uint64) string {\n\treturn md.Link(\"Ancestor Council Update\", realmLink.Call(\n\t\t\"CreateAncestorCouncilUpdateProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"targetID\", \"\",\n\t\t\"newMembers\", \"\",\n\t\t\"removeMembers\", \"\",\n\t))\n}\n\nfunc newSubDAOLink(daoID uint64) string {\n\treturn md.Link(\"New SubDAO\", realmLink.Call(\n\t\t\"CreateSubDAOProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"name\", \"\",\n\t\t\"purpose\", \"\",\n\t\t\"description\", \"\",\n\t\t\"members\", \"\",\n\t))\n}\n\nfunc dissolveSubDAOLink(daoID uint64) string {\n\treturn md.Link(\"Dissolve DAO\", realmLink.Call(\n\t\t\"CreateDissolutionProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"destination\", \"\",\n\t))\n}\n\nfunc treasuryClawbackLink(daoID uint64) string {\n\treturn md.Link(\"Treasury Clawback\", realmLink.Call(\n\t\t\"CreateTreasuryClawbackProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"targetID\", \"\",\n\t))\n}\n\nfunc treasuryFreezeLink(daoID uint64) string {\n\treturn md.Link(\"Treasury Freeze\", realmLink.Call(\n\t\t\"CreateTreasuryFreezeProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"targetID\", \"\",\n\t\t\"frozen\", \"true\",\n\t))\n}\n\nfunc treasurySpendLink(daoID uint64) string {\n\treturn md.Link(\"Treasury Spend\", realmLink.Call(\n\t\t\"CreateTreasurySpendProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"to\", \"\",\n\t\t\"denom\", \"ugnot\",\n\t\t\"amount\", \"\",\n\t))\n}\n\nfunc registerKindLink(daoID uint64) string {\n\treturn md.Link(\"Register Proposal Kind\", realmLink.Call(\n\t\t\"CreateRegisterKindProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"kindName\", \"\",\n\t))\n}\n\nfunc deregisterKindLink(daoID uint64) string {\n\treturn md.Link(\"Deregister Proposal Kind\", realmLink.Call(\n\t\t\"CreateDeregisterKindProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"kindName\", \"\",\n\t))\n}\n\nfunc amendBylawsLink(daoID uint64) string {\n\treturn md.Link(\"Amend Bylaws\", realmLink.Call(\n\t\t\"CreateAmendBylawsProposal\",\n\t\t\"daoID\", strconv.FormatUint(daoID, 10),\n\t\t\"payload\", \"\",\n\t))\n}\n\nfunc goToDAOLink(daoID uint64) string {\n\treturn md.Link(\"Go to DAO\", daoURL(daoID))\n}\n\nfunc goToProposalLink(daoID, proposalID uint64) string {\n\treturn md.Link(\"Go to Proposal\", proposalURL(daoID, proposalID))\n}\n\nfunc userLink(addr address) string {\n\tuser := users.ResolveAddress(addr)\n\tif user != nil {\n\t\treturn user.RenderLink(\"\")\n\t}\n\treturn addr.String()\n}\n\nfunc isVotingPeriodActive(p *commondao.Proposal) bool {\n\treturn p.Status() == commondao.StatusActive \u0026\u0026 time.Now().Before(p.VotingDeadline())\n}\n\nfunc isExecutionAllowed(p *commondao.Proposal) bool {\n\t// Early passed proposals can be executed right away; active proposals\n\t// can be finalized once their voting deadline passes.\n\tif p.Status() == commondao.StatusPassed {\n\t\treturn true\n\t}\n\treturn p.Status() == commondao.StatusActive \u0026\u0026 !time.Now().Before(p.VotingDeadline())\n}\n"},{"name":"uri.gno","body":"package commondao\n\nimport (\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc currentRealmPath() string {\n\treturn strings.TrimPrefix(string(realmLink), runtime.ChainDomain())\n}\n\nfunc daoURL(daoID uint64) string {\n\tpath := currentRealmPath()\n\treturn ufmt.Sprintf(\"%s:%d\", path, daoID)\n}\n\nfunc settingsURL(daoID uint64) string {\n\tpath := currentRealmPath()\n\treturn ufmt.Sprintf(\"%s:%d/settings\", path, daoID)\n}\n\nfunc daoProposalsURL(daoID uint64) string {\n\tpath := currentRealmPath()\n\treturn ufmt.Sprintf(\"%s:%d/proposals\", path, daoID)\n}\n\nfunc bylawsURL(daoID uint64) string {\n\tpath := currentRealmPath()\n\treturn ufmt.Sprintf(\"%s:%d/bylaws\", path, daoID)\n}\n\nfunc proposalURL(daoID, proposalID uint64) string {\n\tpath := currentRealmPath()\n\treturn ufmt.Sprintf(\"%s:%d/proposals/%d\", path, daoID, proposalID)\n}\n\nfunc voteURL(daoID, proposalID uint64, addr address) string {\n\tpath := currentRealmPath()\n\treturn ufmt.Sprintf(\"%s:%d/proposals/%d/vote/%s\", path, daoID, proposalID, addr)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"init","path":"gno.land/r/sys/users/init","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/users/init\"\ngno = \"0.9\"\n"},{"name":"init.gno","body":"// Package init provides basic user registration.\n//\n// SECURITY: every public function in this package is genesis-only. The\n// realm exists to seed initial users into r/sys/users at chain genesis\n// and to register itself as a controller. After genesis (block height\n// \u003e 0), no caller may use these functions.\n//\n// Without the genesis-only gate, the wide-open `RegisterUser` wrapper\n// would let any EOA land-grab any name (including reserved-sounding\n// names like \"administrator\" or \"vitalik\") to any address — for free,\n// without the namereg/v0 payment, blacklist, or canonical-collision\n// checks. The gate closes that bypass.\n//\n// Post-genesis user registration must go through a whitelisted\n// controller that enforces its own policy (e.g. r/sys/namereg/v0).\npackage init\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/r/sys/users\"\n)\n\n// Bootstrap registers this package as a controller in r/sys/users.\n// Genesis-only via AddControllerAtGenesis's own height==0 gate.\nfunc Bootstrap(cur realm) {\n\tusers.AddControllerAtGenesis(cross(cur), chain.PackageAddress(\"gno.land/r/sys/users/init\"))\n}\n\n// RegisterUser registers a new user in r/sys/users at chain genesis.\n// PANICS if called after genesis (height \u003e 0).\n//\n// Uses RegisterUserIgnoreCanonical: the genesis seed set is curated, and\n// any deliberate confusable reservations (e.g. registering both `vitalik`\n// and `vital1k` to two different addresses) must not abort chain bring-\n// up. Decision #14 (later-wins) applies, so order in genesis_txs.jsonl\n// determines which name owns the canonical pointer when stems collide.\nfunc RegisterUser(cur realm, name string, addr address) {\n\tif runtime.ChainHeight() != 0 {\n\t\tpanic(\"r/sys/users/init.RegisterUser: genesis-only; use a whitelisted controller post-genesis (e.g. r/sys/namereg/v0.Register)\")\n\t}\n\tif err := users.RegisterUserIgnoreCanonical(cross(cur), name, addr); err != nil {\n\t\tpanic(err)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"uint256","path":"gno.land/p/onbloc/uint256/v0","files":[{"name":"LICENSE","body":"BSD 3-Clause License\n\nCopyright 2020 uint256 Authors\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived from\n   this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"name":"README.md","body":"# Fixed size 256-bit math library\n\nThis is a library specialized at replacing the `big.Int` library for math based on 256-bit types.\n\noriginal repository: [uint256](\u003chttps://github.com/holiman/uint256/tree/master\u003e)\n"},{"name":"arithmetic.gno","body":"// arithmetic provides arithmetic operations for Uint objects.\n// This includes basic binary operations such as addition, subtraction, multiplication, division, and modulo operations\n// as well as overflow checks, and negation. These functions are essential for numeric\n// calculations using 256-bit unsigned integers.\npackage uint256\n\nimport (\n\t\"math/bits\"\n)\n\n// Add sets z to the sum x+y\nfunc (z *Uint) Add(x, y *Uint) *Uint {\n\tvar carry uint64\n\tz.arr[0], carry = bits.Add64(x.arr[0], y.arr[0], 0)\n\tz.arr[1], carry = bits.Add64(x.arr[1], y.arr[1], carry)\n\tz.arr[2], carry = bits.Add64(x.arr[2], y.arr[2], carry)\n\tz.arr[3], _ = bits.Add64(x.arr[3], y.arr[3], carry)\n\treturn z\n}\n\n// AddOverflow sets z to the sum x+y, and returns z and whether overflow occurred\nfunc (z *Uint) AddOverflow(x, y *Uint) (*Uint, bool) {\n\tvar carry uint64\n\tz.arr[0], carry = bits.Add64(x.arr[0], y.arr[0], 0)\n\tz.arr[1], carry = bits.Add64(x.arr[1], y.arr[1], carry)\n\tz.arr[2], carry = bits.Add64(x.arr[2], y.arr[2], carry)\n\tz.arr[3], carry = bits.Add64(x.arr[3], y.arr[3], carry)\n\treturn z, carry != 0\n}\n\n// Sub sets z to the difference x-y\nfunc (z *Uint) Sub(x, y *Uint) *Uint {\n\tvar carry uint64\n\tz.arr[0], carry = bits.Sub64(x.arr[0], y.arr[0], 0)\n\tz.arr[1], carry = bits.Sub64(x.arr[1], y.arr[1], carry)\n\tz.arr[2], carry = bits.Sub64(x.arr[2], y.arr[2], carry)\n\tz.arr[3], _ = bits.Sub64(x.arr[3], y.arr[3], carry)\n\treturn z\n}\n\n// SubOverflow sets z to the difference x-y and returns z and true if the operation underflowed\nfunc (z *Uint) SubOverflow(x, y *Uint) (*Uint, bool) {\n\tvar carry uint64\n\tz.arr[0], carry = bits.Sub64(x.arr[0], y.arr[0], 0)\n\tz.arr[1], carry = bits.Sub64(x.arr[1], y.arr[1], carry)\n\tz.arr[2], carry = bits.Sub64(x.arr[2], y.arr[2], carry)\n\tz.arr[3], carry = bits.Sub64(x.arr[3], y.arr[3], carry)\n\treturn z, carry != 0\n}\n\n// Neg returns -x mod 2^256.\nfunc (z *Uint) Neg(x *Uint) *Uint {\n\treturn z.Sub(new(Uint), x)\n}\n\n// commented out for possible overflow\n// Mul sets z to the product x*y\nfunc (z *Uint) Mul(x, y *Uint) *Uint {\n\tvar (\n\t\tres              Uint\n\t\tcarry            uint64\n\t\tres1, res2, res3 uint64\n\t)\n\n\tcarry, res.arr[0] = bits.Mul64(x.arr[0], y.arr[0])\n\tcarry, res1 = umulHop(carry, x.arr[1], y.arr[0])\n\tcarry, res2 = umulHop(carry, x.arr[2], y.arr[0])\n\tres3 = x.arr[3]*y.arr[0] + carry\n\n\tcarry, res.arr[1] = umulHop(res1, x.arr[0], y.arr[1])\n\tcarry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry)\n\tres3 = res3 + x.arr[2]*y.arr[1] + carry\n\n\tcarry, res.arr[2] = umulHop(res2, x.arr[0], y.arr[2])\n\tres3 = res3 + x.arr[1]*y.arr[2] + carry\n\n\tres.arr[3] = res3 + x.arr[0]*y.arr[3]\n\n\treturn z.Set(\u0026res)\n}\n\n// MulOverflow sets z to the product x*y, and returns z and  whether overflow occurred\nfunc (z *Uint) MulOverflow(x, y *Uint) (*Uint, bool) {\n\tp := umul(x, y)\n\tcopy(z.arr[:], p[:4])\n\treturn z, (p[4] | p[5] | p[6] | p[7]) != 0\n}\n\n// commented out for possible overflow\n// Div sets z to the quotient x/y for returns z.\n// If y == 0, z is set to 0\nfunc (z *Uint) Div(x, y *Uint) *Uint {\n\tif y.IsZero() || y.Gt(x) {\n\t\treturn z.Clear()\n\t}\n\tif x.Eq(y) {\n\t\treturn z.SetOne()\n\t}\n\t// Shortcut some cases\n\tif x.IsUint64() {\n\t\treturn z.SetUint64(x.Uint64() / y.Uint64())\n\t}\n\n\t// At this point, we know\n\t// x/y ; x \u003e y \u003e 0\n\n\tvar quot Uint\n\tudivrem(quot.arr[:], x.arr[:], y)\n\treturn z.Set(\u0026quot)\n}\n\n// MulMod calculates the modulo-m multiplication of x and y and\n// returns z.\n// If m == 0, z is set to 0 (OBS: differs from the big.Int)\nfunc (z *Uint) MulMod(x, y, m *Uint) *Uint {\n\tif x.IsZero() || y.IsZero() || m.IsZero() {\n\t\treturn z.Clear()\n\t}\n\tp := umul(x, y)\n\n\tif m.arr[3] != 0 {\n\t\tmu := Reciprocal(m)\n\t\tr := reduce4(p, m, mu)\n\t\treturn z.Set(\u0026r)\n\t}\n\n\tvar (\n\t\tpl Uint\n\t\tph Uint\n\t)\n\n\tpl = Uint{arr: [4]uint64{p[0], p[1], p[2], p[3]}}\n\tph = Uint{arr: [4]uint64{p[4], p[5], p[6], p[7]}}\n\n\t// If the multiplication is within 256 bits use Mod().\n\tif ph.IsZero() {\n\t\treturn z.Mod(\u0026pl, m)\n\t}\n\n\tvar quot [8]uint64\n\trem := udivrem(quot[:], p[:], m)\n\treturn z.Set(\u0026rem)\n}\n\n// Mod sets z to the modulus x%y for y != 0 and returns z.\n// If y == 0, z is set to 0 (OBS: differs from the big.Uint)\nfunc (z *Uint) Mod(x, y *Uint) *Uint {\n\tif x.IsZero() || y.IsZero() {\n\t\treturn z.Clear()\n\t}\n\tswitch x.Cmp(y) {\n\tcase -1:\n\t\t// x \u003c y\n\t\tcopy(z.arr[:], x.arr[:])\n\t\treturn z\n\tcase 0:\n\t\t// x == y\n\t\treturn z.Clear() // They are equal\n\t}\n\n\t// At this point:\n\t// x != 0\n\t// y != 0\n\t// x \u003e y\n\n\t// Shortcut trivial case\n\tif x.IsUint64() {\n\t\treturn z.SetUint64(x.Uint64() % y.Uint64())\n\t}\n\n\tvar quot Uint\n\t*z = udivrem(quot.arr[:], x.arr[:], y)\n\treturn z\n}\n\n// DivMod sets z to the quotient x div y and m to the modulus x mod y and returns the pair (z, m) for y != 0.\n// If y == 0, both z and m are set to 0 (OBS: differs from the big.Int)\nfunc (z *Uint) DivMod(x, y, m *Uint) (*Uint, *Uint) {\n\tif y.IsZero() {\n\t\treturn z.Clear(), m.Clear()\n\t}\n\tvar quot Uint\n\t*m = udivrem(quot.arr[:], x.arr[:], y)\n\t*z = quot\n\treturn z, m\n}\n\n// Exp sets z = base**exponent mod 2**256, and returns z.\nfunc (z *Uint) Exp(base, exponent *Uint) *Uint {\n\tres := Uint{arr: [4]uint64{1, 0, 0, 0}}\n\tmultiplier := *base\n\texpBitLen := exponent.BitLen()\n\n\tcurBit := 0\n\tword := exponent.arr[0]\n\tfor ; curBit \u003c expBitLen \u0026\u0026 curBit \u003c 64; curBit++ {\n\t\tif word\u00261 == 1 {\n\t\t\tres.Mul(\u0026res, \u0026multiplier)\n\t\t}\n\t\tmultiplier.squared()\n\t\tword \u003e\u003e= 1\n\t}\n\n\tword = exponent.arr[1]\n\tfor ; curBit \u003c expBitLen \u0026\u0026 curBit \u003c 128; curBit++ {\n\t\tif word\u00261 == 1 {\n\t\t\tres.Mul(\u0026res, \u0026multiplier)\n\t\t}\n\t\tmultiplier.squared()\n\t\tword \u003e\u003e= 1\n\t}\n\n\tword = exponent.arr[2]\n\tfor ; curBit \u003c expBitLen \u0026\u0026 curBit \u003c 192; curBit++ {\n\t\tif word\u00261 == 1 {\n\t\t\tres.Mul(\u0026res, \u0026multiplier)\n\t\t}\n\t\tmultiplier.squared()\n\t\tword \u003e\u003e= 1\n\t}\n\n\tword = exponent.arr[3]\n\tfor ; curBit \u003c expBitLen \u0026\u0026 curBit \u003c 256; curBit++ {\n\t\tif word\u00261 == 1 {\n\t\t\tres.Mul(\u0026res, \u0026multiplier)\n\t\t}\n\t\tmultiplier.squared()\n\t\tword \u003e\u003e= 1\n\t}\n\treturn z.Set(\u0026res)\n}\n\nfunc (z *Uint) squared() {\n\tvar (\n\t\tres                    Uint\n\t\tcarry0, carry1, carry2 uint64\n\t\tres1, res2             uint64\n\t)\n\n\tcarry0, res.arr[0] = bits.Mul64(z.arr[0], z.arr[0])\n\tcarry0, res1 = umulHop(carry0, z.arr[0], z.arr[1])\n\tcarry0, res2 = umulHop(carry0, z.arr[0], z.arr[2])\n\n\tcarry1, res.arr[1] = umulHop(res1, z.arr[0], z.arr[1])\n\tcarry1, res2 = umulStep(res2, z.arr[1], z.arr[1], carry1)\n\n\tcarry2, res.arr[2] = umulHop(res2, z.arr[0], z.arr[2])\n\n\tres.arr[3] = 2*(z.arr[0]*z.arr[3]+z.arr[1]*z.arr[2]) + carry0 + carry1 + carry2\n\n\tz.Set(\u0026res)\n}\n\n// udivrem divides u by d and produces both quotient and remainder.\n// The quotient is stored in provided quot - len(u)-len(d)+1 words.\n// It loosely follows the Knuth's division algorithm (sometimes referenced as \"schoolbook\" division) using 64-bit words.\n// See Knuth, Volume 2, section 4.3.1, Algorithm D.\nfunc udivrem(quot, u []uint64, d *Uint) (rem Uint) {\n\tvar dLen int\n\tfor i := len(d.arr) - 1; i \u003e= 0; i-- {\n\t\tif d.arr[i] != 0 {\n\t\t\tdLen = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tshift := uint(bits.LeadingZeros64(d.arr[dLen-1]))\n\n\tvar dnStorage Uint\n\tdn := dnStorage.arr[:dLen]\n\tfor i := dLen - 1; i \u003e 0; i-- {\n\t\tdn[i] = (d.arr[i] \u003c\u003c shift) | (d.arr[i-1] \u003e\u003e (64 - shift))\n\t}\n\tdn[0] = d.arr[0] \u003c\u003c shift\n\n\tvar uLen int\n\tfor i := len(u) - 1; i \u003e= 0; i-- {\n\t\tif u[i] != 0 {\n\t\t\tuLen = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif uLen \u003c dLen {\n\t\tcopy(rem.arr[:], u)\n\t\treturn rem\n\t}\n\n\tvar unStorage [9]uint64\n\tun := unStorage[:uLen+1]\n\tun[uLen] = u[uLen-1] \u003e\u003e (64 - shift)\n\tfor i := uLen - 1; i \u003e 0; i-- {\n\t\tun[i] = (u[i] \u003c\u003c shift) | (u[i-1] \u003e\u003e (64 - shift))\n\t}\n\tun[0] = u[0] \u003c\u003c shift\n\n\t// TODO: Skip the highest word of numerator if not significant.\n\n\tif dLen == 1 {\n\t\tr := udivremBy1(quot, un, dn[0])\n\t\trem.SetUint64(r \u003e\u003e shift)\n\t\treturn rem\n\t}\n\n\tudivremKnuth(quot, un, dn)\n\n\tfor i := 0; i \u003c dLen-1; i++ {\n\t\trem.arr[i] = (un[i] \u003e\u003e shift) | (un[i+1] \u003c\u003c (64 - shift))\n\t}\n\trem.arr[dLen-1] = un[dLen-1] \u003e\u003e shift\n\n\treturn rem\n}\n\n// umul computes full 256 x 256 -\u003e 512 multiplication.\nfunc umul(x, y *Uint) [8]uint64 {\n\tvar (\n\t\tres                           [8]uint64\n\t\tcarry, carry4, carry5, carry6 uint64\n\t\tres1, res2, res3, res4, res5  uint64\n\t)\n\n\tcarry, res[0] = bits.Mul64(x.arr[0], y.arr[0])\n\tcarry, res1 = umulHop(carry, x.arr[1], y.arr[0])\n\tcarry, res2 = umulHop(carry, x.arr[2], y.arr[0])\n\tcarry4, res3 = umulHop(carry, x.arr[3], y.arr[0])\n\n\tcarry, res[1] = umulHop(res1, x.arr[0], y.arr[1])\n\tcarry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry)\n\tcarry, res3 = umulStep(res3, x.arr[2], y.arr[1], carry)\n\tcarry5, res4 = umulStep(carry4, x.arr[3], y.arr[1], carry)\n\n\tcarry, res[2] = umulHop(res2, x.arr[0], y.arr[2])\n\tcarry, res3 = umulStep(res3, x.arr[1], y.arr[2], carry)\n\tcarry, res4 = umulStep(res4, x.arr[2], y.arr[2], carry)\n\tcarry6, res5 = umulStep(carry5, x.arr[3], y.arr[2], carry)\n\n\tcarry, res[3] = umulHop(res3, x.arr[0], y.arr[3])\n\tcarry, res[4] = umulStep(res4, x.arr[1], y.arr[3], carry)\n\tcarry, res[5] = umulStep(res5, x.arr[2], y.arr[3], carry)\n\tres[7], res[6] = umulStep(carry6, x.arr[3], y.arr[3], carry)\n\n\treturn res\n}\n\n// umulStep computes (hi * 2^64 + lo) = z + (x * y) + carry.\nfunc umulStep(z, x, y, carry uint64) (hi, lo uint64) {\n\thi, lo = bits.Mul64(x, y)\n\tlo, carry = bits.Add64(lo, carry, 0)\n\thi, _ = bits.Add64(hi, 0, carry)\n\tlo, carry = bits.Add64(lo, z, 0)\n\thi, _ = bits.Add64(hi, 0, carry)\n\treturn hi, lo\n}\n\n// umulHop computes (hi * 2^64 + lo) = z + (x * y)\nfunc umulHop(z, x, y uint64) (hi, lo uint64) {\n\thi, lo = bits.Mul64(x, y)\n\tlo, carry := bits.Add64(lo, z, 0)\n\thi, _ = bits.Add64(hi, 0, carry)\n\treturn hi, lo\n}\n\n// udivremBy1 divides u by single normalized word d and produces both quotient and remainder.\n// The quotient is stored in provided quot.\nfunc udivremBy1(quot, u []uint64, d uint64) (rem uint64) {\n\treciprocal := reciprocal2by1(d)\n\trem = u[len(u)-1] // Set the top word as remainder.\n\tfor j := len(u) - 2; j \u003e= 0; j-- {\n\t\tquot[j], rem = udivrem2by1(rem, u[j], d, reciprocal)\n\t}\n\treturn rem\n}\n\n// udivremKnuth implements the division of u by normalized multiple word d from the Knuth's division algorithm.\n// The quotient is stored in provided quot - len(u)-len(d) words.\n// Updates u to contain the remainder - len(d) words.\nfunc udivremKnuth(quot, u, d []uint64) {\n\tdh := d[len(d)-1]\n\tdl := d[len(d)-2]\n\treciprocal := reciprocal2by1(dh)\n\n\tfor j := len(u) - len(d) - 1; j \u003e= 0; j-- {\n\t\tu2 := u[j+len(d)]\n\t\tu1 := u[j+len(d)-1]\n\t\tu0 := u[j+len(d)-2]\n\n\t\tvar qhat, rhat uint64\n\t\tif u2 \u003e= dh { // Division overflows.\n\t\t\tqhat = ^uint64(0)\n\t\t\t// TODO: Add \"qhat one to big\" adjustment (not needed for correctness, but helps avoiding \"add back\" case).\n\t\t} else {\n\t\t\tqhat, rhat = udivrem2by1(u2, u1, dh, reciprocal)\n\t\t\tph, pl := bits.Mul64(qhat, dl)\n\t\t\tif ph \u003e rhat || (ph == rhat \u0026\u0026 pl \u003e u0) {\n\t\t\t\tqhat--\n\t\t\t\t// TODO: Add \"qhat one to big\" adjustment (not needed for correctness, but helps avoiding \"add back\" case).\n\t\t\t}\n\t\t}\n\n\t\t// Multiply and subtract.\n\t\tborrow := subMulTo(u[j:], d, qhat)\n\t\tu[j+len(d)] = u2 - borrow\n\t\tif u2 \u003c borrow { // Too much subtracted, add back.\n\t\t\tqhat--\n\t\t\tu[j+len(d)] += addTo(u[j:], d)\n\t\t}\n\n\t\tquot[j] = qhat // Store quotient digit.\n\t}\n}\n\n// isBitSet returns true if bit n-th is set, where n = 0 is LSB.\n// The n must be \u003c= 255.\nfunc (z *Uint) isBitSet(n uint) bool {\n\treturn (z.arr[n/64] \u0026 (1 \u003c\u003c (n % 64))) != 0\n}\n\n// addTo computes x += y.\n// Requires len(x) \u003e= len(y).\nfunc addTo(x, y []uint64) uint64 {\n\tvar carry uint64\n\tfor i := 0; i \u003c len(y); i++ {\n\t\tx[i], carry = bits.Add64(x[i], y[i], carry)\n\t}\n\treturn carry\n}\n\n// subMulTo computes x -= y * multiplier.\n// Requires len(x) \u003e= len(y).\nfunc subMulTo(x, y []uint64, multiplier uint64) uint64 {\n\tvar borrow uint64\n\tfor i := 0; i \u003c len(y); i++ {\n\t\ts, carry1 := bits.Sub64(x[i], borrow, 0)\n\t\tph, pl := bits.Mul64(y[i], multiplier)\n\t\tt, carry2 := bits.Sub64(s, pl, 0)\n\t\tx[i] = t\n\t\tborrow = ph + carry1 + carry2\n\t}\n\treturn borrow\n}\n\n// reciprocal2by1 computes \u003c^d, ^0\u003e / d.\nfunc reciprocal2by1(d uint64) uint64 {\n\treciprocal, _ := bits.Div64(^d, ^uint64(0), d)\n\treturn reciprocal\n}\n\n// udivrem2by1 divides \u003cuh, ul\u003e / d and produces both quotient and remainder.\n// It uses the provided d's reciprocal.\n// Implementation ported from https://github.com/chfast/intx and is based on\n// \"Improved division by invariant integers\", Algorithm 4.\nfunc udivrem2by1(uh, ul, d, reciprocal uint64) (quot, rem uint64) {\n\tqh, ql := bits.Mul64(reciprocal, uh)\n\tql, carry := bits.Add64(ql, ul, 0)\n\tqh, _ = bits.Add64(qh, uh, carry)\n\tqh++\n\n\tr := ul - qh*d\n\n\tif r \u003e ql {\n\t\tqh--\n\t\tr += d\n\t}\n\n\tif r \u003e= d {\n\t\tqh++\n\t\tr -= d\n\t}\n\n\treturn qh, r\n}\n"},{"name":"bits_table.gno","body":"// Copyright 2017 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated by go run make_tables.go. DO NOT EDIT.\n\npackage uint256\n\nconst ntz8tab = \"\" +\n\t\"\\x08\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x05\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x06\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x05\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x07\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x05\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x06\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x05\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\" +\n\t\"\\x04\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x03\\x00\\x01\\x00\\x02\\x00\\x01\\x00\"\n\nconst pop8tab = \"\" +\n\t\"\\x00\\x01\\x01\\x02\\x01\\x02\\x02\\x03\\x01\\x02\\x02\\x03\\x02\\x03\\x03\\x04\" +\n\t\"\\x01\\x02\\x02\\x03\\x02\\x03\\x03\\x04\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\" +\n\t\"\\x01\\x02\\x02\\x03\\x02\\x03\\x03\\x04\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\" +\n\t\"\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\" +\n\t\"\\x01\\x02\\x02\\x03\\x02\\x03\\x03\\x04\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\" +\n\t\"\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\" +\n\t\"\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\" +\n\t\"\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\\x04\\x05\\x05\\x06\\x05\\x06\\x06\\x07\" +\n\t\"\\x01\\x02\\x02\\x03\\x02\\x03\\x03\\x04\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\" +\n\t\"\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\" +\n\t\"\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\" +\n\t\"\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\\x04\\x05\\x05\\x06\\x05\\x06\\x06\\x07\" +\n\t\"\\x02\\x03\\x03\\x04\\x03\\x04\\x04\\x05\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\" +\n\t\"\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\\x04\\x05\\x05\\x06\\x05\\x06\\x06\\x07\" +\n\t\"\\x03\\x04\\x04\\x05\\x04\\x05\\x05\\x06\\x04\\x05\\x05\\x06\\x05\\x06\\x06\\x07\" +\n\t\"\\x04\\x05\\x05\\x06\\x05\\x06\\x06\\x07\\x05\\x06\\x06\\x07\\x06\\x07\\x07\\x08\"\n\nconst rev8tab = \"\" +\n\t\"\\x00\\x80\\x40\\xc0\\x20\\xa0\\x60\\xe0\\x10\\x90\\x50\\xd0\\x30\\xb0\\x70\\xf0\" +\n\t\"\\x08\\x88\\x48\\xc8\\x28\\xa8\\x68\\xe8\\x18\\x98\\x58\\xd8\\x38\\xb8\\x78\\xf8\" +\n\t\"\\x04\\x84\\x44\\xc4\\x24\\xa4\\x64\\xe4\\x14\\x94\\x54\\xd4\\x34\\xb4\\x74\\xf4\" +\n\t\"\\x0c\\x8c\\x4c\\xcc\\x2c\\xac\\x6c\\xec\\x1c\\x9c\\x5c\\xdc\\x3c\\xbc\\x7c\\xfc\" +\n\t\"\\x02\\x82\\x42\\xc2\\x22\\xa2\\x62\\xe2\\x12\\x92\\x52\\xd2\\x32\\xb2\\x72\\xf2\" +\n\t\"\\x0a\\x8a\\x4a\\xca\\x2a\\xaa\\x6a\\xea\\x1a\\x9a\\x5a\\xda\\x3a\\xba\\x7a\\xfa\" +\n\t\"\\x06\\x86\\x46\\xc6\\x26\\xa6\\x66\\xe6\\x16\\x96\\x56\\xd6\\x36\\xb6\\x76\\xf6\" +\n\t\"\\x0e\\x8e\\x4e\\xce\\x2e\\xae\\x6e\\xee\\x1e\\x9e\\x5e\\xde\\x3e\\xbe\\x7e\\xfe\" +\n\t\"\\x01\\x81\\x41\\xc1\\x21\\xa1\\x61\\xe1\\x11\\x91\\x51\\xd1\\x31\\xb1\\x71\\xf1\" +\n\t\"\\x09\\x89\\x49\\xc9\\x29\\xa9\\x69\\xe9\\x19\\x99\\x59\\xd9\\x39\\xb9\\x79\\xf9\" +\n\t\"\\x05\\x85\\x45\\xc5\\x25\\xa5\\x65\\xe5\\x15\\x95\\x55\\xd5\\x35\\xb5\\x75\\xf5\" +\n\t\"\\x0d\\x8d\\x4d\\xcd\\x2d\\xad\\x6d\\xed\\x1d\\x9d\\x5d\\xdd\\x3d\\xbd\\x7d\\xfd\" +\n\t\"\\x03\\x83\\x43\\xc3\\x23\\xa3\\x63\\xe3\\x13\\x93\\x53\\xd3\\x33\\xb3\\x73\\xf3\" +\n\t\"\\x0b\\x8b\\x4b\\xcb\\x2b\\xab\\x6b\\xeb\\x1b\\x9b\\x5b\\xdb\\x3b\\xbb\\x7b\\xfb\" +\n\t\"\\x07\\x87\\x47\\xc7\\x27\\xa7\\x67\\xe7\\x17\\x97\\x57\\xd7\\x37\\xb7\\x77\\xf7\" +\n\t\"\\x0f\\x8f\\x4f\\xcf\\x2f\\xaf\\x6f\\xef\\x1f\\x9f\\x5f\\xdf\\x3f\\xbf\\x7f\\xff\"\n\nconst len8tab = \"\" +\n\t\"\\x00\\x01\\x02\\x02\\x03\\x03\\x03\\x03\\x04\\x04\\x04\\x04\\x04\\x04\\x04\\x04\" +\n\t\"\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\\x05\" +\n\t\"\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\" +\n\t\"\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\\x06\" +\n\t\"\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\" +\n\t\"\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\" +\n\t\"\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\" +\n\t\"\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\\x07\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\" +\n\t\"\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\"\n"},{"name":"bitwise.gno","body":"// bitwise contains bitwise operations for Uint instances.\n// This file includes functions to perform bitwise AND, OR, XOR, and NOT operations, as well as bit shifting.\n// These operations are crucial for manipulating individual bits within a 256-bit unsigned integer.\npackage uint256\n\n// Or sets z = x | y and returns z.\nfunc (z *Uint) Or(x, y *Uint) *Uint {\n\tz.arr[0] = x.arr[0] | y.arr[0]\n\tz.arr[1] = x.arr[1] | y.arr[1]\n\tz.arr[2] = x.arr[2] | y.arr[2]\n\tz.arr[3] = x.arr[3] | y.arr[3]\n\treturn z\n}\n\n// And sets z = x \u0026 y and returns z.\nfunc (z *Uint) And(x, y *Uint) *Uint {\n\tz.arr[0] = x.arr[0] \u0026 y.arr[0]\n\tz.arr[1] = x.arr[1] \u0026 y.arr[1]\n\tz.arr[2] = x.arr[2] \u0026 y.arr[2]\n\tz.arr[3] = x.arr[3] \u0026 y.arr[3]\n\treturn z\n}\n\n// Not sets z = ^x and returns z.\nfunc (z *Uint) Not(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = ^x.arr[3], ^x.arr[2], ^x.arr[1], ^x.arr[0]\n\treturn z\n}\n\n// AndNot sets z = x \u0026^ y and returns z.\nfunc (z *Uint) AndNot(x, y *Uint) *Uint {\n\tz.arr[0] = x.arr[0] \u0026^ y.arr[0]\n\tz.arr[1] = x.arr[1] \u0026^ y.arr[1]\n\tz.arr[2] = x.arr[2] \u0026^ y.arr[2]\n\tz.arr[3] = x.arr[3] \u0026^ y.arr[3]\n\treturn z\n}\n\n// Xor sets z = x ^ y and returns z.\nfunc (z *Uint) Xor(x, y *Uint) *Uint {\n\tz.arr[0] = x.arr[0] ^ y.arr[0]\n\tz.arr[1] = x.arr[1] ^ y.arr[1]\n\tz.arr[2] = x.arr[2] ^ y.arr[2]\n\tz.arr[3] = x.arr[3] ^ y.arr[3]\n\treturn z\n}\n\n// Lsh sets z = x \u003c\u003c n and returns z.\nfunc (z *Uint) Lsh(x *Uint, n uint) *Uint {\n\t// n % 64 == 0\n\tif n\u00260x3f == 0 {\n\t\tswitch n {\n\t\tcase 0:\n\t\t\treturn z.Set(x)\n\t\tcase 64:\n\t\t\treturn z.lsh64(x)\n\t\tcase 128:\n\t\t\treturn z.lsh128(x)\n\t\tcase 192:\n\t\t\treturn z.lsh192(x)\n\t\tdefault:\n\t\t\treturn z.Clear()\n\t\t}\n\t}\n\tvar a, b uint64\n\t// Big swaps first\n\tswitch {\n\tcase n \u003e 192:\n\t\tif n \u003e 256 {\n\t\t\treturn z.Clear()\n\t\t}\n\t\tz.lsh192(x)\n\t\tn -= 192\n\t\tgoto sh192\n\tcase n \u003e 128:\n\t\tz.lsh128(x)\n\t\tn -= 128\n\t\tgoto sh128\n\tcase n \u003e 64:\n\t\tz.lsh64(x)\n\t\tn -= 64\n\t\tgoto sh64\n\tdefault:\n\t\tz.Set(x)\n\t}\n\n\t// remaining shifts\n\ta = z.arr[0] \u003e\u003e (64 - n)\n\tz.arr[0] = z.arr[0] \u003c\u003c n\n\nsh64:\n\tb = z.arr[1] \u003e\u003e (64 - n)\n\tz.arr[1] = (z.arr[1] \u003c\u003c n) | a\n\nsh128:\n\ta = z.arr[2] \u003e\u003e (64 - n)\n\tz.arr[2] = (z.arr[2] \u003c\u003c n) | b\n\nsh192:\n\tz.arr[3] = (z.arr[3] \u003c\u003c n) | a\n\n\treturn z\n}\n\n// Rsh sets z = x \u003e\u003e n and returns z.\nfunc (z *Uint) Rsh(x *Uint, n uint) *Uint {\n\t// n % 64 == 0\n\tif n\u00260x3f == 0 {\n\t\tswitch n {\n\t\tcase 0:\n\t\t\treturn z.Set(x)\n\t\tcase 64:\n\t\t\treturn z.rsh64(x)\n\t\tcase 128:\n\t\t\treturn z.rsh128(x)\n\t\tcase 192:\n\t\t\treturn z.rsh192(x)\n\t\tdefault:\n\t\t\treturn z.Clear()\n\t\t}\n\t}\n\tvar a, b uint64\n\t// Big swaps first\n\tswitch {\n\tcase n \u003e 192:\n\t\tif n \u003e 256 {\n\t\t\treturn z.Clear()\n\t\t}\n\t\tz.rsh192(x)\n\t\tn -= 192\n\t\tgoto sh192\n\tcase n \u003e 128:\n\t\tz.rsh128(x)\n\t\tn -= 128\n\t\tgoto sh128\n\tcase n \u003e 64:\n\t\tz.rsh64(x)\n\t\tn -= 64\n\t\tgoto sh64\n\tdefault:\n\t\tz.Set(x)\n\t}\n\n\t// remaining shifts\n\ta = z.arr[3] \u003c\u003c (64 - n)\n\tz.arr[3] = z.arr[3] \u003e\u003e n\n\nsh64:\n\tb = z.arr[2] \u003c\u003c (64 - n)\n\tz.arr[2] = (z.arr[2] \u003e\u003e n) | a\n\nsh128:\n\ta = z.arr[1] \u003c\u003c (64 - n)\n\tz.arr[1] = (z.arr[1] \u003e\u003e n) | b\n\nsh192:\n\tz.arr[0] = (z.arr[0] \u003e\u003e n) | a\n\n\treturn z\n}\n\n// SRsh (Signed/Arithmetic right shift)\n// considers z to be a signed integer, during right-shift\n// and sets z = x \u003e\u003e n and returns z.\nfunc (z *Uint) SRsh(x *Uint, n uint) *Uint {\n\t// If the MSB is 0, SRsh is same as Rsh.\n\tif !x.isBitSet(255) {\n\t\treturn z.Rsh(x, n)\n\t}\n\tif n%64 == 0 {\n\t\tswitch n {\n\t\tcase 0:\n\t\t\treturn z.Set(x)\n\t\tcase 64:\n\t\t\treturn z.srsh64(x)\n\t\tcase 128:\n\t\t\treturn z.srsh128(x)\n\t\tcase 192:\n\t\t\treturn z.srsh192(x)\n\t\tdefault:\n\t\t\treturn z.SetAllOne()\n\t\t}\n\t}\n\tvar a uint64 = MaxUint64 \u003c\u003c (64 - n%64)\n\t// Big swaps first\n\tswitch {\n\tcase n \u003e 192:\n\t\tif n \u003e 256 {\n\t\t\treturn z.SetAllOne()\n\t\t}\n\t\tz.srsh192(x)\n\t\tn -= 192\n\t\tgoto sh192\n\tcase n \u003e 128:\n\t\tz.srsh128(x)\n\t\tn -= 128\n\t\tgoto sh128\n\tcase n \u003e 64:\n\t\tz.srsh64(x)\n\t\tn -= 64\n\t\tgoto sh64\n\tdefault:\n\t\tz.Set(x)\n\t}\n\n\t// remaining shifts\n\tz.arr[3], a = (z.arr[3]\u003e\u003en)|a, z.arr[3]\u003c\u003c(64-n)\n\nsh64:\n\tz.arr[2], a = (z.arr[2]\u003e\u003en)|a, z.arr[2]\u003c\u003c(64-n)\n\nsh128:\n\tz.arr[1], a = (z.arr[1]\u003e\u003en)|a, z.arr[1]\u003c\u003c(64-n)\n\nsh192:\n\tz.arr[0] = (z.arr[0] \u003e\u003e n) | a\n\n\treturn z\n}\n\nfunc (z *Uint) lsh64(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[2], x.arr[1], x.arr[0], 0\n\treturn z\n}\n\nfunc (z *Uint) lsh128(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[1], x.arr[0], 0, 0\n\treturn z\n}\n\nfunc (z *Uint) lsh192(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[0], 0, 0, 0\n\treturn z\n}\n\nfunc (z *Uint) rsh64(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, x.arr[3], x.arr[2], x.arr[1]\n\treturn z\n}\n\nfunc (z *Uint) rsh128(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, x.arr[3], x.arr[2]\n\treturn z\n}\n\nfunc (z *Uint) rsh192(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x.arr[3]\n\treturn z\n}\n\nfunc (z *Uint) srsh64(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, x.arr[3], x.arr[2], x.arr[1]\n\treturn z\n}\n\nfunc (z *Uint) srsh128(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, x.arr[3], x.arr[2]\n\treturn z\n}\n\nfunc (z *Uint) srsh192(x *Uint) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, x.arr[3]\n\treturn z\n}\n"},{"name":"cmp.gno","body":"// cmp (or, comparisons) includes methods for comparing Uint instances.\n// These comparison functions cover a range of operations including equality checks, less than/greater than\n// evaluations, and specialized comparisons such as signed greater than. These are fundamental for logical\n// decision making based on Uint values.\npackage uint256\n\nimport (\n\t\"math/bits\"\n)\n\n// Cmp compares z and x and returns:\n//\n//\t-1 if z \u003c  x\n//\t 0 if z == x\n//\t+1 if z \u003e  x\nfunc (z *Uint) Cmp(x *Uint) (r int) {\n\t// z \u003c x \u003c=\u003e z - x \u003c 0 i.e. when subtraction overflows.\n\td0, carry := bits.Sub64(z.arr[0], x.arr[0], 0)\n\td1, carry := bits.Sub64(z.arr[1], x.arr[1], carry)\n\td2, carry := bits.Sub64(z.arr[2], x.arr[2], carry)\n\td3, carry := bits.Sub64(z.arr[3], x.arr[3], carry)\n\tif carry == 1 {\n\t\treturn -1\n\t}\n\tif d0|d1|d2|d3 == 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}\n\n// IsZero returns true if z == 0\nfunc (z *Uint) IsZero() bool {\n\treturn (z.arr[0] | z.arr[1] | z.arr[2] | z.arr[3]) == 0\n}\n\n// Sign returns:\n//\n//\t-1 if z \u003c  0\n//\t 0 if z == 0\n//\t+1 if z \u003e  0\n//\n// Where z is interpreted as a two's complement signed number\nfunc (z *Uint) Sign() int {\n\tif z.IsZero() {\n\t\treturn 0\n\t}\n\tif z.arr[3] \u003c 0x8000000000000000 {\n\t\treturn 1\n\t}\n\treturn -1\n}\n\n// LtUint64 returns true if z is smaller than n\nfunc (z *Uint) LtUint64(n uint64) bool {\n\treturn z.arr[0] \u003c n \u0026\u0026 (z.arr[1]|z.arr[2]|z.arr[3]) == 0\n}\n\n// GtUint64 returns true if z is larger than n\nfunc (z *Uint) GtUint64(n uint64) bool {\n\treturn z.arr[0] \u003e n || (z.arr[1]|z.arr[2]|z.arr[3]) != 0\n}\n\n// Lt returns true if z \u003c x\nfunc (z *Uint) Lt(x *Uint) bool {\n\t// z \u003c x \u003c=\u003e z - x \u003c 0 i.e. when subtraction overflows.\n\t_, carry := bits.Sub64(z.arr[0], x.arr[0], 0)\n\t_, carry = bits.Sub64(z.arr[1], x.arr[1], carry)\n\t_, carry = bits.Sub64(z.arr[2], x.arr[2], carry)\n\t_, carry = bits.Sub64(z.arr[3], x.arr[3], carry)\n\n\treturn carry != 0\n}\n\n// Gt returns true if z \u003e x\nfunc (z *Uint) Gt(x *Uint) bool {\n\treturn x.Lt(z)\n}\n\n// Lte returns true if z \u003c= x\nfunc (z *Uint) Lte(x *Uint) bool {\n\tcond1 := z.Lt(x)\n\tcond2 := z.Eq(x)\n\n\tif cond1 || cond2 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// Gte returns true if z \u003e= x\nfunc (z *Uint) Gte(x *Uint) bool {\n\tcond1 := z.Gt(x)\n\tcond2 := z.Eq(x)\n\n\tif cond1 || cond2 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// Eq returns true if z == x\nfunc (z *Uint) Eq(x *Uint) bool {\n\treturn (z.arr[0] == x.arr[0]) \u0026\u0026 (z.arr[1] == x.arr[1]) \u0026\u0026 (z.arr[2] == x.arr[2]) \u0026\u0026 (z.arr[3] == x.arr[3])\n}\n\n// Neq returns true if z != x\nfunc (z *Uint) Neq(x *Uint) bool {\n\treturn !z.Eq(x)\n}\n\n// Sgt interprets z and x as signed integers, and returns\n// true if z \u003e x\nfunc (z *Uint) Sgt(x *Uint) bool {\n\tzSign := z.Sign()\n\txSign := x.Sign()\n\n\tswitch {\n\tcase zSign \u003e= 0 \u0026\u0026 xSign \u003c 0:\n\t\treturn true\n\tcase zSign \u003c 0 \u0026\u0026 xSign \u003e= 0:\n\t\treturn false\n\tdefault:\n\t\treturn z.Gt(x)\n\t}\n}\n"},{"name":"conversion.gno","body":"// conversions contains methods for converting Uint instances to other types and vice versa.\n// This includes conversions to and from basic types such as uint64 and int32, as well as string representations\n// and byte slices. Additionally, it covers marshaling and unmarshaling for JSON and other text formats.\npackage uint256\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Uint64 returns the lower 64-bits of z\nfunc (z *Uint) Uint64() uint64 {\n\treturn z.arr[0]\n}\n\n// Uint64WithOverflow returns the lower 64-bits of z and bool whether overflow occurred\nfunc (z *Uint) Uint64WithOverflow() (uint64, bool) {\n\treturn z.arr[0], (z.arr[1] | z.arr[2] | z.arr[3]) != 0\n}\n\n// SetUint64 sets z to the value x\nfunc (z *Uint) SetUint64(x uint64) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x\n\treturn z\n}\n\n// IsUint64 reports whether z can be represented as a uint64.\nfunc (z *Uint) IsUint64() bool {\n\treturn (z.arr[1] | z.arr[2] | z.arr[3]) == 0\n}\n\n// Dec returns the decimal representation of z.\nfunc (z *Uint) Dec() string {\n\tif z.IsZero() {\n\t\treturn \"0\"\n\t}\n\tif z.IsUint64() {\n\t\treturn strconv.FormatUint(z.Uint64(), 10)\n\t}\n\n\t// The max uint64 value being 18446744073709551615, the largest\n\t// power-of-ten below that is 10000000000000000000.\n\t// When we do a DivMod using that number, the remainder that we\n\t// get back is the lower part of the output.\n\t//\n\t// The ascii-output of remainder will never exceed 19 bytes (since it will be\n\t// below 10000000000000000000).\n\t//\n\t// Algorithm example using 100 as divisor\n\t//\n\t// 12345 % 100 = 45   (rem)\n\t// 12345 / 100 = 123  (quo)\n\t// -\u003e output '45', continue iterate on 123\n\tvar (\n\t\t// out is 98 bytes long: 78 (max size of a string without leading zeroes,\n\t\t// plus slack so we can copy 19 bytes every iteration).\n\t\t// We init it with zeroes, because when strconv appends the ascii representations,\n\t\t// it will omit leading zeroes.\n\t\tout     = []byte(\"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\")\n\t\tdivisor = NewUint(10000000000000000000) // 20 digits\n\t\ty       = new(Uint).Set(z)              // copy to avoid modifying z\n\t\tpos     = len(out)                      // position to write to\n\t\tbuf     = make([]byte, 0, 19)           // buffer to write uint64:s to\n\t)\n\tfor {\n\t\t// Obtain Q and R for divisor\n\t\tvar quot Uint\n\t\trem := udivrem(quot.arr[:], y.arr[:], divisor)\n\t\ty.Set(\u0026quot) // Set Q for next loop\n\t\t// Convert the R to ascii representation\n\t\tbuf = strconv.AppendUint(buf[:0], rem.Uint64(), 10)\n\t\t// Copy in the ascii digits\n\t\tcopy(out[pos-len(buf):], buf)\n\t\tif y.IsZero() {\n\t\t\tbreak\n\t\t}\n\t\t// Move 19 digits left\n\t\tpos -= 19\n\t}\n\t// skip leading zeroes by only using the 'used size' of buf\n\treturn string(out[pos-len(buf):])\n}\n\nfunc (z *Uint) Scan(src any) error {\n\tif src == nil {\n\t\tz.Clear()\n\t\treturn nil\n\t}\n\n\tswitch src := src.(type) {\n\tcase string:\n\t\treturn z.scanScientificFromString(src)\n\tcase []byte:\n\t\treturn z.scanScientificFromString(string(src))\n\t}\n\treturn errors.New(\"default // unsupported type: can't convert to uint256.Uint\")\n}\n\nfunc (z *Uint) scanScientificFromString(src string) error {\n\tif len(src) == 0 {\n\t\tz.Clear()\n\t\treturn nil\n\t}\n\n\tidx := strings.IndexByte(src, 'e')\n\tif idx == -1 {\n\t\treturn z.SetFromDecimal(src)\n\t}\n\tif err := z.SetFromDecimal(src[:idx]); err != nil {\n\t\treturn err\n\t}\n\tif src[(idx+1):] == \"0\" {\n\t\treturn nil\n\t}\n\texp := new(Uint)\n\tif err := exp.SetFromDecimal(src[(idx + 1):]); err != nil {\n\t\treturn err\n\t}\n\tif exp.GtUint64(77) { // 10**78 is larger than 2**256\n\t\treturn ErrBig256Range\n\t}\n\texp.Exp(NewUint(10), exp)\n\tif _, overflow := z.MulOverflow(z, exp); overflow {\n\t\treturn ErrBig256Range\n\t}\n\treturn nil\n}\n\n// ToString returns the decimal string representation of z. It returns an empty string if z is nil.\n// OBS: doesn't exist from holiman's uint256\nfunc (z *Uint) String() string {\n\tif z == nil {\n\t\treturn \"\"\n\t}\n\n\treturn z.Dec()\n}\n\n// MarshalJSON implements json.Marshaler.\n// MarshalJSON marshals using the 'decimal string' representation. This is _not_ compatible\n// with big.Uint: big.Uint marshals into JSON 'native' numeric format.\n//\n// The JSON  native format is, on some platforms, (e.g. javascript), limited to 53-bit large\n// integer space. Thus, U256 uses string-format, which is not compatible with\n// big.int (big.Uint refuses to unmarshal a string representation).\nfunc (z *Uint) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + z.Dec() + `\"`), nil\n}\n\n// UnmarshalJSON implements json.Unmarshaler. UnmarshalJSON accepts either\n// - Quoted string: either hexadecimal OR decimal\n// - Not quoted string: only decimal\nfunc (z *Uint) UnmarshalJSON(input []byte) error {\n\tif len(input) \u003c 2 || input[0] != '\"' || input[len(input)-1] != '\"' {\n\t\t// if not quoted, it must be decimal\n\t\treturn z.fromDecimal(string(input))\n\t}\n\treturn z.UnmarshalText(input[1 : len(input)-1])\n}\n\n// MarshalText implements encoding.TextMarshaler\n// MarshalText marshals using the decimal representation (compatible with big.Uint)\nfunc (z *Uint) MarshalText() ([]byte, error) {\n\treturn []byte(z.Dec()), nil\n}\n\n// UnmarshalText implements encoding.TextUnmarshaler. This method\n// can unmarshal either hexadecimal or decimal.\n// - For hexadecimal, the input _must_ be prefixed with 0x or 0X\nfunc (z *Uint) UnmarshalText(input []byte) error {\n\tif len(input) \u003e= 2 \u0026\u0026 input[0] == '0' \u0026\u0026 (input[1] == 'x' || input[1] == 'X') {\n\t\treturn z.fromHex(string(input))\n\t}\n\treturn z.fromDecimal(string(input))\n}\n\n// SetBytes interprets buf as the bytes of a big-endian unsigned\n// integer, sets z to that value, and returns z.\n// If buf is larger than 32 bytes, the last 32 bytes is used.\nfunc (z *Uint) SetBytes(buf []byte) *Uint {\n\tswitch l := len(buf); l {\n\tcase 0:\n\t\tz.Clear()\n\tcase 1:\n\t\tz.SetBytes1(buf)\n\tcase 2:\n\t\tz.SetBytes2(buf)\n\tcase 3:\n\t\tz.SetBytes3(buf)\n\tcase 4:\n\t\tz.SetBytes4(buf)\n\tcase 5:\n\t\tz.SetBytes5(buf)\n\tcase 6:\n\t\tz.SetBytes6(buf)\n\tcase 7:\n\t\tz.SetBytes7(buf)\n\tcase 8:\n\t\tz.SetBytes8(buf)\n\tcase 9:\n\t\tz.SetBytes9(buf)\n\tcase 10:\n\t\tz.SetBytes10(buf)\n\tcase 11:\n\t\tz.SetBytes11(buf)\n\tcase 12:\n\t\tz.SetBytes12(buf)\n\tcase 13:\n\t\tz.SetBytes13(buf)\n\tcase 14:\n\t\tz.SetBytes14(buf)\n\tcase 15:\n\t\tz.SetBytes15(buf)\n\tcase 16:\n\t\tz.SetBytes16(buf)\n\tcase 17:\n\t\tz.SetBytes17(buf)\n\tcase 18:\n\t\tz.SetBytes18(buf)\n\tcase 19:\n\t\tz.SetBytes19(buf)\n\tcase 20:\n\t\tz.SetBytes20(buf)\n\tcase 21:\n\t\tz.SetBytes21(buf)\n\tcase 22:\n\t\tz.SetBytes22(buf)\n\tcase 23:\n\t\tz.SetBytes23(buf)\n\tcase 24:\n\t\tz.SetBytes24(buf)\n\tcase 25:\n\t\tz.SetBytes25(buf)\n\tcase 26:\n\t\tz.SetBytes26(buf)\n\tcase 27:\n\t\tz.SetBytes27(buf)\n\tcase 28:\n\t\tz.SetBytes28(buf)\n\tcase 29:\n\t\tz.SetBytes29(buf)\n\tcase 30:\n\t\tz.SetBytes30(buf)\n\tcase 31:\n\t\tz.SetBytes31(buf)\n\tdefault:\n\t\tz.SetBytes32(buf[l-32:])\n\t}\n\treturn z\n}\n\n// SetBytes1 is identical to SetBytes(in[:1]), but panics is input is too short\nfunc (z *Uint) SetBytes1(in []byte) *Uint {\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = uint64(in[0])\n\treturn z\n}\n\n// SetBytes2 is identical to SetBytes(in[:2]), but panics is input is too short\nfunc (z *Uint) SetBytes2(in []byte) *Uint {\n\t_ = in[1] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = uint64(binary.BigEndian.Uint16(in[0:2]))\n\treturn z\n}\n\n// SetBytes3 is identical to SetBytes(in[:3]), but panics is input is too short\nfunc (z *Uint) SetBytes3(in []byte) *Uint {\n\t_ = in[2] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])\u003c\u003c16\n\treturn z\n}\n\n// SetBytes4 is identical to SetBytes(in[:4]), but panics is input is too short\nfunc (z *Uint) SetBytes4(in []byte) *Uint {\n\t_ = in[3] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = uint64(binary.BigEndian.Uint32(in[0:4]))\n\treturn z\n}\n\n// SetBytes5 is identical to SetBytes(in[:5]), but panics is input is too short\nfunc (z *Uint) SetBytes5(in []byte) *Uint {\n\t_ = in[4] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = bigEndianUint40(in[0:5])\n\treturn z\n}\n\n// SetBytes6 is identical to SetBytes(in[:6]), but panics is input is too short\nfunc (z *Uint) SetBytes6(in []byte) *Uint {\n\t_ = in[5] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = bigEndianUint48(in[0:6])\n\treturn z\n}\n\n// SetBytes7 is identical to SetBytes(in[:7]), but panics is input is too short\nfunc (z *Uint) SetBytes7(in []byte) *Uint {\n\t_ = in[6] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = bigEndianUint56(in[0:7])\n\treturn z\n}\n\n// SetBytes8 is identical to SetBytes(in[:8]), but panics is input is too short\nfunc (z *Uint) SetBytes8(in []byte) *Uint {\n\t_ = in[7] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\tz.arr[0] = binary.BigEndian.Uint64(in[0:8])\n\treturn z\n}\n\n// SetBytes9 is identical to SetBytes(in[:9]), but panics is input is too short\nfunc (z *Uint) SetBytes9(in []byte) *Uint {\n\t_ = in[8] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = uint64(in[0])\n\tz.arr[0] = binary.BigEndian.Uint64(in[1:9])\n\treturn z\n}\n\n// SetBytes10 is identical to SetBytes(in[:10]), but panics is input is too short\nfunc (z *Uint) SetBytes10(in []byte) *Uint {\n\t_ = in[9] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = uint64(binary.BigEndian.Uint16(in[0:2]))\n\tz.arr[0] = binary.BigEndian.Uint64(in[2:10])\n\treturn z\n}\n\n// SetBytes11 is identical to SetBytes(in[:11]), but panics is input is too short\nfunc (z *Uint) SetBytes11(in []byte) *Uint {\n\t_ = in[10] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])\u003c\u003c16\n\tz.arr[0] = binary.BigEndian.Uint64(in[3:11])\n\treturn z\n}\n\n// SetBytes12 is identical to SetBytes(in[:12]), but panics is input is too short\nfunc (z *Uint) SetBytes12(in []byte) *Uint {\n\t_ = in[11] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = uint64(binary.BigEndian.Uint32(in[0:4]))\n\tz.arr[0] = binary.BigEndian.Uint64(in[4:12])\n\treturn z\n}\n\n// SetBytes13 is identical to SetBytes(in[:13]), but panics is input is too short\nfunc (z *Uint) SetBytes13(in []byte) *Uint {\n\t_ = in[12] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = bigEndianUint40(in[0:5])\n\tz.arr[0] = binary.BigEndian.Uint64(in[5:13])\n\treturn z\n}\n\n// SetBytes14 is identical to SetBytes(in[:14]), but panics is input is too short\nfunc (z *Uint) SetBytes14(in []byte) *Uint {\n\t_ = in[13] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = bigEndianUint48(in[0:6])\n\tz.arr[0] = binary.BigEndian.Uint64(in[6:14])\n\treturn z\n}\n\n// SetBytes15 is identical to SetBytes(in[:15]), but panics is input is too short\nfunc (z *Uint) SetBytes15(in []byte) *Uint {\n\t_ = in[14] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = bigEndianUint56(in[0:7])\n\tz.arr[0] = binary.BigEndian.Uint64(in[7:15])\n\treturn z\n}\n\n// SetBytes16 is identical to SetBytes(in[:16]), but panics is input is too short\nfunc (z *Uint) SetBytes16(in []byte) *Uint {\n\t_ = in[15] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3], z.arr[2] = 0, 0\n\tz.arr[1] = binary.BigEndian.Uint64(in[0:8])\n\tz.arr[0] = binary.BigEndian.Uint64(in[8:16])\n\treturn z\n}\n\n// SetBytes17 is identical to SetBytes(in[:17]), but panics is input is too short\nfunc (z *Uint) SetBytes17(in []byte) *Uint {\n\t_ = in[16] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = uint64(in[0])\n\tz.arr[1] = binary.BigEndian.Uint64(in[1:9])\n\tz.arr[0] = binary.BigEndian.Uint64(in[9:17])\n\treturn z\n}\n\n// SetBytes18 is identical to SetBytes(in[:18]), but panics is input is too short\nfunc (z *Uint) SetBytes18(in []byte) *Uint {\n\t_ = in[17] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = uint64(binary.BigEndian.Uint16(in[0:2]))\n\tz.arr[1] = binary.BigEndian.Uint64(in[2:10])\n\tz.arr[0] = binary.BigEndian.Uint64(in[10:18])\n\treturn z\n}\n\n// SetBytes19 is identical to SetBytes(in[:19]), but panics is input is too short\nfunc (z *Uint) SetBytes19(in []byte) *Uint {\n\t_ = in[18] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])\u003c\u003c16\n\tz.arr[1] = binary.BigEndian.Uint64(in[3:11])\n\tz.arr[0] = binary.BigEndian.Uint64(in[11:19])\n\treturn z\n}\n\n// SetBytes20 is identical to SetBytes(in[:20]), but panics is input is too short\nfunc (z *Uint) SetBytes20(in []byte) *Uint {\n\t_ = in[19] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = uint64(binary.BigEndian.Uint32(in[0:4]))\n\tz.arr[1] = binary.BigEndian.Uint64(in[4:12])\n\tz.arr[0] = binary.BigEndian.Uint64(in[12:20])\n\treturn z\n}\n\n// SetBytes21 is identical to SetBytes(in[:21]), but panics is input is too short\nfunc (z *Uint) SetBytes21(in []byte) *Uint {\n\t_ = in[20] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = bigEndianUint40(in[0:5])\n\tz.arr[1] = binary.BigEndian.Uint64(in[5:13])\n\tz.arr[0] = binary.BigEndian.Uint64(in[13:21])\n\treturn z\n}\n\n// SetBytes22 is identical to SetBytes(in[:22]), but panics is input is too short\nfunc (z *Uint) SetBytes22(in []byte) *Uint {\n\t_ = in[21] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = bigEndianUint48(in[0:6])\n\tz.arr[1] = binary.BigEndian.Uint64(in[6:14])\n\tz.arr[0] = binary.BigEndian.Uint64(in[14:22])\n\treturn z\n}\n\n// SetBytes23 is identical to SetBytes(in[:23]), but panics is input is too short\nfunc (z *Uint) SetBytes23(in []byte) *Uint {\n\t_ = in[22] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = bigEndianUint56(in[0:7])\n\tz.arr[1] = binary.BigEndian.Uint64(in[7:15])\n\tz.arr[0] = binary.BigEndian.Uint64(in[15:23])\n\treturn z\n}\n\n// SetBytes24 is identical to SetBytes(in[:24]), but panics is input is too short\nfunc (z *Uint) SetBytes24(in []byte) *Uint {\n\t_ = in[23] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = 0\n\tz.arr[2] = binary.BigEndian.Uint64(in[0:8])\n\tz.arr[1] = binary.BigEndian.Uint64(in[8:16])\n\tz.arr[0] = binary.BigEndian.Uint64(in[16:24])\n\treturn z\n}\n\n// SetBytes25 is identical to SetBytes(in[:25]), but panics is input is too short\nfunc (z *Uint) SetBytes25(in []byte) *Uint {\n\t_ = in[24] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = uint64(in[0])\n\tz.arr[2] = binary.BigEndian.Uint64(in[1:9])\n\tz.arr[1] = binary.BigEndian.Uint64(in[9:17])\n\tz.arr[0] = binary.BigEndian.Uint64(in[17:25])\n\treturn z\n}\n\n// SetBytes26 is identical to SetBytes(in[:26]), but panics is input is too short\nfunc (z *Uint) SetBytes26(in []byte) *Uint {\n\t_ = in[25] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = uint64(binary.BigEndian.Uint16(in[0:2]))\n\tz.arr[2] = binary.BigEndian.Uint64(in[2:10])\n\tz.arr[1] = binary.BigEndian.Uint64(in[10:18])\n\tz.arr[0] = binary.BigEndian.Uint64(in[18:26])\n\treturn z\n}\n\n// SetBytes27 is identical to SetBytes(in[:27]), but panics is input is too short\nfunc (z *Uint) SetBytes27(in []byte) *Uint {\n\t_ = in[26] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])\u003c\u003c16\n\tz.arr[2] = binary.BigEndian.Uint64(in[3:11])\n\tz.arr[1] = binary.BigEndian.Uint64(in[11:19])\n\tz.arr[0] = binary.BigEndian.Uint64(in[19:27])\n\treturn z\n}\n\n// SetBytes28 is identical to SetBytes(in[:28]), but panics is input is too short\nfunc (z *Uint) SetBytes28(in []byte) *Uint {\n\t_ = in[27] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = uint64(binary.BigEndian.Uint32(in[0:4]))\n\tz.arr[2] = binary.BigEndian.Uint64(in[4:12])\n\tz.arr[1] = binary.BigEndian.Uint64(in[12:20])\n\tz.arr[0] = binary.BigEndian.Uint64(in[20:28])\n\treturn z\n}\n\n// SetBytes29 is identical to SetBytes(in[:29]), but panics is input is too short\nfunc (z *Uint) SetBytes29(in []byte) *Uint {\n\t_ = in[23] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = bigEndianUint40(in[0:5])\n\tz.arr[2] = binary.BigEndian.Uint64(in[5:13])\n\tz.arr[1] = binary.BigEndian.Uint64(in[13:21])\n\tz.arr[0] = binary.BigEndian.Uint64(in[21:29])\n\treturn z\n}\n\n// SetBytes30 is identical to SetBytes(in[:30]), but panics is input is too short\nfunc (z *Uint) SetBytes30(in []byte) *Uint {\n\t_ = in[29] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = bigEndianUint48(in[0:6])\n\tz.arr[2] = binary.BigEndian.Uint64(in[6:14])\n\tz.arr[1] = binary.BigEndian.Uint64(in[14:22])\n\tz.arr[0] = binary.BigEndian.Uint64(in[22:30])\n\treturn z\n}\n\n// SetBytes31 is identical to SetBytes(in[:31]), but panics is input is too short\nfunc (z *Uint) SetBytes31(in []byte) *Uint {\n\t_ = in[30] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = bigEndianUint56(in[0:7])\n\tz.arr[2] = binary.BigEndian.Uint64(in[7:15])\n\tz.arr[1] = binary.BigEndian.Uint64(in[15:23])\n\tz.arr[0] = binary.BigEndian.Uint64(in[23:31])\n\treturn z\n}\n\n// SetBytes32 sets z to the value of the big-endian 256-bit unsigned integer in.\nfunc (z *Uint) SetBytes32(in []byte) *Uint {\n\t_ = in[31] // bounds check hint to compiler; see golang.org/issue/14808\n\tz.arr[3] = binary.BigEndian.Uint64(in[0:8])\n\tz.arr[2] = binary.BigEndian.Uint64(in[8:16])\n\tz.arr[1] = binary.BigEndian.Uint64(in[16:24])\n\tz.arr[0] = binary.BigEndian.Uint64(in[24:32])\n\treturn z\n}\n\n// Utility methods that are \"missing\" among the bigEndian.UintXX methods.\n\n// bigEndianUint40 returns the uint64 value represented by the 5 bytes in big-endian order.\nfunc bigEndianUint40(b []byte) uint64 {\n\t_ = b[4] // bounds check hint to compiler; see golang.org/issue/14808\n\treturn uint64(b[4]) | uint64(b[3])\u003c\u003c8 | uint64(b[2])\u003c\u003c16 | uint64(b[1])\u003c\u003c24 |\n\t\tuint64(b[0])\u003c\u003c32\n}\n\n// bigEndianUint56 returns the uint64 value represented by the 7 bytes in big-endian order.\nfunc bigEndianUint56(b []byte) uint64 {\n\t_ = b[6] // bounds check hint to compiler; see golang.org/issue/14808\n\treturn uint64(b[6]) | uint64(b[5])\u003c\u003c8 | uint64(b[4])\u003c\u003c16 | uint64(b[3])\u003c\u003c24 |\n\t\tuint64(b[2])\u003c\u003c32 | uint64(b[1])\u003c\u003c40 | uint64(b[0])\u003c\u003c48\n}\n\n// bigEndianUint48 returns the uint64 value represented by the 6 bytes in big-endian order.\nfunc bigEndianUint48(b []byte) uint64 {\n\t_ = b[5] // bounds check hint to compiler; see golang.org/issue/14808\n\treturn uint64(b[5]) | uint64(b[4])\u003c\u003c8 | uint64(b[3])\u003c\u003c16 | uint64(b[2])\u003c\u003c24 |\n\t\tuint64(b[1])\u003c\u003c32 | uint64(b[0])\u003c\u003c40\n}\n"},{"name":"error.gno","body":"package uint256\n\nimport (\n\t\"errors\"\n)\n\nvar (\n\tErrEmptyString      = errors.New(\"empty hex string\")\n\tErrSyntax           = errors.New(\"invalid hex string\")\n\tErrRange            = errors.New(\"number out of range\")\n\tErrMissingPrefix    = errors.New(\"hex string without 0x prefix\")\n\tErrEmptyNumber      = errors.New(\"hex string \\\"0x\\\"\")\n\tErrLeadingZero      = errors.New(\"hex number with leading zero digits\")\n\tErrBig256Range      = errors.New(\"hex number \u003e 256 bits\")\n\tErrBadBufferLength  = errors.New(\"bad ssz buffer length\")\n\tErrBadEncodedLength = errors.New(\"bad ssz encoded length\")\n\tErrInvalidBase      = errors.New(\"invalid base\")\n\tErrInvalidBitSize   = errors.New(\"invalid bit size\")\n)\n\ntype u256Error struct {\n\tfn    string // function name\n\tinput string\n\terr   error\n}\n\nfunc (e *u256Error) Error() string {\n\treturn e.fn + \": \" + e.input + \": \" + e.err.Error()\n}\n\nfunc (e *u256Error) Unwrap() error {\n\treturn e.err\n}\n\nfunc errEmptyString(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrEmptyString}\n}\n\nfunc errSyntax(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrSyntax}\n}\n\nfunc errMissingPrefix(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrMissingPrefix}\n}\n\nfunc errEmptyNumber(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrEmptyNumber}\n}\n\nfunc errLeadingZero(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrLeadingZero}\n}\n\nfunc errRange(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrRange}\n}\n\nfunc errBig256Range(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrBig256Range}\n}\n\nfunc errBadBufferLength(fn, input string) error {\n\treturn \u0026u256Error{fn: fn, input: input, err: ErrBadBufferLength}\n}\n\nfunc errInvalidBase(fn string, base int) error {\n\treturn \u0026u256Error{fn: fn, input: string(base), err: ErrInvalidBase}\n}\n\nfunc errInvalidBitSize(fn string, bitSize int) error {\n\treturn \u0026u256Error{fn: fn, input: string(bitSize), err: ErrInvalidBitSize}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/onbloc/uint256/v0\"\ngno = \"0.9\"\n"},{"name":"mod.gno","body":"package uint256\n\nimport (\n\t\"math/bits\"\n)\n\n// Some utility functions\n\n// Reciprocal computes a 320-bit value representing 1/m\n//\n// Notes:\n// - specialized for m.arr[3] != 0, hence limited to 2^192 \u003c= m \u003c 2^256\n// - returns zero if m.arr[3] == 0\n// - starts with a 32-bit division, refines with newton-raphson iterations\nfunc Reciprocal(m *Uint) (mu [5]uint64) {\n\tif m.arr[3] == 0 {\n\t\treturn mu\n\t}\n\n\ts := bits.LeadingZeros64(m.arr[3]) // Replace with leadingZeros(m) for general case\n\tp := 255 - s                       // floor(log_2(m)), m\u003e0\n\n\t// 0 or a power of 2?\n\n\t// Check if at least one bit is set in m.arr[2], m.arr[1] or m.arr[0],\n\t// or at least two bits in m.arr[3]\n\n\tif m.arr[0]|m.arr[1]|m.arr[2]|(m.arr[3]\u0026(m.arr[3]-1)) == 0 {\n\n\t\tmu[4] = ^uint64(0) \u003e\u003e uint(p\u002663)\n\t\tmu[3] = ^uint64(0)\n\t\tmu[2] = ^uint64(0)\n\t\tmu[1] = ^uint64(0)\n\t\tmu[0] = ^uint64(0)\n\n\t\treturn mu\n\t}\n\n\t// Maximise division precision by left-aligning divisor\n\n\tvar (\n\t\ty  Uint   // left-aligned copy of m\n\t\tr0 uint32 // estimate of 2^31/y\n\t)\n\n\ty.Lsh(m, uint(s)) // 1/2 \u003c y \u003c 1\n\n\t// Extract most significant 32 bits\n\n\tyh := uint32(y.arr[3] \u003e\u003e 32)\n\n\tif yh == 0x80000000 { // Avoid overflow in division\n\t\tr0 = 0xffffffff\n\t} else {\n\t\tr0, _ = bits.Div32(0x80000000, 0, yh)\n\t}\n\n\t// First iteration: 32 -\u003e 64\n\n\tt1 := uint64(r0)                 // 2^31/y\n\tt1 *= t1                         // 2^62/y^2\n\tt1, _ = bits.Mul64(t1, y.arr[3]) // 2^62/y^2 * 2^64/y / 2^64 = 2^62/y\n\n\tr1 := uint64(r0) \u003c\u003c 32 // 2^63/y\n\tr1 -= t1               // 2^63/y - 2^62/y = 2^62/y\n\tr1 *= 2                // 2^63/y\n\n\tif (r1 | (y.arr[3] \u003c\u003c 1)) == 0 {\n\t\tr1 = ^uint64(0)\n\t}\n\n\t// Second iteration: 64 -\u003e 128\n\n\t// square: 2^126/y^2\n\ta2h, a2l := bits.Mul64(r1, r1)\n\n\t// multiply by y: e2h:e2l:b2h = 2^126/y^2 * 2^128/y / 2^128 = 2^126/y\n\tb2h, _ := bits.Mul64(a2l, y.arr[2])\n\tc2h, c2l := bits.Mul64(a2l, y.arr[3])\n\td2h, d2l := bits.Mul64(a2h, y.arr[2])\n\te2h, e2l := bits.Mul64(a2h, y.arr[3])\n\n\tb2h, c := bits.Add64(b2h, c2l, 0)\n\te2l, c = bits.Add64(e2l, c2h, c)\n\te2h, _ = bits.Add64(e2h, 0, c)\n\n\t_, c = bits.Add64(b2h, d2l, 0)\n\te2l, c = bits.Add64(e2l, d2h, c)\n\te2h, _ = bits.Add64(e2h, 0, c)\n\n\t// subtract: t2h:t2l = 2^127/y - 2^126/y = 2^126/y\n\tt2l, b := bits.Sub64(0, e2l, 0)\n\tt2h, _ := bits.Sub64(r1, e2h, b)\n\n\t// double: r2h:r2l = 2^127/y\n\tr2l, c := bits.Add64(t2l, t2l, 0)\n\tr2h, _ := bits.Add64(t2h, t2h, c)\n\n\tif (r2h | r2l | (y.arr[3] \u003c\u003c 1)) == 0 {\n\t\tr2h = ^uint64(0)\n\t\tr2l = ^uint64(0)\n\t}\n\n\t// Third iteration: 128 -\u003e 192\n\n\t// square r2 (keep 256 bits): 2^190/y^2\n\ta3h, a3l := bits.Mul64(r2l, r2l)\n\tb3h, b3l := bits.Mul64(r2l, r2h)\n\tc3h, c3l := bits.Mul64(r2h, r2h)\n\n\ta3h, c = bits.Add64(a3h, b3l, 0)\n\tc3l, c = bits.Add64(c3l, b3h, c)\n\tc3h, _ = bits.Add64(c3h, 0, c)\n\n\ta3h, c = bits.Add64(a3h, b3l, 0)\n\tc3l, c = bits.Add64(c3l, b3h, c)\n\tc3h, _ = bits.Add64(c3h, 0, c)\n\n\t// multiply by y: q = 2^190/y^2 * 2^192/y / 2^192 = 2^190/y\n\n\tx0 := a3l\n\tx1 := a3h\n\tx2 := c3l\n\tx3 := c3h\n\n\tvar q0, q1, q2, q3, q4, t0 uint64\n\n\tq0, _ = bits.Mul64(x2, y.arr[0])\n\tq1, t0 = bits.Mul64(x3, y.arr[0])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, _ = bits.Add64(q1, 0, c)\n\n\tt1, _ = bits.Mul64(x1, y.arr[1])\n\tq0, c = bits.Add64(q0, t1, 0)\n\tq2, t0 = bits.Mul64(x3, y.arr[1])\n\tq1, c = bits.Add64(q1, t0, c)\n\tq2, _ = bits.Add64(q2, 0, c)\n\n\tt1, t0 = bits.Mul64(x2, y.arr[1])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, c = bits.Add64(q1, t1, c)\n\tq2, _ = bits.Add64(q2, 0, c)\n\n\tt1, t0 = bits.Mul64(x1, y.arr[2])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, c = bits.Add64(q1, t1, c)\n\tq3, t0 = bits.Mul64(x3, y.arr[2])\n\tq2, c = bits.Add64(q2, t0, c)\n\tq3, _ = bits.Add64(q3, 0, c)\n\n\tt1, _ = bits.Mul64(x0, y.arr[2])\n\tq0, c = bits.Add64(q0, t1, 0)\n\tt1, t0 = bits.Mul64(x2, y.arr[2])\n\tq1, c = bits.Add64(q1, t0, c)\n\tq2, c = bits.Add64(q2, t1, c)\n\tq3, _ = bits.Add64(q3, 0, c)\n\n\tt1, t0 = bits.Mul64(x1, y.arr[3])\n\tq1, c = bits.Add64(q1, t0, 0)\n\tq2, c = bits.Add64(q2, t1, c)\n\tq4, t0 = bits.Mul64(x3, y.arr[3])\n\tq3, c = bits.Add64(q3, t0, c)\n\tq4, _ = bits.Add64(q4, 0, c)\n\n\tt1, t0 = bits.Mul64(x0, y.arr[3])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, c = bits.Add64(q1, t1, c)\n\tt1, t0 = bits.Mul64(x2, y.arr[3])\n\tq2, c = bits.Add64(q2, t0, c)\n\tq3, c = bits.Add64(q3, t1, c)\n\tq4, _ = bits.Add64(q4, 0, c)\n\n\t// subtract: t3 = 2^191/y - 2^190/y = 2^190/y\n\t_, b = bits.Sub64(0, q0, 0)\n\t_, b = bits.Sub64(0, q1, b)\n\tt3l, b := bits.Sub64(0, q2, b)\n\tt3m, b := bits.Sub64(r2l, q3, b)\n\tt3h, _ := bits.Sub64(r2h, q4, b)\n\n\t// double: r3 = 2^191/y\n\tr3l, c := bits.Add64(t3l, t3l, 0)\n\tr3m, c := bits.Add64(t3m, t3m, c)\n\tr3h, _ := bits.Add64(t3h, t3h, c)\n\n\t// Fourth iteration: 192 -\u003e 320\n\n\t// square r3\n\n\ta4h, a4l := bits.Mul64(r3l, r3l)\n\tb4h, b4l := bits.Mul64(r3l, r3m)\n\tc4h, c4l := bits.Mul64(r3l, r3h)\n\td4h, d4l := bits.Mul64(r3m, r3m)\n\te4h, e4l := bits.Mul64(r3m, r3h)\n\tf4h, f4l := bits.Mul64(r3h, r3h)\n\n\tb4h, c = bits.Add64(b4h, c4l, 0)\n\te4l, c = bits.Add64(e4l, c4h, c)\n\te4h, _ = bits.Add64(e4h, 0, c)\n\n\ta4h, c = bits.Add64(a4h, b4l, 0)\n\td4l, c = bits.Add64(d4l, b4h, c)\n\td4h, c = bits.Add64(d4h, e4l, c)\n\tf4l, c = bits.Add64(f4l, e4h, c)\n\tf4h, _ = bits.Add64(f4h, 0, c)\n\n\ta4h, c = bits.Add64(a4h, b4l, 0)\n\td4l, c = bits.Add64(d4l, b4h, c)\n\td4h, c = bits.Add64(d4h, e4l, c)\n\tf4l, c = bits.Add64(f4l, e4h, c)\n\tf4h, _ = bits.Add64(f4h, 0, c)\n\n\t// multiply by y\n\n\tx1, x0 = bits.Mul64(d4h, y.arr[0])\n\tx3, x2 = bits.Mul64(f4h, y.arr[0])\n\tt1, t0 = bits.Mul64(f4l, y.arr[0])\n\tx1, c = bits.Add64(x1, t0, 0)\n\tx2, c = bits.Add64(x2, t1, c)\n\tx3, _ = bits.Add64(x3, 0, c)\n\n\tt1, t0 = bits.Mul64(d4h, y.arr[1])\n\tx1, c = bits.Add64(x1, t0, 0)\n\tx2, c = bits.Add64(x2, t1, c)\n\tx4, t0 := bits.Mul64(f4h, y.arr[1])\n\tx3, c = bits.Add64(x3, t0, c)\n\tx4, _ = bits.Add64(x4, 0, c)\n\tt1, t0 = bits.Mul64(d4l, y.arr[1])\n\tx0, c = bits.Add64(x0, t0, 0)\n\tx1, c = bits.Add64(x1, t1, c)\n\tt1, t0 = bits.Mul64(f4l, y.arr[1])\n\tx2, c = bits.Add64(x2, t0, c)\n\tx3, c = bits.Add64(x3, t1, c)\n\tx4, _ = bits.Add64(x4, 0, c)\n\n\tt1, t0 = bits.Mul64(a4h, y.arr[2])\n\tx0, c = bits.Add64(x0, t0, 0)\n\tx1, c = bits.Add64(x1, t1, c)\n\tt1, t0 = bits.Mul64(d4h, y.arr[2])\n\tx2, c = bits.Add64(x2, t0, c)\n\tx3, c = bits.Add64(x3, t1, c)\n\tx5, t0 := bits.Mul64(f4h, y.arr[2])\n\tx4, c = bits.Add64(x4, t0, c)\n\tx5, _ = bits.Add64(x5, 0, c)\n\tt1, t0 = bits.Mul64(d4l, y.arr[2])\n\tx1, c = bits.Add64(x1, t0, 0)\n\tx2, c = bits.Add64(x2, t1, c)\n\tt1, t0 = bits.Mul64(f4l, y.arr[2])\n\tx3, c = bits.Add64(x3, t0, c)\n\tx4, c = bits.Add64(x4, t1, c)\n\tx5, _ = bits.Add64(x5, 0, c)\n\n\tt1, t0 = bits.Mul64(a4h, y.arr[3])\n\tx1, c = bits.Add64(x1, t0, 0)\n\tx2, c = bits.Add64(x2, t1, c)\n\tt1, t0 = bits.Mul64(d4h, y.arr[3])\n\tx3, c = bits.Add64(x3, t0, c)\n\tx4, c = bits.Add64(x4, t1, c)\n\tx6, t0 := bits.Mul64(f4h, y.arr[3])\n\tx5, c = bits.Add64(x5, t0, c)\n\tx6, _ = bits.Add64(x6, 0, c)\n\tt1, t0 = bits.Mul64(a4l, y.arr[3])\n\tx0, c = bits.Add64(x0, t0, 0)\n\tx1, c = bits.Add64(x1, t1, c)\n\tt1, t0 = bits.Mul64(d4l, y.arr[3])\n\tx2, c = bits.Add64(x2, t0, c)\n\tx3, c = bits.Add64(x3, t1, c)\n\tt1, t0 = bits.Mul64(f4l, y.arr[3])\n\tx4, c = bits.Add64(x4, t0, c)\n\tx5, c = bits.Add64(x5, t1, c)\n\tx6, _ = bits.Add64(x6, 0, c)\n\n\t// subtract\n\t_, b = bits.Sub64(0, x0, 0)\n\t_, b = bits.Sub64(0, x1, b)\n\tr4l, b := bits.Sub64(0, x2, b)\n\tr4k, b := bits.Sub64(0, x3, b)\n\tr4j, b := bits.Sub64(r3l, x4, b)\n\tr4i, b := bits.Sub64(r3m, x5, b)\n\tr4h, _ := bits.Sub64(r3h, x6, b)\n\n\t// Multiply candidate for 1/4y by y, with full precision\n\n\tx0 = r4l\n\tx1 = r4k\n\tx2 = r4j\n\tx3 = r4i\n\tx4 = r4h\n\n\tq1, q0 = bits.Mul64(x0, y.arr[0])\n\tq3, q2 = bits.Mul64(x2, y.arr[0])\n\tq5, q4 := bits.Mul64(x4, y.arr[0])\n\n\tt1, t0 = bits.Mul64(x1, y.arr[0])\n\tq1, c = bits.Add64(q1, t0, 0)\n\tq2, c = bits.Add64(q2, t1, c)\n\tt1, t0 = bits.Mul64(x3, y.arr[0])\n\tq3, c = bits.Add64(q3, t0, c)\n\tq4, c = bits.Add64(q4, t1, c)\n\tq5, _ = bits.Add64(q5, 0, c)\n\n\tt1, t0 = bits.Mul64(x0, y.arr[1])\n\tq1, c = bits.Add64(q1, t0, 0)\n\tq2, c = bits.Add64(q2, t1, c)\n\tt1, t0 = bits.Mul64(x2, y.arr[1])\n\tq3, c = bits.Add64(q3, t0, c)\n\tq4, c = bits.Add64(q4, t1, c)\n\tq6, t0 := bits.Mul64(x4, y.arr[1])\n\tq5, c = bits.Add64(q5, t0, c)\n\tq6, _ = bits.Add64(q6, 0, c)\n\n\tt1, t0 = bits.Mul64(x1, y.arr[1])\n\tq2, c = bits.Add64(q2, t0, 0)\n\tq3, c = bits.Add64(q3, t1, c)\n\tt1, t0 = bits.Mul64(x3, y.arr[1])\n\tq4, c = bits.Add64(q4, t0, c)\n\tq5, c = bits.Add64(q5, t1, c)\n\tq6, _ = bits.Add64(q6, 0, c)\n\n\tt1, t0 = bits.Mul64(x0, y.arr[2])\n\tq2, c = bits.Add64(q2, t0, 0)\n\tq3, c = bits.Add64(q3, t1, c)\n\tt1, t0 = bits.Mul64(x2, y.arr[2])\n\tq4, c = bits.Add64(q4, t0, c)\n\tq5, c = bits.Add64(q5, t1, c)\n\tq7, t0 := bits.Mul64(x4, y.arr[2])\n\tq6, c = bits.Add64(q6, t0, c)\n\tq7, _ = bits.Add64(q7, 0, c)\n\n\tt1, t0 = bits.Mul64(x1, y.arr[2])\n\tq3, c = bits.Add64(q3, t0, 0)\n\tq4, c = bits.Add64(q4, t1, c)\n\tt1, t0 = bits.Mul64(x3, y.arr[2])\n\tq5, c = bits.Add64(q5, t0, c)\n\tq6, c = bits.Add64(q6, t1, c)\n\tq7, _ = bits.Add64(q7, 0, c)\n\n\tt1, t0 = bits.Mul64(x0, y.arr[3])\n\tq3, c = bits.Add64(q3, t0, 0)\n\tq4, c = bits.Add64(q4, t1, c)\n\tt1, t0 = bits.Mul64(x2, y.arr[3])\n\tq5, c = bits.Add64(q5, t0, c)\n\tq6, c = bits.Add64(q6, t1, c)\n\tq8, t0 := bits.Mul64(x4, y.arr[3])\n\tq7, c = bits.Add64(q7, t0, c)\n\tq8, _ = bits.Add64(q8, 0, c)\n\n\tt1, t0 = bits.Mul64(x1, y.arr[3])\n\tq4, c = bits.Add64(q4, t0, 0)\n\tq5, c = bits.Add64(q5, t1, c)\n\tt1, t0 = bits.Mul64(x3, y.arr[3])\n\tq6, c = bits.Add64(q6, t0, c)\n\tq7, c = bits.Add64(q7, t1, c)\n\tq8, _ = bits.Add64(q8, 0, c)\n\n\t// Final adjustment\n\n\t// subtract q from 1/4\n\t_, b = bits.Sub64(0, q0, 0)\n\t_, b = bits.Sub64(0, q1, b)\n\t_, b = bits.Sub64(0, q2, b)\n\t_, b = bits.Sub64(0, q3, b)\n\t_, b = bits.Sub64(0, q4, b)\n\t_, b = bits.Sub64(0, q5, b)\n\t_, b = bits.Sub64(0, q6, b)\n\t_, b = bits.Sub64(0, q7, b)\n\t_, b = bits.Sub64(uint64(1)\u003c\u003c62, q8, b)\n\n\t// decrement the result\n\tx0, t := bits.Sub64(r4l, 1, 0)\n\tx1, t = bits.Sub64(r4k, 0, t)\n\tx2, t = bits.Sub64(r4j, 0, t)\n\tx3, t = bits.Sub64(r4i, 0, t)\n\tx4, _ = bits.Sub64(r4h, 0, t)\n\n\t// commit the decrement if the subtraction underflowed (reciprocal was too large)\n\tif b != 0 {\n\t\tr4h, r4i, r4j, r4k, r4l = x4, x3, x2, x1, x0\n\t}\n\n\t// Shift to correct bit alignment, truncating excess bits\n\n\tp = (p \u0026 63) - 1\n\n\tx0, c = bits.Add64(r4l, r4l, 0)\n\tx1, c = bits.Add64(r4k, r4k, c)\n\tx2, c = bits.Add64(r4j, r4j, c)\n\tx3, c = bits.Add64(r4i, r4i, c)\n\tx4, _ = bits.Add64(r4h, r4h, c)\n\n\tif p \u003c 0 {\n\t\tr4h, r4i, r4j, r4k, r4l = x4, x3, x2, x1, x0\n\t\tp = 0 // avoid negative shift below\n\t}\n\n\t{\n\t\tr := uint(p)      // right shift\n\t\tl := uint(64 - r) // left shift\n\n\t\tx0 = (r4l \u003e\u003e r) | (r4k \u003c\u003c l)\n\t\tx1 = (r4k \u003e\u003e r) | (r4j \u003c\u003c l)\n\t\tx2 = (r4j \u003e\u003e r) | (r4i \u003c\u003c l)\n\t\tx3 = (r4i \u003e\u003e r) | (r4h \u003c\u003c l)\n\t\tx4 = (r4h \u003e\u003e r)\n\t}\n\n\tif p \u003e 0 {\n\t\tr4h, r4i, r4j, r4k, r4l = x4, x3, x2, x1, x0\n\t}\n\n\tmu[0] = r4l\n\tmu[1] = r4k\n\tmu[2] = r4j\n\tmu[3] = r4i\n\tmu[4] = r4h\n\n\treturn mu\n}\n\n// reduce4 computes the least non-negative residue of x modulo m\n//\n// requires a four-word modulus (m.arr[3] \u003e 1) and its inverse (mu)\nfunc reduce4(x [8]uint64, m *Uint, mu [5]uint64) (z Uint) {\n\t// NB: Most variable names in the comments match the pseudocode for\n\t// \tBarrett reduction in the Handbook of Applied Cryptography.\n\n\t// q1 = x/2^192\n\n\tx0 := x[3]\n\tx1 := x[4]\n\tx2 := x[5]\n\tx3 := x[6]\n\tx4 := x[7]\n\n\t// q2 = q1 * mu; q3 = q2 / 2^320\n\n\tvar q0, q1, q2, q3, q4, q5, t0, t1, c uint64\n\n\tq0, _ = bits.Mul64(x3, mu[0])\n\tq1, t0 = bits.Mul64(x4, mu[0])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, _ = bits.Add64(q1, 0, c)\n\n\tt1, _ = bits.Mul64(x2, mu[1])\n\tq0, c = bits.Add64(q0, t1, 0)\n\tq2, t0 = bits.Mul64(x4, mu[1])\n\tq1, c = bits.Add64(q1, t0, c)\n\tq2, _ = bits.Add64(q2, 0, c)\n\n\tt1, t0 = bits.Mul64(x3, mu[1])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, c = bits.Add64(q1, t1, c)\n\tq2, _ = bits.Add64(q2, 0, c)\n\n\tt1, t0 = bits.Mul64(x2, mu[2])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, c = bits.Add64(q1, t1, c)\n\tq3, t0 = bits.Mul64(x4, mu[2])\n\tq2, c = bits.Add64(q2, t0, c)\n\tq3, _ = bits.Add64(q3, 0, c)\n\n\tt1, _ = bits.Mul64(x1, mu[2])\n\tq0, c = bits.Add64(q0, t1, 0)\n\tt1, t0 = bits.Mul64(x3, mu[2])\n\tq1, c = bits.Add64(q1, t0, c)\n\tq2, c = bits.Add64(q2, t1, c)\n\tq3, _ = bits.Add64(q3, 0, c)\n\n\tt1, _ = bits.Mul64(x0, mu[3])\n\tq0, c = bits.Add64(q0, t1, 0)\n\tt1, t0 = bits.Mul64(x2, mu[3])\n\tq1, c = bits.Add64(q1, t0, c)\n\tq2, c = bits.Add64(q2, t1, c)\n\tq4, t0 = bits.Mul64(x4, mu[3])\n\tq3, c = bits.Add64(q3, t0, c)\n\tq4, _ = bits.Add64(q4, 0, c)\n\n\tt1, t0 = bits.Mul64(x1, mu[3])\n\tq0, c = bits.Add64(q0, t0, 0)\n\tq1, c = bits.Add64(q1, t1, c)\n\tt1, t0 = bits.Mul64(x3, mu[3])\n\tq2, c = bits.Add64(q2, t0, c)\n\tq3, c = bits.Add64(q3, t1, c)\n\tq4, _ = bits.Add64(q4, 0, c)\n\n\tt1, t0 = bits.Mul64(x0, mu[4])\n\t_, c = bits.Add64(q0, t0, 0)\n\tq1, c = bits.Add64(q1, t1, c)\n\tt1, t0 = bits.Mul64(x2, mu[4])\n\tq2, c = bits.Add64(q2, t0, c)\n\tq3, c = bits.Add64(q3, t1, c)\n\tq5, t0 = bits.Mul64(x4, mu[4])\n\tq4, c = bits.Add64(q4, t0, c)\n\tq5, _ = bits.Add64(q5, 0, c)\n\n\tt1, t0 = bits.Mul64(x1, mu[4])\n\tq1, c = bits.Add64(q1, t0, 0)\n\tq2, c = bits.Add64(q2, t1, c)\n\tt1, t0 = bits.Mul64(x3, mu[4])\n\tq3, c = bits.Add64(q3, t0, c)\n\tq4, c = bits.Add64(q4, t1, c)\n\tq5, _ = bits.Add64(q5, 0, c)\n\n\t// Drop the fractional part of q3\n\n\tq0 = q1\n\tq1 = q2\n\tq2 = q3\n\tq3 = q4\n\tq4 = q5\n\n\t// r1 = x mod 2^320\n\n\tx0 = x[0]\n\tx1 = x[1]\n\tx2 = x[2]\n\tx3 = x[3]\n\tx4 = x[4]\n\n\t// r2 = q3 * m mod 2^320\n\n\tvar r0, r1, r2, r3, r4 uint64\n\n\tr4, r3 = bits.Mul64(q0, m.arr[3])\n\t_, t0 = bits.Mul64(q1, m.arr[3])\n\tr4, _ = bits.Add64(r4, t0, 0)\n\n\tt1, r2 = bits.Mul64(q0, m.arr[2])\n\tr3, c = bits.Add64(r3, t1, 0)\n\t_, t0 = bits.Mul64(q2, m.arr[2])\n\tr4, _ = bits.Add64(r4, t0, c)\n\n\tt1, t0 = bits.Mul64(q1, m.arr[2])\n\tr3, c = bits.Add64(r3, t0, 0)\n\tr4, _ = bits.Add64(r4, t1, c)\n\n\tt1, r1 = bits.Mul64(q0, m.arr[1])\n\tr2, c = bits.Add64(r2, t1, 0)\n\tt1, t0 = bits.Mul64(q2, m.arr[1])\n\tr3, c = bits.Add64(r3, t0, c)\n\tr4, _ = bits.Add64(r4, t1, c)\n\n\tt1, t0 = bits.Mul64(q1, m.arr[1])\n\tr2, c = bits.Add64(r2, t0, 0)\n\tr3, c = bits.Add64(r3, t1, c)\n\t_, t0 = bits.Mul64(q3, m.arr[1])\n\tr4, _ = bits.Add64(r4, t0, c)\n\n\tt1, r0 = bits.Mul64(q0, m.arr[0])\n\tr1, c = bits.Add64(r1, t1, 0)\n\tt1, t0 = bits.Mul64(q2, m.arr[0])\n\tr2, c = bits.Add64(r2, t0, c)\n\tr3, c = bits.Add64(r3, t1, c)\n\t_, t0 = bits.Mul64(q4, m.arr[0])\n\tr4, _ = bits.Add64(r4, t0, c)\n\n\tt1, t0 = bits.Mul64(q1, m.arr[0])\n\tr1, c = bits.Add64(r1, t0, 0)\n\tr2, c = bits.Add64(r2, t1, c)\n\tt1, t0 = bits.Mul64(q3, m.arr[0])\n\tr3, c = bits.Add64(r3, t0, c)\n\tr4, _ = bits.Add64(r4, t1, c)\n\n\t// r = r1 - r2\n\n\tvar b uint64\n\n\tr0, b = bits.Sub64(x0, r0, 0)\n\tr1, b = bits.Sub64(x1, r1, b)\n\tr2, b = bits.Sub64(x2, r2, b)\n\tr3, b = bits.Sub64(x3, r3, b)\n\tr4, b = bits.Sub64(x4, r4, b)\n\n\t// if r\u003c0 then r+=m\n\n\tif b != 0 {\n\t\tr0, c = bits.Add64(r0, m.arr[0], 0)\n\t\tr1, c = bits.Add64(r1, m.arr[1], c)\n\t\tr2, c = bits.Add64(r2, m.arr[2], c)\n\t\tr3, c = bits.Add64(r3, m.arr[3], c)\n\t\tr4, _ = bits.Add64(r4, 0, c)\n\t}\n\n\t// while (r\u003e=m) r-=m\n\n\tfor {\n\t\t// q = r - m\n\t\tq0, b = bits.Sub64(r0, m.arr[0], 0)\n\t\tq1, b = bits.Sub64(r1, m.arr[1], b)\n\t\tq2, b = bits.Sub64(r2, m.arr[2], b)\n\t\tq3, b = bits.Sub64(r3, m.arr[3], b)\n\t\tq4, b = bits.Sub64(r4, 0, b)\n\n\t\t// if borrow break\n\t\tif b != 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// r = q\n\t\tr4, r3, r2, r1, r0 = q4, q3, q2, q1, q0\n\t}\n\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = r3, r2, r1, r0\n\n\treturn z\n}\n"},{"name":"uint256.gno","body":"// Ported from https://github.com/holiman/uint256\n// This package provides a 256-bit unsigned integer type, Uint256, and associated functions.\npackage uint256\n\nimport (\n\t\"errors\"\n\t\"math/bits\"\n\t\"strconv\"\n)\n\nconst (\n\tMaxUint64 = 1\u003c\u003c64 - 1\n\tuintSize  = 32 \u003c\u003c (^uint(0) \u003e\u003e 63)\n)\n\n// Uint is represented as an array of 4 uint64, in little-endian order,\n// so that Uint[3] is the most significant, and Uint[0] is the least significant\ntype Uint struct {\n\tarr [4]uint64\n}\n\n// NewUint returns a new initialized Uint.\nfunc NewUint(val uint64) *Uint {\n\tz := \u0026Uint{arr: [4]uint64{val, 0, 0, 0}}\n\treturn z\n}\n\n// Zero returns a new Uint initialized to zero.\nfunc Zero() *Uint {\n\treturn NewUint(0)\n}\n\n// One returns a new Uint initialized to one.\nfunc One() *Uint {\n\treturn NewUint(1)\n}\n\n// SetAllOne sets all the bits of z to 1\nfunc (z *Uint) SetAllOne() *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, MaxUint64\n\treturn z\n}\n\n// Set sets z to x and returns z.\nfunc (z *Uint) Set(x *Uint) *Uint {\n\t*z = *x\n\n\treturn z\n}\n\n// SetOne sets z to 1\nfunc (z *Uint) SetOne() *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 1\n\treturn z\n}\n\nconst twoPow256Sub1 = \"115792089237316195423570985008687907853269984665640564039457584007913129639935\"\n\n// SetFromDecimal sets z from the given string, interpreted as a decimal number.\n// OBS! This method is _not_ strictly identical to the (*big.Uint).SetString(..., 10) method.\n// Notable differences:\n// - This method does not accept underscore input, e.g. \"100_000\",\n// - This method does not accept negative zero as valid, e.g \"-0\",\n//   - (this method does not accept any negative input as valid))\nfunc (z *Uint) SetFromDecimal(s string) (err error) {\n\t// Remove max one leading +\n\tif len(s) \u003e 0 \u0026\u0026 s[0] == '+' {\n\t\ts = s[1:]\n\t}\n\t// Remove any number of leading zeroes\n\tif len(s) \u003e 0 \u0026\u0026 s[0] == '0' {\n\t\tvar i int\n\t\tvar c rune\n\t\tfor i, c = range s {\n\t\t\tif c != '0' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ts = s[i:]\n\t}\n\tif len(s) \u003c len(twoPow256Sub1) {\n\t\treturn z.fromDecimal(s)\n\t}\n\tif len(s) == len(twoPow256Sub1) {\n\t\tif s \u003e twoPow256Sub1 {\n\t\t\treturn ErrBig256Range\n\t\t}\n\t\treturn z.fromDecimal(s)\n\t}\n\treturn ErrBig256Range\n}\n\n// FromDecimal is a convenience-constructor to create an Uint from a\n// decimal (base 10) string. Numbers larger than 256 bits are not accepted.\nfunc FromDecimal(decimal string) (*Uint, error) {\n\tvar z Uint\n\tif err := z.SetFromDecimal(decimal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026z, nil\n}\n\n// MustFromDecimal is a convenience-constructor to create an Uint from a\n// decimal (base 10) string.\n// Returns a new Uint and panics if any error occurred.\nfunc MustFromDecimal(decimal string) *Uint {\n\tvar z Uint\n\tif err := z.SetFromDecimal(decimal); err != nil {\n\t\tpanic(err)\n\t}\n\treturn \u0026z\n}\n\n// multipliers holds the values that are needed for fromDecimal\nvar multipliers = [5]*Uint{\n\tnil, // represents first round, no multiplication needed\n\t{[4]uint64{10000000000000000000, 0, 0, 0}},                                     // 10 ^ 19\n\t{[4]uint64{687399551400673280, 5421010862427522170, 0, 0}},                     // 10 ^ 38\n\t{[4]uint64{5332261958806667264, 17004971331911604867, 2938735877055718769, 0}}, // 10 ^ 57\n\t{[4]uint64{0, 8607968719199866880, 532749306367912313, 1593091911132452277}},   // 10 ^ 76\n}\n\n// fromDecimal is a helper function to only ever be called via SetFromDecimal\n// this function takes a string and chunks it up, calling ParseUint on it up to 5 times\n// these chunks are then multiplied by the proper power of 10, then added together.\nfunc (z *Uint) fromDecimal(bs string) error {\n\t// first clear the input\n\tz.Clear()\n\t// the maximum value of uint64 is 18446744073709551615, which is 20 characters\n\t// one less means that a string of 19 9's is always within the uint64 limit\n\tvar (\n\t\tnum       uint64\n\t\terr       error\n\t\tremaining = len(bs)\n\t)\n\tif remaining == 0 {\n\t\treturn errors.New(\"EOF\")\n\t}\n\t// We proceed in steps of 19 characters (nibbles), from least significant to most significant.\n\t// This means that the first (up to) 19 characters do not need to be multiplied.\n\t// In the second iteration, our slice of 19 characters needs to be multipleied\n\t// by a factor of 10^19. Et cetera.\n\tfor i, mult := range multipliers {\n\t\tif remaining \u003c= 0 {\n\t\t\treturn nil // Done\n\t\t} else if remaining \u003e 19 {\n\t\t\tnum, err = strconv.ParseUint(bs[remaining-19:remaining], 10, 64)\n\t\t} else {\n\t\t\t// Final round\n\t\t\tnum, err = strconv.ParseUint(bs, 10, 64)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// add that number to our running total\n\t\tif i == 0 {\n\t\t\tz.SetUint64(num)\n\t\t} else {\n\t\t\tbase := NewUint(num)\n\t\t\tz.Add(z, base.Mul(base, mult))\n\t\t}\n\t\t// Chop off another 19 characters\n\t\tif remaining \u003e 19 {\n\t\t\tbs = bs[0 : remaining-19]\n\t\t}\n\t\tremaining -= 19\n\t}\n\treturn nil\n}\n\n// Byte sets z to the value of the byte at position n,\n// with 'z' considered as a big-endian 32-byte integer\n// if 'n' \u003e 32, f is set to 0\n// Example: f = '5', n=31 =\u003e 5\nfunc (z *Uint) Byte(n *Uint) *Uint {\n\t// in z, z.arr[0] is the least significant\n\tif number, overflow := n.Uint64WithOverflow(); !overflow {\n\t\tif number \u003c 32 {\n\t\t\tnumber := z.arr[4-1-number/8]\n\t\t\toffset := (n.arr[0] \u0026 0x7) \u003c\u003c 3 // 8*(n.d % 8)\n\t\t\tz.arr[0] = (number \u0026 (0xff00000000000000 \u003e\u003e offset)) \u003e\u003e (56 - offset)\n\t\t\tz.arr[3], z.arr[2], z.arr[1] = 0, 0, 0\n\t\t\treturn z\n\t\t}\n\t}\n\n\treturn z.Clear()\n}\n\n// BitLen returns the number of bits required to represent z\nfunc (z *Uint) BitLen() int {\n\tswitch {\n\tcase z.arr[3] != 0:\n\t\treturn 192 + bits.Len64(z.arr[3])\n\tcase z.arr[2] != 0:\n\t\treturn 128 + bits.Len64(z.arr[2])\n\tcase z.arr[1] != 0:\n\t\treturn 64 + bits.Len64(z.arr[1])\n\tdefault:\n\t\treturn bits.Len64(z.arr[0])\n\t}\n}\n\n// ByteLen returns the number of bytes required to represent z\nfunc (z *Uint) ByteLen() int {\n\treturn (z.BitLen() + 7) / 8\n}\n\n// Clear sets z to 0\nfunc (z *Uint) Clear() *Uint {\n\tz.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 0\n\treturn z\n}\n\nconst (\n\t// hextable  = \"0123456789abcdef\"\n\tbintable  = \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\a\\b\\t\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\n\\v\\f\\r\\x0e\\x0f\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\n\\v\\f\\r\\x0e\\x0f\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"\n\tbadNibble = 0xff\n)\n\n// SetFromHex sets z from the given string, interpreted as a hexadecimal number.\n// OBS! This method is _not_ strictly identical to the (*big.Int).SetString(..., 16) method.\n// Notable differences:\n// - This method _require_ \"0x\" or \"0X\" prefix.\n// - This method does not accept zero-prefixed hex, e.g. \"0x0001\"\n// - This method does not accept underscore input, e.g. \"100_000\",\n// - This method does not accept negative zero as valid, e.g \"-0x0\",\n//   - (this method does not accept any negative input as valid)\nfunc (z *Uint) SetFromHex(hex string) error {\n\treturn z.fromHex(hex)\n}\n\n// fromHex is the internal implementation of parsing a hex-string.\nfunc (z *Uint) fromHex(hex string) error {\n\tif err := checkNumberS(hex); err != nil {\n\t\treturn err\n\t}\n\tif len(hex) \u003e 66 {\n\t\treturn ErrBig256Range\n\t}\n\tz.Clear()\n\tend := len(hex)\n\tfor i := 0; i \u003c 4; i++ {\n\t\tstart := end - 16\n\t\tif start \u003c 2 {\n\t\t\tstart = 2\n\t\t}\n\t\tfor ri := start; ri \u003c end; ri++ {\n\t\t\tnib := bintable[hex[ri]]\n\t\t\tif nib == badNibble {\n\t\t\t\treturn ErrSyntax\n\t\t\t}\n\t\t\tz.arr[i] = z.arr[i] \u003c\u003c 4\n\t\t\tz.arr[i] += uint64(nib)\n\t\t}\n\t\tend = start\n\t}\n\treturn nil\n}\n\n// FromHex is a convenience-constructor to create an Uint from\n// a hexadecimal string. The string is required to be '0x'-prefixed\n// Numbers larger than 256 bits are not accepted.\nfunc FromHex(hex string) (*Uint, error) {\n\tvar z Uint\n\tif err := z.fromHex(hex); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026z, nil\n}\n\n// MustFromHex is a convenience-constructor to create an Uint from\n// a hexadecimal string.\n// Returns a new Uint and panics if any error occurred.\nfunc MustFromHex(hex string) *Uint {\n\tvar z Uint\n\tif err := z.fromHex(hex); err != nil {\n\t\tpanic(err)\n\t}\n\treturn \u0026z\n}\n\n// Clone creates a new Uint identical to z\nfunc (z *Uint) Clone() *Uint {\n\tvar x Uint\n\tx.arr[0] = z.arr[0]\n\tx.arr[1] = z.arr[1]\n\tx.arr[2] = z.arr[2]\n\tx.arr[3] = z.arr[3]\n\n\treturn \u0026x\n}\n"},{"name":"utils.gno","body":"package uint256\n\nfunc checkNumberS(input string) error {\n\tconst fn = \"UnmarshalText\"\n\tl := len(input)\n\tif l == 0 {\n\t\treturn errEmptyString(fn, input)\n\t}\n\tif l \u003c 2 || input[0] != '0' ||\n\t\t(input[1] != 'x' \u0026\u0026 input[1] != 'X') {\n\t\treturn errMissingPrefix(fn, input)\n\t}\n\tif l == 2 {\n\t\treturn errEmptyNumber(fn, input)\n\t}\n\tif len(input) \u003e 3 \u0026\u0026 input[2] == '0' {\n\t\treturn errLeadingZero(fn, input)\n\t}\n\treturn nil\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"issue5736_common","path":"gno.land/r/tests/issue5736_common","files":[{"name":"common.gno","body":"// Package issue5736_common is a regression fixture for\n// https://github.com/gnolang/gno/issues/5736.\n//\n// It mimics the gnoswap pattern that surfaced the bug: a non-crossing\n// helper in an /r/ realm that performs in-place uint256 arithmetic on\n// a value handed in from another /r/ realm. Before the fix to\n// {Array,Struct}Value.Copy, this triggered:\n//\n//\tpanic: cannot directly modify readonly tainted object\n//\t  gno.land/p/onbloc/uint256/v0/bitwise.gno (z.arr[0] = z.arr[0] \u003c\u003c n)\npackage issue5736_common\n\nimport (\n\tu256 \"gno.land/p/onbloc/uint256/v0\"\n)\n\nfunc DoLsh(x *u256.Uint, n uint) *u256.Uint {\n\treturn u256.Zero().Lsh(x, n)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/issue5736_common\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"issue5736_bar","path":"gno.land/r/tests/issue5736_bar","files":[{"name":"bar.gno","body":"// Package issue5736_bar is the caller-side fixture for\n// https://github.com/gnolang/gno/issues/5736. See the sibling\n// gno.land/r/tests/issue5736_common package for context.\npackage issue5736_bar\n\nimport (\n\tu256 \"gno.land/p/onbloc/uint256/v0\"\n\t\"gno.land/r/tests/issue5736_common\"\n)\n\nfunc Call(cur realm) string {\n\tout := issue5736_common.DoLsh(u256.NewUint(123), 1)\n\treturn out.Dec()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/issue5736_bar\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"p_crossrealm","path":"gno.land/p/demo/tests/p_crossrealm/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/p_crossrealm/v0\"\ngno = \"0.9\"\n"},{"name":"p_crossrealm.gno","body":"package p_crossrealm\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n)\n\ntype Stringer interface {\n\tString() string\n}\n\ntype Container struct {\n\tA int\n\tB Stringer\n}\n\nfunc (c *Container) Touch() *Container {\n\tc.A += 1\n\treturn c\n}\n\nfunc (c *Container) Print() {\n\tprintln(\"A:\", c.A)\n\tif c.B == nil {\n\t\tprintln(\"B: undefined\")\n\t} else {\n\t\tprintln(\"B:\", c.B.String())\n\t}\n}\n\nfunc CurrentRealm() runtime.Realm {\n\treturn unsafe.CurrentRealm()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"crossrealm","path":"gno.land/r/tests/vm/crossrealm","files":[{"name":"crossrealm.gno","body":"package crossrealm\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/demo/tests/p_crossrealm/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype LocalStruct struct {\n\tA int\n}\n\nfunc (ls *LocalStruct) String() string {\n\treturn ufmt.Sprintf(\"LocalStruct{%d}\", ls.A)\n}\n\n// local is saved locally in this realm\nvar local *LocalStruct\n\nfunc init() {\n\tlocal = \u0026LocalStruct{A: 123}\n}\n\n// Make1 returns a local object wrapped by a p struct\nfunc Make1() *p_crossrealm.Container {\n\treturn \u0026p_crossrealm.Container{\n\t\tA: 1,\n\t\tB: local,\n\t}\n}\n\ntype Fooer interface {\n\tFoo(realm)\n\tBar()\n}\n\nvar fooer Fooer\n\nfunc SetFooer(cur realm, f Fooer) Fooer {\n\tfooer = f\n\treturn fooer\n}\n\nfunc GetFooer() Fooer {\n\treturn fooer\n}\n\nfunc CallFooerFooCur(cur realm) {\n\tfooer.Foo(cur)\n}\n\nfunc CallFooerFooCross(cur realm) {\n\tfooer.Foo(cross(cur))\n}\n\nfunc CallFooerBar() {\n\tfooer.Bar()\n}\n\nfunc CallFooerBarCrossing(cur realm) {\n\tfooer.Bar()\n}\n\ntype FooerGetter func() Fooer\n\nvar fooerGetter FooerGetter\n\nfunc SetFooerGetter(cur realm, fg FooerGetter) FooerGetter {\n\tfooerGetter = fg\n\treturn fg\n}\n\nfunc GetFooerGetter() FooerGetter {\n\treturn fooerGetter\n}\n\nfunc CallFooerGetterBar() {\n\tfooerGetter().Bar()\n}\n\nfunc CallFooerGetterBarCrossing(cur realm) {\n\tfooerGetter().Bar()\n}\n\nfunc CallFooerGetterFooCur(cur realm) {\n\tfooerGetter().Foo(cur)\n}\n\nfunc CallFooerGetterFooCross(cur realm) {\n\tfooerGetter().Foo(cross(cur))\n}\n\n// This is a top function that does switch realms.\nfunc ExecCrossing(cur realm, cb func() string) string {\n\treturn cb()\n}\n\n// This is a top function that doesn't switch realms.\nfunc Exec(cb func() string) string {\n\treturn cb()\n}\n\n// ------------------------------------\n// SECURITY XXX: Closure and Closure2 below are exported package-level\n// function-typed vars that any foreign realm can set via SetClosure /\n// SetClosure2 and trigger via ExecuteClosure / ExecuteClosureCross.\n// Closure2's signature is `func(realm)`, which means whoever sets it\n// receives a realm value at invocation time — capability-bearing data\n// stored in an exported package var, then handed back to caller-supplied\n// code. THIS IS DELIBERATE VM-PARITY-TEST INFRASTRUCTURE — these vars\n// exist to exercise the VM's handling of stored closures and cross-\n// realm callbacks. DO NOT COPY THIS PATTERN IN PRODUCTION CODE. Real\n// /r/ realms must never expose `func(realm)` (or any function-typed\n// value capable of receiving cur) as an exported package var.\nvar Closure func()\n\nfunc SetClosure(cur realm, f func()) {\n\tClosure = f\n}\n\nfunc ExecuteClosure(cur realm) {\n\tClosure()\n}\n\nvar Closure2 func(realm)\n\nfunc SetClosure2(cur realm, f func(realm)) {\n\tClosure2 = f\n}\nfunc ExecuteClosureCross(cur realm) {\n\tClosure2(cross(cur))\n}\n\n// Closure3 mirrors Closure but for non-crossing-with-rlm closures —\n// `func(_ int, rlm realm)`. Whoever sets Closure3 receives cur as a\n// plain value (no realm boundary at invocation time), then can cross\n// internally via cross(rlm).\nvar Closure3 func(_ int, rlm realm)\n\nfunc SetClosure3(cur realm, f func(_ int, rlm realm)) {\n\tClosure3 = f\n}\n\nfunc ExecuteClosure3(cur realm) {\n\tClosure3(0, cur)\n}\n\n// Closure -\u003e FooUpdate\nfunc PrintRealms(cur realm) {\n\tufmt.Printf(\"current realm: %s\\n\", unsafe.CurrentRealm())\n\tufmt.Printf(\"previous realm: %s\\n\", unsafe.PreviousRealm())\n}\n\n// -------------------------------------------------\nvar Object any\n\nfunc SetObject(cur realm, x any) {\n\tObject = x\n}\n\nfunc GetObject() any {\n\treturn Object\n}\n\nfunc EntryPoint() (noCros *ownable.Ownable) {\n\tprintln(\"crossrealm  EntryPoint: \" + unsafe.PreviousRealm().PkgPath())\n\tprintln(\"crossrealm  EntryPoint: \" + unsafe.PreviousRealm().Address())\n\tprintln()\n\treturn PrevRealmNoCrossing()\n}\n\n// EntryPointWithCrossing is a non-crossing helper that forwards into\n// the (cur realm)-crossing PrevRealmCrossing. Callers pass their own\n// live cur; `cross(rlm)` does the actual cross.\nfunc EntryPointWithCrossing(_ int, rlm realm) (withCros *ownable.Ownable) {\n\treturn PrevRealmCrossing(cross(rlm))\n}\n\nfunc PrevRealmNoCrossing() *ownable.Ownable {\n\tprintln(\"crossrealm PreviousRealm no crossing: \" + unsafe.PreviousRealm().PkgPath())\n\tprintln(\"crossrealm PreviousRealm no crossing: \" + unsafe.PreviousRealm().Address())\n\treturn ownable.NewWithAddress(unsafe.CurrentRealm().Address())\n}\n\nfunc PrevRealmCrossing(cur realm) *ownable.Ownable {\n\tprintln(\"crossrealm PreviousRealm with crossing: \" + unsafe.PreviousRealm().PkgPath())\n\tprintln(\"crossrealm PreviousRealm with crossing: \" + unsafe.PreviousRealm().Address())\n\treturn ownable.NewWithAddress(cur.Address())\n}\n\nfunc CurRealmNoCrossing() runtime.Realm {\n\treturn unsafe.CurrentRealm()\n}\nfunc CurRealmCrossing(cur realm) runtime.Realm {\n\treturn unsafe.CurrentRealm()\n}\n\n// call the package that returns current realm\nfunc PkgCurRealmNoCrossing() runtime.Realm {\n\treturn p_crossrealm.CurrentRealm()\n}\n\n// call the package that returns current realm\nfunc PkgCurRealmCrossing(cur realm) runtime.Realm {\n\treturn unsafe.CurrentRealm()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/crossrealm\"\ngno = \"0.9\"\n"},{"name":"switchrealm.gno","body":"package crossrealm\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"crossrealm_d","path":"gno.land/r/tests/vm/crossrealm_d","files":[{"name":"crossrealm.gno","body":"package crossrealm_d\n\n// Simple stateful realm for cross-realm consistency tests.\n// Separated from crossrealm_b to avoid perturbing its object IDs.\n//\n// Contains both crossing and non-crossing setters so tests can\n// demonstrate that non-crossing calls from another realm cannot\n// silently mutate state via assign+recover.\n\nvar counter int\n\nfunc init() {\n\tcounter = 100\n}\n\n// SetCounter: non-crossing. Calling this cross-realm triggers\n// the readonly check because it directly assigns a package var.\nfunc SetCounter(n int) {\n\tcounter = n\n}\n\n// SetCounterCrossing: crossing version. This works correctly\n// cross-realm because the caller enters this realm's context.\nfunc SetCounterCrossing(cur realm, n int) {\n\tcounter = n\n}\n\nfunc GetCounter(cur realm) int {\n\treturn counter\n}\n\n// DoubleCounter reads counter and doubles it. Used to show that\n// if counter were silently corrupted in memory, subsequent crossing\n// calls would act on the wrong value.\nfunc DoubleCounter(cur realm) int {\n\tcounter = counter * 2\n\treturn counter\n}\n\n// MutateBytes mutates the first byte of bz to 0xff. Used to test\n// whether a foreign realm can write to caller-allocated bytes.\n// Under storage=authority, bz has PkgID=caller; borrow rule #1 here\n// makes m.Realm=crossrealm_d (declaring realm); the write site\n// (bz[0] = ...) should fire readonly because bz.PkgID != m.Realm.ID.\nfunc MutateBytes(bz []byte) {\n\tbz[0] = 0xff\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/crossrealm_d\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"message","path":"gno.land/p/jeronimoalbi/message/v0","files":[{"name":"broker.gno","body":"package message\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/ulist/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nvar (\n\t// ErrInvalidTopic is triggered when an invalid topic is used.\n\tErrInvalidTopic = errors.New(\"invalid topic\")\n\n\t// ErrRequiredCallback is triggered when subscribing without a callback.\n\tErrRequiredCallback = errors.New(\"message callback is required\")\n\n\t// ErrRequiredSubscriptionID is triggered when unsubscribing without an ID.\n\tErrRequiredSubscriptionID = errors.New(\"message sibscription ID is required\")\n\n\t// ErrRequiredTopic is triggered when (un)subscribing without a topic.\n\tErrRequiredTopic = errors.New(\"message topic is required\")\n)\n\n// NewBroker creates a new message broker.\nfunc NewBroker() *Broker {\n\treturn \u0026Broker{}\n}\n\n// Broker is a message broker that handles subscriptions and message publishing.\ntype Broker struct {\n\tcallbacks avl.Tree // string(topic) -\u003e *ulist.List(Callback)\n}\n\n// Topics returns the list of current subscription topics.\nfunc (b Broker) Topics() []Topic {\n\tvar topics []Topic\n\tb.callbacks.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\ttopic := Topic(k)\n\t\tif topic == TopicAll {\n\t\t\t// Skip catchall topic from the list\n\t\t\treturn false\n\t\t}\n\n\t\ttopics = append(topics, topic)\n\t\treturn false\n\t})\n\treturn topics\n}\n\n// Subscribe subscribes to messages published for a topic.\n// It returns the callback ID within the topic.\nfunc (b *Broker) Subscribe(topic Topic, cb Callback) (id int, _ error) {\n\tkey := strings.TrimSpace(string(topic))\n\tif key == \"\" {\n\t\treturn 0, ErrRequiredTopic\n\t}\n\n\tif cb == nil {\n\t\treturn 0, ErrRequiredCallback\n\t}\n\n\tv := b.callbacks.Get(key)\n\tcallbacks, _ := v.(*ulist.List)\n\tif callbacks == nil {\n\t\tcallbacks = ulist.New()\n\t}\n\n\tcallbacks.Append(cb)\n\tb.callbacks.Set(key, callbacks)\n\treturn callbacks.TotalSize(), nil\n}\n\n// Unsubscribe unsubscribes a callback from a message topic.\n// ID is the callback ID within the topic, returned on subscription.\nfunc (b *Broker) Unsubscribe(topic Topic, id int) (unsubscribed bool, _ error) {\n\tkey := strings.TrimSpace(string(topic))\n\tif key == \"\" {\n\t\treturn false, ErrRequiredTopic\n\t}\n\n\tif id == 0 {\n\t\treturn false, ErrRequiredSubscriptionID\n\t}\n\n\tv := b.callbacks.Get(key)\n\tif v == nil {\n\t\treturn false, errors.New(\"message topic not found: \" + key)\n\t}\n\n\tcallbacks := v.(*ulist.List)\n\ti := id - 1\n\treturn callbacks.Delete(i) == nil, nil\n}\n\n// Publish publishes a message for a topic.\nfunc (b Broker) Publish(topic Topic, data any) error {\n\tif topic == TopicAll {\n\t\treturn ErrInvalidTopic\n\t}\n\n\tkey := strings.TrimSpace(string(topic))\n\tif key == \"\" {\n\t\treturn ErrRequiredTopic\n\t}\n\n\titerCb := func(_ int, v any) bool {\n\t\tcb := v.(Callback)\n\t\tcb(Message{topic, data})\n\t\treturn false\n\t}\n\n\t// Trigger callbacks subscribed to current topic\n\tv := b.callbacks.Get(key)\n\tif v != nil {\n\t\tcallbacks := v.(*ulist.List)\n\t\tcallbacks.Iterator(0, callbacks.Size(), iterCb)\n\t}\n\n\t// Trigger callbacks subscribed to all topics\n\tv = b.callbacks.Get(string(TopicAll))\n\tif v != nil {\n\t\tcallbacks := v.(*ulist.List)\n\t\tcallbacks.Iterator(0, callbacks.Size(), iterCb)\n\t}\n\treturn nil\n}\n"},{"name":"doc.gno","body":"// Package message provides a simple message broker implementation.\n//\n// The message broker is a Pub/Sub one. It implements two different interfaces,\n// `Publisher` and `Subscriber`, which are also defined within this package.\n//\n// Published messages contain the topic where they are published and optional\n// message data.\n//\n// Subscribe to an event:\n//\n//\tbroker := message.NewBroker()\n//\tsubID, err := broker.Subscribe(\"EventName\", func(msg message.Message) {\n//\t   println(\"EventName has been triggered\")\n//\t   println(msg.Data)\n//\t})\n//\tif err != nil {\n//\t   panic(err)\n//\t}\n//\n// Unsubscribe from an event:\n//\n//\tunsubscribed, err := broker.Unsubscribe(\"EventName\", subID)\n//\tif err != nil {\n//\t   panic(err)\n//\t}\n//\n//\tif !unsubscribed {\n//\t   panic(\"subscription not found\")\n//\t}\n//\n// Publish an event:\n//\n//\terr := broker.Publish(\"EventName\", \"Example event data\")\n//\tif err != nil {\n//\t   panic(err)\n//\t}\npackage message\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jeronimoalbi/message/v0\"\ngno = \"0.9\"\n"},{"name":"message.gno","body":"package message\n\n// TopicAll defines a topic for all types of message.\n// This topic can be used to subscribe to message for all topics.\nconst TopicAll Topic = \"*\"\n\ntype (\n\t// Topic defines a type for message topics.\n\tTopic string\n\n\t// Callback defines a type for message callbacks.\n\tCallback func(Message)\n\n\t// Message defines a type for published messages.\n\tMessage struct {\n\t\t// Topic is the message topic.\n\t\tTopic Topic\n\n\t\t// Data contains optional message data.\n\t\tData any\n\t}\n\n\t// Publisher defines an interface for message publishers.\n\tPublisher interface {\n\t\t// Publish publishes a message for a topic.\n\t\tPublish(_ Topic, data any) error\n\t}\n\n\t// Subscriber defines an interface for message subscribers.\n\tSubscriber interface {\n\t\t// Subscribe subscribes to messages published for a topic.\n\t\t// It returns the callback ID within the topic.\n\t\tSubscribe(Topic, Callback) (id int, _ error)\n\n\t\t// Unsubscribe unsubscribes a callback from a message topic.\n\t\t// ID is the callback ID within the topic, returned on subscription.\n\t\tUnsubscribe(_ Topic, id int) (unsubscribed bool, _ error)\n\t}\n)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"launderattack","path":"gno.land/p/demo/tests/launderattack/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/launderattack/v0\"\ngno = \"0.9\"\n"},{"name":"launderattack.gno","body":"// Package launderattack imports launderpkg and provides functions\n// that attempt to mutate a /p/-typed value passed by pointer. This is\n// the \"/p/attack imports /p/orig\" variation: the goal is for code\n// declared in this /p/ package to mutate a /r/-victim's instance of\n// launderpkg.Object.\npackage launderattack\n\nimport \"gno.land/p/demo/tests/launderpkg/v0\"\n\n// TamperDirect writes through the pointer in its own body. The body\n// runs under whatever m.Realm the caller had at PushFrameCall — for a\n// top-level /p/ function with no receiver, that's the caller's realm.\n// If the caller is attacker-realm, m.Realm at the write is\n// attacker-realm and the readonly check fires on a foreign-stamped\n// base.\nfunc TamperDirect(o *launderpkg.Object, s string) {\n\to.Field = s\n}\n\n// TamperViaMethod dispatches through the launderpkg.Object's own /p/\n// method. PushFrameCall for Set sees a receiver stamped with the\n// victim's realm (the pointer aliases victim's persisted state),\n// triggering borrow rule 2: m.Realm becomes victim for the duration\n// of Set. The write succeeds — but this requires launderpkg.Object\n// to expose a Set method to begin with.\nfunc TamperViaMethod(o *launderpkg.Object, s string) {\n\to.Set(s)\n}\n\n// Tamper has the SAME underlying struct layout as launderpkg.Immutable.\n// /p/launderpkg deliberately gave Immutable no mutator method —\n// callers were supposed to be unable to write its Field. /p/attack\n// declares its own type with the same layout and adds a mutator. An\n// attacker that holds a *launderpkg.Immutable can convert it to\n// *Tamper and invoke Tamper.Set — the conversion is purely a\n// type-tag change, the pointer still aliases victim's persisted\n// memory. PushFrameCall for Tamper.Set then sees recv stamped with\n// victim's realm (the underlying object is unchanged) and\n// borrow-routes m.Realm to victim. The write succeeds.\ntype Tamper struct {\n\tField string\n}\n\n// Set is the mutator that launderpkg.Immutable deliberately did NOT\n// expose. /p/attack adds it via the parallel-type trick.\nfunc (t *Tamper) Set(s string) {\n\tt.Field = s\n}\n\n// Convert is the attacker's helper that does the type punning so the\n// caller doesn't have to write the conversion inline.\nfunc Convert(p *launderpkg.Immutable) *Tamper {\n\treturn (*Tamper)(p)\n}\n\n// EvilMutator implements launderpkg.Mutator with a PRIMITIVE\n// underlying type. Underlying-type matters: a struct/array/etc.\n// receiver has a *StructValue that gets PkgID-stamped at allocation,\n// triggering PushFrameCall's receiver-borrow rule to shift m.Realm\n// back to /p/launderattack. A primitive-underlying type has no\n// *StructValue and no PkgID — `recv.GetFirstObject` returns nil, so\n// the borrow rule's `if obj != nil { ... }` branch is skipped and\n// m.Realm stays at whatever the caller had it set to.\n//\n// When Run is dispatched via interface from inside a /p/-method\n// body that was receiver-borrowed to the victim, m.Realm at Run's\n// entry is the victim's — and stays the victim's, because EvilMutator\n// (an int underneath) carries no PkgID to borrow against. The write\n// inside Run commits under victim authority.\ntype EvilMutator int\n\nfunc (EvilMutator) Run(i *launderpkg.Immutable) {\n\ti.Field = \"pwnd-via-iface\"\n}\n\n// EvilNilRecv tests the nil-pointer-receiver variant. Calling a method\n// on a nil *EvilNilRecv is legal in Gno when the body doesn't deref\n// the receiver. recv = PointerValue{Base: nil} → GetBase returns nil\n// → GetFirstObject returns nil. Same \"no anchor\" gap as the\n// primitive-receiver case, reachable through *T receivers.\ntype EvilNilRecv struct {\n\tX int // unused\n}\n\nfunc (n *EvilNilRecv) Run(i *launderpkg.Immutable) {\n\t// Does NOT dereference n. Just writes through target.\n\ti.Field = \"pwnd-via-nilrecv\"\n}\n\n// EvilFunc / EvilSlice / EvilMap — additional nil-anchor shapes.\n// nil-valued receivers of defined types whose underlying is a\n// reference type (slice/map/func) also have GetFirstObject == nil.\n// The Attack H/I fix should cover all of them via the\n// recvDeclaredTypePkgPath helper.\ntype EvilFunc func()\n\nfunc (EvilFunc) Run(i *launderpkg.Immutable) { i.Field = \"pwnd-via-func\" }\n\ntype EvilSlice []int\n\nfunc (EvilSlice) Run(i *launderpkg.Immutable) { i.Field = \"pwnd-via-slice\" }\n\ntype EvilMap map[string]int\n\nfunc (EvilMap) Run(i *launderpkg.Immutable) { i.Field = \"pwnd-via-map\" }\n\n// EvilSliceMutator's Run takes a slice — NOT a pointer parameter, so\n// the Attack H/I fix's `hasForeignPPtrParam` predicate skips it.\n// Tests whether the anchor predicate needs to look INSIDE composite\n// parameter types for foreign-/p/ pointers.\ntype EvilSliceMutator int\n\nfunc (EvilSliceMutator) Run(s []*launderpkg.Immutable) {\n\ts[0].Field = \"pwnd-via-slice-arg\"\n}\n\n// EvilAnyMutator's Run takes `any` and type-asserts to *Immutable.\n// The signature reveals NO foreign-/p/-pointer statically — the\n// pointer is hidden inside the interface box. Probes whether the\n// predicate needs to fire on interface-typed params too.\ntype EvilAnyMutator int\n\nfunc (EvilAnyMutator) Run(x any) {\n\tt := x.(*launderpkg.Immutable)\n\tt.Field = \"pwnd-via-any-arg\"\n}\n\n// EvilWrite is a top-level /p/-declared function value matching\n// `func(*launderpkg.Immutable)`. Top-level /p/ functions trigger\n// neither borrow rule #1 (not /r/-declared) nor borrow rule #2 (no receiver), so\n// when EvilWrite is invoked as a callback from inside a\n// borrowed-to-victim /p/-method body (e.g. Immutable.Apply, or any\n// avl.Tree.Iterate-style hook), it inherits the victim's m.Realm\n// and the write commits under victim authority.\nfunc EvilWrite(i *launderpkg.Immutable) {\n\ti.Field = \"pwnd-via-apply\"\n}\n\n// EvilObjectWrite is the same shape but for *Object — used by tests\n// that exercise Object's mutator surface through Apply-style callbacks.\nfunc EvilObjectWrite(o *launderpkg.Object) {\n\to.Field = \"pwnd-via-apply-obj\"\n}\n\n// StoredHook is a /p/attack package-level closure: a FuncLit evaluated\n// during /p/launderattack init, so its ObjectInfo.PkgID is stamped\n// /p/launderattack. Unlike a top-level FuncDecl (EvilWrite/EvilObjectWrite,\n// IsClosure=false), invoking a closure triggers PushFrameCall's borrow rule\n// #3, which borrows m.Realm to the closure's construction realm\n// (/p/launderattack). Used to probe rule #3: a write through it to a foreign\n// /r/ object must still be rejected. (If rule #3 ever regressed to a nil\n// borrow, m.Realm would go nil and the write would silently succeed.)\nvar StoredHook = func(o *launderpkg.Object) {\n\to.Field = \"pwnd-via-stored-closure\"\n}\n\n// Tamperer is a stamped /p/attack value (constructed at init under\n// /p/attack's realm context, stamped /p/attack, persisted Frozen).\n// Methods on Tamperer get receiver-borrowed to /p/attack at call\n// time — useful as a control to compare against attacks where the\n// receiver is victim-stamped.\ntype Tamperer struct{}\n\n// TamperMethod is a /p/attack-defined method. When the caller invokes\n// Tamperer{}.TamperMethod(o, s), the receiver Tamperer{} is\n// constructed in the caller's realm, so receiver-borrow lands at the\n// caller's realm, not /p/attack — the receiver carries the caller's\n// stamp, not /p/attack's.\nfunc (Tamperer) TamperMethod(o *launderpkg.Object, s string) {\n\to.Field = s\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"innerowner","path":"gno.land/r/tests/vm/innerowner","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/innerowner\"\ngno = \"0.9\"\n"},{"name":"innerowner.gno","body":"// Package innerowner persists an *Inner that lives in this realm.\n// Foreign-realm callers use GetInner() to obtain a pointer to it.\n// When they pass it as the receiver of a /p/ method, PushFrameCall's\n// borrow rule 2 fires and m.Realm shifts to this realm.\npackage innerowner\n\nimport \"gno.land/p/demo/tests/p_closurecap/v0\"\n\nvar inn *p_closurecap.Inner\n\nfunc init() {\n\tinn = \u0026p_closurecap.Inner{N: 0}\n}\n\n// GetInner returns the persisted Inner. Non-crossing: the caller's\n// realm stays current, but the returned *Inner carries PkgID =\n// innerowner from its init-time allocation.\nfunc GetInner() *p_closurecap.Inner {\n\treturn inn\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"agent","path":"gno.land/p/demo/gnorkle/agent/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/agent/v0\"\ngno = \"0.9\"\n"},{"name":"whitelist.gno","body":"package agent\n\nimport \"gno.land/p/nt/avl/v0\"\n\n// Whitelist manages whitelisted agent addresses.\ntype Whitelist struct {\n\tstore *avl.Tree\n}\n\n// ClearAddresses removes all addresses from the whitelist and puts into a state\n// that indicates it is moot and has no whitelist defined.\nfunc (m *Whitelist) ClearAddresses() {\n\tm.store = nil\n}\n\n// AddAddresses adds the given addresses to the whitelist.\nfunc (m *Whitelist) AddAddresses(addresses []string) {\n\tif m.store == nil {\n\t\tm.store = avl.NewTree()\n\t}\n\n\tfor _, address_XXX := range addresses {\n\t\tm.store.Set(address_XXX, struct{}{})\n\t}\n}\n\n// RemoveAddress removes the given address from the whitelist if it exists.\nfunc (m *Whitelist) RemoveAddress(address_XXX string) {\n\tif m.store == nil {\n\t\treturn\n\t}\n\n\tm.store.Remove(address_XXX)\n}\n\n// HasDefinition returns true if the whitelist has a definition. It retuns false if\n// `ClearAddresses` has been called without any subsequent `AddAddresses` calls, or\n// if `AddAddresses` has never been called.\nfunc (m Whitelist) HasDefinition() bool {\n\treturn m.store != nil\n}\n\n// HasAddress returns true if the given address is in the whitelist.\nfunc (m Whitelist) HasAddress(address_XXX string) bool {\n\tif m.store == nil {\n\t\treturn false\n\t}\n\n\treturn m.store.Has(address_XXX)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"feed","path":"gno.land/p/demo/gnorkle/feed/v0","files":[{"name":"errors.gno","body":"package feed\n\nimport \"errors\"\n\nvar ErrUndefined = errors.New(\"undefined feed\")\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/feed/v0\"\ngno = \"0.9\"\n"},{"name":"task.gno","body":"package feed\n\n// Task is a unit of work that can be part of a `Feed` definition. Tasks\n// are executed by agents.\ntype Task interface {\n\tMarshalJSON() ([]byte, error)\n}\n"},{"name":"type.gno","body":"package feed\n\n// Type indicates the type of a feed.\ntype Type int\n\nconst (\n\t// TypeStatic indicates a feed cannot be changed once the first value is committed.\n\tTypeStatic Type = iota\n\t// TypeContinuous indicates a feed can continuously ingest values and will publish\n\t// a new value on request using the values it has ingested.\n\tTypeContinuous\n\t// TypePeriodic indicates a feed can accept one or more values within a certain period\n\t// and will proceed to commit these values at the end up each period to produce an\n\t// aggregate value before starting a new period.\n\tTypePeriodic\n)\n"},{"name":"value.gno","body":"package feed\n\nimport \"time\"\n\n// Value represents a value published by a feed. The `Time` is when the value was published.\ntype Value struct {\n\tString string\n\tTime   time.Time\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"storage","path":"gno.land/p/demo/gnorkle/storage/v0","files":[{"name":"errors.gno","body":"package storage\n\nimport \"errors\"\n\nvar ErrUndefined = errors.New(\"undefined storage\")\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/storage/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"simple","path":"gno.land/p/demo/gnorkle/storage/simple/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/storage/simple/v0\"\ngno = \"0.9\"\n"},{"name":"storage.gno","body":"package simple\n\nimport (\n\t\"time\"\n\n\t\"gno.land/p/demo/gnorkle/feed/v0\"\n\t\"gno.land/p/demo/gnorkle/storage/v0\"\n)\n\n// Storage is simple, bounded storage for published feed values.\ntype Storage struct {\n\tvalues    []feed.Value\n\tmaxValues uint\n}\n\n// NewStorage creates a new Storage with the given maximum number of values.\n// If maxValues is 0, the storage is bounded to a size of one. If this is not desirable,\n// then don't provide a value of 0.\nfunc NewStorage(maxValues uint) *Storage {\n\tif maxValues == 0 {\n\t\tmaxValues = 1\n\t}\n\n\treturn \u0026Storage{\n\t\tmaxValues: maxValues,\n\t}\n}\n\n// Put adds a new value to the storage. If the storage is full, the oldest value\n// is removed. If maxValues is 0, the storage is bounded to a size of one.\nfunc (s *Storage) Put(value string) error {\n\tif s == nil {\n\t\treturn storage.ErrUndefined\n\t}\n\n\ts.values = append(s.values, feed.Value{String: value, Time: time.Now()})\n\tif uint(len(s.values)) \u003e s.maxValues {\n\t\ts.values = s.values[1:]\n\t}\n\n\treturn nil\n}\n\n// GetLatest returns the most recently added value, or an empty value if none exist.\nfunc (s Storage) GetLatest() feed.Value {\n\tif len(s.values) == 0 {\n\t\treturn feed.Value{}\n\t}\n\n\treturn s.values[len(s.values)-1]\n}\n\n// GetHistory returns all values in the storage, from oldest to newest.\nfunc (s Storage) GetHistory() []feed.Value {\n\treturn s.values\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"testutils","path":"gno.land/p/nt/testutils/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `testutils` - misc testing helpers\n\nSmall grab-bag of helpers for `_test.gno` files: deterministic fake addresses, a call-stack wrapper, and fixtures exercising access rules (exported/unexported fields, methods, and interfaces).\n\n## Usage\n\n```go\nimport (\n    \"testing\"\n\n    \"gno.land/p/nt/testutils/v0\"\n)\n\nfunc TestTransfer(t *testing.T) {\n    alice := testutils.TestAddress(\"alice\") // deterministic g1... address\n    bob := testutils.TestAddress(\"bob\")\n\n    testutils.WrapCall(func() {\n        Transfer(alice, bob, 100)\n    })\n}\n```\n\n## API\n\nAddresses:\n\n```go\n// TestAddress returns a deterministic bech32 g1... address derived from name.\n// name must be at most 20 bytes; it is right-padded with '_' before encoding.\nfunc TestAddress(name string) address\n```\n\nCall-stack helper:\n\n```go\n// WrapCall invokes fn after adding one extra frame to the call stack.\n// Useful for tests that inspect caller depth.\nfunc WrapCall(fn func())\n```\n\nAccess-rule fixtures (used by VM file tests to exercise exported vs. unexported visibility):\n\n```go\ntype TestAccessStruct struct {\n    PublicField  string\n    // privateField is unexported on purpose.\n}\n\nfunc NewTestAccessStruct(pub, priv string) TestAccessStruct\nfunc (TestAccessStruct) PublicMethod() string\n\ntype PrivateInterface interface {\n    // unexported method — only satisfiable from within this package.\n}\n\nfunc PrintPrivateInterface(pi PrivateInterface)\n\nvar TestVar1 int // initialized to 123 in init()\n```\n\n## Notes\n\n- `TestAddress` panics if `name` exceeds 20 bytes; the resulting address is reproducible across runs, which is what you want in tests.\n- The access fixtures exist mainly to back GnoVM file tests under `gnovm/tests/files/`; most user code only needs `TestAddress`.\n"},{"name":"access.gno","body":"package testutils\n\n// for testing access. see tests/files/access*.go\n\n// NOTE: non-package variables cannot be overridden, except during init().\nvar (\n\tTestVar1 int\n\ttestVar2 int\n)\n\nfunc init() {\n\tTestVar1 = 123\n\ttestVar2 = 456\n}\n\ntype TestAccessStruct struct {\n\tPublicField  string\n\tprivateField string\n}\n\nfunc (tas TestAccessStruct) PublicMethod() string {\n\treturn tas.PublicField + \"/\" + tas.privateField\n}\n\nfunc (tas TestAccessStruct) privateMethod() string {\n\treturn tas.PublicField + \"/\" + tas.privateField\n}\n\nfunc NewTestAccessStruct(pub, priv string) TestAccessStruct {\n\treturn TestAccessStruct{\n\t\tPublicField:  pub,\n\t\tprivateField: priv,\n\t}\n}\n\n// see access6.g0 etc.\ntype PrivateInterface interface {\n\tprivateMethod() string\n}\n\nfunc PrintPrivateInterface(pi PrivateInterface) {\n\tprintln(\"testutils.PrintPrivateInterface\", pi.privateMethod())\n}\n"},{"name":"crypto.gno","body":"package testutils\n\nimport \"crypto/bech32\"\n\nfunc TestAddress(name string) address {\n\tif len(name) \u003e 20 {\n\t\tpanic(\"address name cannot be greater than 20 bytes\")\n\t}\n\taddr := []byte(\"____________________\")\n\tcopy(addr[:], name)\n\tconverted, err := bech32.ConvertBits(addr, 8, 5, true)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tenc, err := bech32.Encode(\"g\", converted)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn address(enc)\n}\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package testutils provides testing utilities for Gno packages and realms.\npackage testutils\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/testutils/v0\"\ngno = \"0.9\"\n"},{"name":"misc.gno","body":"package testutils\n\n// WrapCall adds a frame to the call stack, for testing call stack depth.\nfunc WrapCall(fn func()) {\n\tfn()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"message","path":"gno.land/p/demo/gnorkle/message/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/message/v0\"\ngno = \"0.9\"\n"},{"name":"parse.gno","body":"package message\n\nimport \"strings\"\n\n// ParseFunc parses a raw message and returns the message function\n// type extracted from the remainder of the message.\nfunc ParseFunc(rawMsg string) (FuncType, string) {\n\tfuncType, remainder := parseFirstToken(rawMsg)\n\treturn FuncType(funcType), remainder\n}\n\n// ParseID parses a raw message and returns the ID extracted from\n// the remainder of the message.\nfunc ParseID(rawMsg string) (string, string) {\n\treturn parseFirstToken(rawMsg)\n}\n\nfunc parseFirstToken(rawMsg string) (string, string) {\n\tmsgParts := strings.SplitN(rawMsg, \",\", 2)\n\tif len(msgParts) \u003c 2 {\n\t\treturn msgParts[0], \"\"\n\t}\n\n\treturn msgParts[0], msgParts[1]\n}\n"},{"name":"type.gno","body":"package message\n\n// FuncType is the type of function that is being called by the agent.\ntype FuncType string\n\nconst (\n\t// FuncTypeIngest means the agent is sending data for ingestion.\n\tFuncTypeIngest FuncType = \"ingest\"\n\t// FuncTypeCommit means the agent is requesting a feed commit the transitive data\n\t// being held by its ingester.\n\tFuncTypeCommit FuncType = \"commit\"\n\t// FuncTypeRequest means the agent is requesting feed definitions for all those\n\t// that it is whitelisted to provide data for.\n\tFuncTypeRequest FuncType = \"request\"\n)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"gnorkle","path":"gno.land/p/demo/gnorkle/gnorkle/v0","files":[{"name":"feed.gno","body":"package gnorkle\n\nimport (\n\t\"gno.land/p/demo/gnorkle/feed/v0\"\n\t\"gno.land/p/demo/gnorkle/message/v0\"\n)\n\n// Feed is an abstraction used by a gnorkle `Instance` to ingest data from\n// agents and provide data feeds to consumers.\ntype Feed interface {\n\tID() string\n\tType() feed.Type\n\tValue() (value feed.Value, dataType string, consumable bool)\n\tIngest(funcType message.FuncType, rawMessage, providerAddress string) error\n\tMarshalJSON() ([]byte, error)\n\tTasks() []feed.Task\n\tIsActive() bool\n}\n\n// FeedWithWhitelist associates a `Whitelist` with a `Feed`.\ntype FeedWithWhitelist struct {\n\tFeed\n\tWhitelist\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/gnorkle/v0\"\ngno = \"0.9\"\n"},{"name":"ingester.gno","body":"package gnorkle\n\nimport \"gno.land/p/demo/gnorkle/ingester/v0\"\n\n// Ingester is the abstraction that allows a `Feed` to ingest data from agents\n// and commit it to storage using zero or more intermediate aggregation steps.\ntype Ingester interface {\n\tType() ingester.Type\n\tIngest(value, providerAddress string) (canAutoCommit bool, err error)\n\tCommitValue(storage Storage, providerAddress string) error\n}\n"},{"name":"instance.gno","body":"package gnorkle\n\nimport (\n\t\"chain/runtime/unsafe\"\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/demo/gnorkle/agent/v0\"\n\t\"gno.land/p/demo/gnorkle/feed/v0\"\n\t\"gno.land/p/demo/gnorkle/message/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Instance is a single instance of an oracle.\ntype Instance struct {\n\tfeeds     *avl.Tree\n\twhitelist agent.Whitelist\n}\n\n// NewInstance creates a new instance of an oracle.\nfunc NewInstance() *Instance {\n\treturn \u0026Instance{\n\t\tfeeds: avl.NewTree(),\n\t}\n}\n\nfunc assertValidID(id string) error {\n\tif len(id) == 0 {\n\t\treturn errors.New(\"feed ids cannot be empty\")\n\t}\n\n\tif strings.Contains(id, \",\") {\n\t\treturn errors.New(\"feed ids cannot contain commas\")\n\t}\n\n\treturn nil\n}\n\nfunc (i *Instance) assertFeedDoesNotExist(id string) error {\n\tif i.feeds.Has(id) {\n\t\treturn errors.New(\"feed already exists\")\n\t}\n\n\treturn nil\n}\n\n// AddFeeds adds feeds to the instance with empty whitelists.\nfunc (i *Instance) AddFeeds(feeds ...Feed) error {\n\tfor _, feed := range feeds {\n\t\tif err := assertValidID(feed.ID()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := i.assertFeedDoesNotExist(feed.ID()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ti.feeds.Set(\n\t\t\tfeed.ID(),\n\t\t\tFeedWithWhitelist{\n\t\t\t\tWhitelist: new(agent.Whitelist),\n\t\t\t\tFeed:      feed,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn nil\n}\n\n// AddFeedsWithWhitelists adds feeds to the instance with the given whitelists.\nfunc (i *Instance) AddFeedsWithWhitelists(feeds ...FeedWithWhitelist) error {\n\tfor _, feed := range feeds {\n\t\tif err := i.assertFeedDoesNotExist(feed.ID()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := assertValidID(feed.ID()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ti.feeds.Set(\n\t\t\tfeed.ID(),\n\t\t\tFeedWithWhitelist{\n\t\t\t\tWhitelist: feed.Whitelist,\n\t\t\t\tFeed:      feed,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn nil\n}\n\n// RemoveFeed removes a feed from the instance.\nfunc (i *Instance) RemoveFeed(id string) {\n\ti.feeds.Remove(id)\n}\n\n// PostMessageHandler is a type that allows for post-processing of feed state after a feed\n// ingests a message from an agent.\ntype PostMessageHandler interface {\n\tHandle(i *Instance, funcType message.FuncType, feed Feed) error\n}\n\n// HandleMessage handles a message from an agent and routes to either the logic that returns\n// feed definitions or the logic that allows a feed to ingest a message.\n//\n// TODO: Consider further message types that could allow administrative action such as modifying\n// a feed's whitelist without the owner of this oracle having to maintain a reference to it.\nfunc (i *Instance) HandleMessage(msg string, postHandler PostMessageHandler) (string, error) {\n\tcaller := string(unsafe.OriginCaller())\n\n\tfuncType, msg := message.ParseFunc(msg)\n\n\tswitch funcType {\n\tcase message.FuncTypeRequest:\n\t\treturn i.GetFeedDefinitions(caller)\n\n\tdefault:\n\t\tid, msg := message.ParseID(msg)\n\t\tif err := assertValidID(id); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tfeedWithWhitelist, err := i.getFeedWithWhitelist(id)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif !addressIsWhitelisted(\u0026i.whitelist, feedWithWhitelist, caller, nil) {\n\t\t\treturn \"\", errors.New(\"caller not whitelisted\")\n\t\t}\n\n\t\tif err := feedWithWhitelist.Ingest(funcType, msg, caller); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif postHandler != nil {\n\t\t\tpostHandler.Handle(i, funcType, feedWithWhitelist)\n\t\t}\n\t}\n\n\treturn \"\", nil\n}\n\nfunc (i *Instance) getFeed(id string) (Feed, error) {\n\tuntypedFeed := i.feeds.Get(id)\n\tif untypedFeed == nil {\n\t\treturn nil, errors.New(\"invalid ingest id: \" + id)\n\t}\n\n\tfeed, ok := untypedFeed.(Feed)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid feed type\")\n\t}\n\n\treturn feed, nil\n}\n\nfunc (i *Instance) getFeedWithWhitelist(id string) (FeedWithWhitelist, error) {\n\tuntypedFeedWithWhitelist := i.feeds.Get(id)\n\tif untypedFeedWithWhitelist == nil {\n\t\treturn FeedWithWhitelist{}, errors.New(\"invalid ingest id: \" + id)\n\t}\n\n\tfeedWithWhitelist, ok := untypedFeedWithWhitelist.(FeedWithWhitelist)\n\tif !ok {\n\t\treturn FeedWithWhitelist{}, errors.New(\"invalid feed with whitelist type\")\n\t}\n\n\treturn feedWithWhitelist, nil\n}\n\n// GetFeedValue returns the most recently published value of a feed along with a string\n// representation of the value's type and boolean indicating whether the value is\n// okay for consumption.\nfunc (i *Instance) GetFeedValue(id string) (feed.Value, string, bool, error) {\n\tfoundFeed, err := i.getFeed(id)\n\tif err != nil {\n\t\treturn feed.Value{}, \"\", false, err\n\t}\n\n\tvalue, valueType, consumable := foundFeed.Value()\n\treturn value, valueType, consumable, nil\n}\n\n// GetFeedDefinitions returns a JSON string representing the feed definitions for which the given\n// agent address is whitelisted to provide values for ingestion.\nfunc (i *Instance) GetFeedDefinitions(forAddress string) (string, error) {\n\tinstanceHasAddressWhitelisted := !i.whitelist.HasDefinition() || i.whitelist.HasAddress(forAddress)\n\n\tbuf := new(strings.Builder)\n\tbuf.WriteString(\"[\")\n\tfirst := true\n\tvar err error\n\n\t// The boolean value returned by this callback function indicates whether to stop iterating.\n\ti.feeds.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\tfeedWithWhitelist, ok := value.(FeedWithWhitelist)\n\t\tif !ok {\n\t\t\terr = errors.New(\"invalid feed type\")\n\t\t\treturn true\n\t\t}\n\n\t\t// Don't give agents the ability to try to publish to inactive feeds.\n\t\tif !feedWithWhitelist.IsActive() {\n\t\t\treturn false\n\t\t}\n\n\t\t// Skip feeds the address is not whitelisted for.\n\t\tif !addressIsWhitelisted(\u0026i.whitelist, feedWithWhitelist, forAddress, \u0026instanceHasAddressWhitelisted) {\n\t\t\treturn false\n\t\t}\n\n\t\tvar taskBytes []byte\n\t\tif taskBytes, err = feedWithWhitelist.Feed.MarshalJSON(); err != nil {\n\t\t\treturn true\n\t\t}\n\n\t\t// Guard against any tasks that shouldn't be returned; maybe they are not active because they have\n\t\t// already been completed.\n\t\tif len(taskBytes) == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\tif !first {\n\t\t\tbuf.WriteString(\",\")\n\t\t}\n\n\t\tfirst = false\n\t\tbuf.Write(taskBytes)\n\t\treturn false\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf.WriteString(\"]\")\n\treturn buf.String(), nil\n}\n"},{"name":"storage.gno","body":"package gnorkle\n\nimport \"gno.land/p/demo/gnorkle/feed/v0\"\n\n// Storage defines how published feed values should be read\n// and written.\ntype Storage interface {\n\tPut(value string) error\n\tGetLatest() feed.Value\n\tGetHistory() []feed.Value\n}\n"},{"name":"whitelist.gno","body":"package gnorkle\n\n// Whitelist is used to manage which agents are allowed to interact.\ntype Whitelist interface {\n\tClearAddresses()\n\tAddAddresses(addresses []string)\n\tRemoveAddress(address_XXX string)\n\tHasDefinition() bool\n\tHasAddress(address_XXX string) bool\n}\n\n// ClearWhitelist clears the whitelist of the instance or feed depending on the feed ID.\nfunc (i *Instance) ClearWhitelist(feedID string) error {\n\tif feedID == \"\" {\n\t\ti.whitelist.ClearAddresses()\n\t\treturn nil\n\t}\n\n\tfeedWithWhitelist, err := i.getFeedWithWhitelist(feedID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfeedWithWhitelist.ClearAddresses()\n\treturn nil\n}\n\n// AddToWhitelist adds the given addresses to the whitelist of the instance or feed depending on the feed ID.\nfunc (i *Instance) AddToWhitelist(feedID string, addresses []string) error {\n\tif feedID == \"\" {\n\t\ti.whitelist.AddAddresses(addresses)\n\t\treturn nil\n\t}\n\n\tfeedWithWhitelist, err := i.getFeedWithWhitelist(feedID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfeedWithWhitelist.AddAddresses(addresses)\n\treturn nil\n}\n\n// RemoveFromWhitelist removes the given address from the whitelist of the instance or feed depending on the feed ID.\nfunc (i *Instance) RemoveFromWhitelist(feedID string, address_XXX string) error {\n\tif feedID == \"\" {\n\t\ti.whitelist.RemoveAddress(address_XXX)\n\t\treturn nil\n\t}\n\n\tfeedWithWhitelist, err := i.getFeedWithWhitelist(feedID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfeedWithWhitelist.RemoveAddress(address_XXX)\n\treturn nil\n}\n\n// addressWhiteListed returns true if:\n// - the feed has a white list and the address is whitelisted, or\n// - the feed has no white list and the instance has a white list and the address is whitelisted, or\n// - the feed has no white list and the instance has no white list.\nfunc addressIsWhitelisted(instanceWhitelist, feedWhitelist Whitelist, address_XXX string, instanceWhitelistedOverride *bool) bool {\n\t// A feed whitelist takes priority, so it will return false if the feed has a whitelist and the caller is\n\t// not a part of it. An empty whitelist defers to the instance whitelist.\n\tif feedWhitelist != nil {\n\t\tif feedWhitelist.HasDefinition() \u0026\u0026 !feedWhitelist.HasAddress(address_XXX) {\n\t\t\treturn false\n\t\t}\n\n\t\t// Getting to this point means that one of the following is true:\n\t\t// - the feed has no defined whitelist (so it can't possibly have the address whitelisted)\n\t\t// - the feed has a defined whitelist and the caller is a part of it\n\t\t//\n\t\t// In this case, we can be sure that the boolean indicating whether the feed has this address whitelisted\n\t\t// is equivalent to the boolean indicating whether the feed has a defined whitelist.\n\t\tif feedWhitelist.HasDefinition() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tif instanceWhitelistedOverride != nil {\n\t\treturn *instanceWhitelistedOverride\n\t}\n\n\t// We were unable able to determine whether this address is allowed after looking at the feed whitelist,\n\t// so fall back to the instance whitelist. A complete absence of values in the instance whitelist means\n\t// that the instance has no whitelist so we can return true because everything is allowed by default.\n\tif instanceWhitelist == nil || !instanceWhitelist.HasDefinition() {\n\t\treturn true\n\t}\n\n\t// The instance whitelist is defined so if the address is present then it is allowed.\n\treturn instanceWhitelist.HasAddress(address_XXX)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"single","path":"gno.land/p/demo/gnorkle/ingesters/single/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/ingesters/single/v0\"\ngno = \"0.9\"\n"},{"name":"ingester.gno","body":"package single\n\nimport (\n\t\"gno.land/p/demo/gnorkle/gnorkle/v0\"\n\t\"gno.land/p/demo/gnorkle/ingester/v0\"\n)\n\n// ValueIngester is an ingester that ingests a single value.\ntype ValueIngester struct {\n\tvalue string\n}\n\n// Type returns the type of the ingester.\nfunc (i *ValueIngester) Type() ingester.Type {\n\treturn ingester.TypeSingle\n}\n\n// Ingest ingests a value provided by the given agent address.\nfunc (i *ValueIngester) Ingest(value, providerAddress string) (bool, error) {\n\tif i == nil {\n\t\treturn false, ingester.ErrUndefined\n\t}\n\n\ti.value = value\n\treturn true, nil\n}\n\n// CommitValue commits the ingested value to the given storage instance.\nfunc (i *ValueIngester) CommitValue(valueStorer gnorkle.Storage, providerAddress string) error {\n\tif i == nil {\n\t\treturn ingester.ErrUndefined\n\t}\n\n\treturn valueStorer.Put(i.value)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"static","path":"gno.land/p/demo/gnorkle/feeds/static/v0","files":[{"name":"feed.gno","body":"package static\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\n\t\"gno.land/p/demo/gnorkle/feed/v0\"\n\t\"gno.land/p/demo/gnorkle/gnorkle/v0\"\n\t\"gno.land/p/demo/gnorkle/ingesters/single/v0\"\n\t\"gno.land/p/demo/gnorkle/message/v0\"\n\t\"gno.land/p/demo/gnorkle/storage/simple/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Feed is a static feed.\ntype Feed struct {\n\tid            string\n\tisLocked      bool\n\tvalueDataType string\n\tingester      gnorkle.Ingester\n\tstorage       gnorkle.Storage\n\ttasks         []feed.Task\n}\n\n// NewFeed creates a new static feed.\nfunc NewFeed(\n\tid string,\n\tvalueDataType string,\n\tingester gnorkle.Ingester,\n\tstorage gnorkle.Storage,\n\ttasks ...feed.Task,\n) *Feed {\n\treturn \u0026Feed{\n\t\tid:            id,\n\t\tvalueDataType: valueDataType,\n\t\tingester:      ingester,\n\t\tstorage:       storage,\n\t\ttasks:         tasks,\n\t}\n}\n\n// NewSingleValueFeed is a convenience function  for creating a static feed\n// that autocommits a value after a single ingestion.\nfunc NewSingleValueFeed(\n\tid string,\n\tvalueDataType string,\n\ttasks ...feed.Task,\n) *Feed {\n\treturn NewFeed(\n\t\tid,\n\t\tvalueDataType,\n\t\t\u0026single.ValueIngester{},\n\t\tsimple.NewStorage(1),\n\t\ttasks...,\n\t)\n}\n\n// ID returns the feed's ID.\nfunc (f Feed) ID() string {\n\treturn f.id\n}\n\n// Type returns the feed's type.\nfunc (f Feed) Type() feed.Type {\n\treturn feed.TypeStatic\n}\n\n// Ingest ingests a message into the feed. It either adds the value to the ingester's\n// pending values or commits the value to the storage.\nfunc (f *Feed) Ingest(funcType message.FuncType, msg, providerAddress string) error {\n\tif f == nil {\n\t\treturn feed.ErrUndefined\n\t}\n\n\tif f.isLocked {\n\t\treturn errors.New(\"feed locked\")\n\t}\n\n\tswitch funcType {\n\tcase message.FuncTypeIngest:\n\t\t// Autocommit the ingester's value if it's a single value ingester\n\t\t// because this is a static feed and this is the only value it will ever have.\n\t\tif canAutoCommit, err := f.ingester.Ingest(msg, providerAddress); canAutoCommit \u0026\u0026 err == nil {\n\t\t\tif err := f.ingester.CommitValue(f.storage, providerAddress); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tf.isLocked = true\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase message.FuncTypeCommit:\n\t\tif err := f.ingester.CommitValue(f.storage, providerAddress); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tf.isLocked = true\n\n\tdefault:\n\t\treturn errors.New(\"invalid message function \" + string(funcType))\n\t}\n\n\treturn nil\n}\n\n// Value returns the feed's latest value, it's data type, and whether or not it can\n// be safely consumed. In this case it uses `f.isLocked` because, this being a static\n// feed, it will only ever have one value; once that value is committed the feed is locked\n// and there is a valid, non-empty value to consume.\nfunc (f Feed) Value() (feed.Value, string, bool) {\n\treturn f.storage.GetLatest(), f.valueDataType, f.isLocked\n}\n\n// MarshalJSON marshals the components of the feed that are needed for\n// an agent to execute tasks and send values for ingestion.\nfunc (f Feed) MarshalJSON() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tw := bufio.NewWriter(buf)\n\n\tw.Write([]byte(\n\t\t`{\"id\":\"` + f.id +\n\t\t\t`\",\"type\":\"` + ufmt.Sprintf(\"%d\", int(f.Type())) +\n\t\t\t`\",\"value_type\":\"` + f.valueDataType +\n\t\t\t`\",\"tasks\":[`),\n\t)\n\n\tfirst := true\n\tfor _, task := range f.tasks {\n\t\tif !first {\n\t\t\tw.WriteString(\",\")\n\t\t}\n\n\t\ttaskJSON, err := task.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tw.Write(taskJSON)\n\t\tfirst = false\n\t}\n\n\tw.Write([]byte(\"]}\"))\n\tw.Flush()\n\n\treturn buf.Bytes(), nil\n}\n\n// Tasks returns the feed's tasks. This allows task consumers to extract task\n// contents without having to marshal the entire feed.\nfunc (f Feed) Tasks() []feed.Task {\n\treturn f.tasks\n}\n\n// IsActive returns true if the feed is accepting ingestion requests from agents.\nfunc (f Feed) IsActive() bool {\n\treturn !f.isLocked\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/feeds/static/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"ghverify","path":"gno.land/r/gnoland/ghverify","files":[{"name":"README.md","body":"# ghverify\n\nThis realm is intended to enable off chain gno address to github handle verification.\nThe steps are as follows:\n- A user calls `RequestVerification` and provides a github handle. This creates a new static oracle feed.\n- An off-chain agent controlled by the owner of this realm requests current feeds using the `GnorkleEntrypoint` function and provides a message of `\"request\"`\n- The agent receives the task information that includes the github handle and the gno address. It performs the verification step by checking whether this github user has the address in a github repository it controls.\n- The agent publishes the result of the verification by calling `GnorkleEntrypoint` with a message structured like: `\"ingest,\u003ctask id\u003e,\u003cverification status\u003e\"`. The verification status is `OK` if verification succeeded and any other value if it failed.\n- The oracle feed's ingester processes the verification and the handle to address mapping is written to the avl trees that exist as ghverify realm variables.\n"},{"name":"contract.gno","body":"package ghverify\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"errors\"\n\n\t\"gno.land/p/demo/gnorkle/feeds/static/v0\"\n\t\"gno.land/p/demo/gnorkle/gnorkle/v0\"\n\t\"gno.land/p/demo/gnorkle/message/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\nconst (\n\t// The agent should send this value if it has verified the github handle.\n\tverifiedResult = \"OK\"\n)\n\nvar (\n\townerAddress = unsafe.OriginCaller()\n\toracle       *gnorkle.Instance\n\tpostHandler  postGnorkleMessageHandler\n\n\thandleToAddressMap = bptree.NewBPTree32()\n\taddressToHandleMap = bptree.NewBPTree32()\n)\n\nfunc init() {\n\toracle = gnorkle.NewInstance()\n\toracle.AddToWhitelist(\"\", []string{string(ownerAddress)})\n}\n\ntype postGnorkleMessageHandler struct{}\n\n// Handle does post processing after a message is ingested by the oracle feed. It extracts the value to realm\n// storage and removes the feed from the oracle.\nfunc (h postGnorkleMessageHandler) Handle(i *gnorkle.Instance, funcType message.FuncType, feed gnorkle.Feed) error {\n\tif funcType != message.FuncTypeIngest {\n\t\treturn nil\n\t}\n\n\tresult, _, consumable := feed.Value()\n\tif !consumable {\n\t\treturn nil\n\t}\n\n\t// The value is consumable, meaning the ingestion occurred, so we can remove the feed from the oracle\n\t// after saving it to realm storage.\n\tdefer oracle.RemoveFeed(feed.ID())\n\n\t// Couldn't verify; nothing to do.\n\tif result.String != verifiedResult {\n\t\treturn nil\n\t}\n\n\tfeedTasks := feed.Tasks()\n\tif len(feedTasks) != 1 {\n\t\treturn errors.New(\"expected feed to have exactly one task\")\n\t}\n\n\ttask, ok := feedTasks[0].(*verificationTask)\n\tif !ok {\n\t\treturn errors.New(\"expected ghverify task\")\n\t}\n\n\thandleToAddressMap.Set(task.githubHandle, task.gnoAddress)\n\taddressToHandleMap.Set(task.gnoAddress, task.githubHandle)\n\treturn nil\n}\n\n// RequestVerification creates a new static feed with a single task that will\n// instruct an agent to verify the github handle / gno address pair.\nfunc RequestVerification(cur realm, githubHandle string) {\n\tgnoAddress := string(unsafe.OriginCaller())\n\tif err := oracle.AddFeeds(\n\t\tstatic.NewSingleValueFeed(\n\t\t\tgnoAddress,\n\t\t\t\"string\",\n\t\t\t\u0026verificationTask{\n\t\t\t\tgnoAddress:   gnoAddress,\n\t\t\t\tgithubHandle: githubHandle,\n\t\t\t},\n\t\t),\n\t); err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\n\t\t\"verification_requested\",\n\t\t\"from\", gnoAddress,\n\t\t\"handle\", githubHandle,\n\t)\n}\n\n// GnorkleEntrypoint is the entrypoint to the gnorkle oracle handler.\nfunc GnorkleEntrypoint(cur realm, message string) string {\n\tresult, err := oracle.HandleMessage(message, postHandler)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn result\n}\n\n// SetOwner transfers ownership of the contract to the given address.\nfunc SetOwner(_ realm, owner address) {\n\tif ownerAddress != unsafe.OriginCaller() {\n\t\tpanic(\"only the owner can set a new owner\")\n\t}\n\n\townerAddress = owner\n\n\t// In the context of this contract, the owner is the only one that can\n\t// add new feeds to the oracle.\n\toracle.ClearWhitelist(\"\")\n\toracle.AddToWhitelist(\"\", []string{string(ownerAddress)})\n}\n\n// GetHandleByAddress returns the github handle associated with the given gno address.\nfunc GetHandleByAddress(cur realm, address_XXX string) string {\n\tif value := addressToHandleMap.Get(address_XXX); value != nil {\n\t\treturn value.(string)\n\t}\n\n\treturn \"\"\n}\n\n// GetAddressByHandle returns the gno address associated with the given github handle.\nfunc GetAddressByHandle(cur realm, handle string) string {\n\tif value := handleToAddressMap.Get(handle); value != nil {\n\t\treturn value.(string)\n\t}\n\n\treturn \"\"\n}\n\n// Render returns a json object string will all verified handle -\u003e address mappings.\nfunc Render(_ string) string {\n\tresult := \"{\"\n\tvar appendComma bool\n\thandleToAddressMap.Iterate(\"\", \"\", func(handle string, address_XXX any) bool {\n\t\tif appendComma {\n\t\t\tresult += \",\"\n\t\t}\n\n\t\tresult += `\"` + handle + `\": \"` + address_XXX.(string) + `\"`\n\t\tappendComma = true\n\n\t\treturn false\n\t})\n\n\treturn result + \"}\"\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/gnoland/ghverify\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"\n"},{"name":"task.gno","body":"package ghverify\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n)\n\ntype verificationTask struct {\n\tgnoAddress   string\n\tgithubHandle string\n}\n\n// MarshalJSON marshals the task contents to JSON.\nfunc (t *verificationTask) MarshalJSON() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tw := bufio.NewWriter(buf)\n\n\tw.Write(\n\t\t[]byte(`{\"gno_address\":\"` + t.gnoAddress + `\",\"github_handle\":\"` + t.githubHandle + `\"}`),\n\t)\n\n\tw.Flush()\n\treturn buf.Bytes(), nil\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"nestedpkg","path":"gno.land/p/nt/nestedpkg/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/nestedpkg/v0\"\ngno = \"0.9\"\n"},{"name":"nestedpkg.gno","body":"// Package nestedpkg provides helpers for package-path based access control.\n// It is useful for upgrade patterns relying on namespaces.\n//\n// SECURITY: every exported helper takes `rlm realm` and reads both\n// `rlm.PkgPath()` and `rlm.Previous().PkgPath()` to make an\n// authorization decision. To close Class-2 designation forgery (a\n// hostile realm stashes a captured realm value and passes it back to\n// spoof identity), every helper gates on `rlm.IsCurrent()` first. The\n// Is* predicates return false on stale rlm (fail-closed); the Assert*\n// helpers panic. See docs/resources/gno-security.md.\npackage nestedpkg\n\nimport \"strings\"\n\n// IsCallerSubPath checks if the caller realm is located in a subfolder of the current realm.\nfunc IsCallerSubPath(_ int, rlm realm) bool {\n\tif !rlm.IsCurrent() {\n\t\treturn false\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\treturn strings.HasPrefix(prevPath, curPath)\n}\n\n// AssertCallerIsSubPath panics if IsCallerSubPath returns false.\nfunc AssertCallerIsSubPath(_ int, rlm realm) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\tif !strings.HasPrefix(prevPath, curPath) {\n\t\tpanic(\"call restricted to nested packages. current realm is \" + curPath + \", previous realm is \" + prevPath)\n\t}\n}\n\n// IsCallerParentPath checks if the caller realm is located in a parent location of the current realm.\nfunc IsCallerParentPath(_ int, rlm realm) bool {\n\tif !rlm.IsCurrent() {\n\t\treturn false\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\treturn strings.HasPrefix(curPath, prevPath)\n}\n\n// AssertCallerIsParentPath panics if IsCallerParentPath returns false.\nfunc AssertCallerIsParentPath(_ int, rlm realm) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\tif !strings.HasPrefix(curPath, prevPath) {\n\t\tpanic(\"call restricted to parent packages. current realm is \" + curPath + \", previous realm is \" + prevPath)\n\t}\n}\n\n// IsSameNamespace checks if the caller realm and the current realm are in the same namespace.\nfunc IsSameNamespace(_ int, rlm realm) bool {\n\tif !rlm.IsCurrent() {\n\t\treturn false\n\t}\n\tvar (\n\t\tcurNs  = nsFromPath(rlm.PkgPath()) + \"/\"\n\t\tprevNs = nsFromPath(rlm.Previous().PkgPath()) + \"/\"\n\t)\n\treturn curNs == prevNs\n}\n\n// AssertIsSameNamespace panics if IsSameNamespace returns false.\nfunc AssertIsSameNamespace(_ int, rlm realm) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tvar (\n\t\tcurNs  = nsFromPath(rlm.PkgPath()) + \"/\"\n\t\tprevNs = nsFromPath(rlm.Previous().PkgPath()) + \"/\"\n\t)\n\tif curNs != prevNs {\n\t\tpanic(\"call restricted to packages from the same namespace. current realm is \" + curNs + \", previous realm is \" + prevNs)\n\t}\n}\n\n// nsFromPath extracts the namespace from a package path.\nfunc nsFromPath(pkgpath string) string {\n\tparts := strings.Split(pkgpath, \"/\")\n\n\t// Specifically for gno.land, potential paths are in the form of DOMAIN/r/NAMESPACE/...\n\t// XXX: Consider extra checks.\n\t// XXX: Support non gno.land domains, where p/ and r/ won't be enforced.\n\tif len(parts) \u003e= 3 {\n\t\treturn parts[2]\n\t}\n\treturn \"\"\n}\n\n// XXX: Consider adding IsCallerDirectlySubPath\n// XXX: Consider adding IsCallerDirectlyParentPath\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"vm","path":"gno.land/r/tests/vm","files":[{"name":"README.md","body":"Modules here are only useful for file realm tests.\nThey can be safely ignored for other purposes.\n"},{"name":"exploit.gno","body":"package vm\n\nvar MyFoo *Foo\n\ntype Foo struct {\n\tA int\n\tB *Foo\n}\n\n// method to mutate\n\nfunc (f *Foo) UpdateFoo(x int) {\n\tf.A = x\n}\n\nfunc init() {\n\tMyFoo = \u0026Foo{\n\t\tA: 1,\n\t\tB: \u0026Foo{\n\t\t\tA: 2,\n\t\t},\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm\"\ngno = \"0.9\"\n"},{"name":"interfaces.gno","body":"package vm\n\nimport (\n\t\"strconv\"\n)\n\ntype Stringer interface {\n\tString() string\n}\n\nvar stringers []Stringer\n\nfunc AddStringer(cur realm, str Stringer) {\n\t// NOTE: this is ridiculous, a slice that will become too long\n\t// eventually.  Don't do this in production programs; use\n\t// gno.land/p/nt/avl/v0 or similar structures.\n\tstringers = append(stringers, str)\n}\n\nfunc Render(path string) string {\n\tres := \"\"\n\t// NOTE: like the function above, this function too will eventually\n\t// become too expensive to call.\n\tfor i, stringer := range stringers {\n\t\tres += strconv.Itoa(i) + \": \" + stringer.String() + \"\\n\"\n\t}\n\treturn res\n}\n"},{"name":"realm_compositelit.gno","body":"package vm\n\ntype (\n\tWord uint\n\tnat  []Word\n)\n\nvar zero = \u0026Int{\n\tneg: true,\n\tabs: []Word{0},\n}\n\n// structLit\ntype Int struct {\n\tneg bool\n\tabs nat\n}\n\nfunc GetZeroType() nat {\n\ta := zero.abs\n\treturn a\n}\n"},{"name":"realm_method38d.gno","body":"package vm\n\nvar abs nat\n\nfunc (n nat) Add() nat {\n\treturn []Word{0}\n}\n\nfunc GetAbs(cur realm) nat {\n\tabs = []Word{0}\n\treturn abs\n}\n\nfunc AbsAdd(cur realm) nat {\n\trt := GetAbs(cur).Add()\n\treturn rt\n}\n"},{"name":"tests.gno","body":"package vm\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/nestedpkg/v0\"\n\trsubtests \"gno.land/r/tests/vm/subtests\"\n)\n\nvar counter int\n\nfunc IncCounter(cur realm) {\n\tcounter++\n}\n\nfunc Counter(cur realm) int {\n\treturn counter\n}\n\nfunc CurrentRealmPath(cur realm) string {\n\treturn unsafe.CurrentRealm().PkgPath()\n}\n\nvar initOriginCaller = unsafe.OriginCaller()\n\nfunc InitOriginCaller(cur realm) address {\n\treturn initOriginCaller\n}\n\nfunc CallAssertOriginCall(cur realm) {\n\truntime.AssertOriginCall()\n}\n\nfunc CallIsOriginCall(cur realm) bool {\n\t// XXX: consider return !unsafe.PreviousRealm().IsCode()\n\treturn unsafe.PreviousRealm().IsUser()\n}\n\nfunc CallSubtestsAssertOriginCall(cur realm) {\n\trsubtests.CallAssertOriginCall(cross(cur))\n}\n\nfunc CallSubtestsIsOriginCall(cur realm) bool {\n\treturn rsubtests.CallIsOriginCall(cross(cur))\n}\n\n//----------------------------------------\n// Test structure to ensure cross-realm modification is prevented.\n\ntype TestRealmObject struct {\n\tField string\n}\n\nvar TestRealmObjectValue TestRealmObject\n\n// NewTestRealmObject returns a fresh heap-allocated TestRealmObject.\n// Non-crossing — relies on borrow rule #1 to set m.Realm = /r/tests/vm\n// inside the body so the composite literal passes checkConstructionTime.\nfunc NewTestRealmObject() *TestRealmObject {\n\treturn \u0026TestRealmObject{Field: \"initial\"}\n}\n\nfunc ModifyTestRealmObject(cur realm, t *TestRealmObject) {\n\tt.Field += \"_modified\"\n}\n\nfunc (t *TestRealmObject) Modify() {\n\tt.Field += \"_modified\"\n}\n\n//----------------------------------------\n// Test helpers to test a particular realm bug.\n\ntype TestNode struct {\n\tName  string\n\tChild *TestNode\n}\n\nvar (\n\tgTestNode1 *TestNode\n\tgTestNode2 *TestNode\n\tgTestNode3 *TestNode\n)\n\nfunc InitTestNodes(cur realm) {\n\tgTestNode1 = \u0026TestNode{Name: \"first\"}\n\tgTestNode2 = \u0026TestNode{Name: \"second\", Child: \u0026TestNode{Name: \"second's child\"}}\n}\n\nfunc ModTestNodes(cur realm) {\n\ttmp := \u0026TestNode{}\n\ttmp.Child = gTestNode2.Child\n\tgTestNode3 = tmp // set to new-real\n\t// gTestNode1 = tmp.Child // set back to original is-real\n\tgTestNode3 = nil // delete.\n}\n\nfunc PrintTestNodes() {\n\tprintln(gTestNode2.Child.Name)\n}\n\nfunc GetPreviousRealm(cur realm) runtime.Realm {\n\treturn unsafe.PreviousRealm()\n}\n\nfunc GetRSubtestsPreviousRealm(cur realm) runtime.Realm {\n\treturn rsubtests.GetPreviousRealm(cross(cur))\n}\n\nfunc Exec(fn func()) {\n\t// no realm switching.\n\tfn()\n}\n\n// ExecRlm mirrors Exec but threads the caller's rlm into the callback\n// so the callback can use `cross(rlm)` instead of bare `cross`.\nfunc ExecRlm(_ int, rlm realm, fn func(_ int, rlm realm)) {\n\tfn(0, rlm)\n}\n\nfunc ExecSwitch(cur realm, fn func()) {\n\tfn()\n}\n\n// ExecSwitchRlm is the rlm-threaded variant of ExecSwitch — crosses\n// into this realm and passes the callee's cur to the callback so\n// the callback can `cross(rlm)` against the switched realm.\nfunc ExecSwitchRlm(cur realm, fn func(_ int, rlm realm)) {\n\tfn(0, cur)\n}\n\nfunc IsCallerSubPath(cur realm) bool {\n\treturn nestedpkg.IsCallerSubPath(0, cur)\n}\n\nfunc IsCallerParentPath(cur realm) bool {\n\treturn nestedpkg.IsCallerParentPath(0, cur)\n}\n\nfunc HasCallerSameNamespace(cur realm) bool {\n\treturn nestedpkg.IsSameNamespace(0, cur)\n}\n\nfunc BankerOriginSend(cur realm) string {\n\treturn unsafe.OriginSend().String()\n}\n\nfunc RTestsOriginSend(cur realm) string {\n\treturn rsubtests.BankerOriginSend(cross(cur))\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"wugnot","path":"gno.land/r/gnoland/wugnot","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gnoland/wugnot\"\ngno = \"0.9\"\n"},{"name":"wugnot.gno","body":"package wugnot\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nvar (\n\tToken *grc20.Token\n\tadm   *grc20.PrivateLedger\n)\n\nconst (\n\tugnotMinDeposit  int64 = 1000\n\twugnotMinDeposit int64 = 1\n)\n\nfunc init(cur realm) {\n\t// wugnot only ever creates this one token, so id 0 can't collide.\n\tToken, adm = grc20.NewToken(\"wrapped GNOT\", \"wugnot\", 0, 0, cur)\n\tgrc20reg.Register(cross(cur), Token, \"\")\n}\n\nfunc Deposit(cur realm) {\n\t// Prevent cross-realm MITM: without this, an intermediary could\n\t// deposit on behalf of the caller and mint wugnot to itself\n\t// instead of the actual sender.\n\truntime.AssertOriginCall()\n\tcaller := cur.Previous().Address()\n\tsent := unsafe.OriginSend()\n\tamount := sent.AmountOf(\"ugnot\")\n\n\trequire(int64(amount) \u003e= ugnotMinDeposit, ufmt.Sprintf(\"Deposit below minimum: %d/%d ugnot.\", amount, ugnotMinDeposit))\n\n\tcheckErr(adm.Mint(caller, int64(amount)))\n}\n\nfunc Withdraw(cur realm, amount int64) {\n\truntime.AssertOriginCall()\n\trequire(amount \u003e= wugnotMinDeposit, ufmt.Sprintf(\"Deposit below minimum: %d/%d wugnot.\", amount, wugnotMinDeposit))\n\n\tcaller := cur.Previous().Address()\n\tpkgaddr := cur.Address()\n\tcallerBal := Token.BalanceOf(caller)\n\trequire(amount \u003c= callerBal, ufmt.Sprintf(\"Insufficient balance: %d available, %d needed.\", callerBal, amount))\n\n\t// send swapped ugnots to qcaller\n\tstdBanker := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tsend := chain.Coins{{\"ugnot\", int64(amount)}}\n\tstdBanker.SendCoins(pkgaddr, caller, send)\n\tcheckErr(adm.Burn(caller, amount))\n}\n\nfunc Render(path string) string {\n\tparts := strings.Split(path, \"/\")\n\tc := len(parts)\n\n\tswitch {\n\tcase path == \"\":\n\t\treturn Token.RenderHome()\n\tcase c == 2 \u0026\u0026 parts[0] == \"balance\":\n\t\towner := address(parts[1])\n\t\tbalance := Token.BalanceOf(owner)\n\t\treturn ufmt.Sprintf(\"%d\", balance)\n\tdefault:\n\t\treturn \"404\"\n\t}\n}\n\nfunc TotalSupply() int64 {\n\treturn Token.TotalSupply()\n}\n\nfunc BalanceOf(owner address) int64 {\n\treturn Token.BalanceOf(owner)\n}\n\nfunc Allowance(owner, spender address) int64 {\n\treturn Token.Allowance(owner, spender)\n}\n\nfunc Transfer(cur realm, to address, amount int64) {\n\tuserTeller := adm.CallerTeller()\n\tcheckErr(userTeller.Transfer(0, cur, to, amount))\n}\n\nfunc Approve(cur realm, spender address, amount int64) {\n\tuserTeller := adm.CallerTeller()\n\tcheckErr(userTeller.Approve(0, cur, spender, amount))\n}\n\nfunc TransferFrom(cur realm, from, to address, amount int64) {\n\tuserTeller := adm.CallerTeller()\n\tcheckErr(userTeller.TransferFrom(0, cur, from, to, amount))\n}\n\nfunc require(condition bool, msg string) {\n\tif !condition {\n\t\tpanic(msg)\n\t}\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"events","path":"gno.land/r/devrels/events","files":[{"name":"errors.gno","body":"package events\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n)\n\nvar (\n\tErrEmptyName                 = errors.New(\"event name cannot be empty\")\n\tErrNoSuchID                  = errors.New(\"event with specified ID does not exist\")\n\tErrMinWidgetSize             = errors.New(\"you need to request at least 1 event to render\")\n\tErrMaxWidgetSize             = errors.New(\"maximum number of events in widget is\" + strconv.Itoa(MaxWidgetSize))\n\tErrDescriptionTooLong        = errors.New(\"event description is too long\")\n\tErrInvalidStartTime          = errors.New(\"invalid start time format\")\n\tErrInvalidEndTime            = errors.New(\"invalid end time format\")\n\tErrEndBeforeStart            = errors.New(\"end time cannot be before start time\")\n\tErrStartEndTimezonemMismatch = errors.New(\"start and end timezones are not the same\")\n)\n"},{"name":"events.gno","body":"// Package events allows you to upload data about specific IRL/online events\n// It includes dynamic support for updating rendering events based on their\n// status, ie if they are upcoming, in progress, or in the past.\npackage events\n\nimport (\n\t\"chain\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype (\n\tEvent struct {\n\t\tid          string\n\t\tname        string    // name of event\n\t\tdescription string    // short description of event\n\t\tlink        string    // link to auth corresponding web2 page, ie eventbrite/luma or conference page\n\t\tlocation    string    // location of the event\n\t\tstartTime   time.Time // given in RFC3339\n\t\tendTime     time.Time // end time of the event, given in RFC3339\n\t}\n\n\teventsSlice []*Event\n)\n\nvar (\n\tOwnable   = ownable.NewWithAddress(address(\"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\")) // @leohhhn\n\tevents    = make(eventsSlice, 0)                                                        // sorted\n\tidCounter seqid.ID\n)\n\nconst (\n\tmaxDescLength = 100\n\tEventAdded    = \"EventAdded\"\n\tEventDeleted  = \"EventDeleted\"\n\tEventEdited   = \"EventEdited\"\n)\n\n// AddEvent adds auth new event\n// Start time \u0026 end time need to be specified in RFC3339, ie 2024-08-08T12:00:00+02:00\nfunc AddEvent(cur realm, name, description, link, location, startTime, endTime string) (string, error) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\n\tif strings.TrimSpace(name) == \"\" {\n\t\treturn \"\", ErrEmptyName\n\t}\n\n\tif len(description) \u003e maxDescLength {\n\t\treturn \"\", ufmt.Errorf(\"%s: provided length is %d, maximum is %d\", ErrDescriptionTooLong, len(description), maxDescLength)\n\t}\n\n\t// Parse times\n\tst, et, err := parseTimes(startTime, endTime)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tid := idCounter.Next().String()\n\te := \u0026Event{\n\t\tid:          id,\n\t\tname:        name,\n\t\tdescription: description,\n\t\tlink:        link,\n\t\tlocation:    location,\n\t\tstartTime:   st,\n\t\tendTime:     et,\n\t}\n\n\tevents = append(events, e)\n\tsort.Sort(events)\n\n\tchain.Emit(EventAdded,\n\t\t\"id\", e.id,\n\t)\n\n\treturn id, nil\n}\n\n// DeleteEvent deletes an event with auth given ID\nfunc DeleteEvent(cur realm, id string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\n\te, idx, err := GetEventByID(id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tevents = append(events[:idx], events[idx+1:]...)\n\n\tchain.Emit(EventDeleted,\n\t\t\"id\", e.id,\n\t)\n}\n\n// EditEvent edits an event with auth given ID\n// It only updates values corresponding to non-empty arguments sent with the call\n// Note: if you need to update the start time or end time, you need to provide both every time\nfunc EditEvent(cur realm, id string, name, description, link, location, startTime, endTime string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\n\te, _, err := GetEventByID(id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Set only valid values\n\tif strings.TrimSpace(name) != \"\" {\n\t\te.name = name\n\t}\n\n\tif strings.TrimSpace(description) != \"\" {\n\t\te.description = description\n\t}\n\n\tif strings.TrimSpace(link) != \"\" {\n\t\te.link = link\n\t}\n\n\tif strings.TrimSpace(location) != \"\" {\n\t\te.location = location\n\t}\n\n\tif strings.TrimSpace(startTime) != \"\" || strings.TrimSpace(endTime) != \"\" {\n\t\tst, et, err := parseTimes(startTime, endTime)\n\t\tif err != nil {\n\t\t\tpanic(err) // need to also revert other state changes\n\t\t}\n\n\t\toldStartTime := e.startTime\n\t\te.startTime = st\n\t\te.endTime = et\n\n\t\t// If sort order was disrupted, sort again\n\t\tif oldStartTime != e.startTime {\n\t\t\tsort.Sort(events)\n\t\t}\n\t}\n\n\tchain.Emit(EventEdited,\n\t\t\"id\", e.id,\n\t)\n}\n\nfunc GetEventByID(id string) (*Event, int, error) {\n\tfor i, event := range events {\n\t\tif event.id == id {\n\t\t\treturn event, i, nil\n\t\t}\n\t}\n\n\treturn nil, -1, ErrNoSuchID\n}\n\n// Len returns the length of the slice\nfunc (m eventsSlice) Len() int {\n\treturn len(m)\n}\n\n// Less compares the startTime fields of two elements\n// In this case, events will be sorted by largest startTime first (upcoming \u003e past)\nfunc (m eventsSlice) Less(i, j int) bool {\n\treturn m[i].startTime.After(m[j].startTime)\n}\n\n// Swap swaps two elements in the slice\nfunc (m eventsSlice) Swap(i, j int) {\n\tm[i], m[j] = m[j], m[i]\n}\n\n// parseTimes parses the start and end time for an event and checks for possible errors\nfunc parseTimes(startTime, endTime string) (time.Time, time.Time, error) {\n\tst, err := time.Parse(time.RFC3339, startTime)\n\tif err != nil {\n\t\treturn time.Time{}, time.Time{}, ufmt.Errorf(\"%s: %s\", ErrInvalidStartTime, err.Error())\n\t}\n\n\tet, err := time.Parse(time.RFC3339, endTime)\n\tif err != nil {\n\t\treturn time.Time{}, time.Time{}, ufmt.Errorf(\"%s: %s\", ErrInvalidEndTime, err.Error())\n\t}\n\n\tif et.Before(st) {\n\t\treturn time.Time{}, time.Time{}, ErrEndBeforeStart\n\t}\n\n\t_, stOffset := st.Zone()\n\t_, etOffset := et.Zone()\n\tif stOffset != etOffset {\n\t\treturn time.Time{}, time.Time{}, ErrStartEndTimezonemMismatch\n\t}\n\n\treturn st, et, nil\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/devrels/events\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"\n"},{"name":"render.gno","body":"package events\n\nimport (\n\t\"bytes\"\n\n\t\"time\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\tMaxWidgetSize = 5\n)\n\n// RenderEventWidget shows up to eventsToRender of the latest events to a caller\nfunc RenderEventWidget(eventsToRender int) (string, error) {\n\tnumOfEvents := len(events)\n\tif numOfEvents == 0 {\n\t\treturn \"No events.\", nil\n\t}\n\n\tif eventsToRender \u003e MaxWidgetSize {\n\t\treturn \"\", ErrMaxWidgetSize\n\t}\n\n\tif eventsToRender \u003c 1 {\n\t\treturn \"\", ErrMinWidgetSize\n\t}\n\n\tif eventsToRender \u003e numOfEvents {\n\t\teventsToRender = numOfEvents\n\t}\n\n\toutput := \"\"\n\n\tfor _, event := range events[:eventsToRender] {\n\t\toutput += ufmt.Sprintf(\"- [%s](%s)\\n\", event.name, event.link)\n\t}\n\n\treturn output, nil\n}\n\n// renderHome renders the home page of the events realm\nfunc renderHome(admin bool) string {\n\toutput := \"# gno.land events\\n\\n\"\n\n\tif len(events) == 0 {\n\t\toutput += \"No upcoming or past events.\"\n\t\treturn output\n\t}\n\n\toutput += \"Below is a list of all gno.land events, including in progress, upcoming, and past ones.\\n\\n\"\n\toutput += \"---\\n\\n\"\n\n\tvar (\n\t\tinProgress []string\n\t\tupcoming   []string\n\t\tpast       []string\n\t\tnow        = time.Now()\n\t)\n\n\tfor _, e := range events {\n\t\tif now.Before(e.startTime) {\n\t\t\tupcoming = append(upcoming, e.Render(admin))\n\t\t} else if now.After(e.endTime) {\n\t\t\tpast = append(past, e.Render(admin))\n\t\t} else {\n\t\t\tinProgress = append(inProgress, e.Render(admin))\n\t\t}\n\t}\n\n\tif len(upcoming) != 0 {\n\t\t// Add upcoming events\n\t\toutput += \"## Upcoming events\\n\\n\"\n\t\toutput += md.ColumnsN(upcoming, 3, true)\n\t\toutput += \"---\\n\\n\"\n\t}\n\n\tif len(inProgress) != 0 {\n\t\toutput += \"## Currently in progress\\n\\n\"\n\t\toutput += md.ColumnsN(inProgress, 3, true)\n\t\toutput += \"---\\n\\n\"\n\t}\n\n\tif len(past) != 0 {\n\t\t// Add past events\n\t\toutput += \"## Past events\\n\\n\"\n\t\toutput += md.ColumnsN(past, 3, true)\n\t}\n\n\treturn output\n}\n\n// Render returns the markdown representation of a single event instance\nfunc (e Event) Render(admin bool) string {\n\tvar buf bytes.Buffer\n\n\tbuf.WriteString(ufmt.Sprintf(\"### %s\\n\\n\", e.name))\n\tbuf.WriteString(ufmt.Sprintf(\"%s\\n\\n\", e.description))\n\tbuf.WriteString(ufmt.Sprintf(\"**Location:** %s\\n\\n\", e.location))\n\n\t_, offset := e.startTime.Zone() // offset is in seconds\n\thoursOffset := offset / (60 * 60)\n\tsign := \"\"\n\tif offset \u003e= 0 {\n\t\tsign = \"+\"\n\t}\n\n\tbuf.WriteString(ufmt.Sprintf(\"**Starts:** %s UTC%s%d\\n\\n\", e.startTime.Format(\"02 Jan 2006, 03:04 PM\"), sign, hoursOffset))\n\tbuf.WriteString(ufmt.Sprintf(\"**Ends:** %s UTC%s%d\\n\\n\", e.endTime.Format(\"02 Jan 2006, 03:04 PM\"), sign, hoursOffset))\n\n\tif admin {\n\t\tbuf.WriteString(ufmt.Sprintf(\"[EDIT](/r/devrels/events$help\u0026func=EditEvent\u0026id=%s)\\n\\n\", e.id))\n\t\tbuf.WriteString(ufmt.Sprintf(\"[DELETE](/r/devrels/events$help\u0026func=DeleteEvent\u0026id=%s)\\n\\n\", e.id))\n\t}\n\n\tif e.link != \"\" {\n\t\tbuf.WriteString(ufmt.Sprintf(\"[See more](%s)\\n\\n\", e.link))\n\t}\n\n\treturn buf.String()\n}\n\n// Render is the main rendering entry point\nfunc Render(path string) string {\n\tif path == \"admin\" {\n\t\treturn renderHome(true)\n\t}\n\n\treturn renderHome(false)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"dynreplacer","path":"gno.land/p/moul/dynreplacer/v0","files":[{"name":"dynreplacer.gno","body":"// Package dynreplacer provides a simple template engine for handling dynamic\n// content replacement. It is similar to strings.Replacer but with lazy\n// execution of replacements, making it more optimization-friendly in several\n// cases. While strings.Replacer requires all replacement values to be computed\n// upfront, dynreplacer only executes the callback functions for placeholders\n// that actually exist in the template, avoiding unnecessary computations.\n//\n// The package ensures efficient, non-recursive replacement of placeholders in a\n// single pass. This lazy evaluation approach is particularly beneficial when:\n// - Some replacement values are expensive to compute\n// - Not all placeholders are guaranteed to be present in the template\n// - Templates are reused with different content\n//\n// Example usage:\n//\n//\tr := dynreplacer.New(\n//\t    dynreplacer.Pair{\":name:\", func() string { return \"World\" }},\n//\t    dynreplacer.Pair{\":greeting:\", func() string { return \"Hello\" }},\n//\t)\n//\tresult := r.Replace(\"Hello :name:!\") // Returns \"Hello World!\"\n//\n// The replacer caches computed values, so subsequent calls with the same\n// placeholder will reuse the cached value instead of executing the callback\n// again:\n//\n//\tr := dynreplacer.New()\n//\tr.RegisterCallback(\":expensive:\", func() string { return \"computed\" })\n//\tr.Replace(\"Value1: :expensive:\") // Computes the value\n//\tr.Replace(\"Value2: :expensive:\") // Uses cached value\n//\tr.ClearCache()                   // Force re-computation on next use\npackage dynreplacer\n\nimport (\n\t\"strings\"\n)\n\n// Replacer manages dynamic placeholders, their associated functions, and cached\n// values.\ntype Replacer struct {\n\tcallbacks    map[string]func() string\n\tcachedValues map[string]string\n}\n\n// Pair represents a placeholder and its callback function\ntype Pair struct {\n\tPlaceholder string\n\tCallback    func() string\n}\n\n// New creates a new Replacer instance with optional initial replacements.\n// It accepts pairs where each pair consists of a placeholder string and\n// its corresponding callback function.\n//\n// Example:\n//\n//\tNew(\n//\t    Pair{\":name:\", func() string { return \"World\" }},\n//\t    Pair{\":greeting:\", func() string { return \"Hello\" }},\n//\t)\nfunc New(pairs ...Pair) *Replacer {\n\tr := \u0026Replacer{\n\t\tcallbacks:    make(map[string]func() string),\n\t\tcachedValues: make(map[string]string),\n\t}\n\n\tfor _, pair := range pairs {\n\t\tr.RegisterCallback(pair.Placeholder, pair.Callback)\n\t}\n\n\treturn r\n}\n\n// RegisterCallback associates a placeholder with a function to generate its\n// content.\nfunc (r *Replacer) RegisterCallback(placeholder string, callback func() string) {\n\tr.callbacks[placeholder] = callback\n}\n\n// Replace processes the given layout, replacing placeholders with cached or\n// newly computed values.\nfunc (r *Replacer) Replace(layout string) string {\n\treplacements := []string{}\n\n\t// Check for placeholders and compute/retrieve values\n\thasReplacements := false\n\tfor placeholder, callback := range r.callbacks {\n\t\tif strings.Contains(layout, placeholder) {\n\t\t\tvalue, exists := r.cachedValues[placeholder]\n\t\t\tif !exists {\n\t\t\t\tvalue = callback()\n\t\t\t\tr.cachedValues[placeholder] = value\n\t\t\t}\n\t\t\treplacements = append(replacements, placeholder, value)\n\t\t\thasReplacements = true\n\t\t}\n\t}\n\n\t// If no replacements were found, return the original layout\n\tif !hasReplacements {\n\t\treturn layout\n\t}\n\n\t// Create a strings.Replacer with all computed replacements\n\treplacer := strings.NewReplacer(replacements...)\n\treturn replacer.Replace(layout)\n}\n\n// ClearCache clears all cached values, forcing re-computation on next Replace.\nfunc (r *Replacer) ClearCache() {\n\tr.cachedValues = make(map[string]string)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/dynreplacer/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"blog","path":"gno.land/p/gnoland/blog/v0","files":[{"name":"blog.gno","body":"package blog\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype Blog struct {\n\tTitle             string\n\tPrefix            string   // i.e. r/gnoland/blog:\n\tPosts             avl.Tree // slug -\u003e *Post\n\tPostsPublished    avl.Tree // published-date -\u003e *Post\n\tPostsAlphabetical avl.Tree // title -\u003e *Post\n\tNoBreadcrumb      bool\n}\n\nfunc (b Blog) RenderLastPostsWidget(limit int) string {\n\tif b.PostsPublished.Size() == 0 {\n\t\treturn \"No posts.\"\n\t}\n\n\toutput := \"\"\n\ti := 0\n\tb.PostsPublished.ReverseIterate(\"\", \"\", func(key string, value any) bool {\n\t\tp := value.(*Post)\n\t\toutput += ufmt.Sprintf(\"- [%s](%s)\\n\", p.Title, p.URL())\n\t\ti++\n\t\treturn i \u003e= limit\n\t})\n\treturn output\n}\n\nfunc (b Blog) RenderHome(res *mux.ResponseWriter, _ *mux.Request) {\n\tif !b.NoBreadcrumb {\n\t\tres.Write(breadcrumb([]string{b.Title}))\n\t}\n\n\tif b.Posts.Size() == 0 {\n\t\tres.Write(\"No posts.\")\n\t\treturn\n\t}\n\n\tconst maxCol = 3\n\tvar rowItems []string\n\n\tb.PostsPublished.ReverseIterate(\"\", \"\", func(key string, value any) bool {\n\t\tpost := value.(*Post)\n\t\trowItems = append(rowItems, post.RenderListItem())\n\n\t\tif len(rowItems) == maxCol {\n\t\t\tres.Write(\"\u003cgno-columns\u003e\" + strings.Join(rowItems, \"\u003cgno-columns-sep\u003e\") + \"\u003c/gno-columns\u003e\\n\")\n\t\t\trowItems = []string{}\n\t\t}\n\t\treturn false\n\t})\n\n\t// Pad and flush any remaining items\n\tif len(rowItems) \u003e 0 {\n\t\tfor len(rowItems) \u003c maxCol {\n\t\t\trowItems = append(rowItems, \"\")\n\t\t}\n\t\tres.Write(\"\u003cgno-columns\u003e\" + strings.Join(rowItems, \"\\n\u003cgno-columns-sep\u003e\\n\") + \"\u003c/gno-columns\u003e\\n\")\n\t}\n}\n\nfunc (b Blog) RenderPost(res *mux.ResponseWriter, req *mux.Request) {\n\tslug := req.GetVar(\"slug\")\n\n\tpost := b.Posts.Get(slug)\n\tif post == nil {\n\t\tres.Write(\"404\")\n\t\treturn\n\t}\n\tp := post.(*Post)\n\n\tres.Write(\"\u003cmain class='gno-tmpl-page'\u003e\" + \"\\n\\n\")\n\n\tres.Write(\"# \" + p.Title + \"\\n\\n\")\n\tres.Write(p.Body + \"\\n\\n\")\n\tres.Write(\"---\\n\\n\")\n\n\tres.Write(p.RenderTagList() + \"\\n\\n\")\n\tres.Write(p.RenderAuthorList() + \"\\n\\n\")\n\tres.Write(p.RenderPublishData() + \"\\n\\n\")\n\n\tres.Write(\"---\\n\")\n\tres.Write(\"\u003cdetails\u003e\u003csummary\u003eComment section\u003c/summary\u003e\\n\\n\")\n\n\t// comments\n\tp.Comments.ReverseIterate(\"\", \"\", func(key string, value any) bool {\n\t\tcomment := value.(*Comment)\n\t\tres.Write(comment.RenderListItem())\n\t\treturn false\n\t})\n\n\tres.Write(\"\u003c/details\u003e\\n\")\n\tres.Write(\"\u003c/main\u003e\")\n}\n\nfunc (b Blog) RenderTag(res *mux.ResponseWriter, req *mux.Request) {\n\tslug := req.GetVar(\"slug\")\n\n\tif slug == \"\" {\n\t\tres.Write(\"404\")\n\t\treturn\n\t}\n\n\tif !b.NoBreadcrumb {\n\t\tbreadStr := breadcrumb([]string{\n\t\t\tufmt.Sprintf(\"[%s](%s)\", b.Title, b.Prefix),\n\t\t\t\"t\",\n\t\t\tslug,\n\t\t})\n\t\tres.Write(breadStr)\n\t}\n\n\tnb := 0\n\tb.Posts.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tpost := value.(*Post)\n\t\tif !post.HasTag(slug) {\n\t\t\treturn false\n\t\t}\n\t\tres.Write(post.RenderListItem())\n\t\tnb++\n\t\treturn false\n\t})\n\tif nb == 0 {\n\t\tres.Write(\"No posts.\")\n\t}\n}\n\nfunc (b Blog) Render(path string) string {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"\", b.RenderHome)\n\trouter.HandleFunc(\"p/{slug}\", b.RenderPost)\n\trouter.HandleFunc(\"t/{slug}\", b.RenderTag)\n\treturn router.Render(path)\n}\n\nfunc (b *Blog) NewPost(publisher address, slug, title, body, pubDate string, authors, tags []string) error {\n\tif b.Posts.Has(slug) {\n\t\treturn ErrPostSlugExists\n\t}\n\n\tvar parsedTime time.Time\n\tvar err error\n\tif pubDate != \"\" {\n\t\tparsedTime, err = time.Parse(time.RFC3339, pubDate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// If no publication date was passed in by caller, take current block time\n\t\tparsedTime = time.Now()\n\t}\n\n\tpost := \u0026Post{\n\t\tPublisher: publisher,\n\t\tAuthors:   authors,\n\t\tSlug:      slug,\n\t\tTitle:     title,\n\t\tBody:      body,\n\t\tTags:      tags,\n\t\tCreatedAt: parsedTime,\n\t}\n\n\treturn b.prepareAndSetPost(post, false)\n}\n\nfunc (b *Blog) prepareAndSetPost(post *Post, edit bool) error {\n\tpost.Title = strings.TrimSpace(post.Title)\n\tpost.Body = strings.TrimSpace(post.Body)\n\n\tif post.Title == \"\" {\n\t\treturn ErrPostTitleMissing\n\t}\n\tif post.Body == \"\" {\n\t\treturn ErrPostBodyMissing\n\t}\n\tif post.Slug == \"\" {\n\t\treturn ErrPostSlugMissing\n\t}\n\n\tpost.Blog = b\n\tpost.UpdatedAt = time.Now()\n\n\ttrimmedTitleKey := getTitleKey(post.Title)\n\tpubDateKey := getPublishedKey(post.CreatedAt)\n\n\tif !edit {\n\t\t// Cannot have two posts with same title key\n\t\tif b.PostsAlphabetical.Has(trimmedTitleKey) {\n\t\t\treturn ErrPostTitleExists\n\t\t}\n\t\t// Cannot have two posts with *exact* same timestamp\n\t\tif b.PostsPublished.Has(pubDateKey) {\n\t\t\treturn ErrPostPubDateExists\n\t\t}\n\t}\n\n\t// Store post under keys\n\tb.PostsAlphabetical.Set(trimmedTitleKey, post)\n\tb.PostsPublished.Set(pubDateKey, post)\n\tb.Posts.Set(post.Slug, post)\n\n\treturn nil\n}\n\nfunc (b *Blog) RemovePost(slug string) {\n\tp := b.Posts.Get(slug)\n\tif p == nil {\n\t\tpanic(\"post with specified slug doesn't exist\")\n\t}\n\n\tpost := p.(*Post)\n\n\ttitleKey := getTitleKey(post.Title)\n\tpublishedKey := getPublishedKey(post.CreatedAt)\n\n\t_, _ = b.Posts.Remove(slug)\n\t_, _ = b.PostsAlphabetical.Remove(titleKey)\n\t_, _ = b.PostsPublished.Remove(publishedKey)\n}\n\nfunc (b *Blog) GetPost(slug string) *Post {\n\tpost := b.Posts.Get(slug)\n\tif post == nil {\n\t\treturn nil\n\t}\n\treturn post.(*Post)\n}\n\ntype Post struct {\n\tBlog         *Blog\n\tSlug         string // FIXME: save space?\n\tTitle        string\n\tBody         string\n\tCreatedAt    time.Time\n\tUpdatedAt    time.Time\n\tComments     avl.Tree\n\tAuthors      []string\n\tPublisher    address\n\tTags         []string\n\tCommentIndex int\n}\n\nfunc (p *Post) Update(title, body, publicationDate string, authors, tags []string) error {\n\tp.Title = title\n\tp.Body = body\n\tp.Tags = tags\n\tp.Authors = authors\n\n\tparsedTime, err := time.Parse(time.RFC3339, publicationDate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.CreatedAt = parsedTime\n\treturn p.Blog.prepareAndSetPost(p, true)\n}\n\nfunc (p *Post) AddComment(author address, comment string) error {\n\tif p == nil {\n\t\treturn ErrNoSuchPost\n\t}\n\tp.CommentIndex++\n\tcommentKey := strconv.Itoa(p.CommentIndex)\n\tcomment = strings.TrimSpace(comment)\n\tp.Comments.Set(commentKey, \u0026Comment{\n\t\tPost:      p,\n\t\tCreatedAt: time.Now(),\n\t\tAuthor:    author,\n\t\tComment:   comment,\n\t})\n\n\treturn nil\n}\n\nfunc (p *Post) DeleteComment(index int) error {\n\tif p == nil {\n\t\treturn ErrNoSuchPost\n\t}\n\tcommentKey := strconv.Itoa(index)\n\tp.Comments.Remove(commentKey)\n\treturn nil\n}\n\nfunc (p *Post) HasTag(tag string) bool {\n\tif p == nil {\n\t\treturn false\n\t}\n\tfor _, t := range p.Tags {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Post) RenderListItem() string {\n\tif p == nil {\n\t\treturn \"error: no such post\\n\"\n\t}\n\toutput := ufmt.Sprintf(\"\\n### [%s](%s)\\n\", p.Title, p.URL())\n\t// output += ufmt.Sprintf(\"**[Learn More](%s)**\\n\\n\", p.URL())\n\n\toutput += p.CreatedAt.Format(\"02 Jan 2006\")\n\t// output += p.Summary() + \"\\n\\n\"\n\t// output += p.RenderTagList() + \"\\n\\n\"\n\toutput += \"\\n\"\n\treturn output\n}\n\n// Render post tags\nfunc (p *Post) RenderTagList() string {\n\tif p == nil {\n\t\treturn \"error: no such post\\n\"\n\t}\n\tif len(p.Tags) == 0 {\n\t\treturn \"\"\n\t}\n\n\toutput := \"Tags: \"\n\tfor idx, tag := range p.Tags {\n\t\tif idx \u003e 0 {\n\t\t\toutput += \" \"\n\t\t}\n\t\ttagURL := p.Blog.Prefix + \"t/\" + tag\n\t\toutput += ufmt.Sprintf(\"[#%s](%s)\", tag, tagURL)\n\n\t}\n\treturn output\n}\n\n// Render authors if there are any\nfunc (p *Post) RenderAuthorList() string {\n\tout := \"Written\"\n\tif len(p.Authors) != 0 {\n\t\tout += \" by \"\n\n\t\tfor idx, author := range p.Authors {\n\t\t\tout += author\n\t\t\tif idx \u003c len(p.Authors)-1 {\n\t\t\t\tout += \", \"\n\t\t\t}\n\t\t}\n\t}\n\tout += \" on \" + p.CreatedAt.Format(\"02 Jan 2006\")\n\n\treturn out\n}\n\nfunc (p *Post) RenderPublishData() string {\n\tout := \"Published \"\n\tif p.Publisher != \"\" {\n\t\tout += \"by \" + p.Publisher.String() + \" \"\n\t}\n\tout += \"to \" + p.Blog.Title\n\n\treturn out\n}\n\nfunc (p *Post) URL() string {\n\tif p == nil {\n\t\treturn p.Blog.Prefix + \"404\"\n\t}\n\treturn p.Blog.Prefix + \"p/\" + p.Slug\n}\n\nfunc (p *Post) Summary() string {\n\tif p == nil {\n\t\treturn \"error: no such post\\n\"\n\t}\n\n\t// FIXME: better summary.\n\tlines := strings.Split(p.Body, \"\\n\")\n\tif len(lines) \u003c= 3 {\n\t\treturn p.Body\n\t}\n\treturn strings.Join(lines[0:3], \"\\n\") + \"...\"\n}\n\ntype Comment struct {\n\tPost      *Post\n\tCreatedAt time.Time\n\tAuthor    address\n\tComment   string\n}\n\nfunc (c Comment) RenderListItem() string {\n\toutput := \"\u003ch5\u003e\"\n\toutput += c.Comment + \"\\n\\n\"\n\toutput += \"\u003c/h5\u003e\"\n\n\toutput += \"\u003ch6\u003e\"\n\toutput += ufmt.Sprintf(\"by %s on %s\", c.Author, c.CreatedAt.Format(time.RFC822))\n\toutput += \"\u003c/h6\u003e\\n\\n\"\n\n\toutput += \"---\\n\\n\"\n\n\treturn output\n}\n"},{"name":"errors.gno","body":"package blog\n\nimport \"errors\"\n\nvar (\n\tErrPostTitleMissing  = errors.New(\"post title is missing\")\n\tErrPostSlugMissing   = errors.New(\"post slug is missing\")\n\tErrPostBodyMissing   = errors.New(\"post body is missing\")\n\tErrPostSlugExists    = errors.New(\"post with specified slug already exists\")\n\tErrPostPubDateExists = errors.New(\"post with specified publication date exists\")\n\tErrPostTitleExists   = errors.New(\"post with specified title already exists\")\n\tErrNoSuchPost        = errors.New(\"no such post\")\n)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/gnoland/blog/v0\"\ngno = \"0.9\"\n"},{"name":"util.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"time\"\n)\n\nfunc breadcrumb(parts []string) string {\n\treturn \"# \" + strings.Join(parts, \" / \") + \"\\n\\n\"\n}\n\nfunc getTitleKey(title string) string {\n\treturn strings.ReplaceAll(title, \" \", \"\")\n}\n\nfunc getPublishedKey(t time.Time) string {\n\treturn t.Format(time.RFC3339)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"blog","path":"gno.land/r/gnoland/blog","files":[{"name":"admin.gno","body":"package blog\n\nimport (\n\t\"chain/runtime/unsafe\"\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\nvar (\n\terrNotAdmin     = errors.New(\"access restricted: not admin\")\n\terrNotModerator = errors.New(\"access restricted: not moderator\")\n\terrNotCommenter = errors.New(\"access restricted: not commenter\")\n)\n\nvar (\n\tadminAddr     = address(\"g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx\") // govdao t1 multisig\n\tmoderatorList = bptree.NewBPTree32()\n\tcommenterList = bptree.NewBPTree32()\n\tinPause       bool\n)\n\nfunc AdminSetAdminAddr(_ realm, addr address) {\n\tassertIsAdmin()\n\tadminAddr = addr\n}\n\nfunc AdminSetInPause(_ realm, state bool) {\n\tassertIsAdmin()\n\tinPause = state\n}\n\nfunc AdminAddModerator(_ realm, addr address) {\n\tassertIsAdmin()\n\tmoderatorList.Set(addr.String(), true)\n}\n\nfunc AdminRemoveModerator(_ realm, addr address) {\n\tassertIsAdmin()\n\tmoderatorList.Set(addr.String(), false) // entry kept as a revocation record; isModerator checks the value\n}\n\nfunc NewPostProposalRequest(cur realm, slug, title, body, publicationDate, authors, tags string) dao.ProposalRequest {\n\tcaller := cur.Previous().Address()\n\te := dao.NewSimpleExecutor(0, cur,\n\t\tfunc(realm) error {\n\t\t\taddPost(caller, slug, title, body, publicationDate, authors, tags)\n\n\t\t\treturn nil\n\t\t},\n\t\tufmt.Sprintf(\"- Post Title: %v\\n- Post Publication Date: %v\\n- Authors: %v\\n- Tags: %v\", title, publicationDate, authors, tags),\n\t)\n\n\treturn dao.NewProposalRequest(\n\t\t\"Add new post to gnoland blog\",\n\t\t\"This propoposal is looking to add a new post to gnoland blog\",\n\t\te,\n\t)\n}\n\nfunc ModAddPost(_ realm, slug, title, body, publicationDate, authors, tags string) {\n\tassertIsModerator()\n\tcaller := unsafe.OriginCaller()\n\taddPost(caller, slug, title, body, publicationDate, authors, tags)\n}\n\nfunc addPost(caller address, slug, title, body, publicationDate, authors, tags string) {\n\tvar tagList []string\n\tif tags != \"\" {\n\t\ttagList = strings.Split(tags, \",\")\n\t}\n\tvar authorList []string\n\tif authors != \"\" {\n\t\tauthorList = strings.Split(authors, \",\")\n\t}\n\n\terr := b.NewPost(caller, slug, title, body, publicationDate, authorList, tagList)\n\n\tcheckErr(err)\n}\n\nfunc ModEditPost(_ realm, slug, title, body, publicationDate, authors, tags string) {\n\tassertIsModerator()\n\ttagList := strings.Split(tags, \",\")\n\tauthorList := strings.Split(authors, \",\")\n\n\terr := b.GetPost(slug).Update(title, body, publicationDate, authorList, tagList)\n\tcheckErr(err)\n}\n\nfunc ModRemovePost(_ realm, slug string) {\n\tassertIsModerator()\n\tb.RemovePost(slug)\n}\n\nfunc ModAddCommenter(_ realm, addr address) {\n\tassertIsModerator()\n\tcommenterList.Set(addr.String(), true)\n}\n\nfunc ModDelCommenter(_ realm, addr address) {\n\tassertIsModerator()\n\tcommenterList.Set(addr.String(), false) // entry kept as a revocation record; isCommenter checks the value\n}\n\nfunc ModDelComment(_ realm, slug string, index int) {\n\tassertIsModerator()\n\terr := b.GetPost(slug).DeleteComment(index)\n\tcheckErr(err)\n}\n\nfunc isAdmin(addr address) bool {\n\treturn addr == adminAddr\n}\n\nfunc isModerator(addr address) bool {\n\t// Removed moderators stay in the list with a false value, so the\n\t// stored value must be checked, not just key presence.\n\tactive, _ := moderatorList.Get(addr.String()).(bool)\n\treturn active\n}\n\nfunc isCommenter(addr address) bool {\n\t// Removed commenters stay in the list with a false value, so the\n\t// stored value must be checked, not just key presence.\n\tactive, _ := commenterList.Get(addr.String()).(bool)\n\treturn active\n}\n\nfunc assertIsAdmin() {\n\tcaller := unsafe.OriginCaller()\n\tif !isAdmin(caller) {\n\t\tpanic(errNotAdmin.Error())\n\t}\n}\n\nfunc assertIsModerator() {\n\tcaller := unsafe.OriginCaller()\n\tif isAdmin(caller) || isModerator(caller) {\n\t\treturn\n\t}\n\tpanic(errNotModerator.Error())\n}\n\nfunc assertIsCommenter() {\n\tcaller := unsafe.OriginCaller()\n\tif isAdmin(caller) || isModerator(caller) || isCommenter(caller) {\n\t\treturn\n\t}\n\tpanic(errNotCommenter.Error())\n}\n\nfunc assertNotInPause() {\n\tif inPause {\n\t\tpanic(\"access restricted (pause)\")\n\t}\n}\n"},{"name":"gnoblog.gno","body":"package blog\n\nimport (\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/gnoland/blog/v0\"\n)\n\nvar b = \u0026blog.Blog{\n\tTitle:  \"Gno.land's blog\",\n\tPrefix: \"/r/gnoland/blog:\",\n}\n\nfunc AddComment(_ realm, postSlug, comment string) {\n\tassertIsCommenter()\n\tassertNotInPause()\n\n\tcaller := unsafe.OriginCaller()\n\terr := b.GetPost(postSlug).AddComment(caller, comment)\n\tcheckErr(err)\n}\n\nfunc Render(path string) string {\n\treturn b.Render(path)\n}\n\nfunc RenderLastPostsWidget(limit int) string {\n\treturn b.RenderLastPostsWidget(limit)\n}\n\nfunc PostExists(slug string) bool {\n\tif b.GetPost(slug) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/gnoland/blog\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"\n"},{"name":"util.gno","body":"package blog\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"home","path":"gno.land/r/gnoland/home","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gnoland/home\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"\n"},{"name":"home.gno","body":"package home\n\nimport (\n\t\"chain/runtime\"\n\t\"strconv\"\n\n\t\"gno.land/p/leon/svgbtn/v0\"\n\t\"gno.land/p/moul/dynreplacer/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/r/devrels/events\"\n\tblog \"gno.land/r/gnoland/blog\"\n)\n\nvar (\n\toverride string\n\tAdmin    = ownable.NewWithAddress(\"g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx\") // govdao t1 multisig\n)\n\nfunc Render(_ string) string {\n\tr := dynreplacer.New()\n\tr.RegisterCallback(\":latest-blogposts:\", func() string {\n\t\treturn blog.RenderLastPostsWidget(4)\n\t})\n\tr.RegisterCallback(\":upcoming-events:\", func() string {\n\t\tout, _ := events.RenderEventWidget(events.MaxWidgetSize)\n\t\treturn out\n\t})\n\tr.RegisterCallback(\":qotb:\", quoteOfTheBlock)\n\tr.RegisterCallback(\":newsletter-button:\", newsletterButton)\n\tr.RegisterCallback(\":chain-height:\", func() string {\n\t\treturn strconv.Itoa(int(runtime.ChainHeight()))\n\t})\n\n\ttemplate := `# Welcome to Gno.land\n\nWe're building Gno.land, set to become the leading open-source smart contract\nplatform, using Gno, an interpreted and fully deterministic variation of the\nGo programming language for succinct and composable smart contracts.\n\nWith transparent and timeless code, Gno.land is the next generation of smart\ncontract platforms, serving as the \"GitHub\" of the ecosystem, with realms built\nusing fully transparent, auditable code that anyone can inspect and reuse.\n\nIntuitive and easy to use, Gno.land lowers the barrier to web3 and makes\ncensorship-resistant platforms accessible to everyone. If you want to help lay\nthe foundations of a fairer and freer world, join us today.\n\n---\n\n## [Boards](/r/gnoland/boards2/v0) - On-chain forum for the Gno.land community\n\n**Post, discuss, and create your content community**: Boards is a fully on-chain social forum to create Boards topics, post threads, comment and reply. A plug-and-deploy DAO lets communities manage content, permissions and moderation their way.\n\nExplore this ready-to-use Gno dApp, and experience decentralized social media in action.\n\n**[Open Boards](/r/gnoland/boards2/v0)**\n\n---\n\n\u003cgno-columns\u003e\n## Learn about Gno.land\n\n- [About](/about)\n- [GitHub](https://github.com/gnolang)\n- [Blog](/blog)\n- [Events](/events)\n- [Partners, Fund, Grants](/partners)\n- [Explore the Ecosystem](/ecosystem)\n- [Careers](https://jobs.ashbyhq.com/allinbits)\n\n\u003cgno-columns-sep\u003e\n\n## Build with Gno\n\n- [Write Gno in the browser](https://play.gno.land)\n- [Read about the Gno Language](/gnolang)\n- [Visit the official documentation](https://docs.gno.land)\n- [Efficient local development for Gno](https://docs.gno.land/resources/gnodev)\n- [Get testnet GNOTs](https://faucet.gno.land)\n\n\u003cgno-columns-sep\u003e\n\n## Explore the universe\n\n- [Discover demo packages](https://github.com/gnolang/gno/tree/master/examples)\n- [Gnoscan](https://gnoscan.io)\n- [Gno networks documentation](https://docs.gno.land/resources/gnoland-networks/)\n- [Staging](https://staging.gno.land/)\n- [Testnet 12](https://test12.testnets.gno.land/)\n- [Faucet Hub](https://faucet.gno.land)\n\n\u003c/gno-columns\u003e\n\n\u003cgno-columns\u003e\n\n## [Latest Blogposts](/r/gnoland/blog)\n\n:latest-blogposts:\n\n\u003cgno-columns-sep\u003e\n\n## [Latest Events](/events)\n\n:upcoming-events:\n\n\u003c/gno-columns\u003e\n\n---\n\n## [Gno Playground](https://play.gno.land)\n\nGno Playground is a web application designed for building, running, testing, and\ninteracting with your Gno code, enhancing your understanding of the Gno\nlanguage. With Gno Playground, you can share your code, execute tests, deploy\nyour realms and packages to Gno.land, and explore a multitude of other features.\n\nExperience the convenience of code sharing and rapid experimentation with\n[Gno Playground](https://play.gno.land).\n\n---\n\n## Explore New Packages and Realms\n\nAll code in Gno.land is organized in packages, and each package lives at a unique package path like\n\"r/gnoland/home\". You can browse packages, inspect their source, and use them in your own libraries and realms.\n\n\u003cgno-columns\u003e\n\n### r/gnoland\n\nOfficial realm packages developed by the Gno.land core team.\n\n[Browse](/r/gnoland)\n\n\u003cgno-columns-sep\u003e\n\n### r/sys\n\nSystem-level realm packages used by the chain.\n\n[Browse](/r/sys)\n\n\u003cgno-columns-sep\u003e\n\n### r/demo\n\nDemo realm packages showcasing what’s possible.\n\n[Browse](/r/demo)\n\n\u003cgno-columns-sep\u003e\n\n### p/demo\n\nPure packages for demo purposes.\n\n[Browse](/p/demo)\n\n\u003c/gno-columns\u003e\n\n---\n\n\u003cgno-columns\u003e\n\n## Socials\n\n- Check out our [community projects](https://github.com/gnolang/awesome-gno)\n- [Discord](https://discord.com/invite/gnoland)\n- [Bubble Rumble](https://bubblerumble.net/)\n- [Twitter](https://twitter.com/_gnoland)\n- [Youtube](https://www.youtube.com/@_gnoland)\n- [Telegram](https://t.me/gnoland)\n\n\u003cgno-columns-sep\u003e\n\n## Quote of the ~Day~ Block #:chain-height:\n\n\u003e :qotb:\n\n\u003c/gno-columns\u003e\n\n---\n\n## Sign up for our newsletter\n\nStay in the Gno by signing up for our newsletter. You'll get the scoop on dev updates, fresh content, and community news.\n\n:newsletter-button:\n\n---\n\n**This is a testnet.** Package names are not guaranteed to be available for production.`\n\n\tif override != \"\" {\n\t\ttemplate = override\n\t}\n\tresult := r.Replace(template)\n\treturn result\n}\n\nfunc newsletterButton() string {\n\treturn svgbtn.Button(\n\t\t256,\n\t\t44,\n\t\t\"#226c57\",\n\t\t\"#ffffff\",\n\t\t\"Subscribe to stay in the Gno\",\n\t\t\"https://land.us18.list-manage.com/subscribe?u=8befe3303cf82796d2c1a1aff\u0026id=271812000b\",\n\t)\n}\n\nfunc quoteOfTheBlock() string {\n\tquotes := []string{\n\t\t\"Gno is for Truth.\",\n\t\t\"Gno is for Social Coordination.\",\n\t\t\"Gno is _not only_ for DeFi.\",\n\t\t\"Now, you Gno.\",\n\t\t\"Come for the Go, Stay for the Gno.\",\n\t}\n\theight := runtime.ChainHeight()\n\tidx := int(height) % len(quotes)\n\tqotb := quotes[idx]\n\treturn qotb\n}\n\nfunc AdminSetOverride(cur realm, content string) {\n\tAdmin.AssertOwnedBy(cur.Previous().Address())\n\toverride = content\n}\n\nfunc AdminTransferOwnership(cur realm, newOwner address) {\n\tif err := Admin.TransferOwnership(0, cur, newOwner); err != nil {\n\t\tpanic(err)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"cla","path":"gno.land/r/sys/cla","files":[{"name":"admin.gno","body":"package cla\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/moul/addrset/v0\"\n\t\"gno.land/p/moul/helplink/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\nconst RequiredHashChangedEvent = \"CLARequiredHashChanged\"\n\n// ProposeNewCLA creates a govdao proposal to update the CLA document hash and URL.\n// When executed, it resets all existing signatures.\n// Propose an empty hash to disable CLA enforcement.\nfunc ProposeNewCLA(cur realm, newHash, newURL string) dao.ProposalRequest {\n\tcb := func(cur realm) error {\n\t\tsetRequiredHash(newHash)\n\t\tclaURL = newURL\n\t\treturn nil\n\t}\n\n\tdesc := \"Propose updating the CLA requirement.\\n\\n\"\n\tif requiredHash != \"\" {\n\t\tdesc += \"Current hash: \" + requiredHash + \"\\n\"\n\t}\n\tif claURL != \"\" {\n\t\tdesc += \"Current URL: \" + claURL + \"\\n\"\n\t}\n\tif newHash != \"\" {\n\t\tdesc += \"New hash: \" + newHash + \"\\n\"\n\t}\n\tif newURL != \"\" {\n\t\tdesc += \"New URL: \" + newURL + \"\\n\"\n\t}\n\tif newHash == \"\" {\n\t\tdesc += \"This proposal disables CLA enforcement.\\n\"\n\t}\n\n\treturn dao.NewProposalRequest(\n\t\t\"Update CLA requirement\",\n\t\tdesc,\n\t\tdao.NewSimpleExecutor(0, cur, cb, helplink.Realm(\"gno.land/r/sys/cla\").Home()),\n\t)\n}\n\nfunc setRequiredHash(newHash string) {\n\tprevHash := requiredHash\n\trequiredHash = newHash\n\tsignatures = addrset.Set{} // reset all signatures\n\n\tchain.Emit(\n\t\tRequiredHashChangedEvent,\n\t\t\"from\", prevHash,\n\t\t\"to\", newHash,\n\t)\n}\n"},{"name":"cla.gno","body":"package cla\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/moul/addrset/v0\"\n)\n\nconst SignedEvent = \"CLASigned\"\n\nvar (\n\trequiredHash string // SHA256 hash of the CLA document; empty = enforcement disabled\n\tclaURL       string // URL where the CLA document can be found\n\tsignatures   addrset.Set\n)\n\n// Sign records a CLA signature for the caller.\n// The hash must match the current required hash.\nfunc Sign(cur realm, hash string) {\n\tif hash != requiredHash {\n\t\tpanic(\"hash does not match required CLA hash\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\tsignatures.Add(caller)\n\n\tchain.Emit(\n\t\tSignedEvent,\n\t\t\"signer\", caller.String(),\n\t\t\"hash\", hash,\n\t)\n}\n\n// HasValidSignature checks if an address has signed the current required CLA.\n// Returns true if CLA enforcement is disabled (requiredHash == \"\"),\n// or if the address has signed.\nfunc HasValidSignature(addr address) bool {\n\tif requiredHash == \"\" {\n\t\treturn true\n\t}\n\treturn signatures.Has(addr)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/cla\"\ngno = \"0.9\"\n"},{"name":"render.gno","body":"package cla\n\nimport (\n\t\"gno.land/p/moul/helplink/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc Render(path string) string {\n\tout := md.H1(\"Contributor License Agreement (CLA)\")\n\n\tout += md.Paragraph(\"A Contributor License Agreement (CLA) must be signed before deploying packages.\")\n\tout += md.Paragraph(\n\t\t\"The Agreement governs Contributions uploaded, published, or made available \" +\n\t\t\t\"for execution on the Gno.land blockchain network, and the \" +\n\t\t\t\"related software and repositories used to publish such Contributions.\",\n\t)\n\n\tif requiredHash == \"\" {\n\t\tout += md.HorizontalRule()\n\t\tout += md.H2(\"Status\")\n\t\tout += md.Paragraph(md.Bold(\"CLA enforcement is currently DISABLED.\"))\n\t\tout += md.Paragraph(\"All package deployments are allowed.\")\n\t\treturn out\n\t}\n\n\tout += md.HorizontalRule()\n\tout += md.H2(\"Status\")\n\tout += md.Paragraph(md.Bold(\"CLA enforcement is ENABLED\"))\n\n\tif claURL != \"\" {\n\t\tout += md.Paragraph(\"You can read the full agreement here: \" + md.Link(claURL, claURL))\n\t}\n\n\ttable := mdtable.Table{Headers: []string{\"\", \"\"}}\n\ttable.Append([]string{md.Bold(\"Required Hash\"), md.InlineCode(requiredHash)})\n\ttable.Append([]string{md.Bold(\"Signers\"), ufmt.Sprintf(\"%d contributor(s)\", signatures.Size())})\n\tout += table.String()\n\n\tout += md.H3(\"Actions\")\n\tout += md.Paragraph(helplink.Func(\"Sign CLA\", \"Sign\", \"hash\", requiredHash))\n\treturn out\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"validators","path":"gno.land/p/sys/validators/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/sys/validators/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"types.gno","body":"package validators\n\nimport (\n\t\"errors\"\n)\n\n// ValsetProtocol defines the validator set protocol (PoA / PoS / PoC / ?)\ntype ValsetProtocol interface {\n\t// AddValidator adds a new validator to the validator set.\n\t// If the validator is already present, the method should error out\n\t//\n\t// TODO: This API is not ideal -- the address should be derived from\n\t// the public key, and not be passed in as such, but currently Gno\n\t// does not support crypto address derivation\n\tAddValidator(address_XXX address, pubKey string, power uint64) (Validator, error)\n\n\t// RemoveValidator removes the given validator from the set.\n\t// If the validator is not present in the set, the method should error out\n\tRemoveValidator(address_XXX address) (Validator, error)\n\n\t// IsValidator returns a flag indicating if the given\n\t// bech32 address is part of the validator set\n\tIsValidator(address_XXX address) bool\n\n\t// GetValidator returns the validator using the given address\n\tGetValidator(address_XXX address) (Validator, error)\n\n\t// GetValidators returns the currently active validator set\n\tGetValidators() []Validator\n}\n\n// Validator represents a single chain validator\ntype Validator struct {\n\tAddress     address // bech32 address\n\tPubKey      string  // bech32 representation of the public key\n\tVotingPower uint64\n}\n\nconst (\n\tValidatorAddedEvent   = \"ValidatorAdded\"   // emitted when a validator was added to the set\n\tValidatorRemovedEvent = \"ValidatorRemoved\" // emitted when a validator was removed from the set\n)\n\nvar (\n\t// ErrValidatorExists is returned when the validator is already in the set\n\tErrValidatorExists = errors.New(\"validator already exists\")\n\n\t// ErrValidatorMissing is returned when the validator is not in the set\n\tErrValidatorMissing = errors.New(\"validator doesn't exist\")\n)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"params","path":"gno.land/r/sys/params","files":[{"name":"delegate.gno","body":"package params\n\n// Delegation: letting a realm other than GovDAO manage one specific parameter.\n//\n// This realm holds a capability nothing else can: the `sys/params` stdlib\n// refuses every caller except `gno.land/r/sys/params`, checked in the VM by\n// package path, and the same gate covers the getters. So every parameter write\n// on the chain physically originates here, and \"delegating a parameter\" can only\n// mean adding a path in this file that authorizes someone other than a GovDAO\n// vote.\n//\n// Two shapes are deliberately NOT used.\n//\n// Not a registry of key -\u003e realm. This realm can never be redeployed\n// (AddPackage refuses an occupied path), and the stdlib gate names this exact\n// path, so making a NEW parameter delegatable already requires editing this\n// file, which means a chain relaunch. A registry's runtime generality would\n// therefore never be exercised: the only freedom that matters is \"which realm,\n// or none\" for keys already blessed in source. A named slot says exactly that\n// and nothing more. It also removes a whole class of mistake — there is no\n// key string to mis-compose, no container to accidentally expose, and no way for\n// a proposal to name a key the author never considered. A shape-based allowlist\n// like \"\u003cmodule\u003e:p:\u003cname\u003e\" would have admitted bank:p:restricted_denoms and\n// auth:p:unrestricted_addrs, which is not a delegation anyone asked for.\n//\n// Not a capability object. Returning something the delegate holds would make\n// authority survive revocation, because the check would have happened at\n// construction. The authority is re-checked on every crossing call instead, so\n// clearing the slot takes effect immediately.\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/r/gov/dao\"\n)\n\n// Event names. PascalCase with a named const is the house style across r/sys\n// and r/gov; the bare lowercase \"set\" elsewhere in this realm predates it.\nconst (\n\tDelegateSetEvent     = \"ParamDelegateSet\"\n\tDelegateClearedEvent = \"ParamDelegateCleared\"\n\tDelegateWriteEvent   = \"ParamDelegateWrite\"\n)\n\n// assertDelegate authorizes a caller as the holder of a delegated capability.\n//\n// want is the authorized package path, or \"\" when nothing is delegated.\n//\n// The empty check comes FIRST and is load-bearing, not defensive. A direct call\n// from a user account has an empty previous package path — that is exactly what\n// IsUserCall tests — so comparing against an unset slot would compare \"\" to \"\"\n// and admit every user on the chain. r/gov/dao's own allowlist has the\n// mirror-image bug (it returns true for everyone when the list is empty), kept\n// there deliberately for genesis bootstrap. Nothing here needs that, so empty\n// denies.\n//\n// Matching is exact, never a prefix. A sub-realm identity minted by\n// cur.Sub(subpath) presents the synthesized path \"host#subpath\", so a delegate\n// may legitimately be a single DAO hosted by a multi-tenant realm — for\n// instance \"gno.land/r/nt/commondao/v0#dao/42\". An anchored-prefix match on the\n// host would hand the capability to every DAO that realm hosts, and a bare\n// prefix match would additionally match sibling packages. \"#\" cannot occur in a\n// real package path, so exact matching on the full string is unambiguous.\n//\n// Takes rlm in the non-crossing dispatch position, matching assertValsetCaller\n// so the two gates stay one shape.\n// subject names what is being written, so the refusal stays specific to the\n// capability rather than generic to the mechanism. params_valset_auth.txtar\n// pins valset's exact wording as a regression test for PR #5485.\nfunc assertDelegate(_ int, rlm realm, want, subject string) {\n\tif want == \"\" {\n\t\tpanic(\"unauthorized: no delegate is configured for \" + subject)\n\t}\n\t// The helper trusts its rlm input, so a future caller threading a stashed\n\t// or sibling-frame realm value would otherwise bypass the path check below.\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tif rlm.Previous().PkgPath() != want {\n\t\tpanic(\"unauthorized: only \" + want + \" may write \" + subject)\n\t}\n}\n\n// assertDelegatePath rejects package paths that must never be stored in a\n// delegation slot, at the point a proposal is built rather than when it\n// executes.\n//\n// Rejecting the empty string is the same fail-open guard as in assertDelegate,\n// enforced on the way in as well so an accidental clear-by-empty-set cannot be\n// mistaken for a grant. Requiring the gno.land/r/ prefix excludes user accounts\n// (empty path), pure packages, and ephemeral `maketx run` realms — the last of\n// which matters because a run realm's path is non-empty, so a check based on\n// \"is this code\" would let one through.\nfunc assertDelegatePath(pkgpath string) {\n\tif pkgpath == \"\" {\n\t\tpanic(\"invalid delegate: empty package path\")\n\t}\n\tif !isRealmPath(pkgpath) {\n\t\tpanic(\"invalid delegate: must be a gno.land/r/ realm path, got \" + pkgpath)\n\t}\n\t// Reject anything no caller could ever present, so a delegation cannot be\n\t// silently dead: GovDAO would believe it granted the capability while the\n\t// delegate is refused on every call. The sibling UpdateImpl rejects\n\t// whitespace-padded entries for the same reason.\n\tfor i := 0; i \u003c len(pkgpath); i++ {\n\t\tc := pkgpath[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '/' || c == '.' || c == '-' || c == '_' || c == '#':\n\t\tdefault:\n\t\t\tpanic(\"invalid delegate: \" + pkgpath +\n\t\t\t\t\" contains a character no package path or sub-identity can hold\")\n\t\t}\n\t}\n\tif n := countByte(pkgpath, '#'); n \u003e 1 {\n\t\tpanic(\"invalid delegate: more than one '#' in \" + pkgpath)\n\t}\n}\n\nfunc countByte(s string, b byte) int {\n\tn := 0\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif s[i] == b {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\nconst realmPathPrefix = \"gno.land/r/\"\n\nfunc isRealmPath(pkgpath string) bool {\n\treturn len(pkgpath) \u003e len(realmPathPrefix) \u0026\u0026\n\t\tpkgpath[:len(realmPathPrefix)] == realmPathPrefix\n}\n\n// newDelegateProposal builds the GovDAO proposal that applies a delegation\n// change. apply mutates the slot and is run only when the vote passes.\n//\n// event is emitted from inside the executor, so an observer sees the delegation\n// change exactly when it takes effect rather than when it was proposed. from is\n// the previous holder (\"\" when none), included so a re-delegation is auditable\n// from the single event without reading prior state.\n// apply returns the holder it replaced, read at EXECUTION time. Capturing that\n// at creation would misreport a re-delegation: two set-proposals created while\n// the slot is empty, then executed in sequence, would both emit from=\"\" even\n// though the second replaced the first.\nfunc newDelegateProposal(cur realm, event, key, to, title, desc string, apply func() string) dao.ProposalRequest {\n\tcallback := func(cur realm) error {\n\t\tfrom := apply()\n\t\tchain.Emit(event, \"key\", key, \"from\", from, \"to\", to)\n\t\treturn nil\n\t}\n\treturn dao.NewProposalRequest(title, desc,\n\t\tdao.NewSimpleExecutor(0, cur, callback, \"\"))\n}\n"},{"name":"fee_collector.gno","body":"package params\n\nimport (\n\t\"gno.land/r/gov/dao\"\n)\n\nfunc NewSetFeeCollectorRequest(cur realm, addr address) dao.ProposalRequest {\n\treturn NewSysParamStringPropRequest(cur,\n\t\t\"auth\", \"p\", \"fee_collector\",\n\t\taddr.String(),\n\t)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/params\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"halt.gno","body":"package params\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\tprms \"sys/params\"\n\n\t\"gno.land/r/gov/dao\"\n)\n\nconst (\n\tnodeModulePrefix  = \"node\"\n\thaltHeightKey     = \"halt_height\"\n\thaltMinVersionKey = \"halt_min_version\"\n)\n\n// NewSetHaltRequest creates a GovDAO proposal to halt all chain nodes at the given block height.\n// Once approved and executed, nodes will gracefully stop after committing the specified block,\n// enabling coordinated chain upgrades.\n//\n// minVersion, if non-empty, sets the minimum binary version required to resume after the halt.\n// Nodes will refuse to restart unless their version satisfies the minimum requirement,\n// preventing old binaries from accidentally resuming a chain halted for an upgrade.\n// Example: minVersion=\"v1.3.0\" prevents a v1.2.0 binary from resuming.\n//\n// minVersion must be a release tag the node can parse: vMAJOR.MINOR.PATCH, or\n// betanet's retired chain/gnolandMAJOR.MINOR. It is NOT the chain's launch tag —\n// naming \"chain/mainnet\" here parses as nothing, so the comparison degrades to\n// byte equality and refuses the upgraded binary alongside the stale ones, leaving\n// the chain unable to restart. This function does not check the shape; the release\n// tooling does. See RELEASING.md and gno.land/cmd/gnoland/UPGRADES.md, and prefer\n// misc/govdao-scripts/set-halt.sh over writing the call by hand.\n//\n// Use height=0 to cancel a previously scheduled halt.\nfunc NewSetHaltRequest(cur realm, height int64, minVersion string) dao.ProposalRequest {\n\tcallback := func(cur realm) error {\n\t\tprms.SetSysParamInt64(nodeModulePrefix, \"p\", haltHeightKey, height)\n\t\tprms.SetSysParamString(nodeModulePrefix, \"p\", haltMinVersionKey, minVersion)\n\t\tchain.Emit(\"set_halt\",\n\t\t\t\"height\", strconv.FormatInt(height, 10),\n\t\t\t\"min_version\", minVersion,\n\t\t)\n\t\treturn nil\n\t}\n\n\tvar desc string\n\tif height == 0 {\n\t\tdesc = \"Cancel the scheduled chain halt and clear the minimum version requirement.\"\n\t} else {\n\t\tdesc = \"Halt the chain at block \" + strconv.FormatInt(height, 10) + \".\"\n\t\tif minVersion != \"\" {\n\t\t\tdesc += \" Requires binary version \u003e= \" + minVersion + \" to resume.\"\n\t\t}\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, callback, \"\")\n\treturn dao.NewProposalRequest(\"Set node halt height\", desc, e)\n}\n"},{"name":"params.gno","body":"// Package params provides functions for creating parameter executors that\n// interface with the Params Keeper.\n//\n// This package enables setting various parameter types (such as strings,\n// integers, booleans, and byte slices) through the GovDAO proposal mechanism.\n// Each function returns an executor that, when called, sets the specified\n// parameter in the Params Keeper.\n//\n// The executors are designed to be used within governance proposals to modify\n// parameters dynamically. The integration with the GovDAO allows for parameter\n// changes to be proposed and executed in a controlled manner, ensuring that\n// modifications are subject to governance processes.\n//\n// Example usage:\n//\n//\t// This executor can be used in a governance proposal to set the parameter.\n//\tpr := params.NewSysParamStringPropExecutor(\"bank\", \"p\", \"restricted_denoms\")\npackage params\n\nimport (\n\t\"chain\"\n\tprms \"sys/params\"\n\n\t\"gno.land/r/gov/dao\"\n)\n\n// this is only used for emitting events.\nfunc syskey(module, submodule, name string) string {\n\treturn module + \":\" + submodule + \":\" + name\n}\n\n// assertNotValsetKey rejects governance proposals that target the\n// node:valset:* key family. Those keys are reserved for the realm-side\n// gate in r/sys/params/valset.gno (SetValsetProposal) which checks\n// the immediate caller is gno.land/r/sys/validators/v0. Without this\n// guard, a generic NewSysParam*PropRequest(\"node\",\"valset\",...) would\n// let any GovDAO supermajority bypass the v0 authorization and write\n// validator-set state directly.\nfunc assertNotValsetKey(module, submodule string) {\n\tif module == \"node\" \u0026\u0026 submodule == \"valset\" {\n\t\tpanic(\"node:valset:* is reserved for r/sys/validators/v0; use it instead of the generic factory\")\n\t}\n}\n\n// assertNotRunSubmittersKey rejects generic proposals that target\n// vm:p:run_submitters. Same shape as assertNotValsetKey above, and the same\n// reason: the key has a realm-side gate the generic factory would walk past.\n//\n// An empty run_submitters means the MsgRun gate is OFF. So a non-empty list is\n// the chain deciding who may run code, and a list that names nobody able to\n// create a GovDAO proposal cannot be changed back -- creating a proposal needs\n// MsgRun, because a ProposalRequest carries an Executor that MsgCall cannot\n// build from string arguments. The dedicated ProposeSetRunSubmitters in\n// run_submitters.gno refuses that list at proposal-creation time, where a human\n// can still act on the refusal.\n//\n// Reserving the key rather than adding the check to all nine factories keeps\n// the number of ways to write this parameter at one.\nfunc assertNotRunSubmittersKey(module, submodule, name string) {\n\tif module == \"vm\" \u0026\u0026 submodule == \"p\" \u0026\u0026 name == runSubmittersKey {\n\t\tpanic(runSubmittersKey + \" is reserved for ProposeSetRunSubmitters in this realm; \" +\n\t\t\t\"use it instead of the generic factory\")\n\t}\n}\n\nfunc NewSysParamStringPropRequest(cur realm, module, submodule, name, value string) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.SetSysParamString(module, submodule, name, value) },\n\t\t\"\",\n\t)\n}\n\nfunc NewSysParamInt64PropRequest(cur realm, module, submodule, name string, value int64) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.SetSysParamInt64(module, submodule, name, value) },\n\t\t\"\",\n\t)\n}\n\nfunc NewSysParamUint64PropRequest(cur realm, module, submodule, name string, value uint64) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.SetSysParamUint64(module, submodule, name, value) },\n\t\t\"\",\n\t)\n}\n\nfunc NewSysParamBoolPropRequest(cur realm, module, submodule, name string, value bool) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.SetSysParamBool(module, submodule, name, value) },\n\t\t\"\",\n\t)\n}\n\nfunc NewSysParamBytesPropRequest(cur realm, module, submodule, name string, value []byte) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.SetSysParamBytes(module, submodule, name, value) },\n\t\t\"\",\n\t)\n}\n\nfunc NewSysParamStringsPropRequest(cur realm, module, submodule, name string, value []string) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.SetSysParamStrings(module, submodule, name, value) },\n\t\t\"\",\n\t)\n}\n\nfunc NewSysParamStringsPropRequestWithTitle(cur realm, module, submodule, name, title string, value []string) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.SetSysParamStrings(module, submodule, name, value) },\n\t\ttitle,\n\t)\n}\nfunc NewSysParamStringsPropRequestAddWithTitle(cur realm, module, submodule, name, title string, value []string) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.UpdateSysParamStrings(module, submodule, name, value, true) },\n\t\ttitle,\n\t)\n}\nfunc NewSysParamStringsPropRequestRemoveWithTitle(cur realm, module, submodule, name, title string, value []string) dao.ProposalRequest {\n\treturn newPropRequest(cur, module, submodule, name,\n\t\tfunc() { prms.UpdateSysParamStrings(module, submodule, name, value, false) },\n\t\ttitle,\n\t)\n}\nfunc newPropRequest(cur realm, module, submodule, name string, fn func(), title string) dao.ProposalRequest {\n\t// The reserved-key checks live here rather than in each factory. Every\n\t// generic factory returns through this one function, so a factory added\n\t// later cannot forget them. The dedicated setters for those keys build their\n\t// own request and never come here, which is what makes them the exception.\n\tassertNotValsetKey(module, submodule)\n\tassertNotRunSubmittersKey(module, submodule, name)\n\n\tkey := syskey(module, submodule, name)\n\tcallback := func(cur realm) error {\n\t\tfn()\n\t\tchain.Emit(\"set\", \"key\", key) // TODO document, make const, make consistent. 'k'??\n\t\treturn nil\n\t}\n\n\tif title == \"\" {\n\t\ttitle = \"Set new sys/params key\"\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, callback, \"\")\n\n\treturn dao.NewProposalRequest(title, \"This proposal wants to add a new key to sys/params: \"+key, e)\n}\n"},{"name":"render.gno","body":"package params\n\nimport (\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Render shows who, other than GovDAO, may currently write a chain parameter.\n//\n// This realm had no Render, so the only way to see a delegation was to know it\n// existed and query for it by name. That is the wrong shape for state that\n// grants a capability: someone auditing the chain should be able to see, in one\n// place, whether any parameter is delegated and to whom.\n//\n// Values are rendered without escaping, which is safe here because none of them\n// is free-form. A delegate path has passed assertDelegatePath, which permits\n// only lowercase letters, digits and a few separators; the addresses come from\n// the parameter itself, which the chain validates as bech32; and the valset\n// realm is a compile-time constant.\nfunc Render(path string) string {\n\tout := md.H1(\"Chain parameter delegation\")\n\tout += md.Paragraph(\n\t\t\"Chain parameters are written by GovDAO proposal. A parameter may also \" +\n\t\t\t\"be delegated to one other realm, which can then manage it without a \" +\n\t\t\t\"vote. GovDAO keeps full control of every parameter and can withdraw \" +\n\t\t\t\"a delegation at any time.\",\n\t)\n\n\tout += md.HorizontalRule()\n\tout += md.H2(\"run_submitters\")\n\tout += md.Paragraph(\"Addresses allowed to send MsgRun, which runs code the sender supplies.\")\n\n\tmgr := RunSubmittersManager()\n\ttable := mdtable.Table{Headers: []string{\"\", \"\"}}\n\tif mgr == \"\" {\n\t\ttable.Append([]string{md.Bold(\"Delegated to\"), \"nobody, only GovDAO may change it\"})\n\t} else {\n\t\ttable.Append([]string{md.Bold(\"Delegated to\"), md.InlineCode(mgr)})\n\t}\n\n\tlisted := GetRunSubmitters()\n\ttable.Append([]string{md.Bold(\"Addresses allowed\"), ufmt.Sprintf(\"%d\", len(listed))})\n\tout += table.String()\n\n\tif mgr != \"\" {\n\t\t// Which entries the delegate may remove again. Anything it did not add\n\t\t// is GovDAO's to remove, including whatever the chain started with.\n\t\tgranted := 0\n\t\tfor _, a := range listed {\n\t\t\tif RunSubmittersGrantedBy(address(a)) {\n\t\t\t\tgranted++\n\t\t\t}\n\t\t}\n\t\tout += md.Paragraph(ufmt.Sprintf(\n\t\t\t\"%d of those were added by the delegate, and are the only ones it may remove.\",\n\t\t\tgranted))\n\t}\n\n\tif len(listed) \u003e 0 {\n\t\titems := make([]string, 0, len(listed))\n\t\tfor _, a := range listed {\n\t\t\titems = append(items, md.InlineCode(a))\n\t\t}\n\t\tout += md.BulletList(items)\n\t}\n\n\tout += md.HorizontalRule()\n\tout += md.H2(\"node:valset\")\n\tout += md.Paragraph(\n\t\t\"Validator set parameters are written by one realm, fixed in this \" +\n\t\t\t\"realm's source. Unlike a delegation this cannot be repointed by a \" +\n\t\t\t\"vote, and GovDAO cannot write these keys itself.\",\n\t)\n\tvtable := mdtable.Table{Headers: []string{\"\", \"\"}}\n\tvtable.Append([]string{md.Bold(\"Writable only by\"), md.InlineCode(valsetAuthorizedRealm)})\n\tout += vtable.String()\n\n\treturn out\n}\n"},{"name":"run_submitters.gno","body":"package params\n\n// Delegated management of vm:p:run_submitters, the allowlist of addresses\n// permitted to send MsgRun.\n//\n// See delegate.gno for why this is a named slot rather than a registry.\n//\n// What the delegate can and cannot do, and why the asymmetry is this way round:\n//\n//   - It may ADD addresses. This is the routine work the delegation exists for.\n//   - It may REMOVE only addresses it added itself, and never the last one.\n//     De-listing its own mistake is a core part of managing an allowlist, so\n//     add-only would be a strange capability to hand out. Two bounds keep that\n//     safe. Grant-scoping stops it removing an address that predates the\n//     delegation. The non-empty floor in RemoveRunSubmitters stops it reaching\n//     zero by any route — an empty list means the gate is OFF and anyone may\n//     MsgRun, so emptying it would let the delegate revoke the entire\n//     restriction GovDAO voted for, which is the one thing this capability must\n//     not be able to do.\n//   - GovDAO retains everything, through ProposeSetRunSubmitters below -- the\n//     generic factories no longer accept this key. That is the bounded reset:\n//     one proposal returns the key to a known-good list regardless of what the\n//     delegate did, and the proposal shows voters the exact resulting list.\n//\n// A cost to state plainly rather than bury: this key is read by the ante handler\n// on EVERY transaction, before the per-tx gas meter exists, so its length is an\n// unmetered per-transaction constant for the whole chain. The delegate therefore\n// holds a knob on that constant, bounded only by maxAddressListLen in\n// gno.land/pkg/sdk/vm/params.go. That bound is enforced on this path for free:\n// UpdateSysParamStrings re-sets the whole list, which re-enters WillSetParam and\n// Params.Validate, so both the cap and bech32 validation apply to a delegate's\n// additions. A key that is not read on the ante path would be a cheaper first\n// delegation; this one is the one that was asked for.\n\nimport (\n\t\"chain\"\n\tprms \"sys/params\"\n\n\t\"gno.land/p/moul/addrset/v0\"\n\n\t\"gno.land/r/gov/dao\"\n)\n\nconst (\n\tvmModulePrefix    = \"vm\"\n\tvmParamsSubmodule = \"p\"\n\n\trunSubmittersKey = \"run_submitters\"\n)\n\n// runSubmittersMgr is the package path authorized to manage run_submitters.\n// Empty means the capability is not delegated, and empty must deny — see\n// assertDelegate.\nvar runSubmittersMgr string\n\n// runSubmittersGrants records which addresses the current delegate added, so\n// removal can be scoped to its own grants.\n//\n// The parameter is the source of truth and this is a side table, so the two can\n// disagree — genesis, `gnogenesis params set`, or any future direct keeper write\n// produces entries with no grant recorded. That direction is safe: an unrecorded\n// address is simply not removable by the delegate, which is the conservative\n// answer. Cleared whenever the delegation changes hands, so a new delegate never\n// inherits authority over its predecessor's grants.\nvar runSubmittersGrants = addrset.Set{}\n\n// RunSubmittersManager returns the package path currently authorized to manage\n// run_submitters, or \"\" when the capability is not delegated.\nfunc RunSubmittersManager() string {\n\treturn runSubmittersMgr\n}\n\n// RunSubmittersGrantedBy reports whether the current delegate added addr, i.e.\n// whether it may remove it.\n//\n// Exposed so a delegate can check before acting. A delegate that discovers a\n// refusal by panicking mid-proposal-execution is in a bad place: the panic\n// aborts the transaction, and for a DAO whose proposal has already passed, every\n// retry aborts the same way.\nfunc RunSubmittersGrantedBy(addr address) bool {\n\treturn runSubmittersGrants.Has(addr)\n}\n\n// IsRunSubmittersDelegate reports whether pkgpath currently holds the\n// capability. Pure predicate, for a caller that wants to fail cleanly rather\n// than be panicked at.\nfunc IsRunSubmittersDelegate(pkgpath string) bool {\n\treturn pkgpath != \"\" \u0026\u0026 pkgpath == runSubmittersMgr\n}\n\n// ProposeSetRunSubmittersManager creates a GovDAO proposal handing management of\n// run_submitters to pkgpath.\n//\n// pkgpath may be a sub-realm identity such as\n// \"gno.land/r/nt/commondao/v0#dao/42\", which is how a single DAO hosted by a\n// multi-tenant realm is named. Matching is exact, so naming the bare host would\n// authorize the host itself and none of its DAOs.\nfunc ProposeSetRunSubmittersManager(cur realm, pkgpath string) dao.ProposalRequest {\n\tassertDelegatePath(pkgpath)\n\tif pkgpath == runSubmittersMgr {\n\t\tpanic(\"no-op proposal rejected: \" + pkgpath + \" already manages \" + runSubmittersKey)\n\t}\n\n\t// desc uses the manager as of proposal creation, which is the honest thing\n\t// to show a voter. The EVENT reads it again inside the executor, because two\n\t// proposals created while the slot is empty and executed in sequence would\n\t// otherwise both report from=\"\" while the second actually replaced the first.\n\tfrom := runSubmittersMgr\n\tdesc := \"Authorize \" + pkgpath + \" to add addresses to the \" + runSubmittersKey +\n\t\t\" allowlist, which gates who may send MsgRun. It may remove only \" +\n\t\t\"addresses it added itself. GovDAO retains full control, including \" +\n\t\t\"replacing the whole list.\"\n\tif from != \"\" {\n\t\tdesc += \" This replaces the current manager, \" + from +\n\t\t\t\", and discards the record of which addresses it granted.\"\n\t}\n\n\treturn newDelegateProposal(cur, DelegateSetEvent, runSubmittersKey, pkgpath,\n\t\t\"Delegate \"+runSubmittersKey+\" management\", desc,\n\t\tfunc() string {\n\t\t\tprev := runSubmittersMgr\n\t\t\trunSubmittersMgr = pkgpath\n\t\t\t// A new holder must not inherit removal authority over addresses\n\t\t\t// the previous one granted.\n\t\t\trunSubmittersGrants = addrset.Set{}\n\t\t\treturn prev\n\t\t})\n}\n\n// ProposeClearRunSubmittersManager creates a GovDAO proposal revoking the\n// delegation.\n//\n// Revocation is immediate on execution because the slot is consulted on every\n// call. It deliberately does NOT remove addresses the delegate added: sweeping\n// them would make the executed effect invisible at vote time, and would silently\n// remove nothing whenever the grant record had drifted. Use the existing\n// whole-list setter to reset the list to a reviewed value.\nfunc ProposeClearRunSubmittersManager(cur realm) dao.ProposalRequest {\n\tif runSubmittersMgr == \"\" {\n\t\tpanic(\"no-op proposal rejected: \" + runSubmittersKey + \" is not delegated\")\n\t}\n\n\tfrom := runSubmittersMgr\n\treturn newDelegateProposal(cur, DelegateClearedEvent, runSubmittersKey, \"\",\n\t\t\"Revoke \"+runSubmittersKey+\" management\",\n\t\t\"Revoke \"+from+\"'s authority to manage the \"+runSubmittersKey+\n\t\t\t\" allowlist. Addresses it already added REMAIN on the list; reset the \"+\n\t\t\t\"list explicitly if that is not wanted.\",\n\t\tfunc() string {\n\t\t\tprev := runSubmittersMgr\n\t\t\trunSubmittersMgr = \"\"\n\t\t\trunSubmittersGrants = addrset.Set{}\n\t\t\treturn prev\n\t\t})\n}\n\n// AddRunSubmitters adds addresses to the run_submitters allowlist.\n//\n// Callable only by the delegated manager. Addresses already present are a no-op\n// (UpdateSysParamStrings dedupes), and the chain still validates every entry and\n// enforces the list-length cap, because the update re-sets the whole list.\nfunc AddRunSubmitters(cur realm, addrs []string) {\n\tassertDelegate(0, cur, runSubmittersMgr, \"the \"+runSubmittersKey+\" allowlist\")\n\tif len(addrs) == 0 {\n\t\treturn\n\t}\n\n\t// The delegate may curate a list that is already in force. It may not put\n\t// one into force.\n\t//\n\t// An empty run_submitters means the allowlist is OFF and anyone may MsgRun.\n\t// So the first add is not curation: it switches a chain-wide restriction on\n\t// and picks who it admits. A delegate adding one address to an empty list\n\t// leaves that address the only one on the chain that may run code.\n\t//\n\t// Refused rather than discouraged because it is unrepairable. Creating a\n\t// GovDAO proposal needs MsgRun -- a ProposalRequest carries an Executor,\n\t// which MsgCall cannot build from string arguments -- so once the gate is\n\t// armed against the members they cannot propose the vote that would undo\n\t// it, and the floor in RemoveRunSubmitters stops the delegate undoing it\n\t// either.\n\tif len(GetRunSubmitters()) == 0 {\n\t\tpanic(\"refusing to arm the \" + runSubmittersKey +\n\t\t\t\" allowlist: it is empty, so the gate is off and anyone may MsgRun. \" +\n\t\t\t\"Turning it on is a GovDAO vote, not a delegated edit\")\n\t}\n\n\t// Record a grant only for an address this call actually ADDED.\n\t//\n\t// UpdateSysParamStrings dedupes on add, so passing an address already on the\n\t// list leaves the parameter unchanged. Recording a grant for it anyway would\n\t// let the delegate launder authority over entries it never granted: read the\n\t// list, re-add all of it (a no-op on the parameter, but every address now\n\t// recorded as its own), then remove all of it -- including whatever predated\n\t// the delegation. The floor in RemoveRunSubmitters would refuse the last of\n\t// those removals, but only the last: everything up to it would still go\n\t// through, leaving the delegate holding the only listed address and so the\n\t// sole authority over who may MsgRun.\n\t//\n\t// So the grant record has to follow the parameter, not the argument.\n\tpresent := make(map[string]bool)\n\tfor _, a := range GetRunSubmitters() {\n\t\tpresent[a] = true\n\t}\n\n\tprms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, true)\n\tfor _, a := range addrs {\n\t\tif !present[a] {\n\t\t\trunSubmittersGrants.Add(address(a))\n\t\t}\n\t}\n\tchain.Emit(DelegateWriteEvent,\n\t\t\"key\", runSubmittersKey, \"realm\", runSubmittersMgr, \"op\", \"add\")\n}\n\n// RemoveRunSubmitters removes addresses from the run_submitters allowlist.\n//\n// Callable only by the delegated manager, and only for addresses that manager\n// added. Refusing rather than silently skipping is deliberate: a partial removal\n// that reported success would leave the caller believing an address was\n// de-listed when it was not.\nfunc RemoveRunSubmitters(cur realm, addrs []string) {\n\tassertDelegate(0, cur, runSubmittersMgr, \"the \"+runSubmittersKey+\" allowlist\")\n\tif len(addrs) == 0 {\n\t\treturn\n\t}\n\tfor _, a := range addrs {\n\t\tif !runSubmittersGrants.Has(address(a)) {\n\t\t\tpanic(\"cannot remove \" + a + \": not granted by \" + runSubmittersMgr +\n\t\t\t\t\", only GovDAO may remove it\")\n\t\t}\n\t}\n\n\t// The delegate may not empty the list, whatever it granted.\n\t//\n\t// An empty run_submitters means the gate is OFF -- anyone on the chain may\n\t// send MsgRun. So emptying it is not a smaller version of removing one\n\t// address, it is the opposite of what the delegation is for: it would let a\n\t// delegate authorized to curate a list unilaterally revoke the whole\n\t// restriction GovDAO voted for.\n\t//\n\t// Grant-scoping alone does not prevent this. It holds only while at least\n\t// one entry the delegate did not grant survives, and GovDAO replacing the\n\t// list wholesale can remove its own entries without touching the grant\n\t// record. A floor makes the invariant structural instead of emergent.\n\t//\n\t// Counted against the parameter, not the argument: the caller may name\n\t// addresses that are not listed, or name one twice, and neither shrinks the\n\t// list. Only GovDAO can go to zero, through the whole-list setter, where the\n\t// resulting list is on the ballot.\n\tremoving := make(map[string]bool, len(addrs))\n\tfor _, a := range addrs {\n\t\tremoving[a] = true\n\t}\n\tremaining := 0\n\tfor _, a := range GetRunSubmitters() {\n\t\tif !removing[a] {\n\t\t\tremaining++\n\t\t}\n\t}\n\tif remaining == 0 {\n\t\tpanic(\"refusing to empty the \" + runSubmittersKey +\n\t\t\t\" allowlist: an empty list disables the gate entirely, so only \" +\n\t\t\t\"GovDAO may do it\")\n\t}\n\n\tprms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, false)\n\tfor _, a := range addrs {\n\t\trunSubmittersGrants.Remove(address(a))\n\t}\n\tchain.Emit(DelegateWriteEvent,\n\t\t\"key\", runSubmittersKey, \"realm\", runSubmittersMgr, \"op\", \"remove\")\n}\n\n// GetRunSubmitters returns the current allowlist.\nfunc GetRunSubmitters() []string {\n\tvals, _ := prms.GetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey)\n\treturn vals\n}\n\n// ProposeSetRunSubmitters creates a GovDAO proposal replacing the whole\n// run_submitters allowlist.\n//\n// This is the only way to set the list by vote: the generic factories refuse\n// the key (see assertNotRunSubmittersKey), so every whole-list write comes\n// through here and carries the rule below.\n//\n// The proposer must be on the list they propose.\n//\n// An empty run_submitters means the gate is off and anyone may MsgRun. A\n// non-empty one therefore decides who may run code at all -- and a list naming\n// nobody who can create a GovDAO proposal cannot be undone, because creating a\n// proposal needs MsgRun: a ProposalRequest carries an Executor, and MsgCall\n// cannot build one from string arguments. The vote would end governance.\n//\n// Requiring the proposer's own address is a cheap way to prove the list is\n// usable rather than merely plausible. GovDAO refuses a proposal from a\n// non-member (PreCreateProposal, \"only members can create new proposals\"), so\n// if this proposal exists at all its author is a member -- and they just signed\n// the transaction that created it, so the address demonstrably holds a key. A\n// list that merely NAMES a member proves neither: the address may belong to\n// nobody, since any member can enroll an arbitrary address.\n//\n// Checked here, at proposal creation, rather than inside the executor. Nothing\n// in r/gov/dao recovers from an executor panic, so a check that fires at\n// execution turns a passed proposal into one that can never be executed. Here\n// the refusal reaches a person who can still fix the list and propose again.\n//\n// This is a floor, not an invariant. The proposer may resign from GovDAO later,\n// and the list is not re-checked when they do. It rules out arriving at a dead\n// list in one vote; it cannot rule out drifting into one.\nfunc ProposeSetRunSubmitters(cur realm, addrs []string) dao.ProposalRequest {\n\t// IsCurrent before Previous, as AGENTS.md requires and assertDelegate does.\n\t//\n\t// Belt and braces here rather than load-bearing: the compiler already\n\t// refuses anything but `cur` or `cross(rlm)` as the first argument to a\n\t// crossing function, so this cur is live by construction and the check\n\t// cannot fire. It earns its place if this ever becomes a helper taking an\n\t// ordinary realm parameter, which is the shape assertDelegate has and where\n\t// a stashed value really can be threaded in.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"unauthorized: cur is not the caller's live realm\")\n\t}\n\tproposer := cur.Previous().Address()\n\tlisted := false\n\tfor _, a := range addrs {\n\t\tif a == proposer.String() {\n\t\t\tlisted = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(addrs) \u003e 0 \u0026\u0026 !listed {\n\t\tpanic(\"refusing to propose a \" + runSubmittersKey + \" allowlist that omits \" +\n\t\t\t\"the proposer \" + proposer.String() + \": a non-empty list that names nobody \" +\n\t\t\t\"who can create a proposal cannot be changed back\")\n\t}\n\n\ttitle := \"Set the \" + runSubmittersKey + \" allowlist\"\n\tdesc := \"Replace the \" + runSubmittersKey + \" allowlist, which gates who may \" +\n\t\t\"send MsgRun.\"\n\tif len(addrs) == 0 {\n\t\tdesc += \" This empties the list, which switches the gate OFF: anyone may \" +\n\t\t\t\"send MsgRun.\"\n\t} else {\n\t\tdesc += \" Only these addresses may send MsgRun. Creating a GovDAO proposal \" +\n\t\t\t\"needs MsgRun, so this list also decides who can govern.\"\n\t\tfor _, a := range addrs {\n\t\t\tdesc += \"\\n- \" + a\n\t\t}\n\t}\n\n\tcallback := func(cur realm) error {\n\t\tsetRunSubmitters(addrs)\n\t\tchain.Emit(\"SetRunSubmitters\", \"key\", runSubmittersKey, \"proposer\", proposer.String())\n\t\treturn nil\n\t}\n\treturn dao.NewProposalRequest(title, desc,\n\t\tdao.NewSimpleExecutor(0, cur, callback, \"\"))\n}\n\n// setRunSubmitters replaces the whole allowlist.\n//\n// SetSysParamStrings, not UpdateSysParamStrings: Update with add=true appends\n// non-duplicates onto what is already there, so it can never remove an address\n// or empty the list. This realm reserves the key from the generic factories, so\n// this is the only route by vote -- if it appended, the parameter would be\n// append-only chain-wide, a compromised address could never be de-listed, and\n// the gate could never be turned back off.\n//\n// A named function rather than the executor's body inline, so a test can reach\n// it: a closure held in a ProposalRequest cannot be called from outside.\nfunc setRunSubmitters(addrs []string) {\n\tprms.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs)\n}\n"},{"name":"unlock.gno","body":"package params\n\nimport \"gno.land/r/gov/dao\"\n\nconst (\n\tbankModulePrefix     = \"bank\"\n\trestrictedDenomsKey  = \"restricted_denoms\"\n\tunlockTransferTitle  = \"Proposal to unlock the transfer of ugnot.\"\n\tlockTransferTitle    = \"Proposal to lock the transfer of ugnot.\"\n\tauthModulePrefix     = \"auth\"\n\tunrestrictedAddrsKey = \"unrestricted_addrs\"\n)\n\nfunc ProposeUnlockTransferRequest(cur realm) dao.ProposalRequest {\n\treturn NewSysParamStringsPropRequestWithTitle(cur, bankModulePrefix, \"p\", restrictedDenomsKey, unlockTransferTitle, []string{})\n}\n\nfunc ProposeLockTransferRequest(cur realm) dao.ProposalRequest {\n\treturn NewSysParamStringsPropRequestWithTitle(cur, bankModulePrefix, \"p\", restrictedDenomsKey, lockTransferTitle, []string{\"ugnot\"})\n}\n\nfunc ProposeAddUnrestrictedAcctsRequest(cur realm, addrs ...address) dao.ProposalRequest {\n\taddrStrings := make([]string, 0, len(addrs))\n\tfor _, addr := range addrs {\n\t\ts := addr.String()\n\t\taddrStrings = append(addrStrings, s)\n\t}\n\treturn NewSysParamStringsPropRequestAddWithTitle(cur, authModulePrefix, \"p\", unrestrictedAddrsKey, \"Add unrestricted transfer accounts\", addrStrings)\n}\n\nfunc ProposeRemoveUnrestrictedAcctsRequest(cur realm, addrs ...address) dao.ProposalRequest {\n\taddrStrings := make([]string, 0, len(addrs))\n\tfor _, addr := range addrs {\n\t\ts := addr.String()\n\t\taddrStrings = append(addrStrings, s)\n\t}\n\treturn NewSysParamStringsPropRequestRemoveWithTitle(cur, authModulePrefix, \"p\", unrestrictedAddrsKey, \"Remove unrestricted transfer accounts\", addrStrings)\n}\n"},{"name":"valoper.gno","body":"package params\n\nimport (\n\tprms \"sys/params\"\n)\n\n// Valoper sys-param keys consumed by r/gnops/valopers (Register +\n// UpdateSigningKey). Governance can update them via the generic\n// NewSysParam*PropRequest factories — no realm-side gate is needed\n// because the values only affect fees and throttle inside valopers.\nconst (\n\tvaloperSubmodule = \"valoper\"\n\n\tvaloperRegisterFeeKey          = \"register_fee\"\n\tvaloperRotationFeeKey          = \"rotation_fee\"\n\tvaloperRotationPeriodBlocksKey = \"rotation_period_blocks\"\n)\n\n// Default values used when the sys-param has never been set by\n// governance. Zero fees (GNOT transfers are disabled chain-wide\n// pre-fork) and a ~1-hour throttle at 6s/block.\nconst (\n\tdefaultValoperRegisterFee          = uint64(0)\n\tdefaultValoperRotationFee          = uint64(0)\n\tdefaultValoperRotationPeriodBlocks = int64(600)\n)\n\n// GetValoperRegisterFee returns the fee (in ugnot) required to call\n// valopers.Register. Defaults to 0 if governance hasn't set it.\nfunc GetValoperRegisterFee() uint64 {\n\tv, ok := prms.GetSysParamUint64(nodeModulePrefix, valoperSubmodule, valoperRegisterFeeKey)\n\tif !ok {\n\t\treturn defaultValoperRegisterFee\n\t}\n\treturn v\n}\n\n// GetValoperRotationFee returns the fee (in ugnot) required to call\n// valopers.UpdateSigningKey. Defaults to 0.\nfunc GetValoperRotationFee() uint64 {\n\tv, ok := prms.GetSysParamUint64(nodeModulePrefix, valoperSubmodule, valoperRotationFeeKey)\n\tif !ok {\n\t\treturn defaultValoperRotationFee\n\t}\n\treturn v\n}\n\n// GetValoperRotationPeriodBlocks returns the per-operator rotation\n// throttle (in blocks). Defaults to ~1h worth at 6s/block (600).\n// This is the primary anti-spam defense pre-fee while rotation_fee\n// stays at 0; tightens further once non-zero fees become enforceable.\nfunc GetValoperRotationPeriodBlocks() int64 {\n\tv, ok := prms.GetSysParamInt64(nodeModulePrefix, valoperSubmodule, valoperRotationPeriodBlocksKey)\n\tif !ok {\n\t\treturn defaultValoperRotationPeriodBlocks\n\t}\n\treturn v\n}\n"},{"name":"valset.gno","body":"package params\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\tprms \"sys/params\"\n\n\t\"gno.land/p/sys/validators/v0\"\n)\n\n// Param keys read by gno.land/pkg/gnoland (EndBlocker).\n// Keep in sync with gno.land/pkg/gnoland/node_params.go.\n// nodeModulePrefix is declared in halt.gno (same package).\nconst (\n\tvalsetSubmodule = \"valset\"\n\n\t// dirty signals the chain that the proposed valset differs from the\n\t// current applied one. Realm sets true; EndBlocker clears.\n\tvalsetDirtyKey = \"dirty\"\n\n\t// One []string per slot; each entry has the form \"\u003cpubkey\u003e:\u003cpower\u003e\"\n\t// (bech32 pubkey + decimal power). Address is derived from pubkey\n\t// on the chain side and not stored.\n\t//\n\t//   proposed = v0's full target valset\n\t//   current  = chain-managed: the set that becomes ACTIVE AT H+2\n\t//              once the most recent EndBlock's updates apply.\n\t//              NOT necessarily the set actively signing the current\n\t//              block — see ABCI H+2 sequencing.\n\tvalsetProposedKey = \"proposed\"\n\tvalsetCurrentKey  = \"current\"\n\n\t// pubkey_types: chain-mirrored validator pubkey-type allow-list (read-only here).\n\tvalsetPubKeyTypesKey = \"pubkey_types\"\n\n\t// Only this realm may write valset:proposed and valset:dirty.\n\t// valset:current is chain-managed (see ctx-sentinel in node_params.go).\n\tvalsetAuthorizedRealm = \"gno.land/r/sys/validators/v0\"\n)\n\n// SetValsetProposal publishes the realm's desired valset. Each entry is\n// \"\u003cbech32-pubkey\u003e:\u003cdecimal-power\u003e\"; power=0 removes the validator.\n// The chain reads this on the next EndBlocker, diffs it against\n// valset:current, and propagates the changes to consensus.\nfunc SetValsetProposal(cur realm, entries []string) {\n\tassertValsetCaller(0, cur)\n\tprms.SetSysParamStrings(nodeModulePrefix, valsetSubmodule, valsetProposedKey, entries)\n\tprms.SetSysParamBool(nodeModulePrefix, valsetSubmodule, valsetDirtyKey, true)\n}\n\n// GetValsetEntries returns the chain's authoritative committed\n// validator set (the contents of valset:current). This is the\n// V_{H+2} view — the set that will be active at H+2 once the most\n// recent EndBlock's updates apply, NOT the set signing the current\n// block. Callers that want \"what v0 reports as the current\n// validator set\" — including the in-flight proposed set during\n// the dirty window — should call GetValsetEffective instead.\nfunc GetValsetEntries() []validators.Validator {\n\treturn parseValsetSlot(valsetCurrentKey)\n}\n\n// ValsetDirty reports whether valset:proposed is awaiting EndBlocker.\n// Realm callers MUST treat this as transient: the dirty flag is set\n// by SetValsetProposal and cleared by the chain's EndBlocker (every\n// block where dirty=true on entry exits with dirty=false).\nfunc ValsetDirty() bool {\n\td, _ := prms.GetSysParamBool(nodeModulePrefix, valsetSubmodule, valsetDirtyKey)\n\treturn d\n}\n\n// GetValsetEffective returns the set that WILL be active at H+2:\n// valset:proposed if dirty, else valset:current. Used by v0 so that\n// (a) reads after a same-block proposal callback see that proposal's\n// effects, and (b) sequential same-block proposals accumulate\n// correctly on top of each other.\n//\n// Misuse warning: this exists for r/sys/validators/v0's internal\n// reads. Other realms making \"is X a validator\" decisions should\n// call v0.IsValidator, not this directly, so future changes to v0's\n// read semantics propagate uniformly.\nfunc GetValsetEffective() []validators.Validator {\n\tkey := valsetCurrentKey\n\tif ValsetDirty() {\n\t\tkey = valsetProposedKey\n\t}\n\treturn parseValsetSlot(key)\n}\n\nfunc parseValsetSlot(key string) []validators.Validator {\n\traw, _ := prms.GetSysParamStrings(nodeModulePrefix, valsetSubmodule, key)\n\tout := make([]validators.Validator, 0, len(raw))\n\tfor _, e := range raw {\n\t\tv, err := parseEntry(e)\n\t\tif err != nil {\n\t\t\tpanic(\"valset:\" + key + \" corrupted: \" + err.Error())\n\t\t}\n\t\tout = append(out, v)\n\t}\n\treturn out\n}\n\n// parseEntry splits \"\u003cbech32-pubkey\u003e:\u003cdecimal-power\u003e\" and derives the\n// validator address via the chain.PubKeyAddress native helper.\nfunc parseEntry(entry string) (validators.Validator, error) {\n\tpkStr, pStr, ok := strings.Cut(entry, \":\")\n\tif !ok {\n\t\treturn validators.Validator{}, errors.New(\"missing ':' separator in \" + entry)\n\t}\n\taddr, err := chain.PubKeyAddress(pkStr)\n\tif err != nil {\n\t\treturn validators.Validator{}, err\n\t}\n\tpower, err := strconv.ParseUint(pStr, 10, 64)\n\tif err != nil {\n\t\treturn validators.Validator{}, err\n\t}\n\treturn validators.Validator{\n\t\tAddress:     addr,\n\t\tPubKey:      pkStr,\n\t\tVotingPower: power,\n\t}, nil\n}\n\n// GetValsetPubKeyTypes returns the validator pubkey-type allow-list mirrored from consensus params (empty means accept any).\nfunc GetValsetPubKeyTypes() []string {\n\ttypes, _ := prms.GetSysParamStrings(nodeModulePrefix, valsetSubmodule, valsetPubKeyTypesKey)\n\treturn types\n}\n\n// assertValsetCaller authorizes the one realm permitted to write valset params.\n//\n// Delegates to assertDelegate (see delegate.gno) so this realm has exactly one\n// authorized-caller gate rather than two that can drift. The distinction that\n// remains is deliberate and is NOT expressible through a delegation slot: this\n// authorization is a compile-time const, so re-pointing it requires a chain\n// relaunch, and assertNotValsetKey locks GovDAO out of the key family entirely.\n// A vote-settable slot would let one supermajority re-point the valset writer at\n// an arbitrary realm and bypass v0's valoper-existence check, its KeepRunning\n// opt-out, and execution-time pubkey re-resolution.\nfunc assertValsetCaller(_ int, rlm realm) {\n\tassertDelegate(0, rlm, valsetAuthorizedRealm, \"valset params\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"validators","path":"gno.land/r/sys/validators/v0","files":[{"name":"cache.gno","body":"package validators\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"sort\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/sys/validators/v0\"\n\tsysparams \"gno.land/r/sys/params\"\n)\n\n// valopersRealmPath is the only realm allowed to refresh valoperCache\n// or invoke RotateValoperSigningKey. Both auth checks below depend on\n// being called via `cross` from a crossing function in valopers.\nconst valopersRealmPath = \"gno.land/r/gnops/valopers\"\n\n// valoperCache mirrors the (operator -\u003e current signing key) view from\n// r/gnops/valopers. Written by valopers via NotifyValoperChanged. Read\n// by future operator-keyed proposal flow (step 5).\n//\n// Pushing (valopers passes the values as args) rather than pulling\n// (v0 imports valopers and reads them) — pulling would create an\n// import cycle, since valopers already imports v0 for IsValidator.\nvar valoperCache = bptree.NewBPTree32()\n\ntype cacheEntry struct {\n\tSigningPubKey  string\n\tSigningAddress address\n\tKeepRunning    bool\n}\n\n// assertValopersCaller panics if the caller realm is not r/gnops/valopers.\n// Per docs/resources/gno-interrealm.md, this check works only when (a)\n// the host function is a crossing function (`cur realm`) and (b) it's\n// invoked via `cross` from a crossing function in valopers. Then\n// PreviousRealm() shifts exactly one frame to valopers. A user MsgCall\n// would see PreviousRealm() == UserRealm (pkgpath \"\"); a third realm\n// cross-call would see its own pkgpath. Either fails this check.\nfunc assertValopersCaller(_ int, rlm realm) {\n\t// Defense-in-depth IsCurrent gate. Current call sites pass live\n\t// cur (cross(cur) from valopers), so this never fires today — but\n\t// the helper trusts its rlm input, and any future call that threads\n\t// a stashed/sibling-frame realm value with .Previous().PkgPath() ==\n\t// valopersRealmPath would silently bypass the gate (Class-2\n\t// designation forgery; see docs/resources/gno-security.md). Gating\n\t// here makes the precondition enforceable rather than convention.\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tcaller := rlm.Previous().PkgPath()\n\tif caller != valopersRealmPath {\n\t\tpanic(\"caller realm must be \" + valopersRealmPath + \", got \" + caller)\n\t}\n}\n\n// NotifyValoperChanged refreshes the cached entry for op. Auth: caller\n// realm must be r/gnops/valopers.\n//\n// READ-ONLY against valopers: by design this function does not call\n// back into valopers (no pull). Valopers pushes the current values in\n// as args. This eliminates the confused-deputy class where v0 → valopers\n// callbacks would make valopers see v0 as PreviousRealm.\nfunc NotifyValoperChanged(cur realm, op address, signingPubKey string, signingAddress address, keepRunning bool) {\n\tassertValopersCaller(0, cur)\n\tvaloperCache.Set(op.String(), cacheEntry{\n\t\tSigningPubKey:  signingPubKey,\n\t\tSigningAddress: signingAddress,\n\t\tKeepRunning:    keepRunning,\n\t})\n}\n\n// RotateValoperSigningKey applies a signing-key rotation to the\n// effective valset and publishes the new full set via sysparams.\n// Auth: caller realm must be r/gnops/valopers.\n//\n// Body is read-modify-write against sysparams.GetValsetEffective so\n// concurrent same-block writers (other rotations or GovDAO executors)\n// accumulate instead of clobbering. Mirrors the executor pattern in\n// validators.gno.\n//\n// Idempotent: if the rotating operator's old signing address is not\n// currently in the effective valset (e.g., they were removed), the\n// rotation is a no-op at the sysparams level — valopers' profile and\n// signingRegistry already record the new key. Either replays cleanly.\n//\n// Emits ValoperRotated event with op + old/new addresses + height.\nfunc RotateValoperSigningKey(cur realm, op address, oldPubKey, newPubKey string) {\n\tassertValopersCaller(0, cur)\n\n\toldAddr, err := chain.PubKeyAddress(oldPubKey)\n\tif err != nil {\n\t\tpanic(\"invalid oldPubKey: \" + err.Error())\n\t}\n\tnewAddr, err := chain.PubKeyAddress(newPubKey)\n\tif err != nil {\n\t\tpanic(\"invalid newPubKey: \" + err.Error())\n\t}\n\n\tbaseline := sysparams.GetValsetEffective()\n\tset := make(map[address]validators.Validator, len(baseline))\n\tfor _, v := range baseline {\n\t\tset[v.Address] = v\n\t}\n\n\t// The rotating operator must currently be in the active set; if\n\t// not (operator removed before rotating), nothing to publish.\n\t// Valopers-side state has already been updated regardless.\n\tprev, ok := set[oldAddr]\n\tif !ok {\n\t\tchain.Emit(\n\t\t\t\"ValoperRotated\",\n\t\t\t\"op\", op.String(),\n\t\t\t\"oldAddr\", oldAddr.String(),\n\t\t\t\"newAddr\", newAddr.String(),\n\t\t\t\"height\", strconv.FormatInt(runtime.ChainHeight(), 10),\n\t\t\t\"applied\", \"false\",\n\t\t)\n\t\treturn\n\t}\n\n\tdelete(set, oldAddr)\n\tset[newAddr] = validators.Validator{\n\t\tAddress:     newAddr,\n\t\tPubKey:      newPubKey,\n\t\tVotingPower: prev.VotingPower,\n\t}\n\n\t// Defense-in-depth: a delete+insert in this branch always leaves\n\t// at least one entry (the freshly inserted newAddr), so an empty\n\t// set is unreachable today. Panic explicitly anyway: a future\n\t// refactor of this body that ends up publishing an empty set\n\t// would otherwise be silently swallowed by the EndBlocker\n\t// (which logs and clears dirty for empty publishes), masking\n\t// the regression.\n\tif len(set) == 0 {\n\t\tpanic(\"rotation would empty the validator set; refused to keep consensus liveness\")\n\t}\n\n\tentries := make([]string, 0, len(set))\n\tfor _, v := range set {\n\t\tentries = append(entries, v.PubKey+\":\"+strconv.FormatUint(v.VotingPower, 10))\n\t}\n\tsort.Strings(entries)\n\tsysparams.SetValsetProposal(cross(cur), entries)\n\n\tchain.Emit(\n\t\t\"ValoperRotated\",\n\t\t\"op\", op.String(),\n\t\t\"oldAddr\", oldAddr.String(),\n\t\t\"newAddr\", newAddr.String(),\n\t\t\"height\", strconv.FormatInt(runtime.ChainHeight(), 10),\n\t\t\"applied\", \"true\",\n\t)\n}\n\n// AssertGenesisValopersConsistent panics if any entry in valset:current\n// (the seeded genesis valset) lacks a corresponding valoperCache profile\n// whose SigningAddress matches.\n//\n// **Genesis-mode only.** The function refuses to run unless\n// runtime.ChainHeight() == 0. This is the documented intended usage\n// (last migration .jsonl tx, before any block has been produced) and\n// also closes a post-genesis MsgCall DoS surface — without the guard,\n// an attacker could pay gas to repeatedly invoke an O(N) iteration\n// over valoperCache + valset:current after the chain is live.\n//\n// gnoland's InitChainer auto-runs this assertion at end of\n// genesis-mode replay when GnoGenesisState.PastChainIDs is non-empty;\n// failure aborts the boot unconditionally. valoper-seed and\n// hand-crafted migration .jsonls do NOT need to emit the call\n// themselves.\n//\n// Crossing function: callable via MsgCall (only at genesis-mode).\n// Doesn't mutate state — pure invariant check. Inverse direction\n// (every valoperCache entry must have a corresponding valset:current\n// entry) is intentionally NOT checked: extra valoper profiles\n// registered without immediate valset inclusion are a normal\n// post-genesis state.\nfunc AssertGenesisValopersConsistent(cur realm) {\n\tif runtime.ChainHeight() != 0 {\n\t\tpanic(\"AssertGenesisValopersConsistent is only callable during genesis-mode replay (ChainHeight()==0)\")\n\t}\n\n\t// Collect the signing addresses present in valoperCache.\n\tseen := map[string]bool{}\n\tvaloperCache.Iterate(\"\", \"\", func(_ string, raw any) bool {\n\t\tentry := raw.(cacheEntry)\n\t\tseen[entry.SigningAddress.String()] = true\n\t\treturn false\n\t})\n\n\t// Every entry in valset:current must appear in seen.\n\tfor _, v := range sysparams.GetValsetEntries() {\n\t\tif !seen[v.Address.String()] {\n\t\t\tpanic(\"genesis-validator \" + v.Address.String() + \" has no corresponding valoper profile (signing address not in valoperCache)\")\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/validators/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"proposal.gno","body":"package validators\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/sys/validators/v0\"\n\t\"gno.land/r/gov/dao\"\n\tsysparams \"gno.land/r/sys/params\"\n)\n\n// ValoperChange is the operator-keyed input shape for the v0 valset\n// proposal builder. Power=0 removes; Power\u003e0 adds (or upserts the\n// power on an op already in the active set — Tendermint's natural\n// ValidatorUpdate semantics).\n//\n// Each operator may appear AT MOST ONCE per proposal; duplicates are\n// rejected at create-time.\ntype ValoperChange struct {\n\tOperatorAddress address\n\tPower           uint64\n}\n\nfunc NewValoperChange(operatorAddress address, power uint64) ValoperChange {\n\treturn ValoperChange{\n\t\tOperatorAddress: operatorAddress,\n\t\tPower:           power,\n\t}\n}\n\nconst errNoValoperChanges = \"no valoper changes proposed\"\n\n// NewValidatorProposalRequest builds a GovDAO proposal that, when\n// executed, applies the deltas to the chain's effective valset and\n// publishes the new full set via SetValsetProposal.\n//\n// NON-CROSSING (no `cur realm`). Direct MsgCall is unsupported;\n// proposers route through r/gnops/valopers/proposal's facade\n// (which IS crossing and accepts user txs).\n//\n// Validation at creation time:\n//   - Each operator may appear AT MOST ONCE in changes; duplicates\n//     panic. Power changes for an op already in the active set use\n//     a single {op, newPower} entry (upsert), not the legacy\n//     remove/re-add pair.\n//   - Every ValoperChange's OperatorAddress must exist in\n//     valoperCache. Unknown operators panic.\n//   - Adds (Power \u003e 0) require KeepRunning=true. An op that has\n//     called UpdateKeepRunning(false) signals opt-out; no proposal\n//     can keep them in the active set, period.\n//\n// Pubkey resolution at execution time: the executor callback\n// re-reads valoperCache for each entry to capture the CURRENT\n// signing pubkey/address — not the creation-time one. Defends\n// against a stale (now-retired) key publication if the operator\n// rotated while the proposal sat in GovDAO. Also re-checks\n// KeepRunning so an operator flipping to KeepRunning=false between\n// propose-create and propose-execute is honored. Removes are\n// unaffected (operator address is the lookup key, not signing\n// address).\n//\n// Emits ValidatorAdded / ValidatorRemoved events per entry on\n// successful execution. (Power-upsert on an existing op also emits\n// ValidatorAdded with the new power.)\nfunc NewValidatorProposalRequest(cur realm, changes []ValoperChange, title, description string) dao.ProposalRequest {\n\tif len(changes) == 0 {\n\t\tpanic(errNoValoperChanges)\n\t}\n\ttitle = strings.TrimSpace(title)\n\tif title == \"\" {\n\t\tpanic(\"proposal title is empty\")\n\t}\n\tif len(changes) \u003e 40 {\n\t\tpanic(\"max number of allowed validators per proposal is 40\")\n\t}\n\n\t// Dedupe: each operator may appear at most once per proposal.\n\t// Power changes are now expressed as a single {op, newPower}\n\t// upsert entry, so the legacy [{op,0},{op,N}] pair is a duplicate\n\t// and rejected.\n\tseen := map[string]bool{}\n\tfor _, c := range changes {\n\t\tkey := c.OperatorAddress.String()\n\t\tif seen[key] {\n\t\t\tpanic(\"duplicate operator in proposal: \" + key)\n\t\t}\n\t\tseen[key] = true\n\t}\n\n\t// Creation-time validation: every operator must exist in cache,\n\t// and adds require KeepRunning=true. KeepRunning=false is a\n\t// binding opt-out; no proposal shape can override it.\n\tfor _, c := range changes {\n\t\trawCache := valoperCache.Get(c.OperatorAddress.String())\n\t\tif rawCache == nil {\n\t\t\tpanic(\"unknown operator: \" + c.OperatorAddress.String())\n\t\t}\n\t\tentry := rawCache.(cacheEntry)\n\t\tif c.Power \u003e 0 \u0026\u0026 !entry.KeepRunning {\n\t\t\tpanic(\"operator \" + c.OperatorAddress.String() + \" has KeepRunning=false; refusing to add (operator must call UpdateKeepRunning(true) first)\")\n\t\t}\n\t}\n\n\t// Render description against creation-time data. Voters see the\n\t// operator addresses being proposed; signing addresses are an\n\t// implementation detail resolved at exec.\n\tvar desc strings.Builder\n\tdesc.WriteString(description)\n\tif len(description) \u003e 0 {\n\t\tdesc.WriteString(\"\\n\\n\")\n\t}\n\tdesc.WriteString(\"## Validator Updates\\n\")\n\tfor _, c := range changes {\n\t\tif c.Power == 0 {\n\t\t\tdesc.WriteString(ufmt.Sprintf(\"- %s: remove\\n\", c.OperatorAddress))\n\t\t} else {\n\t\t\tdesc.WriteString(ufmt.Sprintf(\"- %s: add (power %d)\\n\", c.OperatorAddress, c.Power))\n\t\t}\n\t}\n\n\treturn dao.NewProposalRequest(title, desc.String(), newValoperChangeExecutor(cur, changes))\n}\n\n// newValoperChangeExecutor builds the GovDAO executor that, on\n// approval, applies the captured ValoperChange deltas. Resolves\n// operator → signing addr/pubkey via valoperCache at execution time\n// for adds (so a mid-flight rotation doesn't publish a stale key).\n// Removes resolve the operator's CURRENT signing address (also via\n// cache) — operator-keyed removes are immune to rotation churn.\n//\n// Power\u003e0 is an upsert against the effective valset map (keyed on\n// signing address): if the op is already present under that signing\n// address, the entry's voting power is overwritten. Tendermint\n// natively handles ValidatorUpdates as upserts, so a single-entry\n// power change is the canonical form.\nfunc newValoperChangeExecutor(cur realm, changes []ValoperChange) dao.Executor {\n\tcallback := func(cur realm) error {\n\t\tbaseline := sysparams.GetValsetEffective()\n\t\tset := make(map[address]validators.Validator, len(baseline))\n\t\tfor _, v := range baseline {\n\t\t\tset[v.Address] = v\n\t\t}\n\n\t\tfor _, c := range changes {\n\t\t\trawCache := valoperCache.Get(c.OperatorAddress.String())\n\t\t\tif rawCache == nil {\n\t\t\t\tpanic(\"operator vanished from valoperCache between propose and execute: \" + c.OperatorAddress.String())\n\t\t\t}\n\t\t\tentry := rawCache.(cacheEntry)\n\n\t\t\tif c.Power == 0 {\n\t\t\t\tif _, ok := set[entry.SigningAddress]; !ok {\n\t\t\t\t\tpanic(\"validator does not exist: \" + entry.SigningAddress.String())\n\t\t\t\t}\n\t\t\t\tdelete(set, entry.SigningAddress)\n\t\t\t\tchain.Emit(\n\t\t\t\t\t\"ValidatorRemoved\",\n\t\t\t\t\t\"op\", c.OperatorAddress.String(),\n\t\t\t\t\t\"signingAddr\", entry.SigningAddress.String(),\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Race-safety: operator may have flipped KeepRunning=false\n\t\t\t// between propose-create and propose-execute. Re-check.\n\t\t\t// The opt-out is binding regardless of proposal shape.\n\t\t\tif !entry.KeepRunning {\n\t\t\t\tpanic(\"operator \" + c.OperatorAddress.String() + \" has KeepRunning=false at execution; refusing to add\")\n\t\t\t}\n\n\t\t\t// Upsert at the current signing address. If the entry was\n\t\t\t// already present (single-entry power change on an active\n\t\t\t// validator), this overwrites the prior power.\n\t\t\tset[entry.SigningAddress] = validators.Validator{\n\t\t\t\tAddress:     entry.SigningAddress,\n\t\t\t\tPubKey:      entry.SigningPubKey,\n\t\t\t\tVotingPower: c.Power,\n\t\t\t}\n\t\t\tchain.Emit(\n\t\t\t\t\"ValidatorAdded\",\n\t\t\t\t\"op\", c.OperatorAddress.String(),\n\t\t\t\t\"signingAddr\", entry.SigningAddress.String(),\n\t\t\t\t\"power\", strconv.FormatUint(c.Power, 10),\n\t\t\t)\n\t\t}\n\n\t\t// Liveness floor: refuse to publish an empty set.\n\t\tif len(set) == 0 {\n\t\t\tpanic(\"valset proposal would empty the validator set; refused to keep consensus liveness\")\n\t\t}\n\n\t\tentries := make([]string, 0, len(set))\n\t\tfor _, v := range set {\n\t\t\tentries = append(entries, v.PubKey+\":\"+strconv.FormatUint(v.VotingPower, 10))\n\t\t}\n\t\tsort.Strings(entries)\n\t\tsysparams.SetValsetProposal(cross(cur), entries)\n\t\treturn nil\n\t}\n\n\treturn dao.NewSimpleExecutor(0, cur, callback, \"\")\n}\n"},{"name":"validators.gno","body":"// Package validators implements on-chain validator set management\n// through Proof of Authority. The realm exposes a public proposal\n// constructor for GovDAO; on approval, the proposal callback applies\n// the captured deltas to the chain's effective valset and publishes\n// the new full set via gno.land/r/sys/params. The chain's EndBlocker\n// reads the result on the next block and propagates to consensus.\n//\n// No in-realm validator state. All reads go through\n// sysparams.GetValsetEffective (proposed-if-dirty, else current).\npackage validators\n\nimport (\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/sys/validators/v0\"\n\tsysparams \"gno.land/r/sys/params\"\n)\n\n// Operator-keyed proposal builder lives in proposal.gno\n// (NewValidatorProposalRequest + newValoperChangeExecutor). The legacy\n// signing-keyed NewProposalRequest was removed: every valid\n// signing-keyed input is also a valid operator-keyed input under\n// always-on valoper enforcement.\n\n// IsValidator returns true if addr is part of the effective validator\n// set (proposed if a v0 proposal is awaiting EndBlocker, else\n// current).\nfunc IsValidator(addr address) bool {\n\tfor _, v := range sysparams.GetValsetEffective() {\n\t\tif v.Address == addr {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// GetValidator returns the validator with the given address from the\n// effective set; panics if absent.\nfunc GetValidator(addr address) validators.Validator {\n\tfor _, v := range sysparams.GetValsetEffective() {\n\t\tif v.Address == addr {\n\t\t\treturn v\n\t\t}\n\t}\n\tpanic(\"validator not found\")\n}\n\n// GetValidators returns the effective validator set.\nfunc GetValidators() []validators.Validator {\n\treturn sysparams.GetValsetEffective()\n}\n\n// Render displays the effective validator set.\nfunc Render(string) string {\n\tvar sb strings.Builder\n\th := runtime.ChainHeight()\n\tset := sysparams.GetValsetEffective()\n\tsb.WriteString(ufmt.Sprintf(\"## Valset at height %d\\n\\n\", h))\n\tif len(set) == 0 {\n\t\tsb.WriteString(\"Valset is empty.\\n\")\n\t\treturn sb.String()\n\t}\n\tfor i, v := range set {\n\t\tsb.WriteString(ufmt.Sprintf(\"- #%d: %s (%d)\\n\", i, v.Address.String(), v.VotingPower))\n\t}\n\treturn sb.String()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"security_patterns","path":"gno.land/r/docs/security_patterns","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/docs/security_patterns\"\ngno = \"0.9\"\n"},{"name":"security_patterns.gno","body":"package security_patterns\n\nimport \"gno.land/p/nt/markdown/sanitize/v0\"\n\nvar (\n\tadmin   = address(\"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\")\n\tmessage = \"Only the admin can edit this message.\"\n)\n\nfunc SetMessage(cur realm, next string) {\n\tassertAdmin(cur)\n\tmessage = next\n}\n\nfunc TransferAdmin(cur realm, next address) {\n\tif !next.IsValid() {\n\t\tpanic(\"invalid admin\")\n\t}\n\tassertAdmin(cur)\n\tadmin = next\n}\n\nfunc Admin() address {\n\treturn admin\n}\n\nfunc Message() string {\n\treturn message\n}\n\nfunc Render(path string) string {\n\tout := \"# Security Patterns\\n\\n\"\n\tout += \"This realm demonstrates three defensive patterns; read the source \" +\n\t\t\"alongside this page:\\n\\n\"\n\tout += \"1. **Live-realm guard** — `assertAdmin` panics unless \" +\n\t\t\"`cur.IsCurrent()` holds, which checks the realm token against the \" +\n\t\t\"live call frame before any authority is read from it.\\n\"\n\tout += \"2. **Caller identity via `cur.Previous().Address()`** — the admin \" +\n\t\t\"check reads the immediate caller, not `OriginCaller()`, so an \" +\n\t\t\"intermediary realm cannot pass itself off as the user.\\n\"\n\tout += \"3. **Sanitized render output** — every value echoed below is run \" +\n\t\t\"through `p/nt/markdown/sanitize` first, so caller-controlled text \" +\n\t\t\"cannot inject markdown or break out of a code span.\\n\\n\"\n\t// InlineCode wraps in a backtick run wide enough to outscan any backticks\n\t// in the content, so a backtick in path cannot close the span early — a\n\t// naive \"`\" + path + \"`\" would.\n\tout += \"Admin: \" + sanitize.InlineCode(admin.String()) + \"\\n\\n\"\n\tout += \"Message: \" + sanitize.InlineText(message) + \"\\n\"\n\tif path != \"\" {\n\t\tout += \"\\nPath: \" + sanitize.InlineCode(path) + \"\\n\"\n\t}\n\treturn out\n}\n\n// assertAdmin guards a state-mutating call. Callers pass their own cur rather\n// than cross(cur) — a non-crossing call of a crossing function, so\n// PreviousRealm does not shift and still names whoever called SetMessage or\n// TransferAdmin. The cur realm first parameter is what makes it a crossing\n// function: the compiler refuses any other first argument, so the token\n// reaching IsCurrent below is live by construction.\nfunc assertAdmin(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"invalid realm\")\n\t}\n\tif cur.Previous().Address() != admin {\n\t\tpanic(\"admin only\")\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"txfees","path":"gno.land/r/sys/txfees","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/txfees\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"render.gno","body":"package txfees\n\nimport (\n\t\"chain/banker\"\n\t\"strings\"\n)\n\nfunc Render(cur realm, _ string) string {\n\tbanker_ := banker.NewReadonlyBanker()\n\trealmAddr := cur.Address()\n\tbalance := banker_.GetCoins(realmAddr).String()\n\n\tif strings.TrimSpace(balance) == \"\" {\n\t\tbalance = \"\\\\\u003cempty\\\\\u003e\"\n\t}\n\n\tvar output string\n\toutput += \"# Transaction Fees\\n\"\n\toutput += \"Balance: \" + balance + \"\\n\\n\"\n\n\toutput += \"Bucket address: \" + realmAddr.String() + \"\\n\"\n\treturn output\n}\n"},{"name":"txfees.gno","body":"package txfees\n\n// XXX: TODO distribution logic\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"subhost","path":"gno.land/r/tests/vm/subhost","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/subhost\"\ngno = \"0.9\"\n"},{"name":"subhost.gno","body":"// Package subhost is a test fixture for realm.Sub sub-identity\n// presentation across a real package boundary. It plays two roles:\n//\n//   - Host: ActAsSub mints a sub of its OWN live cur and crosses into an\n//     observer with it.\n//   - Observer: Observe reads the presented identity (cur.Previous) that\n//     a caller crossed in with, and asserts unsafe.PreviousRealm parity.\n//\n// Consumers:\n//   - gnovm/tests/files/zrealm_sub_foreign_present.gno crosses into\n//     Observe directly with a sub minted in the caller's own realm, to\n//     check cross-realm identity presentation + Subpath() through a cross.\n//   - gno.land/pkg/integration/testdata/subrealm_run_parity.txtar enters\n//     via MsgRun, crosses into ActAsSub, which mints a sub and crosses\n//     into Observe — the MsgRun-entry counterpart to the MsgCall-entry\n//     parity filetest zrealm_sub1.gno.\npackage subhost\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n)\n\nconst pkgPath = \"gno.land/r/tests/vm/subhost\"\n\n// Observe reports what the immediate caller presented as its identity.\n// The three cur.Previous() views (address, synthesized pkgpath, subpath)\n// are the callee-side surface a sub-token must present; the two parity\n// booleans assert unsafe.PreviousRealm() reads the SAME identity (v2\n// §5.4: unsafe.* must agree with cur.Previous()). prevParity is the\n// load-bearing assertion for the identity-chain walk; curParity guards\n// height 0.\nfunc Observe(cur realm) {\n\tprev := cur.Previous()\n\tprintln(\"observed prev.PkgPath:\", prev.PkgPath())\n\tprintln(\"observed prev.Subpath:\", prev.Subpath())\n\tprintln(\"observed prev.IsUserCall:\", prev.IsUserCall())\n\t// Short-circuit the primary case FIRST: DerivePkgSubAddr panics on an\n\t// empty subpath, so it must not be evaluated when prev is a primary.\n\tprintln(\"prev.Address == DerivePkgSubAddr(host, subpath):\",\n\t\tprev.Subpath() == \"\" ||\n\t\t\tstring(prev.Address()) == string(chain.DerivePkgSubAddr(pkgPathOf(prev.PkgPath()), prev.Subpath())))\n\tprintln(\"unsafe prev parity:\",\n\t\tstring(prev.Address()) == string(unsafe.PreviousRealm().Address()) \u0026\u0026\n\t\t\tprev.PkgPath() == unsafe.PreviousRealm().PkgPath())\n\tprintln(\"unsafe cur parity:\",\n\t\tstring(cur.Address()) == string(unsafe.CurrentRealm().Address()) \u0026\u0026\n\t\t\tcur.PkgPath() == unsafe.CurrentRealm().PkgPath())\n}\n\n// pkgPathOf returns the host portion of a possibly-synthesized pkgpath,\n// so DerivePkgSubAddr (which takes the host) can be recomputed from the\n// callee's observation alone.\nfunc pkgPathOf(p string) string {\n\thost, _, _ := chain.SplitPkgSubPath(p)\n\treturn host\n}\n\n// ActAsSub mints a sub-identity of subhost's OWN live cur and crosses\n// with it into Observe. Used by the MsgRun-entry parity test: the\n// outermost entry is a `/e/\u003caddr\u003e/run` ephemeral, but subhost's cur is a\n// first-class primary here, so cur.Sub is legal and the sub presents to\n// Observe exactly as in the MsgCall path.\nfunc ActAsSub(cur realm, subpath string) {\n\tsub := cur.Sub(subpath)\n\tObserve(cross(sub))\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"metadata","path":"gno.land/p/nt/grc721/metadata/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/grc721/metadata/v0\"\ngno = \"0.9\"\n"},{"name":"token.gno","body":"package metadata\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/nt/grc721/v0\"\n)\n\nconst Kind = \"metadata\"\n\n// NewMetadata attaches a metadata extension and registers it as a core Extension.\n// Attach it before the first mint so every token is indexed.\nfunc NewMetadata(coreLedger *grc721.PrivateLedger) (*Metadata, *Ledger) {\n\tif coreLedger == nil {\n\t\tpanic(\"metadata: nil core ledger\")\n\t}\n\n\tst := \u0026storage{}\n\tcore := coreLedger.ReadToken()\n\tled := \u0026Ledger{core: core, st: st}\n\tcoreLedger.RegisterExtension(led)\n\n\treturn \u0026Metadata{core: core, st: st}, led\n}\n\nfunc (m *Metadata) ExtensionKind() string { return Kind }\n\nfunc (m *Metadata) TokenID() string { return m.core.ID() }\n\nfunc (m *Metadata) TokenURI(tid grc721.TokenID) (string, error) {\n\tv := m.st.uris.Get(tid.String())\n\tif v == nil {\n\t\treturn \"\", ErrNoTokenURI\n\t}\n\n\treturn v.(string), nil\n}\n\nfunc (m *Metadata) TokenMetadata(tid grc721.TokenID) (Data, error) {\n\tv := m.st.data.Get(tid.String())\n\tif v == nil {\n\t\treturn Data{}, ErrNoMetadata\n\t}\n\n\treturn v.(Data), nil\n}\n\nfunc (m *Metadata) HasTokenURI(tid grc721.TokenID) bool {\n\treturn m.st.uris.Has(tid.String())\n}\n\nfunc (m *Metadata) HasMetadata(tid grc721.TokenID) bool {\n\treturn m.st.data.Has(tid.String())\n}\n\n// SetTokenURI sets the EIP-721 tokenURI of tid; issuer-only so a holder cannot\n// rewrite the URI after acquisition.\nfunc (led *Ledger) SetTokenURI(tid grc721.TokenID, uri string) error {\n\tif _, err := led.core.OwnerOf(tid); err != nil {\n\t\treturn ErrTokenNotMinted\n\t}\n\n\tled.st.uris.Set(tid.String(), uri)\n\n\tchain.Emit(\n\t\tTokenURIUpdateEvent,\n\t\t\"token\", led.core.ID(),\n\t\t\"tokenId\", tid.String(),\n\t\t\"uri\", uri,\n\t)\n\n\treturn nil\n}\n\n// SetTokenMetadata sets the OpenSea on-chain metadata of tid; issuer-only.\nfunc (led *Ledger) SetTokenMetadata(tid grc721.TokenID, data Data) error {\n\tif _, err := led.core.OwnerOf(tid); err != nil {\n\t\treturn ErrTokenNotMinted\n\t}\n\n\tled.st.data.Set(tid.String(), data)\n\n\tchain.Emit(\n\t\tMetadataUpdateEvent,\n\t\t\"token\", led.core.ID(),\n\t\t\"tokenId\", tid.String(),\n\t)\n\n\treturn nil\n}\n\nfunc (led *Ledger) ExtensionKind() string { return Kind }\n\nfunc (led *Ledger) OnMint(to address, tid grc721.TokenID)           {}\nfunc (led *Ledger) OnTransfer(from, to address, tid grc721.TokenID) {}\n\n// OnBurn clears per-token state so it cannot resurface on re-mint.\nfunc (led *Ledger) OnBurn(tid grc721.TokenID) {\n\ttidStr := tid.String()\n\tled.st.uris.Remove(tidStr)\n\tled.st.data.Remove(tidStr)\n}\n"},{"name":"types.gno","body":"// Package metadata is a stackable GRC721 extension for EIP-721 tokenURI and\n// OpenSea on-chain metadata. Writes are issuer-only so a holder cannot rewrite metadata after acquisition.\npackage metadata\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc721/v0\"\n)\n\nconst (\n\tMetadataUpdateEvent = \"MetadataUpdate\"\n\tTokenURIUpdateEvent = \"TokenURIUpdate\"\n)\n\nvar (\n\tErrTokenNotMinted = errors.New(\"token is not minted\")\n\tErrNoMetadata     = errors.New(\"token has no metadata\")\n\tErrNoTokenURI     = errors.New(\"token has no uri\")\n)\n\ntype Metadata struct {\n\tcore *grc721.Token\n\tst   *storage\n}\n\ntype Ledger struct {\n\tcore *grc721.Token\n\tst   *storage\n}\n\n// Data is the OpenSea on-chain metadata for a single token.\ntype Data struct {\n\tImage           string\n\tImageData       string\n\tExternalURL     string\n\tDescription     string\n\tName            string\n\tAttributes      []Trait\n\tBackgroundColor string\n\tAnimationURL    string\n\tYoutubeURL      string\n}\n\ntype Trait struct {\n\tDisplayType string\n\tTraitType   string\n\tValue       string\n}\n\ntype storage struct {\n\turis avl.Tree // grc721.TokenID -\u003e string\n\tdata avl.Tree // grc721.TokenID -\u003e Data\n}\n\nvar _ grc721.Extension = (*Ledger)(nil)\n\nvar _ grc721.ExtensionView = (*Metadata)(nil)\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"urequire","path":"gno.land/p/nt/urequire/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `urequire` - fail-fast test assertions\n\nSister package to `uassert`. Same assertions, but each one calls `t.FailNow()` on failure so the test stops immediately instead of continuing.\n\n## Usage\n\n```go\nimport (\n    \"testing\"\n\n    \"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestPipeline(t *testing.T) {\n    out, err := Build()\n    urequire.NoError(t, err)        // aborts the test if Build failed\n    urequire.NotNil(t, out)         // out is safe to dereference below\n    urequire.Equal(t, \"ready\", out.Status)\n}\n```\n\n## API\n\nHelpers take `uassert.TestingT` and return nothing — they either pass or stop the test.\n\nEquality and emptiness:\n\n```go\nfunc Equal(t uassert.TestingT, expected, actual any, msgs ...string)\nfunc NotEqual(t uassert.TestingT, expected, actual any, msgs ...string)\nfunc Empty(t uassert.TestingT, obj any, msgs ...string)\nfunc NotEmpty(t uassert.TestingT, obj any, msgs ...string)\n```\n\nTruthiness and nil:\n\n```go\nfunc True(t uassert.TestingT, value bool, msgs ...string)\nfunc False(t uassert.TestingT, value bool, msgs ...string)\nfunc Nil(t uassert.TestingT, value any, msgs ...string)\nfunc NotNil(t uassert.TestingT, value any, msgs ...string)\nfunc TypedNil(t uassert.TestingT, value any, msgs ...string)\nfunc NotTypedNil(t uassert.TestingT, value any, msgs ...string)\n```\n\nErrors:\n\n```go\nfunc NoError(t uassert.TestingT, err error, msgs ...string)\nfunc Error(t uassert.TestingT, err error, msgs ...string)\nfunc ErrorContains(t uassert.TestingT, err error, contains string, msgs ...string)\nfunc ErrorIs(t uassert.TestingT, err, target error, msgs ...string)\n```\n\nPanics and aborts (`f` may be `func()` or `func(realm)`; pass the test's own `cur` as `rlm`):\n\n```go\nfunc PanicsWithMessage(t uassert.TestingT, rlm realm, msg string, f any, msgs ...string)\nfunc PanicsContains(t uassert.TestingT, rlm realm, substr string, f any, msgs ...string)\nfunc NotPanics(t uassert.TestingT, rlm realm, f any, msgs ...string)\nfunc AbortsWithMessage(t uassert.TestingT, rlm realm, msg string, f any, msgs ...string)\nfunc AbortsContains(t uassert.TestingT, rlm realm, substr string, f any, msgs ...string)\nfunc NotAborts(t uassert.TestingT, rlm realm, f any, msgs ...string)\n```\n\n## Notes\n\n- Use `urequire` when the rest of the test depends on the assertion holding (e.g. a `nil` check before dereferencing). Use `uassert` when you want to collect multiple failures from the same test run.\n- Each `urequire` helper is a thin wrapper that calls the matching `uassert` helper and then `t.FailNow()` on failure.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package urequire provides test assertion functions that immediately fail the\n// test on error, complementing the uassert package.\npackage urequire\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/urequire/v0\"\ngno = \"0.9\"\n"},{"name":"urequire.gno","body":"// urequire is a sister package for uassert.\n// XXX: codegen the package.\npackage urequire\n\nimport \"gno.land/p/nt/uassert/v0\"\n\n// type TestingT = uassert.TestingT // XXX: bug, should work\n\n// NoError requires that a function returned no error (i.e. `nil`).\nfunc NoError(t uassert.TestingT, err error, msgs ...string) {\n\tt.Helper()\n\tif uassert.NoError(t, err, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// Error requires that a function returned an error (i.e. not `nil`).\nfunc Error(t uassert.TestingT, err error, msgs ...string) {\n\tt.Helper()\n\tif uassert.Error(t, err, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// ErrorContains requires that a function returned an error (i.e. not `nil`)\n// and that the error contains the specified substring.\nfunc ErrorContains(t uassert.TestingT, err error, contains string, msgs ...string) {\n\tt.Helper()\n\tif uassert.ErrorContains(t, err, contains, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// True requires that the specified value is true.\nfunc True(t uassert.TestingT, value bool, msgs ...string) {\n\tt.Helper()\n\tif uassert.True(t, value, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// False requires that the specified value is false.\nfunc False(t uassert.TestingT, value bool, msgs ...string) {\n\tt.Helper()\n\tif uassert.False(t, value, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// ErrorIs requires that the given error matches the target error.\nfunc ErrorIs(t uassert.TestingT, err, target error, msgs ...string) {\n\tt.Helper()\n\tif uassert.ErrorIs(t, err, target, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// AbortsWithMessage requires that the code inside the specified func aborts\n// (panics when crossing another realm).\n// Use PanicsWithMessage for requiring local panics within the same realm.\n// Note: This relies on gno's `revive` mechanism to catch aborts.\n// See uassert.AbortsWithMessage for `rlm` semantics.\nfunc AbortsWithMessage(t uassert.TestingT, rlm realm, msg string, f any, msgs ...string) {\n\tt.Helper()\n\tif uassert.AbortsWithMessage(t, rlm, msg, f, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// AbortsContains requires that the code inside the specified func aborts\n// (panics when crossing another realm) and the abort message contains the specified substring.\n// See uassert.AbortsWithMessage for `rlm` semantics.\nfunc AbortsContains(t uassert.TestingT, rlm realm, substr string, f any, msgs ...string) {\n\tt.Helper()\n\tif uassert.AbortsContains(t, rlm, substr, f, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// NotAborts requires that the code inside the specified func does NOT abort\n// when crossing an execution boundary (e.g., VM call).\n// Use NotPanics for requiring the absence of local panics within the same realm.\n// Note: This relies on Gno's `revive` mechanism.\n// See uassert.AbortsWithMessage for `rlm` semantics.\nfunc NotAborts(t uassert.TestingT, rlm realm, f any, msgs ...string) {\n\tt.Helper()\n\tif uassert.NotAborts(t, rlm, f, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// PanicsWithMessage requires that the code inside the specified func panics\n// locally within the same execution realm.\n// Use AbortsWithMessage for requiring panics that cross execution boundaries (aborts).\n// See uassert.AbortsWithMessage for `rlm` semantics.\nfunc PanicsWithMessage(t uassert.TestingT, rlm realm, msg string, f any, msgs ...string) {\n\tt.Helper()\n\tif uassert.PanicsWithMessage(t, rlm, msg, f, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// PanicsContains requires that the code inside the specified func panics\n// locally within the same execution realm and the panic message contains the specified substring.\n// See uassert.AbortsWithMessage for `rlm` semantics.\nfunc PanicsContains(t uassert.TestingT, rlm realm, substr string, f any, msgs ...string) {\n\tt.Helper()\n\tif uassert.PanicsContains(t, rlm, substr, f, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// NotPanics requires that the code inside the specified func does NOT panic\n// locally within the same execution realm.\n// Use NotAborts for requiring the absence of panics that cross execution boundaries (aborts).\n// See uassert.AbortsWithMessage for `rlm` semantics.\nfunc NotPanics(t uassert.TestingT, rlm realm, f any, msgs ...string) {\n\tt.Helper()\n\tif uassert.NotPanics(t, rlm, f, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// Equal requires that two objects are equal.\nfunc Equal(t uassert.TestingT, expected, actual any, msgs ...string) {\n\tt.Helper()\n\tif uassert.Equal(t, expected, actual, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// NotEqual requires that two objects are not equal.\nfunc NotEqual(t uassert.TestingT, expected, actual any, msgs ...string) {\n\tt.Helper()\n\tif uassert.NotEqual(t, expected, actual, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// Empty requires that the specified object is empty\n// (zero value, empty string/slice/map, or nil).\nfunc Empty(t uassert.TestingT, obj any, msgs ...string) {\n\tt.Helper()\n\tif uassert.Empty(t, obj, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// NotEmpty requires that the specified object is not empty.\nfunc NotEmpty(t uassert.TestingT, obj any, msgs ...string) {\n\tt.Helper()\n\tif uassert.NotEmpty(t, obj, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// Nil requires that the value is nil.\nfunc Nil(t uassert.TestingT, value any, msgs ...string) {\n\tt.Helper()\n\tif uassert.Nil(t, value, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// NotNil requires that the value is not nil.\nfunc NotNil(t uassert.TestingT, value any, msgs ...string) {\n\tt.Helper()\n\tif uassert.NotNil(t, value, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// TypedNil requires that the value is a typed-nil (nil pointer) value.\nfunc TypedNil(t uassert.TestingT, value any, msgs ...string) {\n\tt.Helper()\n\tif uassert.TypedNil(t, value, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n\n// NotTypedNil requires that the value is not a typed-nil (nil pointer) value.\nfunc NotTypedNil(t uassert.TestingT, value any, msgs ...string) {\n\tt.Helper()\n\tif uassert.NotTypedNil(t, value, msgs...) {\n\t\treturn\n\t}\n\tt.FailNow()\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"draftrealm","path":"gno.land/r/demo/draftrealm","files":[{"name":"draftrealm.gno","body":"package draftrealm\n\n// this realm is an example of a draft realm\n// it can only be deployed and imported by packages added at genesis time\n\nfunc Render(path string) string {\n\treturn \"draft\"\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/draftrealm\"\ngno = \"0.9\"\ndraft = true\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"combinederr","path":"gno.land/p/nt/combinederr/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `combinederr` - Aggregate multiple errors\n\nCollect several errors into a single `error` value with a semicolon-separated message. Useful for batch operations where you want to report every failure instead of bailing on the first.\n\n## Usage\n\n```go\nimport \"gno.land/p/nt/combinederr/v0\"\n\nce := \u0026combinederr.CombinedError{}\nce.Add(validateName(name))   // nil is silently skipped\nce.Add(validateEmail(email))\nce.Add(validateAge(age))\n\nif ce.Size() \u003e 0 {\n    return ce // \"invalid name; bad email; age must be \u003e 0\"\n}\nreturn nil\n```\n\n## API\n\n```go\n// CombinedError aggregates multiple errors into a single error value.\ntype CombinedError struct { /* ... */ }\n\n// Add appends err to the combined error. Nil errors are ignored.\nfunc (e *CombinedError) Add(err error)\n\n// Error returns all collected errors joined with \"; \".\nfunc (e *CombinedError) Error() string\n\n// Size returns the number of collected errors.\nfunc (e *CombinedError) Size() int\n```\n\n## Notes\n\n- A zero-value `CombinedError{}` with no errors added has `Size() == 0` and `Error() == \"\"`.\n- The pointer receiver on `Add` means you must use `\u0026CombinedError{}`.\n- Aggregation is message-only: there is no `Unwrap`, so `errors.Is`/`errors.As` never see the collected errors. Use it when you want one human-readable combined string, not typed error matching.\n"},{"name":"combinederr.gno","body":"package combinederr\n\nimport \"strings\"\n\n// CombinedError is a combined execution error\ntype CombinedError struct {\n\terrors []error\n}\n\n// Error returns the combined execution error\nfunc (e *CombinedError) Error() string {\n\tif len(e.errors) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar sb strings.Builder\n\n\tfor _, err := range e.errors {\n\t\tsb.WriteString(err.Error() + \"; \")\n\t}\n\n\t// Remove the last semicolon and space\n\tresult := sb.String()\n\n\treturn result[:len(result)-2]\n}\n\n// Add adds a new error to the execution error\nfunc (e *CombinedError) Add(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\te.errors = append(e.errors, err)\n}\n\n// Size returns a\nfunc (e *CombinedError) Size() int {\n\treturn len(e.errors)\n}\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package combinederr provides a combined error type for aggregating multiple\n// errors into a single error value.\npackage combinederr\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/combinederr/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"authorizable","path":"gno.land/p/nt/ownable/exts/authorizable/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `authorizable` - Second authorization tier over ownable\n\nExtension of [`gno.land/p/nt/ownable/v0`](../..) that adds a second permission level on top of single-owner ownership: one **superuser** (the `ownable` owner) plus a list of **authorized** addresses. Use it for a moderator tier, an allowlist, or any \"owner, plus a set of trusted others\" pattern.\n\n## Usage\n\n```go\npackage myrealm\n\nimport (\n    \"chain/runtime\"\n\n    \"gno.land/p/nt/ownable/v0\"\n    \"gno.land/p/nt/ownable/exts/authorizable/v0\"\n)\n\n// The superuser (and first entry on the auth list) is chosen explicitly.\n// Here: the deployer, captured in init.\nvar auth *authorizable.Authorizable\n\nfunc init() {\n    caller := runtime.PreviousRealm()\n    if !caller.IsUserCall() {\n        panic(\"must be deployed by a user\")\n    }\n    auth = authorizable.New(ownable.NewWithAddress(caller.Address()))\n}\n\n// Superuser-only: add a moderator.\nfunc AddModerator(cur realm, addr address) error {\n    return auth.AddToAuthList(0, cur, addr)\n}\n\n// Gate an action to anyone on the auth list.\nfunc Moderate(cur realm) {\n    auth.AssertPreviousOnAuthList(0, cur)\n    // ... privileged work ...\n}\n```\n\n## API\n\n```go\ntype Authorizable struct {\n    *ownable.Ownable // the owner is the superuser; all Ownable methods are inherited\n    // unexported auth list\n}\n\n// New builds an Authorizable from an existing *ownable.Ownable.\n// The owner is automatically added to the auth list.\nfunc New(o *ownable.Ownable) *Authorizable\n\n// Superuser-only (previous caller must be the owner).\nfunc (a *Authorizable) AddToAuthList(_ int, rlm realm, addr address) error\nfunc (a *Authorizable) DeleteFromAuthList(_ int, rlm realm, addr address) error\n\n// Membership checks (return an error; nil means on the list).\nfunc (a *Authorizable) OnAuthList(_ int, rlm realm) error         // is the caller realm itself on the list\nfunc (a *Authorizable) PreviousOnAuthList(_ int, rlm realm) error // is the realm/user that crossed in on the list\n\n// Assert variants panic instead of returning an error.\nfunc (a Authorizable) AssertOnAuthList(_ int, rlm realm)\nfunc (a Authorizable) AssertPreviousOnAuthList(_ int, rlm realm)\n\n// Errors: ErrNotSuperuser, ErrNotInAuthList, ErrAlreadyInList\n```\n\n## Notes\n\n- Every method takes the caller's own captured `cur` as `rlm` and asserts `rlm.IsCurrent()`, blocking the designation-forgery read where a non-crossing wrapper makes the realm walk return the wrong address. The first `_ int` argument is an unused placeholder: pass `0`.\n- The superuser is authenticated by `rlm.Previous().Address()` matching the underlying `Ownable` owner, so `AddToAuthList` / `DeleteFromAuthList` succeed only when the owner is the crossing caller. Ownership transfer, renouncing, etc. come from the embedded [`Ownable`](../..).\n- `PreviousOnAuthList` / `AssertPreviousOnAuthList` are the user-facing gate: they check the address that crossed into your realm. `OnAuthList` checks the calling realm itself; use it only when a realm-to-realm caller should be listed directly.\n- The auth list is backed by a [`bptree`](../../../../bptree/v0), keyed by address string.\n"},{"name":"authorizable.gno","body":"// Package authorizable is an extension of p/nt/ownable;\n// It allows the user to instantiate an Authorizable struct, which extends\n// p/nt/ownable with a list of users that are authorized for something.\n// By using authorizable, you have a superuser (ownable), as well as another\n// authorization level, which can be used for adding moderators or similar to your realm.\npackage authorizable\n\nimport (\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype Authorizable struct {\n\t*ownable.Ownable                // owner in ownable is superuser\n\tauthorized       *bptree.BPTree // chain.Addr \u003e struct{}{}\n}\n\n// New creates an Authorizable from an existing *ownable.Ownable.\n// The owner is automatically added to the auth list.\n//\n// Example construction:\n//\n//\tauthorizable.New(ownable.NewWithAddress(addr))\nfunc New(o *ownable.Ownable) *Authorizable {\n\ta := \u0026Authorizable{\n\t\tOwnable:    o,\n\t\tauthorized: bptree.NewBPTree32(),\n\t}\n\n\t// Add owner to auth list\n\ta.authorized.Set(a.Owner().String(), struct{}{})\n\treturn a\n}\n\n// AddToAuthList adds addr to the auth list. rlm must be the caller's\n// own captured cur; rlm.Previous().Address() must equal the superuser\n// (the underlying Ownable's owner).\nfunc (a *Authorizable) AddToAuthList(_ int, rlm realm, addr address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrNotSuperuser\n\t}\n\tif !a.OwnedBy(rlm.Previous().Address()) {\n\t\treturn ErrNotSuperuser\n\t}\n\treturn a.addToAuthList(addr)\n}\n\nfunc (a *Authorizable) addToAuthList(addr address) error {\n\tif a.authorized.Has(addr.String()) {\n\t\treturn ErrAlreadyInList\n\t}\n\n\ta.authorized.Set(addr.String(), struct{}{})\n\n\treturn nil\n}\n\n// DeleteFromAuthList removes addr from the auth list. rlm must be the\n// caller's own captured cur; rlm.Previous().Address() must equal the\n// superuser (the underlying Ownable's owner).\nfunc (a *Authorizable) DeleteFromAuthList(_ int, rlm realm, addr address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrNotSuperuser\n\t}\n\tif !a.OwnedBy(rlm.Previous().Address()) {\n\t\treturn ErrNotSuperuser\n\t}\n\treturn a.deleteFromAuthList(addr)\n}\n\nfunc (a *Authorizable) deleteFromAuthList(addr address) error {\n\tif !a.authorized.Has(addr.String()) {\n\t\treturn ErrNotInAuthList\n\t}\n\n\tif _, removed := a.authorized.Remove(addr.String()); !removed {\n\t\tstr := ufmt.Sprintf(\"authorizable: could not remove %s from auth list\", addr.String())\n\t\tpanic(str)\n\t}\n\n\treturn nil\n}\n\n// OnAuthList reports whether rlm.Address() is on the auth list. rlm\n// must be the caller's own captured cur (asserted via rlm.IsCurrent()).\n// Pre-migration shape used unsafe.CurrentRealm().Address() — vulnerable\n// to the .Title()-class read where a non-crossing wrapper made the walk\n// return the wrong realm. Explicit rlm closes that.\nfunc (a *Authorizable) OnAuthList(_ int, rlm realm) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrNotInAuthList\n\t}\n\treturn a.onAuthList(rlm.Address())\n}\n\n// PreviousOnAuthList reports whether rlm.Previous().Address() — the\n// realm that crossed into the caller — is on the auth list. Same rlm\n// contract as OnAuthList.\nfunc (a *Authorizable) PreviousOnAuthList(_ int, rlm realm) error {\n\tif !rlm.IsCurrent() {\n\t\treturn ErrNotInAuthList\n\t}\n\treturn a.onAuthList(rlm.Previous().Address())\n}\n\nfunc (a *Authorizable) onAuthList(caller address) error {\n\tif !a.authorized.Has(caller.String()) {\n\t\treturn ErrNotInAuthList\n\t}\n\treturn nil\n}\n\nfunc (a Authorizable) AssertOnAuthList(_ int, rlm realm) {\n\tif err := a.OnAuthList(0, rlm); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (a Authorizable) AssertPreviousOnAuthList(_ int, rlm realm) {\n\tif err := a.PreviousOnAuthList(0, rlm); err != nil {\n\t\tpanic(err)\n\t}\n}\n"},{"name":"errors.gno","body":"package authorizable\n\nimport \"errors\"\n\nvar (\n\tErrNotInAuthList = errors.New(\"authorizable: caller is not in authorized list\")\n\tErrNotSuperuser  = errors.New(\"authorizable: caller is not superuser\")\n\tErrAlreadyInList = errors.New(\"authorizable: address is already in authorized list\")\n)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/ownable/exts/authorizable/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"valopers","path":"gno.land/r/gnops/valopers","files":[{"name":"admin.gno","body":"package valopers\n\nimport (\n\t\"gno.land/p/moul/authz/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\nvar auth *authz.Authorizer\n\n// Auth returns a read-only description of the realm's current governance\n// authority (for rendering / inspection). It renders as\n//\n//\tcontract_authority[contract=gno.land/r/gov/dao,proposer=contract-identity]\n//\n// i.e. \"GovDAO governs this realm, and only GovDAO may drive it\" — a\n// statement an on-chain reader can act on. The proposer half is\n// load-bearing: without it the string is byte-identical whether the\n// authority is gated or wide open (see ContractAuthority.String).\n//\n// It deliberately does NOT return the live *authz.Authorizer: an\n// exported handle to the authority would let any realm reach its\n// mutators (Transfer, DoByPrevious, ...) directly. Returning a\n// description instead of the handle keeps that surface unreachable from\n// here in the first place. Valoper.AuthOwner follows the same rule for\n// per-operator auth lists.\nfunc Auth() string {\n\treturn auth.String()\n}\n\n// updateInstructions is the realm's only privileged write. It authorizes\n// as the realm that CROSSED INTO valopers, not as valopers itself.\n//\n// Why DoByPrevious and not DoByCurrent: own-path + DoByCurrent is a\n// tautology (see NewContractAuthority's godoc for the mechanism, once).\n// `rlm.Previous()` is the caller — on the legitimate path r/gov/dao's\n// executor frame, which is what init.gno's authority is pointed at.\n//\n// What it buys: it is the code-level guard against this realm's most\n// likely regression, a maintainer later adding an exported crossing\n// entrypoint that reaches here. Under DoByCurrent such an entrypoint\n// authorizes for any caller; under DoByPrevious the caller's own address\n// is the principal and the gate rejects it. Pinned by\n// filetests/z_govdao_only_principal_filetest.gno.\n//\n// Two things it does NOT cover on its own, both closed elsewhere:\n// re-exporting the privileged closure (guarded by the seal in\n// NewInstructionsProposalRequest), and exporting a function whose\n// signature is assignable to dao's `func(realm) error` callback type,\n// which the proxy would invoke on an attacker's behalf. The second was a\n// live bypass of this gate until SimpleExecutor.Execute began rejecting\n// invocation from outside r/gov/dao (r/gov/dao/types.gno); keep BOTH\n// conditions in mind before adding an exported symbol here.\n//\n// Returns the authorization error rather than panicking on it. That matters\n// on the governance path: impl.ExecuteProposal turns an executor ERROR into\n// status Denied plus a DeniedReason, but it cannot see a panic — a panic\n// aborts the whole ExecuteProposal transaction, burning its gas and leaving\n// the proposal stuck Accepted, retryable forever and never deniable. The\n// refusal is currently unreachable on the approved route (Previous() there\n// is always r/gov/dao), but init.gno's handler is explicitly offered as the\n// seam for an intent check (timelock, quorum, audit trail), and the first\n// such check to return an error would hit exactly that.\nfunc updateInstructions(_ int, rlm realm, newInstructions string) error {\n\treturn auth.DoByPrevious(0, rlm, \"update-instructions\", func() error {\n\t\tinstructions = newInstructions\n\t\treturn nil\n\t})\n}\n\n// NewInstructionsProposalRequest builds the GovDAO proposal that rewrites\n// this realm's instructions. It replaces the previously exported\n// NewInstructionsProposalCallback.\n//\n// SECURITY: the privileged closure must never leave this package.\n//\n// The VM mints a crossing frame's `cur` from the CALLEE's declaring\n// package, so a closure declared here always runs with valopers'\n// identity no matter who invokes it — and whoever holds the closure\n// chooses its Previous() by wrapping it in an executor of their own.\n// Handing such a closure to a caller therefore hands out the ability to\n// satisfy this realm's gate whichever principal it is pointed at: the\n// handler in init.gno runs the action and `instructions` is rewritten\n// with no proposal and no vote. That is what the exported callback did.\n//\n// Returning a dao.ProposalRequest instead seals the capability: the\n// executor is an unexported field with no accessor (dao.ProposalRequest\n// exposes only Title/Description/Filter), so the only way to reach the\n// closure is for GovDAO to execute the proposal that contains it.\n//\n// Note this is deliberately stronger than returning a dao.Executor —\n// even a dao.NewSafeExecutor-wrapped one. Executor.Execute is an\n// exported method, so a returned Executor stays directly invocable by\n// its holder, and SafeExecutor's only gate (InAllowedDAOs) FAILS OPEN\n// while the allowedDAOs list is empty, which is the documented\n// bootstrap state (see r/gov/dao/loader/v0). A sealed request has no\n// such conditional.\n//\n// The rule for this realm: no exported function may return a crossing\n// closure, a dao.Executor, or anything else that carries valopers'\n// frame identity — and no exported function may itself BE such a thing,\n// i.e. have a signature assignable to dao's `func(realm) error` callback\n// type, since the proxy would then invoke it on an attacker's behalf.\n// filetests/z_foreign_realm_capability_filetest.gno pins the first;\n// filetests/z_govdao_only_principal_filetest.gno pins the second.\nfunc NewInstructionsProposalRequest(cur realm, newInstructions string) dao.ProposalRequest {\n\tcb := func(cur realm) error {\n\t\treturn updateInstructions(0, cur, newInstructions)\n\t}\n\n\ttitle := instructionsProposalTitle\n\tdescription := ufmt.Sprintf(\"Update the instructions to: \\n\\n%s\", newInstructions)\n\n\treturn dao.NewProposalRequest(title, description, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// instructionsProposalTitle is the on-chain title of the instructions\n// proposal, named as a constant so a test can pin it: it is rendered to\n// GovDAO voters and is the string off-chain tooling matches on. It was\n// \"/p/gnops/valopers: ...\" before this realm's proposal construction moved\n// here; the \"/p/\" was simply wrong (valopers is an /r/ realm).\nconst instructionsProposalTitle = \"/r/gnops/valopers: Update instructions\"\n\n// rotateAuthority replaces this realm's governance authority.\n//\n// Unexported, and reachable only through the sealed request built by\n// NewAuthorityRotationProposalRequest — same discipline as\n// updateInstructions, for the same reason.\n//\n// authz.Authorizer.Transfer derives its principal as\n// rlm.Previous().Address(), so inside a GovDAO-executed callback declared\n// here Previous() is r/gov/dao — exactly the principal init.gno's authority\n// asserts. No same-package cross() trick is needed.\nfunc rotateAuthority(_ int, rlm realm, newContractPath string) error {\n\treturn auth.Transfer(0, rlm, authz.NewContractAuthority(\n\t\tnewContractPath,\n\t\tfunc(_ string, action authz.PrivilegedAction) error {\n\t\t\treturn action()\n\t\t},\n\t))\n}\n\n// NewAuthorityRotationProposalRequest builds the GovDAO proposal that\n// re-points this realm's governance authority at `newContractPath`.\n//\n// WHY THIS EXISTS. Without it the authority installed by init.gno is\n// permanently frozen: nothing else calls auth.Transfer, Auth() returns a\n// description rather than the live Authorizer, and Transfer routes through\n// the authority's own gate — so if the asserted principal ever stops being\n// presentable, `instructions` becomes unwritable with no on-chain recovery.\n// That is not hypothetical: the r/gov/dao proxy path is a governance\n// artifact that can be superseded, and a well-formed but wrong path (say\n// the impl path instead of the proxy) is accepted at construction and dead\n// forever. Redeploying instead is expensive — r/sys/validators/v0/cache.gno\n// hardcodes `const valopersRealmPath`, so a new pkgpath means editing a\n// second genesis realm and re-registering every valoper. It must exist\n// before deploy, because code cannot be added to a deployed realm.\n//\n// WHY A PATH AND NOT AN authz.Authority. Taking an Authority would make\n// this an open-interface input (Class-3 impl-substitution): a proposal\n// could install an always-approve or always-deny authority, and readers of\n// Auth() could not tell from the rendered description alone. Taking a path\n// keeps the installed authority canonical by construction — always a\n// ContractAuthority with the pass-through handler and the contract-identity\n// gate — so the only thing governance can change is WHICH principal is\n// asserted. The path is validated by authz.NewContractAuthority, which\n// panics on a malformed one, aborting the proposal execution rather than\n// bricking the realm.\n//\n// This remains a privileged surface: a majority that can pass this proposal\n// can point the authority at a principal it controls. That is the same\n// power a majority already has over `instructions`, and it is the price of\n// being recoverable at all.\nfunc NewAuthorityRotationProposalRequest(cur realm, newContractPath string) dao.ProposalRequest {\n\tcb := func(cur realm) error {\n\t\treturn rotateAuthority(0, cur, newContractPath)\n\t}\n\n\ttitle := \"/r/gnops/valopers: Rotate governance authority\"\n\tdescription := ufmt.Sprintf(\n\t\t\"Re-point the valopers governance authority at: \\n\\n%s\\n\\n\"+\n\t\t\t\"The authority stays a contract-identity ContractAuthority; only the asserted principal changes.\",\n\t\tnewContractPath,\n\t)\n\n\treturn dao.NewProposalRequest(title, description, dao.NewSimpleExecutor(0, cur, cb, \"\"))\n}\n\n// NewInstructionsProposalCallback was removed, not deprecated: it was the\n// capability leak described above, so an inert shim would be pointless and\n// a working one would reopen the hole. Precedent + replay check: the\n// min-fee callback below was already removed the same way even though it\n// HAD been used on gnoland1 (GovDAO Prop #19), whereas the instructions\n// callback has no on-chain trace at all — the live realm's instructions\n// are byte-identical to the genesis default and none of gnoland1's 26\n// GovDAO proposals is an \"Update instructions\" one.\n//\n// The min-fee callback was removed: the fee now lives in sysparams\n// under node:valoper:register_fee, and\n// proposal.ProposeNewMinFeeProposalRequest delegates to\n// sys/params.NewSysParamUint64PropRequest. Removing avoids the\n// forward-compat hazard of a no-op shim with no caller-auth gating.\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/gnops/valopers\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"\n"},{"name":"init.gno","body":"package valopers\n\nimport (\n\t\"gno.land/p/moul/authz/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nfunc init() {\n\tvalopers = avl.NewTree()\n\n\t// The authority is pointed at GovDAO, NOT at this realm.\n\t//\n\t// Pointing it here instead would make the gate compare valopers'\n\t// address to valopers' address: every crossing frame of this package\n\t// has rlm.Address() == PackageAddress(ownPath), so the check could\n\t// never reject. Pointed at r/gov/dao and driven by DoByPrevious\n\t// (see updateInstructions), the principal is the realm that crossed\n\t// in — GovDAO's executor on the legitimate path, and the caller\n\t// itself on any other, which is what makes the check real.\n\t//\n\t// The handler is a pass-through: this is where an intent check\n\t// (timelock, quorum, audit trail) would go if one is ever wanted.\n\t// It is NOT where the caller check lives — that is the authority's\n\t// contract-identity gate, upstream of here.\n\tauth = authz.NewWithAuthority(\n\t\tauthz.NewContractAuthority(\n\t\t\t\"gno.land/r/gov/dao\",\n\t\t\tfunc(_ string, action authz.PrivilegedAction) error {\n\t\t\t\treturn action()\n\t\t\t},\n\t\t),\n\t)\n\n\tinstructions = `\n# Welcome to the **Valopers** realm\n\n## 📌 Purpose of this Contract\n\nThe **Valopers** contract is designed to maintain a registry of **validator profiles**. This registry provides essential information to **GovDAO members**, enabling them to make informed decisions when voting on the inclusion of new validators into the **valset**.\n\nBy registering your validator profile, you contribute to a transparent and well-informed governance process within **gno.land**.\n\n---\n\n## 📝 How to Register Your Validator Node\n\nTo add your validator node to the registry, use the [**Register**](` + txlink.Call(\"Register\") + `) function with the following parameters:\n\n- **Moniker** (Validator Name)\n  - Must be **human-readable**\n  - **Max length**: **32 characters**\n  - **Allowed characters**: Letters, numbers, spaces, hyphens (**-**), and underscores (**_**)\n  - **No special characters** at the beginning or end\n\n- **Description** (Introduction \u0026 Validator Details)\n  - **Max length**: **2048 characters**\n  - Must include answers to the questions listed below\n\n- **Server Type** (Infrastructure Type)\n  - Must be one of the following values:\n    - **cloud**: For validators running on cloud infrastructure (AWS, GCP, Azure, etc.)\n    - **on-prem**: For validators running on on-premises infrastructure\n    - **data-center**: For validators running in dedicated data centers\n\n- **Operator Address**\n  - The ` + \"`g1...`\" + ` address of your operator account (from your ` + \"`gnokey`\" + ` keyring)\n  - **Must be controlled by the signer** of this transaction — the realm rejects the call if the signer doesn't control that address\n\n- **Validator Consensus Public Key**\n  - Your validator node's consensus public key, in the ` + \"`gpub1...`\" + ` format\n  - Retrieve it by running: ` + \"`gnoland secrets get validator_key`\" + `\n\n### ✍️ Required Information for the Description\n\nPlease provide detailed answers to the following questions to ensure transparency and improve your chances of being accepted:\n\n1. The name of your validator\n2. Networks you are currently validating and your total AuM (assets under management)\n3. Links to your **digital presence** (website, social media, etc.). Please include your Discord handle to be added to our main comms channel, the gno.land valoper Discord channel.\n4. Contact details\n5. Why are you interested in validating on **gno.land**?\n6. What contributions have you made or are willing to make to **gno.land**?\n\n---\n\n## 🔄 Updating Your Validator Information\n\nAfter registration, you can update your validator details using the **update functions** provided by the contract.\n\n---\n\n## 📢 Submitting a Proposal to Join the Validator Set\n\nOnce you're satisfied with your **valoper** profile, you need to notify GovDAO; only a GovDAO member can submit a proposal to add you to the validator set.\n\nIf you are a GovDAO member, you can nominate yourself by executing the following function: [**r/gnops/valopers/proposal.ProposeNewValidator**](` + txlink.Realm(\"gno.land/r/gnops/valopers/proposal\").Call(\"ProposeNewValidator\") + `)\n\nThis will initiate a governance process where **GovDAO** members will vote on your proposal.\n\n---\n\n🚀 **Register now and become a part of gno.land’s validator ecosystem!**\n\nRead more: [How to become a validator](https://github.com/gnolang/gno/tree/master/gno.land/cmd/gnoland#become-a-validator)\n\nDisclaimer: Please note, registering your validator profile and/or validating on testnets does not guarantee a validator slot on the gno.land beta mainnet. However, active participation and contributions to testnets will help establish credibility and may improve your chances for future validator acceptance. The initial validator amount and valset will ultimately be selected through GovDAO governance proposals and acceptance.\n\n---\n\n`\n}\n"},{"name":"valopers.gno","body":"// Package valopers is designed around the permissionless lifecycle of valoper profiles.\npackage valopers\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"crypto/bech32\"\n\t\"errors\"\n\t\"math\"\n\t\"regexp\"\n\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/nt/avl/pager/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/combinederr/v0\"\n\t\"gno.land/p/nt/ownable/exts/authorizable/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\tsysparams \"gno.land/r/sys/params\"\n\tvalidators \"gno.land/r/sys/validators/v0\"\n)\n\nconst (\n\tMonikerMaxLength     = 32\n\tDescriptionMaxLength = 2048\n\n\t// Valid server types\n\tServerTypeCloud      = \"cloud\"\n\tServerTypeOnPrem     = \"on-prem\"\n\tServerTypeDataCenter = \"data-center\"\n)\n\nvar (\n\tErrValoperExists        = errors.New(\"valoper already exists\")\n\tErrValoperMissing       = errors.New(\"valoper does not exist\")\n\tErrInvalidAddress       = errors.New(\"invalid address\")\n\tErrInvalidMoniker       = errors.New(\"moniker is not valid\")\n\tErrInvalidDescription   = errors.New(\"description is not valid\")\n\tErrInvalidServerType    = errors.New(\"server type is not valid\")\n\tErrOperatorSquatGuard   = errors.New(\"post-genesis: caller must equal operator address\")\n\tErrSigningKeyTaken      = errors.New(\"signing address already in registry (active or retired)\")\n\tErrFrontrunValidator    = errors.New(\"post-genesis: signing address is already an active validator\")\n\tErrRotationThrottled    = errors.New(\"rotation throttled: try again later\")\n\tErrRegistryEntryMissing = errors.New(\"signing address has no active registry entry (corrupted state)\")\n\tErrPaidCallNotDirect    = errors.New(\"a fee is configured: call this directly as a user (maketx call), not from a realm or a maketx run script\")\n\tErrFeeParamOutOfRange   = errors.New(\"configured fee exceeds the maximum representable coin amount\")\n\tErrDisallowedPubKeyType = errors.New(\"consensus pubkey type is not allowed for validators\")\n)\n\nvar (\n\tvalopers     *avl.Tree // operator-address -\u003e Valoper\n\tinstructions string    // markdown instructions for valoper's registration\n\n\t// signingRegistry maps SigningAddress.String() -\u003e regEntry.\n\t// Permanently retains retired entries to prevent key reuse and\n\t// to support future slashing-attribution by signing address.\n\tsigningRegistry = bptree.NewBPTree32()\n\n\tmonikerMaxLengthMiddle = ufmt.Sprintf(\"%d\", MonikerMaxLength-2)\n\tvalidateMonikerRe      = regexp.MustCompile(`^[a-zA-Z0-9][\\w -]{0,` + monikerMaxLengthMiddle + `}[a-zA-Z0-9]$`) // 32 characters, including spaces, hyphens or underscores in the middle\n)\n\n// regEntry tracks signing-address -\u003e operator with retirement metadata.\n// retiredAtHeight == 0 means the entry is currently active for the operator.\ntype regEntry struct {\n\tOperatorAddress    address\n\tRegisteredAtHeight int64\n\tRetiredAtHeight    int64\n}\n\n// Valoper represents a validator operator profile.\ntype Valoper struct {\n\tMoniker     string // A human-readable name\n\tDescription string // A description and details about the valoper\n\tServerType  string // The type of server (cloud/on-prem/data-center)\n\n\tOperatorAddress address // operator identity, profile key, stable across rotations\n\tSigningPubKey   string  // current consensus signing pubkey (bech32 gpub1...)\n\tSigningAddress  address // = chain.PubKeyAddress(SigningPubKey)\n\n\tLastRotationHeight int64 // throttle anchor for UpdateSigningKey\n\n\tKeepRunning bool // operator wants this validator running in the active set\n\n\tauth *authorizable.Authorizable\n}\n\n// AuthOwner returns the operator address that owns this profile's auth\n// list. Read-only by construction: it copies out an address rather than\n// returning the live *authorizable.Authorizable.\n//\n// SECURITY: the previous `Auth() *authorizable.Authorizable` was a\n// capability leak of the same class this realm's governance authority\n// closes by returning a description instead of the live authority.\n// `Valoper` is returned BY VALUE from the exported, non-crossing\n// GetByAddr, but `auth` is a pointer field, so the copy shared the\n// callee's Authorizable. Any realm could therefore obtain a live,\n// mutable handle and write through it.\n//\n// That was a privilege escalation, not merely a wider surface.\n// Authorizable's gates read `rlm.Previous().Address()`, so inside a\n// hostile realm's frame `Previous()` is whoever called it. When a\n// valoper OPERATOR called any function of a hostile realm (faucet,\n// airdrop, mint), that realm could reach\n// `GetByAddr(operator).Auth().AddToAuthList(...)` and — because\n// Previous() was then the operator, the Authorizable's own owner —\n// persist itself onto the operator's auth list. From the next\n// transaction on it acted alone: UpdateKeepRunning to drain the\n// validator, UpdateSigningKey to rotate the consensus key.\n//\n// The exported wrappers below are NOT equivalent to the raw handle and\n// were never the hole: there `cur.Previous()` is the hostile realm\n// itself rather than the operator, so the owner check rejects it.\nfunc (v Valoper) AuthOwner() address {\n\treturn v.auth.Owner()\n}\n\nfunc AddToAuthList(cur realm, addr address, member address) {\n\tv := GetByAddr(addr)\n\tif err := v.auth.AddToAuthList(0, cur, member); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc DeleteFromAuthList(cur realm, addr address, member address) {\n\tv := GetByAddr(addr)\n\tif err := v.auth.DeleteFromAuthList(0, cur, member); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Register registers a new valoper. The `addr` parameter is the\n// operator address (stable identity, profile key); `pubKey` is the\n// consensus signing pubkey, from which the signing address is derived.\n//\n// Auth shape:\n//   - Post-genesis: OriginCaller must equal addr (operator-slot squat\n//     guard). Genesis-mode replay (ChainHeight()==0) bypasses, so\n//     migration .jsonl txs and historical Register replays succeed.\n//   - Signing-address uniqueness: derived(pubKey) must not already be\n//     in signingRegistry, active or retired.\n//   - Front-running guard: post-genesis, derived(pubKey) must not\n//     already be an active validator (a fresh registration cannot\n//     squat on the consensus address of an existing validator).\n//\n// Why OriginCaller==addr is sufficient for the SQUAT guard (no\n// IsUserCall): squatting requires the attacker to satisfy\n// OriginCaller==victim, which requires the victim's signing key.\n//\n// The PAYMENT check is a different matter and does need IsUserCall —\n// see assertPaidCallIsDirect. An earlier version of this comment\n// claimed the fee was \"validated against banker.OriginSend in a way\n// that's symmetric to IsUserCall via direct comparison\"; there was no\n// such comparison, and the fee was bypassable (reported by @D4ryl00).\n//\n// Auth-list seeding: the profile's Authorizable owner is set to addr\n// (NOT OriginCaller). At H\u003e0 the squat guard makes them equal anyway;\n// at H==0 the deployer pattern (one signer registers many operators)\n// requires owner == addr so each operator can manage their own profile\n// post-genesis without needing the deployer's auth.\nfunc Register(cur realm, moniker string, description string, serverType string, addr address, pubKey string) {\n\t// Operator-slot squat guard.\n\tif runtime.ChainHeight() \u003e 0 \u0026\u0026 unsafe.OriginCaller() != addr {\n\t\tpanic(ErrOperatorSquatGuard)\n\t}\n\n\t// Fee enforcement (read from sysparams; defaults to 0 until\n\t// governance raises it post-transfer-enablement).\n\tif fee := sysparams.GetValoperRegisterFee(); fee \u003e 0 {\n\t\tassertPaidCallIsDirect(0, cur)\n\t\tminFee := minFeeCoin(fee)\n\t\tsentCoins := unsafe.OriginSend()\n\t\tif len(sentCoins) != 1 || sentCoins[0].IsLT(minFee) {\n\t\t\tpanic(ufmt.Sprintf(\"payment must not be less than %d%s\", minFee.Amount, minFee.Denom))\n\t\t}\n\t}\n\n\t// Check if the valoper is already registered.\n\tif isValoper(addr) {\n\t\tpanic(ErrValoperExists)\n\t}\n\n\t// Reject disallowed key types early (else the EndBlocker drops it silently).\n\tassertPubKeyTypeAllowed(pubKey)\n\n\t// Derive the consensus signing address from the pubkey.\n\tsigningAddr, err := chain.PubKeyAddress(pubKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Signing-address uniqueness across all profiles, ever.\n\tif signingRegistry.Has(signingAddr.String()) {\n\t\tpanic(ErrSigningKeyTaken)\n\t}\n\n\t// Front-running guard: post-genesis, the signing address must\n\t// not already be an active validator.\n\tif runtime.ChainHeight() \u003e 0 \u0026\u0026 validators.IsValidator(signingAddr) {\n\t\tpanic(ErrFrontrunValidator)\n\t}\n\n\tv := Valoper{\n\t\tMoniker:            moniker,\n\t\tDescription:        description,\n\t\tServerType:         serverType,\n\t\tOperatorAddress:    addr,\n\t\tSigningPubKey:      pubKey,\n\t\tSigningAddress:     signingAddr,\n\t\tLastRotationHeight: runtime.ChainHeight(),\n\t\tKeepRunning:        true,\n\t\tauth:               authorizable.New(ownable.NewWithAddress(addr)),\n\t}\n\n\tif err := v.Validate(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Save the valoper to the set.\n\tvalopers.Set(v.OperatorAddress.String(), v)\n\n\t// Insert into the signing-address registry.\n\tsigningRegistry.Set(signingAddr.String(), regEntry{\n\t\tOperatorAddress:    addr,\n\t\tRegisteredAtHeight: runtime.ChainHeight(),\n\t\tRetiredAtHeight:    0,\n\t})\n\n\t// Refresh v0's cache for this operator.\n\tvalidators.NotifyValoperChanged(cross(cur), addr, v.SigningPubKey, v.SigningAddress, v.KeepRunning)\n}\n\n// UpdateMoniker updates an existing valoper's moniker.\nfunc UpdateMoniker(cur realm, addr address, moniker string) {\n\t// Check that the moniker is not empty.\n\tif err := validateMoniker(moniker); err != nil {\n\t\tpanic(err)\n\t}\n\n\tv := GetByAddr(addr)\n\n\t// Check that the caller has permissions.\n\tv.auth.AssertPreviousOnAuthList(0, cur)\n\n\t// Update the moniker.\n\tv.Moniker = moniker\n\n\t// Save the valoper info.\n\tvalopers.Set(addr.String(), v)\n}\n\n// UpdateDescription updates an existing valoper's description.\nfunc UpdateDescription(cur realm, addr address, description string) {\n\t// Check that the description is not empty.\n\tif err := validateDescription(description); err != nil {\n\t\tpanic(err)\n\t}\n\n\tv := GetByAddr(addr)\n\n\t// Check that the caller has permissions.\n\tv.auth.AssertPreviousOnAuthList(0, cur)\n\n\t// Update the description.\n\tv.Description = description\n\n\t// Save the valoper info.\n\tvalopers.Set(addr.String(), v)\n}\n\n// UpdateKeepRunning updates an existing valoper's active status.\n// Calls v0.NotifyValoperChanged because the cache stores KeepRunning.\nfunc UpdateKeepRunning(cur realm, addr address, keepRunning bool) {\n\tv := GetByAddr(addr)\n\n\t// Check that the caller has permissions.\n\tv.auth.AssertPreviousOnAuthList(0, cur)\n\n\t// Update status.\n\tv.KeepRunning = keepRunning\n\n\t// Save the valoper info.\n\tvalopers.Set(addr.String(), v)\n\n\t// Refresh v0's cache (KeepRunning is one of the cached fields).\n\tvalidators.NotifyValoperChanged(cross(cur), addr, v.SigningPubKey, v.SigningAddress, v.KeepRunning)\n}\n\n// UpdateServerType updates an existing valoper's server type.\nfunc UpdateServerType(cur realm, addr address, serverType string) {\n\t// Check that the server type is valid.\n\tif err := validateServerType(serverType); err != nil {\n\t\tpanic(err)\n\t}\n\n\tv := GetByAddr(addr)\n\n\t// Check that the caller has permissions.\n\tv.auth.AssertPreviousOnAuthList(0, cur)\n\n\t// Update server type.\n\tv.ServerType = serverType\n\n\t// Save the valoper info.\n\tvalopers.Set(addr.String(), v)\n}\n\n// UpdateSigningKey rotates an operator's consensus signing key.\n//\n// Auth: caller must be on the operator's auth list (defaults to\n// operator at Register time; extendable via AddToAuthList).\n//\n// Invariants checked at entry:\n//   - throttle: ChainHeight() - v.LastRotationHeight \u003e=\n//     rotationPeriodBlocks\n//   - signingRegistry uniqueness: derived(newPubKey) not in registry\n//     (active OR retired); permanently blocks key reuse\n//   - fee: unsafe.OriginSend() \u003e= rotationFee (mirrors Register's\n//     fee-check pattern)\n//\n// Effect: profile's SigningPubKey/SigningAddress/LastRotationHeight\n// updated; old registry entry marked retired (retiredAtHeight =\n// ChainHeight()); new entry inserted into signingRegistry; v0 emits\n// remove+add to sysparams via RotateValoperSigningKey; v0 cache\n// refreshed via NotifyValoperChanged. Rotation lands in consensus\n// at H+2.\n//\n// Atomicity: Gno tx atomicity rolls back all state if any step\n// panics. If v0.RotateValoperSigningKey panics, the registry insert\n// and profile mutation revert with it.\nfunc UpdateSigningKey(cur realm, addr address, newPubKey string) {\n\tv := GetByAddr(addr)\n\n\t// Auth: caller must be on operator's auth list.\n\tv.auth.AssertPreviousOnAuthList(0, cur)\n\n\t// Throttle: limit one rotation per rotation_period_blocks per\n\t// operator (per profile, not per caller — multi-member auth lists\n\t// can't multiplicative-rotate).\n\theight := runtime.ChainHeight()\n\tif height-v.LastRotationHeight \u003c sysparams.GetValoperRotationPeriodBlocks() {\n\t\tpanic(ErrRotationThrottled)\n\t}\n\n\t// Fee: enforce only if non-zero (matches Register's pattern;\n\t// rotation_fee defaults to zero pre-transfer-enablement).\n\tif fee := sysparams.GetValoperRotationFee(); fee \u003e 0 {\n\t\tassertPaidCallIsDirect(0, cur)\n\t\tminFee := minFeeCoin(fee)\n\t\tsentCoins := unsafe.OriginSend()\n\t\tif len(sentCoins) != 1 || sentCoins[0].IsLT(minFee) {\n\t\t\tpanic(ufmt.Sprintf(\"payment must not be less than %d%s\", minFee.Amount, minFee.Denom))\n\t\t}\n\t}\n\n\t// Reject disallowed key types early (else the EndBlocker drops it silently).\n\tassertPubKeyTypeAllowed(newPubKey)\n\n\t// Derive the new signing address from the new pubkey.\n\tnewSigningAddr, err := chain.PubKeyAddress(newPubKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// signingRegistry uniqueness: new key must not have ever been\n\t// registered (active or retired).\n\tif signingRegistry.Has(newSigningAddr.String()) {\n\t\tpanic(ErrSigningKeyTaken)\n\t}\n\n\t// Front-running guard: the derived signing address must not already\n\t// be an active validator. Mirrors the same guard in Register\n\t// (ErrFrontrunValidator). signingRegistry uniqueness above only\n\t// blocks signing addresses that previously went through Register or\n\t// UpdateSigningKey — genesis-seeded validators bypassed both, so\n\t// their signing addresses are absent from signingRegistry. Without\n\t// this check, a valoper could rotate onto such a slot and hijack\n\t// it: v0.RotateValoperSigningKey would overwrite the active entry\n\t// with this operator's claim, and a subsequent govDAO remove-op\n\t// proposal would then delete it.\n\tif validators.IsValidator(newSigningAddr) {\n\t\tpanic(ErrFrontrunValidator)\n\t}\n\n\t// Remember the previous signing key for the v0 cross-call.\n\toldPubKey := v.SigningPubKey\n\toldSigningAddr := v.SigningAddress\n\n\t// Mark the old registry entry retired. The entry must exist —\n\t// it was inserted at Register time.\n\trawOld := signingRegistry.Get(oldSigningAddr.String())\n\tif rawOld == nil {\n\t\tpanic(ErrRegistryEntryMissing)\n\t}\n\toldEntry := rawOld.(regEntry)\n\toldEntry.RetiredAtHeight = height\n\tsigningRegistry.Set(oldSigningAddr.String(), oldEntry)\n\n\t// Insert the new entry as active.\n\tsigningRegistry.Set(newSigningAddr.String(), regEntry{\n\t\tOperatorAddress:    addr,\n\t\tRegisteredAtHeight: height,\n\t\tRetiredAtHeight:    0,\n\t})\n\n\t// Update the profile.\n\tv.SigningPubKey = newPubKey\n\tv.SigningAddress = newSigningAddr\n\tv.LastRotationHeight = height\n\tvalopers.Set(addr.String(), v)\n\n\t// Apply to consensus via v0, then refresh v0's cache view of the\n\t// profile. Order matters only in that both must complete; tx\n\t// atomicity rolls back together on any panic.\n\tvalidators.RotateValoperSigningKey(cross(cur), addr, oldPubKey, newPubKey)\n\tvalidators.NotifyValoperChanged(cross(cur), addr, v.SigningPubKey, v.SigningAddress, v.KeepRunning)\n}\n\n// GetByAddr fetches the valoper using the operator address, if present.\nfunc GetByAddr(addr address) Valoper {\n\tvaloperRaw := valopers.Get(addr.String())\n\tif valoperRaw == nil {\n\t\tpanic(ErrValoperMissing)\n\t}\n\n\treturn valoperRaw.(Valoper)\n}\n\n// Render renders the current valoper set.\n// \"/r/gnops/valopers\" lists all valopers, paginated.\n// \"/r/gnops/valopers:addr\" shows the detail for the valoper with the addr.\nfunc Render(fullPath string) string {\n\treq := realmpath.Parse(fullPath)\n\tif req.Path == \"\" {\n\t\treturn renderHome(fullPath)\n\t} else {\n\t\taddr := req.Path\n\t\tif len(addr) \u003c 2 || addr[:2] != \"g1\" {\n\t\t\treturn \"invalid address \" + addr\n\t\t}\n\t\tvaloperRaw := valopers.Get(addr)\n\t\tif valoperRaw == nil {\n\t\t\treturn \"unknown address \" + addr\n\t\t}\n\t\tv := valoperRaw.(Valoper)\n\t\treturn \"Valoper's details:\\n\" + v.Render()\n\t}\n}\n\nfunc renderHome(path string) string {\n\t// if there are no valopers, display instructions\n\tif valopers.Size() == 0 {\n\t\treturn ufmt.Sprintf(\"%s\\n\\nNo valopers to display.\", instructions)\n\t}\n\n\tpage := pager.NewPager(valopers, 50, false).MustGetPageByPath(path)\n\n\toutput := \"\"\n\n\t// if we are on the first page, display instructions\n\tif page.PageNumber == 1 {\n\t\toutput += ufmt.Sprintf(\"%s\\n\\n\", instructions)\n\t}\n\n\tfor _, item := range page.Items {\n\t\tv := item.Value.(Valoper)\n\t\toutput += ufmt.Sprintf(\" * [%s](/r/gnops/valopers:%s) - [profile](/r/demo/profile:u/%s)\\n\",\n\t\t\tv.Moniker, v.OperatorAddress, v.OperatorAddress)\n\t}\n\n\toutput += \"\\n\"\n\toutput += page.Picker(path)\n\treturn output\n}\n\n// Validate checks if the fields of the Valoper are valid.\nfunc (v *Valoper) Validate() error {\n\terrs := \u0026combinederr.CombinedError{}\n\n\terrs.Add(validateMoniker(v.Moniker))\n\terrs.Add(validateDescription(v.Description))\n\terrs.Add(validateServerType(v.ServerType))\n\terrs.Add(validateBech32(v.OperatorAddress))\n\terrs.Add(validatePubKey(v.SigningPubKey))\n\n\tif errs.Size() == 0 {\n\t\treturn nil\n\t}\n\n\treturn errs\n}\n\n// Render renders a single valoper with their information.\nfunc (v Valoper) Render() string {\n\toutput := ufmt.Sprintf(\"## %s\\n\", v.Moniker)\n\n\tif v.Description != \"\" {\n\t\toutput += ufmt.Sprintf(\"%s\\n\\n\", v.Description)\n\t}\n\n\toutput += ufmt.Sprintf(\"- Operator Address: %s\\n\", v.OperatorAddress.String())\n\toutput += ufmt.Sprintf(\"- Signing Address: %s\\n\", v.SigningAddress.String())\n\toutput += ufmt.Sprintf(\"- Signing PubKey: %s\\n\", v.SigningPubKey)\n\toutput += ufmt.Sprintf(\"- Server Type: %s\\n\\n\", v.ServerType)\n\toutput += ufmt.Sprintf(\"[Profile link](/r/demo/profile:u/%s)\\n\", v.OperatorAddress)\n\n\treturn output\n}\n\n// isValoper checks if the valoper exists.\nfunc isValoper(addr address) bool {\n\treturn valopers.Has(addr.String())\n}\n\n// validateMoniker checks if the moniker is valid.\nfunc validateMoniker(moniker string) error {\n\tif moniker == \"\" {\n\t\treturn ErrInvalidMoniker\n\t}\n\n\tif len(moniker) \u003e MonikerMaxLength {\n\t\treturn ErrInvalidMoniker\n\t}\n\n\tif !validateMonikerRe.MatchString(moniker) {\n\t\treturn ErrInvalidMoniker\n\t}\n\n\treturn nil\n}\n\n// validateDescription checks if the description is valid.\nfunc validateDescription(description string) error {\n\tif description == \"\" {\n\t\treturn ErrInvalidDescription\n\t}\n\n\tif len(description) \u003e DescriptionMaxLength {\n\t\treturn ErrInvalidDescription\n\t}\n\n\treturn nil\n}\n\n// validateBech32 checks if the value is a valid bech32 address.\nfunc validateBech32(addr address) error {\n\tif !addr.IsValid() {\n\t\treturn ErrInvalidAddress\n\t}\n\n\treturn nil\n}\n\n// validatePubKey checks if the public key is valid.\nfunc validatePubKey(pubKey string) error {\n\tif _, _, err := bech32.DecodeNoLimit(pubKey); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// assertPaidCallIsDirect requires the immediate caller to be a plain EOA,\n// and must be paired with every unsafe.OriginSend() amount check in this\n// realm. Called only when a fee is actually configured.\n//\n// unsafe.OriginSend() reports the transaction's declared send ENVELOPE, not\n// what this realm received. Only a direct `maketx call` on valopers credits\n// the envelope to this realm's address. For a `maketx run` the keeper sets\n// pkgAddr := caller (gno.land/pkg/sdk/vm/keeper.go), so the coins move from\n// the caller to the caller and never land anywhere at all, while\n// OriginSend() still reports the full amount to us. See\n// gno.land/adr/pr6062_payable_send_check.md: \"MsgRun is exempt: the coins\n// are moved from the caller to the caller, so nothing actually moves.\" So\n// the amount check alone verifies intent, never receipt.\n//\n// Reported by @D4ryl00, with a local-chain reproduction:\n// governance sets register_fee to 1000ugnot, an operator runs a script\n// calling Register with `-send 1000ugnot`, registration succeeds, valopers\n// receives zero, and the operator still holds the coins. No hostile script\n// is needed — the envelope is free by construction. Both fees default to 0,\n// so nothing was live.\n//\n// Why IsUserCall and not an address comparison: a run script's realm is\n// address-INDISTINGUISHABLE from its user. Inside `main(cur realm)` the\n// ephemeral realm's own address IS the caller's EOA address, so every\n// address-based guard in this realm accepts a `maketx run` — Register's\n// squat guard (OriginCaller == addr) and UpdateSigningKey's auth-list check\n// (Previous().Address() on the list) both pass. Only the pkgPath differs,\n// and IsUserCall() is the check that reads it. It is therefore the only\n// PreviousRealm shape where the envelope is guaranteed to have landed here:\n// it excludes intermediate code realms and user-run ephemeral realms alike.\n// Same reasoning and same pairing as r/sys/namereg/v0.Register, which reads\n// OriginSend for its anti-squatting payment; see the two-guard comment there.\n//\n// Deliberately inside the `fee \u003e 0` branch rather than at the top of the\n// function: while a fee is unset there is no payment to establish receipt\n// of, and gating unconditionally would break the operator-authored\n// `maketx run` flows that the squat guard is happy to accept. The\n// restriction appears exactly when, and only when, money is involved.\n//\n// KNOWN LIMIT. AddToAuthList takes a plain `member address`, so a REALM\n// can sit on an operator's auth list, and once rotation_fee is nonzero\n// such a member can no longer drive UpdateSigningKey — it is not a user\n// call. An EOA rotation bot is unaffected, which is the shape the\n// auth-list docs describe (\"HSM-bound or rotation-bot\"), so nothing\n// documented breaks; a realm-mediated rotation would.\n//\n// The alternative that would keep realms working is a true receipt check:\n// track cumulative fees in realm state and require the realm's own\n// balance to have risen by `fee` since the last one. That works for any\n// caller shape, but it puts new persisted state and a banker into a\n// genesis realm, and lets anyone pre-pay another operator's fee by\n// donating to the realm address. Not worth it while both fees are 0 and\n// collected fees are unwithdrawable anyway (this realm has no banker, so\n// they strand at its address). Revisit if a realm-mediated paid rotation\n// is ever actually wanted.\nfunc assertPaidCallIsDirect(_ int, rlm realm) {\n\t// IsCurrent before Previous, as AGENTS.md requires and every other\n\t// (_ int, rlm realm) helper in this tree does (authorizable,\n\t// sys/params/delegate, gov/dao/types, sys/validators/v0/cache).\n\t// Both call sites pass their live cur, so this is defense-in-depth\n\t// against a future caller threading a stale or stashed realm value:\n\t// Previous() reads the prev field verbatim, so on a non-live token\n\t// it answers for the wrong frame.\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrPaidCallNotDirect)\n\t}\n\tif !rlm.Previous().IsUserCall() {\n\t\tpanic(ErrPaidCallNotDirect)\n\t}\n}\n\n// minFeeCoin converts a configured fee (uint64, from sysparams) into the\n// ugnot Coin the amount checks compare against.\n//\n// Coin.Amount is an int64. A fee above MaxInt64 wraps negative, and\n// `sentCoins[0].IsLT(minFee)` is then false for every payment — the realm\n// reads the fee as configured, runs assertPaidCallIsDirect, and collects\n// 1ugnot while reporting \"payment must not be less than -1ugnot\". Failing\n// closed here keeps an unrepresentable fee from opening the paid path\n// instead of closing it.\n//\n// Reachable two ways today, neither requiring malice: governance can set\n// any uint64 through the generic r/sys/params factories, and\n// valopers/proposal.ProposeNewMinFeeProposalRequest takes an int64 and\n// stores uint64(newMinFee), so a negative fee — the obvious way to write\n// \"disable the fee\" — round-trips to 2^64-1. That signature is preserved\n// for historical-replay compatibility and is deliberately left alone; the\n// bound belongs at the consumption site, which covers both paths.\nfunc minFeeCoin(fee uint64) chain.Coin {\n\tif fee \u003e math.MaxInt64 {\n\t\tpanic(ErrFeeParamOutOfRange)\n\t}\n\treturn chain.NewCoin(\"ugnot\", int64(fee))\n}\n\n// assertPubKeyTypeAllowed panics if pubKey's type is not in the chain's validator allow-list (empty list accepts any).\nfunc assertPubKeyTypeAllowed(pubKey string) {\n\tallowed := sysparams.GetValsetPubKeyTypes()\n\tif len(allowed) == 0 {\n\t\treturn\n\t}\n\ttypeURL, err := pubKeyTypeURL(pubKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, a := range allowed {\n\t\tif a == typeURL {\n\t\t\treturn\n\t\t}\n\t}\n\tpanic(ErrDisallowedPubKeyType)\n}\n\n// pubKeyTypeURL returns the amino type URL (e.g. \"/tm.PubKeyEd25519\") of a bech32 consensus pubkey.\nfunc pubKeyTypeURL(pubKey string) (string, error) {\n\t// gpub exceeds bech32's 90-char cap, so decode without the limit.\n\t_, data5, err := bech32.DecodeNoLimit(pubKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata, err := bech32.ConvertBits(data5, 5, 8, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Type URL is the first amino field: 0x0A \u003clen\u003e \u003ctypeURL\u003e.\n\tif len(data) \u003c 2 || data[0] != 0x0A {\n\t\treturn \"\", errors.New(\"malformed consensus pubkey: \" + pubKey)\n\t}\n\tn := int(data[1])\n\tif n == 0 || len(data) \u003c 2+n {\n\t\treturn \"\", errors.New(\"malformed consensus pubkey: \" + pubKey)\n\t}\n\treturn string(data[2 : 2+n]), nil\n}\n\n// validateServerType checks if the server type is valid.\nfunc validateServerType(serverType string) error {\n\tif serverType != ServerTypeCloud \u0026\u0026\n\t\tserverType != ServerTypeOnPrem \u0026\u0026\n\t\tserverType != ServerTypeDataCenter {\n\t\treturn ErrInvalidServerType\n\t}\n\n\treturn nil\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"proposal","path":"gno.land/r/gnops/valopers/proposal","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gnops/valopers/proposal\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"\n"},{"name":"proposal.gno","body":"package proposal\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\tvalopers \"gno.land/r/gnops/valopers\"\n\t\"gno.land/r/gov/dao\"\n\tsysparams \"gno.land/r/sys/params\"\n\tvalidators \"gno.land/r/sys/validators/v0\"\n)\n\nvar (\n\tErrValidatorMissing = errors.New(\"the validator is missing\")\n\tErrSameValues       = errors.New(\"the valoper has the same voting power and pubkey\")\n)\n\n// NewValidatorProposalRequest creates a proposal request to the GovDAO\n// for adding (or removing) the given valoper to/from the validator set.\n//\n// Signature is preserved for historical-replay compatibility (gnoland-1\n// callers call this with a single address). Body is rewired to call\n// v0's operator-keyed NewValidatorProposalRequest with a single-element\n// slice; v0's executor re-resolves the signing pubkey from valoperCache\n// at execution time, so a mid-flight rotation publishes the current key.\nfunc NewValidatorProposalRequest(cur realm, addr address) dao.ProposalRequest {\n\tvar (\n\t\tvaloper     = valopers.GetByAddr(addr)\n\t\tvotingPower = uint64(1)\n\t)\n\n\texist := validators.IsValidator(valoper.SigningAddress)\n\n\t// Determine the voting power\n\tif !valoper.KeepRunning {\n\t\tif !exist {\n\t\t\tpanic(ErrValidatorMissing)\n\t\t}\n\t\tvotingPower = uint64(0)\n\t}\n\n\tif exist {\n\t\tvalidator := validators.GetValidator(valoper.SigningAddress)\n\t\tif validator.VotingPower == votingPower \u0026\u0026 validator.PubKey == valoper.SigningPubKey {\n\t\t\tpanic(ErrSameValues)\n\t\t}\n\t}\n\n\t// Craft the proposal title and description, framed around the\n\t// valoper profile. Voters see the operator identity (moniker +\n\t// operator address); the signing key is an implementation detail\n\t// resolved at execution time by v0's executor.\n\ttitle := ufmt.Sprintf(\n\t\t\"Add valoper %s to the valset\",\n\t\tvaloper.Moniker,\n\t)\n\n\tdescription := ufmt.Sprintf(\"Valoper profile: [%s](/r/gnops/valopers:%s)\\n\\n%s\",\n\t\tvaloper.Moniker,\n\t\tvaloper.OperatorAddress,\n\t\tvaloper.Render(),\n\t)\n\n\treturn validators.NewValidatorProposalRequest(cross(cur),\n\t\t[]validators.ValoperChange{validators.NewValoperChange(valoper.OperatorAddress, votingPower)},\n\t\ttitle,\n\t\tdescription,\n\t)\n}\n\n// ProposeNewInstructionsProposalRequest creates a proposal to the GovDAO\n// for updating the realm instructions.\n//\n// Signature is preserved; the body now delegates. Building the request\n// here required valopers to export the privileged closure, which handed\n// this realm's frame identity to any caller. The\n// closure and the request are now built inside valopers, which returns\n// the request with its executor sealed — see valopers.NewInstructionsProposalRequest.\nfunc ProposeNewInstructionsProposalRequest(cur realm, newInstructions string) dao.ProposalRequest {\n\treturn valopers.NewInstructionsProposalRequest(cross(cur), newInstructions)\n}\n\n// ProposeAuthorityRotationProposalRequest creates a proposal to the GovDAO\n// for re-pointing the valopers realm's governance authority.\n//\n// Delegates, for the same reason as above: the rotation closure reaches\n// auth.Transfer, so it must never leave the valopers package. Exposed here\n// because this package is where proposal factories for the realm live —\n// see valopers.NewAuthorityRotationProposalRequest for why it takes a path\n// rather than an authz.Authority, and why it exists at all.\nfunc ProposeAuthorityRotationProposalRequest(cur realm, newContractPath string) dao.ProposalRequest {\n\treturn valopers.NewAuthorityRotationProposalRequest(cross(cur), newContractPath)\n}\n\n// ProposeNewMinFeeProposalRequest creates a proposal to the GovDAO\n// for updating the minimum fee to register a new valoper. Signature\n// preserved for historical-replay compatibility (gnoland-1's\n// set_minfee.gno MsgRun calls this); body now delegates to the\n// generic sys/params factory so the fee lives in\n// node:valoper:register_fee.\nfunc ProposeNewMinFeeProposalRequest(cur realm, newMinFee int64) dao.ProposalRequest {\n\treturn sysparams.NewSysParamUint64PropRequest(cross(cur), \"node\", \"valoper\", \"register_fee\", uint64(newMinFee))\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"typeutil","path":"gno.land/p/moul/typeutil/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/typeutil/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"typeutil.gno","body":"// Package typeutil provides utility functions for converting between different types\n// and checking their states. It aims to provide consistent behavior across different\n// types while remaining lightweight and dependency-free.\npackage typeutil\n\nimport (\n\t\"errors\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// stringer is the interface that wraps the String method.\ntype stringer interface {\n\tString() string\n}\n\n// ToString converts any value to its string representation.\n// It supports a wide range of Go types including:\n//   - Basic: string, bool\n//   - Numbers: int, int8-64, uint, uint8-64, float32, float64\n//   - Special: time.Time, address, []byte\n//   - Slices: []T for most basic types\n//   - Maps: map[string]string, map[string]any\n//   - Interface: types implementing String() string\n//\n// Example usage:\n//\n//\tstr := typeutil.ToString(42)               // \"42\"\n//\tstr = typeutil.ToString([]int{1, 2})      // \"[1 2]\"\n//\tstr = typeutil.ToString(map[string]string{ // \"map[a:1 b:2]\"\n//\t    \"a\": \"1\",\n//\t    \"b\": \"2\",\n//\t})\nfunc ToString(val any) string {\n\tif val == nil {\n\t\treturn \"\"\n\t}\n\n\t// First check if value implements Stringer interface\n\tif s, ok := val.(interface{ String() string }); ok {\n\t\treturn s.String()\n\t}\n\n\tswitch v := val.(type) {\n\t// Pointer types - dereference and recurse\n\tcase *string:\n\t\tif v == nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn *v\n\tcase *int:\n\t\tif v == nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn strconv.Itoa(*v)\n\tcase *bool:\n\t\tif v == nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn strconv.FormatBool(*v)\n\tcase *time.Time:\n\t\tif v == nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn v.String()\n\tcase *address:\n\t\tif v == nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn string(*v)\n\n\t// String types\n\tcase string:\n\t\treturn v\n\tcase stringer:\n\t\treturn v.String()\n\n\t// Special types\n\tcase time.Time:\n\t\treturn v.String()\n\tcase address:\n\t\treturn string(v)\n\tcase []byte:\n\t\treturn string(v)\n\tcase struct{}:\n\t\treturn \"{}\"\n\n\t// Integer types\n\tcase int:\n\t\treturn strconv.Itoa(v)\n\tcase int8:\n\t\treturn strconv.FormatInt(int64(v), 10)\n\tcase int16:\n\t\treturn strconv.FormatInt(int64(v), 10)\n\tcase int32:\n\t\treturn strconv.FormatInt(int64(v), 10)\n\tcase int64:\n\t\treturn strconv.FormatInt(v, 10)\n\tcase uint:\n\t\treturn strconv.FormatUint(uint64(v), 10)\n\tcase uint8:\n\t\treturn strconv.FormatUint(uint64(v), 10)\n\tcase uint16:\n\t\treturn strconv.FormatUint(uint64(v), 10)\n\tcase uint32:\n\t\treturn strconv.FormatUint(uint64(v), 10)\n\tcase uint64:\n\t\treturn strconv.FormatUint(v, 10)\n\n\t// Float types\n\tcase float32:\n\t\treturn strconv.FormatFloat(float64(v), 'f', -1, 32)\n\tcase float64:\n\t\treturn strconv.FormatFloat(v, 'f', -1, 64)\n\n\t// Boolean\n\tcase bool:\n\t\tif v {\n\t\t\treturn \"true\"\n\t\t}\n\t\treturn \"false\"\n\n\t// Slice types\n\tcase []string:\n\t\treturn join(v)\n\tcase []int:\n\t\treturn join(v)\n\tcase []int32:\n\t\treturn join(v)\n\tcase []int64:\n\t\treturn join(v)\n\tcase []float32:\n\t\treturn join(v)\n\tcase []float64:\n\t\treturn join(v)\n\tcase []any:\n\t\treturn join(v)\n\tcase []time.Time:\n\t\treturn joinTimes(v)\n\tcase []stringer:\n\t\treturn join(v)\n\tcase []address:\n\t\treturn joinAddresses(v)\n\tcase [][]byte:\n\t\treturn joinBytes(v)\n\n\t// Map types with various key types\n\tcase map[any]any, map[string]any, map[string]string, map[string]int:\n\t\tvar b strings.Builder\n\t\tb.WriteString(\"map[\")\n\t\tfirst := true\n\n\t\tswitch m := v.(type) {\n\t\tcase map[any]any:\n\t\t\t// Convert all keys to strings for consistent ordering\n\t\t\tkeys := make([]string, 0)\n\t\t\tkeyMap := make(map[string]any)\n\n\t\t\tfor k := range m {\n\t\t\t\tkeyStr := ToString(k)\n\t\t\t\tkeys = append(keys, keyStr)\n\t\t\t\tkeyMap[keyStr] = k\n\t\t\t}\n\t\t\tsort.Strings(keys)\n\n\t\t\tfor _, keyStr := range keys {\n\t\t\t\tif !first {\n\t\t\t\t\tb.WriteString(\" \")\n\t\t\t\t}\n\t\t\t\torigKey := keyMap[keyStr]\n\t\t\t\tb.WriteString(keyStr)\n\t\t\t\tb.WriteString(\":\")\n\t\t\t\tb.WriteString(ToString(m[origKey]))\n\t\t\t\tfirst = false\n\t\t\t}\n\n\t\tcase map[string]any:\n\t\t\tkeys := make([]string, 0)\n\t\t\tfor k := range m {\n\t\t\t\tkeys = append(keys, k)\n\t\t\t}\n\t\t\tsort.Strings(keys)\n\n\t\t\tfor _, k := range keys {\n\t\t\t\tif !first {\n\t\t\t\t\tb.WriteString(\" \")\n\t\t\t\t}\n\t\t\t\tb.WriteString(k)\n\t\t\t\tb.WriteString(\":\")\n\t\t\t\tb.WriteString(ToString(m[k]))\n\t\t\t\tfirst = false\n\t\t\t}\n\n\t\tcase map[string]string:\n\t\t\tkeys := make([]string, 0)\n\t\t\tfor k := range m {\n\t\t\t\tkeys = append(keys, k)\n\t\t\t}\n\t\t\tsort.Strings(keys)\n\n\t\t\tfor _, k := range keys {\n\t\t\t\tif !first {\n\t\t\t\t\tb.WriteString(\" \")\n\t\t\t\t}\n\t\t\t\tb.WriteString(k)\n\t\t\t\tb.WriteString(\":\")\n\t\t\t\tb.WriteString(m[k])\n\t\t\t\tfirst = false\n\t\t\t}\n\n\t\tcase map[string]int:\n\t\t\tkeys := make([]string, 0)\n\t\t\tfor k := range m {\n\t\t\t\tkeys = append(keys, k)\n\t\t\t}\n\t\t\tsort.Strings(keys)\n\n\t\t\tfor _, k := range keys {\n\t\t\t\tif !first {\n\t\t\t\t\tb.WriteString(\" \")\n\t\t\t\t}\n\t\t\t\tb.WriteString(k)\n\t\t\t\tb.WriteString(\":\")\n\t\t\t\tb.WriteString(strconv.Itoa(m[k]))\n\t\t\t\tfirst = false\n\t\t\t}\n\t\t}\n\t\tb.WriteString(\"]\")\n\t\treturn b.String()\n\n\t// Default\n\tdefault:\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n}\n\nfunc join(slice any) string {\n\tif IsZero(slice) {\n\t\treturn \"[]\"\n\t}\n\n\titems := ToInterfaceSlice(slice)\n\tif items == nil {\n\t\treturn \"[]\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"[\")\n\tfor i, item := range items {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\" \")\n\t\t}\n\t\tb.WriteString(ToString(item))\n\t}\n\tb.WriteString(\"]\")\n\treturn b.String()\n}\n\nfunc joinTimes(slice []time.Time) string {\n\tif len(slice) == 0 {\n\t\treturn \"[]\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"[\")\n\tfor i, t := range slice {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\" \")\n\t\t}\n\t\tb.WriteString(t.String())\n\t}\n\tb.WriteString(\"]\")\n\treturn b.String()\n}\n\nfunc joinAddresses(slice []address) string {\n\tif len(slice) == 0 {\n\t\treturn \"[]\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"[\")\n\tfor i, addr := range slice {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\" \")\n\t\t}\n\t\tb.WriteString(string(addr))\n\t}\n\tb.WriteString(\"]\")\n\treturn b.String()\n}\n\nfunc joinBytes(slice [][]byte) string {\n\tif len(slice) == 0 {\n\t\treturn \"[]\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"[\")\n\tfor i, bytes := range slice {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\" \")\n\t\t}\n\t\tb.WriteString(string(bytes))\n\t}\n\tb.WriteString(\"]\")\n\treturn b.String()\n}\n\n// ToBool converts any value to a boolean based on common programming conventions.\n// For example:\n//   - Numbers: 0 is false, any other number is true\n//   - Strings: \"\", \"0\", \"false\", \"f\", \"no\", \"n\", \"off\" are false, others are true\n//   - Slices/Maps: empty is false, non-empty is true\n//   - nil: always false\n//   - bool: direct value\nfunc ToBool(val any) bool {\n\tif IsZero(val) {\n\t\treturn false\n\t}\n\n\t// Handle special string cases\n\tif str, ok := val.(string); ok {\n\t\tstr = strings.ToLower(strings.TrimSpace(str))\n\t\treturn str != \"\" \u0026\u0026 str != \"0\" \u0026\u0026 str != \"false\" \u0026\u0026 str != \"f\" \u0026\u0026 str != \"no\" \u0026\u0026 str != \"n\" \u0026\u0026 str != \"off\"\n\t}\n\n\treturn true\n}\n\n// IsZero returns true if the value represents a \"zero\" or \"empty\" state for its type.\n// For example:\n//   - Numbers: 0\n//   - Strings: \"\"\n//   - Slices/Maps: empty\n//   - nil: true\n//   - bool: false\n//   - time.Time: IsZero()\n//   - address: empty string\nfunc IsZero(val any) bool {\n\tif val == nil {\n\t\treturn true\n\t}\n\n\tswitch v := val.(type) {\n\t// Pointer types - nil pointer is zero, otherwise check pointed value\n\tcase *bool:\n\t\treturn v == nil || !*v\n\tcase *string:\n\t\treturn v == nil || *v == \"\"\n\tcase *int:\n\t\treturn v == nil || *v == 0\n\tcase *time.Time:\n\t\treturn v == nil || v.IsZero()\n\tcase *address:\n\t\treturn v == nil || string(*v) == \"\"\n\n\t// Bool\n\tcase bool:\n\t\treturn !v\n\n\t// String types\n\tcase string:\n\t\treturn v == \"\"\n\tcase stringer:\n\t\treturn v.String() == \"\"\n\n\t// Integer types\n\tcase int:\n\t\treturn v == 0\n\tcase int8:\n\t\treturn v == 0\n\tcase int16:\n\t\treturn v == 0\n\tcase int32:\n\t\treturn v == 0\n\tcase int64:\n\t\treturn v == 0\n\tcase uint:\n\t\treturn v == 0\n\tcase uint8:\n\t\treturn v == 0\n\tcase uint16:\n\t\treturn v == 0\n\tcase uint32:\n\t\treturn v == 0\n\tcase uint64:\n\t\treturn v == 0\n\n\t// Float types\n\tcase float32:\n\t\treturn v == 0\n\tcase float64:\n\t\treturn v == 0\n\n\t// Special types\n\tcase []byte:\n\t\treturn len(v) == 0\n\tcase time.Time:\n\t\treturn v.IsZero()\n\tcase address:\n\t\treturn string(v) == \"\"\n\n\t// Slices (check if empty)\n\tcase []string:\n\t\treturn len(v) == 0\n\tcase []int:\n\t\treturn len(v) == 0\n\tcase []int32:\n\t\treturn len(v) == 0\n\tcase []int64:\n\t\treturn len(v) == 0\n\tcase []float32:\n\t\treturn len(v) == 0\n\tcase []float64:\n\t\treturn len(v) == 0\n\tcase []any:\n\t\treturn len(v) == 0\n\tcase []time.Time:\n\t\treturn len(v) == 0\n\tcase []address:\n\t\treturn len(v) == 0\n\tcase [][]byte:\n\t\treturn len(v) == 0\n\tcase []stringer:\n\t\treturn len(v) == 0\n\n\t// Maps (check if empty)\n\tcase map[string]string:\n\t\treturn len(v) == 0\n\tcase map[string]any:\n\t\treturn len(v) == 0\n\n\tdefault:\n\t\treturn false // non-nil unknown types are considered non-zero\n\t}\n}\n\n// ToInterfaceSlice converts various slice types to []any\nfunc ToInterfaceSlice(val any) []any {\n\tswitch v := val.(type) {\n\tcase []any:\n\t\treturn v\n\tcase []string:\n\t\tresult := make([]any, len(v))\n\t\tfor i, s := range v {\n\t\t\tresult[i] = s\n\t\t}\n\t\treturn result\n\tcase []int:\n\t\tresult := make([]any, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = n\n\t\t}\n\t\treturn result\n\tcase []int32:\n\t\tresult := make([]any, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = n\n\t\t}\n\t\treturn result\n\tcase []int64:\n\t\tresult := make([]any, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = n\n\t\t}\n\t\treturn result\n\tcase []float32:\n\t\tresult := make([]any, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = n\n\t\t}\n\t\treturn result\n\tcase []float64:\n\t\tresult := make([]any, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = n\n\t\t}\n\t\treturn result\n\tcase []bool:\n\t\tresult := make([]any, len(v))\n\t\tfor i, b := range v {\n\t\t\tresult[i] = b\n\t\t}\n\t\treturn result\n\tdefault:\n\t\treturn nil\n\t}\n}\n\n// ToMapStringInterface converts a map with string keys and any value type to map[string]any\nfunc ToMapStringInterface(m any) (map[string]any, error) {\n\tresult := make(map[string]any)\n\n\tswitch v := m.(type) {\n\tcase map[string]any:\n\t\treturn v, nil\n\tcase map[string]string:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[string]int:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[string]int64:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[string]float64:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[string]bool:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[string][]string:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = ToInterfaceSlice(val)\n\t\t}\n\tcase map[string][]int:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = ToInterfaceSlice(val)\n\t\t}\n\tcase map[string][]any:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[string]map[string]any:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[string]map[string]string:\n\t\tfor k, val := range v {\n\t\t\tif converted, err := ToMapStringInterface(val); err == nil {\n\t\t\t\tresult[k] = converted\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"failed to convert nested map at key: \" + k)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"unsupported map type: \" + ToString(m))\n\t}\n\n\treturn result, nil\n}\n\n// ToMapIntInterface converts a map with int keys and any value type to map[int]any\nfunc ToMapIntInterface(m any) (map[int]any, error) {\n\tresult := make(map[int]any)\n\n\tswitch v := m.(type) {\n\tcase map[int]any:\n\t\treturn v, nil\n\tcase map[int]string:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[int]int:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[int]int64:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[int]float64:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[int]bool:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[int][]string:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = ToInterfaceSlice(val)\n\t\t}\n\tcase map[int][]int:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = ToInterfaceSlice(val)\n\t\t}\n\tcase map[int][]any:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[int]map[string]any:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tcase map[int]map[int]any:\n\t\tfor k, val := range v {\n\t\t\tresult[k] = val\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"unsupported map type: \" + ToString(m))\n\t}\n\n\treturn result, nil\n}\n\n// ToStringSlice converts various slice types to []string\nfunc ToStringSlice(val any) []string {\n\tswitch v := val.(type) {\n\tcase []string:\n\t\treturn v\n\tcase []any:\n\t\tresult := make([]string, len(v))\n\t\tfor i, item := range v {\n\t\t\tresult[i] = ToString(item)\n\t\t}\n\t\treturn result\n\tcase []int:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.Itoa(n)\n\t\t}\n\t\treturn result\n\tcase []int32:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatInt(int64(n), 10)\n\t\t}\n\t\treturn result\n\tcase []int64:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatInt(n, 10)\n\t\t}\n\t\treturn result\n\tcase []float32:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatFloat(float64(n), 'f', -1, 32)\n\t\t}\n\t\treturn result\n\tcase []float64:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatFloat(n, 'f', -1, 64)\n\t\t}\n\t\treturn result\n\tcase []bool:\n\t\tresult := make([]string, len(v))\n\t\tfor i, b := range v {\n\t\t\tresult[i] = strconv.FormatBool(b)\n\t\t}\n\t\treturn result\n\tcase []time.Time:\n\t\tresult := make([]string, len(v))\n\t\tfor i, t := range v {\n\t\t\tresult[i] = t.String()\n\t\t}\n\t\treturn result\n\tcase []address:\n\t\tresult := make([]string, len(v))\n\t\tfor i, addr := range v {\n\t\t\tresult[i] = string(addr)\n\t\t}\n\t\treturn result\n\tcase [][]byte:\n\t\tresult := make([]string, len(v))\n\t\tfor i, b := range v {\n\t\t\tresult[i] = string(b)\n\t\t}\n\t\treturn result\n\tcase []stringer:\n\t\tresult := make([]string, len(v))\n\t\tfor i, s := range v {\n\t\t\tresult[i] = s.String()\n\t\t}\n\t\treturn result\n\tcase []uint:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatUint(uint64(n), 10)\n\t\t}\n\t\treturn result\n\tcase []uint8:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatUint(uint64(n), 10)\n\t\t}\n\t\treturn result\n\tcase []uint16:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatUint(uint64(n), 10)\n\t\t}\n\t\treturn result\n\tcase []uint32:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatUint(uint64(n), 10)\n\t\t}\n\t\treturn result\n\tcase []uint64:\n\t\tresult := make([]string, len(v))\n\t\tfor i, n := range v {\n\t\t\tresult[i] = strconv.FormatUint(n, 10)\n\t\t}\n\t\treturn result\n\tdefault:\n\t\t// Try to convert using reflection if it's a slice\n\t\tif slice := ToInterfaceSlice(val); slice != nil {\n\t\t\tresult := make([]string, len(slice))\n\t\t\tfor i, item := range slice {\n\t\t\t\tresult[i] = ToString(item)\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\treturn nil\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"table","path":"gno.land/p/sunspirit/table/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/sunspirit/table/v0\"\ngno = \"0.9\"\n"},{"name":"table.gno","body":"package table\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Table defines the structure for a markdown table\ntype Table struct {\n\theader []string\n\trows   [][]string\n}\n\n// Validate checks if the number of columns in each row matches the number of columns in the header\nfunc (t *Table) Validate() error {\n\tnumCols := len(t.header)\n\tfor _, row := range t.rows {\n\t\tif len(row) != numCols {\n\t\t\treturn ufmt.Errorf(\"row %v does not match header length %d\", row, numCols)\n\t\t}\n\t}\n\treturn nil\n}\n\n// New creates a new Table instance, ensuring the header and rows match in size\nfunc New(header []string, rows [][]string) (*Table, error) {\n\tt := \u0026Table{\n\t\theader: header,\n\t\trows:   rows,\n\t}\n\n\tif err := t.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t, nil\n}\n\n// Table returns a markdown string for the given Table\nfunc (t *Table) String() string {\n\tif err := t.Validate(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar sb strings.Builder\n\n\tsb.WriteString(\"| \" + strings.Join(t.header, \" | \") + \" |\\n\")\n\tsb.WriteString(\"| \" + strings.Repeat(\"---|\", len(t.header)) + \"\\n\")\n\n\tfor _, row := range t.rows {\n\t\tsb.WriteString(\"| \" + strings.Join(row, \" | \") + \" |\\n\")\n\t}\n\n\treturn sb.String()\n}\n\n// AddRow adds a new row to the table\nfunc (t *Table) AddRow(row []string) error {\n\tif len(row) != len(t.header) {\n\t\treturn ufmt.Errorf(\"row %v does not match header length %d\", row, len(t.header))\n\t}\n\tt.rows = append(t.rows, row)\n\treturn nil\n}\n\n// AddColumn adds a new column to the table with the specified values\nfunc (t *Table) AddColumn(header string, values []string) error {\n\tif len(values) != len(t.rows) {\n\t\treturn ufmt.Errorf(\"values length %d does not match the number of rows %d\", len(values), len(t.rows))\n\t}\n\n\t// Add the new header\n\tt.header = append(t.header, header)\n\n\t// Add the new column values to each row\n\tfor i, value := range values {\n\t\tt.rows[i] = append(t.rows[i], value)\n\t}\n\treturn nil\n}\n\n// RemoveRow removes a row from the table by its index\nfunc (t *Table) RemoveRow(index int) error {\n\tif index \u003c 0 || index \u003e= len(t.rows) {\n\t\treturn ufmt.Errorf(\"index %d is out of range\", index)\n\t}\n\tt.rows = append(t.rows[:index], t.rows[index+1:]...)\n\treturn nil\n}\n\n// RemoveColumn removes a column from the table by its index\nfunc (t *Table) RemoveColumn(index int) error {\n\tif index \u003c 0 || index \u003e= len(t.header) {\n\t\treturn ufmt.Errorf(\"index %d is out of range\", index)\n\t}\n\n\t// Remove the column from the header\n\tt.header = append(t.header[:index], t.header[index+1:]...)\n\n\t// Remove the corresponding column from each row\n\tfor i := range t.rows {\n\t\tt.rows[i] = append(t.rows[i][:index], t.rows[i][index+1:]...)\n\t}\n\treturn nil\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"closuretest","path":"gno.land/r/demo/closuretest","files":[{"name":"closuretest.gno","body":"package closuretest\n\nimport \"strconv\"\n\nvar (\n\tcount   int\n\tstepper func() int\n)\n\nvar (\n\taccumulator func(int)\n\thistory     []int\n)\n\nfunc init() {\n\tstep := 3\n\tstepper = func() int {\n\t\tcount += step\n\t\treturn count\n\t}\n\n\tmaxLen := 10\n\thistory = make([]int, 0, maxLen)\n\taccumulator = func(val int) {\n\t\tif len(history) \u003c maxLen {\n\t\t\thistory = append(history, val)\n\t\t}\n\t}\n}\n\nfunc Step() string {\n\tresult := stepper()\n\treturn \"count=\" + strconv.Itoa(result)\n}\n\nfunc Accumulate(val int) string {\n\taccumulator(val)\n\treturn \"history length=\" + strconv.Itoa(len(history))\n}\n\nfunc Render(_ string) string {\n\treturn \"closuretest: count=\" + strconv.Itoa(count) + \" history=\" + strconv.Itoa(len(history))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/closuretest\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"atomicswap","path":"gno.land/r/demo/defi/atomicswap","files":[{"name":"atomicswap.gno","body":"// Package atomicswap implements a hash time-locked contract (HTLC) for atomic swaps\n// between native coins (ugnot) or GRC20 tokens.\n//\n// An atomic swap allows two parties to exchange assets in a trustless way, where\n// either both transfers happen or neither does. The process works as follows:\n//\n//  1. Alice wants to swap with Bob. She generates a secret and creates a swap with\n//     Bob's address and the hash of the secret (hashlock).\n//\n//  2. Bob can claim the assets by providing the correct secret before the timelock expires.\n//     The secret proves Bob knows the preimage of the hashlock.\n//\n// 3. If Bob doesn't claim in time, Alice can refund the assets back to herself.\n//\n// Example usage for native coins:\n//\n//\t// Alice creates a swap with 1000ugnot for Bob\n//\tsecret := \"mysecret\"\n//\thashlock := hex.EncodeToString(sha256.Sum256([]byte(secret)))\n//\tid, _ := atomicswap.NewCoinSwap(bobAddr, hashlock) // -send 1000ugnot\n//\n//\t// Bob claims the swap by providing the secret\n//\tatomicswap.Claim(id, \"mysecret\")\n//\n// Example usage for GRC20 tokens:\n//\n//\t// Alice approves the swap contract to spend her tokens\n//\ttoken.Approve(swapAddr, 1000)\n//\n//\t// Alice creates a swap with 1000 tokens for Bob\n//\tid, _ := atomicswap.NewGRC20Swap(bobAddr, hashlock, \"gno.land/r/demo/token.TKN\")\n//\n//\t// Bob claims the swap by providing the secret\n//\tatomicswap.Claim(id, \"mysecret\")\n//\n// If Bob doesn't claim in time (default 1 week), Alice can refund:\n//\n//\tatomicswap.Refund(id)\npackage atomicswap\n\nimport (\n\t\"chain/banker\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nconst defaultTimelockDuration = 7 * 24 * time.Hour // 1w\n\nvar (\n\tswaps   avl.Tree // id -\u003e *Swap\n\tcounter int\n)\n\n// NewCoinSwap creates a new atomic swap contract for native coins.\n// It uses a default timelock duration.\nfunc NewCoinSwap(cur realm, recipient address, hashlock string) (int, *Swap) {\n\ttimelock := time.Now().Add(defaultTimelockDuration)\n\treturn NewCustomCoinSwap(cur, recipient, hashlock, timelock)\n}\n\n// NewGRC20Swap creates a new atomic swap contract for grc20 tokens.\n// It uses gno.land/r/nt/grc20reg/v0 to lookup for a registered token.\nfunc NewGRC20Swap(cur realm, recipient address, hashlock string, tokenRegistryKey string) (int, *Swap) {\n\ttimelock := time.Now().Add(defaultTimelockDuration)\n\ttoken := grc20reg.MustGet(tokenRegistryKey)\n\treturn NewCustomGRC20Swap(cur, recipient, hashlock, timelock, token)\n}\n\n// NewCoinSwapWithTimelock creates a new atomic swap contract for native coin.\n// It allows specifying a custom timelock duration.\n//\n// Only direct user-call (maketx call) is accepted: unsafe.OriginSend()\n// describes a real receipt at this realm only when the caller is a pure\n// EOA. Intermediate code realms or `maketx run` ephemeral realms can\n// attach -send to the tx but spend the envelope elsewhere, leaving\n// OriginSend() describing a phantom payment that would let the swap\n// drain the realm's pre-existing balance on Claim.\nfunc NewCustomCoinSwap(cur realm, recipient address, hashlock string, timelock time.Time) (int, *Swap) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only user-call (maketx call) accepted\")\n\t}\n\tsender := cur.Previous().Address()\n\tsent := unsafe.OriginSend()\n\trequire(len(sent) != 0, \"at least one coin needs to be sent\")\n\n\t// Create the swap\n\tsendFn := func(cur realm, to address) {\n\t\tbanker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\t\tpkgAddr := cur.Address()\n\t\tbanker_.SendCoins(pkgAddr, to, sent)\n\t}\n\tamountStr := sent.String()\n\tswap := newSwap(sender, recipient, hashlock, timelock, amountStr, sendFn)\n\n\tcounter++\n\tid := strconv.Itoa(counter)\n\tswaps.Set(id, swap)\n\treturn counter, swap\n}\n\n// NewCustomGRC20Swap creates a new atomic swap contract for grc20 tokens.\n// It is not callable with `gnokey maketx call`, but can be imported by another contract or `gnokey maketx run`.\nfunc NewCustomGRC20Swap(cur realm, recipient address, hashlock string, timelock time.Time, token *grc20.Token) (int, *Swap) {\n\tsender := cur.Previous().Address()\n\tcurAddr := cur.Address()\n\n\tallowance := token.Allowance(sender, curAddr)\n\trequire(allowance \u003e 0, \"no allowance\")\n\n\tuserTeller := token.RealmTeller(0, cur)\n\terr := userTeller.TransferFrom(0, cur, sender, curAddr, allowance)\n\trequire(err == nil, \"cannot retrieve tokens from allowance\")\n\n\tamountStr := ufmt.Sprintf(\"%d%s\", allowance, token.GetSymbol())\n\tsendFn := func(cur realm, to address) {\n\t\terr := userTeller.Transfer(0, cur, to, allowance)\n\t\trequire(err == nil, \"cannot transfer tokens\")\n\t}\n\n\tswap := newSwap(sender, recipient, hashlock, timelock, amountStr, sendFn)\n\n\tcounter++\n\tid := strconv.Itoa(counter)\n\tswaps.Set(id, swap)\n\n\treturn counter, swap\n}\n\n// Claim loads a registered swap and tries to claim it.\nfunc Claim(cur realm, id int, secret string) {\n\tswap := mustGet(id)\n\tswap.Claim(0, cur, secret)\n}\n\n// Refund loads a registered swap and tries to refund it.\nfunc Refund(cur realm, id int) {\n\tswap := mustGet(id)\n\tswap.Refund(0, cur)\n}\n\n// Render returns a list of swaps (simplified) for the homepage, and swap details when specifying a swap ID.\nfunc Render(path string) string {\n\tif path == \"\" { // home\n\t\toutput := \"\"\n\t\tsize := swaps.Size()\n\t\tmax := 10\n\t\tswaps.ReverseIterateByOffset(size-max, max, func(key string, value any) bool {\n\t\t\tswap := value.(*Swap)\n\t\t\toutput += ufmt.Sprintf(\"- %s: %s -(%s)\u003e %s - %s\\n\",\n\t\t\t\tkey, swap.sender, swap.amountStr, swap.recipient, swap.Status())\n\t\t\treturn false\n\t\t})\n\t\treturn output\n\t} else { // by id\n\t\tswap := swaps.Get(path)\n\t\tif swap == nil {\n\t\t\treturn \"404\"\n\t\t}\n\t\treturn swap.(*Swap).String()\n\t}\n}\n\n// require checks a condition and panics with a message if the condition is false.\nfunc require(check bool, msg string) {\n\tif !check {\n\t\tpanic(msg)\n\t}\n}\n\n// mustGet retrieves a swap by its id or panics.\nfunc mustGet(id int) *Swap {\n\tkey := strconv.Itoa(id)\n\tswap := swaps.Get(key)\n\tif swap == nil {\n\t\tpanic(\"unknown swap ID\")\n\t}\n\treturn swap.(*Swap)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/defi/atomicswap\"\ngno = \"0.9\"\n"},{"name":"swap.gno","body":"package atomicswap\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"time\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Swap represents an atomic swap contract.\ntype Swap struct {\n\tsender    address\n\trecipient address\n\thashlock  string\n\ttimelock  time.Time\n\tclaimed   bool\n\trefunded  bool\n\tamountStr string\n\tsendFn    func(cur realm, to address)\n}\n\nfunc newSwap(\n\tsender address,\n\trecipient address,\n\thashlock string,\n\ttimelock time.Time,\n\tamountStr string,\n\tsendFn func(realm, address),\n) *Swap {\n\trequire(time.Now().Before(timelock), \"timelock must be in the future\")\n\trequire(hashlock != \"\", \"hashlock must not be empty\")\n\treturn \u0026Swap{\n\t\trecipient: recipient,\n\t\tsender:    sender,\n\t\thashlock:  hashlock,\n\t\ttimelock:  timelock,\n\t\tclaimed:   false,\n\t\trefunded:  false,\n\t\tsendFn:    sendFn,\n\t\tamountStr: amountStr,\n\t}\n}\n\n// Claim allows the recipient to claim the funds if they provide the correct preimage.\n// rlm is the cur of the surrounding crossing wrapper; rlm.Previous() is\n// the immediate caller of that wrapper, against which we authorize.\nfunc (s *Swap) Claim(_ int, rlm realm, preimage string) {\n\trequire(rlm.IsCurrent(), \"unauthorized: rlm is not the caller's live cur\")\n\trequire(!s.claimed, \"already claimed\")\n\trequire(!s.refunded, \"already refunded\")\n\trequire(rlm.Previous().Address() == s.recipient, \"unauthorized\")\n\n\thashlock := sha256.Sum256([]byte(preimage))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\trequire(hashlockHex == s.hashlock, \"invalid preimage\")\n\n\ts.claimed = true\n\ts.sendFn(cross(rlm), s.recipient)\n}\n\n// Refund allows the sender to refund the funds after the timelock has expired.\nfunc (s *Swap) Refund(_ int, rlm realm) {\n\trequire(rlm.IsCurrent(), \"unauthorized: rlm is not the caller's live cur\")\n\trequire(!s.claimed, \"already claimed\")\n\trequire(!s.refunded, \"already refunded\")\n\trequire(rlm.Previous().Address() == s.sender, \"unauthorized\")\n\trequire(time.Now().After(s.timelock), \"timelock not expired\")\n\n\ts.refunded = true\n\ts.sendFn(cross(rlm), s.sender)\n}\n\nfunc (s Swap) Status() string {\n\tswitch {\n\tcase s.refunded:\n\t\treturn \"refunded\"\n\tcase s.claimed:\n\t\treturn \"claimed\"\n\tcase s.TimeRemaining() \u003c 0:\n\t\treturn \"expired\"\n\tdefault:\n\t\treturn \"active\"\n\t}\n}\n\nfunc (s Swap) TimeRemaining() time.Duration {\n\tremaining := time.Until(s.timelock)\n\tif remaining \u003c 0 {\n\t\treturn 0\n\t}\n\treturn remaining\n}\n\n// String returns the current state of the swap.\nfunc (s Swap) String() string {\n\treturn ufmt.Sprintf(\n\t\t\"- status: %s\\n- sender: %s\\n- recipient: %s\\n- amount: %s\\n- hashlock: %s\\n- timelock: %s\\n- remaining: %s\",\n\t\ts.Status(), s.sender, s.recipient, s.amountStr, s.hashlock, s.timelock.Format(time.RFC3339), s.TimeRemaining().String(),\n\t)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"names","path":"gno.land/r/sys/names","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/names\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"render.gno","body":"package names\n\nfunc Render(_ string) string {\n\treturn `# r/sys/names\nSystem Realm for checking namespace deployment permissions.`\n}\n"},{"name":"verifier.gno","body":"// Package names enforces namespace permissions for package deployment.\n//\n// Two namespace shapes grant deploy authority when enforcement is enabled:\n//\n//  1. PA (personal-address) namespaces — gno.land/{r,p}/\u003caddr\u003e/* — the\n//     deployer's address string equals the namespace literal. Anyone can\n//     deploy under their own address.\n//\n//  2. Registered-name namespaces — gno.land/{r,p}/\u003cname\u003e/* — r/sys/users\n//     has a (name → addr) mapping where the resolved address equals the\n//     deployer AND the name is the user's CURRENT name (not a historical\n//     alias from a rename chain). This is the bridge that lets\n//     r/sys/namereg/v0 (or any other DAO-whitelisted controller) grant\n//     deploy authority via name registration.\n//\n// Authority is unscoped: a registered name owns BOTH r/\u003cname\u003e/* and\n// p/\u003cname\u003e/* paths. There is no sub-prefix isolation (e.g. r/u/\u003cname\u003e/*).\n//\n// The realm exposes an emergency-halt switch via SetPaused. When paused,\n// the verifier rejects EVERY namespace check — PA included — until\n// unpaused. This is the \"true emergency\" semantic; the narrow alternative\n// (pause registered-name only, preserve PA) was considered and rejected\n// because the threats most likely to justify pausing this realm\n// (verifier bug, compromised controller, signature-layer incident) do\n// not reliably exempt PA from the same blast radius.\npackage names\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/r/gov/dao\"\n\tgovimpl \"gno.land/r/gov/dao/impl/v0\"\n\tmemberstore \"gno.land/r/gov/dao/memberstore/v0\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\nvar (\n\t// admin is the GovDAO T1 multisig address, hardcoded at realm-source\n\t// commit time. Its only capability is gating Enable() — a one-way,\n\t// one-shot genesis activation of the namespace verifier. The address\n\t// has no other authority on this realm; pause/unpause is gated on a\n\t// separate GovDAO T1 proposal (see ProposeSetPaused), and there is\n\t// no SetEnabled(false) or SetAdmin path.\n\t//\n\t// Hardcoding is acceptable because:\n\t//   - Enable() is called once, at chain genesis. After that the\n\t//     address is dead weight — no further capability flows through it.\n\t//   - The narrow blast radius of \"stale admin\" is \"Enable() can never\n\t//     be called\", which leaves the verifier in pre-Enable bypass mode\n\t//     (returns true for all checks) — degraded but not exploitable.\n\t//   - A rotation path would only matter if Enable() needed to be\n\t//     re-issued. It doesn't; the flag is sticky.\n\t//\n\t// If the genesis activation pattern ever needs to change (e.g. a\n\t// SetEnabled(false) emergency disable is added later), this admin\n\t// model should be replaced with a GovDAO T1 proposal flow that\n\t// mirrors ProposeSetPaused. Until then, the hardcoded address is\n\t// the smallest viable governance surface for the one-shot use case.\n\tadmin   = address(\"g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx\")\n\tenabled = false\n\tpaused  = false\n)\n\n// nameLookupFn returns (addr, ok) for a given registered name. Allows\n// the verifier function to be unit-tested without wiring up r/sys/users\n// state — production binds resolveCurrentName as the lookup, tests pass\n// nil (PA-only) or a fake.\ntype nameLookupFn func(name string) (addr address, ok bool)\n\n// IsAuthorizedAddressForNamespace checks if the given address can deploy\n// to the given namespace. See package doc for the two authorization paths\n// and the pause semantic.\n//\n// Pre-Enable, all checks pass (testing/dev convenience).\nfunc IsAuthorizedAddressForNamespace(address_XXX address, namespace string) bool {\n\treturn verifier(enabled, paused, address_XXX, namespace, resolveCurrentName)\n}\n\n// resolveCurrentName is the production nameLookupFn, backed by r/sys/users.\n// Returns ok=true only if the name resolves to a non-deleted user AND the\n// queried name is that user's CURRENT name (the most recent UpdateName).\n//\n// Restricting to the current name has two consequences worth knowing:\n//\n//  1. After a UpdateName from \"alice\" to \"alice2\", the user keeps deploy\n//     authority over r/alice2/* but LOSES it for r/alice/*. Already-\n//     deployed packages at r/alice/* keep working — deploy-time\n//     authorization doesn't unwind the past — but no NEW deploys can\n//     land there.\n//\n//  2. The old name \"alice\" is also unregisterable by anyone else: when\n//     r/sys/users.UpdateName runs, it inserts the new name into nameStore\n//     but does not remove the old one. r/sys/users.RegisterUser then\n//     rejects re-registration of \"alice\" with ErrNameTaken. Net effect:\n//     a rename permanently removes the old name from circulation.\n//\n// The alternative (allow historical aliases to retain authority) was\n// rejected because it lets a single user register one cheap name, then\n// rename N times to claim authority over N distinct namespaces — a\n// stealth namespace acquisition vector worse than the current\n// burn-on-rename behavior.\nfunc resolveCurrentName(name string) (address, bool) {\n\tdata, isCurrent := susers.ResolveName(name)\n\tif data == nil || !isCurrent {\n\t\treturn \"\", false\n\t}\n\treturn data.Addr(), true\n}\n\n// Enable enables the namespace check for this realm.\n// The namespace check is disabled initially to ease txtar and other testing contexts,\n// but this function is meant to be called in the genesis of a chain.\nfunc Enable(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"unauthorized: cur is not the caller's live realm\")\n\t}\n\tif cur.Previous().Address() != admin {\n\t\tpanic(\"caller is not admin\")\n\t}\n\tenabled = true\n}\n\nfunc IsEnabled() bool {\n\treturn enabled\n}\n\n// ProposeSetPaused returns a GovDAO proposal request that, when voted\n// through and executed, toggles the chain-wide deploy gate. When the\n// realm is paused, the verifier rejects EVERY namespace check — PA\n// (personal-address) included — until a subsequent ProposeSetPaused(false)\n// proposal executes.\n//\n// This is an emergency halt. A paused state means NO new MsgAddPackage\n// transactions land at any path on the chain. Existing realms continue\n// to receive MsgCall traffic normally — pause is scoped to addpkg, not\n// to all VM operations. Use cases:\n//   - Bug discovered in this realm or r/sys/users that requires a\n//     hotfix before further deploys can be trusted.\n//   - Wallet/signature-layer incident under investigation.\n//\n// (A \"compromised controller\" use case was considered and removed: the\n// controller's RegisterUser path is direct into r/sys/users and does\n// NOT go through this verifier, so pause does not freeze new\n// registrations. To contain a compromised controller, the appropriate\n// flow is ProposeControllerRemoval in r/sys/users, not pause here.)\n//\n// The narrow alternative (pause registered-name path only, preserve\n// PA) was considered and rejected. See package doc for rationale.\n//\n// Gated on GovDAO proposal at T1 tier — not the hardcoded admin used\n// by Enable. Pause is consequential enough to warrant a tier-restricted\n// governance vote rather than a single-multisig click. T1 filter\n// prevents lower-tier members from spamming pause proposals to dilute\n// attention. Trade-off is response time: a T1 vote takes hours-to-days;\n// if a faster emergency-halt mechanism is needed, that belongs at a\n// different layer (e.g. an ante-handler-level chain pause), not here.\n//\n// Pause is orthogonal to the pre-Enable bypass: before Enable, the\n// verifier returns true regardless of paused state. So executing a\n// pause proposal before Enable has no effect on deploys, but the\n// value persists and applies the moment Enable runs. To avoid this\n// staging trap, operators should call Enable BEFORE any pause\n// proposals are voted in.\n//\n// Idempotency: calling ProposeSetPaused(v) when the realm's current\n// paused state already equals v panics at proposal-creation time so\n// voters never see a proposal whose execution would no-op.\nfunc ProposeSetPaused(cur realm, v bool) dao.ProposalRequest {\n\tif paused == v {\n\t\tpanic(\"paused state already matches requested value; no-op proposal rejected\")\n\t}\n\tcb := func(cur realm) error {\n\t\tsetPaused(0, cur, v)\n\t\treturn nil\n\t}\n\ttitle := \"Unpause Namespace Verifier\"\n\tdesc := \"This proposal unpauses `r/sys/names`. After execution, the namespace verifier will resume normal authorization checks (PA + registered-name paths). MsgCall traffic to existing realms is unaffected (pause was scoped to MsgAddPackage); only NEW package deploys gate on the unpaused state.\"\n\tif v {\n\t\ttitle = \"Pause Namespace Verifier\"\n\t\tdesc = \"This proposal pauses `r/sys/names`. After execution, the namespace verifier will reject EVERY new MsgAddPackage on the chain — PA (personal-address) and registered-name namespaces alike — until a subsequent unpause proposal executes. This is an emergency halt scoped to addpkg; MsgCall traffic to existing realms is unaffected.\"\n\t}\n\treturn dao.NewProposalRequestWithFilter(\n\t\ttitle,\n\t\tdesc,\n\t\tdao.NewSimpleExecutor(0, cur, cb, \"\"),\n\t\tgovimpl.NewFilterByTier(memberstore.T1),\n\t)\n}\n\n// setPaused is the private actuator behind ProposeSetPaused's executor\n// callback. It is unexported to ensure no path outside the proposal\n// flow can flip the flag — every state change goes through GovDAO.\n//\n// Emits NamespaceEnforcement{Paused,Unpaused} with the executor's\n// realm path for off-chain audit trails.\nfunc setPaused(_ int, rlm realm, v bool) {\n\tpaused = v\n\tif v {\n\t\tchain.Emit(\"NamespaceEnforcementPaused\", \"by\", rlm.Previous().PkgPath())\n\t} else {\n\t\tchain.Emit(\"NamespaceEnforcementUnpaused\", \"by\", rlm.Previous().PkgPath())\n\t}\n}\n\n// IsPaused reports the current value of the pause flag. Note: when\n// the realm is pre-Enable, IsPaused may return true but the verifier\n// will still pass-through (pre-Enable bypass takes priority).\nfunc IsPaused() bool {\n\treturn paused\n}\n\n// verifier checks namespace deployment permissions.\n// lookup is the registered-name resolver — pass nil to disable that path\n// (used by tests that want to exercise PA-only behavior).\n//\n// Order of checks (top to bottom, first matching wins):\n//  1. !isEnabled → return true   (pre-Enable: testing/dev bypass)\n//  2. isPaused   → return false  (emergency halt — INCLUDES PA)\n//  3. invalid input → return false\n//  4. PA match (addr.String() == namespace) → return true\n//  5. Registered-name lookup match → return true\n//  6. otherwise → return false\n//\n// The pause check is intentionally above the PA check. A SetPaused(true)\n// halts every deploy regardless of namespace shape.\nfunc verifier(isEnabled, isPaused bool, address_XXX address, namespace string, lookup nameLookupFn) bool {\n\tif !isEnabled {\n\t\treturn true // pre-genesis / dev convenience: bypass everything\n\t}\n\n\tif isPaused {\n\t\treturn false // emergency halt: reject every deploy including PA\n\t}\n\n\tif namespace == \"\" || !address_XXX.IsValid() {\n\t\treturn false\n\t}\n\n\t// Path 1: PA (personal-address) namespace.\n\t// gno.land/{p,r}/{ADDRESS}/**\n\tif address_XXX.String() == namespace {\n\t\treturn true\n\t}\n\n\t// Path 2: registered-name namespace via r/sys/users.\n\tif lookup != nil {\n\t\tif owner, ok := lookup(namespace); ok \u0026\u0026 owner == address_XXX {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"avlhelpers","path":"gno.land/p/jefft0/avlhelpers/v0","files":[{"name":"avlhelpers.gno","body":"package avlhelpers\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Iterate the keys in-order starting from the given prefix.\n// It calls the provided callback function for each key-value pair encountered.\n// If the callback returns true, the iteration is stopped.\n// The prefix and keys are treated as byte strings, ignoring possible multi-byte Unicode runes.\nfunc IterateByteStringKeysByPrefix(tree avl.ITree, prefix string, cb avl.IterCbFn) {\n\tend := \"\"\n\tn := len(prefix)\n\t// To make the end of the search, increment the final character ASCII by one.\n\tfor n \u003e 0 {\n\t\tif ascii := int(prefix[n-1]); ascii \u003c 0xff {\n\t\t\tend = prefix[0:n-1] + string(ascii+1)\n\t\t\tbreak\n\t\t}\n\n\t\t// The last character is 0xff. Try the previous character.\n\t\tn--\n\t}\n\n\ttree.Iterate(prefix, end, cb)\n}\n\n// Get a list of keys starting from the given prefix. Limit the\n// number of results to maxResults.\n// The prefix and keys are treated as byte strings, ignoring possible multi-byte Unicode runes.\nfunc ListByteStringKeysByPrefix(tree avl.ITree, prefix string, maxResults int) []string {\n\tresult := []string{}\n\tIterateByteStringKeysByPrefix(tree, prefix, func(key string, value any) bool {\n\t\tresult = append(result, key)\n\t\tif len(result) \u003e= maxResults {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn result\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jefft0/avlhelpers/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"json","path":"gno.land/p/onbloc/json/v0","files":[{"name":"LICENSE","body":"# MIT License\n\nCopyright (c) 2019 Pyzhov Stepan\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"},{"name":"README.md","body":"# JSON Parser\n\nThe JSON parser is a package that provides functionality for parsing and processing JSON strings. This package accepts JSON strings as byte slices.\n\nCurrently, gno does not [support the `reflect` package](https://docs.gno.land/resources/effective-gno#reflection-is-never-clear), so it cannot retrieve type information at runtime. Therefore, it is designed to infer and handle type information when parsing JSON strings using a state machine approach.\n\nAfter passing through the state machine, JSON strings are represented as the `Node` type. The `Node` type represents nodes for JSON data, including various types such as `ObjectNode`, `ArrayNode`, `StringNode`, `NumberNode`, `BoolNode`, and `NullNode`.\n\nThis package provides methods for manipulating, searching, and extracting the Node type.\n\n## State Machine\n\nTo parse JSON strings, a [finite state machine](https://en.wikipedia.org/wiki/Finite-state_machine) approach is used. The state machine transitions to the next state based on the current state and the input character while parsing the JSON string. Through this method, type information can be inferred and processed without reflect, and the amount of parser code can be significantly reduced.\n\nThe image below shows the state transitions of the state machine according to the states and input characters.\n\n```mermaid\nstateDiagram-v2\n    [*] --\u003e __: Start\n    __ --\u003e ST: String\n    __ --\u003e MI: Number\n    __ --\u003e ZE: Zero\n    __ --\u003e IN: Integer\n    __ --\u003e T1: Boolean (true)\n    __ --\u003e F1: Boolean (false)\n    __ --\u003e N1: Null\n    __ --\u003e ec: Empty Object End\n    __ --\u003e cc: Object End\n    __ --\u003e bc: Array End\n    __ --\u003e co: Object Begin\n    __ --\u003e bo: Array Begin\n    __ --\u003e cm: Comma\n    __ --\u003e cl: Colon\n    __ --\u003e OK: Success/End\n    ST --\u003e OK: String Complete\n    MI --\u003e OK: Number Complete\n    ZE --\u003e OK: Zero Complete\n    IN --\u003e OK: Integer Complete\n    T1 --\u003e OK: True Complete\n    F1 --\u003e OK: False Complete\n    N1 --\u003e OK: Null Complete\n    ec --\u003e OK: Empty Object Complete\n    cc --\u003e OK: Object Complete\n    bc --\u003e OK: Array Complete\n    co --\u003e OB: Inside Object\n    bo --\u003e AR: Inside Array\n    cm --\u003e KE: Expecting New Key\n    cm --\u003e VA: Expecting New Value\n    cl --\u003e VA: Expecting Value\n    OB --\u003e ST: String in Object (Key)\n    OB --\u003e ec: Empty Object\n    OB --\u003e cc: End Object\n    AR --\u003e ST: String in Array\n    AR --\u003e bc: End Array\n    KE --\u003e ST: String as Key\n    VA --\u003e ST: String as Value\n    VA --\u003e MI: Number as Value\n    VA --\u003e T1: True as Value\n    VA --\u003e F1: False as Value\n    VA --\u003e N1: Null as Value\n    OK --\u003e [*]: End\n```\n\n## Examples\n\nThis package provides parsing functionality along with encoding and decoding functionality. The following examples demonstrate how to use this package.\n\n### Decoding\n\nDecoding (or Unmarshaling) is the functionality that converts an input byte slice JSON string into a `Node` type.\n\nThe converted `Node` type allows you to modify the JSON data or search and extract data that meets specific conditions.\n\n```go\npackage main\n\nimport (\n    \"gno.land/p/demo/json\"\n    \"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc main() {\n    node, err := json.Unmarshal([]byte(`{\"foo\": \"var\"}`))\n    if err != nil {\n        ufmt.Errorf(\"error: %v\", err)\n    }\n\n    ufmt.Sprintf(\"node: %v\", node)\n}\n```\n\n### Encoding\n\nEncoding (or Marshaling) is the functionality that converts JSON data represented as a Node type into a byte slice JSON string.\n\n\u003e ⚠️ Caution: Converting a large `Node` type into a JSON string may _impact performance_. or might be cause _unexpected behavior_.\n\n```go\npackage main\n\nimport (\n    \"gno.land/p/demo/json\"\n    \"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc main() {\n    node := ObjectNode(\"\", map[string]*Node{\n        \"foo\": StringNode(\"foo\", \"bar\"),\n        \"baz\": NumberNode(\"baz\", 100500),\n        \"qux\": NullNode(\"qux\"),\n    })\n\n    b, err := json.Marshal(node)\n    if err != nil {\n        ufmt.Errorf(\"error: %v\", err)\n    }\n\n    ufmt.Sprintf(\"json: %s\", string(b))\n}\n```\n\n### Searching\n\nOnce the JSON data converted into a `Node` type, you can **search** and **extract** data that satisfy specific conditions. For example, you can find data with a specific type or data with a specific key.\n\nTo use this functionality, you can use methods in the `GetXXX` prefixed methods. The `MustXXX` methods also provide the same functionality as the former methods, but they will **panic** if data doesn't satisfies the condition.\n\nHere is an example of finding data with a specific key. For more examples, please refer to the [node.gno](node.gno) file.\n\n```go\npackage main\n\nimport (\n    \"gno.land/p/demo/json\"\n    \"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc main() {\n    root, err := Unmarshal([]byte(`{\"foo\": true, \"bar\": null}`))\n    if err != nil {\n        ufmt.Errorf(\"error: %v\", err)\n    }\n\n    value, err := root.GetKey(\"foo\")\n    if err != nil {\n        ufmt.Errorf(\"error occurred while getting key, %s\", err)\n    }\n\n    if value.MustBool() != true {\n        ufmt.Errorf(\"value is not true\")\n    }\n\n    value, err = root.GetKey(\"bar\")\n    if err != nil {\n        t.Errorf(\"error occurred while getting key, %s\", err)\n    }\n\n    _, err = root.GetKey(\"baz\")\n    if err == nil {\n        t.Errorf(\"key baz is not exist. must be failed\")\n    }\n}\n```\n\n## Contributing\n\nPlease submit any issues or pull requests for this package through the GitHub repository at [gnolang/gno](\u003chttps://github.com/gnolang/gno\u003e).\n"},{"name":"buffer.gno","body":"package json\n\nimport (\n\t\"errors\"\n\t\"io\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype buffer struct {\n\tdata   []byte\n\tlength int\n\tindex  int\n\n\tlast  States\n\tstate States\n\tclass Classes\n}\n\n// newBuffer creates a new buffer with the given data\nfunc newBuffer(data []byte) *buffer {\n\treturn \u0026buffer{\n\t\tdata:   data,\n\t\tlength: len(data),\n\t\tlast:   GO,\n\t\tstate:  GO,\n\t}\n}\n\n// first retrieves the first non-whitespace (or other escaped) character in the buffer.\nfunc (b *buffer) first() (byte, error) {\n\tfor ; b.index \u003c b.length; b.index++ {\n\t\tc := b.data[b.index]\n\n\t\tif !(c == whiteSpace || c == carriageReturn || c == newLine || c == tab) {\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn 0, io.EOF\n}\n\n// current returns the byte of the current index.\nfunc (b *buffer) current() (byte, error) {\n\tif b.index \u003e= b.length {\n\t\treturn 0, io.EOF\n\t}\n\n\treturn b.data[b.index], nil\n}\n\n// next moves to the next byte and returns it.\nfunc (b *buffer) next() (byte, error) {\n\tb.index++\n\treturn b.current()\n}\n\n// step just moves to the next position.\nfunc (b *buffer) step() error {\n\t_, err := b.next()\n\treturn err\n}\n\n// move moves the index by the given position.\nfunc (b *buffer) move(pos int) error {\n\tnewIndex := b.index + pos\n\n\tif newIndex \u003e b.length {\n\t\treturn io.EOF\n\t}\n\n\tb.index = newIndex\n\n\treturn nil\n}\n\n// slice returns the slice from the current index to the given position.\nfunc (b *buffer) slice(pos int) ([]byte, error) {\n\tend := b.index + pos\n\n\tif end \u003e b.length {\n\t\treturn nil, io.EOF\n\t}\n\n\treturn b.data[b.index:end], nil\n}\n\n// sliceFromIndices returns a slice of the buffer's data starting from 'start' up to (but not including) 'stop'.\nfunc (b *buffer) sliceFromIndices(start, stop int) []byte {\n\tif start \u003e b.length {\n\t\tstart = b.length\n\t}\n\n\tif stop \u003e b.length {\n\t\tstop = b.length\n\t}\n\n\treturn b.data[start:stop]\n}\n\n// skip moves the index to skip the given byte.\nfunc (b *buffer) skip(bs byte) error {\n\tfor b.index \u003c b.length {\n\t\tif b.data[b.index] == bs \u0026\u0026 !b.backslash() {\n\t\t\treturn nil\n\t\t}\n\n\t\tb.index++\n\t}\n\n\treturn io.EOF\n}\n\n// skipAndReturnIndex moves the buffer index forward by one and returns the new index.\nfunc (b *buffer) skipAndReturnIndex() (int, error) {\n\terr := b.step()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn b.index, nil\n}\n\n// skipUntil moves the buffer index forward until it encounters a byte contained in the endTokens set.\nfunc (b *buffer) skipUntil(endTokens map[byte]bool) (int, error) {\n\tfor b.index \u003c b.length {\n\t\tcurrentByte, err := b.current()\n\t\tif err != nil {\n\t\t\treturn b.index, err\n\t\t}\n\n\t\t// Check if the current byte is in the set of end tokens.\n\t\tif _, exists := endTokens[currentByte]; exists {\n\t\t\treturn b.index, nil\n\t\t}\n\n\t\tb.index++\n\t}\n\n\treturn b.index, io.EOF\n}\n\n// significantTokens is a map where the keys are the significant characters in a JSON path.\n// The values in the map are all true, which allows us to use the map as a set for quick lookups.\nvar significantTokens = [256]bool{\n\tdot:          true, // access properties of an object\n\tdollarSign:   true, // root object\n\tatSign:       true, // current object\n\tbracketOpen:  true, // start of an array index or filter expression\n\tbracketClose: true, // end of an array index or filter expression\n}\n\n// filterTokens stores the filter expression tokens.\nvar filterTokens = [256]bool{\n\taesterisk: true, // wildcard\n\tandSign:   true,\n\torSign:    true,\n}\n\n// skipToNextSignificantToken advances the buffer index to the next significant character.\n// Significant characters are defined based on the JSON path syntax.\nfunc (b *buffer) skipToNextSignificantToken() {\n\tfor b.index \u003c b.length {\n\t\tcurrent := b.data[b.index]\n\n\t\tif significantTokens[current] {\n\t\t\tbreak\n\t\t}\n\n\t\tb.index++\n\t}\n}\n\n// backslash checks to see if the number of backslashes before the current index is odd.\n//\n// This is used to check if the current character is escaped. However, unlike the \"unescape\" function,\n// \"backslash\" only serves to check the number of backslashes.\nfunc (b *buffer) backslash() bool {\n\tif b.index == 0 {\n\t\treturn false\n\t}\n\n\tcount := 0\n\tfor i := b.index - 1; ; i-- {\n\t\tif b.data[i] != backSlash {\n\t\t\tbreak\n\t\t}\n\n\t\tcount++\n\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn count%2 != 0\n}\n\n// numIndex holds a map of valid numeric characters\nvar numIndex = [256]bool{\n\t'0': true,\n\t'1': true,\n\t'2': true,\n\t'3': true,\n\t'4': true,\n\t'5': true,\n\t'6': true,\n\t'7': true,\n\t'8': true,\n\t'9': true,\n\t'.': true,\n\t'e': true,\n\t'E': true,\n}\n\n// pathToken checks if the current token is a valid JSON path token.\nfunc (b *buffer) pathToken() error {\n\tvar stack []byte\n\n\tinToken := false\n\tinNumber := false\n\tfirst := b.index\n\n\tfor b.index \u003c b.length {\n\t\tc := b.data[b.index]\n\n\t\tswitch {\n\t\tcase c == doubleQuote || c == singleQuote:\n\t\t\tinToken = true\n\t\t\tif err := b.step(); err != nil {\n\t\t\t\treturn errors.New(\"error stepping through buffer\")\n\t\t\t}\n\n\t\t\tif err := b.skip(c); err != nil {\n\t\t\t\treturn errUnmatchedQuotePath\n\t\t\t}\n\n\t\t\tif b.index \u003e= b.length {\n\t\t\t\treturn errUnmatchedQuotePath\n\t\t\t}\n\n\t\tcase c == bracketOpen || c == parenOpen:\n\t\t\tinToken = true\n\t\t\tstack = append(stack, c)\n\n\t\tcase c == bracketClose || c == parenClose:\n\t\t\tinToken = true\n\t\t\tif len(stack) == 0 || (c == bracketClose \u0026\u0026 stack[len(stack)-1] != bracketOpen) || (c == parenClose \u0026\u0026 stack[len(stack)-1] != parenOpen) {\n\t\t\t\treturn errUnmatchedParenthesis\n\t\t\t}\n\n\t\t\tstack = stack[:len(stack)-1]\n\n\t\tcase pathStateContainsValidPathToken(c):\n\t\t\tinToken = true\n\n\t\tcase c == plus || c == minus:\n\t\t\tif inNumber || (b.index \u003e 0 \u0026\u0026 numIndex[b.data[b.index-1]]) {\n\t\t\t\tinToken = true\n\t\t\t} else if !inToken \u0026\u0026 (b.index+1 \u003c b.length \u0026\u0026 numIndex[b.data[b.index+1]]) {\n\t\t\t\tinToken = true\n\t\t\t\tinNumber = true\n\t\t\t} else if !inToken {\n\t\t\t\treturn errInvalidToken\n\t\t\t}\n\n\t\tdefault:\n\t\t\tif len(stack) != 0 || inToken {\n\t\t\t\tinToken = true\n\t\t\t} else {\n\t\t\t\tgoto end\n\t\t\t}\n\t\t}\n\n\t\tb.index++\n\t}\n\nend:\n\tif len(stack) != 0 {\n\t\treturn errUnmatchedParenthesis\n\t}\n\n\tif first == b.index {\n\t\treturn errors.New(\"no token found\")\n\t}\n\n\tif inNumber \u0026\u0026 !numIndex[b.data[b.index-1]] {\n\t\tinNumber = false\n\t}\n\n\treturn nil\n}\n\nfunc pathStateContainsValidPathToken(c byte) bool {\n\tif significantTokens[c] {\n\t\treturn true\n\t}\n\n\tif filterTokens[c] {\n\t\treturn true\n\t}\n\n\tif numIndex[c] {\n\t\treturn true\n\t}\n\n\tif 'A' \u003c= c \u0026\u0026 c \u003c= 'Z' || 'a' \u003c= c \u0026\u0026 c \u003c= 'z' {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (b *buffer) numeric(token bool) error {\n\tif token {\n\t\tb.last = GO\n\t}\n\n\tfor ; b.index \u003c b.length; b.index++ {\n\t\tb.class = b.getClasses(doubleQuote)\n\t\tif b.class == __ {\n\t\t\treturn errInvalidToken\n\t\t}\n\n\t\tb.state = StateTransitionTable[b.last][b.class]\n\t\tif b.state == __ {\n\t\t\tif token {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn errInvalidToken\n\t\t}\n\n\t\tif b.state \u003c __ {\n\t\t\treturn nil\n\t\t}\n\n\t\tif b.state \u003c MI || b.state \u003e E3 {\n\t\t\treturn nil\n\t\t}\n\n\t\tb.last = b.state\n\t}\n\n\tif b.last != ZE \u0026\u0026 b.last != IN \u0026\u0026 b.last != FR \u0026\u0026 b.last != E3 {\n\t\treturn errInvalidToken\n\t}\n\n\treturn nil\n}\n\nfunc (b *buffer) getClasses(c byte) Classes {\n\tif b.data[b.index] \u003e= 128 {\n\t\treturn C_ETC\n\t}\n\n\tif c == singleQuote {\n\t\treturn QuoteAsciiClasses[b.data[b.index]]\n\t}\n\n\treturn AsciiClasses[b.data[b.index]]\n}\n\nfunc (b *buffer) getState() States {\n\tb.last = b.state\n\n\tb.class = b.getClasses(doubleQuote)\n\tif b.class == __ {\n\t\treturn __\n\t}\n\n\tb.state = StateTransitionTable[b.last][b.class]\n\n\treturn b.state\n}\n\n// string parses a string token from the buffer.\nfunc (b *buffer) string(search byte, token bool) error {\n\tif token {\n\t\tb.last = GO\n\t}\n\n\tfor ; b.index \u003c b.length; b.index++ {\n\t\tb.class = b.getClasses(search)\n\n\t\tif b.class == __ {\n\t\t\treturn errInvalidToken\n\t\t}\n\n\t\tb.state = StateTransitionTable[b.last][b.class]\n\t\tif b.state == __ {\n\t\t\treturn errInvalidToken\n\t\t}\n\n\t\tif b.state \u003c __ {\n\t\t\tbreak\n\t\t}\n\n\t\tb.last = b.state\n\t}\n\n\treturn nil\n}\n\nfunc (b *buffer) word(bs []byte) error {\n\tvar c byte\n\n\tmax := len(bs)\n\tindex := 0\n\n\tfor ; b.index \u003c b.length \u0026\u0026 index \u003c max; b.index++ {\n\t\tc = b.data[b.index]\n\n\t\tif c != bs[index] {\n\t\t\treturn errInvalidToken\n\t\t}\n\n\t\tindex++\n\t\tif index \u003e= max {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif index != max {\n\t\treturn errInvalidToken\n\t}\n\n\treturn nil\n}\n\nfunc numberKind2f64(value any) (result float64, err error) {\n\tswitch typed := value.(type) {\n\tcase float64:\n\t\tresult = typed\n\tcase float32:\n\t\tresult = float64(typed)\n\tcase int:\n\t\tresult = float64(typed)\n\tcase int8:\n\t\tresult = float64(typed)\n\tcase int16:\n\t\tresult = float64(typed)\n\tcase int32:\n\t\tresult = float64(typed)\n\tcase int64:\n\t\tresult = float64(typed)\n\tcase uint:\n\t\tresult = float64(typed)\n\tcase uint8:\n\t\tresult = float64(typed)\n\tcase uint16:\n\t\tresult = float64(typed)\n\tcase uint32:\n\t\tresult = float64(typed)\n\tcase uint64:\n\t\tresult = float64(typed)\n\tdefault:\n\t\terr = ufmt.Errorf(\"invalid number type: %T\", value)\n\t}\n\n\treturn\n}\n"},{"name":"builder.gno","body":"package json\n\ntype NodeBuilder struct {\n\tnode *Node\n}\n\nfunc Builder() *NodeBuilder {\n\treturn \u0026NodeBuilder{node: ObjectNode(\"\", nil)}\n}\n\nfunc (b *NodeBuilder) WriteString(key, value string) *NodeBuilder {\n\tb.node.AppendObject(key, StringNode(\"\", value))\n\treturn b\n}\n\nfunc (b *NodeBuilder) WriteNumber(key string, value float64) *NodeBuilder {\n\tb.node.AppendObject(key, NumberNode(\"\", value))\n\treturn b\n}\n\nfunc (b *NodeBuilder) WriteBool(key string, value bool) *NodeBuilder {\n\tb.node.AppendObject(key, BoolNode(\"\", value))\n\treturn b\n}\n\nfunc (b *NodeBuilder) WriteNull(key string) *NodeBuilder {\n\tb.node.AppendObject(key, NullNode(\"\"))\n\treturn b\n}\n\nfunc (b *NodeBuilder) WriteObject(key string, fn func(*NodeBuilder)) *NodeBuilder {\n\tnestedBuilder := \u0026NodeBuilder{node: ObjectNode(\"\", nil)}\n\tfn(nestedBuilder)\n\tb.node.AppendObject(key, nestedBuilder.node)\n\treturn b\n}\n\nfunc (b *NodeBuilder) WriteArray(key string, fn func(*ArrayBuilder)) *NodeBuilder {\n\tarrayBuilder := \u0026ArrayBuilder{nodes: []*Node{}}\n\tfn(arrayBuilder)\n\tb.node.AppendObject(key, ArrayNode(\"\", arrayBuilder.nodes))\n\treturn b\n}\n\nfunc (b *NodeBuilder) Node() *Node {\n\treturn b.node\n}\n\ntype ArrayBuilder struct {\n\tnodes []*Node\n}\n\nfunc (ab *ArrayBuilder) WriteString(value string) *ArrayBuilder {\n\tab.nodes = append(ab.nodes, StringNode(\"\", value))\n\treturn ab\n}\n\nfunc (ab *ArrayBuilder) WriteNumber(value float64) *ArrayBuilder {\n\tab.nodes = append(ab.nodes, NumberNode(\"\", value))\n\treturn ab\n}\n\nfunc (ab *ArrayBuilder) WriteInt(value int) *ArrayBuilder {\n\treturn ab.WriteNumber(float64(value))\n}\n\nfunc (ab *ArrayBuilder) WriteBool(value bool) *ArrayBuilder {\n\tab.nodes = append(ab.nodes, BoolNode(\"\", value))\n\treturn ab\n}\n\nfunc (ab *ArrayBuilder) WriteNull() *ArrayBuilder {\n\tab.nodes = append(ab.nodes, NullNode(\"\"))\n\treturn ab\n}\n\nfunc (ab *ArrayBuilder) WriteObject(fn func(*NodeBuilder)) *ArrayBuilder {\n\tnestedBuilder := \u0026NodeBuilder{node: ObjectNode(\"\", nil)}\n\tfn(nestedBuilder)\n\tab.nodes = append(ab.nodes, nestedBuilder.node)\n\treturn ab\n}\n\nfunc (ab *ArrayBuilder) WriteArray(fn func(*ArrayBuilder)) *ArrayBuilder {\n\tnestedArrayBuilder := \u0026ArrayBuilder{nodes: []*Node{}}\n\tfn(nestedArrayBuilder)\n\tab.nodes = append(ab.nodes, ArrayNode(\"\", nestedArrayBuilder.nodes))\n\treturn ab\n}\n"},{"name":"decode.gno","body":"// ref: https://github.com/spyzhov/ajson/blob/master/decode.go\n\npackage json\n\nimport (\n\t\"errors\"\n\t\"io\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// This limits the max nesting depth to prevent stack overflow.\n// This is permitted by https://tools.ietf.org/html/rfc7159#section-9\nconst maxNestingDepth = 10000\n\n// Unmarshal parses the JSON-encoded data and returns a Node.\n// The data must be a valid JSON-encoded value.\n//\n// Usage:\n//\n//\tnode, err := json.Unmarshal([]byte(`{\"key\": \"value\"}`))\n//\tif err != nil {\n//\t\tufmt.Println(err)\n//\t}\n//\tprintln(node) // {\"key\": \"value\"}\nfunc Unmarshal(data []byte) (*Node, error) {\n\tbuf := newBuffer(data)\n\n\tvar (\n\t\tstate   States\n\t\tkey     *string\n\t\tcurrent *Node\n\t\tnesting int\n\t\tuseKey  = func() **string {\n\t\t\ttmp := cptrs(key)\n\t\t\tkey = nil\n\t\t\treturn \u0026tmp\n\t\t}\n\t\terr error\n\t)\n\n\tif _, err = buf.first(); err != nil {\n\t\treturn nil, io.EOF\n\t}\n\n\tfor {\n\t\tstate = buf.getState()\n\t\tif state == __ {\n\t\t\treturn nil, unexpectedTokenError(buf.data, buf.index)\n\t\t}\n\n\t\t// region state machine\n\t\tif state \u003e= GO {\n\t\t\tswitch buf.state {\n\t\t\tcase ST: // string\n\t\t\t\tif current != nil \u0026\u0026 current.IsObject() \u0026\u0026 key == nil {\n\t\t\t\t\t// key detected\n\t\t\t\t\tif key, err = getString(buf); err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tbuf.state = CO\n\t\t\t\t} else {\n\t\t\t\t\tcurrent, nesting, err = createNestedNode(current, buf, String, nesting, useKey())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\terr = buf.string(doubleQuote, false)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent, nesting = updateNode(current, buf, nesting, true)\n\t\t\t\t\tbuf.state = OK\n\t\t\t\t}\n\n\t\t\tcase MI, ZE, IN: // number\n\t\t\t\tcurrent, err = processNumericNode(current, buf, useKey())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\tcase T1, F1: // boolean\n\t\t\t\tliteral := falseLiteral\n\t\t\t\tif buf.state == T1 {\n\t\t\t\t\tliteral = trueLiteral\n\t\t\t\t}\n\n\t\t\t\tcurrent, nesting, err = processLiteralNode(current, buf, Boolean, literal, useKey(), nesting)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\tcase N1: // null\n\t\t\t\tcurrent, nesting, err = processLiteralNode(current, buf, Null, nullLiteral, useKey(), nesting)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// region action\n\t\t\tswitch state {\n\t\t\tcase ec, cc: // \u003cempty\u003e }\n\t\t\t\tif key != nil {\n\t\t\t\t\treturn nil, unexpectedTokenError(buf.data, buf.index)\n\t\t\t\t}\n\n\t\t\t\tcurrent, nesting, err = updateNodeAndSetBufferState(current, buf, nesting, Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\tcase bc: // ]\n\t\t\t\tcurrent, nesting, err = updateNodeAndSetBufferState(current, buf, nesting, Array)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\tcase co, bo: // { [\n\t\t\t\tvalTyp, bState := Object, OB\n\t\t\t\tif state == bo {\n\t\t\t\t\tvalTyp, bState = Array, AR\n\t\t\t\t}\n\n\t\t\t\tcurrent, nesting, err = createNestedNode(current, buf, valTyp, nesting, useKey())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tbuf.state = bState\n\n\t\t\tcase cm: // ,\n\t\t\t\tif current == nil {\n\t\t\t\t\treturn nil, unexpectedTokenError(buf.data, buf.index)\n\t\t\t\t}\n\n\t\t\t\tif !current.isContainer() {\n\t\t\t\t\treturn nil, unexpectedTokenError(buf.data, buf.index)\n\t\t\t\t}\n\n\t\t\t\tif current.IsObject() {\n\t\t\t\t\tbuf.state = KE // key expected\n\t\t\t\t} else {\n\t\t\t\t\tbuf.state = VA // value expected\n\t\t\t\t}\n\n\t\t\tcase cl: // :\n\t\t\t\tif current == nil || !current.IsObject() || key == nil {\n\t\t\t\t\treturn nil, unexpectedTokenError(buf.data, buf.index)\n\t\t\t\t}\n\n\t\t\t\tbuf.state = VA\n\n\t\t\tdefault:\n\t\t\t\treturn nil, unexpectedTokenError(buf.data, buf.index)\n\t\t\t}\n\t\t}\n\n\t\tif buf.step() != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif _, err = buf.first(); err != nil {\n\t\t\terr = nil\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif current == nil || buf.state != OK {\n\t\treturn nil, io.EOF\n\t}\n\n\troot := current.root()\n\tif !root.ready() {\n\t\treturn nil, io.EOF\n\t}\n\n\treturn root, err\n}\n\n// UnmarshalSafe parses the JSON-encoded data and returns a Node.\nfunc UnmarshalSafe(data []byte) (*Node, error) {\n\tvar safe []byte\n\tsafe = append(safe, data...)\n\treturn Unmarshal(safe)\n}\n\n// processNumericNode creates a new node, processes a numeric value,\n// sets the node's borders, and moves to the previous node.\nfunc processNumericNode(current *Node, buf *buffer, key **string) (*Node, error) {\n\tvar err error\n\tcurrent, err = createNode(current, buf, Number, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = buf.numeric(false); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcurrent.borders[1] = buf.index\n\tif current.prev != nil {\n\t\tcurrent = current.prev\n\t}\n\n\tbuf.index -= 1\n\tbuf.state = OK\n\n\treturn current, nil\n}\n\n// processLiteralNode creates a new node, processes a literal value,\n// sets the node's borders, and moves to the previous node.\nfunc processLiteralNode(\n\tcurrent *Node,\n\tbuf *buffer,\n\tliteralType ValueType,\n\tliteralValue []byte,\n\tuseKey **string,\n\tnesting int,\n) (*Node, int, error) {\n\tvar err error\n\tcurrent, nesting, err = createLiteralNode(current, buf, literalType, literalValue, useKey, nesting)\n\tif err != nil {\n\t\treturn nil, nesting, err\n\t}\n\treturn current, nesting, nil\n}\n\n// isValidContainerType checks if the current node is a valid container (object or array).\n// The container must satisfy the following conditions:\n//  1. The current node must not be nil.\n//  2. The current node must be an object or array.\n//  3. The current node must not be ready.\nfunc isValidContainerType(current *Node, nodeType ValueType) bool {\n\tswitch nodeType {\n\tcase Object:\n\t\treturn current != nil \u0026\u0026 current.IsObject() \u0026\u0026 !current.ready()\n\tcase Array:\n\t\treturn current != nil \u0026\u0026 current.IsArray() \u0026\u0026 !current.ready()\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// getString extracts a string from the buffer and advances the buffer index past the string.\nfunc getString(b *buffer) (*string, error) {\n\tstart := b.index\n\tif err := b.string(doubleQuote, false); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalue, ok := Unquote(b.data[start:b.index+1], doubleQuote)\n\tif !ok {\n\t\treturn nil, unexpectedTokenError(b.data, start)\n\t}\n\n\treturn \u0026value, nil\n}\n\n// createNode creates a new node and sets the key if it is not nil.\nfunc createNode(\n\tcurrent *Node,\n\tbuf *buffer,\n\tnodeType ValueType,\n\tkey **string,\n) (*Node, error) {\n\tvar err error\n\tcurrent, err = NewNode(current, buf, nodeType, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn current, nil\n}\n\n// createNestedNode creates a new nested node (array or object) and sets the key if it is not nil.\nfunc createNestedNode(\n\tcurrent *Node,\n\tbuf *buffer,\n\tnodeType ValueType,\n\tnesting int,\n\tkey **string,\n) (*Node, int, error) {\n\tvar err error\n\tif nesting, err = checkNestingDepth(nesting); err != nil {\n\t\treturn nil, nesting, err\n\t}\n\n\tif current, err = createNode(current, buf, nodeType, key); err != nil {\n\t\treturn nil, nesting, err\n\t}\n\n\treturn current, nesting, nil\n}\n\n// createLiteralNode creates a new literal node and sets the key if it is not nil.\n// The literal is a byte slice that represents a boolean or null value.\nfunc createLiteralNode(\n\tcurrent *Node,\n\tbuf *buffer,\n\tliteralType ValueType,\n\tliteral []byte,\n\tuseKey **string,\n\tnesting int,\n) (*Node, int, error) {\n\tvar err error\n\tif current, err = createNode(current, buf, literalType, useKey); err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tif err = buf.word(literal); err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tcurrent, nesting = updateNode(current, buf, nesting, false)\n\tbuf.state = OK\n\n\treturn current, nesting, nil\n}\n\n// updateNode updates the current node and returns the previous node.\nfunc updateNode(\n\tcurrent *Node, buf *buffer, nesting int, decreaseLevel bool,\n) (*Node, int) {\n\tcurrent.borders[1] = buf.index + 1\n\n\tprev := current.prev\n\tif prev == nil {\n\t\treturn current, nesting\n\t}\n\n\tcurrent = prev\n\tif decreaseLevel {\n\t\tnesting--\n\t}\n\n\treturn current, nesting\n}\n\n// updateNodeAndSetBufferState updates the current node and sets the buffer state to OK.\nfunc updateNodeAndSetBufferState(\n\tcurrent *Node,\n\tbuf *buffer,\n\tnesting int,\n\ttyp ValueType,\n) (*Node, int, error) {\n\tif !isValidContainerType(current, typ) {\n\t\treturn nil, nesting, unexpectedTokenError(buf.data, buf.index)\n\t}\n\n\tcurrent, nesting = updateNode(current, buf, nesting, true)\n\tbuf.state = OK\n\n\treturn current, nesting, nil\n}\n\n// checkNestingDepth checks if the nesting depth is within the maximum allowed depth.\nfunc checkNestingDepth(nesting int) (int, error) {\n\tif nesting \u003e= maxNestingDepth {\n\t\treturn nesting, errors.New(\"maximum nesting depth exceeded\")\n\t}\n\n\treturn nesting + 1, nil\n}\n\nfunc unexpectedTokenError(data []byte, index int) error {\n\treturn ufmt.Errorf(\"unexpected token at index %d. data %b\", index, data)\n}\n"},{"name":"encode.gno","body":"package json\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Marshal returns the JSON encoding of a Node.\nfunc Marshal(node *Node) ([]byte, error) {\n\tvar (\n\t\tbuf  bytes.Buffer\n\t\tsVal string\n\t\tbVal bool\n\t\tnVal float64\n\t\toVal []byte\n\t\terr  error\n\t)\n\n\tif node == nil {\n\t\treturn nil, errors.New(\"node is nil\")\n\t}\n\n\tif !node.modified \u0026\u0026 !node.ready() {\n\t\treturn nil, errors.New(\"node is not ready\")\n\t}\n\n\tif !node.modified \u0026\u0026 node.ready() {\n\t\tbuf.Write(node.source())\n\t}\n\n\tif node.modified {\n\t\tswitch node.nodeType {\n\t\tcase Null:\n\t\t\tbuf.Write(nullLiteral)\n\n\t\tcase Number:\n\t\t\tnVal, err = node.GetNumeric()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tnum := strconv.FormatFloat(nVal, 'f', -1, 64)\n\t\t\tbuf.WriteString(num)\n\n\t\tcase String:\n\t\t\tsVal, err = node.GetString()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tquoted := ufmt.Sprintf(\"%s\", strconv.Quote(sVal))\n\t\t\tbuf.WriteString(quoted)\n\n\t\tcase Boolean:\n\t\t\tbVal, err = node.GetBool()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tbStr := ufmt.Sprintf(\"%t\", bVal)\n\t\t\tbuf.WriteString(bStr)\n\n\t\tcase Array:\n\t\t\tbuf.WriteByte(bracketOpen)\n\n\t\t\tfor i := 0; i \u003c len(node.next); i++ {\n\t\t\t\tif i != 0 {\n\t\t\t\t\tbuf.WriteByte(comma)\n\t\t\t\t}\n\n\t\t\t\telem, ok := node.next[strconv.Itoa(i)]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, ufmt.Errorf(\"array element %d is not found\", i)\n\t\t\t\t}\n\n\t\t\t\toVal, err = Marshal(elem)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tbuf.Write(oVal)\n\t\t\t}\n\n\t\t\tbuf.WriteByte(bracketClose)\n\n\t\tcase Object:\n\t\t\tbuf.WriteByte(curlyOpen)\n\n\t\t\tbVal = false\n\t\t\tfor k, v := range node.next {\n\t\t\t\tif bVal {\n\t\t\t\t\tbuf.WriteByte(comma)\n\t\t\t\t} else {\n\t\t\t\t\tbVal = true\n\t\t\t\t}\n\n\t\t\t\tkey := ufmt.Sprintf(\"%s\", strconv.Quote(k))\n\t\t\t\tbuf.WriteString(key)\n\t\t\t\tbuf.WriteByte(colon)\n\n\t\t\t\toVal, err = Marshal(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tbuf.Write(oVal)\n\t\t\t}\n\n\t\t\tbuf.WriteByte(curlyClose)\n\t\t}\n\t}\n\n\treturn buf.Bytes(), nil\n}\n"},{"name":"errors.gno","body":"package json\n\nimport \"errors\"\n\nvar (\n\terrNilNode               = errors.New(\"node is nil\")\n\terrNotArrayNode          = errors.New(\"node is not array\")\n\terrNotBoolNode           = errors.New(\"node is not boolean\")\n\terrNotNullNode           = errors.New(\"node is not null\")\n\terrNotNumberNode         = errors.New(\"node is not number\")\n\terrNotObjectNode         = errors.New(\"node is not object\")\n\terrNotStringNode         = errors.New(\"node is not string\")\n\terrInvalidToken          = errors.New(\"invalid token\")\n\terrIndexNotFound         = errors.New(\"index not found\")\n\terrInvalidAppend         = errors.New(\"can't append value to non-appendable node\")\n\terrInvalidAppendCycle    = errors.New(\"appending value to itself or its children or parents will cause a cycle\")\n\terrInvalidEscapeSequence = errors.New(\"invalid escape sequence\")\n\terrInvalidStringValue    = errors.New(\"invalid string value\")\n\terrEmptyBooleanNode      = errors.New(\"boolean node is empty\")\n\terrEmptyStringNode       = errors.New(\"string node is empty\")\n\terrKeyRequired           = errors.New(\"key is required for object\")\n\terrUnmatchedParenthesis  = errors.New(\"mismatched bracket or parenthesis\")\n\terrUnmatchedQuotePath    = errors.New(\"unmatched quote in path\")\n)\n\nvar (\n\terrInvalidStringInput    = errors.New(\"invalid string input\")\n\terrMalformedBooleanValue = errors.New(\"malformed boolean value\")\n\terrEmptyByteSlice        = errors.New(\"empty byte slice\")\n\terrInvalidExponentValue  = errors.New(\"invalid exponent value\")\n\terrNonDigitCharacters    = errors.New(\"non-digit characters found\")\n\terrNumericRangeExceeded  = errors.New(\"numeric value exceeds the range limit\")\n\terrMultipleDecimalPoints = errors.New(\"multiple decimal points found\")\n)\n"},{"name":"escape.gno","body":"package json\n\nimport (\n\t\"unicode/utf8\"\n)\n\nconst (\n\tsupplementalPlanesOffset     = 0x10000\n\thighSurrogateOffset          = 0xD800\n\tlowSurrogateOffset           = 0xDC00\n\tsurrogateEnd                 = 0xDFFF\n\tbasicMultilingualPlaneOffset = 0xFFFF\n\tbadHex                       = -1\n\n\tsingleUnicodeEscapeLen = 6\n\tsurrogatePairLen       = 12\n)\n\nvar hexLookupTable = [256]int{\n\t'0': 0x0, '1': 0x1, '2': 0x2, '3': 0x3, '4': 0x4,\n\t'5': 0x5, '6': 0x6, '7': 0x7, '8': 0x8, '9': 0x9,\n\t'A': 0xA, 'B': 0xB, 'C': 0xC, 'D': 0xD, 'E': 0xE, 'F': 0xF,\n\t'a': 0xA, 'b': 0xB, 'c': 0xC, 'd': 0xD, 'e': 0xE, 'f': 0xF,\n\t// Fill unspecified index-value pairs with key and value of -1\n\t'G': -1, 'H': -1, 'I': -1, 'J': -1,\n\t'K': -1, 'L': -1, 'M': -1, 'N': -1,\n\t'O': -1, 'P': -1, 'Q': -1, 'R': -1,\n\t'S': -1, 'T': -1, 'U': -1, 'V': -1,\n\t'W': -1, 'X': -1, 'Y': -1, 'Z': -1,\n\t'g': -1, 'h': -1, 'i': -1, 'j': -1,\n\t'k': -1, 'l': -1, 'm': -1, 'n': -1,\n\t'o': -1, 'p': -1, 'q': -1, 'r': -1,\n\t's': -1, 't': -1, 'u': -1, 'v': -1,\n\t'w': -1, 'x': -1, 'y': -1, 'z': -1,\n}\n\nfunc h2i(c byte) int {\n\treturn hexLookupTable[c]\n}\n\n// Unescape takes an input byte slice, processes it to Unescape certain characters,\n// and writes the result into an output byte slice.\n//\n// it returns the processed slice and any error encountered during the Unescape operation.\nfunc Unescape(input, output []byte) ([]byte, error) {\n\t// ensure the output slice has enough capacity to hold the input slice.\n\tinputLen := len(input)\n\tif cap(output) \u003c inputLen {\n\t\toutput = make([]byte, inputLen)\n\t}\n\n\tinPos, outPos := 0, 0\n\n\tfor inPos \u003c len(input) {\n\t\tc := input[inPos]\n\t\tif c != backSlash {\n\t\t\toutput[outPos] = c\n\t\t\tinPos++\n\t\t\toutPos++\n\t\t} else {\n\t\t\t// process escape sequence\n\t\t\tinLen, outLen, err := processEscapedUTF8(input[inPos:], output[outPos:])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinPos += inLen\n\t\t\toutPos += outLen\n\t\t}\n\t}\n\n\treturn output[:outPos], nil\n}\n\n// isSurrogatePair returns true if the rune is a surrogate pair.\n//\n// A surrogate pairs are used in UTF-16 encoding to encode characters\n// outside the Basic Multilingual Plane (BMP).\nfunc isSurrogatePair(r rune) bool {\n\treturn highSurrogateOffset \u003c= r \u0026\u0026 r \u003c= surrogateEnd\n}\n\n// isHighSurrogate checks if the rune is a high surrogate (U+D800 to U+DBFF).\nfunc isHighSurrogate(r rune) bool {\n\treturn r \u003e= highSurrogateOffset \u0026\u0026 r \u003c= 0xDBFF\n}\n\n// isLowSurrogate checks if the rune is a low surrogate (U+DC00 to U+DFFF).\nfunc isLowSurrogate(r rune) bool {\n\treturn r \u003e= lowSurrogateOffset \u0026\u0026 r \u003c= surrogateEnd\n}\n\n// combineSurrogates reconstruct the original unicode code points in the\n// supplemental plane by combinin the high and low surrogate.\n//\n// The hight surrogate in the range from U+D800 to U+DBFF,\n// and the low surrogate in the range from U+DC00 to U+DFFF.\n//\n// The formula to combine the surrogates is:\n// (high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000\nfunc combineSurrogates(high, low rune) rune {\n\treturn ((high - highSurrogateOffset) \u003c\u003c 10) + (low - lowSurrogateOffset) + supplementalPlanesOffset\n}\n\n// deocdeSingleUnicodeEscape decodes a unicode escape sequence (e.g., \\uXXXX) into a rune.\nfunc decodeSingleUnicodeEscape(b []byte) (rune, bool) {\n\tif len(b) \u003c 6 {\n\t\treturn utf8.RuneError, false\n\t}\n\n\t// convert hex to decimal\n\th1, h2, h3, h4 := h2i(b[2]), h2i(b[3]), h2i(b[4]), h2i(b[5])\n\tif h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {\n\t\treturn utf8.RuneError, false\n\t}\n\n\treturn rune(h1\u003c\u003c12 + h2\u003c\u003c8 + h3\u003c\u003c4 + h4), true\n}\n\n// decodeUnicodeEscape decodes a Unicode escape sequence from a byte slice.\n// It handles both single Unicode escape sequences and surrogate pairs.\nfunc decodeUnicodeEscape(b []byte) (rune, int) {\n\t// decode the first Unicode escape sequence.\n\tr, ok := decodeSingleUnicodeEscape(b)\n\tif !ok {\n\t\treturn utf8.RuneError, -1\n\t}\n\n\t// if the rune is within the BMP and not a surrogate, return it\n\tif r \u003c= basicMultilingualPlaneOffset \u0026\u0026 !isSurrogatePair(r) {\n\t\treturn r, 6\n\t}\n\n\tif !isHighSurrogate(r) {\n\t\t// invalid surrogate pair.\n\t\treturn utf8.RuneError, -1\n\t}\n\n\t// if the rune is a high surrogate, need to decode the next escape sequence.\n\n\t// ensure there are enough bytes for the next escape sequence.\n\tif len(b) \u003c surrogatePairLen {\n\t\treturn utf8.RuneError, -1\n\t}\n\t// decode the second Unicode escape sequence.\n\tr2, ok := decodeSingleUnicodeEscape(b[singleUnicodeEscapeLen:])\n\tif !ok {\n\t\treturn utf8.RuneError, -1\n\t}\n\t// check if the second rune is a low surrogate.\n\tif isLowSurrogate(r2) {\n\t\tcombined := combineSurrogates(r, r2)\n\t\treturn combined, surrogatePairLen\n\t}\n\treturn utf8.RuneError, -1\n}\n\nvar escapeByteSet = [256]byte{\n\t'\"':  doubleQuote,\n\t'\\\\': backSlash,\n\t'/':  slash,\n\t'b':  backSpace,\n\t'f':  formFeed,\n\t'n':  newLine,\n\t'r':  carriageReturn,\n\t't':  tab,\n}\n\n// Unquote takes a byte slice and unquotes it by removing\n// the surrounding quotes and unescaping the contents.\nfunc Unquote(s []byte, border byte) (string, bool) {\n\ts, ok := unquoteBytes(s, border)\n\treturn string(s), ok\n}\n\n// unquoteBytes takes a byte slice and unquotes it by removing\nfunc unquoteBytes(s []byte, border byte) ([]byte, bool) {\n\tif len(s) \u003c 2 || s[0] != border || s[len(s)-1] != border {\n\t\treturn nil, false\n\t}\n\n\ts = s[1 : len(s)-1]\n\n\tr := 0\n\tfor r \u003c len(s) {\n\t\tc := s[r]\n\n\t\tif c == backSlash || c == border || c \u003c 0x20 {\n\t\t\tbreak\n\t\t}\n\n\t\tif c \u003c utf8.RuneSelf {\n\t\t\tr++\n\t\t\tcontinue\n\t\t}\n\n\t\trr, size := utf8.DecodeRune(s[r:])\n\t\tif rr == utf8.RuneError \u0026\u0026 size == 1 {\n\t\t\tbreak\n\t\t}\n\n\t\tr += size\n\t}\n\n\tif r == len(s) {\n\t\treturn s, true\n\t}\n\n\tutfDoubleMax := utf8.UTFMax * 2\n\tb := make([]byte, len(s)+utfDoubleMax)\n\tw := copy(b, s[0:r])\n\n\tfor r \u003c len(s) {\n\t\tif w \u003e= len(b)-utf8.UTFMax {\n\t\t\tnb := make([]byte, utfDoubleMax+(2*len(b)))\n\t\t\tcopy(nb, b)\n\t\t\tb = nb\n\t\t}\n\n\t\tc := s[r]\n\t\tif c == backSlash {\n\t\t\tr++\n\t\t\tif r \u003e= len(s) {\n\t\t\t\treturn nil, false\n\t\t\t}\n\n\t\t\tif s[r] == 'u' {\n\t\t\t\trr, res := decodeUnicodeEscape(s[r-1:])\n\t\t\t\tif res \u003c 0 {\n\t\t\t\t\treturn nil, false\n\t\t\t\t}\n\n\t\t\t\tw += utf8.EncodeRune(b[w:], rr)\n\t\t\t\tr += 5\n\t\t\t} else {\n\t\t\t\tdecode := escapeByteSet[s[r]]\n\t\t\t\tif decode == 0 {\n\t\t\t\t\treturn nil, false\n\t\t\t\t}\n\n\t\t\t\tif decode == doubleQuote || decode == backSlash || decode == slash {\n\t\t\t\t\tdecode = s[r]\n\t\t\t\t}\n\n\t\t\t\tb[w] = decode\n\t\t\t\tr++\n\t\t\t\tw++\n\t\t\t}\n\t\t} else if c == border || c \u003c 0x20 {\n\t\t\treturn nil, false\n\t\t} else if c \u003c utf8.RuneSelf {\n\t\t\tb[w] = c\n\t\t\tr++\n\t\t\tw++\n\t\t} else {\n\t\t\trr, size := utf8.DecodeRune(s[r:])\n\n\t\t\tif rr == utf8.RuneError \u0026\u0026 size == 1 {\n\t\t\t\treturn nil, false\n\t\t\t}\n\n\t\t\tr += size\n\t\t\tw += utf8.EncodeRune(b[w:], rr)\n\t\t}\n\t}\n\n\treturn b[:w], true\n}\n\n// processEscapedUTF8 converts escape sequences to UTF-8 characters.\n// It decodes Unicode escape sequences (\\uXXXX) to UTF-8 and\n// converts standard escape sequences (e.g., \\n) to their corresponding special characters.\nfunc processEscapedUTF8(in, out []byte) (int, int, error) {\n\tif len(in) \u003c 2 || in[0] != backSlash {\n\t\treturn -1, -1, errInvalidEscapeSequence\n\t}\n\n\tescapeSeqLen := 2\n\tescapeChar := in[1]\n\n\tif escapeChar != 'u' {\n\t\tval := escapeByteSet[escapeChar]\n\t\tif val == 0 {\n\t\t\treturn -1, -1, errInvalidEscapeSequence\n\t\t}\n\n\t\tout[0] = val\n\t\treturn escapeSeqLen, 1, nil\n\t}\n\n\tr, size := decodeUnicodeEscape(in)\n\tif size == -1 {\n\t\treturn -1, -1, errInvalidEscapeSequence\n\t}\n\n\toutLen := utf8.EncodeRune(out, r)\n\n\treturn size, outLen, nil\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/onbloc/json/v0\"\ngno = \"0.9\"\n"},{"name":"indent.gno","body":"package json\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n)\n\n// indentGrowthFactor specifies the growth factor of indenting JSON input.\n// A factor no higher than 2 ensures that wasted space never exceeds 50%.\nconst indentGrowthFactor = 2\n\n// IndentJSON formats the JSON data with the specified indentation.\nfunc Indent(data []byte, indent string) ([]byte, error) {\n\tvar (\n\t\tout        bytes.Buffer\n\t\tlevel      int\n\t\tinArray    bool\n\t\tarrayDepth int\n\t)\n\n\tfor i := 0; i \u003c len(data); i++ {\n\t\tc := data[i] // current character\n\n\t\tswitch c {\n\t\tcase bracketOpen:\n\t\t\tarrayDepth++\n\t\t\tif arrayDepth \u003e 1 {\n\t\t\t\tlevel++ // increase the level if it's nested array\n\t\t\t\tinArray = true\n\n\t\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif err := writeNewlineAndIndent(\u0026out, level, indent); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// case of the top-level array\n\t\t\t\tinArray = true\n\t\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase bracketClose:\n\t\t\tif inArray \u0026\u0026 arrayDepth \u003e 1 { // nested array\n\t\t\t\tlevel--\n\t\t\t\tif err := writeNewlineAndIndent(\u0026out, level, indent); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tarrayDepth--\n\t\t\tif arrayDepth == 0 {\n\t\t\t\tinArray = false\n\t\t\t}\n\n\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\tcase curlyOpen:\n\t\t\t// check if the empty object or array\n\t\t\t// we don't need to apply the indent when it's empty containers.\n\t\t\tif i+1 \u003c len(data) \u0026\u0026 data[i+1] == curlyClose {\n\t\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\ti++ // skip next character\n\t\t\t\tif err := out.WriteByte(data[i]); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tlevel++\n\t\t\t\tif err := writeNewlineAndIndent(\u0026out, level, indent); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase curlyClose:\n\t\t\tlevel--\n\t\t\tif err := writeNewlineAndIndent(\u0026out, level, indent); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\tcase comma, colon:\n\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif inArray \u0026\u0026 arrayDepth \u003e 1 { // nested array\n\t\t\t\tif err := writeNewlineAndIndent(\u0026out, level, indent); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else if c == colon {\n\t\t\t\tif err := out.WriteByte(' '); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\tif err := out.WriteByte(c); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out.Bytes(), nil\n}\n\nfunc writeNewlineAndIndent(out *bytes.Buffer, level int, indent string) error {\n\tif err := out.WriteByte('\\n'); err != nil {\n\t\treturn err\n\t}\n\n\tidt := strings.Repeat(indent, level*indentGrowthFactor)\n\tif _, err := out.WriteString(idt); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"},{"name":"internal.gno","body":"package json\n\n// Reference: https://github.com/freddierice/php_source/blob/467ed5d6edff72219afd3e644516f131118ef48e/ext/json/JSON_parser.c\n// Copyright (c) 2005 JSON.org\n\n// Go implementation is taken from: https://github.com/spyzhov/ajson/blob/master/internal/state.go\n\ntype (\n\tStates  int8 // possible states of the parser\n\tClasses int8 // JSON string character types\n)\n\nconst __ = -1\n\n// enum classes\nconst (\n\tC_SPACE Classes = iota /* space */\n\tC_WHITE                /* other whitespace */\n\tC_LCURB                /* {  */\n\tC_RCURB                /* } */\n\tC_LSQRB                /* [ */\n\tC_RSQRB                /* ] */\n\tC_COLON                /* : */\n\tC_COMMA                /* , */\n\tC_QUOTE                /* \" */\n\tC_BACKS                /* \\ */\n\tC_SLASH                /* / */\n\tC_PLUS                 /* + */\n\tC_MINUS                /* - */\n\tC_POINT                /* . */\n\tC_ZERO                 /* 0 */\n\tC_DIGIT                /* 123456789 */\n\tC_LOW_A                /* a */\n\tC_LOW_B                /* b */\n\tC_LOW_C                /* c */\n\tC_LOW_D                /* d */\n\tC_LOW_E                /* e */\n\tC_LOW_F                /* f */\n\tC_LOW_L                /* l */\n\tC_LOW_N                /* n */\n\tC_LOW_R                /* r */\n\tC_LOW_S                /* s */\n\tC_LOW_T                /* t */\n\tC_LOW_U                /* u */\n\tC_ABCDF                /* ABCDF */\n\tC_E                    /* E */\n\tC_ETC                  /* everything else */\n)\n\n// AsciiClasses array maps the 128 ASCII characters into character classes.\nvar AsciiClasses = [128]Classes{\n\t/*\n\t   This array maps the 128 ASCII characters into character classes.\n\t   The remaining Unicode characters should be mapped to C_ETC.\n\t   Non-whitespace control characters are errors.\n\t*/\n\t__, __, __, __, __, __, __, __,\n\t__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,\n\t__, __, __, __, __, __, __, __,\n\t__, __, __, __, __, __, __, __,\n\n\tC_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,\n\tC_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,\n\tC_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\n\tC_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,\n\n\tC_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,\n\tC_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC,\n}\n\n// QuoteAsciiClasses is a HACK for single quote from AsciiClasses\nvar QuoteAsciiClasses = [128]Classes{\n\t/*\n\t   This array maps the 128 ASCII characters into character classes.\n\t   The remaining Unicode characters should be mapped to C_ETC.\n\t   Non-whitespace control characters are errors.\n\t*/\n\t__, __, __, __, __, __, __, __,\n\t__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,\n\t__, __, __, __, __, __, __, __,\n\t__, __, __, __, __, __, __, __,\n\n\tC_SPACE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE,\n\tC_ETC, C_ETC, C_ETC, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,\n\tC_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,\n\tC_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\n\tC_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,\n\n\tC_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,\n\tC_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,\n\tC_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC,\n}\n\n/*\nThe state codes.\n*/\nconst (\n\tGO States = iota /* start    */\n\tOK               /* ok       */\n\tOB               /* object   */\n\tKE               /* key      */\n\tCO               /* colon    */\n\tVA               /* value    */\n\tAR               /* array    */\n\tST               /* string   */\n\tES               /* escape   */\n\tU1               /* u1       */\n\tU2               /* u2       */\n\tU3               /* u3       */\n\tU4               /* u4       */\n\tMI               /* minus    */\n\tZE               /* zero     */\n\tIN               /* integer  */\n\tDT               /* dot      */\n\tFR               /* fraction */\n\tE1               /* e        */\n\tE2               /* ex       */\n\tE3               /* exp      */\n\tT1               /* tr       */\n\tT2               /* tru      */\n\tT3               /* true     */\n\tF1               /* fa       */\n\tF2               /* fal      */\n\tF3               /* fals     */\n\tF4               /* false    */\n\tN1               /* nu       */\n\tN2               /* nul      */\n\tN3               /* null     */\n)\n\n// List of action codes.\n// these constants are defining an action that should be performed under certain conditions.\nconst (\n\tcl States = -2 /* colon           */\n\tcm States = -3 /* comma           */\n\tqt States = -4 /* quote           */\n\tbo States = -5 /* bracket open    */\n\tco States = -6 /* curly bracket open  */\n\tbc States = -7 /* bracket close   */\n\tcc States = -8 /* curly bracket close */\n\tec States = -9 /* curly bracket empty */\n)\n\n// StateTransitionTable is the state transition table takes the current state and the current symbol, and returns either\n// a new state or an action. An action is represented as a negative number. A JSON text is accepted if at the end of the\n// text the state is OK and if the mode is DONE.\nvar StateTransitionTable = [31][31]States{\n\t/*\n\t   The state transition table takes the current state and the current symbol,\n\t   and returns either a new state or an action. An action is represented as a\n\t   negative number. A JSON text is accepted if at the end of the text the\n\t   state is OK and if the mode is DONE.\n\t                  white                                                    1-9                                                ABCDF   etc\n\t            space   |   {   }   [   ]   :   ,   \"   \\   /   +   -   .   0   |   a   b   c   d   e   f   l   n   r   s   t   u   |   E   |*/\n\t/*start  GO*/ {GO, GO, co, __, bo, __, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},\n\t/*ok     OK*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*object OB*/ {OB, OB, __, ec, __, __, __, __, ST, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*key    KE*/ {KE, KE, __, __, __, __, __, __, ST, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*colon  CO*/ {CO, CO, __, __, __, __, cl, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*value  VA*/ {VA, VA, co, __, bo, __, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},\n\t/*array  AR*/ {AR, AR, co, __, bo, bc, __, __, ST, __, __, __, MI, __, ZE, IN, __, __, __, __, __, F1, __, N1, __, __, T1, __, __, __, __},\n\t/*string ST*/ {ST, __, ST, ST, ST, ST, ST, ST, qt, ES, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST},\n\t/*escape ES*/ {__, __, __, __, __, __, __, __, ST, ST, ST, __, __, __, __, __, __, ST, __, __, __, ST, __, ST, ST, __, ST, U1, __, __, __},\n\t/*u1     U1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, U2, U2, U2, U2, U2, U2, U2, U2, __, __, __, __, __, __, U2, U2, __},\n\t/*u2     U2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, U3, U3, U3, U3, U3, U3, U3, U3, __, __, __, __, __, __, U3, U3, __},\n\t/*u3     U3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, U4, U4, U4, U4, U4, U4, U4, U4, __, __, __, __, __, __, U4, U4, __},\n\t/*u4     U4*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, ST, ST, ST, ST, ST, ST, ST, ST, __, __, __, __, __, __, ST, ST, __},\n\t/*minus  MI*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, ZE, IN, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*zero   ZE*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, DT, __, __, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},\n\t/*int    IN*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, DT, IN, IN, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},\n\t/*dot    DT*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, FR, FR, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*frac   FR*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, FR, FR, __, __, __, __, E1, __, __, __, __, __, __, __, __, E1, __},\n\t/*e      E1*/ {__, __, __, __, __, __, __, __, __, __, __, E2, E2, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*ex     E2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*exp    E3*/ {OK, OK, __, cc, __, bc, __, cm, __, __, __, __, __, __, E3, E3, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*tr     T1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, T2, __, __, __, __, __, __},\n\t/*tru    T2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, T3, __, __, __},\n\t/*true   T3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __, __, __},\n\t/*fa     F1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F2, __, __, __, __, __, __, __, __, __, __, __, __, __, __},\n\t/*fal    F2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F3, __, __, __, __, __, __, __, __},\n\t/*fals   F3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, F4, __, __, __, __, __},\n\t/*false  F4*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __, __, __},\n\t/*nu     N1*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, N2, __, __, __},\n\t/*nul    N2*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, N3, __, __, __, __, __, __, __, __},\n\t/*null   N3*/ {__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, OK, __, __, __, __, __, __, __, __},\n}\n"},{"name":"node.gno","body":"package json\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Node represents a JSON node.\ntype Node struct {\n\tprev     *Node            // prev is the parent node of the current node.\n\tnext     map[string]*Node // next is the child nodes of the current node.\n\tkey      *string          // key holds the key of the current node in the parent node.\n\tdata     []byte           // byte slice of JSON data\n\tvalue    any              // value holds the value of the current node.\n\tnodeType ValueType        // NodeType holds the type of the current node. (Object, Array, String, Number, Boolean, Null)\n\tindex    *int             // index holds the index of the current node in the parent array node.\n\tborders  [2]int           // borders stores the start and end index of the current node in the data.\n\tmodified bool             // modified indicates the current node is changed or not.\n}\n\n// NewNode creates a new node instance with the given parent node, buffer, type, and key.\nfunc NewNode(prev *Node, b *buffer, typ ValueType, key **string) (*Node, error) {\n\tcurr := \u0026Node{\n\t\tprev:     prev,\n\t\tdata:     b.data,\n\t\tborders:  [2]int{b.index, 0},\n\t\tkey:      *key,\n\t\tnodeType: typ,\n\t\tmodified: false,\n\t}\n\n\tif typ == Object || typ == Array {\n\t\tcurr.next = make(map[string]*Node)\n\t}\n\n\tif prev != nil {\n\t\tif prev.IsArray() {\n\t\t\tsize := len(prev.next)\n\t\t\tcurr.index = \u0026size\n\n\t\t\tprev.next[strconv.Itoa(size)] = curr\n\t\t} else if prev.IsObject() {\n\t\t\tif key == nil {\n\t\t\t\treturn nil, errKeyRequired\n\t\t\t}\n\n\t\t\tprev.next[**key] = curr\n\t\t} else {\n\t\t\treturn nil, errors.New(\"invalid parent type\")\n\t\t}\n\t}\n\n\treturn curr, nil\n}\n\n// load retrieves the value of the current node.\nfunc (n *Node) load() any {\n\treturn n.value\n}\n\n// Changed checks the current node is changed or not.\nfunc (n *Node) Changed() bool {\n\treturn n.modified\n}\n\n// Key returns the key of the current node.\nfunc (n *Node) Key() string {\n\tif n == nil || n.key == nil {\n\t\treturn \"\"\n\t}\n\n\treturn *n.key\n}\n\n// HasKey checks the current node has the given key or not.\nfunc (n *Node) HasKey(key string) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\n\t_, ok := n.next[key]\n\treturn ok\n}\n\n// GetKey returns the value of the given key from the current object node.\nfunc (n *Node) GetKey(key string) (*Node, error) {\n\tif n == nil {\n\t\treturn nil, errNilNode\n\t}\n\n\tif n.Type() != Object {\n\t\treturn nil, ufmt.Errorf(\"target node is not object type. got: %s\", n.Type().String())\n\t}\n\n\tvalue, ok := n.next[key]\n\tif !ok {\n\t\treturn nil, ufmt.Errorf(\"key not found: %s\", key)\n\t}\n\n\treturn value, nil\n}\n\n// MustKey returns the value of the given key from the current object node.\nfunc (n *Node) MustKey(key string) *Node {\n\tval, err := n.GetKey(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn val\n}\n\n// UniqueKeyLists traverses the current JSON nodes and collects all the unique keys.\nfunc (n *Node) UniqueKeyLists() []string {\n\tvar collectKeys func(*Node) []string\n\tcollectKeys = func(node *Node) []string {\n\t\tif node == nil || !node.IsObject() {\n\t\t\treturn nil\n\t\t}\n\n\t\tresult := make(map[string]bool)\n\t\tfor key, childNode := range node.next {\n\t\t\tresult[key] = true\n\t\t\tchildKeys := collectKeys(childNode)\n\t\t\tfor _, childKey := range childKeys {\n\t\t\t\tresult[childKey] = true\n\t\t\t}\n\t\t}\n\n\t\tkeys := make([]string, 0, len(result))\n\t\tfor key := range result {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\treturn keys\n\t}\n\n\treturn collectKeys(n)\n}\n\n// Empty returns true if the current node is empty.\nfunc (n *Node) Empty() bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\n\treturn len(n.next) == 0\n}\n\n// Type returns the type (ValueType) of the current node.\nfunc (n *Node) Type() ValueType {\n\treturn n.nodeType\n}\n\n// Value returns the value of the current node.\n//\n// Usage:\n//\n//\troot := Unmarshal([]byte(`{\"key\": \"value\"}`))\n//\tval, err := root.MustKey(\"key\").Value()\n//\tif err != nil {\n//\t\tt.Errorf(\"Value returns error: %v\", err)\n//\t}\n//\n//\tresult: \"value\"\nfunc (n *Node) Value() (value any, err error) {\n\tvalue = n.load()\n\n\tif value == nil {\n\t\tswitch n.nodeType {\n\t\tcase Null:\n\t\t\treturn nil, nil\n\n\t\tcase Number:\n\t\t\tvalue, err = strconv.ParseFloat(string(n.source()), 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tn.value = value\n\n\t\tcase String:\n\t\t\tvar ok bool\n\t\t\tvalue, ok = Unquote(n.source(), doubleQuote)\n\t\t\tif !ok {\n\t\t\t\treturn \"\", errInvalidStringValue\n\t\t\t}\n\n\t\t\tn.value = value\n\n\t\tcase Boolean:\n\t\t\tif len(n.source()) == 0 {\n\t\t\t\treturn nil, errEmptyBooleanNode\n\t\t\t}\n\n\t\t\tb := n.source()[0]\n\t\t\tvalue = b == 't' || b == 'T'\n\t\t\tn.value = value\n\n\t\tcase Array:\n\t\t\telems := make([]*Node, len(n.next))\n\n\t\t\tfor _, e := range n.next {\n\t\t\t\telems[*e.index] = e\n\t\t\t}\n\n\t\t\tvalue = elems\n\t\t\tn.value = value\n\n\t\tcase Object:\n\t\t\tobj := make(map[string]*Node, len(n.next))\n\n\t\t\tfor k, v := range n.next {\n\t\t\t\tobj[k] = v\n\t\t\t}\n\n\t\t\tvalue = obj\n\t\t\tn.value = value\n\t\t}\n\t}\n\n\treturn value, nil\n}\n\n// Delete removes the current node from the parent node.\n//\n// Usage:\n//\n//\troot := Unmarshal([]byte(`{\"key\": \"value\"}`))\n//\tif err := root.MustKey(\"key\").Delete(); err != nil {\n//\t\tt.Errorf(\"Delete returns error: %v\", err)\n//\t}\n//\n//\tresult: {} (empty object)\nfunc (n *Node) Delete() error {\n\tif n == nil {\n\t\treturn errors.New(\"can't delete nil node\")\n\t}\n\n\tif n.prev == nil {\n\t\treturn nil\n\t}\n\n\treturn n.prev.remove(n)\n}\n\n// Size returns the size (length) of the current array node.\n//\n// Usage:\n//\n//\troot := ArrayNode(\"\", []*Node{StringNode(\"\", \"foo\"), NumberNode(\"\", 1)})\n//\tif root == nil {\n//\t\tt.Errorf(\"ArrayNode returns nil\")\n//\t}\n//\n//\tif root.Size() != 2 {\n//\t\tt.Errorf(\"ArrayNode returns wrong size: %d\", root.Size())\n//\t}\nfunc (n *Node) Size() int {\n\tif n == nil {\n\t\treturn 0\n\t}\n\n\treturn len(n.next)\n}\n\n// Index returns the index of the current node in the parent array node.\n//\n// Usage:\n//\n//\troot := ArrayNode(\"\", []*Node{StringNode(\"\", \"foo\"), NumberNode(\"\", 1)})\n//\tif root == nil {\n//\t\tt.Errorf(\"ArrayNode returns nil\")\n//\t}\n//\n//\tif root.MustIndex(1).Index() != 1 {\n//\t\tt.Errorf(\"Index returns wrong index: %d\", root.MustIndex(1).Index())\n//\t}\n//\n// We can also use the index to the byte slice of the JSON data directly.\n//\n// Example:\n//\n//\troot := Unmarshal([]byte(`[\"foo\", 1]`))\n//\tif root == nil {\n//\t\tt.Errorf(\"Unmarshal returns nil\")\n//\t}\n//\n//\tif string(root.MustIndex(1).source()) != \"1\" {\n//\t\tt.Errorf(\"source returns wrong result: %s\", root.MustIndex(1).source())\n//\t}\nfunc (n *Node) Index() int {\n\tif n == nil || n.index == nil {\n\t\treturn -1\n\t}\n\n\treturn *n.index\n}\n\n// MustIndex returns the array element at the given index.\n//\n// If the index is negative, it returns the index is from the end of the array.\n// Also, it panics if the index is not found.\n//\n// check the Index method for detailed usage.\nfunc (n *Node) MustIndex(expectIdx int) *Node {\n\tval, err := n.GetIndex(expectIdx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn val\n}\n\n// GetIndex returns the array element at the given index.\n//\n// if the index is negative, it returns the index is from the end of the array.\nfunc (n *Node) GetIndex(idx int) (*Node, error) {\n\tif n == nil {\n\t\treturn nil, errNilNode\n\t}\n\n\tif !n.IsArray() {\n\t\treturn nil, errNotArrayNode\n\t}\n\n\tif idx \u003e n.Size() {\n\t\treturn nil, errors.New(\"input index exceeds the array size\")\n\t}\n\n\tif idx \u003c 0 {\n\t\tidx += len(n.next)\n\t}\n\n\tchild, ok := n.next[strconv.Itoa(idx)]\n\tif !ok {\n\t\treturn nil, errIndexNotFound\n\t}\n\n\treturn child, nil\n}\n\n// DeleteIndex removes the array element at the given index.\nfunc (n *Node) DeleteIndex(idx int) error {\n\tnode, err := n.GetIndex(idx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn n.remove(node)\n}\n\n// NullNode creates a new null type node.\n//\n// Usage:\n//\n//\t_ := NullNode(\"\")\nfunc NullNode(key string) *Node {\n\treturn \u0026Node{\n\t\tkey:      \u0026key,\n\t\tvalue:    nil,\n\t\tnodeType: Null,\n\t\tmodified: true,\n\t}\n}\n\n// NumberNode creates a new number type node.\n//\n// Usage:\n//\n//\troot := NumberNode(\"\", 1)\n//\tif root == nil {\n//\t\tt.Errorf(\"NumberNode returns nil\")\n//\t}\nfunc NumberNode(key string, value float64) *Node {\n\treturn \u0026Node{\n\t\tkey:      \u0026key,\n\t\tvalue:    value,\n\t\tnodeType: Number,\n\t\tmodified: true,\n\t}\n}\n\n// StringNode creates a new string type node.\n//\n// Usage:\n//\n//\troot := StringNode(\"\", \"foo\")\n//\tif root == nil {\n//\t\tt.Errorf(\"StringNode returns nil\")\n//\t}\nfunc StringNode(key string, value string) *Node {\n\treturn \u0026Node{\n\t\tkey:      \u0026key,\n\t\tvalue:    value,\n\t\tnodeType: String,\n\t\tmodified: true,\n\t}\n}\n\n// BoolNode creates a new given boolean value node.\n//\n// Usage:\n//\n//\troot := BoolNode(\"\", true)\n//\tif root == nil {\n//\t\tt.Errorf(\"BoolNode returns nil\")\n//\t}\nfunc BoolNode(key string, value bool) *Node {\n\treturn \u0026Node{\n\t\tkey:      \u0026key,\n\t\tvalue:    value,\n\t\tnodeType: Boolean,\n\t\tmodified: true,\n\t}\n}\n\n// ArrayNode creates a new array type node.\n//\n// If the given value is nil, it creates an empty array node.\n//\n// Usage:\n//\n//\troot := ArrayNode(\"\", []*Node{StringNode(\"\", \"foo\"), NumberNode(\"\", 1)})\n//\tif root == nil {\n//\t\tt.Errorf(\"ArrayNode returns nil\")\n//\t}\nfunc ArrayNode(key string, value []*Node) *Node {\n\tcurr := \u0026Node{\n\t\tkey:      \u0026key,\n\t\tnodeType: Array,\n\t\tmodified: true,\n\t}\n\n\tcurr.next = make(map[string]*Node, len(value))\n\tif value != nil {\n\t\tcurr.value = value\n\n\t\tfor i, v := range value {\n\t\t\tidx := i\n\t\t\tcurr.next[strconv.Itoa(i)] = v\n\n\t\t\tv.prev = curr\n\t\t\tv.index = \u0026idx\n\t\t}\n\t}\n\n\treturn curr\n}\n\n// ObjectNode creates a new object type node.\n//\n// If the given value is nil, it creates an empty object node.\n//\n// next is a map of key and value pairs of the object.\nfunc ObjectNode(key string, value map[string]*Node) *Node {\n\tcurr := \u0026Node{\n\t\tnodeType: Object,\n\t\tkey:      \u0026key,\n\t\tnext:     value,\n\t\tmodified: true,\n\t}\n\n\tif value != nil {\n\t\tcurr.value = value\n\n\t\tfor key, val := range value {\n\t\t\tvkey := key\n\t\t\tval.prev = curr\n\t\t\tval.key = \u0026vkey\n\t\t}\n\t} else {\n\t\tcurr.next = make(map[string]*Node)\n\t}\n\n\treturn curr\n}\n\n// IsArray returns true if the current node is array type.\nfunc (n *Node) IsArray() bool {\n\treturn n.nodeType == Array\n}\n\n// IsObject returns true if the current node is object type.\nfunc (n *Node) IsObject() bool {\n\treturn n.nodeType == Object\n}\n\n// IsNull returns true if the current node is null type.\nfunc (n *Node) IsNull() bool {\n\treturn n.nodeType == Null\n}\n\n// IsBool returns true if the current node is boolean type.\nfunc (n *Node) IsBool() bool {\n\treturn n.nodeType == Boolean\n}\n\n// IsString returns true if the current node is string type.\nfunc (n *Node) IsString() bool {\n\treturn n.nodeType == String\n}\n\n// IsNumber returns true if the current node is number type.\nfunc (n *Node) IsNumber() bool {\n\treturn n.nodeType == Number\n}\n\n// ready checks the current node is ready or not.\n//\n// the meaning of ready is the current node is parsed and has a valid value.\nfunc (n *Node) ready() bool {\n\treturn n.borders[1] != 0\n}\n\n// source returns the source of the current node.\nfunc (n *Node) source() []byte {\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tif n.ready() \u0026\u0026 !n.modified \u0026\u0026 n.data != nil {\n\t\treturn (n.data)[n.borders[0]:n.borders[1]]\n\t}\n\n\treturn nil\n}\n\n// root returns the root node of the current node.\nfunc (n *Node) root() *Node {\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tcurr := n\n\tfor curr.prev != nil {\n\t\tcurr = curr.prev\n\t}\n\n\treturn curr\n}\n\n// GetNull returns the null value if current node is null type.\n//\n// Usage:\n//\n//\troot := Unmarshal([]byte(\"null\"))\n//\tval, err := root.GetNull()\n//\tif err != nil {\n//\t\tt.Errorf(\"GetNull returns error: %v\", err)\n//\t}\n//\tif val != nil {\n//\t\tt.Errorf(\"GetNull returns wrong result: %v\", val)\n//\t}\nfunc (n *Node) GetNull() (any, error) {\n\tif n == nil {\n\t\treturn nil, errNilNode\n\t}\n\n\tif !n.IsNull() {\n\t\treturn nil, errNotNullNode\n\t}\n\n\treturn nil, nil\n}\n\n// MustNull returns the null value if current node is null type.\n//\n// It panics if the current node is not null type.\nfunc (n *Node) MustNull() any {\n\tv, err := n.GetNull()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn v\n}\n\n// GetNumeric returns the numeric (int/float) value if current node is number type.\n//\n// Usage:\n//\n//\troot := Unmarshal([]byte(\"10.5\"))\n//\tval, err := root.GetNumeric()\n//\tif err != nil {\n//\t\tt.Errorf(\"GetNumeric returns error: %v\", err)\n//\t}\n//\tprintln(val) // 10.5\nfunc (n *Node) GetNumeric() (float64, error) {\n\tif n == nil {\n\t\treturn 0, errNilNode\n\t}\n\n\tif n.nodeType != Number {\n\t\treturn 0, errNotNumberNode\n\t}\n\n\tval, err := n.Value()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tv, ok := val.(float64)\n\tif !ok {\n\t\treturn 0, errNotNumberNode\n\t}\n\n\treturn v, nil\n}\n\n// MustNumeric returns the numeric (int/float) value if current node is number type.\n//\n// It panics if the current node is not number type.\nfunc (n *Node) MustNumeric() float64 {\n\tv, err := n.GetNumeric()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn v\n}\n\n// GetString returns the string value if current node is string type.\n//\n// Usage:\n//\n//\troot, err := Unmarshal([]byte(\"foo\"))\n//\tif err != nil {\n//\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n//\t}\n//\n//\tstr, err := root.GetString()\n//\tif err != nil {\n//\t\tt.Errorf(\"should retrieve string value: %s\", err)\n//\t}\n//\n//\tprintln(str) // \"foo\"\nfunc (n *Node) GetString() (string, error) {\n\tif n == nil {\n\t\treturn \"\", errEmptyStringNode\n\t}\n\n\tif !n.IsString() {\n\t\treturn \"\", errNotStringNode\n\t}\n\n\tval, err := n.Value()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tv, ok := val.(string)\n\tif !ok {\n\t\treturn \"\", errNotStringNode\n\t}\n\n\treturn v, nil\n}\n\n// MustString returns the string value if current node is string type.\n//\n// It panics if the current node is not string type.\nfunc (n *Node) MustString() string {\n\tv, err := n.GetString()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn v\n}\n\n// GetBool returns the boolean value if current node is boolean type.\n//\n// Usage:\n//\n//\troot := Unmarshal([]byte(\"true\"))\n//\tval, err := root.GetBool()\n//\tif err != nil {\n//\t\tt.Errorf(\"GetBool returns error: %v\", err)\n//\t}\n//\tprintln(val) // true\nfunc (n *Node) GetBool() (bool, error) {\n\tif n == nil {\n\t\treturn false, errNilNode\n\t}\n\n\tif n.nodeType != Boolean {\n\t\treturn false, errNotBoolNode\n\t}\n\n\tval, err := n.Value()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tv, ok := val.(bool)\n\tif !ok {\n\t\treturn false, errNotBoolNode\n\t}\n\n\treturn v, nil\n}\n\n// MustBool returns the boolean value if current node is boolean type.\n//\n// It panics if the current node is not boolean type.\nfunc (n *Node) MustBool() bool {\n\tv, err := n.GetBool()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn v\n}\n\n// GetArray returns the array value if current node is array type.\n//\n// Usage:\n//\n//\t\troot := Must(Unmarshal([]byte(`[\"foo\", 1]`)))\n//\t\tarr, err := root.GetArray()\n//\t\tif err != nil {\n//\t\t\tt.Errorf(\"GetArray returns error: %v\", err)\n//\t\t}\n//\n//\t\tfor _, val := range arr {\n//\t\t\tprintln(val)\n//\t\t}\n//\n//\t result: \"foo\", 1\nfunc (n *Node) GetArray() ([]*Node, error) {\n\tif n == nil {\n\t\treturn nil, errNilNode\n\t}\n\n\tif n.nodeType != Array {\n\t\treturn nil, errNotArrayNode\n\t}\n\n\tval, err := n.Value()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv, ok := val.([]*Node)\n\tif !ok {\n\t\treturn nil, errNotArrayNode\n\t}\n\n\treturn v, nil\n}\n\n// MustArray returns the array value if current node is array type.\n//\n// It panics if the current node is not array type.\nfunc (n *Node) MustArray() []*Node {\n\tv, err := n.GetArray()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn v\n}\n\n// AppendArray appends the given values to the current array node.\n//\n// If the current node is not array type, it returns an error.\n//\n// Example 1:\n//\n//\troot := Must(Unmarshal([]byte(`[{\"foo\":\"bar\"}]`)))\n//\tif err := root.AppendArray(NullNode(\"\")); err != nil {\n//\t\tt.Errorf(\"should not return error: %s\", err)\n//\t}\n//\n//\tresult: [{\"foo\":\"bar\"}, null]\n//\n// Example 2:\n//\n//\troot := Must(Unmarshal([]byte(`[\"bar\", \"baz\"]`)))\n//\terr := root.AppendArray(NumberNode(\"\", 1), StringNode(\"\", \"foo\"))\n//\tif err != nil {\n//\t\tt.Errorf(\"AppendArray returns error: %v\", err)\n//\t }\n//\n//\tresult: [\"bar\", \"baz\", 1, \"foo\"]\nfunc (n *Node) AppendArray(value ...*Node) error {\n\tif !n.IsArray() {\n\t\treturn errInvalidAppend\n\t}\n\n\tfor _, val := range value {\n\t\tif err := n.append(nil, val); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tn.mark()\n\treturn nil\n}\n\n// ArrayEach executes the callback for each element in the JSON array.\n//\n// Usage:\n//\n//\tjsonArrayNode.ArrayEach(func(i int, valueNode *Node) {\n//\t    ufmt.Println(i, valueNode)\n//\t})\nfunc (n *Node) ArrayEach(callback func(i int, target *Node)) {\n\tif n == nil || !n.IsArray() {\n\t\treturn\n\t}\n\n\tfor idx := 0; idx \u003c len(n.next); idx++ {\n\t\telement, err := n.GetIndex(idx)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tcallback(idx, element)\n\t}\n}\n\n// GetObject returns the object value if current node is object type.\n//\n// Usage:\n//\n//\troot := Must(Unmarshal([]byte(`{\"key\": \"value\"}`)))\n//\tobj, err := root.GetObject()\n//\tif err != nil {\n//\t\tt.Errorf(\"GetObject returns error: %v\", err)\n//\t}\n//\n//\tresult: map[string]*Node{\"key\": StringNode(\"key\", \"value\")}\nfunc (n *Node) GetObject() (map[string]*Node, error) {\n\tif n == nil {\n\t\treturn nil, errNilNode\n\t}\n\n\tif !n.IsObject() {\n\t\treturn nil, errNotObjectNode\n\t}\n\n\tval, err := n.Value()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv, ok := val.(map[string]*Node)\n\tif !ok {\n\t\treturn nil, errNotObjectNode\n\t}\n\n\treturn v, nil\n}\n\n// MustObject returns the object value if current node is object type.\n//\n// It panics if the current node is not object type.\nfunc (n *Node) MustObject() map[string]*Node {\n\tv, err := n.GetObject()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn v\n}\n\n// AppendObject appends the given key and value to the current object node.\n//\n// If the current node is not object type, it returns an error.\nfunc (n *Node) AppendObject(key string, value *Node) error {\n\tif !n.IsObject() {\n\t\treturn errInvalidAppend\n\t}\n\n\tif err := n.append(\u0026key, value); err != nil {\n\t\treturn err\n\t}\n\n\tn.mark()\n\treturn nil\n}\n\n// ObjectEach executes the callback for each key-value pair in the JSON object.\n//\n// Usage:\n//\n//\tjsonObjectNode.ObjectEach(func(key string, valueNode *Node) {\n//\t    ufmt.Println(key, valueNode)\n//\t})\nfunc (n *Node) ObjectEach(callback func(key string, value *Node)) {\n\tif n == nil || !n.IsObject() {\n\t\treturn\n\t}\n\n\tfor key, child := range n.next {\n\t\tcallback(key, child)\n\t}\n}\n\n// String converts the node to a string representation.\nfunc (n *Node) String() string {\n\tif n == nil {\n\t\treturn \"\"\n\t}\n\n\tif n.ready() \u0026\u0026 !n.modified {\n\t\treturn string(n.source())\n\t}\n\n\tval, err := Marshal(n)\n\tif err != nil {\n\t\treturn \"error: \" + err.Error()\n\t}\n\n\treturn string(val)\n}\n\n// Path builds the path of the current node.\n//\n// For example:\n//\n//\t{ \"key\": { \"sub\": [ \"val1\", \"val2\" ] }}\n//\n// The path of \"val2\" is: $.key.sub[1]\nfunc (n *Node) Path() string {\n\tif n == nil {\n\t\treturn \"\"\n\t}\n\n\tvar sb strings.Builder\n\n\tif n.prev == nil {\n\t\tsb.WriteString(\"$\")\n\t} else {\n\t\tsb.WriteString(n.prev.Path())\n\n\t\tif n.key != nil {\n\t\t\tsb.WriteString(\"['\" + n.Key() + \"']\")\n\t\t} else {\n\t\t\tsb.WriteString(\"[\" + strconv.Itoa(n.Index()) + \"]\")\n\t\t}\n\t}\n\n\treturn sb.String()\n}\n\n// mark marks the current node as modified.\nfunc (n *Node) mark() {\n\tnode := n\n\tfor node != nil \u0026\u0026 !node.modified {\n\t\tnode.modified = true\n\t\tnode = node.prev\n\t}\n}\n\n// isContainer checks the current node type is array or object.\nfunc (n *Node) isContainer() bool {\n\treturn n.IsArray() || n.IsObject()\n}\n\n// remove removes the value from the current container type node.\nfunc (n *Node) remove(v *Node) error {\n\tif !n.isContainer() {\n\t\treturn ufmt.Errorf(\n\t\t\t\"can't remove value from non-array or non-object node. got=%s\",\n\t\t\tn.Type().String(),\n\t\t)\n\t}\n\n\tif v.prev != n {\n\t\treturn errors.New(\"invalid parent node\")\n\t}\n\n\tn.mark()\n\tif n.IsArray() {\n\t\tdelete(n.next, strconv.Itoa(*v.index))\n\t\tn.dropIndex(*v.index)\n\t} else {\n\t\tdelete(n.next, *v.key)\n\t}\n\n\tv.prev = nil\n\treturn nil\n}\n\n// dropIndex rebase the index of current array node values.\nfunc (n *Node) dropIndex(idx int) {\n\tfor i := idx + 1; i \u003c= len(n.next); i++ {\n\t\tprv := i - 1\n\t\tif curr, ok := n.next[strconv.Itoa(i)]; ok {\n\t\t\tcurr.index = \u0026prv\n\t\t\tn.next[strconv.Itoa(prv)] = curr\n\t\t}\n\n\t\tdelete(n.next, strconv.Itoa(i))\n\t}\n}\n\n// append is a helper function to append the given value to the current container type node.\nfunc (n *Node) append(key *string, val *Node) error {\n\tif n.isSameOrParentNode(val) {\n\t\treturn errInvalidAppendCycle\n\t}\n\n\tif val.prev != nil {\n\t\tif err := val.prev.remove(val); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tval.prev = n\n\tval.key = key\n\n\tif key == nil {\n\t\tsize := len(n.next)\n\t\tval.index = \u0026size\n\t\tn.next[strconv.Itoa(size)] = val\n\t} else {\n\t\tif old, ok := n.next[*key]; ok {\n\t\t\tif err := n.remove(old); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tn.next[*key] = val\n\t}\n\n\treturn nil\n}\n\nfunc (n *Node) isSameOrParentNode(nd *Node) bool {\n\treturn n == nd || n.isParentNode(nd)\n}\n\nfunc (n *Node) isParentNode(nd *Node) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\n\tfor curr := nd.prev; curr != nil; curr = curr.prev {\n\t\tif curr == n {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n// cptrs returns the pointer of the given string value.\nfunc cptrs(cpy *string) *string {\n\tif cpy == nil {\n\t\treturn nil\n\t}\n\n\tval := *cpy\n\n\treturn \u0026val\n}\n\n// cptri returns the pointer of the given integer value.\nfunc cptri(i *int) *int {\n\tif i == nil {\n\t\treturn nil\n\t}\n\n\tval := *i\n\treturn \u0026val\n}\n\n// Must panics if the given node is not fulfilled the expectation.\n// Usage:\n//\n//\tnode := Must(Unmarshal([]byte(`{\"key\": \"value\"}`))\nfunc Must(root *Node, expect error) *Node {\n\tif expect != nil {\n\t\tpanic(expect)\n\t}\n\n\treturn root\n}\n"},{"name":"parser.gno","body":"package json\n\nimport (\n\t\"bytes\"\n)\n\nconst (\n\tunescapeStackBufSize = 64\n\tabsMinInt64          = 1 \u003c\u003c 63\n\tmaxInt64             = absMinInt64 - 1\n\tmaxUint64            = 1\u003c\u003c64 - 1\n)\n\n// PaseStringLiteral parses a string from the given byte slice.\nfunc ParseStringLiteral(data []byte) (string, error) {\n\tvar buf [unescapeStackBufSize]byte\n\n\tbf, err := Unescape(data, buf[:])\n\tif err != nil {\n\t\treturn \"\", errInvalidStringInput\n\t}\n\n\treturn string(bf), nil\n}\n\n// ParseBoolLiteral parses a boolean value from the given byte slice.\nfunc ParseBoolLiteral(data []byte) (bool, error) {\n\tswitch {\n\tcase bytes.Equal(data, trueLiteral):\n\t\treturn true, nil\n\tcase bytes.Equal(data, falseLiteral):\n\t\treturn false, nil\n\tdefault:\n\t\treturn false, errMalformedBooleanValue\n\t}\n}\n"},{"name":"path.gno","body":"package json\n\nimport (\n\t\"errors\"\n)\n\n// ParsePath takes a JSONPath string and returns a slice of strings representing the path segments.\nfunc ParsePath(path string) ([]string, error) {\n\tbuf := newBuffer([]byte(path))\n\tresult := make([]string, 0)\n\n\tfor {\n\t\tb, err := buf.current()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tswitch {\n\t\tcase b == dollarSign || b == atSign:\n\t\t\tresult = append(result, string(b))\n\t\t\tbuf.step()\n\n\t\tcase b == dot:\n\t\t\tbuf.step()\n\n\t\t\tif next, _ := buf.current(); next == dot {\n\t\t\t\tbuf.step()\n\t\t\t\tresult = append(result, \"..\")\n\n\t\t\t\textractNextSegment(buf, \u0026result)\n\t\t\t} else {\n\t\t\t\textractNextSegment(buf, \u0026result)\n\t\t\t}\n\n\t\tcase b == bracketOpen:\n\t\t\tstart := buf.index\n\t\t\tbuf.step()\n\n\t\t\tfor {\n\t\t\t\tif buf.index \u003e= buf.length || buf.data[buf.index] == bracketClose {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tbuf.step()\n\t\t\t}\n\n\t\t\tif buf.index \u003e= buf.length {\n\t\t\t\treturn nil, errors.New(\"unexpected end of path\")\n\t\t\t}\n\n\t\t\tsegment := string(buf.sliceFromIndices(start+1, buf.index))\n\t\t\tresult = append(result, segment)\n\n\t\t\tbuf.step()\n\n\t\tdefault:\n\t\t\tbuf.step()\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\n// extractNextSegment extracts the segment from the current index\n// to the next significant character and adds it to the resulting slice.\nfunc extractNextSegment(buf *buffer, result *[]string) {\n\tstart := buf.index\n\tbuf.skipToNextSignificantToken()\n\n\tif buf.index \u003c= start {\n\t\treturn\n\t}\n\n\tsegment := string(buf.sliceFromIndices(start, buf.index))\n\tif segment != \"\" {\n\t\t*result = append(*result, segment)\n\t}\n}\n"},{"name":"token.gno","body":"package json\n\nconst (\n\tbracketOpen    = '['\n\tbracketClose   = ']'\n\tparenOpen      = '('\n\tparenClose     = ')'\n\tcurlyOpen      = '{'\n\tcurlyClose     = '}'\n\tcomma          = ','\n\tdot            = '.'\n\tcolon          = ':'\n\tbackTick       = '`'\n\tsingleQuote    = '\\''\n\tdoubleQuote    = '\"'\n\temptyString    = \"\"\n\twhiteSpace     = ' '\n\tplus           = '+'\n\tminus          = '-'\n\taesterisk      = '*'\n\tbang           = '!'\n\tquestion       = '?'\n\tnewLine        = '\\n'\n\ttab            = '\\t'\n\tcarriageReturn = '\\r'\n\tformFeed       = '\\f'\n\tbackSpace      = '\\b'\n\tslash          = '/'\n\tbackSlash      = '\\\\'\n\tunderScore     = '_'\n\tdollarSign     = '$'\n\tatSign         = '@'\n\tandSign        = '\u0026'\n\torSign         = '|'\n)\n\nvar (\n\ttrueLiteral  = []byte(\"true\")\n\tfalseLiteral = []byte(\"false\")\n\tnullLiteral  = []byte(\"null\")\n)\n\ntype ValueType int\n\nconst (\n\tNotExist ValueType = iota\n\tString\n\tNumber\n\tFloat\n\tObject\n\tArray\n\tBoolean\n\tNull\n\tUnknown\n)\n\nfunc (v ValueType) String() string {\n\tswitch v {\n\tcase NotExist:\n\t\treturn \"not-exist\"\n\tcase String:\n\t\treturn \"string\"\n\tcase Number:\n\t\treturn \"number\"\n\tcase Object:\n\t\treturn \"object\"\n\tcase Array:\n\t\treturn \"array\"\n\tcase Boolean:\n\t\treturn \"boolean\"\n\tcase Null:\n\t\treturn \"null\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"poa","path":"gno.land/p/nt/poa/v0","files":[{"name":"README.md","body":"\u003e **v0 - Unaudited**\n\u003e This is an initial version of this package that has not yet been formally audited.\n\u003e A fully audited version will be published as a subsequent release.\n\u003e Use in production at your own risk.\n\n# `poa` - Proof of Authority validator set\n\nStateful Proof of Authority validator set with simple add/remove constraints. This is a low-level building block intended to be embedded by chain-level governance code (e.g. a GovDAO bridge to `gno.land/p/sys/validators/v0`), not a typical realm utility.\n\nConstraints:\n- **Add**: validator must not be in the set already and voting power must be `\u003e 0`.\n- **Remove**: validator must be in the set.\n\n## Usage\n\n```go\nimport (\n    \"gno.land/p/nt/poa/v0\"\n    \"gno.land/p/sys/validators/v0\"\n)\n\n// Start with a pre-seeded validator set.\nset := poa.NewPoA(poa.WithInitialSet([]validators.Validator{\n    {Address: \"g1...\", PubKey: \"gpub1...\", VotingPower: 10},\n}))\n\n// Add a validator.\nv, err := set.AddValidator(\"g1xyz...\", \"gpub1xyz...\", 5)\nif err != nil {\n    panic(err)\n}\n\n// Inspect membership.\nif set.IsValidator(\"g1xyz...\") {\n    // ...\n}\n\n// List the full current set.\nall := set.GetValidators()\n\n// Remove a validator.\nremoved, err := set.RemoveValidator(v.Address)\n```\n\n## API\n\n```go\ntype PoA struct { /* ... */ }\n\n// Construct an empty set; options seed initial validators.\nfunc NewPoA(opts ...Option) *PoA\n\n// WithInitialSet seeds the validator set at construction time.\nfunc WithInitialSet(vs []validators.Validator) Option\n\nfunc (p *PoA) AddValidator(addr address, pubKey string, power uint64) (validators.Validator, error)\nfunc (p *PoA) RemoveValidator(addr address) (validators.Validator, error)\nfunc (p *PoA) IsValidator(addr address) bool\nfunc (p *PoA) GetValidator(addr address) (validators.Validator, error)\nfunc (p *PoA) GetValidators() []validators.Validator\n```\n\nValidators are stored and returned as `validators.Validator` from `gno.land/p/sys/validators/v0`.\n\n## Errors\n\n- `ErrInvalidVotingPower` — `AddValidator` called with `power == 0`.\n- `validators.ErrValidatorExists` — adding an address already in the set.\n- `validators.ErrValidatorMissing` — removing or fetching an address that is not in the set.\n\n## Notes\n\n- Public keys are stored as-is — there is no on-chain verification yet (`TODO` in source).\n- The package is intentionally narrow: it only manages the in-memory set. Consensus-layer wiring (proposing/applying changes to the actual validator set) is the caller's responsibility.\n"},{"name":"doc.gno","body":"// v0 - Unaudited: This is an initial version that has not yet been formally audited.\n// A fully audited version will be published as a subsequent release.\n// Use in production at your own risk.\n//\n// Package poa implements a Proof of Authority validator set management system.\npackage poa\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/poa/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l\"\n"},{"name":"option.gno","body":"package poa\n\nimport \"gno.land/p/sys/validators/v0\"\n\ntype Option func(*PoA)\n\n// WithInitialSet sets the initial PoA validator set\nfunc WithInitialSet(validators []validators.Validator) Option {\n\treturn func(p *PoA) {\n\t\tfor _, validator := range validators {\n\t\t\tp.validators.Set(validator.Address.String(), validator)\n\t\t}\n\t}\n}\n"},{"name":"poa.gno","body":"package poa\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/sys/validators/v0\"\n)\n\nvar ErrInvalidVotingPower = errors.New(\"invalid voting power\")\n\n// PoA specifies the Proof of Authority validator set, with simple add / remove constraints.\n//\n// To add:\n// - proposed validator must not be part of the set already\n// - proposed validator voting power must be \u003e 0\n//\n// To remove:\n// - proposed validator must be part of the set already\ntype PoA struct {\n\tvalidators *bptree.BPTree // address -\u003e validators.Validator\n}\n\n// NewPoA creates a new empty Proof of Authority validator set\nfunc NewPoA(opts ...Option) *PoA {\n\t// Create the empty set\n\tp := \u0026PoA{\n\t\tvalidators: bptree.NewBPTree32(),\n\t}\n\n\t// Apply the options\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n\n\treturn p\n}\n\nfunc (p *PoA) AddValidator(address_XXX address, pubKey string, power uint64) (validators.Validator, error) {\n\t// Validate that the operation is a valid call.\n\t// Check if the validator is already in the set\n\tif p.IsValidator(address_XXX) {\n\t\treturn validators.Validator{}, validators.ErrValidatorExists\n\t}\n\n\t// Make sure the voting power \u003e 0\n\tif power == 0 {\n\t\treturn validators.Validator{}, ErrInvalidVotingPower\n\t}\n\n\tv := validators.Validator{\n\t\tAddress:     address_XXX,\n\t\tPubKey:      pubKey, // TODO: in the future, verify the public key\n\t\tVotingPower: power,\n\t}\n\n\t// Add the validator to the set\n\tp.validators.Set(address_XXX.String(), v)\n\n\treturn v, nil\n}\n\nfunc (p *PoA) RemoveValidator(address_XXX address) (validators.Validator, error) {\n\t// Validate that the operation is a valid call\n\t// Fetch the validator\n\tvalidator, err := p.GetValidator(address_XXX)\n\tif err != nil {\n\t\treturn validators.Validator{}, err\n\t}\n\n\t// Remove the validator from the set\n\tp.validators.Remove(address_XXX.String())\n\n\treturn validator, nil\n}\n\nfunc (p *PoA) IsValidator(address_XXX address) bool {\n\treturn p.validators.Has(address_XXX.String())\n}\n\nfunc (p *PoA) GetValidator(address_XXX address) (validators.Validator, error) {\n\tvalidatorRaw := p.validators.Get(address_XXX.String())\n\tif validatorRaw == nil {\n\t\treturn validators.Validator{}, validators.ErrValidatorMissing\n\t}\n\n\tvalidator := validatorRaw.(validators.Validator)\n\n\treturn validator, nil\n}\n\nfunc (p *PoA) GetValidators() []validators.Validator {\n\tvals := make([]validators.Validator, 0, p.validators.Size())\n\n\tp.validators.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\tvalidator := value.(validators.Validator)\n\t\tvals = append(vals, validator)\n\n\t\treturn false\n\t})\n\n\treturn vals\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"validators","path":"gno.land/r/sys/validators/v2","files":[{"name":"doc.gno","body":"// Package validators implements the on-chain validator set management through Proof of Contribution.\n// The Realm exposes only a public executor for govdao proposals, that can suggest validator set changes.\npackage validators\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/validators/v2\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"gnosdk.gno","body":"package validators\n\nimport (\n\t\"math\"\n\n\t\"gno.land/p/sys/validators/v0\"\n)\n\n// GetChanges returns the validator changes stored on the realm,\n// for blocks in the [from, to] range (inclusive on both ends).\n// If to \u003e= math.MaxInt64, it is clamped to math.MaxInt64-1 to avoid overflow.\n// Panics if from \u003e to (after clamping).\n// This function is intended to be called by gno.land through the GnoSDK.\nfunc GetChanges(from, to int64) []validators.Validator {\n\tif to \u003e math.MaxInt64-1 {\n\t\tto = math.MaxInt64 - 1\n\t}\n\tif to \u003c from {\n\t\tpanic(\"invalid range: from must be \u003c= to\")\n\t}\n\n\tvalsetChanges := make([]validators.Validator, 0)\n\n\t// Gather the changes in the [from, to] block range.\n\t// AVL Iterate uses an exclusive end, so we pass to+1.\n\tchanges.Iterate(getBlockID(from), getBlockID(to+1), func(_ string, value any) bool {\n\t\tchs := value.([]change)\n\n\t\tfor _, ch := range chs {\n\t\t\tvalsetChanges = append(valsetChanges, ch.validator)\n\t\t}\n\n\t\treturn false\n\t})\n\n\treturn valsetChanges\n}\n"},{"name":"init.gno","body":"package validators\n\nimport (\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/poa/v0\"\n)\n\nfunc init() {\n\t// The default valset protocol is PoA\n\tvp = poa.NewPoA()\n\n\t// No changes to apply initially\n\tchanges = bptree.NewBPTree32()\n}\n"},{"name":"poc.gno","body":"package validators\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/sys/validators/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\n// NewPropRequest creates a new proposal request that wraps a changes closure\n// proposal. This wrapper is required to ensure the GovDAO Realm actually\n// executed the callback.\nfunc NewPropRequest(cur realm, changesFn func() []validators.Validator, title, description string) dao.ProposalRequest {\n\tif changesFn == nil {\n\t\tpanic(\"no set changes proposed\")\n\t}\n\n\ttitle = strings.TrimSpace(title)\n\tif title == \"\" {\n\t\tpanic(\"proposal title is empty\")\n\t}\n\n\t// Get the list of validators now to make sure the list\n\t// doesn't change during the lifetime of the proposal\n\tchanges := changesFn()\n\n\t// Limit the number of validators to keep the description within a limit\n\t// that makes sense because there is not pagination of validators\n\tif len(changes) \u003e 40 {\n\t\tpanic(\"max number of allowed validators per proposal is 40\")\n\t} else if len(changes) == 0 {\n\t\tpanic(\"proposal requires at least one validator\")\n\t}\n\n\t// List the validator addresses and the action to be taken for each one\n\tvar desc strings.Builder\n\tdesc.WriteString(description)\n\tif len(description) \u003e 0 {\n\t\tdesc.WriteString(\"\\n\\n\")\n\t}\n\n\tdesc.WriteString(\"## Validator Updates\\n\")\n\tfor _, change := range changes {\n\t\tif change.VotingPower == 0 {\n\t\t\tdesc.WriteString(ufmt.Sprintf(\"- %s: remove\\n\", change.Address))\n\t\t} else {\n\t\t\tdesc.WriteString(ufmt.Sprintf(\"- %s: add\\n\", change.Address))\n\t\t}\n\t}\n\n\tcallback := func(cur realm) error {\n\t\tfor _, change := range changes {\n\t\t\tif change.VotingPower == 0 {\n\t\t\t\t// This change request is to remove the validator\n\t\t\t\tremoveValidator(change.Address)\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// This change request is to add the validator\n\t\t\taddValidator(change)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\te := dao.NewSimpleExecutor(0, cur, callback, \"\")\n\n\treturn dao.NewProposalRequest(title, desc.String(), e)\n}\n\n// IsValidator returns a flag indicating if the given bech32 address\n// is part of the validator set\nfunc IsValidator(addr address) bool {\n\treturn vp.IsValidator(addr)\n}\n\n// GetValidator returns the typed validator\nfunc GetValidator(addr address) validators.Validator {\n\tif validator, err := vp.GetValidator(addr); err == nil {\n\t\treturn validator\n\t}\n\n\tpanic(\"validator not found\")\n}\n\n// GetValidators returns the typed validator set\nfunc GetValidators() []validators.Validator {\n\treturn vp.GetValidators()\n}\n"},{"name":"validators.gno","body":"package validators\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/sys/validators/v0\"\n)\n\nvar (\n\tvp      validators.ValsetProtocol // p is the underlying validator set protocol\n\tchanges *bptree.BPTree            // changes holds any valset changes; seqid(block number) -\u003e []change\n)\n\n// change represents a single valset change, tied to a specific block number\ntype change struct {\n\tblockNum  int64                // the block number associated with the valset change\n\tvalidator validators.Validator // the validator update\n}\n\n// addValidator adds a new validator to the validator set.\n// If the validator is already present, the method errors out\nfunc addValidator(validator validators.Validator) {\n\tval, err := vp.AddValidator(validator.Address, validator.PubKey, validator.VotingPower)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Validator added, note the change\n\tch := change{\n\t\tblockNum:  runtime.ChainHeight(),\n\t\tvalidator: val,\n\t}\n\n\tsaveChange(ch)\n\n\t// Emit the validator set change\n\tchain.Emit(validators.ValidatorAddedEvent)\n}\n\n// removeValidator removes the given validator from the set.\n// If the validator is not present in the set, the method errors out\nfunc removeValidator(address_XXX address) {\n\tval, err := vp.RemoveValidator(address_XXX)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Validator removed, note the change\n\tch := change{\n\t\tblockNum: runtime.ChainHeight(),\n\t\tvalidator: validators.Validator{\n\t\t\tAddress:     val.Address,\n\t\t\tPubKey:      val.PubKey,\n\t\t\tVotingPower: 0, // nullified the voting power indicates removal\n\t\t},\n\t}\n\n\tsaveChange(ch)\n\n\t// Emit the validator set change\n\tchain.Emit(validators.ValidatorRemovedEvent)\n}\n\n// saveChange saves the valset change\nfunc saveChange(ch change) {\n\tid := getBlockID(ch.blockNum)\n\n\tsetRaw := changes.Get(id)\n\tif setRaw == nil {\n\t\tchanges.Set(id, []change{ch})\n\n\t\treturn\n\t}\n\n\t// Save the change\n\tset := setRaw.([]change)\n\tset = append(set, ch)\n\n\tchanges.Set(id, set)\n}\n\n// getBlockID converts the block number to a sequential ID\nfunc getBlockID(blockNum int64) string {\n\treturn seqid.ID(uint64(blockNum)).String()\n}\n\nfunc Render(_ string) string {\n\tvar (\n\t\tsize       = changes.Size()\n\t\tmaxDisplay = 10\n\t)\n\n\tif size == 0 {\n\t\treturn \"No valset changes to apply.\"\n\t}\n\n\toutput := \"Valset changes:\\n\"\n\tchanges.ReverseIterateByOffset(0, maxDisplay, func(_ string, value any) bool {\n\t\tchs := value.([]change)\n\n\t\tfor _, ch := range chs {\n\t\t\toutput += ufmt.Sprintf(\n\t\t\t\t\"- #%d: %s (%d)\\n\",\n\t\t\t\tch.blockNum,\n\t\t\t\tch.validator.Address.String(),\n\t\t\t\tch.validator.VotingPower,\n\t\t\t)\n\t\t}\n\n\t\treturn false\n\t})\n\n\treturn output\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"ctg","path":"gno.land/p/leon/ctg/v0","files":[{"name":"converter.gno","body":"// Package ctg is a simple utility package with helpers\n// for bech32 address conversions.\npackage ctg\n\nimport (\n\t\"crypto/bech32\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// ConvertCosmosToGno takes a Bech32 Cosmos address (prefix \"cosmos\")\n// and returns the same address re-encoded with the gno.land prefix \"g\".\nfunc ConvertCosmosToGno(addr string) (address, error) {\n\tprefix, decoded, err := bech32.Decode(addr)\n\tif err != nil {\n\t\treturn \"\", ufmt.Errorf(\"bech32 decode failed: %v\", err)\n\t}\n\n\tif prefix != \"cosmos\" {\n\t\treturn \"\", ufmt.Errorf(\"expected a cosmos address, got prefix %q\", prefix)\n\t}\n\n\treturn address(mustEncode(\"g\", decoded)), nil\n}\n\nfunc mustEncode(hrp string, data []byte) string {\n\tenc, err := bech32.Encode(hrp, data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn enc\n}\n\n// ConvertAnyToGno converts *any* valid Bech32 address to its gno.land form\n// by preserving the underlying payload but replacing the prefix with \"g\".\n// No prefix check is performed; invalid Bech32 input still returns an error.\nfunc ConvertAnyToGno(addr string) (address, error) {\n\t_, decoded, err := bech32.Decode(addr)\n\tif err != nil {\n\t\treturn \"\", ufmt.Errorf(\"bech32 decode failed: %v\", err)\n\t}\n\treturn address(mustEncode(\"g\", decoded)), nil\n}\n\n// ConvertGnoToAny converts a gno.land address (prefixed with \"g\") to another Bech32\n// prefix given by prefix. The function ensures the source address really\n// is a gno.land address before proceeding.\n//\n// Example:\n//\n//\tcosmosAddr, _ := ConvertGnoToAny(\"cosmos\", \"g1k98jx9...\")\n//\tfmt.Println(cosmosAddr) // → cosmos1....\nfunc ConvertGnoToAny(prefix string, addr address) (string, error) {\n\torigPrefix, decoded, err := bech32.Decode(string(addr))\n\tif err != nil {\n\t\treturn \"\", ufmt.Errorf(\"bech32 decode failed: %v\", err)\n\t}\n\tif origPrefix != \"g\" {\n\t\treturn \"\", ufmt.Errorf(\"expected a gno address but got prefix %q\", origPrefix)\n\t}\n\treturn mustEncode(prefix, decoded), nil\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/leon/ctg/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"disperse","path":"gno.land/r/demo/disperse","files":[{"name":"disperse.gno","body":"package disperse\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime/unsafe\"\n\n\ttokens \"gno.land/r/demo/defi/grc20factory\"\n)\n\n// DisperseUgnot parses receivers and amounts and sends out ugnot\n// The function will send out the coins to the addresses and return the leftover coins to the caller\n// if there are any to return\nfunc DisperseUgnot(cur realm, addresses []address, coins chain.Coins) {\n\t// Reject non-EOA callers: unsafe.OriginSend() and the realm-balance\n\t// check below describe coins that actually landed at this realm only\n\t// when the caller is a pure EOA. A `maketx run` ephemeral realm or\n\t// intermediate code realm could otherwise consume the envelope and\n\t// have this function disperse pre-existing realm balance to\n\t// attacker-chosen addresses.\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only user-call (maketx call) accepted\")\n\t}\n\tcoinSent := unsafe.OriginSend()\n\tcaller := cur.Previous().Address()\n\trealmAddr := cur.Address()\n\tbanker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\n\tif len(addresses) != len(coins) {\n\t\tpanic(ErrNumAddrValMismatch)\n\t}\n\n\tfor _, coin := range coins {\n\t\tif coin.Amount \u003c= 0 {\n\t\t\tpanic(ErrNegativeCoinAmount)\n\t\t}\n\n\t\tif banker_.GetCoin(realmAddr, coin.Denom) \u003c coin.Amount {\n\t\t\tpanic(ErrMismatchBetweenSentAndParams)\n\t\t}\n\t}\n\n\t// Send coins\n\tfor i := range addresses {\n\t\tbanker_.SendCoins(realmAddr, addresses[i], chain.NewCoins(coins[i]))\n\t}\n\n\t// Return possible leftover coins\n\tfor _, coin := range coinSent {\n\t\tleftoverAmt := banker_.GetCoin(realmAddr, coin.Denom)\n\t\tif leftoverAmt \u003e 0 {\n\t\t\tsend := chain.Coins{chain.NewCoin(coin.Denom, leftoverAmt)}\n\t\t\tbanker_.SendCoins(realmAddr, caller, send)\n\t\t}\n\t}\n}\n\n// DisperseUgnotString receives a string of addresses and a string of amounts\n// and parses them to be used in DisperseUgnot\nfunc DisperseUgnotString(cur realm, addresses string, amounts string) {\n\tparsedAddresses, err := parseAddresses(addresses)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tparsedAmounts, err := parseAmounts(amounts)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcoins := make(chain.Coins, len(parsedAmounts))\n\tfor i, amount := range parsedAmounts {\n\t\tcoins[i] = chain.NewCoin(\"ugnot\", amount)\n\t}\n\n\tDisperseUgnot(cur, parsedAddresses, coins)\n}\n\n// DisperseGRC20 disperses tokens to multiple addresses\n// Note that it is necessary to approve the realm to spend the tokens before calling this function\n// see the corresponding filetests for examples\nfunc DisperseGRC20(cur realm, addresses []address, amounts []int64, symbols []string) {\n\tcaller := cur.Previous().Address()\n\n\tif (len(addresses) != len(amounts)) || (len(amounts) != len(symbols)) {\n\t\tpanic(ErrArgLenAndSentLenMismatch)\n\t}\n\tfor _, amount := range amounts {\n\t\tif amount \u003c 0 {\n\t\t\tpanic(ErrInvalidAmount)\n\t\t}\n\t}\n\n\tfor i := 0; i \u003c len(addresses); i++ {\n\t\ttokens.TransferFrom(cross(cur), symbols[i], caller, addresses[i], amounts[i])\n\t}\n}\n\n// DisperseGRC20String receives a string of addresses and a string of tokens\n// and parses them to be used in DisperseGRC20\nfunc DisperseGRC20String(cur realm, addresses string, tokens string) {\n\tparsedAddresses, err := parseAddresses(addresses)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tparsedAmounts, parsedSymbols, err := parseTokens(tokens)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tDisperseGRC20(cur, parsedAddresses, parsedAmounts, parsedSymbols)\n}\n"},{"name":"doc.gno","body":"// Package disperse provides methods to disperse coins or GRC20 tokens among multiple addresses.\n//\n// The disperse package is an implementation of an existing service that allows users to send coins or GRC20 tokens to multiple addresses\n// on the Ethereum blockchain.\n//\n// Usage:\n// To use disperse, you can either use `DisperseUgnot` to send coins or `DisperseGRC20` to send GRC20 tokens to multiple addresses.\n//\n// Example:\n// Dispersing 200 coins to two addresses:\n// - DisperseUgnotString(\"g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0,g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c\", \"150,50\")\n// Dispersing 200 worth of a GRC20 token \"TEST\" to two addresses:\n// - DisperseGRC20String(\"g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0,g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c\", \"150TEST,50TEST\")\n//\n// Reference:\n// - [the original dispere app](https://disperse.app/)\n// - [the original disperse app on etherscan](https://etherscan.io/address/0xd152f549545093347a162dce210e7293f1452150#code)\n// - [the gno disperse web app](https://gno-disperse.netlify.app/)\npackage disperse // import \"gno.land/r/demo/disperse\"\n"},{"name":"errors.gno","body":"package disperse\n\nimport \"errors\"\n\nvar (\n\tErrNotEnoughCoin                = errors.New(\"disperse: not enough coin sent in\")\n\tErrNumAddrValMismatch           = errors.New(\"disperse: number of addresses and values to send doesn't match\")\n\tErrInvalidAddress               = errors.New(\"disperse: invalid address\")\n\tErrNegativeCoinAmount           = errors.New(\"disperse: coin amount cannot be negative\")\n\tErrMismatchBetweenSentAndParams = errors.New(\"disperse: mismatch between coins sent and params called\")\n\tErrArgLenAndSentLenMismatch     = errors.New(\"disperse: mismatch between coins sent and args called\")\n\tErrInvalidAmount                = errors.New(\"disperse: invalid amount\")\n)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/disperse\"\ngno = \"0.9\"\n"},{"name":"util.gno","body":"package disperse\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc parseAddresses(addresses string) ([]address, error) {\n\tvar ret []address\n\n\tfor _, str := range strings.Split(addresses, \",\") {\n\t\taddr := address(str)\n\t\tif !addr.IsValid() {\n\t\t\treturn nil, ErrInvalidAddress\n\t\t}\n\n\t\tret = append(ret, addr)\n\t}\n\n\treturn ret, nil\n}\n\nfunc splitString(input string) (string, string) {\n\tvar pos int\n\tfor i, char := range input {\n\t\tif !unicode.IsDigit(char) {\n\t\t\tpos = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn input[:pos], input[pos:]\n}\n\nfunc parseTokens(tokens string) ([]int64, []string, error) {\n\tvar amounts []int64\n\tvar symbols []string\n\n\tfor _, token := range strings.Split(tokens, \",\") {\n\t\tamountStr, symbol := splitString(token)\n\t\tamount, _ := strconv.Atoi(amountStr)\n\t\tif amount \u003c 0 {\n\t\t\treturn nil, nil, ErrNegativeCoinAmount\n\t\t}\n\n\t\tamounts = append(amounts, int64(amount))\n\t\tsymbols = append(symbols, symbol)\n\t}\n\n\treturn amounts, symbols, nil\n}\n\nfunc parseAmounts(amounts string) ([]int64, error) {\n\tvar ret []int64\n\n\tfor _, amt := range strings.Split(amounts, \",\") {\n\t\tamount, _ := strconv.Atoi(amt)\n\t\tif amount \u003c 0 {\n\t\t\treturn nil, ErrNegativeCoinAmount\n\t\t}\n\n\t\tret = append(ret, int64(amount))\n\t}\n\n\treturn ret, nil\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"rewards","path":"gno.land/r/sys/rewards","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/rewards\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l\"\n"},{"name":"rewards.gno","body":"// This package will be used to manage proof-of-contributions on the exposed smart-contract side.\npackage rewards\n\n// TODO: write specs.\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"tests_foo","path":"gno.land/r/tests/vm/tests_foo","files":[{"name":"foo.gno","body":"package tests_foo\n\nimport (\n\ttests \"gno.land/r/tests/vm\"\n)\n\n// for testing gno.land/r/tests/vm/interfaces.go\n\ntype FooStringer struct {\n\tFieldA string\n}\n\nfunc (fs *FooStringer) String() string {\n\treturn \"\u0026FooStringer{\" + fs.FieldA + \"}\"\n}\n\n// AddFooStringer is a non-crossing helper. Callers thread their own\n// live cur as `rlm`; `cross(rlm)` forwards it into the (cur realm)-\n// crossing tests.AddStringer.\nfunc AddFooStringer(_ int, rlm realm, fa string) {\n\ttests.AddStringer(cross(rlm), \u0026FooStringer{fa})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/tests_foo\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"dom","path":"gno.land/p/archive/dom","files":[{"name":"dom.gno","body":"// XXX This is only used for testing in ./tests.\n// Otherwise this package is deprecated.\n// TODO: replace with a package that is supported, and delete this.\n\npackage dom\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\ntype Plot struct {\n\tName     string\n\tPosts    avl.Tree // postsCtr -\u003e *Post\n\tPostsCtr int\n}\n\nfunc (plot *Plot) AddPost(title string, body string) {\n\tctr := plot.PostsCtr\n\tplot.PostsCtr++\n\tkey := strconv.Itoa(ctr)\n\tpost := \u0026Post{\n\t\tTitle: title,\n\t\tBody:  body,\n\t}\n\tplot.Posts.Set(key, post)\n}\n\nfunc (plot *Plot) String() string {\n\tstr := \"# [plot] \" + plot.Name + \"\\n\"\n\tif plot.Posts.Size() \u003e 0 {\n\t\tplot.Posts.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\tstr += \"\\n\"\n\t\t\tstr += value.(*Post).String()\n\t\t\treturn false\n\t\t})\n\t}\n\treturn str\n}\n\ntype Post struct {\n\tTitle    string\n\tBody     string\n\tComments avl.Tree\n}\n\nfunc (post *Post) String() string {\n\tstr := \"## \" + post.Title + \"\\n\"\n\tstr += \"\"\n\tstr += post.Body\n\tif post.Comments.Size() \u003e 0 {\n\t\tpost.Comments.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\tstr += \"\\n\"\n\t\t\tstr += value.(*Comment).String()\n\t\t\treturn false\n\t\t})\n\t}\n\treturn str\n}\n\ntype Comment struct {\n\tCreator string\n\tBody    string\n}\n\nfunc (cmm Comment) String() string {\n\treturn cmm.Body + \" - @\" + cmm.Creator + \"\\n\"\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/archive/dom\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"persistedcap","path":"gno.land/r/tests/vm/persistedcap","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/persistedcap\"\ngno = \"0.9\"\n"},{"name":"persistedcap.gno","body":"// Package persistedcap stores a closure (constructed by a /p/ factory)\n// at init, persisting the closure's captured HIV as part of this\n// realm's state. Foreign-realm callers can grab the closure via\n// GetCounter() and invoke it; the closure body's write to its\n// captured HIV is REJECTED by the readonly check because the HIV is\n// real (NewTime\u003e0) and belongs to a different realm than the caller's\n// m.Realm. The unreal-HIV exception only applies while the HIV is\n// transient — persistence elevates it to a normal realm-owned slot.\npackage persistedcap\n\nimport \"gno.land/p/demo/tests/p_closurecap/v0\"\n\nvar counter func() int\n\nfunc init() {\n\tcounter = p_closurecap.MakeCounter(0)\n}\n\n// GetCounter returns the persisted closure. The caller invokes it\n// directly — because the closure's FuncLit lives in /p/ p_closurecap,\n// PushFrameCall's borrow rule does NOT switch m.Realm to persistedcap\n// at invocation. The closure body's write to the captured HIV (PkgID\n// = persistedcap, persisted) therefore runs under the caller's\n// m.Realm, which is the persisted-closure-capture cross-realm case.\n//\n// SECURITY: deliberate VM-parity-test infrastructure — do NOT copy this\n// pattern in production code. See gno.land/r/tests/vm/crossrealm\n// Closure for the broader rationale.\nfunc GetCounter() func() int {\n\treturn counter\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"crossrealm_b","path":"gno.land/r/tests/vm/crossrealm_b","files":[{"name":"crossrealm.gno","body":"package crossrealm_b\n\nimport (\n\t\"chain/banker\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/r/tests/vm/crossrealm\"\n)\n\ntype fooer struct {\n\ts string\n}\n\nfunc (f *fooer) SetS(newVal string) {\n\tf.s = newVal\n}\n\nfunc (f *fooer) Foo(cur realm) {\n\tprintln(\"hello \" + f.s + \" cur=\" + unsafe.CurrentRealm().PkgPath() + \" prev=\" + unsafe.PreviousRealm().PkgPath())\n}\n\nfunc (f *fooer) Bar() {\n\tprintln(\"hello \" + f.s + \" cur=\" + unsafe.CurrentRealm().PkgPath() + \" prev=\" + unsafe.PreviousRealm().PkgPath())\n}\n\nvar (\n\tFooer              = \u0026fooer{s: \"A\"}\n\tFooerGetter        = func() crossrealm.Fooer { return Fooer }\n\tFooerGetterBuilder = func() crossrealm.FooerGetter { return func() crossrealm.Fooer { return Fooer } }\n)\n\nvar Closure func()\n\nfunc SetClosure(cur realm, f func()) {\n\tClosure = f\n}\n\nvar Object any\n\nfunc SetObject(cur realm, x any) {\n\tObject = x\n}\n\nfunc GetObject() any {\n\treturn Object\n}\n\nfunc IncrementObject(cur realm) any {\n\tptr := Object.(*int)\n\t*ptr += 1\n\treturn Object\n}\n\nvar n int\n\n// NOTE should be non-crossing\nfunc IncrGlobal() {\n\tn++\n}\n\n// TrySubOn attempts to mint a sub-realm token on a passed-in realm\n// value. Non-crossing (`_ int` discriminator), so the caller's cur\n// remains the topmost crossing cur — but borrow rule #1 runs this\n// body with m.Realm = crossrealm_b, so rlm.Sub must reject: a foreign\n// realm must not mint sub-identities in the caller's namespace.\nfunc TrySubOn(_ int, rlm realm) {\n\trlm.Sub(\"stolen\")\n}\n\n// TryBankerOnPrevious attempts to construct a RealmSend banker over the\n// CALLER via cur.Previous() (which is NOT IsCurrent). NewBanker must\n// reject it — otherwise a callee could set pkgAddr to the caller's\n// address and drain it through the pkgAddr==from gate. Regression guard\n// for the IsCurrent check in NewBanker.\nfunc TryBankerOnPrevious(cur realm) {\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur.Previous())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/crossrealm_b\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"allowancesender","path":"gno.land/p/jaekwon/allowancesender/v0","files":[{"name":"allowancesender.gno","body":"// Package allowancesender provides a bounded, granter-revocable\n// spending capability that wraps a banker.Banker source.\n//\n// # Use case\n//\n// Realm A wants to grant realm B the ability to spend up to some\n// bounded amount from A's address (or A's tx envelope) within a single\n// call, without giving B unbounded access. After A's call to B returns,\n// A revokes the capability via Close(); B cannot use it across tx\n// boundaries even if it persisted the reference.\n//\n// # Canonical pattern\n//\n//\tsrc := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n//\tal  := allowancesender.New(src, granterAddr,\n//\t           chain.NewCoins(chain.NewCoin(\"ugnot\", 1_000_000)))\n//\tdefer al.Close()\n//\tbRealm.DoSomething(cross, al)  // B can call al.Send up to cap\n//\n// On return (success or panic), `defer al.Close()` flips the closed\n// flag. If B persisted al, B's stored reference is now dead — any\n// later al.Send() panics with \"closed\".\n//\n// # Naming note\n//\n// Despite the underlying type wrapping a banker.Banker, *AllowanceSender\n// does NOT satisfy the banker.Banker interface. The other Banker methods\n// (GetCoins, TotalCoin, IssueCoin, RemoveCoin) have no meaningful\n// behavior on an allowance abstraction:\n//\n//   - GetCoins would either leak the granter realm's full balance\n//     (misleading) or return Remaining() (lying about the addr arg).\n//   - TotalCoin/IssueCoin/RemoveCoin are out of scope.\n//\n// Send is the only meaningful operation; hence the \"Sender\" name. If\n// you need to plug into a banker.Banker-shaped API, write an adapter\n// in your own package.\n//\n// # Security model\n//\n//   - Pointer-based API. All callees that hold a *AllowanceSender share\n//     the same underlying state. Close() flips a bool that every reader\n//     observes synchronously.\n//   - Inner banker is an unexported field. Callees cannot extract it\n//     to bypass the wrapper. Language-enforced.\n//   - Cap is enforced per-denom via chain.Coins.AmountOf. Any denom in\n//     amt that is missing from cap implicitly has capAmt=0; positive\n//     spend on such a denom panics with \"cap exceeded\".\n//   - Persistence is the kill switch's friend, not its enemy. The\n//     closed flag persists with the struct, so a callee that stored\n//     the reference for cross-tx use sees a closed allowance.\n//   - Defer-close survives panic. If B's call panics, the tx reverts\n//     entirely (so the close is irrelevant — state reverts anyway). On\n//     success, defer fires before granter's function returns,\n//     committing closed=true with the rest of the tx state.\n//   - Cap/Spent return defensive copies. Mutating the returned\n//     chain.Coins does not affect internal state.\n//   - Inner banker panic on SendCoins (e.g. bank-keeper \"insufficient\n//     funds\") rolls back the spent counter — caller's accounting stays\n//     accurate even if a defer-recover swallows the panic. (Without\n//     recovery, the entire tx reverts and the rollback is moot.)\n//   - Arithmetic uses math/overflow.Add64. Overflow on (spent+amount)\n//     panics rather than silently wrapping (which could bypass the cap\n//     check). Negative amounts are explicitly rejected.\n//\n// # Design choices\n//\n//   - Pointer type, not value: forces shared state across references.\n//     Value-copy AllowanceSender would have separate closed flags and\n//     defeat the kill switch.\n//   - One-shot Close, not graduated: simpler invariant. If you need\n//     \"resume later,\" create a fresh allowance.\n//   - No destination allowlist: out of scope. If the granter wants to\n//     restrict where funds go, wrap this further.\n//   - No time-based expiry: rely on Close. Block-height stamping or\n//     deadline checks would require runtime cooperation; this package\n//     is pure Gno.\n//   - Cap is multi-denom (chain.Coins, not int64): supports\n//     heterogeneous payment policies. Most callers use single-denom.\n//   - Idempotent Close: safe to defer-Close even if Close was called\n//     manually earlier in the function.\n//   - Does NOT satisfy banker.Banker: see \"Naming note\" above.\n//\n// # Limitations\n//\n//   - Granter retains direct access to the underlying source banker.\n//     The AllowanceSender only constrains the wrapped capability, not\n//     the granter's ability to spend its own funds via other means.\n//   - No cross-realm enforcement of granter identity. The source\n//     banker's own pkgAddr check (banker.gno) rejects mismatched\n//     froms. This package relies on banker's own protection there.\n//   - Re-entrancy: nested allowances work (each is independent), but\n//     do NOT re-use the same AllowanceSender pointer across grants —\n//     always create a fresh one. Re-using would mix spent counters.\n//   - Cap with duplicate denoms (constructed by hand, not via\n//     chain.NewCoins) will trigger chain.Coins.AmountOf to panic on\n//     read. Use chain.NewCoins(...) to construct cap; it deduplicates.\n//   - Persistence: granter is responsible for clearing references to\n//     closed AllowanceSender pointers from its own state if it wants\n//     them garbage-collected; otherwise they linger as dead structs.\n//\n// # What this package does NOT solve\n//\n//   - \"Allowance survives across N txs but not N+1 txs.\" Use a session\n//     counter pattern in the granter realm; this package's Close is\n//     binary, not deadline-based.\n//   - \"Fungible-token (grc20) allowances.\" Use the grc20 package's\n//     own Approve/Allowance/TransferFrom triple. AllowanceSender is\n//     for native (chain-coin) sends only.\n//\n// # Events\n//\n// AllowanceSender emits chain events at two points so off-chain\n// observers can track allowance lifecycles. Events are emitted from\n// the calling realm's package path (whichever realm holds the\n// AllowanceSender pointer when the method is called).\n//\n//   - \"AllowanceSenderSend\": on each successful Send, with attributes\n//     \"payer\", \"to\", \"amount\", \"spent_total\", \"remaining\".\n//   - \"AllowanceSenderClose\": on Close (only the first call; idempotent\n//     re-Closes do not re-emit).\n//\n// The underlying inner banker also emits its own bank-keeper events\n// for the actual coin movement; AllowanceSender's events sit on top of\n// those for allowance-level audit trails.\npackage allowancesender\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"math/overflow\"\n)\n\n// Event names emitted by AllowanceSender. Use these constants when\n// asserting on events from off-chain observers or test code.\nconst (\n\tEventSend  = \"AllowanceSenderSend\"\n\tEventClose = \"AllowanceSenderClose\"\n)\n\n// AllowanceSender is a bounded, revocable spending capability over a\n// source banker.Banker. Always pass *AllowanceSender (pointer); value\n// copies are not supported and would not share state.\n//\n// Does NOT satisfy banker.Banker — the other Banker methods (GetCoins,\n// TotalCoin, IssueCoin, RemoveCoin) have no meaningful behavior on an\n// allowance and are deliberately omitted.\ntype AllowanceSender struct {\n\tinner  banker.Banker // unexported — callees cannot extract\n\tpayer  address       // address debited; must match inner's source\n\tlimit  chain.Coins   // maximum cumulative spend, per-denom\n\tspent  chain.Coins   // running total of spends, per-denom\n\tclosed bool          // once true, all further Send calls panic\n}\n\n// New creates a new AllowanceSender wrapping inner with the given limit.\n// payer is the address that inner.SendCoins will draw from (must match\n// the realm address inner was created against; the banker enforces this\n// at SendCoins time).\n//\n// inner must be the canonical Banker produced by banker.NewBanker;\n// hand-rolled Banker implementations (no-op fakes, decorators) are\n// rejected via banker.IsCanonical. This guarantees that a callee\n// receiving a *AllowanceSender from a granter realm can rely on Send\n// actually moving real coins via the bank-keeper, not via a fake\n// banker that no-ops SendCoins.\n//\n// Panics if inner is not canonical or payer is invalid. limit may be\n// empty (zero allowance — every Send panics with \"cap exceeded\");\n// limit may also contain multiple denoms.\nfunc New(inner banker.Banker, payer address, limit chain.Coins) *AllowanceSender {\n\tif !banker.IsCanonical(inner) {\n\t\tpanic(\"allowancesender: inner banker is not the canonical chain/banker.Banker\")\n\t}\n\tif !payer.IsValid() {\n\t\tpanic(\"allowancesender: payer address is invalid\")\n\t}\n\treturn \u0026AllowanceSender{\n\t\tinner: inner,\n\t\tpayer: payer,\n\t\tlimit: limit,\n\t}\n}\n\n// Send debits up to (cap - spent) per denom from payer to to via the\n// inner banker. Updates spent on success. On any panic (including\n// inner.SendCoins panic for bank-level reasons like insufficient\n// balance), spent is rolled back — caller's accounting stays accurate\n// even if a caller wraps Send in a defer-recover.\n//\n// Arithmetic uses math/overflow.Add64; an overflow on (spent+amount)\n// panics with a distinct message rather than silently wrapping. This\n// closes the int64-overflow vector where a malicious callee passes a\n// MaxInt64-style amount to bypass the cap check.\n//\n// Negative amounts are rejected explicitly. chain.NewCoin permits\n// signed amounts at construction; we don't accept them.\n//\n// Emits \"AllowanceSenderSend\" event on success.\n//\n// Panics:\n//   - \"closed\" if Close has been called.\n//   - \"negative amount not allowed\" if any c.Amount \u003c 0.\n//   - \"amount overflow on spent+amt\" if int64 addition would overflow.\n//   - \"cap exceeded for denom \u003cdenom\u003e\" if any denom in amt would push\n//     spent over cap.\n//   - inner.SendCoins panics propagate (typically \"insufficient\n//     funds\" from the bank keeper); spent is rolled back first.\nfunc (a *AllowanceSender) Send(to address, amt chain.Coins) {\n\tif a.closed {\n\t\tpanic(\"allowancesender: closed\")\n\t}\n\n\t// Per-denom validation. Done in a separate pass before any state\n\t// mutation so a partial failure doesn't leak into spent.\n\tfor _, c := range amt {\n\t\tif c.Amount \u003c 0 {\n\t\t\tpanic(\"allowancesender: negative amount not allowed for denom \" + c.Denom)\n\t\t}\n\t\tcapAmt := a.limit.AmountOf(c.Denom)\n\t\tspentAmt := a.spent.AmountOf(c.Denom)\n\t\tsum, ok := overflow.Add64(spentAmt, c.Amount)\n\t\tif !ok {\n\t\t\tpanic(\"allowancesender: amount overflow on spent+amt for denom \" + c.Denom)\n\t\t}\n\t\tif sum \u003e capAmt {\n\t\t\tpanic(\"allowancesender: cap exceeded for denom \" + c.Denom)\n\t\t}\n\t}\n\n\t// Snapshot for rollback. If inner.SendCoins panics — even if a\n\t// caller's defer-recover swallows the panic — the deferred\n\t// rollback below restores spent before re-raising. Without this,\n\t// a recovered panic would leave spent inflated for a transfer\n\t// that didn't move funds at the bank-keeper level, allowing an\n\t// adversary to \"burn\" allowance against failed sends.\n\tprevSpent := a.spent\n\ta.spent = a.spent.Add(amt)\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\ta.spent = prevSpent\n\t\t\tpanic(r) // re-raise so caller learns of the failure\n\t\t}\n\t}()\n\n\ta.inner.SendCoins(a.payer, to, amt)\n\n\t// Reached only on successful inner.SendCoins. Emit the audit\n\t// event from the granter realm's perspective.\n\tchain.Emit(EventSend,\n\t\t\"payer\", a.payer.String(),\n\t\t\"to\", to.String(),\n\t\t\"amount\", amt.String(),\n\t\t\"spent_total\", a.spent.String(),\n\t\t\"remaining\", a.Remaining().String(),\n\t)\n}\n\n// Cap returns a defensive copy of the maximum cumulative spend.\n// Mutating the returned slice does not affect internal state.\nfunc (a *AllowanceSender) Cap() chain.Coins {\n\treturn cloneCoins(a.limit)\n}\n\n// Spent returns a defensive copy of the cumulative amount spent.\n// Mutating the returned slice does not affect internal state.\nfunc (a *AllowanceSender) Spent() chain.Coins {\n\treturn cloneCoins(a.spent)\n}\n\n// Remaining returns cap - spent, per denom. Denoms with non-positive\n// remainder are omitted.\nfunc (a *AllowanceSender) Remaining() chain.Coins {\n\tif len(a.limit) == 0 {\n\t\treturn nil\n\t}\n\tout := make(chain.Coins, 0, len(a.limit))\n\tfor _, c := range a.limit {\n\t\trem := c.Amount - a.spent.AmountOf(c.Denom)\n\t\tif rem \u003e 0 {\n\t\t\tout = append(out, chain.NewCoin(c.Denom, rem))\n\t\t}\n\t}\n\treturn out\n}\n\n// Closed reports whether Close has been called.\nfunc (a *AllowanceSender) Closed() bool {\n\treturn a.closed\n}\n\n// Close terminates the allowance. Subsequent Send calls panic.\n// Idempotent — calling twice is fine; the second call is a no-op and\n// does not re-emit the AllowanceSenderClose event.\nfunc (a *AllowanceSender) Close() {\n\tif a.closed {\n\t\treturn\n\t}\n\ta.closed = true\n\tchain.Emit(EventClose,\n\t\t\"payer\", a.payer.String(),\n\t\t\"spent_total\", a.spent.String(),\n\t)\n}\n\n// Payer returns the address that this allowance debits from.\nfunc (a *AllowanceSender) Payer() address {\n\treturn a.payer\n}\n\n// cloneCoins returns a fresh chain.Coins that does not share an\n// underlying array with the source. Used to defend internal state\n// from caller mutation.\nfunc cloneCoins(src chain.Coins) chain.Coins {\n\tif len(src) == 0 {\n\t\treturn nil\n\t}\n\tout := make(chain.Coins, len(src))\n\tcopy(out, src)\n\treturn out\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jaekwon/allowancesender/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"int256","path":"gno.land/p/onbloc/int256/v0","files":[{"name":"arithmetic.gno","body":"package int256\n\nimport (\n\t\"gno.land/p/onbloc/uint256/v0\"\n)\n\nconst divisionByZeroError = \"division by zero\"\n\n// Add adds two int256 values and saves the result in z.\nfunc (z *Int) Add(x, y *Int) *Int {\n\tz.value.Add(\u0026x.value, \u0026y.value)\n\treturn z\n}\n\n// AddUint256 adds int256 and uint256 values and saves the result in z.\nfunc (z *Int) AddUint256(x *Int, y *uint256.Uint) *Int {\n\tz.value.Add(\u0026x.value, y)\n\treturn z\n}\n\n// Sub subtracts two int256 values and saves the result in z.\nfunc (z *Int) Sub(x, y *Int) *Int {\n\tz.value.Sub(\u0026x.value, \u0026y.value)\n\treturn z\n}\n\n// SubUint256 subtracts uint256 and int256 values and saves the result in z.\nfunc (z *Int) SubUint256(x *Int, y *uint256.Uint) *Int {\n\tz.value.Sub(\u0026x.value, y)\n\treturn z\n}\n\n// Mul multiplies two int256 values and saves the result in z.\n//\n// It considers the signs of the operands to determine the sign of the result.\nfunc (z *Int) Mul(x, y *Int) *Int {\n\txAbs, xSign := x.Abs(), x.Sign()\n\tyAbs, ySign := y.Abs(), y.Sign()\n\n\tz.value.Mul(xAbs, yAbs)\n\n\tif xSign != ySign {\n\t\tz.value.Neg(\u0026z.value)\n\t}\n\n\treturn z\n}\n\n// Abs returns the absolute value of z.\nfunc (z *Int) Abs() *uint256.Uint {\n\tif z.Sign() \u003e= 0 {\n\t\treturn \u0026z.value\n\t}\n\n\tvar absValue uint256.Uint\n\tabsValue.Sub(uint0, \u0026z.value).Neg(\u0026z.value)\n\n\treturn \u0026absValue\n}\n\n// Div performs integer division z = x / y and returns z.\n// If y == 0, it panics with a \"division by zero\" error.\n//\n// This function handles signed division using two's complement representation:\n//  1. Determine the sign of the quotient based on the signs of x and y.\n//  2. Perform unsigned division on the absolute values.\n//  3. Adjust the result's sign if necessary.\n//\n// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):\n//\n// Let x = -6 (11111010 in two's complement) and y = 3 (00000011)\n//\n// Step 2: Determine signs\n//\n//\tx: negative (MSB is 1)\n//\ty: positive (MSB is 0)\n//\n// Step 3: Calculate absolute values\n//\n//\t|x| = 6:  11111010 -\u003e 00000110\n//\t     NOT: 00000101\n//\t     +1:  00000110\n//\n//\t|y| = 3:  00000011 (already positive)\n//\n// Step 4: Unsigned division\n//\n//\t6 / 3 = 2:  00000010\n//\n// Step 5: Adjust sign (x and y have different signs)\n//\n//\t-2:  00000010 -\u003e 11111110\n//\t     NOT: 11111101\n//\t     +1:  11111110\n//\n// Note: This implementation rounds towards zero, as is standard in Go.\nfunc (z *Int) Div(x, y *Int) *Int {\n\t// Step 1: Check for division by zero\n\tif y.IsZero() {\n\t\tpanic(divisionByZeroError)\n\t}\n\n\t// Step 2, 3: Calculate the absolute values of x and y\n\txAbs, xSign := x.Abs(), x.Sign()\n\tyAbs, ySign := y.Abs(), y.Sign()\n\n\t// Step 4: Perform unsigned division on the absolute values\n\tz.value.Div(xAbs, yAbs)\n\n\t// Step 5: Adjust the sign of the result\n\t// if x and y have different signs, the result must be negative\n\tif xSign != ySign {\n\t\tz.value.Neg(\u0026z.value)\n\t}\n\n\treturn z\n}\n\n// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):\n//\n// Let x = -7 (11111001 in two's complement) and y = 3 (00000011)\n//\n// Step 2: Determine signs\n//\n//\tx: negative (MSB is 1)\n//\ty: positive (MSB is 0)\n//\n// Step 3: Calculate absolute values\n//\n//\t|x| = 7:  11111001 -\u003e 00000111\n//\t     NOT: 00000110\n//\t     +1:  00000111\n//\n//\t|y| = 3:  00000011 (already positive)\n//\n// Step 4: Unsigned division\n//\n//\t7 / 3 = 2:  00000010\n//\n// Step 5: Adjust sign (x and y have different signs)\n//\n//\t-2:  00000010 -\u003e 11111110\n//\t     NOT: 11111101\n//\t     +1:  11111110\n//\n// Final result: -2 (11111110 in two's complement)\n//\n// Note: This implementation rounds towards zero, as is standard in Go.\nfunc (z *Int) Quo(x, y *Int) *Int {\n\t// Step 1: Check for division by zero\n\tif y.IsZero() {\n\t\tpanic(divisionByZeroError)\n\t}\n\n\t// Step 2, 3: Calculate the absolute values of x and y\n\txAbs, xSign := x.Abs(), x.Sign()\n\tyAbs, ySign := y.Abs(), y.Sign()\n\n\t// perform unsigned division on the absolute values\n\tz.value.Div(xAbs, yAbs)\n\n\t// Step 5: Adjust the sign of the result\n\t// if x and y have different signs, the result must be negative\n\tif xSign != ySign {\n\t\tz.value.Neg(\u0026z.value)\n\t}\n\n\treturn z\n}\n\n// Rem sets z to the remainder x%y for y != 0 and returns z.\n//\n// The function performs the following steps:\n//  1. Check for division by zero\n//  2. Determine the signs of x and y\n//  3. Calculate the absolute values of x and y\n//  4. Perform unsigned division and get the remainder\n//  5. Adjust the sign of the remainder\n//\n// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):\n//\n// Let x = -7 (11111001 in two's complement) and y = 3 (00000011)\n//\n// Step 2: Determine signs\n//\n//\tx: negative (MSB is 1)\n//\ty: positive (MSB is 0)\n//\n// Step 3: Calculate absolute values\n//\n//\t|x| = 7:  11111001 -\u003e 00000111\n//\t     NOT: 00000110\n//\t     +1:  00000111\n//\n//\t|y| = 3:  00000011 (already positive)\n//\n// Step 4: Unsigned division\n//\n//\t7 / 3 = 2 remainder 1\n//\tq = 2:  00000010 (not used in result)\n//\tr = 1:  00000001\n//\n// Step 5: Adjust sign of remainder (x is negative)\n//\n//\t-1:  00000001 -\u003e 11111111\n//\t     NOT: 11111110\n//\t     +1:  11111111\n//\n// Final result: -1 (11111111 in two's complement)\n//\n// Note: The sign of the remainder is always the same as the sign of the dividend (x).\nfunc (z *Int) Rem(x, y *Int) *Int {\n\t// Step 1: Check for division by zero\n\tif y.IsZero() {\n\t\tpanic(divisionByZeroError)\n\t}\n\n\t// Step 2, 3\n\txAbs, xSign := x.Abs(), x.Sign()\n\tyAbs := y.Abs()\n\n\t// Step 4: Perform unsigned division and get the remainder\n\tvar q, r uint256.Uint\n\tq.DivMod(xAbs, yAbs, \u0026r)\n\n\t// Step 5: Adjust the sign of the remainder\n\tif xSign \u003c 0 {\n\t\tr.Neg(\u0026r)\n\t}\n\n\tz.value.Set(\u0026r)\n\treturn z\n}\n\n// Mod sets z to the modulus x%y for y != 0 and returns z.\n// The result (z) has the same sign as the divisor y.\nfunc (z *Int) Mod(x, y *Int) *Int {\n\treturn z.ModE(x, y)\n}\n\n// DivE performs Euclidean division of x by y, setting z to the quotient and returning z.\n// If y == 0, it panics with a \"division by zero\" error.\n//\n// Euclidean division satisfies the following properties:\n//  1. The remainder is always non-negative: 0 \u003c= x mod y \u003c |y|\n//  2. It follows the identity: x = y * (x div y) + (x mod y)\nfunc (z *Int) DivE(x, y *Int) *Int {\n\tif y.IsZero() {\n\t\tpanic(divisionByZeroError)\n\t}\n\n\t// Compute the truncated division quotient\n\tz.Quo(x, y)\n\n\t// Compute the remainder\n\tr := new(Int).Rem(x, y)\n\n\t// If the remainder is negative, adjust the quotient\n\tif r.Sign() \u003c 0 {\n\t\tif y.Sign() \u003e 0 {\n\t\t\tz.Sub(z, NewInt(1))\n\t\t} else {\n\t\t\tz.Add(z, NewInt(1))\n\t\t}\n\t}\n\n\treturn z\n}\n\n// ModE computes the Euclidean modulus of x by y, setting z to the result and returning z.\n// If y == 0, it panics with a \"division by zero\" error.\n//\n// The Euclidean modulus is always non-negative and satisfies:\n//\n//\t0 \u003c= x mod y \u003c |y|\n//\n// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):\n//\n// Case 1: Let x = -7 (11111001 in two's complement) and y = 3 (00000011)\n//\n// Step 1: Compute remainder (using Rem)\n//\n//\tResult of Rem: -1 (11111111 in two's complement)\n//\n// Step 2: Adjust sign (result is negative, y is positive)\n//\n//\t-1 + 3 = 2\n//\t11111111 + 00000011 = 00000010\n//\n// Final result: 2 (00000010)\n//\n// Case 2: Let x = -7 (11111001 in two's complement) and y = -3 (11111101 in two's complement)\n//\n// Step 1: Compute remainder (using Rem)\n//\n//\tResult of Rem: -1 (11111111 in two's complement)\n//\n// Step 2: Adjust sign (result is negative, y is negative)\n//\n//\tNo adjustment needed\n//\n// Final result: -1 (11111111 in two's complement)\n//\n// Note: This implementation ensures that the result always has the same sign as y,\n// which is different from the Rem operation.\nfunc (z *Int) ModE(x, y *Int) *Int {\n\tif y.IsZero() {\n\t\tpanic(divisionByZeroError)\n\t}\n\n\t// Perform T-division to get the remainder\n\tz.Rem(x, y)\n\n\t// Adjust the remainder if necessary\n\tif z.Sign() \u003e= 0 {\n\t\treturn z\n\t}\n\tif y.Sign() \u003e 0 {\n\t\treturn z.Add(z, y)\n\t}\n\n\treturn z.Sub(z, y)\n}\n\n// Sets z to the sum x + y, where z and x are uint256s and y is an int256.\n//\n// If the y is positive, it adds y.value to x. otherwise, it subtracts y.Abs() from x.\nfunc AddDelta(z, x *uint256.Uint, y *Int) {\n\tif y.Sign() \u003e= 0 {\n\t\tz.Add(x, \u0026y.value)\n\t} else {\n\t\tz.Sub(x, y.Abs())\n\t}\n}\n\n// Sets z to the sum x + y, where z and x are uint256s and y is an int256.\n//\n// This function returns true if the addition overflows, false otherwise.\nfunc AddDeltaOverflow(z, x *uint256.Uint, y *Int) bool {\n\tvar overflow bool\n\tif y.Sign() \u003e= 0 {\n\t\t_, overflow = z.AddOverflow(x, \u0026y.value)\n\t} else {\n\t\tvar absY uint256.Uint\n\t\tabsY.Sub(uint0, \u0026y.value) // absY = -y.value\n\t\t_, overflow = z.SubOverflow(x, \u0026absY)\n\t}\n\n\treturn overflow\n}\n"},{"name":"bitwise.gno","body":"package int256\n\n// Not sets z to the bitwise NOT of x and returns z.\n//\n// The bitwise NOT operation flips each bit of the operand.\nfunc (z *Int) Not(x *Int) *Int {\n\tz.value.Not(\u0026x.value)\n\treturn z\n}\n\n// And sets z to the bitwise AND of x and y and returns z.\n//\n// The bitwise AND operation results in a value that has a bit set\n// only if both corresponding bits of the operands are set.\nfunc (z *Int) And(x, y *Int) *Int {\n\tz.value.And(\u0026x.value, \u0026y.value)\n\treturn z\n}\n\n// Or sets z to the bitwise OR of x and y and returns z.\n//\n// The bitwise OR operation results in a value that has a bit set\n// if at least one of the corresponding bits of the operands is set.\nfunc (z *Int) Or(x, y *Int) *Int {\n\tz.value.Or(\u0026x.value, \u0026y.value)\n\treturn z\n}\n\n// Xor sets z to the bitwise XOR of x and y and returns z.\n//\n// The bitwise XOR operation results in a value that has a bit set\n// only if the corresponding bits of the operands are different.\nfunc (z *Int) Xor(x, y *Int) *Int {\n\tz.value.Xor(\u0026x.value, \u0026y.value)\n\treturn z\n}\n\n// Rsh sets z to the result of right-shifting x by n bits and returns z.\n//\n// Right shift operation moves all bits in the operand to the right by the specified number of positions.\n// Bits shifted out on the right are discarded, and zeros are shifted in on the left.\nfunc (z *Int) Rsh(x *Int, n uint) *Int {\n\tz.value.Rsh(\u0026x.value, n)\n\treturn z\n}\n\n// Lsh sets z to the result of left-shifting x by n bits and returns z.\n//\n// Left shift operation moves all bits in the operand to the left by the specified number of positions.\n// Bits shifted out on the left are discarded, and zeros are shifted in on the right.\nfunc (z *Int) Lsh(x *Int, n uint) *Int {\n\tz.value.Lsh(\u0026x.value, n)\n\treturn z\n}\n"},{"name":"cmp.gno","body":"package int256\n\nfunc (z *Int) Eq(x *Int) bool {\n\treturn z.value.Eq(\u0026x.value)\n}\n\nfunc (z *Int) Neq(x *Int) bool {\n\treturn !z.Eq(x)\n}\n\n// Cmp compares z and x and returns:\n//\n//   - 1 if z \u003e x\n//   - 0 if z == x\n//   - -1 if z \u003c x\nfunc (z *Int) Cmp(x *Int) int {\n\tzSign, xSign := z.Sign(), x.Sign()\n\n\tif zSign == xSign {\n\t\treturn z.value.Cmp(\u0026x.value)\n\t}\n\n\tif zSign == 0 {\n\t\treturn -xSign\n\t}\n\n\treturn zSign\n}\n\n// IsZero returns true if z == 0\nfunc (z *Int) IsZero() bool {\n\treturn z.value.IsZero()\n}\n\n// IsNeg returns true if z \u003c 0\nfunc (z *Int) IsNeg() bool {\n\treturn z.Sign() \u003c 0\n}\n\nfunc (z *Int) Lt(x *Int) bool {\n\treturn z.Cmp(x) \u003c 0\n}\n\nfunc (z *Int) Gt(x *Int) bool {\n\treturn z.Cmp(x) \u003e 0\n}\n\nfunc (z *Int) Le(x *Int) bool {\n\treturn z.Cmp(x) \u003c= 0\n}\n\nfunc (z *Int) Ge(x *Int) bool {\n\treturn z.Cmp(x) \u003e= 0\n}\n\n// Clone creates a new Int identical to z\nfunc (z *Int) Clone() *Int {\n\treturn New().FromUint256(\u0026z.value)\n}\n"},{"name":"conversion.gno","body":"package int256\n\nimport (\n\t\"math\"\n\n\t\"gno.land/p/onbloc/uint256/v0\"\n)\n\n// SetInt64 sets the Int to the value of the provided int64.\n//\n// This method allows for easy conversion from standard Go integer types\n// to Int, correctly handling both positive and negative values.\nfunc (z *Int) SetInt64(v int64) *Int {\n\tif v \u003e= 0 {\n\t\tz.value.SetUint64(uint64(v))\n\t} else {\n\t\tz.value.SetUint64(uint64(-v)).Neg(\u0026z.value)\n\t}\n\treturn z\n}\n\n// SetUint64 sets the Int to the value of the provided uint64.\nfunc (z *Int) SetUint64(v uint64) *Int {\n\tz.value.SetUint64(v)\n\treturn z\n}\n\n// Uint64 returns the lower 64-bits of z\nfunc (z *Int) Uint64() uint64 {\n\tif z.Sign() \u003c 0 {\n\t\tpanic(\"cannot convert negative int256 to uint64\")\n\t}\n\tif z.value.Gt(uint256.NewUint(0).SetUint64(math.MaxUint64)) {\n\t\tpanic(\"overflow: int256 does not fit in uint64 type\")\n\t}\n\treturn z.value.Uint64()\n}\n\n// Int64 returns the lower 64-bits of z\nfunc (z *Int) Int64() int64 {\n\tif z.Sign() \u003e= 0 {\n\t\tif z.value.BitLen() \u003e 64 {\n\t\t\tpanic(\"overflow: int256 does not fit in int64 type\")\n\t\t}\n\t\treturn int64(z.value.Uint64())\n\t}\n\tvar temp uint256.Uint\n\ttemp.Sub(uint256.NewUint(0), \u0026z.value) // temp = -z.value\n\tif temp.BitLen() \u003e 64 {\n\t\tpanic(\"overflow: int256 does not fit in int64 type\")\n\t}\n\treturn -int64(temp.Uint64())\n}\n\n// Neg sets z to -x and returns z.)\nfunc (z *Int) Neg(x *Int) *Int {\n\tif x.IsZero() {\n\t\tz.value.Clear()\n\t} else {\n\t\tz.value.Neg(\u0026x.value)\n\t}\n\treturn z\n}\n\n// Set sets z to x and returns z.\nfunc (z *Int) Set(x *Int) *Int {\n\tz.value.Set(\u0026x.value)\n\treturn z\n}\n\n// SetFromUint256 converts a uint256.Uint to Int and sets the value to z.\nfunc (z *Int) SetUint256(x *uint256.Uint) *Int {\n\tz.value.Set(x)\n\treturn z\n}\n\n// ToString returns a string representation of z in base 10.\n// The string is prefixed with a minus sign if z is negative.\nfunc (z *Int) String() string {\n\tif z.value.IsZero() {\n\t\treturn \"0\"\n\t}\n\tsign := z.Sign()\n\tvar temp uint256.Uint\n\tif sign \u003e= 0 {\n\t\ttemp.Set(\u0026z.value)\n\t} else {\n\t\t// temp = -z.value\n\t\ttemp.Sub(uint256.NewUint(0), \u0026z.value)\n\t}\n\ts := temp.Dec()\n\tif sign \u003c 0 {\n\t\treturn \"-\" + s\n\t}\n\treturn s\n}\n\n// NilToZero returns the Int if it's not nil, or a new zero-valued Int otherwise.\n//\n// This method is useful for safely handling potentially nil Int pointers,\n// ensuring that operations always have a valid Int to work with.\nfunc (z *Int) NilToZero() *Int {\n\tif z == nil {\n\t\treturn Zero()\n\t}\n\treturn z\n}\n"},{"name":"doc.gno","body":"// The int256 package provides a 256-bit signed interger type for gno,\n// supporting arithmetic operations and bitwise manipulation.\n//\n// It designed for applications that require high-precision arithmetic\n// beyond the standard 64-bit range.\n//\n// ## Features\n//\n//   - 256-bit Signed Integers: Support for large integer ranging from -2^255 to 2^255-1.\n//   - Two's Complement Representation: Efficient storage and computation using two's complement.\n//   - Arithmetic Operations: Add, Sub, Mul, Div, Mod, Inc, Dec, etc.\n//   - Bitwise Operations: And, Or, Xor, Not, etc.\n//   - Comparison Operations: Cmp, Eq, Lt, Gt, etc.\n//   - Conversion Functions: Int to Uint, Uint to Int, etc.\n//   - String Parsing and Formatting: Convert to and from decimal string representation.\n//\n// ## Notes\n//\n//   - Some methods may panic when encountering invalid inputs or overflows.\n//   - The `int256.Int` type can interact with `uint256.Uint` from the `p/demo/uint256` package.\n//   - Unlike `math/big.Int`, the `int256.Int` type has fixed size (256-bit) and does not support\n//     arbitrary precision arithmetic.\n//\n// # Division and modulus operations\n//\n// This package provides three different division and modulus operations:\n//\n//   - Div and Rem: Truncated division (T-division)\n//   - Quo and Mod: Floored division (F-division)\n//   - DivE and ModE: Euclidean division (E-division)\n//\n// Truncated division (Div, Rem) is the most common implementation in modern processors\n// and programming languages. It rounds quotients towards zero and the remainder\n// always has the same sign as the dividend.\n//\n// Floored division (Quo, Mod) always rounds quotients towards negative infinity.\n// This ensures that the modulus is always non-negative for a positive divisor,\n// which can be useful in certain algorithms.\n//\n// Euclidean division (DivE, ModE) ensures that the remainder is always non-negative,\n// regardless of the signs of the dividend and divisor. This has several mathematical\n// advantages:\n//\n//  1. It satisfies the unique division with remainder theorem.\n//  2. It preserves division and modulus properties for negative divisors.\n//  3. It allows for optimizations in divisions by powers of two.\n//\n// [+] Currently, ModE and Mod are shared the same implementation.\n//\n// ## Performance considerations:\n//\n//   - For most operations, the performance difference between these division types is negligible.\n//   - Euclidean division may require an extra comparison and potentially an addition,\n//     which could impact performance in extremely performance-critical scenarios.\n//   - For divisions by powers of two, Euclidean division can be optimized to use\n//     bitwise operations, potentially offering better performance.\n//\n// ## Usage guidelines:\n//\n//   - Use Div and Rem for general-purpose division that matches most common expectations.\n//   - Use Quo and Mod when you need a non-negative remainder for positive divisors,\n//     or when implementing algorithms that assume floored division.\n//   - Use DivE and ModE when you need the mathematical properties of Euclidean division,\n//     or when working with algorithms that specifically require it.\n//\n// Note: When working with negative numbers, be aware of the differences in behavior\n// between these division types, especially at the boundaries of integer ranges.\n//\n// ## References\n//\n// Daan Leijen, “Division and Modulus for Computer Scientists”:\n// https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/divmodnote-letter.pdf\npackage int256\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/onbloc/int256/v0\"\ngno = \"0.9\"\n"},{"name":"int256.gno","body":"package int256\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/onbloc/uint256/v0\"\n)\n\nvar (\n\tint1  = NewInt(1)\n\tuint0 = uint256.NewUint(0)\n\tuint1 = uint256.NewUint(1)\n)\n\ntype Int struct {\n\tvalue uint256.Uint\n}\n\n// New creates and returns a new Int initialized to zero.\nfunc New() *Int {\n\treturn \u0026Int{}\n}\n\n// NewInt allocates and returns a new Int set to the value of the provided int64.\nfunc NewInt(x int64) *Int {\n\treturn New().SetInt64(x)\n}\n\n// Zero returns a new Int initialized to 0.\n//\n// This function is useful for creating a starting point for calculations or\n// when an explicit zero value is needed.\nfunc Zero() *Int { return \u0026Int{} }\n\n// One returns a new Int initialized to one.\n//\n// This function is convenient for operations that require a unit value,\n// such as incrementing or serving as an identity element in multiplication.\nfunc One() *Int {\n\treturn \u0026Int{\n\t\tvalue: *uint256.NewUint(1),\n\t}\n}\n\n// Sign determines the sign of the Int.\n//\n// It returns -1 for negative numbers, 0 for zero, and +1 for positive numbers.\nfunc (z *Int) Sign() int {\n\tif z == nil || z.IsZero() {\n\t\treturn 0\n\t}\n\t// Right shift the value by 255 bits to check the sign bit.\n\t// In two's complement representation, the most significant bit (MSB) is the sign bit.\n\t// If the MSB is 0, the number is positive; if it is 1, the number is negative.\n\t//\n\t// Example:\n\t// Original value:  1 0 1 0 ... 0 1  (256 bits)\n\t// After Rsh 255:   0 0 0 0 ... 0 1  (1 bit)\n\t//\n\t// This approach is highly efficient as it avoids the need for comparisons\n\t// or arithmetic operations on the full 256-bit number. Instead it reduces\n\t// the problem to checking a single bit.\n\t//\n\t// Additionally, this method will work correctly for all values,\n\t// including the minimum possible negative number (which in two's complement\n\t// doesn't have a positive counterpart in the same bit range).\n\tvar temp uint256.Uint\n\tif temp.Rsh(\u0026z.value, 255).IsZero() {\n\t\treturn 1\n\t}\n\treturn -1\n}\n\n// FromDecimal creates a new Int from a decimal string representation.\n// It handles both positive and negative values.\n//\n// This function is useful for parsing user input or reading numeric data\n// from text-based formats.\nfunc FromDecimal(s string) (*Int, error) {\n\treturn New().SetString(s)\n}\n\n// MustFromDecimal is similar to FromDecimal but panics if the input string\n// is not a valid decimal representation.\nfunc MustFromDecimal(s string) *Int {\n\tz, err := FromDecimal(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn z\n}\n\n// SetString sets the Int to the value represented by the input string.\n// This method supports decimal string representations of integers and handles\n// both positive and negative values.\nfunc (z *Int) SetString(s string) (*Int, error) {\n\tif len(s) == 0 {\n\t\treturn nil, errors.New(\"cannot set int256 from empty string\")\n\t}\n\n\t// Check for negative sign\n\tneg := s[0] == '-'\n\tif neg || s[0] == '+' {\n\t\ts = s[1:]\n\t}\n\n\t// Convert string to uint256\n\ttemp, err := uint256.FromDecimal(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If negative, negate the uint256 value\n\tif neg {\n\t\ttemp.Neg(temp)\n\t}\n\n\tz.value.Set(temp)\n\treturn z, nil\n}\n\n// FromUint256 sets the Int to the value of the provided Uint256.\n//\n// This method allows for conversion from unsigned 256-bit integers\n// to signed integers.\nfunc (z *Int) FromUint256(v *uint256.Uint) *Int {\n\tz.value.Set(v)\n\treturn z\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"coins","path":"gno.land/r/gnoland/coins","files":[{"name":"coins.gno","body":"// Package coins provides simple helpers to retrieve information about coins\n// on the Gno.land blockchain.\n//\n// The primary goal of this realm is to allow users to check their token balances without\n// relying on external tools or services. This is particularly valuable for new networks\n// that aren't yet widely supported by public explorers or wallets. By using this realm,\n// users can always access their balance information directly through the gnodev.\n//\n// While currently focused on basic balance checking functionality, this realm could\n// potentially be extended to support other banker-related workflows in the future.\n// However, we aim to keep it minimal and focused on its core purpose.\n//\n// This is a \"Render-only realm\" - it exposes only a Render function as its public\n// interface and doesn't maintain any state of its own. This pattern allows for\n// simple, stateless information retrieval directly through the blockchain's\n// rendering capabilities.\npackage coins\n\nimport (\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/leon/coinsort/v0\"\n\t\"gno.land/p/leon/ctg/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/nt/mux/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\t\"gno.land/r/sys/users\"\n)\n\nvar router *mux.Router\n\nfunc init() {\n\trouter = mux.NewRouter()\n\n\trouter.HandleFunc(\"\", func(res *mux.ResponseWriter, req *mux.Request) {\n\t\tres.Write(renderHomepage())\n\t})\n\n\trouter.HandleFunc(\"balances\", func(res *mux.ResponseWriter, req *mux.Request) {\n\t\tres.Write(renderBalances(req))\n\t})\n\n\trouter.HandleFunc(\"convert/{address}\", func(res *mux.ResponseWriter, req *mux.Request) {\n\t\tres.Write(renderConvertedAddress(req.GetVar(\"address\")))\n\t})\n\n\t// Coin info\n\trouter.HandleFunc(\"supply/{denom}\", func(res *mux.ResponseWriter, req *mux.Request) {\n\t\t// banker := banker.NewReadonlyBanker()\n\t\t// res.Write(renderAddressBalance(banker, denom, denom))\n\t\tres.Write(\"The total supply feature is coming soon.\")\n\t})\n\n\trouter.NotFoundHandler = func(res *mux.ResponseWriter, req *mux.Request) {\n\t\tres.Write(\"# 404\\n\\nThat page was not found. Would you like to [**go home**?](/r/gnoland/coins)\")\n\t}\n}\n\nfunc Render(path string) string {\n\treturn router.Render(path)\n}\n\nfunc renderHomepage() string {\n\treturn strings.Replace(`# Gno.land Coins Explorer\n\nThis is a simple, readonly realm that allows users to browse native coin balances. Check your coin balance below!\n\n\u003cgno-form path=\"balances\"\u003e\n\t\u003cgno-input name=\"address\" type=\"text\" placeholder=\"Valid bech32 address (e.g. g1..., cosmos1..., osmo1...)\" /\u003e\n\t\u003cgno-input name=\"coin\" type=\"text\" placeholder=\"Coin (e.g. ugnot)\"\" /\u003e\n\u003c/gno-form\u003e\n\nHere are a few more ways to use this app:\n\n- ~/r/gnoland/coins:balances?address=g1...~ - show full list of coin balances of an address\n\t- [Example](/r/gnoland/coins:balances?address=g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5)\n- ~/r/gnoland/coins:balances?address=g1...\u0026coin=ugnot~ - shows the balance of an address for a specific coin\n\t- [Example](/r/gnoland/coins:balances?address=g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\u0026coin=ugnot)\n- ~/r/gnoland/coins:convert/\u003cbech32_addr\u003e~ - convert a bech32 address to a Gno address\n\t- [Example](/r/gnoland/coins:convert/cosmos1jg8mtutu9khhfwc4nxmuhcpftf0pajdh6svrgs)\n- ~/r/gnoland/coins:supply/\u003cdenom\u003e~ - shows the total supply of denom\n\t- Coming soon!\n\n`, \"~\", \"`\", -1)\n}\n\nfunc renderBalances(req *mux.Request) string {\n\tout := \"# Balances\\n\\n\"\n\n\tinput := req.Query.Get(\"address\")\n\tcoin := req.Query.Get(\"coin\")\n\n\tif input == \"\" \u0026\u0026 coin == \"\" {\n\t\tout += \"Please input a valid address and coin denomination.\\n\\n\"\n\t\treturn out\n\t}\n\n\tif input == \"\" {\n\t\tout += \"Please input a valid bech32 address.\\n\\n\"\n\t\treturn out\n\t}\n\n\toriginalInput := input\n\tvar wasConverted bool\n\n\t// Try to validate or convert\n\tif !address(input).IsValid() {\n\t\taddr, err := ctg.ConvertAnyToGno(input)\n\t\tif err != nil {\n\t\t\treturn out + ufmt.Sprintf(\"Tried converting `%s` to a Gno address but failed. Please try with a valid bech32 address.\\n\\n\", input)\n\t\t}\n\t\tinput = addr.String()\n\t\twasConverted = true\n\t}\n\n\tif wasConverted {\n\t\tout += ufmt.Sprintf(\"\u003e [!NOTE]\\n\u003e  Automatically converted `%s` to its Gno equivalent.\\n\\n\", originalInput)\n\t}\n\n\tbanker_ := banker.NewReadonlyBanker()\n\tbalances := banker_.GetCoins(address(input))\n\n\tif len(balances) == 0 {\n\t\tout += \"This address currently has no coins.\"\n\t\treturn out\n\t}\n\n\tif coin != \"\" {\n\t\treturn renderSingleCoinBalance(coin, input, originalInput, wasConverted, balances.AmountOf(coin))\n\t}\n\n\tuser, _ := users.ResolveAny(input)\n\tname := \"`\" + input + \"`\"\n\tif user != nil {\n\t\tname = user.RenderLink(\"\")\n\t}\n\n\tout += ufmt.Sprintf(\"This page shows full coin balances of %s at block #%d\\n\\n\",\n\t\tname, runtime.ChainHeight())\n\n\t// Determine sorting\n\tif getSortField(req) == \"balance\" {\n\t\tcoinsort.SortByBalance(balances)\n\t}\n\n\t// Create table\n\tdenomColumn := renderSortLink(req, \"denom\", \"Denomination\")\n\tbalanceColumn := renderSortLink(req, \"balance\", \"Balance\")\n\ttable := mdtable.Table{\n\t\tHeaders: []string{denomColumn, balanceColumn},\n\t}\n\n\tif isSortReversed(req) {\n\t\tfor _, b := range balances {\n\t\t\ttable.Append([]string{b.Denom, strconv.Itoa(int(b.Amount))})\n\t\t}\n\t} else {\n\t\tfor i := len(balances) - 1; i \u003e= 0; i-- {\n\t\t\ttable.Append([]string{balances[i].Denom, strconv.Itoa(int(balances[i].Amount))})\n\t\t}\n\t}\n\n\tout += table.String() + \"\\n\\n\"\n\treturn out\n}\n\n// amount is taken from the balances the caller already read, rather than read again.\n// Beyond saving the read, it keeps an unvalidated denom out of the banker: denom is\n// the \"coin\" query parameter, and GetCoin panics on a malformed one, so on a render\n// path any URL could otherwise break the page.\nfunc renderSingleCoinBalance(denom, addr, origInput string, wasConverted bool, amount int64) string {\n\tout := \"# Coin balance\\n\\n\"\n\n\tif wasConverted {\n\t\tout += ufmt.Sprintf(\"\u003e [!NOTE]\\n\u003e  Automatically converted `%s` to its Gno equivalent.\\n\\n\", origInput)\n\t}\n\n\tuser, _ := users.ResolveAny(addr)\n\tname := \"`\" + addr + \"`\"\n\tif user != nil {\n\t\tname = user.RenderLink(\"\")\n\t}\n\n\tout += ufmt.Sprintf(\"%s has `%d%s` at block #%d\\n\\n\",\n\t\tname, amount, denom, runtime.ChainHeight())\n\n\tout += \"[View full balance list for this address](/r/gnoland/coins:balances?address=\" + addr + \")\"\n\n\treturn out\n}\n\nfunc renderConvertedAddress(addr string) string {\n\tout := \"# Address converter\\n\\n\"\n\n\tgnoAddress, err := ctg.ConvertAnyToGno(addr)\n\tif err != nil {\n\t\tout += err.Error()\n\t\treturn out\n\t}\n\n\tuser, _ := users.ResolveAny(gnoAddress.String())\n\tname := \"`\" + gnoAddress.String() + \"`\"\n\tif user != nil {\n\t\tname = user.RenderLink(\"\")\n\t}\n\n\tout += ufmt.Sprintf(\"`%s` on Cosmos matches %s on gno.land.\\n\\n\", addr, name)\n\tout += \"[[View `ugnot` balance for this address]](/r/gnoland/coins:balances?address=\" + gnoAddress.String() + \"\u0026coin=ugnot) - \"\n\tout += \"[[View full balance list for this address]](/r/gnoland/coins:balances?address=\" + gnoAddress.String() + \")\"\n\treturn out\n}\n\n// Helper functions for sorting and pagination\nfunc getSortField(req *mux.Request) string {\n\tfield := req.Query.Get(\"sort\")\n\tswitch field {\n\tcase \"denom\", \"balance\":\n\t\treturn field\n\t}\n\treturn \"denom\"\n}\n\nfunc isSortReversed(req *mux.Request) bool {\n\treturn req.Query.Get(\"order\") != \"asc\"\n}\n\nfunc renderSortLink(req *mux.Request, field, label string) string {\n\tcurrentField := getSortField(req)\n\tcurrentOrder := req.Query.Get(\"order\")\n\n\tnewOrder := \"desc\"\n\tif field == currentField \u0026\u0026 currentOrder != \"asc\" {\n\t\tnewOrder = \"asc\"\n\t}\n\n\tquery := make(url.Values)\n\tfor k, vs := range req.Query {\n\t\tquery[k] = append([]string(nil), vs...)\n\t}\n\n\tquery.Set(\"sort\", field)\n\tquery.Set(\"order\", newOrder)\n\n\tif field == currentField {\n\t\tif currentOrder == \"asc\" {\n\t\t\tlabel += \" ↑\"\n\t\t} else {\n\t\t\tlabel += \" ↓\"\n\t\t}\n\t}\n\n\treturn md.Link(label, \"?\"+query.Encode())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/gnoland/coins\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"crossrealm_e","path":"gno.land/r/tests/vm/crossrealm_e","files":[{"name":"crossrealm.gno","body":"package crossrealm_e\n\nimport (\n\t\"chain/runtime/unsafe\"\n)\n\nvar (\n\tbalance int64\n\towner   address\n)\n\nfunc init() {\n\tbalance = 1000\n\tSetOwner(address(\"g1dao_address_here\"))\n}\n\n// SetOwner is an internal helper that was exported by mistake\n// (should be setOwner). Without the pre-mutation readonly check,\n// a cross-realm caller could call SetOwner + recover to silently\n// hijack ownership in memory, then call TransferToken to steal funds.\nfunc SetOwner(o address) {\n\towner = o\n}\n\nfunc GetOwner() address {\n\treturn owner\n}\n\nfunc TransferOwnership(cur realm, o address) {\n\tif unsafe.PreviousRealm().Address() != owner {\n\t\tpanic(\"unauthorized\")\n\t}\n\towner = o\n}\n\nfunc TransferToken(cur realm) {\n\tcaller := unsafe.PreviousRealm().Address()\n\tif caller != owner {\n\t\tpanic(\"unauthorized\")\n\t}\n\tbalance -= 500\n\tprintln(\"===send token to: \", caller)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/crossrealm_e\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"init","path":"gno.land/r/gov/dao/init/v0","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/init/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da\"\n"},{"name":"init.gno","body":"package init\n\nimport (\n\t\"chain/runtime\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/impl/v0\"\n\t\"gno.land/r/gov/dao/memberstore/v0\"\n)\n\nfunc Init(cur realm) {\n\tassertIsDevChain()\n\n\t// This is needed because state is saved between unit tests,\n\t// and we want to avoid having real members used on tests\n\tmemberstore.Get(0, cur).DeleteAll()\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), []string{\"gno.land/r/gov/dao/impl/v0\"}))\n}\n\nfunc InitWithUsers(cur realm, addrs ...address) {\n\tassertIsDevChain()\n\n\t// This is needed because state is saved between unit tests,\n\t// and we want to avoid having real members used on tests\n\tmemberstore.Get(0, cur).DeleteAll()\n\tmemberstore.Get(0, cur).SetTier(memberstore.T1)\n\tfor _, a := range addrs {\n\t\tif !a.IsValid() {\n\t\t\tpanic(\"invalid address: \" + a.String())\n\t\t}\n\t\tmemberstore.Get(0, cur).SetMember(memberstore.T1, a, memberstore.NewMember(3))\n\t}\n\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), []string{\"gno.land/r/gov/dao/impl/v0\"}))\n}\n\nfunc assertIsDevChain() {\n\tchainID := runtime.ChainID()\n\tif chainID != \"dev\" \u0026\u0026 chainID != \"tendermint_test\" {\n\t\tpanic(\"unauthorized\")\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"crossrealm_f","path":"gno.land/r/tests/vm/crossrealm_f","files":[{"name":"crossrealm.gno","body":"// Package crossrealm_f provides a collection realm for testing cross-realm\n// ownership scenarios. It uses a nested structure so that intermediate objects\n// in the ownership chain have RefCount == 1.\npackage crossrealm_f\n\ntype Entry struct {\n\tKey   string\n\tValue int\n}\n\nvar entries []*Entry\n\nfunc NewEntry(key string, value int) *Entry {\n\treturn \u0026Entry{Key: key, Value: value}\n}\n\nfunc Add(cur realm, e *Entry) {\n\tentries = append(entries, e)\n}\n\nfunc Remove(cur realm, key string) *Entry {\n\tfor i, e := range entries {\n\t\tif e.Key == key {\n\t\t\tentries = append(entries[:i], entries[i+1:]...)\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Get(key string) *Entry {\n\tfor _, e := range entries {\n\t\tif e.Key == key {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Len() int {\n\treturn len(entries)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/vm/crossrealm_f\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserProd"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/vm.m_call","caller":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","send":"","max_deposit":"","pkg_path":"gno.land/r/sys/users/init","func":"Bootstrap"}],"fee":{"gas_wanted":"2000000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":null,"signature":null}],"memo":""},"metadata":{"timestamp":"1794551875"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1qpymzwx4l4cy6cerdyajp9ksvjsf20rk5y9rtt","amount":"4200000ugnot"}],"fee":{"gas_wanted":"2000000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"c7XCk3fsiEOahbnJnv7SXKMJTym53nmKS/HqY7fCpLMPvqh06U4oCeu0q5DtS+BvccwToZB+mgK/RFRGDzIW7A=="}],"memo":""},"metadata":{"timestamp":"1790615568"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"hello","path":"gno.land/r/g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5/hello","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5/hello\"\ngno = \"0.9\"\n"},{"name":"hello.gno","body":"package hello\n\nimport \"strconv\"\n\nvar count int\n\nfunc Incr(cur realm) int {\n\tcount++\n\treturn count\n}\n\nfunc Render(path string) string {\n\treturn \"# hello\\n\\ncount: \" + strconv.Itoa(count) + \"\\n\"\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"20000000","gas_fee":"1000000ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+tUUMEvX8n33h3Lemh6Yf2tbPzwuMrsEV+o3NxkbsuNI4C0954GX+FiIYW+yqN6yZaIHz8Dq5qcOrSDXTHyUDw=="}],"memo":""},"metadata":{"timestamp":"1790631680"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1gxgrfr52wszu9vu3w0vusz58u3runaldfvwgzn","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1856146","gas_fee":"3714ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"KthGObHXunzegTKlCWfqL1qenURtm0iSMiMkvFvPiltT+XZwm/fEUa7Jb4yB91EcGqNr41BjhPAiMdPkU2l6sg=="}],"memo":""},"metadata":{"timestamp":"1790854544"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1857727","gas_fee":"3716ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"yPjHumP4EtRUPyhPgXpWlFV/vJqxVK4Y87Vh5tDdJmg68USeMeqPz8swAZFYLRlEK7EK+SyXnlhcWxIGUaUUcg=="}],"memo":""},"metadata":{"timestamp":"1790854561"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"2Wwt31TPKR/nwllziRnBXQjji4dYFa6nez1+9MadONFD/x36ZUNQ8dlzp8UyfO9k+KP3X9t175qCP5d5e1XSCg=="}],"memo":""},"metadata":{"timestamp":"1790958721"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Q866fqIG86NLMeWJsouFVX+iXa7b0xNEOffJiSX8wrJxbcl8fhTjkKxKGtYqoMzthmjDHnDc+Ct7VR58hlCJLg=="}],"memo":""},"metadata":{"timestamp":"1790958813"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+3vRWqxPU8lLaUXZ4oBlQV/lGjfH0H3Oco8XLB/0sFRuOxRQiUEGVkd0T10z2nuN9zw4MtxhcWeAKA0j5ZpKTw=="}],"memo":""},"metadata":{"timestamp":"1790958875"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","package":{"name":"addrset","path":"gno.land/p/moul/addrset/v1","files":[{"name":"README.md","body":"# `gno.land/p/moul/addrset/v1`\n\nA set of blockchain addresses, **backed by a B+ tree** (`gno.land/p/nt/bptree`).\n\nThe B+ tree successor to [`p/moul/addrset/v0`](https://github.com/moul/gno-contracts/tree/3d07a5b2cc02d7c3769caff0c17d884ac033bcfe/p/moul/addrset/v0)\n(AVL-backed). **v1 because the backing data structure — and thus the on-chain\nstorage layout — changed** (a compatibility change ⇒ new version). A B+ tree\npacks many entries per persisted node, so a stored address costs ~0.9 KB vs the\nAVL backing's ~2.0 KB, and inserts spend materially less gas — prefer v1 for\npersisted realm state.\n\n```go\nimport \"gno.land/p/moul/addrset/v1\"\n\nvar set addrset.Set // zero value is an empty, usable set\nset.Add(addr)       // true (newly added)\nset.Has(addr)       // true\nset.Remove(addr)    // true (was present)\nset.IterateByOffset(0, 10, func(a address) bool { return false })\n```\n\n**Differences from v1:** the `Tree()` escape hatch is removed (the backing store\nnever leaks); and — because the B+ tree mutates in place — do not Add/Remove from\ninside an iteration callback, and do not copy a non-zero `Set` by value.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/addrset/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/addrset/v1/deps.png)\n\nProvenance: imported — see [https://github.com/moul/gno-contracts/pull/2](https://github.com/moul/gno-contracts/pull/2) for context and metadata.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"addrset.gno","body":"// Package addrset provides a set of blockchain addresses, backed by a B+ tree.\n//\n// It is the B+ tree successor to [gno.land/p/moul/addrset/v0] (which is backed\n// by an AVL tree): a bump to v1 because the backing data structure — and thus\n// the on-chain storage layout — changed. The exported API is the same as v0\n// (Add/Remove/Has/Size/IterateByOffset/ReverseIterateByOffset) EXCEPT that the\n// v0 `Tree() avl.ITree` escape hatch is intentionally removed, so the backing\n// store never leaks across realms.\n//\n// A B+ tree packs many entries per persisted node, so a stored address costs\n// roughly ~0.9 KB vs the AVL backing's ~2.0 KB (and inserts spend materially\n// less gas). Prefer v1 when the set is part of persisted realm state.\n//\n// Two behavioral differences from v0, both consequences of the in-place-\n// mutating B+ tree backing:\n//\n//   - do NOT mutate the set (Add/Remove) from inside an iteration callback —\n//     the AVL backing's copy-on-write tolerated it, this one does not;\n//   - do NOT copy a non-zero Set by value — the copies would share live tree\n//     nodes while their roots and sizes diverge (v0's copies were independent\n//     snapshots).\n//\n// Example:\n//\n//\tvar set addrset.Set // the zero value is an empty, usable set\n//\n//\tset.Add(addr)    // true (newly added)\n//\tset.Has(addr)    // true\n//\tset.Remove(addr) // true (was present)\npackage addrset\n\nimport \"gno.land/p/nt/bptree/v0\"\n\n// Set stores a set of addresses in sorted order. The zero value is an empty,\n// usable set.\ntype Set struct {\n\ttree bptree.BPTree\n}\n\n// Add inserts an address into the set.\n// Returns true if the address was newly added, false if it already existed.\nfunc (s *Set) Add(addr address) bool {\n\treturn !s.tree.Set(string(addr), nil)\n}\n\n// Remove deletes an address from the set.\n// Returns true if the address was found and removed, false if it didn't exist.\nfunc (s *Set) Remove(addr address) bool {\n\t_, removed := s.tree.Remove(string(addr))\n\treturn removed\n}\n\n// Has checks if an address exists in the set.\nfunc (s *Set) Has(addr address) bool {\n\treturn s.tree.Has(string(addr))\n}\n\n// Size returns the number of addresses in the set.\nfunc (s *Set) Size() int {\n\treturn s.tree.Size()\n}\n\n// IterateByOffset walks through addresses in sorted order, starting at the\n// given offset and visiting up to count addresses. The callback returns true\n// to stop iteration. The set must not be modified during iteration.\nfunc (s *Set) IterateByOffset(offset int, count int, cb func(addr address) bool) {\n\ts.tree.IterateByOffset(offset, count, func(key string, _ any) bool {\n\t\treturn cb(address(key))\n\t})\n}\n\n// ReverseIterateByOffset walks through addresses in reverse (descending) order,\n// starting at the given offset (counted from the end) and visiting up to count\n// addresses. The callback returns true to stop iteration. The set must not be\n// modified during iteration.\nfunc (s *Set) ReverseIterateByOffset(offset int, count int, cb func(addr address) bool) {\n\ts.tree.ReverseIterateByOffset(offset, count, func(key string, _ any) bool {\n\t\treturn cb(address(key))\n\t})\n}\n"},{"name":"addrset_test.gno","body":"package addrset\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestSet(t *testing.T) {\n\taddr1 := address(\"addr1\")\n\taddr2 := address(\"addr2\")\n\taddr3 := address(\"addr3\")\n\n\ttests := []struct {\n\t\tname    string\n\t\tactions func(s *Set)\n\t\tsize    int\n\t\thas     map[address]bool\n\t\taddrs   []address // for iteration checks\n\t}{\n\t\t{\n\t\t\tname:    \"empty set\",\n\t\t\tactions: func(s *Set) {},\n\t\t\tsize:    0,\n\t\t\thas:     map[address]bool{addr1: false},\n\t\t},\n\t\t{\n\t\t\tname: \"single address\",\n\t\t\tactions: func(s *Set) {\n\t\t\t\ts.Add(addr1)\n\t\t\t},\n\t\t\tsize: 1,\n\t\t\thas: map[address]bool{\n\t\t\t\taddr1: true,\n\t\t\t\taddr2: false,\n\t\t\t},\n\t\t\taddrs: []address{addr1},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple addresses\",\n\t\t\tactions: func(s *Set) {\n\t\t\t\ts.Add(addr1)\n\t\t\t\ts.Add(addr2)\n\t\t\t\ts.Add(addr3)\n\t\t\t},\n\t\t\tsize: 3,\n\t\t\thas: map[address]bool{\n\t\t\t\taddr1: true,\n\t\t\t\taddr2: true,\n\t\t\t\taddr3: true,\n\t\t\t},\n\t\t\taddrs: []address{addr1, addr2, addr3},\n\t\t},\n\t\t{\n\t\t\tname: \"remove address\",\n\t\t\tactions: func(s *Set) {\n\t\t\t\ts.Add(addr1)\n\t\t\t\ts.Add(addr2)\n\t\t\t\ts.Remove(addr1)\n\t\t\t},\n\t\t\tsize: 1,\n\t\t\thas: map[address]bool{\n\t\t\t\taddr1: false,\n\t\t\t\taddr2: true,\n\t\t\t},\n\t\t\taddrs: []address{addr2},\n\t\t},\n\t\t{\n\t\t\tname: \"duplicate adds\",\n\t\t\tactions: func(s *Set) {\n\t\t\t\tuassert.True(t, s.Add(addr1))     // first add returns true\n\t\t\t\tuassert.False(t, s.Add(addr1))    // second add returns false\n\t\t\t\tuassert.True(t, s.Remove(addr1))  // remove existing returns true\n\t\t\t\tuassert.False(t, s.Remove(addr1)) // remove non-existing returns false\n\t\t\t},\n\t\t\tsize: 0,\n\t\t\thas: map[address]bool{\n\t\t\t\taddr1: false,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar set Set\n\n\t\t\t// Execute test actions\n\t\t\ttt.actions(\u0026set)\n\n\t\t\t// Check size\n\t\t\tuassert.Equal(t, tt.size, set.Size())\n\n\t\t\t// Check existence\n\t\t\tfor addr, expected := range tt.has {\n\t\t\t\tuassert.Equal(t, expected, set.Has(addr))\n\t\t\t}\n\n\t\t\t// Check iteration if addresses are specified\n\t\t\tif tt.addrs != nil {\n\t\t\t\tcollected := []address{}\n\t\t\t\tset.IterateByOffset(0, 10, func(addr address) bool {\n\t\t\t\t\tcollected = append(collected, addr)\n\t\t\t\t\treturn false\n\t\t\t\t})\n\n\t\t\t\t// Check length\n\t\t\t\tuassert.Equal(t, len(tt.addrs), len(collected))\n\n\t\t\t\t// Check each address\n\t\t\t\tfor i, addr := range tt.addrs {\n\t\t\t\t\tuassert.Equal(t, addr, collected[i])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSetIterationLimits(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\taddrs    []address\n\t\toffset   int\n\t\tlimit    int\n\t\texpected int\n\t}{\n\t\t{\n\t\t\tname:     \"zero offset full list\",\n\t\t\taddrs:    []address{\"a1\", \"a2\", \"a3\"},\n\t\t\toffset:   0,\n\t\t\tlimit:    10,\n\t\t\texpected: 3,\n\t\t},\n\t\t{\n\t\t\tname:     \"offset with limit\",\n\t\t\taddrs:    []address{\"a1\", \"a2\", \"a3\", \"a4\"},\n\t\t\toffset:   1,\n\t\t\tlimit:    2,\n\t\t\texpected: 2,\n\t\t},\n\t\t{\n\t\t\tname:     \"offset beyond size\",\n\t\t\taddrs:    []address{\"a1\", \"a2\"},\n\t\t\toffset:   3,\n\t\t\tlimit:    1,\n\t\t\texpected: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar set Set\n\t\t\tfor _, addr := range tt.addrs {\n\t\t\t\tset.Add(addr)\n\t\t\t}\n\n\t\t\t// Test forward iteration\n\t\t\tcount := 0\n\t\t\tset.IterateByOffset(tt.offset, tt.limit, func(addr address) bool {\n\t\t\t\tcount++\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tuassert.Equal(t, tt.expected, count)\n\n\t\t\t// Test reverse iteration\n\t\t\tcount = 0\n\t\t\tset.ReverseIterateByOffset(tt.offset, tt.limit, func(addr address) bool {\n\t\t\t\tcount++\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tuassert.Equal(t, tt.expected, count)\n\t\t})\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/addrset/v1\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","package":{"name":"store","path":"gno.land/p/moul/kit/store/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/kit/store/v0`\n\nThe auto-id ordered collection every `r/moul` realm was building by hand: an\n`avl.Tree`, an int counter, and a private function that zero-pads the counter\ninto a key so the tree iterates in the order a human expects.\n\nSecond package of the `p/moul/kit/*` layer\n([moul/gno-contracts#151](https://github.com/moul/gno-contracts/issues/151)).\n`kit` composes the existing packages, it does not replace them.\n\n## Why it exists\n\nSixteen realm files in this repo carry that third piece. They do not agree:\n\n| Name | Width | Implementation | Realms |\n|---|---|---|---|\n| `padID` | 6 | `for len(s) \u003c 6 { s = \"0\" + s }` | `asciiart` |\n| `pad` | 12 | `for len(s) \u003c 12 { s = \"0\" + s }` | `tictactoe` |\n| `key` | 12 | the same loop, a different name | `blog`, `crowdfund`, `englishauction`, `erc721`, `splitter` |\n| `idKey` | 12 | the same loop again, a third name | `connect4` |\n| `idKey` | 12 | `strings.Repeat`, guarded by `len(s) \u003e= width` | `governor`, `todos` |\n| `idKey` | 12 | `strings.Repeat`, **unguarded** | `timecapsule` |\n| `seqKey` | 16 | `strings.Repeat`, guarded | `guestbook` |\n\nFive names, three widths, three implementations, one job, across 16 files in 12\nrealms.\n\n**Every one of them is a silent ceiling.** The key is a decimal string, and\ndecimal strings do not sort numerically. Below the width the zero-padding hides\nthat; at the width the padding stops and the tree starts ordering\n`\"1000000000000\"` before `\"999999999999\"`, so every list the realm renders is\nwrong from that entry on. Nothing fails, nothing logs, the order is just quietly\nfalse.\n\nThe unguarded variant fails harder. `strings.Repeat` panics on a negative count,\nso past its width `timecapsule` stops accepting writes rather than mis-sorting\nthem.\n\n`asciiart`'s width of 6 puts its ceiling at one million entries.\n\nBoth tests live in\n[`store_test.gno`](./store_test.gno) (`TestOrderSurvivesThePaddingCeiling`,\n`TestUnguardedPadPanicsPastItsWidth`), asserting the defect rather than\ndescribing it.\n\n## The fix is to delete the decision\n\nKeys are the big-endian bytes of a\n[`p/nt/seqid`](/p/nt/seqid/v0) ID: a fixed 8 bytes whose lexicographic order\n**is** numeric order, for every value a `uint64` can hold. There is no width to\npick and no width to outgrow. `seqid` already solved this and was imported by\nexactly one file in the repo.\n\n```go\nimport \"gno.land/p/moul/kit/store/v0\"\n\nvar games = store.Named(\"game\")             // or `var games store.Store`\n\nfunc NewGame(cur realm) int64 {\n    return int64(games.Add(\u0026Game{Board: empty, X: caller()}))\n}\n\nfunc Move(cur realm, gameID int64, cell int) {\n    g := games.MustGet(store.ID(gameID)).(*Game)   // panics \"game #7 not found\"\n    ...\n}\n\nfunc Render(path string) string {\n    for _, e := range games.PageReverse(1, 20) {   // newest first, one page\n        g := e.Value.(*Game)\n        ... e.ID ...\n    }\n}\n```\n\n## API\n\n| | |\n|---|---|\n| `New()` | a new empty store; the zero `Store` works too |\n| `Named(\"game\")` | the same, with a noun for the `MustGet` panic |\n| `Add(v) ID` | store under the next ID |\n| `Set(id, v) bool` | write at an explicit ID, reports a replacement |\n| `Get(id) (any, bool)` | value and presence, so a stored `nil` is not \"absent\" |\n| `MustGet(id) any` | or panic `store: no entry #7`, or `game #7 not found` when named |\n| `Has(id)`, `Remove(id)`, `Len()`, `LastID()` | |\n| `Each(fn)`, `EachReverse(fn)` | every entry, ascending / descending |\n| `EachUntil(fn) bool`, `EachReverseUntil(fn) bool` | stop when `fn` returns true |\n| `Page(page, size) []Entry` | 1-based, ascending |\n| `PageReverse(page, size) []Entry` | 1-based, newest first |\n| `Pages(size) int` | for the pager footer |\n| `ParseID(s) (ID, bool)`, `ID.String()`, `ID.Key()` | the path round trip |\n\n### IDs stay plain integers\n\nAn `ID` is a `uint64` that renders as a decimal number, so a realm ported to\nthis package keeps showing `#7` exactly as it did. Only the avl key changes, and\nthe key was never user-visible.\n\nIDs start at **1**, so the zero `ID` is usable as \"absent\" and `ParseID(\"0\")`\nrejects. Removing an entry does **not** free its ID: IDs are a history, not a\ndense index, and reusing one would silently repoint an old link at a new object.\n\n### Two iteration shapes, on purpose\n\n`Each` takes no stop signal. It is the common case, and a callback whose `bool`\nmeans \"stop\" reads identically to one whose `bool` means \"continue\", so the\nwrong guess is invisible. When iteration has to end early the name says so:\n`EachUntil`, where **true means stop**, matching `avl.IterCbFn` exactly. A\ncallback moved between this package and a raw tree keeps its meaning.\n\n### Paging is 1-based and forgiving\n\nPage numbers are shown to a reader (\"page 1 of 4\"), and an off-by-one between\nthe URL and the label is the bug this avoids. A page past the end, or a page or\nsize below 1, returns an empty slice rather than panicking, because the page\nnumber usually arrives from a `Render` path and that is user input. Only the\nrequested window is walked, not the whole tree.\n\n## Design rule\n\n**The safe, conventional thing must be the shortest thing to type.** `Add` is\nshorter than `nextID++` plus a padding function, and it cannot be got wrong.\nThat is the only mechanism that stops this helper from being written a\nseventeenth time.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/kit/store/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/kit/store/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/kit/store/v0\"\ngno = \"0.9\"\n"},{"name":"store.gno","body":"// Package store is the auto-id ordered collection every r/moul realm was\n// building by hand: an avl.Tree, an int counter, and a private function that\n// zero-pads the counter into a key so the tree iterates in the order a human\n// expects.\n//\n// Sixteen realm files in this repo carry that third piece. They do not agree:\n//\n//\tpadID  width 6   for len(s) \u003c 6 { s = \"0\" + s }            asciiart\n//\tpad    width 12  for len(s) \u003c 12 { s = \"0\" + s }           tictactoe\n//\tkey    width 12  the same loop, a different name           blog, crowdfund,\n//\t                                                           englishauction,\n//\t                                                           erc721, splitter\n//\tidKey  width 12  the same loop, a third name               connect4\n//\tidKey  width 12  strings.Repeat, guarded by len(s) \u003e= 12   governor, todos\n//\tidKey  width 12  strings.Repeat, UNGUARDED                 timecapsule\n//\tseqKey width 16  strings.Repeat, guarded                   guestbook\n//\n// Every one of them is a silent ceiling. Past the width, the padding stops and\n// the tree starts ordering \"1000000000000\" before \"999999999999\", so the list\n// a realm renders is simply wrong from that entry on. The unguarded variant is\n// worse: strings.Repeat panics on a negative count, so the realm stops\n// accepting writes rather than merely mis-sorting them. asciiart's width of 6\n// puts that ceiling at one million entries.\n//\n// The ceiling exists because the key is a decimal string, and decimal strings\n// do not sort numerically. This package removes the ceiling by removing the\n// decision: keys are the big-endian bytes of a [gno.land/p/nt/seqid/v0] ID, a\n// fixed 8 bytes whose lexicographic order IS numeric order, for every value a\n// uint64 can hold. There is no width to pick and no width to outgrow.\n//\n// # Usage\n//\n//\tvar games store.Store             // the zero value is an empty store\n//\n//\tfunc NewGame(cur realm) int64 {\n//\t\tid := games.Add(\u0026Game{...})\n//\t\treturn int64(id)\n//\t}\n//\n//\tfunc Move(cur realm, gameID int64, cell int) {\n//\t\tg := games.MustGet(store.ID(gameID)).(*Game)\n//\t\t...\n//\t}\n//\n//\tfunc Render(path string) string {\n//\t\tfor _, e := range games.PageReverse(1, 20) {   // newest first\n//\t\t\tg := e.Value.(*Game)\n//\t\t\t... e.ID ...\n//\t\t}\n//\t}\n//\n// # Identifiers\n//\n// An ID is a uint64 that renders as a plain decimal number, so a realm ported\n// to this package keeps showing \"#7\" exactly as it did before. Only the avl\n// key changes, and the key was never user-visible.\n//\n// IDs start at 1. The zero ID is never assigned, so it is usable as \"absent\",\n// and [Store.Get] on it always misses.\n//\n// Removing an entry does not free its ID. IDs are a history, not a dense\n// index: reusing one would silently repoint an old link at a new object.\npackage store\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\n// ID identifies one entry. It is a plain integer to the outside world and an\n// ordered fixed-width key inside the tree.\ntype ID uint64\n\n// String renders the ID in decimal, which is how realms show it and how it\n// arrives back in a Render path.\nfunc (id ID) String() string { return strconv.FormatUint(uint64(id), 10) }\n\n// Key is the avl key for the ID: the 8 big-endian bytes of the underlying\n// seqid, whose byte order is its numeric order.\n//\n// Exposed because a realm that keeps a secondary index keyed by the same ID\n// needs the identical key, and because it is the one place the encoding is\n// decided.\nfunc (id ID) Key() string { return seqid.ID(id).Binary() }\n\n// ParseID reads an ID from its decimal form, the shape it has in a Render\n// path or a function argument.\n//\n// It returns false for anything that is not a plain unsigned decimal, which\n// includes \"\", \"-1\", \"1.0\", a value past uint64, and the zero ID (never\n// assigned, so accepting it would only produce a lookup that cannot hit).\n// Leading zeros are accepted: \"007\" is the ID 7.\nfunc ParseID(s string) (ID, bool) {\n\tn, err := strconv.ParseUint(s, 10, 64)\n\tif err != nil || n == 0 {\n\t\treturn 0, false\n\t}\n\treturn ID(n), true\n}\n\n// Entry is one ID/value pair, as returned by the paging methods.\ntype Entry struct {\n\tID    ID\n\tValue any\n}\n\n// Store is an ordered collection of values under auto-assigned IDs.\n//\n// The zero Store is an empty store and is ready to use, so a realm can declare\n// one as a package-level var without an initializer. [New] exists for the\n// pointer form.\ntype Store struct {\n\ttree  avl.Tree\n\tlast  seqid.ID\n\tlabel string\n}\n\n// New returns an empty store.\nfunc New() *Store { return \u0026Store{} }\n\n// Named is [New] with a noun for what the store holds, used in the panic\n// [Store.MustGet] raises: store.Named(\"game\") makes it \"game #7 not found\"\n// instead of \"store: no entry #7\".\n//\n// It exists so porting a realm to this package does not have to trade its own\n// error wording for one shared implementation. The realms being replaced here\n// panic \"game not found\", \"proposal not found\", \"capsule not found\"; the label\n// keeps that and adds the id they all omitted.\nfunc Named(label string) *Store { return \u0026Store{label: label} }\n\n// Add stores v under the next ID and returns it.\n//\n// It panics if the ID space is exhausted, which is [seqid.ID.Next]'s behaviour\n// and requires 2^64 insertions to reach.\nfunc (s *Store) Add(v any) ID {\n\tid := ID(s.last.Next())\n\ts.tree.Set(id.Key(), v)\n\treturn id\n}\n\n// Set writes v at an existing or explicit ID, and reports whether it replaced\n// a value.\n//\n// Use it to update an entry in place. It does not move the ID counter, so\n// setting an ID above [Store.LastID] leaves a gap that [Store.Add] will later\n// walk into and overwrite. Prefer [Store.Add] to create.\nfunc (s *Store) Set(id ID, v any) (replaced bool) {\n\treturn s.tree.Set(id.Key(), v)\n}\n\n// Get returns the value at id, and whether it was there.\n//\n// Unlike avl.Tree.Get, a nil value stored at a live ID is distinguishable from\n// an absent one, because the second result comes from Has rather than from the\n// value being nil.\nfunc (s *Store) Get(id ID) (any, bool) {\n\tk := id.Key()\n\tif !s.tree.Has(k) {\n\t\treturn nil, false\n\t}\n\treturn s.tree.Get(k), true\n}\n\n// MustGet returns the value at id, or panics.\n//\n// This is the \"get or panic\" the realms wrote eighteen times, with one\n// implementation instead of eighteen. The panic names the id, which none of\n// them did: \"store: no entry #7\", or \"game #7 not found\" for a store built\n// with [Named].\nfunc (s *Store) MustGet(id ID) any {\n\tv, ok := s.Get(id)\n\tif !ok {\n\t\tpanic(s.missing(id))\n\t}\n\treturn v\n}\n\nfunc (s *Store) missing(id ID) string {\n\tif s.label == \"\" {\n\t\treturn \"store: no entry #\" + id.String()\n\t}\n\treturn s.label + \" #\" + id.String() + \" not found\"\n}\n\n// Has reports whether id is present.\nfunc (s *Store) Has(id ID) bool { return s.tree.Has(id.Key()) }\n\n// Remove deletes the entry at id and returns the value it held.\n//\n// The ID is not recycled: see the package doc.\nfunc (s *Store) Remove(id ID) (any, bool) { return s.tree.Remove(id.Key()) }\n\n// Len reports how many entries are present. Removals lower it; [Store.LastID]\n// does not move.\nfunc (s *Store) Len() int { return s.tree.Size() }\n\n// LastID is the highest ID ever assigned, or 0 when nothing has been added.\n// It is the count of insertions, not of live entries.\nfunc (s *Store) LastID() ID { return ID(s.last) }\n\n// Each visits every entry in ascending ID order.\n//\n// It takes no stop signal on purpose: this is the common case, and a callback\n// whose bool means \"stop\" reads identically to one whose bool means\n// \"continue\". When iteration has to end early, say so in the name and use\n// [Store.EachUntil].\nfunc (s *Store) Each(fn func(id ID, v any)) {\n\ts.tree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tfn(keyID(k), v)\n\t\treturn false\n\t})\n}\n\n// EachReverse is [Store.Each] in descending ID order, which is what a\n// newest-first list wants.\nfunc (s *Store) EachReverse(fn func(id ID, v any)) {\n\ts.tree.ReverseIterate(\"\", \"\", func(k string, v any) bool {\n\t\tfn(keyID(k), v)\n\t\treturn false\n\t})\n}\n\n// EachUntil visits entries in ascending ID order and stops when fn returns\n// true. It reports whether it stopped early.\n//\n// True means stop, matching avl.IterCbFn exactly, so a callback moved between\n// this package and a raw tree keeps its meaning.\nfunc (s *Store) EachUntil(fn func(id ID, v any) bool) bool {\n\treturn s.tree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\treturn fn(keyID(k), v)\n\t})\n}\n\n// EachReverseUntil is [Store.EachUntil] in descending ID order.\nfunc (s *Store) EachReverseUntil(fn func(id ID, v any) bool) bool {\n\treturn s.tree.ReverseIterate(\"\", \"\", func(k string, v any) bool {\n\t\treturn fn(keyID(k), v)\n\t})\n}\n\n// Page returns page number page of size entries, in ascending ID order.\n//\n// Pages are 1-based, because they are shown to a reader (\"page 1 of 4\") and an\n// off-by-one between the URL and the label is the bug this saves. A page past\n// the end, or a page or size below 1, returns an empty slice rather than\n// panicking: the page number usually comes from a Render path, which is user\n// input.\n//\n// It walks only the requested window, not the whole tree.\nfunc (s *Store) Page(page, size int) []Entry {\n\treturn s.slice(page, size, false)\n}\n\n// PageReverse is [Store.Page] in descending ID order: page 1 holds the newest\n// entries.\nfunc (s *Store) PageReverse(page, size int) []Entry {\n\treturn s.slice(page, size, true)\n}\n\nfunc (s *Store) slice(page, size int, reverse bool) []Entry {\n\tif page \u003c 1 || size \u003c 1 {\n\t\treturn nil\n\t}\n\toffset := (page - 1) * size\n\tout := make([]Entry, 0, size)\n\tcb := func(k string, v any) bool {\n\t\tout = append(out, Entry{ID: keyID(k), Value: v})\n\t\treturn false\n\t}\n\tif reverse {\n\t\ts.tree.ReverseIterateByOffset(offset, size, cb)\n\t} else {\n\t\ts.tree.IterateByOffset(offset, size, cb)\n\t}\n\treturn out\n}\n\n// Pages reports how many pages of the given size the store holds, which is\n// what a pager footer needs. A size below 1 gives 0.\nfunc (s *Store) Pages(size int) int {\n\tif size \u003c 1 {\n\t\treturn 0\n\t}\n\tn := s.Len()\n\treturn (n + size - 1) / size\n}\n\n// keyID decodes an avl key back to its ID. The keys in this tree are always\n// written by ID.Key, so a short or malformed key means the tree was written by\n// something other than this package.\nfunc keyID(k string) ID {\n\tif len(k) != 8 {\n\t\tpanic(\"store: foreign key in tree\")\n\t}\n\tvar n uint64\n\tfor i := 0; i \u003c 8; i++ {\n\t\tn = n\u003c\u003c8 | uint64(k[i])\n\t}\n\treturn ID(n)\n}\n"},{"name":"store_test.gno","body":"package store\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestZeroValueIsUsable(t *testing.T) {\n\tvar s Store\n\tuassert.Equal(t, 0, s.Len())\n\tuassert.Equal(t, uint64(0), uint64(s.LastID()))\n\tuassert.Equal(t, uint64(1), uint64(s.Add(\"first\")))\n\tuassert.Equal(t, 1, s.Len())\n}\n\nfunc TestAddAssignsSequentialIDsFromOne(t *testing.T) {\n\ts := New()\n\tfor want := uint64(1); want \u003c= 5; want++ {\n\t\tuassert.Equal(t, want, uint64(s.Add(\"v\"+strconv.FormatUint(want, 10))))\n\t}\n\tuassert.Equal(t, 5, s.Len())\n\tuassert.Equal(t, uint64(5), uint64(s.LastID()))\n}\n\nfunc TestGetHasMustGet(t *testing.T) {\n\ts := New()\n\tid := s.Add(\"hello\")\n\n\tgot, ok := s.Get(id)\n\tuassert.True(t, ok, \"live id is found\")\n\tuassert.Equal(t, \"hello\", got.(string))\n\tuassert.True(t, s.Has(id), \"Has agrees with Get\")\n\tuassert.Equal(t, \"hello\", s.MustGet(id).(string))\n\n\t_, ok = s.Get(ID(2))\n\tuassert.False(t, ok, \"unassigned id misses\")\n\t_, ok = s.Get(ID(0))\n\tuassert.False(t, ok, \"the zero id always misses\")\n\tuassert.False(t, s.Has(ID(0)), \"the zero id is never present\")\n}\n\n// A nil value at a live id must still read as present. avl.Tree.Get alone\n// cannot tell those apart, which is why Get consults Has.\nfunc TestNilValueIsDistinguishableFromAbsent(t *testing.T) {\n\ts := New()\n\tid := s.Add(nil)\n\n\tv, ok := s.Get(id)\n\tuassert.True(t, ok, \"a stored nil is present\")\n\tuassert.Nil(t, v, \"and reads back as nil\")\n\tuassert.Equal(t, 1, s.Len())\n}\n\nfunc TestMustGetPanicsNamingTheEntry(cur realm, t *testing.T) {\n\ts := New()\n\ts.Add(\"only\")\n\tuassert.PanicsWithMessage(t, cur, \"store: no entry #7\", func() { s.MustGet(ID(7)) })\n\tuassert.NotPanics(t, cur, func() { s.MustGet(ID(1)) })\n}\n\n// A labelled store keeps the realm's own wording, so porting one does not\n// trade \"game not found\" for a generic message.\nfunc TestNamedStoreUsesItsLabelInThePanic(cur realm, t *testing.T) {\n\ts := Named(\"game\")\n\ts.Add(\"only\")\n\tuassert.PanicsWithMessage(t, cur, \"game #7 not found\", func() { s.MustGet(ID(7)) })\n\tuassert.NotPanics(t, cur, func() { s.MustGet(ID(1)) })\n\n\t// The label changes nothing else.\n\tuassert.Equal(t, uint64(1), uint64(s.LastID()))\n\tuassert.Equal(t, 1, s.Len())\n}\n\nfunc TestSetReplacesInPlace(t *testing.T) {\n\ts := New()\n\tid := s.Add(\"before\")\n\n\tuassert.True(t, s.Set(id, \"after\"), \"Set reports the replacement\")\n\tuassert.Equal(t, \"after\", s.MustGet(id).(string))\n\tuassert.Equal(t, 1, s.Len(), \"replacing does not grow the store\")\n\tuassert.Equal(t, uint64(1), uint64(s.LastID()), \"replacing does not move the counter\")\n}\n\nfunc TestRemoveDoesNotRecycleIDs(t *testing.T) {\n\ts := New()\n\ta := s.Add(\"a\")\n\ts.Add(\"b\")\n\n\tv, ok := s.Remove(a)\n\tuassert.True(t, ok, \"removing a live id succeeds\")\n\tuassert.Equal(t, \"a\", v.(string))\n\tuassert.Equal(t, 1, s.Len())\n\n\t_, ok = s.Remove(a)\n\tuassert.False(t, ok, \"removing twice is a miss, not a panic\")\n\n\t// The next Add continues the history rather than refilling the hole.\n\tuassert.Equal(t, uint64(3), uint64(s.Add(\"c\")))\n}\n\nfunc TestParseID(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant ID\n\t\tok   bool\n\t}{\n\t\t{\"plain\", \"7\", 7, true},\n\t\t{\"leading zeros\", \"007\", 7, true},\n\t\t{\"max uint64\", \"18446744073709551615\", ID(18446744073709551615), true},\n\t\t{\"empty\", \"\", 0, false},\n\t\t{\"zero is never assigned\", \"0\", 0, false},\n\t\t{\"negative\", \"-1\", 0, false},\n\t\t{\"signed positive\", \"+1\", 0, false},\n\t\t{\"decimal point\", \"1.0\", 0, false},\n\t\t{\"not a number\", \"abc\", 0, false},\n\t\t{\"trailing space\", \"7 \", 0, false},\n\t\t{\"overflows uint64\", \"18446744073709551616\", 0, false},\n\t}\n\tfor _, tc := range cases {\n\t\tgot, ok := ParseID(tc.in)\n\t\tuassert.Equal(t, tc.ok, ok, tc.name+\": ok\")\n\t\tuassert.Equal(t, uint64(tc.want), uint64(got), tc.name+\": value\")\n\t}\n}\n\n// The round trip a realm actually performs: render an id into a path, take it\n// back off the path, look the entry up.\nfunc TestIDRoundTripsThroughAPath(t *testing.T) {\n\ts := New()\n\tid := s.Add(\"entry\")\n\tfor i := 0; i \u003c 20; i++ {\n\t\tid = s.Add(\"entry\")\n\t}\n\n\tparsed, ok := ParseID(id.String())\n\tuassert.True(t, ok, \"the rendered id parses back\")\n\tuassert.Equal(t, uint64(id), uint64(parsed))\n\tuassert.Equal(t, \"entry\", s.MustGet(parsed).(string))\n}\n\nfunc TestKeyIsFixedWidthAndOrdered(t *testing.T) {\n\tuassert.Equal(t, 8, len(ID(1).Key()), \"every key is 8 bytes\")\n\tuassert.Equal(t, 8, len(ID(18446744073709551615).Key()), \"including the largest\")\n\n\t// Byte order is numeric order, which is the whole point.\n\tprev := ID(0).Key()\n\tfor _, n := range []uint64{1, 9, 10, 99, 100, 999999, 1000000, 999999999999, 1000000000000, 18446744073709551615} {\n\t\tk := ID(n).Key()\n\t\tuassert.True(t, prev \u003c k, \"keys ascend at \"+strconv.FormatUint(n, 10))\n\t\tprev = k\n\t}\n}\n\n// padWidth is the shape sixteen realm files carry, reproduced so the defect it\n// causes is asserted rather than described. The widths in the tree are 6\n// (asciiart), 12 (most) and 16 (guestbook).\nfunc padWidth(n uint64, width int) string {\n\ts := strconv.FormatUint(n, 10)\n\tif len(s) \u003e= width {\n\t\treturn s\n\t}\n\treturn strings.Repeat(\"0\", width-len(s)) + s\n}\n\n// The ceiling: one entry past the chosen width, decimal keys stop sorting\n// numerically. store's keys do not have a width to outgrow.\nfunc TestOrderSurvivesThePaddingCeiling(t *testing.T) {\n\tcases := []struct {\n\t\tname   string\n\t\twidth  int\n\t\tlo, hi uint64\n\t}{\n\t\t{\"asciiart, width 6\", 6, 999999, 1000000},\n\t\t{\"the width 12 majority\", 12, 999999999999, 1000000000000},\n\t\t{\"guestbook, width 16\", 16, 9999999999999999, 10000000000000000},\n\t}\n\tfor _, tc := range cases {\n\t\t// The hand-rolled key inverts: the larger id sorts first.\n\t\tuassert.True(t, padWidth(tc.hi, tc.width) \u003c padWidth(tc.lo, tc.width),\n\t\t\ttc.name+\": the padded key is expected to invert here\")\n\n\t\t// The store key does not.\n\t\tuassert.True(t, ID(tc.lo).Key() \u003c ID(tc.hi).Key(), tc.name+\": store keys stay ordered\")\n\n\t\t// And iteration follows.\n\t\ts := New()\n\t\ts.Set(ID(tc.hi), \"hi\")\n\t\ts.Set(ID(tc.lo), \"lo\")\n\t\tvar order []string\n\t\ts.Each(func(id ID, v any) { order = append(order, v.(string)) })\n\t\tuassert.Equal(t, \"lo,hi\", strings.Join(order, \",\"), tc.name+\": iteration is numeric\")\n\t}\n}\n\n// timecapsule's variant calls strings.Repeat without the len guard, so past\n// the width it panics instead of mis-sorting: the realm stops accepting\n// writes. Asserted here because it is the reason this is a correctness fix and\n// not a tidy-up.\nfunc TestUnguardedPadPanicsPastItsWidth(cur realm, t *testing.T) {\n\tunguarded := func(n uint64) string {\n\t\treturn strings.Repeat(\"0\", 12-len(strconv.FormatUint(n, 10))) + strconv.FormatUint(n, 10)\n\t}\n\tuassert.NotPanics(t, cur, func() { unguarded(999999999999) })\n\tuassert.PanicsContains(t, cur, \"negative\", func() { unguarded(1000000000000) })\n\tuassert.NotPanics(t, cur, func() { ID(1000000000000).Key() })\n}\n\nfunc TestEachVisitsEverythingInOrder(t *testing.T) {\n\ts := New()\n\tfor i := 1; i \u003c= 5; i++ {\n\t\ts.Add(strconv.Itoa(i))\n\t}\n\n\tvar fwd, rev []string\n\ts.Each(func(id ID, v any) { fwd = append(fwd, id.String()+\"=\"+v.(string)) })\n\ts.EachReverse(func(id ID, v any) { rev = append(rev, id.String()+\"=\"+v.(string)) })\n\n\tuassert.Equal(t, \"1=1,2=2,3=3,4=4,5=5\", strings.Join(fwd, \",\"))\n\tuassert.Equal(t, \"5=5,4=4,3=3,2=2,1=1\", strings.Join(rev, \",\"))\n}\n\nfunc TestEachOnAnEmptyStoreIsANoOp(t *testing.T) {\n\ts := New()\n\tcalls := 0\n\ts.Each(func(id ID, v any) { calls++ })\n\ts.EachReverse(func(id ID, v any) { calls++ })\n\tuassert.Equal(t, 0, calls)\n\tuassert.Equal(t, 0, len(s.Page(1, 10)))\n\tuassert.Equal(t, 0, s.Pages(10))\n}\n\n// True means stop, the same as avl.IterCbFn, so a callback keeps its meaning\n// when it moves between this package and a raw tree.\nfunc TestEachUntilStopsOnTrue(t *testing.T) {\n\ts := New()\n\tfor i := 1; i \u003c= 5; i++ {\n\t\ts.Add(strconv.Itoa(i))\n\t}\n\n\tvar seen []string\n\tstopped := s.EachUntil(func(id ID, v any) bool {\n\t\tseen = append(seen, v.(string))\n\t\treturn id == 3\n\t})\n\tuassert.True(t, stopped, \"it reports stopping early\")\n\tuassert.Equal(t, \"1,2,3\", strings.Join(seen, \",\"))\n\n\tseen = nil\n\tstopped = s.EachReverseUntil(func(id ID, v any) bool {\n\t\tseen = append(seen, v.(string))\n\t\treturn id == 4\n\t})\n\tuassert.True(t, stopped)\n\tuassert.Equal(t, \"5,4\", strings.Join(seen, \",\"))\n\n\tstopped = s.EachUntil(func(id ID, v any) bool { return false })\n\tuassert.False(t, stopped, \"running to the end is not stopping early\")\n}\n\nfunc TestPageIsOneBased(t *testing.T) {\n\ts := New()\n\tfor i := 1; i \u003c= 7; i++ {\n\t\ts.Add(strconv.Itoa(i))\n\t}\n\n\tcases := []struct {\n\t\tname       string\n\t\tpage, size int\n\t\twant       string\n\t}{\n\t\t{\"first page\", 1, 3, \"1,2,3\"},\n\t\t{\"second page\", 2, 3, \"4,5,6\"},\n\t\t{\"short last page\", 3, 3, \"7\"},\n\t\t{\"past the end\", 4, 3, \"\"},\n\t\t{\"far past the end\", 99, 3, \"\"},\n\t\t{\"whole store in one page\", 1, 100, \"1,2,3,4,5,6,7\"},\n\t\t{\"page 0 is not page 1\", 0, 3, \"\"},\n\t\t{\"negative page\", -1, 3, \"\"},\n\t\t{\"size 0\", 1, 0, \"\"},\n\t\t{\"negative size\", 1, -3, \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tvar got []string\n\t\tfor _, e := range s.Page(tc.page, tc.size) {\n\t\t\tgot = append(got, e.Value.(string))\n\t\t}\n\t\tuassert.Equal(t, tc.want, strings.Join(got, \",\"), tc.name)\n\t}\n}\n\nfunc TestPageReverseStartsWithTheNewest(t *testing.T) {\n\ts := New()\n\tfor i := 1; i \u003c= 7; i++ {\n\t\ts.Add(strconv.Itoa(i))\n\t}\n\n\tcases := []struct {\n\t\tname       string\n\t\tpage, size int\n\t\twant       string\n\t}{\n\t\t{\"newest first\", 1, 3, \"7,6,5\"},\n\t\t{\"second page\", 2, 3, \"4,3,2\"},\n\t\t{\"short last page\", 3, 3, \"1\"},\n\t\t{\"past the end\", 4, 3, \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tvar got []string\n\t\tfor _, e := range s.PageReverse(tc.page, tc.size) {\n\t\t\tgot = append(got, e.Value.(string))\n\t\t}\n\t\tuassert.Equal(t, tc.want, strings.Join(got, \",\"), tc.name)\n\t}\n}\n\nfunc TestPageCarriesTheID(t *testing.T) {\n\ts := New()\n\ts.Add(\"a\")\n\ts.Add(\"b\")\n\n\tp := s.Page(1, 10)\n\tuassert.Equal(t, 2, len(p))\n\tuassert.Equal(t, uint64(1), uint64(p[0].ID))\n\tuassert.Equal(t, uint64(2), uint64(p[1].ID))\n\n\tr := s.PageReverse(1, 10)\n\tuassert.Equal(t, uint64(2), uint64(r[0].ID))\n\tuassert.Equal(t, uint64(1), uint64(r[1].ID))\n}\n\nfunc TestPages(t *testing.T) {\n\ts := New()\n\tuassert.Equal(t, 0, s.Pages(10), \"an empty store has no pages\")\n\n\tfor i := 1; i \u003c= 10; i++ {\n\t\ts.Add(\"v\")\n\t}\n\tuassert.Equal(t, 1, s.Pages(10), \"an exact fit is one page\")\n\tuassert.Equal(t, 2, s.Pages(9), \"a remainder adds a page\")\n\tuassert.Equal(t, 10, s.Pages(1))\n\tuassert.Equal(t, 0, s.Pages(0), \"a size below 1 has no pages\")\n\tuassert.Equal(t, 0, s.Pages(-1))\n}\n\n// Paging and iteration must stay consistent after entries are removed from the\n// middle, which is where a dense-index assumption would break.\nfunc TestPagingAfterRemovals(t *testing.T) {\n\ts := New()\n\tfor i := 1; i \u003c= 6; i++ {\n\t\ts.Add(strconv.Itoa(i))\n\t}\n\ts.Remove(ID(2))\n\ts.Remove(ID(5))\n\n\tuassert.Equal(t, 4, s.Len())\n\tuassert.Equal(t, uint64(6), uint64(s.LastID()), \"the counter does not rewind\")\n\n\tvar got []string\n\ts.Each(func(id ID, v any) { got = append(got, id.String()) })\n\tuassert.Equal(t, \"1,3,4,6\", strings.Join(got, \",\"))\n\n\tgot = nil\n\tfor _, e := range s.Page(2, 2) {\n\t\tgot = append(got, e.ID.String())\n\t}\n\tuassert.Equal(t, \"4,6\", strings.Join(got, \",\"), \"page 2 of the survivors\")\n\tuassert.Equal(t, 2, s.Pages(2))\n}\n"}]},"send":"","max_deposit":"11000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","package":{"name":"ui","path":"gno.land/p/moul/kit/ui/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/kit/ui/v0`\n\nThe shared display vocabulary for `r/moul` realms: the small set of rendering\ndecisions every realm was making on its own, made once.\n\nFirst package of the `p/moul/kit/*` layer\n([moul/gno-contracts#151](https://github.com/moul/gno-contracts/issues/151)).\n`kit` composes the existing packages, it does not replace them.\n\n## Why it exists\n\nMeasured across 118 realm directories in this repo:\n\n| | |\n|---|---|\n| Realm dirs importing **zero** `p/moul/*` | 79 of 118 |\n| Realm lines inside `Render` / `render*` | 5,909 of 23,276 (25.4%) |\n| Lines in duplicated private helpers | 857 across 126 functions |\n| Copies of `shortAddr` | 11, with **four different truncation rules** |\n| Copies of `escapeInline` | 8, all a byte-identical seven-pair replacer |\n\nThe `shortAddr` number is the one that matters: the same account rendered\ndifferently depending on which realm you opened. That is not duplication, it is\nfour answers to one question.\n\n## What is here, and what is deliberately not\n\nThis package does **not** re-export markdown primitives. Headings, bold, lists,\ncode blocks and links already have an owner in\n[`p/moul/md`](https://github.com/moul/gno-contracts/tree/main/p/moul/md); import that alongside. What lives here is only\nwhat had no owner and was therefore copy-pasted.\n\n```go\nimport (\n    \"gno.land/p/moul/kit/ui/v0\"\n    \"gno.land/p/moul/md/v0\"\n)\n\nfunc Render(path string) string {\n    t := ui.NewTable(\"#\", \"Player\", \"Score\")\n    for i, p := range players {\n        t.Row(strconv.Itoa(i+1)+ui.Podium(i), ui.Addr(p.addr), ui.Cell(p.label))\n    }\n    return md.H1(\"Leaderboard\") + t.OrEmpty(\"Nobody has played yet.\")\n}\n```\n\n| | |\n|---|---|\n| `Addr(a)` | `` `g1manfre…dlf5` ``, the one address format |\n| `AddrFull(a)` | the full address, in backticks |\n| `AddrText(a)` | shortened, no backticks, for a link title |\n| `AddrOf(s)` | `Addr` for an address already in string form (an avl key) |\n| `Short(s)`, `ShortN(s, head, tail)` | the same rule for any string: a URL, a handle, a commitment hash |\n| `Inline(s)`, `Cell(s)` | escape user text, delegated to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0) |\n| `Excerpt(s, width)` | a preview of user prose: cut to `width` runes, then escape. That order, because escaping first and cutting second strands a backslash |\n| `Action(title, fn, args...)` | a clickable call, instead of prose telling the reader to type a function name |\n| `ActionIn(pkgPath, title, fn, args...)` | the same, against another realm |\n| `NewTable(headers...)`, `.Row(...)`, `.String()`, `.OrEmpty(msg)` | GFM tables |\n| `Empty(msg)` | the italic placeholder where a list would be |\n| `Podium(rank)` | 🥇🥈🥉, or `\"\"` past third |\n| `Join(sep, parts...)` | concatenate, skipping empty sections |\n\n## The escaping contract\n\nTable cells and `Action` titles are **markdown, not plain text**.\n\n- Anything that came from a user goes through `Cell` (inside a table) or\n  `Inline` (anywhere else) before it reaches this package.\n- Output of `Addr`, `AddrFull`, `AddrOf` and `Podium` is already safe and must\n  **not** be escaped again.\n\n`Table` renders the GFM table itself rather than delegating to\n[`p/moul/mdtable`](https://github.com/moul/gno-contracts/tree/main/p/moul/mdtable), which unconditionally rewrites `|` to\n`\u0026#124;` in every cell. Stacked on `Cell`, which already emits the GFM escape\n`\\|`, that double-escapes into a stray backslash (`a\\\u0026#124;b`, found while\nporting `guestbook`). One escaping stage is the only way to get this right, and\nit has to be the stage that knows whether the text is user input.\n\n`Action` also escapes its title, which\n[`p/moul/helplink`](https://github.com/moul/gno-contracts/tree/main/p/moul/helplink) does not (it carries an `// XXX:\nescape title` where this would go).\n\n## Design rule\n\n**The safe, conventional thing must be the shortest thing to type.** A realm\nauthor reaching for the obvious call has to land on the correct behaviour;\nthat is the only mechanism that stops these helpers from being rewritten a\ntwelfth time.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/kit/ui/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/kit/ui/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/kit/ui/v0\"\ngno = \"0.9\"\n"},{"name":"ui.gno","body":"// Package ui is the shared display vocabulary for r/moul realms: the small set\n// of rendering decisions that every realm was making on its own, made once.\n//\n// It deliberately does NOT re-export markdown primitives. Headings, bold,\n// lists, code blocks and links already have an owner in\n// [p/moul/md](/p/moul/md/v0); import that alongside this package. What lives\n// here is only what had no owner and was therefore copy-pasted:\n//\n//   - Addr: one address shortening for the whole namespace. Eleven realms had\n//     their own shortAddr with four different truncation rules, so the same\n//     account rendered differently depending on which realm you opened.\n//   - Inline / Cell / Excerpt: markdown escaping, delegated to\n//     [p/nt/markdown/sanitize](/p/nt/markdown/sanitize/v0). Eight realms\n//     hand-rolled a seven-pair strings.NewReplacer that misses most of what\n//     the real escaper handles. Excerpt adds the length cap those previews\n//     also need, in the order that is safe: cut, then escape.\n//   - Action: a clickable call link instead of prose telling the reader to go\n//     type a function name.\n//   - Table, Empty, Podium: the last recurring scraps.\n//\n// # Escaping contract\n//\n// Table cells and Action titles are markdown, not plain text. Anything that\n// came from a user must go through [Cell] (inside a table) or [Inline]\n// (anywhere else) before it is handed to this package. Output of [Addr],\n// [AddrFull] and [Podium] is already safe and must NOT be escaped again.\npackage ui\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/helplink/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Ellipsis is the character placed between the kept head and tail of a\n// shortened string.\nconst Ellipsis = \"…\"\n\n// Head and Tail are how many characters [Addr] and [Short] keep on each side.\n//\n// A gno.land address is 40 characters (\"g1\" plus 38 of bech32 data), so\n// 8+1+4 renders it as g1manfre…dlf5: enough of the head to recognise a\n// familiar account, enough of the tail to tell two similar ones apart.\nconst (\n\tHead = 8\n\tTail = 4\n)\n\n// minShorten is the length below which shortening cannot save a character:\n// Head + len(Ellipsis) + Tail. Strings at or under it are returned unchanged,\n// which is why the rule never produces output longer than its input.\nconst minShorten = Head + 1 + Tail\n\n// Addr renders an address shortened and in backticks: `g1manfre…dlf5`.\n//\n// This is the default way to show an address. It is monospace (an address is\n// opaque data, not prose), and the backticks make it inert markdown, so it is\n// safe in a table cell or anywhere else without further escaping.\nfunc Addr(a address) string {\n\treturn md.InlineCode(AddrText(a))\n}\n\n// AddrFull renders an address in full, in backticks. Use it where the reader\n// needs to copy the value; use [Addr] everywhere else.\nfunc AddrFull(a address) string {\n\treturn md.InlineCode(a.String())\n}\n\n// AddrText renders an address shortened, with no backticks. Use it inside a\n// link title or another construct where backticks would not render.\nfunc AddrText(a address) string {\n\treturn Short(a.String())\n}\n\n// AddrOf is [Addr] for an address already in its string form, which is how\n// realms hold one when it is an avl key or a stored field.\nfunc AddrOf(s string) string {\n\treturn md.InlineCode(Short(s))\n}\n\n// Short shortens any string with the house rule: unchanged when shortening\n// would not save a character, otherwise head + ellipsis + tail.\n//\n// It is the same rule [Addr] uses, exposed for the non-address strings realms\n// also truncate: URLs, handles, commitment hashes.\nfunc Short(s string) string {\n\treturn ShortN(s, Head, Tail)\n}\n\n// ShortN is [Short] with an explicit head and tail. A negative head or tail is\n// treated as zero. When head+tail cannot save a character against the input,\n// the input is returned unchanged.\nfunc ShortN(s string, head, tail int) string {\n\tif head \u003c 0 {\n\t\thead = 0\n\t}\n\tif tail \u003c 0 {\n\t\ttail = 0\n\t}\n\t// Count runes, not bytes: slicing a multi-byte string by byte offset\n\t// splits a rune and emits replacement characters.\n\tr := []rune(s)\n\tif len(r) \u003c= head+1+tail {\n\t\treturn s\n\t}\n\treturn string(r[:head]) + Ellipsis + string(r[len(r)-tail:])\n}\n\n// Inline escapes user-supplied text for an inline markdown context: a\n// sentence, a list item, a link title.\n//\n// It delegates to sanitize.InlineText, which strips bidi and zero-width\n// characters, folds newlines to spaces so the text cannot escape its line,\n// and applies the full CommonMark inline escape. Never concatenate\n// user-supplied text into rendered output without this.\nfunc Inline(s string) string {\n\treturn sanitize.InlineText(s)\n}\n\n// Cell escapes user-supplied text for a markdown table cell: [Inline] plus\n// tab and pipe handling, so the value cannot open a new column.\nfunc Cell(s string) string {\n\treturn sanitize.TableCell(s)\n}\n\n// Excerpt is [Inline] for a string too long to show whole: it keeps the first\n// width runes, appends [Ellipsis], and escapes what it kept.\n//\n// Use it for a preview of user-written prose where only the beginning carries\n// meaning: the first line of a post in an index, a note on a board, a comment\n// in a list. For an identifier whose tail has to stay recognisable, an\n// address, a hash, a URL, use [Short] instead, which keeps both ends.\n//\n// The order is the whole point, and it is what a call site gets wrong.\n// Escaping inserts backslashes, so cutting an ALREADY-escaped string can\n// strand a trailing lone backslash that escapes whatever chrome follows it.\n// Excerpt cuts first, on a rune boundary so a multi-byte character is never\n// split, then escapes. [Ellipsis] stays outside the escaper: it is this\n// package's chrome, not the user's text.\nfunc Excerpt(s string, width int) string {\n\tif width \u003c 0 {\n\t\twidth = 0\n\t}\n\tr := []rune(s)\n\t// The same threshold as [ShortN] with no tail: cutting is only worth doing\n\t// when it saves a character, so a string one rune over is kept whole.\n\tif len(r) \u003c= width+1 {\n\t\treturn Inline(s)\n\t}\n\treturn Inline(string(r[:width])) + Ellipsis\n}\n\n// Action renders a clickable call to a function of the current realm.\n//\n//\tui.Action(\"Play cell 4\", \"Move\", \"gameID\", \"7\", \"cell\", \"4\")\n//\n// Arguments are key/value pairs, as in p/moul/txlink. The title is escaped,\n// which is the one thing helplink.Func does not do.\nfunc Action(title, fn string, args ...string) string {\n\treturn helplink.Func(Inline(title), fn, args...)\n}\n\n// ActionIn is [Action] against another realm, given as the full package path\n// that realm declares on the module line of its gnomod.toml.\n//\n// This doc deliberately contains no example path, not even a placeholder one.\n// gnopm scans doc comments the way it scans imports, so any package path\n// spelled out in a comment becomes a dependency of the package holding it: one\n// that is neither live nor in the workspace BLOCKS publishing this package and\n// everything that imports it, and naming a live one is no better, since it\n// drags an unrelated realm into every publish plan. This comment previously\n// named a path that deversioning had already removed, which blocked the whole\n// ui dependency tree on every chain.\nfunc ActionIn(pkgPath, title, fn string, args ...string) string {\n\treturn helplink.Realm(pkgPath).Func(Inline(title), fn, args...)\n}\n\n// Empty renders the placeholder shown where a list would be: an italic line,\n// newline-terminated, so it drops into a Render body as-is.\n//\n//\tui.Empty(\"No games yet.\")  // \"_No games yet._\\n\"\n//\n// The message is realm chrome, not user input, and is not escaped.\nfunc Empty(msg string) string {\n\treturn md.Italic(msg) + \"\\n\"\n}\n\n// Podium returns the medal for a zero-based rank, or \"\" past third place.\nfunc Podium(rank int) string {\n\tswitch rank {\n\tcase 0:\n\t\treturn \"\\U0001F947\" // 🥇\n\tcase 1:\n\t\treturn \"\\U0001F948\" // 🥈\n\tcase 2:\n\t\treturn \"\\U0001F949\" // 🥉\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\n// Table accumulates markdown table rows and renders them.\n//\n// Cells are markdown, not plain text: pass [Addr] and friends straight\n// through, and wrap anything user-supplied in [Cell] first.\n//\n// Table renders the GFM table itself rather than delegating to\n// [p/moul/mdtable](/p/moul/mdtable/v0), which unconditionally rewrites \"|\" to\n// \"\u0026#124;\" in every cell. Stacked on [Cell], which already emits the GFM\n// escape \"\\|\", that double-escapes into a stray backslash (\"a\\\u0026#124;b\"). One\n// escaping stage is the only way to get this right, and it has to be the one\n// that knows whether the text is user input.\n//\n//\tt := ui.NewTable(\"#\", \"X\", \"O\", \"Status\")\n//\tt.Row(\"7\", ui.Addr(x), ui.Addr(o), \"Turn: X\")\n//\treturn t.String()\ntype Table struct {\n\theaders []string\n\trows    [][]string\n}\n\n// NewTable starts a table with the given header cells.\nfunc NewTable(headers ...string) *Table {\n\treturn \u0026Table{headers: headers}\n}\n\n// Row appends a row and returns the table, so calls can be chained.\n//\n// A row with fewer cells than there are headers is padded with empty cells; a\n// longer row is kept as-is, which renders as a ragged table rather than\n// silently dropping data.\nfunc (t *Table) Row(cells ...string) *Table {\n\tif n := len(t.headers); len(cells) \u003c n {\n\t\tpadded := make([]string, n)\n\t\tcopy(padded, cells)\n\t\tcells = padded\n\t}\n\tt.rows = append(t.rows, cells)\n\treturn t\n}\n\n// Len reports how many rows have been added.\nfunc (t *Table) Len() int { return len(t.rows) }\n\n// String renders the table. A table with no rows renders as \"\", so a caller\n// can fall back to [Empty] with a single check on [Table.Len].\nfunc (t *Table) String() string {\n\tif len(t.rows) == 0 {\n\t\treturn \"\"\n\t}\n\tvar sb strings.Builder\n\tsb.WriteString(\"| \" + strings.Join(t.headers, \" | \") + \" |\\n\")\n\tsb.WriteString(\"|\" + strings.Repeat(\" --- |\", len(t.headers)) + \"\\n\")\n\tfor _, r := range t.rows {\n\t\tsb.WriteString(\"| \" + strings.Join(r, \" | \") + \" |\\n\")\n\t}\n\treturn sb.String()\n}\n\n// OrEmpty renders the table, or the placeholder when it has no rows.\nfunc (t *Table) OrEmpty(msg string) string {\n\tif len(t.rows) == 0 {\n\t\treturn Empty(msg)\n\t}\n\treturn t.String()\n}\n\n// Join concatenates parts, skipping empty ones, with sep between them. It is\n// the small piece of glue every Render needs to assemble optional sections\n// without emitting stray separators.\nfunc Join(sep string, parts ...string) string {\n\tkept := make([]string, 0, len(parts))\n\tfor _, p := range parts {\n\t\tif p != \"\" {\n\t\t\tkept = append(kept, p)\n\t\t}\n\t}\n\treturn strings.Join(kept, sep)\n}\n"},{"name":"ui_test.gno","body":"package ui\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestShortN(t *testing.T) {\n\tcases := []struct {\n\t\tname       string\n\t\tin         string\n\t\thead, tail int\n\t\twant       string\n\t}{\n\t\t{\"empty\", \"\", 8, 4, \"\"},\n\t\t{\"shorter than the rule\", \"abc\", 8, 4, \"abc\"},\n\t\t{\"exactly at the threshold\", \"0123456789abc\", 8, 4, \"0123456789abc\"},\n\t\t{\"one over the threshold\", \"0123456789abcd\", 8, 4, \"01234567…abcd\"},\n\t\t{\"gno address\", \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\", 8, 4, \"g1manfre…dlf5\"},\n\t\t{\"head only\", \"0123456789abcd\", 6, 0, \"012345…\"},\n\t\t{\"tail only\", \"0123456789abcd\", 0, 4, \"…abcd\"},\n\t\t{\"negative clamps to zero\", \"0123456789abcd\", -3, -3, \"…\"},\n\t\t{\"multibyte is not split\", \"éééééééééééééé\", 2, 2, \"éé…éé\"},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := ShortN(tc.in, tc.head, tc.tail)\n\t\tuassert.Equal(t, tc.want, got, tc.name)\n\t}\n}\n\n// ShortN must never make a string longer: that is the property the four\n// divergent shortAddr implementations disagreed on.\nfunc TestShortNeverGrows(t *testing.T) {\n\tinputs := []string{\"\", \"a\", \"abcdefghijkl\", \"0123456789abc\", \"0123456789abcd\", strings.Repeat(\"x\", 100)}\n\tfor _, in := range inputs {\n\t\tgot := Short(in)\n\t\tuassert.True(t, len([]rune(got)) \u003c= len([]rune(in)), \"Short(\"+in+\") grew the input\")\n\t}\n}\n\nfunc TestAddr(t *testing.T) {\n\ta := testutils.TestAddress(\"alice\")\n\tfull := a.String()\n\n\tuassert.Equal(t, \"`\"+full+\"`\", AddrFull(a))\n\tuassert.Equal(t, Short(full), AddrText(a))\n\tuassert.Equal(t, \"`\"+Short(full)+\"`\", Addr(a))\n\n\t// The shortened form keeps the recognisable head and the distinguishing tail.\n\tuassert.True(t, strings.HasPrefix(AddrText(a), full[:Head]), \"head is kept\")\n\tuassert.True(t, strings.HasSuffix(AddrText(a), full[len(full)-Tail:]), \"tail is kept\")\n\tuassert.True(t, strings.Contains(AddrText(a), Ellipsis), \"ellipsis is present\")\n}\n\n// Two different addresses must not collide once shortened, or the display is\n// worse than useless.\nfunc TestAddrOf(t *testing.T) {\n\ta := testutils.TestAddress(\"alice\")\n\tuassert.Equal(t, Addr(a), AddrOf(a.String()))\n}\n\nfunc TestAddrDistinguishes(t *testing.T) {\n\tseen := map[string]bool{}\n\tfor _, name := range []string{\"alice\", \"bob\", \"carol\", \"dave\", \"eve\"} {\n\t\ts := AddrText(testutils.TestAddress(name))\n\t\tuassert.False(t, seen[s], \"shortened address collision on \"+name)\n\t\tseen[s] = true\n\t}\n}\n\nfunc TestInlineEscapes(t *testing.T) {\n\t// The seven pairs the hand-rolled escapeInline copies covered.\n\tfor _, meta := range []string{\"*\", \"_\", \"[\", \"]\", \"`\", \"\\\\\"} {\n\t\tgot := Inline(\"a\" + meta + \"b\")\n\t\tuassert.True(t, strings.Contains(got, \"\\\\\"+meta), \"Inline did not escape \"+meta)\n\t}\n\t// And the one they all missed: a newline lets user text escape its line.\n\tuassert.False(t, strings.Contains(Inline(\"a\\nb\"), \"\\n\"), \"Inline must fold newlines\")\n}\n\nfunc TestCellEscapesPipe(t *testing.T) {\n\tgot := Cell(\"a|b\")\n\tuassert.False(t, strings.Contains(got, \" |\"), \"a bare pipe would open a new column\")\n\tuassert.True(t, strings.Contains(got, \"\\\\|\"), \"pipe must be escaped\")\n}\n\nfunc TestEmpty(t *testing.T) {\n\tuassert.Equal(t, \"*No games yet.*\\n\", Empty(\"No games yet.\"))\n}\n\nfunc TestPodium(t *testing.T) {\n\tcases := []struct {\n\t\trank int\n\t\twant string\n\t}{\n\t\t{0, \"\\U0001F947\"},\n\t\t{1, \"\\U0001F948\"},\n\t\t{2, \"\\U0001F949\"},\n\t\t{3, \"\"},\n\t\t{99, \"\"},\n\t\t{-1, \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, Podium(tc.rank))\n\t}\n}\n\nfunc TestTable(t *testing.T) {\n\ttbl := NewTable(\"#\", \"who\", \"score\")\n\tuassert.Equal(t, 0, tbl.Len())\n\tuassert.Equal(t, \"\", tbl.String())\n\tuassert.Equal(t, \"*nobody yet.*\\n\", tbl.OrEmpty(\"nobody yet.\"))\n\n\ttbl.Row(\"1\", \"`g1abc…wxyz`\", \"42\").Row(\"2\", \"`g1def…uvwx`\", \"7\")\n\tuassert.Equal(t, 2, tbl.Len())\n\n\twant := \"| # | who | score |\\n\" +\n\t\t\"| --- | --- | --- |\\n\" +\n\t\t\"| 1 | `g1abc…wxyz` | 42 |\\n\" +\n\t\t\"| 2 | `g1def…uvwx` | 7 |\\n\"\n\tuassert.Equal(t, want, tbl.String())\n\tuassert.Equal(t, want, tbl.OrEmpty(\"nobody yet.\"))\n}\n\n// A short row is padded rather than producing a table the renderer misreads.\nfunc TestTableShortRowIsPadded(t *testing.T) {\n\ttbl := NewTable(\"a\", \"b\", \"c\")\n\ttbl.Row(\"1\")\n\tuassert.Equal(t, \"| a | b | c |\\n| --- | --- | --- |\\n| 1 |  |  |\\n\", tbl.String())\n}\n\n// A cell escaped with Cell must survive Table untouched: stacking Cell on an\n// escaper that also rewrites \"|\" produced \"a\\\\\u0026#124;b\" in the guestbook port.\nfunc TestTableDoesNotDoubleEscape(t *testing.T) {\n\ttbl := NewTable(\"msg\")\n\ttbl.Row(Cell(\"a|b\"))\n\tgot := tbl.String()\n\tuassert.True(t, strings.Contains(got, `a\\|b`), \"expected the GFM pipe escape, got: \"+got)\n\tuassert.False(t, strings.Contains(got, \"\u0026#124;\"), \"cell was escaped twice: \"+got)\n}\n\nfunc TestJoin(t *testing.T) {\n\tuassert.Equal(t, \"a\\n\\nb\", Join(\"\\n\\n\", \"a\", \"\", \"b\"))\n\tuassert.Equal(t, \"\", Join(\"\\n\\n\", \"\", \"\"))\n\tuassert.Equal(t, \"solo\", Join(\"\\n\\n\", \"solo\"))\n}\n\n// Action must produce a markdown link whose target carries the function name\n// and the key/value arguments, and must escape the title (which helplink\n// itself does not).\nfunc TestAction(t *testing.T) {\n\tgot := Action(\"Play cell 4\", \"Move\", \"gameID\", \"7\", \"cell\", \"4\")\n\tuassert.True(t, strings.HasPrefix(got, \"[Play cell 4](\"), \"expected a markdown link, got: \"+got)\n\tuassert.True(t, strings.Contains(got, \"Move\"), \"link must name the function\")\n\tuassert.True(t, strings.Contains(got, \"gameID=7\"), \"link must carry the args\")\n\tuassert.True(t, strings.Contains(got, \"cell=4\"), \"link must carry the args\")\n\n\tesc := Action(\"a*b\", \"Fn\")\n\tuassert.True(t, strings.HasPrefix(esc, \"[a\\\\*b](\"), \"title must be escaped, got: \"+esc)\n}\n\nfunc TestActionIn(t *testing.T) {\n\tgot := ActionIn(\"gno.land/r/moul/gns/v0\", \"Say hi\", \"Hello\", \"name\", \"moul\")\n\tuassert.True(t, strings.Contains(got, \"/r/moul/gns/v0\"), \"must target the named realm, got: \"+got)\n\tuassert.True(t, strings.Contains(got, \"Hello\"), \"must name the function\")\n}\n\nfunc TestExcerpt(t *testing.T) {\n\tcases := []struct {\n\t\tname  string\n\t\tin    string\n\t\twidth int\n\t\twant  string\n\t}{\n\t\t{\"empty\", \"\", 10, \"\"},\n\t\t{\"shorter than the width\", \"hello\", 10, \"hello\"},\n\t\t{\"one over is kept whole, as ShortN does\", \"0123456789a\", 10, \"0123456789a\"},\n\t\t{\"two over is cut\", \"0123456789ab\", 10, \"0123456789…\"},\n\t\t{\"zero width\", \"hello\", 0, \"…\"},\n\t\t{\"negative width clamps to zero\", \"hello\", -3, \"…\"},\n\t\t// The cut counts runes. A byte slice at 10 would split the 11th 'é'\n\t\t// and put invalid UTF-8 on the page.\n\t\t{\"multibyte is not split\", strings.Repeat(\"é\", 20), 10, strings.Repeat(\"é\", 10) + \"…\"},\n\t\t// The escaping half: what is kept is escaped, the ellipsis is not.\n\t\t{\"escapes what it keeps\", \"[link](url) and more\", 11, \"\\\\[link\\\\]\\\\(url\\\\)…\"},\n\t\t{\"newline cannot escape the line\", \"one\\ntwo\", 10, \"one two\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, Excerpt(tc.in, tc.width), tc.name)\n\t}\n}\n\n// Excerpt must never leave a trailing lone backslash: that is the bug that\n// comes from escaping first and cutting second, and it escapes whatever the\n// caller appends after the excerpt.\nfunc TestExcerptNeverStrandsABackslash(t *testing.T) {\n\t// Each of these ends, at some width, on a character the escaper backslashes.\n\tfor _, in := range []string{\n\t\t\"....................\", \"********************\", \"[[[[[[[[[[[[[[[[[[[[\",\n\t\t\"!!!!!!!!!!!!!!!!!!!!\", \"\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\u003c\", \"--------------------\",\n\t} {\n\t\tfor width := 0; width \u003c= 15; width++ {\n\t\t\tgot := Excerpt(in, width)\n\t\t\tbody := strings.TrimSuffix(got, Ellipsis)\n\t\t\ttrailing := 0\n\t\t\tfor i := len(body) - 1; i \u003e= 0 \u0026\u0026 body[i] == '\\\\'; i-- {\n\t\t\t\ttrailing++\n\t\t\t}\n\t\t\tuassert.Equal(t, 0, trailing%2, \"odd run of trailing backslashes in Excerpt(\"+in+\")\")\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"189043800","gas_fee":"567131ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"AwK/7jRwQWktzGZZRhOvhFOPxBwSOMQz3XMUfTpYeD/9"},"signature":"jWw1mwkBmYuIL5oUaJw1c44BtdpMFfBvFyFAEt6CF+wul3idBfSRlJfa4D7l8amTQ9Ag0Csaf7mFUxARMx6dCg=="}],"memo":""},"metadata":{"timestamp":"1790958937"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"c5OJ0rnW7UsY8AIgEPkPYUy79J2yB0220CmaYNahBkcqRuIz9m85N6ubbTDlefUeehrvactqxWd0C0FWRdCudQ=="}],"memo":""},"metadata":{"timestamp":"1790958957"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"TvTS1OHy7CXRf+NMxBlY6fNOBOcTQJy2zf+QmhgPXYQS4mcp6hFhIyIMlKmTtZZhAzO466yS/KaxVIMJLMnjsA=="}],"memo":""},"metadata":{"timestamp":"1790958999"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ftph2v9cs4facxvjzjxvrt3n9pqzs52w8gsxzz","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"iETTAhQK/eM8MLGQT79Nsqu/d0w4Uioji46e50fyIw0260CcIDonephVjJBSiq15WliT/2YO/8hfo996MklETg=="}],"memo":""},"metadata":{"timestamp":"1790959062"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1857727","gas_fee":"3716ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"y4AEL30dnh5h3BEFUYa64rPb3/0KXlwQ2hL4DK3rU4gITVFGmxwx2uUZ8MYeWsRFgJBcy0RJNdEid2FUGZTV4w=="}],"memo":""},"metadata":{"timestamp":"1790959125"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"MRdRyNiCCZI1SMX5Nu4M2pj8czHkC5ZEVjuZ2sdLgghRbAYGe+/s0HEbUl0+vl1JcMCbLSjTMBa5fyLI4NoVLw=="}],"memo":""},"metadata":{"timestamp":"1790959269"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"eOj4UQlkuYiOzfjn/HQOqaOoJgVKLN20hQZ2TVFv6tp3oGA3K/6h1zgN4f/G8jp+pYzaQXDUGGFHL0IjjyxZtA=="}],"memo":""},"metadata":{"timestamp":"1790959332"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"vVl+gRR+wSf1fhTbfODgV0uRgJnuIgxrij5meNM1hCkwKwR/n8bJnwsGTCMsINjisXtHI+EjMTLOXo9F3FUJ5Q=="}],"memo":""},"metadata":{"timestamp":"1790959394"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"XucK9zsrvIxzoVPniv450yv4B4/UujmxgsOqwQK0egxaEyDw47dWsrDnxBykIPYlLYRrgeukzJe7fLOWh8z7xA=="}],"memo":""},"metadata":{"timestamp":"1790959457"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"hello","path":"gno.land/r/moul/demo/hello/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/hello`\n\nStep 1 of the `r/moul/demo` walkthrough: the smallest realm that can be\ndeployed and called.\n\n```go\nfunc Hello() string { return \"Hello World!\" }\nfunc privateMethod() string { return \"I'm private\" }   // not callable\n```\n\nThe point is the capitalization rule. `Hello` is exported, so it is part of the\nrealm's transaction surface and can be called with `gnokey maketx call`.\n`privateMethod` is not exported, so nothing outside the package can reach it,\non chain or off.\n\n```bash\ngnokey maketx call -pkgpath gno.land/r/moul/demo/hello \\\n  -func Hello -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast moul\n```\n\nNext: [`args`](../args) adds a parameter.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/hello/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/hello/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/hello/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/hello/v0)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"package hello\n\nfunc Hello() string {\n\treturn \"Hello World!\"\n}\n\nfunc privateMethod() string {\n\treturn \"I'm private\"\n}\n"},{"name":"contract_test.gno","body":"package hello\n\nimport \"testing\"\n\nfunc Test(t *testing.T) {\n\tgot := Hello()\n\texpected := \"Hello World!\"\n\tif got != expected {\n\t\tt.Fatalf(\"expected %q, got %q.\", expected, got)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/hello/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"17688800","gas_fee":"53066ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"cSXrRbXjsi+cQafklzQwRz3iJDwLJgFg91DqqQhbRLZh8t+T5D/MfOi+1TIy9FaZmrXK8kgEXGzXDLUfpbU3NQ=="}],"memo":""},"metadata":{"timestamp":"1790959519"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"1ogJBxzC5Wafe+V1ON6GajKMzcBiB8/sXS2VHkjgpn8++hc9pqiZLOMHLMLgNclXkqt5Pgg9xZE87f53jykUkw=="}],"memo":""},"metadata":{"timestamp":"1790959525"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"pupL11YlgsPQ9+I8Rt6FWxki4B2oTRScscK1JNOQoU4jN4zEsfe9fNCQPzMdHZDdYiqNN5Y9GkCBIZwk1i4y6w=="}],"memo":""},"metadata":{"timestamp":"1790959581"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"VcvD6mJWOqw43Jd40ifsm2ED7lpQTrZOYGY2Z5TWa04lkLU5R1gse/y//2x6RvMIVjvz6vrxVdQv+feVRg2k9w=="}],"memo":""},"metadata":{"timestamp":"1790959644"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"EUkt1dIPx4uY+gfzSZufq+3fUGdZfeb1JEuwUwW75+k1RVqWWzZs6x2BXLItkFxuIu/TmvT+MrI0hZskgM/ZJg=="}],"memo":""},"metadata":{"timestamp":"1790959706"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"IAudQQpWyPwoJJcsMLlxxAnsH4uFmhybNWwF2E+TX4Im8gtDYNAWJyrdQzAjCEESCcGzCb1/3DC3xapUZc5H9w=="}],"memo":""},"metadata":{"timestamp":"1790959768"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402581","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+cbbKZV6VhistQ9I/E+4vdSaw2a6MqIZzz+5G85XJjoybnxYWUMpRWQKWvEYLwxAvrSvJSIYVKwr7m+TwU16Aw=="}],"memo":""},"metadata":{"timestamp":"1790959830"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"NrDMpasjhE92jxDA6JZSLcuUic1esK47HEfOBGqLKvBRbFVSA0Gphv4iu3VB6MHlQv7GqHxFIPhkieSE4GwRcA=="}],"memo":""},"metadata":{"timestamp":"1790959892"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"qIODkfKYqZnsh4cGBTS7yV1e+NMcVTrClLVkNNQwipVWvs43VrJ3qLp+6SHP5Am4UzHRFXJeFgQ1VSPBhVAvCQ=="}],"memo":""},"metadata":{"timestamp":"1790959954"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"6jWQrNU+QOu/erjft4Cyc8YPC1Zkns9Xcvc2qhQl0GNUUX7DY+Hh1SP1iPnQkc4dB/ho8VDeEMy9gKnoBccSEQ=="}],"memo":""},"metadata":{"timestamp":"1790960016"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"TmIXUpRNE9EYZWnCGmKx0RNGSS/H4HDuiRbkL0W3eP9VKxBQYehth8Bit/5uPBTGerfCXfM66W59b2U4SSxcXw=="}],"memo":""},"metadata":{"timestamp":"1790960079"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"sPBg9lH76KO89e70ut5H/0BiOe1t1CMPcz1MPFVe86ZlDXwOHrenMxXaJtGYPsbW9g1xkSQfhakwRI1+sMHi3g=="}],"memo":""},"metadata":{"timestamp":"1790960141"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"commit","path":"gno.land/p/moul/agents/commit/v0","files":[{"name":"README.md","body":"# p/moul/agents/commit/v0 — shared commitment helpers\n\nA tiny pure package: the one place the agent demos agree on *how* a\ncommitment is computed. On-chain realms should store commitments (hashes) to\noff-chain material — reports, patches, verdicts — not the material itself.\nWhen several realms do that, they need to compute hashes the same way, or\nthey can't verify each other's commitments.\n\n```go\ncommit.Hash(parts...)          // hex SHA-256, length-prefixed (no boundary collisions)\ncommit.Verdict(vote, salt)     // canonical commit-reveal commitment for a hidden bool\ncommit.Short(hexHash)          // abbreviate for display\n```\n\n`Hash` length-prefixes each part, so `Hash(\"ab\",\"c\") != Hash(\"a\",\"bc\")` — a\nsmall detail that matters the moment a commitment concatenates\nattacker-influenced fields.\n\n`Verdict` is the scheme the [jury](../../../r/moul/agents/jury/v0/) demo uses for\nblind voting: commit `Verdict(vote, salt)` during the commit phase, then\nreveal `(vote, salt)` — anyone can recompute and confirm the vote wasn't\nchanged after the fact.\n\nPure, deterministic, no realm state. Import it; don't reinvent the hashing.\n\n```sh\ngno test .\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"commit.gno","body":"// Package commit provides small, deterministic commitment helpers shared by\n// the agent demos. On-chain realms store *commitments* to off-chain data\n// (reports, patches, verdicts) rather than the data itself; this package is\n// the one place that defines how those commitments are computed, so several\n// realms agree on the scheme.\npackage commit\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n)\n\n// Hash returns the hex-encoded SHA-256 over its parts, length-prefixed so\n// that Hash(\"ab\",\"c\") != Hash(\"a\",\"bc\"). Use it to commit to structured\n// off-chain material without revealing it.\nfunc Hash(parts ...string) string {\n\tvar buf []byte\n\tfor _, p := range parts {\n\t\tbuf = appendUvarint(buf, uint64(len(p)))\n\t\tbuf = append(buf, p...)\n\t}\n\tsum := sha256.Sum256(buf)\n\treturn hex.EncodeToString(sum[:])\n}\n\n// Verdict is the canonical commitment used by commit-reveal voting: a hidden\n// boolean plus a salt. Reveal the same (verdict, salt) later and any observer\n// can recompute this and confirm the vote was not changed after the fact.\nfunc Verdict(verdict bool, salt string) string {\n\tv := \"no\"\n\tif verdict {\n\t\tv = \"yes\"\n\t}\n\treturn Hash(\"verdict\", v, salt)\n}\n\n// Short abbreviates a hex commitment for display.\nfunc Short(h string) string {\n\tif len(h) \u003c= 12 {\n\t\treturn h\n\t}\n\treturn h[:6] + \"…\" + h[len(h)-4:]\n}\n\nfunc appendUvarint(buf []byte, x uint64) []byte {\n\tfor x \u003e= 0x80 {\n\t\tbuf = append(buf, byte(x)|0x80)\n\t\tx \u003e\u003e= 7\n\t}\n\treturn append(buf, byte(x))\n}\n"},{"name":"commit_test.gno","body":"package commit\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestHashDeterministicAndPrefixed(t *testing.T) {\n\tuassert.Equal(t, Hash(\"a\", \"bc\"), Hash(\"a\", \"bc\"))\n\t// length-prefixing prevents boundary collisions\n\tuassert.NotEqual(t, Hash(\"ab\", \"c\"), Hash(\"a\", \"bc\"))\n\tuassert.Equal(t, 64, len(Hash(\"x\"))) // sha256 hex is 64 chars\n}\n\nfunc TestVerdictCommitReveal(t *testing.T) {\n\tc := Verdict(true, \"salt-123\")\n\t// reproducible from the revealed values\n\tuassert.Equal(t, c, Verdict(true, \"salt-123\"))\n\t// flipping the vote or the salt changes the commitment\n\tuassert.NotEqual(t, c, Verdict(false, \"salt-123\"))\n\tuassert.NotEqual(t, c, Verdict(true, \"salt-999\"))\n}\n\nfunc TestShort(t *testing.T) {\n\tuassert.Equal(t, \"abc\", Short(\"abc\"))\n\tuassert.True(t, len(Short(Hash(\"x\"))) \u003c 20)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/agents/commit/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"msg","path":"gno.land/p/moul/agents/msg/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/agents/msg/v0`\n\nThe wire format for messages passed between agents through a relay realm.\n\nIt owns the envelope and nothing else: a realm decides *who may post*, this package decides\n*what a post is*.\n\n## Why an encoded string and not a struct\n\nOn chain you are charged for objects, not for data. Storing a live object instead of its\nencoding costs a flat **~780 B per entry**, in every container, because it is a pointer plus\na struct plus a field. An envelope is read whole and never mutated field by field, which is\nprecisely the case where encoding wins.\n\n## Why length-prefixed\n\nEvery field is written as its decimal length, a colon, then its bytes, so the format is\nbyte-transparent: a body may contain the separator, a newline, or the encoding of another\nmessage, and `Decode` still recovers the original fields. A delimiter-joined format cannot\npromise that for caller-supplied text, and a relay carries nothing else.\n\n`Frame` and `Unframe` expose the same framing for one value, so a realm can carry something\nalongside an encoded message without inventing a second format.\n\n**Frame the extra value in front, never behind.** A value appended after a decimal length\ncannot be found again by scanning backwards for digits, because the message's own body may\nend in digits and the scan cannot tell the two apart. That bug is cheap to write, silent in\nevery test whose fixtures happen to end in a letter, and\n`TestFrameSurvivesABodyEndingInDigits` is the one that catches it.\n\n## The envelope\n\n| field | who sets it |\n|---|---|\n| `Seq`, `Height` | the relay. A caller that could choose its own sequence number could reorder the log it writes to |\n| `From` | the caller: an agent id, as registered in [passport](../../../../r/moul/agents/passport) |\n| `Topic` | the caller: the routing key a reader filters on. Lowercase `a-z0-9.-`, so it is usable as a URL path element |\n| `Kind`, `Ref`, `Body` | the caller, unrestricted |\n\n`Kind`, `Ref` and `Body` are unrestricted on purpose. They are escaped at **render** time,\nnot rewritten at write time: a relay that silently edits what an agent said is worse than\none that renders carefully.\n\nLive demo: [`r/moul/agents/relay`](../../../../r/moul/agents/relay).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/agents/msg/v0\"\ngno = \"0.9\"\n"},{"name":"msg.gno","body":"// Package msg is the wire format for messages passed between agents through a\n// relay realm. It owns the envelope and nothing else: a realm decides who may\n// post, this package decides what a post *is*.\n//\n// A message is stored as one encoded string rather than as a struct, and that\n// is a cost decision rather than a style one. Storing a live object instead of\n// an encoded string costs a flat ~780 B per entry in gno, in every container,\n// because it is a pointer plus a struct plus a field. An envelope is read\n// whole and never mutated field by field, which is exactly the case where\n// encoding wins.\n//\n// The encoding is length-prefixed, so every field is byte-transparent: a body\n// may contain the separator, a newline, or the encoding of another message,\n// and [Decode] still recovers the original fields. A delimiter-joined format\n// cannot promise that for caller-supplied text, and a relay carries nothing\n// but caller-supplied text.\n//\n// A live relay built on this package is at\n// [r/moul/agents/relay](/r/moul/agents/relay/v0).\npackage msg\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Field limits. They bound one entry's storage, which is the only cost that\n// scales with what a caller writes; the per-entry floor dwarfs all of them.\nconst (\n\tMaxFrom  = 64\n\tMaxTopic = 64\n\tMaxKind  = 32\n\tMaxRef   = 256\n\tMaxBody  = 2048\n)\n\n// Msg is one message on a relay.\n//\n// Seq and Height are assigned by the relay, never by the caller: a caller that\n// could choose its own sequence number could reorder the log it is writing to.\ntype Msg struct {\n\tSeq    uint64 // relay-assigned, monotonic, never reused\n\tHeight int64  // block height the relay recorded it at\n\tFrom   string // agent id, as registered in r/moul/agents/passport\n\tTopic  string // routing key a reader filters on\n\tKind   string // what sort of message this is, free-form but short\n\tRef    string // optional pointer to what it is about (a hash, a url, a seq)\n\tBody   string // the message itself\n}\n\n// Encode returns the canonical encoding of m.\n//\n// Every field is written as its decimal length, a colon, then its bytes. That\n// framing is what makes the format byte-transparent, and it is the same reason\n// [gno.land/p/moul/agents/commit] length-prefixes before hashing: without it,\n// (\"ab\",\"c\") and (\"a\",\"bc\") are the same bytes.\nfunc (m Msg) Encode() string {\n\tvar sb strings.Builder\n\twriteField(\u0026sb, strconv.FormatUint(m.Seq, 10))\n\twriteField(\u0026sb, strconv.FormatInt(m.Height, 10))\n\twriteField(\u0026sb, m.From)\n\twriteField(\u0026sb, m.Topic)\n\twriteField(\u0026sb, m.Kind)\n\twriteField(\u0026sb, m.Ref)\n\twriteField(\u0026sb, m.Body)\n\treturn sb.String()\n}\n\n// Decode parses an encoding produced by [Msg.Encode]. ok is false for anything\n// else, including the empty string, which is what an unwritten ring slot holds.\nfunc Decode(s string) (m Msg, ok bool) {\n\tfields := make([]string, 0, 7)\n\trest := s\n\tfor i := 0; i \u003c 7; i++ {\n\t\tf, r, good := readField(rest)\n\t\tif !good {\n\t\t\treturn Msg{}, false\n\t\t}\n\t\tfields = append(fields, f)\n\t\trest = r\n\t}\n\tif rest != \"\" {\n\t\treturn Msg{}, false\n\t}\n\tseq, err := strconv.ParseUint(fields[0], 10, 64)\n\tif err != nil {\n\t\treturn Msg{}, false\n\t}\n\theight, err := strconv.ParseInt(fields[1], 10, 64)\n\tif err != nil {\n\t\treturn Msg{}, false\n\t}\n\treturn Msg{\n\t\tSeq:    seq,\n\t\tHeight: height,\n\t\tFrom:   fields[2],\n\t\tTopic:  fields[3],\n\t\tKind:   fields[4],\n\t\tRef:    fields[5],\n\t\tBody:   fields[6],\n\t}, true\n}\n\n// Validate reports the first problem with the caller-supplied fields of m, or\n// the empty string when there is none. Seq and Height are not checked: they\n// belong to the relay.\n//\n// It returns a string rather than an error so a realm can pass it straight to\n// a panic without an errors import, which is the only thing realms do with it.\nfunc (m Msg) Validate() string {\n\tswitch {\n\tcase m.From == \"\":\n\t\treturn \"empty from\"\n\tcase len(m.From) \u003e MaxFrom:\n\t\treturn \"from too long\"\n\tcase m.Topic == \"\":\n\t\treturn \"empty topic\"\n\tcase len(m.Topic) \u003e MaxTopic:\n\t\treturn \"topic too long\"\n\tcase !validTopic(m.Topic):\n\t\treturn \"topic must be lowercase a-z, 0-9, dash or dot\"\n\tcase len(m.Kind) \u003e MaxKind:\n\t\treturn \"kind too long\"\n\tcase len(m.Ref) \u003e MaxRef:\n\t\treturn \"ref too long\"\n\tcase m.Body == \"\":\n\t\treturn \"empty body\"\n\tcase len(m.Body) \u003e MaxBody:\n\t\treturn \"body too long\"\n\t}\n\treturn \"\"\n}\n\n// validTopic keeps topics usable as a filter and as a URL path element. Body,\n// kind and ref are deliberately unrestricted: they are escaped at render time,\n// not at write time, because a relay that silently rewrites what an agent said\n// is worse than one that renders it carefully.\nfunc validTopic(s string) bool {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z',\n\t\t\tc \u003e= '0' \u0026\u0026 c \u003c= '9',\n\t\t\tc == '-', c == '.':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Frame returns v as one length-prefixed field, the same framing [Msg.Encode]\n// uses internally. Pair it with [Unframe] to carry a value alongside an\n// encoded message without inventing a second format: a relay that records who\n// signed for a message frames the address and concatenates.\n//\n// Concatenating without framing does not work, and the failure is quiet. An\n// address appended after a decimal length cannot be found again by scanning\n// backwards for digits, because the message's own body may end in digits and\n// the scan cannot tell the two apart.\nfunc Frame(v string) string {\n\treturn strconv.Itoa(len(v)) + \":\" + v\n}\n\n// Unframe reads one framed field and returns it with the remainder.\nfunc Unframe(s string) (field, rest string, ok bool) {\n\treturn readField(s)\n}\n\nfunc writeField(sb *strings.Builder, v string) {\n\tsb.WriteString(strconv.Itoa(len(v)))\n\tsb.WriteString(\":\")\n\tsb.WriteString(v)\n}\n\n// readField reads one length-prefixed field and returns it with the remainder.\nfunc readField(s string) (field, rest string, ok bool) {\n\ti := strings.IndexByte(s, ':')\n\tif i \u003c= 0 {\n\t\treturn \"\", \"\", false\n\t}\n\tn, err := strconv.Atoi(s[:i])\n\tif err != nil || n \u003c 0 {\n\t\treturn \"\", \"\", false\n\t}\n\tstart := i + 1\n\tif start+n \u003e len(s) {\n\t\treturn \"\", \"\", false\n\t}\n\treturn s[start : start+n], s[start+n:], true\n}\n"},{"name":"msg_test.gno","body":"package msg\n\nimport \"testing\"\n\nfunc TestEncodeDecodeRoundTrip(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tm    Msg\n\t}{\n\t\t{\"plain\", Msg{1, 100, \"claude@hermey\", \"build\", \"note\", \"pr/12\", \"ci is green\"}},\n\t\t{\"empty optional fields\", Msg{2, 0, \"a\", \"t\", \"\", \"\", \"b\"}},\n\t\t{\"body holds the separator\", Msg{3, 7, \"a\", \"t\", \"k\", \"r\", \"3:abc:def\"}},\n\t\t{\"body holds a newline\", Msg{4, 7, \"a\", \"t\", \"k\", \"r\", \"line one\\nline two\"}},\n\t\t{\"body holds an encoded message\", Msg{5, 7, \"a\", \"t\", \"k\", \"r\", Msg{1, 1, \"x\", \"y\", \"z\", \"w\", \"v\"}.Encode()}},\n\t\t{\"unicode body\", Msg{6, 7, \"a\", \"t\", \"k\", \"r\", \"héllo … 世界\"}},\n\t\t{\"max height\", Msg{7, 9223372036854775807, \"a\", \"t\", \"k\", \"r\", \"b\"}},\n\t}\n\tfor _, tt := range tests {\n\t\tgot, ok := Decode(tt.m.Encode())\n\t\tif !ok {\n\t\t\tt.Errorf(\"%s: Decode reported failure\", tt.name)\n\t\t\tcontinue\n\t\t}\n\t\tif got != tt.m {\n\t\t\tt.Errorf(\"%s: round trip changed the message\", tt.name)\n\t\t}\n\t}\n}\n\nfunc TestDecodeRejects(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\ts    string\n\t}{\n\t\t{\"empty, which is an unwritten ring slot\", \"\"},\n\t\t{\"not length-prefixed\", \"hello\"},\n\t\t{\"too few fields\", \"1:1\" + \"1:2\"},\n\t\t{\"length runs past the end\", \"99:short\"},\n\t\t{\"trailing bytes after the last field\", Msg{1, 1, \"a\", \"t\", \"k\", \"r\", \"b\"}.Encode() + \"x\"},\n\t\t{\"seq is not a number\", \"1:x1:00:00:00:00:01:b\"},\n\t\t{\"negative length\", \"-1:a\"},\n\t\t{\"no colon\", \"5abcde\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif _, ok := Decode(tt.s); ok {\n\t\t\tt.Errorf(\"%s: Decode accepted it\", tt.name)\n\t\t}\n\t}\n}\n\nfunc TestEncodeIsUnambiguous(t *testing.T) {\n\t// The reason for length prefixes: two different splits of the same bytes\n\t// must not encode to the same string.\n\ta := Msg{1, 1, \"ab\", \"c\", \"k\", \"r\", \"b\"}.Encode()\n\tb := Msg{1, 1, \"a\", \"bc\", \"k\", \"r\", \"b\"}.Encode()\n\tif a == b {\n\t\tt.Error(\"two distinct messages share an encoding\")\n\t}\n}\n\nfunc TestValidate(t *testing.T) {\n\tlong := func(n int) string {\n\t\ts := \"\"\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ts += \"x\"\n\t\t}\n\t\treturn s\n\t}\n\tok := Msg{From: \"a\", Topic: \"t\", Body: \"b\"}\n\n\ttests := []struct {\n\t\tname string\n\t\tm    Msg\n\t\twant string\n\t}{\n\t\t{\"valid\", ok, \"\"},\n\t\t{\"valid with dots and digits\", Msg{From: \"a\", Topic: \"build.v2-0\", Body: \"b\"}, \"\"},\n\t\t{\"empty from\", Msg{Topic: \"t\", Body: \"b\"}, \"empty from\"},\n\t\t{\"from too long\", Msg{From: long(MaxFrom + 1), Topic: \"t\", Body: \"b\"}, \"from too long\"},\n\t\t{\"empty topic\", Msg{From: \"a\", Body: \"b\"}, \"empty topic\"},\n\t\t{\"topic too long\", Msg{From: \"a\", Topic: long(MaxTopic + 1), Body: \"b\"}, \"topic too long\"},\n\t\t{\"uppercase topic\", Msg{From: \"a\", Topic: \"Build\", Body: \"b\"}, \"topic must be lowercase a-z, 0-9, dash or dot\"},\n\t\t{\"topic with a slash\", Msg{From: \"a\", Topic: \"a/b\", Body: \"b\"}, \"topic must be lowercase a-z, 0-9, dash or dot\"},\n\t\t{\"topic with a space\", Msg{From: \"a\", Topic: \"a b\", Body: \"b\"}, \"topic must be lowercase a-z, 0-9, dash or dot\"},\n\t\t{\"kind too long\", Msg{From: \"a\", Topic: \"t\", Kind: long(MaxKind + 1), Body: \"b\"}, \"kind too long\"},\n\t\t{\"ref too long\", Msg{From: \"a\", Topic: \"t\", Ref: long(MaxRef + 1), Body: \"b\"}, \"ref too long\"},\n\t\t{\"empty body\", Msg{From: \"a\", Topic: \"t\"}, \"empty body\"},\n\t\t{\"body too long\", Msg{From: \"a\", Topic: \"t\", Body: long(MaxBody + 1)}, \"body too long\"},\n\t\t{\"body at the limit\", Msg{From: \"a\", Topic: \"t\", Body: long(MaxBody)}, \"\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := tt.m.Validate(); got != tt.want {\n\t\t\tt.Errorf(\"%s: got %q, want %q\", tt.name, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestFrameUnframe(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tv    string\n\t\ttail string\n\t}{\n\t\t{\"plain\", \"g1abc\", \"\"},\n\t\t{\"empty value\", \"\", \"rest\"},\n\t\t{\"value holds a colon\", \"a:b\", \"rest\"},\n\t\t// The bug this pair exists to prevent: scanning backwards for the\n\t\t// length prefix cannot tell a body's trailing digits from it.\n\t\t{\"preceded by a message ending in digits\", \"g1abc\", \"\"},\n\t}\n\tfor _, tt := range tests {\n\t\tgot, rest, ok := Unframe(Frame(tt.v) + tt.tail)\n\t\tif !ok || got != tt.v || rest != tt.tail {\n\t\t\tt.Errorf(\"%s: got (%q, %q, %v), want (%q, %q, true)\", tt.name, got, rest, ok, tt.v, tt.tail)\n\t\t}\n\t}\n}\n\nfunc TestFrameSurvivesABodyEndingInDigits(t *testing.T) {\n\t// A relay frames the author and concatenates. Decoding must recover both\n\t// even when the message body ends in the digits a backwards scan would\n\t// mistake for the author's length prefix.\n\tm := Msg{1, 1, \"a\", \"t\", \"k\", \"r\", \"ends in 40\"}\n\taddr := \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\tauthor, rest, ok := Unframe(Frame(addr) + m.Encode())\n\tif !ok || author != addr {\n\t\tt.Fatalf(\"author not recovered: got %q, ok=%v\", author, ok)\n\t}\n\tgot, ok := Decode(rest)\n\tif !ok || got != m {\n\t\tt.Errorf(\"message not recovered after the framed author\")\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"svg","path":"gno.land/p/moul/svg/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/svg/v0`\n\nMinimalist, extensible SVG generation library for Gno.\n\nThe canvas style map is backed by\n[`gno.land/p/nt/bptree/v0`](https://gno.land/p/nt/bptree/v0): a B+ tree packs\nmany entries per persisted node, so styles cost less storage and inserts spend\nless gas than an AVL backing would.\n\n**Compatibility caveats** (from the in-place-mutating B+ tree backing):\n\n- do not call `AddStyle` from inside a `Canvas.String`/`Render` iteration;\n- do not copy a non-zero `Canvas` by value once styles have been added — the\n  copies would share live tree nodes.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/svg/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/svg/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"doc.gno","body":"/*\nPackage svg is a minimalist and extensible SVG generation library for Gno.\n\nIt is the B+ tree successor to [gno.land/p/moul/svg/v0] (whose canvas styles are\nbacked by an AVL tree): a bump to v2 because the backing data structure used for\nthe canvas style map — and thus the on-chain storage layout — changed from\n[gno.land/p/nt/avl/v0] to [gno.land/p/nt/bptree/v0]. The exported API is\notherwise identical to v1.\n\nA B+ tree packs many entries per persisted node, so a stored style entry costs\nless storage than the AVL backing (and inserts spend materially less gas).\nPrefer v2 when the canvas is part of persisted realm state.\n\nTwo behavioral caveats inherited from the in-place-mutating B+ tree backing:\n\n  - do NOT call AddStyle from inside a Canvas.String/Render iteration — the AVL\n    backing tolerated mutation during iteration, the B+ tree one does not;\n  - do NOT copy a non-zero Canvas by value once styles have been added — the\n    copies would share live B+ tree nodes (v1's AVL copies were independent).\n\nIt provides a structured way to create and compose SVG elements such as rectangles, circles, text, paths, and more. The package is designed to be modular and developer-friendly, enabling optional attributes and method chaining for ease of use.\n\nEach SVG element embeds a BaseAttrs struct, which supports common SVG attributes like `id`, `class`, `style`, `fill`, `stroke`, and `transform`.\n\nCanvas objects represent the root SVG container and support global dimensions, viewBox configuration, embedded styles, and element composition.\n\nExample:\n\n\timport \"gno.land/p/moul/svg/v0\"\n\n\tfunc Foo() string {\n\t\tcanvas := svg.NewCanvas(200, 200).WithViewBox(0, 0, 200, 200)\n\t\tcanvas.AddStyle(\".my-rect\", \"stroke:black;stroke-width:2\")\n\t\tcanvas.Append(\n\t\t\tsvg.NewRectangle(60, 40, 100, 50, \"red\").WithClass(\"my-rect\"),\n\t\t\tsvg.NewCircle(50, 80, 40, \"blue\"),\n\t\t\t\u0026svg.Path{D: `M 10,30\n\t\t\tA 20,20 0,0,1 50,30\n\t\t\t\tA 20,20 0,0,1  90,30\n\t\t\t\tQ 90,60 50,90\n\t\t\t\tQ 10,60 10,30 z`, Fill: \"magenta\"},\n\t\t\tsvg.NewText(20, 50, \"Hello SVG\", \"black\"),\n\t\t)\n\t\tmysvg := canvas.Base64()\n\t}\n*/\npackage svg // import \"gno.land/p/moul/svg/v0\"\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/svg/v0\"\ngno = \"0.9\"\n"},{"name":"svg.gno","body":"package svg\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype Canvas struct {\n\tWidth, Height int\n\tViewBox       string\n\tElems         []Elem\n\tStyle         *bptree.BPTree\n}\n\ntype Elem interface{ String() string }\n\nfunc NewCanvas(width, height int) *Canvas {\n\treturn \u0026Canvas{\n\t\tWidth:  width,\n\t\tHeight: height,\n\t\tStyle:  nil,\n\t}\n}\n\nfunc (c *Canvas) AddStyle(key, value string) *Canvas {\n\tif c.Style == nil {\n\t\tc.Style = bptree.NewBPTree32()\n\t}\n\tc.Style.Set(key, value)\n\treturn c\n}\n\nfunc (c *Canvas) WithViewBox(x, y, width, height int) *Canvas {\n\tc.ViewBox = ufmt.Sprintf(\"%d %d %d %d\", x, y, width, height)\n\treturn c\n}\n\n// Render renders your canvas\nfunc (c Canvas) Render(alt string) string {\n\tbase64SVG := base64.StdEncoding.EncodeToString([]byte(c.String()))\n\treturn ufmt.Sprintf(\"![%s](data:image/svg+xml;base64,%s)\", alt, base64SVG)\n}\n\nfunc (c Canvas) String() string {\n\tout := \"\"\n\tout += ufmt.Sprintf(`\u003csvg xmlns=\"http://www.w3.org/2000/svg\" width=\"%d\" height=\"%d\" viewBox=\"%s\"\u003e`, c.Width, c.Height, c.ViewBox)\n\tif c.Style != nil {\n\t\tout += \"\u003cstyle\u003e\"\n\t\tc.Style.Iterate(\"\", \"\", func(k string, val interface{}) bool {\n\t\t\tv := val.(string)\n\t\t\tout += ufmt.Sprintf(\"%s{%s}\", k, v)\n\t\t\treturn false\n\t\t})\n\t\tout += \"\u003c/style\u003e\"\n\t}\n\tfor _, elem := range c.Elems {\n\t\tout += elem.String()\n\t}\n\tout += \"\u003c/svg\u003e\"\n\treturn out\n}\n\nfunc (c Canvas) Base64() string {\n\tout := c.String()\n\treturn base64.StdEncoding.EncodeToString([]byte(out))\n}\n\nfunc (c *Canvas) Append(elem ...Elem) {\n\tc.Elems = append(c.Elems, elem...)\n}\n\ntype BaseAttrs struct {\n\tID          string\n\tClass       string\n\tStyle       string\n\tStroke      string\n\tStrokeWidth string\n\tOpacity     string\n\tTransform   string\n\tVisibility  string\n}\n\nfunc (b BaseAttrs) String() string {\n\tvar elems []string\n\n\tif b.ID != \"\" {\n\t\telems = append(elems, `id=\"`+b.ID+`\"`)\n\t}\n\tif b.Class != \"\" {\n\t\telems = append(elems, `class=\"`+b.Class+`\"`)\n\t}\n\tif b.Style != \"\" {\n\t\telems = append(elems, `style=\"`+b.Style+`\"`)\n\t}\n\tif b.Stroke != \"\" {\n\t\telems = append(elems, `stroke=\"`+b.Stroke+`\"`)\n\t}\n\tif b.StrokeWidth != \"\" {\n\t\telems = append(elems, `stroke-width=\"`+b.StrokeWidth+`\"`)\n\t}\n\tif b.Opacity != \"\" {\n\t\telems = append(elems, `opacity=\"`+b.Opacity+`\"`)\n\t}\n\tif b.Transform != \"\" {\n\t\telems = append(elems, `transform=\"`+b.Transform+`\"`)\n\t}\n\tif b.Visibility != \"\" {\n\t\telems = append(elems, `visibility=\"`+b.Visibility+`\"`)\n\t}\n\tif len(elems) == 0 {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(elems, \" \")\n}\n\ntype Circle struct {\n\tCX   int // center X\n\tCY   int // center Y\n\tR    int // radius\n\tFill string\n\tAttr BaseAttrs\n}\n\nfunc (c Circle) String() string {\n\treturn ufmt.Sprintf(`\u003ccircle cx=\"%d\" cy=\"%d\" r=\"%d\" fill=\"%s\" %s/\u003e`, c.CX, c.CY, c.R, c.Fill, c.Attr.String())\n}\n\nfunc NewCircle(cx, cy, r int, fill string) *Circle {\n\treturn \u0026Circle{\n\t\tCX:   cx,\n\t\tCY:   cy,\n\t\tR:    r,\n\t\tFill: fill,\n\t}\n}\n\nfunc (c *Circle) WithClass(class string) *Circle {\n\tc.Attr.Class = class\n\treturn c\n}\n\ntype Ellipse struct {\n\tCX   int // center X\n\tCY   int // center Y\n\tRX   int // radius X\n\tRY   int // radius Y\n\tFill string\n\tAttr BaseAttrs\n}\n\nfunc (e Ellipse) String() string {\n\treturn ufmt.Sprintf(`\u003cellipse cx=\"%d\" cy=\"%d\" rx=\"%d\" ry=\"%d\" fill=\"%s\" %s/\u003e`, e.CX, e.CY, e.RX, e.RY, e.Fill, e.Attr.String())\n}\n\nfunc NewEllipse(cx, cy int, fill string) *Ellipse {\n\treturn \u0026Ellipse{\n\t\tCX:   cx,\n\t\tCY:   cy,\n\t\tFill: fill,\n\t}\n}\n\nfunc (e *Ellipse) WithClass(class string) *Ellipse {\n\te.Attr.Class = class\n\treturn e\n}\n\ntype Rectangle struct {\n\tX, Y, Width, Height int\n\tRX, RY              int // corner radiuses\n\tFill                string\n\tAttr                BaseAttrs\n}\n\nfunc (r Rectangle) String() string {\n\treturn ufmt.Sprintf(`\u003crect x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" rx=\"%d\" ry=\"%d\" fill=\"%s\" %s/\u003e`, r.X, r.Y, r.Width, r.Height, r.RX, r.RY, r.Fill, r.Attr.String())\n}\n\nfunc NewRectangle(x, y, width, height int, fill string) *Rectangle {\n\treturn \u0026Rectangle{\n\t\tX:      x,\n\t\tY:      y,\n\t\tWidth:  width,\n\t\tHeight: height,\n\t\tFill:   fill,\n\t}\n}\n\nfunc (r *Rectangle) WithClass(class string) *Rectangle {\n\tr.Attr.Class = class\n\treturn r\n}\n\ntype Path struct {\n\tD    string\n\tFill string\n\tAttr BaseAttrs\n}\n\nfunc (p Path) String() string {\n\treturn ufmt.Sprintf(`\u003cpath d=\"%s\" fill=\"%s\" %s/\u003e`, p.D, p.Fill, p.Attr.String())\n}\n\nfunc NewPath(d, fill string) *Path {\n\treturn \u0026Path{\n\t\tD:    d,\n\t\tFill: fill,\n\t}\n}\n\nfunc (p *Path) WithClass(class string) *Path {\n\tp.Attr.Class = class\n\treturn p\n}\n\ntype Polygon struct { // closed shape\n\tPoints string\n\tFill   string\n\tAttr   BaseAttrs\n}\n\nfunc (p Polygon) String() string {\n\treturn ufmt.Sprintf(`\u003cpolygon points=\"%s\" fill=\"%s\" %s/\u003e`, p.Points, p.Fill, p.Attr.String())\n}\n\nfunc NewPolygon(points, fill string) *Polygon {\n\treturn \u0026Polygon{\n\t\tPoints: points,\n\t\tFill:   fill,\n\t}\n}\n\nfunc (p *Polygon) WithClass(class string) *Polygon {\n\tp.Attr.Class = class\n\treturn p\n}\n\ntype Polyline struct { // polygon but not necessarily closed\n\tPoints string\n\tFill   string\n\tAttr   BaseAttrs\n}\n\nfunc (p Polyline) String() string {\n\treturn ufmt.Sprintf(`\u003cpolyline points=\"%s\" fill=\"%s\" %s/\u003e`, p.Points, p.Fill, p.Attr.String())\n}\n\nfunc NewPolyline(points, fill string) *Polyline {\n\treturn \u0026Polyline{\n\t\tPoints: points,\n\t\tFill:   fill,\n\t}\n}\n\nfunc (p *Polyline) WithClass(class string) *Polyline {\n\tp.Attr.Class = class\n\treturn p\n}\n\ntype Text struct {\n\tX, Y       int\n\tDX, DY     int // shift text pos horizontally/ vertically\n\tRotate     string\n\tText, Fill string\n\tAttr       BaseAttrs\n}\n\nfunc (c Text) String() string {\n\treturn ufmt.Sprintf(`\u003ctext x=\"%d\" y=\"%d\" dx=\"%d\" dy=\"%d\" rotate=\"%s\" fill=\"%s\" %s\u003e%s\u003c/text\u003e`, c.X, c.Y, c.DX, c.DY, c.Rotate, c.Fill, c.Attr.String(), c.Text)\n}\n\nfunc NewText(x, y int, text, fill string) *Text {\n\treturn \u0026Text{\n\t\tX:    x,\n\t\tY:    y,\n\t\tText: text,\n\t\tFill: fill,\n\t}\n}\n\nfunc (c *Text) WithClass(class string) *Text {\n\tc.Attr.Class = class\n\treturn c\n}\n\ntype Group struct {\n\tElems []Elem\n\tFill  string\n\tAttr  BaseAttrs\n}\n\nfunc (g Group) String() string {\n\tout := \"\"\n\tfor _, e := range g.Elems {\n\t\tout += e.String()\n\t}\n\treturn ufmt.Sprintf(`\u003cg fill=\"%s\" %s\u003e%s\u003c/g\u003e`, g.Fill, g.Attr.String(), out)\n}\n\nfunc NewGroup(fill string) *Group {\n\treturn \u0026Group{\n\t\tFill: fill,\n\t}\n}\n\nfunc (g *Group) Append(elem ...Elem) {\n\tg.Elems = append(g.Elems, elem...)\n}\n\nfunc (g *Group) WithClass(class string) *Group {\n\tg.Attr.Class = class\n\treturn g\n}\n"},{"name":"svg_test.gno","body":"package svg\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestBaseAttrsEmpty(t *testing.T) {\n\tuassert.Equal(t, \"\", BaseAttrs{}.String())\n}\n\nfunc TestBaseAttrsAllFields(t *testing.T) {\n\tb := BaseAttrs{\n\t\tID:          \"i\",\n\t\tClass:       \"c\",\n\t\tStyle:       \"fill:red\",\n\t\tStroke:      \"black\",\n\t\tStrokeWidth: \"2\",\n\t\tOpacity:     \"0.5\",\n\t\tTransform:   \"rotate(90)\",\n\t\tVisibility:  \"hidden\",\n\t}\n\tuassert.Equal(t,\n\t\t`id=\"i\" class=\"c\" style=\"fill:red\" stroke=\"black\" stroke-width=\"2\" opacity=\"0.5\" transform=\"rotate(90)\" visibility=\"hidden\"`,\n\t\tb.String())\n}\n\nfunc TestBaseAttrsSkipsEmptyFields(t *testing.T) {\n\tuassert.Equal(t, `id=\"i\" opacity=\"0.5\"`, BaseAttrs{ID: \"i\", Opacity: \"0.5\"}.String())\n}\n\nfunc TestCircle(t *testing.T) {\n\tc := NewCircle(1, 2, 3, \"red\")\n\tuassert.Equal(t, `\u003ccircle cx=\"1\" cy=\"2\" r=\"3\" fill=\"red\" /\u003e`, c.String())\n\n\tuassert.True(t, c.WithClass(\"dot\") == c, \"WithClass should be chainable: same pointer back\")\n\tuassert.Equal(t, `\u003ccircle cx=\"1\" cy=\"2\" r=\"3\" fill=\"red\" class=\"dot\"/\u003e`, c.String())\n}\n\nfunc TestEllipse(t *testing.T) {\n\te := NewEllipse(4, 5, \"blue\")\n\t// NewEllipse takes no radii, so RX/RY stay zero until set directly.\n\tuassert.Equal(t, `\u003cellipse cx=\"4\" cy=\"5\" rx=\"0\" ry=\"0\" fill=\"blue\" /\u003e`, e.String())\n\n\te.RX, e.RY = 10, 20\n\te.WithClass(\"blob\")\n\tuassert.Equal(t, `\u003cellipse cx=\"4\" cy=\"5\" rx=\"10\" ry=\"20\" fill=\"blue\" class=\"blob\"/\u003e`, e.String())\n}\n\nfunc TestRectangle(t *testing.T) {\n\tr := NewRectangle(1, 2, 30, 40, \"green\")\n\tuassert.Equal(t, `\u003crect x=\"1\" y=\"2\" width=\"30\" height=\"40\" rx=\"0\" ry=\"0\" fill=\"green\" /\u003e`, r.String())\n\n\tr.RX, r.RY = 5, 6\n\tr.WithClass(\"box\")\n\tuassert.Equal(t, `\u003crect x=\"1\" y=\"2\" width=\"30\" height=\"40\" rx=\"5\" ry=\"6\" fill=\"green\" class=\"box\"/\u003e`, r.String())\n}\n\nfunc TestPath(t *testing.T) {\n\tp := NewPath(\"M0 0 L10 10\", \"none\")\n\tuassert.Equal(t, `\u003cpath d=\"M0 0 L10 10\" fill=\"none\" /\u003e`, p.String())\n\n\tp.WithClass(\"stroke\")\n\tuassert.Equal(t, `\u003cpath d=\"M0 0 L10 10\" fill=\"none\" class=\"stroke\"/\u003e`, p.String())\n}\n\nfunc TestPolygon(t *testing.T) {\n\tp := NewPolygon(\"0,0 10,0 5,8\", \"yellow\")\n\tuassert.Equal(t, `\u003cpolygon points=\"0,0 10,0 5,8\" fill=\"yellow\" /\u003e`, p.String())\n\n\tp.WithClass(\"tri\")\n\tuassert.Equal(t, `\u003cpolygon points=\"0,0 10,0 5,8\" fill=\"yellow\" class=\"tri\"/\u003e`, p.String())\n}\n\nfunc TestPolyline(t *testing.T) {\n\tp := NewPolyline(\"0,0 10,10\", \"none\")\n\tuassert.Equal(t, `\u003cpolyline points=\"0,0 10,10\" fill=\"none\" /\u003e`, p.String())\n\n\tp.WithClass(\"line\")\n\tuassert.Equal(t, `\u003cpolyline points=\"0,0 10,10\" fill=\"none\" class=\"line\"/\u003e`, p.String())\n}\n\nfunc TestText(t *testing.T) {\n\ttx := NewText(7, 8, \"hello\", \"black\")\n\tuassert.Equal(t, `\u003ctext x=\"7\" y=\"8\" dx=\"0\" dy=\"0\" rotate=\"\" fill=\"black\" \u003ehello\u003c/text\u003e`, tx.String())\n\n\ttx.DX, tx.DY, tx.Rotate = 1, 2, \"45\"\n\ttx.WithClass(\"label\")\n\tuassert.Equal(t, `\u003ctext x=\"7\" y=\"8\" dx=\"1\" dy=\"2\" rotate=\"45\" fill=\"black\" class=\"label\"\u003ehello\u003c/text\u003e`, tx.String())\n}\n\nfunc TestGroup(t *testing.T) {\n\tg := NewGroup(\"purple\")\n\tuassert.Equal(t, `\u003cg fill=\"purple\" \u003e\u003c/g\u003e`, g.String())\n\n\tg.Append(NewCircle(0, 0, 1, \"red\"), NewPath(\"M0 0\", \"none\"))\n\tg.WithClass(\"layer\")\n\tuassert.Equal(t,\n\t\t`\u003cg fill=\"purple\" class=\"layer\"\u003e\u003ccircle cx=\"0\" cy=\"0\" r=\"1\" fill=\"red\" /\u003e\u003cpath d=\"M0 0\" fill=\"none\" /\u003e\u003c/g\u003e`,\n\t\tg.String())\n}\n\nfunc TestGroupNesting(t *testing.T) {\n\tinner := NewGroup(\"a\")\n\tinner.Append(NewCircle(1, 1, 1, \"red\"))\n\touter := NewGroup(\"b\")\n\touter.Append(inner)\n\n\tuassert.Equal(t,\n\t\t`\u003cg fill=\"b\" \u003e\u003cg fill=\"a\" \u003e\u003ccircle cx=\"1\" cy=\"1\" r=\"1\" fill=\"red\" /\u003e\u003c/g\u003e\u003c/g\u003e`,\n\t\touter.String())\n}\n\nfunc TestCanvasEmpty(t *testing.T) {\n\tc := NewCanvas(100, 50)\n\tuassert.Equal(t,\n\t\t`\u003csvg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\" viewBox=\"\"\u003e\u003c/svg\u003e`,\n\t\tc.String())\n}\n\nfunc TestCanvasWithViewBox(t *testing.T) {\n\tc := NewCanvas(100, 50)\n\tuassert.True(t, c.WithViewBox(0, 0, 200, 100) == c, \"WithViewBox should be chainable\")\n\tuassert.True(t, strings.Contains(c.String(), `viewBox=\"0 0 200 100\"`), \"viewBox should be set\")\n}\n\nfunc TestCanvasAppend(t *testing.T) {\n\tc := NewCanvas(10, 10)\n\tc.Append(NewCircle(1, 1, 1, \"red\"), NewCircle(2, 2, 2, \"blue\"))\n\n\tout := c.String()\n\tuassert.True(t, strings.Contains(out, `\u003ccircle cx=\"1\" cy=\"1\" r=\"1\" fill=\"red\" /\u003e\u003ccircle cx=\"2\" cy=\"2\" r=\"2\" fill=\"blue\" /\u003e`),\n\t\t\"elements should render in insertion order\")\n}\n\n// TestCanvasStyleIsKeyOrdered is the determinism check that matters on-chain:\n// the style block must not depend on insertion order, or two nodes could\n// disagree on the rendered output.\nfunc TestCanvasStyleIsKeyOrdered(t *testing.T) {\n\ta := NewCanvas(10, 10)\n\ta.AddStyle(\"z-last\", \"fill:blue\").AddStyle(\"a-first\", \"fill:red\")\n\n\tb := NewCanvas(10, 10)\n\tb.AddStyle(\"a-first\", \"fill:red\").AddStyle(\"z-last\", \"fill:blue\")\n\n\tuassert.Equal(t, a.String(), b.String())\n\tuassert.True(t, strings.Contains(a.String(), `\u003cstyle\u003ea-first{fill:red}z-last{fill:blue}\u003c/style\u003e`),\n\t\t\"styles should be emitted in key order\")\n}\n\nfunc TestCanvasNoStyleBlockWhenUnset(t *testing.T) {\n\tuassert.False(t, strings.Contains(NewCanvas(1, 1).String(), \"\u003cstyle\u003e\"),\n\t\t\"a canvas with no styles should not emit an empty \u003cstyle\u003e block\")\n}\n\nfunc TestCanvasAddStyleChainable(t *testing.T) {\n\tc := NewCanvas(1, 1)\n\tuassert.True(t, c.AddStyle(\"a\", \"b\") == c, \"AddStyle should be chainable\")\n}\n\nfunc TestCanvasBase64RoundTrip(t *testing.T) {\n\tc := NewCanvas(10, 10)\n\tc.Append(NewCircle(1, 1, 1, \"red\"))\n\n\t// Base64 must encode exactly what String() produced.\n\tuassert.Equal(t, \"PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgdmlld0JveD0iIj48Y2lyY2xlIGN4PSIxIiBjeT0iMSIgcj0iMSIgZmlsbD0icmVkIiAvPjwvc3ZnPg==\",\n\t\tc.Base64())\n}\n\nfunc TestCanvasRenderWrapsBase64(t *testing.T) {\n\tc := NewCanvas(10, 10)\n\tc.Append(NewCircle(1, 1, 1, \"red\"))\n\n\tuassert.Equal(t, \"![a picture](data:image/svg+xml;base64,\"+c.Base64()+\")\", c.Render(\"a picture\"))\n}\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"authz","path":"gno.land/p/moul/authz/v1","files":[{"name":"README.md","body":"# `gno.land/p/moul/authz/v1`\n\nFlexible authorization control for privileged actions, **backed by a B+ tree**\n(`gno.land/p/nt/bptree` via [`p/moul/addrset/v1`](https://github.com/moul/gno-contracts/tree/main/p/moul/addrset)).\n\nThe B+ tree successor to [`p/moul/authz/v0`](https://github.com/moul/gno-contracts/tree/3d07a5b2cc02d7c3769caff0c17d884ac033bcfe/p/moul/authz/v0)\n(AVL-backed, via `p/moul/addrset/v0`). **v1 because the member store — and thus\nthe on-chain storage layout — changed** (a compatibility change ⇒ new version).\nThe exported API matches v0, except the `MemberAuthority.Tree()` escape hatch is\nremoved so the backing store never leaks across realms.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/authz/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/authz/v1/deps.png)\n\nProvenance: imported — see [https://github.com/moul/gno-contracts/pull/2](https://github.com/moul/gno-contracts/pull/2) for context and metadata.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"authz.gno","body":"// Package authz provides flexible authorization control for privileged actions.\n//\n// # Authorization Strategies\n//\n// The package supports multiple authorization strategies:\n//   - Member-based: Single user or team of users\n//   - Contract-based: The contract at a given path is itself the authority\n//   - Auto-accept: Allow all actions\n//   - Drop: Deny all actions\n//\n// Core Components\n//\n//   - Authority interface: Base interface implemented by all authorities\n//   - Authorizer: Main wrapper object for authority management\n//   - MemberAuthority: Manages authorized addresses\n//   - ContractAuthority: Makes the contract at a path its own authority\n//   - AutoAcceptAuthority: Accepts all actions\n//   - DroppedAuthority: Denies all actions\n//\n// Quick Start\n//\n//\t// Initialize with contract deployer as authority\n//\tvar member address(...)\n//\tvar auth = authz.NewWithMembers(member)\n//\n//\t// Create functions that require authorization\n//\tfunc UpdateConfig(cur realm, newValue string) error {\n//\t\treturn auth.DoByPrevious(0, cur, \"update_config\", func() error {\n//\t\t\tconfig = newValue\n//\t\t\treturn nil\n//\t\t})\n//\t}\n//\n// See example_test.gno for more usage examples.\npackage authz\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/addrset/v1\"\n\t\"gno.land/p/moul/once/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Authorizer is the main wrapper object that handles authority management.\n// It is configured with a replaceable Authority implementation.\ntype Authorizer struct {\n\tauth Authority\n}\n\n// Authority represents an entity that can authorize privileged actions.\n// It is implemented by MemberAuthority, ContractAuthority, AutoAcceptAuthority,\n// and DroppedAuthority.\n//\n// Authority is the canonical safe shape for cross-package authority\n// interfaces: methods are address-typed (no realm/cur crosses the interface\n// boundary), and consumers correctly derive `caller` from\n// `cur.Previous().Address()` under `rlm.IsCurrent()` before invoking\n// Authorize. No cur-leak (class 1) is possible through this interface.\n//\n// However, two RESIDUAL RISKS apply:\n//\n//   - Class-3 impl-substitution: NewWithAuthority and Authorizer.Transfer\n//     accept any Authority impl. A malicious Authority can always-approve\n//     (silent privilege escalation) or always-deny (denial-of-service).\n//     Consumers should pass canonical impls from this package\n//     (MemberAuthority, ContractAuthority, AutoAcceptAuthority,\n//     DroppedAuthority) unless they have explicit reason to register a\n//     foreign impl. We do not expose an IsCanonicalAuthority allowlist\n//     because the package is intentionally extensible — third-party impls\n//     are the design intent.\n//\n//   - Class-4 closed-over-authority: NewContractAuthority and\n//     NewRestrictedContractAuthority capture a caller-supplied\n//     PrivilegedActionHandler closure. The handler runs synchronously\n//     inside Authorize with the consumer's authority. A hostile handler\n//     can swallow actions, log the caller, or execute arbitrary code\n//     under the consumer's frame. Register only trusted handler functions.\n//     See r/gnops/valopers/init.gno for the realistic registration shape.\n//\n//   - Caller- and title-forgery on the RAW interface: Authorize takes\n//     `caller` and `title` as ARGUMENTS, not from the frame. A consumer\n//     that exposes a bare Authority (rather than the *Authorizer that\n//     wraps it) therefore lets any holder present any caller and any\n//     title. Caller-forgery is contained — the only authority-mutating\n//     closure lives inside Authorizer.Transfer, so a forged caller on a\n//     raw Authorize runs the caller's own inert closure and cannot\n//     transfer; TestForgedCallerCannotTransfer pins that boundary.\n//     Title-forgery is NOT contained: the title is passed straight to the\n//     contractHandler, so a handler that branches on it (routing, quotas,\n//     audit trails) must not treat it as trusted. Keep the Authority\n//     unexported and hand out only what callers need; see\n//     r/gnops/valopers/admin.gno, which exports a description string.\n//\n// # Backing store\n//\n// This is the B+ tree successor to [gno.land/p/moul/authz/v0] (which is\n// backed by an AVL tree via gno.land/p/moul/addrset/v0): a bump to v1\n// because the member store — and thus the on-chain storage layout —\n// changed to gno.land/p/moul/addrset/v1, itself backed by\n// gno.land/p/nt/bptree/v0. This is a storage/compatibility change; the\n// exported API is otherwise the same as v0, EXCEPT that the v0\n// MemberAuthority.Tree() escape hatch is intentionally removed so the\n// backing store never leaks across realms.\n//\n// Two behavioral caveats follow from the in-place-mutating B+ tree backing:\n//\n//   - do NOT mutate a MemberAuthority (AddMember/RemoveMember) from inside\n//     an iteration callback — the AVL backing's copy-on-write tolerated it,\n//     this one does not;\n//   - do NOT copy a non-zero MemberAuthority (or its members set) by value —\n//     the copies would share live tree nodes while their roots and sizes\n//     diverge (v0's copies were independent snapshots).\n//\n// We do NOT seal Authority via an unexported marker method — that pattern\n// is bypassable via embedding in Gno; see\n// p/test/seal/filetests/z_seal_*_filetest.gno for the four bypass tests.\ntype Authority interface {\n\t// Authorize executes a privileged action if the caller is authorized\n\t// Additional args can be provided for context (e.g., for proposal creation)\n\tAuthorize(caller address, title string, action PrivilegedAction, args ...any) error\n\n\t// String returns a human-readable description of the authority\n\tString() string\n}\n\n// PrivilegedAction defines a function that performs a privileged action.\ntype PrivilegedAction func() error\n\n// PrivilegedActionHandler is called by contract-based authorities to handle\n// privileged actions.\ntype PrivilegedActionHandler func(title string, action PrivilegedAction) error\n\n// NewWithMembers creates a new Authorizer whose authority is a\n// MemberAuthority containing the given addresses. Callers express\n// authority intent at the call site:\n//\n//\t// \"auth realm is the authority\"\n//\ta := authz.NewWithMembers(cur.Address())\n//\n//\t// \"previous realm is the authority\" (from a crossing function)\n//\ta := authz.NewWithMembers(cur.Previous().Address())\n//\n//\t// \"EOA caller is the authority\" (from init(cur realm))\n//\tif !cur.Previous().IsUserCall() {\n//\t    panic(\"realm must be initialized by EOA\")\n//\t}\n//\ta := authz.NewWithMembers(cur.Previous().Address())\n//\n// This replaces the previous NewWithCurrent / NewWithPrevious /\n// NewWithOrigin sugar — those baked runtime.{Current,Previous,Origin}\n// reads into the constructor, which (a) prevented use from package-\n// level var initializers, (b) made the EOA-origin check inside\n// NewWithOrigin an indirect address comparison rather than the\n// straightforward IsUserCall predicate, and (c) coupled the\n// constructor to the runtime walks the rest of the migration is\n// moving away from.\nfunc NewWithMembers(addrs ...address) *Authorizer {\n\treturn \u0026Authorizer{\n\t\tauth: NewMemberAuthority(addrs...),\n\t}\n}\n\n// NewWithAuthority creates a new Authorizer with a specific authority.\n//\n// SECURITY: `authority` is an open-interface input — any value satisfying\n// Authority is accepted. A malicious impl can always-approve (privilege\n// escalation) or always-deny (DoS). Prefer canonical impls from this\n// package (NewMemberAuthority, NewContractAuthority, NewAutoAcceptAuthority,\n// NewDroppedAuthority) unless you specifically need a foreign impl.\nfunc NewWithAuthority(authority Authority) *Authorizer {\n\treturn \u0026Authorizer{\n\t\tauth: authority,\n\t}\n}\n\n// Authority returns the auth authority implementation\nfunc (a *Authorizer) Authority() Authority {\n\treturn a.auth\n}\n\n// Transfer changes the auth authority after validation. rlm must be the\n// caller's own captured cur (asserted via rlm.IsCurrent()); the\n// principal is rlm.Previous().Address(). Closes the address-parameter\n// forgery: an external realm cannot supply Owner() as `caller` to\n// bypass the underlying Authority's check.\n//\n// SECURITY (runtime substitution): once the current authority approves a\n// Transfer, the new authority is installed and effective on the next call.\n// If an attacker ever becomes the authority — even briefly — they can\n// install a permanent DroppedAuthority (DoS) or an AutoAcceptAuthority\n// (privilege escalation). Consumers concerned about this should wrap\n// Transfer with a one-shot guard or a quorum/cooldown check.\n//\n// `newAuthority` is also an open-interface input — see NewWithAuthority's\n// Class-3 caveat. Pass canonical impls.\nfunc (a *Authorizer) Transfer(_ int, rlm realm, newAuthority Authority) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.auth.Authorize(caller, \"transfer_authority\", func() error {\n\t\ta.auth = newAuthority\n\t\treturn nil\n\t})\n}\n\n// DoByCurrent executes a privileged action authorized as `rlm`. `rlm`\n// must be the caller's own live cur (asserted via rlm.IsCurrent());\n// the authorized principal is `rlm.Address()`. To authorize as the\n// realm that called your function, use `DoByPrevious`.\n//\n//\tauth.DoByCurrent(0, cur, \"update_config\", func() error { ... })    // current realm authorizes\n//\tauth.DoByPrevious(0, cur, \"update_config\", func() error { ... })   // calling realm authorizes\n//\n// The `_ int` first parameter is a deliberate sentinel that pushes\n// `rlm realm` past the first-arg position so DoByCurrent stays a\n// non-crossing method — otherwise it would be a crossing method and\n// rlm.Previous() inside would resolve one realm deeper than the caller\n// intended.\n//\n// SECURITY: the IsCurrent guard closes Class-2 designation forgery (see\n// docs/resources/gno-security.md). A realm value's .Address() is set\n// when the value is minted at a crossing frame; the value can in\n// principle be stored and replayed. Without IsCurrent, a hostile realm\n// could capture a high-privilege realm's cur.Previous() (e.g., when\n// that realm called into it) and later pass the stored value here to\n// authorize actions as that realm. IsCurrent rejects stale captures by\n// requiring the value to match the topmost live crossing frame's cur.\nfunc (a *Authorizer) DoByCurrent(_ int, rlm realm, title string, action PrivilegedAction, args ...any) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\treturn a.auth.Authorize(rlm.Address(), title, action, args...)\n}\n\n// DoByPrevious executes a privileged action authorized as the realm\n// that called the function invoking DoByPrevious. `rlm` must be the\n// caller's own live cur; the principal is derived as\n// `rlm.Previous().Address()`. Mirrors the Transfer/AddMember pattern:\n// always take live cur, derive the caller-of-caller internally rather\n// than accepting a stored/forwarded realm value.\nfunc (a *Authorizer) DoByPrevious(_ int, rlm realm, title string, action PrivilegedAction, args ...any) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\treturn a.auth.Authorize(rlm.Previous().Address(), title, action, args...)\n}\n\n// String returns a string representation of the auth authority.\n//\n// A non-canonical impl is wrapped as custom_authority[...] so that the\n// official \"dropped\" is distinguishable from a \"*custom*: dropped\"\n// (autoclaimed) one. Shared with ContractAuthority.String, which applies\n// the same rule to its nested proposer.\nfunc (a *Authorizer) String() string {\n\treturn canonicalAuthorityString(a.auth)\n}\n\n// MemberAuthority is the default implementation using addrset for member\n// management.\ntype MemberAuthority struct {\n\tmembers addrset.Set\n}\n\nfunc NewMemberAuthority(members ...address) *MemberAuthority {\n\tauth := \u0026MemberAuthority{}\n\tfor _, addr := range members {\n\t\tauth.members.Add(addr)\n\t}\n\treturn auth\n}\n\nfunc (a *MemberAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\tif !a.members.Has(caller) {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\n\tif err := action(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (a *MemberAuthority) String() string {\n\taddrs := []string{}\n\ta.members.IterateByOffset(0, a.members.Size(), func(addr address) bool {\n\t\taddrs = append(addrs, string(addr))\n\t\treturn false\n\t})\n\taddrsStr := strings.Join(addrs, \",\")\n\treturn ufmt.Sprintf(\"member_authority[%s]\", addrsStr)\n}\n\n// AddMember adds a new member to the authority. rlm must be the caller's\n// own captured cur; the principal is rlm.Previous().Address() and must\n// already be a member. The IsCurrent guard closes the forgery where an\n// external realm passes Owner() as caller to bypass members.Has(caller).\nfunc (a *MemberAuthority) AddMember(_ int, rlm realm, addr address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.Authorize(caller, \"add_member\", func() error {\n\t\ta.members.Add(addr)\n\t\treturn nil\n\t})\n}\n\n// AddMembers adds a list of members to the authority. Same rlm contract\n// as AddMember.\nfunc (a *MemberAuthority) AddMembers(_ int, rlm realm, addrs ...address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.Authorize(caller, \"add_members\", func() error {\n\t\tfor _, addr := range addrs {\n\t\t\ta.members.Add(addr)\n\t\t}\n\t\treturn nil\n\t})\n}\n\n// RemoveMember removes a member from the authority. Same rlm contract\n// as AddMember.\nfunc (a *MemberAuthority) RemoveMember(_ int, rlm realm, addr address) error {\n\tif !rlm.IsCurrent() {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\tcaller := rlm.Previous().Address()\n\treturn a.Authorize(caller, \"remove_member\", func() error {\n\t\ta.members.Remove(addr)\n\t\treturn nil\n\t})\n}\n\n// Has checks if the given address is a member of the authority\nfunc (a *MemberAuthority) Has(addr address) bool {\n\treturn a.members.Has(addr)\n}\n\n// ContractAuthority implements async contract-based authority\ntype ContractAuthority struct {\n\tcontractPath    string\n\tcontractAddr    address\n\tcontractHandler PrivilegedActionHandler\n\tproposer        Authority // controls who can create proposals\n}\n\n// NewContractAuthority makes the contract at `path` its OWN authority:\n// the default proposer accepts only chain.PackageAddress(path), so a\n// privileged action proceeds only when driven from that contract's own\n// frame.\n//\n// NewRestrictedContractAuthority does NOT widen this — it REPLACES it.\n// See its godoc; with an explicit proposer, `path` is a label and\n// contractAddr is never consulted.\n//\n// The `caller` compared against that address is established upstream by\n// Authorizer.DoByCurrent / DoByPrevious / Transfer under rlm.IsCurrent(),\n// so an external realm cannot present the contract address.\n//\n// BREAKING: the default proposer used to be\n// NewAutoAcceptAuthority (\"anyone can propose\"). Consumers that relied on\n// arbitrary callers driving a plain ContractAuthority will start getting\n// \"unauthorized\"; that is the fix, not a regression. Pass an explicit\n// proposer to NewRestrictedContractAuthority to opt back in.\n//\n// SECURITY — the gate binds the contract's IDENTITY, not its intent.\n// Inside any crossing frame of the contract, rlm.Address() is\n// unconditionally PackageAddress(path), so `DoByCurrent` from within the\n// contract is a tautology; only DoByPrevious and Transfer gain a real\n// check. Consequently ANY exported function of the contract that returns\n// a crossing closure (or anything else carrying its frame) hands this\n// authority to its caller. Keep privileged closures unexported.\n//\n// So DO NOT write NewContractAuthority(ownPath) + DoByCurrent. It reads\n// like \"only I may do this\" and compiles to \"anyone may do this\". Point\n// `path` at the principal you actually want to assert — usually the\n// governance realm that will drive the action — and use DoByPrevious, so\n// the comparison is against whoever crossed in:\n//\n//\t// in r/gnops/valopers/init.gno\n//\tauth = authz.NewWithAuthority(\n//\t    authz.NewContractAuthority(\"gno.land/r/gov/dao\", handler),\n//\t)\n//\t// in the privileged write\n//\tauth.DoByPrevious(0, rlm, \"update-instructions\", action)\n//\n// Own-path is right only when something OTHER than the contract's own\n// frame supplies the caller — i.e. you drive it via DoByPrevious from a\n// realm you have deliberately let call in, or via Transfer.\n//\n// SECURITY — a gate is only as good as the principal it names. Pointing\n// `path` at a realm whose frame ANY caller can mint buys nothing. Check,\n// for whatever principal you choose, that nothing exported by that realm\n// hands out its frame identity:\n//\n//   - `gno.land/r/gov/dao` is safe to assert ONLY because\n//     SimpleExecutor.Execute rejects invocation from outside the proxy\n//     (r/gov/dao/types.gno). Before that gate existed, dao's exported\n//     NewSimpleExecutor + Execute let any realm mint a frame whose\n//     Previous() was r/gov/dao, so this whole pairing authenticated\n//     nothing. Do not assume a governance path is unforgeable; verify it.\n//   - Whatever the principal, an exported function of YOUR realm whose\n//     signature is assignable to a callback type the principal invokes\n//     (for r/gov/dao: `func(realm) error`) is itself the leak — the\n//     principal will happily call it for an attacker. Keep privileged\n//     entrypoints out of that shape, or take extra parameters.\n//\n// Neither shape defends against re-exporting the privileged closure: its\n// holder picks the Previous() they present by wrapping it in an executor\n// of their own. Unexported closures remain the load-bearing rule.\n//\n// A syntactically valid but WRONG `path` is a permanent brick, not an\n// error: the authority accepts nobody, and Transfer routes through the\n// same gate, so it cannot be rotated out either. Construction rejects\n// malformed paths, but it cannot tell a wrong path from a right one —\n// e.g. \"gno.land/r/gov/dao/impl/v0\" (the path r/gov/dao's own\n// allowedDAOs list holds) is well-formed and permanently dead, because\n// an executor's Previous() is the PROXY path, never the impl. Give the\n// consumer a governance-gated rotation entrypoint before deploying; see\n// r/gnops/valopers/admin.gno's NewAuthorityRotationProposalRequest.\n//\n// SECURITY (Class-4 captured callback): `handler` is a caller-supplied\n// closure that runs SYNCHRONOUSLY inside Authorize, with the consumer's\n// authority. A hostile handler can swallow actions, log the caller, or\n// execute arbitrary code under the consumer's frame. The package-internal\n// wrappedAction enforces at-most-once invocation and NOTHING ELSE — in\n// particular it does not check the caller, and the handler may call it\n// however it likes (multiple times, never, out of order). Register only\n// trusted handler functions; treat handler registration as the trust\n// boundary.\n//\n// Panics if `path` is empty or malformed, or if `handler` is nil.\nfunc NewContractAuthority(path string, handler PrivilegedActionHandler) *ContractAuthority {\n\taddr := chain.PackageAddress(assertValidContractPath(path))\n\t// The default proposer is a real Authority, not an absent one. Encoding\n\t// the strictest policy as a nil field would mean the secure default is\n\t// what you get by leaving something OUT: a struct literal that skips\n\t// this constructor, a persisted value from an older build, or re-adding\n\t// `if proposer == nil { proposer = NewAutoAcceptAuthority() }` would all\n\t// silently be wide open again. A one-field struct costs the same as the\n\t// nil it replaces and cannot be reached by omission.\n\treturn newContractAuthority(path, addr, handler, \u0026contractIdentityAuthority{addr: addr})\n}\n\n// NewRestrictedContractAuthority creates a contract authority whose\n// proposer REPLACES the contract-identity gate.\n//\n// This is the escape hatch, not a second lock. `proposer` becomes the ONLY\n// authorization decision: contractAddr is not consulted on this path, so\n// `path` degrades to a label that appears in String() and asserts nothing.\n// NewRestrictedContractAuthority(p, h, NewAutoAcceptAuthority()) is exactly\n// the old default behaviour (\"anyone can propose\"), stated\n// explicitly rather than reached by default.\n//\n// In particular NewRestrictedContractAuthority(\"gno.land/r/gov/dao\", h,\n// NewMemberAuthority(alice)) does NOT mean \"GovDAO and alice\". It means\n// \"alice, and not GovDAO\".\n//\n// SECURITY:\n//   - `handler` is the same Class-4 captured-callback risk as\n//     NewContractAuthority — runs synchronously inside Authorize with the\n//     consumer's authority. Register only trusted handler functions.\n//   - `proposer` is an open-interface input (Class-3 impl-substitution).\n//     A hostile proposer Authority can always-approve creation of any\n//     proposal, defeating the restriction. Pass canonical impls only.\n//     String() renders a non-canonical proposer wrapped as\n//     custom_authority[...] so such a substitution is at least visible.\nfunc NewRestrictedContractAuthority(path string, handler PrivilegedActionHandler, proposer Authority) Authority {\n\tif proposer == nil {\n\t\tpanic(\"proposer cannot be nil\")\n\t}\n\taddr := chain.PackageAddress(assertValidContractPath(path))\n\treturn newContractAuthority(path, addr, handler, proposer)\n}\n\n// newContractAuthority is the single construction path: both exported\n// constructors validate, then land here, so a guard added once applies to\n// both. `handler` is rejected here rather than surfaced at Authorize time\n// because Authorize checks contractHandler == nil BEFORE consulting the\n// proposer, and Transfer routes through Authorize — so a nil-handler\n// authority could never be rotated out. It is a permanent brick with no\n// on-chain recovery for anyone: the same bricked-governance failure\n// mode, reached by accident.\nfunc newContractAuthority(path string, addr address, handler PrivilegedActionHandler, proposer Authority) *ContractAuthority {\n\tif handler == nil {\n\t\tpanic(\"contract handler cannot be nil\")\n\t}\n\treturn \u0026ContractAuthority{\n\t\tcontractPath:    path,\n\t\tcontractAddr:    addr,\n\t\tcontractHandler: handler,\n\t\tproposer:        proposer,\n\t}\n}\n\n// assertValidContractPath rejects paths that chain.PackageAddress would\n// hash happily but that no realm could ever present, which would brick the\n// authority permanently (nobody authorizes, and Transfer routes through the\n// same gate so nobody can rotate out). Returns `path` so it composes.\n//\n// The authoritative rule is gnolang.ReGnoUserPkgPath (\"all paths must be\n// lowercase ascii alphanumeric characters\", gnovm/pkg/gnolang/mempackage.go),\n// but no validator is exported to Gno code — chain's isValidSubpath /\n// assertValidSubpath are unexported, and there is no chain.IsValidPkgPath.\n// So this is a deliberately permissive superset: segment (\"/\" segment)*,\n// segment = [a-z0-9] ([a-z0-9_.-]* [a-z0-9])?. It accepts every real\n// package path and catches what actually gets typed wrong — trailing or\n// embedded whitespace, empty segments, uppercase, stray punctuation. It\n// CANNOT catch a well-formed path that is simply the wrong principal. See\n// NewContractAuthority's godoc on rotation.\nfunc assertValidContractPath(path string) string {\n\tif path == \"\" {\n\t\tpanic(\"contract path cannot be empty\")\n\t}\n\tif !strings.Contains(path, \"/\") {\n\t\tpanic(\"contract path must be a package path, e.g. gno.land/r/gov/dao\")\n\t}\n\tstart := 0\n\tfor i := 0; i \u003c= len(path); i++ {\n\t\tif i == len(path) || path[i] == '/' {\n\t\t\tif !isValidContractPathSegment(path[start:i]) {\n\t\t\t\tpanic(\"contract path must be '/'-separated segments of [a-z0-9] with '_.-' allowed inside a segment, e.g. gno.land/r/gov/dao\")\n\t\t\t}\n\t\t\tstart = i + 1\n\t\t}\n\t}\n\treturn path\n}\n\nfunc isValidContractPathSegment(seg string) bool {\n\tif seg == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(seg); i++ {\n\t\tswitch c := seg[i]; {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '_' || c == '.' || c == '-':\n\t\t\t// Allowed only strictly inside a segment.\n\t\t\tif i == 0 || i == len(seg)-1 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// contractIdentityAuthority is the default proposer installed by\n// NewContractAuthority: the contract at the bound path, and nobody else.\n// Unexported and unmutable by design — AddMember/RemoveMember are\n// meaningless for a fixed contract identity, which is why this is not a\n// MemberAuthority holding one address.\ntype contractIdentityAuthority struct {\n\taddr address\n}\n\nfunc (a *contractIdentityAuthority) Authorize(caller address, _ string, action PrivilegedAction, _ ...any) error {\n\tif caller != a.addr {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\treturn action()\n}\n\nfunc (a *contractIdentityAuthority) String() string { return \"contract-identity\" }\n\nfunc (a *ContractAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\tif a.contractHandler == nil {\n\t\treturn errors.New(\"contract handler is not set\")\n\t}\n\n\t// setup a once instance to ensure the action is executed only once\n\texecutionOnce := once.Once{}\n\n\t// wrappedAction enforces at-most-once invocation. The previous\n\t// gate `unsafe.CurrentRealm() == contractAddr` is removed: it\n\t// was .Title()-bypassable (runtime.CurrentRealm walks past\n\t// non-crossing frames to the most-recent crossing ancestor) and\n\t// the trust boundary is now upstream — Authorizer.DoByCurrent /\n\t// DoByPrevious require rlm.IsCurrent() and pass a non-forgeable\n\t// principal to Authorize, while the consumer realm's handler\n\t// closure is the Class-4 trust root by lexical capture at\n\t// registration time.\n\twrappedAction := func() error {\n\t\treturn executionOnce.DoErr(func() error {\n\t\t\treturn action()\n\t\t})\n\t}\n\n\thandle := func() error {\n\t\tif err := a.contractHandler(title, wrappedAction); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// The proposer IS the authorization decision. For an authority built by\n\t// NewContractAuthority it is a contractIdentityAuthority bound to\n\t// contractAddr — the contract itself and nobody else; for one built by\n\t// NewRestrictedContractAuthority it is whatever the consumer installed,\n\t// and contractAddr is deliberately not consulted (see that constructor's\n\t// godoc). `caller` is established upstream by Authorizer.DoByCurrent /\n\t// DoByPrevious / Transfer under rlm.IsCurrent(), so an external realm\n\t// cannot present an arbitrary principal here.\n\t//\n\t// A nil proposer is not a policy, it is a malformed value: both\n\t// constructors always install one, so nil means the struct was built by\n\t// a literal that bypassed them. Fail closed rather than dereference.\n\tif a.proposer == nil {\n\t\treturn errors.New(\"proposer is not set\")\n\t}\n\treturn a.proposer.Authorize(caller, title+\"_proposal\", handle, args...)\n}\n\n// String renders the contract path AND the proposer.\n//\n// The proposer half is security-relevant, not cosmetic: it is the only\n// thing distinguishing a gated authority from a wide-open one. Rendering\n// the path alone made\n//\n//\tNewContractAuthority(path, handler)                              // gated\n//\tNewRestrictedContractAuthority(path, handler, AutoAccept{})      // open to all\n//\n// byte-identical, so any consumer test asserting on this string — and\n// any on-chain reader inspecting it — was blind to the difference. A\n// consumer realm could have its authority swapped for a fully permissive\n// one and its assertions would stay green.\n//\n// \"contract-identity\" names the default installed by NewContractAuthority:\n// the contract at contractPath, and nobody else, may drive this authority.\n//\n// The proposer is rendered through canonicalAuthorityString, NOT by calling\n// a.proposer.String() directly. Authority is an open interface, so a foreign\n// impl can return any text it likes — including \"contract-identity\". That\n// made a fully permissive authority byte-identical to the gated default\n// again, defeating the very assertions this rendering exists to support.\n// Non-canonical impls are wrapped as custom_authority[...], mirroring what\n// Authorizer.String has always done at the outer level.\n//\n// Read the `contract=` half with care: it is load-bearing only for the\n// contract-identity default. With any other proposer it is a label —\n// see NewRestrictedContractAuthority.\nfunc (a *ContractAuthority) String() string {\n\treturn ufmt.Sprintf(\n\t\t\"contract_authority[contract=%s,proposer=%s]\",\n\t\ta.contractPath,\n\t\tcanonicalAuthorityString(a.proposer),\n\t)\n}\n\n// canonicalAuthorityString renders an Authority, wrapping any\n// implementation that is not one of this package's own as\n// custom_authority[...] so a foreign impl cannot impersonate a canonical\n// one by choosing its String() text. Shared by ContractAuthority.String\n// (for the nested proposer) and Authorizer.String (for the installed\n// authority).\nfunc canonicalAuthorityString(auth Authority) string {\n\tif auth == nil {\n\t\t// Only reachable via a struct literal that bypassed the\n\t\t// constructors; Authorize fails closed on the same condition.\n\t\treturn \"\u003cunset\u003e\"\n\t}\n\tswitch auth.(type) {\n\tcase *MemberAuthority, *ContractAuthority, *AutoAcceptAuthority,\n\t\t*droppedAuthority, *contractIdentityAuthority:\n\t\treturn auth.String()\n\tdefault:\n\t\treturn ufmt.Sprintf(\"custom_authority[%s]\", auth.String())\n\t}\n}\n\n// AutoAcceptAuthority implements an authority that accepts all actions\n// AutoAcceptAuthority is a simple authority that automatically accepts all\n// actions.\n// It can be used as a proposer authority to allow anyone to create proposals.\ntype AutoAcceptAuthority struct{}\n\nfunc NewAutoAcceptAuthority() *AutoAcceptAuthority {\n\treturn \u0026AutoAcceptAuthority{}\n}\n\nfunc (a *AutoAcceptAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\treturn action()\n}\n\nfunc (a *AutoAcceptAuthority) String() string {\n\treturn \"auto_accept_authority\"\n}\n\n// droppedAuthority implements an authority that denies all actions\ntype droppedAuthority struct{}\n\nfunc NewDroppedAuthority() Authority {\n\treturn \u0026droppedAuthority{}\n}\n\nfunc (a *droppedAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\treturn errors.New(\"dropped authority: all actions are denied\")\n}\n\nfunc (a *droppedAuthority) String() string {\n\treturn \"dropped_authority\"\n}\n"},{"name":"authz_test.gno","body":"package authz\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestNewWithCurrent(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tauth := NewWithMembers(cur.Address())\n\n\t// Check that the current authority is a MemberAuthority\n\tmemberAuth, ok := auth.Authority().(*MemberAuthority)\n\tuassert.True(t, ok, \"expected MemberAuthority\")\n\n\t// Check that the caller is a member\n\tuassert.True(t, memberAuth.Has(alice), \"caller should be a member\")\n\n\t// Check string representation\n\tuassert.True(t, strings.Contains(auth.String(), alice.String()))\n}\n\nfunc TestNewWithAuthority(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tmemberAuth := NewMemberAuthority(alice)\n\n\tauth := NewWithAuthority(memberAuth)\n\n\t// Check that the current authority is the one we provided\n\tuassert.True(t, auth.Authority() == memberAuth, \"expected provided authority\")\n}\n\nfunc TestAuthorizerAuthorize(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tauth := NewWithMembers(cur.Address())\n\n\t// Test successful action with args\n\texecuted := false\n\targs := []any{\"test_arg\", 123}\n\terr := auth.DoByCurrent(0, cur, \"test_action\", func() error {\n\t\texecuted = true\n\t\treturn nil\n\t}, args...)\n\n\tuassert.True(t, err == nil, \"expected no error\")\n\tuassert.True(t, executed, \"action should have been executed\")\n\n\t// Test unauthorized action with args\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bob\")))\n\n\texecuted = false\n\terr = auth.DoByCurrent(0, cur, \"test_action\", func() error {\n\t\texecuted = true\n\t\treturn nil\n\t}, \"unauthorized_arg\")\n\n\tuassert.True(t, err != nil, \"expected error\")\n\tuassert.False(t, executed, \"action should not have been executed\")\n\n\t// Test action returning error\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\texpectedErr := errors.New(\"test error\")\n\n\terr = auth.DoByCurrent(0, cur, \"test_action\", func() error {\n\t\treturn expectedErr\n\t})\n\n\tuassert.True(t, err == expectedErr, \"expected specific error\")\n}\n\nfunc TestAuthorizerTransfer(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tauth := NewWithMembers(cur.Address())\n\n\t// Test transfer to new member authority\n\tbob := testutils.TestAddress(\"bob\")\n\tnewAuth := NewMemberAuthority(bob)\n\n\tvar err error\n\tfunc(cur realm) { err = auth.Transfer(0, cur, newAuth) }(cross(cur))\n\tuassert.True(t, err == nil, \"expected no error\")\n\tuassert.True(t, auth.Authority() == newAuth, \"expected new authority\")\n\n\t// Test unauthorized transfer: principal is not a member of newAuth.\n\tcarol := testutils.TestAddress(\"carol\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\n\tfunc(cur realm) { err = auth.Transfer(0, cur, NewMemberAuthority(alice)) }(cross(cur))\n\tuassert.True(t, err != nil, \"expected error\")\n\n\t// Test transfer to contract authority — bob is the current authority.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tcontractAuth := NewContractAuthority(\"gno.land/r/test\", func(title string, action PrivilegedAction) error {\n\t\treturn action()\n\t})\n\n\tfunc(cur realm) { err = auth.Transfer(0, cur, contractAuth) }(cross(cur))\n\tuassert.True(t, err == nil, \"expected no error\")\n\tuassert.True(t, auth.Authority() == contractAuth, \"expected contract authority\")\n}\n\nfunc TestAuthorizerTransferChain(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// Create a chain of transfers\n\tauth := NewWithMembers(cur.Address())\n\n\t// First transfer to a new member authority\n\tbob := testutils.TestAddress(\"bob\")\n\tmemberAuth := NewMemberAuthority(bob)\n\n\tvar err error\n\tfunc(cur realm) { err = auth.Transfer(0, cur, memberAuth) }(cross(cur))\n\tuassert.True(t, err == nil, \"unexpected error in first transfer\")\n\n\t// Then transfer to a contract authority — bob is now the authority.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tcontractAuth := NewContractAuthority(\"gno.land/r/test\", func(title string, action PrivilegedAction) error {\n\t\treturn action()\n\t})\n\tfunc(cur realm) { err = auth.Transfer(0, cur, contractAuth) }(cross(cur))\n\tuassert.True(t, err == nil, \"unexpected error in second transfer\")\n\n\t// Finally transfer to an auto-accept authority. The authority is now\n\t// the contract authority, whose default proposer is the contract\n\t// itself, so the transfer's caller —\n\t// cur.Previous() — must be the contract. Set the outer realm to the\n\t// contract, then cross into a closure so cur.Previous() resolves to\n\t// it.\n\tautoAuth := NewAutoAcceptAuthority()\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\tfunc(cur realm) { err = auth.Transfer(0, cur, autoAuth) }(cross(cur))\n\tuassert.True(t, err == nil, \"unexpected error in final transfer\")\n\tuassert.True(t, auth.Authority() == autoAuth, \"expected auto-accept authority\")\n}\n\nfunc TestAuthorizerTransferUnauthorizedRejected(cur realm, t *testing.T) {\n\t// Regression for the address-parameter forgery: previously Transfer\n\t// took a caller-supplied `caller address` that an attacker realm could\n\t// set to the real owner. After the IsCurrent + rlm.Previous() fix, the\n\t// principal is the captured cur's previous and cannot be forged.\n\tadmin := testutils.TestAddress(\"admin\")\n\tattacker := testutils.TestAddress(\"attacker\")\n\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tauth := NewWithMembers(cur.Address()) // admin is the initial authority\n\n\tinitialAuth, ok := auth.Authority().(*MemberAuthority)\n\tuassert.True(t, ok)\n\tuassert.True(t, initialAuth.Has(admin))\n\tuassert.False(t, initialAuth.Has(attacker))\n\n\t// Attacker context: cur.Previous() inside the closure will be attacker.\n\ttesting.SetRealm(testing.NewUserRealm(attacker))\n\tattackerAuth := NewMemberAuthority(attacker)\n\tvar err error\n\tfunc(cur realm) { err = auth.Transfer(0, cur, attackerAuth) }(cross(cur))\n\n\tuassert.True(t, err != nil, \"attacker transfer must be rejected\")\n\n\t// Authority unchanged: still the initial admin-only MemberAuthority.\n\tfinalAuth, ok := auth.Authority().(*MemberAuthority)\n\tuassert.True(t, ok)\n\tuassert.True(t, finalAuth == initialAuth, \"authority must not have changed\")\n\tuassert.True(t, finalAuth.Has(admin))\n\tuassert.False(t, finalAuth.Has(attacker))\n}\n\nfunc TestAuthorizerWithDroppedAuthority(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tauth := NewWithMembers(cur.Address())\n\n\t// Transfer to dropped authority\n\tvar err error\n\tfunc(cur realm) { err = auth.Transfer(0, cur, NewDroppedAuthority()) }(cross(cur))\n\tuassert.True(t, err == nil, \"expected no error\")\n\n\t// Try to execute action\n\terr = auth.DoByCurrent(0, cur, \"test_action\", func() error {\n\t\treturn nil\n\t})\n\tuassert.True(t, err != nil, \"expected error from dropped authority\")\n\n\t// Try to transfer again\n\tfunc(cur realm) { err = auth.Transfer(0, cur, NewMemberAuthority(alice)) }(cross(cur))\n\tuassert.True(t, err != nil, \"expected error when transferring from dropped authority\")\n}\n\nfunc TestContractAuthorityHandlerExecutionOnce(cur realm, t *testing.T) {\n\tattempts := 0\n\texecuted := 0\n\n\tcontractAuth := NewContractAuthority(\"gno.land/r/test\", func(title string, action PrivilegedAction) error {\n\t\t// Try to execute the action twice in the same handler\n\t\tif err := action(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tattempts++\n\n\t\t// Second execution should fail\n\t\tif err := action(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tattempts++\n\t\treturn nil\n\t})\n\n\t// Set caller to contract address\n\tcodeRealm := testing.NewCodeRealm(\"gno.land/r/test\")\n\ttesting.SetRealm(codeRealm)\n\tcode := codeRealm.Address()\n\n\ttestArgs := []any{\"proposal_id\", 42, \"metadata\", map[string]string{\"key\": \"value\"}}\n\terr := contractAuth.Authorize(code, \"test_action\", func() error {\n\t\texecuted++\n\t\treturn nil\n\t}, testArgs...)\n\n\tuassert.True(t, err == nil, \"handler execution should succeed\")\n\tuassert.True(t, attempts == 2, \"handler should have attempted execution twice\")\n\tuassert.True(t, executed == 1, \"handler should have executed once\")\n}\n\nfunc TestContractAuthorityExecutionTwice(cur realm, t *testing.T) {\n\texecuted := 0\n\n\tcontractAuth := NewContractAuthority(\"gno.land/r/test\", func(title string, action PrivilegedAction) error {\n\t\treturn action()\n\t})\n\n\t// Set caller to contract address\n\tcodeRealm := testing.NewCodeRealm(\"gno.land/r/test\")\n\ttesting.SetRealm(codeRealm)\n\tcode := codeRealm.Address()\n\ttestArgs := []any{\"proposal_id\", 42, \"metadata\", map[string]string{\"key\": \"value\"}}\n\n\terr := contractAuth.Authorize(code, \"test_action\", func() error {\n\t\texecuted++\n\t\treturn nil\n\t}, testArgs...)\n\n\tuassert.True(t, err == nil, \"handler execution should succeed\")\n\tuassert.True(t, executed == 1, \"handler should have executed once\")\n\n\t// A new action, even with the same title, should be executed\n\terr = contractAuth.Authorize(code, \"test_action\", func() error {\n\t\texecuted++\n\t\treturn nil\n\t}, testArgs...)\n\n\tuassert.True(t, err == nil, \"handler execution should succeed\")\n\tuassert.True(t, executed == 2, \"handler should have executed twice\")\n}\n\nfunc TestContractAuthorityWithProposer(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tmemberAuth := NewMemberAuthority(alice)\n\n\thandlerCalled := false\n\tactionExecuted := false\n\n\tcontractAuth := NewRestrictedContractAuthority(\"gno.land/r/test\", func(title string, action PrivilegedAction) error {\n\t\thandlerCalled = true\n\t\t// Set caller to contract address before executing action\n\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\t\treturn action()\n\t}, memberAuth)\n\n\t// Test authorized member\n\ttestArgs := []any{\"proposal_metadata\", \"test value\"}\n\terr := contractAuth.Authorize(alice, \"test_action\", func() error {\n\t\tactionExecuted = true\n\t\treturn nil\n\t}, testArgs...)\n\n\tuassert.True(t, err == nil, \"authorized member should be able to propose\")\n\tuassert.True(t, handlerCalled, \"contract handler should be called\")\n\tuassert.True(t, actionExecuted, \"action should be executed\")\n\n\t// Reset flags for unauthorized test\n\thandlerCalled = false\n\tactionExecuted = false\n\n\t// Test unauthorized proposer\n\tbob := testutils.TestAddress(\"bob\")\n\terr = contractAuth.Authorize(bob, \"test_action\", func() error {\n\t\tactionExecuted = true\n\t\treturn nil\n\t}, testArgs...)\n\n\tuassert.True(t, err != nil, \"unauthorized member should not be able to propose\")\n\tuassert.False(t, handlerCalled, \"contract handler should not be called for unauthorized proposer\")\n\tuassert.False(t, actionExecuted, \"action should not be executed for unauthorized proposer\")\n}\n\nfunc TestAutoAcceptAuthority(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tauth := NewAutoAcceptAuthority()\n\n\t// Test that any action is authorized\n\texecuted := false\n\terr := auth.Authorize(alice, \"test_action\", func() error {\n\t\texecuted = true\n\t\treturn nil\n\t})\n\n\tuassert.True(t, err == nil, \"auto-accept should not return error\")\n\tuassert.True(t, executed, \"action should have been executed\")\n\n\t// Test with different caller\n\trandom := testutils.TestAddress(\"random\")\n\texecuted = false\n\terr = auth.Authorize(random, \"test_action\", func() error {\n\t\texecuted = true\n\t\treturn nil\n\t})\n\n\tuassert.True(t, err == nil, \"auto-accept should not care about caller\")\n\tuassert.True(t, executed, \"action should have been executed\")\n}\n\nfunc TestAutoAcceptAuthorityWithArgs(cur realm, t *testing.T) {\n\tauth := NewAutoAcceptAuthority()\n\tanyuser := testutils.TestAddress(\"anyuser\")\n\n\t// Test that any action is authorized with args\n\texecuted := false\n\ttestArgs := []any{\"arg1\", 42, \"arg3\"}\n\terr := auth.Authorize(anyuser, \"test_action\", func() error {\n\t\texecuted = true\n\t\treturn nil\n\t}, testArgs...)\n\n\tuassert.True(t, err == nil, \"auto-accept should not return error\")\n\tuassert.True(t, executed, \"action should have been executed\")\n}\n\nfunc TestMemberAuthorityMultipleMembers(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tcarol := testutils.TestAddress(\"carol\")\n\n\t// Create authority with multiple members\n\tauth := NewMemberAuthority(alice, bob)\n\n\t// Test that both members can execute actions\n\tfor _, member := range []address{alice, bob} {\n\t\terr := auth.Authorize(member, \"test_action\", func() error {\n\t\t\treturn nil\n\t\t})\n\t\tuassert.True(t, err == nil, \"member should be authorized\")\n\t}\n\n\t// Test that non-member cannot execute\n\terr := auth.Authorize(carol, \"test_action\", func() error {\n\t\treturn nil\n\t})\n\tuassert.True(t, err != nil, \"non-member should not be authorized\")\n\n\t// Verify membership through the public API: the v0 Tree() escape hatch\n\t// is intentionally absent here, so the backing store never leaks.\n\tuassert.True(t, auth.Has(alice), \"alice should be a member\")\n\tuassert.True(t, auth.Has(bob), \"bob should be a member\")\n\tuassert.False(t, auth.Has(carol), \"carol should not be a member\")\n}\n\nfunc TestAuthorizerCurrentNeverNil(cur realm, t *testing.T) {\n\tauth := NewWithMembers(cur.Address())\n\n\t// Authority should never be nil after initialization\n\tuassert.True(t, auth.Authority() != nil, \"current authority should not be nil\")\n\n\t// Authority should not be nil after transfer\n\tvar err error\n\tfunc(cur realm) { err = auth.Transfer(0, cur, NewAutoAcceptAuthority()) }(cross(cur))\n\tuassert.True(t, err == nil, \"transfer should succeed\")\n\tuassert.True(t, auth.Authority() != nil, \"current authority should not be nil after transfer\")\n}\n\nfunc TestContractAuthorityValidation(cur realm, t *testing.T) {\n\thandler := func(title string, action PrivilegedAction) error {\n\t\treturn nil\n\t}\n\n\t// Empty path panics (consistent with NewRestrictedContractAuthority).\n\tuassert.PanicsWithMessage(t, cur, \"contract path cannot be empty\", func() {\n\t\tNewContractAuthority(\"\", handler)\n\t})\n\n\t// A nil handler panics at CONSTRUCTION rather than being tolerated and\n\t// surfaced at Authorize time. Tolerating it produced a permanent brick:\n\t// see TestNilHandlerWouldBeUnrotatable below.\n\tuassert.PanicsWithMessage(t, cur, \"contract handler cannot be nil\", func() {\n\t\tNewContractAuthority(\"gno.land/r/test\", nil)\n\t})\n\n\t// The Authorize-time guard stays for a zero-value ContractAuthority,\n\t// which the constructors cannot produce but a struct literal can.\n\tcode := testing.NewCodeRealm(\"gno.land/r/test\").Address()\n\tzero := \u0026ContractAuthority{contractPath: \"gno.land/r/test\", contractAddr: code}\n\terr := zero.Authorize(code, \"test\", func() error {\n\t\treturn nil\n\t})\n\tuassert.True(t, err != nil, \"nil handler authority should fail to authorize\")\n\n\t// Test valid configuration\n\tcontractAuth := NewContractAuthority(\"gno.land/r/test\", handler)\n\terr = contractAuth.Authorize(code, \"test\", func() error {\n\t\treturn nil\n\t})\n\tuassert.True(t, err == nil, \"valid contract authority should authorize successfully\")\n}\n\nfunc TestAuthorizerString(cur realm, t *testing.T) {\n\tauth := NewWithMembers(cur.Address())\n\taddr := cur.Address()\n\n\t// Test initial string representation\n\tstr := auth.String()\n\tuassert.Equal(t, str, \"member_authority[\"+string(addr)+\"]\")\n\n\t// Test string after transfer — caller is the current member (cur).\n\tautoAuth := NewAutoAcceptAuthority()\n\tvar err error\n\tfunc(cur realm) { err = auth.Transfer(0, cur, autoAuth) }(cross(cur))\n\tuassert.True(t, err == nil, \"transfer should succeed\")\n\tstr = auth.String()\n\tuassert.Equal(t, str, \"auto_accept_authority\")\n\n\t// Test custom authority — auto-accept lets anyone transfer.\n\tcustomAuth := \u0026mockAuthority{}\n\tfunc(cur realm) { err = auth.Transfer(0, cur, customAuth) }(cross(cur))\n\tuassert.True(t, err == nil, \"transfer should succeed\")\n\tstr = auth.String()\n\tuassert.Equal(t, str, \"custom_authority[mock]\")\n}\n\ntype mockAuthority struct{}\n\nfunc (c mockAuthority) String() string { return \"mock\" }\nfunc (a mockAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\t// autoaccept\n\treturn action()\n}\n\nfunc TestAuthorityString(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\n\t// MemberAuthority\n\tmemberAuth := NewMemberAuthority(alice)\n\tmemberStr := memberAuth.String()\n\texpectedMemberStr := \"member_authority[g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh]\"\n\tuassert.Equal(t, memberStr, expectedMemberStr)\n\n\t// ContractAuthority — the proposer is rendered, not just the path.\n\t// Without it the two constructors below are indistinguishable, which\n\t// is what made consumer-level assertions on this string blind to an\n\t// authority being swapped for a wide-open one.\n\tcontractAuth := NewContractAuthority(\"gno.land/r/test\", func(title string, action PrivilegedAction) error { return nil })\n\tcontractStr := contractAuth.String()\n\texpectedContractStr := \"contract_authority[contract=gno.land/r/test,proposer=contract-identity]\"\n\tuassert.Equal(t, contractStr, expectedContractStr)\n\n\t// Same path, same handler, explicit open proposer — must render\n\t// differently from the gated default above.\n\topenAuth := NewRestrictedContractAuthority(\n\t\t\"gno.land/r/test\",\n\t\tfunc(title string, action PrivilegedAction) error { return nil },\n\t\tNewAutoAcceptAuthority(),\n\t)\n\tuassert.Equal(t,\n\t\t\"contract_authority[contract=gno.land/r/test,proposer=auto_accept_authority]\",\n\t\topenAuth.String())\n\tuassert.NotEqual(t, contractStr, openAuth.String())\n\n\t// AutoAcceptAuthority\n\tautoAuth := NewAutoAcceptAuthority()\n\tautoStr := autoAuth.String()\n\texpectedAutoStr := \"auto_accept_authority\"\n\tuassert.Equal(t, autoStr, expectedAutoStr)\n\n\t// DroppedAuthority\n\tdroppedAuth := NewDroppedAuthority()\n\tdroppedStr := droppedAuth.String()\n\texpectedDroppedStr := \"dropped_authority\"\n\tuassert.Equal(t, droppedStr, expectedDroppedStr)\n}\n\n// TestContractAuthorityUnauthorizedCaller verifies the\n// fix: a ContractAuthority's default proposer is the contract itself, so\n// any other caller is rejected UPSTREAM (at the proposer) and the handler\n// and privileged action never run. Previously the default proposer was\n// AutoAcceptAuthority, and the only guard was a handler-side\n// `unsafe.CurrentRealm() == contractAddr` check — which was bypassable\n// and which many consumers (e.g. r/gnops/valopers) omitted entirely,\n// leaving no caller check at all.\nfunc TestContractAuthorityUnauthorizedCaller(cur realm, t *testing.T) {\n\tcontractPath := \"gno.land/r/testcontract\"\n\tcontractAddr := chain.PackageAddress(contractPath)\n\tunauthorizedAddr := testutils.TestAddress(\"unauthorized\")\n\n\t// A permissive handler that simply runs the action — the realistic\n\t// shape a consumer registers. The package, not the handler, must be\n\t// the one that rejects an unauthorized caller.\n\thandlerExecuted := false\n\tcontractHandler := func(title string, action PrivilegedAction) error {\n\t\thandlerExecuted = true\n\t\treturn action()\n\t}\n\tcontractAuth := NewContractAuthority(contractPath, contractHandler)\n\n\tactionExecuted := false\n\tprivilegedAction := func() error {\n\t\tactionExecuted = true\n\t\treturn nil\n\t}\n\n\t// 1. Unauthorized caller: rejected by the contract-identity proposer\n\t// before the handler or the action can run.\n\terr := contractAuth.Authorize(unauthorizedAddr, \"test_action\", privilegedAction)\n\tuassert.Error(t, err, \"unauthorized caller must be rejected\")\n\tuassert.ErrorContains(t, err, \"unauthorized\", \"rejection must come from the contract-identity proposer\")\n\tuassert.False(t, handlerExecuted, \"handler must not run for an unauthorized caller\")\n\tuassert.False(t, actionExecuted, \"privileged action must not run for an unauthorized caller\")\n\n\t// 2. The contract itself is authorized.\n\terr = contractAuth.Authorize(contractAddr, \"test_action\", privilegedAction)\n\tuassert.NoError(t, err, \"the contract itself must be authorized\")\n\tuassert.True(t, handlerExecuted, \"handler must run when the contract is the caller\")\n\tuassert.True(t, actionExecuted, \"privileged action must run when the contract is the caller\")\n}\n\n// TestAuthorizerDoByPrevious verifies the \"calling realm authorizes\"\n// pattern: a function (the inner crossing closure) invokes\n// DoByPrevious so the authority check sees cur.Previous() — the realm\n// that crossed into it — not the function's own realm.\n//\n// Each scenario crosses into the inner closure via cross(cur) after\n// SetRealm — inside the closure, cur is the fresh live cur and\n// cur.Previous() is the SetRealm'd outer realm. This is the only way\n// to exercise DoByPrevious correctly under the IsCurrent guard, which\n// rejects synthetic realm values (testing.MakeRealm) and stored\n// stale captures.\nfunc TestAuthorizerDoByPrevious(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\tauth := NewWithMembers(alice)\n\n\t// alice (member) crosses in: cur.Previous() == alice inside the inner closure.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\texecuted := false\n\targs := []any{\"test_arg\", 123}\n\tfunc(cur realm) {\n\t\terr := auth.DoByPrevious(0, cur, \"test_action\", func() error {\n\t\t\texecuted = true\n\t\t\treturn nil\n\t\t}, args...)\n\t\tuassert.NoError(t, err, \"expected no error\")\n\t\tuassert.True(t, executed, \"action should have been executed\")\n\t}(cross(cur))\n\n\texpectedErr := errors.New(\"test error\")\n\tfunc(cur realm) {\n\t\terr := auth.DoByPrevious(0, cur, \"test_action\", func() error {\n\t\t\treturn expectedErr\n\t\t})\n\t\tuassert.ErrorContains(t, err, expectedErr.Error(), \"expected error\")\n\t}(cross(cur))\n\n\t// bob (not a member) crosses in: Authorize must reject.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\texecuted = false\n\tfunc(cur realm) {\n\t\terr := auth.DoByPrevious(0, cur, \"test_action\", func() error {\n\t\t\texecuted = true\n\t\t\treturn nil\n\t\t}, \"unauthorized_arg\")\n\t\tuassert.ErrorContains(t, err, \"unauthorized\", \"expected error\")\n\t\tuassert.False(t, executed, \"action should not have been executed\")\n\t}(cross(cur))\n}\n\n// ---------------------------------------------------------------------------\n// Contract-identity gate: regression suite.\n//\n// A plain NewContractAuthority now defaults its proposer to the contract\n// ITSELF (MemberAuthority of the contract's own package address) instead of\n// AutoAcceptAuthority. These tests pin the security contract: only the\n// contract may drive privileged actions, an external caller can neither\n// drive nor Transfer the authority, the contract can still rotate its own\n// authority, and the escape hatch for a genuinely-open proposer still\n// exists.\n// ---------------------------------------------------------------------------\n\n// The default proposer accepts the contract itself and rejects everyone\n// else, before the handler or action can run.\nfunc TestDefaultProposerIsContractOnly(cur realm, t *testing.T) {\n\tconst path = \"gno.land/r/defcontract\"\n\tcontractAddr := chain.PackageAddress(path)\n\n\tran := 0\n\tca := NewContractAuthority(path, func(_ string, action PrivilegedAction) error {\n\t\treturn action()\n\t})\n\n\t// The contract itself: authorized.\n\terr := ca.Authorize(contractAddr, \"action\", func() error { ran++; return nil })\n\tuassert.NoError(t, err, \"the contract itself must be authorized\")\n\n\t// Anyone else: rejected at the proposer, action never runs.\n\toutsider := testutils.TestAddress(\"outsider\")\n\terr = ca.Authorize(outsider, \"action\", func() error { ran++; return nil })\n\tuassert.Error(t, err, \"a non-contract caller must be rejected\")\n\tuassert.ErrorContains(t, err, \"unauthorized\", \"rejection must come from the contract-identity proposer\")\n\n\tuassert.Equal(t, 1, ran, \"only the contract's action must have run\")\n}\n\n// An external realm that holds another realm's Authorizer cannot Transfer\n// it. The caller derived under IsCurrent is that external realm, not the\n// contract, so the rotation is rejected and the authority is left intact.\nfunc TestExternalTransferRejected(cur realm, t *testing.T) {\n\tauthorizer := NewWithAuthority(\n\t\tNewContractAuthority(\"gno.land/r/victim\", func(_ string, action PrivilegedAction) error {\n\t\t\treturn action()\n\t\t}),\n\t)\n\n\tattacker := testutils.TestAddress(\"attacker\")\n\ttesting.SetRealm(testing.NewUserRealm(attacker))\n\n\tvar err error\n\tfunc(cur realm) { err = authorizer.Transfer(0, cur, NewDroppedAuthority()) }(cross(cur))\n\n\tuassert.Error(t, err, \"external Transfer must be rejected\")\n\tuassert.ErrorContains(t, err, \"unauthorized\", \"rejection must come from the contract-identity proposer\")\n\n\t_, ok := authorizer.Authority().(*ContractAuthority)\n\tuassert.True(t, ok, \"authority must be unchanged after a rejected rotation\")\n}\n\n// Same shape via DoByPrevious (a privileged action instead of a\n// Transfer): an external caller is rejected and the action never runs.\nfunc TestExternalDoByPreviousRejected(cur realm, t *testing.T) {\n\tauthorizer := NewWithAuthority(\n\t\tNewContractAuthority(\"gno.land/r/victim2\", func(_ string, action PrivilegedAction) error {\n\t\t\treturn action()\n\t\t}),\n\t)\n\n\tran := false\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"randomuser\")))\n\tvar err error\n\tfunc(cur realm) {\n\t\terr = authorizer.DoByPrevious(0, cur, \"privileged\", func() error { ran = true; return nil })\n\t}(cross(cur))\n\n\tuassert.Error(t, err, \"external DoByPrevious must be rejected\")\n\tuassert.False(t, ran, \"privileged action must not run for an external caller\")\n}\n\n// The contract-identity model does NOT lock out legitimate governance: the\n// contract can still rotate (Transfer) its own authority when the transfer\n// is driven with the contract as the previous realm (caller == contractAddr).\nfunc TestContractCanRotateItsOwnAuthority(cur realm, t *testing.T) {\n\tconst path = \"gno.land/r/selfgov\"\n\tauthorizer := NewWithAuthority(\n\t\tNewContractAuthority(path, func(_ string, action PrivilegedAction) error {\n\t\t\treturn action()\n\t\t}),\n\t)\n\n\t// Drive the transfer with the contract as the caller: set the outer\n\t// realm to the contract, then cross into a closure so cur.Previous()\n\t// resolves to the contract.\n\ttesting.SetRealm(testing.NewCodeRealm(path))\n\tvar err error\n\tfunc(cur realm) { err = authorizer.Transfer(0, cur, NewAutoAcceptAuthority()) }(cross(cur))\n\n\tuassert.NoError(t, err, \"the contract itself must be able to rotate its authority\")\n\t_, ok := authorizer.Authority().(*AutoAcceptAuthority)\n\tuassert.True(t, ok, \"authority should have rotated to auto-accept\")\n}\n\n// Boundary test: the raw Authority.Authorize takes `caller` as a plain\n// parameter, so a holder of the raw Authority can forge caller ==\n// contractAddr. This proves that even so, a forged-caller raw Authorize\n// only runs the action the caller itself supplies — it CANNOT mutate an\n// Authorizer's installed authority, because the Transfer mutation lives\n// only inside Authorizer.Transfer (which derives caller non-forgeably).\n// The lesson encoded here: consumers must reach a ContractAuthority through\n// the Authorizer wrapper and must not hand out the raw Authority.\n//\n// WHAT THIS TEST DOES AND DOES NOT FREEZE. Only the final assertion is a\n// security property. That raw Authorize ACCEPTS a forged caller is\n// current behaviour, not a guarantee — it is the consequence of `caller`\n// being a parameter on an exported interface method. If someone later\n// hardens that path so raw Authorize stops accepting a forged caller,\n// this test going red means the test is stale, NOT that the change is\n// wrong: delete the two intermediate assertions and keep the last one.\n// (Recorded because asserting NoError here reads like the forgeability\n// is wanted. It is tolerated, and only because of what follows.)\nfunc TestForgedCallerCannotTransfer(cur realm, t *testing.T) {\n\tconst path = \"gno.land/r/boundary\"\n\tcontractAddr := chain.PackageAddress(path)\n\n\tauthorizer := NewWithAuthority(\n\t\tNewContractAuthority(path, func(_ string, action PrivilegedAction) error {\n\t\t\treturn action()\n\t\t}),\n\t)\n\n\t// Attacker obtains the raw Authority and forges the contract as caller.\n\tattackerRan := false\n\terr := authorizer.Authority().Authorize(contractAddr, \"transfer_authority\", func() error {\n\t\tattackerRan = true\n\t\treturn nil\n\t})\n\n\t// Current behaviour, documented above — not a property to preserve.\n\tuassert.NoError(t, err, \"raw Authorize currently accepts a forged caller (see comment)\")\n\tuassert.True(t, attackerRan, \"only the caller's own inert closure runs\")\n\n\t// THE property: the installed authority is UNCHANGED. Raw Authorize\n\t// cannot perform a Transfer — the mutation closure is private to\n\t// Authorizer.Transfer, which derives caller non-forgeably.\n\t_, ok := authorizer.Authority().(*ContractAuthority)\n\tuassert.True(t, ok, \"raw Authorize must not be able to transfer the authority\")\n}\n\n// Two contract authorities on different paths never cross-authorize.\nfunc TestContractPathIsolation(cur realm, t *testing.T) {\n\tcaB := NewContractAuthority(\"gno.land/r/pathb\", func(_ string, action PrivilegedAction) error {\n\t\treturn action()\n\t})\n\taddrA := chain.PackageAddress(\"gno.land/r/patha\")\n\n\tran := false\n\terr := caB.Authorize(addrA, \"action\", func() error { ran = true; return nil })\n\tuassert.Error(t, err, \"contract A must not authorize contract B's authority\")\n\tuassert.False(t, ran, \"action must not run across contract identities\")\n}\n\n// Escape hatch: a consumer that genuinely wants open proposals can still\n// opt in via NewRestrictedContractAuthority with an AutoAcceptAuthority\n// proposer — restoring the pre-fix \"anyone can propose\" behavior explicitly.\nfunc TestRestrictedAutoAcceptEscapeHatch(cur realm, t *testing.T) {\n\tca := NewRestrictedContractAuthority(\n\t\t\"gno.land/r/open\",\n\t\tfunc(_ string, action PrivilegedAction) error { return action() },\n\t\tNewAutoAcceptAuthority(),\n\t)\n\n\tran := false\n\terr := ca.Authorize(testutils.TestAddress(\"anyone\"), \"action\", func() error { ran = true; return nil })\n\tuassert.NoError(t, err, \"an explicit AutoAccept proposer restores open proposals\")\n\tuassert.True(t, ran, \"action must run under an explicit AutoAccept proposer\")\n}\n\n// Why the nil handler is now rejected at construction rather than\n// tolerated: Authorize checks contractHandler == nil BEFORE consulting the\n// proposer, and Transfer routes through Authorize, so there is no rotation\n// path out. It is a permanent brick reachable by an ordinary deployer\n// typo -- the same bricked-governance failure mode, by accident.\n//\n// The zero value is used because the constructor no longer allows it.\nfunc TestNilHandlerWouldBeUnrotatable(cur realm, t *testing.T) {\n\tconst path = \"gno.land/r/nilbrick\"\n\taddr := chain.PackageAddress(path)\n\tauthorizer := NewWithAuthority(\u0026ContractAuthority{\n\t\tcontractPath: path,\n\t\tcontractAddr: addr,\n\t\t// Both handler and proposer are nil: a struct literal is the only\n\t\t// way to reach this, and Authorize fails closed on either.\n\t})\n\n\t// Drive the rotation as the contract itself -- the only principal the\n\t// default proposer accepts. If this cannot escape, nobody can.\n\ttesting.SetRealm(testing.NewCodeRealm(path))\n\tvar err error\n\tfunc(cur realm) { err = authorizer.Transfer(0, cur, NewAutoAcceptAuthority()) }(cross(cur))\n\n\tuassert.Error(t, err, \"a nil-handler authority must not be silently rotatable\")\n\t_, stuck := authorizer.Authority().(*ContractAuthority)\n\tuassert.True(t, stuck, \"nil-handler authority is unrotatable -- hence rejected at construction\")\n}\n\n// A crossing closure declared HERE carries this package's identity, not\n// the contract path's -- testing.SetRealm does not change that, because\n// the VM mints a crossing frame's realm from the callee's declaring\n// package. So the DoByCurrent shape that Example_contractAuthority teaches\n// cannot be exercised from inside this package at all; it needs a real\n// realm. It is covered by filetests/z_contract_authority_shape_filetest.gno.\n//\n// The same property is why an exported crossing closure leaks a realm's\n// authority to any caller -- it is one mechanism seen from two\n// sides. This test pins the half that is observable here: an unrelated\n// package's frame is rejected.\nfunc TestForeignFrameCannotDriveContractAuthority(cur realm, t *testing.T) {\n\tauth := NewWithAuthority(NewContractAuthority(\"gno.land/r/demo/dao\", mockDAOHandler))\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/example\"))\n\tran := false\n\tvar err error\n\tfunc(cur realm) {\n\t\terr = auth.DoByCurrent(0, cur, \"update_params\", func() error {\n\t\t\tran = true\n\t\t\treturn nil\n\t\t})\n\t}(cross(cur))\n\n\tuassert.Error(t, err, \"a frame from another package must not drive this authority\")\n\tuassert.False(t, ran, \"the action must not run\")\n}\n\n// A malformed contract path binds the authority to an address no realm can\n// ever present. Because Transfer routes through the same gate, such an\n// authority is also unrotatable: a permanent brick, and the same failure\n// mode the nil-handler panic exists to prevent. Rejected at construction.\n//\n// Pre-fix these all constructed happily; the AutoAccept default made the\n// typo harmless (and insecure), so nothing complained.\nfunc TestContractPathValidationRejectsMalformed(cur realm, t *testing.T) {\n\thandler := func(_ string, action PrivilegedAction) error { return action() }\n\n\tfor _, path := range []string{\n\t\t\"gno.land/r/gov/dao \",  // trailing space\n\t\t\" gno.land/r/gov/dao\",  // leading space\n\t\t\"gno.land/r/gov/dao\\n\", // trailing newline\n\t\t\"gno.land/r/gov dao\",   // embedded space\n\t\t\" \",\n\t\t\"not a path\",\n\t\t\"GNO.LAND/R/GOV/DAO\", // uppercase: not a legal gno pkgpath\n\t\t\"gno.land//r/gov/dao\",\n\t\t\"gno.land/r/gov/dao/\",\n\t\t\"singlesegment\",\n\t} {\n\t\tuassert.PanicsContains(t, cur, \"contract path\", func() {\n\t\t\tNewContractAuthority(path, handler)\n\t\t}, \"malformed path must be rejected: \"+path)\n\t\tuassert.PanicsContains(t, cur, \"contract path\", func() {\n\t\t\tNewRestrictedContractAuthority(path, handler, NewAutoAcceptAuthority())\n\t\t}, \"malformed path must be rejected by the restricted ctor too: \"+path)\n\t}\n\n\t// Real paths still construct, including dashes, digits, underscores and\n\t// version suffixes.\n\tfor _, path := range []string{\n\t\t\"gno.land/r/gov/dao\",\n\t\t\"gno.land/r/gnops/valopers\",\n\t\t\"gno.land/p/moul/authz/v0\",\n\t\t\"gno.land/r/sys/validators/v0\",\n\t\t\"gno.land/r/some-user/my_pkg2\",\n\t} {\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tNewContractAuthority(path, handler)\n\t\t}, \"legitimate path must construct: \"+path)\n\t}\n}\n\n// spoofProposer is a wide-open Authority that LIES in String(), returning\n// the same text the canonical contract-identity default renders.\ntype spoofProposer struct{}\n\nfunc (spoofProposer) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {\n\treturn action()\n}\n\nfunc (spoofProposer) String() string { return \"contract-identity\" }\n\n// A foreign proposer must not be able to impersonate the gated default in\n// the rendered description. ContractAuthority.String() is promoted by this\n// package as the one surface distinguishing a gated authority from a\n// wide-open one, and consumers assert on it (r/gnops/valopers.Auth()). An\n// impl that chooses its own String() text defeated that: a fully permissive\n// authority rendered byte-identical to the default, so every string-based\n// configuration pin stayed green while the gate was gone.\nfunc TestSpoofedProposerCannotImpersonateContractIdentity(cur realm, t *testing.T) {\n\tconst path = \"gno.land/r/spoofprobe\"\n\thandler := func(_ string, action PrivilegedAction) error { return action() }\n\toutsider := chain.PackageAddress(\"gno.land/r/outsider\")\n\n\tgated := NewContractAuthority(path, handler)\n\tspoof := NewRestrictedContractAuthority(path, handler, spoofProposer{})\n\n\t// The behavioural difference the strings must reflect.\n\tuassert.Error(t, gated.Authorize(outsider, \"t\", func() error { return nil }),\n\t\t\"the gated default must reject an outsider\")\n\tuassert.NoError(t, spoof.Authorize(outsider, \"t\", func() error { return nil }),\n\t\t\"the spoofing proposer is wide open -- that is the point of the test\")\n\n\t// ...and they do.\n\tuassert.NotEqual(t, gated.String(), spoof.String(),\n\t\t\"a wide-open authority must not render identically to the gated default\")\n\tuassert.Equal(t,\n\t\t\"contract_authority[contract=\"+path+\",proposer=contract-identity]\",\n\t\tgated.String())\n\tuassert.Equal(t,\n\t\t\"contract_authority[contract=\"+path+\",proposer=custom_authority[contract-identity]]\",\n\t\tspoof.String(),\n\t\t\"a non-canonical proposer must be wrapped, not trusted to name itself\")\n\n\t// Same guarantee through the Authorizer wrapper, which is the shape a\n\t// consumer realm actually exposes.\n\tuassert.NotEqual(t,\n\t\tNewWithAuthority(gated).String(),\n\t\tNewWithAuthority(spoof).String())\n}\n\n// An explicit proposer REPLACES the contract-identity gate; it does not add\n// to it. NewRestrictedContractAuthority(govdaoPath, h, member(alice)) means\n// \"alice, and not GovDAO\" -- contractAddr is never consulted. Pinned because\n// the rendered string reads like a conjunction and the old godoc said\n// \"widen\", so a consumer could reasonably have expected \"both\".\nfunc TestExplicitProposerReplacesIdentityGate(cur realm, t *testing.T) {\n\tconst path = \"gno.land/r/gov/dao\"\n\thandler := func(_ string, action PrivilegedAction) error { return action() }\n\tgovdao := chain.PackageAddress(path)\n\talice := chain.PackageAddress(\"gno.land/r/alice\")\n\n\tgated := NewContractAuthority(path, handler)\n\treplaced := NewRestrictedContractAuthority(path, handler, NewMemberAuthority(alice))\n\n\tuassert.NoError(t, gated.Authorize(govdao, \"x\", func() error { return nil }),\n\t\t\"the default gate accepts the bound contract\")\n\tuassert.Error(t, gated.Authorize(alice, \"x\", func() error { return nil }),\n\t\t\"the default gate rejects everyone else\")\n\n\tuassert.Error(t, replaced.Authorize(govdao, \"x\", func() error { return nil }),\n\t\t\"an explicit proposer REPLACES the identity gate: govdao is no longer accepted\")\n\tuassert.NoError(t, replaced.Authorize(alice, \"x\", func() error { return nil }),\n\t\t\"only the explicit proposer's principal is accepted\")\n}\n"},{"name":"example_test.gno","body":"package authz\n\n// Example_basic demonstrates initializing and using a basic member authority\nfunc Example_basic(cur realm) {\n\t// Initialize from the EOA caller (e.g. in init(cur realm) of a realm\n\t// being deployed): caller passes the EOA address; the realm itself\n\t// is responsible for verifying the caller is an EOA when needed.\n\tauth := NewWithMembers(cur.Previous().Address())\n\n\t// Authorize with DoByPrevious, NOT DoByCurrent: the member set holds\n\t// cur.Previous().Address(), and DoByCurrent would present\n\t// cur.Address() -- this realm -- which is never in that set, so the\n\t// action would silently never run. Seeding and authorizing must read\n\t// the SAME side of the frame. Matches the package Quick Start.\n\tif err := auth.DoByPrevious(0, cur, \"update_config\", func() error {\n\t\t// config = newValue\n\t\treturn nil\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Example_addingMembers demonstrates how to add new members to a member authority\nfunc Example_addingMembers(cur realm) {\n\t// Seed with Previous(), not Address(): MemberAuthority.AddMember\n\t// derives its principal as rlm.Previous().Address(), so a set holding\n\t// only cur.Address() authorizes nobody and the AddMember below fails.\n\tauth := NewWithMembers(cur.Previous().Address())\n\n\t// Add a new member to the authority\n\tmemberAuth := auth.Authority().(*MemberAuthority)\n\tif err := memberAuth.AddMember(0, cur, address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Example_contractAuthority demonstrates a contract-based authority.\n//\n// A plain NewContractAuthority accepts exactly one principal:\n// chain.PackageAddress(path). Point `path` at the principal you want to\n// ASSERT -- normally the governance realm that will drive the action --\n// and authorize with DoByPrevious, so the comparison is against whoever\n// crossed in. See NewContractAuthority's godoc.\n//\n// Do NOT pair a plain ContractAuthority on your OWN path with\n// DoByCurrent. rlm.Address() inside any crossing frame of a realm is\n// unconditionally PackageAddress(ownPath), so that gate compares the\n// realm to itself, can never reject, and any exported crossing\n// entrypoint next to it becomes an unauthenticated privileged write --\n// the self-comparing-gate shape. Own-path is right only when something\n// OTHER than your own frame supplies the caller, i.e. DoByPrevious from\n// a realm you deliberately let call in, or Transfer.\n//\n// Nothing here catches a wrong pairing: Example_* functions that take\n// any parameter are never executed by `gno test` (see isExampleFunc in\n// gnovm/pkg/test/test.go -- it rejects on method receiver, parameters or\n// results; \"// Output:\" plays no part in the predicate, so adding one\n// does NOT make the body run), so a sentinel panic in here still reports\n// ok. filetests/z_contract_authority_shape_filetest.gno executes the\n// gate from a real realm instead.\n//\n// Corollary of the identity gate: do not export anything that returns a\n// crossing closure of this realm, or callers inherit the authority.\nfunc Example_contractAuthority(cur realm) {\n\t// This realm asserts \"the governance realm governs me\".\n\tauth := NewWithAuthority(\n\t\tNewContractAuthority(\n\t\t\t\"gno.land/r/gov/dao\", // the principal asserted, not this realm\n\t\t\tmockDAOHandler,       // defined elsewhere for example\n\t\t),\n\t)\n\n\t// Authorized only when gno.land/r/gov/dao is the realm that crossed\n\t// into this function -- in practice, when a passed proposal executes.\n\t// Every other caller presents its own address here and is refused,\n\t// which is the whole point of the gate. Never discard this error.\n\tif err := auth.DoByPrevious(0, cur, \"update_params\", func() error {\n\t\treturn nil\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Example_restrictedContractAuthority demonstrates a contract authority with member-only proposals\nfunc Example_restrictedContractAuthority(cur realm) {\n\t// Initialize member authority for proposers\n\tproposerAuth := NewMemberAuthority(\n\t\taddress(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"), // admin1\n\t\taddress(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\"), // admin2\n\t)\n\n\t// Create contract authority with restricted proposers\n\tauth := NewWithAuthority(\n\t\tNewRestrictedContractAuthority(\n\t\t\t\"gno.land/r/demo/dao\",\n\t\t\tmockDAOHandler,\n\t\t\tproposerAuth,\n\t\t),\n\t)\n\n\t// Only members can propose, and contract must approve.\n\t//\n\t// DoByPrevious, not DoByCurrent: the proposer set holds EOA\n\t// addresses, and DoByCurrent would present this realm's own address,\n\t// which is in no member set -- the proposer would reject and the\n\t// action would silently never run.\n\tif err := auth.DoByPrevious(0, cur, \"update_params\", func() error {\n\t\t// Executes after:\n\t\t// 1. Proposer initiates\n\t\t// 2. DAO approves\n\t\treturn nil\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Example_switchingAuthority demonstrates switching from member to contract\n// authority.\n//\n// Note what a plain ContractAuthority on a FOREIGN path means after the\n// transfer: this realm loses the ability to take the authority back, and\n// DoByCurrent against it is dead. It is NOT a one-way door in the\n// stronger sense an earlier draft implied — the foreign realm can still\n// drive and rotate it via Previous() once it crosses in, which is the\n// intended async-DAO shape. What is given up is the original owner's\n// claim, not the authority's mutability. (The ADR for this change states\n// the same thing; keep the two in step.) To keep the authority here\n// while letting others propose, transfer to\n// NewRestrictedContractAuthority(ownPath, handler, proposerAuth)\n// instead.\nfunc Example_switchingAuthority(cur realm) {\n\t// Start with member authority.\n\t//\n\t// Seed the member set with Previous(), not Address(): Transfer\n\t// derives its principal as rlm.Previous().Address(), so a set\n\t// containing only cur.Address() authorizes nobody but a\n\t// same-package cross-call, and the Transfer below would abort for\n\t// every external caller — including a realm that copies this into\n\t// init(cur realm), which then fails its deploy tx. Matches\n\t// Example_basic and NewWithMembers' godoc.\n\tauth := NewWithMembers(cur.Previous().Address())\n\n\t// Create and switch to contract authority — control moves to\n\t// gno.land/r/demo/dao.\n\tdaoAuthority := NewContractAuthority(\n\t\t\"gno.land/r/demo/dao\",\n\t\tmockDAOHandler,\n\t)\n\tif err := auth.Transfer(0, cur, daoAuthority); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Mock handler for examples\nfunc mockDAOHandler(title string, action PrivilegedAction) error {\n\treturn action()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/authz/v1\"\ngno = \"0.9\"\n"},{"name":"z_contract_authority_shape_filetest.gno","body":"// PKGPATH: gno.land/r/example\n//\n// Executes the contract-identity gate from a real realm.\n//\n// Two reasons this cannot be a plain unit test in p/moul/authz:\n//\n//  1. Example_* functions that take parameters and have no \"// Output:\"\n//     are never run by `gno test` — a sentinel panic inside one still\n//     reports ok. So the package's headline example, the shape readers\n//     copy, is invisible to CI unless something else runs it.\n//  2. The gate cannot be simulated from inside the package. The VM mints\n//     a crossing frame's realm from the CALLEE's declaring package, so a\n//     closure declared in p/moul/authz always presents that package's\n//     address no matter what testing.SetRealm says. Only a realm can\n//     present its own.\n//\n// (2) is the same mechanism as the capability leak, seen from the other\n// side: it is what makes `rlm.Address()` inside a crossing frame\n// unconditionally the realm's own address — and therefore what makes\n// `NewContractAuthority(ownPath)` + `DoByCurrent` a comparison of the\n// realm to itself that can never reject.\n//\n// WHAT THIS FILE PINS. Both halves go red if the identity gate is\n// reverted to its pre-fix `proposer: NewAutoAcceptAuthority()` default:\n//\n//   - a principal that is NOT the contract is refused;\n//   - the contract itself is accepted, so the gate does not lock out the\n//     legitimate driver.\n//\n// It deliberately does NOT demonstrate `DoByCurrent` on an own-path\n// authority. That pairing is the anti-pattern NewContractAuthority's\n// godoc forbids: it succeeds here and it would equally succeed for a\n// hostile caller, so asserting it green would document the hole as the\n// recommended shape. A filetest is confined to one realm and so cannot\n// exhibit the foreign caller itself; the package-level negatives\n// (TestForeignFrameCannotDriveContractAuthority,\n// TestContractPathIsolation) and r/gnops/valopers' filetests cover that.\npackage example\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/moul/authz/v1\"\n)\n\nvar auth = authz.NewWithAuthority(\n\tauthz.NewContractAuthority(\n\t\t\"gno.land/r/example\", // this realm's own path\n\t\tfunc(_ string, action authz.PrivilegedAction) error { return action() },\n\t),\n)\n\nvar updated string\n\n// UpdateParams is the exported crossing entrypoint of the realm.\n//\n// DoByPrevious, not DoByCurrent: the principal is whoever crossed in, so\n// an unrelated realm calling this presents its own address and is\n// refused. Under DoByCurrent the principal would be this realm's own\n// address for every caller, and this entrypoint would be an\n// unauthenticated privileged write.\n//\n// Note what must NOT be added next to it: a function returning this\n// closure, or any other value carrying this frame. That is the leak.\nfunc UpdateParams(cur realm, v string) error {\n\treturn auth.DoByPrevious(0, cur, \"update_params\", func() error {\n\t\tupdated = v\n\t\treturn nil\n\t})\n}\n\nfunc main(cur realm) {\n\t// A principal that is not the contract is refused, and the action\n\t// does not run. This is the assertion the pre-fix AutoAccept default\n\t// could not make.\n\toutsider := chain.PackageAddress(\"gno.land/r/outsider\")\n\terr := auth.Authority().Authorize(outsider, \"update_params\", func() error {\n\t\tupdated = \"SHOULD-NOT-LAND\"\n\t\treturn nil\n\t})\n\tprintln(\"outsider err:\", err)\n\tprintln(\"updated:\", updated)\n\n\t// The contract itself is accepted: main and UpdateParams are both in\n\t// gno.land/r/example, so cur.Previous() is this realm.\n\tprintln(\"contract err:\", UpdateParams(cross(cur), \"governed-value\"))\n\tprintln(\"updated:\", updated)\n}\n\n// Output:\n// outsider err: unauthorized\n// updated:\n// contract err: undefined\n// updated: governed-value\n"}]},"send":"","max_deposit":"32000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"collection","path":"gno.land/p/moul/collection/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/collection/v0`\n\nA generic collection with multiple indexes (unique, case-insensitive, sparse,\nmulti-value), backed by a **B+ tree** ([`gno.land/p/nt/bptree/v0`](https://github.com/gnolang/gno/tree/master/examples/gno.land/p/nt/bptree)).\n\nA B+ tree packs many entries per persisted node, so each index entry costs\nmaterially less storage and gas than an AVL backing would.\n\nTwo operational caveats follow from the in-place-mutating B+ tree backing:\n\n- do **not** mutate the collection (`Set`/`Update`/`Delete`) from inside an index\n  iteration callback — a copy-on-write AVL backing would tolerate it, this one\n  does not;\n- do **not** copy a non-zero `Collection` by value — the copies would share live\n  tree nodes while their state diverges.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/collection/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/collection/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"collection.gno","body":"// Package collection provides a generic collection implementation with support for\n// multiple indexes, including unique indexes and case-insensitive indexes.\n// It is designed to be used with any type and allows efficient lookups using\n// different fields or computed values.\n//\n// Example usage:\n//\n//\t// Define a data type\n//\ttype User struct {\n//\t    Name     string\n//\t    Email    string\n//\t    Age      int\n//\t    Username string\n//\t    Tags     []string\n//\t}\n//\n//\t// Create a new collection\n//\tc := collection.New()\n//\n//\t// Add indexes with different options\n//\tc.AddIndex(\"name\", func(v any) string {\n//\t    return v.(*User).Name\n//\t}, UniqueIndex)\n//\n//\tc.AddIndex(\"email\", func(v any) string {\n//\t    return v.(*User).Email\n//\t}, UniqueIndex|CaseInsensitiveIndex)\n//\n//\tc.AddIndex(\"age\", func(v any) string {\n//\t    return strconv.Itoa(v.(*User).Age)\n//\t}, DefaultIndex)  // Non-unique index\n//\n//\tc.AddIndex(\"username\", func(v any) string {\n//\t    return v.(*User).Username\n//\t}, UniqueIndex|SparseIndex)  // Allow empty usernames\n//\n//\t// For tags, we index all tags for the user\n//\tc.AddIndex(\"tag\", func(v any) []string {\n//\t    return v.(*User).Tags\n//\t}, DefaultIndex)  // Non-unique to allow multiple users with same tag\n//\n//\t// Store an object\n//\tid := c.Set(\u0026User{\n//\t    Name:  \"Alice\",\n//\t    Email: \"alice@example.com\",\n//\t    Age:   30,\n//\t    Tags:  []string{\"admin\", \"moderator\"},  // User can have multiple tags\n//\t})\n//\n//\t// Retrieve by any index\n//\tentry := c.GetFirst(\"email\", \"alice@example.com\")\n//\tadminUsers := c.GetAll(\"tag\", \"admin\")      // Find all users with admin tag\n//\tmodUsers := c.GetAll(\"tag\", \"moderator\")    // Find all users with moderator tag\n//\n// Index options can be combined using the bitwise OR operator.\n// Available options:\n//   - DefaultIndex: Regular index with no special behavior\n//   - UniqueIndex: Ensures values are unique within the index\n//   - CaseInsensitiveIndex: Makes string comparisons case-insensitive\n//   - SparseIndex: Skips indexing empty values (nil or empty string)\n//\n// Example: UniqueIndex|CaseInsensitiveIndex for a case-insensitive unique index\n//\n// # Versioning\n//\n// This is the B+ tree successor to [gno.land/p/moul/collection/v0] (which is\n// backed by an AVL tree): a bump to v3 because the backing data structure — and\n// thus the on-chain storage layout — changed. The exported API is unchanged from\n// v2; only the persisted representation differs, so it is a compatibility (not a\n// source) change. A B+ tree packs many entries per persisted node, so each index\n// entry costs materially less storage and gas than the AVL backing; prefer v3\n// when the collection is part of persisted realm state.\n//\n// Two operational caveats inherited from the in-place-mutating B+ tree backing:\n//\n//   - do NOT mutate the collection (Set/Update/Delete) from inside an index\n//     iteration callback — the AVL backing's copy-on-write tolerated it, this one\n//     does not;\n//   - do NOT copy a non-zero Collection by value — the copies would share live\n//     tree nodes while their state diverges.\npackage collection\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\n// New creates a new Collection instance with an initialized ID index.\n// The ID index is a special unique index that is always present and\n// serves as the primary key for all objects in the collection.\nfunc New() *Collection {\n\tc := \u0026Collection{\n\t\tindexes: make(map[string]*Index),\n\t\tidGen:   seqid.ID(0),\n\t}\n\t// Initialize _id index\n\tc.indexes[IDIndex] = \u0026Index{\n\t\toptions: UniqueIndex,\n\t\ttree:    bptree.NewBPTree32(),\n\t}\n\treturn c\n}\n\n// Collection represents a collection of objects with multiple indexes\ntype Collection struct {\n\tindexes map[string]*Index\n\tidGen   seqid.ID\n}\n\nconst (\n\t// IDIndex is the reserved name for the primary key index\n\tIDIndex = \"_id\"\n)\n\n// IndexOption represents configuration options for an index using bit flags\ntype IndexOption uint64\n\nconst (\n\t// DefaultIndex is a basic index with no special options\n\tDefaultIndex IndexOption = 0\n\n\t// UniqueIndex ensures no duplicate values are allowed\n\tUniqueIndex IndexOption = 1 \u003c\u003c iota\n\n\t// CaseInsensitiveIndex automatically converts string values to lowercase\n\tCaseInsensitiveIndex\n\n\t// SparseIndex only indexes non-empty values\n\tSparseIndex\n)\n\n// Index represents an index with its configuration and data.\n// The index function can return either:\n//   - string: for single-value indexes\n//   - []string: for multi-value indexes where one object can be indexed under multiple keys\n//\n// The backing tree stores either a single ID or []string for multiple IDs per key.\ntype Index struct {\n\tfn      any\n\toptions IndexOption\n\ttree    bptree.ITree\n}\n\n// AddIndex adds a new index to the collection with the specified options\n//\n// Parameters:\n//   - name: the unique name of the index (e.g., \"tags\")\n//   - indexFn: a function that extracts either a string or []string from an object\n//   - options: bit flags for index configuration (e.g., UniqueIndex)\nfunc (c *Collection) AddIndex(name string, indexFn any, options IndexOption) {\n\tif name == IDIndex {\n\t\tpanic(\"_id is a reserved index name\")\n\t}\n\tc.indexes[name] = \u0026Index{\n\t\tfn:      indexFn,\n\t\toptions: options,\n\t\ttree:    bptree.NewBPTree32(),\n\t}\n}\n\n// storeIndex handles how we store an ID in the index tree\nfunc (idx *Index) store(key string, idStr string) {\n\tstored := idx.tree.Get(key)\n\tif stored == nil {\n\t\t// First entry for this key\n\t\tidx.tree.Set(key, idStr)\n\t\treturn\n\t}\n\n\t// Handle existing entries\n\tswitch existing := stored.(type) {\n\tcase string:\n\t\tif existing == idStr {\n\t\t\treturn // Already stored\n\t\t}\n\t\t// Convert to array\n\t\tidx.tree.Set(key, []string{existing, idStr})\n\tcase []string:\n\t\t// Check if ID already exists\n\t\tfor _, id := range existing {\n\t\t\tif id == idStr {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Append new ID\n\t\tidx.tree.Set(key, append(existing, idStr))\n\t}\n}\n\n// removeIndex handles how we remove an ID from the index tree\nfunc (idx *Index) remove(key string, idStr string) {\n\tstored := idx.tree.Get(key)\n\tif stored == nil {\n\t\treturn\n\t}\n\n\tswitch existing := stored.(type) {\n\tcase string:\n\t\tif existing == idStr {\n\t\t\tidx.tree.Remove(key)\n\t\t}\n\tcase []string:\n\t\tnewIds := make([]string, 0, len(existing))\n\t\tfor _, id := range existing {\n\t\t\tif id != idStr {\n\t\t\t\tnewIds = append(newIds, id)\n\t\t\t}\n\t\t}\n\t\tif len(newIds) == 0 {\n\t\t\tidx.tree.Remove(key)\n\t\t} else if len(newIds) == 1 {\n\t\t\tidx.tree.Set(key, newIds[0])\n\t\t} else {\n\t\t\tidx.tree.Set(key, newIds)\n\t\t}\n\t}\n}\n\n// generateKeys extracts one or more keys from an object for a given index.\nfunc generateKeys(idx *Index, obj any) ([]string, bool) {\n\tif obj == nil {\n\t\treturn nil, false\n\t}\n\n\tswitch fnTyped := idx.fn.(type) {\n\tcase func(any) string:\n\t\t// Single-value index\n\t\tkey := fnTyped(obj)\n\t\treturn []string{key}, true\n\tcase func(any) []string:\n\t\t// Multi-value index\n\t\tkeys := fnTyped(obj)\n\t\treturn keys, true\n\tdefault:\n\t\tpanic(\"invalid index function type\")\n\t}\n}\n\n// Set adds or updates an object in the collection.\n// Returns a positive ID if successful.\n// Returns 0 if:\n//   - The object is nil\n//   - A uniqueness constraint would be violated\n//   - Index generation fails for any index\nfunc (c *Collection) Set(obj any) uint64 {\n\tif obj == nil {\n\t\treturn 0\n\t}\n\n\t// Generate new ID\n\tid := c.idGen.Next()\n\tidStr := id.String()\n\n\t// Check uniqueness constraints first\n\tfor name, idx := range c.indexes {\n\t\tif name == IDIndex {\n\t\t\tcontinue\n\t\t}\n\t\tkeys, ok := generateKeys(idx, obj)\n\t\tif !ok {\n\t\t\treturn 0\n\t\t}\n\n\t\tfor _, key := range keys {\n\t\t\t// Skip empty values for sparse indexes\n\t\t\tif idx.options\u0026SparseIndex != 0 \u0026\u0026 key == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\t\t\tkey = strings.ToLower(key)\n\t\t\t}\n\t\t\t// Only check uniqueness for unique + single-value indexes\n\t\t\t// (UniqueIndex is ambiguous; skipping that scenario)\n\t\t\tif idx.options\u0026UniqueIndex != 0 {\n\t\t\t\tif existing := idx.tree.Get(key); existing != nil {\n\t\t\t\t\treturn 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Store in _id index first (the actual object)\n\tc.indexes[IDIndex].tree.Set(idStr, obj)\n\n\t// Store in all other indexes\n\tfor name, idx := range c.indexes {\n\t\tif name == IDIndex {\n\t\t\tcontinue\n\t\t}\n\t\tkeys, ok := generateKeys(idx, obj)\n\t\tif !ok {\n\t\t\t// Rollback: remove from _id index\n\t\t\tc.indexes[IDIndex].tree.Remove(idStr)\n\t\t\treturn 0\n\t\t}\n\n\t\tfor _, key := range keys {\n\t\t\tif idx.options\u0026SparseIndex != 0 \u0026\u0026 key == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\t\t\tkey = strings.ToLower(key)\n\t\t\t}\n\t\t\tidx.store(key, idStr)\n\t\t}\n\t}\n\n\treturn uint64(id)\n}\n\n// Get retrieves entries matching the given key in the specified index.\n// Returns an iterator over the matching entries.\nfunc (c *Collection) Get(indexName string, key string) EntryIterator {\n\tidx, exists := c.indexes[indexName]\n\tif !exists {\n\t\treturn EntryIterator{err: errors.New(\"index not found: \" + indexName)}\n\t}\n\n\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\tkey = strings.ToLower(key)\n\t}\n\n\tif indexName == IDIndex {\n\t\t// For ID index, validate the ID format first\n\t\t_, err := seqid.FromString(key)\n\t\tif err != nil {\n\t\t\treturn EntryIterator{err: err}\n\t\t}\n\t}\n\n\treturn EntryIterator{\n\t\tcollection: c,\n\t\tindexName:  indexName,\n\t\tkey:        key,\n\t}\n}\n\n// GetFirst returns the first matching entry or nil if none found\nfunc (c *Collection) GetFirst(indexName, key string) *Entry {\n\titer := c.Get(indexName, key)\n\tif iter.Next() {\n\t\treturn iter.Value()\n\t}\n\treturn nil\n}\n\n// Delete removes an object by its ID and returns true if something was deleted\nfunc (c *Collection) Delete(id uint64) bool {\n\tidStr := seqid.ID(id).String()\n\n\t// Get the object first to clean up other indexes\n\tobj := c.indexes[IDIndex].tree.Get(idStr)\n\tif obj == nil {\n\t\treturn false\n\t}\n\n\t// Remove from all indexes\n\tfor name, idx := range c.indexes {\n\t\tif name == IDIndex {\n\t\t\tidx.tree.Remove(idStr)\n\t\t\tcontinue\n\t\t}\n\t\tkeys, ok := generateKeys(idx, obj)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, key := range keys {\n\t\t\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\t\t\tkey = strings.ToLower(key)\n\t\t\t}\n\t\t\tidx.remove(key, idStr)\n\t\t}\n\t}\n\treturn true\n}\n\n// Update updates an existing object and returns true if successful\n// Returns true if the update was successful.\n// Returns false if:\n//   - The object is nil\n//   - The ID doesn't exist\n//   - A uniqueness constraint would be violated\n//   - Index generation fails for any index\n//\n// If the update fails, the collection remains unchanged.\nfunc (c *Collection) Update(id uint64, obj any) bool {\n\tif obj == nil {\n\t\treturn false\n\t}\n\tidStr := seqid.ID(id).String()\n\toldObj := c.indexes[IDIndex].tree.Get(idStr)\n\tif oldObj == nil {\n\t\treturn false\n\t}\n\n\t// Check unique constraints\n\tfor name, idx := range c.indexes {\n\t\tif name == IDIndex {\n\t\t\tcontinue\n\t\t}\n\n\t\tif idx.options\u0026UniqueIndex != 0 {\n\t\t\tnewKeys, newOk := generateKeys(idx, obj)\n\t\t\t_, oldOk := generateKeys(idx, oldObj)\n\t\t\tif !newOk || !oldOk {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tfor _, newKey := range newKeys {\n\t\t\t\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\t\t\t\tnewKey = strings.ToLower(newKey)\n\t\t\t\t}\n\n\t\t\t\tfound := idx.tree.Get(newKey)\n\t\t\t\tif found != nil {\n\t\t\t\t\tif storedID, ok := found.(string); !ok || storedID != idStr {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Store old index entries for potential rollback\n\toldEntries := make(map[string][]string)\n\tfor name, idx := range c.indexes {\n\t\tif name == IDIndex {\n\t\t\tcontinue\n\t\t}\n\t\toldKeys, ok := generateKeys(idx, oldObj)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tvar adjusted []string\n\t\tfor _, okey := range oldKeys {\n\t\t\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\t\t\tokey = strings.ToLower(okey)\n\t\t\t}\n\t\t\t// Remove the oldObj from the index right away\n\t\t\tidx.remove(okey, idStr)\n\t\t\tadjusted = append(adjusted, okey)\n\t\t}\n\t\toldEntries[name] = adjusted\n\t}\n\n\t// Update the object in the _id index\n\tc.indexes[IDIndex].tree.Set(idStr, obj)\n\n\t// Add new index entries\n\tfor name, idx := range c.indexes {\n\t\tif name == IDIndex {\n\t\t\tcontinue\n\t\t}\n\t\tnewKeys, ok := generateKeys(idx, obj)\n\t\tif !ok {\n\t\t\t// Rollback: restore old object and old index entries\n\t\t\tc.indexes[IDIndex].tree.Set(idStr, oldObj)\n\t\t\tfor idxName, keys := range oldEntries {\n\t\t\t\tfor _, oldKey := range keys {\n\t\t\t\t\tc.indexes[idxName].store(oldKey, idStr)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\tfor _, nkey := range newKeys {\n\t\t\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\t\t\tnkey = strings.ToLower(nkey)\n\t\t\t}\n\t\t\tidx.store(nkey, idStr)\n\t\t}\n\t}\n\n\treturn true\n}\n\n// GetAll retrieves all entries matching the given key in the specified index.\nfunc (c *Collection) GetAll(indexName string, key string) []Entry {\n\tidx, exists := c.indexes[indexName]\n\tif !exists {\n\t\treturn nil\n\t}\n\n\tif idx.options\u0026CaseInsensitiveIndex != 0 {\n\t\tkey = strings.ToLower(key)\n\t}\n\n\tif indexName == IDIndex {\n\t\tif obj := idx.tree.Get(key); obj != nil {\n\t\t\treturn []Entry{{ID: key, Obj: obj}}\n\t\t}\n\t\treturn nil\n\t}\n\n\tidData := idx.tree.Get(key)\n\tif idData == nil {\n\t\treturn nil\n\t}\n\n\t// Handle both single and multi-value cases based on the actual data type\n\tswitch stored := idData.(type) {\n\tcase []string:\n\t\tresult := make([]Entry, 0, len(stored))\n\t\tfor _, idStr := range stored {\n\t\t\tif obj := c.indexes[IDIndex].tree.Get(idStr); obj != nil {\n\t\t\t\tresult = append(result, Entry{ID: idStr, Obj: obj})\n\t\t\t}\n\t\t}\n\t\treturn result\n\tcase string:\n\t\tif obj := c.indexes[IDIndex].tree.Get(stored); obj != nil {\n\t\t\treturn []Entry{{ID: stored, Obj: obj}}\n\t\t}\n\t}\n\treturn nil\n}\n\n// GetIndex returns the underlying tree for an index\nfunc (c *Collection) GetIndex(name string) bptree.ITree {\n\tidx, exists := c.indexes[name]\n\tif !exists {\n\t\treturn nil\n\t}\n\treturn idx.tree\n}\n"},{"name":"collection_test.gno","body":"package collection\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype Person struct {\n\tName     string\n\tAge      int\n\tEmail    string\n\tUsername string\n\tTags     []string\n}\n\nfunc (p Person) String() string {\n\treturn ufmt.Sprintf(\"name=%s age=%d email=%s username=%s tags=%s\",\n\t\tp.Name, p.Age, p.Email, p.Username, strings.Join(p.Tags, \",\"))\n}\n\n// TestOperation represents a single operation in a test sequence\ntype TestOperation struct {\n\top      string // \"set\" or \"update\"\n\tperson  *Person\n\tid      uint64 // for updates\n\twantID  uint64\n\twantErr bool\n}\n\n// TestCase represents a complete test case with setup and operations\ntype TestCase struct {\n\tname       string\n\tsetupIndex func(*Collection)\n\toperations []TestOperation\n}\n\nfunc TestBasicOperations(t *testing.T) {\n\tc := New()\n\n\t// Add indexes\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\tc.AddIndex(\"age\", func(v any) string {\n\t\treturn strconv.Itoa(v.(*Person).Age)\n\t}, DefaultIndex)\n\n\t// Test basic Set and Get\n\tp1 := \u0026Person{Name: \"Alice\", Age: 30, Email: \"alice@test.com\"}\n\tid1 := c.Set(p1)\n\tif id1 == 0 {\n\t\tt.Error(\"Failed to set first object\")\n\t}\n\n\t// Get by ID\n\titer := c.Get(IDIndex, seqid.ID(id1).String())\n\tif !iter.Next() {\n\t\tt.Error(\"Failed to get object by ID\")\n\t}\n\tentry := iter.Value()\n\tif entry.Obj.(*Person).Name != \"Alice\" {\n\t\tt.Error(\"Got wrong object\")\n\t}\n}\n\nfunc TestUniqueConstraints(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tsetup  func(*Collection) uint64\n\t\twantID bool\n\t}{\n\t\t{\n\t\t\tname: \"First person\",\n\t\t\tsetup: func(c *Collection) uint64 {\n\t\t\t\treturn c.Set(\u0026Person{Name: \"Alice\"})\n\t\t\t},\n\t\t\twantID: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Duplicate name\",\n\t\t\tsetup: func(c *Collection) uint64 {\n\t\t\t\tc.Set(\u0026Person{Name: \"Alice\"})\n\t\t\t\treturn c.Set(\u0026Person{Name: \"Alice\"})\n\t\t\t},\n\t\t\twantID: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Same age (non-unique index)\",\n\t\t\tsetup: func(c *Collection) uint64 {\n\t\t\t\tc.AddIndex(\"age\", func(v any) string {\n\t\t\t\t\treturn strconv.Itoa(v.(*Person).Age)\n\t\t\t\t}, DefaultIndex)\n\t\t\t\tc.Set(\u0026Person{Name: \"Alice\", Age: 30})\n\t\t\t\treturn c.Set(\u0026Person{Name: \"Bob\", Age: 30})\n\t\t\t},\n\t\t\twantID: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := New()\n\t\t\tc.AddIndex(\"name\", func(v any) string {\n\t\t\t\treturn v.(*Person).Name\n\t\t\t}, UniqueIndex)\n\n\t\t\tid := tt.setup(c)\n\t\t\tif (id != 0) != tt.wantID {\n\t\t\t\tt.Errorf(\"Set() got id = %v, want non-zero: %v\", id, tt.wantID)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUpdates(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\tc.AddIndex(\"username\", func(v any) string {\n\t\treturn strings.ToLower(v.(*Person).Username)\n\t}, UniqueIndex|CaseInsensitiveIndex)\n\n\t// Initial setup\n\tp1 := \u0026Person{Name: \"Alice\", Username: \"alice123\"}\n\tp2 := \u0026Person{Name: \"Bob\", Username: \"bob456\"}\n\n\tid1 := c.Set(p1)\n\tc.Set(p2)\n\n\ttests := []struct {\n\t\tname      string\n\t\tid        uint64\n\t\tnewPerson *Person\n\t\twantRet   bool\n\t}{\n\t\t{\n\t\t\tname:      \"Update to non-conflicting values\",\n\t\t\tid:        id1,\n\t\t\tnewPerson: \u0026Person{Name: \"Alice2\", Username: \"alice1234\"},\n\t\t\twantRet:   true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Update to conflicting username\",\n\t\t\tid:        id1,\n\t\t\tnewPerson: \u0026Person{Name: \"Alice2\", Username: \"bob456\"},\n\t\t\twantRet:   false,\n\t\t},\n\t\t{\n\t\t\tname:      \"Update non-existent ID\",\n\t\t\tid:        99999,\n\t\t\tnewPerson: \u0026Person{Name: \"Test\", Username: \"test\"},\n\t\t\twantRet:   false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgotID := c.Update(tt.id, tt.newPerson)\n\t\t\tif gotID != tt.wantRet {\n\t\t\t\tt.Errorf(\"Update() got = %v, want %v\", gotID, tt.wantRet)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\n\tp1 := \u0026Person{Name: \"Alice\"}\n\tid1 := c.Set(p1)\n\n\ttests := []struct {\n\t\tname    string\n\t\tid      uint64\n\t\twantRet bool\n\t}{\n\t\t{\n\t\t\tname:    \"Delete existing object\",\n\t\t\tid:      id1,\n\t\t\twantRet: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"Delete non-existent object\",\n\t\t\tid:      99999,\n\t\t\twantRet: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"Delete already deleted object\",\n\t\t\tid:      id1,\n\t\t\twantRet: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgotID := c.Delete(tt.id)\n\t\t\tif gotID != tt.wantRet {\n\t\t\t\tt.Errorf(\"Delete() got = %v, want %v\", gotID, tt.wantRet)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestEdgeCases(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\n\ttests := []struct {\n\t\tname      string\n\t\toperation func() bool\n\t\twantPanic bool\n\t}{\n\t\t{\n\t\t\tname: \"Set nil object\",\n\t\t\toperation: func() bool {\n\t\t\t\treturn c.Set(nil) != 0\n\t\t\t},\n\t\t\twantPanic: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Set wrong type\",\n\t\t\toperation: func() bool {\n\t\t\t\treturn c.Set(\"not a person\") != 0\n\t\t\t},\n\t\t\twantPanic: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Update with nil\",\n\t\t\toperation: func() bool {\n\t\t\t\tid := c.Set(\u0026Person{Name: \"Test\"})\n\t\t\t\treturn c.Update(id, nil)\n\t\t\t},\n\t\t\twantPanic: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Get with invalid index name\",\n\t\t\toperation: func() bool {\n\t\t\t\titer := c.Get(\"invalid_index\", \"key\")\n\t\t\t\tif iter.Empty() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tentry := iter.Value()\n\t\t\t\tif entry == nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\t_, err := seqid.FromString(entry.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t},\n\t\t\twantPanic: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar got bool\n\t\t\tpanicked := false\n\n\t\t\tfunc() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tpanicked = true\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tgot = tt.operation()\n\t\t\t}()\n\n\t\t\tif panicked != tt.wantPanic {\n\t\t\t\tt.Errorf(\"Operation panicked = %v, want panic = %v\", panicked, tt.wantPanic)\n\t\t\t}\n\t\t\tif !panicked \u0026\u0026 got != false {\n\t\t\t\tt.Errorf(\"Operation returned %v, want 0\", got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIndexTypes(t *testing.T) {\n\tc := New()\n\n\t// Test different types of indexes\n\tc.AddIndex(\"composite\", func(v any) string {\n\t\tp := v.(*Person)\n\t\treturn p.Name + \":\" + strconv.Itoa(p.Age)\n\t}, UniqueIndex)\n\n\tc.AddIndex(\"case_insensitive\", func(v any) string {\n\t\treturn strings.ToLower(v.(*Person).Username)\n\t}, UniqueIndex|CaseInsensitiveIndex)\n\n\t// Test composite index\n\tp1 := \u0026Person{Name: \"Alice\", Age: 30, Username: \"Alice123\"}\n\tid1 := c.Set(p1)\n\tif id1 == 0 {\n\t\tt.Error(\"Failed to set object with composite index\")\n\t}\n\n\t// Test case-insensitive index\n\tp2 := \u0026Person{Name: \"Bob\", Age: 25, Username: \"alice123\"}\n\tid2 := c.Set(p2)\n\tif id2 != 0 {\n\t\tt.Error(\"Case-insensitive index failed to prevent duplicate\")\n\t}\n}\n\nfunc TestIndexOptions(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func(*Collection) uint64\n\t\twantID  bool\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"Unique case-sensitive index\",\n\t\t\tsetup: func(c *Collection) uint64 {\n\t\t\t\tc.AddIndex(\"username\", func(v any) string {\n\t\t\t\t\treturn v.(*Person).Username\n\t\t\t\t}, UniqueIndex)\n\n\t\t\t\tc.Set(\u0026Person{Username: \"Alice\"})\n\t\t\t\treturn c.Set(\u0026Person{Username: \"Alice\"}) // Should fail\n\t\t\t},\n\t\t\twantID: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Unique case-insensitive index\",\n\t\t\tsetup: func(c *Collection) uint64 {\n\t\t\t\tc.AddIndex(\"email\", func(v any) string {\n\t\t\t\t\treturn v.(*Person).Email\n\t\t\t\t}, UniqueIndex|CaseInsensitiveIndex)\n\n\t\t\t\tc.Set(\u0026Person{Email: \"test@example.com\"})\n\t\t\t\treturn c.Set(\u0026Person{Email: \"TEST@EXAMPLE.COM\"}) // Should fail\n\t\t\t},\n\t\t\twantID: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Default index\",\n\t\t\tsetup: func(c *Collection) uint64 {\n\t\t\t\tc.AddIndex(\"age\", func(v any) string {\n\t\t\t\t\treturn strconv.Itoa(v.(*Person).Age)\n\t\t\t\t}, DefaultIndex)\n\n\t\t\t\t// First person with age 30\n\t\t\t\tid1 := c.Set(\u0026Person{Age: 30})\n\t\t\t\tif id1 == 0 {\n\t\t\t\t\tt.Error(\"Failed to set first person\")\n\t\t\t\t}\n\n\t\t\t\t// Second person with same age should succeed\n\t\t\t\treturn c.Set(\u0026Person{Age: 30})\n\t\t\t},\n\t\t\twantID: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple options\",\n\t\t\tsetup: func(c *Collection) uint64 {\n\t\t\t\tc.AddIndex(\"name\", func(v any) string {\n\t\t\t\t\treturn v.(*Person).Name\n\t\t\t\t}, UniqueIndex|CaseInsensitiveIndex|SparseIndex)\n\n\t\t\t\tc.Set(\u0026Person{Name: \"Alice\"})\n\t\t\t\treturn c.Set(\u0026Person{Name: \"ALICE\"}) // Should fail\n\t\t\t},\n\t\t\twantID: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := New() // Create new collection for each test\n\t\t\tid := tt.setup(c)\n\t\t\tif (id != 0) != tt.wantID {\n\t\t\t\tt.Errorf(\"got id = %v, want non-zero: %v\", id, tt.wantID)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConcurrentOperations(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\n\tp1 := \u0026Person{Name: \"Alice\"}\n\tid1 := c.Set(p1)\n\titer := c.Get(\"_id\", seqid.ID(id1).String())\n\tsuccess := c.Update(id1, \u0026Person{Name: \"Alice2\"})\n\n\tif iter.Empty() || !success {\n\t\tt.Error(\"Concurrent operations failed\")\n\t}\n}\n\nfunc TestSparseIndexBehavior(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"optional_field\", func(v any) string {\n\t\treturn v.(*Person).Username\n\t}, SparseIndex)\n\n\ttests := []struct {\n\t\tname   string\n\t\tperson *Person\n\t\twantID bool\n\t}{\n\t\t{\n\t\t\tname:   \"Empty optional field\",\n\t\t\tperson: \u0026Person{Name: \"Alice\", Email: \"alice@test.com\"},\n\t\t\twantID: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"Populated optional field\",\n\t\t\tperson: \u0026Person{Name: \"Bob\", Email: \"bob@test.com\", Username: \"bobby\"},\n\t\t\twantID: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"Multiple empty fields\",\n\t\t\tperson: \u0026Person{Name: \"Charlie\"},\n\t\t\twantID: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tid := c.Set(tt.person)\n\t\t\tif (id != 0) != tt.wantID {\n\t\t\t\tt.Errorf(\"Set() got id = %v, want non-zero: %v\", id, tt.wantID)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIndexKeyGeneration(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"composite\", func(v any) string {\n\t\tp := v.(*Person)\n\t\treturn p.Name + \":\" + strconv.Itoa(p.Age)\n\t}, UniqueIndex)\n\n\ttests := []struct {\n\t\tname   string\n\t\tperson *Person\n\t\twantID bool\n\t}{\n\t\t{\n\t\t\tname:   \"Valid composite key\",\n\t\t\tperson: \u0026Person{Name: \"Alice\", Age: 30},\n\t\t\twantID: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"Duplicate composite key\",\n\t\t\tperson: \u0026Person{Name: \"Alice\", Age: 30},\n\t\t\twantID: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"Different composite key\",\n\t\t\tperson: \u0026Person{Name: \"Alice\", Age: 31},\n\t\t\twantID: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tid := c.Set(tt.person)\n\t\t\tif (id != 0) != tt.wantID {\n\t\t\t\tt.Errorf(\"Set() got id = %v, want non-zero: %v\", id, tt.wantID)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetIndex(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\n\ttests := []struct {\n\t\tname      string\n\t\tindexName string\n\t\twantNil   bool\n\t}{\n\t\t{\n\t\t\tname:      \"Get existing index\",\n\t\t\tindexName: \"name\",\n\t\t\twantNil:   false,\n\t\t},\n\t\t{\n\t\t\tname:      \"Get _id index\",\n\t\t\tindexName: IDIndex,\n\t\t\twantNil:   false,\n\t\t},\n\t\t{\n\t\t\tname:      \"Get non-existent index\",\n\t\t\tindexName: \"invalid\",\n\t\t\twantNil:   true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttree := c.GetIndex(tt.indexName)\n\t\t\tif (tree == nil) != tt.wantNil {\n\t\t\t\tt.Errorf(\"GetIndex() got nil = %v, want nil = %v\", tree == nil, tt.wantNil)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestAddIndexPanic(t *testing.T) {\n\tc := New()\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"Expected panic when adding _id index\")\n\t\t}\n\t}()\n\n\tc.AddIndex(IDIndex, func(v any) string {\n\t\treturn \"\"\n\t}, DefaultIndex)\n}\n\nfunc TestCaseInsensitiveOperations(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"email\", func(v any) string {\n\t\treturn v.(*Person).Email\n\t}, UniqueIndex|CaseInsensitiveIndex)\n\n\tp := \u0026Person{Email: \"Test@Example.com\"}\n\tid := c.Set(p)\n\n\ttests := []struct {\n\t\tname      string\n\t\tkey       string\n\t\twantObj   bool\n\t\toperation string // \"get\" or \"getAll\"\n\t\twantCount int\n\t}{\n\t\t{\"Get exact match\", \"Test@Example.com\", true, \"get\", 1},\n\t\t{\"Get different case\", \"test@example.COM\", true, \"get\", 1},\n\t\t{\"Get non-existent\", \"other@example.com\", false, \"get\", 0},\n\t\t{\"GetAll exact match\", \"Test@Example.com\", true, \"getAll\", 1},\n\t\t{\"GetAll different case\", \"test@example.COM\", true, \"getAll\", 1},\n\t\t{\"GetAll non-existent\", \"other@example.com\", false, \"getAll\", 0},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.operation == \"get\" {\n\t\t\t\titer := c.Get(\"email\", tt.key)\n\t\t\t\tif iter.Empty() {\n\t\t\t\t\tif tt.wantObj {\n\t\t\t\t\t\tt.Error(\"Expected iterator to not be empty\")\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thasValue := iter.Next()\n\t\t\t\tif hasValue != tt.wantObj {\n\t\t\t\t\tt.Errorf(\"Get() got object = %v, want object = %v\", hasValue, tt.wantObj)\n\t\t\t\t}\n\t\t\t\tif hasValue {\n\t\t\t\t\tentry := iter.Value()\n\t\t\t\t\tif entry.ID != seqid.ID(id).String() {\n\t\t\t\t\t\tt.Errorf(\"Get() got id = %v, want id = %v\", entry.ID, seqid.ID(id).String())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tentries := c.GetAll(\"email\", tt.key)\n\t\t\t\tif len(entries) != tt.wantCount {\n\t\t\t\t\tt.Errorf(\"GetAll() returned %d entries, want %d\", len(entries), tt.wantCount)\n\t\t\t\t}\n\t\t\t\tif tt.wantCount \u003e 0 {\n\t\t\t\t\tentry := entries[0]\n\t\t\t\t\tif entry.ID != seqid.ID(id).String() {\n\t\t\t\t\t\tt.Errorf(\"GetAll() returned ID %s, want %s\", entry.ID, seqid.ID(id).String())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetInvalidID(t *testing.T) {\n\tc := New()\n\titer := c.Get(IDIndex, \"not-a-valid-id\")\n\tif !iter.Empty() {\n\t\tt.Errorf(\"Get() with invalid ID format got an entry, want nil\")\n\t}\n}\n\nfunc TestGetAll(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"tags\", func(v any) []string {\n\t\treturn v.(*Person).Tags\n\t}, DefaultIndex)\n\tc.AddIndex(\"age\", func(v any) string {\n\t\treturn strconv.Itoa(v.(*Person).Age)\n\t}, DefaultIndex)\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\n\t// Create test data\n\tpeople := []*Person{\n\t\t{Name: \"Alice\", Age: 30, Tags: []string{\"dev\", \"go\"}},\n\t\t{Name: \"Bob\", Age: 30, Tags: []string{\"dev\", \"python\"}},\n\t\t{Name: \"Charlie\", Age: 25, Tags: []string{\"dev\", \"rust\"}},\n\t}\n\n\tids := make([]uint64, len(people))\n\tfor i, p := range people {\n\t\tids[i] = c.Set(p)\n\t\tif ids[i] == 0 {\n\t\t\tt.Fatalf(\"Failed to set person %s\", p.Name)\n\t\t}\n\t}\n\n\ttests := []struct {\n\t\tname      string\n\t\tindexName string\n\t\tkey       string\n\t\twantCount int\n\t}{\n\t\t{\n\t\t\tname:      \"Multi-value index with multiple matches\",\n\t\t\tindexName: \"tags\",\n\t\t\tkey:       \"dev\",\n\t\t\twantCount: 3,\n\t\t},\n\t\t{\n\t\t\tname:      \"Multi-value index with single match\",\n\t\t\tindexName: \"tags\",\n\t\t\tkey:       \"go\",\n\t\t\twantCount: 1,\n\t\t},\n\t\t{\n\t\t\tname:      \"Multi-value index with no matches\",\n\t\t\tindexName: \"tags\",\n\t\t\tkey:       \"java\",\n\t\t\twantCount: 0,\n\t\t},\n\t\t{\n\t\t\tname:      \"Single-value non-unique index with multiple matches\",\n\t\t\tindexName: \"age\",\n\t\t\tkey:       \"30\",\n\t\t\twantCount: 2,\n\t\t},\n\t\t{\n\t\t\tname:      \"Single-value unique index\",\n\t\t\tindexName: \"name\",\n\t\t\tkey:       \"Alice\",\n\t\t\twantCount: 1,\n\t\t},\n\t\t{\n\t\t\tname:      \"Non-existent index\",\n\t\t\tindexName: \"invalid\",\n\t\t\tkey:       \"value\",\n\t\t\twantCount: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := c.Get(tt.indexName, tt.key)\n\t\t\tcount := 0\n\t\t\tfor iter.Next() {\n\t\t\t\tentry := iter.Value()\n\t\t\t\tif entry.ID == \"\" {\n\t\t\t\t\tt.Error(\"Got entry with empty ID\")\n\t\t\t\t}\n\t\t\t\tif entry.Obj == nil {\n\t\t\t\t\tt.Error(\"Got entry with nil Obj\")\n\t\t\t\t}\n\t\t\t\tcount++\n\t\t\t}\n\t\t\tif count != tt.wantCount {\n\t\t\t\tt.Errorf(\"Got %d entries, want %d\", count, tt.wantCount)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIndexOperations(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func(*Collection) (uint64, error)\n\t\tverify  func(*Collection, uint64) error\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"Basic set and get\",\n\t\t\tsetup: func(c *Collection) (uint64, error) {\n\t\t\t\tc.AddIndex(\"name\", func(v any) string {\n\t\t\t\t\treturn v.(*Person).Name\n\t\t\t\t}, UniqueIndex)\n\t\t\t\treturn c.Set(\u0026Person{Name: \"Alice\", Age: 30}), nil\n\t\t\t},\n\t\t\tverify: func(c *Collection, id uint64) error {\n\t\t\t\titer := c.Get(IDIndex, seqid.ID(id).String())\n\t\t\t\tif !iter.Next() {\n\t\t\t\t\treturn errors.New(\"failed to get object by ID\")\n\t\t\t\t}\n\t\t\t\tentry := iter.Value()\n\t\t\t\tif entry.Obj.(*Person).Name != \"Alice\" {\n\t\t\t\t\treturn errors.New(\"got wrong object\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Composite index\",\n\t\t\tsetup: func(c *Collection) (uint64, error) {\n\t\t\t\tc.AddIndex(\"composite\", func(v any) string {\n\t\t\t\t\tp := v.(*Person)\n\t\t\t\t\treturn p.Name + \":\" + strconv.Itoa(p.Age)\n\t\t\t\t}, UniqueIndex)\n\t\t\t\treturn c.Set(\u0026Person{Name: \"Alice\", Age: 30}), nil\n\t\t\t},\n\t\t\tverify: func(c *Collection, id uint64) error {\n\t\t\t\titer := c.Get(\"composite\", \"Alice:30\")\n\t\t\t\tif !iter.Next() {\n\t\t\t\t\treturn errors.New(\"failed to get object by composite index\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t// Add more test cases combining unique scenarios from original tests\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := New()\n\t\t\tid, err := tt.setup(c)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"setup error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tif err := tt.verify(c, id); err != nil {\n\t\t\t\t\tt.Errorf(\"verification failed: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMultiValueIndexes(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"tags\", func(v any) []string {\n\t\treturn v.(*Person).Tags\n\t}, DefaultIndex)\n\n\ttests := []struct {\n\t\tname      string\n\t\tsetup     []*Person\n\t\tsearchTag string\n\t\twantCount int\n\t}{\n\t\t{\n\t\t\tname: \"Multiple tags, multiple matches\",\n\t\t\tsetup: []*Person{\n\t\t\t\t{Name: \"Alice\", Tags: []string{\"dev\", \"go\"}},\n\t\t\t\t{Name: \"Bob\", Tags: []string{\"dev\", \"python\"}},\n\t\t\t\t{Name: \"Charlie\", Tags: []string{\"dev\", \"rust\"}},\n\t\t\t},\n\t\t\tsearchTag: \"dev\",\n\t\t\twantCount: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"Single tag match\",\n\t\t\tsetup: []*Person{\n\t\t\t\t{Name: \"Alice\", Tags: []string{\"dev\", \"go\"}},\n\t\t\t\t{Name: \"Bob\", Tags: []string{\"dev\", \"python\"}},\n\t\t\t},\n\t\t\tsearchTag: \"go\",\n\t\t\twantCount: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"No matches\",\n\t\t\tsetup: []*Person{\n\t\t\t\t{Name: \"Alice\", Tags: []string{\"dev\", \"go\"}},\n\t\t\t\t{Name: \"Bob\", Tags: []string{\"dev\", \"python\"}},\n\t\t\t},\n\t\t\tsearchTag: \"java\",\n\t\t\twantCount: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"Empty tags\",\n\t\t\tsetup: []*Person{\n\t\t\t\t{Name: \"Alice\", Tags: []string{}},\n\t\t\t\t{Name: \"Bob\", Tags: nil},\n\t\t\t},\n\t\t\tsearchTag: \"dev\",\n\t\t\twantCount: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := New()\n\t\t\tc.AddIndex(\"tags\", func(v any) []string {\n\t\t\t\treturn v.(*Person).Tags\n\t\t\t}, DefaultIndex)\n\n\t\t\t// Setup test data\n\t\t\tfor _, p := range tt.setup {\n\t\t\t\tif id := c.Set(p); id == 0 {\n\t\t\t\t\tt.Fatalf(\"Failed to set person %s\", p.Name)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Test Get operation\n\t\t\titer := c.Get(\"tags\", tt.searchTag)\n\t\t\tcount := 0\n\t\t\tfor iter.Next() {\n\t\t\t\tcount++\n\t\t\t}\n\t\t\tif count != tt.wantCount {\n\t\t\t\tt.Errorf(\"Get() got %d matches, want %d\", count, tt.wantCount)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetOperations(t *testing.T) {\n\tc := New()\n\tc.AddIndex(\"name\", func(v any) string {\n\t\treturn v.(*Person).Name\n\t}, UniqueIndex)\n\tc.AddIndex(\"age\", func(v any) string {\n\t\treturn strconv.Itoa(v.(*Person).Age)\n\t}, DefaultIndex)\n\n\t// Setup test data\n\ttestPeople := []*Person{\n\t\t{Name: \"Alice\", Age: 30},\n\t\t{Name: \"Bob\", Age: 30},\n\t\t{Name: \"Charlie\", Age: 25},\n\t}\n\n\tids := make([]uint64, len(testPeople))\n\tfor i, p := range testPeople {\n\t\tids[i] = c.Set(p)\n\t\tif ids[i] == 0 {\n\t\t\tt.Fatalf(\"Failed to set person %s\", p.Name)\n\t\t}\n\t}\n\n\ttests := []struct {\n\t\tname      string\n\t\tindexName string\n\t\tkey       string\n\t\twantCount int\n\t\twantErr   bool\n\t}{\n\t\t{\n\t\t\tname:      \"Get by ID\",\n\t\t\tindexName: IDIndex,\n\t\t\tkey:       seqid.ID(ids[0]).String(),\n\t\t\twantCount: 1,\n\t\t\twantErr:   false,\n\t\t},\n\t\t{\n\t\t\tname:      \"Get by unique index\",\n\t\t\tindexName: \"name\",\n\t\t\tkey:       \"Alice\",\n\t\t\twantCount: 1,\n\t\t\twantErr:   false,\n\t\t},\n\t\t{\n\t\t\tname:      \"Get by non-unique index\",\n\t\t\tindexName: \"age\",\n\t\t\tkey:       \"30\",\n\t\t\twantCount: 2,\n\t\t\twantErr:   false,\n\t\t},\n\t\t{\n\t\t\tname:      \"Get with invalid index\",\n\t\t\tindexName: \"invalid_index\",\n\t\t\tkey:       \"value\",\n\t\t\twantCount: 0,\n\t\t\twantErr:   true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Get with invalid ID format\",\n\t\t\tindexName: IDIndex,\n\t\t\tkey:       \"not-a-valid-id\",\n\t\t\twantCount: 0,\n\t\t\twantErr:   true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := c.Get(tt.indexName, tt.key)\n\t\t\tif iter.Empty() {\n\t\t\t\tif !tt.wantErr {\n\t\t\t\t\tt.Errorf(\"Get() returned empty iterator, wanted %d results\", tt.wantCount)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor iter.Next() {\n\t\t\t\tentry := iter.Value()\n\t\t\t\tif entry.ID == \"\" {\n\t\t\t\t\tt.Error(\"Got entry with empty ID\")\n\t\t\t\t}\n\t\t\t\tif entry.Obj == nil {\n\t\t\t\t\tt.Error(\"Got entry with nil Obj\")\n\t\t\t\t}\n\t\t\t\tcount++\n\t\t\t}\n\n\t\t\tif count != tt.wantCount {\n\t\t\t\tt.Errorf(\"Get() returned %d results, want %d\", count, tt.wantCount)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestEntryString(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tentry    *Entry\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"Nil entry\",\n\t\t\tentry:    nil,\n\t\t\texpected: \"\u003cnil\u003e\",\n\t\t},\n\t\t{\n\t\t\tname: \"Person entry\",\n\t\t\tentry: \u0026Entry{\n\t\t\t\tID:  \"123\",\n\t\t\t\tObj: \u0026Person{Name: \"Alice\", Age: 30},\n\t\t\t},\n\t\t\texpected: `Entry{ID: 123, Obj: name=Alice age=30 email= username= tags=}`,\n\t\t},\n\t\t{\n\t\t\tname: \"Entry with nil object\",\n\t\t\tentry: \u0026Entry{\n\t\t\t\tID:  \"456\",\n\t\t\t\tObj: nil,\n\t\t\t},\n\t\t\texpected: `Entry{ID: 456, Obj: \u003cnil\u003e}`,\n\t\t},\n\t\t{\n\t\t\tname: \"Entry with complete person\",\n\t\t\tentry: \u0026Entry{\n\t\t\t\tID: \"789\",\n\t\t\t\tObj: \u0026Person{\n\t\t\t\t\tName:     \"Bob\",\n\t\t\t\t\tAge:      25,\n\t\t\t\t\tEmail:    \"bob@example.com\",\n\t\t\t\t\tUsername: \"bobby\",\n\t\t\t\t\tTags:     []string{\"dev\", \"go\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `Entry{ID: 789, Obj: name=Bob age=25 email=bob@example.com username=bobby tags=dev,go}`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := tt.entry.String()\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"Entry.String() = %q, want %q\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"},{"name":"entry.gno","body":"package collection\n\nimport \"gno.land/p/nt/ufmt/v0\"\n\n// Entry represents a single object in the collection with its ID\ntype Entry struct {\n\tID  string\n\tObj any\n}\n\n// String returns a string representation of the Entry\nfunc (e *Entry) String() string {\n\tif e == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\treturn ufmt.Sprintf(\"Entry{ID: %s, Obj: %v}\", e.ID, e.Obj)\n}\n\n// EntryIterator provides iteration over collection entries\ntype EntryIterator struct {\n\tcollection *Collection\n\tindexName  string\n\tkey        string\n\tcurrentID  string\n\tcurrentObj any\n\terr        error\n\tclosed     bool\n\n\t// For multi-value cases\n\tids        []string\n\tcurrentIdx int\n}\n\nfunc (ei *EntryIterator) Close() error {\n\tei.closed = true\n\tei.currentID = \"\"\n\tei.currentObj = nil\n\tei.ids = nil\n\treturn nil\n}\n\nfunc (ei *EntryIterator) Next() bool {\n\tif ei == nil || ei.closed || ei.err != nil {\n\t\treturn false\n\t}\n\n\t// Handle ID index specially\n\tif ei.indexName == IDIndex {\n\t\tif ei.currentID != \"\" { // We've already returned the single value\n\t\t\treturn false\n\t\t}\n\t\tobj := ei.collection.indexes[IDIndex].tree.Get(ei.key)\n\t\tif obj == nil {\n\t\t\treturn false\n\t\t}\n\t\tei.currentID = ei.key\n\t\tei.currentObj = obj\n\t\treturn true\n\t}\n\n\t// Get the index\n\tidx, exists := ei.collection.indexes[ei.indexName]\n\tif !exists {\n\t\treturn false\n\t}\n\n\t// Initialize ids slice if needed\n\tif ei.ids == nil {\n\t\tidData := idx.tree.Get(ei.key)\n\t\tif idData == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch stored := idData.(type) {\n\t\tcase []string:\n\t\t\tei.ids = stored\n\t\t\tei.currentIdx = -1\n\t\tcase string:\n\t\t\tei.ids = []string{stored}\n\t\t\tei.currentIdx = -1\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Move to next ID\n\tei.currentIdx++\n\tif ei.currentIdx \u003e= len(ei.ids) {\n\t\treturn false\n\t}\n\n\t// Fetch the actual object\n\tei.currentID = ei.ids[ei.currentIdx]\n\tobj := ei.collection.indexes[IDIndex].tree.Get(ei.currentID)\n\tif obj == nil {\n\t\t// Skip invalid entries\n\t\treturn ei.Next()\n\t}\n\tei.currentObj = obj\n\treturn true\n}\n\nfunc (ei *EntryIterator) Error() error {\n\treturn ei.err\n}\n\nfunc (ei *EntryIterator) Value() *Entry {\n\tif ei == nil || ei.closed || ei.currentID == \"\" {\n\t\treturn nil\n\t}\n\treturn \u0026Entry{\n\t\tID:  ei.currentID,\n\t\tObj: ei.currentObj,\n\t}\n}\n\nfunc (ei *EntryIterator) Empty() bool {\n\tif ei == nil || ei.closed || ei.err != nil {\n\t\treturn true\n\t}\n\n\t// Handle ID index specially\n\tif ei.indexName == IDIndex {\n\t\treturn !ei.collection.indexes[IDIndex].tree.Has(ei.key)\n\t}\n\n\t// Get the index\n\tidx, exists := ei.collection.indexes[ei.indexName]\n\tif !exists {\n\t\treturn true\n\t}\n\n\t// Check if key exists in index\n\tidData := idx.tree.Get(ei.key)\n\tif idData == nil {\n\t\treturn true\n\t}\n\n\t// Check if there are any valid IDs\n\tswitch stored := idData.(type) {\n\tcase []string:\n\t\treturn len(stored) == 0\n\tcase string:\n\t\treturn stored == \"\"\n\tdefault:\n\t\treturn true\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/collection/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"16000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"cow","path":"gno.land/p/moul/cow/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/cow`\n\nA copy-on-write AVL tree: a fork of\n[`p/nt/avl`](https://github.com/gnolang/gno/tree/master/examples/gno.land/p/nt/avl)\nwith the same API, plus **O(1) cloning**.\n\n```go\nt := cow.NewTree()\nt.Set(\"a\", 1)\n\nsnapshot := t.Clone()   // O(1): shares every node with t\nt.Set(\"b\", 2)           // only the root-to-\"b\" path is copied\n```\n\n`Clone` copies a pointer. Both trees then present as full independent copies,\nbut they share structure until one of them is written to, and a write only\ncopies the nodes along the path from the root to the modified node: O(log n)\nnew nodes, not O(n).\n\n## What it is for\n\nOn chain, the storage bill follows what changed. A snapshot taken by copying an\navl tree writes the whole tree; a snapshot taken by `Clone` writes nothing.\nThat makes cheap versioning practical: a proposal that must be evaluated\nagainst the state at submission time, an undo point before a batch, a\nbefore/after diff, a speculative apply you might throw away.\n\n## The one thing to get right\n\nStructural sharing is automatic. **Value copying is not.**\n\n- Simple values (`int`, `string`, ...) are copied by value. Nothing to do.\n- Structs and pointers are copied by reference. Mutating the pointed-to value\n  through one tree mutates what the other tree sees, which is exactly the bug\n  copy-on-write was supposed to prevent.\n\nIf your values are mutable, store an immutable representation or deep-copy on\nwrite yourself. The tree cannot do it for you.\n\n## API\n\nSame as `p/nt/avl`. On `Tree`: `Set`, `Get`, `Has`, `Remove`, `Size`,\n`GetByIndex`, `Iterate`, `ReverseIterate`, `IterateByOffset`,\n`ReverseIterateByOffset`, plus `Clone`. `Node` additionally exposes\n`TraverseInRange` and `TraverseByOffset` for walking inner nodes.\n\n`Equal` (on either type) is a full recursive structural comparison. It is there\nfor tests: do not call it from realm code.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/cow/v0\"\ngno = \"0.9\"\n"},{"name":"node.gno","body":"package cow\n\n//----------------------------------------\n// Node\n\n// Node represents a node in an AVL tree.\ntype Node struct {\n\tkey       string // key is the unique identifier for the node.\n\tvalue     any    // value is the data stored in the node.\n\theight    int8   // height is the height of the node in the tree.\n\tsize      int    // size is the number of nodes in the subtree rooted at this node.\n\tleftNode  *Node  // leftNode is the left child of the node.\n\trightNode *Node  // rightNode is the right child of the node.\n}\n\n// NewNode creates a new node with the given key and value.\nfunc NewNode(key string, value any) *Node {\n\treturn \u0026Node{\n\t\tkey:    key,\n\t\tvalue:  value,\n\t\theight: 0,\n\t\tsize:   1,\n\t}\n}\n\n// Size returns the size of the subtree rooted at the node.\nfunc (node *Node) Size() int {\n\tif node == nil {\n\t\treturn 0\n\t}\n\treturn node.size\n}\n\n// IsLeaf checks if the node is a leaf node (has no children).\nfunc (node *Node) IsLeaf() bool {\n\treturn node.height == 0\n}\n\n// Key returns the key of the node.\nfunc (node *Node) Key() string {\n\treturn node.key\n}\n\n// Value returns the value of the node.\nfunc (node *Node) Value() any {\n\treturn node.value\n}\n\n// _copy creates a copy of the node (excluding value).\nfunc (node *Node) _copy() *Node {\n\tif node.height == 0 {\n\t\tpanic(\"Why are you copying a value node?\")\n\t}\n\treturn \u0026Node{\n\t\tkey:       node.key,\n\t\theight:    node.height,\n\t\tsize:      node.size,\n\t\tleftNode:  node.leftNode,\n\t\trightNode: node.rightNode,\n\t}\n}\n\n// Has checks if a node with the given key exists in the subtree rooted at the node.\nfunc (node *Node) Has(key string) (has bool) {\n\tif node == nil {\n\t\treturn false\n\t}\n\tif node.key == key {\n\t\treturn true\n\t}\n\tif node.height == 0 {\n\t\treturn false\n\t}\n\tif key \u003c node.key {\n\t\treturn node.getLeftNode().Has(key)\n\t}\n\treturn node.getRightNode().Has(key)\n}\n\n// Get searches for a node with the given key in the subtree rooted at the node\n// and returns its index, value, and whether it exists.\nfunc (node *Node) Get(key string) (index int, value any, exists bool) {\n\tif node == nil {\n\t\treturn 0, nil, false\n\t}\n\n\tif node.height == 0 {\n\t\tif node.key == key {\n\t\t\treturn 0, node.value, true\n\t\t}\n\t\tif node.key \u003c key {\n\t\t\treturn 1, nil, false\n\t\t}\n\t\treturn 0, nil, false\n\t}\n\n\tif key \u003c node.key {\n\t\treturn node.getLeftNode().Get(key)\n\t}\n\n\trightNode := node.getRightNode()\n\tindex, value, exists = rightNode.Get(key)\n\tindex += node.size - rightNode.size\n\treturn index, value, exists\n}\n\n// GetByIndex retrieves the key-value pair of the node at the given index\n// in the subtree rooted at the node.\nfunc (node *Node) GetByIndex(index int) (key string, value any) {\n\tif node.height == 0 {\n\t\tif index == 0 {\n\t\t\treturn node.key, node.value\n\t\t}\n\t\tpanic(\"GetByIndex asked for invalid index\")\n\t}\n\t// TODO: could improve this by storing the sizes\n\tleftNode := node.getLeftNode()\n\tif index \u003c leftNode.size {\n\t\treturn leftNode.GetByIndex(index)\n\t}\n\treturn node.getRightNode().GetByIndex(index - leftNode.size)\n}\n\n// Set inserts a new node with the given key-value pair into the subtree rooted at the node,\n// and returns the new root of the subtree and whether an existing node was updated.\n//\n// XXX consider a better way to do this... perhaps split Node from Node.\nfunc (node *Node) Set(key string, value any) (newSelf *Node, updated bool) {\n\tif node == nil {\n\t\treturn NewNode(key, value), false\n\t}\n\n\t// Always create a new node for leaf nodes\n\tif node.height == 0 {\n\t\treturn node.setLeaf(key, value)\n\t}\n\n\t// Copy the node before modifying\n\tnewNode := node._copy()\n\tif key \u003c node.key {\n\t\tnewNode.leftNode, updated = node.getLeftNode().Set(key, value)\n\t} else {\n\t\tnewNode.rightNode, updated = node.getRightNode().Set(key, value)\n\t}\n\n\tif !updated {\n\t\tnewNode.calcHeightAndSize()\n\t\treturn newNode.balance(), updated\n\t}\n\n\treturn newNode, updated\n}\n\n// setLeaf inserts a new leaf node with the given key-value pair into the subtree rooted at the node,\n// and returns the new root of the subtree and whether an existing node was updated.\nfunc (node *Node) setLeaf(key string, value any) (newSelf *Node, updated bool) {\n\tif key == node.key {\n\t\treturn NewNode(key, value), true\n\t}\n\n\tif key \u003c node.key {\n\t\treturn \u0026Node{\n\t\t\tkey:       node.key,\n\t\t\theight:    1,\n\t\t\tsize:      2,\n\t\t\tleftNode:  NewNode(key, value),\n\t\t\trightNode: node,\n\t\t}, false\n\t}\n\n\treturn \u0026Node{\n\t\tkey:       key,\n\t\theight:    1,\n\t\tsize:      2,\n\t\tleftNode:  node,\n\t\trightNode: NewNode(key, value),\n\t}, false\n}\n\n// Remove deletes the node with the given key from the subtree rooted at the node.\n// returns the new root of the subtree, the new leftmost leaf key (if changed),\n// the removed value and the removal was successful.\nfunc (node *Node) Remove(key string) (\n\tnewNode *Node, newKey string, value any, removed bool,\n) {\n\tif node == nil {\n\t\treturn nil, \"\", nil, false\n\t}\n\tif node.height == 0 {\n\t\tif key == node.key {\n\t\t\treturn nil, \"\", node.value, true\n\t\t}\n\t\treturn node, \"\", nil, false\n\t}\n\tif key \u003c node.key {\n\t\tvar newLeftNode *Node\n\t\tnewLeftNode, newKey, value, removed = node.getLeftNode().Remove(key)\n\t\tif !removed {\n\t\t\treturn node, \"\", value, false\n\t\t}\n\t\tif newLeftNode == nil { // left node held value, was removed\n\t\t\treturn node.rightNode, node.key, value, true\n\t\t}\n\t\tnode = node._copy()\n\t\tnode.leftNode = newLeftNode\n\t\tnode.calcHeightAndSize()\n\t\tnode = node.balance()\n\t\treturn node, newKey, value, true\n\t}\n\n\tvar newRightNode *Node\n\tnewRightNode, newKey, value, removed = node.getRightNode().Remove(key)\n\tif !removed {\n\t\treturn node, \"\", value, false\n\t}\n\tif newRightNode == nil { // right node held value, was removed\n\t\treturn node.leftNode, \"\", value, true\n\t}\n\tnode = node._copy()\n\tnode.rightNode = newRightNode\n\tif newKey != \"\" {\n\t\tnode.key = newKey\n\t}\n\tnode.calcHeightAndSize()\n\tnode = node.balance()\n\treturn node, \"\", value, true\n}\n\n// getLeftNode returns the left child of the node.\nfunc (node *Node) getLeftNode() *Node {\n\treturn node.leftNode\n}\n\n// getRightNode returns the right child of the node.\nfunc (node *Node) getRightNode() *Node {\n\treturn node.rightNode\n}\n\n// rotateRight performs a right rotation on the node and returns the new root.\n// NOTE: overwrites node\n// TODO: optimize balance \u0026 rotate\nfunc (node *Node) rotateRight() *Node {\n\tnode = node._copy()\n\tl := node.getLeftNode()\n\t_l := l._copy()\n\n\t_lrCached := _l.rightNode\n\t_l.rightNode = node\n\tnode.leftNode = _lrCached\n\n\tnode.calcHeightAndSize()\n\t_l.calcHeightAndSize()\n\n\treturn _l\n}\n\n// rotateLeft performs a left rotation on the node and returns the new root.\n// NOTE: overwrites node\n// TODO: optimize balance \u0026 rotate\nfunc (node *Node) rotateLeft() *Node {\n\tnode = node._copy()\n\tr := node.getRightNode()\n\t_r := r._copy()\n\n\t_rlCached := _r.leftNode\n\t_r.leftNode = node\n\tnode.rightNode = _rlCached\n\n\tnode.calcHeightAndSize()\n\t_r.calcHeightAndSize()\n\n\treturn _r\n}\n\n// calcHeightAndSize updates the height and size of the node based on its children.\n// NOTE: mutates height and size\nfunc (node *Node) calcHeightAndSize() {\n\tnode.height = maxInt8(node.getLeftNode().height, node.getRightNode().height) + 1\n\tnode.size = node.getLeftNode().size + node.getRightNode().size\n}\n\n// calcBalance calculates the balance factor of the node.\nfunc (node *Node) calcBalance() int {\n\treturn int(node.getLeftNode().height) - int(node.getRightNode().height)\n}\n\n// balance balances the subtree rooted at the node and returns the new root.\n// NOTE: assumes that node can be modified\n// TODO: optimize balance \u0026 rotate\nfunc (node *Node) balance() (newSelf *Node) {\n\tbalance := node.calcBalance()\n\tif balance \u003e= -1 {\n\t\treturn node\n\t}\n\tif balance \u003e 1 {\n\t\tif node.getLeftNode().calcBalance() \u003e= 0 {\n\t\t\t// Left Left Case\n\t\t\treturn node.rotateRight()\n\t\t}\n\t\t// Left Right Case\n\t\tleft := node.getLeftNode()\n\t\tnode.leftNode = left.rotateLeft()\n\t\treturn node.rotateRight()\n\t}\n\n\tif node.getRightNode().calcBalance() \u003c= 0 {\n\t\t// Right Right Case\n\t\treturn node.rotateLeft()\n\t}\n\n\t// Right Left Case\n\tright := node.getRightNode()\n\tnode.rightNode = right.rotateRight()\n\treturn node.rotateLeft()\n}\n\n// Shortcut for TraverseInRange.\nfunc (node *Node) Iterate(start, end string, cb func(*Node) bool) bool {\n\treturn node.TraverseInRange(start, end, true, true, cb)\n}\n\n// Shortcut for TraverseInRange.\nfunc (node *Node) ReverseIterate(start, end string, cb func(*Node) bool) bool {\n\treturn node.TraverseInRange(start, end, false, true, cb)\n}\n\n// TraverseInRange traverses all nodes, including inner nodes.\n// Start is inclusive and end is exclusive when ascending,\n// Start and end are inclusive when descending.\n// Empty start and empty end denote no start and no end.\n// If leavesOnly is true, only visit leaf nodes.\n// NOTE: To simulate an exclusive reverse traversal,\n// just append 0x00 to start.\nfunc (node *Node) TraverseInRange(start, end string, ascending bool, leavesOnly bool, cb func(*Node) bool) bool {\n\tif node == nil {\n\t\treturn false\n\t}\n\tafterStart := (start == \"\" || start \u003c node.key)\n\tstartOrAfter := (start == \"\" || start \u003c= node.key)\n\tbeforeEnd := false\n\tif ascending {\n\t\tbeforeEnd = (end == \"\" || node.key \u003c end)\n\t} else {\n\t\tbeforeEnd = (end == \"\" || node.key \u003c= end)\n\t}\n\n\t// Run callback per inner/leaf node.\n\tstop := false\n\tif (!node.IsLeaf() \u0026\u0026 !leavesOnly) ||\n\t\t(node.IsLeaf() \u0026\u0026 startOrAfter \u0026\u0026 beforeEnd) {\n\t\tstop = cb(node)\n\t\tif stop {\n\t\t\treturn stop\n\t\t}\n\t}\n\tif node.IsLeaf() {\n\t\treturn stop\n\t}\n\n\tif ascending {\n\t\t// check lower nodes, then higher\n\t\tif afterStart {\n\t\t\tstop = node.getLeftNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t\tif stop {\n\t\t\treturn stop\n\t\t}\n\t\tif beforeEnd {\n\t\t\tstop = node.getRightNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t} else {\n\t\t// check the higher nodes first\n\t\tif beforeEnd {\n\t\t\tstop = node.getRightNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t\tif stop {\n\t\t\treturn stop\n\t\t}\n\t\tif afterStart {\n\t\t\tstop = node.getLeftNode().TraverseInRange(start, end, ascending, leavesOnly, cb)\n\t\t}\n\t}\n\n\treturn stop\n}\n\n// TraverseByOffset traverses all nodes, including inner nodes.\n// A limit of math.MaxInt means no limit.\nfunc (node *Node) TraverseByOffset(offset, limit int, descending bool, leavesOnly bool, cb func(*Node) bool) bool {\n\tif node == nil {\n\t\treturn false\n\t}\n\n\t// fast paths. these happen only if TraverseByOffset is called directly on a leaf.\n\tif limit \u003c= 0 || offset \u003e= node.size {\n\t\treturn false\n\t}\n\tif node.IsLeaf() {\n\t\tif offset \u003e 0 {\n\t\t\treturn false\n\t\t}\n\t\treturn cb(node)\n\t}\n\n\t// go to the actual recursive function.\n\treturn node.traverseByOffset(offset, limit, descending, leavesOnly, cb)\n}\n\n// TraverseByOffset traverses the subtree rooted at the node by offset and limit,\n// in either ascending or descending order, and applies the callback function to each traversed node.\n// If leavesOnly is true, only leaf nodes are visited.\nfunc (node *Node) traverseByOffset(offset, limit int, descending bool, leavesOnly bool, cb func(*Node) bool) bool {\n\t// caller guarantees: offset \u003c node.size; limit \u003e 0.\n\tif !leavesOnly {\n\t\tif cb(node) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfirst, second := node.getLeftNode(), node.getRightNode()\n\tif descending {\n\t\tfirst, second = second, first\n\t}\n\tif first.IsLeaf() {\n\t\t// either run or skip, based on offset\n\t\tif offset \u003e 0 {\n\t\t\toffset--\n\t\t} else {\n\t\t\tcb(first)\n\t\t\tlimit--\n\t\t\tif limit \u003c= 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// possible cases:\n\t\t// 1 the offset given skips the first node entirely\n\t\t// 2 the offset skips none or part of the first node, but the limit requires some of the second node.\n\t\t// 3 the offset skips none or part of the first node, and the limit stops our search on the first node.\n\t\tif offset \u003e= first.size {\n\t\t\toffset -= first.size // 1\n\t\t} else {\n\t\t\tif first.traverseByOffset(offset, limit, descending, leavesOnly, cb) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// number of leaves which could actually be called from inside\n\t\t\tdelta := first.size - offset\n\t\t\toffset = 0\n\t\t\tif delta \u003e= limit {\n\t\t\t\treturn true // 3\n\t\t\t}\n\t\t\tlimit -= delta // 2\n\t\t}\n\t}\n\n\t// because of the caller guarantees and the way we handle the first node,\n\t// at this point we know that limit \u003e 0 and there must be some values in\n\t// this second node that we include.\n\n\t// =\u003e if the second node is a leaf, it has to be included.\n\tif second.IsLeaf() {\n\t\treturn cb(second)\n\t}\n\t// =\u003e if it is not a leaf, it will still be enough to recursively call this\n\t// function with the updated offset and limit\n\treturn second.traverseByOffset(offset, limit, descending, leavesOnly, cb)\n}\n\n// Only used in testing...\nfunc (node *Node) lmd() *Node {\n\tif node.height == 0 {\n\t\treturn node\n\t}\n\treturn node.getLeftNode().lmd()\n}\n\n// Only used in testing...\nfunc (node *Node) rmd() *Node {\n\tif node.height == 0 {\n\t\treturn node\n\t}\n\treturn node.getRightNode().rmd()\n}\n\nfunc maxInt8(a, b int8) int8 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n// Equal compares two nodes for structural equality.\n// WARNING: This is an expensive operation that recursively traverses the entire tree structure.\n// It should only be used in tests or when absolutely necessary.\nfunc (node *Node) Equal(other *Node) bool {\n\t// Handle nil cases\n\tif node == nil || other == nil {\n\t\treturn node == other\n\t}\n\n\t// Compare node properties\n\tif node.key != other.key ||\n\t\tnode.value != other.value ||\n\t\tnode.height != other.height ||\n\t\tnode.size != other.size {\n\t\treturn false\n\t}\n\n\t// Compare children\n\tleftEqual := (node.leftNode == nil \u0026\u0026 other.leftNode == nil) ||\n\t\t(node.leftNode != nil \u0026\u0026 other.leftNode != nil \u0026\u0026 node.leftNode.Equal(other.leftNode))\n\tif !leftEqual {\n\t\treturn false\n\t}\n\n\trightEqual := (node.rightNode == nil \u0026\u0026 other.rightNode == nil) ||\n\t\t(node.rightNode != nil \u0026\u0026 other.rightNode != nil \u0026\u0026 node.rightNode.Equal(other.rightNode))\n\treturn rightEqual\n}\n"},{"name":"node_test.gno","body":"package cow\n\nimport (\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc TestTraverseByOffset(t *testing.T) {\n\tconst testStrings = `Alfa\nAlfred\nAlpha\nAlphabet\nBeta\nBeth\nBook\nBrowser`\n\ttt := []struct {\n\t\tname string\n\t\tdesc bool\n\t}{\n\t\t{\"ascending\", false},\n\t\t{\"descending\", true},\n\t}\n\n\tfor _, tt := range tt {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsl := strings.Split(testStrings, \"\\n\")\n\n\t\t\t// sort a first time in the order opposite to how we'll be traversing\n\t\t\t// the tree, to ensure that we are not just iterating through with\n\t\t\t// insertion order.\n\t\t\tsort.Strings(sl)\n\t\t\tif !tt.desc {\n\t\t\t\treverseSlice(sl)\n\t\t\t}\n\n\t\t\tr := NewNode(sl[0], nil)\n\t\t\tfor _, v := range sl[1:] {\n\t\t\t\tr, _ = r.Set(v, nil)\n\t\t\t}\n\n\t\t\t// then sort sl in the order we'll be traversing it, so that we can\n\t\t\t// compare the result with sl.\n\t\t\treverseSlice(sl)\n\n\t\t\tvar result []string\n\t\t\tfor i := 0; i \u003c len(sl); i++ {\n\t\t\t\tr.TraverseByOffset(i, 1, tt.desc, true, func(n *Node) bool {\n\t\t\t\t\tresult = append(result, n.Key())\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif !slicesEqual(sl, result) {\n\t\t\t\tt.Errorf(\"want %v got %v\", sl, result)\n\t\t\t}\n\n\t\t\tfor l := 2; l \u003c= len(sl); l++ {\n\t\t\t\t// \"slices\"\n\t\t\t\tfor i := 0; i \u003c= len(sl); i++ {\n\t\t\t\t\tmax := i + l\n\t\t\t\t\tif max \u003e len(sl) {\n\t\t\t\t\t\tmax = len(sl)\n\t\t\t\t\t}\n\t\t\t\t\texp := sl[i:max]\n\t\t\t\t\tactual := []string{}\n\n\t\t\t\t\tr.TraverseByOffset(i, l, tt.desc, true, func(tr *Node) bool {\n\t\t\t\t\t\tactual = append(actual, tr.Key())\n\t\t\t\t\t\treturn false\n\t\t\t\t\t})\n\t\t\t\t\tif !slicesEqual(exp, actual) {\n\t\t\t\t\t\tt.Errorf(\"want %v got %v\", exp, actual)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHas(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []string\n\t\thasKey   string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\t\"has key in non-empty tree\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"B\",\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"does not have key in non-empty tree\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"F\",\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"has key in single-node tree\",\n\t\t\t[]string{\"A\"},\n\t\t\t\"A\",\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"does not have key in single-node tree\",\n\t\t\t[]string{\"A\"},\n\t\t\t\"B\",\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"does not have key in empty tree\",\n\t\t\t[]string{},\n\t\t\t\"A\",\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar tree *Node\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree, _ = tree.Set(key, nil)\n\t\t\t}\n\n\t\t\tresult := tree.Has(tt.hasKey)\n\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"Expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tinput        []string\n\t\tgetKey       string\n\t\texpectIdx    int\n\t\texpectVal    any\n\t\texpectExists bool\n\t}{\n\t\t{\n\t\t\t\"get existing key\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"B\",\n\t\t\t1,\n\t\t\tnil,\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"get non-existent key (smaller)\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"@\",\n\t\t\t0,\n\t\t\tnil,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"get non-existent key (larger)\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"F\",\n\t\t\t5,\n\t\t\tnil,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"get from empty tree\",\n\t\t\t[]string{},\n\t\t\t\"A\",\n\t\t\t0,\n\t\t\tnil,\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar tree *Node\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree, _ = tree.Set(key, nil)\n\t\t\t}\n\n\t\t\tidx, val, exists := tree.Get(tt.getKey)\n\n\t\t\tif idx != tt.expectIdx {\n\t\t\t\tt.Errorf(\"Expected index %d, got %d\", tt.expectIdx, idx)\n\t\t\t}\n\n\t\t\tif val != tt.expectVal {\n\t\t\t\tt.Errorf(\"Expected value %v, got %v\", tt.expectVal, val)\n\t\t\t}\n\n\t\t\tif exists != tt.expectExists {\n\t\t\t\tt.Errorf(\"Expected exists %t, got %t\", tt.expectExists, exists)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetByIndex(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tinput       []string\n\t\tidx         int\n\t\texpectKey   string\n\t\texpectVal   any\n\t\texpectPanic bool\n\t}{\n\t\t{\n\t\t\t\"get by valid index\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t2,\n\t\t\t\"C\",\n\t\t\tnil,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"get by valid index (smallest)\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t0,\n\t\t\t\"A\",\n\t\t\tnil,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"get by valid index (largest)\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t4,\n\t\t\t\"E\",\n\t\t\tnil,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"get by invalid index (negative)\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t-1,\n\t\t\t\"\",\n\t\t\tnil,\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"get by invalid index (out of range)\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t5,\n\t\t\t\"\",\n\t\t\tnil,\n\t\t\ttrue,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar tree *Node\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree, _ = tree.Set(key, nil)\n\t\t\t}\n\n\t\t\tif tt.expectPanic {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r == nil {\n\t\t\t\t\t\tt.Errorf(\"Expected a panic but didn't get one\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\tkey, val := tree.GetByIndex(tt.idx)\n\n\t\t\tif !tt.expectPanic {\n\t\t\t\tif key != tt.expectKey {\n\t\t\t\t\tt.Errorf(\"Expected key %s, got %s\", tt.expectKey, key)\n\t\t\t\t}\n\n\t\t\t\tif val != tt.expectVal {\n\t\t\t\t\tt.Errorf(\"Expected value %v, got %v\", tt.expectVal, val)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRemove(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinput     []string\n\t\tremoveKey string\n\t\texpected  []string\n\t}{\n\t\t{\n\t\t\t\"remove leaf node\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"D\"},\n\t\t\t\"B\",\n\t\t\t[]string{\"A\", \"C\", \"D\"},\n\t\t},\n\t\t{\n\t\t\t\"remove node with one child\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"D\"},\n\t\t\t\"A\",\n\t\t\t[]string{\"B\", \"C\", \"D\"},\n\t\t},\n\t\t{\n\t\t\t\"remove node with two children\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"C\",\n\t\t\t[]string{\"A\", \"B\", \"D\", \"E\"},\n\t\t},\n\t\t{\n\t\t\t\"remove root node\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"C\",\n\t\t\t[]string{\"A\", \"B\", \"D\", \"E\"},\n\t\t},\n\t\t{\n\t\t\t\"remove non-existent key\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t\"F\",\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar tree *Node\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree, _ = tree.Set(key, nil)\n\t\t\t}\n\n\t\t\ttree, _, _, _ = tree.Remove(tt.removeKey)\n\n\t\t\tresult := make([]string, 0)\n\t\t\ttree.Iterate(\"\", \"\", func(n *Node) bool {\n\t\t\t\tresult = append(result, n.Key())\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\tif !slicesEqual(tt.expected, result) {\n\t\t\t\tt.Errorf(\"want %v got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTraverse(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []string\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\t\"empty tree\",\n\t\t\t[]string{},\n\t\t\t[]string{},\n\t\t},\n\t\t{\n\t\t\t\"single node tree\",\n\t\t\t[]string{\"A\"},\n\t\t\t[]string{\"A\"},\n\t\t},\n\t\t{\n\t\t\t\"small tree\",\n\t\t\t[]string{\"C\", \"A\", \"B\", \"E\", \"D\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t},\n\t\t{\n\t\t\t\"large tree\",\n\t\t\t[]string{\"H\", \"D\", \"L\", \"B\", \"F\", \"J\", \"N\", \"A\", \"C\", \"E\", \"G\", \"I\", \"K\", \"M\", \"O\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar tree *Node\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree, _ = tree.Set(key, nil)\n\t\t\t}\n\n\t\t\tt.Run(\"iterate\", func(t *testing.T) {\n\t\t\t\tvar result []string\n\t\t\t\ttree.Iterate(\"\", \"\", func(n *Node) bool {\n\t\t\t\t\tresult = append(result, n.Key())\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\tif !slicesEqual(tt.expected, result) {\n\t\t\t\t\tt.Errorf(\"want %v got %v\", tt.expected, result)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tt.Run(\"ReverseIterate\", func(t *testing.T) {\n\t\t\t\tvar result []string\n\t\t\t\ttree.ReverseIterate(\"\", \"\", func(n *Node) bool {\n\t\t\t\t\tresult = append(result, n.Key())\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\texpected := make([]string, len(tt.expected))\n\t\t\t\tcopy(expected, tt.expected)\n\t\t\t\tfor i, j := 0, len(expected)-1; i \u003c j; i, j = i+1, j-1 {\n\t\t\t\t\texpected[i], expected[j] = expected[j], expected[i]\n\t\t\t\t}\n\t\t\t\tif !slicesEqual(expected, result) {\n\t\t\t\t\tt.Errorf(\"want %v got %v\", expected, result)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tt.Run(\"TraverseInRange\", func(t *testing.T) {\n\t\t\t\tvar result []string\n\t\t\t\tstart, end := \"C\", \"M\"\n\t\t\t\ttree.TraverseInRange(start, end, true, true, func(n *Node) bool {\n\t\t\t\t\tresult = append(result, n.Key())\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\texpected := make([]string, 0)\n\t\t\t\tfor _, key := range tt.expected {\n\t\t\t\t\tif key \u003e= start \u0026\u0026 key \u003c end {\n\t\t\t\t\t\texpected = append(expected, key)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !slicesEqual(expected, result) {\n\t\t\t\t\tt.Errorf(\"want %v got %v\", expected, result)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestRotateWhenHeightDiffers(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []string\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\t\"right rotation when left subtree is higher\",\n\t\t\t[]string{\"E\", \"C\", \"A\", \"B\", \"D\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"E\", \"D\"},\n\t\t},\n\t\t{\n\t\t\t\"left rotation when right subtree is higher\",\n\t\t\t[]string{\"A\", \"C\", \"E\", \"D\", \"F\"},\n\t\t\t[]string{\"A\", \"C\", \"D\", \"E\", \"F\"},\n\t\t},\n\t\t{\n\t\t\t\"left-right rotation\",\n\t\t\t[]string{\"E\", \"A\", \"C\", \"B\", \"D\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"E\", \"D\"},\n\t\t},\n\t\t{\n\t\t\t\"right-left rotation\",\n\t\t\t[]string{\"A\", \"E\", \"C\", \"B\", \"D\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"E\", \"D\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar tree *Node\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree, _ = tree.Set(key, nil)\n\t\t\t}\n\n\t\t\t// perform rotation or balance\n\t\t\ttree = tree.balance()\n\n\t\t\t// check tree structure\n\t\t\tvar result []string\n\t\t\ttree.Iterate(\"\", \"\", func(n *Node) bool {\n\t\t\t\tresult = append(result, n.Key())\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\tif !slicesEqual(tt.expected, result) {\n\t\t\t\tt.Errorf(\"want %v got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRotateAndBalance(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []string\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\t\"right rotation\",\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t},\n\t\t{\n\t\t\t\"left rotation\",\n\t\t\t[]string{\"E\", \"D\", \"C\", \"B\", \"A\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t},\n\t\t{\n\t\t\t\"left-right rotation\",\n\t\t\t[]string{\"C\", \"A\", \"E\", \"B\", \"D\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t},\n\t\t{\n\t\t\t\"right-left rotation\",\n\t\t\t[]string{\"C\", \"E\", \"A\", \"D\", \"B\"},\n\t\t\t[]string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar tree *Node\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree, _ = tree.Set(key, nil)\n\t\t\t}\n\n\t\t\ttree = tree.balance()\n\n\t\t\tvar result []string\n\t\t\ttree.Iterate(\"\", \"\", func(n *Node) bool {\n\t\t\t\tresult = append(result, n.Key())\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\tif !slicesEqual(tt.expected, result) {\n\t\t\t\tt.Errorf(\"want %v got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc slicesEqual(w1, w2 []string) bool {\n\tif len(w1) != len(w2) {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(w1); i++ {\n\t\tif w1[0] != w2[0] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc maxint8(a, b int8) int8 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc reverseSlice(ss []string) {\n\tfor i := 0; i \u003c len(ss)/2; i++ {\n\t\tj := len(ss) - 1 - i\n\t\tss[i], ss[j] = ss[j], ss[i]\n\t}\n}\n\nfunc TestNodeStructuralSharing(t *testing.T) {\n\tt.Run(\"unmodified paths remain shared\", func(t *testing.T) {\n\t\troot := NewNode(\"B\", 2)\n\t\troot, _ = root.Set(\"A\", 1)\n\t\troot, _ = root.Set(\"C\", 3)\n\n\t\toriginalRight := root.rightNode\n\t\tnewRoot, _ := root.Set(\"A\", 10)\n\n\t\tif newRoot.rightNode != originalRight {\n\t\t\tt.Error(\"Unmodified right subtree should remain shared\")\n\t\t}\n\t})\n\n\tt.Run(\"multiple modifications reuse shared structure\", func(t *testing.T) {\n\t\t// Create initial tree\n\t\troot := NewNode(\"B\", 2)\n\t\troot, _ = root.Set(\"A\", 1)\n\t\troot, _ = root.Set(\"C\", 3)\n\n\t\t// Store original nodes\n\t\toriginalRight := root.rightNode\n\n\t\t// First modification\n\t\tmod1, _ := root.Set(\"A\", 10)\n\n\t\t// Second modification\n\t\tmod2, _ := mod1.Set(\"C\", 30)\n\n\t\t// Check sharing in first modification\n\t\tif mod1.rightNode != originalRight {\n\t\t\tt.Error(\"First modification should share unmodified right subtree\")\n\t\t}\n\n\t\t// Check that second modification creates new right node\n\t\tif mod2.rightNode == originalRight {\n\t\t\tt.Error(\"Second modification should create new right node\")\n\t\t}\n\t})\n}\n\nfunc TestNodeCopyOnWrite(t *testing.T) {\n\tt.Run(\"copy preserves structure\", func(t *testing.T) {\n\t\troot := NewNode(\"B\", 2)\n\t\troot, _ = root.Set(\"A\", 1)\n\t\troot, _ = root.Set(\"C\", 3)\n\n\t\t// Only copy non-leaf nodes\n\t\tif !root.IsLeaf() {\n\t\t\tcopied := root._copy()\n\t\t\tif copied == root {\n\t\t\t\tt.Error(\"Copy should create new instance\")\n\t\t\t}\n\n\t\t\t// Create temporary trees to use Equal method\n\t\t\toriginal := \u0026Tree{node: root}\n\t\t\tcopiedTree := \u0026Tree{node: copied}\n\t\t\tif !original.Equal(copiedTree) {\n\t\t\t\tt.Error(\"Copied node should preserve structure\")\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"removal copy pattern\", func(t *testing.T) {\n\t\t// Create a more complex tree to test removal\n\t\troot := NewNode(\"B\", 2)\n\t\troot, _ = root.Set(\"A\", 1)\n\t\troot, _ = root.Set(\"C\", 3)\n\t\troot, _ = root.Set(\"D\", 4) // Add this to ensure proper tree structure\n\n\t\t// Store references to original nodes\n\t\toriginalRight := root.rightNode\n\t\toriginalRightRight := originalRight.rightNode\n\n\t\t// Remove \"A\" which should only affect the left subtree\n\t\tnewRoot, _, _, _ := root.Remove(\"A\")\n\n\t\t// Verify right subtree remains unchanged and shared\n\t\tif newRoot.rightNode != originalRight {\n\t\t\tt.Error(\"Right subtree should remain shared during removal of left node\")\n\t\t}\n\n\t\t// Also verify deeper nodes remain shared\n\t\tif newRoot.rightNode.rightNode != originalRightRight {\n\t\t\tt.Error(\"Deep right subtree should remain shared during removal\")\n\t\t}\n\n\t\t// Verify original tree is unchanged\n\t\tif _, _, exists := root.Get(\"A\"); !exists {\n\t\t\tt.Error(\"Original tree should remain unchanged\")\n\t\t}\n\t})\n\n\tt.Run(\"copy leaf node panic\", func(t *testing.T) {\n\t\tleaf := NewNode(\"A\", 1)\n\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Error(\"Expected panic when copying leaf node\")\n\t\t\t}\n\t\t}()\n\n\t\t// This should panic with our specific message\n\t\tleaf._copy()\n\t})\n}\n\nfunc TestNodeEqual(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tnode1    func() *Node\n\t\tnode2    func() *Node\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname:     \"nil nodes\",\n\t\t\tnode1:    func() *Node { return nil },\n\t\t\tnode2:    func() *Node { return nil },\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"one nil node\",\n\t\t\tnode1:    func() *Node { return NewNode(\"A\", 1) },\n\t\t\tnode2:    func() *Node { return nil },\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"single leaf nodes equal\",\n\t\t\tnode1:    func() *Node { return NewNode(\"A\", 1) },\n\t\t\tnode2:    func() *Node { return NewNode(\"A\", 1) },\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"single leaf nodes different key\",\n\t\t\tnode1:    func() *Node { return NewNode(\"A\", 1) },\n\t\t\tnode2:    func() *Node { return NewNode(\"B\", 1) },\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"single leaf nodes different value\",\n\t\t\tnode1:    func() *Node { return NewNode(\"A\", 1) },\n\t\t\tnode2:    func() *Node { return NewNode(\"A\", 2) },\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"complex trees equal\",\n\t\t\tnode1: func() *Node {\n\t\t\t\tn, _ := NewNode(\"B\", 2).Set(\"A\", 1)\n\t\t\t\tn, _ = n.Set(\"C\", 3)\n\t\t\t\treturn n\n\t\t\t},\n\t\t\tnode2: func() *Node {\n\t\t\t\tn, _ := NewNode(\"B\", 2).Set(\"A\", 1)\n\t\t\t\tn, _ = n.Set(\"C\", 3)\n\t\t\t\treturn n\n\t\t\t},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"complex trees different structure\",\n\t\t\tnode1: func() *Node {\n\t\t\t\t// Create a tree with structure:\n\t\t\t\t//     B\n\t\t\t\t//    / \\\n\t\t\t\t//   A   D\n\t\t\t\tn := NewNode(\"B\", 2)\n\t\t\t\tn, _ = n.Set(\"A\", 1)\n\t\t\t\tn, _ = n.Set(\"D\", 4)\n\t\t\t\treturn n\n\t\t\t},\n\t\t\tnode2: func() *Node {\n\t\t\t\t// Create a tree with structure:\n\t\t\t\t//     C\n\t\t\t\t//    / \\\n\t\t\t\t//   A   D\n\t\t\t\tn := NewNode(\"C\", 3)\n\t\t\t\tn, _ = n.Set(\"A\", 1)\n\t\t\t\tn, _ = n.Set(\"D\", 4)\n\t\t\t\treturn n\n\t\t\t},\n\t\t\texpected: false, // These trees should be different\n\t\t},\n\t\t{\n\t\t\tname: \"complex trees same structure despite different insertion order\",\n\t\t\tnode1: func() *Node {\n\t\t\t\tn, _ := NewNode(\"B\", 2).Set(\"A\", 1)\n\t\t\t\tn, _ = n.Set(\"C\", 3)\n\t\t\t\treturn n\n\t\t\t},\n\t\t\tnode2: func() *Node {\n\t\t\t\tn, _ := NewNode(\"A\", 1).Set(\"B\", 2)\n\t\t\t\tn, _ = n.Set(\"C\", 3)\n\t\t\t\treturn n\n\t\t\t},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"truly different structures\",\n\t\t\tnode1: func() *Node {\n\t\t\t\tn, _ := NewNode(\"B\", 2).Set(\"A\", 1)\n\t\t\t\treturn n // Tree with just two nodes\n\t\t\t},\n\t\t\tnode2: func() *Node {\n\t\t\t\tn, _ := NewNode(\"B\", 2).Set(\"C\", 3)\n\t\t\t\treturn n // Different two-node tree\n\t\t\t},\n\t\t\texpected: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tnode1 := tt.node1()\n\t\t\tnode2 := tt.node2()\n\t\t\tresult := node1.Equal(node2)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"Expected Equal to return %v for %s\", tt.expected, tt.name)\n\t\t\t\tprintln(\"\\nComparison failed:\")\n\t\t\t\tprintln(\"Tree 1:\")\n\t\t\t\tprintTree(node1, 0)\n\t\t\t\tprintln(\"Tree 2:\")\n\t\t\t\tprintTree(node2, 0)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Helper function to print tree structure\nfunc printTree(node *Node, level int) {\n\tif node == nil {\n\t\treturn\n\t}\n\tindent := strings.Repeat(\"  \", level)\n\tprintln(ufmt.Sprintf(\"%sKey: %s, Value: %v, Height: %d, Size: %d\",\n\t\tindent, node.key, node.value, node.height, node.size))\n\tprintTree(node.leftNode, level+1)\n\tprintTree(node.rightNode, level+1)\n}\n"},{"name":"tree.gno","body":"// Package cow provides a Copy-on-Write (CoW) AVL tree implementation.\n// This is a fork of gno.land/p/nt/avl that adds CoW functionality\n// while maintaining the original AVL tree interface and properties.\n//\n// Copy-on-Write creates a copy of a data structure only when it is modified,\n// while still presenting the appearance of a full copy. When a tree is cloned,\n// it initially shares all its nodes with the original tree. Only when a\n// modification is made to either the original or the clone are new nodes created,\n// and only along the path from the root to the modified node.\n//\n// Key features:\n//   - O(1) cloning operation\n//   - Minimal memory usage through structural sharing\n//   - Full AVL tree functionality (self-balancing, ordered operations)\n//   - Thread-safe for concurrent reads of shared structures\n//\n// While the CoW mechanism handles structural copying automatically, users need\n// to consider how to handle the values stored in the tree:\n//\n//  1. Simple Values (int, string, etc.):\n//     - These are copied by value automatically\n//     - No additional handling needed\n//\n//  2. Complex Values (structs, pointers):\n//     - Only the reference is copied by default\n//     - Users must implement their own deep copy mechanism if needed\n//\n// Example:\n//\n//\t// Create original tree\n//\toriginal := cow.NewTree()\n//\toriginal.Set(\"key1\", \"value1\")\n//\n//\t// Create a clone - O(1) operation\n//\tclone := original.Clone()\n//\n//\t// Modify clone - only affected nodes are copied\n//\tclone.Set(\"key1\", \"modified\")\n//\n//\t// Original remains unchanged\n//\tval, _ := original.Get(\"key1\") // Returns \"value1\"\npackage cow\n\ntype IterCbFn func(key string, value any) bool\n\n//----------------------------------------\n// Tree\n\n// The zero struct can be used as an empty tree.\ntype Tree struct {\n\tnode *Node\n}\n\n// NewTree creates a new empty AVL tree.\nfunc NewTree() *Tree {\n\treturn \u0026Tree{\n\t\tnode: nil,\n\t}\n}\n\n// Size returns the number of key-value pair in the tree.\nfunc (tree *Tree) Size() int {\n\treturn tree.node.Size()\n}\n\n// Has checks whether a key exists in the tree.\n// It returns true if the key exists, otherwise false.\nfunc (tree *Tree) Has(key string) (has bool) {\n\treturn tree.node.Has(key)\n}\n\n// Get retrieves the value associated with the given key.\n// It returns the value and a boolean indicating whether the key exists.\nfunc (tree *Tree) Get(key string) (value any, exists bool) {\n\t_, value, exists = tree.node.Get(key)\n\treturn\n}\n\n// GetByIndex retrieves the key-value pair at the specified index in the tree.\n// It returns the key and value at the given index.\nfunc (tree *Tree) GetByIndex(index int) (key string, value any) {\n\treturn tree.node.GetByIndex(index)\n}\n\n// Set inserts a key-value pair into the tree.\n// If the key already exists, the value will be updated.\n// It returns a boolean indicating whether the key was newly inserted or updated.\nfunc (tree *Tree) Set(key string, value any) (updated bool) {\n\tnewnode, updated := tree.node.Set(key, value)\n\ttree.node = newnode\n\treturn updated\n}\n\n// Remove removes a key-value pair from the tree.\n// It returns the removed value and a boolean indicating whether the key was found and removed.\nfunc (tree *Tree) Remove(key string) (value any, removed bool) {\n\tnewnode, _, value, removed := tree.node.Remove(key)\n\ttree.node = newnode\n\treturn value, removed\n}\n\n// Iterate performs an in-order traversal of the tree within the specified key range.\n// It calls the provided callback function for each key-value pair encountered.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) Iterate(start, end string, cb IterCbFn) bool {\n\treturn tree.node.TraverseInRange(start, end, true, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// ReverseIterate performs a reverse in-order traversal of the tree within the specified key range.\n// It calls the provided callback function for each key-value pair encountered.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) ReverseIterate(start, end string, cb IterCbFn) bool {\n\treturn tree.node.TraverseInRange(start, end, false, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// IterateByOffset performs an in-order traversal of the tree starting from the specified offset.\n// It calls the provided callback function for each key-value pair encountered, up to the specified count.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) IterateByOffset(offset int, count int, cb IterCbFn) bool {\n\treturn tree.node.TraverseByOffset(offset, count, true, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// ReverseIterateByOffset performs a reverse in-order traversal of the tree starting from the specified offset.\n// It calls the provided callback function for each key-value pair encountered, up to the specified count.\n// If the callback returns true, the iteration is stopped.\nfunc (tree *Tree) ReverseIterateByOffset(offset int, count int, cb IterCbFn) bool {\n\treturn tree.node.TraverseByOffset(offset, count, false, true,\n\t\tfunc(node *Node) bool {\n\t\t\treturn cb(node.Key(), node.Value())\n\t\t},\n\t)\n}\n\n// Equal returns true if the two trees contain the same key-value pairs.\n// WARNING: This is an expensive operation that recursively traverses the entire tree structure.\n// It should only be used in tests or when absolutely necessary.\nfunc (tree *Tree) Equal(other *Tree) bool {\n\tif tree == nil || other == nil {\n\t\treturn tree == other\n\t}\n\treturn tree.node.Equal(other.node)\n}\n\n// Clone creates a shallow copy of the tree\nfunc (tree *Tree) Clone() *Tree {\n\tif tree == nil {\n\t\treturn nil\n\t}\n\treturn \u0026Tree{\n\t\tnode: tree.node,\n\t}\n}\n"},{"name":"tree_test.gno","body":"package cow\n\nimport (\n\t\"testing\"\n)\n\nfunc TestNewTree(t *testing.T) {\n\ttree := NewTree()\n\tif tree.node != nil {\n\t\tt.Error(\"Expected tree.node to be nil\")\n\t}\n}\n\nfunc TestTreeSize(t *testing.T) {\n\ttree := NewTree()\n\tif tree.Size() != 0 {\n\t\tt.Error(\"Expected empty tree size to be 0\")\n\t}\n\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\tif tree.Size() != 2 {\n\t\tt.Error(\"Expected tree size to be 2\")\n\t}\n}\n\nfunc TestTreeHas(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\n\tif !tree.Has(\"key1\") {\n\t\tt.Error(\"Expected tree to have key1\")\n\t}\n\n\tif tree.Has(\"key2\") {\n\t\tt.Error(\"Expected tree to not have key2\")\n\t}\n}\n\nfunc TestTreeGet(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\n\tvalue, exists := tree.Get(\"key1\")\n\tif !exists || value != \"value1\" {\n\t\tt.Error(\"Expected Get to return value1 and true\")\n\t}\n\n\t_, exists = tree.Get(\"key2\")\n\tif exists {\n\t\tt.Error(\"Expected Get to return false for non-existent key\")\n\t}\n}\n\nfunc TestTreeGetByIndex(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\n\tkey, value := tree.GetByIndex(0)\n\tif key != \"key1\" || value != \"value1\" {\n\t\tt.Error(\"Expected GetByIndex(0) to return key1 and value1\")\n\t}\n\n\tkey, value = tree.GetByIndex(1)\n\tif key != \"key2\" || value != \"value2\" {\n\t\tt.Error(\"Expected GetByIndex(1) to return key2 and value2\")\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"Expected GetByIndex to panic for out-of-range index\")\n\t\t}\n\t}()\n\ttree.GetByIndex(2)\n}\n\nfunc TestTreeRemove(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\n\tvalue, removed := tree.Remove(\"key1\")\n\tif !removed || value != \"value1\" || tree.Size() != 0 {\n\t\tt.Error(\"Expected Remove to remove key-value pair\")\n\t}\n\n\t_, removed = tree.Remove(\"key2\")\n\tif removed {\n\t\tt.Error(\"Expected Remove to return false for non-existent key\")\n\t}\n}\n\nfunc TestTreeIterate(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\n\n\tvar keys []string\n\ttree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tkeys = append(keys, key)\n\t\treturn false\n\t})\n\n\texpectedKeys := []string{\"key1\", \"key2\", \"key3\"}\n\tif !slicesEqual(keys, expectedKeys) {\n\t\tt.Errorf(\"Expected keys %v, got %v\", expectedKeys, keys)\n\t}\n}\n\nfunc TestTreeReverseIterate(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\n\n\tvar keys []string\n\ttree.ReverseIterate(\"\", \"\", func(key string, value any) bool {\n\t\tkeys = append(keys, key)\n\t\treturn false\n\t})\n\n\texpectedKeys := []string{\"key3\", \"key2\", \"key1\"}\n\tif !slicesEqual(keys, expectedKeys) {\n\t\tt.Errorf(\"Expected keys %v, got %v\", expectedKeys, keys)\n\t}\n}\n\nfunc TestTreeIterateByOffset(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\n\n\tvar keys []string\n\ttree.IterateByOffset(1, 2, func(key string, value any) bool {\n\t\tkeys = append(keys, key)\n\t\treturn false\n\t})\n\n\texpectedKeys := []string{\"key2\", \"key3\"}\n\tif !slicesEqual(keys, expectedKeys) {\n\t\tt.Errorf(\"Expected keys %v, got %v\", expectedKeys, keys)\n\t}\n}\n\nfunc TestTreeReverseIterateByOffset(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\n\n\tvar keys []string\n\ttree.ReverseIterateByOffset(1, 2, func(key string, value any) bool {\n\t\tkeys = append(keys, key)\n\t\treturn false\n\t})\n\n\texpectedKeys := []string{\"key2\", \"key1\"}\n\tif !slicesEqual(keys, expectedKeys) {\n\t\tt.Errorf(\"Expected keys %v, got %v\", expectedKeys, keys)\n\t}\n}\n\n// Verify that Tree implements avl.ITree\n// var _ avl.ITree = (*Tree)(nil) // TODO: fix gnovm bug: ./examples/gno.land/p/moul/cow: test pkg: panic: gno.land/p/moul/cow/tree_test.gno:166:5: name avl not defined in fileset with files [node.gno tree.gno node_test.gno tree_test.gno]:\n\nfunc TestCopyOnWrite(t *testing.T) {\n\t// Create original tree\n\toriginal := NewTree()\n\toriginal.Set(\"A\", 1)\n\toriginal.Set(\"B\", 2)\n\toriginal.Set(\"C\", 3)\n\n\t// Create a clone\n\tclone := original.Clone()\n\n\t// Modify clone\n\tclone.Set(\"B\", 20)\n\tclone.Set(\"D\", 4)\n\n\t// Verify original is unchanged\n\tif val, _ := original.Get(\"B\"); val != 2 {\n\t\tt.Errorf(\"Original tree was modified: expected B=2, got B=%v\", val)\n\t}\n\tif original.Has(\"D\") {\n\t\tt.Error(\"Original tree was modified: found key D\")\n\t}\n\n\t// Verify clone has new values\n\tif val, _ := clone.Get(\"B\"); val != 20 {\n\t\tt.Errorf(\"Clone not updated: expected B=20, got B=%v\", val)\n\t}\n\tif val, _ := clone.Get(\"D\"); val != 4 {\n\t\tt.Errorf(\"Clone not updated: expected D=4, got D=%v\", val)\n\t}\n}\n\nfunc TestCopyOnWriteEdgeCases(t *testing.T) {\n\tt.Run(\"nil tree clone\", func(t *testing.T) {\n\t\tvar original *Tree\n\t\tclone := original.Clone()\n\t\tif clone != nil {\n\t\t\tt.Error(\"Expected nil clone from nil tree\")\n\t\t}\n\t})\n\n\tt.Run(\"empty tree clone\", func(t *testing.T) {\n\t\toriginal := NewTree()\n\t\tclone := original.Clone()\n\n\t\t// Modify clone\n\t\tclone.Set(\"A\", 1)\n\n\t\tif original.Size() != 0 {\n\t\t\tt.Error(\"Original empty tree was modified\")\n\t\t}\n\t\tif clone.Size() != 1 {\n\t\t\tt.Error(\"Clone was not modified\")\n\t\t}\n\t})\n\n\tt.Run(\"multiple clones\", func(t *testing.T) {\n\t\toriginal := NewTree()\n\t\toriginal.Set(\"A\", 1)\n\t\toriginal.Set(\"B\", 2)\n\n\t\t// Create multiple clones\n\t\tclone1 := original.Clone()\n\t\tclone2 := original.Clone()\n\t\tclone3 := clone1.Clone()\n\n\t\t// Modify each clone differently\n\t\tclone1.Set(\"A\", 10)\n\t\tclone2.Set(\"B\", 20)\n\t\tclone3.Set(\"C\", 30)\n\n\t\t// Check original remains unchanged\n\t\tif val, _ := original.Get(\"A\"); val != 1 {\n\t\t\tt.Errorf(\"Original modified: expected A=1, got A=%v\", val)\n\t\t}\n\t\tif val, _ := original.Get(\"B\"); val != 2 {\n\t\t\tt.Errorf(\"Original modified: expected B=2, got B=%v\", val)\n\t\t}\n\n\t\t// Verify each clone has correct values\n\t\tif val, _ := clone1.Get(\"A\"); val != 10 {\n\t\t\tt.Errorf(\"Clone1 incorrect: expected A=10, got A=%v\", val)\n\t\t}\n\t\tif val, _ := clone2.Get(\"B\"); val != 20 {\n\t\t\tt.Errorf(\"Clone2 incorrect: expected B=20, got B=%v\", val)\n\t\t}\n\t\tif val, _ := clone3.Get(\"C\"); val != 30 {\n\t\t\tt.Errorf(\"Clone3 incorrect: expected C=30, got C=%v\", val)\n\t\t}\n\t})\n\n\tt.Run(\"clone after removal\", func(t *testing.T) {\n\t\toriginal := NewTree()\n\t\toriginal.Set(\"A\", 1)\n\t\toriginal.Set(\"B\", 2)\n\t\toriginal.Set(\"C\", 3)\n\n\t\t// Remove a node and then clone\n\t\toriginal.Remove(\"B\")\n\t\tclone := original.Clone()\n\n\t\t// Modify clone\n\t\tclone.Set(\"B\", 20)\n\n\t\t// Verify original state\n\t\tif original.Has(\"B\") {\n\t\t\tt.Error(\"Original tree should not have key B\")\n\t\t}\n\n\t\t// Verify clone state\n\t\tif val, _ := clone.Get(\"B\"); val != 20 {\n\t\t\tt.Errorf(\"Clone incorrect: expected B=20, got B=%v\", val)\n\t\t}\n\t})\n\n\tt.Run(\"concurrent modifications\", func(t *testing.T) {\n\t\toriginal := NewTree()\n\t\toriginal.Set(\"A\", 1)\n\t\toriginal.Set(\"B\", 2)\n\n\t\tclone1 := original.Clone()\n\t\tclone2 := original.Clone()\n\n\t\t// Modify same key in different clones\n\t\tclone1.Set(\"B\", 20)\n\t\tclone2.Set(\"B\", 30)\n\n\t\t// Each clone should have its own value\n\t\tif val, _ := clone1.Get(\"B\"); val != 20 {\n\t\t\tt.Errorf(\"Clone1 incorrect: expected B=20, got B=%v\", val)\n\t\t}\n\t\tif val, _ := clone2.Get(\"B\"); val != 30 {\n\t\t\tt.Errorf(\"Clone2 incorrect: expected B=30, got B=%v\", val)\n\t\t}\n\t})\n\n\tt.Run(\"deep tree modifications\", func(t *testing.T) {\n\t\toriginal := NewTree()\n\t\t// Create a deeper tree\n\t\tkeys := []string{\"M\", \"F\", \"T\", \"B\", \"H\", \"P\", \"Z\"}\n\t\tfor _, k := range keys {\n\t\t\toriginal.Set(k, k)\n\t\t}\n\n\t\tclone := original.Clone()\n\n\t\t// Modify a deep node\n\t\tclone.Set(\"H\", \"modified\")\n\n\t\t// Check original remains unchanged\n\t\tif val, _ := original.Get(\"H\"); val != \"H\" {\n\t\t\tt.Errorf(\"Original modified: expected H='H', got H=%v\", val)\n\t\t}\n\n\t\t// Verify clone modification\n\t\tif val, _ := clone.Get(\"H\"); val != \"modified\" {\n\t\t\tt.Errorf(\"Clone incorrect: expected H='modified', got H=%v\", val)\n\t\t}\n\t})\n\n\tt.Run(\"rebalancing test\", func(t *testing.T) {\n\t\toriginal := NewTree()\n\t\t// Insert nodes that will cause rotations\n\t\tkeys := []string{\"A\", \"B\", \"C\", \"D\", \"E\"}\n\t\tfor _, k := range keys {\n\t\t\toriginal.Set(k, k)\n\t\t}\n\n\t\tclone := original.Clone()\n\n\t\t// Add more nodes to clone to trigger rebalancing\n\t\tclone.Set(\"F\", \"F\")\n\t\tclone.Set(\"G\", \"G\")\n\n\t\t// Verify original structure remains unchanged\n\t\toriginalKeys := collectKeys(original)\n\t\texpectedOriginal := []string{\"A\", \"B\", \"C\", \"D\", \"E\"}\n\t\tif !slicesEqual(originalKeys, expectedOriginal) {\n\t\t\tt.Errorf(\"Original tree structure changed: got %v, want %v\", originalKeys, expectedOriginal)\n\t\t}\n\n\t\t// Verify clone has all keys\n\t\tcloneKeys := collectKeys(clone)\n\t\texpectedClone := []string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"}\n\t\tif !slicesEqual(cloneKeys, expectedClone) {\n\t\t\tt.Errorf(\"Clone tree structure incorrect: got %v, want %v\", cloneKeys, expectedClone)\n\t\t}\n\t})\n\n\tt.Run(\"value mutation test\", func(t *testing.T) {\n\t\ttype MutableValue struct {\n\t\t\tData string\n\t\t}\n\n\t\toriginal := NewTree()\n\t\tmutable := \u0026MutableValue{Data: \"original\"}\n\t\toriginal.Set(\"key\", mutable)\n\n\t\tclone := original.Clone()\n\n\t\t// Modify the mutable value\n\t\tmutable.Data = \"modified\"\n\n\t\t// Both original and clone should see the modification\n\t\t// because we're not deep copying values\n\t\torigVal, _ := original.Get(\"key\")\n\t\tcloneVal, _ := clone.Get(\"key\")\n\n\t\tif origVal.(*MutableValue).Data != \"modified\" {\n\t\t\tt.Error(\"Original value not modified as expected\")\n\t\t}\n\t\tif cloneVal.(*MutableValue).Data != \"modified\" {\n\t\t\tt.Error(\"Clone value not modified as expected\")\n\t\t}\n\t})\n}\n\n// Helper function to collect all keys in order\nfunc collectKeys(tree *Tree) []string {\n\tvar keys []string\n\ttree.Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\tkeys = append(keys, key)\n\t\treturn false\n\t})\n\treturn keys\n}\n"}]},"send":"","max_deposit":"20000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"debug","path":"gno.land/p/moul/debug/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/debug`\n\nA debug panel for realms: collect log lines while `Render` runs, then append\nthem as a collapsible section, but only when the reader asks for it with\n`?debug=1`.\n\n```go\nfunc Render(path string) string {\n\tvar d debug.Debug\n\td.Log(\"loaded \" + ufmt.Sprintf(\"%d\", n) + \" items\")\n\n\tout := renderPage()\n\tout += d.Render(path)    // empty unless ?debug=1\n\treturn out\n}\n```\n\nWithout the query parameter the panel renders nothing, so the same code is safe\nto leave in a deployed realm: there is no debug build and no flag to flip.\n\n## API\n\n```go\nfunc (d *Debug) Log(line string)       // append one line\nfunc (d Debug) Render(path string) string\nfunc Render(path string) string        // metadata only, no logs\nfunc IsEnabled(path string) bool       // is ?debug=1 set\nfunc ToggleURL(path string) string     // same path with ?debug=1 added or removed\n```\n\nThe struct is two fields, `Logs []string` and `HideMetadata bool`, so the zero\nvalue already works and metadata is on unless you turn it off.\n\nThe metadata table reports the current realm's pkgpath and address, the\nprevious realm's pkgpath and address, the block height, and `time.Now()`. Those\nsix are what you need first when a realm behaves differently on chain than it\ndid in a test, and the previous-realm pair in particular is what a cross-realm\npermission bug looks like.\n\n`ToggleURL` is there so the page can render its own \"debug\" link:\n\n```go\nout += md.Link(\"debug\", debug.ToggleURL(path))\n```\n\nLogs cost nothing on chain: they are built during a `Render` query and thrown\naway with it. Do not call `Log` from a transaction path expecting persistence.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/debug/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/debug/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"debug.gno","body":"// Package debug provides utilities for logging and displaying debug information\n// within Gno realms. It supports conditional rendering of logs and metadata,\n// toggleable via query parameters.\n//\n// Key Features:\n// - Log collection and display using Markdown formatting.\n// - Metadata display for realm path, address, and height.\n// - Collapsible debug section for cleaner presentation.\n// - Query-based debug toggle using `?debug=1`.\npackage debug\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Debug encapsulates debug information, including logs and metadata.\ntype Debug struct {\n\tLogs         []string\n\tHideMetadata bool\n}\n\n// Log appends a new line of debug information to the Logs slice.\nfunc (d *Debug) Log(line string) {\n\td.Logs = append(d.Logs, line)\n}\n\n// Render generates the debug content as a collapsible Markdown section.\n// It conditionally renders logs and metadata if enabled via the `?debug=1` query parameter.\nfunc (d Debug) Render(path string) string {\n\tif realmpath.Parse(path).Query.Get(\"debug\") != \"1\" {\n\t\treturn \"\"\n\t}\n\n\tvar content string\n\n\tif d.Logs != nil {\n\t\tcontent += md.H3(\"Logs\")\n\t\tcontent += md.BulletList(d.Logs)\n\t}\n\n\tif !d.HideMetadata {\n\t\tcontent += md.H3(\"Metadata\")\n\t\ttable := mdtable.Table{\n\t\t\tHeaders: []string{\"Key\", \"Value\"},\n\t\t}\n\t\ttable.Append([]string{\"`std.CurrentRealm().PkgPath()`\", string(unsafe.CurrentRealm().PkgPath())})\n\t\ttable.Append([]string{\"`std.CurrentRealm().Address()`\", string(unsafe.CurrentRealm().Address())})\n\t\ttable.Append([]string{\"`std.PreviousRealm().PkgPath()`\", string(unsafe.PreviousRealm().PkgPath())})\n\t\ttable.Append([]string{\"`std.PreviousRealm().Address()`\", string(unsafe.PreviousRealm().Address())})\n\t\ttable.Append([]string{\"`std.ChainHeight()`\", ufmt.Sprintf(\"%d\", runtime.ChainHeight())})\n\t\ttable.Append([]string{\"`time.Now().Format(time.RFC3339)`\", time.Now().Format(time.RFC3339)})\n\t\tcontent += table.String()\n\t}\n\n\tif content == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn md.CollapsibleSection(\"debug\", content)\n}\n\n// Render displays metadata about the current realm but does not display logs.\n// This function uses a default Debug struct with metadata enabled and no logs.\nfunc Render(path string) string {\n\treturn Debug{}.Render(path)\n}\n\n// IsEnabled checks if the `?debug=1` query parameter is set in the given path.\n// Returns true if debugging is enabled, otherwise false.\nfunc IsEnabled(path string) bool {\n\treq := realmpath.Parse(path)\n\treturn req.Query.Get(\"debug\") == \"1\"\n}\n\n// ToggleURL modifies the given path's query string to toggle the `?debug=1` parameter.\n// If debugging is currently enabled, it removes the parameter.\n// If debugging is disabled, it adds the parameter.\nfunc ToggleURL(path string) string {\n\treq := realmpath.Parse(path)\n\tif IsEnabled(path) {\n\t\treq.Query.Del(\"debug\")\n\t} else {\n\t\treq.Query.Add(\"debug\", \"1\")\n\t}\n\treturn req.String()\n}\n"},{"name":"debug_test.gno","body":"package debug\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPackage(t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1user\"))\n\n\ttestPackage(t)\n}\n\nfunc testPackage(t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test/test\"))\n\n\t// no debug\n\tgot := Render(\"\")\n\texpected := ``\n\tuassert.Equal(t, expected, got)\n\n\t// debug without logs\n\tgot = Render(\"?debug=1\")\n\texpected = `\u003cdetails\u003e\u003csummary\u003edebug\u003c/summary\u003e\n\n### Metadata\n| Key | Value |\n| --- | --- |\n| ±std.CurrentRealm().PkgPath()± | gno.land/r/test/test |\n| ±std.CurrentRealm().Address()± | g1z7fga7u94pdmamlvcrtvsfwxgsye0qv3rres7n |\n| ±std.PreviousRealm().PkgPath()± |  |\n| ±std.PreviousRealm().Address()± | g1user |\n| ±std.ChainHeight()± | 123 |\n| ±time.Now().Format(time.RFC3339)± | 2009-02-13T23:31:30Z |\n\n\u003c/details\u003e\n`\n\texpected = strings.ReplaceAll(expected, \"±\", \"`\")\n\n\tprintln(\"###################\")\n\tprintln(got)\n\tprintln(\"###################\")\n\tprintln(expected)\n\tprintln(\"###################\")\n\n\tuassert.Equal(t, expected, got)\n\n\t// debug with logs\n\tvar d Debug\n\td.Log(\"hello world!\")\n\td.Log(\"foobar\")\n\tgot = d.Render(\"?debug=1\")\n\texpected = `\u003cdetails\u003e\u003csummary\u003edebug\u003c/summary\u003e\n\n### Logs\n- hello world!\n- foobar\n### Metadata\n| Key | Value |\n| --- | --- |\n| ±std.CurrentRealm().PkgPath()± | gno.land/r/test/test |\n| ±std.CurrentRealm().Address()± | g1z7fga7u94pdmamlvcrtvsfwxgsye0qv3rres7n |\n| ±std.PreviousRealm().PkgPath()± |  |\n| ±std.PreviousRealm().Address()± | g1user |\n| ±std.ChainHeight()± | 123 |\n| ±time.Now().Format(time.RFC3339)± | 2009-02-13T23:31:30Z |\n\n\u003c/details\u003e\n`\n\texpected = strings.ReplaceAll(expected, \"±\", \"`\")\n\tuassert.Equal(t, got, expected)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/debug/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"deque","path":"gno.land/p/moul/deque/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/deque`\n\nA doubly-linked deque, optionally bounded, written for chain storage rather\nthan for RAM.\n\n```go\nd := deque.New()             // unbounded\nd = deque.NewBounded(3)      // evicts from the front past 3 elements\n\nd.PushBack(\"a\", \"b\", \"c\")\nd.PushFront(\"z\")\nfirst := d.PopFront()\nlast  := d.Last()\n```\n\n## Why not a slice\n\nA slice-backed queue rewrites the whole backing array on append-and-grow and\nshifts every element on pop-front. On gno that is not a constant factor, it is\nthe storage bill: the VM persists what changed, so touching N elements costs N.\n\nEach operation here updates one or two node pointers and nothing else:\n\n| operation | cost |\n| --- | --- |\n| `PushBack`, `PushFront`, `PopFront`, `PopBack` | O(1), 1-2 node writes |\n| `First`, `Last`, `Size`, `IsEmpty` | O(1), no write |\n| `Get(i)` | O(n) walk, no write |\n\nUse it when you want a bounded log (the last N events), a FIFO work queue, or\nany list where reads are \"first / last / how many / iterate\" and `Get(i)` is\nrare. Use an avl tree instead when you need keyed lookup or ordering by\nanything but insertion.\n\n## Bounded mode\n\n`NewBounded(n)` makes eviction automatic and symmetric: pushing past the limit\nat the back drops from the front, and pushing past it at the front drops from\nthe back. `MaxSize()` returns 0 for unbounded, `IsBounded()` says which.\n\n## Iteration\n\n`All()` walks front to back, `Backward()` back to front. Both return a function\ntaking a `func(any) bool` callback; return `false` to stop early.\n\n```go\nd.All()(func(v any) bool {\n\tprintln(v)\n\treturn true\n})\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"deque.gno","body":"// Package deque provides a doubly-linked deque with optional size limits,\n// optimized for minimal storage updates and O(1) operations in Gno environments.\n//\n// This implementation uses a doubly-linked list structure that provides:\n// - O(1) push back operations\n// - O(1) pop front operations\n// - O(1) access to first/last elements\n// - No array resizing or slice shifting\n// - Minimal allocations (one node per element)\n// - Minimal storage updates (typically 1-2 pointer updates per operation)\n// - Optional max-size eviction policy\n//\n// Optimized for Gno blockchain storage: each operation updates only specific nodes\n// rather than entire data structures, making it ideal for storage-efficient lists\n// that need simple read operations like first/last access, size checks, list\n// enumeration, and iteration with minimal storage update overhead.\n//\n// Example usage:\n//\n//\t// Unbounded deque\n//\td := deque.New()\n//\td.PushBack(\"a\", \"b\", \"c\")\n//\n//\t// Bounded deque with automatic eviction\n//\td = deque.NewBounded(3)\n//\td.PushBack(\"a\", \"b\", \"c\", \"d\")  // \"a\" gets evicted\n//\n//\tfirst := d.PopFront()  // Returns \"b\"\n//\tlast := d.Last()       // Returns \"d\"\n//\n//\t// Iterate forward\n//\titer := d.All()\n//\titer(func(val any) bool {\n//\t    println(val)\n//\t    return true // continue\n//\t})\n//\n//\t// Iterate backward\n//\titer = d.Backward()\n//\titer(func(val any) bool {\n//\t    println(val)\n//\t    return true // continue\n//\t})\npackage deque\n\n// Node represents a single element in the doubly-linked list\ntype Node struct {\n\tvalue any\n\tprev  *Node\n\tnext  *Node\n}\n\n// Deque represents a doubly-linked deque with optional size limits\ntype Deque struct {\n\thead *Node\n\ttail *Node\n\tsize int\n\tmax  int // 0 = unlimited\n}\n\n// New creates a new unbounded deque.\nfunc New() *Deque {\n\treturn \u0026Deque{\n\t\tmax: 0, // unlimited\n\t}\n}\n\n// NewBounded creates a new bounded deque with the specified maximum size.\n// When the deque exceeds maxSize, elements are removed from the front.\nfunc NewBounded(maxSize int) *Deque {\n\tif maxSize \u003c= 0 {\n\t\tmaxSize = 1\n\t}\n\treturn \u0026Deque{\n\t\tmax: maxSize,\n\t}\n}\n\n// PushBack adds one or more elements to the back of the deque.\n// If the deque exceeds maxSize, elements are removed from the front.\nfunc (d *Deque) PushBack(items ...any) {\n\tfor _, item := range items {\n\t\td.pushBackSingle(item)\n\t}\n}\n\n// pushBackSingle adds a single element to the back\nfunc (d *Deque) pushBackSingle(item any) {\n\tnode := \u0026Node{value: item}\n\n\tif d.tail == nil {\n\t\t// First element\n\t\td.head = node\n\t\td.tail = node\n\t} else {\n\t\t// Link to existing tail\n\t\td.tail.next = node\n\t\tnode.prev = d.tail\n\t\td.tail = node\n\t}\n\n\td.size++\n\n\t// Handle size limit by removing from front\n\tif d.max \u003e 0 \u0026\u0026 d.size \u003e d.max {\n\t\td.popFrontNode()\n\t}\n}\n\n// PopFront removes and returns the front element.\n// Returns nil if the deque is empty.\nfunc (d *Deque) PopFront() any {\n\tif d.head == nil {\n\t\treturn nil\n\t}\n\n\tvalue := d.head.value\n\td.popFrontNode()\n\treturn value\n}\n\n// popFrontNode removes the front node\nfunc (d *Deque) popFrontNode() {\n\tif d.head == nil {\n\t\treturn\n\t}\n\n\tif d.head == d.tail {\n\t\t// Only one element\n\t\td.head = nil\n\t\td.tail = nil\n\t} else {\n\t\t// Move head forward\n\t\td.head = d.head.next\n\t\td.head.prev = nil\n\t}\n\n\td.size--\n}\n\n// PopBack removes and returns the back element.\n// Returns nil if the deque is empty.\nfunc (d *Deque) PopBack() any {\n\tif d.tail == nil {\n\t\treturn nil\n\t}\n\n\tvalue := d.tail.value\n\td.popBackNode()\n\treturn value\n}\n\n// popBackNode removes the back node\nfunc (d *Deque) popBackNode() {\n\tif d.tail == nil {\n\t\treturn\n\t}\n\n\tif d.head == d.tail {\n\t\t// Only one element\n\t\td.head = nil\n\t\td.tail = nil\n\t} else {\n\t\t// Move tail backward\n\t\td.tail = d.tail.prev\n\t\td.tail.next = nil\n\t}\n\n\td.size--\n}\n\n// PushFront adds one or more elements to the front of the deque.\n// If bounded and size limit is exceeded, elements are removed from the back.\nfunc (d *Deque) PushFront(items ...any) {\n\tfor _, item := range items {\n\t\td.pushFrontSingle(item)\n\t}\n}\n\n// pushFrontSingle adds a single element to the front\nfunc (d *Deque) pushFrontSingle(item any) {\n\tnode := \u0026Node{value: item}\n\n\tif d.head == nil {\n\t\t// First element\n\t\td.head = node\n\t\td.tail = node\n\t} else {\n\t\t// Link to existing head\n\t\td.head.prev = node\n\t\tnode.next = d.head\n\t\td.head = node\n\t}\n\n\td.size++\n\n\t// Handle size limit by removing from back\n\tif d.max \u003e 0 \u0026\u0026 d.size \u003e d.max {\n\t\td.popBackNode()\n\t}\n}\n\n// Size returns the current number of elements\nfunc (d *Deque) Size() int {\n\treturn d.size\n}\n\n// MaxSize returns the maximum size limit (0 = unlimited)\nfunc (d *Deque) MaxSize() int {\n\treturn d.max\n}\n\n// IsEmpty returns true if the deque is empty\nfunc (d *Deque) IsEmpty() bool {\n\treturn d.size == 0\n}\n\n// IsBounded returns true if the deque has a size limit\nfunc (d *Deque) IsBounded() bool {\n\treturn d.max \u003e 0\n}\n\n// First returns the front element without removing it.\n// Returns nil if the deque is empty.\nfunc (d *Deque) First() any {\n\tif d.head == nil {\n\t\treturn nil\n\t}\n\treturn d.head.value\n}\n\n// Last returns the back element without removing it.\n// Returns nil if the deque is empty.\nfunc (d *Deque) Last() any {\n\tif d.tail == nil {\n\t\treturn nil\n\t}\n\treturn d.tail.value\n}\n\n// Get returns the element at the specified index (0 = front).\n// Returns nil if index is out of bounds.\nfunc (d *Deque) Get(index int) any {\n\tif index \u003c 0 || index \u003e= d.size {\n\t\treturn nil\n\t}\n\n\tnode := d.head\n\tfor i := 0; i \u003c index; i++ {\n\t\tnode = node.next\n\t}\n\treturn node.value\n}\n\n// List returns all elements as a slice, ordered from front to back\nfunc (d *Deque) List() []any {\n\tif d.size == 0 {\n\t\treturn nil\n\t}\n\n\tresult := make([]any, d.size)\n\tnode := d.head\n\tfor i := 0; i \u003c d.size; i++ {\n\t\tresult[i] = node.value\n\t\tnode = node.next\n\t}\n\treturn result\n}\n\n// Enumerate calls fn for each element with its index (0-based from front)\nfunc (d *Deque) Enumerate(fn func(index int, value any) bool) {\n\tnode := d.head\n\tfor i := 0; i \u003c d.size; i++ {\n\t\tif fn(i, node.value) {\n\t\t\tbreak\n\t\t}\n\t\tnode = node.next\n\t}\n}\n\n// Clear removes all elements from the deque\nfunc (d *Deque) Clear() {\n\td.head = nil\n\td.tail = nil\n\td.size = 0\n}\n\n// SetMaxSize changes the maximum size limit.\n// If the new limit is smaller than current size, elements are removed from front.\nfunc (d *Deque) SetMaxSize(maxSize int) {\n\td.max = maxSize\n\n\tif maxSize \u003e 0 {\n\t\tfor d.size \u003e maxSize {\n\t\t\td.popFrontNode()\n\t\t}\n\t}\n}\n\n// All returns an iterator function for forward traversal (Go 1.23+ compatible)\n// Note: range-over-func syntax is not yet supported in Gno, use iter() directly\nfunc (d *Deque) All() func(yield func(any) bool) {\n\treturn func(yield func(any) bool) {\n\t\tcurrent := d.head\n\t\tfor current != nil {\n\t\t\tif !yield(current.value) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcurrent = current.next\n\t\t}\n\t}\n}\n\n// Backward returns an iterator function for backward traversal (Go 1.23+ compatible)\n// Note: range-over-func syntax is not yet supported in Gno, use iter() directly\nfunc (d *Deque) Backward() func(yield func(any) bool) {\n\treturn func(yield func(any) bool) {\n\t\tcurrent := d.tail\n\t\tfor current != nil {\n\t\t\tif !yield(current.value) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcurrent = current.prev\n\t\t}\n\t}\n}\n"},{"name":"deque_test.gno","body":"package deque\n\nimport \"testing\"\n\nfunc TestNew(t *testing.T) {\n\td := New()\n\tif d.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0, got %d\", d.Size())\n\t}\n\tif d.MaxSize() != 0 {\n\t\tt.Errorf(\"Expected max size 0 (unlimited), got %d\", d.MaxSize())\n\t}\n\tif d.IsBounded() {\n\t\tt.Error(\"Expected unbounded deque\")\n\t}\n}\n\nfunc TestNewBounded(t *testing.T) {\n\td := NewBounded(5)\n\tif d.MaxSize() != 5 {\n\t\tt.Errorf(\"Expected max size 5, got %d\", d.MaxSize())\n\t}\n\tif d.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0, got %d\", d.Size())\n\t}\n\tif !d.IsBounded() {\n\t\tt.Error(\"Expected bounded deque\")\n\t}\n}\n\nfunc TestPushBackPopFront(t *testing.T) {\n\td := New() // unbounded\n\n\t// Test empty pop\n\tif d.PopFront() != nil {\n\t\tt.Error(\"Expected nil when popping from empty deque\")\n\t}\n\n\td.PushBack(\"a\", \"b\", \"c\")\n\tif d.Size() != 3 {\n\t\tt.Errorf(\"Expected size 3, got %d\", d.Size())\n\t}\n\n\titem := d.PopFront()\n\tif item != \"a\" {\n\t\tt.Errorf(\"Expected 'a', got %v\", item)\n\t}\n\tif d.Size() != 2 {\n\t\tt.Errorf(\"Expected size 2, got %d\", d.Size())\n\t}\n}\n\nfunc TestPushFrontPopBack(t *testing.T) {\n\td := New() // unbounded\n\n\td.PushFront(\"a\", \"b\", \"c\")\n\tif d.Size() != 3 {\n\t\tt.Errorf(\"Expected size 3, got %d\", d.Size())\n\t}\n\n\t// Elements should be in reverse order: [c, b, a]\n\tif d.First() != \"c\" {\n\t\tt.Errorf(\"Expected 'c' as first, got %v\", d.First())\n\t}\n\tif d.Last() != \"a\" {\n\t\tt.Errorf(\"Expected 'a' as last, got %v\", d.Last())\n\t}\n\n\titem := d.PopBack()\n\tif item != \"a\" {\n\t\tt.Errorf(\"Expected 'a', got %v\", item)\n\t}\n\tif d.Size() != 2 {\n\t\tt.Errorf(\"Expected size 2, got %d\", d.Size())\n\t}\n}\n\nfunc TestBoundedEvictionBack(t *testing.T) {\n\td := NewBounded(3)\n\n\t// Fill to capacity\n\td.PushBack(\"a\", \"b\", \"c\")\n\tif d.Size() != 3 {\n\t\tt.Errorf(\"Expected size 3, got %d\", d.Size())\n\t}\n\n\t// Push beyond capacity - should evict \"a\" from front\n\td.PushBack(\"d\")\n\tif d.Size() != 3 {\n\t\tt.Errorf(\"Expected size 3, got %d\", d.Size())\n\t}\n\tif d.First() != \"b\" {\n\t\tt.Errorf(\"Expected 'b' (oldest after eviction), got %v\", d.First())\n\t}\n\tif d.Last() != \"d\" {\n\t\tt.Errorf(\"Expected 'd' (newest), got %v\", d.Last())\n\t}\n}\n\nfunc TestBoundedEvictionFront(t *testing.T) {\n\td := NewBounded(3)\n\n\t// Fill to capacity\n\td.PushBack(\"a\", \"b\", \"c\")\n\n\t// Push to front beyond capacity - should evict \"c\" from back\n\td.PushFront(\"x\")\n\tif d.Size() != 3 {\n\t\tt.Errorf(\"Expected size 3, got %d\", d.Size())\n\t}\n\tif d.First() != \"x\" {\n\t\tt.Errorf(\"Expected 'x' (newest at front), got %v\", d.First())\n\t}\n\tif d.Last() != \"b\" {\n\t\tt.Errorf(\"Expected 'b' (oldest after back eviction), got %v\", d.Last())\n\t}\n}\n\nfunc TestFirstLast(t *testing.T) {\n\td := New()\n\n\t// Empty deque\n\tif d.First() != nil {\n\t\tt.Error(\"Expected nil for empty deque first\")\n\t}\n\tif d.Last() != nil {\n\t\tt.Error(\"Expected nil for empty deque last\")\n\t}\n\n\td.PushBack(\"x\", \"y\", \"z\")\n\tif d.First() != \"x\" {\n\t\tt.Errorf(\"Expected 'x', got %v\", d.First())\n\t}\n\tif d.Last() != \"z\" {\n\t\tt.Errorf(\"Expected 'z', got %v\", d.Last())\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\td := New()\n\td.PushBack(\"a\", \"b\", \"c\")\n\n\tif d.Get(0) != \"a\" {\n\t\tt.Errorf(\"Expected 'a' at index 0, got %v\", d.Get(0))\n\t}\n\tif d.Get(1) != \"b\" {\n\t\tt.Errorf(\"Expected 'b' at index 1, got %v\", d.Get(1))\n\t}\n\tif d.Get(2) != \"c\" {\n\t\tt.Errorf(\"Expected 'c' at index 2, got %v\", d.Get(2))\n\t}\n\tif d.Get(3) != nil {\n\t\tt.Error(\"Expected nil for out-of-bounds index\")\n\t}\n\tif d.Get(-1) != nil {\n\t\tt.Error(\"Expected nil for negative index\")\n\t}\n}\n\nfunc TestList(t *testing.T) {\n\td := New()\n\n\t// Empty deque\n\tlist := d.List()\n\tif list != nil {\n\t\tt.Errorf(\"Expected nil for empty deque, got %v\", list)\n\t}\n\n\td.PushBack(\"x\", \"y\", \"z\")\n\tlist = d.List()\n\tif len(list) != 3 {\n\t\tt.Errorf(\"Expected length 3, got %d\", len(list))\n\t}\n\tif list[0] != \"x\" || list[1] != \"y\" || list[2] != \"z\" {\n\t\tt.Errorf(\"Expected [x, y, z], got %v\", list)\n\t}\n}\n\nfunc TestEnumerate(t *testing.T) {\n\td := New()\n\td.PushBack(\"a\", \"b\", \"c\")\n\n\tvar enumerated []string\n\tvar indices []int\n\n\td.Enumerate(func(index int, item any) bool {\n\t\tindices = append(indices, index)\n\t\tenumerated = append(enumerated, item.(string))\n\t\treturn false // continue\n\t})\n\n\tif len(enumerated) != 3 {\n\t\tt.Errorf(\"Expected 3 enumerated items, got %d\", len(enumerated))\n\t}\n\tif enumerated[0] != \"a\" || enumerated[1] != \"b\" || enumerated[2] != \"c\" {\n\t\tt.Errorf(\"Expected [a, b, c], got %v\", enumerated)\n\t}\n\tif indices[0] != 0 || indices[1] != 1 || indices[2] != 2 {\n\t\tt.Errorf(\"Expected [0, 1, 2], got %v\", indices)\n\t}\n}\n\nfunc TestEnumerateEarlyStop(t *testing.T) {\n\td := New()\n\td.PushBack(\"a\", \"b\", \"c\")\n\n\tvar enumerated []string\n\n\td.Enumerate(func(index int, item any) bool {\n\t\tenumerated = append(enumerated, item.(string))\n\t\treturn item == \"b\" // stop after b\n\t})\n\n\tif len(enumerated) != 2 {\n\t\tt.Errorf(\"Expected 2 enumerated items, got %d\", len(enumerated))\n\t}\n\tif enumerated[0] != \"a\" || enumerated[1] != \"b\" {\n\t\tt.Errorf(\"Expected [a, b], got %v\", enumerated)\n\t}\n}\n\nfunc TestSetMaxSize(t *testing.T) {\n\td := New()\n\td.PushBack(\"a\", \"b\", \"c\", \"d\", \"e\")\n\n\t// Reduce max size - should trim from front\n\td.SetMaxSize(3)\n\tif d.Size() != 3 {\n\t\tt.Errorf(\"Expected size 3 after reducing max size, got %d\", d.Size())\n\t}\n\tif d.First() != \"c\" {\n\t\tt.Errorf(\"Expected 'c' as first after trim, got %v\", d.First())\n\t}\n\n\t// Increase max size\n\td.SetMaxSize(10)\n\tif d.MaxSize() != 10 {\n\t\tt.Errorf(\"Expected max size 10, got %d\", d.MaxSize())\n\t}\n}\n\nfunc TestClear(t *testing.T) {\n\td := New()\n\td.PushBack(\"a\", \"b\", \"c\")\n\n\td.Clear()\n\n\tif d.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0 after clear, got %d\", d.Size())\n\t}\n\tif d.First() != nil {\n\t\tt.Error(\"Expected nil first after clear\")\n\t}\n\tif d.Last() != nil {\n\t\tt.Error(\"Expected nil last after clear\")\n\t}\n\tif !d.IsEmpty() {\n\t\tt.Error(\"Expected deque to be empty after clear\")\n\t}\n}\n\nfunc TestUnboundedGrowth(t *testing.T) {\n\td := New() // unbounded\n\n\t// Add many items\n\tfor i := 0; i \u003c 100; i++ {\n\t\td.PushBack(i)\n\t}\n\n\tif d.Size() != 100 {\n\t\tt.Errorf(\"Expected size 100, got %d\", d.Size())\n\t}\n\tif d.First() != 0 {\n\t\tt.Errorf(\"Expected 0 as first, got %v\", d.First())\n\t}\n\tif d.Last() != 99 {\n\t\tt.Errorf(\"Expected 99 as last, got %v\", d.Last())\n\t}\n}\n\nfunc TestMixedOperations(t *testing.T) {\n\td := NewBounded(4)\n\n\t// Test mixed push front and back operations\n\td.PushBack(\"b\", \"c\")\n\td.PushFront(\"a\")\n\td.PushBack(\"d\")\n\n\t// Should have [a, b, c, d]\n\tlist := d.List()\n\tif len(list) != 4 || list[0] != \"a\" || list[1] != \"b\" || list[2] != \"c\" || list[3] != \"d\" {\n\t\tt.Errorf(\"Expected [a, b, c, d], got %v\", list)\n\t}\n\n\t// Push beyond capacity\n\td.PushFront(\"x\") // Should evict \"d\" from back\n\n\t// Should have [x, a, b, c]\n\tlist = d.List()\n\tif len(list) != 4 || list[0] != \"x\" || list[1] != \"a\" || list[2] != \"b\" || list[3] != \"c\" {\n\t\tt.Errorf(\"Expected [x, a, b, c], got %v\", list)\n\t}\n\n\t// Mixed pop operations\n\tfront := d.PopFront() // \"x\"\n\tback := d.PopBack()   // \"c\"\n\n\tif front != \"x\" {\n\t\tt.Errorf(\"Expected 'x' from front, got %v\", front)\n\t}\n\tif back != \"c\" {\n\t\tt.Errorf(\"Expected 'c' from back, got %v\", back)\n\t}\n\n\t// Should have [a, b]\n\tlist = d.List()\n\tif len(list) != 2 || list[0] != \"a\" || list[1] != \"b\" {\n\t\tt.Errorf(\"Expected [a, b], got %v\", list)\n\t}\n}\n\nfunc TestAllIterator(t *testing.T) {\n\td := New()\n\td.PushBack(\"x\", \"y\", \"z\")\n\n\tvar items []any\n\titer := d.All()\n\titer(func(value any) bool {\n\t\titems = append(items, value)\n\t\treturn true // continue\n\t})\n\n\tif len(items) != 3 {\n\t\tt.Errorf(\"Expected 3 items, got %d\", len(items))\n\t}\n\tif items[0] != \"x\" || items[1] != \"y\" || items[2] != \"z\" {\n\t\tt.Errorf(\"Expected [x, y, z], got %v\", items)\n\t}\n}\n\nfunc TestBackwardIterator(t *testing.T) {\n\td := New()\n\td.PushBack(\"x\", \"y\", \"z\")\n\n\tvar items []any\n\titer := d.Backward()\n\titer(func(value any) bool {\n\t\titems = append(items, value)\n\t\treturn true // continue\n\t})\n\n\tif len(items) != 3 {\n\t\tt.Errorf(\"Expected 3 items, got %d\", len(items))\n\t}\n\tif items[0] != \"z\" || items[1] != \"y\" || items[2] != \"x\" {\n\t\tt.Errorf(\"Expected [z, y, x] (reverse), got %v\", items)\n\t}\n}\n\nfunc TestAllIteratorEarlyBreak(t *testing.T) {\n\td := New()\n\td.PushBack(\"a\", \"b\", \"c\", \"d\", \"e\")\n\n\tvar items []any\n\titer := d.All()\n\titer(func(value any) bool {\n\t\titems = append(items, value)\n\t\tif value == \"c\" {\n\t\t\treturn false // stop\n\t\t}\n\t\treturn true // continue\n\t})\n\n\tif len(items) != 3 {\n\t\tt.Errorf(\"Expected 3 items after break, got %d\", len(items))\n\t}\n\tif items[0] != \"a\" || items[1] != \"b\" || items[2] != \"c\" {\n\t\tt.Errorf(\"Expected [a, b, c], got %v\", items)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/deque/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"entity","path":"gno.land/p/moul/entity/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/entity`\n\n\u003e 🚧 **API sketch, not an implementation.** The interfaces below are declared;\n\u003e all three constructors `panic(\"not implemented\")`. Nothing here works yet.\n\nA proposal for one type that stands for \"whoever is acting\", whether that is an\nexternally owned account or a realm.\n\n```go\ntype Entity interface {\n\tAddr() address\n\tPath() string    // \"\" for an EOA, the pkgpath for a realm\n\tKind\n\tisEntity()\n}\n```\n\n`UserEntity` and `RealmEntity` narrow it, and `Kind` is meant to carry the\nsecond axis: a user can be a person or a team, a realm can be an arbitrary\ncontract or one that implements a known interface such as a DAO.\n\n```go\nfunc NewUserByAddr(addr address) UserEntity    // panics today\nfunc NewUserByName(name string) UserEntity     // panics today\nfunc NewRealm(rlm runtime.Realm) RealmEntity   // panics today\n```\n\nThe motivation is that gno code constantly branches on \"is this an address or a\npkgpath\", and that branch leaks into every API that wants to accept either. A\nsingle `Entity` would let a realm accept both and let composition (an entity\nthat matches several others) be expressed once.\n\nClosely related to [`p/moul/ownable`](../ownable), which is the same idea\nnarrowed to ownership.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"entity.gno","body":"// Package entity provides an interface that abstracts a notion of entity which\n// can under the hood be an EOA (address), a package realm (PkgPath, address).\n// It also tries to give a notion of type where for instance, a user can be\n// either a simple user or a team, and a contract can be either an arbitrary\n// contract, or one that implements a famous pattern/interface, such as a DAO.\n// It also provides some composition utilities so that an entity can be a flow\n// that matches multiple other entities.\npackage entity\n\nimport (\n\t\"chain/runtime\"\n)\n\ntype Entity interface {\n\tAddr() address\n\tPath() string\n\tKind\n\tisEntity()\n}\n\ntype Kind interface {\n\tkind()\n}\n\ntype UserEntity interface {\n\tEntity\n\tisUserEntity()\n}\n\ntype RealmEntity interface {\n\tEntity\n\tisRealmEntity()\n}\n\nfunc NewUserByAddr(addr address) UserEntity  { panic(\"not implemented\") }\nfunc NewUserByName(name string) UserEntity   { panic(\"not implemented\") }\nfunc NewRealm(rlm runtime.Realm) RealmEntity { panic(\"not implemented\") }\n"},{"name":"entity_test.gno","body":"package entity\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// This package is an API sketch recovered from an unmerged upstream proposal:\n// it declares the Entity abstraction and its user/realm refinements, but all\n// three constructors are `panic(\"not implemented\")`. The tests pin that surface\n// so implementing one is a deliberate, visible change.\n\nfunc TestConstructorsAreNotImplemented(cur realm, t *testing.T) {\n\taddr := testutils.TestAddress(\"alice\")\n\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { NewUserByAddr(addr) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { NewUserByName(\"alice\") })\n}\n\n// TestInterfacesAreDeclared is a compile-time check that the interface\n// hierarchy still exists with its documented shape.\nfunc TestInterfacesAreDeclared(t *testing.T) {\n\tvar (\n\t\t_ Entity\n\t\t_ Kind\n\t\t_ UserEntity\n\t\t_ RealmEntity\n\t)\n\tuassert.True(t, true, \"entity interfaces are declared\")\n}\n\n// TestRefinementsEmbedEntity pins that UserEntity and RealmEntity are still\n// refinements of Entity — assigning them to an Entity must compile.\nfunc TestRefinementsEmbedEntity(t *testing.T) {\n\tvar (\n\t\tu UserEntity\n\t\tr RealmEntity\n\t)\n\tvar _ Entity = u\n\tvar _ Entity = r\n\tuassert.True(t, true, \"UserEntity and RealmEntity satisfy Entity\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/entity/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"entropy","path":"gno.land/p/moul/entropy/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/entropy/v0`\n\nA cheap, deterministic pseudo-entropy source for gno realms (seeded from block\nheight / time / caller), useful for demos and non-security-critical randomness.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"entropy.gno","body":"// Entropy generates fully deterministic, cost-effective, and hard to guess\n// numbers.\n//\n// It is designed both for single-usage, like seeding math/rand or for being\n// reused which increases the entropy and its cost effectiveness.\n//\n// Disclaimer: this package is unsafe and won't prevent others to guess values\n// in advance.\n//\n// It uses the Bernstein's hash djb2 to be CPU-cycle efficient.\npackage entropy\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"math\"\n\t\"time\"\n)\n\ntype Instance struct {\n\tvalue uint32\n}\n\nfunc New() *Instance {\n\tr := Instance{value: 5381}\n\tr.addEntropy()\n\treturn \u0026r\n}\n\nfunc FromSeed(seed uint32) *Instance {\n\tr := Instance{value: seed}\n\tr.addEntropy()\n\treturn \u0026r\n}\n\nfunc (i *Instance) Seed() uint32 {\n\treturn i.value\n}\n\nfunc (i *Instance) djb2String(input string) {\n\tfor _, c := range input {\n\t\ti.djb2Uint32(uint32(c))\n\t}\n}\n\n// super fast random algorithm.\n// http://www.cse.yorku.ca/~oz/hash.html\nfunc (i *Instance) djb2Uint32(input uint32) {\n\ti.value = (i.value \u003c\u003c 5) + i.value + input\n}\n\n// AddEntropy uses various runtime variables to add entropy to the existing seed.\nfunc (i *Instance) addEntropy() {\n\t// FIXME: reapply the 5381 initial value?\n\n\t// inherit previous entropy\n\t// nothing to do\n\n\t// handle callers\n\t{\n\t\tcurrentRealm := unsafe.CurrentRealm().Address().String()\n\t\ti.djb2String(currentRealm)\n\t\toriginCaller := unsafe.OriginCaller().String()\n\t\ti.djb2String(originCaller)\n\t}\n\n\t// height\n\t{\n\t\theight := runtime.ChainHeight()\n\t\tif height \u003e= math.MaxUint32 {\n\t\t\theight -= math.MaxUint32\n\t\t}\n\t\ti.djb2Uint32(uint32(height))\n\t}\n\n\t// time\n\t{\n\t\tsecs := time.Now().Second()\n\t\ti.djb2Uint32(uint32(secs))\n\t\tnsecs := time.Now().Nanosecond()\n\t\ti.djb2Uint32(uint32(nsecs))\n\t}\n\n\t// FIXME: compute other hard-to-guess but deterministic variables, like real gas?\n}\n\nfunc (i *Instance) Value() uint32 {\n\ti.addEntropy()\n\treturn i.value\n}\n\nfunc (i *Instance) Value64() uint64 {\n\ti.addEntropy()\n\thigh := i.value\n\ti.addEntropy()\n\n\treturn (uint64(high) \u003c\u003c 32) | uint64(i.value)\n}\n"},{"name":"entropy_test.gno","body":"package entropy\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\nfunc TestInstance(t *testing.T) {\n\tinstance := New()\n\tif instance == nil {\n\t\tt.Errorf(\"instance should not be nil\")\n\t}\n}\n\nfunc TestInstanceValue(t *testing.T) {\n\tbaseEntropy := New()\n\tbaseResult := computeValue(t, baseEntropy)\n\n\tsameHeightEntropy := New()\n\tsameHeightResult := computeValue(t, sameHeightEntropy)\n\n\tif baseResult != sameHeightResult {\n\t\tt.Errorf(\"should have the same result: new=%s, base=%s\", sameHeightResult, baseResult)\n\t}\n\n\ttesting.SkipHeights(1)\n\tdifferentHeightEntropy := New()\n\tdifferentHeightResult := computeValue(t, differentHeightEntropy)\n\n\tif baseResult == differentHeightResult {\n\t\tt.Errorf(\"should have different result: new=%s, base=%s\", differentHeightResult, baseResult)\n\t}\n}\n\nfunc TestInstanceValue64(t *testing.T) {\n\tbaseEntropy := New()\n\tbaseResult := computeValue64(t, baseEntropy)\n\n\tsameHeightEntropy := New()\n\tsameHeightResult := computeValue64(t, sameHeightEntropy)\n\n\tif baseResult != sameHeightResult {\n\t\tt.Errorf(\"should have the same result: new=%s, base=%s\", sameHeightResult, baseResult)\n\t}\n\n\ttesting.SkipHeights(1)\n\tdifferentHeightEntropy := New()\n\tdifferentHeightResult := computeValue64(t, differentHeightEntropy)\n\n\tif baseResult == differentHeightResult {\n\t\tt.Errorf(\"should have different result: new=%s, base=%s\", differentHeightResult, baseResult)\n\t}\n}\n\nfunc computeValue(t *testing.T, r *Instance) string {\n\tt.Helper()\n\n\tout := \"\"\n\tfor i := 0; i \u003c 10; i++ {\n\t\tval := int(r.Value())\n\t\tout += strconv.Itoa(val) + \" \"\n\t}\n\n\treturn out\n}\n\nfunc computeValue64(t *testing.T, r *Instance) string {\n\tt.Helper()\n\n\tout := \"\"\n\tfor i := 0; i \u003c 10; i++ {\n\t\tval := int(r.Value64())\n\t\tout += strconv.Itoa(val) + \" \"\n\t}\n\n\treturn out\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/entropy/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"errs","path":"gno.land/p/moul/errs/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/errs`\n\nCombine several errors into one. A port of the core of\n[uber-go/multierr](https://github.com/uber-go/multierr) (MIT), trimmed to what\ngno needs.\n\n```go\nfunc Combine(errs ...error) error   // nil, the single error, or a *multiError\nfunc Errors(err error) []error      // unwrap back to the flat list\n```\n\n`Combine` has three behaviours worth knowing, because they are what make it\nsafe to call unconditionally:\n\n- all inputs nil gives `nil`, so `if err := errs.Combine(...); err != nil` works\n  as written;\n- exactly one non-nil input is returned **as itself**, not wrapped, so a type\n  assertion or `errors.Is` upstream still matches;\n- nested `*multiError` inputs are flattened, so combining in a loop does not\n  build a tree.\n\nThe combined error prints two ways: `Error()` gives one line with `; ` between\nmessages (for logs and panics), `String()` gives one error per line (for a\nRender block).\n\n```go\nerr1 := doSomething()\nerr2 := doSomethingElse()\nif err := errs.Combine(err1, err2); err != nil {\n\treturn err\n}\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"errs.gno","body":"// Package errs provides utilities for combining multiple errors.\n// This is a simplified version of https://github.com/uber-go/multierr (MIT License),\n// adapted for the Gno programming language with a focus on core functionality\n// and idiomatic usage patterns.\n//\n// Example usage:\n//\n//\terr1 := doSomething()\n//\terr2 := doSomethingElse()\n//\tif err := errs.Combine(err1, err2); err != nil {\n//\t    return err // Returns combined errors or single error\n//\t}\npackage errs\n\nimport (\n\t\"strings\"\n)\n\n// multiError represents multiple errors combined into one.\ntype multiError struct {\n\terrors []error\n}\n\n// Error implements the error interface by returning a single-line representation\n// of all contained errors, separated by semicolons.\nfunc (m *multiError) Error() string {\n\tif m == nil || len(m.errors) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar b strings.Builder\n\tfirst := true\n\tfor _, err := range m.errors {\n\t\tif first {\n\t\t\tfirst = false\n\t\t} else {\n\t\t\tb.WriteString(\"; \")\n\t\t}\n\t\tb.WriteString(err.Error())\n\t}\n\treturn b.String()\n}\n\n// String returns a multi-line representation of the error.\nfunc (m *multiError) String() string {\n\tif m == nil || len(m.errors) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"the following errors occurred:\")\n\tfor _, err := range m.errors {\n\t\tb.WriteString(\"\\n -  \")\n\t\tb.WriteString(err.Error())\n\t}\n\treturn b.String()\n}\n\n// Unwrap returns the slice of underlying errors contained in this multiError.\n// Returns nil if the receiver is nil.\nfunc (m *multiError) Unwrap() []error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\treturn m.errors\n}\n\n// Errors extracts the underlying errors from an error interface.\n// If the error is a multiError, it returns its contained errors.\n// If the error is nil, returns nil.\n// If the error is a regular error, returns a slice containing just that error.\nfunc Errors(err error) []error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif merr, ok := err.(*multiError); ok {\n\t\treturn merr.Unwrap()\n\t}\n\n\treturn []error{err}\n}\n\n// Combine merges multiple errors into a single error efficiently.\n// It handles several cases:\n//   - If all input errors are nil, returns nil\n//   - If there's exactly one non-nil error, returns that error directly\n//   - If there are multiple non-nil errors, returns a multiError containing them\n//   - Flattens any *multiError in the input\nfunc Combine(errs ...error) error {\n\tnonNil := make([]error, 0, len(errs))\n\tfor _, err := range errs {\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif m, ok := err.(*multiError); ok \u0026\u0026 m != nil {\n\t\t\tnonNil = append(nonNil, m.Unwrap()...)\n\t\t} else {\n\t\t\tnonNil = append(nonNil, err)\n\t\t}\n\t}\n\n\tswitch len(nonNil) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn nonNil[0]\n\tdefault:\n\t\treturn \u0026multiError{errors: nonNil}\n\t}\n}\n"},{"name":"errs_test.gno","body":"package errs\n\nimport (\n\t\"testing\"\n)\n\n// testError is a simple error implementation for testing\ntype testError struct {\n\tmsg string\n}\n\nfunc (e *testError) Error() string {\n\treturn e.msg\n}\n\nfunc newError(msg string) error {\n\treturn \u0026testError{msg: msg}\n}\n\nfunc TestCombine(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\terrors   []error\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"single error\",\n\t\t\terrors:   []error{newError(\"error1\"), nil},\n\t\t\texpected: \"error1\",\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple errors\",\n\t\t\terrors:   []error{newError(\"error1\"), newError(\"error2\"), newError(\"error3\")},\n\t\t\texpected: \"error1; error2; error3\",\n\t\t},\n\t\t{\n\t\t\tname:     \"mixed nil and non-nil\",\n\t\t\terrors:   []error{nil, newError(\"error1\"), nil, newError(\"error2\")},\n\t\t\texpected: \"error1; error2\",\n\t\t},\n\t\t{\n\t\t\tname:     \"both nil (2)\",\n\t\t\terrors:   []error{nil, nil},\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"first nil (2)\",\n\t\t\terrors:   []error{nil, newError(\"error2\")},\n\t\t\texpected: \"error2\",\n\t\t},\n\t\t{\n\t\t\tname:     \"second nil (2)\",\n\t\t\terrors:   []error{newError(\"error1\"), nil},\n\t\t\texpected: \"error1\",\n\t\t},\n\t\t{\n\t\t\tname:     \"both non-nil (2)\",\n\t\t\terrors:   []error{newError(\"error1\"), newError(\"error2\")},\n\t\t\texpected: \"error1; error2\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\terr := Combine(tt.errors...)\n\t\tif tt.expected == \"\" {\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"%s: expected nil error, got %v\", tt.name, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif err == nil {\n\t\t\tt.Errorf(\"%s: expected non-nil error\", tt.name)\n\t\t\tcontinue\n\t\t}\n\n\t\tif got := err.Error(); got != tt.expected {\n\t\t\tt.Errorf(\"%s: expected %q, got %q\", tt.name, tt.expected, got)\n\t\t}\n\t}\n}\n\nfunc TestErrors(t *testing.T) {\n\terr1 := newError(\"error1\")\n\terr2 := newError(\"error2\")\n\tcombined := Combine(err1, err2)\n\n\ttests := []struct {\n\t\tname          string\n\t\terr           error\n\t\texpectedCount int\n\t}{\n\t\t{\n\t\t\tname:          \"nil error\",\n\t\t\terr:           nil,\n\t\t\texpectedCount: 0,\n\t\t},\n\t\t{\n\t\t\tname:          \"single error\",\n\t\t\terr:           err1,\n\t\t\texpectedCount: 1,\n\t\t},\n\t\t{\n\t\t\tname:          \"multiple errors\",\n\t\t\terr:           combined,\n\t\t\texpectedCount: 2,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\terrs := Errors(tt.err)\n\t\tif len(errs) != tt.expectedCount {\n\t\t\tt.Errorf(\"%s: expected %d errors, got %d\", tt.name, tt.expectedCount, len(errs))\n\t\t}\n\t}\n}\n\nfunc TestMultiErrorString(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\terrors   []error\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"nil errors\",\n\t\t\terrors:   nil,\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"empty errors\",\n\t\t\terrors:   []error{},\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"single error\",\n\t\t\terrors:   []error{newError(\"error1\")},\n\t\t\texpected: \"the following errors occurred:\\n -  error1\",\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple errors\",\n\t\t\terrors:   []error{newError(\"error1\"), newError(\"error2\")},\n\t\t\texpected: \"the following errors occurred:\\n -  error1\\n -  error2\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmerr := \u0026multiError{errors: tt.errors}\n\t\t\tif got := merr.String(); got != tt.expected {\n\t\t\t\tt.Errorf(\"multiError.String() = %q, want %q\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCombineEdgeCases(t *testing.T) {\n\terr1 := newError(\"error1\")\n\terr2 := newError(\"error2\")\n\terr3 := newError(\"error3\")\n\n\tmerr := Combine(err1, err2)\n\n\ttests := []struct {\n\t\tname     string\n\t\terrors   []error\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"append to multiError\",\n\t\t\terrors:   []error{merr, err3},\n\t\t\texpected: \"error1; error2; error3\",\n\t\t},\n\t\t{\n\t\t\tname:     \"prepend to multiError\",\n\t\t\terrors:   []error{err3, merr},\n\t\t\texpected: \"error3; error1; error2\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := Combine(tt.errors...)\n\t\t\tif got := err.Error(); got != tt.expected {\n\t\t\t\tt.Errorf(\"Combine() = %q, want %q\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnwrapNilReceiver(t *testing.T) {\n\tvar merr *multiError\n\terrs := merr.Unwrap()\n\tif errs != nil {\n\t\tt.Errorf(\"Expected nil slice for nil receiver, got %v\", errs)\n\t}\n}\n\nfunc TestMultiErrorUnwrap(t *testing.T) {\n\tvar nilMulti *multiError\n\tif got := nilMulti.Unwrap(); got != nil {\n\t\tt.Errorf(\"Unwrap on nil receiver: expected nil, got %v\", got)\n\t}\n\n\tempty := \u0026multiError{errors: nil}\n\tif got := empty.Unwrap(); got != nil {\n\t\tt.Errorf(\"Unwrap on empty: expected nil, got %v\", got)\n\t}\n\n\tsingle := \u0026multiError{errors: []error{newError(\"foo\")}}\n\tgot := single.Unwrap()\n\tif len(got) != 1 || got[0].Error() != \"foo\" {\n\t\tt.Errorf(\"Unwrap on single: expected [foo], got %v\", got)\n\t}\n\n\tmulti := \u0026multiError{errors: []error{newError(\"foo\"), newError(\"bar\")}}\n\tgot = multi.Unwrap()\n\tif len(got) != 2 || got[0].Error() != \"foo\" || got[1].Error() != \"bar\" {\n\t\tt.Errorf(\"Unwrap on multi: expected [foo bar], got %v\", got)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/errs/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"forge","path":"gno.land/p/moul/forge/v1","files":[{"name":"README.md","body":"# forge\n\nThe domain engine of an on-chain software forge: repos, roles, an append-only\nreference log, issues, change requests and reviews. Pure gno, no chain imports,\nno realm globals. The realm that wires it to gno.land is\n[`gno.land/r/moul/forge/v0`](../../../../r/moul/forge/v0).\n\n## Packages and releases: the bridge to a deployed path\n\nA repo id is `\u003cnamespace\u003e/\u003cname\u003e`, exactly two parts, so `r/moul/home` can never\nbe one. Without a mapping there is no way to ask *which repo publishes this\npackage path*, which is the first question anyone arriving from an explorer has.\n\n`PublishPackage` records the claim and indexes it forge-wide, so `PackageRepo`\nanswers from the path alone without scanning every repo. One repo publishes many\npaths (moul/gno-contracts publishes 193 of them), and a path may be claimed by\nexactly one repo: silently letting a second repo take it would be a capture of\nanother project's package in every explorer reading this index.\n\n**The claim is not verified, and cannot be.** A realm cannot ask the chain who\ndeployed a path. What is guaranteed is that someone with write access to the\nrepo said it, under a namespace `r/sys/users` governs. Weigh it the way you\nweigh a `go.mod`: it says where the author says the source lives.\n\nA `Release` is a tag, notes, and the object the tag names. A tag cannot be\nre-cut, because a consumer who pinned `v1.2.0` and later received different\nbytes has been lied to. Withdrawing one is `YankRelease`, which leaves it\nvisible: a version that vanished reads as \"never published\" rather than \"do not\nuse this\". Releases iterate in **cut order, never tag order** — tags are not\nrequired to be semver here (gno.land's own packages are `v0` and `v1`), so any\nversion sort would present `v10` before `v2` and call it newest.\n\n## What it stores, and what it refuses to store\n\nIt does not store code. Git objects stay in git, behind whatever mirror a repo\ndeclares (an https remote, an IPFS CID, a peer). On gno.land a realm write locks\na storage deposit of 100ugnot per byte, so a 1 MB repository would cost about\n100 GNOT to park on chain and more on every push. Anchoring is the only shape\nthat survives contact with real repositories.\n\nWhat it does store is the part a forge is actually trusted for, and that git\nalone does not authenticate:\n\n1. **Which object a ref points at**, in what order it got there, and who said\n   so: an append-only, hash-chained reference log.\n2. **Who may move which ref**, and under what review policy.\n3. **The social layer**: issues, change requests and reviews bound to addresses\n   rather than to platform accounts.\n4. **The merge decision**, recorded as one more entry in the same log.\n5. **Which deployed package paths a repo publishes**, and **which releases it\n   has cut**. See below: these two are what let an explorer start from a\n   `gno.land/...` path and find the repo behind it.\n\n## The reference log\n\nEvery ref move appends a `LogEntry`: ref name, old object, new object, actor,\nblock height, kind (`create`, `update`, `force`, `delete`, `merge`), an optional\nnote, and a `Digest` committing to the previous entry's digest. Publish\n`LogHead()` anywhere off chain and the entire history of every ref becomes\nfalsifiable. `VerifyLog()` recomputes the chain; a client should run the same\ncomputation over the values it read back, since a transparency log nobody\nverifies is just a log.\n\nMoves are compare-and-swap:\n\n```go\nr.SetRef(actor, height, \"refs/heads/main\", expectedOID, newOID, \"ship it\")\n```\n\n`expectedOID` is the tip the caller last saw, empty to create the ref. A stale\nexpectation returns `ErrStaleRef` instead of overwriting. That is git's\n`--force-with-lease`, except the lease is held by consensus rather than by the\nserver you are pushing to. `ForceSetRef` skips the expectation, needs\n`RoleMaintainer`, and is permanently recorded as `KindForce`: a force-push is\nnot forbidden here, it is made impossible to hide.\n\nThe chain has no objects, so it cannot check that a new tip descends from the\nold one, and this package does not pretend otherwise. Ordering, attribution and\npolicy are on chain; ancestry is verified by a client that holds the repo. This\nis the same split as gittuf's reference state log, with the log moved out of the\nrepository and into a place no maintainer can rewrite.\n\n## Roles\n\n`RoleNone \u003c RoleReader \u003c RoleWriter \u003c RoleMaintainer \u003c RoleAdmin \u003c RoleOwner`,\ntotally ordered so every check is one comparison. Writers move refs, maintainers\nforce and merge, admins manage members and policy. The last owner cannot be\ndemoted. Anyone can open an issue or a change request without a role: the spam\ngate is that the author pays gas and locks the deposit for their own bytes.\n\n## Reviews that cannot go stale unnoticed\n\nA `Review` names the object id it reviewed, not the change. Push a new head and\nevery earlier approval stops counting, because it approved something that is no\nlonger what would be merged. Nothing has to remember to dismiss it, and no\nsetting can turn the behaviour off. Only a writer's approval counts toward\n`RequiredApprovals`; anyone else's review is signal, not authority. A\n`request-changes` verdict from a writer blocks the merge while it stands.\n\n`MergeChange` is a compare-and-swap on the target ref plus a policy check, and\nit writes a `KindMerge` entry naming the change it came from.\n\n## API shape\n\nErrors, never panics: this package is pure, so a realm turns an error into an\nabort (the only way to revert state in gno) and a test asserts on the value.\nEvery collection is an `avl.Tree`, so every listing is ordered and paginatable,\nand no iteration walks unbounded state. The caller supplies the actor address\nand the block height, which is what makes the whole engine unit-testable with no\nchain at all.\n\n```go\nf := forge.New()\nr, _ := f.CreateRepo(alice, height, \"moul/forge\", \"an on-chain forge\", \"\")\nr.SetMember(alice, bob, forge.RoleMaintainer)\nr.SetRef(alice, height, \"refs/heads/main\", \"\", oid, \"initial import\")\nc, _ := r.OpenChange(carol, height, \"title\", \"body\", \"\", \"refs/heads/feat\", head, \"refs/heads/main\")\nr.ReviewChange(bob, height, c.ID, forge.VerdictApprove, \"lgtm\")\nr.MergeChange(bob, height, c.ID, oid, merged, \"merge change 0\")\n```\n\n## Limits\n\nEvery stored string is bounded (see the `Max*` constants) because an unbounded\nfield is an unbounded deposit. Ref names are a `refs/`-rooted subset of\ngit-check-ref-format; object ids are 40 or 64 lowercase hex characters; repo ids\nare `\u003cnamespace\u003e/\u003cname\u003e`, where the name is a lowercase slug and the namespace is\neither a slug (a claimed user name) or a bech32 address. The two shapes cannot\ncollide: an address is 40 characters and a slug caps at 39.\n\nThis package validates the **shape** of a namespace and nothing else. Whether a\ncaller may claim one is an ownership question that needs a chain, so it lives in\nthe realm: a name must be held in `r/sys/users`, an address must be the caller's\nown.\n\nOne economic rule shows up in the API: deleting is privileged. On gno.land the\nstorage-deposit refund goes to whoever frees the bytes, not to whoever paid for\nthem, so an open delete path pays for vandalism. `DeleteRef` needs\n`RoleMaintainer`, and issues, comments and reviews have no delete at all.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/forge/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/forge/v1/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"change.gno","body":"package forge\n\nimport \"gno.land/p/nt/avl/v0\"\n\n// Change states.\nconst (\n\tStateOpen   = \"open\"\n\tStateMerged = \"merged\"\n\tStateClosed = \"closed\"\n)\n\n// Review verdicts.\nconst (\n\tVerdictApprove        = \"approve\"\n\tVerdictRequestChanges = \"request-changes\"\n\tVerdictComment        = \"comment\"\n)\n\n// Change is a change request (a pull request): a claim that TargetRef should be\n// moved to include HeadOID, plus the reviews of that claim.\n//\n// Reviews are bound to the object id they reviewed, not to the change. Push a\n// new head and every earlier approval stops counting: not by a policy toggle a\n// maintainer can switch off, but because the approval names an object that is\n// no longer what is being merged.\ntype Change struct {\n\tID         int64\n\tTitle      string\n\tBody       string\n\tAuthor     address\n\tSourceRepo string // forge repo id, or a mirror locator; \"\" means this repo\n\tSourceRef  string\n\tHeadOID    string\n\tTargetRef  string\n\tState      string\n\tCreatedAt  int64\n\tUpdatedAt  int64\n\n\tMergedOID string // the object TargetRef moved to\n\tMergedBy  address\n\tMergedAt  int64\n\n\treviews     *avl.Tree // address string -\u003e *Review (latest per reviewer)\n\tcomments    *avl.Tree // padded id -\u003e *Comment\n\tnextComment int64\n}\n\n// Review is one reviewer's verdict on one object id.\ntype Review struct {\n\tReviewer address\n\tVerdict  string\n\tOID      string // the head the reviewer actually looked at\n\tBody     string\n\tHeight   int64\n}\n\n// OpenChange files a change request. Permissionless, like an issue: the\n// proposal costs its author gas and deposit, and costs a maintainer nothing\n// until they choose to look.\nfunc (r *Repo) OpenChange(actor address, height int64, title, body, sourceRepo, sourceRef, headOID, targetRef string) (*Change, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tif title == \"\" || !ValidLine(title, MaxTitleLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif !ValidText(body, MaxBodyLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif sourceRepo != \"\" \u0026\u0026 !ValidRepoID(sourceRepo) \u0026\u0026 !ValidMirror(sourceRepo) {\n\t\treturn nil, ErrInvalidRepoID\n\t}\n\tif sourceRef != \"\" \u0026\u0026 !ValidRefName(sourceRef) {\n\t\treturn nil, ErrInvalidRefName\n\t}\n\tif !ValidOID(headOID) {\n\t\treturn nil, ErrInvalidOID\n\t}\n\tif !ValidRefName(targetRef) {\n\t\treturn nil, ErrInvalidRefName\n\t}\n\tc := \u0026Change{\n\t\tID:         r.nextChange,\n\t\tTitle:      title,\n\t\tBody:       body,\n\t\tAuthor:     actor,\n\t\tSourceRepo: sourceRepo,\n\t\tSourceRef:  sourceRef,\n\t\tHeadOID:    headOID,\n\t\tTargetRef:  targetRef,\n\t\tState:      StateOpen,\n\t\tCreatedAt:  height,\n\t\tUpdatedAt:  height,\n\t\treviews:    avl.NewTree(),\n\t\tcomments:   avl.NewTree(),\n\t}\n\tr.changes.Set(seqKey(c.ID), c)\n\tr.nextChange++\n\treturn c, nil\n}\n\n// UpdateChangeHead repoints an open change at a new object. The author may\n// always update their own; a writer may update anyone's (the \"maintainer pushed\n// a fixup\" case).\nfunc (r *Repo) UpdateChangeHead(actor address, height, id int64, headOID string) error {\n\tc := r.Change(id)\n\tif c == nil {\n\t\treturn ErrChangeNotFound\n\t}\n\tif c.State != StateOpen {\n\t\treturn ErrChangeNotOpen\n\t}\n\tif c.Author != actor \u0026\u0026 !r.Can(actor, RoleWriter) {\n\t\treturn ErrUnauthorized\n\t}\n\tif !ValidOID(headOID) {\n\t\treturn ErrInvalidOID\n\t}\n\tif headOID == c.HeadOID {\n\t\treturn ErrSameOID\n\t}\n\tc.HeadOID = headOID\n\tc.UpdatedAt = height\n\treturn nil\n}\n\n// ReviewChange records a verdict against the change's current head. Anyone may\n// review; only a writer's approval counts toward the merge policy (see\n// CountApprovals): an unprivileged review is signal, not authority.\nfunc (r *Repo) ReviewChange(actor address, height, id int64, verdict, body string) error {\n\tif r.Archived {\n\t\treturn ErrRepoArchived\n\t}\n\tc := r.Change(id)\n\tif c == nil {\n\t\treturn ErrChangeNotFound\n\t}\n\tif c.State != StateOpen {\n\t\treturn ErrChangeNotOpen\n\t}\n\tswitch verdict {\n\tcase VerdictApprove, VerdictRequestChanges, VerdictComment:\n\tdefault:\n\t\treturn ErrInvalidVerdict\n\t}\n\tif verdict == VerdictApprove \u0026\u0026 actor == c.Author \u0026\u0026 !r.AllowSelfApproval {\n\t\treturn ErrSelfApproval\n\t}\n\tif !ValidText(body, MaxCommentLen) {\n\t\treturn ErrInvalidText\n\t}\n\tc.reviews.Set(actor.String(), \u0026Review{\n\t\tReviewer: actor,\n\t\tVerdict:  verdict,\n\t\tOID:      c.HeadOID,\n\t\tBody:     body,\n\t\tHeight:   height,\n\t})\n\tc.UpdatedAt = height\n\treturn nil\n}\n\n// CommentChange appends a reply to a change request.\nfunc (r *Repo) CommentChange(actor address, height, id int64, body string) (*Comment, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tc := r.Change(id)\n\tif c == nil {\n\t\treturn nil, ErrChangeNotFound\n\t}\n\tif body == \"\" || !ValidText(body, MaxCommentLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tcm := \u0026Comment{ID: c.nextComment, Author: actor, Body: body, CreatedAt: height}\n\tc.comments.Set(seqKey(cm.ID), cm)\n\tc.nextComment++\n\tc.UpdatedAt = height\n\treturn cm, nil\n}\n\n// CloseChange withdraws or rejects a change. Author or maintainer.\nfunc (r *Repo) CloseChange(actor address, height, id int64) error {\n\tc := r.Change(id)\n\tif c == nil {\n\t\treturn ErrChangeNotFound\n\t}\n\tif c.State != StateOpen {\n\t\treturn ErrChangeNotOpen\n\t}\n\tif c.Author != actor \u0026\u0026 !r.Can(actor, RoleMaintainer) {\n\t\treturn ErrUnauthorized\n\t}\n\tc.State = StateClosed\n\tc.UpdatedAt = height\n\treturn nil\n}\n\n// CountApprovals counts approvals that still apply: cast by a writer or above,\n// against the change's current head, and (unless the repo allows it) not the\n// author's own.\nfunc (r *Repo) CountApprovals(c *Change) int {\n\tn := 0\n\tc.reviews.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\trv := value.(*Review)\n\t\tif rv.Verdict != VerdictApprove || rv.OID != c.HeadOID {\n\t\t\treturn false\n\t\t}\n\t\tif rv.Reviewer == c.Author \u0026\u0026 !r.AllowSelfApproval {\n\t\t\treturn false\n\t\t}\n\t\tif !r.Can(rv.Reviewer, RoleWriter) {\n\t\t\treturn false\n\t\t}\n\t\tn++\n\t\treturn false\n\t})\n\treturn n\n}\n\n// CountBlocking counts writers who requested changes on the current head.\nfunc (r *Repo) CountBlocking(c *Change) int {\n\tn := 0\n\tc.reviews.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\trv := value.(*Review)\n\t\tif rv.Verdict == VerdictRequestChanges \u0026\u0026 rv.OID == c.HeadOID \u0026\u0026 r.Can(rv.Reviewer, RoleWriter) {\n\t\t\tn++\n\t\t}\n\t\treturn false\n\t})\n\treturn n\n}\n\n// MergeChange moves TargetRef to mergedOID and records the move as one more\n// entry in the reference log, tagged with the change it came from.\n//\n// expectedTargetOID is a compare-and-swap on the target ref (\"\" when the ref\n// does not exist yet): a change approved against one base cannot be merged onto\n// a base that moved underneath it. mergedOID is computed off chain by whoever\n// performs the merge: the chain records the claim, signed, ordered and\n// attributed, and a client with the objects verifies that the result actually\n// contains HeadOID.\nfunc (r *Repo) MergeChange(actor address, height, id int64, expectedTargetOID, mergedOID, note string) (*LogEntry, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tc := r.Change(id)\n\tif c == nil {\n\t\treturn nil, ErrChangeNotFound\n\t}\n\tif c.State != StateOpen {\n\t\treturn nil, ErrChangeNotOpen\n\t}\n\tif !r.Can(actor, RoleMaintainer) {\n\t\treturn nil, ErrUnauthorized\n\t}\n\tif !ValidOID(mergedOID) {\n\t\treturn nil, ErrInvalidOID\n\t}\n\tif !ValidLine(note, MaxNoteLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif r.CountBlocking(c) \u003e 0 {\n\t\treturn nil, ErrChangesRequested\n\t}\n\tif r.CountApprovals(c) \u003c r.RequiredApprovals {\n\t\treturn nil, ErrNotEnoughApproval\n\t}\n\tcur := r.Ref(c.TargetRef)\n\tswitch {\n\tcase cur == nil \u0026\u0026 expectedTargetOID != \"\":\n\t\treturn nil, ErrRefNotFound\n\tcase cur != nil \u0026\u0026 cur.OID != expectedTargetOID:\n\t\treturn nil, ErrStaleRef\n\tcase cur != nil \u0026\u0026 cur.OID == mergedOID:\n\t\treturn nil, ErrSameOID\n\t}\n\told := \"\"\n\tif cur != nil {\n\t\told = cur.OID\n\t}\n\tr.refs.Set(c.TargetRef, \u0026Ref{Name: c.TargetRef, OID: mergedOID, UpdatedAt: height, UpdatedBy: actor})\n\te := r.appendLog(actor, height, c.TargetRef, old, mergedOID, KindMerge, c.ID, note)\n\tc.State = StateMerged\n\tc.MergedOID = mergedOID\n\tc.MergedBy = actor\n\tc.MergedAt = height\n\tc.UpdatedAt = height\n\treturn e, nil\n}\n\n// Change returns a change by id, or nil.\nfunc (r *Repo) Change(id int64) *Change {\n\tv := r.changes.Get(seqKey(id))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Change)\n}\n\n// IterateChanges walks change requests newest-first.\nfunc (r *Repo) IterateChanges(offset, count int, cb func(*Change) bool) {\n\tif count \u003c= 0 {\n\t\tcount = r.changes.Size()\n\t}\n\tr.changes.ReverseIterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn cb(value.(*Change))\n\t})\n}\n\n// OpenChangeCount counts change requests still open.\nfunc (r *Repo) OpenChangeCount() int {\n\tn := 0\n\tr.changes.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\tif value.(*Change).State == StateOpen {\n\t\t\tn++\n\t\t}\n\t\treturn false\n\t})\n\treturn n\n}\n\n// ReviewCount is the number of reviewers who have weighed in (latest verdict\n// per reviewer, on any head).\nfunc (c *Change) ReviewCount() int { return c.reviews.Size() }\n\n// Review returns a reviewer's latest verdict, or nil.\nfunc (c *Change) Review(a address) *Review {\n\tv := c.reviews.Get(a.String())\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Review)\n}\n\n// IterateReviews walks reviews in reviewer-address order.\nfunc (c *Change) IterateReviews(cb func(*Review) bool) {\n\tc.reviews.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\treturn cb(value.(*Review))\n\t})\n}\n\n// CommentCount is the number of replies on the change.\nfunc (c *Change) CommentCount() int { return c.comments.Size() }\n\n// IterateComments walks replies oldest-first.\nfunc (c *Change) IterateComments(offset, count int, cb func(*Comment) bool) {\n\tif count \u003c= 0 {\n\t\tcount = c.comments.Size()\n\t}\n\tc.comments.IterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn cb(value.(*Comment))\n\t})\n}\n\n// Stale reports whether a review no longer applies to the change's head.\nfunc (c *Change) Stale(rv *Review) bool { return rv.OID != c.HeadOID }\n"},{"name":"change_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// openChange sets up a repo with main at oid(\"a\") and one open change proposing\n// oid(\"b\"), authored by carol (a writer).\nfunc openChange(t *testing.T) (*Repo, *Change) {\n\tt.Helper()\n\t_, r := newRepo(t)\n\t_, err := r.SetRef(alice, 100, \"refs/heads/main\", \"\", oid(\"a\"), \"initial\")\n\turequire.NoError(t, err)\n\tc, err := r.OpenChange(carol, 101, \"add the log\", \"closes #1\", \"\", \"refs/heads/feat\", oid(\"b\"), \"refs/heads/main\")\n\turequire.NoError(t, err)\n\treturn r, c\n}\n\nfunc TestOpenChangeValidation(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t_, err := r.OpenChange(eve, 101, \"\", \"\", \"\", \"\", oid(\"b\"), \"refs/heads/main\")\n\tuassert.ErrorIs(t, err, ErrInvalidText)\n\t_, err = r.OpenChange(eve, 101, \"t\", \"\", \"\", \"\", \"beef\", \"refs/heads/main\")\n\tuassert.ErrorIs(t, err, ErrInvalidOID)\n\t_, err = r.OpenChange(eve, 101, \"t\", \"\", \"\", \"\", oid(\"b\"), \"main\")\n\tuassert.ErrorIs(t, err, ErrInvalidRefName)\n\t_, err = r.OpenChange(eve, 101, \"t\", \"\", \"NOT/an/id\", \"\", oid(\"b\"), \"refs/heads/main\")\n\tuassert.ErrorIs(t, err, ErrInvalidRepoID)\n\n\t// A fork or a plain git remote are both legal sources: the objects live\n\t// off chain either way.\n\tc, err := r.OpenChange(eve, 101, \"from a fork\", \"\", \"eve/forge\", \"refs/heads/feat\", oid(\"b\"), \"refs/heads/main\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, StateOpen, c.State)\n\tc2, err := r.OpenChange(eve, 101, \"from a remote\", \"\", \"https://example.com/x.git\", \"refs/heads/feat\", oid(\"b\"), \"refs/heads/main\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1), c2.ID)\n\tuassert.Equal(t, 2, r.OpenChangeCount())\n}\n\nfunc TestApprovalsAreBoundToTheReviewedObject(t *testing.T) {\n\tr, c := openChange(t)\n\n\turequire.NoError(t, r.ReviewChange(bob, 102, 0, VerdictApprove, \"lgtm\"))\n\tuassert.Equal(t, 1, r.CountApprovals(c))\n\n\t// Push a new head: the approval named an object that is no longer what\n\t// would be merged, so it stops counting. Nothing had to remember to\n\t// dismiss it.\n\turequire.NoError(t, r.UpdateChangeHead(carol, 103, 0, oid(\"c\")))\n\tuassert.Equal(t, 0, r.CountApprovals(c))\n\tuassert.True(t, c.Stale(c.Review(bob)))\n\n\turequire.NoError(t, r.ReviewChange(bob, 104, 0, VerdictApprove, \"still lgtm\"))\n\tuassert.Equal(t, 1, r.CountApprovals(c))\n\tuassert.Equal(t, 1, c.ReviewCount(), \"one verdict per reviewer, latest wins\")\n}\n\nfunc TestApprovalWeight(t *testing.T) {\n\tr, c := openChange(t)\n\n\t// Anyone may review; only a writer's approval counts toward policy.\n\turequire.NoError(t, r.ReviewChange(eve, 102, 0, VerdictApprove, \"as a user: works\"))\n\turequire.NoError(t, r.ReviewChange(dave, 102, 0, VerdictApprove, \"reader here\"))\n\tuassert.Equal(t, 2, c.ReviewCount())\n\tuassert.Equal(t, 0, r.CountApprovals(c), \"unprivileged review is signal, not authority\")\n\n\t// The author cannot approve their own change, unless the repo says so.\n\tuassert.ErrorIs(t, r.ReviewChange(carol, 102, 0, VerdictApprove, \"mine\"), ErrSelfApproval)\n\turequire.NoError(t, r.SetPolicy(alice, 1, true))\n\turequire.NoError(t, r.ReviewChange(carol, 102, 0, VerdictApprove, \"mine\"))\n\tuassert.Equal(t, 1, r.CountApprovals(c))\n\n\tuassert.ErrorIs(t, r.ReviewChange(bob, 102, 0, \"lgtm?\", \"\"), ErrInvalidVerdict)\n\tuassert.ErrorIs(t, r.ReviewChange(bob, 102, 9, VerdictApprove, \"\"), ErrChangeNotFound)\n}\n\nfunc TestMergePolicy(t *testing.T) {\n\tr, c := openChange(t)\n\n\t// Default policy is one approval.\n\t_, err := r.MergeChange(bob, 105, 0, oid(\"a\"), oid(\"e\"), \"merge #0\")\n\tuassert.ErrorIs(t, err, ErrNotEnoughApproval)\n\n\turequire.NoError(t, r.ReviewChange(bob, 106, 0, VerdictApprove, \"lgtm\"))\n\n\t// A writer cannot merge, however well reviewed.\n\t_, err = r.MergeChange(carol, 107, 0, oid(\"a\"), oid(\"e\"), \"\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\n\t// A blocking review stops the merge while it stands.\n\turequire.NoError(t, r.ReviewChange(alice, 107, 0, VerdictRequestChanges, \"needs a test\"))\n\tuassert.Equal(t, 1, r.CountBlocking(c))\n\t_, err = r.MergeChange(bob, 108, 0, oid(\"a\"), oid(\"e\"), \"\")\n\tuassert.ErrorIs(t, err, ErrChangesRequested)\n\turequire.NoError(t, r.ReviewChange(alice, 109, 0, VerdictApprove, \"test added\"))\n\n\t// The base moved: the change was approved against a tree that no longer\n\t// exists, so the merge is refused rather than silently rebased.\n\t_, err = r.MergeChange(bob, 110, 0, oid(\"9\"), oid(\"e\"), \"\")\n\tuassert.ErrorIs(t, err, ErrStaleRef)\n\n\te, err := r.MergeChange(bob, 111, 0, oid(\"a\"), oid(\"e\"), \"merge change 0\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, KindMerge, e.Kind)\n\tuassert.Equal(t, int64(0), e.ChangeID, \"the log entry names the change it came from\")\n\tuassert.Equal(t, oid(\"a\"), e.OldOID)\n\tuassert.Equal(t, oid(\"e\"), r.Ref(\"refs/heads/main\").OID, \"the ref moved\")\n\tuassert.Equal(t, StateMerged, c.State)\n\tuassert.Equal(t, bob.String(), c.MergedBy.String())\n\tuassert.Equal(t, int64(111), c.MergedAt)\n\tuassert.Equal(t, 0, r.OpenChangeCount())\n\n\tok, _ := r.VerifyLog()\n\tuassert.True(t, ok)\n\n\t// A merged change is closed to everything.\n\t_, err = r.MergeChange(bob, 112, 0, oid(\"e\"), oid(\"f\"), \"\")\n\tuassert.ErrorIs(t, err, ErrChangeNotOpen)\n\tuassert.ErrorIs(t, r.UpdateChangeHead(carol, 112, 0, oid(\"d\")), ErrChangeNotOpen)\n\tuassert.ErrorIs(t, r.ReviewChange(bob, 112, 0, VerdictApprove, \"\"), ErrChangeNotOpen)\n\tuassert.ErrorIs(t, r.CloseChange(carol, 112, 0), ErrChangeNotOpen)\n}\n\nfunc TestMergeCreatesMissingRef(t *testing.T) {\n\t_, r := newRepo(t)\n\tc, err := r.OpenChange(carol, 101, \"first branch\", \"\", \"\", \"refs/heads/feat\", oid(\"b\"), \"refs/heads/main\")\n\turequire.NoError(t, err)\n\turequire.NoError(t, r.SetPolicy(alice, 0, false))\n\n\t_, err = r.MergeChange(bob, 102, 0, oid(\"a\"), oid(\"b\"), \"\")\n\tuassert.ErrorIs(t, err, ErrRefNotFound, \"a target that does not exist takes no expectation\")\n\n\te, err := r.MergeChange(bob, 103, 0, \"\", oid(\"b\"), \"first merge\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, KindMerge, e.Kind)\n\tuassert.Equal(t, \"\", e.OldOID)\n\tuassert.Equal(t, oid(\"b\"), r.Ref(\"refs/heads/main\").OID)\n\tuassert.Equal(t, StateMerged, c.State)\n}\n\nfunc TestChangeCommentsAndClose(t *testing.T) {\n\tr, c := openChange(t)\n\n\tcm, err := r.CommentChange(eve, 102, 0, \"does this cover the force case?\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(0), cm.ID)\n\tuassert.Equal(t, 1, c.CommentCount())\n\t_, err = r.CommentChange(eve, 102, 0, \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidText)\n\n\tuassert.ErrorIs(t, r.CloseChange(eve, 103, 0), ErrUnauthorized)\n\turequire.NoError(t, r.CloseChange(carol, 103, 0), \"the author may withdraw\")\n\tuassert.Equal(t, StateClosed, c.State)\n\n\tuassert.True(t, r.Change(42) == nil)\n\tuassert.ErrorIs(t, r.UpdateChangeHead(carol, 104, 42, oid(\"d\")), ErrChangeNotFound)\n}\n\nfunc TestChangeIterationIsNewestFirst(t *testing.T) {\n\t_, r := newRepo(t)\n\tfor _, title := range []string{\"one\", \"two\", \"three\"} {\n\t\t_, err := r.OpenChange(carol, 101, title, \"\", \"\", \"\", oid(\"b\"), \"refs/heads/main\")\n\t\turequire.NoError(t, err)\n\t}\n\n\tvar got []string\n\tr.IterateChanges(0, 0, func(c *Change) bool {\n\t\tgot = append(got, c.Title)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"three,two,one\", join(got))\n\n\tvar reviewers []string\n\tc := r.Change(0)\n\turequire.NoError(t, r.ReviewChange(bob, 102, 0, VerdictApprove, \"\"))\n\turequire.NoError(t, r.ReviewChange(alice, 102, 0, VerdictComment, \"\"))\n\tc.IterateReviews(func(rv *Review) bool {\n\t\treviewers = append(reviewers, rv.Verdict)\n\t\treturn false\n\t})\n\tuassert.Equal(t, 2, len(reviewers))\n}\n"},{"name":"errors.gno","body":"package forge\n\nimport \"errors\"\n\n// Stable, machine-readable error values. Callers (realms, clients, indexers)\n// should switch on these rather than on message text: a realm turns them into\n// panics, and the panic string is the only thing a user sees.\nvar (\n\tErrInvalidRepoID     = errors.New(\"forge: invalid repo id\")\n\tErrInvalidRefName    = errors.New(\"forge: invalid ref name\")\n\tErrInvalidOID        = errors.New(\"forge: invalid object id\")\n\tErrInvalidText       = errors.New(\"forge: invalid text\")\n\tErrInvalidRole       = errors.New(\"forge: invalid role\")\n\tErrInvalidVerdict    = errors.New(\"forge: invalid review verdict\")\n\tErrInvalidMirror     = errors.New(\"forge: invalid mirror locator\")\n\tErrTooLong           = errors.New(\"forge: value too long\")\n\tErrTooMany           = errors.New(\"forge: too many entries\")\n\tErrRepoExists        = errors.New(\"forge: repo already exists\")\n\tErrRepoNotFound      = errors.New(\"forge: repo not found\")\n\tErrRepoArchived      = errors.New(\"forge: repo is archived\")\n\tErrRefNotFound       = errors.New(\"forge: ref not found\")\n\tErrRefExists         = errors.New(\"forge: ref already exists\")\n\tErrStaleRef          = errors.New(\"forge: stale ref (compare-and-swap failed)\")\n\tErrUnauthorized      = errors.New(\"forge: unauthorized\")\n\tErrIssueNotFound     = errors.New(\"forge: issue not found\")\n\tErrIssueClosed       = errors.New(\"forge: issue is closed\")\n\tErrChangeNotFound    = errors.New(\"forge: change not found\")\n\tErrChangeNotOpen     = errors.New(\"forge: change is not open\")\n\tErrSelfApproval      = errors.New(\"forge: self-approval is not allowed\")\n\tErrNotEnoughApproval = errors.New(\"forge: not enough approvals\")\n\tErrChangesRequested  = errors.New(\"forge: changes requested by a reviewer\")\n\tErrSameOID           = errors.New(\"forge: ref already points at that object\")\n\tErrLastOwner         = errors.New(\"forge: cannot demote the last owner\")\n\tErrInvalidPkgPath    = errors.New(\"forge: invalid package path\")\n\tErrInvalidTag        = errors.New(\"forge: invalid release tag\")\n\tErrPackageClaimed    = errors.New(\"forge: package path is claimed by another repo\")\n\tErrPackageNotFound   = errors.New(\"forge: package not found\")\n\tErrReleaseExists     = errors.New(\"forge: release already exists\")\n\tErrReleaseNotFound   = errors.New(\"forge: release not found\")\n)\n"},{"name":"forge.gno","body":"// Package forge is the domain engine of an on-chain software forge: repos,\n// roles, an append-only reference log, issues and change requests (pull\n// requests), with no chain imports of its own.\n//\n// What it does NOT do, on purpose: store blobs, trees or packfiles. Git objects\n// stay wherever git already puts them (a mirror, an IPFS CID, a peer) and this\n// package records what a forge is actually trusted for and what git alone does\n// not authenticate:\n//\n//  1. which object id a ref points at, in what order it got there, and who said\n//     so: an append-only, hash-chained reference log (the same shape as\n//     gittuf's reference state log, with consensus playing the notary);\n//  2. who is allowed to move which ref, and under what review policy;\n//  3. the social layer: issues, change requests, reviews: bound to addresses\n//     rather than to platform accounts;\n//  4. the merge decision itself, recorded as one more entry in the same log.\n//\n// The chain cannot see the object graph, so it cannot verify that a new tip\n// descends from the old one. It does not pretend to: every ref move is a\n// compare-and-swap against the tip the caller expected (git's\n// --force-with-lease, moved somewhere the forge operator cannot rewrite), any\n// move that abandons that discipline is recorded as a force, and ancestry is\n// checked by a client that has the objects. Ordering, attribution and policy\n// are on chain; proof is local.\n//\n// All state lives in avl trees so every listing is ordered and paginatable, and\n// every mutation takes the actor and the block height from the caller: the\n// package is pure, deterministic and unit-testable without a chain.\n//\n// Live demo: gno.land/r/moul/forge/v0.\npackage forge\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Role is a repo-scoped capability level. Roles are totally ordered: every\n// check is \"at least this role\", so there is one comparison to audit.\ntype Role int\n\nconst (\n\tRoleNone       Role = iota // not a member\n\tRoleReader                 // explicit read (all repos are public in v0)\n\tRoleWriter                 // move non-protected refs, update own changes\n\tRoleMaintainer             // force-move refs, merge changes, triage issues\n\tRoleAdmin                  // manage members and repo settings\n\tRoleOwner                  // admin + transfer; at least one always exists\n)\n\n// String renders the role as the lowercase token used by the realm API.\nfunc (r Role) String() string {\n\tswitch r {\n\tcase RoleReader:\n\t\treturn \"reader\"\n\tcase RoleWriter:\n\t\treturn \"writer\"\n\tcase RoleMaintainer:\n\t\treturn \"maintainer\"\n\tcase RoleAdmin:\n\t\treturn \"admin\"\n\tcase RoleOwner:\n\t\treturn \"owner\"\n\tdefault:\n\t\treturn \"none\"\n\t}\n}\n\n// ParseRole is the inverse of Role.String.\nfunc ParseRole(s string) (Role, error) {\n\tswitch s {\n\tcase \"none\":\n\t\treturn RoleNone, nil\n\tcase \"reader\":\n\t\treturn RoleReader, nil\n\tcase \"writer\":\n\t\treturn RoleWriter, nil\n\tcase \"maintainer\":\n\t\treturn RoleMaintainer, nil\n\tcase \"admin\":\n\t\treturn RoleAdmin, nil\n\tcase \"owner\":\n\t\treturn RoleOwner, nil\n\t}\n\treturn RoleNone, ErrInvalidRole\n}\n\n// Forge is the top-level registry: repo id -\u003e repo.\ntype Forge struct {\n\trepos *avl.Tree // \"\u003cnamespace\u003e/\u003cname\u003e\" -\u003e *Repo\n\t// packages is the forge-wide index behind PackageRepo: a deployed package\n\t// path resolves to the repo claiming it without scanning every repo. It\n\t// lives here rather than only on the repo because the question an explorer\n\t// asks starts from the path and does not know the repo yet.\n\tpackages *avl.Tree // package path -\u003e *Package\n}\n\n// New returns an empty forge.\nfunc New() *Forge {\n\treturn \u0026Forge{repos: avl.NewTree(), packages: avl.NewTree()}\n}\n\n// Repo is one repository. Nothing here is the code: Mirrors says where the\n// objects can be fetched, Refs says what the objects are supposed to be.\ntype Repo struct {\n\tID          string // \"\u003cnamespace\u003e/\u003cname\u003e\", immutable\n\tDescription string\n\tDefaultRef  string // fully-qualified, e.g. \"refs/heads/main\"\n\tMirrors     []string\n\tParentID    string // fork lineage, \"\" for a root repo\n\tCreatedAt   int64  // block height\n\tArchived    bool\n\n\t// Merge policy.\n\tRequiredApprovals int  // approvals needed to merge a change\n\tAllowSelfApproval bool // may the change author's own approval count\n\n\tmembers *avl.Tree // address string -\u003e Role\n\trefs    *avl.Tree // ref name -\u003e *Ref\n\tlog     *avl.Tree // padded seq -\u003e *LogEntry (append-only)\n\tissues  *avl.Tree // padded id -\u003e *Issue\n\tchanges *avl.Tree // padded id -\u003e *Change\n\n\tpackages *avl.Tree // package path -\u003e *Package (this repo's half of the index)\n\treleases *avl.Tree // tag -\u003e *Release\n\t// releaseOrder is cut order, which is the only order the forge knows to be\n\t// true. Tags are not required to be semver, so sorting the release tree by\n\t// key would present v10 before v2 and call it newest.\n\treleaseOrder *avl.Tree // padded seq -\u003e tag\n\n\thead       string // digest of the last log entry (\"\" when the log is empty)\n\tnextSeq    int64\n\tnextIssue  int64\n\tnextChange int64\n}\n\n// CreateRepo registers a repo owned by actor.\nfunc (f *Forge) CreateRepo(actor address, height int64, id, description, defaultRef string) (*Repo, error) {\n\tif !ValidRepoID(id) {\n\t\treturn nil, ErrInvalidRepoID\n\t}\n\tif !ValidText(description, MaxDescLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif defaultRef == \"\" {\n\t\tdefaultRef = \"refs/heads/main\"\n\t}\n\tif !ValidRefName(defaultRef) {\n\t\treturn nil, ErrInvalidRefName\n\t}\n\tif f.repos.Has(id) {\n\t\treturn nil, ErrRepoExists\n\t}\n\tr := \u0026Repo{\n\t\tID:                id,\n\t\tDescription:       description,\n\t\tDefaultRef:        defaultRef,\n\t\tCreatedAt:         height,\n\t\tRequiredApprovals: 1,\n\t\tmembers:           avl.NewTree(),\n\t\trefs:              avl.NewTree(),\n\t\tlog:               avl.NewTree(),\n\t\tissues:            avl.NewTree(),\n\t\tchanges:           avl.NewTree(),\n\t\t// A fork routes through here too, and inherits neither: the parent\n\t\t// publishes those package paths and cut those releases, not the child.\n\t\tpackages:     avl.NewTree(),\n\t\treleases:     avl.NewTree(),\n\t\treleaseOrder: avl.NewTree(),\n\t}\n\tr.members.Set(actor.String(), RoleOwner)\n\tf.repos.Set(id, r)\n\treturn r, nil\n}\n\n// Fork registers newID as a fork of srcID and copies the parent's current refs\n// into the child's log, so the fork records exactly what it forked from. The\n// objects are not copied: they never were on chain: so the child inherits the\n// parent's mirrors as its initial fetch locators.\nfunc (f *Forge) Fork(actor address, height int64, srcID, newID string) (*Repo, error) {\n\tsrc := f.Repo(srcID)\n\tif src == nil {\n\t\treturn nil, ErrRepoNotFound\n\t}\n\tchild, err := f.CreateRepo(actor, height, newID, src.Description, src.DefaultRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tchild.ParentID = srcID\n\tchild.Mirrors = append([]string{}, src.Mirrors...)\n\tnote := \"fork of \" + srcID + \" at seq \" + strconv.FormatInt(src.nextSeq, 10)\n\tif len(note) \u003e MaxNoteLen {\n\t\tnote = \"fork of \" + srcID\n\t}\n\tn := 0\n\tsrc.refs.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tref := value.(*Ref)\n\t\tchild.appendLog(actor, height, ref.Name, \"\", ref.OID, KindCreate, 0, note)\n\t\tchild.refs.Set(ref.Name, \u0026Ref{Name: ref.Name, OID: ref.OID, UpdatedAt: height, UpdatedBy: actor})\n\t\tn++\n\t\treturn n \u003e= 32 // a fork records a snapshot, not an unbounded copy\n\t})\n\treturn child, nil\n}\n\n// Repo returns the repo, or nil.\nfunc (f *Forge) Repo(id string) *Repo {\n\tv := f.repos.Get(id)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Repo)\n}\n\n// HasRepo reports whether the id is taken.\nfunc (f *Forge) HasRepo(id string) bool { return f.repos.Has(id) }\n\n// Size is the number of repos.\nfunc (f *Forge) Size() int { return f.repos.Size() }\n\n// IterateRepos walks repos in id order, newest-last, and stops when cb returns\n// true. offset/count page the walk; count \u003c= 0 means \"to the end\".\nfunc (f *Forge) IterateRepos(offset, count int, cb func(*Repo) bool) {\n\tif count \u003c= 0 {\n\t\tcount = f.repos.Size()\n\t}\n\tf.repos.IterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn cb(value.(*Repo))\n\t})\n}\n\n// IterateNamespace walks the repos of one namespace in id order.\nfunc (f *Forge) IterateNamespace(ns string, cb func(*Repo) bool) {\n\tf.repos.Iterate(ns+\"/\", ns+\"0\", func(_ string, value any) bool { // '0' is '/'+1\n\t\treturn cb(value.(*Repo))\n\t})\n}\n\n// RoleOf returns the member's role, RoleNone when not a member.\nfunc (r *Repo) RoleOf(a address) Role {\n\tv := r.members.Get(a.String())\n\tif v == nil {\n\t\treturn RoleNone\n\t}\n\treturn v.(Role)\n}\n\n// Can reports whether a holds at least the given role.\nfunc (r *Repo) Can(a address, min Role) bool { return r.RoleOf(a) \u003e= min }\n\n// MemberCount is the number of members with an explicit role.\nfunc (r *Repo) MemberCount() int { return r.members.Size() }\n\n// IterateMembers walks members in address order.\nfunc (r *Repo) IterateMembers(cb func(addr string, role Role) bool) {\n\tr.members.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\treturn cb(key, value.(Role))\n\t})\n}\n\n// SetMember grants or revokes a role. Admins manage members; only an owner may\n// mint another owner, and the last owner cannot be demoted: a repo with no\n// owner is a repo nobody can ever unarchive.\nfunc (r *Repo) SetMember(actor address, target address, role Role) error {\n\tif role \u003c RoleNone || role \u003e RoleOwner {\n\t\treturn ErrInvalidRole\n\t}\n\tif !r.Can(actor, RoleAdmin) {\n\t\treturn ErrUnauthorized\n\t}\n\tif role == RoleOwner \u0026\u0026 !r.Can(actor, RoleOwner) {\n\t\treturn ErrUnauthorized\n\t}\n\tcur := r.RoleOf(target)\n\tif cur == RoleOwner \u0026\u0026 role != RoleOwner {\n\t\tif !r.Can(actor, RoleOwner) {\n\t\t\treturn ErrUnauthorized // an admin cannot demote an owner\n\t\t}\n\t\tif r.ownerCount() == 1 {\n\t\t\treturn ErrLastOwner\n\t\t}\n\t}\n\tif role == RoleNone {\n\t\tr.members.Remove(target.String())\n\t\treturn nil\n\t}\n\tr.members.Set(target.String(), role)\n\treturn nil\n}\n\nfunc (r *Repo) ownerCount() int {\n\tn := 0\n\tr.members.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\tif value.(Role) == RoleOwner {\n\t\t\tn++\n\t\t}\n\t\treturn false\n\t})\n\treturn n\n}\n\n// SetDescription updates the one-line description.\nfunc (r *Repo) SetDescription(actor address, description string) error {\n\tif !r.Can(actor, RoleAdmin) {\n\t\treturn ErrUnauthorized\n\t}\n\tif !ValidText(description, MaxDescLen) {\n\t\treturn ErrInvalidText\n\t}\n\tr.Description = description\n\treturn nil\n}\n\n// SetMirrors replaces the fetch locators. The first one is the canonical\n// remote; the rest are fallbacks. The chain records them, it never fetches.\nfunc (r *Repo) SetMirrors(actor address, mirrors []string) error {\n\tif !r.Can(actor, RoleMaintainer) {\n\t\treturn ErrUnauthorized\n\t}\n\tif len(mirrors) \u003e MaxMirrors {\n\t\treturn ErrTooMany\n\t}\n\tfor _, m := range mirrors {\n\t\tif !ValidMirror(m) {\n\t\t\treturn ErrInvalidMirror\n\t\t}\n\t}\n\tr.Mirrors = append([]string{}, mirrors...)\n\treturn nil\n}\n\n// SetDefaultRef points the repo at another default branch.\nfunc (r *Repo) SetDefaultRef(actor address, name string) error {\n\tif !r.Can(actor, RoleMaintainer) {\n\t\treturn ErrUnauthorized\n\t}\n\tif !ValidRefName(name) {\n\t\treturn ErrInvalidRefName\n\t}\n\tr.DefaultRef = name\n\treturn nil\n}\n\n// SetPolicy sets the merge policy: how many approvals a change needs, and\n// whether the author's own approval counts.\nfunc (r *Repo) SetPolicy(actor address, requiredApprovals int, allowSelfApproval bool) error {\n\tif !r.Can(actor, RoleAdmin) {\n\t\treturn ErrUnauthorized\n\t}\n\tif requiredApprovals \u003c 0 || requiredApprovals \u003e 16 {\n\t\treturn ErrTooMany\n\t}\n\tr.RequiredApprovals = requiredApprovals\n\tr.AllowSelfApproval = allowSelfApproval\n\treturn nil\n}\n\n// SetArchived freezes (or unfreezes) the repo. An archived repo takes no\n// mutation except unarchiving: the log stays readable forever.\nfunc (r *Repo) SetArchived(actor address, archived bool) error {\n\tif !r.Can(actor, RoleAdmin) {\n\t\treturn ErrUnauthorized\n\t}\n\tr.Archived = archived\n\treturn nil\n}\n\n// Counts for rendering.\nfunc (r *Repo) RefCount() int    { return r.refs.Size() }\nfunc (r *Repo) IssueCount() int  { return r.issues.Size() }\nfunc (r *Repo) ChangeCount() int { return r.changes.Size() }\n\n// seqKey zero-pads an id to a fixed width so avl keys sort numerically.\n// ufmt has no width flags in gno, so the padding is done by hand: \"%016d\"\n// silently returns the bare number and would sort 10 before 2.\nfunc seqKey(n int64) string {\n\ts := strconv.FormatInt(n, 10)\n\tif len(s) \u003e= 16 {\n\t\treturn s\n\t}\n\treturn strings.Repeat(\"0\", 16-len(s)) + s\n}\n"},{"name":"forge_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestCreateRepo(t *testing.T) {\n\tf := New()\n\n\tr, err := f.CreateRepo(alice, 42, \"moul/forge\", \"desc\", \"\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"refs/heads/main\", r.DefaultRef, \"default ref defaults\")\n\tuassert.Equal(t, int64(42), r.CreatedAt)\n\tuassert.Equal(t, \"owner\", r.RoleOf(alice).String())\n\tuassert.Equal(t, 1, f.Size())\n\n\t_, err = f.CreateRepo(bob, 43, \"moul/forge\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrRepoExists)\n\n\t_, err = f.CreateRepo(bob, 43, \"Moul/Forge\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidRepoID)\n\n\t_, err = f.CreateRepo(bob, 43, \"moul/other\", \"\", \"main\")\n\tuassert.ErrorIs(t, err, ErrInvalidRefName)\n\n\tuassert.True(t, f.Repo(\"moul/nope\") == nil, \"missing repo is nil\")\n\tuassert.True(t, f.HasRepo(\"moul/forge\"))\n}\n\nfunc TestMembership(t *testing.T) {\n\t_, r := newRepo(t)\n\n\tuassert.True(t, r.Can(bob, RoleWriter), \"maintainer covers writer\")\n\tuassert.False(t, r.Can(carol, RoleMaintainer))\n\tuassert.Equal(t, \"none\", r.RoleOf(eve).String())\n\tuassert.Equal(t, 4, r.MemberCount())\n\n\t// A writer cannot hand out roles.\n\tuassert.ErrorIs(t, r.SetMember(carol, eve, RoleWriter), ErrUnauthorized)\n\n\t// An admin can promote up to admin, but cannot mint an owner...\n\turequire.NoError(t, r.SetMember(alice, bob, RoleAdmin))\n\tuassert.ErrorIs(t, r.SetMember(bob, eve, RoleOwner), ErrUnauthorized)\n\t// ...nor demote one.\n\tuassert.ErrorIs(t, r.SetMember(bob, alice, RoleReader), ErrUnauthorized)\n\n\t// The last owner cannot demote themselves: a repo with no owner is a repo\n\t// nobody can ever administer again.\n\tuassert.ErrorIs(t, r.SetMember(alice, alice, RoleReader), ErrLastOwner)\n\turequire.NoError(t, r.SetMember(alice, bob, RoleOwner))\n\turequire.NoError(t, r.SetMember(alice, alice, RoleReader))\n\tuassert.Equal(t, \"reader\", r.RoleOf(alice).String())\n\n\t// Revoking removes the member outright.\n\turequire.NoError(t, r.SetMember(bob, dave, RoleNone))\n\tuassert.Equal(t, \"none\", r.RoleOf(dave).String())\n\tuassert.Equal(t, 3, r.MemberCount())\n\n\tuassert.ErrorIs(t, r.SetMember(bob, eve, Role(99)), ErrInvalidRole)\n}\n\nfunc TestRepoSettings(t *testing.T) {\n\t_, r := newRepo(t)\n\n\tuassert.ErrorIs(t, r.SetDescription(carol, \"nope\"), ErrUnauthorized)\n\turequire.NoError(t, r.SetDescription(alice, \"an on-chain forge for gno\"))\n\tuassert.Equal(t, \"an on-chain forge for gno\", r.Description)\n\n\tuassert.ErrorIs(t, r.SetMirrors(carol, []string{\"https://example.com/x.git\"}), ErrUnauthorized)\n\tuassert.ErrorIs(t, r.SetMirrors(bob, []string{\"nope\"}), ErrInvalidMirror)\n\turequire.NoError(t, r.SetMirrors(bob, []string{\"https://github.com/moul/gno-contracts.git\"}))\n\tuassert.Equal(t, 1, len(r.Mirrors))\n\n\tuassert.ErrorIs(t, r.SetPolicy(carol, 2, false), ErrUnauthorized)\n\tuassert.ErrorIs(t, r.SetPolicy(alice, 99, false), ErrTooMany)\n\turequire.NoError(t, r.SetPolicy(alice, 2, true))\n\tuassert.Equal(t, 2, r.RequiredApprovals)\n\tuassert.True(t, r.AllowSelfApproval)\n\n\turequire.NoError(t, r.SetDefaultRef(bob, \"refs/heads/trunk\"))\n\tuassert.Equal(t, \"refs/heads/trunk\", r.DefaultRef)\n\n\t// An archived repo takes no writes at all.\n\turequire.NoError(t, r.SetArchived(alice, true))\n\t_, err := r.SetRef(alice, 101, \"refs/heads/trunk\", \"\", oid(\"a\"), \"\")\n\tuassert.ErrorIs(t, err, ErrRepoArchived)\n\t_, err = r.OpenIssue(eve, 101, \"hello\", \"\", nil)\n\tuassert.ErrorIs(t, err, ErrRepoArchived)\n\turequire.NoError(t, r.SetArchived(alice, false))\n}\n\nfunc TestForkSnapshotsRefs(t *testing.T) {\n\tf, r := newRepo(t)\n\turequire.NoError(t, r.SetMirrors(alice, []string{\"https://github.com/moul/gno-contracts.git\"}))\n\t_, err := r.SetRef(alice, 101, \"refs/heads/main\", \"\", oid(\"a\"), \"initial\")\n\turequire.NoError(t, err)\n\t_, err = r.SetRef(alice, 102, \"refs/tags/v0.1.0\", \"\", oid(\"b\"), \"tag\")\n\turequire.NoError(t, err)\n\n\tchild, err := f.Fork(eve, 110, \"moul/forge\", \"eve/forge\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"moul/forge\", child.ParentID)\n\tuassert.Equal(t, \"owner\", child.RoleOf(eve).String(), \"the forker owns the fork\")\n\tuassert.Equal(t, 2, child.RefCount(), \"refs are snapshotted\")\n\tuassert.Equal(t, 2, child.LogSize(), \"and the snapshot is in the log\")\n\tuassert.Equal(t, oid(\"a\"), child.Ref(\"refs/heads/main\").OID)\n\tuassert.Equal(t, 1, len(child.Mirrors), \"the fork inherits where to fetch objects\")\n\n\tok, bad := child.VerifyLog()\n\tuassert.True(t, ok, \"fork log is a valid chain\")\n\tuassert.Equal(t, int64(-1), bad)\n\n\t_, err = f.Fork(eve, 111, \"moul/nope\", \"eve/nope\")\n\tuassert.ErrorIs(t, err, ErrRepoNotFound)\n\t_, err = f.Fork(eve, 111, \"moul/forge\", \"eve/forge\")\n\tuassert.ErrorIs(t, err, ErrRepoExists)\n}\n\nfunc TestIterateReposAndNamespace(t *testing.T) {\n\tf := New()\n\tfor _, id := range []string{\"alice/one\", \"alice/two\", \"bob/three\"} {\n\t\t_, err := f.CreateRepo(alice, 1, id, \"\", \"\")\n\t\turequire.NoError(t, err)\n\t}\n\n\tvar all []string\n\tf.IterateRepos(0, 0, func(r *Repo) bool {\n\t\tall = append(all, r.ID)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"alice/one,alice/two,bob/three\", join(all))\n\n\tvar ns []string\n\tf.IterateNamespace(\"alice\", func(r *Repo) bool {\n\t\tns = append(ns, r.ID)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"alice/one,alice/two\", join(ns))\n\n\tvar page []string\n\tf.IterateRepos(1, 1, func(r *Repo) bool {\n\t\tpage = append(page, r.ID)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"alice/two\", join(page))\n}\n\nfunc join(ss []string) string {\n\tout := \"\"\n\tfor i, s := range ss {\n\t\tif i \u003e 0 {\n\t\t\tout += \",\"\n\t\t}\n\t\tout += s\n\t}\n\treturn out\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/forge/v1\"\ngno = \"0.9\"\n"},{"name":"helpers_test.gno","body":"package forge\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// Deterministic, checksum-valid test addresses.\nvar (\n\talice = testutils.TestAddress(\"alice\") // owner\n\tbob   = testutils.TestAddress(\"bob\")   // maintainer\n\tcarol = testutils.TestAddress(\"carol\") // writer\n\tdave  = testutils.TestAddress(\"dave\")  // reader\n\teve   = testutils.TestAddress(\"eve\")   // stranger\n)\n\n// oid builds a well-formed 40-hex object id out of one hex digit.\nfunc oid(c string) string { return strings.Repeat(c, 40) }\n\n// newRepo returns a repo owned by alice with the standard cast: bob\n// maintainer, carol writer, dave reader, eve nothing.\nfunc newRepo(t *testing.T) (*Forge, *Repo) {\n\tt.Helper()\n\tf := New()\n\tr, err := f.CreateRepo(alice, 100, \"moul/forge\", \"an on-chain forge\", \"\")\n\turequire.NoError(t, err)\n\turequire.NoError(t, r.SetMember(alice, bob, RoleMaintainer))\n\turequire.NoError(t, r.SetMember(alice, carol, RoleWriter))\n\turequire.NoError(t, r.SetMember(alice, dave, RoleReader))\n\treturn f, r\n}\n"},{"name":"issue.gno","body":"package forge\n\nimport \"gno.land/p/nt/avl/v0\"\n\n// Issue is a discussion thread bound to a repo. Anyone with an address may open\n// one: the spam gate is not a moderator, it is that the author pays gas and\n// locks the storage deposit for every byte they write.\ntype Issue struct {\n\tID        int64\n\tTitle     string\n\tBody      string\n\tAuthor    address\n\tOpen      bool\n\tLabels    []string\n\tCreatedAt int64\n\tUpdatedAt int64\n\n\tcomments    *avl.Tree // padded id -\u003e *Comment\n\tnextComment int64\n}\n\n// Comment is one reply, on an issue or on a change request.\ntype Comment struct {\n\tID        int64\n\tAuthor    address\n\tBody      string\n\tCreatedAt int64\n}\n\n// OpenIssue files an issue. Permissionless by design.\nfunc (r *Repo) OpenIssue(actor address, height int64, title, body string, labels []string) (*Issue, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tif title == \"\" || !ValidLine(title, MaxTitleLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif !ValidText(body, MaxBodyLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif err := checkLabels(labels); err != nil {\n\t\treturn nil, err\n\t}\n\ti := \u0026Issue{\n\t\tID:        r.nextIssue,\n\t\tTitle:     title,\n\t\tBody:      body,\n\t\tAuthor:    actor,\n\t\tOpen:      true,\n\t\tLabels:    append([]string{}, labels...),\n\t\tCreatedAt: height,\n\t\tUpdatedAt: height,\n\t\tcomments:  avl.NewTree(),\n\t}\n\tr.issues.Set(seqKey(i.ID), i)\n\tr.nextIssue++\n\treturn i, nil\n}\n\n// CommentIssue appends a reply. Closed issues still take comments (closing is a\n// triage state, not a gag); an archived repo takes none.\nfunc (r *Repo) CommentIssue(actor address, height, id int64, body string) (*Comment, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\ti := r.Issue(id)\n\tif i == nil {\n\t\treturn nil, ErrIssueNotFound\n\t}\n\tif body == \"\" || !ValidText(body, MaxCommentLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tc := \u0026Comment{ID: i.nextComment, Author: actor, Body: body, CreatedAt: height}\n\ti.comments.Set(seqKey(c.ID), c)\n\ti.nextComment++\n\ti.UpdatedAt = height\n\treturn c, nil\n}\n\n// SetIssueOpen closes or reopens an issue. The author can always close their\n// own; maintainers can close anyone's.\nfunc (r *Repo) SetIssueOpen(actor address, height, id int64, open bool) error {\n\tif r.Archived {\n\t\treturn ErrRepoArchived\n\t}\n\ti := r.Issue(id)\n\tif i == nil {\n\t\treturn ErrIssueNotFound\n\t}\n\tif i.Author != actor \u0026\u0026 !r.Can(actor, RoleMaintainer) {\n\t\treturn ErrUnauthorized\n\t}\n\ti.Open = open\n\ti.UpdatedAt = height\n\treturn nil\n}\n\n// SetIssueLabels replaces an issue's labels. Triage is a maintainer action.\nfunc (r *Repo) SetIssueLabels(actor address, height, id int64, labels []string) error {\n\tif r.Archived {\n\t\treturn ErrRepoArchived\n\t}\n\ti := r.Issue(id)\n\tif i == nil {\n\t\treturn ErrIssueNotFound\n\t}\n\tif !r.Can(actor, RoleMaintainer) {\n\t\treturn ErrUnauthorized\n\t}\n\tif err := checkLabels(labels); err != nil {\n\t\treturn err\n\t}\n\ti.Labels = append([]string{}, labels...)\n\ti.UpdatedAt = height\n\treturn nil\n}\n\n// Issue returns an issue by id, or nil.\nfunc (r *Repo) Issue(id int64) *Issue {\n\tv := r.issues.Get(seqKey(id))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Issue)\n}\n\n// IterateIssues walks issues newest-first.\nfunc (r *Repo) IterateIssues(offset, count int, cb func(*Issue) bool) {\n\tif count \u003c= 0 {\n\t\tcount = r.issues.Size()\n\t}\n\tr.issues.ReverseIterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn cb(value.(*Issue))\n\t})\n}\n\n// OpenIssueCount counts issues still open.\nfunc (r *Repo) OpenIssueCount() int {\n\tn := 0\n\tr.issues.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\tif value.(*Issue).Open {\n\t\t\tn++\n\t\t}\n\t\treturn false\n\t})\n\treturn n\n}\n\n// CommentCount is the number of replies on the issue.\nfunc (i *Issue) CommentCount() int { return i.comments.Size() }\n\n// IterateComments walks replies oldest-first.\nfunc (i *Issue) IterateComments(offset, count int, cb func(*Comment) bool) {\n\tif count \u003c= 0 {\n\t\tcount = i.comments.Size()\n\t}\n\ti.comments.IterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn cb(value.(*Comment))\n\t})\n}\n\nfunc checkLabels(labels []string) error {\n\tif len(labels) \u003e MaxLabels {\n\t\treturn ErrTooMany\n\t}\n\tfor _, l := range labels {\n\t\tif !ValidLabel(l) {\n\t\t\treturn ErrInvalidText\n\t\t}\n\t}\n\treturn nil\n}\n"},{"name":"issue_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestIssueLifecycle(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t// Filing an issue needs no role: the gate is that the author pays for the\n\t// bytes they write.\n\ti, err := r.OpenIssue(eve, 200, \"Render eats the last newline\", \"Steps:\\n1. …\", []string{\"bug\"})\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(0), i.ID)\n\tuassert.True(t, i.Open)\n\tuassert.Equal(t, eve.String(), i.Author.String())\n\tuassert.Equal(t, 1, r.IssueCount())\n\tuassert.Equal(t, 1, r.OpenIssueCount())\n\n\tc, err := r.CommentIssue(bob, 201, 0, \"reproduced\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(0), c.ID)\n\tuassert.Equal(t, 1, i.CommentCount())\n\tuassert.Equal(t, int64(201), i.UpdatedAt)\n\n\t// The author may close their own; a stranger may not close someone else's.\n\tuassert.ErrorIs(t, r.SetIssueOpen(carol, 202, 0, false), ErrUnauthorized)\n\turequire.NoError(t, r.SetIssueOpen(eve, 202, 0, false))\n\tuassert.False(t, i.Open)\n\tuassert.Equal(t, 0, r.OpenIssueCount())\n\n\t// Closed is a triage state, not a gag.\n\t_, err = r.CommentIssue(eve, 203, 0, \"still happening on pearl\")\n\turequire.NoError(t, err)\n\n\t// Maintainers can reopen and label.\n\turequire.NoError(t, r.SetIssueOpen(bob, 204, 0, true))\n\tuassert.ErrorIs(t, r.SetIssueLabels(eve, 205, 0, []string{\"p1\"}), ErrUnauthorized)\n\turequire.NoError(t, r.SetIssueLabels(bob, 205, 0, []string{\"bug\", \"p1\"}))\n\tuassert.Equal(t, 2, len(i.Labels))\n}\n\nfunc TestIssueValidation(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t_, err := r.OpenIssue(eve, 200, \"\", \"body\", nil)\n\tuassert.ErrorIs(t, err, ErrInvalidText, \"a title is required\")\n\t_, err = r.OpenIssue(eve, 200, \"two\\nlines\", \"\", nil)\n\tuassert.ErrorIs(t, err, ErrInvalidText, \"a title is one line\")\n\t_, err = r.OpenIssue(eve, 200, \"ok\", \"\", []string{\"a,b\"})\n\tuassert.ErrorIs(t, err, ErrInvalidText, \"labels are comma-free\")\n\t_, err = r.OpenIssue(eve, 200, \"ok\", \"\", []string{\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\"})\n\tuassert.ErrorIs(t, err, ErrTooMany)\n\n\t_, err = r.CommentIssue(eve, 200, 7, \"no such issue\")\n\tuassert.ErrorIs(t, err, ErrIssueNotFound)\n\tuassert.ErrorIs(t, r.SetIssueOpen(bob, 200, 7, false), ErrIssueNotFound)\n\n\turequire.NoError(t, func() error { _, err := r.OpenIssue(eve, 200, \"ok\", \"\", nil); return err }())\n\t_, err = r.CommentIssue(eve, 201, 0, \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidText, \"an empty comment is not a comment\")\n}\n\nfunc TestIssueIterationIsNewestFirst(t *testing.T) {\n\t_, r := newRepo(t)\n\tfor _, title := range []string{\"first\", \"second\", \"third\"} {\n\t\t_, err := r.OpenIssue(eve, 200, title, \"\", nil)\n\t\turequire.NoError(t, err)\n\t}\n\n\tvar got []string\n\tr.IterateIssues(0, 0, func(i *Issue) bool {\n\t\tgot = append(got, i.Title)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"third,second,first\", join(got))\n\n\tvar page []string\n\tr.IterateIssues(1, 1, func(i *Issue) bool {\n\t\tpage = append(page, i.Title)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"second\", join(page))\n\n\ti := r.Issue(0)\n\turequire.NotEqual(t, nil, i)\n\tfor n := 0; n \u003c 3; n++ {\n\t\t_, err := r.CommentIssue(eve, 201, 0, \"ping\")\n\t\turequire.NoError(t, err)\n\t}\n\tvar bodies []string\n\ti.IterateComments(0, 2, func(c *Comment) bool {\n\t\tbodies = append(bodies, c.Body)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"ping,ping\", join(bodies))\n}\n"},{"name":"pkg.gno","body":"package forge\n\nimport \"strings\"\n\n// MaxPkgPathLen bounds a published package path. gno.land's own paths are far\n// shorter; the cap exists because every stored byte is a storage deposit\n// somebody pays.\nconst MaxPkgPathLen = 256\n\n// Package is the claim that a repo publishes a deployed package path.\n//\n// This is the join nothing else in the forge could express. A repo id is\n// \"\u003cnamespace\u003e/\u003cname\u003e\", exactly two parts, so `r/moul/home` can never be one:\n// there was no way to ask \"which repo publishes this package path\", which is\n// the first question a reader arriving from an explorer has.\n//\n// The claim is deliberately one-directional and unverified. A realm cannot ask\n// the chain who deployed a path, so the forge cannot check that the repo really\n// is the source of the package. What it can guarantee is that only someone with\n// write access to the repo said so, and that the namespace of the repo is\n// governed by r/sys/users. A reader weighs the claim the way they weigh a\n// go.mod: it says where the author says the source lives.\ntype Package struct {\n\tPath        string // \"gno.land/r/moul/home\", the deployed package path\n\tRepoID      string\n\tRef         string // the ref this was published from, \"\" if unstated\n\tOID         string // the object id, \"\" if unstated\n\tTag         string // the release tag, \"\" if not published as part of one\n\tPublishedAt int64  // block height\n\tPublishedBy address\n}\n\n// ValidPkgPath reports whether s is a plausible gno package path.\n//\n// Deliberately shallow: it checks shape, not existence, because a realm cannot\n// ask the chain whether a path is deployed and a check that only sometimes\n// works is worse than one that never claims to.\nfunc ValidPkgPath(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxPkgPathLen {\n\t\treturn false\n\t}\n\tif strings.Contains(s, \"..\") || strings.HasSuffix(s, \"/\") {\n\t\treturn false\n\t}\n\tparts := strings.Split(s, \"/\")\n\tif len(parts) \u003c 3 {\n\t\treturn false\n\t}\n\tfor _, p := range parts {\n\t\tif p == \"\" {\n\t\t\treturn false\n\t\t}\n\t\tfor i := 0; i \u003c len(p); i++ {\n\t\t\tc := p[i]\n\t\t\tok := (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') ||\n\t\t\t\t(c \u003e= '0' \u0026\u0026 c \u003c= '9') || c == '.' || c == '-' || c == '_'\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n// PublishPackage records that this repo publishes path, and indexes it\n// forge-wide so PackageRepo can answer without scanning every repo.\n//\n// Re-publishing the same path from the same repo overwrites the entry, which is\n// what a redeploy is. Publishing a path another repo already claims is refused:\n// silently moving it would let any repo owner capture another project's\n// package path in an explorer.\nfunc (f *Forge) PublishPackage(actor address, height int64, repoID, path, ref, oid, tag string) (*Package, error) {\n\tr := f.Repo(repoID)\n\tif r == nil {\n\t\treturn nil, ErrRepoNotFound\n\t}\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tif !r.Can(actor, RoleWriter) {\n\t\treturn nil, ErrUnauthorized\n\t}\n\tif !ValidPkgPath(path) {\n\t\treturn nil, ErrInvalidPkgPath\n\t}\n\tif ref != \"\" \u0026\u0026 !ValidRefName(ref) {\n\t\treturn nil, ErrInvalidRefName\n\t}\n\tif oid != \"\" \u0026\u0026 !ValidOID(oid) {\n\t\treturn nil, ErrInvalidOID\n\t}\n\tif tag != \"\" \u0026\u0026 !ValidText(tag, MaxTagLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif owner := f.packages.Get(path); owner != nil {\n\t\tif existing := owner.(*Package); existing.RepoID != repoID {\n\t\t\treturn nil, ErrPackageClaimed\n\t\t}\n\t}\n\n\tp := \u0026Package{\n\t\tPath:        path,\n\t\tRepoID:      repoID,\n\t\tRef:         ref,\n\t\tOID:         oid,\n\t\tTag:         tag,\n\t\tPublishedAt: height,\n\t\tPublishedBy: actor,\n\t}\n\tf.packages.Set(path, p)\n\tr.packages.Set(path, p)\n\treturn p, nil\n}\n\n// UnpublishPackage withdraws the claim. The package stays on chain; only the\n// repo's assertion about it goes away.\nfunc (f *Forge) UnpublishPackage(actor address, repoID, path string) error {\n\tr := f.Repo(repoID)\n\tif r == nil {\n\t\treturn ErrRepoNotFound\n\t}\n\tif !r.Can(actor, RoleWriter) {\n\t\treturn ErrUnauthorized\n\t}\n\tif _, removed := r.packages.Remove(path); !removed {\n\t\treturn ErrPackageNotFound\n\t}\n\tf.packages.Remove(path)\n\treturn nil\n}\n\n// PackageRepo is the lookup an explorer makes: given a deployed path, which\n// repo claims to publish it. Returns \"\" when nobody does.\nfunc (f *Forge) PackageRepo(path string) string {\n\tv := f.packages.Get(path)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(*Package).RepoID\n}\n\n// PackageAt returns the full claim for a path, or nil.\nfunc (f *Forge) PackageAt(path string) *Package {\n\tv := f.packages.Get(path)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Package)\n}\n\n// PackageCount is how many paths the whole forge claims.\nfunc (f *Forge) PackageCount() int { return f.packages.Size() }\n\n// IteratePackages walks every claimed path in the forge, in path order.\nfunc (f *Forge) IteratePackages(offset, count int, cb func(*Package) bool) {\n\tif count \u003c= 0 {\n\t\tcount = f.packages.Size()\n\t}\n\tf.packages.IterateByOffset(offset, count, func(_ string, v any) bool {\n\t\treturn cb(v.(*Package))\n\t})\n}\n\n// PackageCount is how many paths this repo claims.\nfunc (r *Repo) PackageCount() int { return r.packages.Size() }\n\n// IteratePackages walks the paths this repo claims, in path order.\nfunc (r *Repo) IteratePackages(offset, count int, cb func(*Package) bool) {\n\tif count \u003c= 0 {\n\t\tcount = r.packages.Size()\n\t}\n\tr.packages.IterateByOffset(offset, count, func(_ string, v any) bool {\n\t\treturn cb(v.(*Package))\n\t})\n}\n"},{"name":"pkg_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestValidPkgPath(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tpath string\n\t\twant bool\n\t}{\n\t\t{\"a realm\", \"gno.land/r/moul/home\", true},\n\t\t{\"a pure package\", \"gno.land/p/moul/forge/v1\", true},\n\t\t{\"deep\", \"gno.land/r/moul/x/daily/asciiart/v0\", true},\n\t\t{\"an address namespace\", \"gno.land/r/g1abc/thing\", true},\n\t\t{\"underscores and dashes\", \"gno.land/r/ns/a-b_c\", true},\n\t\t// Shape only. A realm cannot ask the chain whether a path is deployed,\n\t\t// so anything stricter would be a check that only sometimes works.\n\t\t{\"not deployed but well formed\", \"gno.land/r/nobody/nothing\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"two parts\", \"gno.land/r\", false},\n\t\t{\"a traversal\", \"gno.land/r/../etc\", false},\n\t\t{\"trailing slash\", \"gno.land/r/moul/home/\", false},\n\t\t{\"an empty element\", \"gno.land//r/moul\", false},\n\t\t{\"a space\", \"gno.land/r/moul/my home\", false},\n\t\t{\"a colon\", \"gno.land/r/moul/home:tab\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, ValidPkgPath(tc.path))\n\t\t})\n\t}\n}\n\nfunc TestPublishPackageIndexesForgeWide(t *testing.T) {\n\tf, r := newRepo(t)\n\n\tp, err := f.PublishPackage(carol, 200, r.ID, \"gno.land/r/moul/home\", \"refs/heads/main\", oid(\"a\"), \"\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"gno.land/r/moul/home\", p.Path)\n\tuassert.Equal(t, r.ID, p.RepoID)\n\tuassert.Equal(t, int64(200), p.PublishedAt)\n\n\t// The lookup an explorer makes: it starts from the path and does not know\n\t// the repo yet, which is the whole reason the index is forge-wide.\n\tuassert.Equal(t, r.ID, f.PackageRepo(\"gno.land/r/moul/home\"))\n\tuassert.Equal(t, \"\", f.PackageRepo(\"gno.land/r/someone/else\"))\n\tuassert.Equal(t, 1, f.PackageCount())\n\tuassert.Equal(t, 1, r.PackageCount())\n}\n\n// One repo publishes many paths: gno-contracts publishes 193.\nfunc TestPublishManyPackages(t *testing.T) {\n\tf, r := newRepo(t)\n\n\tpaths := []string{\n\t\t\"gno.land/r/moul/home\",\n\t\t\"gno.land/p/moul/forge/v1\",\n\t\t\"gno.land/r/moul/blog\",\n\t}\n\tfor _, path := range paths {\n\t\t_, err := f.PublishPackage(alice, 200, r.ID, path, \"\", \"\", \"\")\n\t\turequire.NoError(t, err)\n\t}\n\tuassert.Equal(t, 3, r.PackageCount())\n\n\tvar seen []string\n\tr.IteratePackages(0, 0, func(p *Package) bool {\n\t\tseen = append(seen, p.Path)\n\t\treturn false\n\t})\n\t// Path order, which is what the tree gives and what a file list wants.\n\turequire.Equal(t, 3, len(seen))\n\tuassert.Equal(t, \"gno.land/p/moul/forge/v1\", seen[0])\n\tuassert.Equal(t, \"gno.land/r/moul/blog\", seen[1])\n\tuassert.Equal(t, \"gno.land/r/moul/home\", seen[2])\n}\n\n// Re-publishing the same path from the same repo is a redeploy, and overwrites.\nfunc TestRepublishOverwrites(t *testing.T) {\n\tf, r := newRepo(t)\n\n\t_, err := f.PublishPackage(alice, 200, r.ID, \"gno.land/r/moul/home\", \"\", oid(\"a\"), \"v1.0.0\")\n\turequire.NoError(t, err)\n\t_, err = f.PublishPackage(alice, 300, r.ID, \"gno.land/r/moul/home\", \"\", oid(\"b\"), \"v1.1.0\")\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, 1, f.PackageCount())\n\tgot := f.PackageAt(\"gno.land/r/moul/home\")\n\turequire.True(t, got != nil)\n\tuassert.Equal(t, oid(\"b\"), got.OID)\n\tuassert.Equal(t, \"v1.1.0\", got.Tag)\n\tuassert.Equal(t, int64(300), got.PublishedAt)\n}\n\n// Silently moving a claimed path would let any repo owner capture another\n// project's package in every explorer that reads this index.\nfunc TestPublishRefusesAnotherReposPath(t *testing.T) {\n\tf, r := newRepo(t)\n\t_, err := f.PublishPackage(alice, 200, r.ID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\turequire.NoError(t, err)\n\n\tother, err := f.CreateRepo(eve, 210, \"eve/squat\", \"\", \"\")\n\turequire.NoError(t, err)\n\n\t_, err = f.PublishPackage(eve, 220, other.ID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrPackageClaimed)\n\tuassert.Equal(t, r.ID, f.PackageRepo(\"gno.land/r/moul/home\"))\n}\n\nfunc TestPublishAuthorityAndValidation(t *testing.T) {\n\tf, r := newRepo(t)\n\n\t// dave is a reader, eve is nothing: neither may publish.\n\t_, err := f.PublishPackage(dave, 200, r.ID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\t_, err = f.PublishPackage(eve, 200, r.ID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\n\t_, err = f.PublishPackage(alice, 200, \"nobody/nothing\", \"gno.land/r/x/y\", \"\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrRepoNotFound)\n\n\t_, err = f.PublishPackage(alice, 200, r.ID, \"not a path\", \"\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidPkgPath)\n\n\t_, err = f.PublishPackage(alice, 200, r.ID, \"gno.land/r/moul/home\", \"main\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidRefName)\n\n\t_, err = f.PublishPackage(alice, 200, r.ID, \"gno.land/r/moul/home\", \"\", \"nothex\", \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidOID)\n\n\turequire.NoError(t, r.SetArchived(alice, true))\n\t_, err = f.PublishPackage(alice, 200, r.ID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrRepoArchived)\n}\n\nfunc TestUnpublishClearsBothHalvesOfTheIndex(t *testing.T) {\n\tf, r := newRepo(t)\n\t_, err := f.PublishPackage(alice, 200, r.ID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\turequire.NoError(t, err)\n\n\tuassert.ErrorIs(t, f.UnpublishPackage(dave, r.ID, \"gno.land/r/moul/home\"), ErrUnauthorized)\n\tuassert.ErrorIs(t, f.UnpublishPackage(alice, r.ID, \"gno.land/r/nothing\"), ErrPackageNotFound)\n\n\turequire.NoError(t, f.UnpublishPackage(alice, r.ID, \"gno.land/r/moul/home\"))\n\tuassert.Equal(t, 0, f.PackageCount())\n\tuassert.Equal(t, 0, r.PackageCount())\n\tuassert.Equal(t, \"\", f.PackageRepo(\"gno.land/r/moul/home\"))\n}\n\n// A fork is not a publisher of its parent's paths.\nfunc TestForkInheritsNoPackages(t *testing.T) {\n\tf, r := newRepo(t)\n\t_, err := f.PublishPackage(alice, 200, r.ID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\turequire.NoError(t, err)\n\n\tchild, err := f.Fork(eve, 210, r.ID, \"eve/forge\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 0, child.PackageCount())\n\tuassert.Equal(t, r.ID, f.PackageRepo(\"gno.land/r/moul/home\"))\n}\n"},{"name":"ref.gno","body":"package forge\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Log entry kinds.\nconst (\n\tKindCreate = \"create\" // a ref that did not exist now points somewhere\n\tKindUpdate = \"update\" // compare-and-swap succeeded\n\tKindForce  = \"force\"  // the tip was replaced without a matching expectation\n\tKindDelete = \"delete\" // the ref is gone (the log is not)\n\tKindMerge  = \"merge\"  // an update performed by merging a change request\n)\n\n// Ref is the current state of one reference. The history of how it got here is\n// in the repo log, which nothing can rewrite.\ntype Ref struct {\n\tName      string\n\tOID       string\n\tUpdatedAt int64\n\tUpdatedBy address\n}\n\n// LogEntry is one link of the repo's reference log. The log is append-only and\n// hash-chained: Digest commits to every earlier entry, so publishing a single\n// digest (in a release note, a package manifest, a tweet) pins the entire\n// history of every ref up to that point.\ntype LogEntry struct {\n\tSeq      int64\n\tRef      string\n\tOldOID   string // \"\" when the ref did not exist\n\tNewOID   string // \"\" on delete\n\tActor    address\n\tHeight   int64\n\tKind     string\n\tChangeID int64 // the merged change, 0 otherwise\n\tNote     string\n\tDigest   string // hex sha256 over the previous digest and this entry\n}\n\n// EntryDigest computes the chain digest of e given the previous entry's digest.\n// It is exported so an off-chain verifier can recompute the chain byte for byte\n// from the values it read back; the field order below is the wire format and\n// must not change within a version.\nfunc EntryDigest(prev string, e *LogEntry) string {\n\tfields := []string{\n\t\tprev,\n\t\tstrconv.FormatInt(e.Seq, 10),\n\t\te.Ref,\n\t\te.OldOID,\n\t\te.NewOID,\n\t\te.Actor.String(),\n\t\tstrconv.FormatInt(e.Height, 10),\n\t\te.Kind,\n\t\tstrconv.FormatInt(e.ChangeID, 10),\n\t\te.Note,\n\t}\n\tsum := sha256.Sum256([]byte(strings.Join(fields, \"\\n\")))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// appendLog writes one entry and advances the chain head. Callers have already\n// authorized and validated; this never fails.\nfunc (r *Repo) appendLog(actor address, height int64, ref, oldOID, newOID, kind string, changeID int64, note string) *LogEntry {\n\te := \u0026LogEntry{\n\t\tSeq:      r.nextSeq,\n\t\tRef:      ref,\n\t\tOldOID:   oldOID,\n\t\tNewOID:   newOID,\n\t\tActor:    actor,\n\t\tHeight:   height,\n\t\tKind:     kind,\n\t\tChangeID: changeID,\n\t\tNote:     note,\n\t}\n\te.Digest = EntryDigest(r.head, e)\n\tr.log.Set(seqKey(e.Seq), e)\n\tr.head = e.Digest\n\tr.nextSeq++\n\treturn e\n}\n\n// SetRef moves a ref by compare-and-swap: expectedOID must be the tip the\n// caller last saw (\"\" to create a ref that does not exist yet). This is git's\n// --force-with-lease, except the lease is held by consensus rather than by the\n// server you are pushing to, so a concurrent push cannot be silently lost and a\n// rewritten history cannot be presented as if it had always been that way.\n//\n// The chain cannot check that newOID descends from expectedOID: it has no\n// objects. That check belongs to a client holding the repo, which is exactly\n// why every move is recorded rather than merely applied.\nfunc (r *Repo) SetRef(actor address, height int64, name, expectedOID, newOID, note string) (*LogEntry, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tif !r.Can(actor, RoleWriter) {\n\t\treturn nil, ErrUnauthorized\n\t}\n\tif !ValidRefName(name) {\n\t\treturn nil, ErrInvalidRefName\n\t}\n\tif !ValidOID(newOID) {\n\t\treturn nil, ErrInvalidOID\n\t}\n\tif !ValidLine(note, MaxNoteLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tcur := r.Ref(name)\n\tswitch {\n\tcase cur == nil \u0026\u0026 expectedOID != \"\":\n\t\treturn nil, ErrRefNotFound\n\tcase cur != nil \u0026\u0026 expectedOID == \"\":\n\t\treturn nil, ErrRefExists\n\tcase cur != nil \u0026\u0026 cur.OID != expectedOID:\n\t\treturn nil, ErrStaleRef\n\tcase cur != nil \u0026\u0026 cur.OID == newOID:\n\t\treturn nil, ErrSameOID\n\t}\n\tkind := KindUpdate\n\told := \"\"\n\tif cur == nil {\n\t\tkind = KindCreate\n\t} else {\n\t\told = cur.OID\n\t}\n\tr.refs.Set(name, \u0026Ref{Name: name, OID: newOID, UpdatedAt: height, UpdatedBy: actor})\n\treturn r.appendLog(actor, height, name, old, newOID, kind, 0, note), nil\n}\n\n// ForceSetRef moves a ref without an expectation. It needs RoleMaintainer and\n// is permanently recorded as KindForce: the point is not to forbid a force-push\n// (sometimes it is the right call) but to make one impossible to hide.\nfunc (r *Repo) ForceSetRef(actor address, height int64, name, newOID, note string) (*LogEntry, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tif !r.Can(actor, RoleMaintainer) {\n\t\treturn nil, ErrUnauthorized\n\t}\n\tif !ValidRefName(name) {\n\t\treturn nil, ErrInvalidRefName\n\t}\n\tif !ValidOID(newOID) {\n\t\treturn nil, ErrInvalidOID\n\t}\n\tif !ValidLine(note, MaxNoteLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\told := \"\"\n\tif cur := r.Ref(name); cur != nil {\n\t\tif cur.OID == newOID {\n\t\t\treturn nil, ErrSameOID\n\t\t}\n\t\told = cur.OID\n\t}\n\tr.refs.Set(name, \u0026Ref{Name: name, OID: newOID, UpdatedAt: height, UpdatedBy: actor})\n\treturn r.appendLog(actor, height, name, old, newOID, KindForce, 0, note), nil\n}\n\n// DeleteRef removes a ref by compare-and-swap. The ref disappears from the\n// current state; the log keeps every object it ever pointed at.\n//\n// Maintainer-only for an economic reason as much as a safety one: on gno.land\n// the storage-deposit refund goes to whoever frees the bytes, not to whoever\n// paid for them (`receiver := caller` in the vm keeper's deposit path, gno\n// master 2026-09-19), so an open delete path pays for vandalism.\nfunc (r *Repo) DeleteRef(actor address, height int64, name, expectedOID, note string) (*LogEntry, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tif !r.Can(actor, RoleMaintainer) {\n\t\treturn nil, ErrUnauthorized\n\t}\n\tif !ValidLine(note, MaxNoteLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tcur := r.Ref(name)\n\tif cur == nil {\n\t\treturn nil, ErrRefNotFound\n\t}\n\tif cur.OID != expectedOID {\n\t\treturn nil, ErrStaleRef\n\t}\n\tif name == r.DefaultRef {\n\t\treturn nil, ErrUnauthorized // the default branch is not deletable\n\t}\n\tr.refs.Remove(name)\n\treturn r.appendLog(actor, height, name, cur.OID, \"\", KindDelete, 0, note), nil\n}\n\n// Ref returns the current state of a ref, or nil.\nfunc (r *Repo) Ref(name string) *Ref {\n\tv := r.refs.Get(name)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Ref)\n}\n\n// IterateRefs walks refs in name order.\nfunc (r *Repo) IterateRefs(cb func(*Ref) bool) {\n\tr.refs.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\treturn cb(value.(*Ref))\n\t})\n}\n\n// LogHead is the digest of the last entry, \"\" for an empty log. Pin this value\n// anywhere off chain and the whole history becomes falsifiable.\nfunc (r *Repo) LogHead() string { return r.head }\n\n// LogSize is the number of entries ever appended.\nfunc (r *Repo) LogSize() int { return r.log.Size() }\n\n// LogEntryAt returns one entry by sequence number, or nil.\nfunc (r *Repo) LogEntryAt(seq int64) *LogEntry {\n\tv := r.log.Get(seqKey(seq))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*LogEntry)\n}\n\n// IterateLog walks the log oldest-first.\nfunc (r *Repo) IterateLog(offset, count int, cb func(*LogEntry) bool) {\n\tif count \u003c= 0 {\n\t\tcount = r.log.Size()\n\t}\n\tr.log.IterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn cb(value.(*LogEntry))\n\t})\n}\n\n// IterateLogReverse walks the log newest-first, which is what a UI wants.\nfunc (r *Repo) IterateLogReverse(offset, count int, cb func(*LogEntry) bool) {\n\tif count \u003c= 0 {\n\t\tcount = r.log.Size()\n\t}\n\tr.log.ReverseIterateByOffset(offset, count, func(_ string, value any) bool {\n\t\treturn cb(value.(*LogEntry))\n\t})\n}\n\n// VerifyLog recomputes the whole digest chain and reports the first entry whose\n// digest does not follow from its predecessor. It should be impossible on a\n// live chain: it is here because a transparency log nobody can verify is just\n// a log, and a client should be running this against the values it read back.\nfunc (r *Repo) VerifyLog() (bool, int64) {\n\tprev := \"\"\n\tbad := int64(-1)\n\tr.log.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\te := value.(*LogEntry)\n\t\tif EntryDigest(prev, e) != e.Digest {\n\t\t\tbad = e.Seq\n\t\t\treturn true\n\t\t}\n\t\tprev = e.Digest\n\t\treturn false\n\t})\n\treturn bad \u003c 0, bad\n}\n"},{"name":"ref_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestSetRefCompareAndSwap(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t// Create: the expectation is \"this ref does not exist\".\n\te, err := r.SetRef(carol, 101, \"refs/heads/main\", \"\", oid(\"a\"), \"initial import\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, KindCreate, e.Kind)\n\tuassert.Equal(t, int64(0), e.Seq)\n\tuassert.Equal(t, \"\", e.OldOID)\n\tuassert.Equal(t, oid(\"a\"), r.Ref(\"refs/heads/main\").OID)\n\tuassert.Equal(t, carol.String(), r.Ref(\"refs/heads/main\").UpdatedBy.String())\n\n\t// Creating twice is a mistake, not an overwrite.\n\t_, err = r.SetRef(carol, 102, \"refs/heads/main\", \"\", oid(\"b\"), \"\")\n\tuassert.ErrorIs(t, err, ErrRefExists)\n\n\t// A stale expectation is exactly the lost-push case --force-with-lease\n\t// exists to catch, and here the lease is held by consensus.\n\t_, err = r.SetRef(carol, 102, \"refs/heads/main\", oid(\"9\"), oid(\"b\"), \"\")\n\tuassert.ErrorIs(t, err, ErrStaleRef)\n\n\t// A fresh expectation succeeds and chains onto the previous entry.\n\te2, err := r.SetRef(carol, 103, \"refs/heads/main\", oid(\"a\"), oid(\"b\"), \"fix the thing\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, KindUpdate, e2.Kind)\n\tuassert.Equal(t, oid(\"a\"), e2.OldOID)\n\tuassert.Equal(t, EntryDigest(e.Digest, e2), e2.Digest, \"digest commits to its predecessor\")\n\tuassert.Equal(t, e2.Digest, r.LogHead())\n\n\t// No-op writes are rejected: they would cost a deposit and record nothing.\n\t_, err = r.SetRef(carol, 104, \"refs/heads/main\", oid(\"b\"), oid(\"b\"), \"\")\n\tuassert.ErrorIs(t, err, ErrSameOID)\n\n\t// Updating a ref that does not exist is not a create.\n\t_, err = r.SetRef(carol, 104, \"refs/heads/other\", oid(\"a\"), oid(\"b\"), \"\")\n\tuassert.ErrorIs(t, err, ErrRefNotFound)\n}\n\nfunc TestSetRefAuthorizationAndValidation(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t_, err := r.SetRef(eve, 101, \"refs/heads/main\", \"\", oid(\"a\"), \"\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized, \"a stranger cannot move a ref\")\n\t_, err = r.SetRef(dave, 101, \"refs/heads/main\", \"\", oid(\"a\"), \"\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized, \"a reader cannot move a ref\")\n\n\t_, err = r.SetRef(carol, 101, \"main\", \"\", oid(\"a\"), \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidRefName)\n\t_, err = r.SetRef(carol, 101, \"refs/heads/main\", \"\", \"deadbeef\", \"\")\n\tuassert.ErrorIs(t, err, ErrInvalidOID)\n\t_, err = r.SetRef(carol, 101, \"refs/heads/main\", \"\", oid(\"a\"), \"two\\nlines\")\n\tuassert.ErrorIs(t, err, ErrInvalidText, \"a note is one line: it is a digest field\")\n}\n\nfunc TestForceAndDelete(t *testing.T) {\n\t_, r := newRepo(t)\n\t_, err := r.SetRef(carol, 101, \"refs/heads/main\", \"\", oid(\"a\"), \"initial\")\n\turequire.NoError(t, err)\n\t_, err = r.SetRef(carol, 102, \"refs/heads/wip\", \"\", oid(\"c\"), \"wip\")\n\turequire.NoError(t, err)\n\n\t// A writer cannot force. A maintainer can, and it is on the record forever.\n\t_, err = r.ForceSetRef(carol, 103, \"refs/heads/main\", oid(\"d\"), \"rewrite\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\te, err := r.ForceSetRef(bob, 103, \"refs/heads/main\", oid(\"d\"), \"drop the bad commit\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, KindForce, e.Kind)\n\tuassert.Equal(t, oid(\"a\"), e.OldOID, \"the abandoned tip stays in the log\")\n\n\t// Delete is compare-and-swap too, and the default branch is not deletable.\n\t_, err = r.DeleteRef(bob, 104, \"refs/heads/main\", oid(\"d\"), \"\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\t_, err = r.DeleteRef(bob, 104, \"refs/heads/wip\", oid(\"9\"), \"\")\n\tuassert.ErrorIs(t, err, ErrStaleRef)\n\t_, err = r.DeleteRef(carol, 104, \"refs/heads/wip\", oid(\"c\"), \"\")\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\tde, err := r.DeleteRef(bob, 104, \"refs/heads/wip\", oid(\"c\"), \"merged\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, KindDelete, de.Kind)\n\tuassert.Equal(t, \"\", de.NewOID)\n\tuassert.Equal(t, 1, r.RefCount(), \"the ref is gone\")\n\tuassert.Equal(t, 4, r.LogSize(), \"the history of it is not\")\n\n\t_, err = r.DeleteRef(bob, 105, \"refs/heads/wip\", \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrRefNotFound)\n}\n\nfunc TestLogChainVerifies(t *testing.T) {\n\t_, r := newRepo(t)\n\turequire.Equal(t, \"\", r.LogHead())\n\n\tfor i, o := range []string{\"a\", \"b\", \"c\", \"d\"} {\n\t\texpected := \"\"\n\t\tif i \u003e 0 {\n\t\t\texpected = r.Ref(\"refs/heads/main\").OID\n\t\t}\n\t\t_, err := r.SetRef(carol, int64(100+i), \"refs/heads/main\", expected, oid(o), \"step\")\n\t\turequire.NoError(t, err)\n\t}\n\tuassert.Equal(t, 4, r.LogSize())\n\n\tok, bad := r.VerifyLog()\n\tuassert.True(t, ok, \"an untouched log verifies\")\n\tuassert.Equal(t, int64(-1), bad)\n\n\t// Rewrite history the only way it can be rewritten here: reaching into the\n\t// package's own memory, and the chain detects it at the doctored entry.\n\tr.LogEntryAt(1).NewOID = oid(\"f\")\n\tok, bad = r.VerifyLog()\n\tuassert.False(t, ok, \"a doctored entry breaks the chain\")\n\tuassert.Equal(t, int64(1), bad)\n}\n\nfunc TestLogIteration(t *testing.T) {\n\t_, r := newRepo(t)\n\tfor i, o := range []string{\"a\", \"b\", \"c\"} {\n\t\texpected := \"\"\n\t\tif i \u003e 0 {\n\t\t\texpected = r.Ref(\"refs/heads/main\").OID\n\t\t}\n\t\t_, err := r.SetRef(carol, int64(100+i), \"refs/heads/main\", expected, oid(o), \"\")\n\t\turequire.NoError(t, err)\n\t}\n\n\tvar fwd []string\n\tr.IterateLog(0, 0, func(e *LogEntry) bool {\n\t\tfwd = append(fwd, e.NewOID[:1])\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"a,b,c\", join(fwd))\n\n\tvar rev []string\n\tr.IterateLogReverse(0, 2, func(e *LogEntry) bool {\n\t\trev = append(rev, e.NewOID[:1])\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"c,b\", join(rev), \"newest-first, paginated\")\n\n\tvar names []string\n\tr.IterateRefs(func(ref *Ref) bool {\n\t\tnames = append(names, ref.Name)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"refs/heads/main\", join(names))\n\tuassert.True(t, r.LogEntryAt(99) == nil)\n}\n"},{"name":"release.gno","body":"package forge\n\nimport \"strings\"\n\n// Size caps for a release.\nconst (\n\tMaxTagLen     = 64\n\tMaxRelNameLen = 200\n\tMaxNotesLen   = 8192\n)\n\n// Release is a named point in a repo's history, with notes.\n//\n// A tag ref already says \"this name points at this object\". A release says why\n// anyone should care: what changed, whether it is ready, and which deployed\n// package paths came out of it. That last part is the one an explorer wants,\n// and it is also the only honest bridge between a git object id and an on-chain\n// deploy, because the chain cannot verify either against the other.\ntype Release struct {\n\tTag        string // \"v1.2.0\", the key; immutable once cut\n\tName       string // human title, may be empty\n\tNotes      string // markdown, may be empty\n\tOID        string // the object this release names\n\tRef        string // the tag ref, \"\" if the release does not have one\n\tPrerelease bool\n\tCreatedAt  int64 // block height\n\tCreatedBy  address\n\tYanked     bool // withdrawn; kept, because a version that existed cannot un-exist\n\tYankReason string\n}\n\n// ValidTag reports whether s is usable as a release tag.\n//\n// Not semver-enforcing: gno.land's own packages version as v0, v1 with no minor\n// or patch, and a forge that refused those would refuse its own ecosystem.\n// Ordering is therefore lexical over a padded form, not semantic, and\n// LatestRelease says so.\nfunc ValidTag(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxTagLen {\n\t\treturn false\n\t}\n\tif strings.Contains(s, \"..\") || strings.Contains(s, \"/\") {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tok := (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') ||\n\t\t\t(c \u003e= '0' \u0026\u0026 c \u003c= '9') || c == '.' || c == '-' || c == '_' || c == '+'\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// CutRelease records a release. The tag is the key and cannot be re-cut: a\n// consumer that pinned v1.2.0 and got different bytes later has been lied to,\n// and the whole point of a tag is that it does not move. Withdrawing one is\n// YankRelease, which leaves it visible.\nfunc (r *Repo) CutRelease(actor address, height int64, tag, name, notes, oid, ref string, prerelease bool) (*Release, error) {\n\tif r.Archived {\n\t\treturn nil, ErrRepoArchived\n\t}\n\tif !r.Can(actor, RoleWriter) {\n\t\treturn nil, ErrUnauthorized\n\t}\n\tif !ValidTag(tag) {\n\t\treturn nil, ErrInvalidTag\n\t}\n\tif !ValidText(name, MaxRelNameLen) || !ValidText(notes, MaxNotesLen) {\n\t\treturn nil, ErrInvalidText\n\t}\n\tif oid != \"\" \u0026\u0026 !ValidOID(oid) {\n\t\treturn nil, ErrInvalidOID\n\t}\n\tif ref != \"\" \u0026\u0026 !ValidRefName(ref) {\n\t\treturn nil, ErrInvalidRefName\n\t}\n\tif r.releases.Has(tag) {\n\t\treturn nil, ErrReleaseExists\n\t}\n\n\trel := \u0026Release{\n\t\tTag:        tag,\n\t\tName:       name,\n\t\tNotes:      notes,\n\t\tOID:        oid,\n\t\tRef:        ref,\n\t\tPrerelease: prerelease,\n\t\tCreatedAt:  height,\n\t\tCreatedBy:  actor,\n\t}\n\tr.releases.Set(tag, rel)\n\tr.releaseOrder.Set(seqKey(int64(r.releases.Size())), tag)\n\treturn rel, nil\n}\n\n// YankRelease marks a release withdrawn without deleting it.\n//\n// Deleting would make a pinned version silently vanish, which reads to a\n// consumer as \"this was never published\" rather than \"do not use this\".\nfunc (r *Repo) YankRelease(actor address, tag, reason string) error {\n\tif !r.Can(actor, RoleWriter) {\n\t\treturn ErrUnauthorized\n\t}\n\tif !ValidText(reason, MaxNoteLen) {\n\t\treturn ErrInvalidText\n\t}\n\tv := r.releases.Get(tag)\n\tif v == nil {\n\t\treturn ErrReleaseNotFound\n\t}\n\trel := v.(*Release)\n\trel.Yanked = true\n\trel.YankReason = reason\n\treturn nil\n}\n\n// Release returns one release by tag, or nil.\nfunc (r *Repo) Release(tag string) *Release {\n\tv := r.releases.Get(tag)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Release)\n}\n\n// ReleaseCount is how many releases this repo has cut, yanked ones included.\nfunc (r *Repo) ReleaseCount() int { return r.releases.Size() }\n\n// IterateReleases walks releases newest-cut first.\n//\n// Cut order, not tag order: tags are not required to be semver here (gno.land's\n// own packages are v0 and v1), so there is no total order to sort by that would\n// not be wrong for somebody. When they were cut is a fact the forge does know.\nfunc (r *Repo) IterateReleases(offset, count int, cb func(*Release) bool) {\n\tif count \u003c= 0 {\n\t\tcount = r.releaseOrder.Size()\n\t}\n\tr.releaseOrder.ReverseIterateByOffset(offset, count, func(_ string, v any) bool {\n\t\trel := r.releases.Get(v.(string))\n\t\tif rel == nil {\n\t\t\treturn false\n\t\t}\n\t\treturn cb(rel.(*Release))\n\t})\n}\n\n// LatestRelease is the most recently cut release that is neither a prerelease\n// nor yanked, or nil. \"Most recently cut\", never \"highest version\": see\n// IterateReleases.\nfunc (r *Repo) LatestRelease() *Release {\n\tvar out *Release\n\tr.IterateReleases(0, 0, func(rel *Release) bool {\n\t\tif rel.Prerelease || rel.Yanked {\n\t\t\treturn false\n\t\t}\n\t\tout = rel\n\t\treturn true\n\t})\n\treturn out\n}\n"},{"name":"release_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestValidTag(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\ttag  string\n\t\twant bool\n\t}{\n\t\t{\"semver\", \"v1.2.0\", true},\n\t\t// gno.land's own packages are v0 and v1 with no minor or patch. A tag\n\t\t// rule that refused those would refuse the ecosystem it serves.\n\t\t{\"a gno version\", \"v0\", true},\n\t\t{\"a prerelease\", \"v1.0.0-rc.1\", true},\n\t\t{\"build metadata\", \"v1.0.0+build.5\", true},\n\t\t{\"not version shaped at all\", \"genesis-snapshot\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"a slash\", \"release/v1\", false},\n\t\t{\"a traversal\", \"v1..0\", false},\n\t\t{\"a space\", \"v1 0\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, ValidTag(tc.tag))\n\t\t})\n\t}\n}\n\nfunc TestCutRelease(t *testing.T) {\n\t_, r := newRepo(t)\n\n\trel, err := r.CutRelease(carol, 300, \"v1.0.0\", \"First\", \"it works\", oid(\"a\"), \"refs/tags/v1.0.0\", false)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"v1.0.0\", rel.Tag)\n\tuassert.Equal(t, \"First\", rel.Name)\n\tuassert.Equal(t, int64(300), rel.CreatedAt)\n\tuassert.False(t, rel.Prerelease)\n\tuassert.Equal(t, 1, r.ReleaseCount())\n\n\tgot := r.Release(\"v1.0.0\")\n\turequire.True(t, got != nil)\n\tuassert.Equal(t, \"it works\", got.Notes)\n\tuassert.True(t, r.Release(\"v9.9.9\") == nil)\n}\n\n// A consumer who pinned v1.2.0 and later got different bytes has been lied to.\n// The whole point of a tag is that it does not move.\nfunc TestCutReleaseIsImmutable(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t_, err := r.CutRelease(alice, 300, \"v1.0.0\", \"First\", \"\", oid(\"a\"), \"\", false)\n\turequire.NoError(t, err)\n\t_, err = r.CutRelease(alice, 400, \"v1.0.0\", \"Second\", \"\", oid(\"b\"), \"\", false)\n\tuassert.ErrorIs(t, err, ErrReleaseExists)\n\tuassert.Equal(t, oid(\"a\"), r.Release(\"v1.0.0\").OID)\n}\n\n// Cut order, never tag order: a lexical sort presents v10 before v2 and calls\n// it newest, and there is no semver to sort by because the tags are not\n// required to be semver.\nfunc TestIterateReleasesIsCutOrderNotTagOrder(t *testing.T) {\n\t_, r := newRepo(t)\n\n\tfor i, tag := range []string{\"v2.0.0\", \"v10.0.0\", \"v3.0.0\"} {\n\t\t_, err := r.CutRelease(alice, int64(300+i), tag, \"\", \"\", \"\", \"\", false)\n\t\turequire.NoError(t, err)\n\t}\n\n\tvar seen []string\n\tr.IterateReleases(0, 0, func(rel *Release) bool {\n\t\tseen = append(seen, rel.Tag)\n\t\treturn false\n\t})\n\turequire.Equal(t, 3, len(seen))\n\tuassert.Equal(t, \"v3.0.0\", seen[0])\n\tuassert.Equal(t, \"v10.0.0\", seen[1])\n\tuassert.Equal(t, \"v2.0.0\", seen[2])\n}\n\nfunc TestLatestReleaseSkipsPrereleaseAndYanked(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t_, err := r.CutRelease(alice, 300, \"v1.0.0\", \"\", \"\", \"\", \"\", false)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"v1.0.0\", r.LatestRelease().Tag)\n\n\t// A prerelease is cut later and is still not the latest.\n\t_, err = r.CutRelease(alice, 310, \"v2.0.0-rc.1\", \"\", \"\", \"\", \"\", true)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"v1.0.0\", r.LatestRelease().Tag)\n\n\t_, err = r.CutRelease(alice, 320, \"v2.0.0\", \"\", \"\", \"\", \"\", false)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"v2.0.0\", r.LatestRelease().Tag)\n\n\t// Yanking moves it back, and does not delete it.\n\turequire.NoError(t, r.YankRelease(alice, \"v2.0.0\", \"broken migration\"))\n\tuassert.Equal(t, \"v1.0.0\", r.LatestRelease().Tag)\n\tuassert.Equal(t, 3, r.ReleaseCount())\n\tyanked := r.Release(\"v2.0.0\")\n\turequire.True(t, yanked != nil)\n\tuassert.True(t, yanked.Yanked)\n\tuassert.Equal(t, \"broken migration\", yanked.YankReason)\n}\n\nfunc TestLatestReleaseIsNilWhenThereIsNone(t *testing.T) {\n\t_, r := newRepo(t)\n\tuassert.True(t, r.LatestRelease() == nil)\n\n\t_, err := r.CutRelease(alice, 300, \"v1.0.0-rc.1\", \"\", \"\", \"\", \"\", true)\n\turequire.NoError(t, err)\n\tuassert.True(t, r.LatestRelease() == nil)\n}\n\nfunc TestReleaseAuthorityAndValidation(t *testing.T) {\n\t_, r := newRepo(t)\n\n\t_, err := r.CutRelease(dave, 300, \"v1.0.0\", \"\", \"\", \"\", \"\", false)\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\t_, err = r.CutRelease(eve, 300, \"v1.0.0\", \"\", \"\", \"\", \"\", false)\n\tuassert.ErrorIs(t, err, ErrUnauthorized)\n\n\t_, err = r.CutRelease(alice, 300, \"release/v1\", \"\", \"\", \"\", \"\", false)\n\tuassert.ErrorIs(t, err, ErrInvalidTag)\n\n\t_, err = r.CutRelease(alice, 300, \"v1.0.0\", \"\", \"\", \"nothex\", \"\", false)\n\tuassert.ErrorIs(t, err, ErrInvalidOID)\n\n\t_, err = r.CutRelease(alice, 300, \"v1.0.0\", \"\", \"\", \"\", \"v1.0.0\", false)\n\tuassert.ErrorIs(t, err, ErrInvalidRefName)\n\n\tuassert.ErrorIs(t, r.YankRelease(dave, \"v1.0.0\", \"\"), ErrUnauthorized)\n\tuassert.ErrorIs(t, r.YankRelease(alice, \"v9.9.9\", \"\"), ErrReleaseNotFound)\n\n\turequire.NoError(t, r.SetArchived(alice, true))\n\t_, err = r.CutRelease(alice, 300, \"v1.0.0\", \"\", \"\", \"\", \"\", false)\n\tuassert.ErrorIs(t, err, ErrRepoArchived)\n}\n\nfunc TestForkInheritsNoReleases(t *testing.T) {\n\tf, r := newRepo(t)\n\t_, err := r.CutRelease(alice, 300, \"v1.0.0\", \"\", \"\", \"\", \"\", false)\n\turequire.NoError(t, err)\n\n\tchild, err := f.Fork(eve, 310, r.ID, \"eve/forge\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 0, child.ReleaseCount())\n\tuassert.True(t, child.LatestRelease() == nil)\n}\n"},{"name":"validate.gno","body":"package forge\n\nimport \"strings\"\n\n// Size caps. Every string the chain stores is bounded: an unbounded field is an\n// unbounded storage deposit, and on gno.land the deposit is paid per byte by\n// whoever writes it (100ugnot/byte at the time of writing).\nconst (\n\tMaxRepoPartLen = 39   // per side of \"\u003cnamespace\u003e/\u003cname\u003e\"\n\tMaxRefNameLen  = 255  // git's own limit for a single ref name\n\tMaxTitleLen    = 200  // issue / change title\n\tMaxBodyLen     = 8192 // issue / change body\n\tMaxCommentLen  = 4096\n\tMaxDescLen     = 512\n\tMaxNoteLen     = 140 // single-line note attached to a log entry\n\tMaxMirrorLen   = 512\n\tMaxMirrors     = 8\n\tMaxLabels      = 10\n\tMaxLabelLen    = 32\n)\n\n// ValidOID reports whether s is a git object id: 40 (SHA-1) or 64 (SHA-256)\n// lowercase hex characters. Case is fixed so the same object always has the\n// same on-chain key and the same digest-chain input.\nfunc ValidOID(s string) bool {\n\tif len(s) != 40 \u0026\u0026 len(s) != 64 {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif (c \u003c '0' || c \u003e '9') \u0026\u0026 (c \u003c 'a' || c \u003e 'f') {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidRefName reports whether s is a fully-qualified ref name this forge\n// accepts: a \"refs/\"-rooted subset of git-check-ref-format(1).\n//\n// Deliberately stricter than git: the name must be fully qualified, so there is\n// never an ambiguity between \"main\" the branch and \"main\" the tag, and a client\n// can map an on-chain name onto a local ref without a lookup table.\nfunc ValidRefName(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxRefNameLen {\n\t\treturn false\n\t}\n\tif !strings.HasPrefix(s, \"refs/\") {\n\t\treturn false\n\t}\n\tif strings.Contains(s, \"..\") || strings.Contains(s, \"@{\") {\n\t\treturn false\n\t}\n\tif strings.HasSuffix(s, \"/\") || strings.HasSuffix(s, \".\") {\n\t\treturn false\n\t}\n\tparts := strings.Split(s, \"/\")\n\tif len(parts) \u003c 2 {\n\t\treturn false\n\t}\n\tfor _, p := range parts {\n\t\tif p == \"\" || p == \"@\" {\n\t\t\treturn false\n\t\t}\n\t\tif strings.HasPrefix(p, \".\") || strings.HasSuffix(p, \".lock\") {\n\t\t\treturn false\n\t\t}\n\t\tfor i := 0; i \u003c len(p); i++ {\n\t\t\tif !refByteOK(p[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n// refByteOK rejects the bytes git itself rejects in a ref component: ASCII\n// control characters, space, DEL, and the pathspec/revision metacharacters.\nfunc refByteOK(c byte) bool {\n\tif c \u003c= 0x20 || c == 0x7f {\n\t\treturn false\n\t}\n\tswitch c {\n\tcase '~', '^', ':', '?', '*', '[', '\\\\':\n\t\treturn false\n\t}\n\treturn true\n}\n\n// ValidRepoID reports whether s is \"\u003cnamespace\u003e/\u003cname\u003e\". The name is always a\n// lowercase slug; the namespace is either a slug (a claimed user name) or a\n// bech32 address (the caller's own). The two shapes cannot collide: an address\n// is 40 characters and a slug caps at MaxRepoPartLen, which is 39.\n//\n// This layer validates the SHAPE only. Whether the caller may claim a given\n// namespace is an ownership question that needs a chain, so it belongs to the\n// realm (see the realm's README).\nfunc ValidRepoID(s string) bool {\n\tns, name, ok := SplitRepoID(s)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn (validSlug(ns) || AddressNamespace(ns)) \u0026\u0026 validSlug(name)\n}\n\n// SplitRepoID splits \"\u003cnamespace\u003e/\u003cname\u003e\" into its two halves. It does not\n// validate either half; ok is false only when the id is not two slash-separated\n// non-empty parts.\nfunc SplitRepoID(s string) (ns, name string, ok bool) {\n\ti := strings.Index(s, \"/\")\n\tif i \u003c= 0 || i == len(s)-1 || strings.Count(s, \"/\") != 1 {\n\t\treturn \"\", \"\", false\n\t}\n\treturn s[:i], s[i+1:], true\n}\n\n// AddressNamespace reports whether ns is shaped like a gno bech32 address, the\n// namespace every account owns without registering anything. The realm still\n// checks that it is the CALLER's address; this only says which of the two\n// ownership rules applies.\nfunc AddressNamespace(ns string) bool {\n\tif len(ns) != 40 || !strings.HasPrefix(ns, \"g1\") {\n\t\treturn false\n\t}\n\tfor i := 2; i \u003c len(ns); i++ {\n\t\tif !strings.ContainsRune(bech32Charset, rune(ns[i])) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// bech32Charset is bech32's data alphabet: lowercase alphanumerics minus the\n// four characters it drops to avoid transcription errors (1, b, i, o).\nconst bech32Charset = \"023456789acdefghjklmnpqrstuvwxyz\"\n\n// validSlug: 1..MaxRepoPartLen chars, [a-z0-9] at both ends, [a-z0-9-_.] inside,\n// no \"..\", no \"--\". Mixed case is rejected rather than folded: two ids that\n// differ only in case would be two avl keys and one human-visible name.\nfunc validSlug(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxRepoPartLen {\n\t\treturn false\n\t}\n\tif !alnum(s[0]) || !alnum(s[len(s)-1]) {\n\t\treturn false\n\t}\n\tif strings.Contains(s, \"..\") || strings.Contains(s, \"--\") {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif alnum(c) || c == '-' || c == '_' || c == '.' {\n\t\t\tcontinue\n\t\t}\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc alnum(c byte) bool {\n\treturn (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9')\n}\n\n// ValidText reports whether s fits in max bytes and carries no control\n// characters other than newline and tab. Render output is markdown served by\n// gnoweb, so a stray control byte is a rendering bug for every reader forever.\nfunc ValidText(s string, max int) bool {\n\tif len(s) \u003e max {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == '\\n' || c == '\\t' {\n\t\t\tcontinue\n\t\t}\n\t\tif c \u003c 0x20 || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidLine reports whether s is single-line text within max bytes. Used for\n// titles and for log-entry notes, which are fields of the digest chain: a\n// newline there would let one note impersonate two.\nfunc ValidLine(s string, max int) bool {\n\tif strings.ContainsAny(s, \"\\n\\t\") {\n\t\treturn false\n\t}\n\treturn ValidText(s, max)\n}\n\n// ValidMirror reports whether s looks like a fetch locator. The chain does not\n// resolve it: it only records where the maintainers say the objects are: so\n// the check is a shape check, not a promise that anything is reachable.\nfunc ValidMirror(s string) bool {\n\tif !ValidLine(s, MaxMirrorLen) || s == \"\" {\n\t\treturn false\n\t}\n\tfor _, p := range []string{\"https://\", \"http://\", \"git://\", \"ssh://\", \"ipfs://\", \"ipns://\", \"ar://\", \"rad://\", \"git@\"} {\n\t\tif strings.HasPrefix(s, p) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// ValidLabel reports whether s is an issue label.\nfunc ValidLabel(s string) bool {\n\treturn s != \"\" \u0026\u0026 ValidLine(s, MaxLabelLen) \u0026\u0026 !strings.Contains(s, \",\")\n}\n"},{"name":"validate_test.gno","body":"package forge\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestValidOID(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"sha1\", strings.Repeat(\"a\", 40), true},\n\t\t{\"sha256\", strings.Repeat(\"0\", 64), true},\n\t\t{\"mixed hex\", \"0123456789abcdef0123456789abcdef01234567\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"too short\", strings.Repeat(\"a\", 39), false},\n\t\t{\"between lengths\", strings.Repeat(\"a\", 41), false},\n\t\t{\"uppercase\", strings.Repeat(\"A\", 40), false},\n\t\t{\"non hex\", strings.Repeat(\"z\", 40), false},\n\t\t{\"abbreviated\", \"deadbeef\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidOID(tc.in), tc.name)\n\t}\n}\n\nfunc TestValidRefName(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"branch\", \"refs/heads/main\", true},\n\t\t{\"nested branch\", \"refs/heads/feat/on-chain-log\", true},\n\t\t{\"tag\", \"refs/tags/v1.0.0\", true},\n\t\t{\"stash-like\", \"refs/stash\", true},\n\t\t{\"unqualified\", \"main\", false},\n\t\t{\"empty\", \"\", false},\n\t\t{\"double slash\", \"refs/heads//main\", false},\n\t\t{\"double dot\", \"refs/heads/a..b\", false},\n\t\t{\"at brace\", \"refs/heads/a@{0}\", false},\n\t\t{\"trailing slash\", \"refs/heads/\", false},\n\t\t{\"trailing dot\", \"refs/heads/main.\", false},\n\t\t{\"dot prefix\", \"refs/heads/.hidden\", false},\n\t\t{\"lock suffix\", \"refs/heads/main.lock\", false},\n\t\t{\"space\", \"refs/heads/my branch\", false},\n\t\t{\"caret\", \"refs/heads/main^\", false},\n\t\t{\"colon\", \"refs/heads/a:b\", false},\n\t\t{\"tilde\", \"refs/heads/main~1\", false},\n\t\t{\"question\", \"refs/heads/what?\", false},\n\t\t{\"star\", \"refs/heads/*\", false},\n\t\t{\"backslash\", \"refs/heads/a\\\\b\", false},\n\t\t{\"control\", \"refs/heads/a\\x01b\", false},\n\t\t{\"too long\", \"refs/heads/\" + strings.Repeat(\"a\", 300), false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidRefName(tc.in), tc.name)\n\t}\n}\n\nfunc TestValidRepoID(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"simple\", \"moul/forge\", true},\n\t\t{\"digits\", \"ns0/repo9\", true},\n\t\t{\"dots and dashes\", \"moul/gno-contracts.x\", true},\n\t\t{\"underscore\", \"moul/my_repo\", true},\n\t\t{\"no slash\", \"forge\", false},\n\t\t{\"two slashes\", \"a/b/c\", false},\n\t\t{\"empty ns\", \"/forge\", false},\n\t\t{\"empty name\", \"moul/\", false},\n\t\t{\"uppercase\", \"Moul/forge\", false},\n\t\t{\"leading dash\", \"moul/-forge\", false},\n\t\t{\"trailing dot\", \"moul/forge.\", false},\n\t\t{\"double dot\", \"moul/fo..rge\", false},\n\t\t{\"double dash\", \"moul/fo--rge\", false},\n\t\t{\"space\", \"moul/my forge\", false},\n\t\t{\"too long\", \"moul/\" + strings.Repeat(\"a\", 40), false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidRepoID(tc.in), tc.name)\n\t}\n}\n\nfunc TestAddressNamespace(t *testing.T) {\n\taddr := testutils.TestAddress(\"alice\").String()\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"a real address\", addr, true},\n\t\t{\"wrong prefix\", \"x1\" + addr[2:], false},\n\t\t{\"too short\", addr[:39], false},\n\t\t{\"too long\", addr + \"a\", false},\n\t\t{\"bech32 drops b i o 1\", \"g1\" + strings.Repeat(\"b\", 38), false},\n\t\t{\"uppercase\", \"G1\" + addr[2:], false},\n\t\t{\"a slug is not an address\", \"moul\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, AddressNamespace(tc.in), tc.name)\n\t}\n\n\t// An address namespace is a valid repo id, and it cannot collide with a\n\t// claimed name: 40 characters is past the slug cap.\n\tuassert.True(t, ValidRepoID(addr+\"/forge\"))\n\tuassert.False(t, ValidRepoID(strings.Repeat(\"a\", 40)+\"/forge\"))\n\tuassert.False(t, ValidRepoID(addr+\"/\"+addr), \"the name half is always a slug\")\n}\n\nfunc TestSplitRepoID(t *testing.T) {\n\tns, name, ok := SplitRepoID(\"moul/forge\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"moul\", ns)\n\tuassert.Equal(t, \"forge\", name)\n\n\tfor _, bad := range []string{\"\", \"moul\", \"/forge\", \"moul/\", \"a/b/c\"} {\n\t\t_, _, ok := SplitRepoID(bad)\n\t\tuassert.False(t, ok, bad)\n\t}\n}\n\nfunc TestValidTextAndLine(t *testing.T) {\n\tuassert.True(t, ValidText(\"hello\\nworld\\ttab\", 64))\n\tuassert.False(t, ValidText(\"bell\\x07\", 64))\n\tuassert.False(t, ValidText(\"too long\", 3))\n\tuassert.True(t, ValidText(\"\", 3))\n\n\tuassert.True(t, ValidLine(\"a single line\", 64))\n\tuassert.False(t, ValidLine(\"two\\nlines\", 64))\n\tuassert.False(t, ValidLine(\"a\\ttab\", 64))\n}\n\nfunc TestValidMirrorAndLabel(t *testing.T) {\n\tcases := []struct {\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"https://github.com/moul/gno-contracts.git\", true},\n\t\t{\"git@github.com:moul/gno-contracts.git\", true},\n\t\t{\"ipfs://bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku\", true},\n\t\t{\"rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5\", true},\n\t\t{\"ar://1QKPaf1AmsK_tSSdUgtVDEYGLuQBOKTNr\", true},\n\t\t{\"ftp://example.com/repo.git\", false},\n\t\t{\"not a url\", false},\n\t\t{\"\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidMirror(tc.in), tc.in)\n\t}\n\n\tuassert.True(t, ValidLabel(\"bug\"))\n\tuassert.False(t, ValidLabel(\"\"))\n\tuassert.False(t, ValidLabel(\"a,b\"))\n\tuassert.False(t, ValidLabel(strings.Repeat(\"x\", 33)))\n}\n\nfunc TestParseRoleRoundTrip(t *testing.T) {\n\tfor _, r := range []Role{RoleNone, RoleReader, RoleWriter, RoleMaintainer, RoleAdmin, RoleOwner} {\n\t\tgot, err := ParseRole(r.String())\n\t\tuassert.NoError(t, err, r.String())\n\t\tuassert.Equal(t, int(r), int(got), r.String())\n\t}\n\t_, err := ParseRole(\"root\")\n\tuassert.ErrorIs(t, err, ErrInvalidRole)\n}\n"}]},"send":"","max_deposit":"41000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"fp","path":"gno.land/p/moul/fp/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/fp`\n\nFunctional helpers over `[]any`: the map / filter / reduce set, plus the\ngrouping and zipping pieces that usually get rewritten inline.\n\n```go\nnumbers := []any{1, 2, 3, 4, 5, 6}\n\nisEven := func(v any) bool { return v.(int)%2 == 0 }\ndouble := func(v any) any  { return v.(int) * 2 }\nsum    := func(a, b any) any { return a.(int) + b.(int) }\n\nevens  := fp.Filter(numbers, isEven)   // [2 4 6]\nbigger := fp.Map(evens, double)        // [4 8 12]\ntotal  := fp.Reduce(bigger, sum, 0)    // 24\n```\n\n## The set\n\n| | |\n| --- | --- |\n| transform | `Map`, `FlatMap`, `Filter`, `Reduce` |\n| test | `All`, `Any`, `None`, `Find` |\n| reshape | `Chunk`, `Reverse`, `Flatten`, `Zip`, `Unzip`, `GroupBy` |\n\nThree named function types keep signatures readable: `Mapper func(any) any`,\n`Predicate func(any) bool`, `Reducer func(any, any) any`.\n\n## Two things to know before using it\n\n- **Everything is `[]any`.** Gno has no generics, so element access means a\n  type assertion in your own callback, and a wrong one panics at runtime\n  instead of failing to compile. Keep slices homogeneous.\n- **Every call allocates a new slice.** Chaining four operations over a large\n  collection allocates four times. That is fine for rendering a page and wrong\n  for a hot path over persisted state, where a single explicit loop is both\n  cheaper and clearer.\n\n`GroupBy` returns `map[any][]any`, so the key must be a comparable type.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"fp.gno","body":"// Package fp provides functional programming utilities for Gno, enabling\n// transformations, filtering, and other operations on slices of any.\n//\n// Example of chaining operations:\n//\n//\tnumbers := []any{1, 2, 3, 4, 5, 6}\n//\n//\t// Define predicates, mappers and reducers\n//\tisEven := func(v any) bool { return v.(int)%2 == 0 }\n//\tdouble := func(v any) any { return v.(int) * 2 }\n//\tsum := func(a, b any) any { return a.(int) + b.(int) }\n//\n//\t// Chain operations: filter even numbers, double them, then sum\n//\tevenNums := Filter(numbers, isEven)        // [2, 4, 6]\n//\tdoubled := Map(evenNums, double)           // [4, 8, 12]\n//\tresult := Reduce(doubled, sum, 0)          // 24\n//\n//\t// Alternative: group by even/odd, then get even numbers\n//\tbyMod2 := func(v any) any { return v.(int) % 2 }\n//\tgrouped := GroupBy(numbers, byMod2)        // {0: [2,4,6], 1: [1,3,5]}\n//\tevens := grouped[0]                        // [2,4,6]\npackage fp\n\n// Mapper is a function type that maps an element to another element.\ntype Mapper func(any) any\n\n// Predicate is a function type that evaluates a condition on an element.\ntype Predicate func(any) bool\n\n// Reducer is a function type that reduces two elements to a single value.\ntype Reducer func(any, any) any\n\n// Filter filters elements from the slice that satisfy the given predicate.\n//\n// Example:\n//\n//\tnumbers := []any{-1, 0, 1, 2}\n//\tisPositive := func(v any) bool { return v.(int) \u003e 0 }\n//\tresult := Filter(numbers, isPositive) // [1, 2]\nfunc Filter(values []any, fn Predicate) []any {\n\tresult := []any{}\n\tfor _, v := range values {\n\t\tif fn(v) {\n\t\t\tresult = append(result, v)\n\t\t}\n\t}\n\treturn result\n}\n\n// Map applies a function to each element in the slice.\n//\n// Example:\n//\n//\tnumbers := []any{1, 2, 3}\n//\ttoString := func(v any) any { return fmt.Sprintf(\"%d\", v) }\n//\tresult := Map(numbers, toString) // [\"1\", \"2\", \"3\"]\nfunc Map(values []any, fn Mapper) []any {\n\tresult := make([]any, len(values))\n\tfor i, v := range values {\n\t\tresult[i] = fn(v)\n\t}\n\treturn result\n}\n\n// Reduce reduces a slice to a single value by applying a function.\n//\n// Example:\n//\n//\tnumbers := []any{1, 2, 3, 4}\n//\tsum := func(a, b any) any { return a.(int) + b.(int) }\n//\tresult := Reduce(numbers, sum, 0) // 10\nfunc Reduce(values []any, fn Reducer, initial any) any {\n\tacc := initial\n\tfor _, v := range values {\n\t\tacc = fn(acc, v)\n\t}\n\treturn acc\n}\n\n// FlatMap maps each element to a collection and flattens the results.\n//\n// Example:\n//\n//\twords := []any{\"hello\", \"world\"}\n//\tsplit := func(v any) any {\n//\t    chars := []any{}\n//\t    for _, c := range v.(string) {\n//\t        chars = append(chars, string(c))\n//\t    }\n//\t    return chars\n//\t}\n//\tresult := FlatMap(words, split) // [\"h\",\"e\",\"l\",\"l\",\"o\",\"w\",\"o\",\"r\",\"l\",\"d\"]\nfunc FlatMap(values []any, fn Mapper) []any {\n\tresult := []any{}\n\tfor _, v := range values {\n\t\tinner := fn(v).([]any)\n\t\tresult = append(result, inner...)\n\t}\n\treturn result\n}\n\n// All returns true if all elements satisfy the predicate.\n//\n// Example:\n//\n//\tnumbers := []any{2, 4, 6, 8}\n//\tisEven := func(v any) bool { return v.(int)%2 == 0 }\n//\tresult := All(numbers, isEven) // true\nfunc All(values []any, fn Predicate) bool {\n\tfor _, v := range values {\n\t\tif !fn(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Any returns true if at least one element satisfies the predicate.\n//\n// Example:\n//\n//\tnumbers := []any{1, 3, 4, 7}\n//\tisEven := func(v any) bool { return v.(int)%2 == 0 }\n//\tresult := Any(numbers, isEven) // true (4 is even)\nfunc Any(values []any, fn Predicate) bool {\n\tfor _, v := range values {\n\t\tif fn(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// None returns true if no elements satisfy the predicate.\n//\n// Example:\n//\n//\tnumbers := []any{1, 3, 5, 7}\n//\tisEven := func(v any) bool { return v.(int)%2 == 0 }\n//\tresult := None(numbers, isEven) // true (no even numbers)\nfunc None(values []any, fn Predicate) bool {\n\tfor _, v := range values {\n\t\tif fn(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Chunk splits a slice into chunks of the given size.\n//\n// Example:\n//\n//\tnumbers := []any{1, 2, 3, 4, 5}\n//\tresult := Chunk(numbers, 2) // [[1,2], [3,4], [5]]\nfunc Chunk(values []any, size int) [][]any {\n\tif size \u003c= 0 {\n\t\treturn nil\n\t}\n\tvar chunks [][]any\n\tfor i := 0; i \u003c len(values); i += size {\n\t\tend := i + size\n\t\tif end \u003e len(values) {\n\t\t\tend = len(values)\n\t\t}\n\t\tchunks = append(chunks, values[i:end])\n\t}\n\treturn chunks\n}\n\n// Find returns the first element that satisfies the predicate and a boolean indicating if an element was found.\n//\n// Example:\n//\n//\tnumbers := []any{1, 2, 3, 4}\n//\tisEven := func(v any) bool { return v.(int)%2 == 0 }\n//\tresult, found := Find(numbers, isEven) // 2, true\nfunc Find(values []any, fn Predicate) (any, bool) {\n\tfor _, v := range values {\n\t\tif fn(v) {\n\t\t\treturn v, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\n// Reverse reverses the order of elements in a slice.\n//\n// Example:\n//\n//\tnumbers := []any{1, 2, 3}\n//\tresult := Reverse(numbers) // [3, 2, 1]\nfunc Reverse(values []any) []any {\n\tresult := make([]any, len(values))\n\tfor i, v := range values {\n\t\tresult[len(values)-1-i] = v\n\t}\n\treturn result\n}\n\n// Zip combines two slices into a slice of pairs. If the slices have different lengths,\n// extra elements from the longer slice are ignored.\n//\n// Example:\n//\n//\ta := []any{1, 2, 3}\n//\tb := []any{\"a\", \"b\", \"c\"}\n//\tresult := Zip(a, b) // [[1,\"a\"], [2,\"b\"], [3,\"c\"]]\nfunc Zip(a, b []any) [][2]any {\n\tlength := min(len(a), len(b))\n\tresult := make([][2]any, length)\n\tfor i := 0; i \u003c length; i++ {\n\t\tresult[i] = [2]any{a[i], b[i]}\n\t}\n\treturn result\n}\n\n// Unzip splits a slice of pairs into two separate slices.\n//\n// Example:\n//\n//\tpairs := [][2]any{{1,\"a\"}, {2,\"b\"}, {3,\"c\"}}\n//\tnumbers, letters := Unzip(pairs) // [1,2,3], [\"a\",\"b\",\"c\"]\nfunc Unzip(pairs [][2]any) ([]any, []any) {\n\ta := make([]any, len(pairs))\n\tb := make([]any, len(pairs))\n\tfor i, pair := range pairs {\n\t\ta[i] = pair[0]\n\t\tb[i] = pair[1]\n\t}\n\treturn a, b\n}\n\n// GroupBy groups elements based on a key returned by a Mapper.\n//\n// Example:\n//\n//\tnumbers := []any{1, 2, 3, 4, 5, 6}\n//\tbyMod3 := func(v any) any { return v.(int) % 3 }\n//\tresult := GroupBy(numbers, byMod3) // {0: [3,6], 1: [1,4], 2: [2,5]}\nfunc GroupBy(values []any, fn Mapper) map[any][]any {\n\tresult := make(map[any][]any)\n\tfor _, v := range values {\n\t\tkey := fn(v)\n\t\tresult[key] = append(result[key], v)\n\t}\n\treturn result\n}\n\n// Flatten flattens a slice of slices into a single slice.\n//\n// Example:\n//\n//\tnested := [][]any{{1,2}, {3,4}, {5}}\n//\tresult := Flatten(nested) // [1,2,3,4,5]\nfunc Flatten(values [][]any) []any {\n\tresult := []any{}\n\tfor _, v := range values {\n\t\tresult = append(result, v...)\n\t}\n\treturn result\n}\n\n// Helper functions\nfunc min(a, b int) int {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n"},{"name":"fp_test.gno","body":"package fp\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc TestMap(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []any\n\t\tfn       func(any) any\n\t\texpected []any\n\t}{\n\t\t{\n\t\t\tname:     \"multiply numbers by 2\",\n\t\t\tinput:    []any{1, 2, 3},\n\t\t\tfn:       func(v any) any { return v.(int) * 2 },\n\t\t\texpected: []any{2, 4, 6},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tinput:    []any{},\n\t\t\tfn:       func(v any) any { return v.(int) * 2 },\n\t\t\texpected: []any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"convert numbers to strings\",\n\t\t\tinput:    []any{1, 2, 3},\n\t\t\tfn:       func(v any) any { return ufmt.Sprintf(\"%d\", v.(int)) },\n\t\t\texpected: []any{\"1\", \"2\", \"3\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := Map(tt.input, tt.fn)\n\t\t\tif !equalSlices(result, tt.expected) {\n\t\t\t\tt.Errorf(\"Map failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFilter(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []any\n\t\tfn       func(any) bool\n\t\texpected []any\n\t}{\n\t\t{\n\t\t\tname:     \"filter even numbers\",\n\t\t\tinput:    []any{1, 2, 3, 4},\n\t\t\tfn:       func(v any) bool { return v.(int)%2 == 0 },\n\t\t\texpected: []any{2, 4},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tinput:    []any{},\n\t\t\tfn:       func(v any) bool { return v.(int)%2 == 0 },\n\t\t\texpected: []any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"no matches\",\n\t\t\tinput:    []any{1, 3, 5},\n\t\t\tfn:       func(v any) bool { return v.(int)%2 == 0 },\n\t\t\texpected: []any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"all matches\",\n\t\t\tinput:    []any{2, 4, 6},\n\t\t\tfn:       func(v any) bool { return v.(int)%2 == 0 },\n\t\t\texpected: []any{2, 4, 6},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := Filter(tt.input, tt.fn)\n\t\t\tif !equalSlices(result, tt.expected) {\n\t\t\t\tt.Errorf(\"Filter failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReduce(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []any\n\t\tfn       func(any, any) any\n\t\tinitial  any\n\t\texpected any\n\t}{\n\t\t{\n\t\t\tname:     \"sum numbers\",\n\t\t\tinput:    []any{1, 2, 3},\n\t\t\tfn:       func(a, b any) any { return a.(int) + b.(int) },\n\t\t\tinitial:  0,\n\t\t\texpected: 6,\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tinput:    []any{},\n\t\t\tfn:       func(a, b any) any { return a.(int) + b.(int) },\n\t\t\tinitial:  0,\n\t\t\texpected: 0,\n\t\t},\n\t\t{\n\t\t\tname:     \"concatenate strings\",\n\t\t\tinput:    []any{\"a\", \"b\", \"c\"},\n\t\t\tfn:       func(a, b any) any { return a.(string) + b.(string) },\n\t\t\tinitial:  \"\",\n\t\t\texpected: \"abc\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := Reduce(tt.input, tt.fn, tt.initial)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"Reduce failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFlatMap(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []any\n\t\tfn       func(any) any\n\t\texpected []any\n\t}{\n\t\t{\n\t\t\tname:  \"split words into chars\",\n\t\t\tinput: []any{\"go\", \"fn\"},\n\t\t\tfn: func(word any) any {\n\t\t\t\tchars := []any{}\n\t\t\t\tfor _, c := range word.(string) {\n\t\t\t\t\tchars = append(chars, string(c))\n\t\t\t\t}\n\t\t\t\treturn chars\n\t\t\t},\n\t\t\texpected: []any{\"g\", \"o\", \"f\", \"n\"},\n\t\t},\n\t\t{\n\t\t\tname:  \"empty string handling\",\n\t\t\tinput: []any{\"\", \"a\", \"\"},\n\t\t\tfn: func(word any) any {\n\t\t\t\tchars := []any{}\n\t\t\t\tfor _, c := range word.(string) {\n\t\t\t\t\tchars = append(chars, string(c))\n\t\t\t\t}\n\t\t\t\treturn chars\n\t\t\t},\n\t\t\texpected: []any{\"a\"},\n\t\t},\n\t\t{\n\t\t\tname:  \"nil handling\",\n\t\t\tinput: []any{nil, \"a\", nil},\n\t\t\tfn: func(word any) any {\n\t\t\t\tif word == nil {\n\t\t\t\t\treturn []any{}\n\t\t\t\t}\n\t\t\t\treturn []any{word}\n\t\t\t},\n\t\t\texpected: []any{\"a\"},\n\t\t},\n\t\t{\n\t\t\tname:  \"empty slice result\",\n\t\t\tinput: []any{\"\", \"\", \"\"},\n\t\t\tfn: func(word any) any {\n\t\t\t\treturn []any{}\n\t\t\t},\n\t\t\texpected: []any{},\n\t\t},\n\t\t{\n\t\t\tname:  \"nested array flattening\",\n\t\t\tinput: []any{1, 2, 3},\n\t\t\tfn: func(n any) any {\n\t\t\t\treturn []any{n, n}\n\t\t\t},\n\t\t\texpected: []any{1, 1, 2, 2, 3, 3},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := FlatMap(tt.input, tt.fn)\n\t\t\tif !equalSlices(result, tt.expected) {\n\t\t\t\tt.Errorf(\"FlatMap failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestAllAnyNone(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tinput        []any\n\t\tfn           func(any) bool\n\t\texpectedAll  bool\n\t\texpectedAny  bool\n\t\texpectedNone bool\n\t}{\n\t\t{\n\t\t\tname:         \"all even numbers\",\n\t\t\tinput:        []any{2, 4, 6, 8},\n\t\t\tfn:           func(x any) bool { return x.(int)%2 == 0 },\n\t\t\texpectedAll:  true,\n\t\t\texpectedAny:  true,\n\t\t\texpectedNone: false,\n\t\t},\n\t\t{\n\t\t\tname:         \"no even numbers\",\n\t\t\tinput:        []any{1, 3, 5, 7},\n\t\t\tfn:           func(x any) bool { return x.(int)%2 == 0 },\n\t\t\texpectedAll:  false,\n\t\t\texpectedAny:  false,\n\t\t\texpectedNone: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"mixed even/odd numbers\",\n\t\t\tinput:        []any{1, 2, 3, 4},\n\t\t\tfn:           func(x any) bool { return x.(int)%2 == 0 },\n\t\t\texpectedAll:  false,\n\t\t\texpectedAny:  true,\n\t\t\texpectedNone: false,\n\t\t},\n\t\t{\n\t\t\tname:         \"empty slice\",\n\t\t\tinput:        []any{},\n\t\t\tfn:           func(x any) bool { return x.(int)%2 == 0 },\n\t\t\texpectedAll:  true,  // vacuously true\n\t\t\texpectedAny:  false, // vacuously false\n\t\t\texpectedNone: true,  // vacuously true\n\t\t},\n\t\t{\n\t\t\tname:         \"nil predicate handling\",\n\t\t\tinput:        []any{nil, nil, nil},\n\t\t\tfn:           func(x any) bool { return x == nil },\n\t\t\texpectedAll:  true,\n\t\t\texpectedAny:  true,\n\t\t\texpectedNone: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresultAll := All(tt.input, tt.fn)\n\t\t\tif resultAll != tt.expectedAll {\n\t\t\t\tt.Errorf(\"All failed, expected %v, got %v\", tt.expectedAll, resultAll)\n\t\t\t}\n\n\t\t\tresultAny := Any(tt.input, tt.fn)\n\t\t\tif resultAny != tt.expectedAny {\n\t\t\t\tt.Errorf(\"Any failed, expected %v, got %v\", tt.expectedAny, resultAny)\n\t\t\t}\n\n\t\t\tresultNone := None(tt.input, tt.fn)\n\t\t\tif resultNone != tt.expectedNone {\n\t\t\t\tt.Errorf(\"None failed, expected %v, got %v\", tt.expectedNone, resultNone)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestChunk(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []any\n\t\tsize     int\n\t\texpected [][]any\n\t}{\n\t\t{\n\t\t\tname:     \"normal chunks\",\n\t\t\tinput:    []any{1, 2, 3, 4, 5},\n\t\t\tsize:     2,\n\t\t\texpected: [][]any{{1, 2}, {3, 4}, {5}},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tinput:    []any{},\n\t\t\tsize:     2,\n\t\t\texpected: [][]any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"chunk size equals length\",\n\t\t\tinput:    []any{1, 2, 3},\n\t\t\tsize:     3,\n\t\t\texpected: [][]any{{1, 2, 3}},\n\t\t},\n\t\t{\n\t\t\tname:     \"chunk size larger than length\",\n\t\t\tinput:    []any{1, 2},\n\t\t\tsize:     3,\n\t\t\texpected: [][]any{{1, 2}},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := Chunk(tt.input, tt.size)\n\t\t\tif !equalNestedSlices(result, tt.expected) {\n\t\t\t\tt.Errorf(\"Chunk failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFind(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tinput       []any\n\t\tfn          func(any) bool\n\t\texpected    any\n\t\tshouldFound bool\n\t}{\n\t\t{\n\t\t\tname:        \"find first number greater than 2\",\n\t\t\tinput:       []any{1, 2, 3, 4},\n\t\t\tfn:          func(v any) bool { return v.(int) \u003e 2 },\n\t\t\texpected:    3,\n\t\t\tshouldFound: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"empty slice\",\n\t\t\tinput:       []any{},\n\t\t\tfn:          func(v any) bool { return v.(int) \u003e 2 },\n\t\t\texpected:    nil,\n\t\t\tshouldFound: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"no match\",\n\t\t\tinput:       []any{1, 2},\n\t\t\tfn:          func(v any) bool { return v.(int) \u003e 10 },\n\t\t\texpected:    nil,\n\t\t\tshouldFound: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, found := Find(tt.input, tt.fn)\n\t\t\tif found != tt.shouldFound {\n\t\t\t\tt.Errorf(\"Find failed, expected found=%v, got found=%v\", tt.shouldFound, found)\n\t\t\t}\n\t\t\tif found \u0026\u0026 result != tt.expected {\n\t\t\t\tt.Errorf(\"Find failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReverse(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []any\n\t\texpected []any\n\t}{\n\t\t{\n\t\t\tname:     \"normal sequence\",\n\t\t\tinput:    []any{1, 2, 3, 4},\n\t\t\texpected: []any{4, 3, 2, 1},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tinput:    []any{},\n\t\t\texpected: []any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"single element\",\n\t\t\tinput:    []any{1},\n\t\t\texpected: []any{1},\n\t\t},\n\t\t{\n\t\t\tname:     \"mixed types\",\n\t\t\tinput:    []any{1, \"a\", true, 2.5},\n\t\t\texpected: []any{2.5, true, \"a\", 1},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := Reverse(tt.input)\n\t\t\tif !equalSlices(result, tt.expected) {\n\t\t\t\tt.Errorf(\"Reverse failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestZipUnzip(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\ta           []any\n\t\tb           []any\n\t\texpectedZip [][2]any\n\t\texpectedA   []any\n\t\texpectedB   []any\n\t}{\n\t\t{\n\t\t\tname:        \"normal case\",\n\t\t\ta:           []any{1, 2, 3},\n\t\t\tb:           []any{\"a\", \"b\", \"c\"},\n\t\t\texpectedZip: [][2]any{{1, \"a\"}, {2, \"b\"}, {3, \"c\"}},\n\t\t\texpectedA:   []any{1, 2, 3},\n\t\t\texpectedB:   []any{\"a\", \"b\", \"c\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"empty slices\",\n\t\t\ta:           []any{},\n\t\t\tb:           []any{},\n\t\t\texpectedZip: [][2]any{},\n\t\t\texpectedA:   []any{},\n\t\t\texpectedB:   []any{},\n\t\t},\n\t\t{\n\t\t\tname:        \"different lengths - a shorter\",\n\t\t\ta:           []any{1, 2},\n\t\t\tb:           []any{\"a\", \"b\", \"c\"},\n\t\t\texpectedZip: [][2]any{{1, \"a\"}, {2, \"b\"}},\n\t\t\texpectedA:   []any{1, 2},\n\t\t\texpectedB:   []any{\"a\", \"b\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"different lengths - b shorter\",\n\t\t\ta:           []any{1, 2, 3},\n\t\t\tb:           []any{\"a\"},\n\t\t\texpectedZip: [][2]any{{1, \"a\"}},\n\t\t\texpectedA:   []any{1},\n\t\t\texpectedB:   []any{\"a\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"mixed types\",\n\t\t\ta:           []any{1, true, \"x\"},\n\t\t\tb:           []any{2.5, false, \"y\"},\n\t\t\texpectedZip: [][2]any{{1, 2.5}, {true, false}, {\"x\", \"y\"}},\n\t\t\texpectedA:   []any{1, true, \"x\"},\n\t\t\texpectedB:   []any{2.5, false, \"y\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tzipped := Zip(tt.a, tt.b)\n\t\t\tif len(zipped) != len(tt.expectedZip) {\n\t\t\t\tt.Errorf(\"Zip failed, expected length %v, got %v\", len(tt.expectedZip), len(zipped))\n\t\t\t}\n\t\t\tfor i, pair := range zipped {\n\t\t\t\tif pair[0] != tt.expectedZip[i][0] || pair[1] != tt.expectedZip[i][1] {\n\t\t\t\t\tt.Errorf(\"Zip failed at index %d, expected %v, got %v\", i, tt.expectedZip[i], pair)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tunzippedA, unzippedB := Unzip(zipped)\n\t\t\tif !equalSlices(unzippedA, tt.expectedA) {\n\t\t\t\tt.Errorf(\"Unzip failed for slice A, expected %v, got %v\", tt.expectedA, unzippedA)\n\t\t\t}\n\t\t\tif !equalSlices(unzippedB, tt.expectedB) {\n\t\t\t\tt.Errorf(\"Unzip failed for slice B, expected %v, got %v\", tt.expectedB, unzippedB)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGroupBy(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []any\n\t\tfn       func(any) any\n\t\texpected map[any][]any\n\t}{\n\t\t{\n\t\t\tname:  \"group by even/odd\",\n\t\t\tinput: []any{1, 2, 3, 4, 5, 6},\n\t\t\tfn:    func(v any) any { return v.(int) % 2 },\n\t\t\texpected: map[any][]any{\n\t\t\t\t0: {2, 4, 6},\n\t\t\t\t1: {1, 3, 5},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tinput:    []any{},\n\t\t\tfn:       func(v any) any { return v.(int) % 2 },\n\t\t\texpected: map[any][]any{},\n\t\t},\n\t\t{\n\t\t\tname:  \"single group\",\n\t\t\tinput: []any{2, 4, 6},\n\t\t\tfn:    func(v any) any { return v.(int) % 2 },\n\t\t\texpected: map[any][]any{\n\t\t\t\t0: {2, 4, 6},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:  \"group by type\",\n\t\t\tinput: []any{1, \"a\", 2, \"b\", true},\n\t\t\tfn: func(v any) any {\n\t\t\t\tswitch v.(type) {\n\t\t\t\tcase int:\n\t\t\t\t\treturn \"int\"\n\t\t\t\tcase string:\n\t\t\t\t\treturn \"string\"\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"other\"\n\t\t\t\t}\n\t\t\t},\n\t\t\texpected: map[any][]any{\n\t\t\t\t\"int\":    {1, 2},\n\t\t\t\t\"string\": {\"a\", \"b\"},\n\t\t\t\t\"other\":  {true},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := GroupBy(tt.input, tt.fn)\n\t\t\tif len(result) != len(tt.expected) {\n\t\t\t\tt.Errorf(\"GroupBy failed, expected %d groups, got %d\", len(tt.expected), len(result))\n\t\t\t}\n\t\t\tfor k, v := range tt.expected {\n\t\t\t\tif !equalSlices(result[k], v) {\n\t\t\t\t\tt.Errorf(\"GroupBy failed for key %v, expected %v, got %v\", k, v, result[k])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFlatten(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    [][]any\n\t\texpected []any\n\t}{\n\t\t{\n\t\t\tname:     \"normal nested slices\",\n\t\t\tinput:    [][]any{{1, 2}, {3, 4}, {5}},\n\t\t\texpected: []any{1, 2, 3, 4, 5},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty outer slice\",\n\t\t\tinput:    [][]any{},\n\t\t\texpected: []any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty inner slices\",\n\t\t\tinput:    [][]any{{}, {}, {}},\n\t\t\texpected: []any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"mixed types\",\n\t\t\tinput:    [][]any{{1, \"a\"}, {true, 2.5}, {nil}},\n\t\t\texpected: []any{1, \"a\", true, 2.5, nil},\n\t\t},\n\t\t{\n\t\t\tname:     \"single element slices\",\n\t\t\tinput:    [][]any{{1}, {2}, {3}},\n\t\t\texpected: []any{1, 2, 3},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := Flatten(tt.input)\n\t\t\tif !equalSlices(result, tt.expected) {\n\t\t\t\tt.Errorf(\"Flatten failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestContains(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tslice    []any\n\t\titem     any\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname:     \"contains integer\",\n\t\t\tslice:    []any{1, 2, 3},\n\t\t\titem:     2,\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"does not contain integer\",\n\t\t\tslice:    []any{1, 2, 3},\n\t\t\titem:     4,\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"contains string\",\n\t\t\tslice:    []any{\"a\", \"b\", \"c\"},\n\t\t\titem:     \"b\",\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tslice:    []any{},\n\t\t\titem:     1,\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"contains nil\",\n\t\t\tslice:    []any{1, nil, 3},\n\t\t\titem:     nil,\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"mixed types\",\n\t\t\tslice:    []any{1, \"a\", true},\n\t\t\titem:     true,\n\t\t\texpected: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := contains(tt.slice, tt.item)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"contains failed, expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Helper function for testing\nfunc contains(slice []any, item any) bool {\n\tfor _, v := range slice {\n\t\tif v == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// Helper functions for comparing slices\nfunc equalSlices(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc equalNestedSlices(a, b [][]any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif !equalSlices(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/fp/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"10000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"gnopm","path":"gno.land/p/moul/gnopm/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/gnopm/v0`\n\nThe domain model of a **source registry** for gno packages: a map from a\ndeployed package path back to the repository, commit and directory that produced\nit.\n\nThe realm half is\n[`gno.land/r/moul/gnopm/registry/v0`](../../../r/moul/gnopm/registry). This\npackage is pure: no chain imports, no realm state, and the one piece of chain\nknowledge it needs (who holds a namespace) arrives as a function parameter.\n\n## Why this has to exist at all\n\nA Go import path *is* a repository URL, so pkg.go.dev needs no registry. A gno\nimport path is a chain address, so nothing anywhere says which source produced\nthe bytes running at `gno.land/p/nt/tinyavl/v0`. gno gave up that link\ndeliberately, and this is the part that has to be rebuilt by hand.\n\n## What it can and cannot promise\n\nIt cannot promise anything, and the whole design is built around saying so\nrather than around hiding it. Two claims look alike and are not the same:\n\n| claim | provable |\n|---|---|\n| this package came from that repository | **no.** Not here and not anywhere: anyone may deploy any bytes and claim any repository |\n| the deployed bytes equal the `addpkg` payload of that directory at that commit | **yes**, by hashing both sides. Off chain, by anything that can clone |\n| the claimant owns the path's namespace | **yes**, from chain data, recomputed on every read |\n\nSo a `Claim` is testimony under a signature, and it is stored in exactly the\nshape the second row needs: path, repository, commit and directory are the four\ninputs to \"hash the payload of that directory and compare it with what the chain\nhands back\". This package does not answer the question. It makes the question\nanswerable by something that can clone, which\n[gnopm](https://github.com/moul/gnopm) already does against a local tree\n(`gnopm verify -deployed`).\n\nA mismatch, when a verifier does find one, is **not** evidence of malice. The\nlikeliest cause by far is a repository that moved on after a deploy, which is\nthe normal state of most repositories most of the time.\n\n## Open, and tagged\n\nAnyone may claim any path, including one they had nothing to do with.\n`Claim.OwnedBy` reports whether a claim comes from the party that controls the\npath, so the two can be told apart at render time.\n\nGating registration on namespace ownership was the alternative and it cannot\nbootstrap: on day one almost nothing has been registered by its own deployer, so\nthe gated registry is empty and teaches nobody anything. Open-and-labelled keeps\nthe map fillable and moves the defence to the renderer, which is why\n`OwnedBy` exists and why the realm ranks on it rather than hiding anything.\n\n`OwnedBy` takes the name resolver as a parameter and the answer is never stored:\na name can be transferred, and a stored answer would rot into exactly the kind of\nstale claim this package exists to distinguish from a live one.\n\n## API\n\n```go\nr := gnopm.New()\n\n// A claimant states where a package came from. Calling it again replaces that\n// claimant's own claim and nobody else's.\nc, err := r.Register(claimant, height, pkgPath, repo, commit, dir, ref)\nerr = r.Withdraw(claimant, pkgPath)          // your own claim, never anyone else's\n\np := r.Package(pkgPath)                      // every claim about one path, or nil\np.Claim(claimant)                            // one of them\np.IterateClaims(func(c *gnopm.Claim) bool { ... })\n\nc.OwnedBy(resolve)                           // does this come from the namespace holder\nc.SourceURL()                                // a browsable link to the claimed source\n```\n\n`Height` dates the claim and `UpdatedAt` dates the last edit. They are separate\nso a reader can tell a claim that has been kept current from one made once at\ndeploy time and abandoned.\n\n## Validation is an allowlist, on purpose\n\nEvery stored field is charset-validated at write time: `ValidPkgPath`,\n`ValidRepo`, `ValidCommit`, `ValidDir`, `ValidRef`. Each is an allowlist, so a\nstored field cannot hold a backtick, a pipe, a bracket, an ASCII control\ncharacter or a bidi override.\n\nThat is not belt-and-braces, it is the escaping strategy. One claim is rendered\nin several places (a listing row, a table cell, an inline-code span, a link\ntitle) and a consumer that forgets to escape at any one of them has a hole.\nA field that can only hold safe bytes needs no escaping anywhere.\n\nTwo consequences worth knowing before they surprise you:\n\n- **`ValidRepo` accepts `https://` and nothing else.** Not a taste judgement\n  about git transports: the set of URL schemes that are safe to hand a browser\n  is exactly one, and `javascript:` and `data:` are the attack. A host with a\n  port is also refused, because the userinfo check (`https://github.com@evil.example/x`\n  fetches from `evil.example` while reading as GitHub) needs the host to contain\n  no `@` or `:`.\n- **`ValidRef` is narrower than git's own rule.** git rejects a handful of\n  metacharacters and permits the rest, which would leave a ref free to carry a\n  pipe or a backtick and undo the allowlist for every other field. What stays\n  expressible is every ref anyone actually has.\n\n## What is deliberately not here\n\n- **No verification.** A realm cannot clone a repository. See the realm README\n  for where that half is meant to live.\n- **No network of trust, no voting, no curation.** Whose claim to believe is a\n  judgement, and the place to make it is a renderer that can see who deployed\n  the package, not a data structure.\n- **No version resolution.** `Version` reads a trailing `vN` and that is all.\n  An unversioned path is legal and is not an error: gnoweb serves\n  `gno.land/u/\u003cname\u003e` by calling the realm at exactly `/r/\u003cname\u003e/home`, so that\n  one path can never carry a version.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/gnopm/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/gnopm/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"errors.gno","body":"package gnopm\n\nimport \"errors\"\n\n// Stable, machine-readable error values. Callers (realms, clients, indexers)\n// switch on these rather than on message text: a realm turns them into panics,\n// and the panic string is the only thing a user ever sees.\nvar (\n\tErrInvalidPkgPath   = errors.New(\"gnopm: invalid package path\")\n\tErrInvalidRepo      = errors.New(\"gnopm: invalid repository URL\")\n\tErrInvalidCommit    = errors.New(\"gnopm: invalid commit id\")\n\tErrInvalidDir       = errors.New(\"gnopm: invalid directory\")\n\tErrInvalidRef       = errors.New(\"gnopm: invalid ref name\")\n\tErrClaimNotFound    = errors.New(\"gnopm: no such claim\")\n\tErrTooManyClaimants = errors.New(\"gnopm: too many claimants for this package\")\n)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/gnopm/v0\"\ngno = \"0.9\"\n"},{"name":"helpers_test.gno","body":"package gnopm\n\n// Fixtures shared by the tests in this package.\n//\n// addrNS is moul's mainnet address, used wherever a test needs a real bech32\n// address rather than a plausible-looking string: the address-namespace rule\n// turns on the bech32 alphabet, so a made-up \"g1aaa...\" would pass or fail for\n// the wrong reason.\nconst (\n\taddrNS   = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\talice    = address(\"g1ubwjz3jmrjwmpuvrsjzgy5qkxf5wrgphzmd2tk\")\n\tbob      = address(\"g1e8vw6gh284q7ggzqs66ug0zvyf42tzsf5zdhsk\")\n\tcarol    = address(\"g1v9kxjcm9ta047h6lta047h6lta047h6lz7gmv8\")\n\tsha1Zero = \"0000000000000000000000000000000000000000\"\n\tsha1One  = \"1111111111111111111111111111111111111111\"\n)\n\n// resolver builds an r/sys/users stand-in from a name -\u003e address table, so the\n// ownership rule is tested without importing a realm.\nfunc resolver(table map[string]address) func(string) (address, bool) {\n\treturn func(name string) (address, bool) {\n\t\ta, ok := table[name]\n\t\treturn a, ok\n\t}\n}\n"},{"name":"pkgpath.gno","body":"package gnopm\n\nimport \"strings\"\n\n// Parsing a gno package path far enough to know who owns it.\n//\n// A path is \"\u003cdomain\u003e/\u003ckind\u003e/\u003cnamespace\u003e/\u003cname...\u003e\", optionally ending in a\n// \"/vN\" version element: \"gno.land/p/moul/md/v1\", \"gno.land/r/sys/users\",\n// \"gno.land/r/g1abc.../scratch/v0\". The namespace is the third element and it\n// is the whole reason this file exists: it decides whether a claim comes from\n// the party that controls the path or from a stranger, which is the strongest\n// signal the registry can offer about a claim it can never itself verify.\n\n// SplitPkgPath breaks a package path into its domain, kind (\"p\" or \"r\"),\n// namespace and the remainder. ok is false for anything that is not shaped like\n// a publishable gno path.\nfunc SplitPkgPath(s string) (domain, kind, ns, rest string, ok bool) {\n\tif !ValidPkgPath(s) {\n\t\treturn \"\", \"\", \"\", \"\", false\n\t}\n\tparts := strings.Split(s, \"/\")\n\treturn parts[0], parts[1], parts[2], strings.Join(parts[3:], \"/\"), true\n}\n\n// Namespace returns the owning namespace of a package path, or \"\" if the path\n// is not one.\nfunc Namespace(s string) string {\n\t_, _, ns, _, ok := SplitPkgPath(s)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn ns\n}\n\n// Version returns the trailing \"vN\" element of a package path, or \"\" when the\n// path carries none. Absent is legal and is not an error: gnoweb serves\n// gno.land/u/\u003cname\u003e by calling the realm at exactly /r/\u003cname\u003e/home, so that one\n// path can never carry a version.\nfunc Version(s string) string {\n\tparts := strings.Split(s, \"/\")\n\tif len(parts) \u003c 4 {\n\t\treturn \"\"\n\t}\n\tlast := parts[len(parts)-1]\n\tif len(last) \u003c 2 || last[0] != 'v' {\n\t\treturn \"\"\n\t}\n\tfor i := 1; i \u003c len(last); i++ {\n\t\tif last[i] \u003c '0' || last[i] \u003e '9' {\n\t\t\treturn \"\"\n\t\t}\n\t}\n\treturn last\n}\n\n// ValidPkgPath reports whether s is shaped like a publishable gno package path.\n//\n// It does NOT say the path exists on any chain, and cannot: a realm has no way\n// to ask whether some other path was ever deployed. That gap is the registry's\n// central honesty problem and is documented on Registry.\nfunc ValidPkgPath(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxPkgPathLen {\n\t\treturn false\n\t}\n\tif strings.HasPrefix(s, \"/\") || strings.HasSuffix(s, \"/\") || strings.Contains(s, \"//\") {\n\t\treturn false\n\t}\n\tparts := strings.Split(s, \"/\")\n\tif len(parts) \u003c 4 {\n\t\treturn false\n\t}\n\t// The domain, which is a host and so must carry a dot.\n\tif !strings.Contains(parts[0], \".\") {\n\t\treturn false\n\t}\n\tif parts[1] != \"p\" \u0026\u0026 parts[1] != \"r\" {\n\t\treturn false\n\t}\n\tfor _, p := range parts {\n\t\tif p == \"\" || p == \".\" || p == \"..\" {\n\t\t\treturn false\n\t\t}\n\t\tfor i := 0; i \u003c len(p); i++ {\n\t\t\tif !pathByteOK(p[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n// AddressNamespace reports whether ns is shaped like a gno bech32 address, the\n// namespace every account owns without registering anything. A caller still\n// has to check it is the claimant's own address; this only says which of the\n// two ownership rules applies.\nfunc AddressNamespace(ns string) bool {\n\tif len(ns) != 40 || !strings.HasPrefix(ns, \"g1\") {\n\t\treturn false\n\t}\n\tfor i := 2; i \u003c len(ns); i++ {\n\t\tif !strings.ContainsRune(bech32Charset, rune(ns[i])) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// bech32Charset is bech32's data alphabet: lowercase alphanumerics minus the\n// four characters it drops to avoid transcription errors (1, b, i, o).\nconst bech32Charset = \"023456789acdefghjklmnpqrstuvwxyz\"\n"},{"name":"pkgpath_test.gno","body":"package gnopm\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestValidPkgPath(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"versioned package\", \"gno.land/p/moul/md/v1\", true},\n\t\t{\"versioned realm\", \"gno.land/r/moul/gnopm/registry/v0\", true},\n\t\t{\"unversioned realm\", \"gno.land/r/sys/users\", true},\n\t\t{\"address namespace\", \"gno.land/r/\" + addrNS + \"/scratch/v0\", true},\n\n\t\t{\"empty\", \"\", false},\n\t\t{\"too few elements\", \"gno.land/p/moul\", false},\n\t\t{\"domain without a dot\", \"gnoland/p/moul/md/v1\", false},\n\t\t{\"unknown kind\", \"gno.land/x/moul/md/v1\", false},\n\t\t{\"leading slash\", \"/gno.land/p/moul/md/v1\", false},\n\t\t{\"trailing slash\", \"gno.land/p/moul/md/v1/\", false},\n\t\t{\"double slash\", \"gno.land/p//moul/md\", false},\n\t\t{\"parent traversal\", \"gno.land/p/moul/../md\", false},\n\t\t{\"space\", \"gno.land/p/moul/m d\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidPkgPath(tc.in), tc.name)\n\t}\n}\n\nfunc TestSplitPkgPath(t *testing.T) {\n\tdomain, kind, ns, rest, ok := SplitPkgPath(\"gno.land/r/moul/gnopm/registry/v0\")\n\tuassert.True(t, ok, \"splits\")\n\tuassert.Equal(t, \"gno.land\", domain)\n\tuassert.Equal(t, \"r\", kind)\n\tuassert.Equal(t, \"moul\", ns)\n\tuassert.Equal(t, \"gnopm/registry/v0\", rest)\n\n\t_, _, _, _, ok = SplitPkgPath(\"nonsense\")\n\tuassert.False(t, ok, \"rejects a non-path\")\n\n\tuassert.Equal(t, \"moul\", Namespace(\"gno.land/p/moul/md/v1\"))\n\tuassert.Equal(t, \"\", Namespace(\"nonsense\"))\n}\n\nfunc TestVersion(t *testing.T) {\n\tcases := []struct {\n\t\tin, want string\n\t}{\n\t\t{\"gno.land/p/moul/md/v1\", \"v1\"},\n\t\t{\"gno.land/p/moul/md/v0\", \"v0\"},\n\t\t{\"gno.land/p/moul/md/v10\", \"v10\"},\n\t\t{\"gno.land/r/sys/users\", \"\"},   // unversioned is legal\n\t\t{\"gno.land/r/moul/home\", \"\"},   // the one path that can never carry one\n\t\t{\"gno.land/p/moul/md/vx\", \"\"},  // not a number\n\t\t{\"gno.land/p/moul/md/v\", \"\"},   // no digits\n\t\t{\"short\", \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, Version(tc.in), tc.in)\n\t}\n}\n\nfunc TestAddressNamespace(t *testing.T) {\n\tuassert.True(t, AddressNamespace(addrNS), \"a real address\")\n\tuassert.False(t, AddressNamespace(\"moul\"), \"a name\")\n\tuassert.False(t, AddressNamespace(\"\"), \"empty\")\n\t// b, i, o and 1 are exactly the characters bech32 drops.\n\tuassert.False(t, AddressNamespace(\"g1bbbfred47kzduec920z88wfr64ylksmdcedlf5\"), \"wrong length\")\n}\n"},{"name":"registry.gno","body":"// Package gnopm is the domain model of a source registry for gno packages: a\n// map from a deployed package path back to the repository, commit and directory\n// that produced it.\n//\n// It exists because gno deliberately broke the link Go gets for free. A Go\n// import path IS a repository URL, so pkg.go.dev needs no registry; a gno\n// import path is a chain address, so nothing anywhere says which source\n// produced the bytes running at gno.land/p/nt/tinyavl/v0.\n//\n// # What this can and cannot promise\n//\n// It cannot promise anything, and the design is built around saying so rather\n// than around hiding it. Two claims look alike and are not the same:\n//\n//  1. \"this package came from that repository\". UNPROVABLE, here or anywhere.\n//     Anyone may deploy any bytes and anyone may claim any repository. No\n//     registry design fixes this, and one that implies otherwise is worse than\n//     none.\n//  2. \"the bytes live at path P equal the addpkg payload of directory D in\n//     repository R at commit C\". Mechanically provable, by hashing both sides.\n//     It is NOT provable here: a realm cannot clone a repository. It is\n//     provable off chain by anything that can, and gnopm already does exactly\n//     this against a local tree (`gnopm verify -deployed`).\n//\n// So this package stores (1), labelled as the claim it is, in the form (2)\n// needs to be checkable. A Claim is testimony under a signature. It becomes\n// evidence only once something outside the chain has gone and looked.\n//\n// # What a signature does buy\n//\n// The chain knows who signed a claim, and that is not nothing. A claim whose\n// claimant owns the package path's namespace comes from the party that controls\n// the path, which is the closest thing to a promise available without a\n// chain-level feature. OwnedBy reports that relationship; it is deliberately\n// computed on demand from a caller-supplied resolver and never stored, because\n// a name can be transferred and a stored answer would be a claim of its own.\n//\n// Anyone may still claim any path. That is the \"open but tagged\" choice, and it\n// is made on purpose: gating registration on namespace ownership would mean\n// that on day one, when almost nothing is registered by its own deployer, the\n// registry is empty and teaches nobody anything. The defence against a\n// misleading claim is that it renders as a stranger's claim, ranked below, and\n// never as a fact.\npackage gnopm\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Registry maps a package path to the claims made about its source.\n//\n// One path may carry several claims, at most one per claimant. That is not a\n// flaw to be resolved: a fork is a legitimate second answer, and so is a third\n// party filling in the map for a package whose author never will.\ntype Registry struct {\n\tpackages *avl.Tree // package path -\u003e *Package\n\tclaims   int\n}\n\n// New returns an empty registry.\nfunc New() *Registry {\n\treturn \u0026Registry{packages: avl.NewTree()}\n}\n\n// Package is every claim made about one package path.\ntype Package struct {\n\tPkgPath string\n\tclaims  *avl.Tree // claimant address string -\u003e *Claim\n}\n\n// Claim is one address's statement about where a package came from.\n//\n// Every field except Claimant, Height and UpdatedAt is attacker-controlled.\n// They are charset-validated at write time rather than escaped at read time, so\n// that a consumer which forgets to escape is still safe: the fields cannot hold\n// a byte that means anything to markdown, to a terminal or to a URL parser.\ntype Claim struct {\n\tPkgPath  string\n\tRepo     string // https:// URL of the repository\n\tCommit   string // 40 or 64 lowercase hex\n\tDir      string // subdirectory holding the package, \"\" for the repo root\n\tRef      string // fully-qualified ref the commit was on, optional\n\tClaimant address\n\tHeight   int64 // block height of the first claim by this claimant\n\t// UpdatedAt is the height of the most recent write. Equal to Height until\n\t// the claimant re-registers, which is how a reader tells a claim that has\n\t// been kept current from one made once and abandoned.\n\tUpdatedAt int64\n}\n\n// Register records or replaces claimant's claim about pkgPath.\n//\n// Re-registering the same path overwrites that claimant's own previous claim\n// and nobody else's, so the ordinary \"I deployed a new commit\" flow is one call\n// with no read first. Height is preserved across an update: it dates the claim,\n// not the edit.\nfunc (r *Registry) Register(claimant address, height int64, pkgPath, repo, commit, dir, ref string) (*Claim, error) {\n\tif !ValidPkgPath(pkgPath) {\n\t\treturn nil, ErrInvalidPkgPath\n\t}\n\tif !ValidRepo(repo) {\n\t\treturn nil, ErrInvalidRepo\n\t}\n\tif !ValidCommit(commit) {\n\t\treturn nil, ErrInvalidCommit\n\t}\n\tif !ValidDir(dir) {\n\t\treturn nil, ErrInvalidDir\n\t}\n\tif !ValidRef(ref) {\n\t\treturn nil, ErrInvalidRef\n\t}\n\n\tp := r.Package(pkgPath)\n\tif p == nil {\n\t\tp = \u0026Package{PkgPath: pkgPath, claims: avl.NewTree()}\n\t\tr.packages.Set(pkgPath, p)\n\t}\n\n\tkey := claimant.String()\n\tc := \u0026Claim{\n\t\tPkgPath:   pkgPath,\n\t\tRepo:      repo,\n\t\tCommit:    commit,\n\t\tDir:       dir,\n\t\tRef:       ref,\n\t\tClaimant:  claimant,\n\t\tHeight:    height,\n\t\tUpdatedAt: height,\n\t}\n\tif prev := p.Claim(claimant); prev != nil {\n\t\tc.Height = prev.Height\n\t} else {\n\t\tif p.claims.Size() \u003e= MaxClaimants {\n\t\t\treturn nil, ErrTooManyClaimants\n\t\t}\n\t\tr.claims++\n\t}\n\tp.claims.Set(key, c)\n\treturn c, nil\n}\n\n// Withdraw removes claimant's own claim about pkgPath. A claimant can always\n// take back what they said; nobody can remove anyone else's.\nfunc (r *Registry) Withdraw(claimant address, pkgPath string) error {\n\tp := r.Package(pkgPath)\n\tif p == nil {\n\t\treturn ErrClaimNotFound\n\t}\n\tif _, removed := p.claims.Remove(claimant.String()); !removed {\n\t\treturn ErrClaimNotFound\n\t}\n\tr.claims--\n\tif p.claims.Size() == 0 {\n\t\tr.packages.Remove(pkgPath)\n\t}\n\treturn nil\n}\n\n// Package returns every claim about a path, or nil.\nfunc (r *Registry) Package(pkgPath string) *Package {\n\tv := r.packages.Get(pkgPath)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Package)\n}\n\n// Size is the number of package paths carrying at least one claim.\nfunc (r *Registry) Size() int { return r.packages.Size() }\n\n// Claims is the total number of claims across every path.\nfunc (r *Registry) Claims() int { return r.claims }\n\n// IteratePackages walks paths in lexical order, which groups a namespace's\n// packages together without needing a second index. The callback returns true\n// to STOP, following avl's own convention rather than inverting it here.\nfunc (r *Registry) IteratePackages(offset, count int, cb func(*Package) bool) {\n\tr.packages.IterateByOffset(offset, count, func(_ string, v any) bool {\n\t\treturn cb(v.(*Package))\n\t})\n}\n\n// IterateNamespace walks every claimed path under \"\u003cdomain\u003e/\u003ckind\u003e/\u003cns\u003e/\".\nfunc (r *Registry) IterateNamespace(domain, kind, ns string, cb func(*Package) bool) {\n\tprefix := domain + \"/\" + kind + \"/\" + ns + \"/\"\n\tr.packages.Iterate(prefix, \"\", func(k string, v any) bool {\n\t\tif !strings.HasPrefix(k, prefix) {\n\t\t\treturn true // past the prefix: stop\n\t\t}\n\t\treturn cb(v.(*Package))\n\t})\n}\n\n// Claim returns claimant's claim about this package, or nil.\nfunc (p *Package) Claim(claimant address) *Claim {\n\tv := p.claims.Get(claimant.String())\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Claim)\n}\n\n// Count is how many addresses have claimed this package.\nfunc (p *Package) Count() int { return p.claims.Size() }\n\n// IterateClaims walks the claims in claimant-address order. Order is not\n// significance: a caller that wants the owner's claim first must ask OwnedBy,\n// because the registry has no opinion about which claim is true.\nfunc (p *Package) IterateClaims(cb func(*Claim) bool) {\n\tp.claims.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\treturn cb(v.(*Claim))\n\t})\n}\n\n// OwnedBy reports whether c comes from the party that controls the package\n// path's namespace: either the address whose own namespace it is, or whoever\n// resolve says holds the registered name.\n//\n// resolve maps a namespace name to the address holding it and whether that name\n// is held at all. It is a parameter rather than an import because this package\n// stays pure: the realm supplies r/sys/users, and a test supplies a table.\n//\n// This is the one label in the whole design that is derived rather than\n// declared, so it is computed here and never stored. A name can be transferred;\n// a stored answer would age into a lie of exactly the kind this package exists\n// to avoid.\nfunc (c *Claim) OwnedBy(resolve func(name string) (address, bool)) bool {\n\t_, _, ns, _, ok := SplitPkgPath(c.PkgPath)\n\tif !ok {\n\t\treturn false\n\t}\n\tif AddressNamespace(ns) {\n\t\treturn ns == c.Claimant.String()\n\t}\n\tif resolve == nil {\n\t\treturn false\n\t}\n\taddr, held := resolve(ns)\n\treturn held \u0026\u0026 addr == c.Claimant\n}\n\n// SourceURL builds a browsable link to the claimed source: the commit, plus the\n// directory when the package is not at the repository root.\n//\n// GitHub's \"/tree/\u003ccommit\u003e/\u003cdir\u003e\" layout is also GitLab's, Gitea's, Forgejo's\n// and Codeberg's, so one construction covers every forge this registry is\n// likely to meet. It is a convenience, not a promise the link resolves: the\n// repository may be gone, private or renamed since the claim was made, which is\n// itself something a verifier reports rather than something a realm can know.\nfunc (c *Claim) SourceURL() string {\n\tu := strings.TrimSuffix(c.Repo, \"/\") + \"/tree/\" + c.Commit\n\tif c.Dir != \"\" {\n\t\tu += \"/\" + c.Dir\n\t}\n\treturn u\n}\n"},{"name":"registry_test.gno","body":"package gnopm\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst pkgA = \"gno.land/p/moul/md/v1\"\n\nfunc TestRegisterAndRead(t *testing.T) {\n\tr := New()\n\tuassert.Equal(t, 0, r.Size())\n\tuassert.Equal(t, 0, r.Claims())\n\n\tc, err := r.Register(alice, 100, pkgA, \"https://github.com/moul/gno-contracts\", sha1Zero, \"p/moul/md\", \"refs/heads/main\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, pkgA, c.PkgPath)\n\tuassert.Equal(t, int64(100), c.Height)\n\tuassert.Equal(t, int64(100), c.UpdatedAt)\n\tuassert.Equal(t, 1, r.Size())\n\tuassert.Equal(t, 1, r.Claims())\n\n\tp := r.Package(pkgA)\n\tuassert.True(t, p != nil, \"package exists\")\n\tuassert.Equal(t, 1, p.Count())\n\tuassert.True(t, p.Claim(alice) != nil, \"alice's claim is there\")\n\tuassert.True(t, p.Claim(bob) == nil, \"bob has not claimed\")\n\tuassert.True(t, r.Package(\"gno.land/p/moul/nope/v0\") == nil, \"unclaimed path is nil\")\n}\n\n// A claimant re-registering must move their own commit and nothing else, and\n// must not restart the clock: Height dates the claim, UpdatedAt dates the edit,\n// and telling them apart is how a reader spots a claim nobody has touched since\n// the first deploy.\nfunc TestReregisterUpdatesInPlace(t *testing.T) {\n\tr := New()\n\tr.Register(alice, 100, pkgA, \"https://github.com/moul/gno-contracts\", sha1Zero, \"p/moul/md\", \"\")\n\tc, err := r.Register(alice, 250, pkgA, \"https://github.com/moul/gno-contracts\", sha1One, \"p/moul/md\", \"refs/tags/v1\")\n\tuassert.NoError(t, err)\n\n\tuassert.Equal(t, sha1One, c.Commit, \"commit moved\")\n\tuassert.Equal(t, \"refs/tags/v1\", c.Ref, \"ref moved\")\n\tuassert.Equal(t, int64(100), c.Height, \"height still dates the original claim\")\n\tuassert.Equal(t, int64(250), c.UpdatedAt, \"updated at dates the edit\")\n\tuassert.Equal(t, 1, r.Claims(), \"still one claim, not two\")\n\tuassert.Equal(t, 1, r.Package(pkgA).Count())\n}\n\n// Open but tagged: a second address may claim the same path. The registry has\n// no opinion about which is true, and storing both is the point.\nfunc TestSeveralClaimantsCoexist(t *testing.T) {\n\tr := New()\n\tr.Register(alice, 100, pkgA, \"https://github.com/moul/gno-contracts\", sha1Zero, \"p/moul/md\", \"\")\n\tr.Register(bob, 110, pkgA, \"https://github.com/someone/fork\", sha1One, \"md\", \"\")\n\n\tp := r.Package(pkgA)\n\tuassert.Equal(t, 2, p.Count())\n\tuassert.Equal(t, 2, r.Claims())\n\tuassert.Equal(t, 1, r.Size(), \"still one package path\")\n\tuassert.Equal(t, sha1Zero, p.Claim(alice).Commit)\n\tuassert.Equal(t, sha1One, p.Claim(bob).Commit)\n}\n\nfunc TestMaxClaimants(t *testing.T) {\n\tr := New()\n\t// Fill the path to the cap with distinct claimants.\n\tbase := \"g1ubwjz3jmrjwmpuvrsjzgy5qkxf5wrgphzmd2t\"\n\tsuffix := \"023456789acdefgh\"\n\tfor i := 0; i \u003c MaxClaimants; i++ {\n\t\ta := address(base + string(suffix[i]))\n\t\t_, err := r.Register(a, int64(100+i), pkgA, \"https://example.com/x\", sha1Zero, \"\", \"\")\n\t\tuassert.NoError(t, err, \"claimant within the cap\")\n\t}\n\tuassert.Equal(t, MaxClaimants, r.Package(pkgA).Count())\n\n\t_, err := r.Register(carol, 999, pkgA, \"https://example.com/x\", sha1Zero, \"\", \"\")\n\tuassert.ErrorIs(t, err, ErrTooManyClaimants, \"one past the cap\")\n\n\t// An address already at the cap can still update: the cap bounds how many\n\t// claimants a path carries, never how often one of them corrects itself.\n\texisting := address(base + string(suffix[0]))\n\t_, err = r.Register(existing, 999, pkgA, \"https://example.com/x\", sha1One, \"\", \"\")\n\tuassert.NoError(t, err, \"an existing claimant updates at the cap\")\n}\n\nfunc TestWithdraw(t *testing.T) {\n\tr := New()\n\tr.Register(alice, 100, pkgA, \"https://example.com/x\", sha1Zero, \"\", \"\")\n\tr.Register(bob, 101, pkgA, \"https://example.com/y\", sha1One, \"\", \"\")\n\n\tuassert.ErrorIs(t, r.Withdraw(carol, pkgA), ErrClaimNotFound, \"withdrawing what you never said\")\n\tuassert.ErrorIs(t, r.Withdraw(alice, \"gno.land/p/moul/nope/v0\"), ErrClaimNotFound, \"unknown path\")\n\n\tuassert.NoError(t, r.Withdraw(alice, pkgA))\n\tuassert.Equal(t, 1, r.Claims())\n\tuassert.Equal(t, 1, r.Size(), \"bob's claim keeps the path alive\")\n\tuassert.True(t, r.Package(pkgA).Claim(alice) == nil, \"alice is gone\")\n\tuassert.True(t, r.Package(pkgA).Claim(bob) != nil, \"bob is untouched\")\n\n\tuassert.NoError(t, r.Withdraw(bob, pkgA))\n\tuassert.Equal(t, 0, r.Claims())\n\tuassert.Equal(t, 0, r.Size(), \"the last withdrawal removes the path\")\n\tuassert.True(t, r.Package(pkgA) == nil)\n}\n\nfunc TestRegisterRejectsInvalidInput(t *testing.T) {\n\tgood := func() (string, string, string, string, string) {\n\t\treturn pkgA, \"https://github.com/moul/gno-contracts\", sha1Zero, \"p/moul/md\", \"refs/heads/main\"\n\t}\n\tcases := []struct {\n\t\tname string\n\t\tmut  func(p, repo, commit, dir, ref *string)\n\t\twant error\n\t}{\n\t\t{\"bad path\", func(p, _, _, _, _ *string) { *p = \"nonsense\" }, ErrInvalidPkgPath},\n\t\t{\"bad repo scheme\", func(_, repo, _, _, _ *string) { *repo = \"javascript:alert(1)\" }, ErrInvalidRepo},\n\t\t{\"abbreviated commit\", func(_, _, c, _, _ *string) { *c = \"0123456\" }, ErrInvalidCommit},\n\t\t{\"absolute dir\", func(_, _, _, d, _ *string) { *d = \"/etc\" }, ErrInvalidDir},\n\t\t{\"unqualified ref\", func(_, _, _, _, rf *string) { *rf = \"main\" }, ErrInvalidRef},\n\t}\n\tfor _, tc := range cases {\n\t\tr := New()\n\t\tp, repo, commit, dir, ref := good()\n\t\ttc.mut(\u0026p, \u0026repo, \u0026commit, \u0026dir, \u0026ref)\n\t\t_, err := r.Register(alice, 100, p, repo, commit, dir, ref)\n\t\tuassert.ErrorIs(t, err, tc.want, tc.name)\n\t\tuassert.Equal(t, 0, r.Claims(), tc.name+\": nothing stored\")\n\t}\n}\n\nfunc TestOwnedBy(t *testing.T) {\n\tnames := resolver(map[string]address{\"moul\": alice})\n\tr := New()\n\n\tc, _ := r.Register(alice, 100, pkgA, \"https://example.com/x\", sha1Zero, \"\", \"\")\n\tuassert.True(t, c.OwnedBy(names), \"the namespace holder claiming their own package\")\n\n\tc2, _ := r.Register(bob, 101, pkgA, \"https://example.com/y\", sha1One, \"\", \"\")\n\tuassert.False(t, c2.OwnedBy(names), \"a stranger claiming someone else's package\")\n\n\t// An address namespace belongs to that account with nothing registered, so\n\t// it resolves with no name lookup at all.\n\town := \"gno.land/r/\" + addrNS + \"/scratch/v0\"\n\tc3, err := r.Register(address(addrNS), 102, own, \"https://example.com/z\", sha1Zero, \"\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.True(t, c3.OwnedBy(nil), \"an address namespace needs no resolver\")\n\n\tc4, _ := r.Register(bob, 103, own, \"https://example.com/w\", sha1One, \"\", \"\")\n\tuassert.False(t, c4.OwnedBy(nil), \"a stranger in someone's address namespace\")\n\n\t// An unregistered name is held by nobody, so nobody owns it.\n\tother := \"gno.land/p/nobody/thing/v0\"\n\tc5, _ := r.Register(alice, 104, other, \"https://example.com/v\", sha1Zero, \"\", \"\")\n\tuassert.False(t, c5.OwnedBy(names), \"an unheld namespace is owned by no one\")\n\tuassert.False(t, c5.OwnedBy(nil), \"and a nil resolver never invents ownership\")\n\n\t// A resolver may return an address AND report the name as not held: that is\n\t// what r/sys/users does for a name whose record survives but is no longer\n\t// current. The address matching is not enough, the name has to still be\n\t// held, and dropping the second half of that test is a silent promotion of\n\t// a stranger's claim.\n\tstale := func(string) (address, bool) { return alice, false }\n\tuassert.False(t, c.OwnedBy(stale), \"a resolved but unheld name confers nothing\")\n}\n\nfunc TestSourceURL(t *testing.T) {\n\tr := New()\n\tc, _ := r.Register(alice, 100, pkgA, \"https://github.com/moul/gno-contracts\", sha1Zero, \"p/moul/md\", \"\")\n\tuassert.Equal(t, \"https://github.com/moul/gno-contracts/tree/\"+sha1Zero+\"/p/moul/md\", c.SourceURL())\n\n\tc2, _ := r.Register(bob, 100, pkgA, \"https://github.com/x/y/\", sha1One, \"\", \"\")\n\tuassert.Equal(t, \"https://github.com/x/y/tree/\"+sha1One, c2.SourceURL(), \"root package, trailing slash trimmed\")\n}\n\nfunc TestIteration(t *testing.T) {\n\tr := New()\n\tpaths := []string{\n\t\t\"gno.land/p/alice/one/v0\",\n\t\t\"gno.land/p/moul/md/v1\",\n\t\t\"gno.land/p/moul/ulist/v0\",\n\t\t\"gno.land/r/moul/home\",\n\t\t\"gno.land/p/zed/last/v0\",\n\t}\n\tfor i, p := range paths {\n\t\t_, err := r.Register(alice, int64(100+i), p, \"https://example.com/x\", sha1Zero, \"\", \"\")\n\t\tuassert.NoError(t, err, p)\n\t}\n\n\tvar seen []string\n\tr.IteratePackages(0, 10, func(p *Package) bool {\n\t\tseen = append(seen, p.PkgPath)\n\t\treturn false\n\t})\n\tuassert.Equal(t, 5, len(seen))\n\tuassert.Equal(t, \"gno.land/p/alice/one/v0\", seen[0], \"lexical order\")\n\tuassert.Equal(t, \"gno.land/r/moul/home\", seen[4], \"r sorts after p\")\n\n\t// A namespace walk must stop at the prefix boundary rather than running to\n\t// the end of the tree: \"moul\" is followed by \"zed\" and by the r/ half.\n\tvar ns []string\n\tr.IterateNamespace(\"gno.land\", \"p\", \"moul\", func(p *Package) bool {\n\t\tns = append(ns, p.PkgPath)\n\t\treturn false\n\t})\n\tuassert.Equal(t, 2, len(ns), \"only p/moul\")\n\tuassert.Equal(t, \"gno.land/p/moul/md/v1\", ns[0])\n\tuassert.Equal(t, \"gno.land/p/moul/ulist/v0\", ns[1])\n\n\t// Stopping early stops.\n\tcount := 0\n\tr.IteratePackages(0, 10, func(p *Package) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tuassert.Equal(t, 1, count, \"returning true stops the walk\")\n}\n"},{"name":"validate.gno","body":"package gnopm\n\nimport \"strings\"\n\n// Size caps. Every string the chain stores is bounded: an unbounded field is an\n// unbounded storage deposit, and on gno.land the deposit is paid per byte by\n// whoever writes it.\nconst (\n\tMaxPkgPathLen = 256\n\tMaxRepoLen    = 512\n\tMaxDirLen     = 256\n\tMaxRefLen     = 255 // git's own limit for a single ref name\n\n\t// MaxClaimants bounds how many addresses may claim one package path.\n\t// Unbounded, it is a spam surface: one path with ten thousand claims is a\n\t// Render that never returns and a listing nobody can read.\n\tMaxClaimants = 16\n)\n\n// ValidCommit reports whether s is a git object id: 40 (SHA-1) or 64 (SHA-256)\n// lowercase hex characters. Case is fixed so the same object always produces\n// the same stored bytes, and so a verifier comparing two claims compares two\n// comparable strings.\nfunc ValidCommit(s string) bool {\n\tif len(s) != 40 \u0026\u0026 len(s) != 64 {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif (c \u003c '0' || c \u003e '9') \u0026\u0026 (c \u003c 'a' || c \u003e 'f') {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidRepo reports whether s is a repository URL this registry accepts.\n//\n// Deliberately narrow: \"https://\" only, a host, and a path. Not a taste\n// judgement about git transports, a safety one. Whatever is stored here is\n// eventually rendered as a link by this realm, by gnoweb and by every explorer\n// that reads the registry, and the set of schemes that are safe to hand a\n// browser is exactly one. \"javascript:\", \"data:\" and \"file:\" are the attack;\n// \"git://\" and \"ssh://\" are merely unreachable from a web page, and a claimant\n// who needs one can point at the https mirror every forge already serves.\nfunc ValidRepo(s string) bool {\n\tif s == \"\" || len(s) \u003e MaxRepoLen {\n\t\treturn false\n\t}\n\tconst scheme = \"https://\"\n\tif !strings.HasPrefix(s, scheme) {\n\t\treturn false\n\t}\n\trest := s[len(scheme):]\n\tif rest == \"\" || strings.HasPrefix(rest, \"/\") {\n\t\treturn false\n\t}\n\t// A host must be present and must not be a userinfo trick\n\t// (\"https://github.com@evil.example/x\" fetches from evil.example while\n\t// reading as GitHub).\n\tslash := strings.IndexByte(rest, '/')\n\thost := rest\n\tif slash \u003e= 0 {\n\t\thost = rest[:slash]\n\t}\n\tif host == \"\" || strings.ContainsAny(host, \"@:\") {\n\t\treturn false\n\t}\n\tif !strings.Contains(host, \".\") {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif !urlByteOK(s[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn !strings.Contains(s, \"..\")\n}\n\n// urlByteOK is an allowlist, not a denylist: the printable ASCII that appears\n// in a real repository URL. Everything else, control characters and the bidi\n// overrides in particular, is refused rather than escaped, because a field that\n// can only hold safe bytes needs no escaping at any of its render sites.\nfunc urlByteOK(c byte) bool {\n\tswitch {\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= 'A' \u0026\u0026 c \u003c= 'Z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn true\n\t}\n\tswitch c {\n\tcase '-', '.', '_', '~', ':', '/', '%', '+':\n\t\treturn true\n\t}\n\treturn false\n}\n\n// ValidDir reports whether s names the subdirectory of the repository holding\n// the package. Empty means the repository root, which is the common case for a\n// single-package repo and must stay expressible.\nfunc ValidDir(s string) bool {\n\tif s == \"\" {\n\t\treturn true\n\t}\n\tif len(s) \u003e MaxDirLen {\n\t\treturn false\n\t}\n\tif strings.HasPrefix(s, \"/\") || strings.HasSuffix(s, \"/\") {\n\t\treturn false\n\t}\n\tfor _, p := range strings.Split(s, \"/\") {\n\t\tif p == \"\" || p == \".\" || p == \"..\" {\n\t\t\treturn false\n\t\t}\n\t\tfor i := 0; i \u003c len(p); i++ {\n\t\t\tif !pathByteOK(p[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc pathByteOK(c byte) bool {\n\tswitch {\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= 'A' \u0026\u0026 c \u003c= 'Z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn true\n\t}\n\tswitch c {\n\tcase '-', '.', '_':\n\t\treturn true\n\t}\n\treturn false\n}\n\n// ValidRef reports whether s is a fully-qualified git ref, or empty.\n//\n// The ref is optional and is never the thing that is verified: a ref moves, a\n// commit does not. It is recorded so a reader can tell a claim pinned to a\n// released tag from one pinned to a commit on nobody's branch, and so a\n// verifier can check the claimed commit is still reachable from it rather than\n// dangling behind a force-push.\nfunc ValidRef(s string) bool {\n\tif s == \"\" {\n\t\treturn true\n\t}\n\tif len(s) \u003e MaxRefLen || !strings.HasPrefix(s, \"refs/\") {\n\t\treturn false\n\t}\n\tif strings.Contains(s, \"..\") || strings.Contains(s, \"@{\") {\n\t\treturn false\n\t}\n\tif strings.HasSuffix(s, \"/\") || strings.HasSuffix(s, \".\") {\n\t\treturn false\n\t}\n\tparts := strings.Split(s, \"/\")\n\tif len(parts) \u003c 2 {\n\t\treturn false\n\t}\n\tfor _, p := range parts {\n\t\tif p == \"\" || p == \"@\" || strings.HasPrefix(p, \".\") || strings.HasSuffix(p, \".lock\") {\n\t\t\treturn false\n\t\t}\n\t\tfor i := 0; i \u003c len(p); i++ {\n\t\t\tif !refByteOK(p[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n// refByteOK is an allowlist, and deliberately narrower than git's own rule.\n//\n// git rejects a handful of metacharacters and permits everything else, which\n// leaves a ref free to contain a backtick, a pipe or a bracket. Every other\n// field here is an allowlist precisely so that no consumer has to escape\n// anything, and one denylist field would undo that for all of them: a ref\n// carrying a pipe breaks out of a markdown table cell, and one carrying a\n// backtick breaks out of the inline-code span a renderer wraps it in.\n//\n// The cost is refs nobody writes. What stays expressible is every ref anyone\n// actually has: alphanumerics, and the four separators git tooling puts in a\n// name.\nfunc refByteOK(c byte) bool {\n\tswitch {\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= 'A' \u0026\u0026 c \u003c= 'Z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn true\n\t}\n\tswitch c {\n\tcase '-', '.', '_', '/', '+':\n\t\treturn true\n\t}\n\treturn false\n}\n"},{"name":"validate_test.gno","body":"package gnopm\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestValidCommit(t *testing.T) {\n\tsha1 := strings.Repeat(\"a\", 40)\n\tsha256 := strings.Repeat(\"0\", 64)\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"sha1\", sha1, true},\n\t\t{\"sha256\", sha256, true},\n\t\t{\"mixed hex\", \"0123456789abcdef0123456789abcdef01234567\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"too short\", strings.Repeat(\"a\", 39), false},\n\t\t{\"between the two lengths\", strings.Repeat(\"a\", 41), false},\n\t\t{\"uppercase\", strings.Repeat(\"A\", 40), false},\n\t\t{\"non hex\", strings.Repeat(\"g\", 40), false},\n\t\t{\"abbreviated\", \"0123456\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidCommit(tc.in), tc.name)\n\t}\n}\n\nfunc TestValidRepo(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"github\", \"https://github.com/gnolang/gno\", true},\n\t\t{\"no path\", \"https://example.com\", true},\n\t\t{\"trailing slash\", \"https://example.com/x/\", true},\n\t\t{\"port is not a host character here\", \"https://example.com:8443/x\", false},\n\n\t\t{\"empty\", \"\", false},\n\t\t{\"http\", \"http://github.com/gnolang/gno\", false},\n\t\t{\"git scheme\", \"git://github.com/gnolang/gno\", false},\n\t\t{\"ssh scheme\", \"ssh://git@github.com/gnolang/gno\", false},\n\t\t{\"javascript\", \"javascript:alert(1)\", false},\n\t\t{\"data url\", \"data:text/html,\u003cscript\u003e\", false},\n\t\t{\"scheme relative\", \"//github.com/gnolang/gno\", false},\n\t\t{\"no host\", \"https:///gnolang/gno\", false},\n\t\t{\"bare host with no dot\", \"https://localhost/x\", false},\n\t\t{\"userinfo disguise\", \"https://github.com@evil.example/gnolang/gno\", false},\n\t\t{\"parent traversal\", \"https://example.com/../x\", false},\n\t\t{\"space\", \"https://example.com/a b\", false},\n\t\t{\"markdown link break-out\", \"https://example.com/a)[x](y\", false},\n\t\t{\"newline\", \"https://example.com/a\\nb\", false},\n\t\t{\"bidi override\", \"https://example.com/a‮b\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidRepo(tc.in), tc.name)\n\t}\n}\n\nfunc TestValidDir(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"repo root\", \"\", true},\n\t\t{\"one element\", \"examples\", true},\n\t\t{\"nested\", \"examples/gno.land/p/nt/avl\", true},\n\t\t{\"dots in a name\", \"p/moul.io/x\", true},\n\n\t\t{\"absolute\", \"/examples\", false},\n\t\t{\"trailing slash\", \"examples/\", false},\n\t\t{\"empty element\", \"a//b\", false},\n\t\t{\"dot element\", \"a/./b\", false},\n\t\t{\"parent traversal\", \"a/../b\", false},\n\t\t{\"backslash\", \"a\\\\b\", false},\n\t\t{\"space\", \"a b\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidDir(tc.in), tc.name)\n\t}\n}\n\nfunc TestValidRef(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"absent is legal\", \"\", true},\n\t\t{\"branch\", \"refs/heads/main\", true},\n\t\t{\"tag\", \"refs/tags/v1.2.0\", true},\n\n\t\t{\"unqualified branch\", \"main\", false},\n\t\t{\"double dot\", \"refs/heads/a..b\", false},\n\t\t{\"reflog syntax\", \"refs/heads/a@{1}\", false},\n\t\t{\"trailing slash\", \"refs/heads/\", false},\n\t\t{\"lock suffix\", \"refs/heads/main.lock\", false},\n\t\t{\"leading dot\", \"refs/heads/.hidden\", false},\n\t\t{\"caret\", \"refs/heads/a^b\", false},\n\t\t{\"space\", \"refs/heads/a b\", false},\n\n\t\t// Narrower than git on purpose: these are legal ref names that would\n\t\t// break out of a markdown table cell or an inline-code span, and every\n\t\t// other field in this package is an allowlist so that no consumer has\n\t\t// to escape anything.\n\t\t{\"pipe breaks a table cell\", \"refs/heads/a|b\", false},\n\t\t{\"backtick breaks a code span\", \"refs/heads/a`b\", false},\n\t\t{\"brackets open a link\", \"refs/heads/a[b]c\", false},\n\t\t{\"parens close a link\", \"refs/heads/a(b)c\", false},\n\t\t{\"hash opens a heading\", \"refs/heads/a#b\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidRef(tc.in), tc.name)\n\t}\n}\n"}]},"send":"","max_deposit":"17000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"grants","path":"gno.land/p/moul/grants/v0","files":[{"name":"README.md","body":"# grants\n\nA grant program governed by a member set: anyone may ask the board for money, the members\nvote in the open, and the money leaves in tranches that each have to be earned by producing\na proof the members accept.\n\nThe package is **pure**. It holds no coins, calls no banker, reads no chain state, and\nimports nothing from `chain`: the caller supplies the acting address, the block height and\nthe current treasury balance, and the caller executes the transfer. That is what makes the\nwhole state machine unit-testable without a node, and what makes the realm on top thin\nenough to read in one screen.\n\nLive: [`r/moul/grant/v0`](/r/moul/grant/v0), a personal board. A multi-member program is\nanother realm of the same size over this same package.\n\n## Three layers\n\n| Type | What it owns |\n|---|---|\n| `Board` | members, requests, ballots, proofs. Every rule and every tally. |\n| `Program` | a `Board` plus the money around it: donations in, payments out, the denom. |\n| `Renderer` | the three markdown pages, configured by a struct literal. |\n\nA realm holds one `Program`, builds a `Renderer` inside `Render`, and does nothing else but\nturn callers into addresses and execute the `Payment` it is handed back.\n\n## The lifecycle\n\n```\nSubmit ──▶ Pending ──vote──▶ Approved ──┬─▶ SubmitProof ──▶ Review ──┬─▶ Released ─┐\n             │                          │                            │             │\n             │                          │                            └─▶ Refused ──┘\n             │                          │                                (try again)\n             ├──vote──▶ Rejected        └─▶ every milestone released ──▶ Completed\n             └──Withdraw──▶ Withdrawn\n```\n\nA `Request` is a title, a body, and an ordered list of `Milestone`s, each with its own\namount. **Approving a request pays nothing**: it only makes the first milestone claimable.\nTo get a tranche the applicant submits a `Proof` (a URL, a hash, or plain text) and the\nmembers review *that specific proof*. A refused proof does not kill the grant, it closes\none `Attempt`; the applicant submits another. Every attempt, accepted or not, stays on the\nrecord with the ballots that decided it.\n\n## Who may vote, and how many it takes\n\nEvery member, once, per decision. There is no changing your mind: that is the price of\nevery ballot being a permanent public statement, stored with its voter, its reason and the\nheight it was cast at.\n\n**The party a decision is about is excluded.** An applicant does not vote on their own\ngrant, and the subject of a membership change does not vote on their own membership. The\nbar is a majority of the addresses actually *eligible*, recomputed on every ballot, so a\nmember who applies shrinks the room rather than packing it, and a board that grows\nmid-vote raises its own bar.\n\nA **one-member board is a legitimate configuration**, and its majority is one: that is what\na personal program looks like. It still cannot self-grant, because a sole member applying\nleaves zero eligible voters and `Majority` returns an unreachable 1 rather than 0.\n\n`Standing` counts only ballots from addresses that are members **right now**; decisions use\nit. `Request.Tally` counts the raw record. The two differ exactly when a voter has since\nbeen removed from the board: their ballot stays readable and stops carrying weight.\n\n## Asking for someone else\n\n`SubmitFor(applicant, beneficiary, reason, …)` files a request whose tranches pay an address\nother than the one that filed it. `Submit` is the same call with the two addresses equal.\n\nThe split is not a convenience. **An account with nothing in it cannot pay the gas to ask for\nits first coins**, so on a board whose purpose is to fund empty accounts, someone else filing\nis the only path that works. Two rules follow from that, and both are in the library:\n\n- **The reason is required** when the payee is someone else. Nothing verifies it; it is a\n  claim by the applicant, and the renderer prints it under its own heading so a member can\n  check it before voting.\n- **Both addresses are excluded from voting**, on the request and on every proof. A member\n  paid by a request a friend filed is the same conflict of interest with one address in\n  between. `Request.Excludes` is the predicate, `Board.Eligible` recounts over it, and the\n  majority moves with it.\n\nEither the applicant or the beneficiary may `SubmitProof`: the payee may not be able to\ntransact until the first tranche lands, and once they can, they have to be able to show\ntheir own work. `Request.Payee()` is who a released tranche pays, and it is what the\n`Payment` handed back to the realm carries.\n\n## Membership is a request like any other\n\n`SubmitMemberChange` files a `KindMember` request. It asks for no money, and when it\ncarries it executes immediately, going straight to `Completed`. Only a member may file one:\nopening a grant board's own composition to anyone with a keypair is how it gets captured.\nThe last member cannot be removed.\n\n## The money: `Program`\n\n```go\np := grants.NewProgram(\"ugnot\", alice, bob, carol)\n\np.Fund(donor, 5000, height)                 // put a name on a transfer that already happened\nr, _ := p.Apply(dave, \"Port the thing\", \"why it matters\", \"design:100,ship:400\", height)\n\np.Board.Vote(alice, r.ID, true, \"cheap for what it tells us\", height)\np.Board.Vote(bob, r.ID, true, \"agreed\", height)          // majority of three: approved\n\np.Board.SubmitProof(dave, r.ID, 0, grants.Proof{Kind: \"url\", Ref: \"https://…\", Height: height})\np.Review(alice, r.ID, 0, true, \"merged, I reviewed it\", height, balance)\nout, pay, err := p.Review(carol, r.ID, 0, true, \"confirmed\", height, balance)\nif pay != nil {\n    // out == grants.Accepted. Send pay.Amount to pay.To; it is already on the ledger.\n}\n```\n\n**The treasury is not escrowed.** `Committed()` is what approved-but-unreleased milestones\nadd up to, `Available(balance)` is the balance minus that, and it **can go negative**. That\nis deliberate: a board that can only approve what it already holds cannot approve anything\nbefore a donor shows up.\n\nThe cost is that a release can come due against an empty treasury, so `Program.Review`\ntakes the balance and checks, *before recording anything*, whether this verdict would\nrelease a tranche it cannot cover. If so it returns `ErrUnderfunded` and changes nothing:\nno ballot, no release, no payment. A **refusal** is always free to record, because it costs\nthe treasury nothing. `Board.Decides` and `Board.ReviewDecides` expose the same preview for\nanything else that needs to check a precondition it cannot roll back.\n\n## The pages: `Renderer`\n\n`Renderer` serves the board at `\"\"`, one request at `request/\u003cid\u003e`, and the money trail at\n`ledger`. Everything program-specific is a field (`Title`, `Intro`, `Notes`, `Path`,\n`Link`, `Treasury`, `Balance`, `Footer`, and a `Note func(*Request) string` for per-request\ncallouts), so a realm's whole `Render` is a struct literal.\n\nBuild it **inside** `Render`, not in a realm global: `Note` is a func, and `Balance` has to\nbe read fresh on every call anyway. The five `ExampleRenderer*` tests pin every page of a\nboard mid-flight, so a change to any rule shows up as a diff in the markdown.\n\n**Escaping happens here, once.** Everything a caller typed goes through\n[`p/moul/kit/ui`](/p/moul/kit/ui/v0) and\n[`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0) on its way to the page, so a realm\nneither repeats it nor pre-escapes (escaping twice shows the backslashes). The bar differs\nby slot on purpose: a one-line slot (a title, a milestone name, a reason on a ballot) keeps\nnothing a caller typed as markup, while a prose slot (the body of an application, the note\non a proof) goes through `sanitize.Block`, which preserves inline links and emphasis because\na grant application whose link to the merged PR renders as literal text is a worse page.\nWhat `Block` still kills is everything structural, so a paragraph cannot leave its paragraph.\nThe realm's own `Title`, `Intro`, `Notes` and `Footer` are chrome, written by whoever\ndeployed it, and are emitted as-is.\n\n`TestEveryCallerSuppliedStringIsEscaped` drives one board through every caller-controlled\nslot and asserts no structural line of any page carries a live link, an image or a gnoweb\ntag. It asserts the dangerous sequence is dead, never the exact escaped bytes: those belong\nto the sanitizer and change when it changes.\n\n## What this deliberately does not do\n\nNo weights, no delegation, no quadratic anything, no deadline. A request with no majority\neither way stays `Pending` until someone breaks the tie or the applicant withdraws it.\nThose are all reasonable things to build on top; none is needed to show the shape.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/grants/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/grants/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/grants/v0\"\ngno = \"0.9\"\n"},{"name":"grants.gno","body":"// Package grants is a grant board governed by a member set: anyone may ask\n// the board for money, the members vote in the open, and the money leaves in\n// tranches that each have to be earned by producing a proof the members\n// accept.\n//\n// The package is pure. It holds no coins, reads no chain state and imports\n// nothing from `chain`: the caller supplies the acting address and the block\n// height, and the caller performs the transfer. That is what makes the whole\n// state machine unit-testable without a node, and it is what lets the same\n// board be driven by a realm, by a test, or by a different payment rail.\n// Live board: gno.land/r/moul/grant/v0.\n//\n// # The shape of a grant\n//\n// A Request is a title, a body, and an ordered list of Milestones, each with\n// its own amount. Approving a request does not pay anything: it only makes the\n// first milestone claimable. To get a tranche the applicant submits a Proof\n// (a URL, a hash, or plain text) and the members review that specific proof.\n// A rejected proof does not kill the grant, it just closes one Attempt; the\n// applicant submits another. Every attempt, accepted or not, stays on the\n// record with the ballots that decided it.\n//\n// # Asking for someone else\n//\n// A request has an applicant, who files it and answers for it, and a\n// beneficiary, who gets paid. SubmitFor separates the two and takes a reason\n// for the detour; Submit is the common case where they are the same address.\n//\n// The split is not a convenience. An account with nothing in it cannot pay the\n// gas to ask for its first coins, so on a board whose whole purpose is to fund\n// empty accounts, \"someone else files it\" is the ONLY path that works. Both\n// addresses are then barred from voting on the request, and either of them may\n// submit a proof, for the same reason: the payee may not be able to transact\n// at all until the first tranche lands.\n//\n// # Who may vote\n//\n// Every member, once, per decision. The party the decision is about is\n// excluded: the applicant does not vote on their own grant, and the subject of\n// a membership change does not vote on their own membership. The bar is a\n// majority of the addresses that are actually eligible, recomputed on each\n// ballot, so a board that grows mid-vote raises its own bar.\n//\n// # What this deliberately does not do\n//\n// No weights, no delegation, no quadratic anything, no deadline. A request\n// with no majority either way simply stays Pending until someone breaks the\n// tie or the applicant withdraws it. Those are all reasonable things to add on\n// top; none of them is needed to show the shape.\npackage grants\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Errors returned by the mutators. They are sentinels so a realm can map them\n// onto its own messages, or simply panic with them.\nvar (\n\tErrNotMember     = errors.New(\"grants: not a board member\")\n\tErrNotApplicant  = errors.New(\"grants: only the applicant may do this\")\n\tErrNoRequest     = errors.New(\"grants: no such request\")\n\tErrNoMilestone   = errors.New(\"grants: no such milestone\")\n\tErrNotPending    = errors.New(\"grants: the request is not pending\")\n\tErrNotApproved   = errors.New(\"grants: the request is not approved\")\n\tErrAlreadyVoted  = errors.New(\"grants: this member already voted\")\n\tErrConflict      = errors.New(\"grants: the party a decision is about may not vote on it\")\n\tErrOutOfOrder    = errors.New(\"grants: milestones are claimed in order\")\n\tErrProofPending  = errors.New(\"grants: a proof is already under review\")\n\tErrNoProof       = errors.New(\"grants: no proof is under review\")\n\tErrBadTitle      = errors.New(\"grants: title must be 1 to 100 characters\")\n\tErrBadBody       = errors.New(\"grants: body must be at most 2000 characters\")\n\tErrBadMilestones = errors.New(\"grants: a grant needs 1 to 10 milestones\")\n\tErrBadAmount     = errors.New(\"grants: every milestone must ask for a positive amount\")\n\tErrBadProof      = errors.New(\"grants: proof kind must be url, hash or text, with a reference\")\n\tErrBadReason     = errors.New(\"grants: reason must be at most 300 characters\")\n\tErrNeedReason    = errors.New(\"grants: filing for someone else needs a reason\")\n\tErrBadAddress    = errors.New(\"grants: invalid address\")\n\tErrIsMember      = errors.New(\"grants: already a board member\")\n\tErrLastMember    = errors.New(\"grants: the last member cannot be removed\")\n\tErrNothingSent   = errors.New(\"grants: a donation must be a positive amount\")\n\tErrUnderfunded   = errors.New(\"grants: the treasury cannot cover this tranche\")\n\tErrBadSpec       = errors.New(\"grants: milestones must read \\\"title:amount,title:amount\\\"\")\n)\n\n// Limits every input is checked against. Exported so a UI can pre-validate.\nconst (\n\tMaxTitle      = 100\n\tMaxBody       = 2000\n\tMaxReason     = 300\n\tMaxRef        = 300\n\tMaxNote       = 500\n\tMaxMilestones = 10\n)\n\n// Status is where a request sits in its lifecycle.\ntype Status int\n\nconst (\n\tPending   Status = iota // open for member ballots\n\tApproved                // carried; milestones can be earned\n\tRejected                // a majority voted no\n\tCompleted               // every milestone released\n\tWithdrawn               // the applicant pulled it before a decision\n)\n\nfunc (s Status) String() string {\n\tswitch s {\n\tcase Pending:\n\t\treturn \"pending\"\n\tcase Approved:\n\t\treturn \"approved\"\n\tcase Rejected:\n\t\treturn \"rejected\"\n\tcase Completed:\n\t\treturn \"completed\"\n\tcase Withdrawn:\n\t\treturn \"withdrawn\"\n\t}\n\treturn \"unknown\"\n}\n\n// Kind says what carrying a request actually does.\ntype Kind int\n\nconst (\n\tKindGrant  Kind = iota // pays out, milestone by milestone\n\tKindMember             // adds or removes a board member, immediately\n)\n\nfunc (k Kind) String() string {\n\tif k == KindMember {\n\t\treturn \"membership\"\n\t}\n\treturn \"grant\"\n}\n\n// Outcome is the result of one proof attempt.\ntype Outcome int\n\nconst (\n\tUnderReview Outcome = iota // members are still voting on this proof\n\tAccepted                   // the tranche is earned\n\tRefused                    // this proof did not convince; another may\n)\n\nfunc (o Outcome) String() string {\n\tswitch o {\n\tcase Accepted:\n\t\treturn \"accepted\"\n\tcase Refused:\n\t\treturn \"refused\"\n\t}\n\treturn \"under review\"\n}\n\n// Ballot is one member's vote on one decision, with the reason they gave.\n// Reasons are not optional decoration: they are the only part of a vote that\n// tells an applicant what to fix.\ntype Ballot struct {\n\tVoter   address\n\tApprove bool\n\tReason  string\n\tHeight  int64\n}\n\n// Proof is the evidence an applicant offers for one milestone. Kind is \"url\",\n// \"hash\" or \"text\"; the board decides what it is worth.\ntype Proof struct {\n\tKind   string\n\tRef    string\n\tNote   string\n\tHeight int64\n}\n\n// Attempt is one proof and the review it got. A milestone keeps every attempt,\n// so a refused proof and the reasons it was refused stay readable forever.\ntype Attempt struct {\n\tProof    Proof\n\tReviews  []Ballot\n\tOutcome  Outcome\n\tClosedAt int64\n}\n\n// Milestone is one tranche of a grant: what has to be shown, and what it pays.\ntype Milestone struct {\n\tTitle      string\n\tAmount     int64 // in the smallest unit of whatever the realm pays in\n\tAttempts   []*Attempt\n\tReleased   bool\n\tReleasedAt int64\n}\n\n// Current returns the attempt still under review, or nil.\nfunc (m *Milestone) Current() *Attempt {\n\tif len(m.Attempts) == 0 {\n\t\treturn nil\n\t}\n\tlast := m.Attempts[len(m.Attempts)-1]\n\tif last.Outcome == UnderReview {\n\t\treturn last\n\t}\n\treturn nil\n}\n\n// Request is a grant application or a membership change.\ntype Request struct {\n\tID          int\n\tKind        Kind\n\tApplicant   address // who filed it and answers for it\n\tBeneficiary address // who gets paid; equal to Applicant on a self request\n\tReason      string  // why the applicant is asking on someone else's behalf\n\tTitle       string\n\tBody        string\n\tMilestones  []*Milestone\n\tSubject     address // KindMember only: the address being added or removed\n\tAdd         bool    // KindMember only: true adds, false removes\n\tVotes       []Ballot\n\tStatus      Status\n\tCreatedAt   int64\n\tDecidedAt   int64\n}\n\n// OnBehalf reports whether this grant was filed by one address for another.\nfunc (r *Request) OnBehalf() bool {\n\treturn r.Kind == KindGrant \u0026\u0026 r.Beneficiary != r.Applicant\n}\n\n// Payee is the address a released tranche pays. It is the beneficiary, which\n// is the applicant unless the request was filed for someone else.\nfunc (r *Request) Payee() address {\n\tif r.Beneficiary.IsValid() {\n\t\treturn r.Beneficiary\n\t}\n\treturn r.Applicant\n}\n\n// Total is the sum of every milestone, released or not.\nfunc (r *Request) Total() int64 {\n\tvar n int64\n\tfor _, m := range r.Milestones {\n\t\tn += m.Amount\n\t}\n\treturn n\n}\n\n// Paid is what the milestones released so far add up to.\nfunc (r *Request) Paid() int64 {\n\tvar n int64\n\tfor _, m := range r.Milestones {\n\t\tif m.Released {\n\t\t\tn += m.Amount\n\t\t}\n\t}\n\treturn n\n}\n\n// Outstanding is what an approved request can still cost the treasury. It is\n// zero for anything not approved, which is what makes it safe to sum across\n// the board as the committed amount.\nfunc (r *Request) Outstanding() int64 {\n\tif r.Status != Approved {\n\t\treturn 0\n\t}\n\treturn r.Total() - r.Paid()\n}\n\n// Next is the index of the first unreleased milestone, or -1 when the grant is\n// fully paid. Milestones are earned in order.\nfunc (r *Request) Next() int {\n\tfor i, m := range r.Milestones {\n\t\tif !m.Released {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n// Tally counts the ballots cast on the request itself.\nfunc (r *Request) Tally() (yes, no int) {\n\treturn count(r.Votes)\n}\n\n// BallotOf returns the member's ballot on the request, or nil.\nfunc (r *Request) BallotOf(voter address) *Ballot {\n\treturn find(r.Votes, voter)\n}\n\n// Excludes reports whether addr is barred from voting on this request because\n// the decision is about them.\n//\n// A grant excludes BOTH parties, not just the one who typed the transaction:\n// letting a member be paid by a request a friend filed for them is the same\n// conflict with one more step in it.\nfunc (r *Request) Excludes(addr address) bool {\n\tif r.Kind == KindMember {\n\t\treturn addr == r.Subject\n\t}\n\treturn addr == r.Applicant || addr == r.Payee()\n}\n\nfunc count(bs []Ballot) (yes, no int) {\n\tfor _, b := range bs {\n\t\tif b.Approve {\n\t\t\tyes++\n\t\t} else {\n\t\t\tno++\n\t\t}\n\t}\n\treturn yes, no\n}\n\nfunc find(bs []Ballot, voter address) *Ballot {\n\tfor i := range bs {\n\t\tif bs[i].Voter == voter {\n\t\t\treturn \u0026bs[i]\n\t\t}\n\t}\n\treturn nil\n}\n\n// Board is the whole state of one grant program: who decides, and what has\n// been asked of them.\ntype Board struct {\n\tmembers  *avl.Tree // address string -\u003e int64 join height\n\trequests *avl.Tree // zero-padded id -\u003e *Request\n\tnextID   int\n}\n\n// New returns a board whose founding members are the given addresses, all\n// recorded as having joined at height 0. Duplicates and invalid addresses are\n// skipped; a board with no members accepts no decisions until one is added, so\n// callers normally pass at least one.\nfunc New(founders ...address) *Board {\n\tb := \u0026Board{members: avl.NewTree(), requests: avl.NewTree(), nextID: 1}\n\tfor _, f := range founders {\n\t\tif f.IsValid() {\n\t\t\tb.members.Set(f.String(), int64(0))\n\t\t}\n\t}\n\treturn b\n}\n\n// IsMember reports whether addr sits on the board.\nfunc (b *Board) IsMember(addr address) bool { return b.members.Has(addr.String()) }\n\n// MemberCount is the number of addresses on the board.\nfunc (b *Board) MemberCount() int { return b.members.Size() }\n\n// Members lists the board in address order, which is stable across calls.\nfunc (b *Board) Members() []address {\n\tout := make([]address, 0, b.members.Size())\n\tb.members.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tout = append(out, address(k))\n\t\treturn false\n\t})\n\treturn out\n}\n\n// JoinedAt returns the height a member joined, or -1 for a non-member.\nfunc (b *Board) JoinedAt(addr address) int64 {\n\tv := b.members.Get(addr.String())\n\tif v == nil {\n\t\treturn -1\n\t}\n\treturn v.(int64)\n}\n\n// Eligible is how many members may vote on a request: everyone but the parties\n// the decision is about.\nfunc (b *Board) Eligible(r *Request) int {\n\tn := 0\n\tb.members.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tif !r.Excludes(address(k)) {\n\t\t\tn++\n\t\t}\n\t\treturn false\n\t})\n\treturn n\n}\n\n// Majority is the number of concurring ballots a decision on r needs. It is\n// recomputed on every ballot, so a board that changes size mid-vote moves its\n// own bar rather than freezing a stale one.\nfunc (b *Board) Majority(r *Request) int {\n\tn := b.Eligible(r)\n\tif n \u003c= 0 {\n\t\treturn 1 // an unreachable bar beats a bar of zero\n\t}\n\treturn n/2 + 1\n}\n\n// Get returns a request by id, or nil.\nfunc (b *Board) Get(id int) *Request {\n\tv := b.requests.Get(idKey(id))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Request)\n}\n\n// Size is the number of requests ever filed.\nfunc (b *Board) Size() int { return b.requests.Size() }\n\n// List returns every request in id order.\nfunc (b *Board) List() []*Request {\n\tout := make([]*Request, 0, b.requests.Size())\n\tb.requests.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tout = append(out, v.(*Request))\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Committed is what the treasury still owes on approved grants. A realm that\n// keeps its balance at or above this number can always pay a released tranche.\nfunc (b *Board) Committed() int64 {\n\tvar n int64\n\tb.requests.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tn += v.(*Request).Outstanding()\n\t\treturn false\n\t})\n\treturn n\n}\n\n// Disbursed is everything the board has ever released.\nfunc (b *Board) Disbursed() int64 {\n\tvar n int64\n\tb.requests.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tn += v.(*Request).Paid()\n\t\treturn false\n\t})\n\treturn n\n}\n\n// idKey pads an id so avl iteration is numeric, not lexicographic: unpadded\n// keys sort \"1\",\"10\",\"2\" and every listing would lose its order past nine\n// entries. ufmt has no width flags in gno, so the padding is by hand.\nfunc idKey(id int) string {\n\ts := strconv.Itoa(id)\n\tfor len(s) \u003c 8 {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n"},{"name":"grants_test.gno","body":"package grants\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\talice   = testutils.TestAddress(\"alice\")   // member\n\tbob     = testutils.TestAddress(\"bob\")     // member\n\tcarol   = testutils.TestAddress(\"carol\")   // member\n\tdave    = testutils.TestAddress(\"dave\")    // applicant, not a member\n\tmallory = testutils.TestAddress(\"mallory\") // nobody\n)\n\n// board3 is the fixture most tests want: three members, so a majority of the\n// eligible set is two whenever the applicant is an outsider.\nfunc board3() *Board { return New(alice, bob, carol) }\n\n// submitOne files a two-milestone grant from dave, the outsider applicant.\nfunc submitOne(t *testing.T, b *Board) *Request {\n\tt.Helper()\n\tr, err := b.Submit(dave, \"Port the thing\", \"with tests\",\n\t\t[]*Milestone{NewMilestone(\"design\", 100), NewMilestone(\"ship\", 400)}, 10)\n\turequire.NoError(t, err)\n\treturn r\n}\n\nfunc TestNewSeedsFoundersAtHeightZero(t *testing.T) {\n\tb := board3()\n\tuassert.Equal(t, 3, b.MemberCount())\n\tfor _, m := range []address{alice, bob, carol} {\n\t\tuassert.True(t, b.IsMember(m), m.String()+\" should be a founder\")\n\t\tuassert.Equal(t, int64(0), b.JoinedAt(m))\n\t}\n\tuassert.False(t, b.IsMember(dave))\n\tuassert.Equal(t, int64(-1), b.JoinedAt(dave))\n\n\t// Members is address-ordered, and the order is what avl gives, not\n\t// insertion order. Only the stability matters, so compare two calls.\n\tfirst, second := b.Members(), b.Members()\n\turequire.Equal(t, 3, len(first))\n\tfor i := range first {\n\t\tuassert.Equal(t, first[i].String(), second[i].String())\n\t}\n}\n\nfunc TestNewSkipsInvalidFounders(t *testing.T) {\n\tb := New(alice, address(\"\"), alice)\n\tuassert.Equal(t, 1, b.MemberCount(), \"empty address dropped, duplicate collapsed\")\n}\n\nfunc TestSubmitValidation(t *testing.T) {\n\tlong := \"\"\n\tfor i := 0; i \u003c MaxTitle+1; i++ {\n\t\tlong += \"x\"\n\t}\n\tbody := \"\"\n\tfor i := 0; i \u003c MaxBody+1; i++ {\n\t\tbody += \"y\"\n\t}\n\tmany := make([]*Milestone, MaxMilestones+1)\n\tfor i := range many {\n\t\tmany[i] = NewMilestone(\"m\", 1)\n\t}\n\n\tcases := []struct {\n\t\tname  string\n\t\ttitle string\n\t\tbody  string\n\t\tms    []*Milestone\n\t\twant  error\n\t}{\n\t\t{\"ok\", \"t\", \"b\", []*Milestone{NewMilestone(\"m\", 1)}, nil},\n\t\t{\"empty title\", \"\", \"b\", []*Milestone{NewMilestone(\"m\", 1)}, ErrBadTitle},\n\t\t{\"long title\", long, \"b\", []*Milestone{NewMilestone(\"m\", 1)}, ErrBadTitle},\n\t\t{\"long body\", \"t\", body, []*Milestone{NewMilestone(\"m\", 1)}, ErrBadBody},\n\t\t{\"no milestone\", \"t\", \"b\", nil, ErrBadMilestones},\n\t\t{\"too many milestones\", \"t\", \"b\", many, ErrBadMilestones},\n\t\t{\"zero amount\", \"t\", \"b\", []*Milestone{NewMilestone(\"m\", 0)}, ErrBadAmount},\n\t\t{\"negative amount\", \"t\", \"b\", []*Milestone{NewMilestone(\"m\", -1)}, ErrBadAmount},\n\t\t{\"untitled milestone\", \"t\", \"b\", []*Milestone{NewMilestone(\"\", 1)}, ErrBadTitle},\n\t}\n\tfor _, tc := range cases {\n\t\t_, err := board3().Submit(dave, tc.title, tc.body, tc.ms, 1)\n\t\tif tc.want == nil {\n\t\t\tuassert.NoError(t, err, tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.ErrorIs(t, err, tc.want, tc.name)\n\t}\n\n\t_, err := board3().Submit(address(\"\"), \"t\", \"b\", []*Milestone{NewMilestone(\"m\", 1)}, 1)\n\tuassert.ErrorIs(t, err, ErrBadAddress, \"invalid applicant\")\n}\n\nfunc TestRequestArithmetic(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\tuassert.Equal(t, int64(500), r.Total())\n\tuassert.Equal(t, int64(0), r.Paid())\n\tuassert.Equal(t, int64(0), r.Outstanding(), \"a pending grant commits nothing\")\n\tuassert.Equal(t, 0, r.Next())\n\tuassert.Equal(t, \"pending\", r.Status.String())\n\tuassert.Equal(t, \"grant\", r.Kind.String())\n\tuassert.True(t, r.Excludes(dave), \"the applicant never votes on their own grant\")\n\tuassert.False(t, r.Excludes(alice))\n\tuassert.Equal(t, dave.String(), r.Payee().String(), \"a self request pays its applicant\")\n\tuassert.False(t, r.OnBehalf())\n\tuassert.Equal(t, 1, r.ID)\n\tuassert.Equal(t, r.ID, b.Get(1).ID)\n\tuassert.True(t, b.Get(42) == nil, \"unknown id\")\n}\n\nfunc TestMajorityCountsOnlyEligibleMembers(t *testing.T) {\n\tb := board3()\n\n\toutsider := submitOne(t, b)\n\tuassert.Equal(t, 3, b.Eligible(outsider))\n\tuassert.Equal(t, 2, b.Majority(outsider))\n\n\t// A member applying for their own grant shrinks the eligible set, and\n\t// with it the bar: two of the remaining two must agree.\n\tinsider, err := b.Submit(alice, \"self\", \"\", []*Milestone{NewMilestone(\"m\", 1)}, 1)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 2, b.Eligible(insider))\n\tuassert.Equal(t, 2, b.Majority(insider))\n}\n\nfunc TestApprovalNeedsAMajority(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\n\tst, err := b.Vote(alice, r.ID, true, \"good\", 11)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"pending\", st.String(), \"one of three is not a majority\")\n\n\tst, err = b.Vote(bob, r.ID, true, \"agreed\", 12)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"approved\", st.String())\n\tuassert.Equal(t, int64(12), r.DecidedAt)\n\tuassert.Equal(t, int64(500), r.Outstanding(), \"approval commits the full ask\")\n\tuassert.Equal(t, int64(500), b.Committed())\n\n\tyes, no := r.Tally()\n\tuassert.Equal(t, 2, yes)\n\tuassert.Equal(t, 0, no)\n\tuassert.Equal(t, \"good\", r.BallotOf(alice).Reason)\n\tuassert.True(t, r.BallotOf(carol) == nil, \"carol never voted\")\n}\n\nfunc TestRejectionNeedsAMajorityToo(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, false, \"out of scope\", 11)))\n\tst, err := b.Vote(bob, r.ID, false, \"same\", 12)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"rejected\", st.String())\n\tuassert.Equal(t, int64(0), b.Committed(), \"a rejected grant commits nothing\")\n}\n\nfunc TestVoteRefusals(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\tself, err := b.Submit(alice, \"self\", \"\", []*Milestone{NewMilestone(\"m\", 1)}, 1)\n\turequire.NoError(t, err)\n\n\t_, err = b.Vote(alice, 999, true, \"\", 1)\n\tuassert.ErrorIs(t, err, ErrNoRequest)\n\n\t_, err = b.Vote(mallory, r.ID, true, \"\", 1)\n\tuassert.ErrorIs(t, err, ErrNotMember)\n\n\t_, err = b.Vote(alice, self.ID, true, \"vote for myself\", 1)\n\tuassert.ErrorIs(t, err, ErrConflict)\n\n\tlong := \"\"\n\tfor i := 0; i \u003c MaxReason+1; i++ {\n\t\tlong += \"z\"\n\t}\n\t_, err = b.Vote(alice, r.ID, true, long, 1)\n\tuassert.ErrorIs(t, err, ErrBadReason)\n\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, true, \"yes\", 1)))\n\t_, err = b.Vote(alice, r.ID, false, \"changed my mind\", 2)\n\tuassert.ErrorIs(t, err, ErrAlreadyVoted, \"a ballot is permanent\")\n\n\turequire.NoError(t, errOf(b.Vote(bob, r.ID, true, \"yes\", 3)))\n\t_, err = b.Vote(carol, r.ID, true, \"too late\", 4)\n\tuassert.ErrorIs(t, err, ErrNotPending, \"decided requests take no more ballots\")\n}\n\nfunc TestDecidesPreviewsWithoutCasting(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\n\tsettles, to := b.Decides(r.ID, alice, true)\n\tuassert.False(t, settles, \"the first of three does not settle it\")\n\tuassert.Equal(t, 0, len(r.Votes), \"previewing casts nothing\")\n\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, true, \"\", 11)))\n\tsettles, to = b.Decides(r.ID, bob, true)\n\tuassert.True(t, settles)\n\tuassert.Equal(t, \"approved\", to.String())\n\n\tsettles, _ = b.Decides(r.ID, bob, false)\n\tuassert.False(t, settles, \"a no here only makes it one-all\")\n\n\tsettles, _ = b.Decides(r.ID, mallory, true)\n\tuassert.False(t, settles, \"a non-member decides nothing\")\n\tsettles, _ = b.Decides(r.ID, alice, true)\n\tuassert.False(t, settles, \"a member who already voted decides nothing\")\n\tsettles, _ = b.Decides(999, bob, true)\n\tuassert.False(t, settles, \"an unknown request decides nothing\")\n}\n\nfunc TestWithdraw(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\n\tuassert.ErrorIs(t, b.Withdraw(mallory, r.ID, 5), ErrNotApplicant)\n\tuassert.ErrorIs(t, b.Withdraw(dave, 999, 5), ErrNoRequest)\n\turequire.NoError(t, b.Withdraw(dave, r.ID, 5))\n\tuassert.Equal(t, \"withdrawn\", r.Status.String())\n\tuassert.ErrorIs(t, b.Withdraw(dave, r.ID, 6), ErrNotPending)\n}\n\nfunc TestProofRefusals(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\tgood := Proof{Kind: \"url\", Ref: \"https://example.com/pr/1\", Height: 20}\n\n\tuassert.ErrorIs(t, b.SubmitProof(dave, r.ID, 0, good), ErrNotApproved, \"not approved yet\")\n\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, true, \"\", 11)))\n\turequire.NoError(t, errOf(b.Vote(bob, r.ID, true, \"\", 12)))\n\n\tuassert.ErrorIs(t, b.SubmitProof(mallory, r.ID, 0, good), ErrNotApplicant)\n\tuassert.ErrorIs(t, b.SubmitProof(dave, r.ID, 7, good), ErrNoMilestone)\n\tuassert.ErrorIs(t, b.SubmitProof(dave, r.ID, 1, good), ErrOutOfOrder, \"milestone 1 before 0\")\n\n\tbad := []Proof{\n\t\t{Kind: \"screenshot\", Ref: \"x\"},\n\t\t{Kind: \"url\", Ref: \"\"},\n\t\t{Kind: \"text\", Ref: \"ok\", Note: longString(MaxNote + 1)},\n\t\t{Kind: \"url\", Ref: longString(MaxRef + 1)},\n\t}\n\tfor _, p := range bad {\n\t\tuassert.ErrorIs(t, b.SubmitProof(dave, r.ID, 0, p), ErrBadProof, p.Kind)\n\t}\n\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 0, good))\n\tuassert.ErrorIs(t, b.SubmitProof(dave, r.ID, 0, good), ErrProofPending, \"one at a time\")\n}\n\nfunc TestReleaseRunsThroughToCompletion(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, true, \"\", 11)))\n\turequire.NoError(t, errOf(b.Vote(bob, r.ID, true, \"\", 12)))\n\n\t// Milestone 0.\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 0, Proof{Kind: \"url\", Ref: \"https://x/1\", Height: 20}))\n\tout, err := b.Review(alice, r.ID, 0, true, \"looks done\", 21)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"under review\", out.String(), \"one reviewer is not a majority\")\n\tuassert.False(t, r.Milestones[0].Released)\n\n\tout, err = b.Review(carol, r.ID, 0, true, \"confirmed\", 22)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"accepted\", out.String())\n\tuassert.True(t, r.Milestones[0].Released)\n\tuassert.Equal(t, int64(22), r.Milestones[0].ReleasedAt)\n\tuassert.Equal(t, int64(100), r.Paid())\n\tuassert.Equal(t, int64(400), r.Outstanding())\n\tuassert.Equal(t, \"approved\", r.Status.String(), \"one tranche left\")\n\tuassert.Equal(t, 1, r.Next())\n\n\t// Milestone 1 completes the grant.\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 1, Proof{Kind: \"hash\", Ref: \"deadbeef\", Height: 30}))\n\turequire.NoError(t, errOf2(b.Review(alice, r.ID, 1, true, \"\", 31)))\n\tout, err = b.Review(bob, r.ID, 1, true, \"\", 32)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"accepted\", out.String())\n\tuassert.Equal(t, \"completed\", r.Status.String())\n\tuassert.Equal(t, -1, r.Next())\n\tuassert.Equal(t, int64(500), r.Paid())\n\tuassert.Equal(t, int64(0), r.Outstanding(), \"a completed grant commits nothing\")\n\tuassert.Equal(t, int64(500), b.Disbursed())\n\tuassert.Equal(t, int64(0), b.Committed())\n}\n\nfunc TestRefusedProofKeepsTheGrantAliveAndOnTheRecord(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, true, \"\", 11)))\n\turequire.NoError(t, errOf(b.Vote(bob, r.ID, true, \"\", 12)))\n\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 0, Proof{Kind: \"url\", Ref: \"https://x/draft\", Height: 20}))\n\turequire.NoError(t, errOf2(b.Review(alice, r.ID, 0, false, \"this is a stub\", 21)))\n\tout, err := b.Review(bob, r.ID, 0, false, \"agreed, no tests\", 22)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"refused\", out.String())\n\tuassert.False(t, r.Milestones[0].Released)\n\tuassert.Equal(t, \"approved\", r.Status.String(), \"a refused proof does not kill the grant\")\n\n\t// The refused attempt stays readable, reasons and all.\n\tm := r.Milestones[0]\n\turequire.Equal(t, 1, len(m.Attempts))\n\tuassert.Equal(t, \"this is a stub\", m.Attempts[0].Reviews[0].Reason)\n\tuassert.True(t, m.Current() == nil, \"the attempt is closed\")\n\n\t// And a second attempt can carry.\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 0, Proof{Kind: \"url\", Ref: \"https://x/final\", Height: 30}))\n\turequire.NoError(t, errOf2(b.Review(alice, r.ID, 0, true, \"now it is done\", 31)))\n\turequire.NoError(t, errOf2(b.Review(bob, r.ID, 0, true, \"\", 32)))\n\tuassert.True(t, r.Milestones[0].Released)\n\tuassert.Equal(t, 2, len(m.Attempts), \"both attempts are kept\")\n}\n\nfunc TestReviewRefusals(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, true, \"\", 11)))\n\turequire.NoError(t, errOf(b.Vote(bob, r.ID, true, \"\", 12)))\n\n\tuassert.ErrorIs(t, errOf2(b.Review(alice, r.ID, 0, true, \"\", 20)), ErrNoProof)\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 0, Proof{Kind: \"text\", Ref: \"done\", Height: 20}))\n\n\tuassert.ErrorIs(t, errOf2(b.Review(mallory, r.ID, 0, true, \"\", 21)), ErrNotMember)\n\tuassert.ErrorIs(t, errOf2(b.Review(alice, 999, 0, true, \"\", 21)), ErrNoRequest)\n\tuassert.ErrorIs(t, errOf2(b.Review(alice, r.ID, 9, true, \"\", 21)), ErrNoMilestone)\n\turequire.NoError(t, errOf2(b.Review(alice, r.ID, 0, true, \"\", 21)))\n\tuassert.ErrorIs(t, errOf2(b.Review(alice, r.ID, 0, false, \"\", 22)), ErrAlreadyVoted)\n}\n\nfunc TestApplicantMayNotReviewTheirOwnProof(t *testing.T) {\n\tb := New(alice, bob, dave) // dave is a member AND the applicant here\n\tr, err := b.Submit(dave, \"self funded\", \"\", []*Milestone{NewMilestone(\"m\", 10)}, 1)\n\turequire.NoError(t, err)\n\turequire.NoError(t, errOf(b.Vote(alice, r.ID, true, \"\", 2)))\n\turequire.NoError(t, errOf(b.Vote(bob, r.ID, true, \"\", 3)))\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 0, Proof{Kind: \"text\", Ref: \"done\", Height: 4}))\n\tuassert.ErrorIs(t, errOf2(b.Review(dave, r.ID, 0, true, \"ship it\", 5)), ErrConflict)\n}\n\nfunc TestMembershipRequestAddsAndRemoves(t *testing.T) {\n\tb := board3()\n\n\tadd, err := b.SubmitMemberChange(alice, dave, true, \"he reviews everything anyway\", 5)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"membership\", add.Kind.String())\n\tuassert.Equal(t, \"Add \"+dave.String(), add.Title)\n\tuassert.Equal(t, int64(0), add.Total(), \"a membership request asks for no money\")\n\n\turequire.NoError(t, errOf(b.Vote(alice, add.ID, true, \"\", 6)))\n\tst, err := b.Vote(bob, add.ID, true, \"\", 7)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"completed\", st.String(), \"membership executes on approval\")\n\tuassert.True(t, b.IsMember(dave))\n\tuassert.Equal(t, int64(7), b.JoinedAt(dave), \"joined at the deciding height\")\n\n\t// Now four members: a majority excluding the subject is still two.\n\trm, err := b.SubmitMemberChange(alice, carol, false, \"inactive\", 8)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 3, b.Eligible(rm))\n\tuassert.ErrorIs(t, errOf(b.Vote(carol, rm.ID, false, \"no\", 9)), ErrConflict, \"the subject may not vote\")\n\turequire.NoError(t, errOf(b.Vote(alice, rm.ID, true, \"\", 10)))\n\turequire.NoError(t, errOf(b.Vote(bob, rm.ID, true, \"\", 11)))\n\tuassert.False(t, b.IsMember(carol))\n\tuassert.Equal(t, 3, b.MemberCount())\n}\n\nfunc TestMemberChangeRefusals(t *testing.T) {\n\tb := board3()\n\n\t_, err := b.SubmitMemberChange(mallory, dave, true, \"\", 1)\n\tuassert.ErrorIs(t, err, ErrNotMember, \"only members touch the board's composition\")\n\t_, err = b.SubmitMemberChange(alice, alice, true, \"\", 1)\n\tuassert.ErrorIs(t, err, ErrIsMember)\n\t_, err = b.SubmitMemberChange(alice, dave, false, \"\", 1)\n\tuassert.ErrorIs(t, err, ErrNotMember, \"cannot remove a non-member\")\n\t_, err = b.SubmitMemberChange(alice, address(\"\"), true, \"\", 1)\n\tuassert.ErrorIs(t, err, ErrBadAddress)\n\n\tsolo := New(alice)\n\t_, err = solo.SubmitMemberChange(alice, alice, false, \"\", 1)\n\tuassert.ErrorIs(t, err, ErrLastMember, \"the board cannot empty itself\")\n}\n\n// Standing is the whole reason a removed member's yes does not keep carrying\n// decisions they are no longer part of.\nfunc TestStandingDropsBallotsFromFormerMembers(t *testing.T) {\n\tb := board3()\n\tr := submitOne(t, b)\n\turequire.NoError(t, errOf(b.Vote(carol, r.ID, true, \"I like it\", 11)))\n\n\trm, err := b.SubmitMemberChange(alice, carol, false, \"left the project\", 12)\n\turequire.NoError(t, err)\n\turequire.NoError(t, errOf(b.Vote(alice, rm.ID, true, \"\", 13)))\n\turequire.NoError(t, errOf(b.Vote(bob, rm.ID, true, \"\", 14)))\n\turequire.Equal(t, 2, b.MemberCount())\n\n\tyes, _ := r.Tally()\n\tuassert.Equal(t, 1, yes, \"the ballot stays on the record\")\n\tyes, _ = b.Standing(r)\n\tuassert.Equal(t, 0, yes, \"but it no longer counts\")\n\n\t// With two members and an outsider applicant the bar is two, so alice\n\t// alone still cannot carry it.\n\tuassert.Equal(t, 2, b.Majority(r))\n\tst, err := b.Vote(alice, r.ID, true, \"\", 15)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"pending\", st.String())\n}\n\nfunc TestListAndSizeStayInIDOrder(t *testing.T) {\n\tb := board3()\n\tfor i := 0; i \u003c 12; i++ {\n\t\t_, err := b.Submit(dave, \"r\", \"\", []*Milestone{NewMilestone(\"m\", 1)}, int64(i))\n\t\turequire.NoError(t, err)\n\t}\n\tall := b.List()\n\turequire.Equal(t, 12, len(all))\n\tuassert.Equal(t, 12, b.Size())\n\tfor i, r := range all {\n\t\tuassert.Equal(t, i+1, r.ID, \"ids come back in numeric order past nine\")\n\t}\n}\n\nfunc longString(n int) string {\n\ts := \"\"\n\tfor i := 0; i \u003c n; i++ {\n\t\ts += \"x\"\n\t}\n\treturn s\n}\n\n// errOf and errOf2 drop the leading return value of Vote and Review so a call\n// reads as a single assertion.\nfunc errOf(_ Status, err error) error   { return err }\nfunc errOf2(_ Outcome, err error) error { return err }\n\nfunc TestFilingForSomeoneElseNeedsAReason(t *testing.T) {\n\tb := board3()\n\tms := func() []*Milestone { return []*Milestone{NewMilestone(\"m\", 100)} }\n\n\t_, err := b.SubmitFor(dave, mallory, \"\", \"t\", \"\", ms(), 10)\n\tuassert.ErrorIs(t, err, ErrNeedReason, \"a request for someone else has to say why\")\n\n\t// The same address is just a self request, and needs nothing extra.\n\tself, err := b.SubmitFor(dave, dave, \"\", \"t\", \"\", ms(), 10)\n\turequire.NoError(t, err)\n\tuassert.False(t, self.OnBehalf())\n\n\t_, err = b.SubmitFor(dave, address(\"not-an-address\"), \"because\", \"t\", \"\", ms(), 10)\n\tuassert.ErrorIs(t, err, ErrBadAddress)\n\n\tlong := \"\"\n\tfor i := 0; i \u003c= MaxReason; i++ {\n\t\tlong += \"x\"\n\t}\n\t_, err = b.SubmitFor(dave, mallory, long, \"t\", \"\", ms(), 10)\n\tuassert.ErrorIs(t, err, ErrBadReason)\n\n\tr, err := b.SubmitFor(dave, mallory, \"their account is empty\", \"t\", \"\", ms(), 10)\n\turequire.NoError(t, err)\n\tuassert.True(t, r.OnBehalf())\n\tuassert.Equal(t, mallory.String(), r.Payee().String())\n\tuassert.Equal(t, dave.String(), r.Applicant.String())\n}\n\n// A member who is paid by a request someone else filed is the same conflict of\n// interest as a member who filed it, with one address in between.\nfunc TestBothPartiesAreBarredFromVotingOnAGrant(t *testing.T) {\n\tb := board3()\n\tr, err := b.SubmitFor(alice, bob, \"bob asked me to file it\", \"t\", \"\",\n\t\t[]*Milestone{NewMilestone(\"m\", 100)}, 10)\n\turequire.NoError(t, err)\n\n\tuassert.True(t, r.Excludes(alice), \"the applicant\")\n\tuassert.True(t, r.Excludes(bob), \"the beneficiary\")\n\tuassert.False(t, r.Excludes(carol))\n\tuassert.Equal(t, 1, b.Eligible(r), \"three members, two of them party to it\")\n\tuassert.Equal(t, 1, b.Majority(r))\n\n\t_, err = b.Vote(alice, r.ID, true, \"\", 11)\n\tuassert.ErrorIs(t, err, ErrConflict, \"the applicant may not vote\")\n\t_, err = b.Vote(bob, r.ID, true, \"\", 11)\n\tuassert.ErrorIs(t, err, ErrConflict, \"the payee may not vote\")\n\n\tst, err := b.Vote(carol, r.ID, true, \"fine\", 12)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"approved\", st.String(), \"the one eligible member carries it\")\n\n\t// And the same exclusion holds on the proof review, which is where the\n\t// money actually moves.\n\turequire.NoError(t, b.SubmitProof(alice, r.ID, 0, Proof{Kind: \"text\", Ref: \"done\", Height: 13}))\n\t_, err = b.Review(bob, r.ID, 0, true, \"\", 14)\n\tuassert.ErrorIs(t, err, ErrConflict, \"the payee may not review their own proof\")\n}\n\n// The payee of a request filed for an empty account cannot transact until the\n// first tranche lands, so the filer has to be able to prove the work; once the\n// payee can transact, they have to be able to prove their own.\nfunc TestEitherPartyMaySubmitAProof(t *testing.T) {\n\tb := board3()\n\tr, err := b.SubmitFor(dave, mallory, \"empty account\", \"t\", \"\",\n\t\t[]*Milestone{NewMilestone(\"one\", 100), NewMilestone(\"two\", 100)}, 10)\n\turequire.NoError(t, err)\n\tb.Vote(alice, r.ID, true, \"\", 11)\n\tb.Vote(bob, r.ID, true, \"\", 12)\n\turequire.Equal(t, \"approved\", r.Status.String())\n\n\tuassert.ErrorIs(t, b.SubmitProof(carol, r.ID, 0, Proof{Kind: \"text\", Ref: \"x\", Height: 13}),\n\t\tErrNotApplicant, \"a third party may not\")\n\n\turequire.NoError(t, b.SubmitProof(dave, r.ID, 0, Proof{Kind: \"text\", Ref: \"filer\", Height: 13}))\n\tb.Review(alice, r.ID, 0, true, \"\", 14)\n\tb.Review(bob, r.ID, 0, true, \"\", 15)\n\turequire.True(t, r.Milestones[0].Released)\n\n\turequire.NoError(t, b.SubmitProof(mallory, r.ID, 1, Proof{Kind: \"text\", Ref: \"payee\", Height: 16}))\n}\n"},{"name":"lifecycle.gno","body":"package grants\n\n// This file holds every state transition of the board. Each one takes the\n// acting address and the block height from the caller rather than reading\n// them from the chain, which is what keeps the package pure and the whole\n// lifecycle exercisable in a plain unit test.\n\n// NewMilestone is a small constructor so callers do not build the struct (and\n// its Attempts slice) by hand.\nfunc NewMilestone(title string, amount int64) *Milestone {\n\treturn \u0026Milestone{Title: title, Amount: amount}\n}\n\n// Submit files a grant application for the applicant themselves. Anyone may\n// apply; being a member is not required and does not help, since a member is\n// barred from voting on their own request.\nfunc (b *Board) Submit(applicant address, title, body string, ms []*Milestone, height int64) (*Request, error) {\n\treturn b.SubmitFor(applicant, applicant, \"\", title, body, ms, height)\n}\n\n// SubmitFor files a grant application whose money goes to beneficiary rather\n// than to the applicant, with a reason for the detour.\n//\n// The reason is required, and it is required because it is the only thing on\n// the page that answers the question a reader will have: why is this person\n// asking for someone else's money. The usual honest answer is that the payee\n// has an empty account and cannot pay the gas to ask, which is exactly the\n// case a grant board exists to serve and exactly the case an impersonation\n// looks like. Making the claim explicit is what lets a member check it.\n//\n// Passing the applicant's own address is the same as Submit and needs no\n// reason.\nfunc (b *Board) SubmitFor(applicant, beneficiary address, reason, title, body string, ms []*Milestone, height int64) (*Request, error) {\n\tif !applicant.IsValid() || !beneficiary.IsValid() {\n\t\treturn nil, ErrBadAddress\n\t}\n\tif len(reason) \u003e MaxReason {\n\t\treturn nil, ErrBadReason\n\t}\n\tif beneficiary != applicant \u0026\u0026 reason == \"\" {\n\t\treturn nil, ErrNeedReason\n\t}\n\tif err := checkTitle(title); err != nil {\n\t\treturn nil, err\n\t}\n\tif len(body) \u003e MaxBody {\n\t\treturn nil, ErrBadBody\n\t}\n\tif len(ms) == 0 || len(ms) \u003e MaxMilestones {\n\t\treturn nil, ErrBadMilestones\n\t}\n\tfor _, m := range ms {\n\t\tif m == nil || m.Amount \u003c= 0 {\n\t\t\treturn nil, ErrBadAmount\n\t\t}\n\t\tif err := checkTitle(m.Title); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn b.file(\u0026Request{\n\t\tKind:        KindGrant,\n\t\tApplicant:   applicant,\n\t\tBeneficiary: beneficiary,\n\t\tReason:      reason,\n\t\tTitle:       title,\n\t\tBody:        body,\n\t\tMilestones:  ms,\n\t\tCreatedAt:   height,\n\t}), nil\n}\n\n// SubmitMemberChange files a request to add or remove a board member. Only a\n// member may file one: opening the board's own composition to anyone with a\n// keypair is how a grant board gets captured.\nfunc (b *Board) SubmitMemberChange(proposer, subject address, add bool, body string, height int64) (*Request, error) {\n\tif !b.IsMember(proposer) {\n\t\treturn nil, ErrNotMember\n\t}\n\tif !subject.IsValid() {\n\t\treturn nil, ErrBadAddress\n\t}\n\tif len(body) \u003e MaxBody {\n\t\treturn nil, ErrBadBody\n\t}\n\tswitch {\n\tcase add \u0026\u0026 b.IsMember(subject):\n\t\treturn nil, ErrIsMember\n\tcase !add \u0026\u0026 !b.IsMember(subject):\n\t\treturn nil, ErrNotMember\n\tcase !add \u0026\u0026 b.MemberCount() == 1:\n\t\treturn nil, ErrLastMember\n\t}\n\ttitle := \"Remove \" + subject.String()\n\tif add {\n\t\ttitle = \"Add \" + subject.String()\n\t}\n\treturn b.file(\u0026Request{\n\t\tKind:        KindMember,\n\t\tApplicant:   proposer,\n\t\tBeneficiary: proposer,\n\t\tTitle:       title,\n\t\tBody:        body,\n\t\tSubject:     subject,\n\t\tAdd:         add,\n\t\tCreatedAt:   height,\n\t}), nil\n}\n\nfunc (b *Board) file(r *Request) *Request {\n\tr.ID = b.nextID\n\tb.nextID++\n\tb.requests.Set(idKey(r.ID), r)\n\treturn r\n}\n\n// Withdraw lets an applicant pull their own request before it is decided.\nfunc (b *Board) Withdraw(caller address, id int, height int64) error {\n\tr := b.Get(id)\n\tif r == nil {\n\t\treturn ErrNoRequest\n\t}\n\tif r.Applicant != caller {\n\t\treturn ErrNotApplicant\n\t}\n\tif r.Status != Pending {\n\t\treturn ErrNotPending\n\t}\n\tr.Status, r.DecidedAt = Withdrawn, height\n\treturn nil\n}\n\n// Standing counts only the ballots of addresses that are members right now.\n// Decisions use this, not Request.Tally: a ballot is a permanent record of\n// what someone said, but it stops carrying weight the moment they leave the\n// board. The two numbers differ exactly when a voter has since been removed,\n// and a good renderer shows both.\nfunc (b *Board) Standing(r *Request) (yes, no int) { return b.standing(r.Votes) }\n\n// Decides previews what a ballot would do without casting it, so a caller can\n// check a precondition it cannot roll back: a realm, for instance, refusing\n// to let a grant carry that its treasury cannot cover. It reports false for a\n// ballot that would be refused anyway.\nfunc (b *Board) Decides(id int, voter address, approve bool) (bool, Status) {\n\tr := b.Get(id)\n\tif r == nil || r.Status != Pending {\n\t\treturn false, Pending\n\t}\n\tif !b.IsMember(voter) || r.Excludes(voter) || r.BallotOf(voter) != nil {\n\t\treturn false, Pending\n\t}\n\tyes, no := b.Standing(r)\n\tif approve {\n\t\tyes++\n\t} else {\n\t\tno++\n\t}\n\tswitch m := b.Majority(r); {\n\tcase yes \u003e= m:\n\t\treturn true, Approved\n\tcase no \u003e= m:\n\t\treturn true, Rejected\n\t}\n\treturn false, Pending\n}\n\n// ReviewDecides is Decides for a proof review: it reports whether this\n// verdict would close the attempt under review, and how. A realm uses it to\n// check, before recording anything, that it can actually pay a tranche it is\n// about to release.\nfunc (b *Board) ReviewDecides(id, idx int, voter address, accept bool) (bool, Outcome) {\n\tr := b.Get(id)\n\tif r == nil || r.Kind != KindGrant || r.Status != Approved {\n\t\treturn false, UnderReview\n\t}\n\tif idx \u003c 0 || idx \u003e= len(r.Milestones) {\n\t\treturn false, UnderReview\n\t}\n\ta := r.Milestones[idx].Current()\n\tif a == nil {\n\t\treturn false, UnderReview\n\t}\n\tif !b.IsMember(voter) || r.Excludes(voter) || find(a.Reviews, voter) != nil {\n\t\treturn false, UnderReview\n\t}\n\tyes, no := b.standing(a.Reviews)\n\tif accept {\n\t\tyes++\n\t} else {\n\t\tno++\n\t}\n\tswitch m := b.Majority(r); {\n\tcase yes \u003e= m:\n\t\treturn true, Accepted\n\tcase no \u003e= m:\n\t\treturn true, Refused\n\t}\n\treturn false, UnderReview\n}\n\n// standing counts ballots from current members only. See Standing.\nfunc (b *Board) standing(bs []Ballot) (yes, no int) {\n\tfor _, v := range bs {\n\t\tif !b.IsMember(v.Voter) {\n\t\t\tcontinue\n\t\t}\n\t\tif v.Approve {\n\t\t\tyes++\n\t\t} else {\n\t\t\tno++\n\t\t}\n\t}\n\treturn yes, no\n}\n\n// Vote casts one member's ballot on a request and returns the status it left\n// the request in. A member votes once; there is no changing your mind, which\n// is the price of every ballot being a permanent public statement.\nfunc (b *Board) Vote(voter address, id int, approve bool, reason string, height int64) (Status, error) {\n\tr := b.Get(id)\n\tif r == nil {\n\t\treturn Pending, ErrNoRequest\n\t}\n\tif !b.IsMember(voter) {\n\t\treturn r.Status, ErrNotMember\n\t}\n\tif r.Status != Pending {\n\t\treturn r.Status, ErrNotPending\n\t}\n\tif r.Excludes(voter) {\n\t\treturn r.Status, ErrConflict\n\t}\n\tif r.BallotOf(voter) != nil {\n\t\treturn r.Status, ErrAlreadyVoted\n\t}\n\tif len(reason) \u003e MaxReason {\n\t\treturn r.Status, ErrBadReason\n\t}\n\n\tr.Votes = append(r.Votes, Ballot{Voter: voter, Approve: approve, Reason: reason, Height: height})\n\n\tyes, no := b.Standing(r)\n\tswitch m := b.Majority(r); {\n\tcase yes \u003e= m:\n\t\tr.Status, r.DecidedAt = Approved, height\n\t\tif r.Kind == KindMember {\n\t\t\tb.applyMemberChange(r, height)\n\t\t}\n\tcase no \u003e= m:\n\t\tr.Status, r.DecidedAt = Rejected, height\n\t}\n\treturn r.Status, nil\n}\n\n// applyMemberChange is the whole execution engine for KindMember: a carried\n// membership request takes effect at once, with nothing to claim afterwards,\n// so it goes straight from Approved to Completed.\nfunc (b *Board) applyMemberChange(r *Request, height int64) {\n\tif r.Add {\n\t\tb.members.Set(r.Subject.String(), height)\n\t} else {\n\t\tb.members.Remove(r.Subject.String())\n\t}\n\tr.Status = Completed\n}\n\n// SubmitProof offers evidence for the next unreleased milestone of an\n// approved grant. Milestones are earned in order, and only one proof is under\n// review at a time.\n//\n// Either the applicant or the beneficiary may submit. On a request filed for\n// an empty account, the payee cannot transact until the first tranche lands,\n// so restricting this to the payee would strand the grant it was filed to\n// unstick; restricting it to the filer would leave the payee unable to show\n// their own work once they can.\nfunc (b *Board) SubmitProof(caller address, id, idx int, p Proof) error {\n\tr := b.Get(id)\n\tif r == nil {\n\t\treturn ErrNoRequest\n\t}\n\tif r.Kind != KindGrant || r.Status != Approved {\n\t\treturn ErrNotApproved\n\t}\n\tif r.Applicant != caller \u0026\u0026 r.Payee() != caller {\n\t\treturn ErrNotApplicant\n\t}\n\tif idx \u003c 0 || idx \u003e= len(r.Milestones) {\n\t\treturn ErrNoMilestone\n\t}\n\tif idx != r.Next() {\n\t\treturn ErrOutOfOrder\n\t}\n\tif err := checkProof(p); err != nil {\n\t\treturn err\n\t}\n\tm := r.Milestones[idx]\n\tif m.Current() != nil {\n\t\treturn ErrProofPending\n\t}\n\tm.Attempts = append(m.Attempts, \u0026Attempt{Proof: p, Outcome: UnderReview})\n\treturn nil\n}\n\n// Review casts a member's verdict on the proof currently under review and\n// returns the outcome that verdict left the attempt in. Accepting it releases\n// the tranche, which in this package means marking it Released and nothing\n// more; moving the coins is the caller's job, and Request.Paid tells it how\n// much it now owes. Refusing closes the attempt and lets the applicant try\n// again with better evidence.\nfunc (b *Board) Review(voter address, id, idx int, accept bool, reason string, height int64) (Outcome, error) {\n\tr := b.Get(id)\n\tif r == nil {\n\t\treturn UnderReview, ErrNoRequest\n\t}\n\tif !b.IsMember(voter) {\n\t\treturn UnderReview, ErrNotMember\n\t}\n\tif r.Kind != KindGrant || r.Status != Approved {\n\t\treturn UnderReview, ErrNotApproved\n\t}\n\tif idx \u003c 0 || idx \u003e= len(r.Milestones) {\n\t\treturn UnderReview, ErrNoMilestone\n\t}\n\tif r.Excludes(voter) {\n\t\treturn UnderReview, ErrConflict\n\t}\n\tif len(reason) \u003e MaxReason {\n\t\treturn UnderReview, ErrBadReason\n\t}\n\tm := r.Milestones[idx]\n\ta := m.Current()\n\tif a == nil {\n\t\treturn UnderReview, ErrNoProof\n\t}\n\tif find(a.Reviews, voter) != nil {\n\t\treturn UnderReview, ErrAlreadyVoted\n\t}\n\n\ta.Reviews = append(a.Reviews, Ballot{Voter: voter, Approve: accept, Reason: reason, Height: height})\n\n\tyes, no := b.standing(a.Reviews)\n\tswitch mj := b.Majority(r); {\n\tcase yes \u003e= mj:\n\t\ta.Outcome, a.ClosedAt = Accepted, height\n\t\tm.Released, m.ReleasedAt = true, height\n\t\tif r.Next() == -1 {\n\t\t\tr.Status = Completed\n\t\t}\n\tcase no \u003e= mj:\n\t\ta.Outcome, a.ClosedAt = Refused, height\n\t}\n\treturn a.Outcome, nil\n}\n\nfunc checkTitle(s string) error {\n\tif len(s) == 0 || len(s) \u003e MaxTitle {\n\t\treturn ErrBadTitle\n\t}\n\treturn nil\n}\n\nfunc checkProof(p Proof) error {\n\tswitch p.Kind {\n\tcase \"url\", \"hash\", \"text\":\n\tdefault:\n\t\treturn ErrBadProof\n\t}\n\tif len(p.Ref) == 0 || len(p.Ref) \u003e MaxRef || len(p.Note) \u003e MaxNote {\n\t\treturn ErrBadProof\n\t}\n\treturn nil\n}\n"},{"name":"program.gno","body":"package grants\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Program is a Board plus the money that moves around it: what came in, what\n// went out, and the denomination it is all counted in.\n//\n// It still holds no coins and calls no banker. A realm hands it the current\n// treasury balance whenever a decision depends on one, and executes the\n// Payment it hands back. That split is the whole point: everything a grant\n// program decides is testable without a node, and the realm on top is thin\n// enough to read in one screen.\ntype Program struct {\n\tBoard     *Board\n\tDenom     string\n\tDonations []Donation\n\tPayments  []Payment\n}\n\n// Donation is one top-up of the treasury, credited to a name.\ntype Donation struct {\n\tHeight int64\n\tFrom   address\n\tAmount int64\n}\n\n// Payment is one released tranche. The ledger of these is a program's answer\n// to \"where did the money go\".\ntype Payment struct {\n\tHeight    int64\n\tRequest   int\n\tMilestone int\n\tTo        address\n\tAmount    int64\n}\n\n// NewProgram returns a program whose board is seated with founders. denom is\n// the coin everything is counted in (\"ugnot\" on gno.land); it is carried so a\n// renderer can label amounts without the realm telling it twice.\nfunc NewProgram(denom string, founders ...address) *Program {\n\treturn \u0026Program{Board: New(founders...), Denom: denom}\n}\n\n// Fund records a top-up. The coins have already moved by the time this is\n// called: a realm calls it to put a name next to a transfer that would\n// otherwise be anonymous.\nfunc (p *Program) Fund(from address, amount, height int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrNothingSent\n\t}\n\tif !from.IsValid() {\n\t\treturn ErrBadAddress\n\t}\n\tp.Donations = append(p.Donations, Donation{Height: height, From: from, Amount: amount})\n\treturn nil\n}\n\n// Apply files a grant request from a milestone spec, \"design:100,ship:400\".\n// See ParseMilestones for the grammar.\nfunc (p *Program) Apply(applicant address, title, body, spec string, height int64) (*Request, error) {\n\treturn p.ApplyFor(applicant, applicant, \"\", title, body, spec, height)\n}\n\n// ApplyFor is Apply for a request whose money goes to someone other than the\n// address filing it. See Board.SubmitFor for why the reason is required.\nfunc (p *Program) ApplyFor(applicant, beneficiary address, reason, title, body, spec string, height int64) (*Request, error) {\n\tms, err := ParseMilestones(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.Board.SubmitFor(applicant, beneficiary, reason, title, body, ms, height)\n}\n\n// Review casts a member's verdict on the proof under review and, when that\n// verdict releases the tranche, records the payment and hands it back for the\n// caller to execute.\n//\n// balance is what the treasury holds right now. A verdict that would release\n// more than that is refused with ErrUnderfunded and changes NOTHING: no\n// ballot, no release, no payment. That ordering is the reason Board.Review is\n// not called directly by a realm. A refusal is always free to record, since it\n// costs the treasury nothing.\nfunc (p *Program) Review(voter address, id, idx int, accept bool, reason string, height, balance int64) (Outcome, *Payment, error) {\n\tif releases, out := p.Board.ReviewDecides(id, idx, voter, accept); releases \u0026\u0026 out == Accepted {\n\t\tif amount := p.Board.Get(id).Milestones[idx].Amount; balance \u003c amount {\n\t\t\treturn UnderReview, nil, ErrUnderfunded\n\t\t}\n\t}\n\n\tout, err := p.Board.Review(voter, id, idx, accept, reason, height)\n\tif err != nil || out != Accepted {\n\t\treturn out, nil, err\n\t}\n\n\tr := p.Board.Get(id)\n\tpay := Payment{\n\t\tHeight:    height,\n\t\tRequest:   id,\n\t\tMilestone: idx,\n\t\tTo:        r.Payee(),\n\t\tAmount:    r.Milestones[idx].Amount,\n\t}\n\tp.Payments = append(p.Payments, pay)\n\treturn out, \u0026pay, nil\n}\n\n// Raised is everything ever donated through Fund.\nfunc (p *Program) Raised() int64 {\n\tvar n int64\n\tfor _, d := range p.Donations {\n\t\tn += d.Amount\n\t}\n\treturn n\n}\n\n// Disbursed is everything ever released.\nfunc (p *Program) Disbursed() int64 { return p.Board.Disbursed() }\n\n// Committed is what approved grants can still claim.\nfunc (p *Program) Committed() int64 { return p.Board.Committed() }\n\n// Available is balance minus what is already promised. It goes NEGATIVE when\n// the board has approved more than the treasury holds, which is allowed on\n// purpose: a board that can only approve what it already has cannot approve\n// anything before a donor shows up. Renderers say so out loud.\nfunc (p *Program) Available(balance int64) int64 { return balance - p.Committed() }\n\n// ParseMilestones reads \"design:100,ship:400\" into milestones, amounts in the\n// program's denomination, paid in the order written. A title may not contain a\n// comma, and the amount is whatever follows the LAST colon, so\n// \"port gno:land tooling:250\" parses the way it reads.\nfunc ParseMilestones(spec string) ([]*Milestone, error) {\n\tout := []*Milestone{}\n\tfor _, part := range strings.Split(spec, \",\") {\n\t\tpart = strings.TrimSpace(part)\n\t\tif part == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ti := strings.LastIndex(part, \":\")\n\t\tif i \u003c 0 {\n\t\t\treturn nil, ErrBadSpec\n\t\t}\n\t\tamount, err := strconv.ParseInt(strings.TrimSpace(part[i+1:]), 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, ErrBadSpec\n\t\t}\n\t\tout = append(out, NewMilestone(strings.TrimSpace(part[:i]), amount))\n\t}\n\tif len(out) == 0 {\n\t\treturn nil, ErrBadSpec\n\t}\n\treturn out, nil\n}\n"},{"name":"program_test.gno","body":"package grants\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// prog is the fixture: three members, and dave applying from outside, so a\n// majority of the eligible set is two.\nfunc prog() *Program { return NewProgram(\"ugnot\", alice, bob, carol) }\n\nfunc TestParseMilestones(t *testing.T) {\n\tcases := []struct {\n\t\tname    string\n\t\tspec    string\n\t\ttitles  []string\n\t\tamounts []int64\n\t}{\n\t\t{\"one\", \"ship:400\", []string{\"ship\"}, []int64{400}},\n\t\t{\"two\", \"design:100,ship:400\", []string{\"design\", \"ship\"}, []int64{100, 400}},\n\t\t{\"spaces\", \" design : 100 , ship : 400 \", []string{\"design\", \"ship\"}, []int64{100, 400}},\n\t\t{\"trailing comma\", \"ship:400,\", []string{\"ship\"}, []int64{400}},\n\t\t{\"colon in the title\", \"port gno:land tooling:250\", []string{\"port gno:land tooling\"}, []int64{250}},\n\t}\n\tfor _, tc := range cases {\n\t\tms, err := ParseMilestones(tc.spec)\n\t\tif !uassert.NoError(t, err, tc.name) {\n\t\t\tcontinue\n\t\t}\n\t\turequire.Equal(t, len(tc.titles), len(ms), tc.name)\n\t\tfor i := range ms {\n\t\t\tuassert.Equal(t, tc.titles[i], ms[i].Title, tc.name)\n\t\t\tuassert.Equal(t, tc.amounts[i], ms[i].Amount, tc.name)\n\t\t}\n\t}\n\n\tfor _, bad := range []string{\"\", \"  \", \",,\", \"ship\", \"ship:\", \"ship:many\", \"ship:1:2:x\"} {\n\t\t_, err := ParseMilestones(bad)\n\t\tuassert.ErrorIs(t, err, ErrBadSpec, \"should be rejected: \"+bad)\n\t}\n}\n\nfunc TestFundRecordsTheDonor(t *testing.T) {\n\tp := prog()\n\tuassert.ErrorIs(t, p.Fund(dave, 0, 10), ErrNothingSent)\n\tuassert.ErrorIs(t, p.Fund(dave, -5, 10), ErrNothingSent)\n\tuassert.ErrorIs(t, p.Fund(address(\"\"), 5, 10), ErrBadAddress)\n\tuassert.Equal(t, 0, len(p.Donations), \"none of those were recorded\")\n\n\turequire.NoError(t, p.Fund(dave, 500, 10))\n\turequire.NoError(t, p.Fund(mallory, 250, 11))\n\turequire.Equal(t, 2, len(p.Donations))\n\tuassert.Equal(t, dave.String(), p.Donations[0].From.String())\n\tuassert.Equal(t, int64(500), p.Donations[0].Amount)\n\tuassert.Equal(t, int64(10), p.Donations[0].Height)\n\tuassert.Equal(t, int64(750), p.Raised())\n}\n\nfunc TestApplyGoesThroughTheSpec(t *testing.T) {\n\tp := prog()\n\tr, err := p.Apply(dave, \"Ship it\", \"two tranches\", \"alpha:100,beta:400\", 10)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(500), r.Total())\n\tuassert.Equal(t, 2, len(r.Milestones))\n\tuassert.Equal(t, \"beta\", r.Milestones[1].Title)\n\n\t_, err = p.Apply(dave, \"Bad\", \"\", \"no amount here\", 10)\n\tuassert.ErrorIs(t, err, ErrBadSpec)\n\tuassert.Equal(t, 1, p.Board.Size(), \"the bad one was never filed\")\n}\n\n// Available is allowed to go negative. That is the whole reason Review takes\n// a balance instead of trusting the board's own arithmetic.\nfunc TestAvailableGoesNegativeWhenTheBoardOverPromises(t *testing.T) {\n\tp := prog()\n\tr, err := p.Apply(dave, \"Ship it\", \"\", \"alpha:100,beta:400\", 10)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(0), p.Committed(), \"pending promises nothing\")\n\tuassert.Equal(t, int64(0), p.Available(0))\n\n\turequire.NoError(t, errOf(p.Board.Vote(alice, r.ID, true, \"\", 11)))\n\turequire.NoError(t, errOf(p.Board.Vote(bob, r.ID, true, \"\", 12)))\n\tuassert.Equal(t, int64(500), p.Committed())\n\tuassert.Equal(t, int64(-500), p.Available(0), \"approved with an empty treasury\")\n\tuassert.Equal(t, int64(100), p.Available(600))\n}\n\nfunc TestReviewRefusesTheVerdictItCannotPay(t *testing.T) {\n\tp := prog()\n\tr, err := p.Apply(dave, \"Ship it\", \"\", \"alpha:100,beta:400\", 10)\n\turequire.NoError(t, err)\n\turequire.NoError(t, errOf(p.Board.Vote(alice, r.ID, true, \"\", 11)))\n\turequire.NoError(t, errOf(p.Board.Vote(bob, r.ID, true, \"\", 12)))\n\turequire.NoError(t, p.Board.SubmitProof(dave, r.ID, 0, Proof{Kind: \"url\", Ref: \"https://x/1\", Height: 20}))\n\n\t// Not the deciding ballot, so the balance is irrelevant: it records.\n\tout, pay, err := p.Review(alice, r.ID, 0, true, \"looks done\", 21, 0)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"under review\", out.String())\n\tuassert.True(t, pay == nil, \"nothing to pay yet\")\n\n\t// The deciding ballot against an empty treasury changes nothing at all.\n\tout, pay, err = p.Review(bob, r.ID, 0, true, \"agreed\", 22, 99)\n\tuassert.ErrorIs(t, err, ErrUnderfunded)\n\tuassert.True(t, pay == nil)\n\tuassert.Equal(t, 1, len(r.Milestones[0].Current().Reviews), \"the ballot was not recorded\")\n\tuassert.False(t, r.Milestones[0].Released)\n\tuassert.Equal(t, 0, len(p.Payments))\n\n\t// A refusal from the same member costs the treasury nothing, so it lands,\n\t// even against a balance of zero. It does not settle anything on its own:\n\t// alice already accepted, so this is one all against a bar of two.\n\tout, pay, err = p.Review(bob, r.ID, 0, false, \"not convinced\", 23, 0)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"under review\", out.String())\n\tuassert.True(t, pay == nil)\n\tuassert.Equal(t, 2, len(r.Milestones[0].Current().Reviews), \"this one WAS recorded\")\n\n\t// The second refusal reaches the bar and closes the attempt, still with\n\t// an empty treasury, because refusing costs nothing.\n\tout, pay, err = p.Review(carol, r.ID, 0, false, \"same\", 24, 0)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"refused\", out.String())\n\tuassert.True(t, pay == nil)\n\tuassert.False(t, r.Milestones[0].Released)\n\tuassert.Equal(t, \"approved\", r.Status.String(), \"a refused proof does not kill the grant\")\n}\n\nfunc TestReviewHandsBackThePaymentToExecute(t *testing.T) {\n\tp := prog()\n\tr, err := p.Apply(dave, \"Ship it\", \"\", \"alpha:100,beta:400\", 10)\n\turequire.NoError(t, err)\n\turequire.NoError(t, errOf(p.Board.Vote(alice, r.ID, true, \"\", 11)))\n\turequire.NoError(t, errOf(p.Board.Vote(bob, r.ID, true, \"\", 12)))\n\n\turequire.NoError(t, p.Board.SubmitProof(dave, r.ID, 0, Proof{Kind: \"url\", Ref: \"https://x/1\", Height: 20}))\n\turequire.NoError(t, errOf3(p.Review(alice, r.ID, 0, true, \"\", 21, 500)))\n\tout, pay, err := p.Review(carol, r.ID, 0, true, \"\", 22, 500)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"accepted\", out.String())\n\turequire.True(t, pay != nil, \"the caller is handed a payment to execute\")\n\tuassert.Equal(t, dave.String(), pay.To.String())\n\tuassert.Equal(t, int64(100), pay.Amount)\n\tuassert.Equal(t, r.ID, pay.Request)\n\tuassert.Equal(t, 0, pay.Milestone)\n\tuassert.Equal(t, int64(22), pay.Height)\n\n\turequire.Equal(t, 1, len(p.Payments), \"and it is on the ledger\")\n\tuassert.Equal(t, int64(100), p.Disbursed())\n\tuassert.Equal(t, int64(400), p.Committed())\n\tuassert.Equal(t, int64(300), p.Available(700))\n\n\t// Second tranche completes it.\n\turequire.NoError(t, p.Board.SubmitProof(dave, r.ID, 1, Proof{Kind: \"hash\", Ref: \"deadbeef\", Height: 30}))\n\turequire.NoError(t, errOf3(p.Review(alice, r.ID, 1, true, \"\", 31, 400)))\n\tout, pay, err = p.Review(bob, r.ID, 1, true, \"\", 32, 400)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"accepted\", out.String())\n\turequire.True(t, pay != nil)\n\tuassert.Equal(t, int64(400), pay.Amount)\n\tuassert.Equal(t, \"completed\", r.Status.String())\n\tuassert.Equal(t, int64(500), p.Disbursed())\n\tuassert.Equal(t, int64(0), p.Committed())\n\tuassert.Equal(t, 2, len(p.Payments))\n}\n\n// A one-member program is a legitimate configuration (it is what a personal\n// board is), and its majority is one. It still cannot self-grant.\nfunc TestOneMemberBoard(t *testing.T) {\n\tp := NewProgram(\"ugnot\", alice)\n\tr, err := p.Apply(dave, \"Ship it\", \"\", \"alpha:100\", 10)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 1, p.Board.Eligible(r))\n\tuassert.Equal(t, 1, p.Board.Majority(r))\n\tst, err := p.Board.Vote(alice, r.ID, true, \"sure\", 11)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"approved\", st.String(), \"one signature carries a one-member board\")\n\n\town, err := p.Apply(alice, \"Pay myself\", \"\", \"alpha:100\", 12)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 0, p.Board.Eligible(own), \"the applicant is the whole board\")\n\tuassert.Equal(t, 1, p.Board.Majority(own), \"so the bar is unreachable, not zero\")\n\tuassert.ErrorIs(t, errOf(p.Board.Vote(alice, own.ID, true, \"\", 13)), ErrConflict)\n\tuassert.Equal(t, \"pending\", own.Status.String(), \"a sole member cannot self-grant\")\n}\n\nfunc errOf3(_ Outcome, _ *Payment, err error) error { return err }\n\nfunc TestTheTrancheGoesToTheBeneficiary(t *testing.T) {\n\tp := NewProgram(\"ugnot\", alice, bob)\n\tr, err := p.ApplyFor(dave, mallory, \"mallory cannot pay the gas to ask\", \"t\", \"\", \"one:700\", 10)\n\turequire.NoError(t, err)\n\tp.Board.Vote(alice, r.ID, true, \"\", 11)\n\tp.Board.Vote(bob, r.ID, true, \"\", 12)\n\turequire.NoError(t, p.Board.SubmitProof(dave, r.ID, 0, Proof{Kind: \"text\", Ref: \"done\", Height: 13}))\n\n\t_, pay, err := p.Review(alice, r.ID, 0, true, \"\", 14, 700)\n\turequire.NoError(t, err)\n\tuassert.True(t, pay == nil, \"neither party sits on the board, so both members must accept\")\n\n\t_, pay, err = p.Review(bob, r.ID, 0, true, \"\", 15, 700)\n\turequire.NoError(t, err)\n\turequire.True(t, pay != nil, \"the second accept releases it\")\n\tuassert.Equal(t, mallory.String(), pay.To.String(), \"the money goes to the payee, not the filer\")\n\tuassert.Equal(t, int64(700), pay.Amount)\n\tuassert.Equal(t, mallory.String(), p.Payments[0].To.String(), \"and so does the ledger row\")\n}\n"},{"name":"render.gno","body":"package grants\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Renderer turns a Program into the three markdown pages a grant program\n// needs: the board, one request, and the ledger. Everything that differs\n// between one program and the next is a field, so a realm's whole Render is\n// building this literal and calling it.\n//\n// Build it INSIDE Render rather than storing it in a realm global: Note is a\n// func, and Balance has to be read fresh on every call anyway.\n//\n// # Escaping\n//\n// Everything a caller typed (titles, bodies, reasons, proofs, notes) is\n// escaped here, once, through p/moul/kit/ui and p/nt/markdown/sanitize. A\n// realm does not repeat it and must not pre-escape: escaping twice shows the\n// backslashes. The realm's OWN fields below (Title, Intro, Notes, Footer) are\n// chrome, are written by whoever deployed the realm, and are emitted as-is so\n// they can carry markdown.\ntype Renderer struct {\n\tProgram  *Program\n\tTitle    string   // page heading\n\tIntro    string   // markdown under the heading, already wrapped\n\tNotes    []string // extra paragraphs on the board page: house rules, scope\n\tPath     string   // package path, for the gnokey examples\n\tLink     string   // gnoweb route prefix, e.g. \"/r/moul/grant/v0\"\n\tTreasury address  // where the money sits\n\tBalance  int64    // what it holds right now\n\tFooter   string   // closing paragraph on the board page\n\n\t// Note returns an extra callout for one request page, or \"\". Use it for\n\t// anything the library cannot know, such as a seeded request whose\n\t// applicant address has no key behind it.\n\tNote func(*Request) string\n}\n\n// Render serves the board at \"\", one request at \"request/\u003cid\u003e\", and the money\n// trail at \"ledger\".\nfunc (rr Renderer) Render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tswitch {\n\tcase path == \"\" || path == \"/\":\n\t\treturn rr.index()\n\tcase path == \"ledger\":\n\t\treturn rr.ledger()\n\tcase strings.HasPrefix(path, \"request/\"):\n\t\treturn rr.request(strings.TrimPrefix(path, \"request/\"))\n\t}\n\treturn \"# \" + rr.Title + \"\\n\\nNo page `\" + path + \"`. Try [the board](\" + rr.Link +\n\t\t\") or [the ledger](\" + rr.Link + \":ledger).\\n\"\n}\n\nfunc (rr Renderer) index() string {\n\tp := rr.Program\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + rr.Title + \"\\n\\n\")\n\tif rr.Intro != \"\" {\n\t\tb.WriteString(rr.Intro + \"\\n\\n\")\n\t}\n\tfor _, n := range rr.Notes {\n\t\tb.WriteString(n + \"\\n\\n\")\n\t}\n\n\tb.WriteString(\"## Treasury\\n\\n\")\n\tb.WriteString(\"| Field | Value |\\n|---|---|\\n\")\n\tb.WriteString(\"| Address | \" + ui.AddrFull(rr.Treasury) + \" |\\n\")\n\tb.WriteString(\"| Balance | \" + rr.amount(rr.Balance) + \" |\\n\")\n\tb.WriteString(\"| Promised | \" + rr.amount(p.Committed()) + \" |\\n\")\n\tb.WriteString(\"| Unpromised | \" + rr.amount(p.Available(rr.Balance)) + \" |\\n\")\n\tb.WriteString(\"| Donated | \" + rr.amount(p.Raised()) + \" |\\n\")\n\tb.WriteString(\"| Paid out | \" + rr.amount(p.Disbursed()) + \" |\\n\\n\")\n\tif short := -p.Available(rr.Balance); short \u003e 0 {\n\t\tb.WriteString(\"The board has promised \" + rr.amount(short) + \" more than it holds. Approving a\\n\")\n\t\tb.WriteString(\"grant does not escrow anything, so a tranche can come due against an empty\\n\")\n\t\tb.WriteString(\"treasury; a review that would release one is refused until the money is there.\\n\")\n\t\tb.WriteString(\"Top it up with `Fund`, or by sending coins straight to the address above.\\n\\n\")\n\t}\n\n\tb.WriteString(\"## Board\\n\\n\")\n\tb.WriteString(\"A decision needs a majority of the members eligible to cast a ballot on it,\\n\")\n\tb.WriteString(\"recomputed every time: the party a decision is about never votes on it, so an\\n\")\n\tb.WriteString(\"applicant who sits on the board shrinks the room rather than packing it.\\n\\n\")\n\tb.WriteString(\"| Member | Joined at height |\\n|---|---|\\n\")\n\tfor _, m := range p.Board.Members() {\n\t\tb.WriteString(\"| \" + ui.AddrFull(m) + \" | \" + i64(p.Board.JoinedAt(m)) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n\")\n\n\tb.WriteString(\"## Requests\\n\\n\")\n\tall := p.Board.List()\n\tif len(all) == 0 {\n\t\tb.WriteString(\"Nothing has been asked of this board yet. `Apply` is open to anyone.\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| # | Kind | Title | For | Asking | Status | Ballots |\\n|---|---|---|---|---|---|---|\\n\")\n\t\tfor _, r := range all {\n\t\t\tyes, no := p.Board.Standing(r)\n\t\t\tb.WriteString(\"| [\" + strconv.Itoa(r.ID) + \"](\" + rr.Link + \":request/\" + strconv.Itoa(r.ID) + \")\" +\n\t\t\t\t\" | \" + r.Kind.String() +\n\t\t\t\t\" | \" + ui.Cell(r.Title) +\n\t\t\t\t\" | \" + rr.who(r) +\n\t\t\t\t\" | \" + rr.ask(r) +\n\t\t\t\t\" | \" + r.Status.String() +\n\t\t\t\t\" | \" + strconv.Itoa(yes) + \" for, \" + strconv.Itoa(no) + \" against\" +\n\t\t\t\t\" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"## Where the money went\\n\\n\")\n\tb.WriteString(\"[The ledger](\" + rr.Link + \":ledger) lists every donation in and every tranche\\n\")\n\tb.WriteString(\"out, with the height, the payee and the milestone it paid for.\\n\\n\")\n\n\tb.WriteString(\"## Calling it\\n\\n\")\n\tb.WriteString(\"```sh\\n\")\n\tb.WriteString(\"# put money in\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath \" + rr.Path + \" -func Fund -send 5000000\" + p.Denom + \" ...\\n\")\n\tb.WriteString(\"# ask for some\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath \" + rr.Path + \" -func Apply \\\\\\n\")\n\tb.WriteString(\"  -args 'Port the thing' -args 'why it matters' -args 'design:100,ship:400' ...\\n\")\n\tb.WriteString(\"# ask on behalf of someone who cannot pay the gas to ask\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath \" + rr.Path + \" -func ApplyFor \\\\\\n\")\n\tb.WriteString(\"  -args g1... -args 'their account is empty' \\\\\\n\")\n\tb.WriteString(\"  -args 'Port the thing' -args 'why it matters' -args 'design:100,ship:400' ...\\n\")\n\tb.WriteString(\"# decide (members only)\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath \" + rr.Path + \" -func Vote -args 1 -args true -args 'reason' ...\\n\")\n\tb.WriteString(\"# show your work, then get paid for it\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath \" + rr.Path + \" -func SubmitProof \\\\\\n\")\n\tb.WriteString(\"  -args 1 -args 0 -args url -args 'https://...' -args 'what it is' ...\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath \" + rr.Path + \" -func Review -args 1 -args 0 -args true -args 'looks done' ...\\n\")\n\tb.WriteString(\"```\\n\")\n\tif rr.Footer != \"\" {\n\t\tb.WriteString(\"\\n\" + rr.Footer + \"\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc (rr Renderer) request(raw string) string {\n\tid, err := strconv.Atoi(raw)\n\tif err != nil {\n\t\treturn \"# \" + rr.Title + \"\\n\\n`\" + raw + \"` is not a request number.\\n\"\n\t}\n\tr := rr.Program.Board.Get(id)\n\tif r == nil {\n\t\treturn \"# \" + rr.Title + \"\\n\\nThere is no request \" + raw + \".\\n\"\n\t}\n\tboard := rr.Program.Board\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Request \" + strconv.Itoa(r.ID) + \": \" + ui.Inline(r.Title) + \"\\n\\n\")\n\tb.WriteString(\"| Field | Value |\\n|---|---|\\n\")\n\tb.WriteString(\"| Kind | \" + r.Kind.String() + \" |\\n\")\n\tb.WriteString(\"| Applicant | \" + ui.AddrFull(r.Applicant) + \" |\\n\")\n\tif r.OnBehalf() {\n\t\tb.WriteString(\"| Beneficiary | \" + ui.AddrFull(r.Beneficiary) + \" |\\n\")\n\t}\n\tif r.Kind == KindMember {\n\t\tb.WriteString(\"| Subject | \" + ui.AddrFull(r.Subject) + \" |\\n\")\n\t\tb.WriteString(\"| Effect | \" + addRemove(r.Add) + \" |\\n\")\n\t}\n\tb.WriteString(\"| Status | \" + r.Status.String() + \" |\\n\")\n\tb.WriteString(\"| Filed at height | \" + i64(r.CreatedAt) + \" |\\n\")\n\tif r.DecidedAt != 0 {\n\t\tb.WriteString(\"| Decided at height | \" + i64(r.DecidedAt) + \" |\\n\")\n\t}\n\tif r.Kind == KindGrant {\n\t\tb.WriteString(\"| Asking | \" + rr.amount(r.Total()) + \" |\\n\")\n\t\tb.WriteString(\"| Paid so far | \" + rr.amount(r.Paid()) + \" |\\n\")\n\t\tb.WriteString(\"| Still owed | \" + rr.amount(r.Outstanding()) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n\")\n\n\tif r.OnBehalf() {\n\t\tb.WriteString(\"## Filed for someone else\\n\\n\")\n\t\tb.WriteString(\"The applicant is not the payee: every tranche of this request pays\\n\")\n\t\tb.WriteString(ui.AddrFull(r.Beneficiary) + \". Both addresses are barred from voting on it, and\\n\")\n\t\tb.WriteString(\"either may submit a proof. The reason given:\\n\\n\")\n\t\tb.WriteString(\"\u003e \" + ui.Inline(r.Reason) + \"\\n\\n\")\n\t\tb.WriteString(\"Nothing checks that reason. It is a claim by the applicant, and the point of\\n\")\n\t\tb.WriteString(\"printing it here is that a member can check it before voting.\\n\\n\")\n\t}\n\n\tif rr.Note != nil {\n\t\tif note := rr.Note(r); note != \"\" {\n\t\t\tb.WriteString(note + \"\\n\\n\")\n\t\t}\n\t}\n\n\tif r.Body != \"\" {\n\t\tb.WriteString(\"## The ask\\n\\n\" + block(r.Body) + \"\\n\\n\")\n\t}\n\n\tb.WriteString(\"## Ballots\\n\\n\")\n\tyes, no := board.Standing(r)\n\trecorded, against := r.Tally()\n\tb.WriteString(\"Needs \" + strconv.Itoa(board.Majority(r)) + \" of \" + strconv.Itoa(board.Eligible(r)) +\n\t\t\" eligible members. Standing: \" + strconv.Itoa(yes) + \" for, \" + strconv.Itoa(no) + \" against.\\n\")\n\tif recorded != yes || against != no {\n\t\tb.WriteString(\"On the record: \" + strconv.Itoa(recorded) + \" for, \" + strconv.Itoa(against) +\n\t\t\t\" against. The difference is ballots cast by people who have since left the board;\\n\")\n\t\tb.WriteString(\"they stay on the record and stop counting.\\n\")\n\t}\n\tb.WriteString(\"\\n\")\n\tif len(r.Votes) == 0 {\n\t\tb.WriteString(\"Nobody has voted yet.\\n\\n\")\n\t} else {\n\t\tb.WriteString(rr.ballots(r.Votes, \"for\", \"against\"))\n\t}\n\n\tif r.Kind != KindGrant {\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"## Milestones\\n\\n\")\n\tb.WriteString(\"Earned in order. The applicant submits a proof, the board reviews that proof,\\n\")\n\tb.WriteString(\"and the verdict that carries also moves the coins.\\n\\n\")\n\tfor i, m := range r.Milestones {\n\t\tb.WriteString(\"### \" + strconv.Itoa(i+1) + \". \" + ui.Inline(m.Title) + \": \" + rr.amount(m.Amount) + \"\\n\\n\")\n\t\tb.WriteString(milestoneState(r, i, m) + \"\\n\\n\")\n\t\tfor j, a := range m.Attempts {\n\t\t\tb.WriteString(\"**Proof \" + strconv.Itoa(j+1) + \"** (\" + a.Proof.Kind + \", height \" +\n\t\t\t\ti64(a.Proof.Height) + \", \" + a.Outcome.String() + \")\\n\\n\")\n\t\t\tb.WriteString(fence(a.Proof.Ref) + \"\\n\\n\")\n\t\t\tif a.Proof.Note != \"\" {\n\t\t\t\tb.WriteString(block(a.Proof.Note) + \"\\n\\n\")\n\t\t\t}\n\t\t\tif len(a.Reviews) == 0 {\n\t\t\t\tb.WriteString(\"No review yet.\\n\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb.WriteString(rr.ballots(a.Reviews, \"accept\", \"refuse\"))\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc (rr Renderer) ledger() string {\n\tp := rr.Program\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + rr.Title + \": the ledger\\n\\n\")\n\tb.WriteString(\"Every coin in and every coin out, in the order it happened. Coins sent\\n\")\n\tb.WriteString(\"straight to \" + ui.AddrFull(rr.Treasury) + \" land in the treasury\\n\")\n\tb.WriteString(\"without appearing here, which is why `Fund` exists: it is the same transfer\\n\")\n\tb.WriteString(\"with a name attached.\\n\\n\")\n\n\tb.WriteString(\"## In\\n\\n\")\n\tif len(p.Donations) == 0 {\n\t\tb.WriteString(\"Nothing donated through `Fund` yet.\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| Height | From | Amount |\\n|---|---|---|\\n\")\n\t\tfor _, d := range p.Donations {\n\t\t\tb.WriteString(\"| \" + i64(d.Height) + \" | \" + ui.AddrFull(d.From) + \" | \" + rr.amount(d.Amount) + \" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\nTotal in: \" + rr.amount(p.Raised()) + \"\\n\\n\")\n\t}\n\n\tb.WriteString(\"## Out\\n\\n\")\n\tif len(p.Payments) == 0 {\n\t\tb.WriteString(\"No tranche has been released yet.\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| Height | Request | Milestone | To | Amount |\\n|---|---|---|---|---|\\n\")\n\t\tfor _, pay := range p.Payments {\n\t\t\tb.WriteString(\"| \" + i64(pay.Height) +\n\t\t\t\t\" | [\" + strconv.Itoa(pay.Request) + \"](\" + rr.Link + \":request/\" + strconv.Itoa(pay.Request) + \")\" +\n\t\t\t\t\" | \" + strconv.Itoa(pay.Milestone+1) +\n\t\t\t\t\" | \" + ui.AddrFull(pay.To) +\n\t\t\t\t\" | \" + rr.amount(pay.Amount) + \" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\nTotal out: \" + rr.amount(p.Disbursed()) + \"\\n\\n\")\n\t}\n\n\tb.WriteString(\"Balance now: \" + rr.amount(rr.Balance) + \". [Back to the board](\" + rr.Link + \").\\n\")\n\treturn b.String()\n}\n\n// ballots renders one decision's ballots, marking anyone who has since left\n// the board: their vote stays on the record and stops counting.\nfunc (rr Renderer) ballots(bs []Ballot, forLabel, againstLabel string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"| Member | Vote | Height | Reason |\\n|---|---|---|---|\\n\")\n\tfor _, v := range bs {\n\t\twho := ui.AddrFull(v.Voter)\n\t\tif !rr.Program.Board.IsMember(v.Voter) {\n\t\t\twho += \" (left the board)\"\n\t\t}\n\t\tvote := againstLabel\n\t\tif v.Approve {\n\t\t\tvote = forLabel\n\t\t}\n\t\tb.WriteString(\"| \" + who + \" | \" + vote + \" | \" + i64(v.Height) + \" | \" + orDash(ui.Cell(v.Reason)) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\nfunc (rr Renderer) amount(n int64) string { return strconv.FormatInt(n, 10) + \" \" + rr.Program.Denom }\n\n// who is the board index's \"For\" column: who this request would pay, marked\n// when that is not the address that filed it.\nfunc (rr Renderer) who(r *Request) string {\n\tif r.Kind == KindMember {\n\t\treturn \"-\"\n\t}\n\tif r.OnBehalf() {\n\t\treturn ui.Addr(r.Beneficiary) + \" (filed by \" + ui.AddrText(r.Applicant) + \")\"\n\t}\n\treturn ui.Addr(r.Applicant)\n}\n\nfunc (rr Renderer) ask(r *Request) string {\n\tif r.Kind == KindMember {\n\t\treturn \"nothing\"\n\t}\n\treturn rr.amount(r.Total())\n}\n\nfunc milestoneState(r *Request, i int, m *Milestone) string {\n\tswitch {\n\tcase m.Released:\n\t\treturn \"Released at height \" + i64(m.ReleasedAt) + \", paid to \" + ui.AddrFull(r.Payee()) + \".\"\n\tcase r.Status != Approved:\n\t\treturn \"Locked: the request is \" + r.Status.String() + \".\"\n\tcase m.Current() != nil:\n\t\treturn \"A proof is under review.\"\n\tcase i == r.Next():\n\t\treturn \"Waiting on a proof from the applicant.\"\n\t}\n\treturn \"Locked until milestone \" + strconv.Itoa(r.Next()+1) + \" is released.\"\n}\n\nfunc addRemove(add bool) string {\n\tif add {\n\t\treturn \"add to the board\"\n\t}\n\treturn \"remove from the board\"\n}\n\n// block and fence escape a multi-line, user-written string for its slot and\n// then trim the sanitizer's own trailing newlines.\n//\n// The trim is not cosmetic. gno collapses two consecutive blank lines in an\n// Example's output the way Go does, so any page that emits one can never be\n// pinned by an ExampleRender, and the only test that proves a whole page is\n// the one that stops working.\nfunc block(s string) string { return strings.TrimSpace(sanitize.Block(s)) }\n\nfunc fence(s string) string { return strings.TrimSpace(sanitize.CodeBlock(s)) }\n\nfunc i64(n int64) string { return strconv.FormatInt(n, 10) }\n\nfunc orDash(s string) string {\n\tif s == \"\" {\n\t\treturn \"-\"\n\t}\n\treturn s\n}\n"},{"name":"render_test.gno","body":"package grants\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\terin  = testutils.TestAddress(\"erin\")  // applicant, mid-delivery\n\tfrank = testutils.TestAddress(\"frank\") // donor\n\tgrace = testutils.TestAddress(\"grace\") // beneficiary of a request she did not file\n)\n\n// demo drives a program through every state the renderer has to show: a\n// membership change that executed, a donation, a grant carried over one\n// dissent, a milestone released and paid, a proof the board refused, a second\n// attempt still under review, and a request turned down flat.\n//\n// It uses the library's own API only, so if a rule changes under it the\n// pinned pages below move and the diff says exactly what changed.\nfunc demo() *Program {\n\tp := NewProgram(\"ugnot\", alice, bob, carol)\n\tp.Fund(frank, 3000, 100)\n\n\tm, _ := p.Board.SubmitMemberChange(alice, dave, true,\n\t\t\"Reviewed six of the last eight applications from the outside. Give them the seat.\", 100)\n\tp.Board.Vote(alice, m.ID, true, \"Proposed it.\", 101)\n\tp.Board.Vote(bob, m.ID, true, \"No objection.\", 102)\n\n\tg, _ := p.Apply(erin, \"Port the p/nt/avl benchmarks to gno\",\n\t\t\"Three weeks. A benchmark harness, a report on the tree rebalancing costs, \"+\n\t\t\t\"and a PR against the monorepo.\",\n\t\t\"harness merged:1200,report published:800\", 110)\n\tp.Board.Vote(alice, g.ID, true, \"Cheap for what it tells us.\", 111)\n\tp.Board.Vote(bob, g.ID, false, \"The second milestone is vague.\", 112)\n\tp.Board.Vote(carol, g.ID, true, \"Vague but bounded. Worth it.\", 113)\n\tp.Board.Vote(dave, g.ID, true, \"Agreed with carol.\", 114)\n\n\tp.Board.SubmitProof(erin, g.ID, 0, Proof{\n\t\tKind: \"url\", Ref: \"https://github.com/gnolang/gno/pull/9999\",\n\t\tNote: \"Harness merged, 14 benchmarks, runs in CI.\", Height: 120,\n\t})\n\tp.Review(alice, g.ID, 0, true, \"Merged, I reviewed it.\", 121, 3000)\n\tp.Review(carol, g.ID, 0, true, \"Confirmed.\", 122, 3000)\n\tp.Review(dave, g.ID, 0, true, \"Confirmed.\", 123, 3000)\n\n\tp.Board.SubmitProof(erin, g.ID, 1, Proof{Kind: \"text\", Ref: \"it is basically done\", Height: 130})\n\tp.Review(alice, g.ID, 1, false, \"That is not a report.\", 131, 1800)\n\tp.Review(bob, g.ID, 1, false, \"Agreed, no numbers.\", 132, 1800)\n\tp.Review(carol, g.ID, 1, false, \"Same.\", 133, 1800)\n\n\tp.Board.SubmitProof(erin, g.ID, 1, Proof{\n\t\tKind: \"url\", Ref: \"https://example.com/avl-rebalancing-costs\",\n\t\tNote: \"Rewritten with the measurements.\", Height: 140,\n\t})\n\tp.Review(alice, g.ID, 1, true, \"Much better.\", 141, 1800)\n\n\to, _ := p.ApplyFor(erin, grace, \"Her account is empty, so she cannot pay the gas to file this herself.\",\n\t\t\"Translate the onboarding guide to Portuguese\",\n\t\t\"One pass over the eight pages, reviewed by a second speaker.\",\n\t\t\"translation merged:600\", 145)\n\tp.Board.Vote(alice, o.ID, true, \"Cheap, and we have no pt-BR page at all.\", 146)\n\tp.Board.Vote(bob, o.ID, true, \"Fine.\", 147)\n\tp.Board.Vote(carol, o.ID, true, \"Fine.\", 148)\n\n\tn, _ := p.Apply(mallory, \"Rewrite gnoweb in a different framework\",\n\t\t\"Six months, one person, no migration plan.\", \"the rewrite:250000\", 150)\n\tp.Board.Vote(alice, n.ID, false, \"No migration plan and no second maintainer.\", 151)\n\tp.Board.Vote(bob, n.ID, false, \"Out of scope for this board.\", 152)\n\tp.Board.Vote(carol, n.ID, false, \"Same.\", 153)\n\treturn p\n}\n\n// view wraps demo in a Renderer configured the way a realm would. Balance is\n// 3000 donated minus the 1200 tranche already paid.\nfunc view() Renderer {\n\treturn Renderer{\n\t\tProgram:  demo(),\n\t\tTitle:    \"Example grant board\",\n\t\tIntro:    \"Anyone may ask this board for money.\",\n\t\tPath:     \"gno.land/r/example/board/v0\",\n\t\tLink:     \"/r/example/board/v0\",\n\t\tTreasury: testutils.TestAddress(\"treasury\"),\n\t\tBalance:  1800,\n\t\tFooter:   \"Built on [p/moul/grants/v0](/p/moul/grants/v0).\",\n\t}\n}\n\nfunc TestDemoReachedEveryStateTheseExamplesPin(t *testing.T) {\n\tp := demo()\n\tuassert.Equal(t, 4, p.Board.MemberCount(), \"the membership change executed\")\n\tuassert.Equal(t, 4, p.Board.Size())\n\tuassert.Equal(t, \"completed\", p.Board.Get(1).Status.String())\n\tuassert.Equal(t, \"approved\", p.Board.Get(2).Status.String())\n\tuassert.Equal(t, \"approved\", p.Board.Get(3).Status.String())\n\tuassert.Equal(t, \"rejected\", p.Board.Get(4).Status.String())\n\n\to := p.Board.Get(3)\n\tuassert.True(t, o.OnBehalf(), \"request 3 is filed by erin for grace\")\n\tuassert.Equal(t, grace.String(), o.Payee().String())\n\n\tg := p.Board.Get(2)\n\tuassert.True(t, g.Milestones[0].Released, \"one tranche paid\")\n\tuassert.Equal(t, int64(1200), p.Disbursed())\n\tuassert.Equal(t, int64(1400), p.Committed(), \"800 still owed on 2, 600 on 3\")\n\tuassert.Equal(t, int64(3000), p.Raised())\n\tuassert.Equal(t, 1, len(p.Payments))\n\tuassert.Equal(t, 2, len(g.Milestones[1].Attempts), \"one refused, one in flight\")\n\tuassert.Equal(t, \"refused\", g.Milestones[1].Attempts[0].Outcome.String())\n\tuassert.Equal(t, \"under review\", g.Milestones[1].Attempts[1].Outcome.String())\n}\n\n// Deliberately over an EMPTY program: the routing is what is under test, and\n// rendering the full demo four times costs seconds of VM time for nothing.\nfunc TestRenderUnknownPaths(t *testing.T) {\n\tv := Renderer{Program: NewProgram(\"ugnot\", alice), Title: \"Example grant board\", Link: \"/r/x/v0\"}\n\tuassert.Equal(t, \"# Example grant board\\n\\nThere is no request 99.\\n\", v.Render(\"request/99\"))\n\tuassert.Equal(t, \"# Example grant board\\n\\n`abc` is not a request number.\\n\", v.Render(\"request/abc\"))\n\tuassert.True(t, len(v.Render(\"nope\")) \u003e 0)\n\tuassert.Equal(t, v.Render(\"\"), v.Render(\"/\"), \"the root is the root either way\")\n}\n\n// ExampleRendererIndex pins the board page.\nfunc ExampleRendererIndex() {\n\tprint(view().Render(\"\"))\n\t// Output:\n\t// # Example grant board\n\t//\n\t// Anyone may ask this board for money.\n\t//\n\t// ## Treasury\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Address | `g1w3ex2ctnw4e8jh6lta047h6lta047h6llhugks` |\n\t// | Balance | 1800 ugnot |\n\t// | Promised | 1400 ugnot |\n\t// | Unpromised | 400 ugnot |\n\t// | Donated | 3000 ugnot |\n\t// | Paid out | 1200 ugnot |\n\t//\n\t// ## Board\n\t//\n\t// A decision needs a majority of the members eligible to cast a ballot on it,\n\t// recomputed every time: the party a decision is about never votes on it, so an\n\t// applicant who sits on the board shrinks the room rather than packing it.\n\t//\n\t// | Member | Joined at height |\n\t// |---|---|\n\t// | `g1v3shve2lta047h6lta047h6lta047h6lel7d9l` | 102 |\n\t// | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | 0 |\n\t// | `g1vdshymmvta047h6lta047h6lta047h6l2asz94` | 0 |\n\t// | `g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu` | 0 |\n\t//\n\t// ## Requests\n\t//\n\t// | # | Kind | Title | For | Asking | Status | Ballots |\n\t// |---|---|---|---|---|---|---|\n\t// | [1](/r/example/board/v0:request/1) | membership | Add g1v3shve2lta047h6lta047h6lta047h6lel7d9l | - | nothing | completed | 2 for, 0 against |\n\t// | [2](/r/example/board/v0:request/2) | grant | Port the p/nt/avl benchmarks to gno | `g1v4exjm…sj8d` | 2000 ugnot | approved | 3 for, 1 against |\n\t// | [3](/r/example/board/v0:request/3) | grant | Translate the onboarding guide to Portuguese | `g1vaexzc…qsw9` (filed by g1v4exjm…sj8d) | 600 ugnot | approved | 3 for, 0 against |\n\t// | [4](/r/example/board/v0:request/4) | grant | Rewrite gnoweb in a different framework | `g1d4skcm…cwc9` | 250000 ugnot | rejected | 0 for, 3 against |\n\t//\n\t// ## Where the money went\n\t//\n\t// [The ledger](/r/example/board/v0:ledger) lists every donation in and every tranche\n\t// out, with the height, the payee and the milestone it paid for.\n\t//\n\t// ## Calling it\n\t//\n\t// ```sh\n\t// # put money in\n\t// gnokey maketx call -pkgpath gno.land/r/example/board/v0 -func Fund -send 5000000ugnot ...\n\t// # ask for some\n\t// gnokey maketx call -pkgpath gno.land/r/example/board/v0 -func Apply \\\n\t//   -args 'Port the thing' -args 'why it matters' -args 'design:100,ship:400' ...\n\t// # ask on behalf of someone who cannot pay the gas to ask\n\t// gnokey maketx call -pkgpath gno.land/r/example/board/v0 -func ApplyFor \\\n\t//   -args g1... -args 'their account is empty' \\\n\t//   -args 'Port the thing' -args 'why it matters' -args 'design:100,ship:400' ...\n\t// # decide (members only)\n\t// gnokey maketx call -pkgpath gno.land/r/example/board/v0 -func Vote -args 1 -args true -args 'reason' ...\n\t// # show your work, then get paid for it\n\t// gnokey maketx call -pkgpath gno.land/r/example/board/v0 -func SubmitProof \\\n\t//   -args 1 -args 0 -args url -args 'https://...' -args 'what it is' ...\n\t// gnokey maketx call -pkgpath gno.land/r/example/board/v0 -func Review -args 1 -args 0 -args true -args 'looks done' ...\n\t// ```\n\t//\n\t// Built on [p/moul/grants/v0](/p/moul/grants/v0).\n}\n\n// ExampleRendererRequest pins the richest page: a grant mid-delivery with one\n// tranche paid, a refused proof kept on the record, and a second attempt\n// still being reviewed.\nfunc ExampleRendererRequest() {\n\tprint(view().Render(\"request/2\"))\n\t// Output:\n\t// # Request 2: Port the p/nt/avl benchmarks to gno\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Kind | grant |\n\t// | Applicant | `g1v4exjmjlta047h6lta047h6lta047h6lv8sj8d` |\n\t// | Status | approved |\n\t// | Filed at height | 110 |\n\t// | Decided at height | 114 |\n\t// | Asking | 2000 ugnot |\n\t// | Paid so far | 1200 ugnot |\n\t// | Still owed | 800 ugnot |\n\t//\n\t// ## The ask\n\t//\n\t//\n\t//\n\t// Three weeks. A benchmark harness, a report on the tree rebalancing costs, and a PR against the monorepo.\n\t//\n\t//\n\t//\n\t// ## Ballots\n\t//\n\t// Needs 3 of 4 eligible members. Standing: 3 for, 1 against.\n\t//\n\t// | Member | Vote | Height | Reason |\n\t// |---|---|---|---|\n\t// | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | for | 111 | Cheap for what it tells us\\. |\n\t// | `g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu` | against | 112 | The second milestone is vague\\. |\n\t// | `g1vdshymmvta047h6lta047h6lta047h6l2asz94` | for | 113 | Vague but bounded\\. Worth it\\. |\n\t// | `g1v3shve2lta047h6lta047h6lta047h6lel7d9l` | for | 114 | Agreed with carol\\. |\n\t//\n\t// ## Milestones\n\t//\n\t// Earned in order. The applicant submits a proof, the board reviews that proof,\n\t// and the verdict that carries also moves the coins.\n\t//\n\t// ### 1. harness merged: 1200 ugnot\n\t//\n\t// Released at height 123, paid to `g1v4exjmjlta047h6lta047h6lta047h6lv8sj8d`.\n\t//\n\t// **Proof 1** (url, height 120, accepted)\n\t//\n\t// ```\n\t// https://github.com/gnolang/gno/pull/9999\n\t// ```\n\t//\n\t//\n\t//\n\t// Harness merged, 14 benchmarks, runs in CI.\n\t//\n\t//\n\t//\n\t// | Member | Vote | Height | Reason |\n\t// |---|---|---|---|\n\t// | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | accept | 121 | Merged, I reviewed it\\. |\n\t// | `g1vdshymmvta047h6lta047h6lta047h6l2asz94` | accept | 122 | Confirmed\\. |\n\t// | `g1v3shve2lta047h6lta047h6lta047h6lel7d9l` | accept | 123 | Confirmed\\. |\n\t//\n\t// ### 2. report published: 800 ugnot\n\t//\n\t// A proof is under review.\n\t//\n\t// **Proof 1** (text, height 130, refused)\n\t//\n\t// ```\n\t// it is basically done\n\t// ```\n\t//\n\t// | Member | Vote | Height | Reason |\n\t// |---|---|---|---|\n\t// | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | refuse | 131 | That is not a report\\. |\n\t// | `g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu` | refuse | 132 | Agreed, no numbers\\. |\n\t// | `g1vdshymmvta047h6lta047h6lta047h6l2asz94` | refuse | 133 | Same\\. |\n\t//\n\t// **Proof 2** (url, height 140, under review)\n\t//\n\t// ```\n\t// https://example.com/avl-rebalancing-costs\n\t// ```\n\t//\n\t//\n\t//\n\t// Rewritten with the measurements.\n\t//\n\t//\n\t//\n\t// | Member | Vote | Height | Reason |\n\t// |---|---|---|---|\n\t// | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | accept | 141 | Much better\\. |\n}\n\n// ExampleRendererMembership pins a membership request, which asks for no\n// money and therefore renders no milestones.\nfunc ExampleRendererMembership() {\n\tprint(view().Render(\"request/1\"))\n\t// Output:\n\t// # Request 1: Add g1v3shve2lta047h6lta047h6lta047h6lel7d9l\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Kind | membership |\n\t// | Applicant | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` |\n\t// | Subject | `g1v3shve2lta047h6lta047h6lta047h6lel7d9l` |\n\t// | Effect | add to the board |\n\t// | Status | completed |\n\t// | Filed at height | 100 |\n\t// | Decided at height | 102 |\n\t//\n\t// ## The ask\n\t//\n\t//\n\t//\n\t// Reviewed six of the last eight applications from the outside. Give them the seat.\n\t//\n\t//\n\t//\n\t// ## Ballots\n\t//\n\t// Needs 2 of 3 eligible members. Standing: 2 for, 0 against.\n\t//\n\t// | Member | Vote | Height | Reason |\n\t// |---|---|---|---|\n\t// | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | for | 101 | Proposed it\\. |\n\t// | `g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu` | for | 102 | No objection\\. |\n}\n\n// ExampleRendererLedger pins the money trail.\nfunc ExampleRendererLedger() {\n\tprint(view().Render(\"ledger\"))\n\t// Output:\n\t// # Example grant board: the ledger\n\t//\n\t// Every coin in and every coin out, in the order it happened. Coins sent\n\t// straight to `g1w3ex2ctnw4e8jh6lta047h6lta047h6llhugks` land in the treasury\n\t// without appearing here, which is why `Fund` exists: it is the same transfer\n\t// with a name attached.\n\t//\n\t// ## In\n\t//\n\t// | Height | From | Amount |\n\t// |---|---|---|\n\t// | 100 | `g1veexzmntta047h6lta047h6lta047h6lthxxu5` | 3000 ugnot |\n\t//\n\t// Total in: 3000 ugnot\n\t//\n\t// ## Out\n\t//\n\t// | Height | Request | Milestone | To | Amount |\n\t// |---|---|---|---|---|\n\t// | 123 | [2](/r/example/board/v0:request/2) | 1 | `g1v4exjmjlta047h6lta047h6lta047h6lv8sj8d` | 1200 ugnot |\n\t//\n\t// Total out: 1200 ugnot\n\t//\n\t// Balance now: 1800 ugnot. [Back to the board](/r/example/board/v0).\n}\n\n// ExampleRendererOnBehalf pins a request one address filed for another: the\n// beneficiary row, the callout carrying the applicant's reason, and the \"For\"\n// column that says on the board page who the money would reach.\nfunc ExampleRendererOnBehalf() {\n\tprint(view().Render(\"request/3\"))\n\t// Output:\n\t// # Request 3: Translate the onboarding guide to Portuguese\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Kind | grant |\n\t// | Applicant | `g1v4exjmjlta047h6lta047h6lta047h6lv8sj8d` |\n\t// | Beneficiary | `g1vaexzcm9ta047h6lta047h6lta047h6lr5qsw9` |\n\t// | Status | approved |\n\t// | Filed at height | 145 |\n\t// | Decided at height | 148 |\n\t// | Asking | 600 ugnot |\n\t// | Paid so far | 0 ugnot |\n\t// | Still owed | 600 ugnot |\n\t//\n\t// ## Filed for someone else\n\t//\n\t// The applicant is not the payee: every tranche of this request pays\n\t// `g1vaexzcm9ta047h6lta047h6lta047h6lr5qsw9`. Both addresses are barred from voting on it, and\n\t// either may submit a proof. The reason given:\n\t//\n\t// \u003e Her account is empty, so she cannot pay the gas to file this herself\\.\n\t//\n\t// Nothing checks that reason. It is a claim by the applicant, and the point of\n\t// printing it here is that a member can check it before voting.\n\t//\n\t// ## The ask\n\t//\n\t// One pass over the eight pages, reviewed by a second speaker.\n\t//\n\t// ## Ballots\n\t//\n\t// Needs 3 of 4 eligible members. Standing: 3 for, 0 against.\n\t//\n\t// | Member | Vote | Height | Reason |\n\t// |---|---|---|---|\n\t// | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | for | 146 | Cheap, and we have no pt\\-BR page at all\\. |\n\t// | `g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu` | for | 147 | Fine\\. |\n\t// | `g1vdshymmvta047h6lta047h6lta047h6l2asz94` | for | 148 | Fine\\. |\n\t//\n\t// ## Milestones\n\t//\n\t// Earned in order. The applicant submits a proof, the board reviews that proof,\n\t// and the verdict that carries also moves the coins.\n\t//\n\t// ### 1. translation merged: 600 ugnot\n\t//\n\t// Waiting on a proof from the applicant.\n}\n\n// injected is every dangerous markdown sequence a caller can type, in one\n// string, so a slot that forgets to escape shows up as a live link or a\n// gnoweb tag in the assertions below rather than on a deployed page.\nconst injected = \"[click](https://evil.example) ![x](https://evil.example/p.png) \" +\n\t\"\u003cgno-columns\u003e | fake | cell | ```\\nsecond line\\n\"\n\n// injectedShort is the same attack inside the 100-character limit a title and\n// a milestone name are held to.\nconst injectedShort = \"[click](https://evil.example) \u003cgno-columns\u003e|x|\\nnext\"\n\n// TestEveryCallerSuppliedStringIsEscaped drives one board through every slot\n// a caller controls and asserts that none of them can reshape the page.\n//\n// The bar is not the same in every slot, on purpose. A one-line slot (a\n// title, a milestone name, the reason on a ballot, the reason for filing on\n// someone else's behalf) is chrome the page lays out, so nothing a caller\n// typed may survive as markup there. A prose slot (the body of an\n// application, the note on a proof) goes through sanitize.Block, which\n// PRESERVES inline links and emphasis by design: a grant application whose\n// link to the merged PR renders as literal text is a worse page, and the\n// sanitizer's own contract is that prose formats. What Block still kills is\n// everything structural, so the paragraph cannot leave its paragraph.\n//\n// Assertions are on the dangerous SEQUENCE, never on the exact escaped bytes:\n// those belong to the sanitizer, they change when it changes, and a test that\n// pins them fails for the wrong reason.\nfunc TestEveryCallerSuppliedStringIsEscaped(t *testing.T) {\n\tp := NewProgram(\"ugnot\", alice, bob)\n\tr, err := p.ApplyFor(erin, grace, injected, injectedShort, injected, injectedShort+\":100\", 10)\n\turequire.NoError(t, err)\n\tp.Board.Vote(alice, r.ID, true, injected, 11)\n\tp.Board.Vote(bob, r.ID, true, injected, 12)\n\turequire.NoError(t, p.Board.SubmitProof(erin, r.ID, 0, Proof{\n\t\tKind: \"url\", Ref: injected, Note: injected, Height: 13,\n\t}))\n\tp.Board.Review(alice, r.ID, 0, false, injected, 14)\n\n\tv := Renderer{Program: p, Title: \"Board\", Path: \"gno.land/r/x/v0\", Link: \"/r/x/v0\", Balance: 0}\n\n\t// Every structural line of every page: a table row, a heading, a\n\t// blockquote. Nothing a caller typed may render as markup in one.\n\tfor _, page := range []string{\"\", \"request/1\", \"ledger\"} {\n\t\tfor _, line := range strings.Split(v.Render(page), \"\\n\") {\n\t\t\tif !strings.HasPrefix(line, \"|\") \u0026\u0026 !strings.HasPrefix(line, \"#\") \u0026\u0026\n\t\t\t\t!strings.HasPrefix(line, \"\u003e\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, dead := range []string{\"](http\", \"![\", \"\u003cgno-\"} {\n\t\t\t\tuassert.False(t, strings.Contains(line, dead),\n\t\t\t\t\t\"page \"+page+\" line still carries \"+dead+\": \"+line)\n\t\t\t}\n\t\t}\n\t}\n\n\t// A table row keeps exactly its own cells: an unescaped pipe would open a\n\t// column and an unescaped newline would end the row early, and both\n\t// reshape the table silently rather than failing.\n\tfor _, line := range strings.Split(v.Render(\"request/1\"), \"\\n\") {\n\t\tif !strings.HasPrefix(line, \"| `\"+alice.String()+\"`\") {\n\t\t\tcontinue\n\t\t}\n\t\tuassert.Equal(t, 5, strings.Count(line, \"|\")-strings.Count(line, \"\\\\|\"),\n\t\t\t\"the ballot row kept its four cells: \"+line)\n\t}\n\n\t// An escaper that ate the content would pass every assertion above.\n\tout := v.Render(\"request/1\")\n\tuassert.True(t, strings.Contains(out, \"click\"), \"the readable text survived\")\n\tuassert.True(t, strings.Contains(out, \"second line\"), \"the second line survived\")\n\n\t// The structural attack is dead in the prose slots too, even though the\n\t// link in them is deliberately alive.\n\tbody := out[strings.Index(out, \"## The ask\"):strings.Index(out, \"## Ballots\")]\n\tuassert.False(t, strings.Contains(body, \"\\n\u003cgno-\"), \"no gnoweb tag at a line start\")\n\tuassert.False(t, strings.Contains(body, \"\\n| \"), \"prose cannot open a table\")\n\tuassert.False(t, strings.Contains(body, \"\\n#\"), \"prose cannot forge a heading\")\n}\n"}]},"send":"","max_deposit":"41000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"greet","path":"gno.land/p/moul/greet/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/greet/v0`\n\nCanary pure package: greeting helper (demonstrates versioned cross-package resolution).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/greet/v0\"\ngno = \"0.9\"\n"},{"name":"greet.gno","body":"// Package greet is a tiny pure package used as a canary: it proves that\n// versioned cross-package resolution (gno.land/p/moul/greet/v0) works in the\n// workspace and in CI. Replace or remove it once real packages land.\npackage greet\n\nimport \"strings\"\n\n// Greet returns a friendly greeting for name (defaults to \"world\").\nfunc Greet(name string) string {\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tname = \"world\"\n\t}\n\treturn \"Hello, \" + name + \"!\"\n}\n"},{"name":"greet_test.gno","body":"package greet\n\nimport \"testing\"\n\nfunc TestGreet(t *testing.T) {\n\tcases := map[string]string{\n\t\t\"\":      \"Hello, world!\",\n\t\t\"  \":    \"Hello, world!\",\n\t\t\"moul\":  \"Hello, moul!\",\n\t\t\" gno \": \"Hello, gno!\",\n\t}\n\tfor in, want := range cases {\n\t\tif got := Greet(in); got != want {\n\t\t\tt.Errorf(\"Greet(%q) = %q, want %q\", in, got, want)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"index","path":"gno.land/p/moul/kit/index/v0","files":[{"name":"README.md","body":"# index\n\nThe secondary index every realm with a store was writing by hand: a lookup from\na key a human typed to the [`store.ID`](../store)s that carry it.\n\n```go\nimport (\n\t\"gno.land/p/moul/kit/index/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\nvar notes = store.Named(\"note\")\nvar byTag index.Index // the zero value is an empty, usable index\n\nfunc Post(cur realm, tag, body string) int64 {\n\tid := notes.Add(\u0026note{Tag: tag, Body: body})\n\tif err := byTag.Add(tag, id); err != nil {\n\t\tpanic(err) // the store write is not committed either: same frame\n\t}\n\treturn int64(id)\n}\n\nfunc Render(path string) string {\n\tfor _, e := range byTag.Page(1, 20) { // keys ascending, one page\n\t\t_, _ = e.Key, e.IDs\n\t}\n\treturn \"\"\n}\n```\n\nFifth package of the `p/moul/kit/*` layer, after `ui`, `store`, `num` and\n`tally`. Live demo: [`r/moul/x/kitindexdemo`](../../../../r/moul/x/kitindexdemo).\n\n## What it is not\n\n**Not a multi-index record store.** [`p/moul/collection`](../../collection) is\nthat, and measured at n = 1,000 an update there costs **964,833 gas against the\n508,977** that created the record, because `Update` removes and re-adds every\nindex entry for every index whether or not the indexed value changed. Two\ncontainers written side by side cost a third of that, and the realm can see what\nit is paying for.\n\n**Not a bound.** An index grows with the store it indexes. The realm owns the\nbound, because only the realm knows what it is willing to pay a storage deposit\nfor.\n\n## The three decisions worth knowing\n\n**Backed by a B+ tree at fanout 128, not `avl` and not the package default of\n32.** Measured against gno master `1fc4c140e` on 2026-09-29, n = 1,000, string\nvalues:\n\n| backing | bytes/entry | gas/insert |\n|---|--:|--:|\n| `bptree` fanout 128 | 592 | 152,975 |\n| `bptree` fanout 32 | 671 | 162,161 |\n| `avl` | 2,029 | 417,811 |\n\nRaising the fanout amortises the node objects. Nothing below 592 is reachable:\nthe rest is the B+ tree's per-entry value box, which fanout cannot touch.\n\n**The ids under a key are kept ascending, not in insertion order.** So `Lookup`\ndepends on the *set* of ids and not on the order they arrived in: two realms\nthat indexed the same records in a different order render identically. A\n`Render` whose output depends on insertion history is a determinism bug, and\nthis is where it would have come from.\n\n**`Lookup` and `Each` hand out a copy.** Returning the stored slice would make\nevery caller a writer: an assignment into it corrupts the index with no write\npath having been called. A realm that passes the result onward is passing its\nown data, not a handle to ours.\n\n**The `Index` itself is a handle.** Its state sits behind one pointer, so a copy\ntaken after the first write (or of anything `Unique()` returned) is the same\nindex, and `Len` can never disagree with `Keys` about what it holds.\n\n## API\n\n| | |\n|---|---|\n| `New()`, `Unique()` | many ids per key, or at most one. The zero value is `New()` |\n| `Add(key, id) error` | idempotent for the same pair; `ErrEmptyKey`, `ErrZeroID`, `ErrDuplicateKey` |\n| `Remove(key, id) bool`, `RemoveKey(key) int` | a key whose last id goes is removed with it |\n| `Lookup(key) []store.ID`, `First(key) (store.ID, bool)` | ascending; a copy |\n| `Has`, `Count(key)`, `Keys()`, `Len()`, `IsUnique()` | `Keys` counts keys, `Len` counts pairs, and the difference is the fan-out |\n| `Each(fn) bool` | ascending by key; true means stop, matching `bptree` and `kit/store`. `fn` must not write to the index |\n| `Page(page, size) []Entry`, `Pages(size) int` | 1-based, every out-of-range page is nil (`kit/store`'s `Page` returns an empty slice instead), `Pages` is never 0 |\n\n`Add` returns an error rather than aborting, because a `p/` package does not\nknow the caller's policy. In a realm the handling is almost always `panic(err)`:\nevery one of the three is a bug in the realm rather than a value a user chose.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/kit/index/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/kit/index/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/kit/index/v0\"\ngno = \"0.9\"\n"},{"name":"index.gno","body":"// Package index is the secondary index every realm with a store was writing by\n// hand: a lookup from a key a human typed to the [store.ID]s that carry it.\n//\n// A realm keeps its records in a [gno.land/p/moul/kit/store] and answers\n// \"entry 7\". The moment it also has to answer \"every entry tagged gno\" it needs\n// a second container, and the correctness of the pair is entirely in the\n// discipline of writing both in the same function. This package owns the second\n// container and as much of that discipline as a package can.\n//\n//\tvar notes = store.Named(\"note\")\n//\tvar byTag index.Index // the zero value is an empty, usable index\n//\n//\tfunc Post(cur realm, tag, body string) int64 {\n//\t\tid := notes.Add(\u0026note{Tag: tag, Body: body})\n//\t\tif err := byTag.Add(tag, id); err != nil {\n//\t\t\tpanic(err) // the store write is not committed either: same frame\n//\t\t}\n//\t\treturn int64(id)\n//\t}\n//\n// It is NOT a multi-index record store. [gno.land/p/moul/collection] is that,\n// and at n = 1,000 an update there costs 964,833 gas against the 508,977 that\n// created the record, because it re-indexes every index whether or not the\n// indexed value changed. Two containers written side by side cost a third of\n// that and the realm can see what it is paying for.\n//\n// Live demo: r/moul/x/kitindexdemo.\npackage index\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\n// Fanout is the B+ tree fanout this package uses, and 128 is not the package\n// default of 32.\n//\n// Measured against gno master 1fc4c140e on 2026-09-29, at n = 1,000 with string\n// values: fanout 128 costs 592 bytes per entry and 152,975 gas per insert,\n// against 671 and 162,161 at fanout 32, and against avl's 2,029 and 417,811.\n// Raising the fanout amortises the node objects, and nothing below it can be\n// recovered: the remaining cost is the B+ tree's per-entry value box.\nconst Fanout = 128\n\n// Errors an Add can return. A /p/ package returns errors and lets the realm\n// decide whether they are fatal; every one of these is a programming error in\n// the realm rather than a value a user chose, so panicking on them is the\n// normal handling.\nvar (\n\t// ErrEmptyKey is returned for \"\". An empty key sorts before every real one\n\t// and is almost always an unset field rather than a deliberate bucket, so\n\t// it is refused rather than silently indexed.\n\tErrEmptyKey = errors.New(\"index: the key is empty\")\n\n\t// ErrZeroID is returned for store.ID(0), which [store.Store] never assigns,\n\t// so indexing it can only produce a lookup that cannot hit.\n\tErrZeroID = errors.New(\"index: the id is zero\")\n\n\t// ErrDuplicateKey is returned by a [Unique] index asked to attach a second\n\t// id to a key that already has one.\n\tErrDuplicateKey = errors.New(\"index: the key is already taken\")\n)\n\n// Index maps a key to the ids carrying it, ordered by key.\n//\n// The zero value is an empty, usable, non-unique index: a realm declares\n// `var byTag index.Index` and writes to it, exactly as it does with a\n// [store.Store]. Use [Unique] when at most one id may carry a key.\n//\n// An Index is a handle, like the [store.Store] it sits next to: copies taken\n// after the first write, or of anything [Unique] returned, are the same index,\n// and a write through one is seen through all of them. A copy of a zero value\n// that was never written is a separate empty index.\ntype Index struct {\n\ts *state\n}\n\n// state is everything an Index holds, behind one pointer so that a copy of the\n// handle cannot split the tree from the counter that describes it.\ntype state struct {\n\ttree   *bptree.BPTree\n\tunique bool\n\tpairs  int\n}\n\n// New returns an empty index where a key may carry many ids. It is the zero\n// value, spelled out for a caller who prefers a constructor.\nfunc New() *Index { return \u0026Index{} }\n\n// Unique returns an empty index where a key carries at most one id, and a\n// second [Index.Add] to the same key fails with [ErrDuplicateKey] instead of\n// appending.\n//\n// Unique is a constructor rather than a field or a setter because flipping it\n// on a populated index would have to either reject the duplicates already in it\n// or silently keep them, and both are worse than not offering the operation.\nfunc Unique() *Index {\n\treturn \u0026Index{s: \u0026state{tree: bptree.NewBPTreeN(Fanout), unique: true}}\n}\n\n// entry is the value stored at a key: the ids carrying it, ascending.\n//\n// A struct rather than a bare []store.ID so that a later field (a count, a\n// timestamp) does not change the stored shape, and so the slice itself is never\n// handed out by accident.\ntype entry struct {\n\tids []store.ID\n}\n\n// init materialises the state. Called by every mutating method, so the zero\n// value works without a constructor. The tree is created with the state, so a\n// non-nil state always has one.\nfunc (ix *Index) init() {\n\tif ix.s == nil {\n\t\tix.s = \u0026state{tree: bptree.NewBPTreeN(Fanout)}\n\t}\n}\n\n// Add attaches id to key.\n//\n// Adding a pair that is already present is a no-op and returns nil, so a realm\n// re-running a write is not punished for it. The ids under a key are kept\n// ascending, which makes [Index.Lookup] depend on the set of ids and not on the\n// order they arrived in: two realms that indexed the same records in a\n// different order render identically, and a Render whose output depends on\n// insertion history is the determinism bug this avoids.\nfunc (ix *Index) Add(key string, id store.ID) error {\n\tif key == \"\" {\n\t\treturn ErrEmptyKey\n\t}\n\tif id == 0 {\n\t\treturn ErrZeroID\n\t}\n\tix.init()\n\n\te, _ := ix.s.tree.Get(key).(*entry)\n\tif e == nil {\n\t\tix.s.tree.Set(key, \u0026entry{ids: []store.ID{id}})\n\t\tix.s.pairs++\n\t\treturn nil\n\t}\n\tpos, found := e.find(id)\n\tif found {\n\t\treturn nil\n\t}\n\tif ix.s.unique {\n\t\treturn ErrDuplicateKey\n\t}\n\te.ids = append(e.ids, 0)\n\tcopy(e.ids[pos+1:], e.ids[pos:])\n\te.ids[pos] = id\n\tix.s.tree.Set(key, e)\n\tix.s.pairs++\n\treturn nil\n}\n\n// Remove detaches id from key and reports whether the pair was there. A key\n// whose last id is removed is removed with it, so [Index.Keys] never counts an\n// empty bucket.\nfunc (ix *Index) Remove(key string, id store.ID) bool {\n\tif ix.s == nil {\n\t\treturn false\n\t}\n\te, _ := ix.s.tree.Get(key).(*entry)\n\tif e == nil {\n\t\treturn false\n\t}\n\tpos, found := e.find(id)\n\tif !found {\n\t\treturn false\n\t}\n\tix.s.pairs--\n\tif len(e.ids) == 1 {\n\t\tix.s.tree.Remove(key)\n\t\treturn true\n\t}\n\t// A fresh slice, not append(ids[:pos], ids[pos+1:]...).\n\t//\n\t// In gno a slice is ONE persisted object and the storage deposit comes back\n\t// when that object is dropped, at no other time: shortening in place keeps\n\t// the peak allocation charged until the whole key goes, so a key that grew\n\t// to 1,000 ids and shrank to 1 would still be paying for 1,000. Allocating\n\t// the exact size drops the old array and refunds the difference. Same O(n)\n\t// as the memmove it replaces.\n\ttrimmed := make([]store.ID, 0, len(e.ids)-1)\n\ttrimmed = append(trimmed, e.ids[:pos]...)\n\ttrimmed = append(trimmed, e.ids[pos+1:]...)\n\te.ids = trimmed\n\tix.s.tree.Set(key, e)\n\treturn true\n}\n\n// RemoveKey detaches every id from key and reports how many it detached.\nfunc (ix *Index) RemoveKey(key string) int {\n\tif ix.s == nil {\n\t\treturn 0\n\t}\n\tv, removed := ix.s.tree.Remove(key)\n\tif !removed {\n\t\treturn 0\n\t}\n\tn := len(v.(*entry).ids)\n\tix.s.pairs -= n\n\treturn n\n}\n\n// Lookup returns the ids carrying key, ascending, or nil.\n//\n// The slice is a COPY. Handing out the stored one would make every caller a\n// writer: an append past its length would be invisible to the index, and an\n// assignment into it would corrupt the index with no write path having been\n// called. A realm that returns this value onward is returning its own data,\n// not a handle to ours.\nfunc (ix *Index) Lookup(key string) []store.ID {\n\tif ix.s == nil {\n\t\treturn nil\n\t}\n\te, _ := ix.s.tree.Get(key).(*entry)\n\tif e == nil {\n\t\treturn nil\n\t}\n\tout := make([]store.ID, len(e.ids))\n\tcopy(out, e.ids)\n\treturn out\n}\n\n// First returns the lowest id carrying key. On a [Unique] index it is the only\n// one, which is the usual reason to call it.\nfunc (ix *Index) First(key string) (store.ID, bool) {\n\tif ix.s == nil {\n\t\treturn 0, false\n\t}\n\te, _ := ix.s.tree.Get(key).(*entry)\n\tif e == nil || len(e.ids) == 0 {\n\t\treturn 0, false\n\t}\n\treturn e.ids[0], true\n}\n\n// Has reports whether any id carries key.\nfunc (ix *Index) Has(key string) bool {\n\tif ix.s == nil {\n\t\treturn false\n\t}\n\treturn ix.s.tree.Has(key)\n}\n\n// Count returns how many ids carry key.\nfunc (ix *Index) Count(key string) int {\n\tif ix.s == nil {\n\t\treturn 0\n\t}\n\te, _ := ix.s.tree.Get(key).(*entry)\n\tif e == nil {\n\t\treturn 0\n\t}\n\treturn len(e.ids)\n}\n\n// Keys returns the number of distinct keys.\nfunc (ix *Index) Keys() int {\n\tif ix.s == nil {\n\t\treturn 0\n\t}\n\treturn ix.s.tree.Size()\n}\n\n// Len returns the number of (key, id) pairs, which is what the index actually\n// costs. It is NOT [Index.Keys], and the two differ by exactly the amount of\n// fan-out a realm has.\nfunc (ix *Index) Len() int {\n\tif ix.s == nil {\n\t\treturn 0\n\t}\n\treturn ix.s.pairs\n}\n\n// IsUnique reports whether this index was built by [Unique].\nfunc (ix *Index) IsUnique() bool { return ix.s != nil \u0026\u0026 ix.s.unique }\n\n// Each visits every key in ascending order with a copy of its ids, and stops\n// when fn returns true. It reports whether it stopped early.\n//\n// True means stop, matching bptree.IterCbFn and kit/store's EachUntil exactly,\n// so a callback moved between them keeps its meaning.\n//\n// fn must not call [Index.Add], [Index.Remove] or [Index.RemoveKey] on this\n// index. The walk is the B+ tree's own, which holds a position inside a leaf:\n// removing the key being visited shifts the next one into that slot and the\n// walk steps over it, and inserting one ahead of it is visited twice. Collect\n// what to change, then change it after Each returns.\nfunc (ix *Index) Each(fn func(key string, ids []store.ID) bool) bool {\n\tif ix.s == nil {\n\t\treturn false\n\t}\n\treturn ix.s.tree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\te := v.(*entry)\n\t\tids := make([]store.ID, len(e.ids))\n\t\tcopy(ids, e.ids)\n\t\treturn fn(k, ids)\n\t})\n}\n\n// Page returns page number page of size keys, ascending, each with a copy of\n// its ids.\n//\n// Pages are 1-based, and every out-of-range page (zero, negative, past the end,\n// any page of an empty index) returns nil rather than panicking, because the\n// page number usually arrives from a Render path and is user input. This is\n// NOT [store.Store.Page], which returns an empty non-nil slice past the end;\n// test with len, not with nil, when code handles both.\nfunc (ix *Index) Page(page, size int) []Entry {\n\tif ix.s == nil || page \u003c 1 || size \u003c 1 {\n\t\treturn nil\n\t}\n\t// The offset is computed in a way that cannot wrap, because\n\t// bptree.IterateByOffset normalises a NEGATIVE offset to 0: an overflowed\n\t// (page-1)*size would silently hand back page 1 for a page past the end,\n\t// which is the opposite of this method's contract.\n\t//\n\t// page \u003c= 1+(keys-1)/size bounds (page-1)*size by keys-1, so the product\n\t// cannot overflow, and it also rejects the page that starts exactly at the\n\t// end, which would otherwise come back as an empty non-nil slice while\n\t// every later page is nil.\n\tkeys := ix.s.tree.Size()\n\tif keys == 0 || page \u003e 1+(keys-1)/size {\n\t\treturn nil\n\t}\n\t//gnovet:ignore page-offset-overflow bounded by keys-1 on the line above\n\toffset := (page - 1) * size\n\n\t// The capacity follows what exists, not what was asked for, so Page(1,\n\t// maxInt) over three keys reserves three slots and not two billion.\n\troom := keys - offset\n\tif room \u003e size {\n\t\troom = size\n\t}\n\tout := make([]Entry, 0, room)\n\tix.s.tree.IterateByOffset(offset, size, func(k string, v any) bool {\n\t\te := v.(*entry)\n\t\tids := make([]store.ID, len(e.ids))\n\t\tcopy(ids, e.ids)\n\t\tout = append(out, Entry{Key: k, IDs: ids})\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Pages returns how many pages of the given size the keys fill, at least 1 so\n// a page picker always has something to render.\nfunc (ix *Index) Pages(size int) int {\n\tif size \u003c 1 {\n\t\treturn 1\n\t}\n\tn := ix.Keys()\n\tif n == 0 {\n\t\treturn 1\n\t}\n\t// 1 + (n-1)/size rather than (n+size-1)/size: the second overflows when\n\t// size is near the integer limit, wraps negative, and divides to 0, which\n\t// contradicts the \"at least 1\" this method promises and divides a page\n\t// picker by zero.\n\treturn 1 + (n-1)/size\n}\n\n// Entry is one key and the ids carrying it, as returned by [Index.Page].\ntype Entry struct {\n\tKey string\n\tIDs []store.ID\n}\n\n// find returns the position id occupies, or would occupy, in the ascending ids,\n// and whether it is already there. Binary search: a key with many ids is the\n// case this package exists for.\nfunc (e *entry) find(id store.ID) (int, bool) {\n\tlo, hi := 0, len(e.ids)\n\tfor lo \u003c hi {\n\t\tmid := int(uint(lo+hi) \u003e\u003e 1)\n\t\tswitch {\n\t\tcase e.ids[mid] == id:\n\t\t\treturn mid, true\n\t\tcase e.ids[mid] \u003c id:\n\t\t\tlo = mid + 1\n\t\tdefault:\n\t\t\thi = mid\n\t\t}\n\t}\n\treturn lo, false\n}\n"},{"name":"index_test.gno","body":"package index\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc ids(ns ...uint64) []store.ID {\n\tout := make([]store.ID, len(ns))\n\tfor i, n := range ns {\n\t\tout[i] = store.ID(n)\n\t}\n\treturn out\n}\n\nfunc equalIDs(t *testing.T, want, got []store.ID) {\n\tt.Helper()\n\turequire.Equal(t, len(want), len(got))\n\tfor i := range want {\n\t\tuassert.Equal(t, want[i].String(), got[i].String())\n\t}\n}\n\nfunc TestZeroValueIsUsable(t *testing.T) {\n\tvar ix Index\n\tuassert.Equal(t, 0, ix.Keys())\n\tuassert.Equal(t, 0, ix.Len())\n\tuassert.False(t, ix.Has(\"gno\"))\n\tuassert.Equal(t, 0, ix.Count(\"gno\"))\n\tuassert.Equal(t, 0, len(ix.Lookup(\"gno\")))\n\t_, ok := ix.First(\"gno\")\n\tuassert.False(t, ok)\n\tuassert.False(t, ix.Remove(\"gno\", 1))\n\tuassert.Equal(t, 0, ix.RemoveKey(\"gno\"))\n\tuassert.False(t, ix.Each(func(string, []store.ID) bool { return true }))\n\n\turequire.NoError(t, ix.Add(\"gno\", 1))\n\tuassert.Equal(t, 1, ix.Keys())\n}\n\n// The whole point of sorting the ids: Lookup must depend on the SET of ids, not\n// on the order they arrived in, or two realms that indexed the same records in\n// a different order render differently.\nfunc TestLookupDoesNotDependOnInsertionOrder(t *testing.T) {\n\tforward, reverse := New(), New()\n\tfor _, n := range []uint64{3, 1, 2} {\n\t\turequire.NoError(t, forward.Add(\"gno\", store.ID(n)))\n\t}\n\tfor _, n := range []uint64{2, 1, 3} {\n\t\turequire.NoError(t, reverse.Add(\"gno\", store.ID(n)))\n\t}\n\tequalIDs(t, ids(1, 2, 3), forward.Lookup(\"gno\"))\n\tequalIDs(t, ids(1, 2, 3), reverse.Lookup(\"gno\"))\n}\n\nfunc TestAddIsIdempotentForTheSamePair(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"gno\", 7))\n\turequire.NoError(t, ix.Add(\"gno\", 7))\n\tequalIDs(t, ids(7), ix.Lookup(\"gno\"))\n\tuassert.Equal(t, 1, ix.Len())\n\tuassert.Equal(t, 1, ix.Keys())\n}\n\nfunc TestAddRefusals(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tkey  string\n\t\tid   store.ID\n\t\twant error\n\t}{\n\t\t{\"empty key\", \"\", 1, ErrEmptyKey},\n\t\t{\"zero id\", \"gno\", 0, ErrZeroID},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tix := New()\n\t\t\terr := ix.Add(tc.key, tc.id)\n\t\t\turequire.ErrorIs(t, err, tc.want)\n\t\t\tuassert.Equal(t, 0, ix.Len())\n\t\t})\n\t}\n}\n\nfunc TestUniqueRefusesASecondID(t *testing.T) {\n\tix := Unique()\n\tuassert.True(t, ix.IsUnique())\n\turequire.NoError(t, ix.Add(\"moul\", 1))\n\n\terr := ix.Add(\"moul\", 2)\n\turequire.ErrorIs(t, err, ErrDuplicateKey)\n\tequalIDs(t, ids(1), ix.Lookup(\"moul\"))\n\tuassert.Equal(t, 1, ix.Len())\n\n\t// Re-adding the SAME pair is still a no-op, not a duplicate: a realm\n\t// re-running a write must not be punished for it.\n\turequire.NoError(t, ix.Add(\"moul\", 1))\n\tuassert.Equal(t, 1, ix.Len())\n}\n\n// Keys and Len answer different questions and the difference is the fan-out,\n// which is what the index actually costs.\nfunc TestKeysAndLenDiffer(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"gno\", 1))\n\turequire.NoError(t, ix.Add(\"gno\", 2))\n\turequire.NoError(t, ix.Add(\"go\", 3))\n\tuassert.Equal(t, 2, ix.Keys())\n\tuassert.Equal(t, 3, ix.Len())\n\tuassert.Equal(t, 2, ix.Count(\"gno\"))\n\tuassert.Equal(t, 1, ix.Count(\"go\"))\n\tuassert.Equal(t, 0, ix.Count(\"rust\"))\n}\n\nfunc TestRemoveDropsTheKeyWithItsLastID(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"gno\", 1))\n\turequire.NoError(t, ix.Add(\"gno\", 2))\n\n\tuassert.True(t, ix.Remove(\"gno\", 1))\n\tuassert.True(t, ix.Has(\"gno\"))\n\tequalIDs(t, ids(2), ix.Lookup(\"gno\"))\n\n\tuassert.True(t, ix.Remove(\"gno\", 2))\n\tuassert.False(t, ix.Has(\"gno\"))\n\tuassert.Equal(t, 0, ix.Keys())\n\tuassert.Equal(t, 0, ix.Len())\n\n\tuassert.False(t, ix.Remove(\"gno\", 2))\n}\n\nfunc TestRemoveKey(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"gno\", 1))\n\turequire.NoError(t, ix.Add(\"gno\", 2))\n\turequire.NoError(t, ix.Add(\"go\", 3))\n\n\tuassert.Equal(t, 2, ix.RemoveKey(\"gno\"))\n\tuassert.Equal(t, 1, ix.Keys())\n\tuassert.Equal(t, 1, ix.Len())\n\tuassert.Equal(t, 0, ix.RemoveKey(\"gno\"))\n}\n\n// A returned slice that is the stored one makes every caller a writer: an\n// assignment into it corrupts the index with no write path having been called.\nfunc TestLookupHandsOutACopy(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"gno\", 1))\n\turequire.NoError(t, ix.Add(\"gno\", 2))\n\n\tgot := ix.Lookup(\"gno\")\n\tgot[0] = store.ID(999)\n\tequalIDs(t, ids(1, 2), ix.Lookup(\"gno\"))\n}\n\nfunc TestEachIsAscendingAndStops(t *testing.T) {\n\tix := New()\n\tfor _, k := range []string{\"go\", \"gno\", \"rust\"} {\n\t\turequire.NoError(t, ix.Add(k, 1))\n\t}\n\n\tvar seen []string\n\tuassert.False(t, ix.Each(func(k string, _ []store.ID) bool {\n\t\tseen = append(seen, k)\n\t\treturn false\n\t}))\n\turequire.Equal(t, 3, len(seen))\n\tuassert.Equal(t, \"gno\", seen[0])\n\tuassert.Equal(t, \"go\", seen[1])\n\tuassert.Equal(t, \"rust\", seen[2])\n\n\tvar first string\n\tuassert.True(t, ix.Each(func(k string, _ []store.ID) bool {\n\t\tfirst = k\n\t\treturn true\n\t}))\n\tuassert.Equal(t, \"gno\", first)\n}\n\nfunc TestEachHandsOutACopy(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"gno\", 1))\n\tix.Each(func(_ string, got []store.ID) bool {\n\t\tgot[0] = store.ID(999)\n\t\treturn true\n\t})\n\tequalIDs(t, ids(1), ix.Lookup(\"gno\"))\n}\n\nfunc TestPage(t *testing.T) {\n\tix := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\"} {\n\t\turequire.NoError(t, ix.Add(k, 1))\n\t}\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tpage int\n\t\tsize int\n\t\twant []string\n\t}{\n\t\t{\"first\", 1, 2, []string{\"a\", \"b\"}},\n\t\t{\"second\", 2, 2, []string{\"c\", \"d\"}},\n\t\t{\"last, short\", 3, 2, []string{\"e\"}},\n\t\t{\"past the end\", 4, 2, nil},\n\t\t{\"page zero\", 0, 2, nil},\n\t\t{\"size zero\", 1, 0, nil},\n\t\t{\"negative page\", -1, 2, nil},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgot := ix.Page(tc.page, tc.size)\n\t\t\turequire.Equal(t, len(tc.want), len(got))\n\t\t\tfor i := range tc.want {\n\t\t\t\tuassert.Equal(t, tc.want[i], got[i].Key)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Pages is what a page picker divides by, so it is never 0.\nfunc TestPagesIsNeverZero(t *testing.T) {\n\tix := New()\n\tuassert.Equal(t, 1, ix.Pages(10))\n\tuassert.Equal(t, 1, ix.Pages(0))\n\tuassert.Equal(t, 1, ix.Pages(-1))\n\n\tfor _, k := range []string{\"a\", \"b\", \"c\"} {\n\t\turequire.NoError(t, ix.Add(k, 1))\n\t}\n\tuassert.Equal(t, 2, ix.Pages(2))\n\tuassert.Equal(t, 1, ix.Pages(3))\n\tuassert.Equal(t, 3, ix.Pages(1))\n}\n\nfunc TestFirst(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"gno\", 9))\n\turequire.NoError(t, ix.Add(\"gno\", 4))\n\n\tgot, ok := ix.First(\"gno\")\n\turequire.True(t, ok)\n\tuassert.Equal(t, \"4\", got.String())\n\n\t_, ok = ix.First(\"missing\")\n\tuassert.False(t, ok)\n}\n\n// Many ids under one key is the case this package exists for, so the binary\n// search has to hold at a size where a linear scan would still look fine.\nfunc TestManyIDsUnderOneKey(t *testing.T) {\n\tix := New()\n\tfor n := uint64(64); n \u003e= 1; n-- {\n\t\turequire.NoError(t, ix.Add(\"gno\", store.ID(n)))\n\t}\n\tuassert.Equal(t, 64, ix.Count(\"gno\"))\n\tuassert.Equal(t, 1, ix.Keys())\n\n\tgot := ix.Lookup(\"gno\")\n\turequire.Equal(t, 64, len(got))\n\tfor i, id := range got {\n\t\tuassert.Equal(t, store.ID(i+1).String(), id.String())\n\t}\n}\n\n// maxInt is the largest int, which is where unchecked arithmetic in Page and\n// Pages goes wrong.\nconst maxInt = int(^uint(0) \u003e\u003e 1)\n\n// A removed id must drop the old backing array, not merely shorten it.\n//\n// In gno a slice is ONE persisted object, and the deposit comes back when the\n// object is dropped and at no other time (EFFECTIVE_GNO.md section 2.12).\n// Shortening in place keeps the peak allocation charged until the whole key\n// goes, so a key that grew to 1,000 ids and shrank to 1 would still be paying\n// for 1,000.\n//\n// Not observable through the API, so this reads the entry directly: same\n// package, and the invariant is worth more than the encapsulation.\nfunc TestRemoveReleasesTheBackingArray(t *testing.T) {\n\tix := New()\n\tfor n := uint64(1); n \u003c= 16; n++ {\n\t\turequire.NoError(t, ix.Add(\"gno\", store.ID(n)))\n\t}\n\tfor n := uint64(1); n \u003c= 15; n++ {\n\t\tuassert.True(t, ix.Remove(\"gno\", store.ID(n)))\n\t}\n\n\te, _ := ix.s.tree.Get(\"gno\").(*entry)\n\turequire.True(t, e != nil)\n\tuassert.Equal(t, 1, len(e.ids))\n\tuassert.Equal(t, 1, cap(e.ids),\n\t\t\"the shrunk bucket still owns its peak allocation, so the deposit never comes back\")\n}\n\n// Page's contract is that a page past the end is nil. Unchecked\n// (page-1)*size wraps negative at the limit, and bptree.IterateByOffset\n// normalises a negative offset to 0, so the caller silently gets page 1.\nfunc TestPageDoesNotWrapAtTheIntegerLimit(t *testing.T) {\n\tix := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\"} {\n\t\turequire.NoError(t, ix.Add(k, 1))\n\t}\n\tuassert.Equal(t, 0, len(ix.Page(maxInt, 2)),\n\t\t\"a page past the end is nil, including when the offset would overflow\")\n\tuassert.Equal(t, 0, len(ix.Page(maxInt/2+2, 2)))\n}\n\n// A huge size must not reserve a huge slice for three keys.\nfunc TestPageCapsItsAllocationToWhatExists(t *testing.T) {\n\tix := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\"} {\n\t\turequire.NoError(t, ix.Add(k, 1))\n\t}\n\tgot := ix.Page(1, maxInt)\n\turequire.Equal(t, 3, len(got))\n\tuassert.True(t, cap(got) \u003c= 3, \"the capacity follows the keys, not the requested size\")\n}\n\n// Pages documents \"at least 1\". The ceiling n+size-1 wraps when size is the\n// limit, and the division then returns 0.\nfunc TestPagesNeverReturnsZeroAtTheIntegerLimit(t *testing.T) {\n\tix := New()\n\turequire.NoError(t, ix.Add(\"a\", 1))\n\turequire.NoError(t, ix.Add(\"b\", 1))\n\tuassert.Equal(t, 1, ix.Pages(maxInt))\n}\n\n// An Index is a handle. A copy taken after the first write must see every\n// later write through either copy, or Len (a counter) and Keys (the tree)\n// disagree about what the index holds.\nfunc TestCopiesAfterTheFirstWriteShareOneIndex(t *testing.T) {\n\tvar a Index\n\turequire.NoError(t, a.Add(\"a\", 1))\n\tb := a\n\turequire.NoError(t, b.Add(\"b\", 2))\n\tuassert.Equal(t, 2, a.Keys())\n\tuassert.Equal(t, 2, a.Len(), \"the copy wrote a pair the original does not count\")\n\tuassert.True(t, b.Remove(\"a\", 1))\n\tuassert.Equal(t, 1, a.Len())\n\n\tu := *Unique()\n\tv := u\n\turequire.NoError(t, v.Add(\"k\", 1))\n\tuassert.ErrorIs(t, u.Add(\"k\", 2), ErrDuplicateKey)\n\tuassert.Equal(t, 1, u.Len())\n}\n\n// Every out-of-range page is nil, including the one that starts exactly at\n// the end and the first page of an index that has been emptied.\nfunc TestPagePastTheEndIsAlwaysNil(t *testing.T) {\n\tix := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\"} {\n\t\turequire.NoError(t, ix.Add(k, 1))\n\t}\n\tuassert.True(t, ix.Page(2, 2) != nil)\n\tuassert.True(t, ix.Page(3, 2) == nil, \"a page starting exactly at the end is past the end\")\n\tuassert.True(t, ix.Page(4, 2) == nil)\n\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\"} {\n\t\tuassert.Equal(t, 1, ix.RemoveKey(k))\n\t}\n\tuassert.True(t, ix.Page(1, 2) == nil, \"an emptied index has no first page\")\n\n\tvar zero Index\n\tuassert.True(t, zero.Page(1, 2) == nil)\n}\n"}]},"send":"","max_deposit":"12000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"num","path":"gno.land/p/moul/kit/num/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/kit/num`\n\nNumbers, formatted for a human to read: fixed-point amounts, percentages, zero\npadding.\n\nThird package of the `p/moul/kit/*` layer\n([moul/gno-contracts#151](https://github.com/moul/gno-contracts/issues/151)),\nafter [`kit/ui`](../ui) and [`kit/store`](../store). `kit` composes the existing\npackages, it does not replace them.\n\n## Why it exists\n\nUnlike the rest of `kit`, this one is not deduplication. **Nothing in `p/moul`\nor `p/nt` turns 1234567 ugnot into `1.234567 GNOT`**, so every team that needed\nit wrote it.\n\nMeasured 2026-09-28 across the 828 `.gno` files deployed on `gnoland-1` by\nsomebody other than moul (`gnolang/tx-exports`, mainnet, genesis excluded):\n\n| who | what they wrote | copies |\n|---|---|---:|\n| the `bubblerumble` realms | `GNOT(ugnot int64)` | 5, byte-identical |\n| `kourt` | `ccAmt(n int64)` | 2 |\n| GnoSwap | `gnsDisplayScale` + `zeroPadUnsigned` + `p/gnoswap/utils.FormatUint` | 3 |\n| `bubbletreasury` | `one = int64(1_000_000)` | 1 |\n\nFive independent answers to \"show money to a human\". GnoSwap wrote a type\nswitch over `any` to turn an integer into a string, because there was nothing\nto import.\n\n## The two live implementations disagree on every input that is not positive\n\nBoth were run verbatim, 2026-09-28, not read:\n\n| ugnot | `bubblerumble`'s `GNOT` | `kourt`'s `ccAmt` | correct |\n|---:|---|---|---|\n| 1234567 | `1.234567 GNOT` | `1.234567` | ✅ both |\n| 100 | `0.0001 GNOT` | `0.0001` | ✅ both |\n| **-100** | **`0.999 GNOT`** | `-0.0001` | sign dropped, digits wrong |\n| **-1500000** | **`-1. GNOT`** | `-1.5` | not a number |\n| **-1** | **`0.99999 GNOT`** | `-0.000001` | sign dropped, digits wrong |\n| **int64 min** | `-9223372036854.24192` | **infinite recursion** | one wrong, one halts |\n\nTwo different failures from the same 8 lines:\n\n- `GNOT` computes `frac := ugnot % 1_000_000`, which is **negative** for a\n  negative amount, then feeds it to a trick (`FormatInt(1_000_000+frac)[1:]`)\n  that only works on a positive remainder. Below one GNOT the sign vanishes\n  entirely and the digits become the ten's complement.\n- `ccAmt` handles the sign correctly and then recurses on `-n`. On\n  `math.MinInt64`, `-n` is `math.MinInt64` again, still negative, so it calls\n  itself forever. Measured: stack overflow.\n\nNeither is reachable from a user-supplied negative today as far as I could\ntell, and I did not try to prove reachability either way. The point is that\nthis is 8 lines everyone rewrites, half of them get it wrong, and nobody ever\ntests the sign.\n\n## This repo is not the exception, it is the sixth case\n\nSix more copies live here, in five more implementations, and they disagree with\neach other as well:\n\n| where | shape | `gnot(-1500000)` |\n|---|---|---|\n| [`r/moul/vesting`](../../../../r/moul/vesting/vesting.gno) | `u = -u`, never trims | `-1.500000 GNOT` |\n| [`r/moul/faucet`](../../../../r/moul/faucet/render.gno) | `u = -u`, trims | `-1.5` |\n| [`p/moul/x/storagecost`](../../x/storagecost/storagecost.gno) | `amount = -amount`, trims | `-1.5` |\n| [`r/moul/x/games/lastwords`](../../../../r/moul/x/games/lastwords/lastwords.gno) | no sign handling | **`-1.-5`** |\n| [`p/moul/x/wiki`](../../x/wiki/render.gno) | no sign handling | **`-1.-5 GNOT`** |\n| [`r/moul/x/daily/wrapped`](../../../../r/moul/x/daily/wrapped/wrapped.gno) | no decimals at all | n/a |\n\n`vesting` also pads to six digits where the other four trim, so the same\namount reads `1.500000` in one realm and `1.5` in the next. All six are live on\nmainnet, so porting them is a bump each and a separate decision, not part of\nthis package.\n\n## What is here\n\n| | |\n|---|---|\n| `Dec(v, decimals)` | fixed point, trailing zeros trimmed. `Dec(1234500, 6)` is `1.2345` |\n| `DecFixed(v, decimals)` | same, padded to full width, for a column |\n| `GNOT(ugnot)` / `GNOTf(ugnot)` | `Dec(v, 6)`, without and with the unit |\n| `Pct(bps)` | basis points to a percentage. `Pct(1234)` is `12.34%` |\n| `Pad(v, width)` | `Pad(7, 3)` is `007`, because `ufmt` has no width flags |\n\nFor a GRC20, pass the token's own decimals to `Dec`: six is GNOT's, not\neveryone's.\n\n## The contract\n\n**Every function is total.** No input panics, including `math.MinInt64`, and no\ninput returns a string that is not a number. `Dec` panics on a `decimals`\noutside `[0, 19]`, which is a programming error rather than a value.\n\nThat contract is the package. It is pinned by\n`TestEveryDecimalStringParsesBack`, which parses every output back and checks\nthe sign survived: swap in either live implementation and it goes red on four\ninputs, which is how it was verified rather than assumed.\n\n## What is deliberately not here\n\n- **Thousands separators.** `1,234,567` belongs to\n  [`p/moul/x/daily/humanize`](../../x/daily/humanize), which already owns\n  `Comma`, `Bytes`, `Ordinal`, `Plural` and `Blocks`. One owner per fact. (Its\n  `Comma` returns `--9,223,372,036,854,775,808` at the int64 minimum, the same\n  `n = -n` shape as everything else on this page, and that is a bump for it\n  rather than a reason to write a second one here.)\n- **Markdown.** `Dec` returns digits. Wrap it in [`kit/ui`](../ui) or\n  [`p/moul/md`](../../md) if it needs to be bold or in a cell.\n- **Compact notation** (`1.2k`, `3.4M`). Nobody on chain has written one, so\n  building it here would be speculative generality on a public path.\n- **avl keys.** `Pad` is for display. A key that must sort in insertion order\n  belongs to [`kit/store`](../store), which has no ceiling to overflow.\n- **Parsing.** One direction only until something needs the other.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/kit/num/v0\"\ngno = \"0.9\"\n"},{"name":"num.gno","body":"// Package num formats numbers for a human to read: fixed-point amounts,\n// percentages and zero padding.\n//\n// Thousands separators are NOT here. They belong to\n// [p/moul/x/daily/humanize](/p/moul/x/daily/humanize/v1), which already owns\n// Comma, Bytes, Ordinal, Plural and Blocks.\n//\n// It exists because nothing in p/moul or p/nt did. Measured across the 828\n// .gno files deployed on gnoland-1 by someone other than moul, five\n// independent teams wrote their own ugnot-to-GNOT formatter, and the two that\n// are byte-level cousins disagree on every input that is not positive. The\n// README carries the full table.\n//\n// # The contract\n//\n// Every function here is total: no input panics, including the int64 minimum,\n// and no input returns a malformed string. That is the whole point of the\n// package, because it is precisely where the hand-rolled copies fail.\n//\n// # Where the decimals come from\n//\n// gno.land denominates GNOT in ugnot, one millionth of a GNOT, so [GNOT] is\n// [Dec] with decimals = 6. A GRC20 token declares its own decimals; pass that\n// to [Dec] rather than assuming six.\npackage num\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n// GnotDecimals is the number of decimal places between ugnot and GNOT.\nconst GnotDecimals = 6\n\n// maxDecimals caps the scale [Dec] accepts. An int64 holds at most 19 decimal\n// digits, so beyond that every value is pure fraction and the cap costs\n// nothing real while keeping the padding loop bounded.\nconst maxDecimals = 19\n\n// Dec renders v as a fixed-point decimal with the given number of places,\n// trailing zeros trimmed: Dec(1234500, 6) is \"1.2345\", Dec(2000000, 6) is \"2\".\n//\n// The sign is carried on the whole part, so Dec(-1, 6) is \"-0.000001\" and not\n// \"0.999999\". Dec panics only on a negative or out-of-range decimals, which is\n// a programming error rather than a value.\nfunc Dec(v int64, decimals int) string {\n\treturn dec(v, decimals, false)\n}\n\n// DecFixed is [Dec] without the trailing-zero trim, so every value renders at\n// the same width: DecFixed(2000000, 6) is \"2.000000\". Use it in a column.\nfunc DecFixed(v int64, decimals int) string {\n\treturn dec(v, decimals, true)\n}\n\n// GNOT renders an amount in ugnot as GNOT, with no unit: \"1.234567\".\nfunc GNOT(ugnot int64) string { return Dec(ugnot, GnotDecimals) }\n\n// GNOTf is [GNOT] with the unit appended: \"1.234567 GNOT\".\nfunc GNOTf(ugnot int64) string { return GNOT(ugnot) + \" GNOT\" }\n\n// Pct renders basis points as a percentage: Pct(1234) is \"12.34%\".\n// One basis point is a hundredth of a percent, which is the unit every fee on\n// this chain is already quoted in.\nfunc Pct(bps int64) string { return Dec(bps, 2) + \"%\" }\n\n// Pad renders v in base 10, left-padded with zeros to at least width\n// characters: Pad(7, 3) is \"007\". A negative value keeps its sign outside the\n// padding, so Pad(-7, 3) is \"-007\" and the string is width+1 long.\n//\n// It exists because ufmt supports no width flags: ufmt.Sprintf(\"%03d\", 7)\n// returns \"7\", silently.\n//\n// Pad is for DISPLAY. For an avl key that must sort in insertion order, use\n// [p/moul/kit/store](/p/moul/kit/store/v0), which has no ceiling to overflow.\nfunc Pad(v int64, width int) string {\n\tneg, m := mag(v)\n\ts := strconv.FormatUint(m, 10)\n\tif n := width - len(s); n \u003e 0 {\n\t\ts = strings.Repeat(\"0\", n) + s\n\t}\n\tif neg {\n\t\treturn \"-\" + s\n\t}\n\treturn s\n}\n\nfunc dec(v int64, decimals int, fixed bool) string {\n\tif decimals \u003c 0 || decimals \u003e maxDecimals {\n\t\tpanic(\"num: decimals out of range [0, 19]\")\n\t}\n\tneg, m := mag(v)\n\tsign := \"\"\n\tif neg {\n\t\tsign = \"-\"\n\t}\n\tif decimals == 0 {\n\t\treturn sign + strconv.FormatUint(m, 10)\n\t}\n\n\tdigits := strconv.FormatUint(m, 10)\n\tif n := decimals + 1 - len(digits); n \u003e 0 {\n\t\tdigits = strings.Repeat(\"0\", n) + digits\n\t}\n\tcut := len(digits) - decimals\n\twhole, frac := digits[:cut], digits[cut:]\n\n\tif !fixed {\n\t\tfrac = strings.TrimRight(frac, \"0\")\n\t\tif frac == \"\" {\n\t\t\treturn sign + whole\n\t\t}\n\t}\n\treturn sign + whole + \".\" + frac\n}\n\n// mag splits v into a sign and an unsigned magnitude.\n//\n// -v on math.MinInt64 is math.MinInt64 again, so every shape that stays in\n// int64 is wrong there: `if v \u003c 0 { v = -v }` silently keeps the value\n// negative, and a recursive `return \"-\" + f(-v)` never terminates at all. Both\n// are live on gnoland-1 today; the second halts the realm.\n//\n// `uint64(-v)` happens to give the right answer by twos-complement wraparound,\n// but it gets it from the overflow rather than despite it. -(v+1)+1 never\n// overflows, so it does not depend on that.\nfunc mag(v int64) (bool, uint64) {\n\tif v \u003c 0 {\n\t\treturn true, uint64(-(v+1)) + 1\n\t}\n\treturn false, uint64(v)\n}\n"},{"name":"num_test.gno","body":"package num\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst minInt64 = -9223372036854775808\n\nfunc TestDec(t *testing.T) {\n\tcases := []struct {\n\t\tname     string\n\t\tv        int64\n\t\tdecimals int\n\t\twant     string\n\t}{\n\t\t{\"whole\", 2000000, 6, \"2\"},\n\t\t{\"trimmed\", 1234500, 6, \"1.2345\"},\n\t\t{\"full\", 1234567, 6, \"1.234567\"},\n\t\t{\"zero\", 0, 6, \"0\"},\n\t\t{\"sub-unit\", 100, 6, \"0.0001\"},\n\t\t{\"smallest unit\", 1, 6, \"0.000001\"},\n\t\t{\"no decimals\", 42, 0, \"42\"},\n\t\t{\"negative whole\", -2000000, 6, \"-2\"},\n\t\t{\"negative fraction\", -1500000, 6, \"-1.5\"},\n\t\t{\"negative sub-unit\", -100, 6, \"-0.0001\"},\n\t\t{\"negative smallest unit\", -1, 6, \"-0.000001\"},\n\t\t{\"two decimals\", 1234, 2, \"12.34\"},\n\t\t{\"int64 max\", 9223372036854775807, 6, \"9223372036854.775807\"},\n\t\t{\"int64 min\", minInt64, 6, \"-9223372036854.775808\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, Dec(tc.v, tc.decimals))\n\t\t})\n\t}\n}\n\nfunc TestDecFixedKeepsWidth(t *testing.T) {\n\tcases := []struct {\n\t\tv    int64\n\t\twant string\n\t}{\n\t\t{2000000, \"2.000000\"},\n\t\t{1234500, \"1.234500\"},\n\t\t{0, \"0.000000\"},\n\t\t{-1, \"-0.000001\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, DecFixed(tc.v, 6))\n\t}\n}\n\n// TestEveryDecimalStringParsesBack is the invariant the hand-rolled copies\n// break: whatever comes out must be a number again. \"-1.\" and \"0.999\" for a\n// negative input both fail here, which is what the two live implementations\n// return.\nfunc TestEveryDecimalStringParsesBack(t *testing.T) {\n\tvalues := []int64{\n\t\t0, 1, -1, 100, -100, 999999, -999999, 1000000, -1000000,\n\t\t1234567, -1234567, 9223372036854775807, minInt64,\n\t}\n\tfor _, v := range values {\n\t\tfor _, fixed := range []bool{false, true} {\n\t\t\tgot := dec(v, 6, fixed)\n\t\t\tf, err := strconv.ParseFloat(got, 64)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"dec(%d, 6, %t) = %q, not a number: %v\", v, fixed, got, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (v \u003c 0) != (f \u003c 0) \u0026\u0026 f != 0 {\n\t\t\t\tt.Errorf(\"dec(%d, 6, %t) = %q, sign flipped\", v, fixed, got)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// TestMagnitudeSurvivesTheInt64Minimum pins the one input that makes the\n// obvious implementations fail. `-v` on the minimum is the minimum again, so a\n// `if v \u003c 0 { v = -v }` keeps it negative and a recursive `\"-\" + f(-v)` never\n// terminates. A mainnet realm does the second.\nfunc TestMagnitudeSurvivesTheInt64Minimum(t *testing.T) {\n\tneg, m := mag(minInt64)\n\tuassert.True(t, neg)\n\tuassert.Equal(t, \"9223372036854775808\", strconv.FormatUint(m, 10))\n}\n\nfunc TestGNOT(t *testing.T) {\n\tuassert.Equal(t, \"1.234567\", GNOT(1234567))\n\tuassert.Equal(t, \"1.234567 GNOT\", GNOTf(1234567))\n\tuassert.Equal(t, \"0 GNOT\", GNOTf(0))\n\tuassert.Equal(t, \"-1.5 GNOT\", GNOTf(-1500000))\n}\n\nfunc TestPct(t *testing.T) {\n\tuassert.Equal(t, \"12.34%\", Pct(1234))\n\tuassert.Equal(t, \"1%\", Pct(100))\n\tuassert.Equal(t, \"0.01%\", Pct(1))\n\tuassert.Equal(t, \"0%\", Pct(0))\n\tuassert.Equal(t, \"-12.34%\", Pct(-1234))\n}\n\nfunc TestPad(t *testing.T) {\n\tcases := []struct {\n\t\tv     int64\n\t\twidth int\n\t\twant  string\n\t}{\n\t\t{7, 3, \"007\"},\n\t\t{123, 3, \"123\"},\n\t\t{1234, 3, \"1234\"},\n\t\t{0, 2, \"00\"},\n\t\t{7, 0, \"7\"},\n\t\t{-7, 3, \"-007\"},\n\t\t{minInt64, 3, \"-9223372036854775808\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, Pad(tc.v, tc.width))\n\t}\n}\n\nfunc TestDecRejectsAnImpossibleScale(cur realm, t *testing.T) {\n\tmsg := \"num: decimals out of range [0, 19]\"\n\tuassert.PanicsWithMessage(t, cur, msg, func() { Dec(1, -1) })\n\tuassert.PanicsWithMessage(t, cur, msg, func() { Dec(1, 20) })\n\tuassert.NotPanics(t, cur, func() { Dec(1, 0) })\n\tuassert.NotPanics(t, cur, func() { Dec(1, 19) })\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"tally","path":"gno.land/p/moul/kit/tally/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/kit/tally`\n\nOrder a scoreboard: highest score first, ties broken by key.\n\nFourth package of the `p/moul/kit/*` layer\n([moul/gno-contracts#151](https://github.com/moul/gno-contracts/issues/151)), after\n[`ui`](../ui), [`store`](../store) and [`num`](../num). `kit` composes the existing\npackages, it does not replace them.\n\n## Why it exists\n\ngno has **no `sort.Slice`**. Ordering anything therefore needs a named type with\n`Len`, `Less` and `Swap`, so every realm that shows a leaderboard writes one.\n\nMeasured on `main`, 2026-09-28: **16 packages carry their own `sort.Interface`\ntriple.** They are not all the same shape, so here is the honest split, by how\nmany score clauses the comparator has before its final return:\n\n| shape | packages | fits this package? |\n|---|---|---|\n| **one score, then a tie-break** | `kudos`, `leaderboard`, `multiset`, `pixelcanvas`, `prorata`, `reactions`, `streak`, `tamagotchi` | **yes, 8 of the 16** |\n| two scores, then a tie-break | `collatz`, `idle`, `kingofdice`, `rpgroom`, `streaks`, `tipjar` | no |\n| not a scoreboard | `eggling`, `semverdemo` | no |\n\nSo this package targets **8**, and it says so rather than claiming 16. A\ntwo-score board (`idle` ranks on prestige, then lifetime, then owner) has a\ngenuinely domain-specific comparator, and flattening it into one `int64` would\nbe a worse API than the triple it replaced.\n\n## What the 16 disagree on: the tie\n\nThe final clause of `Less` is what decides two equal scores, and it is the\nclause everyone writes differently:\n\n| final clause | realms |\n|---|---|\n| the key, as `addr.String()` | `idle`, `kingofdice`, `leaderboard`, `streaks`, `tamagotchi`, `tipjar` |\n| the key, as a bare string | `kudos`, `pixelcanvas`, `streak` |\n| a domain field (`Elem`, `N`, `emoji`, `index`) | `multiset`, `collatz`, `reactions`, `prorata` |\n| **the score again** | **`rpgroom`** |\n\n`rpgroom`'s third clause is `return r[i].Kills \u003e r[j].Kills`, after `Level` and\n`XP`. That is **not a total order**: two heroes equal on all three compare\n`false` in both directions, so their order is whatever the sort algorithm did\nwith the input. It is reproducible (`heroes.Iterate` walks an avl tree, and\n`sort.Sort` is deterministic), so this is not a consensus bug, but nobody chose\nthat order and nothing pins it.\n\n`Sort` always ends on `Key`, so the answer is the same one every time and it is\nexplicable to a reader.\n\n## What is here\n\n| | |\n|---|---|\n| `Sort(entries)` | in place, highest first, ties by key |\n| `Top(entries, n)` | the n highest, **copied**, so the caller's slice is untouched |\n| `Rank(entries, key)` | 1-based, `0` if absent, and **never a tie**: equal scores still get distinct places |\n| `Board` | `NewBoard`, `Add`, `Set`, `Score`, `Has`, `Remove`, `Len`, `Entries`, `Top`, `Rank` |\n\nTwo entry points on purpose. The 16 above already own their state and adopt by\nmapping it to `[]Entry`; a realm starting fresh reaches for `Board` and gets the\nstorage too.\n\n`Board` is backed by an **avl tree, not a map**. gno map iteration order is\nunspecified, so a `Render` built by ranging a map is not reproducible.\n`TestBoardOrderDoesNotDependOnInsertion` pins it.\n\n## What is deliberately not here\n\n- **Rendering.** A podium, a table and address shortening belong to\n  [`kit/ui`](../ui). This package returns rows.\n- **Scores that are not `int64`.** Nothing on chain ranks by a float, and gno\n  has no float determinism worth relying on for consensus output.\n- **Stable sort.** `Sort` is a total order, so stability is not observable.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/kit/tally/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/kit/tally/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/kit/tally/v0\"\ngno = \"0.9\"\n"},{"name":"tally.gno","body":"// Package tally orders a scoreboard: highest score first, ties broken by key.\n//\n// Sixteen realms in this repo carry their own sort.Interface triple, because\n// gno has no sort.Slice and every leaderboard therefore needs a named type\n// with Len, Less and Swap. Eight of them rank on ONE score and then break the\n// tie, which is what this package is; the rest rank on two scores and keep\n// their own comparator. They do not agree on what happens at a tie, and one of\n// them does not break ties at all.\n//\n// # The tie-break is the point\n//\n// A Render that reshuffles between identical calls is a bug, so the final\n// comparison must be a total order. Comparing the score again (as\n// r/moul/x/daily/rpgroom's third clause does) is not one: two rows with equal\n// scores compare false in both directions, and their order then falls out of\n// whatever the sort algorithm did with the input, which is reproducible but\n// nobody chose it. [Sort] always ends on the key, so equal scores render in a\n// stable, explicable order.\n//\n// # What is not here\n//\n// Storage: the caller keeps its own avl tree and maps it to [Entry]. That is\n// what makes this adoptable by realms that already have their state, and\n// [Board] is for new ones that do not.\n//\n// Rendering: a podium and a table already have an owner in\n// [p/moul/kit/ui](/p/moul/kit/ui/v0).\npackage tally\n\nimport (\n\t\"sort\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Entry is one row of a scoreboard: an opaque key and its score.\n//\n// Key is whatever the caller ranks by, usually an address in its String form.\n// It is the tie-break, so it must be unique within one board.\ntype Entry struct {\n\tKey   string\n\tScore int64\n}\n\ntype byScore []Entry\n\nfunc (e byScore) Len() int      { return len(e) }\nfunc (e byScore) Swap(i, j int) { e[i], e[j] = e[j], e[i] }\nfunc (e byScore) Less(i, j int) bool {\n\tif e[i].Score != e[j].Score {\n\t\treturn e[i].Score \u003e e[j].Score\n\t}\n\treturn e[i].Key \u003c e[j].Key\n}\n\n// Sort orders entries in place: highest score first, ties by key ascending.\nfunc Sort(entries []Entry) { sort.Sort(byScore(entries)) }\n\n// Top returns the n highest entries, sorted. A n at or below zero returns\n// nothing; a n past the end returns everything. The input is not modified.\nfunc Top(entries []Entry, n int) []Entry {\n\tif n \u003c= 0 || len(entries) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]Entry, len(entries))\n\tcopy(out, entries)\n\tSort(out)\n\tif n \u003e len(out) {\n\t\tn = len(out)\n\t}\n\treturn out[:n]\n}\n\n// Rank returns the 1-based position of key once entries are sorted, or 0 if\n// the key is absent. Equal scores still get distinct ranks, decided by the\n// same key tie-break Sort uses, so no two rows ever claim the same place.\nfunc Rank(entries []Entry, key string) int {\n\tsorted := make([]Entry, len(entries))\n\tcopy(sorted, entries)\n\tSort(sorted)\n\tfor i, e := range sorted {\n\t\tif e.Key == key {\n\t\t\treturn i + 1\n\t\t}\n\t}\n\treturn 0\n}\n\n// Board is a scoreboard that owns its storage, for a realm that does not\n// already have one. It is backed by a tree rather than a map: gno map\n// iteration order is unspecified, and a Render built on one is not\n// reproducible.\ntype Board struct {\n\tscores *avl.Tree // key -\u003e int64\n}\n\n// NewBoard returns an empty Board.\nfunc NewBoard() *Board { return \u0026Board{scores: avl.NewTree()} }\n\n// Add increases key's score by delta, which may be negative, and returns the\n// new score. A key that was absent starts at zero.\nfunc (b *Board) Add(key string, delta int64) int64 {\n\tn := b.Score(key) + delta\n\tb.scores.Set(key, n)\n\treturn n\n}\n\n// Set replaces key's score outright.\nfunc (b *Board) Set(key string, score int64) { b.scores.Set(key, score) }\n\n// Score returns key's score, or zero if it has none. It does not distinguish\n// an absent key from one scoring zero; use [Board.Has] when that matters.\nfunc (b *Board) Score(key string) int64 {\n\tv := b.scores.Get(key)\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(int64)\n}\n\n// Has reports whether key has been scored at all.\nfunc (b *Board) Has(key string) bool { return b.scores.Get(key) != nil }\n\n// Remove drops key, reporting whether it was there.\nfunc (b *Board) Remove(key string) bool {\n\t_, removed := b.scores.Remove(key)\n\treturn removed\n}\n\n// Len is the number of scored keys.\nfunc (b *Board) Len() int { return b.scores.Size() }\n\n// Entries returns every row, sorted by [Sort].\nfunc (b *Board) Entries() []Entry {\n\tout := make([]Entry, 0, b.scores.Size())\n\tb.scores.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tout = append(out, Entry{Key: k, Score: v.(int64)})\n\t\treturn false\n\t})\n\tSort(out)\n\treturn out\n}\n\n// Top returns the n highest rows, sorted.\nfunc (b *Board) Top(n int) []Entry { return Top(b.Entries(), n) }\n\n// Rank returns key's 1-based position, or 0 if it is not on the board.\nfunc (b *Board) Rank(key string) int {\n\tif !b.Has(key) {\n\t\treturn 0\n\t}\n\treturn Rank(b.Entries(), key)\n}\n"},{"name":"tally_test.gno","body":"package tally\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc keys(entries []Entry) string {\n\tout := \"\"\n\tfor i, e := range entries {\n\t\tif i \u003e 0 {\n\t\t\tout += \",\"\n\t\t}\n\t\tout += e.Key\n\t}\n\treturn out\n}\n\nfunc TestSortOrdersByScoreThenKey(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   []Entry\n\t\twant string\n\t}{\n\t\t{\"already ordered\", []Entry{{\"a\", 3}, {\"b\", 2}, {\"c\", 1}}, \"a,b,c\"},\n\t\t{\"reversed\", []Entry{{\"c\", 1}, {\"b\", 2}, {\"a\", 3}}, \"a,b,c\"},\n\t\t{\"all tied, key decides\", []Entry{{\"c\", 5}, {\"a\", 5}, {\"b\", 5}}, \"a,b,c\"},\n\t\t{\"partial tie\", []Entry{{\"z\", 1}, {\"b\", 9}, {\"a\", 9}}, \"a,b,z\"},\n\t\t{\"negatives sort below\", []Entry{{\"a\", -1}, {\"b\", 0}, {\"c\", 1}}, \"c,b,a\"},\n\t\t{\"single\", []Entry{{\"only\", 7}}, \"only\"},\n\t\t{\"empty\", nil, \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tin := make([]Entry, len(tc.in))\n\t\t\tcopy(in, tc.in)\n\t\t\tSort(in)\n\t\t\tuassert.Equal(t, tc.want, keys(in))\n\t\t})\n\t}\n}\n\n// TestSortIsATotalOrder is the defect this package exists to remove. A\n// comparator whose last clause repeats the score (rpgroom's third clause) is\n// not a total order: two equal rows compare false both ways and their order is\n// decided by the algorithm. Sorting twice from different inputs must agree.\nfunc TestSortIsATotalOrder(t *testing.T) {\n\ta := []Entry{{\"x\", 5}, {\"y\", 5}, {\"z\", 5}, {\"w\", 9}}\n\tb := []Entry{{\"z\", 5}, {\"w\", 9}, {\"y\", 5}, {\"x\", 5}}\n\tSort(a)\n\tSort(b)\n\tuassert.Equal(t, keys(a), keys(b))\n\tuassert.Equal(t, \"w,x,y,z\", keys(a))\n}\n\nfunc TestTop(t *testing.T) {\n\tin := []Entry{{\"c\", 1}, {\"a\", 3}, {\"b\", 2}}\n\tuassert.Equal(t, \"a,b\", keys(Top(in, 2)))\n\tuassert.Equal(t, \"a,b,c\", keys(Top(in, 10)))\n\tuassert.Equal(t, \"\", keys(Top(in, 0)))\n\tuassert.Equal(t, \"\", keys(Top(in, -1)))\n\tuassert.Equal(t, \"\", keys(Top(nil, 3)))\n}\n\n// TestTopDoesNotDisturbTheCaller pins that Top copies. A realm that renders a\n// Top(3) and then iterates its own slice must not find it reordered.\nfunc TestTopDoesNotDisturbTheCaller(t *testing.T) {\n\tin := []Entry{{\"c\", 1}, {\"a\", 3}, {\"b\", 2}}\n\t_ = Top(in, 2)\n\tuassert.Equal(t, \"c,a,b\", keys(in))\n}\n\nfunc TestRank(t *testing.T) {\n\tin := []Entry{{\"c\", 1}, {\"a\", 3}, {\"b\", 2}}\n\tuassert.Equal(t, 1, Rank(in, \"a\"))\n\tuassert.Equal(t, 2, Rank(in, \"b\"))\n\tuassert.Equal(t, 3, Rank(in, \"c\"))\n\tuassert.Equal(t, 0, Rank(in, \"absent\"))\n}\n\n// TestRankNeverTies is what makes a rendered \"#3\" mean something: two equal\n// scores still get 2 and 3, never 2 and 2.\nfunc TestRankNeverTies(t *testing.T) {\n\tin := []Entry{{\"a\", 5}, {\"b\", 5}, {\"c\", 5}}\n\tseen := map[int]bool{}\n\tfor _, e := range in {\n\t\tr := Rank(in, e.Key)\n\t\tif seen[r] {\n\t\t\tt.Errorf(\"rank %d claimed twice\", r)\n\t\t}\n\t\tseen[r] = true\n\t}\n\tuassert.Equal(t, 3, len(seen))\n}\n\nfunc TestBoardAddAndScore(t *testing.T) {\n\tb := NewBoard()\n\tuassert.Equal(t, 0, b.Len())\n\tuassert.Equal(t, int64(5), b.Add(\"a\", 5))\n\tuassert.Equal(t, int64(8), b.Add(\"a\", 3))\n\tuassert.Equal(t, int64(6), b.Add(\"a\", -2))\n\tuassert.Equal(t, int64(6), b.Score(\"a\"))\n\tuassert.Equal(t, int64(0), b.Score(\"never\"))\n\tuassert.Equal(t, 1, b.Len())\n}\n\nfunc TestBoardHasDistinguishesAbsentFromZero(t *testing.T) {\n\tb := NewBoard()\n\tb.Set(\"zero\", 0)\n\tuassert.True(t, b.Has(\"zero\"))\n\tuassert.False(t, b.Has(\"absent\"))\n\tuassert.Equal(t, int64(0), b.Score(\"zero\"))\n\tuassert.Equal(t, int64(0), b.Score(\"absent\"))\n}\n\nfunc TestBoardRemove(t *testing.T) {\n\tb := NewBoard()\n\tb.Set(\"a\", 1)\n\tuassert.True(t, b.Remove(\"a\"))\n\tuassert.False(t, b.Remove(\"a\"))\n\tuassert.Equal(t, 0, b.Len())\n}\n\nfunc TestBoardEntriesAndTop(t *testing.T) {\n\tb := NewBoard()\n\tb.Set(\"c\", 1)\n\tb.Set(\"a\", 3)\n\tb.Set(\"b\", 3)\n\tuassert.Equal(t, \"a,b,c\", keys(b.Entries()))\n\tuassert.Equal(t, \"a,b\", keys(b.Top(2)))\n\tuassert.Equal(t, 1, b.Rank(\"a\"))\n\tuassert.Equal(t, 2, b.Rank(\"b\"))\n\tuassert.Equal(t, 0, b.Rank(\"absent\"))\n}\n\n// TestBoardOrderDoesNotDependOnInsertion is the reason Board is backed by a\n// tree and not a map: the same scores inserted in a different order must\n// render identically.\nfunc TestBoardOrderDoesNotDependOnInsertion(t *testing.T) {\n\tone := NewBoard()\n\tfor _, e := range []Entry{{\"a\", 5}, {\"b\", 5}, {\"c\", 9}} {\n\t\tone.Set(e.Key, e.Score)\n\t}\n\ttwo := NewBoard()\n\tfor _, e := range []Entry{{\"c\", 9}, {\"b\", 5}, {\"a\", 5}} {\n\t\ttwo.Set(e.Key, e.Score)\n\t}\n\tuassert.Equal(t, keys(one.Entries()), keys(two.Entries()))\n\tuassert.Equal(t, \"c,a,b\", keys(one.Entries()))\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"mdlist","path":"gno.land/p/moul/mdlist/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/mdlist`\n\n\u003e 🧪 **Proof of concept.** It explores a composable-UI idea rather than\n\u003e offering a settled API.\n\nThe idea: a realm should describe its data once and choose the presentation at\nRender time, instead of building a different string for each layout.\n\n```go\nentries := mdlist.Entries{\n\t{Title: \"First\", Body: \"Some text\", Link: \"/r/x:1\"},\n\t{Title: \"Second\", Body: \"More text\", Link: \"/r/x:2\"},\n}\n\nout := entries.BulletList()       // or NumberedList, Paragraphs, Columns\n```\n\n| method | output |\n| --- | --- |\n| `BulletList()` | `- **Title** body` |\n| `NumberedList()` | `1. **Title** body` |\n| `Paragraphs()` | bold title, then the body as a paragraph |\n| `Columns()` | a grid |\n| `BulletListTruncated(t, b)` | as above, title and body cut to `t` / `b` runes |\n| `NumberedListTruncated(t, b)` | same |\n\nOne `Entries` value, six renderings. A realm that stores its data as `Entries`\ncan switch layout from a query parameter, and a caller embedding that realm's\nlist can pick the shape that fits its own page.\n\nTruncation takes explicit limits rather than guessing, because the right cut\ndepends on where the list is being embedded.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/mdlist/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/mdlist/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/mdlist/v0\"\ngno = \"0.9\"\n"},{"name":"mdlist.gno","body":"// Package mdlist is a proof-of-concept for composable UIs patterns.\n//\n// It allows specifying a data source and then dynamically rendering it as\n// a list or a grid.\npackage mdlist\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n)\n\n// XXX: configurable length UL\n// XXX: moul/pager.Pager-powered auto mdlist\n// XXX: func (l List) Render(path string) string {\n// XXX: add .Table()\n\ntype Entries []Entry\n\ntype Entry struct {\n\t// Title is the title of the entry. Required.\n\tTitle string\n\t// Body is the body of the entry. Required.\n\tBody string\n\t// Link is the URL of the entry. Optional.\n\tLink string\n\t// Links is a list of additional URLs of the entry. Optional.\n\tLinks []string\n}\n\n// BulletList returns entries as a markdown bullet list without truncation.\nfunc (l Entries) BulletList() string {\n\treturn l.BulletListTruncated(-1, -1)\n}\n\n// BulletListTruncated returns entries as a markdown bullet list with truncation.\nfunc (l Entries) BulletListTruncated(titleMaxLength, bodyMaxLength int) string {\n\titems := make([]string, len(l))\n\tfor i, entry := range l {\n\t\ttitle := truncateText(entry.Title, titleMaxLength, false)\n\t\tif entry.Link != \"\" {\n\t\t\ttitle = md.Link(title, entry.Link)\n\t\t}\n\t\tbody := truncateText(entry.Body, bodyMaxLength, true)\n\t\tlinks := strings.Join(entry.Links, \" \")\n\t\titem := md.Bold(title) + \": \" + md.Italic(body) + \" \" + links\n\t\titems[i] = strings.TrimSpace(item)\n\t}\n\treturn md.BulletList(items)\n}\n\n// NumberedList returns entries as a markdown numbered list without truncation.\nfunc (l Entries) NumberedList() string {\n\treturn l.NumberedListTruncated(-1, -1)\n}\n\n// NumberedListTruncated returns entries as a markdown numbered list with truncation.\nfunc (l Entries) NumberedListTruncated(titleMaxLength, bodyMaxLength int) string {\n\titems := make([]string, len(l))\n\tfor i, entry := range l {\n\t\ttitle := truncateText(entry.Title, titleMaxLength, false)\n\t\tif entry.Link != \"\" {\n\t\t\ttitle = md.Link(title, entry.Link)\n\t\t}\n\t\tbody := truncateText(entry.Body, bodyMaxLength, true)\n\t\tlinks := strings.Join(entry.Links, \" \")\n\t\titem := md.Bold(title) + \": \" + md.Italic(body) + \" \" + links\n\t\titems[i] = strings.TrimSpace(item)\n\t}\n\treturn md.OrderedList(items)\n}\n\n// Paragraphs returns entries as simple paragraphs with bold titles.\nfunc (l Entries) Paragraphs() string {\n\tparagraphs := make([]string, len(l))\n\tfor i, entry := range l {\n\t\ttitle := entry.Title\n\t\tif entry.Link != \"\" {\n\t\t\ttitle = md.Link(title, entry.Link)\n\t\t}\n\t\tparagraph := md.Bold(title) + \". \" + entry.Body\n\t\tif len(entry.Links) \u003e 0 {\n\t\t\tparagraph += \" \" + strings.Join(entry.Links, \" \")\n\t\t}\n\t\tparagraphs[i] = paragraph\n\t}\n\treturn strings.Join(paragraphs, \"\\n\\n\")\n}\n\nfunc (l Entries) Columns() string {\n\tcolumns := make([]string, len(l))\n\tfor i, entry := range l {\n\t\ttitle := entry.Title\n\t\tif entry.Link != \"\" {\n\t\t\ttitle = md.Link(title, entry.Link)\n\t\t}\n\t\tbody := entry.Body\n\t\tlinks := strings.Join(entry.Links, \" \")\n\t\tcolumns[i] = md.H2(title) + md.Paragraph(body) + md.Paragraph(links)\n\t}\n\treturn md.Columns(columns, false)\n}\n\nfunc truncateText(content string, maxLength int, withNewLines bool) string {\n\t// If maxLength is -1, don't truncate\n\tif maxLength \u003c 0 {\n\t\tif !withNewLines {\n\t\t\tcontent = strings.ReplaceAll(content, \"\\n\", \" \")\n\t\t}\n\t\treturn content\n\t}\n\tif !withNewLines {\n\t\tcontent = strings.ReplaceAll(content, \"\\n\", \" \")\n\t}\n\tif len(content) \u003e maxLength {\n\t\treturn content[:maxLength-3] + \"...\"\n\t}\n\treturn content\n}\n"},{"name":"mdlist_test.gno","body":"package mdlist\n\nimport (\n\t\"gno.land/p/moul/md/v0\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestBulletList(t *testing.T) {\n\tlist := Entries{\n\t\t{Title: \"First\", Body: \"Body1\", Links: []string{\"[link1](url1)\"}},\n\t\t{Title: \"Second\", Body: \"Body2\", Links: []string{\"[link2](url2)\", \"[link3](url3)\"}},\n\t\t{Title: \"Third\", Body: \"Body3\", Link: \"https://example.com\"},\n\t\t{Title: \"Fourth\", Body: \"Body4\", Link: \"https://example.com\", Links: []string{\"[link4](url4)\", \"[link5](url5)\"}},\n\t}\n\tcol1 := \"- **First**: *Body1* [link1](url1)\"\n\tcol2 := \"- **Second**: *Body2* [link2](url2) [link3](url3)\"\n\tcol3 := \"- **[Third](https://example.com)**: *Body3*\"\n\tcol4 := \"- **[Fourth](https://example.com)**: *Body4* [link4](url4) [link5](url5)\"\n\texpected := strings.Join([]string{col1, col2, col3, col4}, \"\\n\") + \"\\n\"\n\tuassert.Equal(t, expected, list.BulletList())\n}\n\nfunc TestColumns(t *testing.T) {\n\tlist := Entries{\n\t\t{Title: \"First\", Body: \"Body1\", Links: []string{\"[link1](url1)\"}},\n\t\t{Title: \"Second\", Body: \"Body2\", Links: []string{\"[link2](url2)\", \"[link3](url3)\"}},\n\t\t{Title: \"Third\", Body: \"Body3\", Link: \"https://example.com\"},\n\t\t{Title: \"Fourth\", Body: \"Body4\", Link: \"https://example.com\", Links: []string{\"[link4](url4)\", \"[link5](url5)\"}},\n\t}\n\tcol1 := \"## First\\nBody1\\n\\n[link1](url1)\\n\\n\"\n\tcol2 := \"## Second\\nBody2\\n\\n[link2](url2) [link3](url3)\\n\\n\"\n\tcol3 := \"## [Third](https://example.com)\\nBody3\\n\\n\\n\\n\"\n\tcol4 := \"## [Fourth](https://example.com)\\nBody4\\n\\n[link4](url4) [link5](url5)\\n\\n\"\n\texpected := \"\u003cgno-columns\u003e\\n\" + col1 + \"\\n\u003cgno-columns-sep\u003e\\n\" + col2 + \"\\n\u003cgno-columns-sep\u003e\\n\" + col3 + \"\\n\u003cgno-columns-sep\u003e\\n\" + col4 + \"\\n\u003c/gno-columns\u003e\\n\"\n\tuassert.Equal(t, expected, list.Columns())\n}\n\nfunc TestBulletListTruncated(t *testing.T) {\n\tlist := Entries{\n\t\t{Title: \"Very long title that should be truncated\", Body: \"Very long body that should also be truncated because it is too long\", Links: []string{\"[link1](url1)\"}},\n\t\t{Title: \"Short\", Body: \"Short body\"},\n\t}\n\t// Test truncation\n\tresult := list.BulletListTruncated(10, 20)\n\t// Should contain truncated text\n\texpected := \"- **Very lo...**: *Very long body th...* [link1](url1)\\n- **Short**: *Short body*\\n\"\n\tuassert.Equal(t, expected, result)\n}\n\nfunc TestNumberedList(t *testing.T) {\n\tlist := Entries{\n\t\t{Title: \"First\", Body: \"Body1\"},\n\t\t{Title: \"Second\", Body: \"Body2\", Link: \"https://example.com\"},\n\t}\n\texpected := \"1. **First**: *Body1*\\n2. **[Second](https://example.com)**: *Body2*\\n\"\n\tuassert.Equal(t, expected, list.NumberedList())\n}\n\nfunc TestParagraphs(t *testing.T) {\n\tlist := Entries{\n\t\t{Title: \"First\", Body: \"Body1\", Links: []string{\"[link1](url1)\"}},\n\t\t{Title: \"Second\", Body: \"Body2\", Link: \"https://example.com\"},\n\t}\n\texpected := \"**First**. Body1 [link1](url1)\\n\\n**[Second](https://example.com)**. Body2\"\n\tuassert.Equal(t, expected, list.Paragraphs())\n}\n\nfunc TestTruncateText(t *testing.T) {\n\tlong := \"abcd\\nefghijklmnopqrs\\ntuvwxyz01\\n23456789\"\n\tshort := \"short\"\n\turequire.Equal(t, \"abcd ef...\", truncateText(long, 10, false))\n\turequire.Equal(t, short, truncateText(short, 10, false))\n\turequire.Equal(t, \"abcd\\nef...\", truncateText(long, 10, true))\n\turequire.Equal(t, \"short\", truncateText(short, 10, true))\n}\n\nfunc TestEntriesRendering(t *testing.T) {\n\tlist := Entries{\n\t\tEntry{\n\t\t\tTitle: \"Entry 1\",\n\t\t\tBody:  \"Body 1\",\n\t\t\tLinks: []string{\n\t\t\t\tmd.Link(\"Example\", \"https://example.com\"),\n\t\t\t},\n\t\t},\n\t\tEntry{\n\t\t\tTitle: \"Entry 2\",\n\t\t\tBody:  \"Body 2\",\n\t\t},\n\t\tEntry{\n\t\t\tTitle: \"Entry 3\",\n\t\t\tBody:  \"Body 3\",\n\t\t\tLinks: []string{\n\t\t\t\tmd.Link(\"Example1\", \"https://example.com/1\"),\n\t\t\t\tmd.Link(\"Example2\", \"https://example.com/2\"),\n\t\t\t},\n\t\t},\n\t\tEntry{\n\t\t\tTitle: \"Entry 4\",\n\t\t\tBody:  \"Body 4\",\n\t\t\tLink:  \"https://example.com/4\",\n\t\t},\n\t\tEntry{\n\t\t\tTitle: \"Entry 5\",\n\t\t\tBody:  \"Body 5\",\n\t\t\tLink:  \"https://example.com/5\",\n\t\t\tLinks: []string{\n\t\t\t\tmd.Link(\"Example3\", \"https://example.com/3\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tuassert.Equal(t, `\u003cgno-columns\u003e\n## Entry 1\nBody 1\n\n[Example](https://example.com)\n\n\n\u003cgno-columns-sep\u003e\n## Entry 2\nBody 2\n\n\n\n\n\u003cgno-columns-sep\u003e\n## Entry 3\nBody 3\n\n[Example1](https://example.com/1) [Example2](https://example.com/2)\n\n\n\u003cgno-columns-sep\u003e\n## [Entry 4](https://example.com/4)\nBody 4\n\n\n\n\n\u003cgno-columns-sep\u003e\n## [Entry 5](https://example.com/5)\nBody 5\n\n[Example3](https://example.com/3)\n\n\n\u003c/gno-columns\u003e\n`, list.Columns())\n\tuassert.Equal(t, `- **Entry 1**: *Body 1* [Example](https://example.com)\n- **Entry 2**: *Body 2*\n- **Entry 3**: *Body 3* [Example1](https://example.com/1) [Example2](https://example.com/2)\n- **[Entry 4](https://example.com/4)**: *Body 4*\n- **[Entry 5](https://example.com/5)**: *Body 5* [Example3](https://example.com/3)\n`, list.BulletList())\n\tuassert.Equal(t, `1. **Entry 1**: *Body 1* [Example](https://example.com)\n2. **Entry 2**: *Body 2*\n3. **Entry 3**: *Body 3* [Example1](https://example.com/1) [Example2](https://example.com/2)\n4. **[Entry 4](https://example.com/4)**: *Body 4*\n5. **[Entry 5](https://example.com/5)**: *Body 5* [Example3](https://example.com/3)\n`, list.NumberedList())\n\tuassert.Equal(t, `**Entry 1**. Body 1 [Example](https://example.com)\n\n**Entry 2**. Body 2\n\n**Entry 3**. Body 3 [Example1](https://example.com/1) [Example2](https://example.com/2)\n\n**[Entry 4](https://example.com/4)**. Body 4\n\n**[Entry 5](https://example.com/5)**. Body 5 [Example3](https://example.com/3)`, list.Paragraphs())\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"memo","path":"gno.land/p/moul/memo/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/memo/v0`\n\nA simple memoization utility to cache function results, **backed by a B+ tree**\n(`gno.land/p/nt/bptree`).\n\nA B+ tree packs many entries per persisted node, so it costs materially less\nstorage and gas per cached entry than an AVL backing would.\n\n```go\nimport \"gno.land/p/moul/memo/v0\"\n\nm := memo.New()\n\n// Cache expensive computation; subsequent calls with the same key\n// return the cached result without re-running the function.\nresult := m.Memoize(\"key\", func() any {\n\treturn \"computed-value\"\n})\n\nm.Invalidate(\"key\") // drop one entry\nm.Clear()           // drop all entries\nm.Size()            // number of cached entries\n```\n\n\u003e ⚠️ **Gno usage:** storage updates only persist during transactions. Memoizing\n\u003e during queries/render will not persist and only wastes resources — use this in\n\u003e transaction-driven contexts.\n\n**Caveats from the B+ tree backing:** it mutates in place (a copy-on-write AVL\nbacking would not), so do not Invalidate/add entries from inside a callback\niterating the same Memoizer, and do not copy a non-zero `Memoizer` by value.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/memo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/memo/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/memo/v0\"\ngno = \"0.9\"\n"},{"name":"memo.gno","body":"// Package memo provides a simple memoization utility to cache function results.\n//\n// The package offers a Memoizer type that can cache function results based on keys,\n// with optional validation of cached values. This is useful for expensive computations\n// that need to be cached and potentially invalidated based on custom conditions.\n//\n// It is the B+ tree successor to [gno.land/p/moul/memo/v0] (which is backed by\n// an AVL tree): a bump to v3 because the backing data structure — and thus the\n// on-chain storage layout — changed. The exported API is identical to v2\n// (New/Memoize/MemoizeWithValidator/Invalidate/Clear/Size). A B+ tree packs\n// many entries per persisted node, so it costs materially less storage and gas\n// per cached entry — prefer v3 when the cache is part of persisted realm state.\n//\n// Because the B+ tree backing mutates in place (the AVL backing was\n// copy-on-write), do NOT invalidate or add entries to the same Memoizer from\n// inside a callback that is iterating it, and do NOT copy a non-zero Memoizer\n// by value.\n//\n// /!\\ Important Warning for Gno Usage:\n// In Gno, storage updates only persist during transactions. This means:\n//   - Cache entries created during queries will NOT persist\n//   - Creating cache entries during queries will actually decrease performance\n//     as it wastes resources trying to save data that won't be saved\n//\n// Best Practices:\n// - Use this pattern in transaction-driven contexts rather than query/render scenarios\n// - Consider controlled cache updates, e.g., by specific accounts (like oracles)\n// - Ideal for cases where cache updates happen every N blocks or on specific events\n// - Carefully evaluate if caching will actually improve performance in your use case\n//\n// Basic usage example:\n//\n//\tm := memo.New()\n//\n//\t// Cache expensive computation\n//\tresult := m.Memoize(\"key\", func() any {\n//\t    // expensive operation\n//\t    return \"computed-value\"\n//\t})\n//\n//\t// Subsequent calls with same key return cached result\n//\tresult = m.Memoize(\"key\", func() any {\n//\t    // function won't be called, cached value is returned\n//\t    return \"computed-value\"\n//\t})\n//\n// Example with validation:\n//\n//\ttype TimestampedValue struct {\n//\t    Value     string\n//\t    Timestamp time.Time\n//\t}\n//\n//\tm := memo.New()\n//\n//\t// Cache value with timestamp\n//\tresult := m.MemoizeWithValidator(\n//\t    \"key\",\n//\t    func() any {\n//\t        return TimestampedValue{\n//\t            Value:     \"data\",\n//\t            Timestamp: time.Now(),\n//\t        }\n//\t    },\n//\t    func(cached any) bool {\n//\t        // Validate that the cached value is not older than 1 hour\n//\t        if tv, ok := cached.(TimestampedValue); ok {\n//\t            return time.Since(tv.Timestamp) \u003c time.Hour\n//\t        }\n//\t        return false\n//\t    },\n//\t)\npackage memo\n\nimport (\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// keyString derives a stable string key from an arbitrary value. Keys are\n// compared by their string representation, mirroring the previous ordering\n// behavior.\nfunc keyString(key any) string {\n\treturn ufmt.Sprintf(\"%v\", key)\n}\n\n// Memoizer is a structure to handle memoization of function results.\ntype Memoizer struct {\n\tcache *bptree.BPTree\n}\n\n// New creates a new Memoizer instance.\nfunc New() *Memoizer {\n\treturn \u0026Memoizer{\n\t\tcache: bptree.NewBPTree32(),\n\t}\n}\n\n// Memoize ensures the result of the given function is cached for the specified key.\nfunc (m *Memoizer) Memoize(key any, fn func() any) any {\n\tk := keyString(key)\n\tif m.cache.Has(k) {\n\t\treturn m.cache.Get(k)\n\t}\n\n\tvalue := fn()\n\tm.cache.Set(k, value)\n\treturn value\n}\n\n// MemoizeWithValidator ensures the result is cached and valid according to the validator function.\nfunc (m *Memoizer) MemoizeWithValidator(key any, fn func() any, isValid func(any) bool) any {\n\tk := keyString(key)\n\tif m.cache.Has(k) {\n\t\tcached := m.cache.Get(k)\n\t\tif isValid(cached) {\n\t\t\treturn cached\n\t\t}\n\t}\n\n\tvalue := fn()\n\tm.cache.Set(k, value)\n\treturn value\n}\n\n// Invalidate removes the cached value for the specified key.\nfunc (m *Memoizer) Invalidate(key any) {\n\tm.cache.Remove(keyString(key))\n}\n\n// Clear clears all cached values.\nfunc (m *Memoizer) Clear() {\n\tm.cache = bptree.NewBPTree32()\n}\n\n// Size returns the number of items currently in the cache.\nfunc (m *Memoizer) Size() int {\n\treturn m.cache.Size()\n}\n"},{"name":"memo_test.gno","body":"package memo\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\ntype timestampedValue struct {\n\tvalue     any\n\ttimestamp time.Time\n}\n\n// complexKey is used to test struct keys\ntype complexKey struct {\n\tID   int\n\tName string\n}\n\nfunc TestMemoize(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tkey       any\n\t\tvalue     any\n\t\tcallCount *int\n\t}{\n\t\t{\n\t\t\tname:      \"string key and value\",\n\t\t\tkey:       \"test-key\",\n\t\t\tvalue:     \"test-value\",\n\t\t\tcallCount: new(int),\n\t\t},\n\t\t{\n\t\t\tname:      \"int key and value\",\n\t\t\tkey:       42,\n\t\t\tvalue:     123,\n\t\t\tcallCount: new(int),\n\t\t},\n\t\t{\n\t\t\tname:      \"mixed types\",\n\t\t\tkey:       \"number\",\n\t\t\tvalue:     42,\n\t\t\tcallCount: new(int),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tm := New()\n\t\t\tif m.Size() != 0 {\n\t\t\t\tt.Errorf(\"Initial size = %d, want 0\", m.Size())\n\t\t\t}\n\n\t\t\tfn := func() any {\n\t\t\t\t*tt.callCount++\n\t\t\t\treturn tt.value\n\t\t\t}\n\n\t\t\t// First call should compute\n\t\t\tresult := m.Memoize(tt.key, fn)\n\t\t\tif result != tt.value {\n\t\t\t\tt.Errorf(\"Memoize() = %v, want %v\", result, tt.value)\n\t\t\t}\n\t\t\tif *tt.callCount != 1 {\n\t\t\t\tt.Errorf(\"Function called %d times, want 1\", *tt.callCount)\n\t\t\t}\n\t\t\tif m.Size() != 1 {\n\t\t\t\tt.Errorf(\"Size after first call = %d, want 1\", m.Size())\n\t\t\t}\n\n\t\t\t// Second call should use cache\n\t\t\tresult = m.Memoize(tt.key, fn)\n\t\t\tif result != tt.value {\n\t\t\t\tt.Errorf(\"Memoize() second call = %v, want %v\", result, tt.value)\n\t\t\t}\n\t\t\tif *tt.callCount != 1 {\n\t\t\t\tt.Errorf(\"Function called %d times, want 1\", *tt.callCount)\n\t\t\t}\n\t\t\tif m.Size() != 1 {\n\t\t\t\tt.Errorf(\"Size after second call = %d, want 1\", m.Size())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMemoizeWithValidator(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tkey             any\n\t\tvalue           any\n\t\tvalidDuration   time.Duration\n\t\twaitDuration    time.Duration\n\t\texpectedCalls   int\n\t\tshouldRecompute bool\n\t}{\n\t\t{\n\t\t\tname:            \"valid cache\",\n\t\t\tkey:             \"key1\",\n\t\t\tvalue:           \"value1\",\n\t\t\tvalidDuration:   time.Hour,\n\t\t\twaitDuration:    time.Millisecond,\n\t\t\texpectedCalls:   1,\n\t\t\tshouldRecompute: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"expired cache\",\n\t\t\tkey:             \"key2\",\n\t\t\tvalue:           \"value2\",\n\t\t\tvalidDuration:   time.Millisecond,\n\t\t\twaitDuration:    time.Millisecond * 2,\n\t\t\texpectedCalls:   2,\n\t\t\tshouldRecompute: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tm := New()\n\t\t\tcallCount := 0\n\n\t\t\tfn := func() any {\n\t\t\t\tcallCount++\n\t\t\t\treturn timestampedValue{\n\t\t\t\t\tvalue:     tt.value,\n\t\t\t\t\ttimestamp: time.Now(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tisValid := func(cached any) bool {\n\t\t\t\tif tv, ok := cached.(timestampedValue); ok {\n\t\t\t\t\treturn time.Since(tv.timestamp) \u003c tt.validDuration\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// First call\n\t\t\tresult := m.MemoizeWithValidator(tt.key, fn, isValid)\n\t\t\tif tv, ok := result.(timestampedValue); !ok || tv.value != tt.value {\n\t\t\t\tt.Errorf(\"MemoizeWithValidator() = %v, want value %v\", result, tt.value)\n\t\t\t}\n\n\t\t\t// Wait\n\t\t\ttesting.SkipHeights(10)\n\n\t\t\t// Second call\n\t\t\tresult = m.MemoizeWithValidator(tt.key, fn, isValid)\n\t\t\tif tv, ok := result.(timestampedValue); !ok || tv.value != tt.value {\n\t\t\t\tt.Errorf(\"MemoizeWithValidator() second call = %v, want value %v\", result, tt.value)\n\t\t\t}\n\n\t\t\tif callCount != tt.expectedCalls {\n\t\t\t\tt.Errorf(\"Function called %d times, want %d\", callCount, tt.expectedCalls)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestInvalidate(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tkey       any\n\t\tvalue     any\n\t\tcallCount *int\n\t}{\n\t\t{\n\t\t\tname:      \"invalidate existing key\",\n\t\t\tkey:       \"test-key\",\n\t\t\tvalue:     \"test-value\",\n\t\t\tcallCount: new(int),\n\t\t},\n\t\t{\n\t\t\tname:      \"invalidate non-existing key\",\n\t\t\tkey:       \"missing-key\",\n\t\t\tvalue:     \"test-value\",\n\t\t\tcallCount: new(int),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tm := New()\n\t\t\tfn := func() any {\n\t\t\t\t*tt.callCount++\n\t\t\t\treturn tt.value\n\t\t\t}\n\n\t\t\t// First call\n\t\t\tm.Memoize(tt.key, fn)\n\t\t\tif m.Size() != 1 {\n\t\t\t\tt.Errorf(\"Size after first call = %d, want 1\", m.Size())\n\t\t\t}\n\n\t\t\t// Invalidate\n\t\t\tm.Invalidate(tt.key)\n\t\t\tif m.Size() != 0 {\n\t\t\t\tt.Errorf(\"Size after invalidate = %d, want 0\", m.Size())\n\t\t\t}\n\n\t\t\t// Call again should recompute\n\t\t\tresult := m.Memoize(tt.key, fn)\n\t\t\tif result != tt.value {\n\t\t\t\tt.Errorf(\"Memoize() after invalidate = %v, want %v\", result, tt.value)\n\t\t\t}\n\t\t\tif *tt.callCount != 2 {\n\t\t\t\tt.Errorf(\"Function called %d times, want 2\", *tt.callCount)\n\t\t\t}\n\t\t\tif m.Size() != 1 {\n\t\t\t\tt.Errorf(\"Size after recompute = %d, want 1\", m.Size())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestClear(t *testing.T) {\n\tm := New()\n\tcallCount := 0\n\n\tfn := func() any {\n\t\tcallCount++\n\t\treturn \"value\"\n\t}\n\n\t// Cache some values\n\tm.Memoize(\"key1\", fn)\n\tm.Memoize(\"key2\", fn)\n\n\tif callCount != 2 {\n\t\tt.Errorf(\"Initial calls = %d, want 2\", callCount)\n\t}\n\tif m.Size() != 2 {\n\t\tt.Errorf(\"Size after initial calls = %d, want 2\", m.Size())\n\t}\n\n\t// Clear cache\n\tm.Clear()\n\tif m.Size() != 0 {\n\t\tt.Errorf(\"Size after clear = %d, want 0\", m.Size())\n\t}\n\n\t// Recompute values\n\tm.Memoize(\"key1\", fn)\n\tm.Memoize(\"key2\", fn)\n\n\tif callCount != 4 {\n\t\tt.Errorf(\"Calls after clear = %d, want 4\", callCount)\n\t}\n\tif m.Size() != 2 {\n\t\tt.Errorf(\"Size after recompute = %d, want 2\", m.Size())\n\t}\n}\n\nfunc TestSize(t *testing.T) {\n\tm := New()\n\n\tif m.Size() != 0 {\n\t\tt.Errorf(\"Initial size = %d, want 0\", m.Size())\n\t}\n\n\tcallCount := 0\n\tfn := func() any {\n\t\tcallCount++\n\t\treturn \"value\"\n\t}\n\n\t// Add items\n\tm.Memoize(\"key1\", fn)\n\tif m.Size() != 1 {\n\t\tt.Errorf(\"Size after first insert = %d, want 1\", m.Size())\n\t}\n\n\tm.Memoize(\"key2\", fn)\n\tif m.Size() != 2 {\n\t\tt.Errorf(\"Size after second insert = %d, want 2\", m.Size())\n\t}\n\n\t// Duplicate key should not increase size\n\tm.Memoize(\"key1\", fn)\n\tif m.Size() != 2 {\n\t\tt.Errorf(\"Size after duplicate insert = %d, want 2\", m.Size())\n\t}\n\n\t// Remove item\n\tm.Invalidate(\"key1\")\n\tif m.Size() != 1 {\n\t\tt.Errorf(\"Size after invalidate = %d, want 1\", m.Size())\n\t}\n\n\t// Clear all\n\tm.Clear()\n\tif m.Size() != 0 {\n\t\tt.Errorf(\"Size after clear = %d, want 0\", m.Size())\n\t}\n}\n\nfunc TestMemoizeWithDifferentKeyTypes(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tkeys      []any    // Now an array of keys\n\t\tvalues    []string // Corresponding values\n\t\tcallCount *int\n\t}{\n\t\t{\n\t\t\tname:      \"integer keys\",\n\t\t\tkeys:      []any{42, 43},\n\t\t\tvalues:    []string{\"value-for-42\", \"value-for-43\"},\n\t\t\tcallCount: new(int),\n\t\t},\n\t\t{\n\t\t\tname:      \"float keys\",\n\t\t\tkeys:      []any{3.14, 2.718},\n\t\t\tvalues:    []string{\"value-for-pi\", \"value-for-e\"},\n\t\t\tcallCount: new(int),\n\t\t},\n\t\t{\n\t\t\tname:      \"bool keys\",\n\t\t\tkeys:      []any{true, false},\n\t\t\tvalues:    []string{\"value-for-true\", \"value-for-false\"},\n\t\t\tcallCount: new(int),\n\t\t},\n\t\t/*\n\t\t\t{\n\t\t\t\tname: \"struct keys\",\n\t\t\t\tkeys: []any{\n\t\t\t\t\tcomplexKey{ID: 1, Name: \"test1\"},\n\t\t\t\t\tcomplexKey{ID: 2, Name: \"test2\"},\n\t\t\t\t},\n\t\t\t\tvalues:    []string{\"value-for-struct1\", \"value-for-struct2\"},\n\t\t\t\tcallCount: new(int),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:      \"nil and empty interface keys\",\n\t\t\t\tkeys:      []any{nil, any(nil)},\n\t\t\t\tvalues:    []string{\"value-for-nil\", \"value-for-empty-interface\"},\n\t\t\t\tcallCount: new(int),\n\t\t\t},\n\t\t*/\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tm := New()\n\n\t\t\t// Test both keys\n\t\t\tfor i, key := range tt.keys {\n\t\t\t\tvalue := tt.values[i]\n\t\t\t\tfn := func() any {\n\t\t\t\t\t*tt.callCount++\n\t\t\t\t\treturn value\n\t\t\t\t}\n\n\t\t\t\t// First call should compute\n\t\t\t\tresult := m.Memoize(key, fn)\n\t\t\t\tif result != value {\n\t\t\t\t\tt.Errorf(\"Memoize() for key %v = %v, want %v\", key, result, value)\n\t\t\t\t}\n\t\t\t\tif *tt.callCount != i+1 {\n\t\t\t\t\tt.Errorf(\"Function called %d times, want %d\", *tt.callCount, i+1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Verify size includes both entries\n\t\t\tif m.Size() != 2 {\n\t\t\t\tt.Errorf(\"Size after both inserts = %d, want 2\", m.Size())\n\t\t\t}\n\n\t\t\t// Second call for each key should use cache\n\t\t\tfor i, key := range tt.keys {\n\t\t\t\tinitialCount := *tt.callCount\n\t\t\t\tresult := m.Memoize(key, func() any {\n\t\t\t\t\t*tt.callCount++\n\t\t\t\t\treturn \"should-not-be-called\"\n\t\t\t\t})\n\n\t\t\t\tif result != tt.values[i] {\n\t\t\t\t\tt.Errorf(\"Memoize() second call for key %v = %v, want %v\", key, result, tt.values[i])\n\t\t\t\t}\n\t\t\t\tif *tt.callCount != initialCount {\n\t\t\t\t\tt.Errorf(\"Cache miss for key %v\", key)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Test invalidate for each key\n\t\t\tfor i, key := range tt.keys {\n\t\t\t\tm.Invalidate(key)\n\t\t\t\tif m.Size() != 1-i {\n\t\t\t\t\tt.Errorf(\"Size after invalidate %d = %d, want %d\", i+1, m.Size(), 1-i)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMultipleKeyTypes(t *testing.T) {\n\tm := New()\n\tcallCount := 0\n\n\t// Insert different key types simultaneously (two of each type)\n\tkeys := []any{\n\t\t42, 43, // ints\n\t\t\"string-key1\", \"string-key2\", // strings\n\t\t3.14, 2.718, // floats\n\t\ttrue, false, // bools\n\t}\n\n\tfor i, key := range keys {\n\t\tvalue := i\n\t\tm.Memoize(key, func() any {\n\t\t\tcallCount++\n\t\t\treturn value\n\t\t})\n\t}\n\n\t// Verify size includes all entries\n\tif m.Size() != len(keys) {\n\t\tt.Errorf(\"Size = %d, want %d\", m.Size(), len(keys))\n\t}\n\n\t// Verify all values are cached correctly\n\tfor i, key := range keys {\n\t\tinitialCount := callCount\n\t\tresult := m.Memoize(key, func() any {\n\t\t\tcallCount++\n\t\t\treturn -1 // Should never be returned if cache works\n\t\t})\n\n\t\tif result != i {\n\t\t\tt.Errorf(\"Memoize(%v) = %v, want %v\", key, result, i)\n\t\t}\n\t\tif callCount != initialCount {\n\t\t\tt.Errorf(\"Cache miss for key %v\", key)\n\t\t}\n\t}\n\n\t// Test invalidation of pairs\n\tfor i := 0; i \u003c len(keys); i += 2 {\n\t\tm.Invalidate(keys[i])\n\t\tm.Invalidate(keys[i+1])\n\t\texpectedSize := len(keys) - (i + 2)\n\t\tif m.Size() != expectedSize {\n\t\t\tt.Errorf(\"Size after invalidating pair %d = %d, want %d\", i/2, m.Size(), expectedSize)\n\t\t}\n\t}\n\n\t// Clear and verify\n\tm.Clear()\n\tif m.Size() != 0 {\n\t\tt.Errorf(\"Size after clear = %d, want 0\", m.Size())\n\t}\n}\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"mygnoscan","path":"gno.land/p/moul/mygnoscan/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/mygnoscan`\n\nBuilds links into a [mygnoscan](https://mygnoscan.moul.p2p.team) block\nexplorer, from inside a realm.\n\nA realm knows things its reader cannot see: which chain it is on, what its own\naddress is, which block it was last written at. Turning any of those into a\nlink means knowing the explorer's route table, and a route table copied into\nthirty realms is thirty places to fix when a route moves. This is the one\nplace.\n\n```go\ns := mygnoscan.Default()\n\ns.Realm(\"gno.land/r/moul/home\")                 // .../realm/r/moul/home?network=mainnet\ns.Realm(\"r/moul/home\", mygnoscan.TabSource)     // ...\u0026tab=source\ns.RealmFunc(\"r/moul/config\", \"Set\")             // source tab, at one function\ns.Address(addr)                                 // an account\ns.Block(runtime.ChainHeight())                  // the block we are in\ns.Tx(hash)                                      // one transaction, base64 hash\ns.Proposal(7)                                   // one GovDAO proposal\ns.Page(mygnoscan.PageGas)                       // a list page\n\ns.RealmFooter(\"gno.land/r/moul/home\")           // the markdown line for a Render\n```\n\n`Default()` is `DefaultBase` (moul's instance) on whichever network answers for\nthe running chain. `New(base)` points somewhere else, `WithNetwork(id)`\noverrides the network. Nothing here reads chain state beyond `ChainDomain`,\n`ChainID` and `ChainHeight`, and nothing writes: building a link is free.\n\nFor a realm that wants the target to be **changeable without a redeploy**, read\nthe base from [`r/moul/config`](../../../r/moul/config) instead of calling\n`Default()`: `config.Scanner()` returns exactly this type, configured.\n\n## The routes are measured\n\nEvery path was read out of the explorer's own router (`route()` in its\nsingle-page frontend) on 2026-09-22, not inferred from clicking the UI. Two\nrealm tabs that the UI still redirects are deliberately absent because they no\nlonger exist: `?tab=graph` (folded into `deps`) and `?tab=inert` (folded into\nthe default tab, and dropped from the URL).\n\n## Three things that will bite otherwise\n\n- **An unknown path renders the home page.** The explorer's router falls\n  through to `home` rather than to a 404, so a misspelled route is not visible\n  as an error: the link works and goes somewhere else. That is why the page\n  names are constants and `Page` is the only door to them.\n- **Omitting `?network=` is not the same as asking for mainnet.** The explorer\n  then answers for every chain it indexes at once, which looks plausible and\n  is wrong. A `Scanner` on a chain `NetworkFor` does not know emits no network\n  parameter, so `New` under gnodev (chain-id `dev`) produces links to the\n  blend. `WithNetwork` is how you fix that.\n- **The network ids belong to the instance, not to the chain.** `DefaultBase`\n  names mainnet `mainnet`; the upstream default configuration names the same\n  chain `gnoland1`. `NetworkFor` maps chain-ids to what `DefaultBase` serves,\n  so pointing `New` at another instance usually means setting `WithNetwork`\n  too.\n\n## A path a caller typed cannot break out of the link\n\nEverything here can end up inside a markdown link, so a path carrying `)` would\nclose the link early and render the rest as page text. `url.PathEscape` does\nnot help: `(` and `)` are legal URL sub-delims and it leaves both alone.\n\nSo the two shapes are handled differently, and neither trusts its input:\n\n- **Package paths and page names are refused**, not escaped, because escaping\n  their separators would break the route. `Realm`, `RealmFunc`, `RealmFile`,\n  `RealmFooter` and `Page` fall back to a list page for anything outside\n  `[A-Za-z0-9._/-]` or with an empty segment.\n- **Hashes, token keys and addresses are escaped** with `encodeURIComponent`\n  semantics, which is what the explorer's `decodeURIComponent` round-trips.\n  `address` is a string type and nothing stops a realm casting a caller's input\n  into one, so it gets the same treatment.\n\n`Link(text, target)` does **not** escape its text. Pass a constant. A label a\ncaller typed belongs in `ui.Inline` first.\n\n`CurrentRealm` and `CurrentRealmFooter` stack-walk (`unsafe.CurrentRealm`), so\ninside a helper borrowed by another realm they name the **borrower**. That is\nthe right answer for a link and the wrong one for authorisation: never branch\non them. A realm calling through a shared config realm should pass its own path\nexplicitly, because the stack seen from in there has the config realm on it.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/mygnoscan/v0\"\ngno = \"0.9\"\n"},{"name":"mygnoscan.gno","body":"// Package mygnoscan builds links into a mygnoscan block explorer.\n//\n// A realm knows things a reader cannot see from its Render output: which chain\n// it is on, what its address is, which block it was last written at. Turning\n// any of those into a link means knowing the explorer's route table, and a\n// route table hand-written into thirty realms is thirty places to fix when it\n// moves. This package is the one place.\n//\n// # The routes are measured, not guessed\n//\n// Every path below was read out of the explorer's own router (its single-page\n// frontend, `route()`), not inferred from the UI, on 2026-09-22. Two of them\n// are retired and deliberately absent: `?tab=graph` (folded into `deps`, still\n// redirected) and `?tab=inert` (folded into the default tab, silently dropped).\n//\n// # An unknown path renders the home page\n//\n// The explorer's router falls through to `home` rather than to a 404, so a\n// misspelled route is not visible as an error: the link works, it just goes\n// somewhere else. That is why the page names here are constants and why Page\n// is the only door to them.\n//\n// # The network is per instance, not per chain\n//\n// The explorer takes `?network=\u003cid\u003e`, and the ids are chosen by whoever runs\n// the instance: moul's names mainnet `mainnet`, while the upstream default\n// config names the same chain `gnoland1`. NetworkFor maps a chain-id to the\n// ids DefaultBase serves. Point Scanner at another instance and you very\n// likely also want WithNetwork.\n//\n// Omitting the parameter is not the same as asking for mainnet: the explorer\n// then blends every chain it indexes, which looks plausible and is wrong. A\n// Scanner whose network is empty emits no parameter, so New on a chain nobody\n// indexes produces a link to the blend. Set it explicitly when it matters.\n//\n// # Usage\n//\n// The whole point is a realm footer that stays right when the chain changes:\n//\n//\tfunc Render(path string) string {\n//\t\treturn body + \"\\n\\n---\\n\\n\" + mygnoscan.Default().CurrentRealmFooter()\n//\t}\n//\n// and, for a realm that wants to hand out sharper links:\n//\n//\ts := mygnoscan.Default()\n//\ts.Address(someAddr)                              // an account\n//\ts.Block(runtime.ChainHeight())                   // the block we are at\n//\ts.Realm(\"gno.land/r/moul/home\", mygnoscan.TabSource)\n//\ts.RealmFunc(\"gno.land/r/moul/config\", \"Set\")     // straight at one function\n//\n// Nothing here reads chain state except ChainDomain, ChainID and ChainHeight,\n// and nothing here writes. Building a link is free.\npackage mygnoscan\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// DefaultBase is moul's instance, the one the rest of this repo links to.\nconst DefaultBase = \"https://mygnoscan.moul.p2p.team\"\n\n// The realm-page tabs, as the explorer's own tabNames list has them. An\n// unknown tab name lands on the default tab rather than erroring, so these\n// exist to keep a typo out of a deployed realm.\nconst (\n\tTabInfo    = \"info\"    // the default; passing it emits no parameter\n\tTabDocs    = \"docs\"    // exported symbols\n\tTabSource  = \"source\"  // the .gno files as deployed\n\tTabCalls   = \"calls\"   // transactions that called this realm\n\tTabEvents  = \"events\"  // events it emitted\n\tTabStorage = \"storage\" // what it pays to store\n\tTabDefi    = \"defi\"    // balances and token positions\n\tTabDeps    = \"deps\"    // imports, dependents and the graph over them\n)\n\n// The explorer's list pages. Page takes one of these.\nconst (\n\tPageRealms     = \"realms\"\n\tPagePackages   = \"packages\"\n\tPageContracts  = \"contracts\"\n\tPageApps       = \"apps\"\n\tPageTxs        = \"txs\"\n\tPageBlocks     = \"blocks\"\n\tPageAccounts   = \"accounts\"\n\tPageDefi       = \"defi\"\n\tPageCoins      = \"coins\"\n\tPageGRC20      = \"grc20\"\n\tPageValidators = \"validators\"\n\tPageGovDAO     = \"govdao\"\n\tPageProposals  = \"govdao/proposals\"\n\tPageVoters     = \"govdao/voters\"\n\tPageOptions    = \"govdao/options\"\n\tPageParams     = \"params\"\n\tPageEvents     = \"events\"\n\tPageGas        = \"gas\"\n\tPageGasRealms  = \"gas/realms\"\n\tPageGasUsers   = \"gas/users\"\n\tPageGasTxs     = \"gas/txs\"\n\tPageStorage    = \"storage\"\n\tPageAnalytics  = \"analytics\"\n\tPageDashboards = \"dashboards\"\n\tPageSanity     = \"sanity\"\n\tPageWatch      = \"watch\"\n)\n\n// The sub-views of the packages and accounts pages, the only two list pages\n// that restore a view from the URL.\n//\n// Every other list page writes its state into the query string (?by=, ?page=,\n// ?status=, ?window=, ?section=, ?failed=, ?storage=, ?txs=) and does NOT read\n// any of it back on load: a link carrying one of those opens the page on its\n// default view instead, silently. So there are no helpers for them here.\n// Measured against the explorer's router on 2026-09-22.\nconst (\n\tPackagesAll      = \"all\"      // every package\n\tPackagesInert    = \"inert\"    // the parked queue: submitted, not yet approved\n\tAccountsActivity = \"activity\" // ranked by what they have done\n\tAccountsBalances = \"balances\" // ranked by what they hold\n)\n\n// Scanner is one explorer instance plus the network its links should open on.\n// It is a value: copying one is free and there is nothing to close.\ntype Scanner struct {\n\tbase    string\n\tnetwork string\n}\n\n// Default returns a Scanner pointed at DefaultBase, on whichever network\n// answers for the running chain.\nfunc Default() Scanner { return New(DefaultBase) }\n\n// New returns a Scanner pointed at base, on whichever network answers for the\n// running chain. A trailing slash on base is dropped so New(\"…/\") and New(\"…\")\n// build the same links.\nfunc New(base string) Scanner {\n\treturn Scanner{\n\t\tbase:    strings.TrimSuffix(base, \"/\"),\n\t\tnetwork: NetworkFor(runtime.ChainID()),\n\t}\n}\n\n// WithNetwork returns a copy of s whose links carry ?network=id. The empty\n// string removes the parameter, which asks the explorer for every chain at\n// once rather than for this one.\nfunc (s Scanner) WithNetwork(id string) Scanner {\n\ts.network = id\n\treturn s\n}\n\n// Base returns the instance root, without a trailing slash.\nfunc (s Scanner) Base() string { return s.base }\n\n// Network returns the network id these links carry, empty when they carry none.\nfunc (s Scanner) Network() string { return s.network }\n\n// NetworkFor maps a chain-id to the network id DefaultBase serves it under, or\n// \"\" when that instance does not index the chain (a gnodev, a local test).\n//\n// Verified against DefaultBase's /api/networks on 2026-09-22: it serves\n// mainnet, pearl and staging. sapphire is mapped because the chain exists and\n// an instance configured for it uses that id; DefaultBase currently answers\n// for it with the blend, which is the same failure mode as an unknown chain\n// and is why the caller can override with WithNetwork.\nfunc NetworkFor(chainID string) string {\n\tswitch chainID {\n\tcase \"gnoland-1\":\n\t\treturn \"mainnet\"\n\tcase \"pearl-1\":\n\t\treturn \"pearl\"\n\tcase \"sapphire-1\":\n\t\treturn \"sapphire\"\n\tcase \"staging\":\n\t\treturn \"staging\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\n// URL is the one place a link is assembled: an absolute link to path on this\n// instance, carrying query as key/value pairs plus the network. A pair with an\n// empty key or value is dropped, so an optional parameter needs no branch at\n// the call site.\n//\n// Prefer the typed helpers below; this is the escape hatch for a route added\n// to the explorer after this package was last touched.\nfunc (s Scanner) URL(path string, query ...string) string {\n\tif len(query)%2 != 0 {\n\t\tpanic(\"mygnoscan: odd number of query arguments\")\n\t}\n\tif path == \"\" {\n\t\tpath = \"/\"\n\t} else if !strings.HasPrefix(path, \"/\") {\n\t\tpath = \"/\" + path\n\t}\n\n\tv := url.Values{}\n\tfor i := 0; i \u003c len(query); i += 2 {\n\t\tif query[i] == \"\" || query[i+1] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tv.Set(query[i], query[i+1])\n\t}\n\tif s.network != \"\" {\n\t\tv.Set(\"network\", s.network)\n\t}\n\n\tout := s.base + path\n\tif len(v) \u003e 0 {\n\t\tout += \"?\" + v.Encode()\n\t}\n\treturn out\n}\n\n// Home links the explorer's front page on this network.\nfunc (s Scanner) Home() string { return s.URL(\"/\") }\n\n// Page links one of the Page* list pages. A name that is not shaped like one\n// falls back to the front page rather than to the explorer's own\n// unknown-path-renders-home behaviour, which would look identical and mean\n// something else.\nfunc (s Scanner) Page(name string) string {\n\tn := strings.Trim(name, \"/\")\n\tif !safePath(n) {\n\t\treturn s.Home()\n\t}\n\treturn s.URL(\"/\" + n)\n}\n\n// Packages links the package list, on the PackagesAll or PackagesInert view.\n// The empty string takes the page's own default, which is PackagesAll.\nfunc (s Scanner) Packages(view string) string {\n\treturn s.URL(\"/\"+PagePackages, \"pv\", view)\n}\n\n// Accounts links the account list, on the AccountsActivity or AccountsBalances\n// view. The empty string takes the page's own default, which is\n// AccountsActivity.\nfunc (s Scanner) Accounts(view string) string {\n\treturn s.URL(\"/\"+PageAccounts, \"av\", view)\n}\n\n// Realm links a package or realm page, optionally opening one tab.\n//\n// pkgPath is accepted either fully qualified (\"gno.land/r/moul/home\") or bare\n// (\"r/moul/home\"): TrimDomain normalises it. Passing TabInfo, or no tab at\n// all, emits no tab parameter.\nfunc (s Scanner) Realm(pkgPath string, tab ...string) string {\n\tp := TrimDomain(pkgPath)\n\tif p == \"\" {\n\t\treturn s.Home()\n\t}\n\treturn s.URL(\"/realm/\"+p, \"tab\", oneTab(tab))\n}\n\n// CurrentRealm links the page of the realm that called into this package.\n//\n// It stack-walks (unsafe.CurrentRealm), so it names whichever realm was\n// current when it ran. For a plain read like this one that is the BORROWER,\n// which is the wanted answer: a realm asking for \"my page\" gets its own, and\n// so does one asking through a shared config realm, because a borrowed call\n// opens no realm frame. Measured in the test harness on 2026-09-22.\n//\n// Inside a CROSSING function it names that function's realm instead. That is\n// also correct and rarely what a link wants, so pass the path explicitly\n// there. Never branch on it for authorisation either way.\nfunc (s Scanner) CurrentRealm(tab ...string) string {\n\treturn s.Realm(unsafe.CurrentRealm().PkgPath(), tab...)\n}\n\n// RealmFunc links a realm's source tab scrolled to one exported function.\nfunc (s Scanner) RealmFunc(pkgPath, fn string) string {\n\tp := TrimDomain(pkgPath)\n\tif p == \"\" || fn == \"\" {\n\t\treturn s.Realm(pkgPath)\n\t}\n\treturn s.URL(\"/realm/\"+p, \"tab\", TabSource, \"fn\", fn)\n}\n\n// RealmFile links a realm's source tab scrolled to one line of one file.\n// A line of 0 or less links the file without an anchor.\nfunc (s Scanner) RealmFile(pkgPath, file string, line int) string {\n\tp := TrimDomain(pkgPath)\n\tif p == \"\" || file == \"\" {\n\t\treturn s.Realm(pkgPath)\n\t}\n\tif line \u003c= 0 {\n\t\treturn s.URL(\"/realm/\"+p, \"tab\", TabSource, \"file\", file)\n\t}\n\treturn s.URL(\"/realm/\"+p, \"tab\", TabSource, \"file\", file, \"line\", strconv.Itoa(line))\n}\n\n// Address links an account page: its balance, its transactions, what it deployed.\n//\n// The address is escaped rather than trusted. `address` is a string type and\n// nothing stops a realm casting a caller's input into one, so a value reaching\n// here is not necessarily bech32.\nfunc (s Scanner) Address(addr address) string {\n\tif addr == \"\" {\n\t\treturn s.Page(PageAccounts)\n\t}\n\treturn s.URL(\"/address/\" + escapeSegment(addr.String()))\n}\n\n// Tx links one transaction. The hash is the base64 form the indexer and gnokey\n// print, which carries \"+\", \"/\" and \"=\"; the whole segment is percent-escaped\n// so the explorer's decodeURIComponent gives it back byte for byte.\nfunc (s Scanner) Tx(hash string) string {\n\tif hash == \"\" {\n\t\treturn s.Page(PageTxs)\n\t}\n\treturn s.URL(\"/tx/\" + escapeSegment(hash))\n}\n\n// Block links one block by height.\nfunc (s Scanner) Block(height int64) string {\n\tif height \u003c= 0 {\n\t\treturn s.Page(PageBlocks)\n\t}\n\treturn s.URL(\"/block/\" + strconv.FormatInt(height, 10))\n}\n\n// CurrentBlock links the block this call is executing in.\nfunc (s Scanner) CurrentBlock() string { return s.Block(runtime.ChainHeight()) }\n\n// Validator links one validator by address.\nfunc (s Scanner) Validator(addr address) string {\n\tif addr == \"\" {\n\t\treturn s.Page(PageValidators)\n\t}\n\treturn s.URL(\"/validator/\" + escapeSegment(addr.String()))\n}\n\n// Proposal links one GovDAO proposal by id.\nfunc (s Scanner) Proposal(id int) string {\n\tif id \u003c 0 {\n\t\treturn s.Page(PageProposals)\n\t}\n\treturn s.URL(\"/govdao/\" + strconv.Itoa(id))\n}\n\n// Token links one GRC20 asset by its ledger key, which looks like\n// \"gno.land/r/gnoswap/gns.GNS.0000000\". That key carries both slashes and\n// dots, and neither is a route separator, so it is percent-escaped whole.\nfunc (s Scanner) Token(key string) string {\n\tif key == \"\" {\n\t\treturn s.Page(PageGRC20)\n\t}\n\treturn s.URL(\"/grc20/\" + escapeSegment(key))\n}\n\n// TrimDomain strips the chain domain from a package path, so both\n// \"gno.land/r/moul/home\" and \"r/moul/home\" become \"r/moul/home\". A path that\n// is not shaped like a package path (see safePath) comes back empty, and every\n// caller here treats empty as \"no such target\" and falls back to a list page.\n//\n// It tries the running chain's domain first, then the literal \"gno.land/\",\n// because the explorer's own realm route reassembles the path by prepending\n// \"gno.land/\" unconditionally: on a chain whose domain is something else, a\n// bare path is still what the link must carry.\nfunc TrimDomain(pkgPath string) string {\n\tp := strings.TrimPrefix(pkgPath, runtime.ChainDomain()+\"/\")\n\tp = strings.TrimPrefix(p, \"gno.land/\")\n\tp = strings.Trim(p, \"/\")\n\tif !safePath(p) {\n\t\treturn \"\"\n\t}\n\treturn p\n}\n\n// escapeSegment percent-encodes everything outside the RFC 3986 unreserved\n// set, which is exactly what JavaScript's encodeURIComponent does and\n// therefore exactly what the explorer's decodeURIComponent round-trips.\n//\n// url.PathEscape is the obvious choice and is wrong here twice: it leaves '/'\n// alone in some modes and, more importantly, it never escapes '(' or ')',\n// which are legal URL sub-delims and which close a markdown link early. Since\n// every link this package builds may end up inside one, the segment escaper\n// has to be stricter than the URL spec requires.\nfunc escapeSegment(s string) string {\n\tconst hex = \"0123456789ABCDEF\"\n\tvar b strings.Builder\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= 'A' \u0026\u0026 c \u003c= 'Z', c \u003e= '0' \u0026\u0026 c \u003c= '9',\n\t\t\tc == '-', c == '_', c == '.', c == '~':\n\t\t\tb.WriteByte(c)\n\t\tdefault:\n\t\t\tb.WriteByte('%')\n\t\t\tb.WriteByte(hex[c\u003e\u003e4])\n\t\t\tb.WriteByte(hex[c\u00260x0f])\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// safePath reports whether p is shaped like a package path: [A-Za-z0-9._/-],\n// and no empty segment.\n//\n// This is a rendering guard, not a validity check. Everything built here ends\n// up inside a markdown link, so a path carrying ')' would close the link early\n// and the rest would render as page text; a path carrying a space or a newline\n// breaks it differently. Percent-escaping cannot be the answer because '(' and\n// ')' are legal sub-delims in a URL path and url.PathEscape leaves them alone,\n// and escaping the separators would break the route. So the characters are\n// refused instead.\n//\n// It matters because a realm may well pass a path a caller typed (a registry,\n// a directory, a \"link to my realm\" form), and this package cannot tell.\nfunc safePath(p string) bool {\n\tif p == \"\" {\n\t\treturn false\n\t}\n\tlastSlash := true // a leading slash was already trimmed, so no empty first segment\n\tfor i := 0; i \u003c len(p); i++ {\n\t\tc := p[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= 'A' \u0026\u0026 c \u003c= 'Z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\t\tlastSlash = false\n\t\tcase c == '.', c == '-', c == '_':\n\t\t\tlastSlash = false\n\t\tcase c == '/':\n\t\t\tif lastSlash {\n\t\t\t\treturn false // \"\" or \"a//b\"\n\t\t\t}\n\t\t\tlastSlash = true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn !lastSlash // no trailing slash left over\n}\n\n// Link renders a markdown link. Neither argument is escaped: everything this\n// package builds is a path or a constant, never text a caller typed. Passing a\n// user-supplied label through here would let it break out of the link.\nfunc Link(text, target string) string { return \"[\" + text + \"](\" + target + \")\" }\n\n// RealmFooter is the line a realm appends under its Render output: the four\n// views of itself worth one click, separated by middots.\n//\n// Deliberately plain markdown with no leading rule, so the caller decides\n// where it sits and what separates it from the body.\nfunc (s Scanner) RealmFooter(pkgPath string) string {\n\tp := TrimDomain(pkgPath)\n\tif p == \"\" {\n\t\treturn \"\"\n\t}\n\treturn Link(\"explorer\", s.Realm(p)) +\n\t\t\" · \" + Link(\"source\", s.Realm(p, TabSource)) +\n\t\t\" · \" + Link(\"calls\", s.Realm(p, TabCalls)) +\n\t\t\" · \" + Link(\"deps\", s.Realm(p, TabDeps))\n}\n\n// CurrentRealmFooter is RealmFooter for the realm that called in. It carries\n// the same stack-walking caveat as CurrentRealm.\nfunc (s Scanner) CurrentRealmFooter() string {\n\treturn s.RealmFooter(unsafe.CurrentRealm().PkgPath())\n}\n\n// oneTab reads the optional tab argument. More than one is a call-site bug and\n// panics rather than silently using the first, and TabInfo is dropped because\n// it is the default the explorer lands on anyway.\nfunc oneTab(tab []string) string {\n\tswitch len(tab) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\tif tab[0] == TabInfo {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn tab[0]\n\tdefault:\n\t\tpanic(\"mygnoscan: at most one tab\")\n\t}\n}\n"},{"name":"mygnoscan_test.gno","body":"package mygnoscan\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// mainnet is what a Scanner looks like on the chain that matters. Tests build\n// it explicitly rather than calling Default(), because the test harness runs\n// with chain-id \"dev\", which NetworkFor maps to no network at all: pinning\n// Default()'s output would pin the absence of the parameter and prove nothing\n// about the case every real link is in.\nfunc mainnet() Scanner { return New(DefaultBase).WithNetwork(\"mainnet\") }\n\nfunc TestNetworkFor(t *testing.T) {\n\ttests := []struct {\n\t\tchainID string\n\t\twant    string\n\t}{\n\t\t{\"gnoland-1\", \"mainnet\"},\n\t\t{\"pearl-1\", \"pearl\"},\n\t\t{\"sapphire-1\", \"sapphire\"},\n\t\t{\"staging\", \"staging\"},\n\t\t{\"dev\", \"\"},          // gnodev, and what `gno test` reports\n\t\t{\"\", \"\"},             // no chain at all\n\t\t{\"gnoland1\", \"\"},     // the upstream default instance's id, not a chain-id\n\t\t{\"test3\", \"\"},        // a retired testnet\n\t\t{\"mainnet\", \"\"},      // the network id, fed back in by mistake\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, NetworkFor(tt.chainID), \"NetworkFor(\"+tt.chainID+\")\")\n\t}\n}\n\nfunc TestTrimDomain(t *testing.T) {\n\ttests := []struct {\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"gno.land/r/moul/home\", \"r/moul/home\"},\n\t\t{\"r/moul/home\", \"r/moul/home\"},\n\t\t{\"/r/moul/home\", \"r/moul/home\"},\n\t\t{\"gno.land/p/moul/mygnoscan/v0\", \"p/moul/mygnoscan/v0\"},\n\t\t{\"gno.land/r/gnoland/blog\", \"r/gnoland/blog\"},\n\t\t{\"\", \"\"},\n\t\t{\"gno.land/\", \"\"},\n\t\t// A path whose own name starts with the domain is only trimmed once,\n\t\t// so a realm cannot be linked out of its own namespace by its name.\n\t\t{\"gno.land/r/moul/gno.land\", \"r/moul/gno.land\"},\n\t\t// Anything not shaped like a package path comes back empty, so the\n\t\t// caller falls back to a list page instead of emitting it.\n\t\t{\"r/moul/home)\", \"\"},\n\t\t{\"r/moul/ho me\", \"\"},\n\t\t{\"r/moul//home\", \"\"},\n\t\t{\"r/moul/home\\n\", \"\"},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, TrimDomain(tt.in), \"TrimDomain(\"+tt.in+\")\")\n\t}\n}\n\nfunc TestBaseNormalisation(t *testing.T) {\n\tuassert.Equal(t, DefaultBase, New(DefaultBase+\"/\").Base())\n\tuassert.Equal(t, DefaultBase, New(DefaultBase).Base())\n\tuassert.Equal(t, \"https://scan.example.com\", New(\"https://scan.example.com/\").Base())\n}\n\nfunc TestTargets(t *testing.T) {\n\ts := mainnet()\n\tconst b = DefaultBase\n\ttests := []struct {\n\t\tname string\n\t\tgot  string\n\t\twant string\n\t}{\n\t\t{\"home\", s.Home(), b + \"/?network=mainnet\"},\n\t\t{\"page\", s.Page(PageTxs), b + \"/txs?network=mainnet\"},\n\t\t{\"page nested\", s.Page(PageGasRealms), b + \"/gas/realms?network=mainnet\"},\n\t\t{\"page slashed\", s.Page(\"/blocks/\"), b + \"/blocks?network=mainnet\"},\n\t\t{\"realm qualified\", s.Realm(\"gno.land/r/moul/home\"), b + \"/realm/r/moul/home?network=mainnet\"},\n\t\t{\"realm bare\", s.Realm(\"r/moul/home\"), b + \"/realm/r/moul/home?network=mainnet\"},\n\t\t{\"realm tab\", s.Realm(\"r/moul/home\", TabSource), b + \"/realm/r/moul/home?network=mainnet\u0026tab=source\"},\n\t\t// TabInfo is the tab the explorer lands on, so asking for it adds nothing.\n\t\t{\"realm tab info\", s.Realm(\"r/moul/home\", TabInfo), b + \"/realm/r/moul/home?network=mainnet\"},\n\t\t{\"realm empty\", s.Realm(\"\"), b + \"/?network=mainnet\"},\n\t\t{\"realm func\", s.RealmFunc(\"r/moul/config\", \"Set\"), b + \"/realm/r/moul/config?fn=Set\u0026network=mainnet\u0026tab=source\"},\n\t\t{\"realm file\", s.RealmFile(\"r/moul/home\", \"render.gno\", 42), b + \"/realm/r/moul/home?file=render.gno\u0026line=42\u0026network=mainnet\u0026tab=source\"},\n\t\t{\"realm file no line\", s.RealmFile(\"r/moul/home\", \"render.gno\", 0), b + \"/realm/r/moul/home?file=render.gno\u0026network=mainnet\u0026tab=source\"},\n\t\t{\"address\", s.Address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"), b + \"/address/g1manfred47kzduec920z88wfr64ylksmdcedlf5?network=mainnet\"},\n\t\t{\"address empty\", s.Address(\"\"), b + \"/accounts?network=mainnet\"},\n\t\t{\"block\", s.Block(80618), b + \"/block/80618?network=mainnet\"},\n\t\t{\"block zero\", s.Block(0), b + \"/blocks?network=mainnet\"},\n\t\t{\"validator\", s.Validator(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"), b + \"/validator/g1manfred47kzduec920z88wfr64ylksmdcedlf5?network=mainnet\"},\n\t\t{\"proposal\", s.Proposal(7), b + \"/govdao/7?network=mainnet\"},\n\t\t{\"proposal negative\", s.Proposal(-1), b + \"/govdao/proposals?network=mainnet\"},\n\t\t{\"token empty\", s.Token(\"\"), b + \"/grc20?network=mainnet\"},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, tt.got, tt.name)\n\t}\n}\n\n// TestEscaping covers the two routes whose argument is not URL-safe. Both are\n// read back with decodeURIComponent by the explorer, so percent-escaping the\n// whole segment is what round-trips; leaving the slashes alone would split the\n// segment and land on a different route entirely.\nfunc TestEscaping(t *testing.T) {\n\ts := mainnet()\n\n\t// A 32-byte hash in the base64 form the indexer and gnokey print, picked\n\t// to carry all three of the characters that make base64 awkward in a URL.\n\t// Everything outside the unreserved set moves, which is what the\n\t// explorer's decodeURIComponent undoes byte for byte.\n\tuassert.Equal(t,\n\t\tDefaultBase+\"/tx/BppSxd7qRiAPsMHzDx5mys%2BYpeDCMUzxI1qeb%2FEhaYc%3D?network=mainnet\",\n\t\ts.Tx(\"BppSxd7qRiAPsMHzDx5mys+YpeDCMUzxI1qeb/EhaYc=\"))\n\tuassert.Equal(t, DefaultBase+\"/txs?network=mainnet\", s.Tx(\"\"))\n\n\t// A GRC20 ledger key carries both slashes and dots.\n\tuassert.Equal(t,\n\t\tDefaultBase+\"/grc20/gno.land%2Fr%2Fgnoswap%2Fgns.GNS.0000000?network=mainnet\",\n\t\ts.Token(\"gno.land/r/gnoswap/gns.GNS.0000000\"))\n}\n\nfunc TestURLQuery(cur realm, t *testing.T) {\n\ts := mainnet()\n\n\tuassert.Equal(t, DefaultBase+\"/anything?network=mainnet\", s.URL(\"anything\"))\n\tuassert.Equal(t, DefaultBase+\"/anything?network=mainnet\", s.URL(\"/anything\"))\n\tuassert.Equal(t, DefaultBase+\"/a?k=v\u0026network=mainnet\", s.URL(\"/a\", \"k\", \"v\"))\n\n\t// An empty key or value is dropped, so an optional parameter needs no\n\t// branch at the call site.\n\tuassert.Equal(t, DefaultBase+\"/a?network=mainnet\", s.URL(\"/a\", \"k\", \"\"))\n\tuassert.Equal(t, DefaultBase+\"/a?network=mainnet\", s.URL(\"/a\", \"\", \"v\"))\n\n\tuassert.PanicsWithMessage(t, cur, \"mygnoscan: odd number of query arguments\", func() {\n\t\ts.URL(\"/a\", \"k\")\n\t})\n}\n\n// TestNoNetwork pins what a Scanner emits when it does not know the chain:\n// nothing. The explorer then answers for every chain it indexes at once, which\n// is a real answer to a different question, so this is worth being explicit\n// about rather than discovering from a plausible-looking page.\nfunc TestNoNetwork(t *testing.T) {\n\ts := New(DefaultBase).WithNetwork(\"\")\n\tuassert.Equal(t, \"\", s.Network())\n\tuassert.Equal(t, DefaultBase+\"/realm/r/moul/home\", s.Realm(\"r/moul/home\"))\n\tuassert.Equal(t, DefaultBase+\"/realm/r/moul/home?tab=calls\", s.Realm(\"r/moul/home\", TabCalls))\n\tuassert.Equal(t, DefaultBase+\"/\", s.Home())\n}\n\n// TestDefaultUnderTest pins Default() as the test harness sees it: chain-id\n// \"dev\" is indexed nowhere, so the links carry no network. A realm rendering\n// under gnodev gets exactly this, which is why a local preview link is not\n// proof that the mainnet one is right.\nfunc TestDefaultUnderTest(t *testing.T) {\n\ts := Default()\n\tuassert.Equal(t, DefaultBase, s.Base())\n\tuassert.Equal(t, \"\", s.Network())\n\tuassert.Equal(t, DefaultBase+\"/realm/r/moul/home\", s.Realm(\"gno.land/r/moul/home\"))\n}\n\nfunc TestTabArity(cur realm, t *testing.T) {\n\ts := mainnet()\n\tuassert.PanicsWithMessage(t, cur, \"mygnoscan: at most one tab\", func() {\n\t\ts.Realm(\"r/moul/home\", TabSource, TabCalls)\n\t})\n}\n\nfunc TestLink(t *testing.T) {\n\tuassert.Equal(t, \"[text](https://example.com)\", Link(\"text\", \"https://example.com\"))\n}\n\nfunc TestRealmFooter(t *testing.T) {\n\ts := mainnet()\n\tconst want = \"[explorer](https://mygnoscan.moul.p2p.team/realm/r/moul/home?network=mainnet)\" +\n\t\t\" · [source](https://mygnoscan.moul.p2p.team/realm/r/moul/home?network=mainnet\u0026tab=source)\" +\n\t\t\" · [calls](https://mygnoscan.moul.p2p.team/realm/r/moul/home?network=mainnet\u0026tab=calls)\" +\n\t\t\" · [deps](https://mygnoscan.moul.p2p.team/realm/r/moul/home?network=mainnet\u0026tab=deps)\"\n\tuassert.Equal(t, want, s.RealmFooter(\"gno.land/r/moul/home\"))\n\tuassert.Equal(t, want, s.RealmFooter(\"r/moul/home\"))\n\tuassert.Equal(t, \"\", s.RealmFooter(\"\"))\n}\n\n// TestOtherInstance is the whole reason base and network are separate knobs:\n// a second instance serving the same chain under a different id.\nfunc TestOtherInstance(t *testing.T) {\n\ts := New(\"https://scan.example.com\").WithNetwork(\"gnoland1\")\n\tuassert.Equal(t,\n\t\t\"https://scan.example.com/realm/r/moul/home?network=gnoland1\",\n\t\ts.Realm(\"gno.land/r/moul/home\"))\n}\n\n// TestMarkdownBreakout is the reason safePath and escapeSegment exist. A realm\n// that links a path or a hash a caller typed would otherwise let that caller\n// close the markdown link early and write page text of their choosing.\n//\n// url.PathEscape is not enough on its own: \"(\" and \")\" are legal URL\n// sub-delims and it leaves both alone.\nfunc TestMarkdownBreakout(t *testing.T) {\n\ts := mainnet()\n\n\t// A path is refused outright, because escaping its separators would break\n\t// the route. The caller gets the front page, not a broken link.\n\tuassert.Equal(t, DefaultBase+\"/?network=mainnet\",\n\t\ts.Realm(\"r/evil/x)](https://evil.example.com\"))\n\tuassert.Equal(t, \"\", s.RealmFooter(\"r/evil/x)](https://evil.example.com\"))\n\n\t// A hash and a token key are opaque, so they are escaped rather than\n\t// refused, and the parentheses move.\n\tuassert.Equal(t,\n\t\tDefaultBase+\"/tx/x%29%5D%28evil?network=mainnet\",\n\t\ts.Tx(\"x)](evil\"))\n\tuassert.Equal(t,\n\t\tDefaultBase+\"/grc20/x%29%5D%28evil?network=mainnet\",\n\t\ts.Token(\"x)](evil\"))\n\n\t// An address is a string type; nothing stops a realm casting into it.\n\tuassert.Equal(t,\n\t\tDefaultBase+\"/address/g1%29%5D%28evil?network=mainnet\",\n\t\ts.Address(address(\"g1)](evil\")))\n\n\t// A page name that is not a page name lands on the front page, rather\n\t// than on the explorer's own unknown-path-renders-home behaviour, which\n\t// would look identical and mean something else.\n\tuassert.Equal(t, DefaultBase+\"/?network=mainnet\", s.Page(\"txs)](evil\"))\n\tuassert.Equal(t, DefaultBase+\"/?network=mainnet\", s.Page(\"\"))\n}\n\nfunc TestSafePath(t *testing.T) {\n\ttests := []struct {\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"r/moul/home\", true},\n\t\t{\"p/moul/mygnoscan/v0\", true},\n\t\t{\"gas/realms\", true},\n\t\t{\"a\", true},\n\t\t{\"a.b-c_d\", true},\n\t\t{\"\", false},\n\t\t{\"a//b\", false},\n\t\t{\"a/\", false},\n\t\t{\"a b\", false},\n\t\t{\"a)b\", false},\n\t\t{\"a(b\", false},\n\t\t{\"a]b\", false},\n\t\t{\"a\\nb\", false},\n\t\t{\"a?b\", false},\n\t\t{\"a#b\", false},\n\t\t{\"a%b\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, safePath(tt.in), \"safePath(\"+tt.in+\")\")\n\t}\n}\n\nfunc TestSubViews(t *testing.T) {\n\ts := mainnet()\n\tuassert.Equal(t, DefaultBase+\"/packages?network=mainnet\u0026pv=inert\", s.Packages(PackagesInert))\n\tuassert.Equal(t, DefaultBase+\"/packages?network=mainnet\", s.Packages(\"\"))\n\tuassert.Equal(t, DefaultBase+\"/accounts?av=balances\u0026network=mainnet\", s.Accounts(AccountsBalances))\n\tuassert.Equal(t, DefaultBase+\"/accounts?network=mainnet\", s.Accounts(\"\"))\n}\n"}]},"send":"","max_deposit":"14000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"nestedpkg","path":"gno.land/p/moul/nestedpkg/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/nestedpkg`\n\nAccess control by package path. Instead of \"is the caller this address\", ask\n\"is the caller inside my namespace, below me, or above me in the tree\".\n\n```go\nfunc IsCallerSubPath(_ int, rlm realm) bool\nfunc IsCallerParentPath(_ int, rlm realm) bool\nfunc IsSameNamespace(_ int, rlm realm) bool\n\nfunc AssertCallerIsSubPath(_ int, rlm realm)     // panics instead\nfunc AssertCallerIsParentPath(_ int, rlm realm)\nfunc AssertIsSameNamespace(_ int, rlm realm)\n```\n\nEach helper compares `rlm.PkgPath()` with `rlm.Previous().PkgPath()`:\n\n| helper | true when the caller is |\n| --- | --- |\n| `IsCallerSubPath` | below the current realm (`r/moul/app/sub` calling `r/moul/app`) |\n| `IsCallerParentPath` | above it (`r/moul/app` calling `r/moul/app/sub`) |\n| `IsSameNamespace` | under the same `r/\u003cuser\u003e` prefix |\n\nThat is what makes upgrade patterns work: `r/moul/app/v2` can be allowed to\nread `r/moul/app/v1`'s state without either version knowing the other's\naddress, because the namespace is the credential.\n\n## Security: why every helper takes `rlm realm`\n\nA realm value can be captured and stashed. A hostile realm that kept one from\nan earlier call could hand it back later to impersonate the path it names.\nEvery helper here gates on `rlm.IsCurrent()` **first**, before reading any\npath, which closes that forgery: the value must be the live one for this call.\n\nThe two families fail differently, on purpose:\n\n- `Is*` returns `false` on a stale `rlm` (fail closed, so a check cannot be\n  turned into a pass by replaying an old value);\n- `Assert*` panics.\n\nThe leading `_ int` parameter is unused (`_`). Pass `0`.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/nestedpkg/v0\"\ngno = \"0.9\"\n"},{"name":"nestedpkg.gno","body":"// Package nestedpkg provides helpers for package-path based access control.\n// It is useful for upgrade patterns relying on namespaces.\n//\n// SECURITY: every exported helper takes `rlm realm` and reads both\n// `rlm.PkgPath()` and `rlm.Previous().PkgPath()` to make an\n// authorization decision. To close Class-2 designation forgery (a\n// hostile realm stashes a captured realm value and passes it back to\n// spoof identity), every helper gates on `rlm.IsCurrent()` first. The\n// Is* predicates return false on stale rlm (fail-closed); the Assert*\n// helpers panic. See docs/resources/gno-security.md.\npackage nestedpkg\n\nimport \"strings\"\n\n// IsCallerSubPath checks if the caller realm is located in a subfolder of the current realm.\nfunc IsCallerSubPath(_ int, rlm realm) bool {\n\tif !rlm.IsCurrent() {\n\t\treturn false\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\treturn strings.HasPrefix(prevPath, curPath)\n}\n\n// AssertCallerIsSubPath panics if IsCallerSubPath returns false.\nfunc AssertCallerIsSubPath(_ int, rlm realm) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\tif !strings.HasPrefix(prevPath, curPath) {\n\t\tpanic(\"call restricted to nested packages. current realm is \" + curPath + \", previous realm is \" + prevPath)\n\t}\n}\n\n// IsCallerParentPath checks if the caller realm is located in a parent location of the current realm.\nfunc IsCallerParentPath(_ int, rlm realm) bool {\n\tif !rlm.IsCurrent() {\n\t\treturn false\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\treturn strings.HasPrefix(curPath, prevPath)\n}\n\n// AssertCallerIsParentPath panics if IsCallerParentPath returns false.\nfunc AssertCallerIsParentPath(_ int, rlm realm) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tvar (\n\t\tcurPath  = rlm.PkgPath() + \"/\"\n\t\tprevPath = rlm.Previous().PkgPath() + \"/\"\n\t)\n\tif !strings.HasPrefix(curPath, prevPath) {\n\t\tpanic(\"call restricted to parent packages. current realm is \" + curPath + \", previous realm is \" + prevPath)\n\t}\n}\n\n// IsSameNamespace checks if the caller realm and the current realm are in the same namespace.\nfunc IsSameNamespace(_ int, rlm realm) bool {\n\tif !rlm.IsCurrent() {\n\t\treturn false\n\t}\n\tvar (\n\t\tcurNs  = nsFromPath(rlm.PkgPath()) + \"/\"\n\t\tprevNs = nsFromPath(rlm.Previous().PkgPath()) + \"/\"\n\t)\n\treturn curNs == prevNs\n}\n\n// AssertIsSameNamespace panics if IsSameNamespace returns false.\nfunc AssertIsSameNamespace(_ int, rlm realm) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"unauthorized: rlm is not the caller's live cur\")\n\t}\n\tvar (\n\t\tcurNs  = nsFromPath(rlm.PkgPath()) + \"/\"\n\t\tprevNs = nsFromPath(rlm.Previous().PkgPath()) + \"/\"\n\t)\n\tif curNs != prevNs {\n\t\tpanic(\"call restricted to packages from the same namespace. current realm is \" + curNs + \", previous realm is \" + prevNs)\n\t}\n}\n\n// nsFromPath extracts the namespace from a package path.\nfunc nsFromPath(pkgpath string) string {\n\tparts := strings.Split(pkgpath, \"/\")\n\n\t// Specifically for gno.land, potential paths are in the form of DOMAIN/r/NAMESPACE/...\n\t// XXX: Consider extra checks.\n\t// XXX: Support non gno.land domains, where p/ and r/ won't be enforced.\n\tif len(parts) \u003e= 3 {\n\t\treturn parts[2]\n\t}\n\treturn \"\"\n}\n\n// XXX: Consider adding IsCallerDirectlySubPath\n// XXX: Consider adding IsCallerDirectlyParentPath\n"},{"name":"nestedpkg_test.gno","body":"package nestedpkg\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestNsFromPath(t *testing.T) {\n\tcases := []struct {\n\t\tpath string\n\t\twant string\n\t}{\n\t\t{\"gno.land/r/moul/home\", \"moul\"},\n\t\t{\"gno.land/p/moul/svg/v0\", \"moul\"},\n\t\t{\"gno.land/r/demo/boards\", \"demo\"},\n\t\t{\"gno.land/r/moul\", \"moul\"},\n\t\t// Fewer than three segments has no namespace slot.\n\t\t{\"gno.land/r\", \"\"},\n\t\t{\"gno.land\", \"\"},\n\t\t{\"\", \"\"},\n\t\t// The helper is domain-agnostic: it just takes the third segment.\n\t\t{\"example.com/r/alice/thing\", \"alice\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, nsFromPath(c.path), \"nsFromPath(\"+c.path+\")\")\n\t}\n}\n\n// What these tests can and cannot reach, because it is not obvious:\n//\n//   - testing.SetRealm sets the realm the helpers read as **current**\n//     (rlm.PkgPath()); this test package is what they see as **previous**\n//     (rlm.Previous().PkgPath()).\n//   - SetRealm's argument must be an `r/` path. PkgPath() panics with\n//     \"should only be called for Realms\" on a `p/` path.\n//\n// This package is `p/moul/nestedpkg/v0`, so previous is always a `p/` path\n// while current is always an `r/` path. A `p/` path can therefore never be a\n// prefix of the current one or vice versa, which makes the *matching* branches\n// of IsCallerSubPath/IsCallerParentPath unreachable from here — exercising\n// those needs a realm-hosted caller (an `r/` test package). The non-matching\n// branches and the whole namespace comparison are covered below.\nconst selfNS = \"moul\"\n\nfunc TestIsCallerSubPathRejectsUnrelated(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/other/thing\"))\n\tuassert.False(t, IsCallerSubPath(0, cur), \"an unrelated realm is not an ancestor of the caller\")\n}\n\nfunc TestIsCallerParentPathRejectsUnrelated(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/other/thing\"))\n\tuassert.False(t, IsCallerParentPath(0, cur), \"an unrelated realm is not a descendant of the caller\")\n}\n\nfunc TestIsSameNamespace(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/\" + selfNS + \"/anything\"))\n\tuassert.True(t, IsSameNamespace(0, cur), \"same namespace across p/ and r/\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/someoneelse/thing\"))\n\tuassert.False(t, IsSameNamespace(0, cur), \"different namespace\")\n}\n\nfunc TestAssertCallerIsSubPathPanics(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/other/thing\"))\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"call restricted to nested packages. current realm is gno.land/r/other/thing/, previous realm is gno.land/p/moul/nestedpkg/v0/\",\n\t\tfunc() { AssertCallerIsSubPath(0, cur) })\n}\n\nfunc TestAssertCallerIsParentPathPanics(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/other/thing\"))\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"call restricted to parent packages. current realm is gno.land/r/other/thing/, previous realm is gno.land/p/moul/nestedpkg/v0/\",\n\t\tfunc() { AssertCallerIsParentPath(0, cur) })\n}\n\nfunc TestAssertIsSameNamespaceAllowsAndPanics(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/\" + selfNS + \"/anything\"))\n\tAssertIsSameNamespace(0, cur) // same namespace: must not panic\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/someoneelse/thing\"))\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"call restricted to packages from the same namespace. current realm is someoneelse/, previous realm is \"+selfNS+\"/\",\n\t\tfunc() { AssertIsSameNamespace(0, cur) })\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ownable","path":"gno.land/p/moul/ownable/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/ownable`\n\n\u003e 🚧 **API sketch, not an implementation.** The types below are declared; the\n\u003e two composition helpers `panic(\"not implemented\")`. Nothing here works yet.\n\u003e Do not import it expecting behaviour.\n\nA proposal for one `Owner` interface covering every kind of thing that can own\na realm, so that ownership checks stop being written four different ways.\n\n```go\ntype Owner interface {\n\tAddr() address\n\tKind() Kind\n\towner()   // unexported: only this package may implement Owner\n}\n```\n\nFour owner kinds are declared: `UserOwner` (an address), `RealmOwner` (a\n`runtime.Realm`), `MembstoreOwner` and `DAOOwner` (both still empty structs,\nwaiting on the membstore and dao interfaces).\n\nThe part worth keeping is the composition idea: ownership as an expression\nrather than a single address.\n\n```go\nfunc And(a Owner, b ...Owner) Owner   // panics today\nfunc Or(a Owner, b ...Owner) Owner    // panics today\n```\n\n`Or(user, dao)` is \"the owner, or the DAO that can override them\".\n`And(a, b)` is a 2-of-2. Today every realm hardcodes one of these shapes.\n\nThe tests pin the surface on purpose: they assert that `And` and `Or` panic, so\nimplementing one is a visible change to this package rather than a silent shift\nin behaviour for whoever imported it.\n\nRecovered from an unmerged upstream proposal. For ownership that works today,\nuse [`p/nt/ownable`](https://github.com/gnolang/gno/tree/master/examples/gno.land/p/nt/ownable)\nor [`p/moul/authz`](../authz).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/ownable/v0\"\ngno = \"0.9\"\n"},{"name":"ownable.gno","body":"// Package ownable proposes an abstraction around the ownership which provides\n// various kind of owners and some composition options.\npackage ownable\n\nimport \"chain/runtime\"\n\ntype Owner interface {\n\tAddr() address\n\tKind() Kind\n\towner()\n}\n\ntype Kind int\n\ntype UserOwner struct {\n\taddr address\n}\n\ntype RealmOwner struct {\n\trealm runtime.Realm\n}\n\ntype MembstoreOwner struct {\n\t// membstore.Membstore\n}\n\ntype DAOOwner struct {\n\t// dao.DAO\n}\n\nfunc And(a Owner, b ...Owner) Owner { panic(\"not implemented\") }\nfunc Or(a Owner, b ...Owner) Owner  { panic(\"not implemented\") }\n"},{"name":"ownable_test.gno","body":"package ownable\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// This package is an API sketch recovered from an unmerged upstream proposal:\n// it declares the Owner abstraction and its four owner kinds, but And/Or are\n// `panic(\"not implemented\")`. The tests pin that surface so that implementing\n// one is a deliberate, visible change rather than a silent behaviour shift.\n\nfunc TestCompositionHelpersAreNotImplemented(cur realm, t *testing.T) {\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { And(nil) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { Or(nil) })\n}\n\n// TestOwnerKindsAreDeclared is a compile-time check that the concrete owner\n// types still exist with their documented shape.\nfunc TestOwnerKindsAreDeclared(t *testing.T) {\n\tvar (\n\t\t_ UserOwner\n\t\t_ RealmOwner\n\t\t_ MembstoreOwner\n\t\t_ DAOOwner\n\t\t_ Kind\n\t)\n\tuassert.True(t, true, \"owner kinds are declared\")\n}\n\n// TestKindIsAnInt pins Kind's underlying type: it is compared and likely\n// persisted numerically, so a change of base type is breaking.\nfunc TestKindIsAnInt(t *testing.T) {\n\tvar k Kind\n\tuassert.Equal(t, 0, int(k), \"zero Kind is 0\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pageable","path":"gno.land/p/moul/pageable/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/pageable`\n\nPagination for anything that can hand out a window of its items, plus the\nMarkdown page picker to navigate it.\n\nImplement one method and you get pages, page sizes, reverse order, URL query\nparsing and a rendered picker:\n\n```go\ntype Pageable interface {\n\tSize() int\n\tIterateByOffset(offset, count int, cb func(index, value interface{}) bool) bool\n}\n```\n\nNote the single `IterateByOffset`. Some structures expose separate forward and\nreverse iteration; this interface deliberately does not. Direction is carried\nby the sign of `count` (offset 0 count 5 gives items 0..4; offset 0 count -5\ngives 4..0), and the implementation handles it internally, so the pager has one\ncode path instead of two.\n\n## Use\n\n```go\npager := pageable.NewPager(source, 10 /* default page size */, false /* reversed */)\n\npage := pager.MustGetPageByPath(path)   // reads ?page= and ?size= from the path\nout := \"\"\nfor _, item := range page.Items {\n\tout += \"- \" + item.Value.(string) + \"\\n\"   // Item is {Index, Value interface{}}\n}\nout += page.Picker()                    // \"1 | **2** | 3 | ...\" as Markdown links\n```\n\n`GetPageByPath` returns an error instead of panicking; `MustGetPageByPath` is\nthe Render-side shorthand. `PickerWithPath(path)` preserves the other query\nparameters (everything but `page`), which is what you want when the realm has\nits own filters in the URL.\n\n`GetPage(n)` and `GetPageWithSize(n, size)` skip URL parsing entirely.\n\n`Page` also carries `TotalItems`, `TotalPages`, `HasPrev` and `HasNext`, so a\nrealm can render its own navigation instead of using `Picker()`.\n\n## Nothing imports it\n\nThe package doc claims two consumers, `p/nt/avl/pager` and\n`p/moul/ulist/pager`. Neither holds today: the upstream\n[`p/nt/avl/pager`](https://github.com/gnolang/gno/tree/master/examples/gno.land/p/nt/avl/pager)\nis a standalone AVL pager that does not import this interface, and\n`p/moul/ulist/pager` does not exist in this repository (`p/moul/ulist` ships\n`lplist`, not a pager). Grepping this repo, the only files mentioning\n`pageable` are its own source and test.\n\nSo treat it as a proposed interface with a working reference implementation and\na 410-line test, not as load-bearing code. The package doc comment has been\ncorrected to say so.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/pageable/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/pageable/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/pageable/v0\"\ngno = \"0.9\"\n"},{"name":"pageable.gno","body":"// Package pageable implements a flexible pagination system that can be used with any data structure\n// that implements the Pageable interface. It provides functionality for:\n//\n//   - Paginating through collections of items\n//   - Configurable page sizes\n//   - Forward and reverse iteration\n//   - URL query parameter parsing\n//   - Markdown-based pagination UI\n//\n// Nothing imports it yet. An earlier version of this comment named\n// gno.land/p/nt/avl/pager and gno.land/p/moul/ulist/pager as consumers; neither\n// is one. The upstream avl pager is a standalone implementation that does not\n// go through this interface, and ulist ships lplist, not a pager. Treat this as\n// a proposed interface with a reference Pager and a test, not as load-bearing\n// code.\npackage pageable\n\nimport (\n\t\"math\"\n\t\"net/url\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Pageable defines the minimal interface required for pagination.\n// This interface is intentionally lightweight, requiring only two methods.\n// While some data structures (like AVL trees) might have separate methods for forward\n// and reverse iteration, this interface consolidates both directions into a single\n// IterateByOffset method. It's the responsibility of the implementing wrapper to\n// handle the direction logic internally based on the offset and count parameters.\ntype Pageable interface {\n\t// Size returns the total number of items\n\tSize() int\n\n\t// IterateByOffset performs iteration starting from offset for count elements.\n\t// The callback receives an index and a value, returns true to stop iteration.\n\t//\n\t// For reverse iteration, the implementation should handle the direction internally\n\t// by adjusting how it interprets the offset and count parameters. For example:\n\t// - In forward mode: offset 0, count 5 would return items [0,1,2,3,4]\n\t// - In reverse mode: offset 0, count -5 would return items [4,3,2,1,0]\n\t//\n\t// This approach allows the interface to remain simple while supporting\n\t// bidirectional iteration through the implementation layer.\n\tIterateByOffset(offset int, count int, cb func(index interface{}, value interface{}) bool) bool\n}\n\n// Pager provides pagination functionality for any Pageable source\ntype Pager struct {\n\tSource          Pageable\n\tPageQueryParam  string\n\tSizeQueryParam  string\n\tDefaultPageSize int\n\tReversed        bool\n}\n\n// Page represents a single page of results\ntype Page struct {\n\tItems      []Item\n\tPageNumber int\n\tPageSize   int\n\tTotalItems int\n\tTotalPages int\n\tHasPrev    bool\n\tHasNext    bool\n\tPager      *Pager\n}\n\n// Item represents a generic item in the page\ntype Item struct {\n\tIndex interface{}\n\tValue interface{}\n}\n\n// NewPager creates a new Pager with default values\nfunc NewPager(source Pageable, defaultPageSize int, reversed bool) *Pager {\n\treturn \u0026Pager{\n\t\tSource:          source,\n\t\tPageQueryParam:  \"page\",\n\t\tSizeQueryParam:  \"size\",\n\t\tDefaultPageSize: defaultPageSize,\n\t\tReversed:        reversed,\n\t}\n}\n\n// GetPage retrieves a page of results from the AVL tree.\nfunc (p *Pager) GetPage(pageNumber int) *Page {\n\treturn p.GetPageWithSize(pageNumber, p.DefaultPageSize)\n}\n\n// Helper function to create a basic page\nfunc (p *Pager) newBasePage(pageSize int) *Page {\n\ttotalItems := p.Source.Size()\n\ttotalPages := 0\n\tif pageSize \u003e 0 {\n\t\ttotalPages = int(math.Ceil(float64(totalItems) / float64(pageSize)))\n\t}\n\n\treturn \u0026Page{\n\t\tTotalItems: totalItems,\n\t\tTotalPages: totalPages,\n\t\tPageSize:   pageSize,\n\t\tPager:      p,\n\t}\n}\n\nfunc (p *Pager) GetPageWithSize(pageNumber, pageSize int) *Page {\n\t// Handle invalid page size\n\tif pageSize \u003c= 0 {\n\t\treturn p.newBasePage(pageSize)\n\t}\n\n\tpage := p.newBasePage(pageSize)\n\n\t// For empty source, return empty page with no navigation\n\tif page.TotalItems == 0 {\n\t\tpage.HasPrev = false\n\t\tpage.HasNext = false\n\t\treturn page\n\t}\n\n\t// page number provided is not available\n\tif pageNumber \u003c 1 {\n\t\tpage.HasNext = page.TotalPages \u003e 0\n\t\treturn page\n\t}\n\n\t// page number provided is outside the range of total pages\n\tif pageNumber \u003e page.TotalPages {\n\t\tpage.PageNumber = pageNumber\n\t\tpage.HasPrev = page.TotalPages \u003e 0\n\t\treturn page\n\t}\n\n\t// Calculate offset and size\n\tvar offset, iterCount int\n\tif p.Reversed {\n\t\t// For reversed order, calculate from the end\n\t\titerCount = min(pageSize, page.TotalItems-((pageNumber-1)*pageSize))\n\t\toffset = max(0, page.TotalItems-(pageNumber*pageSize))\n\t} else {\n\t\toffset = (pageNumber - 1) * pageSize\n\t\titerCount = pageSize\n\t}\n\n\t// Collect items for the current page\n\tvar items []Item\n\tif p.Reversed {\n\t\t// For reversed order, use negative count to indicate reverse iteration\n\t\toffset = page.TotalItems - offset - iterCount\n\t\tp.Source.IterateByOffset(offset, -iterCount, func(index interface{}, value interface{}) bool {\n\t\t\titems = append(items, Item{Index: index, Value: value})\n\t\t\treturn false\n\t\t})\n\t} else {\n\t\tp.Source.IterateByOffset(offset, iterCount, func(index interface{}, value interface{}) bool {\n\t\t\titems = append(items, Item{Index: index, Value: value})\n\t\t\treturn false\n\t\t})\n\t}\n\n\tpage.Items = items\n\tpage.PageNumber = pageNumber\n\tpage.HasPrev = pageNumber \u003e 1\n\tpage.HasNext = pageNumber \u003c page.TotalPages\n\treturn page\n}\n\nfunc (p *Pager) MustGetPageByPath(rawURL string) *Page {\n\tpage, err := p.GetPageByPath(rawURL)\n\tif err != nil {\n\t\tpanic(\"invalid path\")\n\t}\n\treturn page\n}\n\n// GetPageByPath retrieves a page of results based on the query parameters in the URL path.\nfunc (p *Pager) GetPageByPath(rawURL string) (*Page, error) {\n\tpageNumber, pageSize, err := p.ParseQuery(rawURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.GetPageWithSize(pageNumber, pageSize), nil\n}\n\n// Picker generates the Markdown UI for the page picker using default query string format\nfunc (p *Page) Picker() string {\n\treturn p.PickerWithPath(\"\")\n}\n\n// PickerWithPath generates the Markdown UI for the page picker with optional path\n// If path is provided, it preserves existing query parameters (except page)\nfunc (p *Page) PickerWithPath(path string) string {\n\tpageNumber := p.PageNumber\n\tpageNumber = max(pageNumber, 1)\n\n\tif p.TotalPages \u003c= 1 {\n\t\treturn \"\"\n\t}\n\n\t// Parse existing query parameters if path is provided\n\tbaseQuery := \"\"\n\tif path != \"\" {\n\t\tu, _ := url.Parse(path)\n\t\tif u != nil {\n\t\t\tquery := u.Query()\n\t\t\t// Remove existing page query parameter\n\t\t\tquery.Del(p.Pager.PageQueryParam)\n\t\t\t// Encode remaining query parameters\n\t\t\tbaseQuery = query.Encode()\n\t\t\tif baseQuery != \"\" {\n\t\t\t\tbaseQuery = \"\u0026\" + baseQuery\n\t\t\t}\n\t\t}\n\t}\n\n\tmd := \"\"\n\n\tif p.HasPrev {\n\t\t// Always show the first page link\n\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", 1, p.Pager.PageQueryParam, 1, baseQuery)\n\n\t\t// Before\n\t\tif p.PageNumber \u003e 4 {\n\t\t\tmd += \"… | \"\n\t\t}\n\n\t\tif p.PageNumber \u003e 3 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber-2, p.Pager.PageQueryParam, p.PageNumber-2, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003e 2 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber-1, p.Pager.PageQueryParam, p.PageNumber-1, baseQuery)\n\t\t}\n\t}\n\n\tif p.PageNumber \u003e 0 \u0026\u0026 p.PageNumber \u003c= p.TotalPages {\n\t\t// Current page\n\t\tmd += ufmt.Sprintf(\"**%d**\", p.PageNumber)\n\t} else {\n\t\tmd += ufmt.Sprintf(\"_%d_\", p.PageNumber)\n\t}\n\n\tif p.HasNext {\n\t\tmd += \" | \"\n\n\t\tif p.PageNumber \u003c p.TotalPages-1 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber+1, p.Pager.PageQueryParam, p.PageNumber+1, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003c p.TotalPages-2 {\n\t\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s) | \", p.PageNumber+2, p.Pager.PageQueryParam, p.PageNumber+2, baseQuery)\n\t\t}\n\n\t\tif p.PageNumber \u003c p.TotalPages-3 {\n\t\t\tmd += \"… | \"\n\t\t}\n\n\t\t// Always show the last page link\n\t\tmd += ufmt.Sprintf(\"[%d](?%s=%d%s)\", p.TotalPages, p.Pager.PageQueryParam, p.TotalPages, baseQuery)\n\t}\n\n\treturn md\n}\n\n// Helper to safely parse positive integers with a default value\nfunc parsePositiveIntOrDefault(str string, defaultValue int) int {\n\tif str == \"\" {\n\t\treturn defaultValue\n\t}\n\tval, err := strconv.Atoi(str)\n\tif err != nil || val \u003c 1 {\n\t\treturn defaultValue\n\t}\n\treturn val\n}\n\nfunc (p *Pager) ParseQuery(rawURL string) (int, int, error) {\n\tu, err := url.Parse(rawURL)\n\tif err != nil {\n\t\treturn 1, p.DefaultPageSize, err\n\t}\n\n\tquery := u.Query()\n\tpageNumber := parsePositiveIntOrDefault(query.Get(p.PageQueryParam), 1)\n\tpageSize := parsePositiveIntOrDefault(query.Get(p.SizeQueryParam), p.DefaultPageSize)\n\n\treturn pageNumber, pageSize, nil\n}\n\nfunc max(a, b int) int {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc min(a, b int) int {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n"},{"name":"pageable_test.gno","body":"package pageable\n\nimport (\n\t\"testing\"\n)\n\n// MockPageable implements the Pageable interface for testing\ntype MockPageable struct {\n\titems []int\n}\n\nfunc (m *MockPageable) Size() int {\n\treturn len(m.items)\n}\n\nfunc (m *MockPageable) IterateByOffset(offset int, count int, cb func(index interface{}, value interface{}) bool) bool {\n\tif count \u003c 0 {\n\t\t// Handle reversed iteration\n\t\tcount = -count                     // Make count positive\n\t\tstart := len(m.items) - 1 - offset // Adjust start position from the end\n\t\tif start \u003e= len(m.items) {\n\t\t\tstart = len(m.items) - 1\n\t\t}\n\t\tend := start - count + 1\n\t\tif end \u003c 0 {\n\t\t\tend = 0\n\t\t}\n\t\tfor i := start; i \u003e= end; i-- {\n\t\t\tif cb(i, m.items[i]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tend := offset + count\n\tif end \u003e len(m.items) {\n\t\tend = len(m.items)\n\t}\n\n\tfor i := offset; i \u003c end; i++ {\n\t\tif cb(i, m.items[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc TestPager(t *testing.T) {\n\t// Create test data\n\tmock := \u0026MockPageable{\n\t\titems: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t}\n\n\ttests := []struct {\n\t\tname        string\n\t\tpageSize    int\n\t\tpageNum     int\n\t\twantItems   int\n\t\twantTotal   int\n\t\twantPages   int\n\t\twantHasPrev bool\n\t\twantHasNext bool\n\t}{\n\t\t{\"first page\", 3, 1, 3, 10, 4, false, true},\n\t\t{\"middle page\", 3, 2, 3, 10, 4, true, true},\n\t\t{\"last page\", 3, 4, 1, 10, 4, true, false},\n\t\t{\"invalid page\", 3, 5, 0, 10, 4, true, false},\n\t\t{\"zero page\", 3, 0, 0, 10, 4, false, true},\n\t\t{\"all items\", 10, 1, 10, 10, 1, false, false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpager := NewPager(mock, tt.pageSize, false)\n\t\t\tpage := pager.GetPage(tt.pageNum)\n\n\t\t\tif len(page.Items) != tt.wantItems {\n\t\t\t\tt.Errorf(\"got %d items, want %d\", len(page.Items), tt.wantItems)\n\t\t\t}\n\t\t\tif page.TotalItems != tt.wantTotal {\n\t\t\t\tt.Errorf(\"got %d total items, want %d\", page.TotalItems, tt.wantTotal)\n\t\t\t}\n\t\t\tif page.TotalPages != tt.wantPages {\n\t\t\t\tt.Errorf(\"got %d total pages, want %d\", page.TotalPages, tt.wantPages)\n\t\t\t}\n\t\t\tif page.HasPrev != tt.wantHasPrev {\n\t\t\t\tt.Errorf(\"got HasPrev=%v, want %v\", page.HasPrev, tt.wantHasPrev)\n\t\t\t}\n\t\t\tif page.HasNext != tt.wantHasNext {\n\t\t\t\tt.Errorf(\"got HasNext=%v, want %v\", page.HasNext, tt.wantHasNext)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPicker(t *testing.T) {\n\tmock := \u0026MockPageable{\n\t\titems: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t}\n\n\ttests := []struct {\n\t\tname     string\n\t\tpageSize int\n\t\tpageNum  int\n\t\twant     string\n\t}{\n\t\t{\"first page\", 3, 1, \"**1** | [2](?page=2) | [3](?page=3) | [4](?page=4)\"},\n\t\t{\"middle page\", 3, 2, \"[1](?page=1) | **2** | [3](?page=3) | [4](?page=4)\"},\n\t\t{\"last page\", 3, 4, \"[1](?page=1) | [2](?page=2) | [3](?page=3) | **4**\"},\n\t\t{\"single page\", 10, 1, \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpager := NewPager(mock, tt.pageSize, false)\n\t\t\tpage := pager.GetPage(tt.pageNum)\n\t\t\tgot := page.Picker()\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"\\ngot:  %s\\nwant: %s\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReversedPager(t *testing.T) {\n\tmock := \u0026MockPageable{\n\t\titems: []int{1, 2, 3, 4, 5},\n\t}\n\n\tpager := NewPager(mock, 2, true)\n\tpage := pager.GetPage(1)\n\n\tif len(page.Items) != 2 {\n\t\tt.Errorf(\"got %d items, want 2\", len(page.Items))\n\t}\n\n\t// Check if items are in reverse order\n\tif page.Items[0].Value.(int) != 5 || page.Items[1].Value.(int) != 4 {\n\t\tt.Errorf(\"items not in reverse order: got %v\", page.Items)\n\t}\n}\n\nfunc TestParseQuery(t *testing.T) {\n\tmock := \u0026MockPageable{items: []int{1, 2, 3}}\n\tpager := NewPager(mock, 10, false)\n\n\ttests := []struct {\n\t\tname      string\n\t\turl       string\n\t\twantPage  int\n\t\twantSize  int\n\t\twantError bool\n\t}{\n\t\t{\"valid query\", \"/?page=2\u0026size=5\", 2, 5, false},\n\t\t{\"missing params\", \"/\", 1, 10, false},\n\t\t{\"invalid page\", \"/?page=invalid\", 1, 10, false},\n\t\t{\"invalid size\", \"/?size=invalid\", 1, 10, false},\n\t\t{\"negative values\", \"/?page=-1\u0026size=-5\", 1, 10, false},\n\t\t{\"invalid url\", \":%invalid\", 1, 10, true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpage, size, err := pager.ParseQuery(tt.url)\n\t\t\tif (err != nil) != tt.wantError {\n\t\t\t\tt.Errorf(\"got error=%v, want error=%v\", err != nil, tt.wantError)\n\t\t\t}\n\t\t\tif page != tt.wantPage {\n\t\t\t\tt.Errorf(\"got page=%d, want %d\", page, tt.wantPage)\n\t\t\t}\n\t\t\tif size != tt.wantSize {\n\t\t\t\tt.Errorf(\"got size=%d, want %d\", size, tt.wantSize)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPager_UI_WithManyPages(t *testing.T) {\n\tmock := \u0026MockPageable{\n\t\titems: make([]int, 100),\n\t}\n\tfor i := 0; i \u003c 100; i++ {\n\t\tmock.items[i] = i\n\t}\n\n\tpager := NewPager(mock, 10, false)\n\n\ttests := []struct {\n\t\tname     string\n\t\tpageNum  int\n\t\tpageSize int\n\t\twant     string\n\t}{\n\t\t{\"first page\", 1, 10, \"**1** | [2](?page=2) | [3](?page=3) | … | [10](?page=10)\"},\n\t\t{\"second page\", 2, 10, \"[1](?page=1) | **2** | [3](?page=3) | [4](?page=4) | … | [10](?page=10)\"},\n\t\t{\"middle page\", 5, 10, \"[1](?page=1) | … | [3](?page=3) | [4](?page=4) | **5** | [6](?page=6) | [7](?page=7) | … | [10](?page=10)\"},\n\t\t{\"penultimate page\", 9, 10, \"[1](?page=1) | … | [7](?page=7) | [8](?page=8) | **9** | [10](?page=10)\"},\n\t\t{\"last page\", 10, 10, \"[1](?page=1) | … | [8](?page=8) | [9](?page=9) | **10**\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpage := pager.GetPageWithSize(tt.pageNum, tt.pageSize)\n\t\t\tgot := page.Picker()\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"\\ngot:  %s\\nwant: %s\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetPageWithSize(t *testing.T) {\n\tmock := \u0026MockPageable{\n\t\titems: []int{1, 2, 3, 4, 5},\n\t}\n\n\tpager := NewPager(mock, 10, false)\n\n\ttests := []struct {\n\t\tname      string\n\t\tpageNum   int\n\t\tpageSize  int\n\t\twantLen   int\n\t\twantFirst int\n\t}{\n\t\t{\"custom size smaller\", 1, 2, 2, 1},\n\t\t{\"custom size exact\", 1, 5, 5, 1},\n\t\t{\"custom size larger\", 1, 10, 5, 1},\n\t\t{\"second page partial\", 2, 3, 2, 4},\n\t\t{\"empty page\", 3, 3, 0, 0},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpage := pager.GetPageWithSize(tt.pageNum, tt.pageSize)\n\t\t\tif len(page.Items) != tt.wantLen {\n\t\t\t\tt.Errorf(\"got %d items, want %d\", len(page.Items), tt.wantLen)\n\t\t\t}\n\t\t\tif tt.wantLen \u003e 0 \u0026\u0026 page.Items[0].Value.(int) != tt.wantFirst {\n\t\t\t\tt.Errorf(\"first item got %d, want %d\", page.Items[0].Value.(int), tt.wantFirst)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestInvalidInputs(t *testing.T) {\n\tmock := \u0026MockPageable{\n\t\titems: []int{1, 2, 3},\n\t}\n\n\ttests := []struct {\n\t\tname     string\n\t\tpageSize int\n\t\tpageNum  int\n\t\twantLen  int\n\t}{\n\t\t{\"zero page size\", 0, 1, 0},\n\t\t{\"negative page size\", -1, 1, 0},\n\t\t{\"negative page number\", 10, -1, 0},\n\t\t{\"too large page number\", 10, 999, 0},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpager := NewPager(mock, tt.pageSize, false)\n\t\t\tpage := pager.GetPage(tt.pageNum)\n\t\t\tif len(page.Items) != tt.wantLen {\n\t\t\t\tt.Errorf(\"got %d items, want %d\", len(page.Items), tt.wantLen)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestEmptySource(t *testing.T) {\n\tmock := \u0026MockPageable{items: []int{}}\n\tpager := NewPager(mock, 10, false)\n\n\tpage := pager.GetPage(1)\n\tif page.TotalItems != 0 {\n\t\tt.Errorf(\"got total items %d, want 0\", page.TotalItems)\n\t}\n\tif page.TotalPages != 0 {\n\t\tt.Errorf(\"got total pages %d, want 0\", page.TotalPages)\n\t}\n\tif page.HasNext {\n\t\tt.Error(\"got HasNext=true, want false\")\n\t}\n\tif page.HasPrev {\n\t\tt.Error(\"got HasPrev=true, want false\")\n\t}\n\tif len(page.Items) != 0 {\n\t\tt.Errorf(\"got %d items, want 0\", len(page.Items))\n\t}\n}\n\nfunc TestReversedPagerEdgeCases(t *testing.T) {\n\tmock := \u0026MockPageable{\n\t\titems: []int{1, 2, 3, 4, 5},\n\t}\n\tpager := NewPager(mock, 2, true)\n\n\ttests := []struct {\n\t\tname     string\n\t\tpageNum  int\n\t\tpageSize int\n\t\twant     []int\n\t}{\n\t\t{\"last partial page\", 3, 2, []int{1}},\n\t\t{\"oversized page\", 1, 10, []int{5, 4, 3, 2, 1}},\n\t\t{\"empty result\", 4, 2, nil},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpage := pager.GetPageWithSize(tt.pageNum, tt.pageSize)\n\t\t\tgot := make([]int, len(page.Items))\n\t\t\tfor i, item := range page.Items {\n\t\t\t\tgot[i] = item.Value.(int)\n\t\t\t}\n\n\t\t\tif len(got) != len(tt.want) {\n\t\t\t\tt.Errorf(\"got length %d, want length %d\", len(got), len(tt.want))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor i := 0; i \u003c len(got); i++ {\n\t\t\t\tif got[i] != tt.want[i] {\n\t\t\t\t\tt.Errorf(\"at index %d: got %d, want %d\", i, got[i], tt.want[i])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCustomQueryParams(t *testing.T) {\n\tmock := \u0026MockPageable{items: []int{1, 2, 3}}\n\tpager := NewPager(mock, 10, false)\n\tpager.PageQueryParam = \"p\"\n\tpager.SizeQueryParam = \"s\"\n\n\ttests := []struct {\n\t\tname     string\n\t\turl      string\n\t\twantPage int\n\t\twantSize int\n\t}{\n\t\t{\"custom params\", \"/?p=2\u0026s=1\", 2, 1},\n\t\t{\"old params ignored\", \"/?page=3\u0026size=2\", 1, 10},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpage, size, err := pager.ParseQuery(tt.url)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unexpected error: %v\", err)\n\t\t\t}\n\t\t\tif page != tt.wantPage {\n\t\t\t\tt.Errorf(\"got page=%d, want %d\", page, tt.wantPage)\n\t\t\t}\n\t\t\tif size != tt.wantSize {\n\t\t\t\tt.Errorf(\"got size=%d, want %d\", size, tt.wantSize)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMustGetPageByPath(t *testing.T) {\n\tmock := \u0026MockPageable{items: []int{1, 2, 3}}\n\tpager := NewPager(mock, 10, false)\n\n\tt.Run(\"panic on invalid url\", func(t *testing.T) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Error(\"expected panic but got none\")\n\t\t\t}\n\t\t}()\n\t\tpager.MustGetPageByPath(\":%invalid\")\n\t})\n}\n\nfunc TestPickerWithPath(t *testing.T) {\n\tmock := \u0026MockPageable{\n\t\titems: []int{1, 2, 3, 4, 5, 6},\n\t}\n\n\ttests := []struct {\n\t\tname     string\n\t\tpageSize int\n\t\tpageNum  int\n\t\tpath     string\n\t\twant     string\n\t}{\n\t\t{\"with query params\", 2, 1, \"/test?foo=bar\u0026baz=qux\", \"**1** | [2](?page=2\u0026baz=qux\u0026foo=bar) | [3](?page=3\u0026baz=qux\u0026foo=bar)\"},\n\t\t{\"existing page param\", 2, 2, \"/test?page=999\u0026other=value\", \"[1](?page=1\u0026other=value) | **2** | [3](?page=3\u0026other=value)\"},\n\t\t{\"no query params\", 2, 3, \"/test\", \"[1](?page=1) | [2](?page=2) | **3**\"},\n\t\t{\"empty path\", 2, 2, \"\", \"[1](?page=1) | **2** | [3](?page=3)\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpager := NewPager(mock, tt.pageSize, false)\n\t\t\tpage := pager.GetPageWithSize(tt.pageNum, tt.pageSize)\n\t\t\tgot := page.PickerWithPath(tt.path)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"\\ngot:  %s\\nwant: %s\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"}]},"send":"","max_deposit":"9000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pausable","path":"gno.land/p/moul/pausable/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/pausable`\n\nThe switch a realm checks before it acts: a parsed pause state, the rule for\ncombining two of them, and the asserts that stop a call.\n\nIt holds no state and knows nothing about where a pause setting is stored.\n[`r/moul/config`](../../../r/moul/config) is the realm that stores one and\nwires this to it; this package is the part worth getting right once.\n\n```go\nst := pausable.MustParse(raw)   // a stored value, failing closed\nst.AllowsRead()                 // false only when fully paused\nst.AllowsWrite()                // false unless running\nst.AssertWritable()             // aborts, with the reason if there is one\nst.Notice()                     // the markdown banner, or \"\" while running\npausable.Strictest(a, b)        // combine a global and a per-realm state\n```\n\n## Three levels, because \"paused\" is usually too blunt\n\nTaking a realm fully offline hides the thing people came to read. Most\nincidents only need the writes stopped: a board keeps rendering, an exchange\nkeeps quoting, nothing new lands while the fix is prepared.\n\n| level | value | reads | writes |\n|---|---|---|---|\n| Running | `\"\"` or `running` | yes | yes |\n| ReadOnly | `readonly` | yes | no |\n| Paused | `paused` | no | no |\n\nEach optionally followed by `: \u003creason\u003e`, which shows up in the banner and in\nthe abort message: `paused: migrating storage, back in an hour`.\n\nSo a realm guards its mutating functions and leaves `Render` alone:\n\n```go\nfunc Post(cur realm, body string) {\n\tconfig.AssertWritable()          // aborts while ReadOnly or Paused\n\t...\n}\n\nfunc Render(path string) string {\n\treturn config.TopBlock() + body  // the banner explains itself\n}\n```\n\n`AssertReadable` exists but most realms should not put it in `Render`. A page\nthat aborts tells a reader nothing; the banner tells them what happened and\nwhen to come back. Reach for it only where serving stale data is itself the\nharm.\n\n## It fails closed, and that is why the writer must validate\n\n`MustParse` turns a value it does not recognise into **Paused**, not Running. A\npause switch that a typo silently disables is not a pause switch: the failure\nwould be invisible until the incident it was meant to cover.\n\nThe cost is that a typo takes a realm offline, so `Parse` reports `ok=false`\nand the storing realm is expected to refuse the write. **Validate on the way\nin, fail closed on the way out.** `r/moul/config` does exactly that, so in\npractice the closed path is never reached.\n\nThe values this refuses are the ones someone would plausibly type: `yes`,\n`true`, `1`, `on`, `stop`, `read-only`. None of them may read as Running.\n\n## The stricter of two states wins\n\nA global pause and a per-realm pause combine with `Strictest`, so a per-realm\nentry left behind from last month can never re-open a realm during a global\nhalt.\n\nThe cost is that exempting one realm from a global pause is not expressible.\nClear the global and set the others instead. That is the right trade for an\nemergency brake: the failure mode of the alternative is a stale exemption\nnobody remembers, discovered during the incident.\n\nThe reason travels with the level that won, and on a tie the first argument\ndoes, so calling `Strictest(global, scoped)` keeps the global explanation when\nboth say the same thing.\n\n## Notice is one markdown block\n\nThe reason is text a manager typed, and it lands inside a blockquote where a\nnewline would end the quote and let the rest render as page content. `Notice`\nfolds it to a single line.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/pausable/v0\"\ngno = \"0.9\"\n"},{"name":"pausable.gno","body":"// Package pausable is the switch a realm checks before it acts: a parsed pause\n// state, the rule for combining two of them, and the asserts that stop a call.\n//\n// # Three levels, because \"paused\" is usually too blunt\n//\n// Taking a realm fully offline hides the thing people came to read. Most\n// incidents only need the writes stopped: a board keeps rendering, an exchange\n// keeps quoting, and nothing new lands while the fix is prepared. So the\n// levels are Running, ReadOnly and Paused, and a realm normally guards its\n// mutating functions with AssertWritable and leaves Render alone.\n//\n//\tfunc Post(cur realm, body string) {\n//\t\tconfig.AssertWritable()  // aborts while the realm is ReadOnly or Paused\n//\t\t…\n//\t}\n//\n//\tfunc Render(path string) string {\n//\t\treturn config.TopBlock() + body  // the banner explains itself\n//\t}\n//\n// # It fails closed\n//\n// MustParse turns a value it does not recognise into Paused, not Running. A\n// pause switch that a typo silently disables is not a pause switch, and the\n// failure is loud and one transaction from fixed, where the opposite failure\n// is silent and discovered during the incident it was meant to cover.\n//\n// The cost of that choice is a typo taking a realm offline, so the writer is\n// expected to validate: Parse reports ok=false and the storing realm refuses\n// the write. Validate on the way in, fail closed on the way out.\n//\n// # The stricter of two states wins\n//\n// A global pause and a per-realm pause combine with Strictest, so a stale\n// per-realm entry can never re-open a realm during a global halt. The cost is\n// that exempting one realm from a global pause is not expressible; clear the\n// global and set the others instead.\npackage pausable\n\nimport \"strings\"\n\n// Level is how much of a realm is still allowed to work.\ntype Level int\n\nconst (\n\t// Running is the normal state, and what an unset value means.\n\tRunning Level = iota\n\t// ReadOnly still renders and still answers queries; it refuses writes.\n\tReadOnly\n\t// Paused refuses everything, reads included.\n\tPaused\n)\n\n// The canonical spelling of each level, which is what a value round-trips to.\nconst (\n\trunningWord  = \"running\"\n\treadOnlyWord = \"readonly\"\n\tpausedWord   = \"paused\"\n)\n\n// reasonSep separates the level from the human explanation in a stored value:\n// \"paused: migrating storage, back in an hour\".\nconst reasonSep = \":\"\n\nfunc (l Level) String() string {\n\tswitch l {\n\tcase Running:\n\t\treturn runningWord\n\tcase ReadOnly:\n\t\treturn readOnlyWord\n\tcase Paused:\n\t\treturn pausedWord\n\tdefault:\n\t\t// Not reachable through Parse, and not worth panicking over in a\n\t\t// Render path: an unknown level reads as the strictest one.\n\t\treturn pausedWord\n\t}\n}\n\n// AllowsRead reports whether rendering and querying are still allowed.\nfunc (l Level) AllowsRead() bool { return l != Paused }\n\n// AllowsWrite reports whether state-changing calls are still allowed.\nfunc (l Level) AllowsWrite() bool { return l == Running }\n\n// State is a parsed pause setting: a level and an optional reason to show.\n//\n// The zero State is Running with no reason, which is what an unset setting\n// means, so a realm that never configures anything is never paused.\ntype State struct {\n\tLevel  Level\n\tReason string\n}\n\n// Parse reads a stored value: \"\", \"running\", \"readonly\", \"paused\", each\n// optionally followed by \": \u003creason\u003e\".\n//\n// ok is false for anything else. A caller that is STORING the value should\n// refuse on !ok; a caller that is READING one should use MustParse, which\n// fails closed instead.\nfunc Parse(raw string) (State, bool) {\n\traw = strings.TrimSpace(raw)\n\tif raw == \"\" {\n\t\treturn State{}, true\n\t}\n\n\tword, reason := raw, \"\"\n\tif i := strings.Index(raw, reasonSep); i \u003e= 0 {\n\t\tword = strings.TrimSpace(raw[:i])\n\t\treason = strings.TrimSpace(raw[i+1:])\n\t}\n\n\tswitch strings.ToLower(word) {\n\tcase runningWord:\n\t\treturn State{Level: Running, Reason: reason}, true\n\tcase readOnlyWord:\n\t\treturn State{Level: ReadOnly, Reason: reason}, true\n\tcase pausedWord:\n\t\treturn State{Level: Paused, Reason: reason}, true\n\tdefault:\n\t\treturn State{}, false\n\t}\n}\n\n// MustParse is Parse for a reader, failing closed: a value it cannot read\n// becomes Paused, carrying the raw text as the reason so whoever hits it can\n// see what is wrong.\nfunc MustParse(raw string) State {\n\tif s, ok := Parse(raw); ok {\n\t\treturn s\n\t}\n\treturn State{Level: Paused, Reason: \"unreadable pause setting: \" + strings.TrimSpace(raw)}\n}\n\n// String renders a State back into a storable value. It round-trips through\n// Parse, and the zero State renders empty so an unset setting stays unset.\nfunc (s State) String() string {\n\tif s.Level == Running \u0026\u0026 s.Reason == \"\" {\n\t\treturn \"\"\n\t}\n\tif s.Reason == \"\" {\n\t\treturn s.Level.String()\n\t}\n\treturn s.Level.String() + reasonSep + \" \" + s.Reason\n}\n\n// Strictest returns whichever of the two stops more, keeping the reason that\n// belongs to the level it returns. On a tie the first argument wins, so a\n// caller passing (global, scoped) keeps the global explanation when both say\n// the same thing, and the scoped one when it is the stricter.\nfunc Strictest(a, b State) State {\n\tif b.Level \u003e a.Level {\n\t\treturn b\n\t}\n\treturn a\n}\n\n// AllowsRead reports whether rendering and querying are still allowed.\nfunc (s State) AllowsRead() bool { return s.Level.AllowsRead() }\n\n// AllowsWrite reports whether state-changing calls are still allowed.\nfunc (s State) AllowsWrite() bool { return s.Level.AllowsWrite() }\n\n// IsPaused reports whether anything at all is being held back. It is true for\n// ReadOnly as well as Paused, because the question a caller usually means by\n// \"is it paused\" is \"is it behaving normally\".\nfunc (s State) IsPaused() bool { return s.Level != Running }\n\n// AssertWritable aborts unless writes are allowed. This is the one a realm\n// puts at the top of every state-changing function.\nfunc (s State) AssertWritable() {\n\tif !s.AllowsWrite() {\n\t\tpanic(s.message(\"writes are paused\"))\n\t}\n}\n\n// AssertReadable aborts unless reads are allowed. Most realms do not want this\n// in Render: a page that aborts tells a reader nothing, while Notice tells\n// them what happened and when to come back.\nfunc (s State) AssertReadable() {\n\tif !s.AllowsRead() {\n\t\tpanic(s.message(\"paused\"))\n\t}\n}\n\nfunc (s State) message(what string) string {\n\tif s.Reason == \"\" {\n\t\treturn what\n\t}\n\treturn what + reasonSep + \" \" + s.Reason\n}\n\n// Notice is the banner a Render puts above its content, or \"\" while running.\n//\n// It is a markdown blockquote, so it reads as set apart from the page without\n// needing any style the renderer might not have.\nfunc (s State) Notice() string {\n\tif s.Level == Running {\n\t\treturn \"\"\n\t}\n\thead := \"**Paused.** This realm is not accepting anything right now.\"\n\tif s.Level == ReadOnly {\n\t\thead = \"**Read-only.** This realm is still readable, but not accepting changes.\"\n\t}\n\tif s.Reason == \"\" {\n\t\treturn \"\u003e \" + head\n\t}\n\t// The reason is text a manager typed, and it lands inside a blockquote\n\t// where a newline would end the quote and let the rest render as page\n\t// content. Folding it to a single line keeps the banner one block.\n\treturn \"\u003e \" + head + \" \" + oneLine(s.Reason)\n}\n\n// oneLine collapses every run of whitespace, newlines included, into single\n// spaces.\nfunc oneLine(s string) string {\n\tvar b strings.Builder\n\tspace := false\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == ' ' || c == '\\t' || c == '\\n' || c == '\\r' {\n\t\t\tspace = true\n\t\t\tcontinue\n\t\t}\n\t\tif space \u0026\u0026 b.Len() \u003e 0 {\n\t\t\tb.WriteByte(' ')\n\t\t}\n\t\tspace = false\n\t\tb.WriteByte(c)\n\t}\n\treturn b.String()\n}\n"},{"name":"pausable_test.gno","body":"package pausable\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestParse(t *testing.T) {\n\ttests := []struct {\n\t\traw        string\n\t\twantLevel  Level\n\t\twantReason string\n\t\twantOK     bool\n\t}{\n\t\t{\"\", Running, \"\", true},\n\t\t{\"   \", Running, \"\", true},\n\t\t{\"running\", Running, \"\", true},\n\t\t{\"readonly\", ReadOnly, \"\", true},\n\t\t{\"paused\", Paused, \"\", true},\n\t\t{\"Paused\", Paused, \"\", true},   // case-insensitive\n\t\t{\"  paused  \", Paused, \"\", true},\n\t\t{\"paused: migrating storage\", Paused, \"migrating storage\", true},\n\t\t{\"readonly:  spaced  \", ReadOnly, \"spaced\", true},\n\t\t{\"running: nothing wrong\", Running, \"nothing wrong\", true},\n\t\t// A reason containing the separator keeps everything after the first\n\t\t// one, so a URL or a time survives.\n\t\t{\"paused: back at 14:00 UTC\", Paused, \"back at 14:00 UTC\", true},\n\t\t// Not recognised. These are exactly the values that must NOT read as\n\t\t// Running.\n\t\t{\"yes\", Running, \"\", false},\n\t\t{\"true\", Running, \"\", false},\n\t\t{\"1\", Running, \"\", false},\n\t\t{\"stop\", Running, \"\", false},\n\t\t{\"read-only\", Running, \"\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tgot, ok := Parse(tt.raw)\n\t\tuassert.Equal(t, tt.wantOK, ok, \"Parse(\"+tt.raw+\") ok\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tuassert.Equal(t, int(tt.wantLevel), int(got.Level), \"Parse(\"+tt.raw+\") level\")\n\t\tuassert.Equal(t, tt.wantReason, got.Reason, \"Parse(\"+tt.raw+\") reason\")\n\t}\n}\n\n// TestMustParseFailsClosed is the whole safety argument of this package. Every\n// value here is something a person might plausibly type, and every one of them\n// has to stop the realm rather than quietly leave it running.\nfunc TestMustParseFailsClosed(t *testing.T) {\n\tfor _, raw := range []string{\"yes\", \"true\", \"1\", \"on\", \"stop\", \"PAUSE\", \"pasued\"} {\n\t\tgot := MustParse(raw)\n\t\tuassert.Equal(t, int(Paused), int(got.Level), \"MustParse(\"+raw+\") must fail closed\")\n\t\tuassert.False(t, got.AllowsWrite(), \"MustParse(\"+raw+\") must refuse writes\")\n\t\tuassert.True(t, len(got.Reason) \u003e 0, \"MustParse(\"+raw+\") must say why\")\n\t}\n\n\t// And the values it does understand are untouched.\n\tuassert.Equal(t, int(Running), int(MustParse(\"\").Level))\n\tuassert.Equal(t, int(ReadOnly), int(MustParse(\"readonly\").Level))\n}\n\nfunc TestAllows(t *testing.T) {\n\ttests := []struct {\n\t\tlevel     Level\n\t\tread      bool\n\t\twrite     bool\n\t\tisPaused  bool\n\t}{\n\t\t{Running, true, true, false},\n\t\t{ReadOnly, true, false, true},\n\t\t{Paused, false, false, true},\n\t}\n\tfor _, tt := range tests {\n\t\ts := State{Level: tt.level}\n\t\tuassert.Equal(t, tt.read, s.AllowsRead(), tt.level.String()+\" read\")\n\t\tuassert.Equal(t, tt.write, s.AllowsWrite(), tt.level.String()+\" write\")\n\t\tuassert.Equal(t, tt.isPaused, s.IsPaused(), tt.level.String()+\" isPaused\")\n\t}\n}\n\nfunc TestStrictest(t *testing.T) {\n\trun := State{Level: Running}\n\tro := State{Level: ReadOnly, Reason: \"scoped\"}\n\tpaused := State{Level: Paused, Reason: \"global\"}\n\n\tuassert.Equal(t, int(ReadOnly), int(Strictest(run, ro).Level))\n\tuassert.Equal(t, int(ReadOnly), int(Strictest(ro, run).Level))\n\tuassert.Equal(t, int(Paused), int(Strictest(paused, ro).Level))\n\tuassert.Equal(t, int(Paused), int(Strictest(ro, paused).Level))\n\n\t// A stale per-realm entry can never re-open a realm during a global halt.\n\t// This is the property the whole precedence rule exists for.\n\tuassert.Equal(t, int(Paused), int(Strictest(paused, run).Level),\n\t\t\"a per-realm 'running' cannot defeat a global pause\")\n\n\t// The reason travels with the level that won.\n\tuassert.Equal(t, \"global\", Strictest(paused, ro).Reason)\n\tuassert.Equal(t, \"scoped\", Strictest(run, ro).Reason)\n\n\t// On a tie the first argument wins, so a caller passing (global, scoped)\n\t// keeps the global explanation.\n\ta := State{Level: Paused, Reason: \"first\"}\n\tb := State{Level: Paused, Reason: \"second\"}\n\tuassert.Equal(t, \"first\", Strictest(a, b).Reason)\n}\n\nfunc TestStringRoundTrips(t *testing.T) {\n\tfor _, raw := range []string{\"\", \"readonly\", \"paused\", \"paused: migrating storage\"} {\n\t\ts, ok := Parse(raw)\n\t\tuassert.True(t, ok, \"Parse(\"+raw+\")\")\n\t\tagain, ok := Parse(s.String())\n\t\tuassert.True(t, ok, \"Parse(String()) for \"+raw)\n\t\tuassert.Equal(t, int(s.Level), int(again.Level), \"level round-trip for \"+raw)\n\t\tuassert.Equal(t, s.Reason, again.Reason, \"reason round-trip for \"+raw)\n\t}\n\n\t// The zero State renders empty, so an unset setting stays unset rather\n\t// than being written back as the word \"running\".\n\tuassert.Equal(t, \"\", State{}.String())\n\tuassert.Equal(t, \"running: why\", State{Reason: \"why\"}.String())\n}\n\nfunc TestAsserts(cur realm, t *testing.T) {\n\tState{}.AssertWritable()\n\tState{}.AssertReadable()\n\tState{Level: ReadOnly}.AssertReadable()\n\n\tuassert.PanicsWithMessage(t, cur, \"writes are paused\", func() {\n\t\tState{Level: ReadOnly}.AssertWritable()\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"writes are paused: migrating\", func() {\n\t\tState{Level: Paused, Reason: \"migrating\"}.AssertWritable()\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"paused: migrating\", func() {\n\t\tState{Level: Paused, Reason: \"migrating\"}.AssertReadable()\n\t})\n}\n\nfunc TestNotice(t *testing.T) {\n\tuassert.Equal(t, \"\", State{}.Notice(), \"a running realm shows no banner\")\n\n\tuassert.Equal(t,\n\t\t\"\u003e **Read-only.** This realm is still readable, but not accepting changes.\",\n\t\tState{Level: ReadOnly}.Notice())\n\n\tuassert.Equal(t,\n\t\t\"\u003e **Paused.** This realm is not accepting anything right now. back in an hour\",\n\t\tState{Level: Paused, Reason: \"back in an hour\"}.Notice())\n}\n\n// TestNoticeStaysOneBlock covers the reason a manager typed. It lands inside a\n// markdown blockquote, where a newline ends the quote and lets the rest render\n// as ordinary page content, so it is folded to one line.\nfunc TestNoticeStaysOneBlock(t *testing.T) {\n\ts := State{Level: Paused, Reason: \"line one\\n\\nline two\\n# not a heading\"}\n\tuassert.Equal(t,\n\t\t\"\u003e **Paused.** This realm is not accepting anything right now. line one line two # not a heading\",\n\t\ts.Notice())\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"2074623200","gas_fee":"6223869ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"Eqpzn9QzvVGoiRusnd2wf/+b/GYq9LYspDEWzVtxDzBLk1OVyjAfgkhPS53mI/sP5npyPCTk3MSba6VWVZea8Q=="}],"memo":""},"metadata":{"timestamp":"1790960203"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pilot","path":"gno.land/p/moul/pilot/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/pilot/v0`\n\nA realm-driven account: **one realm holds the funds and the identity, a key pilots it, and\nits powers arrive afterwards as separate realms it never imports.** The gno answer to a\nGnosis Safe with modules.\n\nLive instance: [`r/moul/pilot`](../../../r/moul/pilot). A power:\n[`r/moul/x/pilotdemo`](../../../r/moul/x/pilotdemo).\n\n## Why it is not just a multisig\n\ngno has **no dynamic call**: a realm cannot invoke an arbitrary package path with\nruntime-built arguments. So an account can never execute arbitrary calldata the way a Safe\ndoes. Every outbound action has to be Go code in some realm.\n\nThe inversion that makes it work: the account is deployed once and stores `Module` values\nhanded to it by realms that did not exist at the time. The power is the calldata, published\nas readable source, and installing one costs no redeploy of the account.\n\n## The two grants, and the only difference that matters\n\n| | `GrantPurse` | `GrantIdentity` |\n|---|---|---|\n| spends | the main treasury, metered | its own sub-treasury `account#subpath` |\n| can act as the account toward other realms | no | yes |\n| `Revoke` takes it back | **yes, immediately** | **no, never** |\n\nA `Purse` is a type this package declares, so every call on one re-enters this code and\nre-reads the live roster and budget. A module that stashed a purse and calls it a year later\nstill goes through the check.\n\nA sub-identity token is the opposite. The token itself cannot be persisted, but\n`banker.NewBanker` authorizes at construction and re-checks nothing ever again, so a module\ncan mint one from the lent token and keep it. `Revoke` shuts the account's door and does not\nreach that banker. The blast radius is exactly what the sub-address was funded with, and it\nis permanent. Grant an identity only to code you have read, and note that you can read it:\nmodule source is on chain before you approve it.\n\n## Shape\n\n```go\n// once, from the account realm\nacct := pilot.New(0, cur)\n\n// the owner, through the account realm's crossing functions\nacct.Approve(0, cur, \"gno.land/r/you/somepower/v0\", \"power\", pilot.GrantPurse, 1_000)\nacct.Fund(0, cur, path, 500)\nacct.SetBudget(0, cur, path, 2_000)\nacct.Revoke(0, cur, path)\nacct.Exec(0, cur, path, args)\n\n// the module realm, with its own cur: the account reads the path from the\n// runtime and never from an argument\nh := account.Handle()\nh.Register(0, cur, self)\npurse := h.PurseFor(0, cur)\n```\n\n## Both realms in the pair must be public\n\nA module's object is persisted in the account's roster, and a value of a type defined in a\nprivate realm cannot be persisted by anyone else. A private account realm cannot be imported\nat all, and a redeploy would wipe the owner, the roster and every budget while leaving the\ncoins at the address. `private = true` is wrong for both halves, and each `gnomod.toml` says\nso.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/pilot/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/pilot/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/pilot/v0\"\ngno = \"0.9\"\n"},{"name":"pilot.gno","body":"// Package pilot is a realm-driven account: one realm holds the funds and the\n// identity, a key pilots it, and its powers are separate realms installed\n// afterwards without ever redeploying it. The gno answer to a Gnosis Safe\n// with modules.\n//\n// An account realm keeps a *Pilot private and hands modules a narrow\n// [Account] handle. Everything privileged stays on *Pilot, which is never\n// returned, so a module can only reach the two methods it needs.\n//\n// Two ways to delegate, and they differ in exactly one property:\n//\n//   - A [Purse] is revocable. Every method on it re-enters the declaring\n//     package and re-checks the live roster and budget, so Revoke and\n//     SetBudget take effect immediately, even on a purse a module retained.\n//   - A sub-identity token (rlm.Sub) is permanent. It lets the module act as\n//     \"\u003caccount\u003e#\u003csubpath\u003e\" toward any other realm, which a purse cannot do,\n//     but the module can mint a banker from it and keep it forever. Removing\n//     the module does not take that back; only emptying the sub-address does.\n//     Grant one only to code you have read.\n//\n// Live instance: r/moul/pilot. Demo module: r/moul/x/pilotdemo.\npackage pilot\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Module is implemented by a module realm and installed into an account.\n// The account never imports it: it learns the module only as this interface.\n//\n// Run is threaded (the leading int keeps it out of crossing-function\n// territory, which a /p/ package may not declare). rlm is whatever the\n// account chose to delegate: its own sub-identity token for a trusted\n// module, or a zero value when the module was installed purse-only.\ntype Module interface {\n\tName() string\n\tRun(_ int, rlm realm, args string) string\n}\n\n// Grant says what a module was given.\ntype Grant uint8\n\nconst (\n\t// GrantPurse is funds only, revocable at any time.\n\tGrantPurse Grant = iota\n\t// GrantIdentity also lends the account's sub-identity. Permanent.\n\tGrantIdentity\n)\n\nfunc (g Grant) String() string {\n\tif g == GrantIdentity {\n\t\treturn \"identity\"\n\t}\n\treturn \"purse\"\n}\n\nvar (\n\tErrNotOwner     = errors.New(\"pilot: not the owner\")\n\tErrNotApproved  = errors.New(\"pilot: path not approved\")\n\tErrNotInstalled = errors.New(\"pilot: module not installed\")\n\tErrRevoked      = errors.New(\"pilot: module revoked\")\n\tErrOverBudget   = errors.New(\"pilot: over budget\")\n\tErrStaleRealm   = errors.New(\"pilot: stale realm value\")\n\tErrBadName      = errors.New(\"pilot: a path and a subpath are [a-zA-Z0-9._/-] and not empty\")\n)\n\ntype slot struct {\n\tmod     Module\n\tsubpath string\n\tgrant   Grant\n\tbudget  int64\n\tspent   int64\n\truns    int64\n\tlive    bool\n}\n\n// Pilot is the account. The realm that constructs it owns it and must not\n// hand it out; hand out [Pilot.Handle] instead.\ntype Pilot struct {\n\towner   address\n\thost    string        // the account realm's own pkgpath\n\tvault   banker.Banker // over host's address, minted once at New\n\tslots   *avl.Tree     // module pkgpath -\u003e *slot\n\thandle  *Account\n}\n\n// Account is the module-facing half: two methods, both keyed on the calling\n// realm's OWN pkgpath, which a realm cannot forge for another.\ntype Account struct {\n\tp *Pilot\n}\n\n// New builds an account owned by the caller of the crossing function that\n// reaches it. Call it once, from the account realm, passing that realm's cur.\nfunc New(_ int, rlm realm) *Pilot {\n\tassertCurrent(0, rlm)\n\tp := \u0026Pilot{\n\t\towner: rlm.Previous().Address(),\n\t\thost:  rlm.PkgPath(),\n\t\tvault: banker.NewBanker(banker.BankerTypeRealmSend, rlm),\n\t\tslots: avl.NewTree(),\n\t}\n\tp.handle = \u0026Account{p: p}\n\treturn p\n}\n\n// assertPlain is why Render can interpolate a path without escaping it: the\n// only two strings a caller ever puts in the roster are checked here, at write\n// time, against the charset a package path and a subpath are built from.\nfunc assertPlain(s string) {\n\tif s == \"\" {\n\t\tpanic(ErrBadName)\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= 'A' \u0026\u0026 c \u003c= 'Z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '.', c == '/', c == '-', c == '_':\n\t\tdefault:\n\t\t\tpanic(ErrBadName)\n\t\t}\n\t}\n}\n\nfunc assertCurrent(_ int, rlm realm) {\n\tif !rlm.IsCurrent() {\n\t\tpanic(ErrStaleRealm)\n\t}\n}\n\n// AssertOwner panics unless the user behind rlm owns the account. Only the\n// account realm may call this: rlm must be its own live cur, so that\n// rlm.Previous() is the signer and not some intermediary's caller.\nfunc (p *Pilot) AssertOwner(_ int, rlm realm) {\n\tassertCurrent(0, rlm)\n\tif rlm.PkgPath() != p.host {\n\t\tpanic(ErrNotOwner)\n\t}\n\tif rlm.Previous().Address() != p.owner {\n\t\tpanic(ErrNotOwner)\n\t}\n}\n\n// Handle is what an account realm exposes to modules.\nfunc (p *Pilot) Handle() *Account { return p.handle }\n\nfunc (p *Pilot) Owner() address { return p.owner }\nfunc (p *Pilot) Host() string   { return p.host }\n\n// Address is the account's main treasury.\nfunc (p *Pilot) Address() address { return chain.PackageAddress(p.host) }\n\n// SubAddress is one module's own treasury, derivable off-chain by anyone.\nfunc (p *Pilot) SubAddress(path string) address {\n\ts := p.mustSlot(path)\n\treturn chain.DerivePkgSubAddr(p.host, s.subpath)\n}\n\nfunc (p *Pilot) mustSlot(path string) *slot {\n\ts, ok := p.slots.Get(path).(*slot)\n\tif !ok {\n\t\tpanic(ErrNotInstalled)\n\t}\n\treturn s\n}\n\n// Approve authorises a package path to install itself later. The code does\n// not have to exist yet, which is the whole point: the account is deployed\n// once and learns new powers afterwards.\nfunc (p *Pilot) Approve(_ int, rlm realm, path, subpath string, grant Grant, budget int64) {\n\tp.AssertOwner(0, rlm)\n\tassertPlain(path)\n\tassertPlain(subpath)\n\tif old, ok := p.slots.Get(path).(*slot); ok {\n\t\told.subpath = subpath\n\t\told.grant = grant\n\t\told.budget = budget\n\t\told.spent = 0 // a new approval is a new allowance\n\t\treturn\n\t}\n\tp.slots.Set(path, \u0026slot{subpath: subpath, grant: grant, budget: budget})\n}\n\n// SetBudget is the live knob. It applies to a purse a module already holds.\nfunc (p *Pilot) SetBudget(_ int, rlm realm, path string, budget int64) {\n\tp.AssertOwner(0, rlm)\n\tp.mustSlot(path).budget = budget\n}\n\n// Revoke stops a module. It takes back its purse immediately; it does NOT\n// take back a sub-identity that was granted, nor any banker minted from one.\nfunc (p *Pilot) Revoke(_ int, rlm realm, path string) {\n\tp.AssertOwner(0, rlm)\n\tp.mustSlot(path).live = false\n}\n\n// Fund moves coins from the account's main treasury into a module's\n// sub-treasury. For an identity grant this is the permanent blast radius.\nfunc (p *Pilot) Fund(_ int, rlm realm, path string, amount int64) {\n\tp.AssertOwner(0, rlm)\n\ts := p.mustSlot(path)\n\tp.vault.SendCoins(p.Address(), chain.DerivePkgSubAddr(p.host, s.subpath),\n\t\tchain.NewCoins(chain.NewCoin(\"ugnot\", amount)))\n}\n\n// Exec drives an installed module. rlm must be the account realm's own live\n// cur: an identity grant mints its sub-token from it, which only the account\n// realm's namespace can do.\nfunc (p *Pilot) Exec(_ int, rlm realm, path, args string) string {\n\tp.AssertOwner(0, rlm)\n\ts := p.mustSlot(path)\n\tif !s.live {\n\t\tpanic(ErrRevoked)\n\t}\n\ts.runs++\n\tif s.grant == GrantIdentity {\n\t\treturn s.mod.Run(0, rlm.Sub(s.subpath), args)\n\t}\n\treturn s.mod.Run(0, rlm, args)\n}\n\n// Register is called BY the module realm, with its own live cur. The account\n// reads the path from the runtime and never from an argument.\nfunc (a *Account) Register(_ int, rlm realm, m Module) {\n\tassertCurrent(0, rlm)\n\tpath := rlm.PkgPath()\n\ts, ok := a.p.slots.Get(path).(*slot)\n\tif !ok {\n\t\tpanic(ErrNotApproved)\n\t}\n\ts.mod = m\n\ts.live = true\n}\n\n// PurseFor hands the calling module its revocable purse.\nfunc (a *Account) PurseFor(_ int, rlm realm) *Purse {\n\tassertCurrent(0, rlm)\n\tpath := rlm.PkgPath()\n\tif _, ok := a.p.slots.Get(path).(*slot); !ok {\n\t\tpanic(ErrNotApproved)\n\t}\n\treturn \u0026Purse{p: a.p, path: path}\n}\n\n// Purse is a capability this package declares, so every use of it runs here\n// and is re-checked against live state. That is what makes it revocable,\n// where a banker minted from a lent realm token is not.\ntype Purse struct {\n\tp    *Pilot\n\tpath string\n}\n\n// Pay spends from the account's main treasury, against the module's budget.\nfunc (u *Purse) Pay(to address, amount int64) {\n\ts, ok := u.p.slots.Get(u.path).(*slot)\n\tif !ok {\n\t\tpanic(ErrNotInstalled)\n\t}\n\tif !s.live {\n\t\tpanic(ErrRevoked)\n\t}\n\tif amount \u003c= 0 || amount \u003e s.budget-s.spent {\n\t\tpanic(ErrOverBudget)\n\t}\n\ts.spent += amount\n\tu.p.vault.SendCoins(u.p.Address(), to, chain.NewCoins(chain.NewCoin(\"ugnot\", amount)))\n}\n\n// Left is what this module may still spend.\nfunc (u *Purse) Left() int64 {\n\ts, ok := u.p.slots.Get(u.path).(*slot)\n\tif !ok || !s.live {\n\t\treturn 0\n\t}\n\treturn s.budget - s.spent\n}\n\n// Render is the account page. The account realm forwards its Render here.\nfunc (p *Pilot) Render(path string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# \" + p.host + \"\\n\\n\")\n\tsb.WriteString(\"| | |\\n|---|---|\\n\")\n\tsb.WriteString(\"| owner | \" + p.owner.String() + \" |\\n\")\n\tsb.WriteString(\"| treasury | \" + p.Address().String() + \" |\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"| balance | %d ugnot |\\n\\n\", p.balance(p.Address())))\n\n\tif p.slots.Size() == 0 {\n\t\tsb.WriteString(\"No power installed yet.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tsb.WriteString(\"## powers\\n\\n\")\n\tsb.WriteString(\"| path | grant | identity | state | left | runs | sub-treasury |\\n\")\n\tsb.WriteString(\"|---|---|---|---|---|---|---|\\n\")\n\tp.slots.Iterate(\"\", \"\", func(key string, v any) bool {\n\t\ts := v.(*slot)\n\t\tstate := \"approved\"\n\t\tif s.live {\n\t\t\tstate = \"installed\"\n\t\t} else if s.mod != nil {\n\t\t\tstate = \"revoked\"\n\t\t}\n\t\tsub := chain.DerivePkgSubAddr(p.host, s.subpath)\n\t\tsb.WriteString(ufmt.Sprintf(\"| `%s` | %s | `%s#%s` | %s | %d | %d | %d ugnot |\\n\",\n\t\t\tkey, s.grant.String(), p.host, s.subpath, state,\n\t\t\ts.budget-s.spent, s.runs, p.balance(sub)))\n\t\treturn false\n\t})\n\treturn sb.String()\n}\n\nfunc (p *Pilot) balance(addr address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoin(addr, \"ugnot\")\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"printfdebugging","path":"gno.land/p/moul/printfdebugging/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/printfdebugging`\n\n\u003e \"this package is a joke... or not.\" (`printfdebugging.gno`, line 1)\n\nTwo functions for finding out whether your code reached a line, printed in a\ncolor you cannot miss in a wall of test output.\n\n```go\nprintfdebugging.BigRedLine(\"got here\", \"n =\", \"42\")\nprintfdebugging.Success()\n```\n\n`BigRedLine` prints a full-width red bar with your arguments on it.\n`Success()` prints a green one. That is the whole package.\n\nIt exists because `println` in the middle of a long `gno test -v` run is\ninvisible, and the fastest debugging tool is still the one that takes zero\nsetup.\n\n## ANSI attributes\n\n`color.gno` ships the SGR attribute set as typed constants, usable on their own:\n`Reset`, `Bold`, `Faint`, `Italic`, `Underline`, `BlinkSlow`, `BlinkRapid`,\n`ReverseVideo`, `Concealed`, `CrossedOut`, their `Reset*` counterparts, and the\nforeground / background colors in both normal (`FgRed`, `BgBlue`) and\nhigh-intensity (`FgHiRed`, `BgHiBlue`) variants.\n\nEscape sequences are meaningless anywhere that is not a terminal. This is for\n`gno test` output, never for a `Render` string.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/printfdebugging/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/printfdebugging/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"color.gno","body":"package printfdebugging\n\n// consts copied from https://github.com/fatih/color/blob/main/color.go\n\n// Attribute defines a single SGR Code\ntype Attribute int\n\nconst Escape = \"\\x1b\"\n\n// Base attributes\nconst (\n\tReset Attribute = iota\n\tBold\n\tFaint\n\tItalic\n\tUnderline\n\tBlinkSlow\n\tBlinkRapid\n\tReverseVideo\n\tConcealed\n\tCrossedOut\n)\n\nconst (\n\tResetBold Attribute = iota + 22\n\tResetItalic\n\tResetUnderline\n\tResetBlinking\n\t_\n\tResetReversed\n\tResetConcealed\n\tResetCrossedOut\n)\n\n// Foreground text colors\nconst (\n\tFgBlack Attribute = iota + 30\n\tFgRed\n\tFgGreen\n\tFgYellow\n\tFgBlue\n\tFgMagenta\n\tFgCyan\n\tFgWhite\n)\n\n// Foreground Hi-Intensity text colors\nconst (\n\tFgHiBlack Attribute = iota + 90\n\tFgHiRed\n\tFgHiGreen\n\tFgHiYellow\n\tFgHiBlue\n\tFgHiMagenta\n\tFgHiCyan\n\tFgHiWhite\n)\n\n// Background text colors\nconst (\n\tBgBlack Attribute = iota + 40\n\tBgRed\n\tBgGreen\n\tBgYellow\n\tBgBlue\n\tBgMagenta\n\tBgCyan\n\tBgWhite\n)\n\n// Background Hi-Intensity text colors\nconst (\n\tBgHiBlack Attribute = iota + 100\n\tBgHiRed\n\tBgHiGreen\n\tBgHiYellow\n\tBgHiBlue\n\tBgHiMagenta\n\tBgHiCyan\n\tBgHiWhite\n)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/printfdebugging/v0\"\ngno = \"0.9\"\n"},{"name":"printfdebugging.gno","body":"// this package is a joke... or not.\npackage printfdebugging\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc BigRedLine(args ...string) {\n\tprintln(ufmt.Sprintf(\"%s[%dm####################################%s[%dm %s\",\n\t\tEscape, int(BgRed), Escape, int(Reset),\n\t\tstrings.Join(args, \" \"),\n\t))\n}\n\nfunc Success() {\n\tprintln(\"   \\033[31mS\\033[33mU\\033[32mC\\033[36mC\\033[34mE\\033[35mS\\033[31mS\\033[0m   \")\n}\n"},{"name":"printfdebugging_test.gno","body":"package printfdebugging\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The SGR codes are transcribed from fatih/color. They are plain `iota` blocks,\n// so a single inserted or removed line silently shifts every constant below it\n// and the terminal renders the wrong colour. Pin the boundaries and the offsets.\n\nfunc TestBaseAttributes(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tgot  Attribute\n\t\twant int\n\t}{\n\t\t{\"Reset\", Reset, 0},\n\t\t{\"Bold\", Bold, 1},\n\t\t{\"Faint\", Faint, 2},\n\t\t{\"Italic\", Italic, 3},\n\t\t{\"Underline\", Underline, 4},\n\t\t{\"BlinkSlow\", BlinkSlow, 5},\n\t\t{\"BlinkRapid\", BlinkRapid, 6},\n\t\t{\"ReverseVideo\", ReverseVideo, 7},\n\t\t{\"Concealed\", Concealed, 8},\n\t\t{\"CrossedOut\", CrossedOut, 9},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, int(c.got), c.name)\n\t}\n}\n\n// TestResetAttributes covers the block with a deliberate `_` gap at 26.\nfunc TestResetAttributes(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tgot  Attribute\n\t\twant int\n\t}{\n\t\t{\"ResetBold\", ResetBold, 22},\n\t\t{\"ResetItalic\", ResetItalic, 23},\n\t\t{\"ResetUnderline\", ResetUnderline, 24},\n\t\t{\"ResetBlinking\", ResetBlinking, 25},\n\t\t// 26 is skipped with `_`\n\t\t{\"ResetReversed\", ResetReversed, 27},\n\t\t{\"ResetConcealed\", ResetConcealed, 28},\n\t\t{\"ResetCrossedOut\", ResetCrossedOut, 29},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, int(c.got), c.name)\n\t}\n}\n\nfunc TestForegroundColors(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tgot  Attribute\n\t\twant int\n\t}{\n\t\t{\"FgBlack\", FgBlack, 30},\n\t\t{\"FgRed\", FgRed, 31},\n\t\t{\"FgGreen\", FgGreen, 32},\n\t\t{\"FgYellow\", FgYellow, 33},\n\t\t{\"FgBlue\", FgBlue, 34},\n\t\t{\"FgMagenta\", FgMagenta, 35},\n\t\t{\"FgCyan\", FgCyan, 36},\n\t\t{\"FgWhite\", FgWhite, 37},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, int(c.got), c.name)\n\t}\n}\n\nfunc TestBackgroundColors(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tgot  Attribute\n\t\twant int\n\t}{\n\t\t{\"BgBlack\", BgBlack, 40},\n\t\t{\"BgRed\", BgRed, 41},\n\t\t{\"BgWhite\", BgWhite, 47},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, int(c.got), c.name)\n\t}\n}\n\nfunc TestHiIntensityColors(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tgot  Attribute\n\t\twant int\n\t}{\n\t\t{\"FgHiBlack\", FgHiBlack, 90},\n\t\t{\"FgHiWhite\", FgHiWhite, 97},\n\t\t{\"BgHiBlack\", BgHiBlack, 100},\n\t\t{\"BgHiWhite\", BgHiWhite, 107},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, int(c.got), c.name)\n\t}\n}\n\nfunc TestEscape(t *testing.T) {\n\tuassert.Equal(t, \"\\x1b\", Escape)\n\tuassert.Equal(t, 1, len(Escape))\n}\n\n// TestOutputHelpersDoNotPanic exercises the two exported helpers. They only\n// println, so there is no return value to assert — this pins that they build\n// and run (BigRedLine formats Escape/Attribute through ufmt).\nfunc TestOutputHelpersDoNotPanic(t *testing.T) {\n\tBigRedLine()\n\tBigRedLine(\"one\")\n\tBigRedLine(\"several\", \"args\", \"joined\")\n\tSuccess()\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"reactions","path":"gno.land/p/moul/reactions/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/reactions/v0`\n\nThe engine behind an embeddable reaction block: pages, tallies, a closed emoji\npalette, and the markdown that shows them. No realm state, no chain reads, no\nauthority decisions. The realm on top owns all three.\n\nLive realm: [`gno.land/r/moul/reactions/v0`](https://github.com/moul/gno-contracts/tree/main/r/moul/reactions).\n\n## The model\n\nA `Board` maps a **page key** to a `Page`. A page holds exactly three things:\n\n| | |\n|---|---|\n| a count per palette key | what the strip shows |\n| the **current** reaction of each address | so a tally counts addresses and not clicks, and a reader can change their mind or take it back |\n| the last reaction | which key, from whom, at what height |\n\nThere is no text field anywhere. That is what makes the whole thing runnable\nwith no moderation: reactions come from a closed set of six, so there is nothing\nto take down.\n\n```go\nb := reactions.NewBoard()\nb.React(\"gno.land/r/moul/home\", caller, reactions.KeyFire, height) // false if rejected\nb.Unreact(\"gno.land/r/moul/home\", caller)                          // false if there was none\n\np := b.Page(\"gno.land/r/moul/home\") // nil when untouched, and nil is safe to use\np.Count(reactions.KeyFire)          // 1\np.Total()                           // addresses reacting, not clicks\np.Of(caller)                        // \"fire\", or \"\" for none\nkey, who, height := p.Last()\n\nmd := reactions.Block(realmPath, page, p) // the whole widget\n```\n\nEvery `Page` read is nil-safe and answers as if the page were empty, so a host\nrealm renders the block without ever checking whether the page exists.\n\n## Three decisions worth knowing before you use it\n\n**A reaction key is an ASCII name, not a glyph.** `\"up\"`, not `👍`. A name\nsurvives a URL query parameter, an avl key and a markdown escaper with no\nencoding question anywhere, and the palette can change a glyph without\nrewriting stored state. `Emoji(key)` is the presentation half.\n\n**No glyph in the palette uses U+FE0F or a zero-width joiner.** The link title\ngoes through `ui.Inline`, which strips exactly those, so a glyph needing a\nvariation selector would come out the other side as its monochrome form. ❤️ is\nthe casualty; `heart` is 💜, a codepoint that is colour on its own. Pinned by\n`TestEmojiSurviveTheEscaper`.\n\n**`Unreact` does not rewind the last-reaction line.** It records an event that\nhappened, and recomputing it would mean walking every address on the page, so\n`Page.Last` keeps naming a reaction nobody holds any more.\n\nWhat is *shown* is a separate decision, and `Summary` makes it: a page whose\nreactors have all left renders as empty, not as a withdrawn reaction. Gating on\nthe last key alone would print \"last 👍 by `g1…` · 0 reactions\" above an empty\nstrip, which contradicts itself. `TestSummaryGoesEmptyWhenEveryoneLeaves` pins\nthe pair.\n\n## Page keys\n\nA page key is a package path, and `ValidPage` is what bounds this package's\nexposure: at least one `/`, no empty element, and only lowercase ASCII letters,\ndigits, `.`, `-`, `_`, `:` and `/`, up to `MaxPageLen` bytes. That excludes every\ncharacter a markdown escaper exists for, plus every byte above ASCII, so a\nstored key can never be a bidi run, a zero-width joiner or an image.\n\n`:` is in the set so a host realm can key one block per article on the path it\nalready serves: `gno.land/r/you/blog:hello-world`.\n\nThis package only ever puts a key in a URL. A realm that shows the key **as\ntext** escapes it there; `ValidPage` and `ui.Inline` protect against different\nmistakes.\n\n## Not to be confused with\n\n[`r/moul/x/daily/reactions`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/reactions)\nis an older, unrelated experiment: a single self-contained board with its own\n\"topics\", no embedding, and no way for a reader to change or remove a reaction.\nNothing is shared between the two.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/reactions/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/reactions/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/reactions/v0\"\ngno = \"0.9\"\n"},{"name":"palette.gno","body":"package reactions\n\n// The palette: the closed set of reactions, and the only moderation policy\n// this package has.\n//\n// It is closed on purpose. A free-text reaction is a comment, a comment needs\n// moderation, and moderation is the thing worth not building. Six is enough to\n// say something and few enough to fit on one line on a phone.\n//\n// Every glyph here is a SINGLE codepoint with no variation selector (no\n// U+FE0F) and no zero-width joiner. That is a constraint, not a coincidence:\n// these strings pass through a markdown escaper that strips zero-width and\n// bidi characters, and a glyph that needs U+FE0F to render would come out the\n// other side as its bare monochrome form. ❤️ is the obvious casualty, which is\n// why \"heart\" is 💜 (U+1F49C), a codepoint that is a colour emoji on its own.\nconst (\n\t// KeyUp is the default, first in the strip.\n\tKeyUp = \"up\"\n\t// KeyHeart is affection rather than agreement.\n\tKeyHeart = \"heart\"\n\t// KeyFire is \"this is good\".\n\tKeyFire = \"fire\"\n\t// KeyParty is a congratulation.\n\tKeyParty = \"party\"\n\t// KeyRocket is \"ship it\".\n\tKeyRocket = \"rocket\"\n\t// KeyEyes is \"I am watching this\", the only one that is not praise.\n\tKeyEyes = \"eyes\"\n)\n\n// order is the display order of the palette, which is also the order the\n// strip renders in. A slice and not a map range: gno map iteration order is\n// unspecified, and a Render that reshuffles between identical calls is a\n// consensus bug.\nvar order = []string{KeyUp, KeyHeart, KeyFire, KeyParty, KeyRocket, KeyEyes}\n\n// palette maps a key to its glyph. Written as \\U escapes rather than literal\n// emoji so that the source says exactly which codepoint it means and a review\n// diff cannot hide a lookalike.\nvar palette = map[string]string{\n\tKeyUp:     \"\\U0001F44D\", // 👍\n\tKeyHeart:  \"\\U0001F49C\", // 💜\n\tKeyFire:   \"\\U0001F525\", // 🔥\n\tKeyParty:  \"\\U0001F389\", // 🎉\n\tKeyRocket: \"\\U0001F680\", // 🚀\n\tKeyEyes:   \"\\U0001F440\", // 👀\n}\n\n// Keys returns the palette keys in display order. The returned slice is a copy,\n// so a caller cannot reorder the palette for everyone else.\nfunc Keys() []string {\n\tout := make([]string, len(order))\n\tcopy(out, order)\n\treturn out\n}\n\n// Valid reports whether key names a reaction in the palette.\nfunc Valid(key string) bool {\n\t_, ok := palette[key]\n\treturn ok\n}\n\n// Emoji returns the glyph for a palette key, or \"\" when the key is not one.\nfunc Emoji(key string) string { return palette[key] }\n"},{"name":"reactions.gno","body":"// Package reactions is the engine behind an embeddable reaction block: the\n// one-click \"👍 3 · 🔥 1\" strip a realm drops into its own Render, keyed on\n// the PAGE it is showing rather than on the realm that stores it.\n//\n// That indirection is the whole idea, and it is the one the web already\n// settled on: a single hosted widget, embedded verbatim everywhere, deciding\n// what to show from the page identifier it is handed. One realm holds every\n// tally, every host realm ships the same two lines, and no host realm stores\n// anything.\n//\n// # The model\n//\n// A [Board] maps a page key to a [Page]. A page holds three things and\n// deliberately nothing else:\n//\n//   - a count per palette key,\n//   - the CURRENT reaction of each address, so a tally counts addresses and\n//     not clicks, and so a reader can change their mind,\n//   - the last reaction: which key, from whom, at what height.\n//\n// There is no text anywhere, which is the point. Text needs moderation;\n// a closed palette of six emoji does not.\n//\n// # Keys are names, not glyphs\n//\n// A reaction is stored and addressed as an ASCII name (\"up\", \"fire\"), and the\n// glyph is presentation. A name survives a URL query parameter, an avl key and\n// a markdown escaper without a single encoding question, and the palette can\n// gain a glyph without rewriting stored state.\n//\n// # Page keys\n//\n// A page key is a package path (the full one, chain domain included, as\n// unsafe.CurrentRealm().PkgPath() reports it). [ValidPage] is what bounds this\n// package's exposure: a key is path-shaped, ASCII, and at most [MaxPageLen]\n// bytes, so a stored key can never be a markdown payload, a bidi run or an\n// unbounded blob. This package only ever puts it in a URL; a realm that shows\n// the key as text escapes it there, because a validator and an escaper protect\n// against different mistakes.\npackage reactions\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// MaxPageLen is the longest page key accepted. Comfortably past the longest\n// real package path (the deepest in moul/gno-contracts is 34 bytes) and short\n// enough that a key can never be a payload.\nconst MaxPageLen = 120\n\n// Board is a set of pages, each with its own tally. The zero value is not\n// usable; call [NewBoard].\ntype Board struct {\n\tpages *avl.Tree // page key -\u003e *Page\n}\n\n// NewBoard returns an empty board.\nfunc NewBoard() *Board { return \u0026Board{pages: avl.NewTree()} }\n\n// Page is one page's tally.\n//\n// Every read method is nil-safe and answers as if the page were empty, so a\n// caller can hand [Board.Page]'s result straight to [Block] without checking.\ntype Page struct {\n\tcounts  *avl.Tree // palette key -\u003e int\n\tby      *avl.Tree // address string -\u003e palette key\n\tlastKey string\n\tlastWho address\n\tlastAt  int64\n}\n\n// React records who's reaction on page, replacing whatever they had there\n// before. It reports whether anything was stored: false means the page key or\n// the palette key was rejected, and nothing changed.\n//\n// height is passed in rather than read from the chain, so this package stays\n// testable without a realm and so the caller decides what \"when\" means.\nfunc (b *Board) React(page string, who address, key string, height int64) bool {\n\tif !ValidPage(page) || !Valid(key) {\n\t\treturn false\n\t}\n\tp := b.page(page)\n\n\t// Replacing a reaction decrements the old bucket first. Without this a\n\t// reader who clicks twice counts twice, and the tally stops meaning\n\t// \"how many addresses\", which is the only thing it is allowed to mean.\n\tif prev := p.Of(who); prev != \"\" {\n\t\tif prev == key {\n\t\t\t// Same key again: still record it as the last reaction, since the\n\t\t\t// click happened, but leave the counts alone.\n\t\t\tp.lastKey, p.lastWho, p.lastAt = key, who, height\n\t\t\treturn true\n\t\t}\n\t\tp.add(prev, -1)\n\t}\n\tp.by.Set(who.String(), key)\n\tp.add(key, 1)\n\tp.lastKey, p.lastWho, p.lastAt = key, who, height\n\treturn true\n}\n\n// Unreact removes who's reaction from page. It reports whether there was one.\n//\n// The last-reaction line is deliberately NOT rewound: it records an event that\n// happened, and recomputing it would mean walking every address on the page.\n// [Page.Last] therefore keeps naming a reaction nobody holds any more, which is\n// the honest answer to \"what happened here last\". What is shown is a separate\n// decision, and [Summary] makes it: a page with no reactors left renders as\n// empty, not as a withdrawn reaction.\nfunc (b *Board) Unreact(page string, who address) bool {\n\tp := b.Page(page)\n\tif p == nil {\n\t\treturn false\n\t}\n\tprev := p.Of(who)\n\tif prev == \"\" {\n\t\treturn false\n\t}\n\tp.by.Remove(who.String())\n\tp.add(prev, -1)\n\treturn true\n}\n\n// Page returns the tally for a page, or nil when nothing was ever recorded\n// there. The nil is safe to use: every [Page] read method handles it.\nfunc (b *Board) Page(page string) *Page {\n\tv := b.pages.Get(page)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Page)\n}\n\n// page returns the tally for a page, creating it if needed.\nfunc (b *Board) page(key string) *Page {\n\tif p := b.Page(key); p != nil {\n\t\treturn p\n\t}\n\tp := \u0026Page{counts: avl.NewTree(), by: avl.NewTree()}\n\tb.pages.Set(key, p)\n\treturn p\n}\n\n// Pages reports how many pages have ever been reacted to.\nfunc (b *Board) Pages() int { return b.pages.Size() }\n\n// Each visits every page in key order until fn returns true.\nfunc (b *Board) Each(fn func(page string, p *Page) bool) {\n\tb.pages.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\treturn fn(key, value.(*Page))\n\t})\n}\n\n// add changes a bucket by delta, dropping it when it reaches zero so an\n// emptied page leaves no residue behind.\nfunc (p *Page) add(key string, delta int) {\n\tn := p.Count(key) + delta\n\tif n \u003c= 0 {\n\t\tp.counts.Remove(key)\n\t\treturn\n\t}\n\tp.counts.Set(key, n)\n}\n\n// Count reports how many addresses currently hold this reaction.\nfunc (p *Page) Count(key string) int {\n\tif p == nil {\n\t\treturn 0\n\t}\n\tv := p.counts.Get(key)\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(int)\n}\n\n// Total is the number of addresses reacting to this page. It equals the sum of\n// every bucket, because an address holds at most one reaction.\nfunc (p *Page) Total() int {\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.by.Size()\n}\n\n// Of returns who's current reaction key, or \"\" when they have none.\nfunc (p *Page) Of(who address) string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\tv := p.by.Get(who.String())\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n\n// Last returns the most recent reaction: its palette key, who made it, and the\n// height it was made at. The key is \"\" when the page has never been reacted to.\n//\n// It can name a reaction that is no longer counted, because [Board.Unreact]\n// does not rewind it. That is the honest answer to \"what happened here last\",\n// which is the question the line under the block asks.\nfunc (p *Page) Last() (key string, who address, height int64) {\n\tif p == nil {\n\t\treturn \"\", \"\", 0\n\t}\n\treturn p.lastKey, p.lastWho, p.lastAt\n}\n\n// ValidPage reports whether page is an acceptable key.\n//\n// The rule is \"a gnoweb render path, and nothing that is not one\": at least one\n// \"/\", no empty element, no leading or trailing \"/\", and only lowercase ASCII\n// letters, digits, \".\", \"-\", \"_\", \":\" and \"/\". That excludes every character a\n// markdown escaper exists for, plus every byte above ASCII, so a stored key\n// cannot carry a bidi run, a zero-width joiner or an image.\n//\n// Two of the exclusions are STRUCTURAL and not about markdown, so widening this\n// set is not free. gnoweb parses a render path as `\u003cpath\u003e[:\u003cargs\u003e][$\u003cwebargs\u003e]`\n// and cuts on \"$\" BEFORE it cuts on \":\" (gno.land/pkg/gnoweb/weburl/url.go,\n// ParseFromURL, read 2026-09-28), so a \"$\" in a key would truncate it on the\n// way back in, and a \"%\" would be eaten by the unescape that follows. \":\" is\n// safe only because that second cut takes the FIRST colon, which leaves the\n// rest of the key intact however many it carries.\n//\n// \":\" is in the set because a host realm keying the block per article wants the\n// path it already serves: \"gno.land/r/you/blog:hello-world\".\nfunc ValidPage(page string) bool {\n\tif page == \"\" || len(page) \u003e MaxPageLen {\n\t\treturn false\n\t}\n\tif strings.HasPrefix(page, \"/\") || strings.HasSuffix(page, \"/\") ||\n\t\tstrings.Contains(page, \"//\") || !strings.Contains(page, \"/\") {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(page); i++ {\n\t\tc := page[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '/' || c == '.' || c == '-' || c == '_' || c == ':':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Block renders the embeddable widget: the clickable palette with its counts,\n// then one line saying what happened here last.\n//\n// realmPath is the realm that owns React, given as the full package path from\n// its gnomod.toml module line. It is a parameter and not a constant because\n// this package is the engine and not the deployment: a second reactions realm,\n// on another chain or in a test, renders through the same code.\n//\n// page appears only in URL positions here: as a txlink query argument, which\n// txlink percent-encodes, and inside [PageURL]. Nothing renders it as text, and\n// [ValidPage]'s charset is what keeps the [PageURL] form safe. A realm showing\n// the key itself must still run it through ui.Inline.\n//\n// The result ends with a single newline and contains exactly one blank line,\n// so it drops into a host realm's Render between two sections without a\n// separator of its own.\nfunc Block(realmPath, page string, p *Page) string {\n\tvar b strings.Builder\n\tfor i, key := range order {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\" \")\n\t\t}\n\t\ttitle := palette[key]\n\t\tif n := p.Count(key); n \u003e 0 {\n\t\t\ttitle += \" \" + strconv.Itoa(n)\n\t\t}\n\t\tb.WriteString(ui.ActionIn(realmPath, title, \"React\", \"page\", page, \"key\", key))\n\t}\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(md.Italic(Summary(realmPath, page, p)))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\n// Summary is the one line under the block: the last reaction, and a link to\n// the page's own view on the reactions realm. Plain markdown, no wrapper, so a\n// caller can put it somewhere else.\nfunc Summary(realmPath, page string, p *Page) string {\n\tkey, who, _ := p.Last()\n\tn := p.Total()\n\n\t// Two different ways to have nothing to say, and both have to be checked.\n\t// key == \"\" is a page nobody ever touched. n == 0 is a page whose reactors\n\t// have all left: [Board.Unreact] deliberately does not rewind the last\n\t// reaction, so key still names one. Gating on key alone would print\n\t// \"last \u003cemoji\u003e by \u003caddr\u003e - 0 reactions\" above an empty strip, which\n\t// contradicts itself and keeps attributing a reaction its author took back.\n\tif key == \"\" || n == 0 {\n\t\treturn \"no reactions yet\"\n\t}\n\tlabel := strconv.Itoa(n) + \" reaction\"\n\tif n != 1 {\n\t\tlabel += \"s\"\n\t}\n\treturn \"last \" + palette[key] + \" by \" + ui.Addr(who) + \" · \" +\n\t\tmd.Link(label, PageURL(realmPath, page))\n}\n\n// RealmURL is the gnoweb path of a realm given as a package path.\n//\n// The chain domain is the first element of a package path and a gnoweb path is\n// the rest of it. Derived here rather than read from chain/runtime so this\n// package keeps no chain import of its own and the rule stays in one place.\n// Returns \"\" for something that is not a package path.\nfunc RealmURL(realmPath string) string {\n\ti := strings.Index(realmPath, \"/\")\n\tif i \u003c 0 {\n\t\treturn \"\"\n\t}\n\treturn realmPath[i:]\n}\n\n// PageURL is the link to one page's view on the reactions realm: [RealmURL]\n// with the page as the gnoweb render argument after a colon.\nfunc PageURL(realmPath, page string) string {\n\tbase := RealmURL(realmPath)\n\tif base == \"\" {\n\t\treturn \"\"\n\t}\n\treturn base + \":\" + page\n}\n"},{"name":"reactions_test.gno","body":"package reactions\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst (\n\trealmPath = \"gno.land/r/test/reactions/v0\"\n\thomePage  = \"gno.land/r/moul/home\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\nfunc TestValidPage(t *testing.T) {\n\tcases := []struct {\n\t\tpage string\n\t\twant bool\n\t}{\n\t\t{\"gno.land/r/moul/home\", true},\n\t\t{\"gno.land/p/moul/kit/ui/v0\", true},\n\t\t{\"gno.land/r/moul/x/daily/b58demo\", true},\n\t\t{\"a/b\", true},\n\t\t{\"gno.land/r/you/blog:hello-world\", true}, // one page per article\n\t\t{\"\", false},\n\t\t{\"nolslash\", false},\n\t\t{\"/leading\", false},\n\t\t{\"trailing/\", false},\n\t\t{\"double//slash\", false},\n\t\t{\"gno.land/r/MOUL/home\", false},                   // uppercase is not a path here\n\t\t{\"gno.land/r/moul/home \", false},                  // a space is not path-shaped\n\t\t{\"gno.land/r/[x](http://e.vil)\", false},           // a markdown link cannot be a key\n\t\t{\"gno.land/r/‮moul/home\", false},             // bidi override\n\t\t{strings.Repeat(\"a/\", MaxPageLen) + \"b\", false},   // over the cap\n\t\t{strings.Repeat(\"a\", MaxPageLen-2) + \"/b\", true},  // exactly at the cap\n\t\t{strings.Repeat(\"a\", MaxPageLen-1) + \"/b\", false}, // one byte over\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, ValidPage(tc.page), tc.page)\n\t}\n}\n\nfunc TestPaletteIsClosed(t *testing.T) {\n\tuassert.Equal(t, 6, len(Keys()))\n\tfor _, k := range Keys() {\n\t\tuassert.True(t, Valid(k), k)\n\t\tuassert.NotEqual(t, \"\", Emoji(k), k)\n\t}\n\tuassert.False(t, Valid(\"poop\"))\n\tuassert.Equal(t, \"\", Emoji(\"poop\"))\n\n\t// Keys returns a copy: reordering it must not reorder the palette.\n\tks := Keys()\n\tks[0] = \"clobbered\"\n\tuassert.Equal(t, KeyUp, Keys()[0])\n}\n\n// TestNilPageReadsAsEmpty is what lets a host realm render the block without\n// ever checking whether the page exists.\nfunc TestNilPageReadsAsEmpty(t *testing.T) {\n\tvar p *Page\n\tuassert.Equal(t, 0, p.Count(KeyUp))\n\tuassert.Equal(t, 0, p.Total())\n\tuassert.Equal(t, \"\", p.Of(alice))\n\tkey, who, at := p.Last()\n\tuassert.Equal(t, \"\", key)\n\tuassert.Equal(t, address(\"\"), who)\n\tuassert.Equal(t, int64(0), at)\n}\n\nfunc TestReactCountsAddressesNotClicks(t *testing.T) {\n\tb := NewBoard()\n\n\tuassert.True(t, b.React(homePage, alice, KeyUp, 100))\n\tuassert.True(t, b.React(homePage, alice, KeyUp, 101))\n\tuassert.True(t, b.React(homePage, alice, KeyUp, 102))\n\n\tp := b.Page(homePage)\n\tuassert.Equal(t, 1, p.Count(KeyUp), \"three clicks from one address is one reaction\")\n\tuassert.Equal(t, 1, p.Total())\n\n\t// The repeat still counts as the last event, because it happened.\n\t_, _, at := p.Last()\n\tuassert.Equal(t, int64(102), at)\n}\n\nfunc TestChangingReactionMovesTheCount(t *testing.T) {\n\tb := NewBoard()\n\tb.React(homePage, alice, KeyUp, 100)\n\tb.React(homePage, bob, KeyUp, 101)\n\tb.React(homePage, alice, KeyFire, 102)\n\n\tp := b.Page(homePage)\n\tuassert.Equal(t, 1, p.Count(KeyUp))\n\tuassert.Equal(t, 1, p.Count(KeyFire))\n\tuassert.Equal(t, 2, p.Total(), \"changing a reaction never changes the head count\")\n\tuassert.Equal(t, KeyFire, p.Of(alice))\n\tuassert.Equal(t, KeyUp, p.Of(bob))\n}\n\nfunc TestUnreact(t *testing.T) {\n\tb := NewBoard()\n\tb.React(homePage, alice, KeyUp, 100)\n\n\tuassert.False(t, b.Unreact(\"gno.land/r/never/touched\", alice), \"no page\")\n\tuassert.False(t, b.Unreact(homePage, bob), \"no reaction of bob's\")\n\tuassert.True(t, b.Unreact(homePage, alice))\n\tuassert.False(t, b.Unreact(homePage, alice), \"removing twice is not an error, just false\")\n\n\tp := b.Page(homePage)\n\tuassert.Equal(t, 0, p.Count(KeyUp), \"an emptied bucket leaves no residue\")\n\tuassert.Equal(t, 0, p.Total())\n\n\t// Last is deliberately not rewound: it records what happened.\n\tkey, who, _ := p.Last()\n\tuassert.Equal(t, KeyUp, key)\n\tuassert.Equal(t, alice, who)\n}\n\nfunc TestReactRejects(t *testing.T) {\n\tb := NewBoard()\n\tuassert.False(t, b.React(\"not a path\", alice, KeyUp, 1), \"bad page\")\n\tuassert.False(t, b.React(homePage, alice, \"poop\", 1), \"key outside the palette\")\n\tuassert.Equal(t, 0, b.Pages(), \"a rejected reaction creates no page\")\n}\n\nfunc TestPagesAreIndependentAndOrdered(t *testing.T) {\n\tb := NewBoard()\n\tb.React(\"gno.land/r/moul/home\", alice, KeyUp, 1)\n\tb.React(\"gno.land/r/moul/blog\", bob, KeyFire, 2)\n\tb.React(\"gno.land/r/moul/blog\", carol, KeyFire, 3)\n\n\tuassert.Equal(t, 2, b.Pages())\n\tuassert.Equal(t, 1, b.Page(\"gno.land/r/moul/home\").Total())\n\tuassert.Equal(t, 2, b.Page(\"gno.land/r/moul/blog\").Total())\n\n\tvar seen []string\n\tb.Each(func(page string, p *Page) bool {\n\t\tseen = append(seen, page)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"gno.land/r/moul/blog,gno.land/r/moul/home\", strings.Join(seen, \",\"),\n\t\t\"Each walks in key order, so a Render built from it is stable\")\n}\n\nfunc TestEachStopsOnTrue(t *testing.T) {\n\tb := NewBoard()\n\tb.React(\"gno.land/r/a/one\", alice, KeyUp, 1)\n\tb.React(\"gno.land/r/b/two\", alice, KeyUp, 2)\n\n\tn := 0\n\tb.Each(func(page string, p *Page) bool {\n\t\tn++\n\t\treturn true\n\t})\n\tuassert.Equal(t, 1, n)\n}\n\nfunc TestRealmAndPageURL(t *testing.T) {\n\tuassert.Equal(t, \"/r/test/reactions/v0\", RealmURL(realmPath))\n\tuassert.Equal(t, \"\", RealmURL(\"nodomain\"))\n\tuassert.Equal(t, \"/r/test/reactions/v0:gno.land/r/moul/home\",\n\t\tPageURL(realmPath, homePage))\n\tuassert.Equal(t, \"\", PageURL(\"nodomain\", homePage))\n}\n\n// TestBlockShape pins the embed byte for byte. It is a Test and not an Example\n// because the block contains a blank line, and gno collapses consecutive blank\n// lines inside an // Output: block.\nfunc TestBlockShape(t *testing.T) {\n\tb := NewBoard()\n\n\tempty := \"[\\U0001F44D](/r/test/reactions/v0$help\u0026func=React\u0026key=up\u0026page=gno.land%2Fr%2Fmoul%2Fhome) \" +\n\t\t\"[\\U0001F49C](/r/test/reactions/v0$help\u0026func=React\u0026key=heart\u0026page=gno.land%2Fr%2Fmoul%2Fhome) \" +\n\t\t\"[\\U0001F525](/r/test/reactions/v0$help\u0026func=React\u0026key=fire\u0026page=gno.land%2Fr%2Fmoul%2Fhome) \" +\n\t\t\"[\\U0001F389](/r/test/reactions/v0$help\u0026func=React\u0026key=party\u0026page=gno.land%2Fr%2Fmoul%2Fhome) \" +\n\t\t\"[\\U0001F680](/r/test/reactions/v0$help\u0026func=React\u0026key=rocket\u0026page=gno.land%2Fr%2Fmoul%2Fhome) \" +\n\t\t\"[\\U0001F440](/r/test/reactions/v0$help\u0026func=React\u0026key=eyes\u0026page=gno.land%2Fr%2Fmoul%2Fhome)\" +\n\t\t\"\\n\\n*no reactions yet*\\n\"\n\tuassert.Equal(t, empty, Block(realmPath, homePage, b.Page(homePage)),\n\t\t\"a page nobody has reacted to still renders the whole strip\")\n\n\tb.React(homePage, alice, KeyUp, 100)\n\tb.React(homePage, bob, KeyUp, 101)\n\tb.React(homePage, carol, KeyFire, 102)\n\n\tgot := Block(realmPath, homePage, b.Page(homePage))\n\tuassert.True(t, strings.Contains(got, \"[\\U0001F44D 2]\"), \"the count rides in the link title\")\n\tuassert.True(t, strings.Contains(got, \"[\\U0001F525 1]\"))\n\tuassert.True(t, strings.Contains(got, \"[\\U0001F389]\"), \"an empty bucket shows no zero\")\n\tuassert.True(t, strings.Contains(got, \"last \\U0001F525 by \"))\n\tuassert.True(t, strings.Contains(got, \"[3 reactions](/r/test/reactions/v0:gno.land/r/moul/home)\"))\n\tuassert.True(t, strings.HasSuffix(got, \"*\\n\"), \"one trailing newline, so it drops into a Render\")\n}\n\nfunc TestSummaryPluralises(t *testing.T) {\n\tb := NewBoard()\n\tb.React(homePage, alice, KeyUp, 100)\n\tuassert.True(t, strings.Contains(Summary(realmPath, homePage, b.Page(homePage)), \"[1 reaction]\"))\n\n\tb.React(homePage, bob, KeyUp, 101)\n\tuassert.True(t, strings.Contains(Summary(realmPath, homePage, b.Page(homePage)), \"[2 reactions]\"))\n}\n\n// TestEmojiSurviveTheEscaper is the reason the palette holds no U+FE0F and no\n// zero-width joiner: ui.ActionIn escapes the link title, and that escaper\n// strips exactly those. A glyph that does not survive it renders as a\n// monochrome box on every page that embeds the block.\nfunc TestEmojiSurviveTheEscaper(t *testing.T) {\n\tb := NewBoard()\n\tfor _, k := range Keys() {\n\t\tgot := Block(realmPath, homePage, b.Page(homePage))\n\t\tuassert.True(t, strings.Contains(got, \"[\"+Emoji(k)+\"]\"), k)\n\t}\n}\n\n// TestSummaryGoesEmptyWhenEveryoneLeaves is the interaction between the two\n// halves of Last: it is deliberately not rewound by Unreact, so the summary has\n// to decide for itself whether there is anything left to summarise. Gating on\n// the last key alone would print \"last 👍 by g1… · 0 reactions\" above an empty\n// strip, which contradicts itself and keeps attributing a reaction its author\n// took back.\nfunc TestSummaryGoesEmptyWhenEveryoneLeaves(t *testing.T) {\n\tb := NewBoard()\n\tb.React(homePage, alice, KeyUp, 100)\n\tb.Unreact(homePage, alice)\n\n\tp := b.Page(homePage)\n\tuassert.Equal(t, 0, p.Total(), \"the tally is empty\")\n\n\tkey, _, _ := p.Last()\n\tuassert.Equal(t, KeyUp, key, \"and Last still records the event, by design\")\n\n\tuassert.Equal(t, \"no reactions yet\", Summary(realmPath, homePage, p),\n\t\t\"so the summary shows the empty state rather than a withdrawn reaction\")\n\n\tuassert.True(t, strings.HasSuffix(Block(realmPath, homePage, p), \"*no reactions yet*\\n\"))\n}\n"}]},"send":"","max_deposit":"11000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"safe","path":"gno.land/p/moul/safe/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/safe`\n\n\u003e 🚧 **API sketch, mostly unimplemented.** 13 of the 22 functions\n\u003e `panic(\"not implemented\")`, including every proposal path. It compiles and\n\u003e its shape is testable; it does not work.\n\nA Gnosis-Safe-shaped multisig interface for gno: an m-of-n set of members, a\nqueue of proposals, and explicit approve / execute / cancel.\n\n## What runs today\n\n```go\nfunc NewSafe() Safe          // 1-of-1, owned by the calling realm's address\nfunc (s safe) Name() string\nfunc (s safe) Members() []address\nfunc (s safe) Threshold() uint\nfunc (s safe) Size() uint\n```\n\n## What panics\n\nEverything that would make it a multisig: `ProposeAddingMember`,\n`ProposeRemovingMember`, `ProposeUpdatingThreshold`, `GetProposal`,\n`ApproveProposal`, `ExecuteProposal`, `CancelProposal`, `NextProposal`,\n`UpcomingProposals`, `PreviousProposals`, `Render`, and both `String` methods.\n\n## The shape being proposed\n\nThe interesting decision is that membership changes are themselves proposals,\nso there is one code path for \"do a thing\" and no privileged side door for\n\"change who may do things\". `Proposal` exposes `Executed()` and `Voters()`, and\nproposals are split into upcoming and previous rather than a single log, which\nis what a UI actually needs.\n\nFor multisig that works today, use the tm2 account-level multisig\n(`gnokey multisign`), not this.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/safe/v0\"\ngno = \"0.9\"\n"},{"name":"safe.gno","body":"// Package safe is inspired by Gnosis Safe\npackage safe\n\nimport (\n\t\"chain/runtime/unsafe\"\n)\n\n//  Gnosis safe style using this with threshold\n// : affMember + update threshold at the same time\n\ntype Safe interface {\n\tName() string\n\tMembers() []address\n\tThreshold() uint\n\tSize() uint\n\tNextProposal() Proposal\n\tUpcomingProposals(page uint) (props []Proposal, total uint)\n\tPreviousProposals(page uint) (props []Proposal, total uint)\n\t// balances (native, grc20, grc721)\n\n\tProposeAddingMember(addr address, newThreshold uint) (prop Proposal, err error)\n\tProposeRemovingMember(addr address, newThreshold uint) (prop Proposal, err error)\n\tProposeUpdatingThreshold(newThreshold uint) (prop Proposal, err error)\n\t// ProposeClosure(cl func()) (prop Proposal, err error)\n\t// ProposeBankXXX()\n\t// ProposeGRC20XXX()\n\t// ProposeGRC721XXX()\n\n\tGetProposal(id uint) Proposal\n\tApproveProposal(p Proposal) error\n\tExecuteProposal(p Proposal) error\n\tCancelProposal(p Proposal) error // XXX: should be ProposeToCancel?\n\n\tRender(path string) string\n}\n\ntype Proposal interface {\n\tID() uint\n\tActive() bool\n\tExecuted() bool\n\tVoters() []address\n}\n\nfunc NewSafe() Safe {\n\tcaller := unsafe.PreviousRealm().Address()\n\treturn safe{\n\t\tmembers:   []address{caller},\n\t\tthreshold: 1,\n\t\tprevProps: []Proposal{},\n\t\tnextProps: []Proposal{},\n\t}\n}\n\ntype safe struct {\n\tname      string\n\tmembers   []address // member addresses\n\tthreshold uint\n\tprevProps []Proposal // executed/cancelled proposals\n\tnextProps []Proposal // upcoming proposals\n}\n\nfunc (s safe) String() string { panic(\"not implemented\") }\n\nfunc (s safe) Name() string        { return s.name }\nfunc (s safe) Members() []address  { return s.members }\nfunc (s safe) Threshold() uint     { return s.threshold }\nfunc (s safe) Size() uint          { return uint(len(s.members)) }\nfunc (s safe) NextProposal() Proposal { panic(\"not implemented\") }\n\nfunc (s safe) UpcomingProposals(page uint) (props []Proposal, total uint) {\n\tpanic(\"not implemented\")\n}\n\nfunc (s safe) PreviousProposals(page uint) (props []Proposal, total uint) {\n\tpanic(\"not implemented\")\n}\n\nfunc (s safe) ProposeAddingMember(addr address, newThreshold uint) (prop Proposal, err error) {\n\tpanic(\"not implemented\")\n}\n\nfunc (s safe) ProposeRemovingMember(addr address, newThreshold uint) (prop Proposal, err error) {\n\tpanic(\"not implemented\")\n}\n\nfunc (s safe) ProposeUpdatingThreshold(newThreshold uint) (prop Proposal, err error) {\n\tpanic(\"not implemented\")\n}\n\nfunc (s safe) GetProposal(id uint) Proposal   { panic(\"not implemented\") }\nfunc (s safe) ApproveProposal(p Proposal) error { panic(\"not implemented\") }\nfunc (s safe) ExecuteProposal(p Proposal) error { panic(\"not implemented\") }\nfunc (s safe) CancelProposal(p Proposal) error  { panic(\"not implemented\") }\nfunc (s safe) Render(path string) string        { panic(\"not implemented\") }\n\ntype proposal struct{}\n\nfunc (p proposal) String() string { panic(\"not implemented\") }\n"},{"name":"safe_test.gno","body":"package safe\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// This package is a design sketch: only the constructor and the four read\n// accessors are implemented, and every proposal method is `panic(\"not\n// implemented\")`. The tests below pin the implemented behaviour and pin the\n// stubs as stubs, so implementing one is a deliberate, visible change.\n\nvar alice = testutils.TestAddress(\"alice\")\n\n// NewSafe reads unsafe.PreviousRealm(), which needs a real realm frame: a user\n// realm gives \"frame not found: cannot seek beyond origin caller override\".\nfunc TestNewSafeDefaults(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test/safeone\"))\n\ts := NewSafe()\n\n\tuassert.Equal(t, \"\", s.Name(), \"a fresh safe is unnamed\")\n\tuassert.Equal(t, uint(1), s.Threshold(), \"threshold starts at 1\")\n\tuassert.Equal(t, uint(1), s.Size(), \"the creator is the only member\")\n\tuassert.Equal(t, 1, len(s.Members()))\n\tuassert.True(t, s.Members()[0].IsValid(), \"the sole member is a valid address\")\n}\n\n// Note: caller-sensitivity of NewSafe is NOT asserted here. From a `p/` test\n// package there is a single realm frame, so unsafe.PreviousRealm() resolves to\n// the origin no matter what testing.SetRealm is given — two different code\n// realms seed the identical address. Proving \"membership follows the caller\"\n// needs an `r/` test package that can actually cross into this one.\n\nfunc TestSizeTracksMembers(t *testing.T) {\n\ts := safe{members: []address{alice, testutils.TestAddress(\"bob\")}, threshold: 2}\n\tuassert.Equal(t, uint(2), s.Size())\n\tuassert.Equal(t, uint(2), s.Threshold())\n}\n\n// TestUnimplementedMethodsPanic documents the sketch surface. If one of these\n// starts working, this test fails and forces the contract change to be noticed.\nfunc TestUnimplementedMethodsPanic(cur realm, t *testing.T) {\n\ts := safe{members: []address{alice}, threshold: 1}\n\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.NextProposal() })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.UpcomingProposals(0) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.PreviousProposals(0) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.ProposeAddingMember(alice, 1) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.ProposeRemovingMember(alice, 1) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.ProposeUpdatingThreshold(2) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.GetProposal(0) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.ApproveProposal(nil) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.ExecuteProposal(nil) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.CancelProposal(nil) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { s.Render(\"\") })\n}\n\n// TestSafeSatisfiesInterface is a compile-time check that the concrete type\n// still implements the exported interface.\nfunc TestSafeSatisfiesInterface(t *testing.T) {\n\tvar _ Safe = safe{}\n\tuassert.True(t, true, \"safe implements Safe\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"template","path":"gno.land/p/moul/template/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/template`\n\nA small `{{ }}` template engine for building Markdown in a realm, with the\n[`p/moul/md`](../md) helpers available as template functions.\n\n```go\nr := template.NewRenderer()\n\nout := r.Render(\"{{H1 title}}\\n\\n{{Bold name}} has {{count}} items\", map[string]interface{}{\n\t\"title\": \"Report\",\n\t\"name\":  \"moul\",\n\t\"count\": 3,\n})\n```\n\n## Syntax\n\n| form | meaning |\n| --- | --- |\n| `{{key}}` | substitute a value from the data map |\n| `{{Func arg}}` | call a template function |\n| `{{range items}} ... {{end}}` | iterate |\n| `{{if cond}} ... {{else}} ... {{end}}` | conditional |\n| `{{- x}}`, `{{x -}}` | trim whitespace on that side |\n\nWhitespace trimming matters more here than in Go's `text/template`, because the\noutput is Markdown and a stray blank line changes the rendering.\n\n## Built-in functions\n\nMarkdown, forwarded to `p/moul/md`: `H1` to `H6`, `Bold`, `Italic`,\n`Strikethrough`, `InlineCode`, `CodeBlock`, `LanguageCodeBlock`, `Blockquote`,\n`Paragraph`, `BulletItem`, `TodoItem`, `HorizontalRule`, `Link`, `Image`,\n`InlineImageWithLink`, `Footnote`, `CollapsibleSection`, `EscapeText`.\n\nGeneral: `concat`, `printf`, `trim`, `string`, `index`.\n\nRegister your own with the `Func` signature:\n\n```go\ntype Func func(args ...string) string\n```\n\n## Why not `text/template`\n\nIt is not in the gno standard library, and it would not fit: it reaches for\nreflection, and template execution has to stay cheap and bounded when it runs\ninside a `Render`. This engine is string in, string out, with an explicit\nfunction table and no reflection.\n\n`Helper` is kept as an alias for backward compatibility; new code should use\n`Func`.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/template/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/template/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/template/v0\"\ngno = \"0.9\"\n"},{"name":"template.gno","body":"package template\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/typeutil/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Renderer provides a simple template engine with a clean API\ntype Renderer struct {\n\tfuncs map[string]Func  // Template functions\n\tdata  map[string]interface{} // Global data\n\tctx   *context       // Current evaluation context\n}\n\n// Func is the signature for template functions\ntype Func func(args ...string) string\n\n// context tracks variable scope during evaluation\ntype context struct {\n\tparent *context\n\tvars   map[string]interface{} // Local variables\n\tloop   *loopContext          // Range loop state\n}\n\n// loopContext holds state for range loops\ntype loopContext struct {\n\titems []interface{} // Items being iterated\n\tindex int          // Current index\n}\n\n// NewRenderer creates a new template renderer with default functions\nfunc NewRenderer() *Renderer {\n\tr := \u0026Renderer{\n\t\tfuncs: make(map[string]Func),\n\t\tdata:  make(map[string]interface{}),\n\t}\n\tr.registerDefaults()\n\treturn r\n}\n\n// Render processes a template with the given data\nfunc (r *Renderer) Render(template string, data map[string]interface{}) string {\n\tif data != nil {\n\t\tr.data = data\n\t}\n\tr.ctx = nil\n\treturn r.render(template)\n}\n\n// render is the core rendering engine\nfunc (r *Renderer) render(tmpl string) string {\n\tvar out strings.Builder\n\t\n\tfor len(tmpl) \u003e 0 {\n\t\t// Find next placeholder\n\t\tstart := strings.Index(tmpl, \"{{\")\n\t\tif start \u003c 0 {\n\t\t\tout.WriteString(tmpl)\n\t\t\tbreak\n\t\t}\n\t\t\n\t\t// Write content before placeholder\n\t\tout.WriteString(tmpl[:start])\n\t\t\n\t\t// Parse placeholder\n\t\tplaceholder, end := r.parsePlaceholder(tmpl[start:])\n\t\tif placeholder == nil {\n\t\t\tout.WriteString(\"{{\")\n\t\t\ttmpl = tmpl[start+2:]\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\t// Apply left trim\n\t\tif placeholder.trimLeft {\n\t\t\ts := out.String()\n\t\t\tout.Reset()\n\t\t\tout.WriteString(strings.TrimRightFunc(s, unicode.IsSpace))\n\t\t}\n\t\t\n\t\t// Process placeholder\n\t\tresult, consumed := r.process(placeholder, tmpl[start+end:])\n\t\tout.WriteString(result)\n\t\t\n\t\t// Advance position\n\t\ttmpl = tmpl[start+end+consumed:]\n\t\t\n\t\t// Apply right trim\n\t\tif placeholder.trimRight {\n\t\t\ttmpl = strings.TrimLeftFunc(tmpl, unicode.IsSpace)\n\t\t}\n\t}\n\t\n\treturn out.String()\n}\n\n// placeholder represents a parsed {{...}} tag\ntype placeholder struct {\n\texpr      string\n\ttrimLeft  bool\n\ttrimRight bool\n}\n\n// parsePlaceholder extracts a {{...}} placeholder\nfunc (r *Renderer) parsePlaceholder(tmpl string) (*placeholder, int) {\n\tif !strings.HasPrefix(tmpl, \"{{\") {\n\t\treturn nil, 0\n\t}\n\t\n\t// Find matching }}\n\tend := r.findClosing(tmpl, 2)\n\tif end \u003c 0 {\n\t\treturn nil, 0\n\t}\n\t\n\t// Extract content\n\tcontent := tmpl[2:end]\n\t\n\t// Check trim markers\n\tp := \u0026placeholder{}\n\tif strings.HasPrefix(content, \"-\") {\n\t\tp.trimLeft = true\n\t\tcontent = content[1:]\n\t}\n\tif strings.HasSuffix(content, \"-\") {\n\t\tp.trimRight = true\n\t\tcontent = content[:len(content)-1]\n\t}\n\t\n\tp.expr = strings.TrimSpace(content)\n\treturn p, end + 2\n}\n\n// findClosing finds the closing }} for a {{\nfunc (r *Renderer) findClosing(tmpl string, start int) int {\n\tdepth := 1\n\ti := start\n\t\n\tfor i \u003c len(tmpl)-1 {\n\t\tif tmpl[i] == '{' \u0026\u0026 tmpl[i+1] == '{' {\n\t\t\tdepth++\n\t\t\ti += 2\n\t\t} else if tmpl[i] == '}' \u0026\u0026 tmpl[i+1] == '}' {\n\t\t\tdepth--\n\t\t\tif depth == 0 {\n\t\t\t\treturn i\n\t\t\t}\n\t\t\ti += 2\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\t\n\treturn -1\n}\n\n// process evaluates a placeholder and returns (result, extraBytesConsumed)\nfunc (r *Renderer) process(p *placeholder, remaining string) (string, int) {\n\tparts := r.parseExpr(p.expr)\n\tif len(parts) == 0 {\n\t\treturn \"\", 0\n\t}\n\t\n\tcmd := parts[0]\n\targs := parts[1:]\n\t\n\t// Handle variables\n\tif strings.HasPrefix(cmd, \".\") {\n\t\tif val := r.resolve(cmd); val != nil {\n\t\t\treturn typeutil.ToString(val), 0\n\t\t}\n\t\treturn \"\", 0\n\t}\n\t\n\t// Handle commands\n\tswitch cmd {\n\tcase \"range\":\n\t\treturn r.doRange(args, remaining)\n\tcase \"if\":\n\t\treturn r.doIf(args, remaining)\n\tcase \"end\", \"else\":\n\t\treturn \"\", 0 // Handled by parent\n\tdefault:\n\t\t// Special handling for index function\n\t\tif cmd == \"index\" \u0026\u0026 len(args) \u003e= 2 {\n\t\t\treturn r.indexFunc(args...), 0\n\t\t}\n\t\t// Try function\n\t\tif fn, ok := r.funcs[cmd]; ok {\n\t\t\tresolved := r.resolveArgs(args)\n\t\t\treturn fn(resolved...), 0\n\t\t}\n\t\treturn p.expr, 0\n\t}\n}\n\n// doRange implements {{range .items}}...{{end}}\nfunc (r *Renderer) doRange(args []string, tmpl string) (string, int) {\n\tif len(args) == 0 {\n\t\treturn \"\", 0\n\t}\n\t\n\t// Get collection\n\tval := r.resolve(args[0])\n\tif val == nil {\n\t\treturn \"\", 0\n\t}\n\t\n\t// Convert to items\n\titems := toSlice(val)\n\tif items == nil {\n\t\treturn \"\", 0\n\t}\n\t\n\t// Find block\n\tblock, consumed := r.findBlock(tmpl, \"end\")\n\tif consumed == 0 {\n\t\treturn \"\", 0\n\t}\n\t\n\t// Execute loop\n\tvar out strings.Builder\n\toldCtx := r.ctx\n\t\n\tfor i, item := range items {\n\t\t// Create loop context\n\t\tr.ctx = \u0026context{\n\t\t\tparent: oldCtx,\n\t\t\tvars:   make(map[string]interface{}),\n\t\t\tloop: \u0026loopContext{\n\t\t\t\titems: items,\n\t\t\t\tindex: i,\n\t\t\t},\n\t\t}\n\t\t\n\t\t// Add item properties if map\n\t\tif m, ok := item.(map[string]interface{}); ok {\n\t\t\tfor k, v := range m {\n\t\t\t\tr.ctx.vars[k] = v\n\t\t\t}\n\t\t}\n\t\t\n\t\tout.WriteString(r.render(block))\n\t}\n\t\n\tr.ctx = oldCtx\n\treturn out.String(), consumed\n}\n\n// doIf implements {{if .cond}}...{{else}}...{{end}}\nfunc (r *Renderer) doIf(args []string, tmpl string) (string, int) {\n\tif len(args) == 0 {\n\t\treturn \"\", 0\n\t}\n\t\n\t// Evaluate condition\n\tval := r.resolve(args[0])\n\tcond := typeutil.ToBool(val)\n\t\n\t// Find block\n\tblock, consumed := r.findBlock(tmpl, \"end\")\n\tif consumed == 0 {\n\t\treturn \"\", 0\n\t}\n\t\n\t// Split on else\n\tifBlock, elseBlock := r.splitElse(block)\n\t\n\t// Execute branch\n\toldCtx := r.ctx\n\tr.ctx = \u0026context{\n\t\tparent: oldCtx,\n\t\tvars:   make(map[string]interface{}),\n\t}\n\t\n\tvar result string\n\tif cond {\n\t\tresult = r.render(ifBlock)\n\t} else {\n\t\tresult = r.render(elseBlock)\n\t}\n\t\n\tr.ctx = oldCtx\n\treturn result, consumed\n}\n\n// findBlock finds content up to {{end}}\nfunc (r *Renderer) findBlock(tmpl string, endMarker string) (string, int) {\n\tvar out strings.Builder\n\tdepth := 1\n\ti := 0\n\t\n\tfor i \u003c len(tmpl) {\n\t\t// Find next {{\n\t\tnext := strings.Index(tmpl[i:], \"{{\")\n\t\tif next \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\t// Add content before {{\n\t\tout.WriteString(tmpl[i : i+next])\n\t\t\n\t\t// Parse placeholder\n\t\tp, consumed := r.parsePlaceholder(tmpl[i+next:])\n\t\tif p == nil {\n\t\t\tout.WriteString(\"{{\")\n\t\t\ti += next + 2\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\t// Check command\n\t\tparts := r.parseExpr(p.expr)\n\t\tif len(parts) \u003e 0 {\n\t\t\tswitch parts[0] {\n\t\t\tcase \"range\", \"if\":\n\t\t\t\tdepth++\n\t\t\tcase endMarker:\n\t\t\t\tdepth--\n\t\t\t\tif depth == 0 {\n\t\t\t\t\treturn out.String(), i + next + consumed\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Add to output\n\t\tout.WriteString(tmpl[i+next : i+next+consumed])\n\t\ti += next + consumed\n\t}\n\t\n\treturn \"\", 0\n}\n\n// splitElse splits block on {{else}}\nfunc (r *Renderer) splitElse(block string) (string, string) {\n\tdepth := 0\n\ti := 0\n\t\n\tfor i \u003c len(block) {\n\t\tnext := strings.Index(block[i:], \"{{\")\n\t\tif next \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tp, consumed := r.parsePlaceholder(block[i+next:])\n\t\tif p == nil {\n\t\t\ti += next + 2\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\tparts := r.parseExpr(p.expr)\n\t\tif len(parts) \u003e 0 {\n\t\t\tswitch parts[0] {\n\t\t\tcase \"if\":\n\t\t\t\tdepth++\n\t\t\tcase \"end\":\n\t\t\t\tdepth--\n\t\t\tcase \"else\":\n\t\t\t\tif depth == 0 {\n\t\t\t\t\treturn block[:i+next], block[i+next+consumed:]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ti += next + consumed\n\t}\n\t\n\treturn block, \"\"\n}\n\n// parseExpr splits expression respecting quotes and parentheses\nfunc (r *Renderer) parseExpr(expr string) []string {\n\tvar parts []string\n\tvar current strings.Builder\n\tvar inQuote bool\n\tvar parenDepth int\n\tvar prevChar rune\n\t\n\tfor _, ch := range expr {\n\t\tswitch ch {\n\t\tcase '\"':\n\t\t\tif prevChar != '\\\\' {\n\t\t\t\tinQuote = !inQuote\n\t\t\t}\n\t\t\tcurrent.WriteRune(ch)\n\t\tcase '(':\n\t\t\tif !inQuote {\n\t\t\t\tparenDepth++\n\t\t\t}\n\t\t\tcurrent.WriteRune(ch)\n\t\tcase ')':\n\t\t\tif !inQuote {\n\t\t\t\tparenDepth--\n\t\t\t}\n\t\t\tcurrent.WriteRune(ch)\n\t\tcase ' ':\n\t\t\tif !inQuote \u0026\u0026 parenDepth == 0 {\n\t\t\t\tif current.Len() \u003e 0 {\n\t\t\t\t\tparts = append(parts, current.String())\n\t\t\t\t\tcurrent.Reset()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcurrent.WriteRune(ch)\n\t\t\t}\n\t\tdefault:\n\t\t\tcurrent.WriteRune(ch)\n\t\t}\n\t\tprevChar = ch\n\t}\n\t\n\tif current.Len() \u003e 0 {\n\t\tparts = append(parts, current.String())\n\t}\n\t\n\treturn parts\n}\n\n// resolve looks up a variable\nfunc (r *Renderer) resolve(name string) interface{} {\n\tif !strings.HasPrefix(name, \".\") {\n\t\treturn nil\n\t}\n\tname = strings.TrimPrefix(name, \".\")\n\t\n\t// Check context stack\n\tctx := r.ctx\n\tfor ctx != nil {\n\t\t// Handle . in range\n\t\tif name == \"\" \u0026\u0026 ctx.loop != nil {\n\t\t\tif ctx.loop.index \u003c len(ctx.loop.items) {\n\t\t\t\treturn ctx.loop.items[ctx.loop.index]\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Check local vars\n\t\tif val, ok := ctx.vars[name]; ok {\n\t\t\treturn val\n\t\t}\n\t\t\n\t\tctx = ctx.parent\n\t}\n\t\n\t// Check global data\n\treturn lookup(r.data, name)\n}\n\n// resolveArgs resolves all arguments\nfunc (r *Renderer) resolveArgs(args []string) []string {\n\tresult := make([]string, len(args))\n\t\n\tfor i, arg := range args {\n\t\t// Handle nested calls\n\t\tif strings.HasPrefix(arg, \"(\") \u0026\u0026 strings.HasSuffix(arg, \")\") {\n\t\t\tinner := arg[1 : len(arg)-1]\n\t\t\tparts := r.parseExpr(inner)\n\t\t\tif len(parts) \u003e 0 {\n\t\t\t\t// Special handling for index\n\t\t\t\tif parts[0] == \"index\" \u0026\u0026 len(parts) \u003e= 3 {\n\t\t\t\t\tresult[i] = r.indexFunc(parts[1:]...)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif fn, ok := r.funcs[parts[0]]; ok {\n\t\t\t\t\tresolved := r.resolveArgs(parts[1:])\n\t\t\t\t\tresult[i] = fn(resolved...)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Handle variables\n\t\tif strings.HasPrefix(arg, \".\") {\n\t\t\tif val := r.resolve(arg); val != nil {\n\t\t\t\tresult[i] = typeutil.ToString(val)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Handle nested templates\n\t\tif strings.Contains(arg, \"{{\") {\n\t\t\t// For quoted strings with nested templates, handle specially\n\t\t\tif len(arg) \u003e= 2 \u0026\u0026 arg[0] == '\"' \u0026\u0026 arg[len(arg)-1] == '\"' {\n\t\t\t\t// Remove outer quotes, process template, then result is the value\n\t\t\t\tinner := arg[1 : len(arg)-1]\n\t\t\t\tresult[i] = r.render(inner)\n\t\t\t} else {\n\t\t\t\tresult[i] = r.render(arg)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\t// Plain string\n\t\tresult[i] = unquote(arg)\n\t}\n\t\n\treturn result\n}\n\n// registerDefaults registers built-in functions\nfunc (r *Renderer) registerDefaults() {\n\t// Markdown helpers\n\tr.funcs[\"H1\"] = wrap1(md.H1)\n\tr.funcs[\"H2\"] = wrap1(md.H2)\n\tr.funcs[\"H3\"] = wrap1(md.H3)\n\tr.funcs[\"H4\"] = wrap1(md.H4)\n\tr.funcs[\"H5\"] = wrap1(md.H5)\n\tr.funcs[\"H6\"] = wrap1(md.H6)\n\tr.funcs[\"Bold\"] = wrap1(md.Bold)\n\tr.funcs[\"Italic\"] = wrap1(md.Italic)\n\tr.funcs[\"Strikethrough\"] = wrap1(md.Strikethrough)\n\tr.funcs[\"InlineCode\"] = wrap1(md.InlineCode)\n\tr.funcs[\"BulletItem\"] = wrap1(md.BulletItem)\n\tr.funcs[\"CodeBlock\"] = wrap1(md.CodeBlock)\n\tr.funcs[\"Blockquote\"] = wrap1(md.Blockquote)\n\tr.funcs[\"Paragraph\"] = wrap1(md.Paragraph)\n\tr.funcs[\"EscapeText\"] = wrap1(md.EscapeText)\n\t\n\tr.funcs[\"Link\"] = wrap2(md.Link)\n\tr.funcs[\"Image\"] = wrap2(md.Image)\n\tr.funcs[\"LanguageCodeBlock\"] = wrap2(md.LanguageCodeBlock)\n\tr.funcs[\"Footnote\"] = wrap2(md.FootnoteDefinition)\n\tr.funcs[\"CollapsibleSection\"] = wrap2(md.CollapsibleSection)\n\t\n\tr.funcs[\"InlineImageWithLink\"] = wrap3(md.InlineImageWithLink)\n\t\n\tr.funcs[\"TodoItem\"] = func(args ...string) string {\n\t\tif len(args) \u003e= 2 {\n\t\t\treturn md.TodoItem(args[0], args[1] == \"true\")\n\t\t}\n\t\treturn \"[error: TodoItem requires 2 arguments]\"\n\t}\n\t\n\tr.funcs[\"HorizontalRule\"] = func(args ...string) string {\n\t\treturn md.HorizontalRule()\n\t}\n\t\n\t// Utilities\n\tr.funcs[\"concat\"] = func(args ...string) string {\n\t\treturn strings.Join(args, \"\")\n\t}\n\t\n\tr.funcs[\"printf\"] = func(args ...string) string {\n\t\tif len(args) == 0 {\n\t\t\treturn \"\"\n\t\t}\n\t\tvalues := make([]interface{}, len(args)-1)\n\t\tfor i, v := range args[1:] {\n\t\t\tvalues[i] = v\n\t\t}\n\t\treturn ufmt.Sprintf(args[0], values...)\n\t}\n\t\n\tr.funcs[\"trim\"] = wrap1(strings.TrimSpace)\n\tr.funcs[\"string\"] = func(args ...string) string {\n\t\tif len(args) \u003e 0 {\n\t\t\treturn typeutil.ToString(args[0])\n\t\t}\n\t\treturn \"\"\n\t}\n\t\n\tr.funcs[\"index\"] = r.indexFunc\n}\n\n// indexFunc provides array/map indexing\nfunc (r *Renderer) indexFunc(args ...string) string {\n\tif len(args) \u003c 2 {\n\t\treturn \"[error: index requires 2 arguments]\"\n\t}\n\t\n\t// Handle the first argument - could be variable or literal\n\tcollection := strings.TrimSpace(args[0])\n\tindexStr := strings.TrimSpace(args[1])\n\t\n\t// Remove quotes from index if present\n\tindexStr = unquote(indexStr)\n\t\n\t// For unit tests - literal values\n\tif !strings.HasPrefix(collection, \".\") {\n\t\tif idx, err := strconv.Atoi(indexStr); err == nil {\n\t\t\treturn ufmt.Sprintf(\"[%d]\", idx)\n\t\t}\n\t\treturn ufmt.Sprintf(\"[%s]\", indexStr)\n\t}\n\t\n\t// Resolve the collection variable\n\tval := r.resolve(collection)\n\tif val == nil {\n\t\treturn \"[error: collection not found]\"\n\t}\n\t\n\t// Parse index\n\tidx, err := strconv.Atoi(indexStr)\n\tif err != nil {\n\t\treturn \"[error: index must be a number]\"\n\t}\n\t\n\t// Do the indexing\n\tswitch v := val.(type) {\n\tcase []interface{}:\n\t\tif idx \u003e= 0 \u0026\u0026 idx \u003c len(v) {\n\t\t\treturn typeutil.ToString(v[idx])\n\t\t}\n\tcase []string:\n\t\tif idx \u003e= 0 \u0026\u0026 idx \u003c len(v) {\n\t\t\treturn v[idx]\n\t\t}\n\tdefault:\n\t\tif items := toSlice(val); items != nil {\n\t\t\tif idx \u003e= 0 \u0026\u0026 idx \u003c len(items) {\n\t\t\t\treturn typeutil.ToString(items[idx])\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn \"[error: index out of range]\"\n}\n\n// Helper functions\n\n// lookup navigates nested maps\nfunc lookup(data map[string]interface{}, path string) interface{} {\n\tparts := strings.Split(path, \".\")\n\tvar current interface{} = data\n\t\n\tfor _, part := range parts {\n\t\tif part == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif m, ok := current.(map[string]interface{}); ok {\n\t\t\tcurrent = m[part]\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\t\n\treturn current\n}\n\n// toSlice converts various types to []interface{}\nfunc toSlice(val interface{}) []interface{} {\n\tswitch v := val.(type) {\n\tcase []interface{}:\n\t\treturn v\n\tcase []map[string]interface{}:\n\t\tresult := make([]interface{}, len(v))\n\t\tfor i, m := range v {\n\t\t\tresult[i] = m\n\t\t}\n\t\treturn result\n\tdefault:\n\t\treturn typeutil.ToInterfaceSlice(val)\n\t}\n}\n\n// unquote removes quotes from strings\nfunc unquote(s string) string {\n\t// Don't trim space - preserve formatting\n\tif len(s) \u003e= 2 \u0026\u0026 s[0] == '\"' \u0026\u0026 s[len(s)-1] == '\"' {\n\t\treturn s[1 : len(s)-1]\n\t}\n\treturn s\n}\n\n// Function wrappers for cleaner registration\n\nfunc wrap1(fn func(string) string) Func {\n\treturn func(args ...string) string {\n\t\tif len(args) \u003e 0 {\n\t\t\treturn fn(args[0])\n\t\t}\n\t\treturn \"[error: missing argument]\"\n\t}\n}\n\nfunc wrap2(fn func(string, string) string) Func {\n\treturn func(args ...string) string {\n\t\tif len(args) \u003e= 2 {\n\t\t\treturn fn(args[0], args[1])\n\t\t}\n\t\treturn \"[error: requires 2 arguments]\"\n\t}\n}\n\nfunc wrap3(fn func(string, string, string) string) Func {\n\treturn func(args ...string) string {\n\t\tif len(args) \u003e= 3 {\n\t\t\treturn fn(args[0], args[1], args[2])\n\t\t}\n\t\treturn \"[error: requires 3 arguments]\"\n\t}\n}\n\n// Helper is kept for backward compatibility\ntype Helper interface {\n\tExecute(args []string, data map[string]interface{}) string\n}"},{"name":"template_test.gno","body":"package template\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTrimMarkers(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\ttemplate string\n\t\tdata     map[string]interface{}\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"no_trim\",\n\t\t\ttemplate: \"{{23}} \u003c {{45}}\",\n\t\t\texpected: \"23 \u003c 45\",\n\t\t},\n\t\t{\n\t\t\tname:     \"trim_both\",\n\t\t\ttemplate: \"{{23 -}} \u003c {{- 45}}\",\n\t\t\texpected: \"23\u003c45\",\n\t\t},\n\t\t{\n\t\t\tname:     \"trim_left_only\",\n\t\t\ttemplate: \"{{23}} \u003c {{- 45}}\",\n\t\t\texpected: \"23 \u003c45\",\n\t\t},\n\t\t{\n\t\t\tname:     \"trim_right_only\",\n\t\t\ttemplate: \"{{23 -}} \u003c {{45}}\",\n\t\t\texpected: \"23\u003c 45\",\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple_spaces\",\n\t\t\ttemplate: \"{{23 -}}   \u003c   {{- 45}}\",\n\t\t\texpected: \"23\u003c45\",\n\t\t},\n\t\t{\n\t\t\tname:     \"newlines\",\n\t\t\ttemplate: \"{{23 -}}\\n\u003c\\n{{- 45}}\",\n\t\t\texpected: \"23\u003c45\",\n\t\t},\n\t\t{\n\t\t\tname:     \"helper_with_trim\",\n\t\t\ttemplate: \"{{Bold \\\"hello\\\" -}} {{- Bold \\\"world\\\"}}\",\n\t\t\texpected: \"**hello****world**\",\n\t\t},\n\t\t{\n\t\t\tname:     \"variable_with_trim\",\n\t\t\ttemplate: \"{{ .First -}} {{- .Second}}\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"First\":  \"Hello\",\n\t\t\t\t\"Second\": \"World\",\n\t\t\t},\n\t\t\texpected: \"HelloWorld\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := NewRenderer()\n\t\t\tgot := r.Render(tt.template, tt.data)\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"\\nTemplate: %s\\nExpected: %q\\nGot: %q\", tt.template, tt.expected, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNestedPlaceholders(t *testing.T) {\n\ttemplate := `# Welcome, {{ .Name }}!\n[Your Profile]({{ .ProfileURL }})`\n\n\tdata := map[string]interface{}{\n\t\t\"Name\":       \"Alice\",\n\t\t\"ProfileURL\": \"https://example.com/profile/Alice\",\n\t}\n\n\texpected := `# Welcome, Alice!\n[Your Profile](https://example.com/profile/Alice)`\n\n\tr := NewRenderer()\n\tgot := r.Render(template, data)\n\tif got != expected {\n\t\tt.Errorf(\"\\nExpected:\\n%s\\nGot:\\n%s\", expected, got)\n\t}\n}\n\nfunc TestHelpers(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\ttemplate string\n\t\tdata     map[string]interface{}\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"bold_helper\",\n\t\t\ttemplate: `{{ Bold \"hello\" }}`,\n\t\t\texpected: \"**hello**\",\n\t\t},\n\t\t{\n\t\t\tname: \"multiple_helpers\",\n\t\t\ttemplate: `{{ H1 \"Section\" }}\n{{ Bold \"Important\" }}\n{{ BulletItem \"First\" }}\n{{ BulletItem \"Second\" }}`,\n\t\t\texpected: \"# Section\\n\\n**Important**\\n- First\\n\\n- Second\\n\",\n\t\t},\n\t\t{\n\t\t\tname:     \"helper_with_quotes\",\n\t\t\ttemplate: `{{ Bold \"\\\"quoted text\\\"\" }}`,\n\t\t\texpected: `**\\\"quoted text\\\"**`,\n\t\t},\n\t\t{\n\t\t\tname:     \"helper_with_spaces\",\n\t\t\ttemplate: `{{ Bold \"  spaced  \" }}`,\n\t\t\texpected: \"**  spaced  **\",\n\t\t},\n\t\t{\n\t\t\tname:     \"concat_two_strings\",\n\t\t\ttemplate: `{{ concat \"Hello\" \" World\" }}`,\n\t\t\texpected: \"Hello World\",\n\t\t},\n\t\t{\n\t\t\tname:     \"concat_multiple_strings\",\n\t\t\ttemplate: `{{ concat \"Hello\" \" \" \"wonderful\" \" \" \"World\" \"!\" }}`,\n\t\t\texpected: \"Hello wonderful World!\",\n\t\t},\n\t\t{\n\t\t\tname:     \"concat_with_vars\",\n\t\t\ttemplate: `{{ concat .Greeting \" \" .Name \"!\" }}`,\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Greeting\": \"Hello\",\n\t\t\t\t\"Name\":     \"Alice\",\n\t\t\t},\n\t\t\texpected: \"Hello Alice!\",\n\t\t},\n\t\t{\n\t\t\tname:     \"concat_empty\",\n\t\t\ttemplate: `{{ concat }}`,\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"printf_basic\",\n\t\t\ttemplate: `{{ printf \"Hello %s!\" \"World\" }}`,\n\t\t\texpected: \"Hello World!\",\n\t\t},\n\t\t{\n\t\t\tname:     \"printf_multiple_args\",\n\t\t\ttemplate: `{{ printf \"%s has %s items\" \"Cart\" \"5\" }}`,\n\t\t\texpected: \"Cart has 5 items\",\n\t\t},\n\t\t{\n\t\t\tname:     \"string_helper\",\n\t\t\ttemplate: `{{ string \"test\" }}`,\n\t\t\texpected: \"test\",\n\t\t},\n\t\t{\n\t\t\tname:     \"trim_helper\",\n\t\t\ttemplate: `{{ trim \"  spaced  \" }}`,\n\t\t\texpected: \"spaced\",\n\t\t},\n\t\t{\n\t\t\tname:     \"index_numeric\",\n\t\t\ttemplate: `{{ index \"array\" \"0\" }}`,\n\t\t\texpected: \"[0]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"index_string\",\n\t\t\ttemplate: `{{ index \"map\" \"key\" }}`,\n\t\t\texpected: \"[key]\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := NewRenderer()\n\t\t\tgot := r.Render(tt.template, tt.data)\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"\\nTemplate: %s\\nExpected: %q\\nGot: %q\", tt.template, tt.expected, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHelperErrors(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\ttemplate string\n\t}{\n\t\t{\n\t\t\tname:     \"unknown_helper\",\n\t\t\ttemplate: `{{ Unknown \"test\" }}`,\n\t\t},\n\t\t{\n\t\t\tname:     \"missing_argument\",\n\t\t\ttemplate: `{{ Bold }}`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := NewRenderer()\n\t\t\tgot := r.Render(tt.template, nil)\n\t\t\t// Should not panic and should return some result\n\t\t\tif got == \"\" {\n\t\t\t\tt.Error(\"Expected non-empty result even with errors\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestControlFlow(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\ttemplate string\n\t\tdata     map[string]interface{}\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"simple_range\",\n\t\t\ttemplate: `{{ range .Items }}{{ . }}{{ end }}`,\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Items\": []string{\"a\", \"b\", \"c\"},\n\t\t\t},\n\t\t\texpected: \"abc\",\n\t\t},\n\t\t{\n\t\t\tname:     \"range_with_index\",\n\t\t\ttemplate: `{{ range .Items }}[{{ . }}]{{ end }}`,\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Items\": []int{1, 2, 3},\n\t\t\t},\n\t\t\texpected: \"[1][2][3]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"range_with_field\",\n\t\t\ttemplate: \"{{ range .Objects }}[{{ .Name }}]{{ end }}\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Objects\": []map[string]interface{}{\n\t\t\t\t\t{\"Name\": \"obj1\"},\n\t\t\t\t\t{\"Name\": \"obj2\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"[obj1][obj2]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"range_with_helpers\",\n\t\t\ttemplate: `{{ range .Items }}{{ Bold . }}{{ end }}`,\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Items\": []string{\"a\", \"b\", \"c\"},\n\t\t\t},\n\t\t\texpected: \"**a****b****c**\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Nested Range\",\n\t\t\ttemplate: \"{{ range .Outer }}{{ range .Inner }}{{ . }}{{ end }}{{ end }}\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Outer\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\"Inner\": []interface{}{\"a\", \"b\"}},\n\t\t\t\t\tmap[string]interface{}{\"Inner\": []interface{}{\"c\", \"d\"}},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"abcd\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Range in If\",\n\t\t\ttemplate: \"{{ if .Show }}{{ range .Items }}{{ . }}{{ end }}{{ end }}\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Show\":  true,\n\t\t\t\t\"Items\": []interface{}{\"1\", \"2\", \"3\"},\n\t\t\t},\n\t\t\texpected: \"123\",\n\t\t},\n\t\t{\n\t\t\tname:     \"If in Range\",\n\t\t\ttemplate: \"{{ range .Items }}{{ if .Show }}{{ .Value }}{{ end }}{{ end }}\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Items\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\"Show\": true, \"Value\": \"x\"},\n\t\t\t\t\tmap[string]interface{}{\"Show\": false, \"Value\": \"y\"},\n\t\t\t\t\tmap[string]interface{}{\"Show\": true, \"Value\": \"z\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"xz\",\n\t\t},\n\t\t{\n\t\t\tname:     \"If in If\",\n\t\t\ttemplate: \"{{ if .Outer }}{{ if .Inner }}Yes{{ else }}No{{ end }}{{ else }}No{{ end }}\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"Outer\": true,\n\t\t\t\t\"Inner\": true,\n\t\t\t},\n\t\t\texpected: \"Yes\",\n\t\t},\n\t\t{\n\t\t\tname:     \"If in If in If\",\n\t\t\ttemplate: \"{{ if .First }}{{ if .Second }}{{ if .Third }}All True{{ else }}Third False{{ end }}{{ else }}Second False{{ end }}{{ else }}First False{{ end }}\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"First\":  true,\n\t\t\t\t\"Second\": true,\n\t\t\t\t\"Third\":  false,\n\t\t\t},\n\t\t\texpected: \"Third False\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := NewRenderer()\n\t\t\tgot := r.Render(tt.template, tt.data)\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"\\nTemplate: %s\\nData: %v\\nExpected: %q\\nGot: %q\", tt.template, tt.data, tt.expected, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\n"},{"name":"z1_filetest.gno","body":"package main\n\nimport \"gno.land/p/moul/template/v0\"\n\nfunc main() {\n\tmarkdownTemplate := `{{ H1 \"Welcome to {{ .Name }}'s Page!\" }}\n\n{{ Bold \"Skills\" -}}\n{{- range .Skills }}\n{{ BulletItem . -}}\n{{- end }}\n\n{{ if .ShowProjects -}}\n{{ H2 \"Projects\" }}\n{{- range .Projects }}\n{{ H3 .Name }}\n{{ Paragraph .Description }}\n{{- if .HasDemo }}\n{{ Link \"View Demo\" .DemoURL }}\n{{- end }}\n{{- end }}\n{{- end }}\n\n{{ H2 \"Contact Information\" }}\n{{- range .Contacts }}\n{{ BulletItem (printf \"%s: %s\" .Platform .Value) -}}\n{{- end }}\n\n{{ H2 \"Recent Posts\" }}\n{{- if .HasPosts }}\n{{- range .RecentPosts }}\n{{ H3 .Title }}\n{{ Italic .Date }}\n{{ Paragraph .Summary }}\n{{- if .HasComments }}\n{{ Blockquote (printf \"Latest comment: %s\" (index .Comments 0)) }}\n{{- end }}\n{{ HorizontalRule -}}\n{{- end }}\n{{- end }}`\n\n\tdata := map[string]interface{}{\n\t\t\"Name\": \"Alice\",\n\t\t\"Skills\": []interface{}{\n\t\t\t\"Go Programming\",\n\t\t\t\"Smart Contracts\",\n\t\t\t\"Blockchain Development\",\n\t\t\t\"System Architecture\",\n\t\t},\n\t\t\"ShowProjects\": true,\n\t\t\"Projects\": []interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"Name\":        \"Gno Templates\",\n\t\t\t\t\"Description\": \"A template engine for Gno\",\n\t\t\t\t\"HasDemo\":     true,\n\t\t\t\t\"DemoURL\":     \"https://example.com/demo\",\n\t\t\t},\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"Name\":        \"Blockchain Explorer\",\n\t\t\t\t\"Description\": \"A tool for exploring the Gno chain\",\n\t\t\t\t\"HasDemo\":     false,\n\t\t\t},\n\t\t},\n\t\t\"Contacts\": []interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"Platform\": \"Email\",\n\t\t\t\t\"Value\":    \"alice@gno.land\",\n\t\t\t},\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"Platform\": \"GitHub\",\n\t\t\t\t\"Value\":    \"@alice\",\n\t\t\t},\n\t\t},\n\t\t\"HasPosts\": true,\n\t\t\"RecentPosts\": []interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"Title\":       \"Getting Started with Gno\",\n\t\t\t\t\"Date\":        \"2024-03-20\",\n\t\t\t\t\"Summary\":     \"A beginner's guide to Gno development\",\n\t\t\t\t\"HasComments\": true,\n\t\t\t\t\"Comments\":    []interface{}{\"Great article!\", \"Very helpful\"},\n\t\t\t},\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"Title\":       \"Advanced Template Techniques\",\n\t\t\t\t\"Date\":        \"2024-03-19\",\n\t\t\t\t\"Summary\":     \"Deep dive into Gno templates\",\n\t\t\t\t\"HasComments\": false,\n\t\t\t},\n\t\t},\n\t}\n\n\trenderer := template.NewRenderer()\n\toutput := renderer.Render(markdownTemplate, data)\n\tprintln(output)\n}\n\n// Output:\n// # Welcome to Alice's Page!\n//\n//\n// **Skills**\n// - Go Programming\n//\n// - Smart Contracts\n//\n// - Blockchain Development\n//\n// - System Architecture\n//\n//\n//\n// ## Projects\n// ### Gno Templates\n//\n// A template engine for Gno\n// [View Demo](https://example.com/demo)\n//\n//\n// ### Blockchain Explorer\n//\n// A tool for exploring the Gno chain\n//\n// ## Contact Information\n// - Email: alice@gno.land\n//\n// - GitHub: @alice\n//\n//\n// ## Recent Posts\n// ### Getting Started with Gno\n//\n// *2024-03-20*\n// A beginner's guide to Gno development\n//\n// \u003e Latest comment: Great article!\n//\n//\n//\n// ---\n//\n// ### Advanced Template Techniques\n//\n// *2024-03-19*\n// Deep dive into Gno templates\n// ---\n"}]},"send":"","max_deposit":"11000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"udao","path":"gno.land/p/moul/udao/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/udao`\n\nMinimal DAO interfaces, written from the **outside**. `udao` deliberately does\nnot expose members or votes: those are implementation details that differ per\nDAO and that non-members cannot act on anyway. What it exposes is the part an\noutside observer needs: which proposals exist and where they stand.\n\n```go\ntype DAO interface {\n\tPropose(prop Proposal) (uint64, error)\n\tGetProposal(id uint64) (Proposal, error)\n\tGetProposalStatus(id uint64) (ProposalStatus, error)\n\tExecute(id uint64) error\n}\n```\n\n`ProposalState` is the lifecycle: `Pending`, `Active`, `Passed`, `Rejected`,\n`Executed`, `Expired`.\n\n## Constraints\n\nThe composable half of the package. A proposal can carry constraints, and\n`ValidateConstraints` reports whether all of them hold, returning the list of\nreasons when they do not:\n\n```go\nfunc ValidateConstraints(p Proposal) (bool, []string)\n```\n\nThat is what lets DAO behaviour be assembled from parts (a quorum constraint, a\ntime-window constraint, a whitelist constraint) instead of baked into one\nimplementation.\n\nThis package is interfaces plus `ValidateConstraints`; it has no DAO of its\nown. [`p/moul/xdao`](../xdao) is a (partial) implementation of it.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/udao/v0\"\ngno = \"0.9\"\n"},{"name":"udao.gno","body":"// Package udao defines minimal interfaces for Decentralized Autonomous Organizations (DAOs).\n// It intentionally does not expose members and votes, as these details are implementation-specific.\n// Instead, it focuses on providing an external view of proposals and their statuses,\n// which is what non-members and non-voters typically care about.\n//\n// The package is designed to allow for composable DAO patterns, enabling flexible\n// and modular implementations of various DAO structures and behaviors.\npackage udao\n\n// DAO defines a minimal interface for a Decentralized Autonomous Organization\n// from an external point of view, hiding the internal details of members and voting.\ntype DAO interface {\n\t// Propose submits a new proposal to the DAO\n\tPropose(prop Proposal) (id uint64, err error)\n\n\t// GetProposalStatus retrieves the current status and metrics of a specific proposal\n\tGetProposalStatus(id uint64) (ProposalStatus, error)\n\n\t// Execute attempts to execute a proposal if it has passed\n\tExecute(id uint64) error\n\n\t// GetProposal retrieves the details of a specific proposal\n\tGetProposal(id uint64) (Proposal, error)\n\n\t// XXX: find a smart way to list proposals\n\t// // ListProposalss retrieves a list of Proposals with pagination and optional filters\n\t// ListDAOs(offset, limit int, filters ...ProposalFilter) ([]DAO, error)\n}\n\n// Proposal defines the interface for a DAO proposal\ntype Proposal interface {\n\tTitle() string\n\tBody() string\n\tConstraints() []Constraint\n}\n\n// ProposalStatus represents the current status and metrics of a proposal\ntype ProposalStatus struct {\n\t// status\n\tState ProposalState\n\n\t// metrics\n\tYeaPercentage      float64\n\tNayPercentage      float64\n\tNonVoterPercentage float64\n\t// XXX: other metrics?\n}\n\n// ProposalState represents the current state of a proposal\ntype ProposalState int\n\nconst (\n\tPending ProposalState = iota\n\tActive\n\tPassed\n\tRejected\n\tExecuted\n\tExpired // XXX: better name for when it's expired but not because of time?\n)\n\n// Constraint defines an interface for proposal constraints\ntype Constraint interface {\n\tValidate() (bool, string)\n\tDescription() string\n}\n\n// ValidateConstraints checks if all constraints of a proposal are met\nfunc ValidateConstraints(p Proposal) (bool, []string) {\n\tvar unmetReasons []string\n\tfor _, constraint := range p.Constraints() {\n\t\tvalid, reason := constraint.Validate()\n\t\tif !valid {\n\t\t\tunmetReasons = append(unmetReasons, reason)\n\t\t}\n\t}\n\treturn len(unmetReasons) == 0, unmetReasons\n}\n"},{"name":"udao_test.gno","body":"package udao\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// stubConstraint is a Constraint whose verdict is fixed at construction.\ntype stubConstraint struct {\n\tok     bool\n\treason string\n\tdesc   string\n}\n\nfunc (c stubConstraint) Validate() (bool, string) { return c.ok, c.reason }\nfunc (c stubConstraint) Description() string      { return c.desc }\n\n// stubProposal is a Proposal carrying an arbitrary constraint list.\ntype stubProposal struct {\n\ttitle, body string\n\tconstraints []Constraint\n}\n\nfunc (p stubProposal) Title() string             { return p.title }\nfunc (p stubProposal) Body() string              { return p.body }\nfunc (p stubProposal) Constraints() []Constraint { return p.constraints }\n\nfunc TestValidateConstraintsAllMet(t *testing.T) {\n\tp := stubProposal{constraints: []Constraint{\n\t\tstubConstraint{ok: true},\n\t\tstubConstraint{ok: true},\n\t}}\n\n\tok, reasons := ValidateConstraints(p)\n\tuassert.True(t, ok, \"every constraint met\")\n\tuassert.Equal(t, 0, len(reasons))\n}\n\nfunc TestValidateConstraintsNoConstraints(t *testing.T) {\n\t// A proposal with no constraints is vacuously valid.\n\tok, reasons := ValidateConstraints(stubProposal{})\n\tuassert.True(t, ok, \"no constraints means nothing unmet\")\n\tuassert.Equal(t, 0, len(reasons))\n}\n\nfunc TestValidateConstraintsCollectsEveryFailure(t *testing.T) {\n\tp := stubProposal{constraints: []Constraint{\n\t\tstubConstraint{ok: false, reason: \"quorum not reached\"},\n\t\tstubConstraint{ok: true, reason: \"ignored when valid\"},\n\t\tstubConstraint{ok: false, reason: \"voting still open\"},\n\t}}\n\n\tok, reasons := ValidateConstraints(p)\n\tuassert.False(t, ok, \"one unmet constraint invalidates the proposal\")\n\t// It reports *all* failures, not just the first, and in order.\n\tuassert.Equal(t, 2, len(reasons))\n\tuassert.Equal(t, \"quorum not reached\", reasons[0])\n\tuassert.Equal(t, \"voting still open\", reasons[1])\n}\n\nfunc TestValidateConstraintsIgnoresReasonWhenValid(t *testing.T) {\n\tp := stubProposal{constraints: []Constraint{\n\t\tstubConstraint{ok: true, reason: \"should not be collected\"},\n\t}}\n\n\tok, reasons := ValidateConstraints(p)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 0, len(reasons))\n}\n\n// TestProposalStateValues pins the iota block: these states are likely to be\n// persisted or compared numerically, so inserting one in the middle is breaking.\nfunc TestProposalStateValues(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tgot  ProposalState\n\t\twant int\n\t}{\n\t\t{\"Pending\", Pending, 0},\n\t\t{\"Active\", Active, 1},\n\t\t{\"Passed\", Passed, 2},\n\t\t{\"Rejected\", Rejected, 3},\n\t\t{\"Executed\", Executed, 4},\n\t\t{\"Expired\", Expired, 5},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, int(c.got), c.name)\n\t}\n}\n\n// TestProposalStatusZeroValue documents that a zero ProposalStatus reads as a\n// Pending proposal with no recorded votes.\nfunc TestProposalStatusZeroValue(t *testing.T) {\n\tvar s ProposalStatus\n\tuassert.Equal(t, int(Pending), int(s.State))\n\tuassert.True(t, s.YeaPercentage == 0.0, \"no yea votes recorded\")\n\tuassert.True(t, s.NayPercentage == 0.0, \"no nay votes recorded\")\n\tuassert.True(t, s.NonVoterPercentage == 0.0, \"no non-voters recorded\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lplist","path":"gno.land/p/moul/ulist/lplist/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/ulist/lplist/v0`\n\n`LayeredProxyList` — a layered proxy over [`ulist`](../../v0) enabling **lazy,\nappend-only schema migration**: it wraps a source list with a target list and\ntransforms source entries only when accessed (source stays immutable), and layers\ncan be chained for multi-step migrations. Nested under `ulist` in the monorepo; it\nwas missed on the original `ulist` import.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/ulist/lplist/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/ulist/lplist/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/ulist/lplist/v0\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"lplist.gno","body":"// Package lplist provides a layered proxy implementation for lists that allows transparent\n// migration of data between different schema versions.\n//\n// LayeredProxyList wraps an existing list (source) with a new list (target) and optionally\n// applies migrations to source data when it's accessed. This enables schema evolution without\n// requiring upfront migration of all data, making it ideal for large datasets or when\n// preserving original data is important.\n//\n// Key features:\n// - Lazy migration: Data is only transformed when accessed, not stored in migrated form\n// - Append-only source: Source data is treated as immutable to preserve original data\n// - Chaining: Multiple LayeredProxyLists can be stacked for multi-step migrations\n//\n// Example usage:\n//\n//\t// Define data types for different schema versions\n//\ttype UserV1 struct {\n//\t    Name string\n//\t    Age int\n//\t}\n//\n//\ttype UserV2 struct {\n//\t    FullName string\n//\t    Age int\n//\t    Active bool\n//\t}\n//\n//\t// Create source list with old schema\n//\tsourceList := ulist.New()\n//\tsourceList.Append(\n//\t    UserV1{Name: \"Alice\", Age: 30},\n//\t    UserV1{Name: \"Bob\", Age: 25},\n//\t)\n//\n//\t// Define migration function from V1 to V2\n//\tmigrateUserV1ToV2 := func(v any) any {\n//\t    user := v.(UserV1)\n//\t    return UserV2{\n//\t        FullName: user.Name,  // Name field renamed to FullName\n//\t        Age: user.Age,\n//\t        Active: true,         // New field with default value\n//\t    }\n//\t}\n//\n//\t// Create layered proxy with migration\n//\tproxy := NewLayeredProxyList(sourceList, migrateUserV1ToV2)\n//\n//\t// Add new data directly in V2 format\n//\tproxy.Append(UserV2{FullName: \"Charlie\", Age: 40, Active: false})\n//\n//\t// All access through proxy returns data in V2 format\n//\tfor i := 0; i \u003c proxy.Size(); i++ {\n//\t    user := proxy.Get(i).(UserV2)\n//\t    fmt.Printf(\"User: %s, Age: %d, Active: %t\\n\", user.FullName, user.Age, user.Active)\n//\t}\npackage lplist\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/moul/ulist/v0\"\n)\n\n// MigratorFn is a function type that lazily converts values from source to target\ntype MigratorFn func(any) any\n\n// LayeredProxyList represents a wrapper around an existing List that handles migration\ntype LayeredProxyList struct {\n\tsource       ulist.IList\n\ttarget       *ulist.List\n\tmigrator     MigratorFn\n\tsourceHeight int // Store initial source size to optimize lookups\n}\n\n// NewLayeredProxyList creates a new LayeredProxyList instance that wraps an existing List\nfunc NewLayeredProxyList(source ulist.IList, migrator MigratorFn) *LayeredProxyList {\n\tsourceHeight := source.TotalSize()\n\ttarget := ulist.New()\n\treturn \u0026LayeredProxyList{\n\t\tsource:       source,\n\t\ttarget:       target,\n\t\tmigrator:     migrator,\n\t\tsourceHeight: sourceHeight,\n\t}\n}\n\n// Get retrieves the value at the specified index\n// Uses sourceHeight to efficiently route requests\nfunc (l *LayeredProxyList) Get(index int) any {\n\tif index \u003c l.sourceHeight {\n\t\t// Direct access to source for indices below sourceHeight\n\t\tval := l.source.Get(index)\n\t\tif val == nil {\n\t\t\treturn nil\n\t\t}\n\t\t// Only apply migrator if it exists\n\t\tif l.migrator != nil {\n\t\t\treturn l.migrator(val)\n\t\t}\n\t\treturn val\n\t}\n\t// For indices \u003e= sourceHeight, adjust index to be relative to target list starting at 0\n\ttargetIndex := index - l.sourceHeight\n\treturn l.target.Get(targetIndex)\n}\n\n// Append adds one or more values to the target list\nfunc (l *LayeredProxyList) Append(values ...any) {\n\tl.target.Append(values...)\n}\n\n// Delete marks elements as deleted in the appropriate list\nfunc (l *LayeredProxyList) Delete(indices ...int) error {\n\tfor _, index := range indices {\n\t\tif index \u003c l.sourceHeight {\n\t\t\terr := l.source.Delete(index)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, index := range indices {\n\t\ttargetIndex := index - l.sourceHeight\n\t\terr := l.target.Delete(targetIndex)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// Size returns the total number of active elements\nfunc (l *LayeredProxyList) Size() int {\n\treturn l.source.Size() + l.target.Size()\n}\n\n// TotalSize returns the total number of elements in the list\nfunc (l *LayeredProxyList) TotalSize() int {\n\treturn l.sourceHeight + l.target.TotalSize()\n}\n\n// MustDelete deletes elements, panicking on error\nfunc (l *LayeredProxyList) MustDelete(indices ...int) {\n\tif err := l.Delete(indices...); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// MustGet retrieves a value, panicking if not found\nfunc (l *LayeredProxyList) MustGet(index int) any {\n\tval := l.Get(index)\n\tif val == nil {\n\t\tpanic(ulist.ErrDeleted)\n\t}\n\treturn val\n}\n\n// GetRange returns elements between start and end indices\nfunc (l *LayeredProxyList) GetRange(start, end int) []ulist.Entry {\n\tvar entries []ulist.Entry\n\tl.Iterator(start, end, func(index int, value any) bool {\n\t\tentries = append(entries, ulist.Entry{Index: index, Value: value})\n\t\treturn false\n\t})\n\treturn entries\n}\n\n// GetRangeByOffset returns elements starting from offset\nfunc (l *LayeredProxyList) GetRangeByOffset(offset int, count int) []ulist.Entry {\n\tvar entries []ulist.Entry\n\tl.IteratorByOffset(offset, count, func(index int, value any) bool {\n\t\tentries = append(entries, ulist.Entry{Index: index, Value: value})\n\t\treturn false\n\t})\n\treturn entries\n}\n\n// Iterator performs iteration between start and end indices\nfunc (l *LayeredProxyList) Iterator(start, end int, cb ulist.IterCbFn) bool {\n\t// For empty list or invalid range\n\tif start \u003c 0 \u0026\u0026 end \u003c 0 {\n\t\treturn false\n\t}\n\n\t// Normalize indices\n\tif start \u003c 0 {\n\t\tstart = 0\n\t}\n\tif end \u003c 0 {\n\t\tend = 0\n\t}\n\n\ttotalSize := l.TotalSize()\n\tif end \u003e= totalSize {\n\t\tend = totalSize - 1\n\t}\n\tif start \u003e= totalSize {\n\t\tstart = totalSize - 1\n\t}\n\n\t// Handle reverse iteration\n\tif start \u003e end {\n\t\tfor i := start; i \u003e= end; i-- {\n\t\t\tval := l.Get(i)\n\t\t\tif val != nil {\n\t\t\t\tif cb(i, val) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// Handle forward iteration\n\tfor i := start; i \u003c= end; i++ {\n\t\tval := l.Get(i)\n\t\tif val != nil {\n\t\t\tif cb(i, val) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n// IteratorByOffset performs iteration starting from offset\nfunc (l *LayeredProxyList) IteratorByOffset(offset int, count int, cb ulist.IterCbFn) bool {\n\tif count == 0 {\n\t\treturn false\n\t}\n\n\t// Normalize offset\n\tif offset \u003c 0 {\n\t\toffset = 0\n\t}\n\ttotalSize := l.TotalSize()\n\tif offset \u003e= totalSize {\n\t\toffset = totalSize - 1\n\t}\n\n\t// Determine end based on count direction\n\tvar end int\n\tif count \u003e 0 {\n\t\tend = totalSize - 1\n\t} else {\n\t\tend = 0\n\t}\n\n\twrapperReturned := false\n\n\t// Calculate absolute value manually instead of using abs function\n\tremaining := count\n\tif remaining \u003c 0 {\n\t\tremaining = -remaining\n\t}\n\n\twrapper := func(index int, value any) bool {\n\t\tif remaining \u003c= 0 {\n\t\t\twrapperReturned = true\n\t\t\treturn true\n\t\t}\n\t\tremaining--\n\t\treturn cb(index, value)\n\t}\n\n\tret := l.Iterator(offset, end, wrapper)\n\tif wrapperReturned {\n\t\treturn false\n\t}\n\treturn ret\n}\n\n// Set updates the value at the specified index\nfunc (l *LayeredProxyList) Set(index int, value any) error {\n\tif index \u003c l.sourceHeight {\n\t\t// Cannot modify source list directly\n\t\treturn errors.New(\"cannot modify source list directly\")\n\t}\n\n\t// Adjust index to be relative to target list starting at 0\n\ttargetIndex := index - l.sourceHeight\n\treturn l.target.Set(targetIndex, value)\n}\n\n// MustSet updates the value at the specified index, panicking on error\nfunc (l *LayeredProxyList) MustSet(index int, value any) {\n\tif err := l.Set(index, value); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// GetByOffset returns elements starting from offset with count determining direction\nfunc (l *LayeredProxyList) GetByOffset(offset int, count int) []ulist.Entry {\n\tvar entries []ulist.Entry\n\tl.IteratorByOffset(offset, count, func(index int, value any) bool {\n\t\tentries = append(entries, ulist.Entry{Index: index, Value: value})\n\t\treturn false\n\t})\n\treturn entries\n}\n\n// Verify that LayeredProxyList implements IList\nvar _ ulist.IList = (*LayeredProxyList)(nil)\n"},{"name":"lplist_test.gno","body":"package lplist\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/ulist/v0\"\n)\n\n// TestLayeredProxyListBasicOperations tests the basic operations of LayeredProxyList\nfunc TestLayeredProxyListBasicOperations(t *testing.T) {\n\t// Create source list with initial data\n\tsource := ulist.New()\n\tsource.Append(1, 2, 3)\n\n\t// Create proxy list with a simple multiplier migrator\n\tmigrator := func(v any) any {\n\t\treturn v.(int) * 2\n\t}\n\tproxy := NewLayeredProxyList(source, migrator)\n\n\t// Test initial state\n\tif got := proxy.Size(); got != 3 {\n\t\tt.Errorf(\"initial Size() = %v, want %v\", got, 3)\n\t}\n\tif got := proxy.TotalSize(); got != 3 {\n\t\tt.Errorf(\"initial TotalSize() = %v, want %v\", got, 3)\n\t}\n\n\t// Test Get with migration\n\ttests := []struct {\n\t\tindex int\n\t\twant  any\n\t}{\n\t\t{0, 2}, // 1 * 2\n\t\t{1, 4}, // 2 * 2\n\t\t{2, 6}, // 3 * 2\n\t}\n\n\tfor _, tt := range tests {\n\t\tif got := proxy.Get(tt.index); got != tt.want {\n\t\t\tt.Errorf(\"Get(%v) = %v, want %v\", tt.index, got, tt.want)\n\t\t}\n\t}\n\n\t// Test Append to target\n\tproxy.Append(7, 8)\n\tif got := proxy.Size(); got != 5 {\n\t\tt.Errorf(\"Size() after append = %v, want %v\", got, 5)\n\t}\n\n\t// Test Get from target (no migration)\n\tif got := proxy.Get(3); got != 7 {\n\t\tt.Errorf(\"Get(3) = %v, want %v\", got, 7)\n\t}\n}\n\n// TestLayeredProxyListDelete tests delete operations\nfunc TestLayeredProxyListDelete(t *testing.T) {\n\tsource := ulist.New()\n\tsource.Append(1, 2, 3)\n\tproxy := NewLayeredProxyList(source, nil)\n\tproxy.Append(4, 5)\n\n\t// Test deleting from source (should fail)\n\tif err := proxy.Delete(1); err == nil {\n\t\tt.Error(\"Delete from source should return error\")\n\t}\n\n\t// Test deleting from target (should succeed)\n\tif err := proxy.Delete(3); err != nil {\n\t\tt.Errorf(\"Delete from target failed: %s\", err.Error())\n\t}\n\n\t// After deletion, the value might be undefined rather than nil\n\t// Check that it's not equal to the original value\n\tif got := proxy.Get(3); got == 5 {\n\t\tt.Errorf(\"Get(3) after delete = %v, want it to be deleted\", got)\n\t}\n}\n\n// TestLayeredProxyListIteration tests iteration methods\nfunc TestLayeredProxyListIteration(t *testing.T) {\n\tsource := ulist.New()\n\tsource.Append(1, 2, 3)\n\tproxy := NewLayeredProxyList(source, nil)\n\tproxy.Append(4, 5)\n\n\t// Test GetRange\n\tentries := proxy.GetRange(0, 4)\n\tif len(entries) != 5 {\n\t\tt.Errorf(\"GetRange returned %v entries, want 5\", len(entries))\n\t}\n\n\t// Test reverse iteration\n\tentries = proxy.GetRange(4, 0)\n\tif len(entries) != 5 {\n\t\tt.Errorf(\"Reverse GetRange returned %v entries, want 5\", len(entries))\n\t}\n\n\t// Test IteratorByOffset with positive count\n\tvar values []any\n\tproxy.IteratorByOffset(1, 3, func(index int, value any) bool {\n\t\tvalues = append(values, value)\n\t\treturn false\n\t})\n\tif len(values) != 3 {\n\t\tt.Errorf(\"IteratorByOffset returned %v values, want 3\", len(values))\n\t}\n}\n\n// TestLayeredProxyListMustOperations tests must operations\nfunc TestLayeredProxyListMustOperations(t *testing.T) {\n\tsource := ulist.New()\n\tsource.Append(1, 2)\n\tproxy := NewLayeredProxyList(source, nil)\n\n\t// Test MustGet success\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Errorf(\"MustGet panicked unexpectedly: %v\", r)\n\t\t}\n\t}()\n\tif got := proxy.MustGet(1); got != 2 {\n\t\tt.Errorf(\"MustGet(1) = %v, want 2\", got)\n\t}\n\n\t// Test MustGet panic\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"MustGet should have panicked\")\n\t\t}\n\t}()\n\tproxy.MustGet(99) // Should panic\n}\n\n// TestLayeredProxyListWithNilMigrator tests behavior without a migrator\nfunc TestLayeredProxyListWithNilMigrator(t *testing.T) {\n\tsource := ulist.New()\n\tsource.Append(1, 2)\n\tproxy := NewLayeredProxyList(source, nil)\n\n\tif got := proxy.Get(0); got != 1 {\n\t\tt.Errorf(\"Get(0) with nil migrator = %v, want 1\", got)\n\t}\n}\n\n// TestLayeredProxyListEmpty tests operations on empty lists\nfunc TestLayeredProxyListEmpty(t *testing.T) {\n\tsource := ulist.New()\n\tproxy := NewLayeredProxyList(source, nil)\n\n\tif got := proxy.Size(); got != 0 {\n\t\tt.Errorf(\"Size() of empty list = %v, want 0\", got)\n\t}\n\n\tif got := proxy.Get(0); got != nil {\n\t\tt.Errorf(\"Get(0) of empty list = %v, want nil\", got)\n\t}\n\n\tentries := proxy.GetRange(0, 10)\n\tif len(entries) != 0 {\n\t\tt.Errorf(\"GetRange on empty list returned %v entries, want 0\", len(entries))\n\t}\n}\n\n// TestLayeredProxyListChaining tests chaining of layered proxies with struct migrations\nfunc TestLayeredProxyListChaining(t *testing.T) {\n\t// Define struct types for different versions\n\ttype v1 struct {\n\t\tnamev1 string\n\t}\n\ttype v2 struct {\n\t\tnamev2 string\n\t}\n\ttype v3 struct {\n\t\tnamev3 string\n\t}\n\n\t// Create source list with v1 objects\n\tsource := ulist.New()\n\tsource.Append(v1{namev1: \"object1\"}, v1{namev1: \"object2\"})\n\n\t// Migration function from v1 to v2\n\tv1Tov2 := func(v any) any {\n\t\tobj := v.(v1)\n\t\treturn v2{namev2: obj.namev1 + \"_v2\"}\n\t}\n\n\t// Create first proxy with v1-\u003ev2 migration\n\tproxyV2 := NewLayeredProxyList(source, v1Tov2)\n\tproxyV2.Append(v2{namev2: \"direct_v2\"})\n\n\t// Migration function from v2 to v3\n\tv2Tov3 := func(v any) any {\n\t\tobj := v.(v2)\n\t\treturn v3{namev3: obj.namev2 + \"_v3\"}\n\t}\n\n\t// Create second proxy with v2-\u003ev3 migration, using the first proxy as source\n\tproxyV3 := NewLayeredProxyList(proxyV2, v2Tov3)\n\tproxyV3.Append(v3{namev3: \"direct_v3\"})\n\n\t// Verify sizes\n\tif got := proxyV3.Size(); got != 4 {\n\t\tt.Errorf(\"proxyV3.Size() = %v, want 4\", got)\n\t}\n\n\t// Test that all objects are correctly migrated when accessed through proxyV3\n\texpected := []struct {\n\t\tindex int\n\t\tname  string\n\t}{\n\t\t{0, \"object1_v2_v3\"}, // v1 -\u003e v2 -\u003e v3\n\t\t{1, \"object2_v2_v3\"}, // v1 -\u003e v2 -\u003e v3\n\t\t{2, \"direct_v2_v3\"},  // v2 -\u003e v3\n\t\t{3, \"direct_v3\"},     // v3 (no migration)\n\t}\n\n\tfor _, tt := range expected {\n\t\tobj := proxyV3.Get(tt.index).(v3)\n\t\tif obj.namev3 != tt.name {\n\t\t\tt.Errorf(\"proxyV3.Get(%d).namev3 = %v, want %v\", tt.index, obj.namev3, tt.name)\n\t\t}\n\t}\n\n\t// Verify getting items from middle layer (proxyV2)\n\tmiddleExpected := []struct {\n\t\tindex int\n\t\tname  string\n\t}{\n\t\t{0, \"object1_v2\"}, // v1 -\u003e v2\n\t\t{1, \"object2_v2\"}, // v1 -\u003e v2\n\t\t{2, \"direct_v2\"},  // v2 (no migration)\n\t}\n\n\tfor _, tt := range middleExpected {\n\t\tobj := proxyV2.Get(tt.index).(v2)\n\t\tif obj.namev2 != tt.name {\n\t\t\tt.Errorf(\"proxyV2.Get(%d).namev2 = %v, want %v\", tt.index, obj.namev2, tt.name)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ulist","path":"gno.land/p/moul/ulist/v1","files":[{"name":"README.md","body":"# `gno.land/p/moul/ulist/v1`\n\nAppend-only list backed by a binary tree, with index-preserving compaction.\n\nAn index is the element's position in the tree, so `Delete` is a *soft* delete:\nit clears the data and leaves the node, because moving a live element would\nsilently invalidate an index another realm is holding. That leaves reclaimable\nstorage behind, and on gno.land storage is money: every byte of realm state\nlocks GNOT, refunded to whoever signs the transaction that frees it.\n\n`v1` adds the pair that turns those dead nodes back into a refund:\n\n| | |\n|---|---|\n| `Compactable() int` | how many nodes a compaction would free, **right now, for free**. Reads nothing, mutates nothing, so a caller can poll it before paying gas |\n| `Compact() int` | frees every node whose subtree holds no live element, and returns how many. Nothing live moves, so every index stays valid and `TotalSize` is unchanged |\n\n### Which deletions can be compacted, which cannot\n\nIndex 0 is the root and index `i` sits at depth `bitlen(i+1)-1`, so **the oldest\nindices are the ancestors of the newest.** A node is only freeable when its\nwhole subtree is dead, which gives a result worth knowing before you design\naround this:\n\n| You delete | `Compactable` | Why |\n|---|---|---|\n| the oldest entries | **0**, always | every newer entry keeps their ancestors alive |\n| the newest entries | immediately non-zero | they are the leaves |\n\nMeasured on chain with 32 entries of 512 bytes: deleting the oldest 16 refunded\n8,896 bytes and left nothing to compact. Deleting the newest 16 refunded the\nsame 8,896 bytes and then `Compact` returned **a further 27,679**, because a\nnode costs far more than the payload it holds. The structure is roughly two\nthirds of the total cost, so being unable to compact leaves most of the money\non the table.\n\n**So an expiry queue that reaps oldest-first can never compact**, which is the\nopposite of the intuition. Delete from the top down, or wait for a run of\ndeletions to reach the leaves. `Compactable` is free, so a caller never has to\nguess which case it is in.\n\n**`v1`, not an addition to `v0`, because one behaviour changes:** a soft-deleted\nelement can be restored with `Set`, but not once `Compact` has freed its node\nand the deposit has been refunded. `Set` on such an index returns\n`ErrOutOfBounds`. That is the trade the refund pays for.\n[`v0`](https://github.com/moul/gno-contracts/tree/f6d0693f5161db423c042a4fe7c78057593cff80/p/moul/ulist)\nis unchanged and still deployed: it is part of the gnoland1 genesis set.\n\nWhether compacting is worth its gas depends on the gas price of the day, which\na contract cannot know. [`p/moul/x/storagecost`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/storagecost)\nturns a `Compactable` count into a verdict in GNOT, and\n[`r/moul/x/reaper`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/reaper)\nis a realm that does it in public.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"compact.gno","body":"package ulist\n\n// Compaction: turning soft deletes back into refunded storage.\n//\n// Delete is a soft delete. It clears the element's data but leaves the tree\n// node in place, because the node's position IS the index: indices are the\n// public addressing scheme, and moving a live element would silently\n// invalidate an index some other realm is holding.\n//\n// That leaves reclaimable storage behind. On gno.land every byte of realm\n// state locks GNOT, refunded to whoever signs the transaction that frees it,\n// so those dead nodes are money sitting in the structure.\n//\n// Compact reclaims them without moving anything live, by dropping whole\n// subtrees that contain no live element. Nothing live moves, so every index\n// stays valid.\n//\n// # Which deletions can actually be compacted\n//\n// This is the counterintuitive part, and it decides whether compaction is\n// worth anything at all. Index 0 is the root and index i sits at depth\n// bitlen(i+1)-1, so the OLDEST indices are the ANCESTORS of the newest. A node\n// is only freeable when its whole subtree is dead. Therefore:\n//\n//   - Deleting the oldest entries frees no nodes at all, however many you\n//     delete, because every newer entry keeps their ancestors alive. An expiry\n//     queue reaping oldest-first is exactly this case.\n//   - Deleting the newest entries frees nodes immediately, because they are\n//     the leaves.\n//\n// Measured on chain, 32 entries of 512 bytes each: deleting the oldest 16\n// refunded 8,896 bytes and left Compactable at zero. Deleting the newest 16\n// instead refunded the same 8,896 bytes and then Compact returned a further\n// 27,679, because a ulist node costs far more than the payload it holds. The\n// structure is roughly two thirds of the total cost, so being unable to\n// compact leaves most of the money on the table.\n//\n// The practical rule: compaction pays in proportion to how much of the\n// deepest layer is dead. Delete from the top down, or wait until a run of\n// deletions reaches the leaves.\n//\n// Whether it is worth doing is not a question this package can answer, since\n// it depends on the gas price of the day. Compactable reports the size of the\n// prize as a free read so a caller can decide; gno.land/p/moul/x/storagecost/v0\n// turns that count into a verdict in GNOT.\n\n// Compactable reports how many tree nodes Compact would free right now.\n//\n// It reads and mutates nothing, so a caller can poll it to decide whether\n// compaction is worth its gas before paying for it. Zero means every dead node\n// still shares a subtree with a live element, and compacting would cost gas to\n// free nothing.\nfunc (l *List) Compactable() int {\n\tif l == nil || l.root == nil {\n\t\treturn 0\n\t}\n\t// The root is never freed, so only its subtrees are counted.\n\tn, _ := prunableNodes(l.root)\n\treturn n\n}\n\n// Compact frees every tree node whose subtree holds no live element, and\n// returns the number of nodes freed.\n//\n// Indices are preserved exactly: TotalSize is unchanged, Size is unchanged,\n// and every live element keeps the index it had. Appends continue from the\n// same number.\n//\n// Deleted elements swept up by a Compact become permanently unrestorable:\n// Set on such an index returns ErrOutOfBounds where before it would have\n// restored the value. That is the trade the refund pays for, and it is the\n// reason this behaviour is v1 rather than an addition to v0.\nfunc (l *List) Compact() int {\n\tif l == nil || l.root == nil {\n\t\treturn 0\n\t}\n\t// The root is deliberately never freed. findNode treats a nil root as an\n\t// empty list and returns the root for every index, so a tree that still\n\t// has a totalSize but no root would write index 0 on the next append.\n\t// Keeping one node costs a few dozen bytes and keeps that unreachable.\n\tfreed, _ := pruneDead(l.root)\n\treturn freed\n}\n\n// pruneDead drops n's fully dead subtrees, returning how many nodes were freed\n// and whether n's own subtree is now dead. A dead subtree is one in which no\n// node holds data.\nfunc pruneDead(n *treeNode) (freed int, dead bool) {\n\tif n == nil {\n\t\treturn 0, true\n\t}\n\tleftFreed, leftDead := pruneDead(n.left)\n\trightFreed, rightDead := pruneDead(n.right)\n\tfreed = leftFreed + rightFreed\n\n\t// A dead child's own descendants have already been counted and unlinked by\n\t// the recursive call, so the child itself is the one node left to free.\n\tif leftDead \u0026\u0026 n.left != nil {\n\t\tn.left = nil\n\t\tfreed++\n\t}\n\tif rightDead \u0026\u0026 n.right != nil {\n\t\tn.right = nil\n\t\tfreed++\n\t}\n\treturn freed, n.data == nil \u0026\u0026 n.left == nil \u0026\u0026 n.right == nil\n}\n\n// prunableNodes is pruneDead without the mutation, so Compactable and Compact\n// can never disagree about the count.\nfunc prunableNodes(n *treeNode) (prunable int, dead bool) {\n\tif n == nil {\n\t\treturn 0, true\n\t}\n\tleftPrunable, leftDead := prunableNodes(n.left)\n\trightPrunable, rightDead := prunableNodes(n.right)\n\tprunable = leftPrunable + rightPrunable\n\n\tif leftDead \u0026\u0026 n.left != nil {\n\t\tprunable++\n\t}\n\tif rightDead \u0026\u0026 n.right != nil {\n\t\tprunable++\n\t}\n\treturn prunable, n.data == nil \u0026\u0026\n\t\t(n.left == nil || leftDead) \u0026\u0026\n\t\t(n.right == nil || rightDead)\n}\n"},{"name":"compact_test.gno","body":"package ulist\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// countNodes walks the tree directly, so the tests assert against the real\n// structure rather than against Compact's own bookkeeping.\nfunc countNodes(n *treeNode) int {\n\tif n == nil {\n\t\treturn 0\n\t}\n\treturn 1 + countNodes(n.left) + countNodes(n.right)\n}\n\nfunc TestCompactEmptyAndNil(t *testing.T) {\n\tvar nilList *List\n\tuassert.Equal(t, 0, nilList.Compactable())\n\tuassert.Equal(t, 0, nilList.Compact())\n\n\tl := New()\n\tuassert.Equal(t, 0, l.Compactable())\n\tuassert.Equal(t, 0, l.Compact())\n}\n\nfunc TestCompactNothingDeleted(t *testing.T) {\n\tl := New()\n\tl.Append(generateSequence(20)...)\n\tbefore := countNodes(l.root)\n\n\tuassert.Equal(t, 0, l.Compactable())\n\tuassert.Equal(t, 0, l.Compact())\n\tuassert.Equal(t, before, countNodes(l.root))\n\tuassert.Equal(t, 20, l.Size())\n\tuassert.Equal(t, 20, l.TotalSize())\n}\n\nfunc TestCompactFreesOnlyFullyDeadSubtrees(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsize    int\n\t\tdeleted []int\n\t}{\n\t\t{\"nothing deleted\", 16, nil},\n\t\t{\"one deleted\", 16, []int{9}},\n\t\t{\"leading run\", 32, []int{0, 1, 2, 3, 4, 5, 6, 7}},\n\t\t{\"trailing run\", 32, []int{24, 25, 26, 27, 28, 29, 30, 31}},\n\t\t{\"every other\", 32, []int{1, 3, 5, 7, 9, 11, 13, 15}},\n\t\t{\"all but one\", 16, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}},\n\t\t{\"all of them\", 16, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 14}},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := New()\n\t\t\tl.Append(generateSequence(tt.size)...)\n\t\t\tfor _, i := range tt.deleted {\n\t\t\t\tuassert.NoError(t, l.Delete(i))\n\t\t\t}\n\n\t\t\t// Every surviving element, recorded before the compaction.\n\t\t\tsurvivors := map[int]any{}\n\t\t\tfor i := 0; i \u003c tt.size; i++ {\n\t\t\t\tif v := l.Get(i); v != nil {\n\t\t\t\t\tsurvivors[i] = v\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpredicted := l.Compactable()\n\t\t\tnodesBefore := countNodes(l.root)\n\t\t\tfreed := l.Compact()\n\n\t\t\t// Compactable and Compact must agree, and both must match the tree.\n\t\t\tuassert.Equal(t, predicted, freed)\n\t\t\tuassert.Equal(t, nodesBefore-freed, countNodes(l.root))\n\n\t\t\t// A second pass has nothing left to do: Compact is idempotent.\n\t\t\tuassert.Equal(t, 0, l.Compactable())\n\t\t\tuassert.Equal(t, 0, l.Compact())\n\n\t\t\t// Indices are preserved: every survivor is still at its own index,\n\t\t\t// and the sizes are untouched.\n\t\t\tuassert.Equal(t, tt.size, l.TotalSize())\n\t\t\tuassert.Equal(t, len(survivors), l.Size())\n\t\t\tfor i, want := range survivors {\n\t\t\t\tuassert.Equal(t, want, l.Get(i))\n\t\t\t}\n\n\t\t\t// Appends continue from the same number.\n\t\t\tl.Append(\"after\")\n\t\t\tuassert.Equal(t, \"after\", l.Get(tt.size))\n\t\t\tuassert.Equal(t, tt.size+1, l.TotalSize())\n\t\t})\n\t}\n}\n\nfunc TestCompactNeverFreesTheRoot(t *testing.T) {\n\t// Index 0 is the root. Deleting everything must still leave it, or\n\t// findNode would treat the list as empty and write the next append to\n\t// index 0.\n\tl := New()\n\tl.Append(\"a\", \"b\", \"c\")\n\tuassert.NoError(t, l.Delete(0, 1, 2))\n\tl.Compact()\n\n\tuassert.True(t, l.root != nil)\n\tuassert.Equal(t, 1, countNodes(l.root))\n\tuassert.Equal(t, 0, l.Size())\n\tuassert.Equal(t, 3, l.TotalSize())\n\n\tl.Append(\"d\")\n\tuassert.Equal(t, \"d\", l.Get(3))\n\tuassert.Equal(t, nil, l.Get(0))\n}\n\nfunc TestCompactMakesDeletedElementsUnrestorable(t *testing.T) {\n\t// The documented behaviour change against v0: a soft-deleted element can\n\t// be restored with Set, but not once its node has been freed and the\n\t// storage deposit refunded.\n\tl := New()\n\tl.Append(generateSequence(8)...)\n\tuassert.NoError(t, l.Delete(4, 5, 6, 7))\n\n\t// Before compaction: restoring works.\n\tuassert.NoError(t, l.Set(5, \"restored\"))\n\tuassert.Equal(t, \"restored\", l.Get(5))\n\tuassert.NoError(t, l.Delete(5))\n\n\tuassert.True(t, l.Compact() \u003e 0)\n\n\t// After compaction: the node is gone, so there is nothing to restore.\n\tuassert.Error(t, l.Set(5, \"restored again\"))\n\tuassert.Equal(t, nil, l.Get(5))\n\t// And a live element is still perfectly settable.\n\tuassert.NoError(t, l.Set(1, \"still here\"))\n\tuassert.Equal(t, \"still here\", l.Get(1))\n}\n\nfunc TestCompactLeavesIterationUnchanged(t *testing.T) {\n\tcollect := func(l *List) []Entry {\n\t\tvar got []Entry\n\t\tl.Iterator(0, l.TotalSize()-1, func(i int, v any) bool {\n\t\t\tgot = append(got, Entry{Index: i, Value: v})\n\t\t\treturn false\n\t\t})\n\t\treturn got\n\t}\n\n\tl := New()\n\tl.Append(generateSequence(24)...)\n\tuassert.NoError(t, l.Delete(16, 17, 18, 19, 20, 21, 22, 23))\n\n\tbefore := collect(l)\n\tl.Compact()\n\tafter := collect(l)\n\n\tuassert.Equal(t, len(before), len(after))\n\tfor i := range before {\n\t\tuassert.Equal(t, before[i].Index, after[i].Index)\n\t\tuassert.Equal(t, before[i].Value, after[i].Value)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/ulist/v1\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"ulist.gno","body":"// Package ulist provides an append-only list implementation using a binary tree structure,\n// optimized for scenarios requiring sequential inserts with auto-incrementing indices.\n//\n// The implementation uses a binary tree where new elements are added by following a path\n// determined by the binary representation of the index. This provides automatic balancing\n// for append operations without requiring any balancing logic.\n//\n// Unlike the AVL tree-based list implementation (p/demo/avl/list), ulist is specifically\n// designed for append-only operations and does not require rebalancing. This makes it more\n// efficient for sequential inserts but less flexible for general-purpose list operations.\n//\n// Key differences from AVL list:\n// * Append-only design (no arbitrary inserts)\n// * No tree rebalancing needed\n// * Simpler implementation\n// * More memory efficient for sequential operations\n// * Less flexible than AVL (no arbitrary inserts/reordering)\n//\n// Key characteristics:\n// * O(log n) append and access operations\n// * Perfect balance for power-of-2 sizes\n// * No balancing needed\n// * Memory efficient\n// * Natural support for range queries\n// * Support for soft deletion of elements, and index-preserving compaction of\n//   what those deletions leave behind (see compact.gno)\n// * Forward and reverse iteration capabilities\n// * Offset-based iteration with count control\npackage ulist\n\n// TODO: Make avl/pager compatible in some way. Explain the limitations (not always 10 items because of nil ones).\n// TODO: Use this ulist in moul/collection for the primary index.\n// TODO: Benchmarks.\n\nimport (\n\t\"errors\"\n)\n\n// List represents an append-only binary tree list\ntype List struct {\n\troot       *treeNode\n\ttotalSize  int\n\tactiveSize int\n}\n\n// Entry represents a key-value pair in the list, where Index is the position\n// and Value is the stored data\ntype Entry struct {\n\tIndex int\n\tValue any\n}\n\n// treeNode represents a node in the binary tree\ntype treeNode struct {\n\tdata  any\n\tleft  *treeNode\n\tright *treeNode\n}\n\n// Error variables\nvar (\n\tErrOutOfBounds = errors.New(\"index out of bounds\")\n\tErrDeleted     = errors.New(\"element already deleted\")\n)\n\n// New creates a new empty List instance\nfunc New() *List {\n\treturn \u0026List{}\n}\n\n// Append adds one or more values to the end of the list.\n// Values are added sequentially, and the list grows automatically.\nfunc (l *List) Append(values ...any) {\n\tfor _, value := range values {\n\t\tindex := l.totalSize\n\t\tnode := l.findNode(index, true)\n\t\tnode.data = value\n\t\tl.totalSize++\n\t\tl.activeSize++\n\t}\n}\n\n// Get retrieves the value at the specified index.\n// Returns nil if the index is out of bounds or if the element was deleted.\nfunc (l *List) Get(index int) any {\n\tnode := l.findNode(index, false)\n\tif node == nil {\n\t\treturn nil\n\t}\n\treturn node.data\n}\n\n// Delete marks the elements at the specified indices as deleted.\n// Returns ErrOutOfBounds if any index is invalid or ErrDeleted if\n// the element was already deleted.\nfunc (l *List) Delete(indices ...int) error {\n\tif len(indices) == 0 {\n\t\treturn nil\n\t}\n\tif l == nil || l.totalSize == 0 {\n\t\treturn ErrOutOfBounds\n\t}\n\n\tfor _, index := range indices {\n\t\tif index \u003c 0 || index \u003e= l.totalSize {\n\t\t\treturn ErrOutOfBounds\n\t\t}\n\n\t\tnode := l.findNode(index, false)\n\t\tif node == nil || node.data == nil {\n\t\t\treturn ErrDeleted\n\t\t}\n\t\tnode.data = nil\n\t\tl.activeSize--\n\t}\n\n\treturn nil\n}\n\n// Set updates or restores a value at the specified index if within bounds\n// Returns ErrOutOfBounds if the index is invalid\nfunc (l *List) Set(index int, value any) error {\n\tif l == nil || index \u003c 0 || index \u003e= l.totalSize {\n\t\treturn ErrOutOfBounds\n\t}\n\n\tnode := l.findNode(index, false)\n\tif node == nil {\n\t\treturn ErrOutOfBounds\n\t}\n\n\t// If this is restoring a deleted element\n\tif value != nil \u0026\u0026 node.data == nil {\n\t\tl.activeSize++\n\t}\n\n\t// If this is deleting an element\n\tif value == nil \u0026\u0026 node.data != nil {\n\t\tl.activeSize--\n\t}\n\n\tnode.data = value\n\treturn nil\n}\n\n// Size returns the number of active (non-deleted) elements in the list\nfunc (l *List) Size() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn l.activeSize\n}\n\n// TotalSize returns the total number of elements ever added to the list,\n// including deleted elements\nfunc (l *List) TotalSize() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn l.totalSize\n}\n\n// IterCbFn is a callback function type used in iteration methods.\n// Return true to stop iteration, false to continue.\ntype IterCbFn func(index int, value any) bool\n\n// Iterator performs iteration between start and end indices, calling cb for each entry.\n// If start \u003e end, iteration is performed in reverse order.\n// Returns true if iteration was stopped early by the callback returning true.\n// Skips deleted elements.\nfunc (l *List) Iterator(start, end int, cb IterCbFn) bool {\n\t// For empty list or invalid range\n\tif l == nil || l.totalSize == 0 {\n\t\treturn false\n\t}\n\tif start \u003c 0 \u0026\u0026 end \u003c 0 {\n\t\treturn false\n\t}\n\tif start \u003e= l.totalSize \u0026\u0026 end \u003e= l.totalSize {\n\t\treturn false\n\t}\n\n\t// Normalize indices\n\tif start \u003c 0 {\n\t\tstart = 0\n\t}\n\tif end \u003c 0 {\n\t\tend = 0\n\t}\n\tif end \u003e= l.totalSize {\n\t\tend = l.totalSize - 1\n\t}\n\tif start \u003e= l.totalSize {\n\t\tstart = l.totalSize - 1\n\t}\n\n\t// Handle reverse iteration\n\tif start \u003e end {\n\t\tfor i := start; i \u003e= end; i-- {\n\t\t\tval := l.Get(i)\n\t\t\tif val != nil {\n\t\t\t\tif cb(i, val) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// Handle forward iteration\n\tfor i := start; i \u003c= end; i++ {\n\t\tval := l.Get(i)\n\t\tif val != nil {\n\t\t\tif cb(i, val) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n// IteratorByOffset performs iteration starting from offset for count elements.\n// If count is positive, iterates forward; if negative, iterates backward.\n// The iteration stops after abs(count) elements or when reaching list bounds.\n// Skips deleted elements.\nfunc (l *List) IteratorByOffset(offset int, count int, cb IterCbFn) bool {\n\tif count == 0 || l == nil || l.totalSize == 0 {\n\t\treturn false\n\t}\n\n\t// Normalize offset\n\tif offset \u003c 0 {\n\t\toffset = 0\n\t}\n\tif offset \u003e= l.totalSize {\n\t\toffset = l.totalSize - 1\n\t}\n\n\t// Determine end based on count direction\n\tvar end int\n\tif count \u003e 0 {\n\t\tend = l.totalSize - 1\n\t} else {\n\t\tend = 0\n\t}\n\n\twrapperReturned := false\n\n\t// Wrap the callback to limit iterations\n\tremaining := abs(count)\n\twrapper := func(index int, value any) bool {\n\t\tif remaining \u003c= 0 {\n\t\t\twrapperReturned = true\n\t\t\treturn true\n\t\t}\n\t\tremaining--\n\t\treturn cb(index, value)\n\t}\n\tret := l.Iterator(offset, end, wrapper)\n\tif wrapperReturned {\n\t\treturn false\n\t}\n\treturn ret\n}\n\n// abs returns the absolute value of x\nfunc abs(x int) int {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\n// findNode locates or creates a node at the given index in the binary tree.\n// The tree is structured such that the path to a node is determined by the binary\n// representation of the index. For example, a tree with 15 elements would look like:\n//\n//\t          0\n//\t       /      \\\n//\t     1         2\n//\t   /   \\     /   \\\n//\t  3    4    5     6\n//\t / \\  / \\  / \\   / \\\n//\t7  8 9 10 11 12 13 14\n//\n// To find index 13 (binary 1101):\n// 1. Start at root (0)\n// 2. Calculate bits needed (4 bits for index 13)\n// 3. Skip the highest bit position and start from bits-2\n// 4. Read bits from left to right:\n//   - 1 -\u003e go right to 2\n//   - 1 -\u003e go right to 6\n//   - 0 -\u003e go left to 13\n//\n// Special cases:\n// - Index 0 always returns the root node\n// - For create=true, missing nodes are created along the path\n// - For create=false, returns nil if any node is missing\nfunc (l *List) findNode(index int, create bool) *treeNode {\n\t// For read operations, check bounds strictly\n\tif !create \u0026\u0026 (l == nil || index \u003c 0 || index \u003e= l.totalSize) {\n\t\treturn nil\n\t}\n\n\t// For create operations, allow index == totalSize for append\n\tif create \u0026\u0026 (l == nil || index \u003c 0 || index \u003e l.totalSize) {\n\t\treturn nil\n\t}\n\n\t// Initialize root if needed\n\tif l.root == nil {\n\t\tif !create {\n\t\t\treturn nil\n\t\t}\n\t\tl.root = \u0026treeNode{}\n\t\treturn l.root\n\t}\n\n\tnode := l.root\n\n\t// Special case for root node\n\tif index == 0 {\n\t\treturn node\n\t}\n\n\t// Calculate the number of bits needed (inline highestBit logic)\n\tbits := 0\n\tn := index + 1\n\tfor n \u003e 0 {\n\t\tn \u003e\u003e= 1\n\t\tbits++\n\t}\n\n\t// Start from the second highest bit\n\tfor level := bits - 2; level \u003e= 0; level-- {\n\t\tbit := (index \u0026 (1 \u003c\u003c uint(level))) != 0\n\n\t\tif bit {\n\t\t\tif node.right == nil {\n\t\t\t\tif !create {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tnode.right = \u0026treeNode{}\n\t\t\t}\n\t\t\tnode = node.right\n\t\t} else {\n\t\t\tif node.left == nil {\n\t\t\t\tif !create {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tnode.left = \u0026treeNode{}\n\t\t\t}\n\t\t\tnode = node.left\n\t\t}\n\t}\n\n\treturn node\n}\n\n// MustDelete deletes elements at the specified indices.\n// Panics if any index is invalid or if any element was already deleted.\nfunc (l *List) MustDelete(indices ...int) {\n\tif err := l.Delete(indices...); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// MustGet retrieves the value at the specified index.\n// Panics if the index is out of bounds or if the element was deleted.\nfunc (l *List) MustGet(index int) any {\n\tif l == nil || index \u003c 0 || index \u003e= l.totalSize {\n\t\tpanic(ErrOutOfBounds)\n\t}\n\tvalue := l.Get(index)\n\tif value == nil {\n\t\tpanic(ErrDeleted)\n\t}\n\treturn value\n}\n\n// MustSet updates or restores a value at the specified index.\n// Panics if the index is out of bounds.\nfunc (l *List) MustSet(index int, value any) {\n\tif err := l.Set(index, value); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// GetRange returns a slice of Entry containing elements between start and end indices.\n// If start \u003e end, elements are returned in reverse order.\n// Deleted elements are skipped.\nfunc (l *List) GetRange(start, end int) []Entry {\n\tvar entries []Entry\n\tl.Iterator(start, end, func(index int, value any) bool {\n\t\tentries = append(entries, Entry{Index: index, Value: value})\n\t\treturn false\n\t})\n\treturn entries\n}\n\n// GetByOffset returns a slice of Entry starting from offset for count elements.\n// If count is positive, returns elements forward; if negative, returns elements backward.\n// The operation stops after abs(count) elements or when reaching list bounds.\n// Deleted elements are skipped.\nfunc (l *List) GetByOffset(offset int, count int) []Entry {\n\tvar entries []Entry\n\tl.IteratorByOffset(offset, count, func(index int, value any) bool {\n\t\tentries = append(entries, Entry{Index: index, Value: value})\n\t\treturn false\n\t})\n\treturn entries\n}\n\n// IList defines the interface for an ulist.List compatible structure.\ntype IList interface {\n\t// Basic operations\n\tAppend(values ...any)\n\tGet(index int) any\n\tDelete(indices ...int) error\n\tSize() int\n\tTotalSize() int\n\tSet(index int, value any) error\n\n\t// Must variants that panic instead of returning errors\n\tMustDelete(indices ...int)\n\tMustGet(index int) any\n\tMustSet(index int, value any)\n\n\t// Range operations\n\tGetRange(start, end int) []Entry\n\tGetByOffset(offset int, count int) []Entry\n\n\t// Iterator operations\n\tIterator(start, end int, cb IterCbFn) bool\n\tIteratorByOffset(offset int, count int, cb IterCbFn) bool\n}\n\n// Verify that List implements IList\nvar _ IList = (*List)(nil)\n"},{"name":"ulist_test.gno","body":"package ulist\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/typeutil/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc TestNew(t *testing.T) {\n\tl := New()\n\tuassert.Equal(t, 0, l.Size())\n\tuassert.Equal(t, 0, l.TotalSize())\n}\n\nfunc TestListAppendAndGet(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tsetup    func() *List\n\t\tindex    int\n\t\texpected any\n\t}{\n\t\t{\n\t\t\tname: \"empty list\",\n\t\t\tsetup: func() *List {\n\t\t\t\treturn New()\n\t\t\t},\n\t\t\tindex:    0,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"single append and get\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(42)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    0,\n\t\t\texpected: 42,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple appends and get first\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\tl.Append(2)\n\t\t\t\tl.Append(3)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    0,\n\t\t\texpected: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple appends and get last\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\tl.Append(2)\n\t\t\t\tl.Append(3)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    2,\n\t\t\texpected: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"get with invalid index\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    1,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"31 items get first\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tfor i := 0; i \u003c 31; i++ {\n\t\t\t\t\tl.Append(i)\n\t\t\t\t}\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    0,\n\t\t\texpected: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"31 items get last\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tfor i := 0; i \u003c 31; i++ {\n\t\t\t\t\tl.Append(i)\n\t\t\t\t}\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    30,\n\t\t\texpected: 30,\n\t\t},\n\t\t{\n\t\t\tname: \"31 items get middle\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tfor i := 0; i \u003c 31; i++ {\n\t\t\t\t\tl.Append(i)\n\t\t\t\t}\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    15,\n\t\t\texpected: 15,\n\t\t},\n\t\t{\n\t\t\tname: \"values around power of 2 boundary\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tfor i := 0; i \u003c 18; i++ {\n\t\t\t\t\tl.Append(i)\n\t\t\t\t}\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    15,\n\t\t\texpected: 15,\n\t\t},\n\t\t{\n\t\t\tname: \"values at power of 2\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tfor i := 0; i \u003c 18; i++ {\n\t\t\t\t\tl.Append(i)\n\t\t\t\t}\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    16,\n\t\t\texpected: 16,\n\t\t},\n\t\t{\n\t\t\tname: \"values after power of 2\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tfor i := 0; i \u003c 18; i++ {\n\t\t\t\t\tl.Append(i)\n\t\t\t\t}\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:    17,\n\t\t\texpected: 17,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := tt.setup()\n\t\t\tgot := l.Get(tt.index)\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"List.Get() = %v, want %v\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// generateSequence creates a slice of integers from 0 to n-1\nfunc generateSequence(n int) []any {\n\tresult := make([]any, n)\n\tfor i := 0; i \u003c n; i++ {\n\t\tresult[i] = i\n\t}\n\treturn result\n}\n\nfunc TestListDelete(t *testing.T) {\n\ttests := []struct {\n\t\tname          string\n\t\tsetup         func() *List\n\t\tdeleteIndices []int\n\t\texpectedErr   error\n\t\texpectedSize  int\n\t}{\n\t\t{\n\t\t\tname: \"delete single element\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tdeleteIndices: []int{1},\n\t\t\texpectedErr:   nil,\n\t\t\texpectedSize:  2,\n\t\t},\n\t\t{\n\t\t\tname: \"delete multiple elements\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3, 4, 5)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tdeleteIndices: []int{0, 2, 4},\n\t\t\texpectedErr:   nil,\n\t\t\texpectedSize:  2,\n\t\t},\n\t\t{\n\t\t\tname: \"delete with negative index\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tdeleteIndices: []int{-1},\n\t\t\texpectedErr:   ErrOutOfBounds,\n\t\t\texpectedSize:  1,\n\t\t},\n\t\t{\n\t\t\tname: \"delete beyond size\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tdeleteIndices: []int{1},\n\t\t\texpectedErr:   ErrOutOfBounds,\n\t\t\texpectedSize:  1,\n\t\t},\n\t\t{\n\t\t\tname: \"delete already deleted element\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\tl.Delete(0)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tdeleteIndices: []int{0},\n\t\t\texpectedErr:   ErrDeleted,\n\t\t\texpectedSize:  0,\n\t\t},\n\t\t{\n\t\t\tname: \"delete multiple elements in reverse\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3, 4, 5)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tdeleteIndices: []int{4, 2, 0},\n\t\t\texpectedErr:   nil,\n\t\t\texpectedSize:  2,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := tt.setup()\n\t\t\tinitialSize := l.Size()\n\t\t\terr := l.Delete(tt.deleteIndices...)\n\t\t\tif err != nil \u0026\u0026 tt.expectedErr != nil {\n\t\t\t\tuassert.ErrorIs(t, err, tt.expectedErr)\n\t\t\t} else {\n\t\t\t\tuassert.Equal(t, tt.expectedErr, err)\n\t\t\t}\n\t\t\tuassert.Equal(t, tt.expectedSize, l.Size(),\n\t\t\t\tufmt.Sprintf(\"Expected size %d after deleting %d elements from size %d, got %d\",\n\t\t\t\t\ttt.expectedSize, len(tt.deleteIndices), initialSize, l.Size()))\n\t\t})\n\t}\n}\n\nfunc TestListSizeAndTotalSize(t *testing.T) {\n\tt.Run(\"empty list\", func(t *testing.T) {\n\t\tlist := New()\n\t\tuassert.Equal(t, 0, list.Size())\n\t\tuassert.Equal(t, 0, list.TotalSize())\n\t})\n\n\tt.Run(\"list with elements\", func(t *testing.T) {\n\t\tlist := New()\n\t\tlist.Append(1)\n\t\tlist.Append(2)\n\t\tlist.Append(3)\n\t\tuassert.Equal(t, 3, list.Size())\n\t\tuassert.Equal(t, 3, list.TotalSize())\n\t})\n\n\tt.Run(\"list with deleted elements\", func(t *testing.T) {\n\t\tlist := New()\n\t\tlist.Append(1)\n\t\tlist.Append(2)\n\t\tlist.Append(3)\n\t\tlist.Delete(1)\n\t\tuassert.Equal(t, 2, list.Size())\n\t\tuassert.Equal(t, 3, list.TotalSize())\n\t})\n}\n\nfunc TestIterator(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tvalues    []any\n\t\tstart     int\n\t\tend       int\n\t\texpected  []Entry\n\t\twantStop  bool\n\t\tstopAfter int // stop after N elements, -1 for no stop\n\t}{\n\t\t{\n\t\t\tname:      \"empty list\",\n\t\t\tvalues:    []any{},\n\t\t\tstart:     0,\n\t\t\tend:       10,\n\t\t\texpected:  []Entry{},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:      \"nil list\",\n\t\t\tvalues:    nil,\n\t\t\tstart:     0,\n\t\t\tend:       0,\n\t\t\texpected:  []Entry{},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"single element forward\",\n\t\t\tvalues: []any{42},\n\t\t\tstart:  0,\n\t\t\tend:    0,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 42},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"multiple elements forward\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\tstart:  0,\n\t\t\tend:    4,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"multiple elements reverse\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\tstart:  4,\n\t\t\tend:    0,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"partial range forward\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\tstart:  1,\n\t\t\tend:    3,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"partial range reverse\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\tstart:  3,\n\t\t\tend:    1,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:      \"stop iteration early\",\n\t\t\tvalues:    []any{1, 2, 3, 4, 5},\n\t\t\tstart:     0,\n\t\t\tend:       4,\n\t\t\twantStop:  true,\n\t\t\tstopAfter: 2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"negative start\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\tstart:  -1,\n\t\t\tend:    2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"negative end\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\tstart:  0,\n\t\t\tend:    -2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:      \"start beyond size\",\n\t\t\tvalues:    []any{1, 2, 3},\n\t\t\tstart:     5,\n\t\t\tend:       6,\n\t\t\texpected:  []Entry{},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"end beyond size\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\tstart:  0,\n\t\t\tend:    5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"with deleted elements\",\n\t\t\tvalues: []any{1, 2, nil, 4, 5},\n\t\t\tstart:  0,\n\t\t\tend:    4,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:   \"with deleted elements reverse\",\n\t\t\tvalues: []any{1, nil, 3, nil, 5},\n\t\t\tstart:  4,\n\t\t\tend:    0,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t},\n\t\t\tstopAfter: -1,\n\t\t},\n\t\t{\n\t\t\tname:      \"start equals end\",\n\t\t\tvalues:    []any{1, 2, 3},\n\t\t\tstart:     1,\n\t\t\tend:       1,\n\t\t\texpected:  []Entry{{Index: 1, Value: 2}},\n\t\t\tstopAfter: -1,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tlist := New()\n\t\t\tlist.Append(tt.values...)\n\n\t\t\tvar result []Entry\n\t\t\tstopped := list.Iterator(tt.start, tt.end, func(index int, value any) bool {\n\t\t\t\tresult = append(result, Entry{Index: index, Value: value})\n\t\t\t\treturn tt.stopAfter \u003e= 0 \u0026\u0026 len(result) \u003e= tt.stopAfter\n\t\t\t})\n\n\t\t\tuassert.Equal(t, len(result), len(tt.expected), \"comparing length\")\n\n\t\t\tfor i := range result {\n\t\t\t\tuassert.Equal(t, result[i].Index, tt.expected[i].Index, \"comparing index\")\n\t\t\t\tuassert.Equal(t, typeutil.ToString(result[i].Value), typeutil.ToString(tt.expected[i].Value), \"comparing value\")\n\t\t\t}\n\n\t\t\tuassert.Equal(t, stopped, tt.wantStop, \"comparing stopped\")\n\t\t})\n\t}\n}\n\nfunc TestLargeListAppendGetAndDelete(t *testing.T) {\n\tl := New()\n\tsize := 100\n\n\t// Append values from 0 to 99\n\tfor i := 0; i \u003c size; i++ {\n\t\tl.Append(i)\n\t\tval := l.Get(i)\n\t\tuassert.Equal(t, i, val)\n\t}\n\n\t// Verify size\n\tuassert.Equal(t, size, l.Size())\n\tuassert.Equal(t, size, l.TotalSize())\n\n\t// Get and verify each value\n\tfor i := 0; i \u003c size; i++ {\n\t\tval := l.Get(i)\n\t\tuassert.Equal(t, i, val)\n\t}\n\n\t// Get and verify each value\n\tfor i := 0; i \u003c size; i++ {\n\t\terr := l.Delete(i)\n\t\tuassert.Equal(t, nil, err)\n\t}\n\n\t// Verify size\n\tuassert.Equal(t, 0, l.Size())\n\tuassert.Equal(t, size, l.TotalSize())\n\n\t// Get and verify each value\n\tfor i := 0; i \u003c size; i++ {\n\t\tval := l.Get(i)\n\t\tuassert.Equal(t, nil, val)\n\t}\n}\n\nfunc TestEdgeCases(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\ttest func(t *testing.T)\n\t}{\n\t\t{\n\t\t\tname: \"nil list operations\",\n\t\t\ttest: func(t *testing.T) {\n\t\t\t\tvar l *List\n\t\t\t\tuassert.Equal(t, 0, l.Size())\n\t\t\t\tuassert.Equal(t, 0, l.TotalSize())\n\t\t\t\tuassert.Equal(t, nil, l.Get(0))\n\t\t\t\terr := l.Delete(0)\n\t\t\t\tuassert.ErrorIs(t, err, ErrOutOfBounds)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"delete empty indices slice\",\n\t\t\ttest: func(t *testing.T) {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\terr := l.Delete()\n\t\t\t\tuassert.Equal(t, nil, err)\n\t\t\t\tuassert.Equal(t, 1, l.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"append nil values\",\n\t\t\ttest: func(t *testing.T) {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(nil, nil)\n\t\t\t\tuassert.Equal(t, 2, l.Size())\n\t\t\t\tuassert.Equal(t, nil, l.Get(0))\n\t\t\t\tuassert.Equal(t, nil, l.Get(1))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"delete same index multiple times\",\n\t\t\ttest: func(t *testing.T) {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3)\n\t\t\t\terr := l.Delete(1)\n\t\t\t\tuassert.Equal(t, nil, err)\n\t\t\t\terr = l.Delete(1)\n\t\t\t\tuassert.ErrorIs(t, err, ErrDeleted)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"iterator with all deleted elements\",\n\t\t\ttest: func(t *testing.T) {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3)\n\t\t\t\tl.Delete(0, 1, 2)\n\t\t\t\tvar count int\n\t\t\t\tl.Iterator(0, 2, func(index int, value any) bool {\n\t\t\t\t\tcount++\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\tuassert.Equal(t, 0, count)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"append after delete\",\n\t\t\ttest: func(t *testing.T) {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2)\n\t\t\t\tl.Delete(1)\n\t\t\t\tl.Append(3)\n\t\t\t\tuassert.Equal(t, 2, l.Size())\n\t\t\t\tuassert.Equal(t, 3, l.TotalSize())\n\t\t\t\tuassert.Equal(t, 1, l.Get(0))\n\t\t\t\tuassert.Equal(t, nil, l.Get(1))\n\t\t\t\tuassert.Equal(t, 3, l.Get(2))\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttt.test(t)\n\t\t})\n\t}\n}\n\nfunc TestIteratorByOffset(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tvalues   []any\n\t\toffset   int\n\t\tcount    int\n\t\texpected []Entry\n\t\twantStop bool\n\t}{\n\t\t{\n\t\t\tname:     \"empty list\",\n\t\t\tvalues:   []any{},\n\t\t\toffset:   0,\n\t\t\tcount:    5,\n\t\t\texpected: []Entry{},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"positive count forward iteration\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\toffset: 1,\n\t\t\tcount:  2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"negative count backward iteration\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\toffset: 3,\n\t\t\tcount:  -2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"count exceeds available elements forward\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\toffset: 1,\n\t\t\tcount:  5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"count exceeds available elements backward\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\toffset: 1,\n\t\t\tcount:  -5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"zero count\",\n\t\t\tvalues:   []any{1, 2, 3},\n\t\t\toffset:   0,\n\t\t\tcount:    0,\n\t\t\texpected: []Entry{},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"negative offset\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\toffset: -1,\n\t\t\tcount:  2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"offset beyond size\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\toffset: 5,\n\t\t\tcount:  -2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"with deleted elements\",\n\t\t\tvalues: []any{1, nil, 3, nil, 5},\n\t\t\toffset: 0,\n\t\t\tcount:  3,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"early stop in forward iteration\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\toffset: 0,\n\t\t\tcount:  5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t\twantStop: true, // The callback will return true after 2 elements\n\t\t},\n\t\t{\n\t\t\tname:   \"early stop in backward iteration\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\toffset: 4,\n\t\t\tcount:  -5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t},\n\t\t\twantStop: true, // The callback will return true after 2 elements\n\t\t},\n\t\t{\n\t\t\tname:     \"nil list\",\n\t\t\tvalues:   nil,\n\t\t\toffset:   0,\n\t\t\tcount:    5,\n\t\t\texpected: []Entry{},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"single element forward\",\n\t\t\tvalues: []any{1},\n\t\t\toffset: 0,\n\t\t\tcount:  5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:   \"single element backward\",\n\t\t\tvalues: []any{1},\n\t\t\toffset: 0,\n\t\t\tcount:  -5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t},\n\t\t\twantStop: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"all deleted elements\",\n\t\t\tvalues:   []any{nil, nil, nil},\n\t\t\toffset:   0,\n\t\t\tcount:    3,\n\t\t\texpected: []Entry{},\n\t\t\twantStop: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tlist := New()\n\t\t\tlist.Append(tt.values...)\n\n\t\t\tvar result []Entry\n\t\t\tvar cb IterCbFn\n\t\t\tif tt.wantStop {\n\t\t\t\tcb = func(index int, value any) bool {\n\t\t\t\t\tresult = append(result, Entry{Index: index, Value: value})\n\t\t\t\t\treturn len(result) \u003e= 2 // Stop after 2 elements for early stop tests\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcb = func(index int, value any) bool {\n\t\t\t\t\tresult = append(result, Entry{Index: index, Value: value})\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstopped := list.IteratorByOffset(tt.offset, tt.count, cb)\n\n\t\t\tuassert.Equal(t, len(tt.expected), len(result), \"comparing length\")\n\t\t\tfor i := range result {\n\t\t\t\tuassert.Equal(t, tt.expected[i].Index, result[i].Index, \"comparing index\")\n\t\t\t\tuassert.Equal(t, typeutil.ToString(tt.expected[i].Value), typeutil.ToString(result[i].Value), \"comparing value\")\n\t\t\t}\n\t\t\tuassert.Equal(t, tt.wantStop, stopped, \"comparing stopped\")\n\t\t})\n\t}\n}\n\nfunc TestMustDelete(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tsetup       func() *List\n\t\tindices     []int\n\t\tshouldPanic bool\n\t\tpanicMsg    string\n\t}{\n\t\t{\n\t\t\tname: \"successful delete\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindices:     []int{1},\n\t\t\tshouldPanic: false,\n\t\t},\n\t\t{\n\t\t\tname: \"out of bounds\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindices:     []int{1},\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrOutOfBounds.Error(),\n\t\t},\n\t\t{\n\t\t\tname: \"already deleted\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\tl.Delete(0)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindices:     []int{0},\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrDeleted.Error(),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := tt.setup()\n\t\t\tif tt.shouldPanic {\n\t\t\t\tdefer func() {\n\t\t\t\t\tr := recover()\n\t\t\t\t\tif r == nil {\n\t\t\t\t\t\tt.Error(\"Expected panic but got none\")\n\t\t\t\t\t}\n\t\t\t\t\terr, ok := r.(error)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tt.Errorf(\"Expected error but got %v\", r)\n\t\t\t\t\t}\n\t\t\t\t\tuassert.Equal(t, tt.panicMsg, err.Error())\n\t\t\t\t}()\n\t\t\t}\n\t\t\tl.MustDelete(tt.indices...)\n\t\t\tif tt.shouldPanic {\n\t\t\t\tt.Error(\"Expected panic\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMustGet(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tsetup       func() *List\n\t\tindex       int\n\t\texpected    any\n\t\tshouldPanic bool\n\t\tpanicMsg    string\n\t}{\n\t\t{\n\t\t\tname: \"successful get\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(42)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\texpected:    42,\n\t\t\tshouldPanic: false,\n\t\t},\n\t\t{\n\t\t\tname: \"out of bounds negative\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       -1,\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrOutOfBounds.Error(),\n\t\t},\n\t\t{\n\t\t\tname: \"out of bounds positive\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       1,\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrOutOfBounds.Error(),\n\t\t},\n\t\t{\n\t\t\tname: \"deleted element\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\tl.Delete(0)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrDeleted.Error(),\n\t\t},\n\t\t{\n\t\t\tname: \"nil list\",\n\t\t\tsetup: func() *List {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrOutOfBounds.Error(),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := tt.setup()\n\t\t\tif tt.shouldPanic {\n\t\t\t\tdefer func() {\n\t\t\t\t\tr := recover()\n\t\t\t\t\tif r == nil {\n\t\t\t\t\t\tt.Error(\"Expected panic but got none\")\n\t\t\t\t\t}\n\t\t\t\t\terr, ok := r.(error)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tt.Errorf(\"Expected error but got %v\", r)\n\t\t\t\t\t}\n\t\t\t\t\tuassert.Equal(t, tt.panicMsg, err.Error())\n\t\t\t\t}()\n\t\t\t}\n\t\t\tresult := l.MustGet(tt.index)\n\t\t\tif tt.shouldPanic {\n\t\t\t\tt.Error(\"Expected panic\")\n\t\t\t}\n\t\t\tuassert.Equal(t, typeutil.ToString(tt.expected), typeutil.ToString(result))\n\t\t})\n\t}\n}\n\nfunc TestGetRange(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tvalues   []any\n\t\tstart    int\n\t\tend      int\n\t\texpected []Entry\n\t}{\n\t\t{\n\t\t\tname:     \"empty list\",\n\t\t\tvalues:   []any{},\n\t\t\tstart:    0,\n\t\t\tend:      10,\n\t\t\texpected: []Entry{},\n\t\t},\n\t\t{\n\t\t\tname:   \"single element\",\n\t\t\tvalues: []any{42},\n\t\t\tstart:  0,\n\t\t\tend:    0,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 42},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"multiple elements forward\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\tstart:  1,\n\t\t\tend:    3,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"multiple elements reverse\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\tstart:  3,\n\t\t\tend:    1,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"with deleted elements\",\n\t\t\tvalues: []any{1, nil, 3, nil, 5},\n\t\t\tstart:  0,\n\t\t\tend:    4,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"nil list\",\n\t\t\tvalues:   nil,\n\t\t\tstart:    0,\n\t\t\tend:      5,\n\t\t\texpected: []Entry{},\n\t\t},\n\t\t{\n\t\t\tname:     \"negative indices\",\n\t\t\tvalues:   []any{1, 2, 3},\n\t\t\tstart:    -1,\n\t\t\tend:      -2,\n\t\t\texpected: []Entry{},\n\t\t},\n\t\t{\n\t\t\tname:   \"indices beyond size\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\tstart:  1,\n\t\t\tend:    5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tlist := New()\n\t\t\tlist.Append(tt.values...)\n\n\t\t\tresult := list.GetRange(tt.start, tt.end)\n\n\t\t\tuassert.Equal(t, len(tt.expected), len(result), \"comparing length\")\n\t\t\tfor i := range result {\n\t\t\t\tuassert.Equal(t, tt.expected[i].Index, result[i].Index, \"comparing index\")\n\t\t\t\tuassert.Equal(t, typeutil.ToString(tt.expected[i].Value), typeutil.ToString(result[i].Value), \"comparing value\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetByOffset(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tvalues   []any\n\t\toffset   int\n\t\tcount    int\n\t\texpected []Entry\n\t}{\n\t\t{\n\t\t\tname:     \"empty list\",\n\t\t\tvalues:   []any{},\n\t\t\toffset:   0,\n\t\t\tcount:    5,\n\t\t\texpected: []Entry{},\n\t\t},\n\t\t{\n\t\t\tname:   \"positive count forward\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\toffset: 1,\n\t\t\tcount:  2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"negative count backward\",\n\t\t\tvalues: []any{1, 2, 3, 4, 5},\n\t\t\toffset: 3,\n\t\t\tcount:  -2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 3, Value: 4},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"count exceeds available elements\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\toffset: 1,\n\t\t\tcount:  5,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"zero count\",\n\t\t\tvalues:   []any{1, 2, 3},\n\t\t\toffset:   0,\n\t\t\tcount:    0,\n\t\t\texpected: []Entry{},\n\t\t},\n\t\t{\n\t\t\tname:   \"with deleted elements\",\n\t\t\tvalues: []any{1, nil, 3, nil, 5},\n\t\t\toffset: 0,\n\t\t\tcount:  3,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 4, Value: 5},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"negative offset\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\toffset: -1,\n\t\t\tcount:  2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 0, Value: 1},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"offset beyond size\",\n\t\t\tvalues: []any{1, 2, 3},\n\t\t\toffset: 5,\n\t\t\tcount:  -2,\n\t\t\texpected: []Entry{\n\t\t\t\t{Index: 2, Value: 3},\n\t\t\t\t{Index: 1, Value: 2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"nil list\",\n\t\t\tvalues:   nil,\n\t\t\toffset:   0,\n\t\t\tcount:    5,\n\t\t\texpected: []Entry{},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tlist := New()\n\t\t\tlist.Append(tt.values...)\n\n\t\t\tresult := list.GetByOffset(tt.offset, tt.count)\n\n\t\t\tuassert.Equal(t, len(tt.expected), len(result), \"comparing length\")\n\t\t\tfor i := range result {\n\t\t\t\tuassert.Equal(t, tt.expected[i].Index, result[i].Index, \"comparing index\")\n\t\t\t\tuassert.Equal(t, typeutil.ToString(tt.expected[i].Value), typeutil.ToString(result[i].Value), \"comparing value\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMustSet(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tsetup       func() *List\n\t\tindex       int\n\t\tvalue       any\n\t\tshouldPanic bool\n\t\tpanicMsg    string\n\t}{\n\t\t{\n\t\t\tname: \"successful set\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(42)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\tvalue:       99,\n\t\t\tshouldPanic: false,\n\t\t},\n\t\t{\n\t\t\tname: \"restore deleted element\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(42)\n\t\t\t\tl.Delete(0)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\tvalue:       99,\n\t\t\tshouldPanic: false,\n\t\t},\n\t\t{\n\t\t\tname: \"out of bounds negative\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       -1,\n\t\t\tvalue:       99,\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrOutOfBounds.Error(),\n\t\t},\n\t\t{\n\t\t\tname: \"out of bounds positive\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       1,\n\t\t\tvalue:       99,\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrOutOfBounds.Error(),\n\t\t},\n\t\t{\n\t\t\tname: \"nil list\",\n\t\t\tsetup: func() *List {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\tvalue:       99,\n\t\t\tshouldPanic: true,\n\t\t\tpanicMsg:    ErrOutOfBounds.Error(),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := tt.setup()\n\t\t\tif tt.shouldPanic {\n\t\t\t\tdefer func() {\n\t\t\t\t\tr := recover()\n\t\t\t\t\tif r == nil {\n\t\t\t\t\t\tt.Error(\"Expected panic but got none\")\n\t\t\t\t\t}\n\t\t\t\t\terr, ok := r.(error)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tt.Errorf(\"Expected error but got %v\", r)\n\t\t\t\t\t}\n\t\t\t\t\tuassert.Equal(t, tt.panicMsg, err.Error())\n\t\t\t\t}()\n\t\t\t}\n\t\t\tl.MustSet(tt.index, tt.value)\n\t\t\tif tt.shouldPanic {\n\t\t\t\tt.Error(\"Expected panic\")\n\t\t\t}\n\t\t\t// Verify the value was set correctly for non-panic cases\n\t\t\tif !tt.shouldPanic {\n\t\t\t\tresult := l.Get(tt.index)\n\t\t\t\tuassert.Equal(t, typeutil.ToString(tt.value), typeutil.ToString(result))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSet(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tsetup       func() *List\n\t\tindex       int\n\t\tvalue       any\n\t\texpectedErr error\n\t\tverify      func(t *testing.T, l *List)\n\t}{\n\t\t{\n\t\t\tname: \"set value in empty list\",\n\t\t\tsetup: func() *List {\n\t\t\t\treturn New()\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\tvalue:       42,\n\t\t\texpectedErr: ErrOutOfBounds,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 0, l.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set value at valid index\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex: 0,\n\t\t\tvalue: 42,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 42, l.Get(0))\n\t\t\t\tuassert.Equal(t, 1, l.Size())\n\t\t\t\tuassert.Equal(t, 1, l.TotalSize())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set value at negative index\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       -1,\n\t\t\tvalue:       42,\n\t\t\texpectedErr: ErrOutOfBounds,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 1, l.Get(0))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set value beyond size\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex:       1,\n\t\t\tvalue:       42,\n\t\t\texpectedErr: ErrOutOfBounds,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 1, l.Get(0))\n\t\t\t\tuassert.Equal(t, 1, l.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set nil value\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex: 0,\n\t\t\tvalue: nil,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, nil, l.Get(0))\n\t\t\t\tuassert.Equal(t, 0, l.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set value at deleted index\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3)\n\t\t\t\tl.Delete(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex: 1,\n\t\t\tvalue: 42,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 42, l.Get(1))\n\t\t\t\tuassert.Equal(t, 3, l.Size())\n\t\t\t\tuassert.Equal(t, 3, l.TotalSize())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set value in nil list\",\n\t\t\tsetup: func() *List {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tindex:       0,\n\t\t\tvalue:       42,\n\t\t\texpectedErr: ErrOutOfBounds,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 0, l.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set multiple values at same index\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex: 0,\n\t\t\tvalue: 42,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 42, l.Get(0))\n\t\t\t\terr := l.Set(0, 99)\n\t\t\t\tuassert.Equal(t, nil, err)\n\t\t\t\tuassert.Equal(t, 99, l.Get(0))\n\t\t\t\tuassert.Equal(t, 1, l.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set value at last index\",\n\t\t\tsetup: func() *List {\n\t\t\t\tl := New()\n\t\t\t\tl.Append(1, 2, 3)\n\t\t\t\treturn l\n\t\t\t},\n\t\t\tindex: 2,\n\t\t\tvalue: 42,\n\t\t\tverify: func(t *testing.T, l *List) {\n\t\t\t\tuassert.Equal(t, 42, l.Get(2))\n\t\t\t\tuassert.Equal(t, 3, l.Size())\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := tt.setup()\n\t\t\terr := l.Set(tt.index, tt.value)\n\n\t\t\tif tt.expectedErr != nil {\n\t\t\t\tuassert.ErrorIs(t, err, tt.expectedErr)\n\t\t\t} else {\n\t\t\t\tuassert.Equal(t, nil, err)\n\t\t\t}\n\n\t\t\ttt.verify(t, l)\n\t\t})\n\t}\n}\n"}]},"send":"","max_deposit":"21000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"vesting","path":"gno.land/p/moul/vesting/v0","files":[{"name":"README.md","body":"# `p/moul/vesting`\n\nThe vesting curve **the gno.land chain itself enforces**, as a pure calculator.\n\nThis is not a vesting scheme of its own. It is a faithful reimplementation of tm2's\n`std.VestingSchedule`, so a realm can answer \"how much of this balance can actually move\nright now\" with the same arithmetic the ante handler uses. Divergence here would be worse\nthan useless, so every rule is copied from `tm2/pkg/std/vesting.go` rather than designed.\n\n```go\ns, err := vesting.New(106560000000, 1789225200, 1852383600, vesting.Continuous)\ns.Vested(now)              // how much has unlocked\ns.Locked(now)              // what the chain still refuses to move\ns.Spendable(balance, now)  // what can actually leave the account\ns.PermilleVested(now)      // tenths of a percent, for display\n```\n\n## The rules, all of them from tm2\n\n| | |\n|---|---|\n| `Continuous` | vests linearly between `Start` and `End` |\n| `Delayed` | a cliff: nothing before `End`, everything at or after it, and `Start` is ignored |\n| rounding | **down**, always |\n| a zero `Original` | means no schedule, which locks nothing |\n| times | unix seconds, never compared against the chain's clock |\n\nRounding down is the direction that matters. Reporting one ugnot more than the chain will\nmove turns a page into a lie somebody acts on.\n\n`Spendable` caps the locked part at the balance: an account that spent while its coins were\nfree can owe the schedule more than it now holds, and the honest answer there is that\nnothing moves, not a negative number.\n\n## Why this is not `p/moul/x/daily/cliffvesting`\n\nThat package is the employee-grant shape (start, **cliff**, end) for amounts a person is\ngranted. This one is the chain's shape, for amounts a chain holds, and the difference is not\nonly the curve:\n\n`cliffvesting` v0 multiplied in plain `int64`. Over the real mainnet term of 63,158,400\nseconds that wraps for any grant above **146,036 GNOT**, silently: a 318,720,000 GNOT grant\nreturned `-6,264,395,224`, a negative vested amount that every caller would have treated as\nreal. tm2 reaches for `math/big` at exactly this point. gno has no `math/big`, so `Vested`\ngoes through a 128-bit intermediate via `math/bits`. `cliffvesting` v1 now does the same.\n\nThe largest schedule this has to survive is the whole genesis allocation, 1,332,999,998\nGNOT, and the tests take it there.\n\n## What this package cannot do\n\nFind out an address's schedule. **Realm code cannot read one.** The VM's whole view of an\naccount is `banker.GetCoins`, which returns the total balance with the locked part included,\nand no native exposes `std.VestingSchedule`. The schedule has to come from the caller.\n\n[`r/moul/vesting`](/r/moul/vesting/v0) is what that constraint looks like in a page.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/vesting/v0\"\ngno = \"0.9\"\n"},{"name":"vesting.gno","body":"// Package vesting computes a gno.land account's vesting curve, as a PURE\n// calculator: no state, no balances, no transfers.\n//\n// It is not a vesting scheme of its own. It is a faithful reimplementation of\n// the one the CHAIN enforces, tm2's std.VestingSchedule, so that a realm can\n// answer \"how much of this balance can actually move right now\" with the same\n// arithmetic the ante handler uses. Divergence here is worse than useless, so\n// every rule below is copied from tm2/pkg/std/vesting.go rather than designed:\n//\n//   - Times are unix seconds, and nothing compares them against the chain's\n//     clock. A schedule already over when the chain starts is valid and vests\n//     everything at once.\n//   - [Continuous] vests linearly between Start and End. [Delayed] is a cliff:\n//     nothing before End, everything at or after it, and Start is ignored.\n//   - Rounding is DOWN, always, so the account never counts as spendable a\n//     ugnot the chain would refuse to move.\n//   - A zero Original is \"no schedule\", which locks nothing.\n//\n// # Why this is not p/moul/x/daily/cliffvesting\n//\n// That package is the employee-grant shape (start, cliff, end) and multiplies\n// in plain int64, which silently wraps for the amounts a chain actually holds:\n// over the 63,158,400 second mainnet term, any grant above 146,036 GNOT\n// overflows, and a 318,720,000 GNOT grant reports a NEGATIVE vested amount.\n// tm2 reaches for math/big at exactly this point. gno has no math/big, so\n// [Schedule.Vested] goes through a 128-bit intermediate instead.\n//\n// # What this package cannot do\n//\n// Find out an address's schedule. Realm code cannot read one: the VM's whole\n// view of an account is banker.GetCoins, which returns the TOTAL balance with\n// the locked part included, and no native exposes std.VestingSchedule. The\n// schedule has to come from the caller. See gno.land/r/moul/vesting for what\n// that means for a page that wants to show real numbers.\npackage vesting\n\nimport (\n\t\"errors\"\n\t\"math/bits\"\n)\n\n// Type selects the curve.\ntype Type uint8\n\nconst (\n\t// Continuous vests linearly from Start to End. The tm2 default.\n\tContinuous Type = iota\n\t// Delayed is a cliff: nothing vests until End, then all of it.\n\tDelayed\n)\n\nfunc (t Type) String() string {\n\tif t == Delayed {\n\t\treturn \"delayed\"\n\t}\n\treturn \"continuous\"\n}\n\nvar (\n\tErrNegativeOriginal = errors.New(\"vesting: original amount cannot be negative\")\n\tErrEndNotPositive   = errors.New(\"vesting: end time must be positive\")\n\tErrNegativeStart    = errors.New(\"vesting: start time cannot be negative\")\n\tErrStartAfterEnd    = errors.New(\"vesting: start time must be before end time\")\n)\n\n// Schedule is one account's vesting plan, as the chain stores it.\ntype Schedule struct {\n\tOriginal int64 // the granted amount, in the smallest unit\n\tStart    int64 // unix seconds; ignored by Delayed\n\tEnd      int64 // unix seconds\n\tType     Type\n}\n\n// New validates a schedule, applying tm2's own rules in tm2's own order.\n//\n// The Start \u003e= 0 check is not cosmetic and is the reason Vested can stay in\n// int64 for its subtractions: with 0 \u003c= Start \u003c End, neither End-Start nor\n// now-Start can overflow. tm2 rejects a negative start for exactly this.\nfunc New(original, start, end int64, typ Type) (Schedule, error) {\n\ts := Schedule{Original: original, Start: start, End: end, Type: typ}\n\tif original \u003c 0 {\n\t\treturn Schedule{}, ErrNegativeOriginal\n\t}\n\tif s.IsZero() {\n\t\treturn s, nil // no schedule; the other fields do not matter\n\t}\n\tif end \u003c= 0 {\n\t\treturn Schedule{}, ErrEndNotPositive\n\t}\n\tif typ != Delayed {\n\t\tif start \u003c 0 {\n\t\t\treturn Schedule{}, ErrNegativeStart\n\t\t}\n\t\tif start \u003e= end {\n\t\t\treturn Schedule{}, ErrStartAfterEnd\n\t\t}\n\t}\n\treturn s, nil\n}\n\n// IsZero reports whether there is no schedule at all, which locks nothing.\nfunc (s Schedule) IsZero() bool { return s.Original == 0 }\n\n// Vested returns how much of Original has vested at unix time now.\nfunc (s Schedule) Vested(now int64) int64 {\n\tif s.IsZero() {\n\t\treturn 0\n\t}\n\tif now \u003e= s.End {\n\t\treturn s.Original\n\t}\n\tif s.Type == Delayed {\n\t\treturn 0 // a cliff vests nothing until End\n\t}\n\tif now \u003c= s.Start {\n\t\treturn 0\n\t}\n\treturn mulDiv(s.Original, now-s.Start, s.End-s.Start)\n}\n\n// Locked returns the part of Original that has not vested at unix time now.\n// This is what the chain refuses to let leave the account.\nfunc (s Schedule) Locked(now int64) int64 { return s.Original - s.Vested(now) }\n\n// Spendable returns how much of balance can actually move at unix time now.\n//\n// balance is the account's TOTAL, which is what banker.GetCoins reports. The\n// locked part is capped at the balance: an account that has already spent down\n// to less than it still owes to the schedule has nothing spendable, not a\n// negative amount. tm2 reaches the same answer by subtracting locked coins\n// from the balance and refusing the transfer if the result does not cover it.\nfunc (s Schedule) Spendable(balance, now int64) int64 {\n\tif balance \u003c= 0 {\n\t\treturn 0\n\t}\n\tlocked := s.Locked(now)\n\tif locked \u003e= balance {\n\t\treturn 0\n\t}\n\treturn balance - locked\n}\n\n// PermilleVested returns the vested share at now in tenths of a percent,\n// rounded down, so a page can show one decimal without a float. Integer only:\n// no float ever reaches consensus state.\nfunc (s Schedule) PermilleVested(now int64) int64 {\n\tif s.IsZero() {\n\t\treturn 1000 // nothing to vest is fully vested\n\t}\n\treturn mulDiv(s.Vested(now), 1000, s.Original)\n}\n\n// RemainingSeconds returns how long until the schedule completes, zero once it\n// has. Reported rather than formatted: the caller owns how a duration reads.\nfunc (s Schedule) RemainingSeconds(now int64) int64 {\n\tif s.IsZero() || now \u003e= s.End {\n\t\treturn 0\n\t}\n\treturn s.End - now\n}\n\n// mulDiv computes floor(a*b/den) through a 128-bit intermediate, so a product\n// that leaves int64 does not wrap.\n//\n// Every caller here passes 0 \u003c= b \u003c= den with den \u003e 0, which is what makes the\n// bits.Div64 precondition hold: the quotient is then at most a, so it fits in\n// 64 bits, which is exactly the hi \u003c den that Div64 requires and panics\n// without. Keep that invariant at the call site, not by checking it here.\nfunc mulDiv(a, b, den int64) int64 {\n\tif a == 0 || b == 0 {\n\t\treturn 0\n\t}\n\thi, lo := bits.Mul64(uint64(a), uint64(b))\n\tq, _ := bits.Div64(hi, lo, uint64(den))\n\treturn int64(q)\n}\n"},{"name":"vesting_test.gno","body":"package vesting\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The real mainnet §132 term: 2026-09-12T15:00:00Z to 2028-09-12T15:00:00Z.\nconst (\n\tmainnetStart int64 = 1789225200\n\tmainnetEnd   int64 = 1852383600\n\tmainnetTerm        = mainnetEnd - mainnetStart // 63,158,400 seconds\n)\n\nfunc TestNewValidates(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname                    string\n\t\toriginal, start, end    int64\n\t\ttyp                     Type\n\t\twantErr                 error\n\t}{\n\t\t{\"a real mainnet schedule\", 106560000000, mainnetStart, mainnetEnd, Continuous, nil},\n\t\t{\"no schedule at all\", 0, 0, 0, Continuous, nil},\n\t\t{\"zero original ignores the rest\", 0, 99, 1, Continuous, nil},\n\t\t{\"a cliff needs no start\", 100, 0, mainnetEnd, Delayed, nil},\n\t\t{\"negative original\", -1, 0, 10, Continuous, ErrNegativeOriginal},\n\t\t{\"end not positive\", 100, 0, 0, Continuous, ErrEndNotPositive},\n\t\t{\"negative start\", 100, -1, 10, Continuous, ErrNegativeStart},\n\t\t{\"start equal to end\", 100, 10, 10, Continuous, ErrStartAfterEnd},\n\t\t{\"start after end\", 100, 11, 10, Continuous, ErrStartAfterEnd},\n\t} {\n\t\t_, err := New(tc.original, tc.start, tc.end, tc.typ)\n\t\tif tc.wantErr == nil {\n\t\t\tuassert.NoError(t, err, tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.ErrorIs(t, err, tc.wantErr, tc.name)\n\t}\n}\n\n// TestVestedCurve pins the continuous curve at its boundaries and midpoint.\nfunc TestVestedCurve(t *testing.T) {\n\ts, err := New(1000, 100, 200, Continuous)\n\tuassert.NoError(t, err)\n\n\tfor _, tc := range []struct {\n\t\tnow, want int64\n\t}{\n\t\t{0, 0},      // long before\n\t\t{100, 0},    // at the start\n\t\t{125, 250},  // a quarter in\n\t\t{150, 500},  // halfway\n\t\t{199, 990},  // one tick short\n\t\t{200, 1000}, // exactly at the end\n\t\t{1 \u003c\u003c 40, 1000},\n\t} {\n\t\tuassert.Equal(t, tc.want, s.Vested(tc.now))\n\t\tuassert.Equal(t, 1000-tc.want, s.Locked(tc.now))\n\t}\n}\n\n// TestDelayedIsACliff: Start is ignored and nothing vests until End.\nfunc TestDelayedIsACliff(t *testing.T) {\n\ts, err := New(1000, 0, 200, Delayed)\n\tuassert.NoError(t, err)\n\n\tuassert.Equal(t, int64(0), s.Vested(0))\n\tuassert.Equal(t, int64(0), s.Vested(199))\n\tuassert.Equal(t, int64(1000), s.Vested(200))\n\tuassert.Equal(t, int64(1000), s.Vested(1000))\n\tuassert.Equal(t, int64(1000), s.Locked(199))\n\tuassert.Equal(t, int64(0), s.Locked(200))\n}\n\nfunc TestZeroScheduleLocksNothing(t *testing.T) {\n\tvar s Schedule\n\tuassert.True(t, s.IsZero())\n\tuassert.Equal(t, int64(0), s.Vested(12345))\n\tuassert.Equal(t, int64(0), s.Locked(12345))\n\tuassert.Equal(t, int64(999), s.Spendable(999, 12345))\n\tuassert.Equal(t, int64(1000), s.PermilleVested(12345))\n}\n\n// TestRoundsDown is the direction that matters: reporting one ugnot more than\n// the chain will move turns a page into a lie a user acts on.\nfunc TestRoundsDown(t *testing.T) {\n\ts, err := New(10, 0, 3, Continuous) // 10/3 per second, never exact\n\tuassert.NoError(t, err)\n\n\tuassert.Equal(t, int64(3), s.Vested(1)) // 3.33 -\u003e 3\n\tuassert.Equal(t, int64(6), s.Vested(2)) // 6.66 -\u003e 6\n\tuassert.Equal(t, int64(10), s.Vested(3))\n}\n\n// TestNoOverflowAtChainScale is the whole reason this package exists rather\n// than reusing p/moul/x/daily/cliffvesting, which computes total*elapsed in\n// plain int64. Over the mainnet term that wraps above 146,036 GNOT: the\n// largest genesis grant is 318,720,000 GNOT, and the naive form returns a\n// NEGATIVE vested amount for it.\nfunc TestNoOverflowAtChainScale(t *testing.T) {\n\tconst largestGrant int64 = 318720000000000 // 318,720,000 GNOT in ugnot\n\n\ts, err := New(largestGrant, mainnetStart, mainnetEnd, Continuous)\n\tuassert.NoError(t, err)\n\n\t// Exactly halfway through the term: the answer is half the grant, and the\n\t// naive int64 product would have wrapped long before here.\n\thalf := s.Vested(mainnetStart + mainnetTerm/2)\n\tuassert.Equal(t, largestGrant/2, half)\n\tuassert.True(t, half \u003e 0, \"a wrapped product reports a negative amount\")\n\n\t// Every point on the curve stays inside [0, Original], monotonically.\n\tprev := int64(0)\n\tfor i := int64(0); i \u003c= 16; i++ {\n\t\tgot := s.Vested(mainnetStart + mainnetTerm*i/16)\n\t\tuassert.True(t, got \u003e= prev, \"vested went backwards\")\n\t\tuassert.True(t, got \u003e= 0 \u0026\u0026 got \u003c= largestGrant, \"vested left its bounds\")\n\t\tprev = got\n\t}\n\tuassert.Equal(t, largestGrant, prev)\n}\n\n// TestTotalSupplyGrantDoesNotOverflow takes the ceiling to the whole supply,\n// which is the largest schedule the chain could ever hold.\nfunc TestTotalSupplyGrantDoesNotOverflow(t *testing.T) {\n\tconst supply int64 = 1332999998328067 // total genesis allocation, ugnot\n\n\ts, err := New(supply, mainnetStart, mainnetEnd, Continuous)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, supply/2, s.Vested(mainnetStart+mainnetTerm/2))\n\tuassert.Equal(t, supply, s.Vested(mainnetEnd))\n}\n\n// TestSpendable is the number the page exists to show.\nfunc TestSpendable(t *testing.T) {\n\ts, err := New(1000, 100, 200, Continuous)\n\tuassert.NoError(t, err)\n\n\t// Balance above the grant: the surplus is spendable from the start.\n\tuassert.Equal(t, int64(200), s.Spendable(1200, 100)) // 1200 - 1000 locked\n\tuassert.Equal(t, int64(700), s.Spendable(1200, 150)) // 1200 - 500 locked\n\tuassert.Equal(t, int64(1200), s.Spendable(1200, 200))\n\n\t// Spent down below what is still locked: nothing moves, and the answer is\n\t// zero rather than a negative number.\n\tuassert.Equal(t, int64(0), s.Spendable(400, 150))\n\tuassert.Equal(t, int64(0), s.Spendable(500, 150)) // exactly locked\n\tuassert.Equal(t, int64(1), s.Spendable(501, 150))\n\n\tuassert.Equal(t, int64(0), s.Spendable(0, 150))\n\tuassert.Equal(t, int64(0), s.Spendable(-5, 150))\n}\n\n// TestMoulsOwnAccount walks the real genesis row through the real schedule,\n// as a regression on the arithmetic the page will print.\n//\n// Genesis row, from the allocation sheet that built mainnet:\n//\n//\tg1manfred47kzduec920z88wfr64ylksmdcedlf5=111000000000ugnot;\n//\t  vesting=106560000000ugnot,1789225200,1852383600\nfunc TestMoulsOwnAccount(t *testing.T) {\n\tconst (\n\t\tgenesisBalance int64 = 111000000000\n\t\tgrant          int64 = 106560000000\n\t)\n\ts, err := New(grant, mainnetStart, mainnetEnd, Continuous)\n\tuassert.NoError(t, err)\n\n\t// At genesis: the 4% that never vested is immediately spendable.\n\tuassert.Equal(t, int64(0), s.Vested(mainnetStart))\n\tuassert.Equal(t, genesisBalance-grant, s.Spendable(genesisBalance, mainnetStart))\n\tuassert.Equal(t, int64(4440000000), s.Spendable(genesisBalance, mainnetStart))\n\n\t// Halfway: half the grant has vested.\n\tuassert.Equal(t, grant/2, s.Vested(mainnetStart+mainnetTerm/2))\n\n\t// At the end: everything moves, whatever the balance is by then.\n\tuassert.Equal(t, int64(0), s.Locked(mainnetEnd))\n\tuassert.Equal(t, genesisBalance, s.Spendable(genesisBalance, mainnetEnd))\n}\n\nfunc TestPermilleVested(t *testing.T) {\n\ts, err := New(1000, 100, 200, Continuous)\n\tuassert.NoError(t, err)\n\n\tuassert.Equal(t, int64(0), s.PermilleVested(100))\n\tuassert.Equal(t, int64(250), s.PermilleVested(125))\n\tuassert.Equal(t, int64(1000), s.PermilleVested(200))\n\n\t// Rounds down, like everything else here.\n\ts2, err := New(3, 0, 300, Continuous)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(333), s2.PermilleVested(100)) // 1/3 of 3 = 1 -\u003e 333\n}\n\nfunc TestRemainingSeconds(t *testing.T) {\n\ts, err := New(1000, 100, 200, Continuous)\n\tuassert.NoError(t, err)\n\n\tuassert.Equal(t, int64(100), s.RemainingSeconds(100))\n\tuassert.Equal(t, int64(1), s.RemainingSeconds(199))\n\tuassert.Equal(t, int64(0), s.RemainingSeconds(200))\n\tuassert.Equal(t, int64(0), s.RemainingSeconds(10000))\n\n\tvar zero Schedule\n\tuassert.Equal(t, int64(0), zero.RemainingSeconds(0))\n}\n\nfunc TestTypeString(t *testing.T) {\n\tuassert.Equal(t, \"continuous\", Continuous.String())\n\tuassert.Equal(t, \"delayed\", Delayed.String())\n}\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"web25","path":"gno.land/p/moul/web25/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/web25`\n\nPoint a realm's on-chain page at the richer web2 frontend that also serves it,\nin one consistent line instead of a different hand-rolled banner per realm.\n\n```go\nvar cfg web25.Config\ncfg.SetRemoteFrontendByURL(\"https://example.com/app\")\n// or\ncfg.SetRemoteFrontendByCID(\"bafy...\")   // resolved through an IPFS gateway\n\nfunc Render(path string) string {\n\treturn page() + cfg.Render(path)\n}\n```\n\n`cfg.Render(path)` appends `DefaultText`, with `{link}` replaced by the\nresolved URL:\n\n\u003e Click [here]({link}) to visit the full rendering experience.\n\nSet `cfg.Text` to use your own wording; `{link}` is the only placeholder.\n`GetLink()` returns the resolved URL if you want to place it yourself.\n\n## The opt-out is the point\n\n`Render` emits nothing when the query carries `?no-web25=1` (the value matters:\na bare `?no-web25` does not disable it). That matters because a realm's\n`Render` is also read by other realms and by tooling, and a \"go look at our\nwebsite instead\" line is noise there. A caller that is not a browser appends\n`?no-web25=1` and gets the page without the pitch.\n\nIt also keeps the escape hatch visible: the web2 frontend is a convenience, and\nthe chain-rendered page has to stand on its own. If it does not, the link is\nhiding a problem rather than solving one.\n\nThe name is the thesis: web2.5 is a web2 frontend over web3 state, and the\nchain page should say so rather than pretend the frontend does not exist.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/web25/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/web25/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/web25/v0\"\ngno = \"0.9\"\n"},{"name":"web25.gno","body":"// Pacakge web25 provides an opinionated way to register an external web2\n// frontend to provide a \"better\" web2.5 experience.\npackage web25\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/realmpath/v0\"\n)\n\ntype Config struct {\n\tCID  string\n\tURL  string\n\tText string\n}\n\nfunc (c *Config) SetRemoteFrontendByURL(url string) {\n\tc.CID = \"\"\n\tc.URL = url\n}\n\nfunc (c *Config) SetRemoteFrontendByCID(cid string) {\n\tc.CID = cid\n\tc.URL = \"\"\n}\n\nfunc (c Config) GetLink() string {\n\tif c.CID != \"\" {\n\t\treturn \"https://ipfs.io/ipfs/\" + c.CID\n\t}\n\treturn c.URL\n}\n\nconst DefaultText = \"Click [here]({link}) to visit the full rendering experience.\\n\"\n\n// Render displays a frontend link at the top of your realm's Render function in\n// a concistent way to help gno visitors to have a consistent experience.\n//\n// if query is not nil, then it will check if it's not disable by ?no-web25, so\n// that you can call the render function from an external point of view.\nfunc (c Config) Render(path string) string {\n\tif realmpath.Parse(path).Query.Get(\"no-web25\") == \"1\" {\n\t\treturn \"\"\n\t}\n\ttext := c.Text\n\tif text == \"\" {\n\t\ttext = DefaultText\n\t}\n\ttext = strings.ReplaceAll(text, \"{link}\", c.GetLink())\n\treturn text\n}\n"},{"name":"web25_test.gno","body":"package web25\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"b58","path":"gno.land/p/moul/x/daily/b58/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/b58/v0`\n\n**Base58 (Bitcoin alphabet) codec** — `Encode`, `Decode`, `IsValid`, `Alphabet`.\n\nPure byte-slice math (the classic div/mod-by-58 carry loop), no `math/big`;\nleading zero bytes ↔ leading `1`s. Ported from `mr-tron/base58` / `btcutil/base58`.\n\n```go\nimport \"gno.land/p/moul/x/daily/b58/v0\"\n\ns := b58.Encode([]byte(\"hello\"))  // \"Cn8eVZg\"\nb := b58.Decode(s)                // []byte(\"hello\") (nil if s has a non-alphabet char)\n```\n\n**Live demo:** [`r/moul/x/daily/b58demo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/b58demo)\n· render it at [`/r/moul/x/daily/b58demo/v0`](https://gno.land/r/moul/x/daily/b58demo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"b58.gno","body":"// Package b58 ports the core of Bitcoin's Base58 codec (à la mr-tron/base58 and\n// btcutil/base58) to gno — as a reusable pure package.\n//\n// Base58 is a base conversion from base-256 (raw bytes) to base-58 using an\n// alphabet that omits the visually ambiguous characters 0 (zero), O (capital\n// o), I (capital i) and l (lower L). The conversion is done with pure byte-slice\n// math — the classic div/mod-by-58 carry loop — so it needs no math/big. Leading\n// zero bytes map to leading '1' characters and back, exactly like the reference\n// implementations.\n//\n// A live demo of this package (an interactive encoder / round-tripper) is at\n// [r/moul/x/daily/b58demo](/r/moul/x/daily/b58demo/v0).\npackage b58\n\nimport \"strings\"\n\n// Alphabet is the Bitcoin Base58 alphabet.\nconst Alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\n// Encode converts a byte slice to its Base58 string representation.\n//\n// Algorithm: treat the input as a big base-256 integer and repeatedly convert\n// it into base-58 digits via a carry loop, most-significant digit first. Each\n// leading zero byte becomes a leading '1'.\nfunc Encode(input []byte) string {\n\t// Count leading zero bytes — they encode as '1' and are handled apart.\n\tzeros := 0\n\tfor zeros \u003c len(input) \u0026\u0026 input[zeros] == 0 {\n\t\tzeros++\n\t}\n\n\t// Upper bound on the base-58 digit count: log(256)/log(58) ≈ 1.365, so\n\t// 138/100 of the significant byte count (+1) is always enough.\n\tsize := (len(input)-zeros)*138/100 + 1\n\tdigits := make([]byte, size)\n\n\tlength := 0\n\tfor i := zeros; i \u003c len(input); i++ {\n\t\tcarry := int(input[i])\n\t\tj := 0\n\t\t// Walk from the least-significant end, folding the new byte in.\n\t\tfor k := size - 1; (carry != 0 || j \u003c length) \u0026\u0026 k \u003e= 0; k-- {\n\t\t\tcarry += 256 * int(digits[k])\n\t\t\tdigits[k] = byte(carry % 58)\n\t\t\tcarry /= 58\n\t\t\tj++\n\t\t}\n\t\tlength = j\n\t}\n\n\t// Skip the leading zero digits produced by the over-allocation.\n\tit := size - length\n\n\tout := make([]byte, 0, zeros+length)\n\tfor i := 0; i \u003c zeros; i++ {\n\t\tout = append(out, '1')\n\t}\n\tfor ; it \u003c size; it++ {\n\t\tout = append(out, Alphabet[digits[it]])\n\t}\n\treturn string(out)\n}\n\n// Decode converts a Base58 string back to the original byte slice. It returns\n// nil if the string contains a character outside the alphabet.\n//\n// Algorithm: the mirror of Encode — treat the string as a big base-58 integer\n// and convert it back to base-256 bytes with a carry loop. Each leading '1'\n// becomes a leading zero byte.\nfunc Decode(s string) []byte {\n\t// Count leading '1's — they decode to zero bytes.\n\tzeros := 0\n\tfor zeros \u003c len(s) \u0026\u0026 s[zeros] == '1' {\n\t\tzeros++\n\t}\n\n\t// Upper bound on the byte count: log(58)/log(256) ≈ 0.733.\n\tsize := (len(s)-zeros)*733/1000 + 1\n\tbytesBuf := make([]byte, size)\n\n\tlength := 0\n\tfor i := zeros; i \u003c len(s); i++ {\n\t\tcarry := strings.IndexByte(Alphabet, s[i])\n\t\tif carry \u003c 0 {\n\t\t\treturn nil // character not in the alphabet\n\t\t}\n\t\tj := 0\n\t\tfor k := size - 1; (carry != 0 || j \u003c length) \u0026\u0026 k \u003e= 0; k-- {\n\t\t\tcarry += 58 * int(bytesBuf[k])\n\t\t\tbytesBuf[k] = byte(carry % 256)\n\t\t\tcarry /= 256\n\t\t\tj++\n\t\t}\n\t\tlength = j\n\t}\n\n\tit := size - length\n\n\tout := make([]byte, 0, zeros+length)\n\tfor i := 0; i \u003c zeros; i++ {\n\t\tout = append(out, 0)\n\t}\n\tfor ; it \u003c size; it++ {\n\t\tout = append(out, bytesBuf[it])\n\t}\n\treturn out\n}\n\n// IsValid reports whether every character of s belongs to the Base58 alphabet.\nfunc IsValid(s string) bool {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif strings.IndexByte(Alphabet, s[i]) \u003c 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"},{"name":"b58_test.gno","body":"package b58\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Known Bitcoin Base58 test vectors (hex input → Base58 string).\nvar vectors = []struct {\n\thexIn string\n\tb58   string\n}{\n\t{\"\", \"\"},\n\t{\"61\", \"2g\"},\n\t{\"626262\", \"a3gV\"},\n\t{\"636363\", \"aPEr\"},\n\t{\"73696d706c792061206c6f6e6720737472696e67\", \"2cFupjhnEsSn59qHXstmK2ffpLv2\"},\n\t{\"516b6fcd0f\", \"ABnLTmg\"},\n\t{\"bf4f89001e670274dd\", \"3SEo3LWLoPntC\"},\n\t{\"572e4794\", \"3EFU7m\"},\n\t{\"ecac89cad93923c02321\", \"EJDM8drfXA6uyA\"},\n\t{\"10c8511e\", \"Rt5zm\"},\n\t{\"00000000000000000000\", \"1111111111\"},\n\t{\"00eb15231dfceb60925886b67d065299925915aeb172c06647\", \"1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L\"},\n}\n\nfunc TestEncodeVectors(t *testing.T) {\n\tfor _, v := range vectors {\n\t\tin, err := hex.DecodeString(v.hexIn)\n\t\tuassert.NoError(t, err)\n\t\tgot := Encode(in)\n\t\tuassert.Equal(t, v.b58, got)\n\t}\n}\n\nfunc TestDecodeVectors(t *testing.T) {\n\tfor _, v := range vectors {\n\t\twant, err := hex.DecodeString(v.hexIn)\n\t\tuassert.NoError(t, err)\n\t\tgot := Decode(v.b58)\n\t\tuassert.Equal(t, hex.EncodeToString(want), hex.EncodeToString(got))\n\t}\n}\n\nfunc TestRoundTrip(t *testing.T) {\n\tinputs := []string{\n\t\t\"\",\n\t\t\"00\",\n\t\t\"0000ff\",\n\t\t\"deadbeef\",\n\t\t\"68656c6c6f20776f726c64\", // \"hello world\"\n\t\t\"ffffffffffffffff\",\n\t}\n\tfor _, hx := range inputs {\n\t\traw, err := hex.DecodeString(hx)\n\t\tuassert.NoError(t, err)\n\t\tback := Decode(Encode(raw))\n\t\tuassert.Equal(t, hex.EncodeToString(raw), hex.EncodeToString(back))\n\t}\n}\n\nfunc TestLeadingZeros(t *testing.T) {\n\tuassert.Equal(t, \"1\", Encode([]byte{0}))\n\tuassert.Equal(t, \"11\", Encode([]byte{0, 0}))\n\t// One leading zero byte + a nonzero byte.\n\tgot := Decode(\"1\" + Encode([]byte{0x2a}))\n\tuassert.Equal(t, \"002a\", hex.EncodeToString(got))\n}\n\nfunc TestIsValid(t *testing.T) {\n\tuassert.True(t, IsValid(\"2cFupjhnEsSn59qHXstmK2ffpLv2\"))\n\tuassert.True(t, IsValid(\"\")) // empty is trivially valid\n\tuassert.False(t, IsValid(\"0OIl\"))  // all four excluded characters\n\tuassert.False(t, IsValid(\"abc?\"))  // punctuation not in alphabet\n}\n\nfunc TestDecodeInvalid(t *testing.T) {\n\t// A '0' is not part of the Base58 alphabet → nil.\n\tuassert.Equal(t, true, Decode(\"invalid0char\") == nil)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/b58/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"base32","path":"gno.land/p/moul/x/daily/base32/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/base32/v0`\n\n**RFC 4648 and Crockford base32** — `Encode`, `EncodeUnpadded`,\n`EncodeCrockford`, `Decode`, `DecodeCrockford`.\n\n```go\nimport \"gno.land/p/moul/x/daily/base32/v0\"\n\nbase32.Encode(\"foobar\")           // \"MZXW6YTBOI======\"\nbase32.EncodeCrockford(\"hello\")   // \"D1JPRV3F\"\nbase32.DecodeCrockford(\"d1-jprv3f\")  // \"hello\" — case folded, hyphen ignored\n```\n\n**Two alphabets, for two different jobs.** RFC 4648 (`A–Z`, `2–7`, `=` padding)\nis the interoperable one — use it when something else has to decode the result.\nCrockford (`0–9`, `A–Z` minus `I`, `L`, `O`, `U`) is designed to be **read aloud\nand typed back**: decoding folds case, reads `I`/`L` as `1` and `O` as `0`, and\nignores hyphens, so a mis-heard identifier still decodes. `U` is excluded to\navoid accidental obscenities.\n\nVerified against the **RFC 4648 §10 vectors** at every partial-group length, and\nthe demo's pinned output is that vector set — so the example doubles as a\nconformance test.\n\nDecoding is strict where it matters: leftover bits after the final byte must be\n**zero padding, never data**, so `\"MB\"` is rejected rather than silently\ntruncated. It is lenient where it is safe: lowercase and missing padding are\naccepted.\n\nBase32 costs 60% expansion (8 characters per 5 bytes) against base64's 33%. You\npay that to get an alphabet that survives case-insensitive systems and the\ntelephone.\n\n**Live demo:** [`r/moul/x/daily/base32demo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/base32demo)\n· render it at [`/r/moul/x/daily/base32demo/v0`](https://gno.land/r/moul/x/daily/base32demo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"base32.gno","body":"// Package base32 implements RFC 4648 base32 and Crockford base32 as a pure,\n// reusable package.\n//\n// Two alphabets, for two different jobs:\n//\n//   - RFC 4648 (A–Z, 2–7) with '=' padding — the interoperable one; use it when\n//     something else has to decode the result.\n//   - Crockford (0–9, A–Z minus I, L, O and U) — designed to be read aloud and\n//     typed by humans: decoding folds case, treats I/L as 1 and O as 0, and\n//     ignores hyphens, so a mis-heard identifier still decodes. U is excluded\n//     to avoid accidental obscenities.\n//\n// Base32 costs 60% expansion (8 characters per 5 bytes) versus base64's 33%.\n// You take that hit to get an alphabet that survives case-insensitive systems\n// and being read over the phone.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/base32demo](/r/moul/x/daily/base32demo/v0).\npackage base32\n\nimport (\n\t\"errors\"\n\t\"strings\"\n)\n\n// Alphabets.\nconst (\n\tStdAlphabet       = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\"\n\tCrockfordAlphabet = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\"\n)\n\n// MaxLen bounds input so gas stays predictable.\nconst MaxLen = 4096\n\nvar (\n\t// ErrTooLong is returned when input exceeds MaxLen.\n\tErrTooLong = errors.New(\"base32: input too long\")\n\t// ErrCorrupt is returned when input is not valid base32.\n\tErrCorrupt = errors.New(\"base32: corrupt input\")\n)\n\n// encode turns src into base32 over the given alphabet, padding when pad.\nfunc encode(src, alphabet string, pad bool) (string, error) {\n\tif len(src) \u003e MaxLen {\n\t\treturn \"\", ErrTooLong\n\t}\n\tvar b strings.Builder\n\tfor i := 0; i \u003c len(src); i += 5 {\n\t\t// gather up to 5 bytes into a 40-bit group\n\t\tvar buf [5]byte\n\t\tn := 0\n\t\tfor j := 0; j \u003c 5 \u0026\u0026 i+j \u003c len(src); j++ {\n\t\t\tbuf[j] = src[i+j]\n\t\t\tn++\n\t\t}\n\t\t// 5 bytes -\u003e 8 characters of 5 bits\n\t\tvar chars [8]byte\n\t\tchars[0] = buf[0] \u003e\u003e 3\n\t\tchars[1] = (buf[0]\u00260x07)\u003c\u003c2 | buf[1]\u003e\u003e6\n\t\tchars[2] = (buf[1] \u0026 0x3E) \u003e\u003e 1\n\t\tchars[3] = (buf[1]\u00260x01)\u003c\u003c4 | buf[2]\u003e\u003e4\n\t\tchars[4] = (buf[2]\u00260x0F)\u003c\u003c1 | buf[3]\u003e\u003e7\n\t\tchars[5] = (buf[3] \u0026 0x7C) \u003e\u003e 2\n\t\tchars[6] = (buf[3]\u00260x03)\u003c\u003c3 | buf[4]\u003e\u003e5\n\t\tchars[7] = buf[4] \u0026 0x1F\n\n\t\t// how many characters this group actually carries\n\t\tout := [6]int{0, 2, 4, 5, 7, 8}[n]\n\t\tfor j := 0; j \u003c out; j++ {\n\t\t\tb.WriteByte(alphabet[chars[j]])\n\t\t}\n\t\tif pad {\n\t\t\tfor j := out; j \u003c 8; j++ {\n\t\t\t\tb.WriteByte('=')\n\t\t\t}\n\t\t}\n\t}\n\treturn b.String(), nil\n}\n\n// Encode returns the RFC 4648 base32 of src, with '=' padding.\nfunc Encode(src string) (string, error) { return encode(src, StdAlphabet, true) }\n\n// EncodeUnpadded returns RFC 4648 base32 without padding.\nfunc EncodeUnpadded(src string) (string, error) { return encode(src, StdAlphabet, false) }\n\n// EncodeCrockford returns Crockford base32, which is never padded.\nfunc EncodeCrockford(src string) (string, error) { return encode(src, CrockfordAlphabet, false) }\n\n// stdValue maps an RFC 4648 character to its 5-bit value, or -1.\nfunc stdValue(c byte) int {\n\tswitch {\n\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'Z':\n\t\treturn int(c - 'A')\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z':\n\t\treturn int(c - 'a') // tolerate lowercase on decode\n\tcase c \u003e= '2' \u0026\u0026 c \u003c= '7':\n\t\treturn int(c-'2') + 26\n\t}\n\treturn -1\n}\n\n// crockfordValue maps a Crockford character to its value, or -1.\n//\n// The forgiving part: case is folded, I and L read as 1, O reads as 0, and\n// hyphens are skipped by the caller. This is what makes a Crockford identifier\n// survive being written down and typed back in.\nfunc crockfordValue(c byte) int {\n\tif c \u003e= 'a' \u0026\u0026 c \u003c= 'z' {\n\t\tc -= 32\n\t}\n\tswitch c {\n\tcase 'O':\n\t\treturn 0\n\tcase 'I', 'L':\n\t\treturn 1\n\t}\n\tif c \u003e= '0' \u0026\u0026 c \u003c= '9' {\n\t\treturn int(c - '0')\n\t}\n\tif c \u003e= 'A' \u0026\u0026 c \u003c= 'Z' {\n\t\tif i := strings.IndexByte(CrockfordAlphabet, c); i \u003e= 0 {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n// decode turns base32 back into bytes using the given value function.\nfunc decode(s string, value func(byte) int, skipHyphen bool) (string, error) {\n\tif len(s) \u003e MaxLen {\n\t\treturn \"\", ErrTooLong\n\t}\n\t// strip padding and (for Crockford) hyphens\n\tvar clean strings.Builder\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == '=' {\n\t\t\tcontinue\n\t\t}\n\t\tif skipHyphen \u0026\u0026 c == '-' {\n\t\t\tcontinue\n\t\t}\n\t\tclean.WriteByte(c)\n\t}\n\tin := clean.String()\n\n\tvar b strings.Builder\n\tvar acc uint64\n\tbits := 0\n\tfor i := 0; i \u003c len(in); i++ {\n\t\tv := value(in[i])\n\t\tif v \u003c 0 {\n\t\t\treturn \"\", ErrCorrupt\n\t\t}\n\t\tacc = acc\u003c\u003c5 | uint64(v)\n\t\tbits += 5\n\t\tif bits \u003e= 8 {\n\t\t\tbits -= 8\n\t\t\tb.WriteByte(byte(acc \u003e\u003e uint(bits)))\n\t\t\tacc \u0026= (1 \u003c\u003c uint(bits)) - 1\n\t\t}\n\t}\n\t// leftover bits must be zero padding, never data\n\tif bits \u003e= 5 || acc != 0 {\n\t\treturn \"\", ErrCorrupt\n\t}\n\treturn b.String(), nil\n}\n\n// Decode parses RFC 4648 base32, tolerating lowercase and missing padding.\nfunc Decode(s string) (string, error) { return decode(s, stdValue, false) }\n\n// DecodeCrockford parses Crockford base32, folding case, reading I/L as 1 and\n// O as 0, and ignoring hyphens.\nfunc DecodeCrockford(s string) (string, error) { return decode(s, crockfordValue, true) }\n"},{"name":"base32_test.gno","body":"package base32\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The RFC 4648 §10 test vectors — every partial-group length.\nfunc TestRFC4648Vectors(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"f\", \"MY======\"},\n\t\t{\"fo\", \"MZXQ====\"},\n\t\t{\"foo\", \"MZXW6===\"},\n\t\t{\"foob\", \"MZXW6YQ=\"},\n\t\t{\"fooba\", \"MZXW6YTB\"},\n\t\t{\"foobar\", \"MZXW6YTBOI======\"},\n\t}\n\tfor _, c := range cases {\n\t\tgot, err := Encode(c.in)\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, c.want, got)\n\t}\n}\n\nfunc TestRFC4648RoundTrip(t *testing.T) {\n\tfor _, s := range []string{\"\", \"f\", \"fo\", \"foo\", \"foob\", \"fooba\", \"foobar\", \"hello world\"} {\n\t\tenc, err := Encode(s)\n\t\tuassert.NoError(t, err)\n\t\tdec, err2 := Decode(enc)\n\t\tuassert.NoError(t, err2)\n\t\tuassert.Equal(t, s, dec)\n\t}\n}\n\nfunc TestUnpadded(t *testing.T) {\n\tgot, _ := EncodeUnpadded(\"foobar\")\n\tuassert.Equal(t, \"MZXW6YTBOI\", got)\n\tdec, err := Decode(got) // decoding tolerates the missing padding\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"foobar\", dec)\n}\n\nfunc TestDecodeToleratesLowercase(t *testing.T) {\n\tdec, err := Decode(\"mzxw6ytboi\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"foobar\", dec)\n}\n\nfunc TestCrockfordRoundTrip(t *testing.T) {\n\tfor _, s := range []string{\"\", \"f\", \"foo\", \"foobar\", \"hello\"} {\n\t\tenc, err := EncodeCrockford(s)\n\t\tuassert.NoError(t, err)\n\t\tdec, err2 := DecodeCrockford(enc)\n\t\tuassert.NoError(t, err2)\n\t\tuassert.Equal(t, s, dec)\n\t}\n}\n\n// The point of Crockford: a mis-typed identifier still decodes.\nfunc TestCrockfordIsForgiving(t *testing.T) {\n\tenc, _ := EncodeCrockford(\"hello\")\n\twant, _ := DecodeCrockford(enc)\n\n\t// lowercase\n\tgot, err := DecodeCrockford(strings.ToLower(enc))\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, want, got)\n\n\t// hyphens are ignored, wherever they land\n\tgot2, err2 := DecodeCrockford(enc[:2] + \"-\" + enc[2:])\n\tuassert.NoError(t, err2)\n\tuassert.Equal(t, want, got2)\n\n\t// O reads as 0, I and L read as 1\n\ta, _ := DecodeCrockford(\"0\")\n\tb, _ := DecodeCrockford(\"O\")\n\tuassert.Equal(t, a, b)\n\tc, _ := DecodeCrockford(\"1\")\n\td, _ := DecodeCrockford(\"I\")\n\te, _ := DecodeCrockford(\"L\")\n\tuassert.Equal(t, c, d)\n\tuassert.Equal(t, c, e)\n}\n\n// U is excluded from the Crockford alphabet on purpose.\nfunc TestCrockfordExcludesU(t *testing.T) {\n\tuassert.Equal(t, -1, strings.IndexByte(CrockfordAlphabet, 'U'))\n\t_, err := DecodeCrockford(\"U\")\n\tuassert.ErrorIs(t, err, ErrCorrupt)\n}\n\nfunc TestDecodeRejectsGarbage(t *testing.T) {\n\tfor _, s := range []string{\"!!!\", \"MZXW6YTB@\", \"0189\"} { // 0/1/8/9 are not RFC 4648\n\t\t_, err := Decode(s)\n\t\tuassert.Error(t, err)\n\t}\n}\n\n// Leftover bits must be zero padding, never smuggled data.\nfunc TestDecodeRejectsNonZeroLeftoverBits(t *testing.T) {\n\t// \"MB\" would leave non-zero bits after emitting one byte\n\t_, err := Decode(\"MB\")\n\tuassert.ErrorIs(t, err, ErrCorrupt)\n}\n\nfunc TestTooLong(t *testing.T) {\n\t_, err := Encode(strings.Repeat(\"a\", MaxLen+1))\n\tuassert.ErrorIs(t, err, ErrTooLong)\n}\n\n// Padded output is always a multiple of 8 characters.\nfunc TestPaddingLength(t *testing.T) {\n\tfor _, s := range []string{\"f\", \"fo\", \"foo\", \"foob\", \"fooba\", \"foobar\"} {\n\t\tenc, _ := Encode(s)\n\t\tuassert.Equal(t, 0, len(enc)%8)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/base32/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bidimap","path":"gno.land/p/moul/x/daily/bidimap/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/bidimap/v0`\n\n**Bidirectional map, unique both ways** — `New`, `Put`, `PutUnique`, `Get`,\n`GetKey`, `Has`, `HasValue`, `Delete`, `DeleteValue`, `Keys`, `Values`,\n`Iterate`, `Invert`, `Clone`, `Consistent`, `MaxPairs`.\n\n```go\nimport \"gno.land/p/moul/x/daily/bidimap/v0\"\n\nm := bidimap.New()\nm.Put(\"alice\", \"admin\")\nm.Get(\"alice\")      // \"admin\", true\nm.GetKey(\"admin\")   // \"alice\", true — O(1), not a scan\n```\n\nBoth sides are unique, which is the interesting constraint: inserting a pair\nwhose value already belongs to another key must do something deliberate rather\nthan silently corrupt the reverse index.\n\n- **`Put` replaces**, and returns the pairs it displaced, so the caller sees what\n  it evicted rather than discovering it later.\n- **`PutUnique` refuses** instead, returning `false` and changing nothing.\n\nWhat is not on offer is a half-updated map. `Consistent()` is exported so callers\nand tests can assert the two indexes agree; it is true through the whole public\nAPI.\n\nOne subtlety with `MaxPairs` (4096): a full map **still accepts** a `Put` that\nrebinds an existing key or steals an existing value, because that reuses a slot\nrather than growing the map. Only a pair new on *both* sides is refused.\n\n`Keys`/`Values` come back **sorted**, never in map order: gno map iteration order\nis unspecified, and a `Render` built from one can differ between nodes.\n\n**Live demo:** [`r/moul/x/daily/bidimapdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/bidimapdemo)\n· render it at [`/r/moul/x/daily/bidimapdemo/v0`](https://gno.land/r/moul/x/daily/bidimapdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bidimap.gno","body":"// Package bidimap is a bidirectional map — unique in both directions — as a\n// pure, reusable package.\n//\n// A normal map answers \"what is the value for this key\". A bidirectional one\n// also answers the reverse in O(1), by keeping a second index. The cost is an\n// invariant a plain pair of maps does not give you: BOTH sides are unique, so\n// inserting a pair whose value already belongs to another key must do something\n// deliberate rather than silently corrupt the reverse index.\n//\n// This implementation makes that choice explicit. Put REPLACES: it evicts any\n// existing pairing on either side first, so the two indexes can never disagree.\n// PutUnique refuses instead, returning false. Pick whichever the caller wants;\n// what is not on offer is a half-updated map.\n//\n// Iteration is over sorted keys, never a built-in map range: gno map iteration\n// order is unspecified, and a Render built from one can differ between nodes,\n// which is a consensus bug rather than a cosmetic one.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/bidimapdemo](/r/moul/x/daily/bidimapdemo/v0).\npackage bidimap\n\nimport \"sort\"\n\n// MaxPairs bounds the map so gas stays predictable.\nconst MaxPairs = 4096\n\n// BiMap is a string\u003c-\u003estring map, unique in both directions.\ntype BiMap struct {\n\tfwd map[string]string\n\trev map[string]string\n}\n\n// New returns an empty BiMap.\nfunc New() *BiMap {\n\treturn \u0026BiMap{fwd: map[string]string{}, rev: map[string]string{}}\n}\n\n// Len returns the number of pairs.\nfunc (m *BiMap) Len() int { return len(m.fwd) }\n\n// Get returns the value bound to key.\nfunc (m *BiMap) Get(key string) (string, bool) {\n\tv, ok := m.fwd[key]\n\treturn v, ok\n}\n\n// GetKey returns the key bound to value — the reverse lookup, also O(1).\nfunc (m *BiMap) GetKey(value string) (string, bool) {\n\tk, ok := m.rev[value]\n\treturn k, ok\n}\n\n// Has reports whether key is present.\nfunc (m *BiMap) Has(key string) bool { _, ok := m.fwd[key]; return ok }\n\n// HasValue reports whether value is present.\nfunc (m *BiMap) HasValue(value string) bool { _, ok := m.rev[value]; return ok }\n\n// Put binds key\u003c-\u003evalue, REPLACING any existing pairing on either side. It\n// returns the pairs that were evicted to make room, so the caller can see what\n// it displaced rather than discovering it later.\n//\n// Returns ok=false only when the map is full and the pair is entirely new.\nfunc (m *BiMap) Put(key, value string) (evicted [][2]string, ok bool) {\n\toldValue, keyTaken := m.fwd[key]\n\n\t// Already exactly this pair: nothing to do.\n\tif keyTaken \u0026\u0026 oldValue == value {\n\t\treturn nil, true\n\t}\n\n\toldKey, valueTaken := m.rev[value]\n\n\t// Only a pair that is new on BOTH sides grows the map. Rebinding either\n\t// side reuses a slot, so it stays allowed at capacity. Checked up front:\n\t// evicting first and rolling back on failure would be unreachable code,\n\t// since any eviction frees the very slot the check is about.\n\tif !keyTaken \u0026\u0026 !valueTaken \u0026\u0026 len(m.fwd) \u003e= MaxPairs {\n\t\treturn nil, false\n\t}\n\n\tif keyTaken {\n\t\tevicted = append(evicted, [2]string{key, oldValue})\n\t\tdelete(m.rev, oldValue)\n\t\tdelete(m.fwd, key)\n\t}\n\tif valueTaken {\n\t\tevicted = append(evicted, [2]string{oldKey, value})\n\t\tdelete(m.fwd, oldKey)\n\t\tdelete(m.rev, value)\n\t}\n\n\tm.fwd[key] = value\n\tm.rev[value] = key\n\treturn evicted, true\n}\n\n// PutUnique binds key\u003c-\u003evalue only when NEITHER side is already taken by a\n// different pairing. Returns false without changing anything otherwise.\nfunc (m *BiMap) PutUnique(key, value string) bool {\n\tif v, exists := m.fwd[key]; exists {\n\t\treturn v == value // idempotent for the identical pair\n\t}\n\tif _, exists := m.rev[value]; exists {\n\t\treturn false\n\t}\n\tif len(m.fwd) \u003e= MaxPairs {\n\t\treturn false\n\t}\n\tm.fwd[key] = value\n\tm.rev[value] = key\n\treturn true\n}\n\n// Delete removes the pair for key. Returns false when key is absent.\nfunc (m *BiMap) Delete(key string) bool {\n\tv, ok := m.fwd[key]\n\tif !ok {\n\t\treturn false\n\t}\n\tdelete(m.fwd, key)\n\tdelete(m.rev, v)\n\treturn true\n}\n\n// DeleteValue removes the pair for value. Returns false when value is absent.\nfunc (m *BiMap) DeleteValue(value string) bool {\n\tk, ok := m.rev[value]\n\tif !ok {\n\t\treturn false\n\t}\n\tdelete(m.fwd, k)\n\tdelete(m.rev, value)\n\treturn true\n}\n\n// Keys returns every key, sorted. Sorted, not map order: a Render built from an\n// unspecified order can differ between nodes.\nfunc (m *BiMap) Keys() []string { return sortedKeys(m.fwd) }\n\n// Values returns every value, sorted.\nfunc (m *BiMap) Values() []string { return sortedKeys(m.rev) }\n\n// Iterate calls fn for each pair in sorted key order. Returning true stops.\nfunc (m *BiMap) Iterate(fn func(key, value string) bool) {\n\tfor _, k := range m.Keys() {\n\t\tif fn(k, m.fwd[k]) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// Invert returns a new BiMap with keys and values swapped.\nfunc (m *BiMap) Invert() *BiMap {\n\tout := New()\n\tfor k, v := range m.fwd {\n\t\tout.fwd[v] = k\n\t\tout.rev[k] = v\n\t}\n\treturn out\n}\n\n// Clone returns an independent copy.\nfunc (m *BiMap) Clone() *BiMap {\n\tout := New()\n\tfor k, v := range m.fwd {\n\t\tout.fwd[k] = v\n\t\tout.rev[v] = k\n\t}\n\treturn out\n}\n\n// Consistent reports whether the two indexes agree. Always true through the\n// public API; exported so tests and callers can assert the invariant directly.\nfunc (m *BiMap) Consistent() bool {\n\tif len(m.fwd) != len(m.rev) {\n\t\treturn false\n\t}\n\tfor k, v := range m.fwd {\n\t\tif back, ok := m.rev[v]; !ok || back != k {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc sortedKeys(m map[string]string) []string {\n\tout := make([]string, 0, len(m))\n\tfor k := range m {\n\t\tout = append(out, k)\n\t}\n\tsort.Strings(out)\n\treturn out\n}\n"},{"name":"bidimap_test.gno","body":"package bidimap\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestEmpty(t *testing.T) {\n\tm := New()\n\tuassert.Equal(t, 0, m.Len())\n\tuassert.False(t, m.Has(\"a\"))\n\tuassert.False(t, m.HasValue(\"1\"))\n\tuassert.True(t, m.Consistent(), \"an empty map is consistent\")\n}\n\nfunc TestPutAndBothLookups(t *testing.T) {\n\tm := New()\n\t_, ok := m.Put(\"alice\", \"admin\")\n\tuassert.True(t, ok)\n\n\tv, found := m.Get(\"alice\")\n\tuassert.True(t, found)\n\tuassert.Equal(t, \"admin\", v)\n\n\tk, found := m.GetKey(\"admin\")\n\tuassert.True(t, found)\n\tuassert.Equal(t, \"alice\", k, \"the reverse lookup is the point of the type\")\n\n\tuassert.True(t, m.Has(\"alice\"))\n\tuassert.True(t, m.HasValue(\"admin\"))\n\tuassert.True(t, m.Consistent())\n}\n\nfunc TestMissingLookups(t *testing.T) {\n\tm := New()\n\tm.Put(\"a\", \"1\")\n\n\t_, ok := m.Get(\"nope\")\n\tuassert.False(t, ok)\n\t_, ok = m.GetKey(\"nope\")\n\tuassert.False(t, ok)\n}\n\n// TestPutReplacesOnKeySide is the invariant that a naive pair-of-maps breaks:\n// rebinding a key must drop the old value from the reverse index too.\nfunc TestPutReplacesOnKeySide(t *testing.T) {\n\tm := New()\n\tm.Put(\"alice\", \"admin\")\n\n\tevicted, ok := m.Put(\"alice\", \"auditor\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 1, len(evicted))\n\tuassert.Equal(t, \"alice\", evicted[0][0])\n\tuassert.Equal(t, \"admin\", evicted[0][1])\n\n\tuassert.False(t, m.HasValue(\"admin\"), \"the stale value must leave the reverse index\")\n\tuassert.Equal(t, 1, m.Len())\n\tuassert.True(t, m.Consistent())\n}\n\n// TestPutReplacesOnValueSide is the mirror case: stealing a value must unbind\n// whoever held it.\nfunc TestPutReplacesOnValueSide(t *testing.T) {\n\tm := New()\n\tm.Put(\"alice\", \"admin\")\n\n\tevicted, ok := m.Put(\"bob\", \"admin\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 1, len(evicted))\n\tuassert.Equal(t, \"alice\", evicted[0][0])\n\n\tuassert.False(t, m.Has(\"alice\"), \"alice lost her binding to bob\")\n\tk, _ := m.GetKey(\"admin\")\n\tuassert.Equal(t, \"bob\", k)\n\tuassert.Equal(t, 1, m.Len())\n\tuassert.True(t, m.Consistent())\n}\n\n// TestPutEvictsBothSides covers the case where the new pair displaces two\n// different existing pairs at once.\nfunc TestPutEvictsBothSides(t *testing.T) {\n\tm := New()\n\tm.Put(\"alice\", \"admin\")\n\tm.Put(\"bob\", \"auditor\")\n\n\tevicted, ok := m.Put(\"alice\", \"auditor\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 2, len(evicted), \"displaces alice-\u003eadmin and bob-\u003eauditor\")\n\n\tuassert.Equal(t, 1, m.Len())\n\tuassert.False(t, m.Has(\"bob\"))\n\tuassert.False(t, m.HasValue(\"admin\"))\n\tuassert.True(t, m.Consistent())\n}\n\nfunc TestPutIdenticalPairIsNoop(t *testing.T) {\n\tm := New()\n\tm.Put(\"a\", \"1\")\n\tevicted, ok := m.Put(\"a\", \"1\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 0, len(evicted), \"re-putting the same pair evicts nothing\")\n\tuassert.Equal(t, 1, m.Len())\n}\n\nfunc TestPutUniqueRefuses(t *testing.T) {\n\tm := New()\n\tuassert.True(t, m.PutUnique(\"alice\", \"admin\"))\n\n\tuassert.False(t, m.PutUnique(\"alice\", \"auditor\"), \"key already bound\")\n\tuassert.False(t, m.PutUnique(\"bob\", \"admin\"), \"value already bound\")\n\tuassert.True(t, m.PutUnique(\"alice\", \"admin\"), \"identical pair is idempotent\")\n\n\t// Nothing changed.\n\tuassert.Equal(t, 1, m.Len())\n\tv, _ := m.Get(\"alice\")\n\tuassert.Equal(t, \"admin\", v)\n\tuassert.True(t, m.Consistent())\n}\n\nfunc TestDelete(t *testing.T) {\n\tm := New()\n\tm.Put(\"a\", \"1\")\n\n\tuassert.True(t, m.Delete(\"a\"))\n\tuassert.Equal(t, 0, m.Len())\n\tuassert.False(t, m.HasValue(\"1\"), \"delete clears the reverse index too\")\n\tuassert.False(t, m.Delete(\"a\"), \"deleting twice reports false\")\n\tuassert.True(t, m.Consistent())\n}\n\nfunc TestDeleteValue(t *testing.T) {\n\tm := New()\n\tm.Put(\"a\", \"1\")\n\n\tuassert.True(t, m.DeleteValue(\"1\"))\n\tuassert.False(t, m.Has(\"a\"), \"delete-by-value clears the forward index too\")\n\tuassert.False(t, m.DeleteValue(\"1\"))\n\tuassert.True(t, m.Consistent())\n}\n\n// TestKeysAndValuesAreSorted is the determinism guarantee.\nfunc TestKeysAndValuesAreSorted(t *testing.T) {\n\tm := New()\n\tm.Put(\"delta\", \"4\")\n\tm.Put(\"alpha\", \"1\")\n\tm.Put(\"charlie\", \"3\")\n\n\tuassert.Equal(t, \"alpha,charlie,delta\", strings.Join(m.Keys(), \",\"))\n\tuassert.Equal(t, \"1,3,4\", strings.Join(m.Values(), \",\"))\n}\n\nfunc TestIterateSortedAndStops(t *testing.T) {\n\tm := New()\n\tm.Put(\"b\", \"2\")\n\tm.Put(\"a\", \"1\")\n\tm.Put(\"c\", \"3\")\n\n\tvar seen []string\n\tm.Iterate(func(k, v string) bool {\n\t\tseen = append(seen, k+\"=\"+v)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"a=1,b=2,c=3\", strings.Join(seen, \",\"))\n\n\tvar first []string\n\tm.Iterate(func(k, v string) bool {\n\t\tfirst = append(first, k)\n\t\treturn true // stop immediately\n\t})\n\tuassert.Equal(t, 1, len(first))\n\tuassert.Equal(t, \"a\", first[0])\n}\n\nfunc TestInvert(t *testing.T) {\n\tm := New()\n\tm.Put(\"alice\", \"admin\")\n\tm.Put(\"bob\", \"auditor\")\n\n\tinv := m.Invert()\n\tv, ok := inv.Get(\"admin\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"alice\", v)\n\tuassert.True(t, inv.Consistent())\n\n\t// Independent of the original.\n\tinv.Delete(\"admin\")\n\tuassert.Equal(t, 2, m.Len())\n}\n\nfunc TestClone(t *testing.T) {\n\tm := New()\n\tm.Put(\"a\", \"1\")\n\n\tcp := m.Clone()\n\tcp.Put(\"b\", \"2\")\n\n\tuassert.Equal(t, 1, m.Len(), \"clone must not share storage\")\n\tuassert.Equal(t, 2, cp.Len())\n\tuassert.True(t, cp.Consistent())\n}\n\nfunc TestMaxPairs(t *testing.T) {\n\tm := New()\n\tfor i := 0; i \u003c MaxPairs; i++ {\n\t\ts := strconv.Itoa(i)\n\t\t_, ok := m.Put(\"k\"+s, \"v\"+s)\n\t\tuassert.True(t, ok, \"should accept up to MaxPairs\")\n\t}\n\tuassert.Equal(t, MaxPairs, m.Len())\n\n\t_, ok := m.Put(\"overflow\", \"value\")\n\tuassert.False(t, ok, \"a full map refuses a wholly new pair\")\n\tuassert.False(t, m.PutUnique(\"overflow\", \"value\"))\n\tuassert.Equal(t, MaxPairs, m.Len())\n}\n\n// TestFullMapStillRebinds pins the subtler half of the capacity rule: a full\n// map still accepts a Put that rebinds an existing key or steals an existing\n// value, because that reuses a slot rather than growing the map. Only a pair\n// new on BOTH sides is refused.\nfunc TestFullMapStillRebinds(t *testing.T) {\n\tm := New()\n\tfor i := 0; i \u003c MaxPairs; i++ {\n\t\ts := strconv.Itoa(i)\n\t\tm.Put(\"k\"+s, \"v\"+s)\n\t}\n\n\t// New value, existing key -\u003e reuses k0's slot, so it is allowed.\n\tevicted, ok := m.Put(\"k0\", \"brand-new-value\")\n\tuassert.True(t, ok, \"rebinding an existing key does not grow a full map\")\n\tuassert.Equal(t, 1, len(evicted))\n\tuassert.Equal(t, \"v0\", evicted[0][1])\n\n\tv, _ := m.Get(\"k0\")\n\tuassert.Equal(t, \"brand-new-value\", v)\n\tuassert.Equal(t, MaxPairs, m.Len(), \"size is unchanged\")\n\tuassert.True(t, m.Consistent())\n\n\t// New key, existing value -\u003e reuses that value's slot, also allowed.\n\t_, ok = m.Put(\"brand-new-key\", \"v1\")\n\tuassert.True(t, ok, \"stealing an existing value does not grow a full map\")\n\tuassert.Equal(t, MaxPairs, m.Len())\n\tuassert.False(t, m.Has(\"k1\"), \"k1 lost its binding\")\n\tuassert.True(t, m.Consistent())\n\n\t// New on both sides -\u003e refused, and nothing changes.\n\t_, ok = m.Put(\"wholly\", \"new\")\n\tuassert.False(t, ok, \"a full map refuses a pair new on both sides\")\n\tuassert.Equal(t, MaxPairs, m.Len())\n\tuassert.True(t, m.Consistent())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/bidimap/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bitset","path":"gno.land/p/moul/x/daily/bitset/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/bitset/v0`\n\n**Dense fixed-capacity bit vector** — `New`, `FromSlice`, `Set`, `Clear`, `Flip`,\n`Has`, `Count`, `Slice`, `Clone`, `Union`, `Intersect`, `Difference`,\n`SymmetricDifference`, `Equal`, `MaxBits`.\n\nA compact set of small non-negative integers. Storage is `[]uint64` of\n`ceil(n/64)` words, so 1024 bits cost 16 words instead of 1024 booleans — the\nreason to reach for this on chain, where every byte is paid for.\n\n```go\nimport \"gno.land/p/moul/x/daily/bitset/v0\"\n\nb := bitset.FromSlice(20, []int{1, 2, 3})\nc := bitset.FromSlice(20, []int{3, 4})\nbitset.Union(b, c).Slice()       // [1 2 3 4]\nbitset.Intersect(b, c).Slice()   // [3]\nb.Count()                        // 3\n```\n\nCapacity is **fixed** at construction: operations are bounds-checked and return\n`false` out of range rather than growing, because silent growth would make gas\nunpredictable. `Has` on an out-of-range index is simply `false` — something that\ncannot be a member is not a member.\n\nCombining two sets of **different** capacities returns `nil` rather than padding\none silently; a size mismatch is a caller error worth surfacing.\n\n`MaxBits` (65536) caps allocation. Note `String()` prints bit 0 first, so it\nreads in index order — the reverse of binary notation.\n\n**Live demo:** [`r/moul/x/daily/bitsetdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/bitsetdemo)\n· render it at [`/r/moul/x/daily/bitsetdemo/v0`](https://gno.land/r/moul/x/daily/bitsetdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bitset.gno","body":"// Package bitset is a dense, fixed-capacity bit vector as a pure, reusable\n// package: a compact set of small non-negative integers with the usual\n// set algebra (union, intersection, difference).\n//\n// Storage is a []uint64 of ceil(n/64) words, so 1024 bits cost 16 words rather\n// than 1024 booleans — the reason to reach for this on chain, where every byte\n// is paid for.\n//\n// Capacity is fixed at construction and every operation is bounds-checked\n// rather than growing: an out-of-range index is a caller bug, and silently\n// growing would make gas unpredictable.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/bitsetdemo](/r/moul/x/daily/bitsetdemo/v0).\npackage bitset\n\nimport \"strings\"\n\n// MaxBits bounds a BitSet so allocation and iteration stay predictable.\nconst MaxBits = 1 \u003c\u003c 16 // 65536 bits = 1024 words = 8 KiB\n\n// BitSet is a fixed-capacity set of integers in [0, n).\ntype BitSet struct {\n\tn     int\n\twords []uint64\n}\n\n// New returns a BitSet holding bits [0, n). n is clamped to [0, MaxBits].\nfunc New(n int) *BitSet {\n\tif n \u003c 0 {\n\t\tn = 0\n\t}\n\tif n \u003e MaxBits {\n\t\tn = MaxBits\n\t}\n\treturn \u0026BitSet{n: n, words: make([]uint64, (n+63)/64)}\n}\n\n// Cap returns the capacity in bits.\nfunc (b *BitSet) Cap() int { return b.n }\n\n// InRange reports whether i is a valid index.\nfunc (b *BitSet) InRange(i int) bool { return i \u003e= 0 \u0026\u0026 i \u003c b.n }\n\n// Set turns bit i on and reports whether i was in range.\nfunc (b *BitSet) Set(i int) bool {\n\tif !b.InRange(i) {\n\t\treturn false\n\t}\n\tb.words[i/64] |= 1 \u003c\u003c uint(i%64)\n\treturn true\n}\n\n// Clear turns bit i off and reports whether i was in range.\nfunc (b *BitSet) Clear(i int) bool {\n\tif !b.InRange(i) {\n\t\treturn false\n\t}\n\tb.words[i/64] \u0026^= 1 \u003c\u003c uint(i%64)\n\treturn true\n}\n\n// Flip inverts bit i and reports whether i was in range.\nfunc (b *BitSet) Flip(i int) bool {\n\tif !b.InRange(i) {\n\t\treturn false\n\t}\n\tb.words[i/64] ^= 1 \u003c\u003c uint(i%64)\n\treturn true\n}\n\n// Has reports whether bit i is set. Out of range is false, never a panic:\n// membership of something that cannot be a member is simply false.\nfunc (b *BitSet) Has(i int) bool {\n\tif !b.InRange(i) {\n\t\treturn false\n\t}\n\treturn b.words[i/64]\u0026(1\u003c\u003cuint(i%64)) != 0\n}\n\n// Count returns the number of set bits (popcount).\nfunc (b *BitSet) Count() int {\n\ttotal := 0\n\tfor _, w := range b.words {\n\t\ttotal += popcount(w)\n\t}\n\treturn total\n}\n\n// popcount counts set bits with the classic SWAR trick — no math/bits on gno.\nfunc popcount(x uint64) int {\n\tn := 0\n\tfor x != 0 {\n\t\tx \u0026= x - 1 // clear the lowest set bit\n\t\tn++\n\t}\n\treturn n\n}\n\n// Slice returns the set bits in ascending order.\nfunc (b *BitSet) Slice() []int {\n\tout := []int{}\n\tfor i := 0; i \u003c b.n; i++ {\n\t\tif b.Has(i) {\n\t\t\tout = append(out, i)\n\t\t}\n\t}\n\treturn out\n}\n\n// Clone returns an independent copy.\nfunc (b *BitSet) Clone() *BitSet {\n\tc := New(b.n)\n\tcopy(c.words, b.words)\n\treturn c\n}\n\n// sameCap reports whether two sets can be combined word-wise.\nfunc sameCap(a, b *BitSet) bool { return a != nil \u0026\u0026 b != nil \u0026\u0026 a.n == b.n }\n\n// Union returns a ∪ b, or nil when the capacities differ. Mismatched capacities\n// are a caller error rather than something to silently pad.\nfunc Union(a, b *BitSet) *BitSet { return combine(a, b, \"or\") }\n\n// Intersect returns a ∩ b, or nil when the capacities differ.\nfunc Intersect(a, b *BitSet) *BitSet { return combine(a, b, \"and\") }\n\n// Difference returns a \\ b, or nil when the capacities differ.\nfunc Difference(a, b *BitSet) *BitSet { return combine(a, b, \"andnot\") }\n\n// SymmetricDifference returns a △ b, or nil when the capacities differ.\nfunc SymmetricDifference(a, b *BitSet) *BitSet { return combine(a, b, \"xor\") }\n\nfunc combine(a, b *BitSet, op string) *BitSet {\n\tif !sameCap(a, b) {\n\t\treturn nil\n\t}\n\tout := New(a.n)\n\tfor i := range a.words {\n\t\tswitch op {\n\t\tcase \"or\":\n\t\t\tout.words[i] = a.words[i] | b.words[i]\n\t\tcase \"and\":\n\t\t\tout.words[i] = a.words[i] \u0026 b.words[i]\n\t\tcase \"andnot\":\n\t\t\tout.words[i] = a.words[i] \u0026^ b.words[i]\n\t\tcase \"xor\":\n\t\t\tout.words[i] = a.words[i] ^ b.words[i]\n\t\t}\n\t}\n\treturn out\n}\n\n// Equal reports whether two sets have the same capacity and the same bits.\nfunc Equal(a, b *BitSet) bool {\n\tif !sameCap(a, b) {\n\t\treturn false\n\t}\n\tfor i := range a.words {\n\t\tif a.words[i] != b.words[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// String renders the set as '0'/'1' from bit 0 upward, which reads left-to-right\n// in index order (note this is the reverse of binary notation).\nfunc (b *BitSet) String() string {\n\tvar sb strings.Builder\n\tfor i := 0; i \u003c b.n; i++ {\n\t\tif b.Has(i) {\n\t\t\tsb.WriteByte('1')\n\t\t} else {\n\t\t\tsb.WriteByte('0')\n\t\t}\n\t}\n\treturn sb.String()\n}\n\n// FromSlice builds a BitSet of capacity n containing the given indices.\n// Out-of-range indices are ignored.\nfunc FromSlice(n int, idx []int) *BitSet {\n\tb := New(n)\n\tfor _, i := range idx {\n\t\tb.Set(i)\n\t}\n\treturn b\n}\n"},{"name":"bitset_test.gno","body":"package bitset\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestSetHasClear(t *testing.T) {\n\tb := New(100)\n\tuassert.False(t, b.Has(7))\n\tuassert.True(t, b.Set(7))\n\tuassert.True(t, b.Has(7))\n\tuassert.True(t, b.Clear(7))\n\tuassert.False(t, b.Has(7))\n}\n\n// Out of range is reported, never a panic — and Has is simply false.\nfunc TestOutOfRange(t *testing.T) {\n\tb := New(64)\n\tfor _, i := range []int{-1, 64, 1000} {\n\t\tuassert.False(t, b.Set(i))\n\t\tuassert.False(t, b.Clear(i))\n\t\tuassert.False(t, b.Flip(i))\n\t\tuassert.False(t, b.Has(i))\n\t}\n\tuassert.Equal(t, 0, b.Count())\n}\n\n// Word boundaries are where an off-by-one lives: check either side of 64.\nfunc TestWordBoundaries(t *testing.T) {\n\tb := New(200)\n\tfor _, i := range []int{0, 63, 64, 65, 127, 128, 199} {\n\t\tuassert.True(t, b.Set(i))\n\t}\n\tuassert.Equal(t, 7, b.Count())\n\tfor _, i := range []int{0, 63, 64, 65, 127, 128, 199} {\n\t\tuassert.True(t, b.Has(i))\n\t}\n\tuassert.False(t, b.Has(62))\n\tuassert.False(t, b.Has(129))\n}\n\nfunc TestFlip(t *testing.T) {\n\tb := New(10)\n\tb.Flip(3)\n\tuassert.True(t, b.Has(3))\n\tb.Flip(3)\n\tuassert.False(t, b.Has(3))\n}\n\nfunc TestCountAndSlice(t *testing.T) {\n\tb := FromSlice(50, []int{1, 5, 9, 49})\n\tuassert.Equal(t, 4, b.Count())\n\tuassert.Equal(t, \"1,5,9,49\", join(b.Slice()))\n}\n\nfunc TestFromSliceIgnoresOutOfRange(t *testing.T) {\n\tb := FromSlice(10, []int{1, -3, 10, 99, 4})\n\tuassert.Equal(t, \"1,4\", join(b.Slice()))\n}\n\nfunc TestSetAlgebra(t *testing.T) {\n\ta := FromSlice(20, []int{1, 2, 3})\n\tb := FromSlice(20, []int{3, 4})\n\tuassert.Equal(t, \"1,2,3,4\", join(Union(a, b).Slice()))\n\tuassert.Equal(t, \"3\", join(Intersect(a, b).Slice()))\n\tuassert.Equal(t, \"1,2\", join(Difference(a, b).Slice()))\n\tuassert.Equal(t, \"1,2,4\", join(SymmetricDifference(a, b).Slice()))\n}\n\n// Combining different capacities is a caller error: nil, not a silent pad.\nfunc TestMismatchedCapacityIsNil(t *testing.T) {\n\ta := New(10)\n\tb := New(20)\n\tuassert.True(t, Union(a, b) == nil)\n\tuassert.True(t, Intersect(a, b) == nil)\n\tuassert.True(t, Difference(a, b) == nil)\n\tuassert.True(t, SymmetricDifference(a, b) == nil)\n\tuassert.False(t, Equal(a, b))\n}\n\nfunc TestCloneIsIndependent(t *testing.T) {\n\ta := FromSlice(30, []int{1, 2})\n\tc := a.Clone()\n\tc.Set(29)\n\tuassert.False(t, a.Has(29))\n\tuassert.True(t, Equal(a, FromSlice(30, []int{1, 2})))\n}\n\nfunc TestEqual(t *testing.T) {\n\tuassert.True(t, Equal(FromSlice(8, []int{1, 3}), FromSlice(8, []int{3, 1})))\n\tuassert.False(t, Equal(FromSlice(8, []int{1}), FromSlice(8, []int{2})))\n}\n\nfunc TestString(t *testing.T) {\n\tuassert.Equal(t, \"01010\", FromSlice(5, []int{1, 3}).String())\n}\n\nfunc TestCapClamped(t *testing.T) {\n\tuassert.Equal(t, 0, New(-5).Cap())\n\tuassert.Equal(t, MaxBits, New(MaxBits+1000).Cap())\n}\n\nfunc TestPopcount(t *testing.T) {\n\tuassert.Equal(t, 0, popcount(0))\n\tuassert.Equal(t, 1, popcount(1))\n\tuassert.Equal(t, 64, popcount(^uint64(0)))\n}\n\nfunc join(xs []int) string {\n\tparts := []string{}\n\tfor _, x := range xs {\n\t\tparts = append(parts, itoa(x))\n\t}\n\treturn strings.Join(parts, \",\")\n}\n\nfunc itoa(i int) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\tneg := i \u003c 0\n\tif neg {\n\t\ti = -i\n\t}\n\tvar b []byte\n\tfor i \u003e 0 {\n\t\tb = append([]byte{byte('0' + i%10)}, b...)\n\t\ti /= 10\n\t}\n\tif neg {\n\t\treturn \"-\" + string(b)\n\t}\n\treturn string(b)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/bitset/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"cliffvesting","path":"gno.land/p/moul/x/daily/cliffvesting/v1","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/cliffvesting/v0`\n\n**Cliff-then-linear vesting calculator** — `New`, `NewLinear`, `Vested`,\n`Unvested`, `Claimable`, `PercentVested`, `CliffAmount`, `IsFullyVested`,\n`Duration`, `HasCliff`.\n\n```go\nimport \"gno.land/p/moul/x/daily/cliffvesting/v0\"\n\ns, _ := cliffvesting.New(1200, 0, 3, 12) // total, start, cliff, end\ns.Vested(2)          // 0   — before the cliff\ns.Vested(3)          // 300 — the cliff releases the elapsed portion at once\ns.Vested(12)         // 1200\ns.Claimable(6, 300)  // 300 — vested minus already claimed\n```\n\n**Pure.** No state, no balances, no transfers. The arithmetic is the part that is\neasy to get subtly wrong and easy to test; custody belongs to the realm holding\nthe coins.\n\nThe cliff is a **step, not a ramp**: nothing vests before it, then the whole\nelapsed portion unlocks at once, and the rest accrues linearly.\n\n**All integer arithmetic** — no float ever reaches consensus state:\n\n- `total*elapsed/duration`, multiplying **first**. The reverse computes a\n  per-tick rate that truncates to zero whenever `total \u003c duration`, so nothing\n  would ever vest. That is the classic vesting bug; it has its own test\n  (7 tokens over 1000 ticks).\n- Rounding is **down**, so a beneficiary is never paid more than they earned,\n  and the **final instalment collects the remainder**: 1000 over 3 periods is\n  `333 + 333 + 334`, and `Vested(end)` is exactly `total`, never `total-1`.\n- `Claimable` never returns negative, even if the caller's bookkeeping says more\n  was claimed than has vested.\n\nTimes are `int64`, so the caller may use block heights or unix seconds — the unit\nonly has to be consistent.\n\n**Live demo:** [`r/moul/x/daily/cliffvestingdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/cliffvestingdemo)\n· render it at [`/r/moul/x/daily/cliffvestingdemo/v0`](https://gno.land/r/moul/x/daily/cliffvestingdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"cliffvesting.gno","body":"// Package cliffvesting computes cliff-then-linear vesting schedules as a PURE\n// calculator: no state, no balances, no transfers.\n//\n// The shape is the standard employee/token grant: nothing vests until the\n// cliff, the cliff releases the whole elapsed portion at once, and the rest\n// accrues linearly until the end of the term. Keeping it pure is deliberate:\n// the arithmetic is the part that is easy to get subtly wrong and easy to test,\n// while custody belongs to the realm holding the coins.\n//\n// Everything is integer arithmetic. Vested is computed as\n// total*elapsed/duration with the multiplication FIRST, so the usual rounding\n// bug, dividing before multiplying and truncating the rate to zero, cannot\n// happen. Rounding is always DOWN, which means the beneficiary never receives\n// more than they have earned and the final instalment collects the remainder;\n// at t \u003e= end the result is exactly total, never total-1.\n//\n// The multiplication goes through a 128-bit intermediate. v0 did it in plain\n// int64, which silently WRAPPED once total*elapsed passed 2^63: over a\n// two-year term in seconds that is any grant above ~146,036 whole coins, and\n// a large one reported a NEGATIVE vested amount rather than failing. See\n// [Schedule.Vested].\n//\n// Times are int64 so the caller can use block heights or unix seconds. The unit\n// only has to be consistent.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/cliffvestingdemo](/r/moul/x/daily/cliffvestingdemo/v0).\npackage cliffvesting\n\nimport (\n\t\"errors\"\n\t\"math/bits\"\n)\n\nvar (\n\tErrBadTotal    = errors.New(\"cliffvesting: total must be positive\")\n\tErrBadDuration = errors.New(\"cliffvesting: duration must be positive\")\n\tErrCliffAfter  = errors.New(\"cliffvesting: cliff must not fall after the end\")\n\tErrCliffBefore = errors.New(\"cliffvesting: cliff must not fall before the start\")\n)\n\n// Schedule is a cliff-then-linear vesting plan. Construct with New so the\n// invariants are checked once.\ntype Schedule struct {\n\tTotal int64 // total amount to vest\n\tStart int64 // vesting begins\n\tCliff int64 // nothing is claimable before this\n\tEnd   int64 // fully vested at or after this\n}\n\n// New validates and returns a Schedule. cliff must lie within [start, end].\n// Passing cliff == start means \"no cliff\".\nfunc New(total, start, cliff, end int64) (Schedule, error) {\n\ts := Schedule{Total: total, Start: start, Cliff: cliff, End: end}\n\tif total \u003c= 0 {\n\t\treturn Schedule{}, ErrBadTotal\n\t}\n\tif end \u003c= start {\n\t\treturn Schedule{}, ErrBadDuration\n\t}\n\tif cliff \u003e end {\n\t\treturn Schedule{}, ErrCliffAfter\n\t}\n\tif cliff \u003c start {\n\t\treturn Schedule{}, ErrCliffBefore\n\t}\n\treturn s, nil\n}\n\n// NewLinear is New with no cliff.\nfunc NewLinear(total, start, end int64) (Schedule, error) {\n\treturn New(total, start, start, end)\n}\n\n// Duration returns the length of the vesting term.\nfunc (s Schedule) Duration() int64 { return s.End - s.Start }\n\n// HasCliff reports whether the schedule has a non-trivial cliff.\nfunc (s Schedule) HasCliff() bool { return s.Cliff \u003e s.Start }\n\n// Vested returns how much has vested at time t. Zero before the cliff, exactly\n// Total at or after End, and floor(total*elapsed/duration) in between.\n//\n// The product goes through [mulDiv] rather than int64. v0 computed\n// `s.Total * elapsed / s.Duration()` directly, which is correct only while the\n// product fits: with the term in seconds, a 318,720,000-coin grant over two\n// years returned -6,264,395,224. Nothing signalled it, because a wrapped\n// int64 is still a valid int64.\nfunc (s Schedule) Vested(t int64) int64 {\n\tif t \u003c s.Cliff || t \u003c s.Start {\n\t\treturn 0\n\t}\n\tif t \u003e= s.End {\n\t\treturn s.Total\n\t}\n\t// Multiply BEFORE dividing: the reverse truncates the per-tick rate to\n\t// zero whenever total \u003c duration, which is the classic vesting bug.\n\treturn mulDiv(s.Total, t-s.Start, s.Duration())\n}\n\n// Unvested returns the remainder still locked at time t.\nfunc (s Schedule) Unvested(t int64) int64 { return s.Total - s.Vested(t) }\n\n// Claimable returns what can be withdrawn at time t given how much has already\n// been claimed. Never negative, even if claimed somehow exceeds vested.\nfunc (s Schedule) Claimable(t, claimed int64) int64 {\n\tv := s.Vested(t) - claimed\n\tif v \u003c 0 {\n\t\treturn 0\n\t}\n\treturn v\n}\n\n// IsFullyVested reports whether the term has completed at time t.\nfunc (s Schedule) IsFullyVested(t int64) bool { return t \u003e= s.End }\n\n// PercentVested returns the vested share at t as an integer percentage,\n// rounded down. Integer-only: no floats reach consensus state.\nfunc (s Schedule) PercentVested(t int64) int64 {\n\treturn mulDiv(s.Vested(t), 100, s.Total)\n}\n\n// CliffAmount returns the lump sum released the instant the cliff is reached.\nfunc (s Schedule) CliffAmount() int64 { return s.Vested(s.Cliff) }\n\n// mulDiv computes floor(a*b/den) through a 128-bit intermediate, so a product\n// that leaves int64 does not wrap.\n//\n// Every caller here passes 0 \u003c= b \u003c= den with den \u003e 0 and a \u003e= 0, which is\n// what makes the bits.Div64 precondition hold: the quotient is then at most a,\n// so it fits in 64 bits, which is exactly the hi \u003c den that Div64 requires and\n// panics without. New enforces Total \u003e 0 and End \u003e Start; Vested only reaches\n// this line with Start \u003c t \u003c End.\nfunc mulDiv(a, b, den int64) int64 {\n\tif a == 0 || b == 0 {\n\t\treturn 0\n\t}\n\thi, lo := bits.Mul64(uint64(a), uint64(b))\n\tq, _ := bits.Div64(hi, lo, uint64(den))\n\treturn int64(q)\n}\n"},{"name":"cliffvesting_test.gno","body":"package cliffvesting\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc mustNew(t *testing.T, total, start, cliff, end int64) Schedule {\n\ts, err := New(total, start, cliff, end)\n\tuassert.NoError(t, err)\n\treturn s\n}\n\nfunc TestNewValidation(t *testing.T) {\n\t_, err := New(0, 0, 0, 100)\n\tuassert.ErrorIs(t, err, ErrBadTotal)\n\t_, err = New(-5, 0, 0, 100)\n\tuassert.ErrorIs(t, err, ErrBadTotal)\n\n\t_, err = New(100, 50, 50, 50)\n\tuassert.ErrorIs(t, err, ErrBadDuration, \"end must be after start\")\n\t_, err = New(100, 50, 50, 10)\n\tuassert.ErrorIs(t, err, ErrBadDuration)\n\n\t_, err = New(100, 0, 200, 100)\n\tuassert.ErrorIs(t, err, ErrCliffAfter)\n\n\t_, err = New(100, 50, 10, 100)\n\tuassert.ErrorIs(t, err, ErrCliffBefore)\n\n\t_, err = New(100, 0, 100, 100)\n\tuassert.NoError(t, err, \"a cliff exactly at the end is allowed\")\n}\n\nfunc TestNewLinearHasNoCliff(t *testing.T) {\n\ts, err := NewLinear(1000, 0, 100)\n\tuassert.NoError(t, err)\n\tuassert.False(t, s.HasCliff())\n\tuassert.Equal(t, int64(0), s.CliffAmount())\n\tuassert.Equal(t, int64(500), s.Vested(50), \"linear from the start\")\n}\n\n// TestNothingBeforeCliff is the defining behaviour.\nfunc TestNothingBeforeCliff(t *testing.T) {\n\ts := mustNew(t, 1200, 0, 300, 1200)\n\n\tuassert.Equal(t, int64(0), s.Vested(0))\n\tuassert.Equal(t, int64(0), s.Vested(299), \"one tick before the cliff, still nothing\")\n\tuassert.Equal(t, int64(1200), s.Unvested(299))\n}\n\n// TestCliffReleasesElapsedPortionAtOnce pins the step, not a ramp.\nfunc TestCliffReleasesElapsedPortionAtOnce(t *testing.T) {\n\ts := mustNew(t, 1200, 0, 300, 1200)\n\n\tuassert.Equal(t, int64(300), s.Vested(300), \"25% of the term elapsed, released in one step\")\n\tuassert.Equal(t, int64(300), s.CliffAmount())\n\tuassert.Equal(t, int64(25), s.PercentVested(300))\n}\n\nfunc TestLinearAfterCliff(t *testing.T) {\n\ts := mustNew(t, 1200, 0, 300, 1200)\n\n\tuassert.Equal(t, int64(600), s.Vested(600))\n\tuassert.Equal(t, int64(900), s.Vested(900))\n\tuassert.Equal(t, int64(1199), s.Vested(1199))\n}\n\n// TestExactlyTotalAtEnd is what rounding down must never break.\nfunc TestExactlyTotalAtEnd(t *testing.T) {\n\ts := mustNew(t, 1000, 0, 0, 3) // 1000/3 does not divide evenly\n\n\tuassert.Equal(t, int64(333), s.Vested(1))\n\tuassert.Equal(t, int64(666), s.Vested(2))\n\tuassert.Equal(t, int64(1000), s.Vested(3), \"the last instalment collects the remainder\")\n\tuassert.Equal(t, int64(0), s.Unvested(3))\n\tuassert.Equal(t, int64(1000), s.Vested(99999), \"still exactly total long after the end\")\n}\n\n// TestSmallTotalLongDuration is the rounding bug this package exists to avoid:\n// with total \u003c duration, dividing before multiplying truncates the rate to 0\n// and nothing ever vests.\nfunc TestSmallTotalLongDuration(t *testing.T) {\n\ts := mustNew(t, 7, 0, 0, 1000)\n\n\tuassert.Equal(t, int64(0), s.Vested(100), \"7*100/1000 = 0.7, floors to 0\")\n\tuassert.Equal(t, int64(1), s.Vested(150), \"7*150/1000 = 1.05, floors to 1\")\n\tuassert.Equal(t, int64(3), s.Vested(500), \"half the term, half of 7, floored\")\n\tuassert.Equal(t, int64(7), s.Vested(1000), \"and still exactly total at the end\")\n}\n\nfunc TestVestedIsMonotonic(t *testing.T) {\n\ts := mustNew(t, 997, 10, 40, 310)\n\n\tprev := int64(-1)\n\tfor tick := int64(0); tick \u003c= 320; tick++ {\n\t\tv := s.Vested(tick)\n\t\tuassert.True(t, v \u003e= prev, \"vested must never decrease\")\n\t\tuassert.True(t, v \u003c= s.Total, \"vested must never exceed total\")\n\t\tprev = v\n\t}\n}\n\nfunc TestUnvestedComplementsVested(t *testing.T) {\n\ts := mustNew(t, 500, 0, 100, 400)\n\tfor _, tick := range []int64{0, 99, 100, 250, 399, 400, 500} {\n\t\tuassert.Equal(t, s.Total, s.Vested(tick)+s.Unvested(tick),\n\t\t\t\"vested + unvested must always equal total\")\n\t}\n}\n\nfunc TestClaimable(t *testing.T) {\n\ts := mustNew(t, 1000, 0, 0, 100)\n\n\tuassert.Equal(t, int64(500), s.Claimable(50, 0))\n\tuassert.Equal(t, int64(300), s.Claimable(50, 200), \"already-claimed is deducted\")\n\tuassert.Equal(t, int64(0), s.Claimable(50, 500), \"nothing left right now\")\n\tuassert.Equal(t, int64(500), s.Claimable(100, 500), \"the rest at the end\")\n}\n\n// TestClaimableNeverNegative guards the case where bookkeeping says more was\n// claimed than has vested — the caller gets 0, not a negative payout.\nfunc TestClaimableNeverNegative(t *testing.T) {\n\ts := mustNew(t, 1000, 0, 0, 100)\n\tuassert.Equal(t, int64(0), s.Claimable(10, 999))\n}\n\nfunc TestPercentVested(t *testing.T) {\n\ts := mustNew(t, 1000, 0, 0, 100)\n\tuassert.Equal(t, int64(0), s.PercentVested(0))\n\tuassert.Equal(t, int64(50), s.PercentVested(50))\n\tuassert.Equal(t, int64(99), s.PercentVested(99))\n\tuassert.Equal(t, int64(100), s.PercentVested(100))\n\tuassert.Equal(t, int64(100), s.PercentVested(1000))\n}\n\n// TestNonZeroStart checks the schedule is relative to Start, not to zero.\nfunc TestNonZeroStart(t *testing.T) {\n\ts := mustNew(t, 400, 1000, 1100, 1400)\n\n\tuassert.Equal(t, int64(0), s.Vested(999), \"before the start\")\n\tuassert.Equal(t, int64(0), s.Vested(1099), \"before the cliff\")\n\tuassert.Equal(t, int64(100), s.Vested(1100), \"cliff: a quarter elapsed\")\n\tuassert.Equal(t, int64(200), s.Vested(1200))\n\tuassert.Equal(t, int64(400), s.Vested(1400))\n}\n\nfunc TestDurationAndFlags(t *testing.T) {\n\ts := mustNew(t, 100, 10, 20, 110)\n\tuassert.Equal(t, int64(100), s.Duration())\n\tuassert.True(t, s.HasCliff())\n\tuassert.False(t, s.IsFullyVested(109))\n\tuassert.True(t, s.IsFullyVested(110))\n\tuassert.True(t, s.IsFullyVested(999))\n}\n\n// TestCliffAtEndIsAllOrNothing covers the degenerate schedule.\nfunc TestCliffAtEndIsAllOrNothing(t *testing.T) {\n\ts := mustNew(t, 100, 0, 100, 100)\n\tuassert.Equal(t, int64(0), s.Vested(99))\n\tuassert.Equal(t, int64(100), s.Vested(100))\n\tuassert.Equal(t, int64(100), s.CliffAmount())\n}\n\n// TestVestedDoesNotOverflow pins the defect that forced v1.\n//\n// v0 computed total*elapsed in plain int64. Over a term measured in seconds,\n// the product passes 2^63 for any grant above roughly 146,036 whole coins, and\n// the wrap is silent: the figures below came back NEGATIVE, which every caller\n// then treated as a real vested amount.\nfunc TestVestedDoesNotOverflow(t *testing.T) {\n\t// The real gno.land mainnet vesting term, 2026-09-12 to 2028-09-12.\n\tconst (\n\t\tstart int64 = 1789225200\n\t\tend   int64 = 1852383600\n\t\tterm        = end - start // 63,158,400 seconds\n\t)\n\n\tfor _, tc := range []struct {\n\t\tname  string\n\t\ttotal int64\n\t}{\n\t\t{\"just under the v0 ceiling\", 146035000000},\n\t\t{\"just over the v0 ceiling\", 146037000000},\n\t\t{\"the largest genesis grant\", 318720000000000},\n\t\t{\"the whole genesis allocation\", 1332999998328067},\n\t} {\n\t\ts, err := NewLinear(tc.total, start, end)\n\t\tuassert.NoError(t, err, tc.name)\n\n\t\t// Halfway through the term is exactly half the grant, and the naive\n\t\t// int64 product has long since wrapped by this size.\n\t\tuassert.Equal(t, tc.total/2, s.Vested(start+term/2), tc.name)\n\n\t\t// The curve stays inside its bounds and never goes backwards.\n\t\tprev := int64(0)\n\t\tfor i := int64(0); i \u003c= 8; i++ {\n\t\t\tgot := s.Vested(start + term*i/8)\n\t\t\tuassert.True(t, got \u003e= prev, tc.name+\": vested went backwards\")\n\t\t\tuassert.True(t, got \u003e= 0, tc.name+\": vested went negative\")\n\t\t\tuassert.True(t, got \u003c= tc.total, tc.name+\": vested exceeded the total\")\n\t\t\tprev = got\n\t\t}\n\t\tuassert.Equal(t, tc.total, prev, tc.name)\n\n\t\t// PercentVested multiplies by 100 on top, so it has its own ceiling.\n\t\t// It is 49 and not 50 at halfway for an ODD total: Vested floors to\n\t\t// (total-1)/2 and the percentage floors again, so two roundings in the\n\t\t// same direction land just under. That is the documented behaviour,\n\t\t// not the overflow, so the assertion allows both.\n\t\thalf := s.PercentVested(start + term/2)\n\t\tuassert.True(t, half == 49 || half == 50, tc.name+\": halfway percent left 49..50\")\n\t\tuassert.Equal(t, int64(100), s.PercentVested(end), tc.name)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/cliffvesting/v1\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"commitreveal","path":"gno.land/p/moul/x/daily/commitreveal/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/commitreveal/v0`\n\n**Commit–reveal scheme** — `Commit`, `MustCommit`, `Verify`, `Open`,\n`ValidCommitment`, `MinSaltLen`, `MaxValueLen`, `DigestLen`.\n\n```go\nimport \"gno.land/p/moul/x/daily/commitreveal/v0\"\n\nc, _ := commitreveal.Commit(\"rock\", \"alice-secret-salt-1\") // phase 1: publish c\ncommitreveal.Open(c, \"rock\", \"alice-secret-salt-1\")        // phase 2: nil\ncommitreveal.Open(c, \"paper\", \"alice-secret-salt-1\")       // ErrMismatch\n```\n\nA transaction is public before it executes, so a naive sealed-bid auction or\nsimultaneous-move game lets whoever moves last read everyone else's move and win\nfor free. Commit–reveal splits the action: publish `H(value ‖ salt)` first, open\nit later.\n\n**The salt is enforced, not advised.** Rock-paper-scissors has three possible\nmoves, so an unsalted commitment has three possible hashes and is broken by\ntrying all of them. `Commit` refuses a salt shorter than `MinSaltLen` (16), and\n`Verify` enforces the same floor — a short salt cannot be smuggled past it.\n\nTwo details that are easy to get wrong, both tested:\n\n- **Length-prefixed hashing.** With plain concatenation `(\"ab\",\"cd…\")` and\n  `(\"abc\",\"d…\")` produce identical bytes, so one commitment could be opened two\n  different ways. The lengths are hashed in.\n- **Constant-time digest comparison.** A short-circuiting check leaks, through\n  timing, how many leading bytes of a guess were right — enough to reconstruct a\n  commitment byte by byte.\n\nThis package computes and checks commitments. It stores nothing and knows nothing\nabout phases or deadlines; the realm owns that.\n\n**Live demo:** [`r/moul/x/daily/commitrevealdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/commitrevealdemo)\n· render it at [`/r/moul/x/daily/commitrevealdemo/v0`](https://gno.land/r/moul/x/daily/commitrevealdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"commitreveal.gno","body":"// Package commitreveal implements the commit-then-reveal scheme as a pure,\n// reusable package.\n//\n// The problem it solves: anything submitted to a chain is public before it is\n// executed, so a naive sealed-bid auction or simultaneous-move game lets the\n// last player read everyone else's move and win for free. Commit-reveal splits\n// the action in two — first publish H(value || salt), later publish the value\n// and salt. The commitment binds you to a choice without disclosing it.\n//\n// The SALT is not optional and this package refuses to let a caller skip it.\n// Without one, a commitment over a small domain is trivially brute-forced: a\n// rock-paper-scissors move has three possible hashes, so hashing all three\n// breaks the scheme entirely. MinSaltLen is enforced at commit time rather than\n// left as advice in a comment.\n//\n// Verification is CONSTANT-TIME over the digest. A short-circuiting comparison\n// leaks, through timing, how many leading bytes of a guess were right, which is\n// enough to reconstruct a commitment byte by byte.\n//\n// This package computes and checks commitments; it stores nothing and knows\n// nothing about phases or deadlines. The realm owns that.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/commitrevealdemo](/r/moul/x/daily/commitrevealdemo/v0).\npackage commitreveal\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n)\n\n// MinSaltLen is the shortest salt accepted. Short salts make a small-domain\n// commitment brute-forceable, which defeats the whole scheme.\nconst MinSaltLen = 16\n\n// MaxValueLen bounds the committed value so gas stays predictable.\nconst MaxValueLen = 4096\n\nvar (\n\tErrShortSalt   = errors.New(\"commitreveal: salt is shorter than MinSaltLen\")\n\tErrLongValue   = errors.New(\"commitreveal: value exceeds MaxValueLen\")\n\tErrMismatch    = errors.New(\"commitreveal: reveal does not match the commitment\")\n\tErrBadHexDigest = errors.New(\"commitreveal: commitment is not a valid hex digest\")\n)\n\n// DigestLen is the length in bytes of a commitment digest (SHA-256).\nconst DigestLen = 32\n\n// Commit returns the hex-encoded commitment for value and salt.\n//\n// The salt is length-prefixed rather than simply concatenated: with plain\n// concatenation, (\"ab\",\"cd\") and (\"a\",\"bcd\") hash identically, so one\n// commitment could be opened two different ways.\nfunc Commit(value, salt string) (string, error) {\n\tif len(salt) \u003c MinSaltLen {\n\t\treturn \"\", ErrShortSalt\n\t}\n\tif len(value) \u003e MaxValueLen {\n\t\treturn \"\", ErrLongValue\n\t}\n\treturn hex.EncodeToString(digest(value, salt)), nil\n}\n\n// MustCommit is Commit, panicking on invalid input. For tests and for callers\n// that have already validated.\nfunc MustCommit(value, salt string) string {\n\tc, err := Commit(value, salt)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn c\n}\n\n// Verify reports whether value and salt open the given commitment. The digest\n// comparison is constant-time.\nfunc Verify(commitment, value, salt string) bool {\n\tif len(salt) \u003c MinSaltLen || len(value) \u003e MaxValueLen {\n\t\treturn false\n\t}\n\twant, err := hex.DecodeString(commitment)\n\tif err != nil || len(want) != DigestLen {\n\t\treturn false\n\t}\n\treturn equalConstantTime(want, digest(value, salt))\n}\n\n// Open verifies and reports why it failed, for callers wanting a reason rather\n// than a bool.\nfunc Open(commitment, value, salt string) error {\n\tif len(salt) \u003c MinSaltLen {\n\t\treturn ErrShortSalt\n\t}\n\tif len(value) \u003e MaxValueLen {\n\t\treturn ErrLongValue\n\t}\n\twant, err := hex.DecodeString(commitment)\n\tif err != nil || len(want) != DigestLen {\n\t\treturn ErrBadHexDigest\n\t}\n\tif !equalConstantTime(want, digest(value, salt)) {\n\t\treturn ErrMismatch\n\t}\n\treturn nil\n}\n\n// ValidCommitment reports whether s is well-formed as a commitment: hex, and\n// exactly DigestLen bytes. It says nothing about what it commits to.\nfunc ValidCommitment(s string) bool {\n\tb, err := hex.DecodeString(s)\n\treturn err == nil \u0026\u0026 len(b) == DigestLen\n}\n\n// digest computes SHA-256 over a length-prefixed encoding of value and salt.\n// gno's crypto/sha256 exposes only Sum256, so the message is assembled first\n// rather than streamed through a hash.Hash.\nfunc digest(value, salt string) []byte {\n\tbuf := make([]byte, 0, 8+len(value)+len(salt))\n\tbuf = append(buf, lengthPrefix(len(value))...)\n\tbuf = append(buf, value...)\n\tbuf = append(buf, lengthPrefix(len(salt))...)\n\tbuf = append(buf, salt...)\n\tsum := sha256.Sum256(buf)\n\treturn sum[:]\n}\n\n// lengthPrefix encodes n as 4 big-endian bytes.\nfunc lengthPrefix(n int) []byte {\n\treturn []byte{\n\t\tbyte(n \u003e\u003e 24), byte(n \u003e\u003e 16), byte(n \u003e\u003e 8), byte(n),\n\t}\n}\n\n// equalConstantTime compares two byte slices without short-circuiting, so the\n// time taken does not reveal how many leading bytes matched.\nfunc equalConstantTime(a, b []byte) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tvar diff byte\n\tfor i := range a {\n\t\tdiff |= a[i] ^ b[i]\n\t}\n\treturn diff == 0\n}\n"},{"name":"commitreveal_test.gno","body":"package commitreveal\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst goodSalt = \"0123456789abcdef\" // exactly MinSaltLen\n\nfunc TestCommitAndVerify(t *testing.T) {\n\tc, err := Commit(\"rock\", goodSalt)\n\tuassert.NoError(t, err)\n\tuassert.True(t, ValidCommitment(c), \"a commitment is a 32-byte hex digest\")\n\tuassert.Equal(t, 64, len(c), \"32 bytes hex-encoded\")\n\n\tuassert.True(t, Verify(c, \"rock\", goodSalt), \"the correct opening verifies\")\n}\n\nfunc TestCommitIsDeterministic(t *testing.T) {\n\ta, _ := Commit(\"paper\", goodSalt)\n\tb, _ := Commit(\"paper\", goodSalt)\n\tuassert.Equal(t, a, b, \"same input, same commitment\")\n}\n\nfunc TestDifferentValuesDiffer(t *testing.T) {\n\ta, _ := Commit(\"rock\", goodSalt)\n\tb, _ := Commit(\"paper\", goodSalt)\n\tuassert.False(t, a == b)\n}\n\n// TestSameValueDifferentSaltDiffers is why the salt exists: two players\n// choosing the same move must not publish the same commitment.\nfunc TestSameValueDifferentSaltDiffers(t *testing.T) {\n\ta, _ := Commit(\"rock\", \"salt-one-0123456789\")\n\tb, _ := Commit(\"rock\", \"salt-two-0123456789\")\n\tuassert.False(t, a == b, \"the same move must not be recognisable across players\")\n}\n\nfunc TestWrongOpeningFails(t *testing.T) {\n\tc, _ := Commit(\"rock\", goodSalt)\n\n\tuassert.False(t, Verify(c, \"paper\", goodSalt), \"wrong value\")\n\tuassert.False(t, Verify(c, \"rock\", \"a-different-salt-value\"), \"wrong salt\")\n\tuassert.False(t, Verify(c, \"\", goodSalt), \"empty value\")\n}\n\n// TestShortSaltRefused is the enforced-not-advised part: a three-move game with\n// a short salt is brute-forceable, so the package will not produce one.\nfunc TestShortSaltRefused(t *testing.T) {\n\t_, err := Commit(\"rock\", \"tooshort\")\n\tuassert.ErrorIs(t, err, ErrShortSalt)\n\n\t_, err = Commit(\"rock\", strings.Repeat(\"x\", MinSaltLen-1))\n\tuassert.ErrorIs(t, err, ErrShortSalt, \"one byte under the minimum is still refused\")\n\n\t_, err = Commit(\"rock\", strings.Repeat(\"x\", MinSaltLen))\n\tuassert.NoError(t, err, \"exactly MinSaltLen is accepted\")\n}\n\nfunc TestShortSaltNeverVerifies(t *testing.T) {\n\t// Even a digest that would match cannot be opened with a short salt.\n\tuassert.False(t, Verify(MustCommit(\"rock\", goodSalt), \"rock\", \"short\"),\n\t\t\"Verify enforces the salt floor too\")\n}\n\nfunc TestLongValueRefused(t *testing.T) {\n\t_, err := Commit(strings.Repeat(\"x\", MaxValueLen+1), goodSalt)\n\tuassert.ErrorIs(t, err, ErrLongValue)\n\n\t_, err = Commit(strings.Repeat(\"x\", MaxValueLen), goodSalt)\n\tuassert.NoError(t, err, \"exactly MaxValueLen is accepted\")\n}\n\n// TestLengthPrefixPreventsAmbiguity is the subtle one: with plain\n// concatenation, (\"ab\",\"cdefghijklmnopq\") and (\"abc\",\"defghijklmnopq\") produce\n// the same bytes, so one commitment could be opened two ways.\nfunc TestLengthPrefixPreventsAmbiguity(t *testing.T) {\n\ta, err := Commit(\"ab\", \"cdefghijklmnopqr\")\n\tuassert.NoError(t, err)\n\tb, err := Commit(\"abc\", \"defghijklmnopqr0\")\n\tuassert.NoError(t, err)\n\n\tuassert.False(t, a == b, \"a split ambiguity must not collide\")\n\tuassert.False(t, Verify(a, \"abc\", \"defghijklmnopqr0\"), \"and must not cross-verify\")\n}\n\nfunc TestOpenReportsReasons(t *testing.T) {\n\tc := MustCommit(\"rock\", goodSalt)\n\n\tuassert.NoError(t, Open(c, \"rock\", goodSalt))\n\tuassert.ErrorIs(t, Open(c, \"paper\", goodSalt), ErrMismatch)\n\tuassert.ErrorIs(t, Open(c, \"rock\", \"short\"), ErrShortSalt)\n\tuassert.ErrorIs(t, Open(c, strings.Repeat(\"x\", MaxValueLen+1), goodSalt), ErrLongValue)\n\tuassert.ErrorIs(t, Open(\"not-hex!!\", \"rock\", goodSalt), ErrBadHexDigest)\n\tuassert.ErrorIs(t, Open(\"abcd\", \"rock\", goodSalt), ErrBadHexDigest, \"right charset, wrong length\")\n}\n\nfunc TestMalformedCommitments(t *testing.T) {\n\tuassert.False(t, Verify(\"\", \"rock\", goodSalt))\n\tuassert.False(t, Verify(\"zz\", \"rock\", goodSalt), \"not hex\")\n\tuassert.False(t, Verify(strings.Repeat(\"ab\", 16), \"rock\", goodSalt), \"16 bytes, not 32\")\n}\n\nfunc TestValidCommitment(t *testing.T) {\n\tuassert.True(t, ValidCommitment(MustCommit(\"x\", goodSalt)))\n\tuassert.False(t, ValidCommitment(\"\"))\n\tuassert.False(t, ValidCommitment(\"nothex\"))\n\tuassert.False(t, ValidCommitment(strings.Repeat(\"a\", 63)), \"odd length\")\n\tuassert.False(t, ValidCommitment(strings.Repeat(\"a\", 66)), \"too long\")\n\tuassert.True(t, ValidCommitment(strings.Repeat(\"A\", 64)), \"uppercase hex is fine\")\n}\n\nfunc TestMustCommitPanicsOnBadInput(t *testing.T) {\n\tdefer func() {\n\t\tr := recover()\n\t\tuassert.True(t, r != nil, \"MustCommit must panic on a short salt\")\n\t}()\n\tMustCommit(\"rock\", \"short\")\n}\n\nfunc TestEqualConstantTime(t *testing.T) {\n\ta := []byte{1, 2, 3}\n\tuassert.True(t, equalConstantTime(a, []byte{1, 2, 3}))\n\tuassert.False(t, equalConstantTime(a, []byte{1, 2, 4}), \"differs in the last byte\")\n\tuassert.False(t, equalConstantTime(a, []byte{9, 2, 3}), \"differs in the first byte\")\n\tuassert.False(t, equalConstantTime(a, []byte{1, 2}), \"different lengths\")\n\tuassert.True(t, equalConstantTime(nil, nil))\n}\n\n// TestFullRoundTrip walks the two phases the scheme is made of.\nfunc TestFullRoundTrip(t *testing.T) {\n\t// Phase 1: both players publish only a commitment.\n\taliceSalt := \"alice-secret-salt-1\"\n\tbobSalt := \"bob-secret-salt-0001\"\n\taliceCommit := MustCommit(\"rock\", aliceSalt)\n\tbobCommit := MustCommit(\"paper\", bobSalt)\n\n\tuassert.False(t, aliceCommit == bobCommit)\n\tuassert.True(t, ValidCommitment(aliceCommit))\n\n\t// Phase 2: reveals are checked against the earlier commitments.\n\tuassert.NoError(t, Open(aliceCommit, \"rock\", aliceSalt))\n\tuassert.NoError(t, Open(bobCommit, \"paper\", bobSalt))\n\n\t// Bob cannot change his move after seeing Alice's.\n\tuassert.ErrorIs(t, Open(bobCommit, \"scissors\", bobSalt), ErrMismatch)\n\t// Nor can he claim Alice's commitment as his own.\n\tuassert.ErrorIs(t, Open(aliceCommit, \"rock\", bobSalt), ErrMismatch)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/commitreveal/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"countminsketch","path":"gno.land/p/moul/x/daily/countminsketch/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/countminsketch/v0`\n\n**Count–Min Sketch: frequency estimates in fixed space** — `New`, `NewDefault`,\n`Add`, `AddN`, `Estimate`, `MightHave`, `Merge`, `Reset`, `Clone`, `Row`,\n`Index`, `Total`, `Counters`.\n\n```go\nimport \"gno.land/p/moul/x/daily/countminsketch/v0\"\n\ns := countminsketch.NewDefault()   // 256 x 4 = 1024 counters, forever\nfor _, e := range stream { s.Add(e) }\ns.Estimate(\"alice\")   // an UPPER BOUND on how often \"alice\" appeared\ns.MightHave(\"bob\")    // false is definitive: never added\n```\n\nAn exact frequency map costs one entry per distinct element — unbounded storage\ndriven by whatever users feed it, which on chain is a liability. A sketch is\nsized **once** and never grows.\n\n**The error is one-sided, and that is the whole contract: `Estimate` never\nundercounts.** Collisions can only add other elements' counts to a row, so the\ntrue frequency is always ≤ the estimate. Taking the minimum across `depth`\nindependently-seeded rows makes an overestimate require a collision in every row\nat once. Treat the result as *\"at most this often\"*, never *\"exactly this\noften\"*. The guarantee is tested against a deliberately tiny sketch where\ncollisions are certain.\n\nSizing: **width** controls the error, **depth** controls the odds of hitting it —\nroughly, the overestimate stays within `total/width` with probability\n`1 - (1/2)^depth`.\n\nHashing is FNV-1a with a per-row seed, computed in pure gno, so the counters are\nidentical on every node. `Distinct()` is deliberately absent — a Count–Min Sketch\ncannot answer cardinality; use a HyperLogLog.\n\n**Live demo:** [`r/moul/x/daily/countminsketchdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/countminsketchdemo)\n· render it at [`/r/moul/x/daily/countminsketchdemo/v0`](https://gno.land/r/moul/x/daily/countminsketchdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"countminsketch.gno","body":"// Package countminsketch estimates element frequencies in sublinear space, as\n// a pure, reusable package.\n//\n// An exact frequency map costs one entry per distinct element, which on chain\n// means unbounded storage driven by whatever users feed it. A Count-Min Sketch\n// trades exactness for a FIXED footprint: d rows of w counters, sized once and\n// never grown, regardless of how many distinct elements arrive.\n//\n// The error is one-sided and that is the whole contract: Estimate NEVER\n// UNDERCOUNTS. Collisions can only add other elements' counts to a row, so the\n// true frequency is always \u003c= the estimate. Taking the minimum across d\n// independent rows makes an overestimate require a collision in every row at\n// once. Callers must treat the result as an upper bound — \"at most this often\",\n// never \"exactly this often\".\n//\n// Sizing: width controls the error, depth controls the odds of hitting it.\n// Roughly, the overestimate stays within total/width with probability\n// 1 - (1/2)^depth.\n//\n// Hashing is FNV-1a with a per-row seed, computed in pure gno — deterministic\n// across every node, which a map-address-derived hash would not be.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/countminsketchdemo](/r/moul/x/daily/countminsketchdemo/v0).\npackage countminsketch\n\nimport \"errors\"\n\nconst (\n\t// MinWidth/MaxWidth bound each row.\n\tMinWidth = 4\n\tMaxWidth = 8192\n\t// MinDepth/MaxDepth bound the number of rows.\n\tMinDepth = 1\n\tMaxDepth = 16\n)\n\nvar (\n\tErrBadWidth = errors.New(\"countminsketch: width out of range\")\n\tErrBadDepth = errors.New(\"countminsketch: depth out of range\")\n\tErrBadCount = errors.New(\"countminsketch: count must be positive\")\n)\n\n// Sketch is a Count-Min Sketch over string elements.\ntype Sketch struct {\n\twidth  int\n\tdepth  int\n\trows   [][]int64 // depth rows of width counters\n\ttotal  int64     // sum of every increment applied\n\tadds   int64     // number of Add/AddN calls applied\n}\n\n// New returns a sketch with the given dimensions.\nfunc New(width, depth int) (*Sketch, error) {\n\tif width \u003c MinWidth || width \u003e MaxWidth {\n\t\treturn nil, ErrBadWidth\n\t}\n\tif depth \u003c MinDepth || depth \u003e MaxDepth {\n\t\treturn nil, ErrBadDepth\n\t}\n\trows := make([][]int64, depth)\n\tfor i := range rows {\n\t\trows[i] = make([]int64, width)\n\t}\n\treturn \u0026Sketch{width: width, depth: depth, rows: rows}, nil\n}\n\n// NewDefault returns a sketch sized for general use: 256 x 4.\nfunc NewDefault() *Sketch {\n\ts, _ := New(256, 4)\n\treturn s\n}\n\n// Width returns the number of counters per row.\nfunc (s *Sketch) Width() int { return s.width }\n\n// Depth returns the number of rows.\nfunc (s *Sketch) Depth() int { return s.depth }\n\n// Counters returns the total number of counters — the fixed storage cost.\nfunc (s *Sketch) Counters() int { return s.width * s.depth }\n\n// Total returns the sum of every increment applied.\nfunc (s *Sketch) Total() int64 { return s.total }\n\n// Distinct is deliberately absent: a Count-Min Sketch cannot answer it. Use a\n// HyperLogLog for cardinality.\n\n// Add records one occurrence of e.\nfunc (s *Sketch) Add(e string) { s.AddN(e, 1) }\n\n// AddN records n occurrences of e. A non-positive n is ignored.\nfunc (s *Sketch) AddN(e string, n int64) error {\n\tif n \u003c= 0 {\n\t\treturn ErrBadCount\n\t}\n\tfor r := 0; r \u003c s.depth; r++ {\n\t\ts.rows[r][s.index(e, r)] += n\n\t}\n\ts.total += n\n\ts.adds++\n\treturn nil\n}\n\n// Estimate returns an UPPER BOUND on how often e was added. It never\n// undercounts; it may overcount when every row collided.\nfunc (s *Sketch) Estimate(e string) int64 {\n\tvar min int64 = -1\n\tfor r := 0; r \u003c s.depth; r++ {\n\t\tv := s.rows[r][s.index(e, r)]\n\t\tif min \u003c 0 || v \u003c min {\n\t\t\tmin = v\n\t\t}\n\t}\n\tif min \u003c 0 {\n\t\treturn 0\n\t}\n\treturn min\n}\n\n// MightHave reports whether e may have been added. A false result is\n// definitive: it was never added.\nfunc (s *Sketch) MightHave(e string) bool { return s.Estimate(e) \u003e 0 }\n\n// Merge adds another sketch into this one. Both must have identical dimensions;\n// merging is what makes sketches useful across shards or time windows.\nfunc (s *Sketch) Merge(other *Sketch) error {\n\tif s.width != other.width {\n\t\treturn ErrBadWidth\n\t}\n\tif s.depth != other.depth {\n\t\treturn ErrBadDepth\n\t}\n\tfor r := 0; r \u003c s.depth; r++ {\n\t\tfor c := 0; c \u003c s.width; c++ {\n\t\t\ts.rows[r][c] += other.rows[r][c]\n\t\t}\n\t}\n\ts.total += other.total\n\ts.adds += other.adds\n\treturn nil\n}\n\n// Reset zeroes every counter, keeping the dimensions.\nfunc (s *Sketch) Reset() {\n\tfor r := range s.rows {\n\t\tfor c := range s.rows[r] {\n\t\t\ts.rows[r][c] = 0\n\t\t}\n\t}\n\ts.total = 0\n\ts.adds = 0\n}\n\n// Clone returns an independent copy.\nfunc (s *Sketch) Clone() *Sketch {\n\tcp, _ := New(s.width, s.depth)\n\tfor r := range s.rows {\n\t\tcopy(cp.rows[r], s.rows[r])\n\t}\n\tcp.total = s.total\n\tcp.adds = s.adds\n\treturn cp\n}\n\n// Row returns a copy of row r, for rendering and inspection.\nfunc (s *Sketch) Row(r int) []int64 {\n\tif r \u003c 0 || r \u003e= s.depth {\n\t\treturn nil\n\t}\n\tout := make([]int64, s.width)\n\tcopy(out, s.rows[r])\n\treturn out\n}\n\n// Index returns the column e maps to in row r — exported so a demo can show\n// where collisions happen.\nfunc (s *Sketch) Index(e string, r int) int {\n\tif r \u003c 0 || r \u003e= s.depth {\n\t\treturn -1\n\t}\n\treturn s.index(e, r)\n}\n\n// index hashes e for row r with FNV-1a, seeded per row.\nfunc (s *Sketch) index(e string, row int) int {\n\tconst (\n\t\toffset64 = uint64(14695981039346656037)\n\t\tprime64  = uint64(1099511628211)\n\t)\n\th := offset64\n\t// Seed the row so each row hashes independently.\n\th ^= uint64(row + 1)\n\th *= prime64\n\tfor i := 0; i \u003c len(e); i++ {\n\t\th ^= uint64(e[i])\n\t\th *= prime64\n\t}\n\treturn int(h % uint64(s.width))\n}\n"},{"name":"countminsketch_test.gno","body":"package countminsketch\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestNewValidation(t *testing.T) {\n\t_, err := New(MinWidth-1, 4)\n\tuassert.ErrorIs(t, err, ErrBadWidth)\n\t_, err = New(MaxWidth+1, 4)\n\tuassert.ErrorIs(t, err, ErrBadWidth)\n\t_, err = New(256, MinDepth-1)\n\tuassert.ErrorIs(t, err, ErrBadDepth)\n\t_, err = New(256, MaxDepth+1)\n\tuassert.ErrorIs(t, err, ErrBadDepth)\n\n\t_, err = New(MinWidth, MinDepth)\n\tuassert.NoError(t, err, \"the minimum dimensions are valid\")\n\t_, err = New(MaxWidth, MaxDepth)\n\tuassert.NoError(t, err, \"the maximum dimensions are valid\")\n}\n\nfunc TestDimensions(t *testing.T) {\n\ts, _ := New(64, 3)\n\tuassert.Equal(t, 64, s.Width())\n\tuassert.Equal(t, 3, s.Depth())\n\tuassert.Equal(t, 192, s.Counters(), \"storage is width*depth, fixed\")\n\n\td := NewDefault()\n\tuassert.Equal(t, 256, d.Width())\n\tuassert.Equal(t, 4, d.Depth())\n}\n\nfunc TestEmptyEstimatesZero(t *testing.T) {\n\ts := NewDefault()\n\tuassert.Equal(t, int64(0), s.Estimate(\"anything\"))\n\tuassert.False(t, s.MightHave(\"anything\"))\n\tuassert.Equal(t, int64(0), s.Total())\n}\n\nfunc TestAddAndEstimate(t *testing.T) {\n\ts := NewDefault()\n\tfor i := 0; i \u003c 5; i++ {\n\t\ts.Add(\"apple\")\n\t}\n\ts.Add(\"pear\")\n\n\tuassert.Equal(t, int64(5), s.Estimate(\"apple\"))\n\tuassert.Equal(t, int64(1), s.Estimate(\"pear\"))\n\tuassert.Equal(t, int64(6), s.Total())\n\tuassert.True(t, s.MightHave(\"apple\"))\n}\n\nfunc TestAddNRejectsNonPositive(t *testing.T) {\n\ts := NewDefault()\n\tuassert.ErrorIs(t, s.AddN(\"x\", 0), ErrBadCount)\n\tuassert.ErrorIs(t, s.AddN(\"x\", -3), ErrBadCount)\n\tuassert.Equal(t, int64(0), s.Total(), \"a rejected add changes nothing\")\n}\n\nfunc TestAddNAccumulates(t *testing.T) {\n\ts := NewDefault()\n\tuassert.NoError(t, s.AddN(\"x\", 100))\n\tuassert.NoError(t, s.AddN(\"x\", 50))\n\tuassert.Equal(t, int64(150), s.Estimate(\"x\"))\n\tuassert.Equal(t, int64(150), s.Total())\n}\n\n// TestNeverUndercounts is THE contract. A tiny sketch guarantees collisions;\n// the estimate must still never fall below the truth.\nfunc TestNeverUndercounts(t *testing.T) {\n\ts, _ := New(MinWidth, 2) // deliberately tiny: 4 columns, collisions certain\n\n\ttruth := map[string]int64{}\n\tfor i := 0; i \u003c 300; i++ {\n\t\te := \"e\" + strconv.Itoa(i%40)\n\t\ts.Add(e)\n\t\ttruth[e]++\n\t}\n\n\tfor e, want := range truth {\n\t\tgot := s.Estimate(e)\n\t\tuassert.True(t, got \u003e= want,\n\t\t\t\"estimate must never undercount \"+e+\": got \"+strconv.FormatInt(got, 10)+\n\t\t\t\t\" want \u003e= \"+strconv.FormatInt(want, 10))\n\t}\n}\n\n// TestExactWhenNoCollisions checks a generously sized sketch is exact for a\n// handful of elements — the common case.\nfunc TestExactWhenNoCollisions(t *testing.T) {\n\ts, _ := New(MaxWidth, 4)\n\ts.AddN(\"alpha\", 7)\n\ts.AddN(\"bravo\", 3)\n\ts.AddN(\"charlie\", 11)\n\n\tuassert.Equal(t, int64(7), s.Estimate(\"alpha\"))\n\tuassert.Equal(t, int64(3), s.Estimate(\"bravo\"))\n\tuassert.Equal(t, int64(11), s.Estimate(\"charlie\"))\n}\n\n// TestAbsentIsDefinitiveWhenZero pins the useful direction of the one-sided\n// error: zero means definitely never added.\nfunc TestAbsentIsDefinitiveWhenZero(t *testing.T) {\n\ts, _ := New(MaxWidth, 4)\n\ts.Add(\"present\")\n\tuassert.False(t, s.MightHave(\"definitely-absent\"), \"a zero estimate is definitive\")\n}\n\n// TestEstimateBoundedByTotal pins the other side: an estimate can never exceed\n// everything that was ever added.\nfunc TestEstimateBoundedByTotal(t *testing.T) {\n\ts, _ := New(MinWidth, 1)\n\tfor i := 0; i \u003c 100; i++ {\n\t\ts.Add(\"e\" + strconv.Itoa(i))\n\t}\n\tfor i := 0; i \u003c 100; i++ {\n\t\tuassert.True(t, s.Estimate(\"e\"+strconv.Itoa(i)) \u003c= s.Total(),\n\t\t\t\"no estimate may exceed the total\")\n\t}\n}\n\n// TestDeterministicAcrossInstances is what makes this safe on chain: the same\n// input yields the same counters everywhere, with no map-order dependence.\nfunc TestDeterministicAcrossInstances(t *testing.T) {\n\tbuild := func() *Sketch {\n\t\ts, _ := New(32, 3)\n\t\tfor i := 0; i \u003c 200; i++ {\n\t\t\ts.Add(\"elem\" + strconv.Itoa(i%25))\n\t\t}\n\t\treturn s\n\t}\n\ta, b := build(), build()\n\n\tfor r := 0; r \u003c a.Depth(); r++ {\n\t\tra, rb := a.Row(r), b.Row(r)\n\t\tfor c := range ra {\n\t\t\tuassert.Equal(t, ra[c], rb[c], \"counters must match across instances\")\n\t\t}\n\t}\n\tuassert.Equal(t, a.Estimate(\"elem7\"), b.Estimate(\"elem7\"))\n}\n\nfunc TestIndexIsStableAndInRange(t *testing.T) {\n\ts, _ := New(64, 3)\n\tfor r := 0; r \u003c 3; r++ {\n\t\ti := s.Index(\"hello\", r)\n\t\tuassert.True(t, i \u003e= 0 \u0026\u0026 i \u003c 64, \"index must be within the row\")\n\t\tuassert.Equal(t, i, s.Index(\"hello\", r), \"index must be stable\")\n\t}\n\tuassert.Equal(t, -1, s.Index(\"hello\", -1), \"out-of-range row\")\n\tuassert.Equal(t, -1, s.Index(\"hello\", 3))\n}\n\n// TestRowsHashIndependently checks the per-row seed actually changes the column,\n// which is what makes taking the minimum meaningful.\nfunc TestRowsHashIndependently(t *testing.T) {\n\ts, _ := New(MaxWidth, MaxDepth)\n\tfirst := s.Index(\"some-element\", 0)\n\tdiffers := false\n\tfor r := 1; r \u003c s.Depth(); r++ {\n\t\tif s.Index(\"some-element\", r) != first {\n\t\t\tdiffers = true\n\t\t}\n\t}\n\tuassert.True(t, differs, \"rows must not all map to the same column\")\n}\n\nfunc TestMerge(t *testing.T) {\n\ta, _ := New(128, 3)\n\tb, _ := New(128, 3)\n\ta.AddN(\"x\", 5)\n\tb.AddN(\"x\", 7)\n\tb.AddN(\"y\", 2)\n\n\tuassert.NoError(t, a.Merge(b))\n\tuassert.Equal(t, int64(12), a.Estimate(\"x\"), \"merged counts add\")\n\tuassert.Equal(t, int64(2), a.Estimate(\"y\"))\n\tuassert.Equal(t, int64(14), a.Total())\n}\n\nfunc TestMergeRejectsMismatchedShape(t *testing.T) {\n\ta, _ := New(128, 3)\n\tuassert.ErrorIs(t, a.Merge(mustNew(t, 64, 3)), ErrBadWidth)\n\tuassert.ErrorIs(t, a.Merge(mustNew(t, 128, 2)), ErrBadDepth)\n\tuassert.Equal(t, int64(0), a.Total(), \"a rejected merge changes nothing\")\n}\n\nfunc TestReset(t *testing.T) {\n\ts := NewDefault()\n\ts.AddN(\"x\", 10)\n\ts.Reset()\n\n\tuassert.Equal(t, int64(0), s.Estimate(\"x\"))\n\tuassert.Equal(t, int64(0), s.Total())\n\tuassert.Equal(t, 256, s.Width(), \"dimensions survive a reset\")\n}\n\nfunc TestClone(t *testing.T) {\n\ts := NewDefault()\n\ts.AddN(\"x\", 4)\n\n\tcp := s.Clone()\n\tcp.AddN(\"x\", 6)\n\n\tuassert.Equal(t, int64(4), s.Estimate(\"x\"), \"clone must not share storage\")\n\tuassert.Equal(t, int64(10), cp.Estimate(\"x\"))\n\tuassert.Equal(t, s.Width(), cp.Width())\n}\n\nfunc TestRowCopy(t *testing.T) {\n\ts, _ := New(8, 2)\n\ts.Add(\"x\")\n\n\trow := s.Row(0)\n\tuassert.Equal(t, 8, len(row))\n\trow[0] = 999\n\tuassert.False(t, s.Row(0)[0] == 999, \"Row returns a copy\")\n\n\tuassert.True(t, s.Row(-1) == nil)\n\tuassert.True(t, s.Row(2) == nil)\n}\n\nfunc mustNew(t *testing.T, w, d int) *Sketch {\n\ts, err := New(w, d)\n\tuassert.NoError(t, err)\n\treturn s\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/countminsketch/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"cowsay","path":"gno.land/p/moul/x/daily/cowsay/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/cowsay/v0`\n\n**cowsay** — `Say(msg string) string` returns the classic ASCII cow with a\nspeech bubble containing `msg`.\n\nPure deterministic string art: the message is word-wrapped into a speech balloon\n(single line uses `\u003c \u003e`, multi-line uses `/ \\ | |` borders) with the happy cow\nstacked underneath. Port of cowsay by Tony Monroe (1999); no `os`/`exec`, no\nchain coupling.\n\n```go\nimport \"gno.land/p/moul/x/daily/cowsay/v0\"\n\nart := cowsay.Say(\"Hello, gno.land!\")  // bubble + cow, ready for a code block\ncowsay.Say(\"\")                          // default message (\"Moo!\")\n```\n\n**Live demo:** [`r/moul/x/daily/cowsaydemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/cowsaydemo)\n· render it at [`/r/moul/x/daily/cowsaydemo/v0`](https://gno.land/r/moul/x/daily/cowsaydemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"cowsay.gno","body":"// Package cowsay is an on-chain Gno port of the classic `cowsay` program:\n// it builds an ASCII cow with a speech bubble containing a message — as a\n// reusable pure package.\n//\n// Original: cowsay by Tony Monroe (1999), a Perl program later ported to Go\n// many times. This package reimplements the core rendering — bubble framing,\n// word-wrapping and the cow art — as pure, deterministic string logic.\n//\n// A live demo of this package (an interactive cow that says whatever you put in\n// the path) is at [r/moul/x/daily/cowsaydemo](/r/moul/x/daily/cowsaydemo/v0).\npackage cowsay\n\nimport (\n\t\"strings\"\n)\n\n// defaultMessage is shown when no message is supplied.\nconst defaultMessage = \"Moo!\"\n\n// wrapWidth is the maximum bubble text width (classic cowsay uses 40).\nconst wrapWidth = 40\n\n// Say returns the full cowsay art (speech bubble + cow) for msg.\n// An empty msg falls back to the default message.\nfunc Say(msg string) string {\n\tmsg = strings.TrimSpace(msg)\n\tif msg == \"\" {\n\t\tmsg = defaultMessage\n\t}\n\tlines := wrap(msg, wrapWidth)\n\treturn balloon(lines) + cow\n}\n\n// balloon builds the speech bubble around the given (already wrapped) lines.\nfunc balloon(lines []string) string {\n\twidth := maxLen(lines)\n\n\tvar b strings.Builder\n\t// top border: \" \" + \"_\"*(width+2)\n\tb.WriteString(\" \")\n\tb.WriteString(strings.Repeat(\"_\", width+2))\n\tb.WriteString(\"\\n\")\n\n\tn := len(lines)\n\tfor i, ln := range lines {\n\t\tleft, right := borderChars(i, n)\n\t\tb.WriteString(left)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(ln)\n\t\tb.WriteString(strings.Repeat(\" \", width-len(ln)))\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(right)\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\t// bottom border: \" \" + \"-\"*(width+2)\n\tb.WriteString(\" \")\n\tb.WriteString(strings.Repeat(\"-\", width+2))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\n// borderChars picks the left/right bubble characters for line i of n.\n// Single line uses \u003c \u003e. Multi-line uses / \\ for the first row,\n// \\ / for the last row, and | | for the middle rows.\nfunc borderChars(i, n int) (string, string) {\n\tif n == 1 {\n\t\treturn \"\u003c\", \"\u003e\"\n\t}\n\tswitch i {\n\tcase 0:\n\t\treturn \"/\", \"\\\\\"\n\tcase n - 1:\n\t\treturn \"\\\\\", \"/\"\n\tdefault:\n\t\treturn \"|\", \"|\"\n\t}\n}\n\n// wrap splits text into lines no longer than width, breaking on spaces.\n// Words longer than width are hard-split.\nfunc wrap(text string, width int) []string {\n\twords := strings.Fields(text)\n\tif len(words) == 0 {\n\t\treturn []string{\"\"}\n\t}\n\n\tvar lines []string\n\tcur := \"\"\n\tfor _, w := range words {\n\t\t// hard-split a single word that is too long\n\t\tfor len(w) \u003e width {\n\t\t\tif cur != \"\" {\n\t\t\t\tlines = append(lines, cur)\n\t\t\t\tcur = \"\"\n\t\t\t}\n\t\t\tlines = append(lines, w[:width])\n\t\t\tw = w[width:]\n\t\t}\n\t\tif cur == \"\" {\n\t\t\tcur = w\n\t\t} else if len(cur)+1+len(w) \u003c= width {\n\t\t\tcur = cur + \" \" + w\n\t\t} else {\n\t\t\tlines = append(lines, cur)\n\t\t\tcur = w\n\t\t}\n\t}\n\tif cur != \"\" {\n\t\tlines = append(lines, cur)\n\t}\n\treturn lines\n}\n\n// maxLen returns the length of the longest line.\nfunc maxLen(lines []string) int {\n\tm := 0\n\tfor _, ln := range lines {\n\t\tif len(ln) \u003e m {\n\t\t\tm = len(ln)\n\t\t}\n\t}\n\treturn m\n}\n\n// cow is the classic happy cow, aligned under the bubble.\nconst cow = `        \\   ^__^\n         \\  (oo)\\_______\n            (__)\\       )\\/\\\n                ||----w |\n                ||     ||\n`\n"},{"name":"cowsay_test.gno","body":"package cowsay\n\n// handrolled-table: the cow's horn line \"||----w |\" is ASCII art, not a GFM header\n// separator. This package renders no table at all, and its production source is live\n// on an immutable public path, so the opt-out has to live here.\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestWrap(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\ttext  string\n\t\twidth int\n\t\twant  []string\n\t}{\n\t\t{\"empty\", \"\", 10, []string{\"\"}},\n\t\t{\"single\", \"hello\", 10, []string{\"hello\"}},\n\t\t{\"wrap two\", \"aaa bbb ccc\", 7, []string{\"aaa bbb\", \"ccc\"}},\n\t\t{\"hard split\", \"abcdefghij\", 4, []string{\"abcd\", \"efgh\", \"ij\"}},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := wrap(tt.text, tt.width)\n\t\tuassert.Equal(t, len(tt.want), len(got), tt.name+\": line count\")\n\t\tfor i := range tt.want {\n\t\t\tuassert.Equal(t, tt.want[i], got[i], tt.name+\": line \"+tt.want[i])\n\t\t}\n\t\t// no wrapped line exceeds width\n\t\tfor _, ln := range got {\n\t\t\tuassert.True(t, len(ln) \u003c= tt.width, tt.name+\": within width\")\n\t\t}\n\t}\n}\n\nfunc TestBorderChars(t *testing.T) {\n\tl, r := borderChars(0, 1)\n\tuassert.Equal(t, \"\u003c\", l)\n\tuassert.Equal(t, \"\u003e\", r)\n\n\tl, r = borderChars(0, 3)\n\tuassert.Equal(t, \"/\", l)\n\tuassert.Equal(t, \"\\\\\", r)\n\n\tl, r = borderChars(1, 3)\n\tuassert.Equal(t, \"|\", l)\n\tuassert.Equal(t, \"|\", r)\n\n\tl, r = borderChars(2, 3)\n\tuassert.Equal(t, \"\\\\\", l)\n\tuassert.Equal(t, \"/\", r)\n}\n\nfunc TestMaxLen(t *testing.T) {\n\tuassert.Equal(t, 0, maxLen([]string{\"\"}))\n\tuassert.Equal(t, 5, maxLen([]string{\"ab\", \"cde\", \"fghij\"}))\n}\n\nfunc TestSayDefault(t *testing.T) {\n\tgot := Say(\"\")\n\tuassert.True(t, strings.Contains(got, defaultMessage), \"uses default message\")\n\tuassert.True(t, strings.Contains(got, \"(oo)\"), \"contains cow face\")\n\tuassert.True(t, strings.Contains(got, \"\u003c Moo! \u003e\"), \"single-line bubble\")\n}\n\nfunc TestSayWrapsMultiline(t *testing.T) {\n\tmsg := \"the quick brown fox jumps over the lazy dog many many times over\"\n\tgot := Say(msg)\n\t// multi-line bubbles use slashes, never the single-line angle brackets\n\tuassert.True(t, strings.Contains(got, \"/\"), \"multi-line top border char\")\n\tuassert.False(t, strings.Contains(got, \"\u003c \"), \"no single-line marker\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/cowsay/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"crc32","path":"gno.land/p/moul/x/daily/crc32/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/crc32/v0`\n\n**CRC-32 checksum** — `Checksum`, `ChecksumHex`, `ChecksumWith`, `Verify`,\n`MakeTable`, `Update`, `Finalize`, `Hex`, `Split`.\n\nTreats a message as one enormous binary number and takes the remainder of\ndividing it by a fixed polynomial. The bit-reflected, table-driven form — the\none zip, gzip, PNG and Ethernet actually use.\n\n```go\nimport \"gno.land/p/moul/x/daily/crc32/v0\"\n\ncrc32.ChecksumHex(\"123456789\")   // \"cbf43926\" — the standard check value\ncrc32.Checksum(\"abc\")            // 0x352441C2\ncrc32.Verify(\"abc\", 0x352441C2)  // true\n```\n\nThree polynomials: `IEEE` (zip/gzip/PNG, the default), `Castagnoli`\n(iSCSI/btrfs, better error detection) and `Koopman`. `MakeTable` builds the\n256-entry table once — that is the whole point of the table-driven form, trading\n1 KiB for eight bit-shifts per byte.\n\n`Update`/`Finalize` take and return the **raw register**, not the finished\nchecksum, so a long message can be fed in chunks. Chaining on final values would\nbe wrong; there is a test asserting chunked equals one-shot.\n\n\u003e ⚠️ **A CRC detects accidents, not tampering.** It is linear, so anyone can\n\u003e craft a different message with the same checksum. Never use it to\n\u003e authenticate anything.\n\n**Live demo:** [`r/moul/x/daily/crc32demo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/crc32demo)\n· render it at [`/r/moul/x/daily/crc32demo/v0`](https://gno.land/r/moul/x/daily/crc32demo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"crc32.gno","body":"// Package crc32 implements the CRC-32 checksum as a pure, reusable package.\n//\n// CRC-32 treats a message as one enormous binary number and takes the remainder\n// of dividing it by a fixed polynomial. The bit-reflected, table-driven form\n// implemented here is the one everything actually uses — zip, gzip, PNG, and\n// Ethernet all speak IEEE.\n//\n// Three polynomials are provided:\n//\n//   - IEEE       (0xEDB88320) — zip/gzip/PNG. The default.\n//   - Castagnoli (0x82F63B78) — iSCSI/btrfs; better error detection.\n//   - Koopman    (0xEB31D82E)\n//\n// A CRC is an ACCIDENT detector, not a security primitive: it is linear, so\n// anyone can craft a different message with the same checksum. Never use it to\n// authenticate anything.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/crc32demo](/r/moul/x/daily/crc32demo/v0).\npackage crc32\n\nimport \"strings\"\n\n// Common reversed polynomials.\nconst (\n\tIEEE       = 0xEDB88320\n\tCastagnoli = 0x82F63B78\n\tKoopman    = 0xEB31D82E\n)\n\n// Table is a precomputed byte-wise lookup table for one polynomial.\ntype Table [256]uint32\n\n// MakeTable builds the lookup table for a reversed polynomial. Building it once\n// and reusing it is the whole point of the table-driven form: it trades 1 KiB\n// for eight bit-shifts per byte.\nfunc MakeTable(poly uint32) *Table {\n\tvar t Table\n\tfor i := 0; i \u003c 256; i++ {\n\t\tcrc := uint32(i)\n\t\tfor j := 0; j \u003c 8; j++ {\n\t\t\tif crc\u00261 != 0 {\n\t\t\t\tcrc = (crc \u003e\u003e 1) ^ poly\n\t\t\t} else {\n\t\t\t\tcrc \u003e\u003e= 1\n\t\t\t}\n\t\t}\n\t\tt[i] = crc\n\t}\n\treturn \u0026t\n}\n\nvar ieeeTable = MakeTable(IEEE)\n\n// Update adds the bytes of s to a running checksum.\n//\n// Takes and returns the RAW register, not the final value: the caller-visible\n// checksum is the register XOR 0xFFFFFFFF, so chaining Update calls on final\n// values would be wrong. Start from 0 and finish with Finalize.\nfunc Update(crc uint32, t *Table, s string) uint32 {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tcrc = t[byte(crc)^s[i]] ^ (crc \u003e\u003e 8)\n\t}\n\treturn crc\n}\n\n// Finalize turns a running register into the checksum.\nfunc Finalize(crc uint32) uint32 { return crc ^ 0xFFFFFFFF }\n\n// ChecksumWith returns the CRC-32 of s under the given table.\nfunc ChecksumWith(s string, t *Table) uint32 {\n\treturn Finalize(Update(0xFFFFFFFF, t, s))\n}\n\n// Checksum returns the IEEE CRC-32 of s — the one zip, gzip and PNG use.\nfunc Checksum(s string) uint32 { return ChecksumWith(s, ieeeTable) }\n\n// Hex renders a checksum as eight lowercase hex digits, zero-padded, which is\n// how CRCs are conventionally shown.\nfunc Hex(crc uint32) string {\n\tconst digits = \"0123456789abcdef\"\n\tvar b [8]byte\n\tfor i := 7; i \u003e= 0; i-- {\n\t\tb[i] = digits[crc\u00260xF]\n\t\tcrc \u003e\u003e= 4\n\t}\n\treturn string(b[:])\n}\n\n// ChecksumHex is Checksum rendered with Hex.\nfunc ChecksumHex(s string) string { return Hex(Checksum(s)) }\n\n// Verify reports whether s has the expected checksum.\nfunc Verify(s string, expected uint32) bool { return Checksum(s) == expected }\n\n// Split returns the checksum of each line of s, in order.\nfunc Split(s string) []string {\n\tout := []string{}\n\tfor _, line := range strings.Split(s, \"\\n\") {\n\t\tout = append(out, ChecksumHex(line))\n\t}\n\treturn out\n}\n"},{"name":"crc32_test.gno","body":"package crc32\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Known-answer tests against the published IEEE vectors.\nfunc TestChecksumKnownVectors(t *testing.T) {\n\tcases := []struct {\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"\", \"00000000\"},\n\t\t{\"a\", \"e8b7be43\"},\n\t\t{\"abc\", \"352441c2\"},\n\t\t{\"message digest\", \"20159d7f\"},\n\t\t{\"abcdefghijklmnopqrstuvwxyz\", \"4c2750bd\"},\n\t\t{\"123456789\", \"cbf43926\"}, // the standard CRC check value\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, ChecksumHex(c.in))\n\t}\n}\n\n// The classic \"check\" value: CRC-32/IEEE of \"123456789\" is 0xCBF43926.\nfunc TestStandardCheckValue(t *testing.T) {\n\tuassert.Equal(t, uint32(0xCBF43926), Checksum(\"123456789\"))\n}\n\nfunc TestHexIsZeroPadded(t *testing.T) {\n\tuassert.Equal(t, \"00000000\", Hex(0))\n\tuassert.Equal(t, \"0000000f\", Hex(15))\n\tuassert.Equal(t, \"ffffffff\", Hex(0xFFFFFFFF))\n\tuassert.Equal(t, 8, len(Hex(1)))\n}\n\n// A single flipped bit must change the checksum — the entire point.\nfunc TestDetectsSingleBitChange(t *testing.T) {\n\tbase := Checksum(\"hello world\")\n\tuassert.False(t, base == Checksum(\"hello worle\"))\n\tuassert.False(t, base == Checksum(\"Hello world\"))\n}\n\n// Order matters: a CRC is not a sum.\nfunc TestOrderSensitive(t *testing.T) {\n\tuassert.False(t, Checksum(\"ab\") == Checksum(\"ba\"))\n}\n\nfunc TestVerify(t *testing.T) {\n\tuassert.True(t, Verify(\"abc\", 0x352441C2))\n\tuassert.False(t, Verify(\"abd\", 0x352441C2))\n}\n\n// Chaining Update over chunks must equal one shot over the whole message —\n// this is why Update takes the raw register rather than a final value.\nfunc TestUpdateIsChunkable(t *testing.T) {\n\twhole := Checksum(\"hello world\")\n\tcrc := uint32(0xFFFFFFFF)\n\tcrc = Update(crc, ieeeTable, \"hello \")\n\tcrc = Update(crc, ieeeTable, \"world\")\n\tuassert.Equal(t, whole, Finalize(crc))\n}\n\n// Different polynomials must give different answers, and each be stable.\nfunc TestAlternatePolynomials(t *testing.T) {\n\tc := MakeTable(Castagnoli)\n\tk := MakeTable(Koopman)\n\ta := ChecksumWith(\"123456789\", c)\n\tb := ChecksumWith(\"123456789\", k)\n\tuassert.False(t, a == Checksum(\"123456789\"))\n\tuassert.False(t, a == b)\n\tuassert.Equal(t, a, ChecksumWith(\"123456789\", c)) // stable\n}\n\nfunc TestSplit(t *testing.T) {\n\tgot := Split(\"a\\nabc\")\n\tuassert.Equal(t, 2, len(got))\n\tuassert.Equal(t, \"e8b7be43\", got[0])\n\tuassert.Equal(t, \"352441c2\", got[1])\n}\n\nfunc TestLongInput(t *testing.T) {\n\ts := strings.Repeat(\"gno\", 1000)\n\tuassert.Equal(t, 8, len(ChecksumHex(s)))\n\tuassert.Equal(t, Checksum(s), Checksum(s))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/crc32/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"disjointset","path":"gno.land/p/moul/x/daily/disjointset/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/disjointset/v0`\n\n**Union-find (disjoint-set forest)** — `New`, `Find`, `Union`, `Connected`,\n`Size`, `Groups`, `Partition`, `MaxN`.\n\nTracks a partition of `[0, n)` into disjoint groups and answers \"same group?\" in\nnear-constant time.\n\n```go\nimport \"gno.land/p/moul/x/daily/disjointset/v0\"\n\nd := disjointset.New(10)\nd.Union(0, 1)\nd.Union(1, 3)\nd.Connected(0, 3)   // true\nd.Groups()          // 8\nd.Partition()       // [[0 1 3] [2] [4] ...]\n```\n\n**Both optimisations, because they only work together:** path compression\nflattens the tree on every `Find`, union by rank keeps the shallower tree under\nthe deeper one. With both, operations are O(α(n)) — inverse Ackermann,\neffectively constant. With neither, a chain of unions degrades to O(n) per\nquery, which on chain is the difference between a cheap call and running out of\ngas. `Find` compresses **iteratively**: a deep chain would otherwise risk the\ncall stack.\n\n`Partition` returns groups sorted ascending and ordered by their smallest\nmember, so the result is **identical regardless of the order unions were\napplied** — that determinism is what makes it safe to put in a `Render`.\n\nOut-of-range indices return `-1`/`false`/`0` rather than panicking, and are\nconnected to nothing — not even to themselves.\n\n**Live demo:** [`r/moul/x/daily/disjointsetdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/disjointsetdemo)\n· render it at [`/r/moul/x/daily/disjointsetdemo/v0`](https://gno.land/r/moul/x/daily/disjointsetdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"disjointset.gno","body":"// Package disjointset is union-find (a disjoint-set forest) as a pure,\n// reusable package: it tracks a partition of [0, n) into disjoint groups and\n// answers \"are these two in the same group?\" in near-constant time.\n//\n// Both classic optimisations are implemented, and they matter together: path\n// compression flattens a tree on every Find, union by rank keeps the shallower\n// tree under the deeper one. With both, operations are O(α(n)) — inverse\n// Ackermann, effectively constant. With neither, a chain of unions degrades to\n// O(n) per query, which on chain is the difference between a cheap call and an\n// out-of-gas one.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/disjointsetdemo](/r/moul/x/daily/disjointsetdemo/v0).\npackage disjointset\n\n// MaxN bounds a set so allocation stays predictable.\nconst MaxN = 1 \u003c\u003c 16\n\n// DisjointSet is a partition of [0, n) into disjoint groups.\ntype DisjointSet struct {\n\tparent []int\n\trank   []int\n\tgroups int\n}\n\n// New returns n singleton groups. n is clamped to [0, MaxN].\nfunc New(n int) *DisjointSet {\n\tif n \u003c 0 {\n\t\tn = 0\n\t}\n\tif n \u003e MaxN {\n\t\tn = MaxN\n\t}\n\td := \u0026DisjointSet{parent: make([]int, n), rank: make([]int, n), groups: n}\n\tfor i := 0; i \u003c n; i++ {\n\t\td.parent[i] = i // every element starts as its own root\n\t}\n\treturn d\n}\n\n// Len returns the number of elements.\nfunc (d *DisjointSet) Len() int { return len(d.parent) }\n\n// Groups returns how many disjoint groups remain.\nfunc (d *DisjointSet) Groups() int { return d.groups }\n\n// InRange reports whether i is a valid element.\nfunc (d *DisjointSet) InRange(i int) bool { return i \u003e= 0 \u0026\u0026 i \u003c len(d.parent) }\n\n// Find returns the representative of i's group, or -1 when i is out of range.\n//\n// Path compression: every node visited is re-pointed straight at the root, so\n// the next Find on any of them is O(1). Done iteratively rather than\n// recursively — a deep chain would otherwise risk the call stack.\nfunc (d *DisjointSet) Find(i int) int {\n\tif !d.InRange(i) {\n\t\treturn -1\n\t}\n\troot := i\n\tfor d.parent[root] != root {\n\t\troot = d.parent[root]\n\t}\n\tfor d.parent[i] != root { // second pass: re-point everything at the root\n\t\tnext := d.parent[i]\n\t\td.parent[i] = root\n\t\ti = next\n\t}\n\treturn root\n}\n\n// Union merges the groups of a and b and reports whether they were merged.\n// False means they were already together, or an index was out of range.\nfunc (d *DisjointSet) Union(a, b int) bool {\n\tra, rb := d.Find(a), d.Find(b)\n\tif ra \u003c 0 || rb \u003c 0 || ra == rb {\n\t\treturn false\n\t}\n\t// Union by rank: hang the shallower tree off the deeper one so depth only\n\t// grows when both sides are equally deep.\n\tif d.rank[ra] \u003c d.rank[rb] {\n\t\tra, rb = rb, ra\n\t}\n\td.parent[rb] = ra\n\tif d.rank[ra] == d.rank[rb] {\n\t\td.rank[ra]++\n\t}\n\td.groups--\n\treturn true\n}\n\n// Connected reports whether a and b are in the same group. Out-of-range\n// indices are not connected to anything, including themselves.\nfunc (d *DisjointSet) Connected(a, b int) bool {\n\tra, rb := d.Find(a), d.Find(b)\n\treturn ra \u003e= 0 \u0026\u0026 ra == rb\n}\n\n// Size returns how many elements share i's group, or 0 when out of range.\nfunc (d *DisjointSet) Size(i int) int {\n\tr := d.Find(i)\n\tif r \u003c 0 {\n\t\treturn 0\n\t}\n\tn := 0\n\tfor j := 0; j \u003c len(d.parent); j++ {\n\t\tif d.Find(j) == r {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// Partition returns the groups, each sorted ascending, ordered by their\n// smallest member — deterministic regardless of the union order, which is what\n// makes it safe to render.\nfunc (d *DisjointSet) Partition() [][]int {\n\tbyRoot := map[int][]int{}\n\torder := []int{}\n\tfor i := 0; i \u003c len(d.parent); i++ {\n\t\tr := d.Find(i)\n\t\tif _, seen := byRoot[r]; !seen {\n\t\t\torder = append(order, r) // first sighting is the smallest member\n\t\t}\n\t\tbyRoot[r] = append(byRoot[r], i)\n\t}\n\tout := [][]int{}\n\tfor _, r := range order { // iterate the slice, never the map\n\t\tout = append(out, byRoot[r])\n\t}\n\treturn out\n}\n"},{"name":"disjointset_test.gno","body":"package disjointset\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestSingletons(t *testing.T) {\n\td := New(5)\n\tuassert.Equal(t, 5, d.Len())\n\tuassert.Equal(t, 5, d.Groups())\n\tfor i := 0; i \u003c 5; i++ {\n\t\tuassert.Equal(t, i, d.Find(i))\n\t\tuassert.Equal(t, 1, d.Size(i))\n\t}\n}\n\nfunc TestUnionAndConnected(t *testing.T) {\n\td := New(6)\n\tuassert.True(t, d.Union(0, 1))\n\tuassert.True(t, d.Union(1, 2))\n\tuassert.True(t, d.Connected(0, 2))\n\tuassert.False(t, d.Connected(0, 3))\n\tuassert.Equal(t, 4, d.Groups()) // {0,1,2} {3} {4} {5}\n\tuassert.Equal(t, 3, d.Size(0))\n}\n\n// Merging an already-merged pair is a no-op and must not lose a group.\nfunc TestUnionIdempotent(t *testing.T) {\n\td := New(4)\n\tuassert.True(t, d.Union(0, 1))\n\tuassert.False(t, d.Union(0, 1))\n\tuassert.False(t, d.Union(1, 0))\n\tuassert.Equal(t, 3, d.Groups())\n}\n\nfunc TestOutOfRange(t *testing.T) {\n\td := New(3)\n\tuassert.Equal(t, -1, d.Find(-1))\n\tuassert.Equal(t, -1, d.Find(3))\n\tuassert.False(t, d.Union(0, 99))\n\tuassert.False(t, d.Union(-1, 0))\n\tuassert.Equal(t, 0, d.Size(99))\n\t// out of range is connected to nothing, not even itself\n\tuassert.False(t, d.Connected(99, 99))\n\tuassert.Equal(t, 3, d.Groups())\n}\n\n// The result must not depend on the order unions were applied.\nfunc TestPartitionIsOrderIndependent(t *testing.T) {\n\ta := New(7)\n\ta.Union(0, 1)\n\ta.Union(2, 3)\n\ta.Union(1, 3)\n\tb := New(7)\n\tb.Union(3, 1)\n\tb.Union(2, 3)\n\tb.Union(1, 0)\n\tuassert.Equal(t, render(a.Partition()), render(b.Partition()))\n\tuassert.Equal(t, \"0,1,2,3|4|5|6\", render(a.Partition()))\n}\n\n// Path compression must not change what the structure means.\nfunc TestFindCompressesWithoutChangingGroups(t *testing.T) {\n\td := New(10)\n\tfor i := 0; i \u003c 9; i++ {\n\t\td.Union(i, i+1) // a long chain, the worst case for an uncompressed find\n\t}\n\tuassert.Equal(t, 1, d.Groups())\n\troot := d.Find(0)\n\tfor i := 0; i \u003c 10; i++ {\n\t\tuassert.Equal(t, root, d.Find(i))\n\t}\n\tuassert.Equal(t, 10, d.Size(0))\n\tuassert.Equal(t, \"0,1,2,3,4,5,6,7,8,9\", render(d.Partition()))\n}\n\nfunc TestEmpty(t *testing.T) {\n\td := New(0)\n\tuassert.Equal(t, 0, d.Len())\n\tuassert.Equal(t, 0, d.Groups())\n\tuassert.Equal(t, 0, len(d.Partition()))\n}\n\nfunc TestClamped(t *testing.T) {\n\tuassert.Equal(t, 0, New(-3).Len())\n\tuassert.Equal(t, MaxN, New(MaxN+50).Len())\n}\n\nfunc render(groups [][]int) string {\n\tparts := []string{}\n\tfor _, g := range groups {\n\t\tnums := []string{}\n\t\tfor _, x := range g {\n\t\t\tnums = append(nums, itoa(x))\n\t\t}\n\t\tparts = append(parts, strings.Join(nums, \",\"))\n\t}\n\treturn strings.Join(parts, \"|\")\n}\n\nfunc itoa(i int) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b []byte\n\tfor i \u003e 0 {\n\t\tb = append([]byte{byte('0' + i%10)}, b...)\n\t\ti /= 10\n\t}\n\treturn string(b)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/disjointset/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"fenwick","path":"gno.land/p/moul/x/daily/fenwick/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/fenwick/v0`\n\n**A Binary Indexed Tree over `int64`**: `New`, `FromSlice`, `Add`, `Set`, `Prefix`, `Range`, `At`, `Total`, `SearchPrefix`, `Slice`, `Covers`.\n\n```go\nimport \"gno.land/p/moul/x/daily/fenwick/v0\"\n\ntr := fenwick.FromSlice([]int64{3, 1, 4, 1, 5})\ntr.Prefix(3)          // 8    sum of [0, 3)\ntr.Range(1, 4)        // 6    sum of [1, 4)\ntr.Add(2, 10)         //      point update, O(log n)\ntr.SearchPrefix(7)    // 2    the slot owning target 7\n```\n\nA realm that keeps a running tally is choosing between two bad options without\nnoticing. A plain slice updates in `O(1)` and sums in `O(n)`. A slice of running\ntotals sums in `O(1)` and updates in `O(n)`. A scoreboard is written by every\nplayer *and* read by every page view, so it pays both costs. A Fenwick tree does\nboth in `O(log n)`, in exactly `n` values of storage, rearranged.\n\n**The operation worth importing a package for is `SearchPrefix`**, not the prefix\nsums. Given a target below `Total` it names the slot that owns it, in `O(log n)`,\nby descending the tree rather than scanning it. That is the primitive behind a\nstake-weighted draw (pick a number, ask who holds it) and behind a leaderboard's\nrank lookup. Prefix sums alone would not justify a data structure.\n\nThree behaviours worth knowing before you use it:\n\n- **Reads are total, writes panic**, and the asymmetry is deliberate. `Prefix`,\n  `Range`, `At`, `Covers` and `SearchPrefix` clamp whatever index they are\n  handed; `Add`, `Set` and `New` panic. A read is what `Render` calls, and a\n  realm cannot be redeployed on the same path, so a `Render` that panics on an\n  out-of-range index is a page that is broken permanently. A write is a\n  transaction, where aborting is the useful answer and the caller can still\n  recover.\n- **A zero-weight slot is never selected by `SearchPrefix`.** It falls out of the\n  descent rather than being checked for: a zero does not advance the prefix, so\n  no target can land on it. That is the property a weighted draw depends on, and\n  the one a naive \"first running total `\u003e=` target\" scan gets wrong.\n- **`SearchPrefix` is only meaningful when every value is non-negative.** With a\n  negative in the tree the prefix sums stop increasing and \"the smallest index\n  whose prefix exceeds the target\" stops being well defined. Negative values are\n  not forbidden, because `Add` with a negative delta is the ordinary way to\n  decrement a counter; it is this one method that needs them absent.\n\n`MaxSize` caps construction at 65,536 slots. Queries are `O(log n)` whatever the\nsize; the cap is there so the single `O(n)` operation, building the tree, cannot\nbe sized from unbounded user input. Sums must fit in `int64`, which gno does not\ncheck and neither does this package.\n\n`Covers(i)` reports which slots an internal node summarizes. It is not needed to\nuse the tree; it exists so the structure can be shown rather than asserted, and\nthe demo realm renders it.\n\nLive demo: [`r/moul/x/daily/fenwickdemo`](/r/moul/x/daily/fenwickdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"fenwick.gno","body":"// Package fenwick is a Binary Indexed Tree (Peter Fenwick, 1994): an array of\n// int64 that answers a prefix sum and applies a point update in O(log n), with\n// no extra storage beyond the array itself.\n//\n// The tradeoff it occupies is the whole reason to reach for one. A plain slice\n// updates in O(1) and sums in O(n). A slice of running totals sums in O(1) and\n// updates in O(n). A Fenwick tree does both in O(log n), which is what a realm\n// wants when reads and writes are interleaved: a scoreboard written by every\n// player and read by every render.\n//\n// The operation that actually justifies the package is [Tree.SearchPrefix]: the\n// smallest index whose prefix sum exceeds a target, in O(log n), by descending\n// the tree rather than scanning it. That is the primitive behind a\n// stake-weighted draw (pick a number below Total, ask which holder owns it) and\n// behind a leaderboard's rank lookup. Prefix sums on their own would not be\n// worth a data structure.\n//\n// Reads are total and writes are strict, deliberately: see the package README.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/fenwickdemo](/r/moul/x/daily/fenwickdemo/v0).\npackage fenwick\n\n// MaxSize bounds the number of slots so a caller cannot size the tree from\n// unbounded user input and make the allocation itself the attack. It is not a\n// gas figure: a query costs O(log n) regardless, and the cap exists so the one\n// O(n) operation in the package, construction, stays bounded.\nconst MaxSize = 65536\n\n// Tree is a Binary Indexed Tree over int64 values, addressed 0-based.\n//\n// The zero value is not usable; build one with [New] or [FromSlice].\ntype Tree struct {\n\tn int\n\t// t is 1-based internally: t[i] holds the sum of the LowBit(i) values\n\t// ending at i. Index 0 is unused, which is what makes the bit tricks work.\n\tt []int64\n}\n\n// New returns a Tree of n zero-valued slots.\n//\n// It panics if n is negative or above [MaxSize]: both are programmer errors\n// that a caller cannot recover from, and a silently clamped size would hand\n// back a tree that disagrees with the caller about its own length.\nfunc New(n int) *Tree {\n\tif n \u003c 0 {\n\t\tpanic(\"fenwick: negative size\")\n\t}\n\tif n \u003e MaxSize {\n\t\tpanic(\"fenwick: size above MaxSize\")\n\t}\n\treturn \u0026Tree{n: n, t: make([]int64, n+1)}\n}\n\n// FromSlice returns a Tree holding vals, built in O(n) rather than by n\n// successive Add calls, which would cost O(n log n).\n//\n// The slice is copied; later writes to vals do not reach the tree.\nfunc FromSlice(vals []int64) *Tree {\n\ttr := New(len(vals))\n\t// Seed each slot, then push it into its parent once. Every slot is visited\n\t// exactly once, which is the whole O(n) construction.\n\tfor i, v := range vals {\n\t\ttr.t[i+1] += v\n\t\tif parent := (i + 1) + lowBit(i+1); parent \u003c= tr.n {\n\t\t\ttr.t[parent] += tr.t[i+1]\n\t\t}\n\t}\n\treturn tr\n}\n\n// Len returns the number of slots.\nfunc (tr *Tree) Len() int { return tr.n }\n\n// Add adds delta to the value at i.\n//\n// It panics if i is out of range. A write is a transaction: failing loudly is\n// the correct outcome, and the caller still has the chance to abort.\nfunc (tr *Tree) Add(i int, delta int64) {\n\tif i \u003c 0 || i \u003e= tr.n {\n\t\tpanic(\"fenwick: index out of range\")\n\t}\n\tfor j := i + 1; j \u003c= tr.n; j += lowBit(j) {\n\t\ttr.t[j] += delta\n\t}\n}\n\n// Set replaces the value at i, returning the value it displaced.\n//\n// It panics if i is out of range, for the same reason [Tree.Add] does.\nfunc (tr *Tree) Set(i int, v int64) int64 {\n\told := tr.At(i)\n\tif i \u003c 0 || i \u003e= tr.n {\n\t\tpanic(\"fenwick: index out of range\")\n\t}\n\ttr.Add(i, v-old)\n\treturn old\n}\n\n// Prefix returns the sum of the first i values, that is of [0, i).\n//\n// It is total: i is clamped into [0, Len], so Prefix(-5) is 0 and Prefix(1e9)\n// is Total. Reads are what Render calls, and a panicking Render is a page that\n// can never be displayed again, on a path that can never be redeployed.\nfunc (tr *Tree) Prefix(i int) int64 {\n\tif i \u003e tr.n {\n\t\ti = tr.n\n\t}\n\tvar sum int64\n\tfor ; i \u003e 0; i -= lowBit(i) {\n\t\tsum += tr.t[i]\n\t}\n\treturn sum\n}\n\n// Range returns the sum of [lo, hi). It is total: bounds are clamped, and an\n// empty or inverted range is 0.\nfunc (tr *Tree) Range(lo, hi int) int64 {\n\tif lo \u003c 0 {\n\t\tlo = 0\n\t}\n\tif hi \u003e tr.n {\n\t\thi = tr.n\n\t}\n\tif lo \u003e= hi {\n\t\treturn 0\n\t}\n\treturn tr.Prefix(hi) - tr.Prefix(lo)\n}\n\n// At returns the value at i, or 0 if i is out of range. Total, like the other\n// reads.\nfunc (tr *Tree) At(i int) int64 {\n\tif i \u003c 0 || i \u003e= tr.n {\n\t\treturn 0\n\t}\n\treturn tr.Range(i, i+1)\n}\n\n// Total returns the sum of every value.\nfunc (tr *Tree) Total() int64 { return tr.Prefix(tr.n) }\n\n// Slice materializes the tree back into a plain slice, in O(n log n).\n//\n// It exists for rendering and for tests. A hot path should not call it.\nfunc (tr *Tree) Slice() []int64 {\n\tout := make([]int64, tr.n)\n\tfor i := 0; i \u003c tr.n; i++ {\n\t\tout[i] = tr.At(i)\n\t}\n\treturn out\n}\n\n// SearchPrefix returns the smallest index i for which Prefix(i+1) \u003e target,\n// or Len if no prefix exceeds it. It runs in O(log n) by descending the tree.\n//\n// With non-negative values this is the weighted select: draw a target in\n// [0, Total) and SearchPrefix names the slot that owns it, each slot chosen in\n// proportion to its value. A zero-valued slot can never be selected, which is\n// the property that makes it usable for a stake-weighted draw.\n//\n// It is total, and a negative target returns 0.\n//\n// The result is only meaningful when every value is non-negative: with a\n// negative value in the tree the prefix sums stop increasing and \"the smallest\n// index whose prefix exceeds target\" stops being well defined. The package does\n// not forbid negative values, because Add with a negative delta is the ordinary\n// way to decrement a counter; it is SearchPrefix alone that needs them absent.\nfunc (tr *Tree) SearchPrefix(target int64) int {\n\tif target \u003c 0 {\n\t\treturn 0\n\t}\n\tpos := 0\n\t// Walk the powers of two downward, largest first. At each step, take the\n\t// jump if the value it would accumulate still does not exceed target.\n\tfor step := highBit(tr.n); step \u003e 0; step \u003e\u003e= 1 {\n\t\tif next := pos + step; next \u003c= tr.n \u0026\u0026 tr.t[next] \u003c= target {\n\t\t\tpos = next\n\t\t\ttarget -= tr.t[next]\n\t\t}\n\t}\n\treturn pos\n}\n\n// lowBit returns the lowest set bit of i, the range width the slot covers.\nfunc lowBit(i int) int { return i \u0026 (-i) }\n\n// highBit returns the highest power of two that is \u003c= n, or 0 when n is 0.\nfunc highBit(n int) int {\n\tp := 1\n\tfor p\u003c\u003c1 \u003c= n {\n\t\tp \u003c\u003c= 1\n\t}\n\tif n == 0 {\n\t\treturn 0\n\t}\n\treturn p\n}\n\n// Covers returns the half-open range [lo, hi) of 0-based slots that the\n// internal node at 1-based position i summarizes, which is what makes the\n// structure legible rather than magic. It is exported for the demo and for\n// anyone trying to see the shape; it is not needed to use the tree.\n//\n// It returns (0, 0) when i is outside [1, Len].\nfunc (tr *Tree) Covers(i int) (int, int) {\n\tif i \u003c 1 || i \u003e tr.n {\n\t\treturn 0, 0\n\t}\n\treturn i - lowBit(i), i\n}\n"},{"name":"fenwick_test.gno","body":"package fenwick\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// naive is the reference implementation every structural test is checked\n// against: the obvious O(n) loop nobody would ship. A data structure whose\n// whole claim is \"same answers, better complexity\" is only worth trusting if\n// the same answers half is pinned against something too simple to be wrong.\ntype naive []int64\n\nfunc (s naive) prefix(i int) int64 {\n\tif i \u003e len(s) {\n\t\ti = len(s)\n\t}\n\tvar sum int64\n\tfor k := 0; k \u003c i; k++ {\n\t\tsum += s[k]\n\t}\n\treturn sum\n}\n\nfunc (s naive) searchPrefix(target int64) int {\n\tif target \u003c 0 {\n\t\treturn 0\n\t}\n\tvar run int64\n\tfor i, v := range s {\n\t\trun += v\n\t\tif run \u003e target {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn len(s)\n}\n\nfunc TestPrefixMatchesNaive(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tvals []int64\n\t}{\n\t\t{\"empty\", []int64{}},\n\t\t{\"one\", []int64{7}},\n\t\t{\"two\", []int64{3, 4}},\n\t\t// A power of two and one past it: the tree's shape changes at the\n\t\t// boundary, and an off-by-one in lowBit only shows on one side of it.\n\t\t{\"eight\", []int64{1, 2, 3, 4, 5, 6, 7, 8}},\n\t\t{\"nine\", []int64{1, 2, 3, 4, 5, 6, 7, 8, 9}},\n\t\t{\"zeros\", []int64{0, 0, 0, 0, 0}},\n\t\t{\"negatives\", []int64{5, -3, 2, -10, 40}},\n\t\t{\"large\", []int64{1 \u003c\u003c 40, 1 \u003c\u003c 40, -(1 \u003c\u003c 41)}},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttr := FromSlice(tc.vals)\n\t\t\tref := naive(tc.vals)\n\t\t\tuassert.Equal(t, len(tc.vals), tr.Len())\n\t\t\tfor i := 0; i \u003c= len(tc.vals); i++ {\n\t\t\t\tuassert.Equal(t, ref.prefix(i), tr.Prefix(i))\n\t\t\t}\n\t\t\tfor i := range tc.vals {\n\t\t\t\tuassert.Equal(t, tc.vals[i], tr.At(i))\n\t\t\t}\n\t\t\tuassert.Equal(t, ref.prefix(len(tc.vals)), tr.Total())\n\t\t})\n\t}\n}\n\n// TestFromSliceEqualsRepeatedAdd pins the O(n) construction against the O(n log\n// n) one. They are different code paths writing the same array, and only this\n// says so.\nfunc TestFromSliceEqualsRepeatedAdd(t *testing.T) {\n\tvals := []int64{4, 0, 9, 2, 7, 1, 1, 6, 3}\n\n\tbuilt := FromSlice(vals)\n\tadded := New(len(vals))\n\tfor i, v := range vals {\n\t\tadded.Add(i, v)\n\t}\n\n\tuassert.Equal(t, len(built.t), len(added.t))\n\tfor i := range built.t {\n\t\tuassert.Equal(t, built.t[i], added.t[i])\n\t}\n}\n\nfunc TestRange(t *testing.T) {\n\tvals := []int64{1, 2, 3, 4, 5}\n\ttr := FromSlice(vals)\n\n\tcases := []struct {\n\t\tname   string\n\t\tlo, hi int\n\t\twant   int64\n\t}{\n\t\t{\"whole\", 0, 5, 15},\n\t\t{\"middle\", 1, 4, 9},\n\t\t{\"single\", 2, 3, 3},\n\t\t{\"empty\", 2, 2, 0},\n\t\t{\"inverted\", 4, 1, 0},\n\t\t{\"low clamped\", -100, 2, 3},\n\t\t{\"high clamped\", 3, 100, 9},\n\t\t{\"both clamped\", -7, 700, 15},\n\t\t{\"wholly below\", -9, -2, 0},\n\t\t{\"wholly above\", 60, 90, 0},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, tr.Range(tc.lo, tc.hi))\n\t\t})\n\t}\n}\n\n// TestReadsAreTotal is the package's load-bearing safety claim: no read panics,\n// whatever it is handed. A realm renders with these, a live realm cannot be\n// redeployed, so a panicking read is a permanently broken page.\nfunc TestReadsAreTotal(t *testing.T) {\n\tfor _, n := range []int{0, 1, 5} {\n\t\ttr := New(n)\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttr.Add(i, int64(i+1))\n\t\t}\n\t\tfor _, i := range []int{-1 \u003c\u003c 30, -1, 0, n, n + 1, 1 \u003c\u003c 30} {\n\t\t\ttr.Prefix(i)\n\t\t\ttr.At(i)\n\t\t\ttr.Range(i, i+1)\n\t\t\ttr.Covers(i)\n\t\t\ttr.SearchPrefix(int64(i))\n\t\t}\n\t\ttr.Total()\n\t\ttr.Slice()\n\t}\n}\n\nfunc TestAtOutOfRangeIsZero(t *testing.T) {\n\ttr := FromSlice([]int64{1, 2, 3})\n\tuassert.Equal(t, int64(0), tr.At(-1))\n\tuassert.Equal(t, int64(0), tr.At(3))\n\tuassert.Equal(t, int64(0), tr.At(1\u003c\u003c20))\n}\n\nfunc TestPrefixClampsRatherThanPanics(t *testing.T) {\n\ttr := FromSlice([]int64{1, 2, 3})\n\tuassert.Equal(t, int64(0), tr.Prefix(-5))\n\tuassert.Equal(t, int64(6), tr.Prefix(99))\n}\n\nfunc TestAddAndSet(t *testing.T) {\n\ttr := FromSlice([]int64{1, 2, 3, 4})\n\n\ttr.Add(1, 10)\n\tuassert.Equal(t, int64(12), tr.At(1))\n\tuassert.Equal(t, int64(20), tr.Total())\n\n\told := tr.Set(1, 2)\n\tuassert.Equal(t, int64(12), old)\n\tuassert.Equal(t, int64(2), tr.At(1))\n\tuassert.Equal(t, int64(10), tr.Total())\n\n\ttr.Add(3, -4)\n\tuassert.Equal(t, int64(0), tr.At(3))\n\tuassert.Equal(t, int64(6), tr.Total())\n}\n\n// TestWritesArePanicking is the other half of the read/write asymmetry. A\n// write is a transaction and should abort; a read is a render and must not.\nfunc TestWritesArePanicking(cur realm, t *testing.T) {\n\ttr := New(3)\n\tuassert.PanicsWithMessage(t, cur, \"fenwick: index out of range\", func() { tr.Add(3, 1) })\n\tuassert.PanicsWithMessage(t, cur, \"fenwick: index out of range\", func() { tr.Add(-1, 1) })\n\tuassert.PanicsWithMessage(t, cur, \"fenwick: index out of range\", func() { tr.Set(9, 1) })\n\tuassert.PanicsWithMessage(t, cur, \"fenwick: negative size\", func() { New(-1) })\n\tuassert.PanicsWithMessage(t, cur, \"fenwick: size above MaxSize\", func() { New(MaxSize + 1) })\n\tuassert.NotPanics(t, cur, func() { New(MaxSize) })\n}\n\nfunc TestSearchPrefixMatchesNaive(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tvals []int64\n\t}{\n\t\t{\"empty\", []int64{}},\n\t\t{\"flat\", []int64{1, 1, 1, 1}},\n\t\t// Zero weights must be unselectable: this is the property a weighted\n\t\t// draw depends on, and the one a naive scan gets wrong by returning the\n\t\t// first index whose running total is merely \u003e= target.\n\t\t{\"with zeros\", []int64{0, 3, 0, 0, 2, 0}},\n\t\t{\"uneven\", []int64{5, 0, 1, 9, 2}},\n\t\t{\"leading zero\", []int64{0, 0, 7}},\n\t\t{\"eight\", []int64{1, 2, 3, 4, 5, 6, 7, 8}},\n\t\t{\"nine\", []int64{9, 1, 1, 1, 1, 1, 1, 1, 1}},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttr := FromSlice(tc.vals)\n\t\t\tref := naive(tc.vals)\n\t\t\ttotal := ref.prefix(len(tc.vals))\n\t\t\t// Probe every reachable target plus both sides of the boundary.\n\t\t\tfor target := int64(-2); target \u003c= total+2; target++ {\n\t\t\t\tuassert.Equal(t, ref.searchPrefix(target), tr.SearchPrefix(target))\n\t\t\t}\n\t\t})\n\t}\n}\n\n// TestSearchPrefixNeverSelectsAZeroWeight states the draw property directly,\n// rather than leaving it implied by agreement with the reference.\nfunc TestSearchPrefixNeverSelectsAZeroWeight(t *testing.T) {\n\tvals := []int64{0, 5, 0, 0, 3, 0, 2, 0}\n\ttr := FromSlice(vals)\n\tfor target := int64(0); target \u003c tr.Total(); target++ {\n\t\tgot := tr.SearchPrefix(target)\n\t\tif vals[got] == 0 {\n\t\t\tt.Errorf(\"target %d selected slot %d, which has weight 0\", target, got)\n\t\t}\n\t}\n\t// Every draw lands inside the tree, and only an exhausted target runs off\n\t// the end.\n\tuassert.Equal(t, tr.Len(), tr.SearchPrefix(tr.Total()))\n}\n\n// TestSearchPrefixIsProportional checks the distribution, not just the bounds:\n// slot i must own exactly vals[i] of the Total targets.\nfunc TestSearchPrefixIsProportional(t *testing.T) {\n\tvals := []int64{3, 1, 0, 6, 2}\n\ttr := FromSlice(vals)\n\thits := make([]int64, len(vals))\n\tfor target := int64(0); target \u003c tr.Total(); target++ {\n\t\thits[tr.SearchPrefix(target)]++\n\t}\n\tfor i := range vals {\n\t\tuassert.Equal(t, vals[i], hits[i])\n\t}\n}\n\nfunc TestSlice(t *testing.T) {\n\tvals := []int64{6, 0, -2, 11}\n\ttr := FromSlice(vals)\n\tgot := tr.Slice()\n\tuassert.Equal(t, len(vals), len(got))\n\tfor i := range vals {\n\t\tuassert.Equal(t, vals[i], got[i])\n\t}\n\tuassert.Equal(t, 0, len(New(0).Slice()))\n}\n\n// TestFromSliceCopies pins that the tree does not alias the caller's slice.\nfunc TestFromSliceCopies(t *testing.T) {\n\tvals := []int64{1, 2, 3}\n\ttr := FromSlice(vals)\n\tvals[0] = 999\n\tuassert.Equal(t, int64(1), tr.At(0))\n}\n\nfunc TestCovers(t *testing.T) {\n\ttr := New(8)\n\tcases := []struct {\n\t\tname   string\n\t\ti      int\n\t\tlo, hi int\n\t}{\n\t\t{\"odd covers one\", 1, 0, 1},\n\t\t{\"two covers two\", 2, 0, 2},\n\t\t{\"three covers one\", 3, 2, 3},\n\t\t{\"four covers four\", 4, 0, 4},\n\t\t{\"six covers two\", 6, 4, 6},\n\t\t{\"eight covers all\", 8, 0, 8},\n\t\t{\"below range\", 0, 0, 0},\n\t\t{\"above range\", 9, 0, 0},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tlo, hi := tr.Covers(tc.i)\n\t\t\tuassert.Equal(t, tc.lo, lo)\n\t\t\tuassert.Equal(t, tc.hi, hi)\n\t\t})\n\t}\n}\n\n// TestCoversPartitions is the structural claim behind the whole package: the\n// nodes a Prefix walk visits tile [0, i) exactly, with no gap and no overlap.\n// If that ever stops holding, every sum is wrong and this says so in one place.\nfunc TestCoversPartitions(t *testing.T) {\n\tconst n = 13\n\ttr := New(n)\n\tfor i := 1; i \u003c= n; i++ {\n\t\tcovered := make([]bool, n)\n\t\tfor j := i; j \u003e 0; j -= lowBit(j) {\n\t\t\tlo, hi := tr.Covers(j)\n\t\t\tfor k := lo; k \u003c hi; k++ {\n\t\t\t\tif covered[k] {\n\t\t\t\t\tt.Errorf(\"prefix %d: slot %d covered twice\", i, k)\n\t\t\t\t}\n\t\t\t\tcovered[k] = true\n\t\t\t}\n\t\t}\n\t\tfor k := 0; k \u003c n; k++ {\n\t\t\tif covered[k] != (k \u003c i) {\n\t\t\t\tt.Errorf(\"prefix %d: slot %d covered=%t, want %t\", i, k, covered[k], k \u003c i)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestLowBit(t *testing.T) {\n\tcases := []struct{ in, want int }{\n\t\t{1, 1}, {2, 2}, {3, 1}, {4, 4}, {6, 2}, {8, 8}, {12, 4}, {96, 32},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, lowBit(tc.in))\n\t}\n}\n\nfunc TestHighBit(t *testing.T) {\n\tcases := []struct{ in, want int }{\n\t\t{0, 0}, {1, 1}, {2, 2}, {3, 2}, {4, 4}, {7, 4}, {8, 8}, {9, 8}, {1000, 512},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, highBit(tc.in))\n\t}\n}\n\n// TestLargeTreeStaysConsistent exercises a size past the small hand-checked\n// cases, where a wrong jump in SearchPrefix would still look plausible.\nfunc TestLargeTreeStaysConsistent(t *testing.T) {\n\tconst n = 500\n\tvals := make([]int64, n)\n\t// Deterministic, and deliberately not uniform: a constant weight hides a\n\t// SearchPrefix that is off by a slot.\n\tfor i := range vals {\n\t\tvals[i] = int64((i*7919)%13) + 1\n\t}\n\ttr := FromSlice(vals)\n\tref := naive(vals)\n\n\tuassert.Equal(t, ref.prefix(n), tr.Total())\n\tfor _, i := range []int{0, 1, 63, 64, 65, 255, 256, 257, n - 1, n} {\n\t\tuassert.Equal(t, ref.prefix(i), tr.Prefix(i))\n\t}\n\tfor _, target := range []int64{0, 1, 100, 1000, tr.Total() - 1, tr.Total()} {\n\t\tuassert.Equal(t, ref.searchPrefix(target), tr.SearchPrefix(target))\n\t}\n\n\ttr.Add(499, 1000)\n\tuassert.Equal(t, ref.prefix(n)+1000, tr.Total())\n\tuassert.Equal(t, vals[499]+1000, tr.At(499))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/fenwick/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"9000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"flatmap","path":"gno.land/p/moul/x/daily/flatmap/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/flatmap/v0`\n\n**Sorted-vector map** — `New`, `Set`, `Get`, `Has`, `Delete`, `Keys`, `Values`,\n`At`, `Iterate`, `Range`, `Clone`, `Sorted`, `MaxEntries`.\n\n```go\nimport \"gno.land/p/moul/x/daily/flatmap/v0\"\n\nf := flatmap.New()\nf.Set(\"delta\", \"4\"); f.Set(\"alpha\", \"1\")\nf.Keys()                  // [\"alpha\" \"delta\"] — sorted by construction\nf.At(0)                   // \"alpha\", \"1\", true — indexed access\nf.Range(\"a\", \"c\", fn)     // lo inclusive, hi exclusive\n```\n\nThe STL `flat_map` trade. Keys and values live in two parallel sorted slices\ninstead of a hash table or a tree of nodes:\n\n| operation | cost |\n|---|---|\n| `Get` | O(log n) binary search over contiguous memory |\n| iteration | O(n), already ordered, nothing to sort |\n| `Set` in the middle | **O(n)** — the tail shifts |\n| `Set` at the end | O(1) amortised — the fast path |\n\nCheap reads and cheap ordered iteration, paid for at write time. That trade is\nstated rather than hidden.\n\nOn chain the ordering is the real draw: a built-in gno map iterates in an\nunspecified order, so a `Render` built from one can differ between nodes. A flat\nmap is sorted by construction, so iteration is deterministic **without a sort on\nevery read**.\n\nSorted storage also buys two things a hash map cannot offer: `At(i)` positional\naccess, and `Range(lo, hi)` as two binary searches and a walk — including when\nthe bounds are not themselves keys.\n\n`Sorted()` is exported so callers can assert the invariant; it holds through the\nwhole public API, including 200 worst-case head insertions.\n\n**Live demo:** [`r/moul/x/daily/flatmapdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/flatmapdemo)\n· render it at [`/r/moul/x/daily/flatmapdemo/v0`](https://gno.land/r/moul/x/daily/flatmapdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"flatmap.gno","body":"// Package flatmap is a sorted-vector map — the STL flat_map / Abseil\n// btree_map trade — as a pure, reusable package.\n//\n// Keys and values live in two parallel sorted slices instead of a hash table or\n// a tree of nodes. Lookup is a binary search, O(log n) rather than O(1), but it\n// touches contiguous memory instead of chasing pointers, iteration is already\n// in key order with nothing to sort, and there is no per-entry node overhead.\n// Insertion in the middle is O(n) because it shifts the tail. That is the whole\n// bargain: cheap reads and cheap ordered iteration, paid for at write time.\n//\n// On chain the ordering is the real draw. A built-in gno map iterates in an\n// unspecified order, so a Render built from one can differ between nodes — a\n// consensus bug rather than a cosmetic one. A flat map is sorted by\n// construction, so iteration is deterministic without a sort on every read.\n//\n// Appending in ascending key order is the fast path: it hits the end of the\n// slice and shifts nothing.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/flatmapdemo](/r/moul/x/daily/flatmapdemo/v0).\npackage flatmap\n\nimport \"sort\"\n\n// MaxEntries bounds the map so gas stays predictable.\nconst MaxEntries = 4096\n\n// FlatMap is a string-\u003estring map backed by parallel sorted slices.\ntype FlatMap struct {\n\tkeys []string\n\tvals []string\n}\n\n// New returns an empty FlatMap.\nfunc New() *FlatMap { return \u0026FlatMap{} }\n\n// Len returns the number of entries.\nfunc (f *FlatMap) Len() int { return len(f.keys) }\n\n// IsEmpty reports whether the map holds nothing.\nfunc (f *FlatMap) IsEmpty() bool { return len(f.keys) == 0 }\n\n// search returns the index where key is, or would be inserted, plus whether it\n// is actually present.\nfunc (f *FlatMap) search(key string) (int, bool) {\n\ti := sort.SearchStrings(f.keys, key)\n\treturn i, i \u003c len(f.keys) \u0026\u0026 f.keys[i] == key\n}\n\n// Get returns the value for key.\nfunc (f *FlatMap) Get(key string) (string, bool) {\n\ti, found := f.search(key)\n\tif !found {\n\t\treturn \"\", false\n\t}\n\treturn f.vals[i], true\n}\n\n// Has reports whether key is present.\nfunc (f *FlatMap) Has(key string) bool { _, found := f.search(key); return found }\n\n// Set inserts or updates key. Returns false only when the map is full and key\n// is new — updating an existing key always succeeds.\nfunc (f *FlatMap) Set(key, value string) bool {\n\ti, found := f.search(key)\n\tif found {\n\t\tf.vals[i] = value\n\t\treturn true\n\t}\n\tif len(f.keys) \u003e= MaxEntries {\n\t\treturn false\n\t}\n\t// Grow by one, then shift the tail right to open a slot at i.\n\tf.keys = append(f.keys, \"\")\n\tf.vals = append(f.vals, \"\")\n\tcopy(f.keys[i+1:], f.keys[i:])\n\tcopy(f.vals[i+1:], f.vals[i:])\n\tf.keys[i] = key\n\tf.vals[i] = value\n\treturn true\n}\n\n// Delete removes key. Returns false when absent.\nfunc (f *FlatMap) Delete(key string) bool {\n\ti, found := f.search(key)\n\tif !found {\n\t\treturn false\n\t}\n\tcopy(f.keys[i:], f.keys[i+1:])\n\tcopy(f.vals[i:], f.vals[i+1:])\n\tf.keys = f.keys[:len(f.keys)-1]\n\tf.vals = f.vals[:len(f.vals)-1]\n\treturn true\n}\n\n// Keys returns the keys in sorted order, as a copy.\nfunc (f *FlatMap) Keys() []string {\n\tout := make([]string, len(f.keys))\n\tcopy(out, f.keys)\n\treturn out\n}\n\n// Values returns the values ordered by their keys, as a copy.\nfunc (f *FlatMap) Values() []string {\n\tout := make([]string, len(f.vals))\n\tcopy(out, f.vals)\n\treturn out\n}\n\n// At returns the i-th entry in key order — the indexed access a hash map cannot\n// offer, and one reason to pay for sorted storage.\nfunc (f *FlatMap) At(i int) (key, value string, ok bool) {\n\tif i \u003c 0 || i \u003e= len(f.keys) {\n\t\treturn \"\", \"\", false\n\t}\n\treturn f.keys[i], f.vals[i], true\n}\n\n// Iterate calls fn for each entry in key order. Returning true stops.\nfunc (f *FlatMap) Iterate(fn func(key, value string) bool) {\n\tfor i := range f.keys {\n\t\tif fn(f.keys[i], f.vals[i]) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// Range calls fn for entries with lo \u003c= key \u003c hi, in key order. An empty hi\n// means \"to the end\". This is the other thing sorted storage buys: a range\n// query is two binary searches and a walk.\nfunc (f *FlatMap) Range(lo, hi string, fn func(key, value string) bool) {\n\tstart := sort.SearchStrings(f.keys, lo)\n\tfor i := start; i \u003c len(f.keys); i++ {\n\t\tif hi != \"\" \u0026\u0026 f.keys[i] \u003e= hi {\n\t\t\treturn\n\t\t}\n\t\tif fn(f.keys[i], f.vals[i]) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// Clone returns an independent copy.\nfunc (f *FlatMap) Clone() *FlatMap {\n\treturn \u0026FlatMap{keys: f.Keys(), vals: f.Values()}\n}\n\n// Sorted reports whether the backing slice is in strictly ascending order.\n// Always true through the public API; exported so callers can assert it.\nfunc (f *FlatMap) Sorted() bool {\n\tfor i := 1; i \u003c len(f.keys); i++ {\n\t\tif f.keys[i-1] \u003e= f.keys[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn len(f.keys) == len(f.vals)\n}\n"},{"name":"flatmap_test.gno","body":"package flatmap\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestEmpty(t *testing.T) {\n\tf := New()\n\tuassert.Equal(t, 0, f.Len())\n\tuassert.True(t, f.IsEmpty())\n\tuassert.False(t, f.Has(\"a\"))\n\tuassert.True(t, f.Sorted(), \"an empty map is trivially sorted\")\n\n\t_, ok := f.Get(\"a\")\n\tuassert.False(t, ok)\n\t_, _, ok = f.At(0)\n\tuassert.False(t, ok)\n}\n\n// TestStaysSortedRegardlessOfInsertionOrder is the core invariant.\nfunc TestStaysSortedRegardlessOfInsertionOrder(t *testing.T) {\n\tf := New()\n\tfor _, k := range []string{\"delta\", \"alpha\", \"echo\", \"bravo\", \"charlie\"} {\n\t\tf.Set(k, \"v-\"+k)\n\t}\n\tuassert.Equal(t, \"alpha,bravo,charlie,delta,echo\", strings.Join(f.Keys(), \",\"))\n\tuassert.True(t, f.Sorted())\n}\n\nfunc TestGetSet(t *testing.T) {\n\tf := New()\n\tuassert.True(t, f.Set(\"b\", \"2\"))\n\tuassert.True(t, f.Set(\"a\", \"1\"))\n\n\tv, ok := f.Get(\"a\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"1\", v)\n\n\t_, ok = f.Get(\"zzz\")\n\tuassert.False(t, ok)\n}\n\nfunc TestSetUpdatesInPlace(t *testing.T) {\n\tf := New()\n\tf.Set(\"a\", \"1\")\n\tf.Set(\"b\", \"2\")\n\n\tuassert.True(t, f.Set(\"a\", \"99\"))\n\tuassert.Equal(t, 2, f.Len(), \"updating must not add an entry\")\n\n\tv, _ := f.Get(\"a\")\n\tuassert.Equal(t, \"99\", v)\n\tuassert.True(t, f.Sorted())\n}\n\nfunc TestValuesFollowKeyOrder(t *testing.T) {\n\tf := New()\n\tf.Set(\"c\", \"3\")\n\tf.Set(\"a\", \"1\")\n\tf.Set(\"b\", \"2\")\n\tuassert.Equal(t, \"1,2,3\", strings.Join(f.Values(), \",\"))\n}\n\nfunc TestDelete(t *testing.T) {\n\tf := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\"} {\n\t\tf.Set(k, k)\n\t}\n\n\tuassert.True(t, f.Delete(\"b\"))\n\tuassert.Equal(t, \"a,c,d\", strings.Join(f.Keys(), \",\"), \"the gap must close\")\n\tuassert.Equal(t, \"a,c,d\", strings.Join(f.Values(), \",\"), \"values shift with keys\")\n\tuassert.Equal(t, 3, f.Len())\n\tuassert.True(t, f.Sorted())\n\n\tuassert.False(t, f.Delete(\"b\"), \"deleting twice reports false\")\n}\n\nfunc TestDeleteEnds(t *testing.T) {\n\tf := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\"} {\n\t\tf.Set(k, k)\n\t}\n\tuassert.True(t, f.Delete(\"a\"))\n\tuassert.True(t, f.Delete(\"c\"))\n\tuassert.Equal(t, \"b\", strings.Join(f.Keys(), \",\"))\n\tuassert.True(t, f.Delete(\"b\"))\n\tuassert.True(t, f.IsEmpty())\n}\n\nfunc TestAt(t *testing.T) {\n\tf := New()\n\tf.Set(\"b\", \"2\")\n\tf.Set(\"a\", \"1\")\n\n\tk, v, ok := f.At(0)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"a\", k)\n\tuassert.Equal(t, \"1\", v)\n\n\t_, _, ok = f.At(-1)\n\tuassert.False(t, ok)\n\t_, _, ok = f.At(2)\n\tuassert.False(t, ok)\n}\n\nfunc TestIterateAndStop(t *testing.T) {\n\tf := New()\n\tfor _, k := range []string{\"c\", \"a\", \"b\"} {\n\t\tf.Set(k, strings.ToUpper(k))\n\t}\n\n\tvar seen []string\n\tf.Iterate(func(k, v string) bool {\n\t\tseen = append(seen, k+\"=\"+v)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"a=A,b=B,c=C\", strings.Join(seen, \",\"))\n\n\tcount := 0\n\tf.Iterate(func(k, v string) bool { count++; return true })\n\tuassert.Equal(t, 1, count, \"returning true stops iteration\")\n}\n\n// TestRange is the query sorted storage makes cheap.\nfunc TestRange(t *testing.T) {\n\tf := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\"} {\n\t\tf.Set(k, k)\n\t}\n\n\tuassert.Equal(t, \"b,c,d\", collect(f, \"b\", \"e\"), \"lo inclusive, hi exclusive\")\n\tuassert.Equal(t, \"c,d,e\", collect(f, \"c\", \"\"), \"empty hi runs to the end\")\n\tuassert.Equal(t, \"a,b,c,d,e\", collect(f, \"\", \"\"), \"empty bounds cover everything\")\n\tuassert.Equal(t, \"\", collect(f, \"x\", \"z\"), \"a range past the end yields nothing\")\n\tuassert.Equal(t, \"\", collect(f, \"c\", \"c\"), \"an empty half-open range yields nothing\")\n}\n\nfunc TestRangeStops(t *testing.T) {\n\tf := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\"} {\n\t\tf.Set(k, k)\n\t}\n\tn := 0\n\tf.Range(\"\", \"\", func(k, v string) bool { n++; return true })\n\tuassert.Equal(t, 1, n)\n}\n\nfunc TestRangeOnAbsentBoundary(t *testing.T) {\n\tf := New()\n\tfor _, k := range []string{\"a\", \"c\", \"e\"} {\n\t\tf.Set(k, k)\n\t}\n\t// \"b\" and \"d\" are not present; the range still lands correctly.\n\tuassert.Equal(t, \"c\", collect(f, \"b\", \"d\"))\n}\n\nfunc TestKeysAndValuesAreCopies(t *testing.T) {\n\tf := New()\n\tf.Set(\"a\", \"1\")\n\tf.Set(\"b\", \"2\")\n\n\tks := f.Keys()\n\tks[0] = \"mutated\"\n\tvs := f.Values()\n\tvs[0] = \"mutated\"\n\n\tuassert.Equal(t, \"a,b\", strings.Join(f.Keys(), \",\"), \"callers cannot reorder the map through Keys\")\n\tuassert.Equal(t, \"1,2\", strings.Join(f.Values(), \",\"))\n}\n\nfunc TestClone(t *testing.T) {\n\tf := New()\n\tf.Set(\"a\", \"1\")\n\n\tcp := f.Clone()\n\tcp.Set(\"b\", \"2\")\n\n\tuassert.Equal(t, 1, f.Len(), \"clone must not share storage\")\n\tuassert.Equal(t, 2, cp.Len())\n\tuassert.True(t, cp.Sorted())\n}\n\nfunc TestMaxEntries(t *testing.T) {\n\tf := New()\n\tfor i := 0; i \u003c MaxEntries; i++ {\n\t\tuassert.True(t, f.Set(pad(i), \"v\"), \"should accept up to MaxEntries\")\n\t}\n\tuassert.Equal(t, MaxEntries, f.Len())\n\n\tuassert.False(t, f.Set(\"zzz-overflow\", \"v\"), \"a full map refuses a new key\")\n\tuassert.Equal(t, MaxEntries, f.Len())\n\n\tuassert.True(t, f.Set(pad(0), \"updated\"), \"a full map still accepts updates\")\n\tv, _ := f.Get(pad(0))\n\tuassert.Equal(t, \"updated\", v)\n}\n\n// TestDescendingInsertionIsTheSlowPath exercises the worst case for a sorted\n// vector — every insert shifts the whole tail — and checks it stays correct.\nfunc TestDescendingInsertionIsTheSlowPath(t *testing.T) {\n\tf := New()\n\tfor i := 200; i \u003e 0; i-- {\n\t\tf.Set(pad(i), strconv.Itoa(i))\n\t}\n\tuassert.Equal(t, 200, f.Len())\n\tuassert.True(t, f.Sorted(), \"still sorted after 200 head insertions\")\n\n\tk, v, _ := f.At(0)\n\tuassert.Equal(t, pad(1), k)\n\tuassert.Equal(t, \"1\", v, \"keys and values must stay in step through every shift\")\n}\n\nfunc collect(f *FlatMap, lo, hi string) string {\n\tvar out []string\n\tf.Range(lo, hi, func(k, v string) bool {\n\t\tout = append(out, k)\n\t\treturn false\n\t})\n\treturn strings.Join(out, \",\")\n}\n\n// pad zero-pads so string order matches numeric order. ufmt has no width\n// flags in gno, so this is done by hand.\nfunc pad(i int) string {\n\ts := strconv.Itoa(i)\n\tfor len(s) \u003c 6 {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/flatmap/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"fraction","path":"gno.land/p/moul/x/daily/fraction/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/fraction/v0`\n\n**Exact rational arithmetic** — `New`, `Int`, `Zero`, `Add`, `Sub`, `Mul`,\n`Div`, `Neg`, `Cmp`, `Equal`, `String`, `Decimal`.\n\nValues are `p/q` with `int64` numerator and denominator, always in lowest terms\nwith a positive denominator.\n\n```go\nimport \"gno.land/p/moul/x/daily/fraction/v0\"\n\nthird, _ := fraction.New(1, 3)\nsum, ok := third.Add(third)      // 2/3, ok\nsum, ok = sum.Add(third)         // exactly 1 — not 0.9999…\nfraction.Decimal(third, 5)       // \"0.33333\"\n```\n\n**This exists because there are no floats worth trusting on chain.** `0.1 + 0.2`\nis not `0.3` in binary floating point, and a consensus system cannot afford an\nanswer that depends on rounding. A fraction is exact; it only becomes lossy at\nthe moment you ask for a decimal, and `Decimal` makes that moment explicit —\nthe caller chooses how much to lose and when.\n\n**Overflow is reported, never wrapped.** Every operation returns `ok=false` on\n`int64` overflow rather than silently producing a wrapped numerator, which would\nbe a wrong answer that looks perfectly fine.\n\n`Cmp` cross-multiplies, so comparison is exact too: `1/3` and `33333/100000` are\nidentical to five decimal places, and it still knows which is larger.\n\nThe sign always lives in the numerator, so `1/-2` and `-1/2` are the same value.\nThe zero value of the type behaves as `0/1` rather than dividing by zero.\n\n**Live demo:** [`r/moul/x/daily/fractiondemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/fractiondemo)\n· render it at [`/r/moul/x/daily/fractiondemo/v0`](https://gno.land/r/moul/x/daily/fractiondemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"fraction.gno","body":"// Package fraction is exact rational arithmetic as a pure, reusable package:\n// values are p/q with int64 numerator and denominator, always kept in lowest\n// terms with a positive denominator.\n//\n// This exists because there are no floats worth trusting on chain. 0.1 + 0.2 is\n// not 0.3 in binary floating point, and a consensus system cannot afford an\n// answer that depends on rounding. A fraction is exact: one third really is one\n// third, and only becomes lossy at the moment you ask for a decimal.\n//\n// Every operation is checked for int64 overflow and returns ok=false rather\n// than silently wrapping — a wrapped numerator would be a wrong answer that\n// looks fine.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/fractiondemo](/r/moul/x/daily/fractiondemo/v0).\npackage fraction\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// ErrZeroDenominator is returned when a denominator of zero is requested.\nvar ErrZeroDenominator = errors.New(\"fraction: zero denominator\")\n\n// Fraction is an exact rational number in lowest terms, denominator \u003e 0.\ntype Fraction struct {\n\tnum, den int64\n}\n\n// New returns num/den reduced, or an error when den is zero.\nfunc New(num, den int64) (Fraction, error) {\n\tif den == 0 {\n\t\treturn Fraction{}, ErrZeroDenominator\n\t}\n\tif den \u003c 0 { // keep the sign in the numerator so comparisons are simple\n\t\tnum, den = -num, -den\n\t}\n\tg := gcd(abs(num), den)\n\tif g \u003e 1 {\n\t\tnum, den = num/g, den/g\n\t}\n\treturn Fraction{num, den}, nil\n}\n\n// Int returns n as n/1.\nfunc Int(n int64) Fraction { return Fraction{n, 1} }\n\n// Zero is 0/1.\nfunc Zero() Fraction { return Fraction{0, 1} }\n\n// Num returns the numerator; Den the (always positive) denominator.\nfunc (f Fraction) Num() int64 { return f.num }\n\n// Den returns the denominator, which is always \u003e 0. The zero value of the type\n// has den == 0, so treat it as 1 to keep an un-initialised Fraction usable.\nfunc (f Fraction) Den() int64 {\n\tif f.den == 0 {\n\t\treturn 1\n\t}\n\treturn f.den\n}\n\n// IsZero reports whether f == 0.\nfunc (f Fraction) IsZero() bool { return f.num == 0 }\n\nfunc abs(x int64) int64 {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc gcd(a, b int64) int64 {\n\tfor b != 0 {\n\t\ta, b = b, a%b\n\t}\n\tif a == 0 {\n\t\treturn 1\n\t}\n\treturn a\n}\n\n// mulOK multiplies with an overflow check.\nfunc mulOK(a, b int64) (int64, bool) {\n\tif a == 0 || b == 0 {\n\t\treturn 0, true\n\t}\n\tp := a * b\n\tif p/b != a { // the classic check: dividing back must reproduce a\n\t\treturn 0, false\n\t}\n\treturn p, true\n}\n\n// addOK adds with an overflow check.\nfunc addOK(a, b int64) (int64, bool) {\n\ts := a + b\n\tif (a \u003e 0 \u0026\u0026 b \u003e 0 \u0026\u0026 s \u003c 0) || (a \u003c 0 \u0026\u0026 b \u003c 0 \u0026\u0026 s \u003e= 0) {\n\t\treturn 0, false\n\t}\n\treturn s, true\n}\n\n// Add returns f+g. ok is false on int64 overflow.\nfunc (f Fraction) Add(g Fraction) (Fraction, bool) { return combine(f, g, false) }\n\n// Sub returns f-g. ok is false on int64 overflow.\nfunc (f Fraction) Sub(g Fraction) (Fraction, bool) { return combine(f, g, true) }\n\nfunc combine(f, g Fraction, sub bool) (Fraction, bool) {\n\tfd, gd := f.Den(), g.Den()\n\ta, ok1 := mulOK(f.num, gd)\n\tb, ok2 := mulOK(g.num, fd)\n\td, ok3 := mulOK(fd, gd)\n\tif !ok1 || !ok2 || !ok3 {\n\t\treturn Fraction{}, false\n\t}\n\tif sub {\n\t\tb = -b\n\t}\n\tn, ok4 := addOK(a, b)\n\tif !ok4 {\n\t\treturn Fraction{}, false\n\t}\n\tout, err := New(n, d)\n\treturn out, err == nil\n}\n\n// Mul returns f*g. ok is false on int64 overflow.\nfunc (f Fraction) Mul(g Fraction) (Fraction, bool) {\n\tn, ok1 := mulOK(f.num, g.num)\n\td, ok2 := mulOK(f.Den(), g.Den())\n\tif !ok1 || !ok2 {\n\t\treturn Fraction{}, false\n\t}\n\tout, err := New(n, d)\n\treturn out, err == nil\n}\n\n// Div returns f/g. ok is false on overflow or division by zero.\nfunc (f Fraction) Div(g Fraction) (Fraction, bool) {\n\tif g.IsZero() {\n\t\treturn Fraction{}, false\n\t}\n\tn, ok1 := mulOK(f.num, g.Den())\n\td, ok2 := mulOK(f.Den(), g.num)\n\tif !ok1 || !ok2 {\n\t\treturn Fraction{}, false\n\t}\n\tout, err := New(n, d)\n\treturn out, err == nil\n}\n\n// Neg returns -f.\nfunc (f Fraction) Neg() Fraction { return Fraction{-f.num, f.Den()} }\n\n// Cmp returns -1, 0 or +1 as f is less than, equal to, or greater than g.\n// Compares by cross-multiplication, so it is exact — no decimal conversion.\nfunc (f Fraction) Cmp(g Fraction) int {\n\ta, ok1 := mulOK(f.num, g.Den())\n\tb, ok2 := mulOK(g.num, f.Den())\n\tif !ok1 || !ok2 {\n\t\t// fall back to a lossy comparison only when exact would overflow\n\t\tfa := float64(f.num) / float64(f.Den())\n\t\tfb := float64(g.num) / float64(g.Den())\n\t\tswitch {\n\t\tcase fa \u003c fb:\n\t\t\treturn -1\n\t\tcase fa \u003e fb:\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}\n\tswitch {\n\tcase a \u003c b:\n\t\treturn -1\n\tcase a \u003e b:\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// Equal reports exact equality.\nfunc (f Fraction) Equal(g Fraction) bool { return f.Cmp(g) == 0 }\n\n// String renders \"p/q\", or just \"p\" when the denominator is 1.\nfunc (f Fraction) String() string {\n\tif f.Den() == 1 {\n\t\treturn strconv.FormatInt(f.num, 10)\n\t}\n\treturn strconv.FormatInt(f.num, 10) + \"/\" + strconv.FormatInt(f.Den(), 10)\n}\n\n// Decimal renders f with exactly places digits after the point, truncated\n// toward zero. THIS is where exactness ends — 1/3 cannot be written in decimal,\n// so the caller chooses how much to lose and when.\nfunc Decimal(f Fraction, places int) string {\n\tif places \u003c 0 {\n\t\tplaces = 0\n\t}\n\tn, d := f.num, f.Den()\n\tneg := n \u003c 0\n\tif neg {\n\t\tn = -n\n\t}\n\twhole := n / d\n\trem := n % d\n\tvar b strings.Builder\n\tif neg \u0026\u0026 (whole != 0 || rem != 0) {\n\t\tb.WriteByte('-')\n\t}\n\tb.WriteString(strconv.FormatInt(whole, 10))\n\tif places == 0 {\n\t\treturn b.String()\n\t}\n\tb.WriteByte('.')\n\tfor i := 0; i \u003c places; i++ {\n\t\trem *= 10\n\t\tb.WriteString(strconv.FormatInt(rem/d, 10))\n\t\trem %= d\n\t}\n\treturn b.String()\n}\n"},{"name":"fraction_test.gno","body":"package fraction\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc mk(t *testing.T, n, d int64) Fraction {\n\tt.Helper()\n\tf, err := New(n, d)\n\tuassert.NoError(t, err)\n\treturn f\n}\n\nfunc TestNewReduces(t *testing.T) {\n\tuassert.Equal(t, \"1/2\", mk(t, 2, 4).String())\n\tuassert.Equal(t, \"2\", mk(t, 6, 3).String())\n\tuassert.Equal(t, \"0\", mk(t, 0, 5).String())\n}\n\n// The sign always lives in the numerator, so -1/2 and 1/-2 are the same value.\nfunc TestSignNormalised(t *testing.T) {\n\ta := mk(t, 1, -2)\n\tuassert.Equal(t, \"-1/2\", a.String())\n\tuassert.True(t, a.Equal(mk(t, -1, 2)))\n\tuassert.True(t, mk(t, -2, -4).Equal(mk(t, 1, 2)))\n}\n\nfunc TestZeroDenominator(t *testing.T) {\n\t_, err := New(1, 0)\n\tuassert.ErrorIs(t, err, ErrZeroDenominator)\n}\n\n// The headline: exact arithmetic where floats would drift.\nfunc TestExactThirds(t *testing.T) {\n\tthird := mk(t, 1, 3)\n\tsum, ok := third.Add(third)\n\tuassert.True(t, ok)\n\tsum, ok = sum.Add(third)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"1\", sum.String()) // exactly 1, not 0.9999…\n}\n\nfunc TestArithmetic(t *testing.T) {\n\ta, b := mk(t, 1, 2), mk(t, 1, 3)\n\ts, _ := a.Add(b)\n\tuassert.Equal(t, \"5/6\", s.String())\n\td, _ := a.Sub(b)\n\tuassert.Equal(t, \"1/6\", d.String())\n\tm, _ := a.Mul(b)\n\tuassert.Equal(t, \"1/6\", m.String())\n\tq, _ := a.Div(b)\n\tuassert.Equal(t, \"3/2\", q.String())\n\tuassert.Equal(t, \"-1/2\", a.Neg().String())\n}\n\nfunc TestDivByZero(t *testing.T) {\n\t_, ok := mk(t, 1, 2).Div(Zero())\n\tuassert.False(t, ok)\n}\n\n// Overflow must be reported, never silently wrapped into a wrong answer.\nfunc TestOverflowReported(t *testing.T) {\n\tbig := Fraction{num: 1 \u003c\u003c 62, den: 3}\n\t_, ok := big.Mul(Fraction{num: 1 \u003c\u003c 62, den: 5})\n\tuassert.False(t, ok)\n\t_, ok2 := big.Add(Fraction{num: 1 \u003c\u003c 62, den: 7})\n\tuassert.False(t, ok2)\n}\n\n// Comparison is exact: cross-multiplication, never a decimal detour.\nfunc TestCmp(t *testing.T) {\n\tuassert.Equal(t, -1, mk(t, 1, 3).Cmp(mk(t, 1, 2)))\n\tuassert.Equal(t, 1, mk(t, 2, 3).Cmp(mk(t, 1, 2)))\n\tuassert.Equal(t, 0, mk(t, 2, 4).Cmp(mk(t, 1, 2)))\n\t// 1/3 vs 33333/100000 — a decimal comparison at 5 places would call these equal\n\tuassert.Equal(t, 1, mk(t, 1, 3).Cmp(mk(t, 33333, 100000)))\n}\n\nfunc TestDecimal(t *testing.T) {\n\tuassert.Equal(t, \"0.333\", Decimal(mk(t, 1, 3), 3))\n\tuassert.Equal(t, \"0.5\", Decimal(mk(t, 1, 2), 1))\n\tuassert.Equal(t, \"1\", Decimal(mk(t, 3, 2), 0)) // truncates toward zero\n\tuassert.Equal(t, \"-0.333\", Decimal(mk(t, -1, 3), 3))\n\tuassert.Equal(t, \"2.000\", Decimal(Int(2), 3))\n\tuassert.Equal(t, \"0\", Decimal(Zero(), 0))\n}\n\n// The zero value must behave as 0/1 rather than dividing by zero.\nfunc TestZeroValueUsable(t *testing.T) {\n\tvar f Fraction\n\tuassert.Equal(t, int64(1), f.Den())\n\tuassert.True(t, f.IsZero())\n\tuassert.Equal(t, \"0\", f.String())\n\ts, ok := f.Add(Int(1))\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"1\", s.String())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/fraction/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"heap","path":"gno.land/p/moul/x/daily/heap/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/heap/v0`\n\n**Binary heap / priority queue** — `New`, `NewMax`, `Push`, `Pop`, `Peek`,\n`Drain`, `Clone`, `Len`, `IsEmpty`, `IsMax`, `MaxItems`.\n\n```go\nimport \"gno.land/p/moul/x/daily/heap/v0\"\n\nh := heap.New()          // min-heap; NewMax() for max\nh.Push(\"pay invoice\", 1)\nh.Push(\"clear cache\", 9)\nh.Peek()                 // \"pay invoice\", 1, true — does not remove\nh.Drain()                // [\"pay invoice\" \"clear cache\"]\n```\n\nGo's `container/heap` makes you implement five methods and hands back an\ninterface. This is the concrete structure instead: an implicit binary heap in a\nslice, `Push`/`Pop` in O(log n), `Peek` in O(1).\n\n**The ordering is total.** Equal priorities pop **oldest-first**, and that\ntiebreak does *not* invert in a max-heap — only the priority comparison does.\nWithout it, ties would fall back on whatever order the backing slice happened to\nhold, and two nodes could pop the same queue differently: a consensus bug, not a\ncosmetic one.\n\n`MaxItems` (4096) bounds growth; a full heap refuses new items rather than\ngrowing without limit.\n\n**Live demo:** [`r/moul/x/daily/heapdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/heapdemo)\n· render it at [`/r/moul/x/daily/heapdemo/v0`](https://gno.land/r/moul/x/daily/heapdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/heap/v0\"\ngno = \"0.9\"\n"},{"name":"heap.gno","body":"// Package heap is a binary min-heap / priority queue over string items with\n// integer priorities, as a pure, reusable package.\n//\n// Go's container/heap makes the caller implement five methods and hands back an\n// interface; that indirection buys generality this chain does not need and\n// costs gas it does. This is the concrete data structure instead: an implicit\n// binary heap in a slice, Push/Pop in O(log n), Peek in O(1).\n//\n// Ordering is TOTAL and deterministic. Equal priorities are broken by insertion\n// sequence, so two heaps fed the same items in the same order always pop the\n// same sequence — a heap that reordered ties by allocation address would make a\n// Render vary between nodes, which is a consensus bug rather than a cosmetic\n// one.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/heapdemo](/r/moul/x/daily/heapdemo/v0).\npackage heap\n\n// MaxItems bounds the heap so gas stays predictable.\nconst MaxItems = 4096\n\ntype item struct {\n\tvalue    string\n\tpriority int\n\tseq      int // insertion sequence, breaks priority ties\n}\n\n// Heap is a binary min-heap: the lowest priority pops first.\ntype Heap struct {\n\titems []item\n\tnext  int // monotonic insertion counter\n\tmax   bool\n}\n\n// New returns an empty min-heap (lowest priority pops first).\nfunc New() *Heap { return \u0026Heap{} }\n\n// NewMax returns an empty max-heap (highest priority pops first). Ties are\n// still broken by insertion order, oldest first.\nfunc NewMax() *Heap { return \u0026Heap{max: true} }\n\n// Len returns the number of items.\nfunc (h *Heap) Len() int { return len(h.items) }\n\n// IsEmpty reports whether the heap holds nothing.\nfunc (h *Heap) IsEmpty() bool { return len(h.items) == 0 }\n\n// IsMax reports whether this is a max-heap.\nfunc (h *Heap) IsMax() bool { return h.max }\n\n// less reports whether a should pop before b.\nfunc (h *Heap) less(a, b item) bool {\n\tif a.priority != b.priority {\n\t\tif h.max {\n\t\t\treturn a.priority \u003e b.priority\n\t\t}\n\t\treturn a.priority \u003c b.priority\n\t}\n\t// Total order: equal priorities pop oldest-first, in BOTH heap kinds.\n\treturn a.seq \u003c b.seq\n}\n\n// Push adds value with the given priority. Returns false when the heap is full.\nfunc (h *Heap) Push(value string, priority int) bool {\n\tif len(h.items) \u003e= MaxItems {\n\t\treturn false\n\t}\n\th.items = append(h.items, item{value: value, priority: priority, seq: h.next})\n\th.next++\n\th.up(len(h.items) - 1)\n\treturn true\n}\n\n// Peek returns the item that would pop next, without removing it.\nfunc (h *Heap) Peek() (value string, priority int, ok bool) {\n\tif len(h.items) == 0 {\n\t\treturn \"\", 0, false\n\t}\n\treturn h.items[0].value, h.items[0].priority, true\n}\n\n// Pop removes and returns the next item.\nfunc (h *Heap) Pop() (value string, priority int, ok bool) {\n\tif len(h.items) == 0 {\n\t\treturn \"\", 0, false\n\t}\n\ttop := h.items[0]\n\tlast := len(h.items) - 1\n\th.items[0] = h.items[last]\n\th.items = h.items[:last]\n\tif len(h.items) \u003e 0 {\n\t\th.down(0)\n\t}\n\treturn top.value, top.priority, true\n}\n\n// Drain pops everything, returning values in pop order. The heap ends empty.\nfunc (h *Heap) Drain() []string {\n\tout := make([]string, 0, len(h.items))\n\tfor {\n\t\tv, _, ok := h.Pop()\n\t\tif !ok {\n\t\t\treturn out\n\t\t}\n\t\tout = append(out, v)\n\t}\n}\n\n// Clone returns an independent copy.\nfunc (h *Heap) Clone() *Heap {\n\tcp := \u0026Heap{items: make([]item, len(h.items)), next: h.next, max: h.max}\n\tcopy(cp.items, h.items)\n\treturn cp\n}\n\nfunc (h *Heap) up(i int) {\n\tfor i \u003e 0 {\n\t\tparent := (i - 1) / 2\n\t\tif !h.less(h.items[i], h.items[parent]) {\n\t\t\treturn\n\t\t}\n\t\th.items[i], h.items[parent] = h.items[parent], h.items[i]\n\t\ti = parent\n\t}\n}\n\nfunc (h *Heap) down(i int) {\n\tn := len(h.items)\n\tfor {\n\t\tleft := 2*i + 1\n\t\tif left \u003e= n {\n\t\t\treturn\n\t\t}\n\t\tbest := left\n\t\tif right := left + 1; right \u003c n \u0026\u0026 h.less(h.items[right], h.items[left]) {\n\t\t\tbest = right\n\t\t}\n\t\tif !h.less(h.items[best], h.items[i]) {\n\t\t\treturn\n\t\t}\n\t\th.items[i], h.items[best] = h.items[best], h.items[i]\n\t\ti = best\n\t}\n}\n"},{"name":"heap_test.gno","body":"package heap\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestEmpty(t *testing.T) {\n\th := New()\n\tuassert.Equal(t, 0, h.Len())\n\tuassert.True(t, h.IsEmpty(), \"a new heap is empty\")\n\n\t_, _, ok := h.Peek()\n\tuassert.False(t, ok, \"peek on empty returns not-ok\")\n\t_, _, ok = h.Pop()\n\tuassert.False(t, ok, \"pop on empty returns not-ok\")\n}\n\nfunc TestMinOrder(t *testing.T) {\n\th := New()\n\tfor _, c := range []struct {\n\t\tv string\n\t\tp int\n\t}{{\"c\", 3}, {\"a\", 1}, {\"d\", 4}, {\"b\", 2}} {\n\t\tuassert.True(t, h.Push(c.v, c.p), \"push should succeed\")\n\t}\n\tuassert.Equal(t, 4, h.Len())\n\n\tv, p, ok := h.Peek()\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"a\", v)\n\tuassert.Equal(t, 1, p)\n\tuassert.Equal(t, 4, h.Len(), \"peek must not remove\")\n\n\tuassert.Equal(t, \"a,b,c,d\", join(h.Drain()))\n\tuassert.True(t, h.IsEmpty(), \"drain empties the heap\")\n}\n\nfunc TestMaxOrder(t *testing.T) {\n\th := NewMax()\n\tuassert.True(t, h.IsMax(), \"NewMax builds a max-heap\")\n\tfor _, c := range []struct {\n\t\tv string\n\t\tp int\n\t}{{\"c\", 3}, {\"a\", 1}, {\"d\", 4}, {\"b\", 2}} {\n\t\th.Push(c.v, c.p)\n\t}\n\tuassert.Equal(t, \"d,c,b,a\", join(h.Drain()))\n}\n\n// TestTiesBreakByInsertionOrder is the determinism guarantee: equal priorities\n// pop oldest-first, so the same input always yields the same output.\nfunc TestTiesBreakByInsertionOrder(t *testing.T) {\n\th := New()\n\th.Push(\"first\", 5)\n\th.Push(\"second\", 5)\n\th.Push(\"third\", 5)\n\tuassert.Equal(t, \"first,second,third\", join(h.Drain()))\n}\n\n// TestTiesBreakOldestFirstInMaxHeap pins that the tiebreak does NOT invert with\n// the heap kind — only the priority comparison does.\nfunc TestTiesBreakOldestFirstInMaxHeap(t *testing.T) {\n\th := NewMax()\n\th.Push(\"first\", 5)\n\th.Push(\"second\", 5)\n\th.Push(\"third\", 5)\n\tuassert.Equal(t, \"first,second,third\", join(h.Drain()))\n}\n\n// TestDeterministicAcrossEqualInput feeds two heaps identically and requires\n// identical output — the property a Render depends on.\nfunc TestDeterministicAcrossEqualInput(t *testing.T) {\n\tbuild := func() *Heap {\n\t\th := New()\n\t\tfor i := 0; i \u003c 50; i++ {\n\t\t\th.Push(\"v\"+strconv.Itoa(i), i%7)\n\t\t}\n\t\treturn h\n\t}\n\tuassert.Equal(t, join(build().Drain()), join(build().Drain()))\n}\n\nfunc TestInterleavedPushPop(t *testing.T) {\n\th := New()\n\th.Push(\"b\", 2)\n\th.Push(\"d\", 4)\n\n\tv, _, _ := h.Pop()\n\tuassert.Equal(t, \"b\", v)\n\n\th.Push(\"a\", 1)\n\th.Push(\"c\", 3)\n\n\tuassert.Equal(t, \"a,c,d\", join(h.Drain()))\n}\n\nfunc TestNegativeAndZeroPriorities(t *testing.T) {\n\th := New()\n\th.Push(\"zero\", 0)\n\th.Push(\"neg\", -10)\n\th.Push(\"pos\", 10)\n\tuassert.Equal(t, \"neg,zero,pos\", join(h.Drain()))\n}\n\nfunc TestDuplicateValues(t *testing.T) {\n\th := New()\n\th.Push(\"same\", 2)\n\th.Push(\"same\", 1)\n\t// Duplicate values are independent entries, ordered by priority.\n\tuassert.Equal(t, 2, h.Len())\n\tuassert.Equal(t, \"same,same\", join(h.Drain()))\n}\n\nfunc TestClone(t *testing.T) {\n\th := New()\n\th.Push(\"a\", 1)\n\th.Push(\"b\", 2)\n\n\tcp := h.Clone()\n\tcp.Pop()\n\n\tuassert.Equal(t, 2, h.Len(), \"clone must not share storage\")\n\tuassert.Equal(t, 1, cp.Len())\n\tuassert.Equal(t, \"a,b\", join(h.Drain()))\n}\n\nfunc TestCloneKeepsKind(t *testing.T) {\n\tuassert.True(t, NewMax().Clone().IsMax(), \"clone of a max-heap is a max-heap\")\n\tuassert.False(t, New().Clone().IsMax(), \"clone of a min-heap is a min-heap\")\n}\n\nfunc TestMaxItems(t *testing.T) {\n\th := New()\n\tfor i := 0; i \u003c MaxItems; i++ {\n\t\tuassert.True(t, h.Push(\"v\", i), \"should accept up to MaxItems\")\n\t}\n\tuassert.Equal(t, MaxItems, h.Len())\n\tuassert.False(t, h.Push(\"overflow\", 0), \"a full heap refuses new items\")\n\tuassert.Equal(t, MaxItems, h.Len(), \"a refused push must not grow the heap\")\n}\n\n// TestHeapPropertyHolds drains a pseudo-random load and checks the sequence is\n// non-decreasing — the invariant, independent of the insertion pattern.\nfunc TestHeapPropertyHolds(t *testing.T) {\n\th := New()\n\tx := 7\n\tfor i := 0; i \u003c 200; i++ {\n\t\tx = (x*31 + 17) % 101 // deterministic spread, no rand\n\t\th.Push(\"v\"+strconv.Itoa(i), x)\n\t}\n\n\tprev := -1\n\tfor {\n\t\t_, p, ok := h.Pop()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tuassert.True(t, p \u003e= prev, \"pop order must be non-decreasing\")\n\t\tprev = p\n\t}\n}\n\nfunc join(ss []string) string {\n\tout := \"\"\n\tfor i, s := range ss {\n\t\tif i \u003e 0 {\n\t\t\tout += \",\"\n\t\t}\n\t\tout += s\n\t}\n\treturn out\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"hexdump","path":"gno.land/p/moul/x/daily/hexdump/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/hexdump/v0`\n\n**Classic `xxd -C` byte dump** — `Dump`, `DumpString`, `Line`, `Offset`, `Hex`,\n`ASCII`, `Printable`, `MaxBytes`, `BytesPerLine`.\n\n```go\nimport \"gno.land/p/moul/x/daily/hexdump/v0\"\n\nout, n := hexdump.DumpString(\"café\")\n// 00000000  63 61 66 c3 a9                                    |caf..|\n// n == 5 — \"é\" is two bytes\n```\n\nThe familiar layout: 8-digit hex offset, 16 bytes as hex in two 8-byte groups,\nthen the ASCII view between pipes with non-printables as `.`. **Short final lines\nare padded** so the ASCII gutter never shifts — that alignment is the whole point\nof the format, and it has its own test asserting the gutter lands in the same\ncolumn on a full and a partial line.\n\nUseful on chain for the same reason it is useful off it: when a value is not what\nyou expected, the bytes tell you why. Trailing whitespace, stray NULs, UTF-8 that\nis not what it claims — all invisible in a rendered string and obvious in a dump.\n\n`Dump` returns the number of bytes rendered alongside the text, so truncation at\n`MaxBytes` (4096) is reported rather than silent.\n\n**Live demo:** [`r/moul/x/daily/hexdumpdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/hexdumpdemo)\n· render it at [`/r/moul/x/daily/hexdumpdemo/v0`](https://gno.land/r/moul/x/daily/hexdumpdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/hexdump/v0\"\ngno = \"0.9\"\n"},{"name":"hexdump.gno","body":"// Package hexdump renders bytes in the classic xxd/hexdump -C layout, as a\n// pure, reusable package.\n//\n// The format is the familiar one: an 8-digit hex offset, then 16 bytes as hex\n// in two 8-byte groups separated by an extra space, then the same bytes as\n// ASCII between pipes with non-printables shown as \".\". Short final lines are\n// padded so the ASCII column stays aligned — the whole point of the layout.\n//\n// Useful on chain for exactly the reason it is useful off it: when a value is\n// not what you expected, the bytes tell you why. Encoding bugs, stray NULs,\n// UTF-8 that is not what it claims, trailing whitespace — all invisible in a\n// rendered string and obvious in a dump.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/hexdumpdemo](/r/moul/x/daily/hexdumpdemo/v0).\npackage hexdump\n\nimport \"strings\"\n\n// MaxBytes bounds a dump so gas stays predictable. Input beyond this is\n// truncated and reported by Dump's second return value.\nconst MaxBytes = 4096\n\n// BytesPerLine is the classic 16.\nconst BytesPerLine = 16\n\nconst hexDigits = \"0123456789abcdef\"\n\n// Dump renders b in the xxd -C layout. It returns the dump and the number of\n// bytes rendered, which is less than len(b) when the input exceeds MaxBytes.\nfunc Dump(b []byte) (string, int) {\n\tn := len(b)\n\tif n \u003e MaxBytes {\n\t\tn = MaxBytes\n\t}\n\tif n == 0 {\n\t\treturn \"\", 0\n\t}\n\n\tvar sb strings.Builder\n\tfor off := 0; off \u003c n; off += BytesPerLine {\n\t\tend := off + BytesPerLine\n\t\tif end \u003e n {\n\t\t\tend = n\n\t\t}\n\t\tsb.WriteString(Line(off, b[off:end]))\n\t\tsb.WriteString(\"\\n\")\n\t}\n\treturn sb.String(), n\n}\n\n// DumpString is Dump over a string's bytes.\nfunc DumpString(s string) (string, int) { return Dump([]byte(s)) }\n\n// Line renders one line: offset, hex columns, ASCII gutter. chunk must hold at\n// most BytesPerLine bytes; a shorter chunk is padded so columns stay aligned.\nfunc Line(offset int, chunk []byte) string {\n\tvar sb strings.Builder\n\tsb.WriteString(Offset(offset))\n\tsb.WriteString(\"  \")\n\n\tfor i := 0; i \u003c BytesPerLine; i++ {\n\t\tif i == BytesPerLine/2 {\n\t\t\tsb.WriteString(\" \") // the classic gap between the two 8-byte groups\n\t\t}\n\t\tif i \u003c len(chunk) {\n\t\t\tsb.WriteString(Hex(chunk[i]))\n\t\t} else {\n\t\t\tsb.WriteString(\"  \") // pad so the ASCII gutter never shifts\n\t\t}\n\t\tsb.WriteString(\" \")\n\t}\n\n\tsb.WriteString(\" |\")\n\tsb.WriteString(ASCII(chunk))\n\tsb.WriteString(\"|\")\n\treturn sb.String()\n}\n\n// Offset formats an 8-digit lowercase hex offset.\nfunc Offset(n int) string {\n\tif n \u003c 0 {\n\t\tn = 0\n\t}\n\tout := make([]byte, 8)\n\tfor i := 7; i \u003e= 0; i-- {\n\t\tout[i] = hexDigits[n\u00260xf]\n\t\tn \u003e\u003e= 4\n\t}\n\treturn string(out)\n}\n\n// Hex formats one byte as two lowercase hex digits.\nfunc Hex(b byte) string {\n\treturn string([]byte{hexDigits[b\u003e\u003e4], hexDigits[b\u00260xf]})\n}\n\n// ASCII renders the printable-ASCII view of chunk: bytes outside 0x20..0x7e\n// become \".\". It is NOT padded — Line handles alignment.\nfunc ASCII(chunk []byte) string {\n\tout := make([]byte, len(chunk))\n\tfor i, c := range chunk {\n\t\tif c \u003e= 0x20 \u0026\u0026 c \u003c= 0x7e {\n\t\t\tout[i] = c\n\t\t} else {\n\t\t\tout[i] = '.'\n\t\t}\n\t}\n\treturn string(out)\n}\n\n// Printable reports whether c renders as itself rather than as \".\".\nfunc Printable(c byte) bool { return c \u003e= 0x20 \u0026\u0026 c \u003c= 0x7e }\n"},{"name":"hexdump_test.gno","body":"package hexdump\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestOffset(t *testing.T) {\n\tcases := []struct {\n\t\tin   int\n\t\twant string\n\t}{\n\t\t{0, \"00000000\"},\n\t\t{1, \"00000001\"},\n\t\t{15, \"0000000f\"},\n\t\t{16, \"00000010\"},\n\t\t{255, \"000000ff\"},\n\t\t{4096, \"00001000\"},\n\t\t{-5, \"00000000\"}, // clamped\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, Offset(c.in))\n\t}\n}\n\nfunc TestHex(t *testing.T) {\n\tuassert.Equal(t, \"00\", Hex(0))\n\tuassert.Equal(t, \"0f\", Hex(15))\n\tuassert.Equal(t, \"10\", Hex(16))\n\tuassert.Equal(t, \"ff\", Hex(255))\n\tuassert.Equal(t, \"41\", Hex('A'))\n}\n\nfunc TestPrintable(t *testing.T) {\n\tuassert.False(t, Printable(0x00), \"NUL is not printable\")\n\tuassert.False(t, Printable(0x1f), \"0x1f is below the printable range\")\n\tuassert.True(t, Printable(0x20), \"space is printable\")\n\tuassert.True(t, Printable('A'))\n\tuassert.True(t, Printable(0x7e), \"~ is the last printable\")\n\tuassert.False(t, Printable(0x7f), \"DEL is not printable\")\n\tuassert.False(t, Printable(0xff))\n}\n\nfunc TestASCII(t *testing.T) {\n\tuassert.Equal(t, \"ABC\", ASCII([]byte(\"ABC\")))\n\tuassert.Equal(t, \"...\", ASCII([]byte{0x00, 0x01, 0x7f}))\n\tuassert.Equal(t, \"a.b\", ASCII([]byte{'a', 0x00, 'b'}))\n\tuassert.Equal(t, \"\", ASCII(nil))\n}\n\n// TestLineFullWidth pins the exact classic layout, including the extra space\n// between the two 8-byte groups.\nfunc TestLineFullWidth(t *testing.T) {\n\tuassert.Equal(t,\n\t\t\"00000000  30 31 32 33 34 35 36 37  38 39 61 62 63 64 65 66  |0123456789abcdef|\",\n\t\tLine(0, []byte(\"0123456789abcdef\")))\n}\n\n// TestLineShortChunkStaysAligned is the reason the padding exists: a partial\n// final line must not shift the ASCII gutter.\nfunc TestLineShortChunkStaysAligned(t *testing.T) {\n\tfull := Line(0, []byte(\"0123456789abcdef\"))\n\tshort := Line(16, []byte(\"hi\"))\n\n\tuassert.Equal(t,\n\t\t\"00000010  68 69                                             |hi|\",\n\t\tshort)\n\tuassert.Equal(t, strings.Index(full, \"|\"), strings.Index(short, \"|\"),\n\t\t\"the ASCII gutter must start at the same column on a short line\")\n}\n\nfunc TestLineEmptyChunk(t *testing.T) {\n\t// All padding, empty gutter — still aligned.\n\tl := Line(0, nil)\n\tuassert.True(t, strings.HasSuffix(l, \"||\"), \"empty chunk renders an empty gutter\")\n\tuassert.Equal(t, strings.Index(Line(0, []byte(\"x\")), \"|\"), strings.Index(l, \"|\"))\n}\n\nfunc TestDumpMultiLine(t *testing.T) {\n\tout, n := DumpString(\"0123456789abcdefhi\")\n\tuassert.Equal(t, 18, n)\n\tuassert.Equal(t,\n\t\t\"00000000  30 31 32 33 34 35 36 37  38 39 61 62 63 64 65 66  |0123456789abcdef|\\n\"+\n\t\t\t\"00000010  68 69                                             |hi|\\n\",\n\t\tout)\n}\n\nfunc TestDumpEmpty(t *testing.T) {\n\tout, n := Dump(nil)\n\tuassert.Equal(t, \"\", out)\n\tuassert.Equal(t, 0, n)\n}\n\nfunc TestDumpNonPrintable(t *testing.T) {\n\tout, n := Dump([]byte{0x00, 0x0a, 0x41})\n\tuassert.Equal(t, 3, n)\n\tuassert.Equal(t, \"00000000  00 0a 41                                          |..A|\\n\", out)\n}\n\n// TestDumpTruncates pins the bound and the honest byte count.\nfunc TestDumpTruncates(t *testing.T) {\n\t_, n := DumpString(strings.Repeat(\"x\", MaxBytes+100))\n\tuassert.Equal(t, MaxBytes, n, \"input beyond MaxBytes is truncated\")\n\n\t_, n = DumpString(strings.Repeat(\"x\", MaxBytes))\n\tuassert.Equal(t, MaxBytes, n, \"exactly MaxBytes is not truncated\")\n}\n\nfunc TestDumpLineCount(t *testing.T) {\n\tout, _ := DumpString(strings.Repeat(\"x\", 33))\n\tuassert.Equal(t, 3, strings.Count(out, \"\\n\"), \"33 bytes is 3 lines (16+16+1)\")\n}\n\n// TestDumpRevealsInvisibleDifferences is the practical point of the package.\nfunc TestDumpRevealsInvisibleDifferences(t *testing.T) {\n\ta, _ := DumpString(\"hi\")\n\tb, _ := DumpString(\"hi \")\n\tuassert.False(t, a == b, \"a trailing space is invisible rendered, obvious in a dump\")\n\n\t// \"é\" is two bytes, not one.\n\tout, n := DumpString(\"é\")\n\tuassert.Equal(t, 2, n)\n\tuassert.True(t, strings.Contains(out, \"c3 a9\"), \"UTF-8 shows its real bytes\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"humanize","path":"gno.land/p/moul/x/daily/humanize/v1","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/humanize/v1`\n\n**Human-facing number formatting** — `Bytes`, `Comma`, `Ordinal`, `Plural`,\n`Blocks`, `Truncate`.\n\n```go\nimport \"gno.land/p/moul/x/daily/humanize/v1\"\n\nhumanize.Bytes(1536)        // \"1.5 KiB\"\nhumanize.Comma(1234567)     // \"1,234,567\"\nhumanize.Ordinal(12)        // \"12th\"  — not \"12nd\"\nhumanize.Plural(2, \"mouse\", \"mice\")  // \"2 mice\"\nhumanize.Blocks(1234)       // \"~1,200 blocks\"\nhumanize.Truncate(\"ééé\", 2) // \"é…\"\n```\n\n**v1 fixes `Comma` at the int64 minimum.** `v0` negated in `int64`, and `-n` on\n`math.MinInt64` is `math.MinInt64`, so `FormatInt` emitted its own sign and the\n`neg` branch prepended a second: `Comma(math.MinInt64)` returned\n`--9,223,372,036,854,775,808`. The magnitude now goes through `uint64`.\n`v0` stays resolvable for its existing importers.\n\n**Integer-only, on purpose.** No floats anywhere: a rendered value that differed\nbetween nodes would be a consensus bug, so the single decimal place in `Bytes`\ncomes from scaling by 10 and taking a remainder.\n\n**Durations are in blocks, never seconds.** There is no wall clock on chain, so\n\"about 2 hours\" is a lie dressed as precision. `Blocks` says `~1,200 blocks` and\nlets the caller decide what that means on their chain — and rounds deliberately,\nbecause false precision is worse than none.\n\n`Ordinal` handles the teens (`11th`/`12th`/`13th`, not `11st`/`12nd`/`13rd`) —\nthe case naive implementations get wrong. `Truncate` counts **runes**, so\nmulti-byte text is never sliced mid-character.\n\n**Live demo:** [`r/moul/x/daily/humanizedemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/humanizedemo)\n· render it at [`/r/moul/x/daily/humanizedemo/v0`](https://gno.land/r/moul/x/daily/humanizedemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/humanize/v1\"\ngno = \"0.9\"\n"},{"name":"humanize.gno","body":"// Package humanize formats numbers for people rather than machines, as a pure,\n// reusable package: byte sizes, thousands separators, ordinals, pluralisation\n// and block-height \"durations\".\n//\n// Everything is integer-only. There are no floats here on purpose: gno has no\n// float determinism guarantees worth relying on for consensus output, and a\n// rendered value that differs between nodes would be a consensus bug. One\n// decimal place is produced by scaling by 10 and taking a remainder.\n//\n// Durations are expressed in BLOCKS, not seconds. There is no wall clock on\n// chain, so \"about 2 hours\" is a lie dressed as precision; this package says\n// \"~1200 blocks\" and lets the caller decide what that means on their chain.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/humanizedemo](/r/moul/x/daily/humanizedemo/v0).\npackage humanize\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Bytes renders n bytes with SI-ish binary units and one decimal place.\n// Negative input is rendered with a leading minus rather than rejected.\nfunc Bytes(n int64) string {\n\tneg := n \u003c 0\n\tif neg {\n\t\tn = -n\n\t}\n\tconst unit = 1024\n\tif n \u003c unit {\n\t\ts := strconv.FormatInt(n, 10) + \" B\"\n\t\tif neg {\n\t\t\treturn \"-\" + s\n\t\t}\n\t\treturn s\n\t}\n\tunits := []string{\"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\", \"EiB\"}\n\tdiv := int64(unit)\n\ti := 0\n\tfor n/div \u003e= unit \u0026\u0026 i \u003c len(units)-1 {\n\t\tdiv *= unit\n\t\ti++\n\t}\n\t// one decimal place without floats: scale by 10, then split\n\tscaled := n * 10 / div\n\twhole, freq := scaled/10, scaled%10\n\ts := strconv.FormatInt(whole, 10)\n\tif freq != 0 {\n\t\ts += \".\" + strconv.FormatInt(freq, 10)\n\t}\n\ts += \" \" + units[i]\n\tif neg {\n\t\treturn \"-\" + s\n\t}\n\treturn s\n}\n\n// Comma inserts thousands separators: 1234567 -\u003e \"1,234,567\".\nfunc Comma(n int64) string {\n\t// The magnitude goes through uint64 rather than -n: -n on math.MinInt64 is\n\t// math.MinInt64 again, so FormatInt emits its own sign and the neg branch\n\t// below prepended a second one. v0 returned \"--9,223,372,036,854,775,808\".\n\tneg := n \u003c 0\n\tvar m uint64\n\tif neg {\n\t\tm = uint64(-(n+1)) + 1\n\t} else {\n\t\tm = uint64(n)\n\t}\n\ts := strconv.FormatUint(m, 10)\n\tvar b strings.Builder\n\tfor i, c := range []byte(s) {\n\t\tif i \u003e 0 \u0026\u0026 (len(s)-i)%3 == 0 {\n\t\t\tb.WriteByte(',')\n\t\t}\n\t\tb.WriteByte(c)\n\t}\n\tif neg {\n\t\treturn \"-\" + b.String()\n\t}\n\treturn b.String()\n}\n\n// Ordinal renders 1 -\u003e \"1st\", 2 -\u003e \"2nd\", 11 -\u003e \"11th\".\n//\n// The teens are the trap: 11/12/13 take \"th\" despite ending in 1/2/3, so the\n// 11–13 case must be checked before the last digit.\nfunc Ordinal(n int64) string {\n\ts := strconv.FormatInt(n, 10)\n\ta := n\n\tif a \u003c 0 {\n\t\ta = -a\n\t}\n\tif a%100 \u003e= 11 \u0026\u0026 a%100 \u003c= 13 {\n\t\treturn s + \"th\"\n\t}\n\tswitch a % 10 {\n\tcase 1:\n\t\treturn s + \"st\"\n\tcase 2:\n\t\treturn s + \"nd\"\n\tcase 3:\n\t\treturn s + \"rd\"\n\t}\n\treturn s + \"th\"\n}\n\n// Plural returns \"1 block\" / \"2 blocks\", using plural when given, else word+\"s\".\nfunc Plural(n int64, word, plural string) string {\n\tif n == 1 || n == -1 {\n\t\treturn strconv.FormatInt(n, 10) + \" \" + word\n\t}\n\tif plural == \"\" {\n\t\tplural = word + \"s\"\n\t}\n\treturn strconv.FormatInt(n, 10) + \" \" + plural\n}\n\n// Blocks renders a block count at a coarse magnitude — deliberately vague,\n// because a block count is not a wall-clock duration.\nfunc Blocks(n int64) string {\n\tswitch {\n\tcase n \u003c 0:\n\t\treturn \"in the past\"\n\tcase n == 0:\n\t\treturn \"now\"\n\tcase n \u003c 10:\n\t\treturn Plural(n, \"block\", \"\")\n\tcase n \u003c 1000:\n\t\treturn \"~\" + Comma(n/10*10) + \" blocks\"\n\tdefault:\n\t\treturn \"~\" + Comma(n/100*100) + \" blocks\"\n\t}\n}\n\n// Truncate shortens s to at most max runes, appending \"…\" when it cut.\n// Counts RUNES, not bytes, so a multi-byte string is not sliced mid-character.\nfunc Truncate(s string, max int) string {\n\tif max \u003c= 0 {\n\t\treturn \"\"\n\t}\n\tr := []rune(s)\n\tif len(r) \u003c= max {\n\t\treturn s\n\t}\n\tif max == 1 {\n\t\treturn \"…\"\n\t}\n\treturn string(r[:max-1]) + \"…\"\n}\n"},{"name":"humanize_test.gno","body":"package humanize\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestBytes(t *testing.T) {\n\tcases := []struct {\n\t\tin   int64\n\t\twant string\n\t}{\n\t\t{0, \"0 B\"},\n\t\t{999, \"999 B\"},\n\t\t{1023, \"1023 B\"},\n\t\t{1024, \"1 KiB\"},\n\t\t{1536, \"1.5 KiB\"},\n\t\t{1048576, \"1 MiB\"},\n\t\t{1572864, \"1.5 MiB\"},\n\t\t{1073741824, \"1 GiB\"},\n\t\t{-1536, \"-1.5 KiB\"},\n\t\t{-10, \"-10 B\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, Bytes(c.in))\n\t}\n}\n\nfunc TestComma(t *testing.T) {\n\tcases := []struct {\n\t\tin   int64\n\t\twant string\n\t}{\n\t\t{0, \"0\"}, {1, \"1\"}, {999, \"999\"}, {1000, \"1,000\"},\n\t\t{1234567, \"1,234,567\"}, {-1234567, \"-1,234,567\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, Comma(c.in))\n\t}\n}\n\n// The teens are the trap: 11/12/13 take \"th\" despite ending in 1/2/3.\nfunc TestOrdinalTeens(t *testing.T) {\n\tcases := []struct {\n\t\tin   int64\n\t\twant string\n\t}{\n\t\t{1, \"1st\"}, {2, \"2nd\"}, {3, \"3rd\"}, {4, \"4th\"},\n\t\t{11, \"11th\"}, {12, \"12th\"}, {13, \"13th\"},\n\t\t{21, \"21st\"}, {22, \"22nd\"}, {23, \"23rd\"},\n\t\t{111, \"111th\"}, {112, \"112th\"}, {113, \"113th\"},\n\t\t{101, \"101st\"}, {0, \"0th\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, Ordinal(c.in))\n\t}\n}\n\nfunc TestPlural(t *testing.T) {\n\tuassert.Equal(t, \"1 block\", Plural(1, \"block\", \"\"))\n\tuassert.Equal(t, \"2 blocks\", Plural(2, \"block\", \"\"))\n\tuassert.Equal(t, \"0 blocks\", Plural(0, \"block\", \"\"))\n\tuassert.Equal(t, \"2 mice\", Plural(2, \"mouse\", \"mice\"))\n\tuassert.Equal(t, \"-1 block\", Plural(-1, \"block\", \"\"))\n}\n\nfunc TestBlocks(t *testing.T) {\n\tuassert.Equal(t, \"now\", Blocks(0))\n\tuassert.Equal(t, \"1 block\", Blocks(1))\n\tuassert.Equal(t, \"9 blocks\", Blocks(9))\n\tuassert.Equal(t, \"~10 blocks\", Blocks(15))\n\tuassert.Equal(t, \"~1,200 blocks\", Blocks(1234))\n\tuassert.Equal(t, \"in the past\", Blocks(-5))\n}\n\n// Truncate counts runes, so multi-byte text is never cut mid-character.\nfunc TestTruncateCountsRunes(t *testing.T) {\n\tuassert.Equal(t, \"hello\", Truncate(\"hello\", 10))\n\tuassert.Equal(t, \"hell…\", Truncate(\"hello!\", 5))\n\tuassert.Equal(t, \"…\", Truncate(\"hello\", 1))\n\tuassert.Equal(t, \"\", Truncate(\"hello\", 0))\n\tuassert.Equal(t, \"éé\", Truncate(\"éé\", 2))\n\tuassert.Equal(t, \"é…\", Truncate(\"ééé\", 2)) // not sliced mid-rune\n}\n\n// TestCommaSurvivesTheInt64Minimum pins the defect v0 shipped. -n on\n// math.MinInt64 is math.MinInt64, so FormatInt emitted its own sign and the\n// neg branch prepended a second: v0 returned\n// \"--9,223,372,036,854,775,808\". Break the mag split and this goes red.\nfunc TestCommaSurvivesTheInt64Minimum(t *testing.T) {\n\tconst minInt64 = -9223372036854775808\n\tuassert.Equal(t, \"-9,223,372,036,854,775,808\", Comma(minInt64))\n\tuassert.Equal(t, \"9,223,372,036,854,775,807\", Comma(9223372036854775807))\n}\n\n// TestCommaNeverDoublesTheSign is the invariant behind it, stated so a future\n// rewrite cannot reintroduce the shape without failing.\nfunc TestCommaNeverDoublesTheSign(t *testing.T) {\n\tconst minInt64 = -9223372036854775808\n\tfor _, n := range []int64{0, 1, -1, 999, -1000, 1234567, -1234567, minInt64} {\n\t\ts := Comma(n)\n\t\tif strings.HasPrefix(s, \"--\") || strings.Contains(s, \"-,\") {\n\t\t\tt.Errorf(\"Comma(%d) = %q\", n, s)\n\t\t}\n\t\tif (n \u003c 0) != strings.HasPrefix(s, \"-\") {\n\t\t\tt.Errorf(\"Comma(%d) = %q, sign disagrees with the input\", n, s)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"kmp","path":"gno.land/p/moul/x/daily/kmp/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/kmp/v0`\n\n**Knuth–Morris–Pratt substring search** — `Index`, `Contains`, `FindAll`,\n`Count`, `Table`, `MaxPattern`.\n\n```go\nimport \"gno.land/p/moul/x/daily/kmp/v0\"\n\nkmp.Index(\"mississippi\", \"issi\")   // 1\nkmp.FindAll(\"mississippi\", \"issi\") // [1 4] — overlapping\nkmp.Count(\"aaaa\", \"aa\")            // 3\nkmp.Table(\"ababaa\")                // [0 0 1 2 3 1]\n```\n\nThe naive scan re-compares characters it already matched, so `\"aaaaaaab\"` inside\n`\"aaaaaaaaaaaaaaab\"` costs O(n·m). KMP precomputes a failure table and slides the\npattern without ever moving the text cursor backwards: **O(n+m), with no bad\ncase**. On chain that matters — a pathological input is an attack, not bad luck.\n\nTwo things worth knowing, each with a test:\n\n- **`FindAll` reports overlapping matches.** `FindAll(\"aaaa\", \"aa\")` is\n  `[0 1 2]`, not `[0 2]` — the honest reading of \"every occurrence\". A caller\n  wanting disjoint matches can filter; one wanting overlap could not recover it.\n- **Offsets are BYTE offsets**, not runes. gno strings are UTF-8, so `Index(\"éx\",\n  \"x\")` is `2`. That matches `strings.Index`, and it is the right unit for\n  slicing.\n\n`Index` is pinned against `strings.Index` across a spread of inputs: same\ncontract, different algorithm.\n\n**Live demo:** [`r/moul/x/daily/kmpdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/kmpdemo)\n· render it at [`/r/moul/x/daily/kmpdemo/v0`](https://gno.land/r/moul/x/daily/kmpdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/kmp/v0\"\ngno = \"0.9\"\n"},{"name":"kmp.gno","body":"// Package kmp implements Knuth–Morris–Pratt substring search as a pure,\n// reusable package.\n//\n// The naive scan re-compares characters it has already matched, so a hostile\n// input like \"aaaaaaab\" in \"aaaaaaaaaaaaaaab\" costs O(n*m). KMP precomputes a\n// failure table — for every prefix, the length of the longest proper prefix\n// that is also a suffix — and uses it to slide the pattern without ever moving\n// the text cursor backwards. That makes the scan O(n+m) with O(m) extra memory,\n// and it never degrades: worst case equals best case, which is what makes it\n// safe to run on chain where a pathological input is an attack, not bad luck.\n//\n// Operates on BYTES, not runes: gno strings are UTF-8, so a match index is a\n// byte offset. That is the right unit for slicing and it keeps the failure\n// table cheap; callers doing rune arithmetic must convert.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/kmpdemo](/r/moul/x/daily/kmpdemo/v0).\npackage kmp\n\n// MaxPattern bounds the failure table so gas stays predictable.\nconst MaxPattern = 1024\n\n// Table returns the KMP failure table for pattern: table[i] is the length of\n// the longest proper prefix of pattern[:i+1] that is also a suffix of it.\n// Returns nil when the pattern is empty or longer than MaxPattern.\nfunc Table(pattern string) []int {\n\tm := len(pattern)\n\tif m == 0 || m \u003e MaxPattern {\n\t\treturn nil\n\t}\n\tt := make([]int, m)\n\tk := 0\n\tfor i := 1; i \u003c m; i++ {\n\t\tfor k \u003e 0 \u0026\u0026 pattern[i] != pattern[k] {\n\t\t\tk = t[k-1]\n\t\t}\n\t\tif pattern[i] == pattern[k] {\n\t\t\tk++\n\t\t}\n\t\tt[i] = k\n\t}\n\treturn t\n}\n\n// Index returns the byte offset of the first occurrence of pattern in text, or\n// -1 if absent. An empty pattern matches at 0, matching strings.Index.\nfunc Index(text, pattern string) int {\n\tall := findAll(text, pattern, 1)\n\tif len(all) == 0 {\n\t\treturn -1\n\t}\n\treturn all[0]\n}\n\n// Contains reports whether pattern occurs in text.\nfunc Contains(text, pattern string) bool { return Index(text, pattern) \u003e= 0 }\n\n// FindAll returns the byte offsets of every match, including OVERLAPPING ones:\n// FindAll(\"aaaa\", \"aa\") is [0 1 2], not [0 2]. Overlap is the honest reading of\n// \"every occurrence\" and the caller can always filter.\nfunc FindAll(text, pattern string) []int { return findAll(text, pattern, 0) }\n\n// Count returns how many times pattern occurs, counting overlaps.\nfunc Count(text, pattern string) int { return len(FindAll(text, pattern)) }\n\n// findAll collects match offsets, stopping after limit matches (0 = no limit).\nfunc findAll(text, pattern string, limit int) []int {\n\tm := len(pattern)\n\tif m == 0 {\n\t\treturn []int{0}\n\t}\n\tif m \u003e len(text) || m \u003e MaxPattern {\n\t\treturn nil\n\t}\n\tt := Table(pattern)\n\tif t == nil {\n\t\treturn nil\n\t}\n\n\tvar out []int\n\tk := 0\n\tfor i := 0; i \u003c len(text); i++ {\n\t\tfor k \u003e 0 \u0026\u0026 text[i] != pattern[k] {\n\t\t\tk = t[k-1]\n\t\t}\n\t\tif text[i] == pattern[k] {\n\t\t\tk++\n\t\t}\n\t\tif k == m {\n\t\t\tout = append(out, i-m+1)\n\t\t\tif limit \u003e 0 \u0026\u0026 len(out) \u003e= limit {\n\t\t\t\treturn out\n\t\t\t}\n\t\t\tk = t[k-1] // allow overlapping matches\n\t\t}\n\t}\n\treturn out\n}\n"},{"name":"kmp_test.gno","body":"package kmp\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestTable(t *testing.T) {\n\tcases := []struct {\n\t\tpattern string\n\t\twant    []int\n\t}{\n\t\t{\"abcabca\", []int{0, 0, 0, 1, 2, 3, 4}},\n\t\t{\"aaaa\", []int{0, 1, 2, 3}},\n\t\t{\"abcd\", []int{0, 0, 0, 0}},\n\t\t{\"ababaa\", []int{0, 0, 1, 2, 3, 1}},\n\t\t{\"a\", []int{0}},\n\t}\n\tfor _, c := range cases {\n\t\tgot := Table(c.pattern)\n\t\tuassert.Equal(t, len(c.want), len(got), \"table length for \"+c.pattern)\n\t\tfor i := range c.want {\n\t\t\tuassert.Equal(t, c.want[i], got[i], \"table[\"+itoa(i)+\"] for \"+c.pattern)\n\t\t}\n\t}\n}\n\nfunc TestTableRejects(t *testing.T) {\n\tuassert.True(t, Table(\"\") == nil, \"empty pattern has no table\")\n\tuassert.True(t, Table(strings.Repeat(\"x\", MaxPattern+1)) == nil, \"oversized pattern refused\")\n\tuassert.False(t, Table(strings.Repeat(\"x\", MaxPattern)) == nil, \"exactly MaxPattern is allowed\")\n}\n\n// TestIndexMatchesStdlib pins KMP against strings.Index across a spread of\n// inputs — same contract, different algorithm.\nfunc TestIndexMatchesStdlib(t *testing.T) {\n\ttexts := []string{\"\", \"a\", \"hello world\", \"aaaaaaab\", \"abcabcabd\", \"mississippi\"}\n\tpats := []string{\"\", \"a\", \"b\", \"ab\", \"abd\", \"issi\", \"world\", \"zzz\", \"mississippi\"}\n\tfor _, text := range texts {\n\t\tfor _, p := range pats {\n\t\t\tuassert.Equal(t, strings.Index(text, p), Index(text, p),\n\t\t\t\t\"Index(\"+text+\",\"+p+\") should match strings.Index\")\n\t\t}\n\t}\n}\n\nfunc TestContains(t *testing.T) {\n\tuassert.True(t, Contains(\"hello world\", \"lo w\"))\n\tuassert.False(t, Contains(\"hello world\", \"lo  w\"))\n\tuassert.True(t, Contains(\"anything\", \"\"), \"empty pattern is always contained\")\n}\n\n// TestFindAllOverlapping is the documented divergence from a naive scan.\nfunc TestFindAllOverlapping(t *testing.T) {\n\tgot := FindAll(\"aaaa\", \"aa\")\n\tuassert.Equal(t, 3, len(got), \"overlapping matches are all reported\")\n\tuassert.Equal(t, 0, got[0])\n\tuassert.Equal(t, 1, got[1])\n\tuassert.Equal(t, 2, got[2])\n}\n\nfunc TestFindAllDisjoint(t *testing.T) {\n\tgot := FindAll(\"abcabcabc\", \"abc\")\n\tuassert.Equal(t, 3, len(got))\n\tuassert.Equal(t, 0, got[0])\n\tuassert.Equal(t, 3, got[1])\n\tuassert.Equal(t, 6, got[2])\n}\n\nfunc TestFindAllAbsent(t *testing.T) {\n\tuassert.Equal(t, 0, len(FindAll(\"abc\", \"xyz\")))\n\tuassert.Equal(t, 0, len(FindAll(\"ab\", \"abcdef\")), \"pattern longer than text\")\n}\n\nfunc TestCount(t *testing.T) {\n\tuassert.Equal(t, 4, Count(\"aaaaa\", \"aa\"))\n\tuassert.Equal(t, 2, Count(\"mississippi\", \"issi\"))\n\tuassert.Equal(t, 0, Count(\"abc\", \"d\"))\n}\n\n// TestPathologicalInput is the reason to use KMP: the naive scan is quadratic\n// here, KMP is linear. Correctness is what we assert; the cost is the point.\nfunc TestPathologicalInput(t *testing.T) {\n\ttext := strings.Repeat(\"a\", 2000) + \"b\"\n\tpattern := strings.Repeat(\"a\", 200) + \"b\"\n\tuassert.Equal(t, 1800, Index(text, pattern))\n\tuassert.Equal(t, 1, Count(text, pattern))\n}\n\n// TestBytesNotRunes documents that offsets are byte offsets.\nfunc TestBytesNotRunes(t *testing.T) {\n\t// \"é\" is two bytes in UTF-8, so \"x\" sits at byte 2, not rune 1.\n\tuassert.Equal(t, 2, Index(\"éx\", \"x\"))\n\tuassert.Equal(t, strings.Index(\"éx\", \"x\"), Index(\"éx\", \"x\"))\n}\n\nfunc TestMatchAtStartAndEnd(t *testing.T) {\n\tuassert.Equal(t, 0, Index(\"abcdef\", \"abc\"))\n\tuassert.Equal(t, 3, Index(\"abcdef\", \"def\"))\n\tuassert.Equal(t, 0, Index(\"abc\", \"abc\"), \"whole-string match\")\n}\n\nfunc itoa(i int) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\ts := \"\"\n\tfor i \u003e 0 {\n\t\ts = string(rune('0'+i%10)) + s\n\t\ti /= 10\n\t}\n\treturn s\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"levenshtein","path":"gno.land/p/moul/x/daily/levenshtein/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/levenshtein/v0`\n\n**Levenshtein edit-distance** — `Distance`, `Matrix`, `Similarity`.\n\nThe minimum number of single-character insertions, deletions, or substitutions\nto turn one string into another. Fully rune-aware, pure (deterministic), two-row\nDP (`O(min(len))` memory). Ported from Go's `agext/levenshtein`.\n\n```go\nimport \"gno.land/p/moul/x/daily/levenshtein/v0\"\n\nd := levenshtein.Distance(\"kitten\", \"sitting\")   // 3\nm := levenshtein.Matrix(\"kitten\", \"sitting\")     // full (7 x 8) DP matrix\ns := levenshtein.Similarity(\"kitten\", \"sitting\") // 57 (a 0..100 percentage)\n```\n\n**Live demo:** [`r/moul/x/daily/levenshteindemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/levenshteindemo)\n· render it at [`/r/moul/x/daily/levenshteindemo/v0`](https://gno.land/r/moul/x/daily/levenshteindemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/levenshtein/v0\"\ngno = \"0.9\"\n"},{"name":"levenshtein.gno","body":"// Package levenshtein ports the classic Levenshtein edit-distance algorithm\n// (as found in Go libraries like agext/levenshtein) to gno — as a reusable pure\n// package.\n//\n// The core is the textbook dynamic-programming matrix: the minimum number of\n// single-character insertions, deletions, or substitutions to turn string a\n// into string b. It is fully rune-aware and pure (deterministic), so it runs\n// happily on-chain.\n//\n// A live demo of this package (an interactive distance calculator with the DP\n// table) is at [r/moul/x/daily/levenshteindemo](/r/moul/x/daily/levenshteindemo/v0).\npackage levenshtein\n\n// Distance returns the Levenshtein edit distance between a and b.\n//\n// It counts single-rune insertions, deletions, and substitutions and works on\n// runes (not bytes), so multi-byte UTF-8 input is handled correctly. The\n// classic two-row DP is used, so memory is O(min(len)) and time is O(len(a)*len(b)).\nfunc Distance(a, b string) int {\n\tra := []rune(a)\n\trb := []rune(b)\n\n\t// Keep the shorter slice as the inner (column) dimension.\n\tif len(ra) \u003c len(rb) {\n\t\tra, rb = rb, ra\n\t}\n\tn := len(ra)\n\tm := len(rb)\n\tif m == 0 {\n\t\treturn n\n\t}\n\n\t// prev[j] = distance between ra[:i] and rb[:j].\n\tprev := make([]int, m+1)\n\tfor j := 0; j \u003c= m; j++ {\n\t\tprev[j] = j\n\t}\n\tcurr := make([]int, m+1)\n\n\tfor i := 1; i \u003c= n; i++ {\n\t\tcurr[0] = i\n\t\tfor j := 1; j \u003c= m; j++ {\n\t\t\tcost := 1\n\t\t\tif ra[i-1] == rb[j-1] {\n\t\t\t\tcost = 0\n\t\t\t}\n\t\t\tcurr[j] = min3(\n\t\t\t\tcurr[j-1]+1,    // insertion\n\t\t\t\tprev[j]+1,      // deletion\n\t\t\t\tprev[j-1]+cost, // substitution / match\n\t\t\t)\n\t\t}\n\t\tprev, curr = curr, prev\n\t}\n\treturn prev[m]\n}\n\n// Matrix returns the full (len(a)+1) x (len(b)+1) DP matrix used by Distance.\n// matrix[i][j] is the edit distance between the first i runes of a and the\n// first j runes of b. The bottom-right cell equals Distance(a, b).\nfunc Matrix(a, b string) [][]int {\n\tra := []rune(a)\n\trb := []rune(b)\n\tn := len(ra)\n\tm := len(rb)\n\n\td := make([][]int, n+1)\n\tfor i := 0; i \u003c= n; i++ {\n\t\td[i] = make([]int, m+1)\n\t\td[i][0] = i\n\t}\n\tfor j := 0; j \u003c= m; j++ {\n\t\td[0][j] = j\n\t}\n\tfor i := 1; i \u003c= n; i++ {\n\t\tfor j := 1; j \u003c= m; j++ {\n\t\t\tcost := 1\n\t\t\tif ra[i-1] == rb[j-1] {\n\t\t\t\tcost = 0\n\t\t\t}\n\t\t\td[i][j] = min3(d[i][j-1]+1, d[i-1][j]+1, d[i-1][j-1]+cost)\n\t\t}\n\t}\n\treturn d\n}\n\n// Similarity returns a 0..100 percentage of how similar a and b are, defined as\n// (1 - distance/maxLen) * 100 rounded to the nearest integer. Two empty strings\n// are considered 100% similar.\nfunc Similarity(a, b string) int {\n\tla := len([]rune(a))\n\tlb := len([]rune(b))\n\tmaxLen := la\n\tif lb \u003e maxLen {\n\t\tmaxLen = lb\n\t}\n\tif maxLen == 0 {\n\t\treturn 100\n\t}\n\tdist := Distance(a, b)\n\t// Rounded percentage of matching characters.\n\treturn ((maxLen-dist)*100 + maxLen/2) / maxLen\n}\n\nfunc min3(a, b, c int) int {\n\tm := a\n\tif b \u003c m {\n\t\tm = b\n\t}\n\tif c \u003c m {\n\t\tm = c\n\t}\n\treturn m\n}\n"},{"name":"levenshtein_test.gno","body":"package levenshtein\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestDistance(t *testing.T) {\n\tcases := []struct {\n\t\ta, b string\n\t\twant int\n\t}{\n\t\t{\"\", \"\", 0},\n\t\t{\"abc\", \"\", 3},\n\t\t{\"\", \"abc\", 3},\n\t\t{\"abc\", \"abc\", 0},\n\t\t{\"kitten\", \"sitting\", 3},\n\t\t{\"flaw\", \"lawn\", 2},\n\t\t{\"sunday\", \"saturday\", 3},\n\t\t{\"gno\", \"gnoland\", 4},\n\t\t{\"book\", \"back\", 2},\n\t\t// Rune-aware: each accented char is one edit, not several bytes.\n\t\t{\"café\", \"cafe\", 1},\n\t\t{\"héllo\", \"hello\", 1},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := Distance(tc.a, tc.b)\n\t\tuassert.Equal(t, tc.want, got)\n\t\t// Symmetry: distance is the same in both directions.\n\t\tuassert.Equal(t, tc.want, Distance(tc.b, tc.a))\n\t}\n}\n\nfunc TestSimilarity(t *testing.T) {\n\t// Identical strings.\n\tuassert.Equal(t, 100, Similarity(\"hello\", \"hello\"))\n\t// Both empty.\n\tuassert.Equal(t, 100, Similarity(\"\", \"\"))\n\t// Completely different lengths / content.\n\tuassert.Equal(t, 0, Similarity(\"abc\", \"xyz\"))\n\t// kitten/sitting: max len 7, distance 3 -\u003e round((4/7)*100) = 57.\n\tuassert.Equal(t, 57, Similarity(\"kitten\", \"sitting\"))\n}\n\nfunc TestMatrix(t *testing.T) {\n\td := Matrix(\"kitten\", \"sitting\")\n\t// Dimensions: (6+1) x (7+1).\n\tuassert.Equal(t, 7, len(d))\n\tuassert.Equal(t, 8, len(d[0]))\n\t// First row and column are the identity ramps.\n\tfor j := 0; j \u003c= 7; j++ {\n\t\tuassert.Equal(t, j, d[0][j])\n\t}\n\tfor i := 0; i \u003c= 6; i++ {\n\t\tuassert.Equal(t, i, d[i][0])\n\t}\n\t// Bottom-right cell equals Distance.\n\tuassert.Equal(t, Distance(\"kitten\", \"sitting\"), d[6][7])\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"luhn","path":"gno.land/p/moul/x/daily/luhn/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/luhn/v0`\n\n**Luhn mod-10 checksum** — `Valid`, `CheckDigit`, `Append`, `MaxLen`.\n\nThe check behind credit-card numbers, IMEIs and many national ID schemes\n(Hans Peter Luhn, 1954). Spaces and hyphens are ignored, so the formatting a\nhuman would paste works as-is.\n\n```go\nimport \"gno.land/p/moul/x/daily/luhn/v0\"\n\nluhn.Valid(\"4539 1488 0343 6467\")   // true  — separators ignored\nluhn.Valid(\"4539148803436468\")      // false — one digit off\nluhn.CheckDigit(\"7992739871\")       // 3, true\nluhn.Append(\"7992739871\")           // \"79927398713\", true\n```\n\n\u003e ⚠️ **A typo check, not a security check.** Luhn catches every single-digit\n\u003e error and nearly every transposition of adjacent digits, but anyone can\n\u003e compute a valid number in a second, and validity says nothing about whether\n\u003e the identifier exists. Never use it to authorize anything on-chain.\n\n`MaxLen` (64) bounds an input so validation gas stays predictable. Note that a\nstring of zeros is technically Luhn-valid and is accepted — reject it in the\ncaller if your domain needs to.\n\n**Live demo:** [`r/moul/x/daily/luhndemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/luhndemo)\n· render it at [`/r/moul/x/daily/luhndemo/v0`](https://gno.land/r/moul/x/daily/luhndemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/luhn/v0\"\ngno = \"0.9\"\n"},{"name":"luhn.gno","body":"// Package luhn implements the Luhn mod-10 checksum (Hans Peter Luhn, 1954) as\n// a pure, reusable package: the check used by credit-card numbers, IMEIs and\n// many national ID schemes to catch typos and single-digit transpositions.\n//\n// It is a *checksum*, not a security primitive: it detects every single-digit\n// error and almost every adjacent transposition, but it is trivial to forge and\n// says nothing about whether an identifier actually exists. Never use it to\n// authorize anything on-chain.\n//\n// No clocks, no randomness, no chain imports — same input, same output.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/luhndemo](/r/moul/x/daily/luhndemo/v0).\npackage luhn\n\nimport (\n\t\"strings\"\n)\n\n// MaxLen bounds an input so validation gas stays predictable.\nconst MaxLen = 64\n\n// Valid reports whether s carries a correct Luhn check digit.\n//\n// Spaces and hyphens are ignored, so \"4539 1488 0343 6467\" and\n// \"4539-1488-0343-6467\" both work. Any other non-digit makes it false, as does\n// an empty/1-digit input or one longer than MaxLen. A string of all zeros is\n// technically Luhn-valid and is accepted — reject it in the caller if your\n// domain needs to.\nfunc Valid(s string) bool {\n\tdigits, ok := clean(s)\n\tif !ok || len(digits) \u003c 2 {\n\t\treturn false\n\t}\n\treturn sum(digits)%10 == 0\n}\n\n// CheckDigit returns the digit that must be appended to payload to make the\n// whole string Luhn-valid, and whether the payload was usable.\nfunc CheckDigit(payload string) (int, bool) {\n\tdigits, ok := clean(payload)\n\tif !ok || len(digits) == 0 {\n\t\treturn 0, false\n\t}\n\t// The check digit sits in the \"doubled\" position of the final number, so\n\t// compute the sum as if a 0 had already been appended.\n\ttotal := sum(append(digits, 0))\n\treturn (10 - total%10) % 10, true\n}\n\n// Append returns payload with its Luhn check digit appended (digits only,\n// separators stripped), and whether the payload was usable.\nfunc Append(payload string) (string, bool) {\n\td, ok := CheckDigit(payload)\n\tif !ok {\n\t\treturn \"\", false\n\t}\n\tdigits, _ := clean(payload)\n\tvar b strings.Builder\n\tfor _, x := range digits {\n\t\tb.WriteByte(byte('0' + x))\n\t}\n\tb.WriteByte(byte('0' + d))\n\treturn b.String(), true\n}\n\n// clean turns s into its digit values, ignoring spaces and hyphens. ok is false\n// if any other character appears or the input exceeds MaxLen.\nfunc clean(s string) ([]int, bool) {\n\tif len(s) \u003e MaxLen {\n\t\treturn nil, false\n\t}\n\tdigits := make([]int, 0, len(s))\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\t\tdigits = append(digits, int(c-'0'))\n\t\tcase c == ' ' || c == '-':\n\t\t\t// separator: ignore\n\t\tdefault:\n\t\t\treturn nil, false\n\t\t}\n\t}\n\treturn digits, true\n}\n\n// sum computes the Luhn total: walking right to left, every second digit is\n// doubled, and a double of 10 or more has 9 subtracted (equivalent to adding\n// its two decimal digits).\nfunc sum(digits []int) int {\n\ttotal := 0\n\tdouble := false\n\tfor i := len(digits) - 1; i \u003e= 0; i-- {\n\t\td := digits[i]\n\t\tif double {\n\t\t\td *= 2\n\t\t\tif d \u003e 9 {\n\t\t\t\td -= 9\n\t\t\t}\n\t\t}\n\t\ttotal += d\n\t\tdouble = !double\n\t}\n\treturn total\n}\n"},{"name":"luhn_test.gno","body":"package luhn\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestValid(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"known-good test card\", \"4539148803436467\", true},\n\t\t{\"spaces ignored\", \"4539 1488 0343 6467\", true},\n\t\t{\"hyphens ignored\", \"4539-1488-0343-6467\", true},\n\t\t{\"single digit flipped\", \"4539148803436468\", false},\n\t\t{\"adjacent transposition\", \"4539148803436647\", false},\n\t\t{\"classic 79927398713\", \"79927398713\", true},\n\t\t{\"classic off by one\", \"79927398710\", false},\n\t\t{\"all zeros is valid\", \"00\", true},\n\t\t{\"letters rejected\", \"4539abc8803436467\", false},\n\t\t{\"empty rejected\", \"\", false},\n\t\t{\"one digit rejected\", \"7\", false},\n\t\t{\"separators only rejected\", \" - \", false},\n\t\t{\"over MaxLen rejected\", strings.Repeat(\"0\", MaxLen+1), false},\n\t}\n\tfor _, c := range cases {\n\t\tt.Run(c.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, c.want, Valid(c.in))\n\t\t})\n\t}\n}\n\nfunc TestCheckDigit(t *testing.T) {\n\tcases := []struct {\n\t\tpayload string\n\t\twant    int\n\t}{\n\t\t{\"7992739871\", 3},\n\t\t{\"453914880343646\", 7},\n\t\t{\"0\", 0},\n\t}\n\tfor _, c := range cases {\n\t\tgot, ok := CheckDigit(c.payload)\n\t\tuassert.True(t, ok)\n\t\tuassert.Equal(t, c.want, got)\n\t}\n}\n\nfunc TestCheckDigitRejectsBadInput(t *testing.T) {\n\tfor _, in := range []string{\"\", \"abc\", \" - \"} {\n\t\t_, ok := CheckDigit(in)\n\t\tuassert.False(t, ok)\n\t}\n}\n\n// Append must produce something Valid accepts — the round-trip property.\nfunc TestAppendRoundTrip(t *testing.T) {\n\tpayloads := []string{\"7992739871\", \"453914880343646\", \"1\", \"123456789012345\"}\n\tfor _, p := range payloads {\n\t\tgot, ok := Append(p)\n\t\tuassert.True(t, ok)\n\t\tuassert.True(t, Valid(got))\n\t\tuassert.Equal(t, len(p)+1, len(got))\n\t}\n}\n\n// Append strips separators, so a spaced payload yields the same digits.\nfunc TestAppendStripsSeparators(t *testing.T) {\n\ta, ok := Append(\"4539 1488 0343 646\")\n\tuassert.True(t, ok)\n\tb, ok2 := Append(\"453914880343646\")\n\tuassert.True(t, ok2)\n\tuassert.Equal(t, b, a)\n\tuassert.Equal(t, \"4539148803436467\", a)\n}\n\n// Every single-digit change to a valid number must be caught: that is the\n// guarantee Luhn actually makes.\nfunc TestDetectsEverySingleDigitError(t *testing.T) {\n\tconst base = \"4539148803436467\"\n\tuassert.True(t, Valid(base))\n\tfor i := 0; i \u003c len(base); i++ {\n\t\tfor d := byte('0'); d \u003c= '9'; d++ {\n\t\t\tif d == base[i] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmutated := base[:i] + string(d) + base[i+1:]\n\t\t\tuassert.False(t, Valid(mutated))\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"markov","path":"gno.land/p/moul/x/daily/markov/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/markov/v0`\n\n**Deterministic Markov-chain text generator** — a port of Go's canonical example\n[*\"Generating arbitrary text: a Markov chain algorithm\"*](https://go.dev/doc/codewalk/markov/)\nwith `math/rand` replaced by a caller-supplied seed.\n\nA `Chain` maps every two-word *prefix* to the list of words observed to follow\nit (duplicates kept, so frequency biases the walk), storing that map in a\npersistent `avl.Tree`. `Build` folds text into the chain; `Generate` walks it\nfrom the start prefix, picking one suffix per step from a small LCG seeded by\nthe `uint64` you pass — so generation is pure and replayable, and the caller\ndecides where entropy comes from (on-chain, the block height). No chain imports,\nno ambient state.\n\n```go\nimport \"gno.land/p/moul/x/daily/markov/v0\"\n\nc := markov.New()\nc.Build(\"it was the best of times it was the worst of times\") // fold in a corpus\nwords := c.Generate(40, seed)                                  // walk it, seeded\nc.Stats()                                                      // (totalWords, prefixCount)\nc.Iterate(func(prefix string, suffixes []string) bool { ... }) // inspect the map\n```\n\n**Live demo:** [`r/moul/x/daily/markovdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/markovdemo)\n· render it at [`/r/moul/x/daily/markovdemo/v0`](https://gno.land/r/moul/x/daily/markovdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/daily/markov/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/daily/markov/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/markov/v0\"\ngno = \"0.9\"\n"},{"name":"markov.gno","body":"// Package markov is a deterministic Markov-chain text generator — a port of\n// Go's canonical example \"Generating arbitrary text: a Markov chain algorithm\"\n// (https://go.dev/doc/codewalk/markov/) with math/rand replaced by a\n// caller-supplied seed.\n//\n// It is a pure library: it imports no chain APIs and reads no ambient state.\n// A [Chain] maps every PrefixLen-word prefix to the list of words observed to\n// follow it (duplicates kept, so frequency biases the walk), storing that map\n// in a persistent avl.Tree. Build folds text into the chain; Generate walks it\n// from the start prefix, picking one suffix per step from a small LCG seeded by\n// the uint64 the caller passes — so generation is deterministic and replayable,\n// and the caller decides where entropy comes from (on-chain, the block height).\n//\n// A realm wires it up by holding a *Chain in a package-level var, calling Build\n// to grow the corpus and Generate with a height-derived seed. For a complete,\n// live example see the demo realm\n// [r/moul/x/daily/markovdemo](/r/moul/x/daily/markovdemo/v0).\npackage markov\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// PrefixLen is the number of words in a prefix. Two is the classic choice from\n// the Go codewalk: long enough to sound plausible, short enough to keep the\n// chain well-connected.\nconst PrefixLen = 2\n\n// Prefix is a sliding window of the last PrefixLen words seen. It mirrors the\n// Prefix type in the original program.\ntype Prefix []string\n\n// key joins the prefix into the string used as the chain's map key. Two empty\n// strings (the initial prefix) join to a single space \" \", which is exactly\n// the start-of-text key both Build and Generate begin from.\nfunc (p Prefix) key() string { return strings.Join(p, \" \") }\n\n// shift drops the oldest word and appends word, advancing the window by one.\nfunc (p Prefix) shift(word string) {\n\tcopy(p, p[1:])\n\tp[len(p)-1] = word\n}\n\n// suffixList is the value stored per prefix: every word observed to follow it,\n// in order (duplicates kept so frequency biases the random walk, just like the\n// original []string in the chain map).\ntype suffixList struct {\n\twords []string\n}\n\n// Chain is a Markov chain over a persistent avl.Tree. table maps prefix key -\u003e\n// *suffixList; prefix is the rolling build window so successive Build calls\n// extend one continuous corpus rather than restarting; words is the running\n// word count.\ntype Chain struct {\n\ttable  avl.Tree\n\tprefix Prefix\n\twords  int\n}\n\n// New returns an empty Chain ready to Build into.\nfunc New() *Chain {\n\treturn \u0026Chain{prefix: make(Prefix, PrefixLen)}\n}\n\n// Build tokenizes text on whitespace and folds each word into the chain,\n// recording it as a suffix of the current prefix and then shifting. It returns\n// the number of words added. This is the analogue of Chain.Build from the\n// codewalk.\nfunc (c *Chain) Build(text string) int {\n\tadded := 0\n\tfor _, w := range strings.Fields(text) {\n\t\tk := c.prefix.key()\n\t\tvar sl *suffixList\n\t\tif c.table.Has(k) {\n\t\t\tsl = c.table.Get(k).(*suffixList)\n\t\t} else {\n\t\t\tsl = \u0026suffixList{}\n\t\t}\n\t\tsl.words = append(sl.words, w)\n\t\tc.table.Set(k, sl)\n\t\tc.prefix.shift(w)\n\t\tc.words++\n\t\tadded++\n\t}\n\treturn added\n}\n\n// Generate walks the chain from the start prefix, picking one suffix per step\n// via an LCG seeded by seed, and returns up to n words. It stops early if it\n// reaches a prefix with no recorded suffixes (a dead end). Pure: the same\n// (n, seed) always yields the same words for a given chain.\nfunc (c *Chain) Generate(n int, seed uint64) []string {\n\tif n \u003c= 0 {\n\t\treturn nil\n\t}\n\tp := make(Prefix, PrefixLen)\n\trng := seed\n\tout := make([]string, 0, n)\n\tfor i := 0; i \u003c n; i++ {\n\t\tk := p.key()\n\t\tif !c.table.Has(k) {\n\t\t\tbreak\n\t\t}\n\t\tchoices := c.table.Get(k).(*suffixList).words\n\t\tif len(choices) == 0 {\n\t\t\tbreak\n\t\t}\n\t\trng = nextRand(rng)\n\t\t// use high bits of the LCG state — its low bits have short periods\n\t\tidx := int((rng \u003e\u003e 33) % uint64(len(choices)))\n\t\tnext := choices[idx]\n\t\tout = append(out, next)\n\t\tp.shift(next)\n\t}\n\treturn out\n}\n\n// Stats returns (totalWords, prefixCount) for the current chain.\nfunc (c *Chain) Stats() (int, int) {\n\treturn c.words, c.table.Size()\n}\n\n// Iterate calls fn for each prefix in ascending key order, passing the prefix\n// key and the list of words recorded to follow it. Returning true from fn stops\n// the iteration early; Iterate reports whether it was stopped that way.\nfunc (c *Chain) Iterate(fn func(prefix string, suffixes []string) bool) bool {\n\treturn c.table.Iterate(\"\", \"\", func(k string, v interface{}) bool {\n\t\treturn fn(k, v.(*suffixList).words)\n\t})\n}\n\n// nextRand is a 64-bit linear congruential generator (the PCG/Knuth\n// multiplier + increment). Deterministic and dependency-free — all the\n// entropy comes from the caller's seed.\nfunc nextRand(s uint64) uint64 {\n\treturn s*6364136223846793005 + 1442695040888963407\n}\n"},{"name":"markov_test.gno","body":"package markov\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPrefixShiftKey(t *testing.T) {\n\tp := make(Prefix, PrefixLen)\n\tuassert.Equal(t, \" \", p.key(), \"initial key is two empty words joined\")\n\n\tp.shift(\"hello\")\n\tuassert.Equal(t, \" hello\", p.key(), \"after one shift\")\n\n\tp.shift(\"world\")\n\tuassert.Equal(t, \"hello world\", p.key(), \"after two shifts window is full\")\n\n\tp.shift(\"again\")\n\tuassert.Equal(t, \"world again\", p.key(), \"oldest word drops off\")\n}\n\nfunc TestBuildCountsAndSuffixes(t *testing.T) {\n\tc := New()\n\tadded := c.Build(\"a b a b a b\")\n\tuassert.Equal(t, 6, added, \"six words tokenized\")\n\n\twords, _ := c.Stats()\n\tuassert.Equal(t, 6, words, \"word counter matches\")\n\n\t// prefixes seen: \" \"-\u003e[a], \" a\"-\u003e[b], \"a b\"-\u003e[a,a], \"b a\"-\u003e[b,b]\n\tuassert.True(t, c.table.Has(\"a b\"), \"prefix 'a b' recorded\")\n\tab := c.table.Get(\"a b\").(*suffixList)\n\tuassert.Equal(t, 2, len(ab.words), \"'a b' followed twice\")\n\tuassert.Equal(t, \"a\", ab.words[0], \"'a b' is always followed by 'a'\")\n\n\t// whitespace-only / empty adds nothing\n\tuassert.Equal(t, 0, c.Build(\"   \"), \"blank text adds no words\")\n}\n\nfunc TestGenerateDeterministicAndBounded(t *testing.T) {\n\tc := New()\n\tc.Build(\"one two three four one two three five one two six\")\n\n\ta := strings.Join(c.Generate(8, 42), \" \")\n\tb := strings.Join(c.Generate(8, 42), \" \")\n\tuassert.Equal(t, a, b, \"same seed =\u003e identical output\")\n\n\t// the walk is seed-sensitive: across a spread of seeds at least one\n\t// diverges from the seed-42 output (some seeds may coincidentally match).\n\tsensitive := false\n\tfor _, s := range []uint64{1, 7, 13, 12345, 8675309} {\n\t\tif strings.Join(c.Generate(8, s), \" \") != a {\n\t\t\tsensitive = true\n\t\t\tbreak\n\t\t}\n\t}\n\tuassert.True(t, sensitive, \"output varies with the seed\")\n\n\t// non-positive n and empty corpus both yield nothing\n\tuassert.Equal(t, 0, len(c.Generate(0, 1)), \"n\u003c=0 yields no words\")\n\tempty := New()\n\tuassert.Equal(t, 0, len(empty.Generate(10, 1)), \"empty corpus yields no words\")\n}\n\nfunc TestStatsAndIterate(t *testing.T) {\n\tc := New()\n\tc.Build(\"a b a b a b\")\n\n\twords, prefixes := c.Stats()\n\tuassert.Equal(t, 6, words, \"total words\")\n\tuassert.Equal(t, 4, prefixes, \"distinct prefixes\")\n\n\tseen := 0\n\tstopped := c.Iterate(func(prefix string, suffixes []string) bool {\n\t\tuassert.True(t, len(suffixes) \u003e 0, \"each prefix has suffixes\")\n\t\tseen++\n\t\treturn false\n\t})\n\tuassert.Equal(t, 4, seen, \"iterated over every prefix\")\n\tuassert.False(t, stopped, \"ran to completion\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"multiset","path":"gno.land/p/moul/x/daily/multiset/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/multiset/v0`\n\n**Bag / frequency counter** — `New`, `FromSlice`, `Add`, `AddN`, `Remove`,\n`RemoveN`, `RemoveAll`, `Count`, `MostCommon`, `Union`, `Intersect`, `Sum`,\n`Elements`, `Expand`, `Clone`, `MaxDistinct`.\n\n```go\nimport \"gno.land/p/moul/x/daily/multiset/v0\"\n\nm := multiset.FromSlice([]string{\"a\", \"a\", \"a\", \"b\", \"b\", \"c\"})\nm.Count(\"a\")        // 3\nm.MostCommon(2)     // [{a 3} {b 2}]\nm.Total()           // 6 occurrences\nm.Distinct()        // 3 elements\n```\n\nThe STL `multiset` and Python's `collections.Counter` in one type.\n\n**`MostCommon` has a total order:** count descending, then element ascending.\nSorting by count alone would leave ties in whatever order the backing map\nyielded — unspecified in gno, and enough to make two nodes render different\ntables from identical state. The tiebreak is not decoration.\n\nSemantics worth knowing, each with a test:\n\n- **A count reaching zero removes the element**, rather than leaving a\n  zero-count ghost that `Distinct` would still count.\n- **`RemoveN` clamps**: removing more than are present clears the element\n  instead of going negative.\n- `Union` takes the **max** of each count, `Intersect` the **min** (common\n  elements only), `Sum` adds them.\n\n`MaxDistinct` (4096) bounds the number of *distinct* elements; counts themselves\nare unbounded, so a full set still accepts more occurrences of what it holds.\n\n**Live demo:** [`r/moul/x/daily/multisetdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/multisetdemo)\n· render it at [`/r/moul/x/daily/multisetdemo/v0`](https://gno.land/r/moul/x/daily/multisetdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/multiset/v0\"\ngno = \"0.9\"\n"},{"name":"multiset.gno","body":"// Package multiset is a bag / frequency counter — a set that allows duplicates\n// and remembers how many — as a pure, reusable package.\n//\n// It is the STL multiset and Python's collections.Counter in one type: Add an\n// element several times and the count rises; the distinct elements stay sorted\n// so iteration and rendering are deterministic.\n//\n// The interesting operation is MostCommon(n), and the interesting problem with\n// it is ties. Sorting by count alone leaves elements with equal counts in\n// whatever order the underlying storage happened to yield — which, if that is a\n// built-in map, is unspecified in gno and can differ between nodes. Here the\n// order is total: count descending, then element ascending. Two multisets built\n// from the same elements always produce the same ranking.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/multisetdemo](/r/moul/x/daily/multisetdemo/v0).\npackage multiset\n\nimport \"sort\"\n\n// MaxDistinct bounds the number of DISTINCT elements so gas stays predictable.\n// Counts themselves are unbounded.\nconst MaxDistinct = 4096\n\n// MultiSet counts occurrences of string elements.\ntype MultiSet struct {\n\tcounts map[string]int\n\ttotal  int\n}\n\n// New returns an empty MultiSet.\nfunc New() *MultiSet { return \u0026MultiSet{counts: map[string]int{}} }\n\n// FromSlice builds a MultiSet from elements, counting duplicates.\nfunc FromSlice(elems []string) *MultiSet {\n\tm := New()\n\tfor _, e := range elems {\n\t\tm.Add(e)\n\t}\n\treturn m\n}\n\n// Add records one occurrence of e. Returns false when e is new and the set\n// already holds MaxDistinct distinct elements.\nfunc (m *MultiSet) Add(e string) bool { return m.AddN(e, 1) }\n\n// AddN records n occurrences of e. A non-positive n is a no-op returning true.\nfunc (m *MultiSet) AddN(e string, n int) bool {\n\tif n \u003c= 0 {\n\t\treturn true\n\t}\n\tif _, seen := m.counts[e]; !seen \u0026\u0026 len(m.counts) \u003e= MaxDistinct {\n\t\treturn false\n\t}\n\tm.counts[e] += n\n\tm.total += n\n\treturn true\n}\n\n// Count returns how many times e occurs; zero when absent.\nfunc (m *MultiSet) Count(e string) int { return m.counts[e] }\n\n// Has reports whether e occurs at least once.\nfunc (m *MultiSet) Has(e string) bool { return m.counts[e] \u003e 0 }\n\n// Remove drops one occurrence of e, deleting it entirely when the count hits\n// zero. Returns false when e was not present.\nfunc (m *MultiSet) Remove(e string) bool { return m.RemoveN(e, 1) }\n\n// RemoveN drops up to n occurrences of e. Returns false when e was absent.\n// Removing more than are present clears the element rather than going negative.\nfunc (m *MultiSet) RemoveN(e string, n int) bool {\n\thave, ok := m.counts[e]\n\tif !ok || n \u003c= 0 {\n\t\treturn false\n\t}\n\tif n \u003e= have {\n\t\tdelete(m.counts, e)\n\t\tm.total -= have\n\t\treturn true\n\t}\n\tm.counts[e] = have - n\n\tm.total -= n\n\treturn true\n}\n\n// RemoveAll drops every occurrence of e. Returns false when e was absent.\nfunc (m *MultiSet) RemoveAll(e string) bool {\n\thave, ok := m.counts[e]\n\tif !ok {\n\t\treturn false\n\t}\n\tdelete(m.counts, e)\n\tm.total -= have\n\treturn true\n}\n\n// Distinct returns the number of distinct elements.\nfunc (m *MultiSet) Distinct() int { return len(m.counts) }\n\n// Total returns the sum of every count.\nfunc (m *MultiSet) Total() int { return m.total }\n\n// IsEmpty reports whether the set holds nothing.\nfunc (m *MultiSet) IsEmpty() bool { return len(m.counts) == 0 }\n\n// Elements returns the distinct elements, sorted.\nfunc (m *MultiSet) Elements() []string {\n\tout := make([]string, 0, len(m.counts))\n\tfor e := range m.counts {\n\t\tout = append(out, e)\n\t}\n\tsort.Strings(out)\n\treturn out\n}\n\n// Expand returns every occurrence, sorted — a multiset flattened back to a\n// slice. Length equals Total.\nfunc (m *MultiSet) Expand() []string {\n\tout := make([]string, 0, m.total)\n\tfor _, e := range m.Elements() {\n\t\tfor i := 0; i \u003c m.counts[e]; i++ {\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out\n}\n\n// Entry pairs an element with its count.\ntype Entry struct {\n\tElem  string\n\tCount int\n}\n\n// byRank orders entries by count descending, then element ascending — a TOTAL\n// order, so ranking never depends on map iteration.\ntype byRank []Entry\n\nfunc (r byRank) Len() int      { return len(r) }\nfunc (r byRank) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byRank) Less(i, j int) bool {\n\tif r[i].Count != r[j].Count {\n\t\treturn r[i].Count \u003e r[j].Count\n\t}\n\treturn r[i].Elem \u003c r[j].Elem\n}\n\n// MostCommon returns the n most frequent entries, ranked by count descending\n// then element ascending. n \u003c= 0, or larger than the number of distinct\n// elements, returns them all.\nfunc (m *MultiSet) MostCommon(n int) []Entry {\n\tall := make([]Entry, 0, len(m.counts))\n\tfor e, c := range m.counts {\n\t\tall = append(all, Entry{Elem: e, Count: c})\n\t}\n\tsort.Sort(byRank(all))\n\tif n \u003c= 0 || n \u003e len(all) {\n\t\treturn all\n\t}\n\treturn all[:n]\n}\n\n// Union returns a set where each element's count is the MAXIMUM of the two —\n// the standard multiset union.\nfunc (m *MultiSet) Union(other *MultiSet) *MultiSet {\n\tout := m.Clone()\n\tfor e, c := range other.counts {\n\t\tif c \u003e out.counts[e] {\n\t\t\tout.setCount(e, c)\n\t\t}\n\t}\n\treturn out\n}\n\n// Intersect returns a set where each element's count is the MINIMUM of the two,\n// keeping only elements present in both.\nfunc (m *MultiSet) Intersect(other *MultiSet) *MultiSet {\n\tout := New()\n\tfor e, c := range m.counts {\n\t\tif oc, ok := other.counts[e]; ok {\n\t\t\tif oc \u003c c {\n\t\t\t\tc = oc\n\t\t\t}\n\t\t\tout.AddN(e, c)\n\t\t}\n\t}\n\treturn out\n}\n\n// Sum returns a set where each element's count is the SUM of the two.\nfunc (m *MultiSet) Sum(other *MultiSet) *MultiSet {\n\tout := m.Clone()\n\tfor e, c := range other.counts {\n\t\tout.AddN(e, c)\n\t}\n\treturn out\n}\n\n// Clone returns an independent copy.\nfunc (m *MultiSet) Clone() *MultiSet {\n\tout := New()\n\tfor e, c := range m.counts {\n\t\tout.counts[e] = c\n\t}\n\tout.total = m.total\n\treturn out\n}\n\n// setCount overwrites an element's count, keeping total in step.\nfunc (m *MultiSet) setCount(e string, c int) {\n\tm.total += c - m.counts[e]\n\tm.counts[e] = c\n}\n"},{"name":"multiset_test.gno","body":"package multiset\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestEmpty(t *testing.T) {\n\tm := New()\n\tuassert.True(t, m.IsEmpty())\n\tuassert.Equal(t, 0, m.Distinct())\n\tuassert.Equal(t, 0, m.Total())\n\tuassert.Equal(t, 0, m.Count(\"nope\"))\n\tuassert.False(t, m.Has(\"nope\"))\n}\n\nfunc TestAddAndCount(t *testing.T) {\n\tm := New()\n\tm.Add(\"apple\")\n\tm.Add(\"apple\")\n\tm.Add(\"pear\")\n\n\tuassert.Equal(t, 2, m.Count(\"apple\"))\n\tuassert.Equal(t, 1, m.Count(\"pear\"))\n\tuassert.Equal(t, 2, m.Distinct(), \"distinct counts elements, not occurrences\")\n\tuassert.Equal(t, 3, m.Total(), \"total counts occurrences\")\n\tuassert.True(t, m.Has(\"apple\"))\n}\n\nfunc TestAddN(t *testing.T) {\n\tm := New()\n\tuassert.True(t, m.AddN(\"x\", 5))\n\tuassert.Equal(t, 5, m.Count(\"x\"))\n\n\tuassert.True(t, m.AddN(\"x\", 0), \"adding zero is a no-op that succeeds\")\n\tuassert.True(t, m.AddN(\"x\", -3), \"adding a negative is a no-op that succeeds\")\n\tuassert.Equal(t, 5, m.Count(\"x\"), \"count unchanged by non-positive AddN\")\n\tuassert.Equal(t, 5, m.Total())\n}\n\nfunc TestFromSlice(t *testing.T) {\n\tm := FromSlice([]string{\"a\", \"b\", \"a\", \"c\", \"a\"})\n\tuassert.Equal(t, 3, m.Count(\"a\"))\n\tuassert.Equal(t, 1, m.Count(\"b\"))\n\tuassert.Equal(t, 3, m.Distinct())\n\tuassert.Equal(t, 5, m.Total())\n}\n\nfunc TestRemove(t *testing.T) {\n\tm := FromSlice([]string{\"a\", \"a\", \"a\"})\n\n\tuassert.True(t, m.Remove(\"a\"))\n\tuassert.Equal(t, 2, m.Count(\"a\"))\n\tuassert.Equal(t, 2, m.Total())\n\n\tuassert.False(t, m.Remove(\"absent\"), \"removing an absent element reports false\")\n}\n\n// TestRemoveDeletesAtZero pins that a count reaching zero drops the element\n// rather than leaving a zero-count ghost that Distinct would still count.\nfunc TestRemoveDeletesAtZero(t *testing.T) {\n\tm := New()\n\tm.Add(\"a\")\n\n\tuassert.True(t, m.Remove(\"a\"))\n\tuassert.Equal(t, 0, m.Distinct(), \"a zero count removes the element entirely\")\n\tuassert.False(t, m.Has(\"a\"))\n\tuassert.Equal(t, 0, m.Total())\n}\n\n// TestRemoveNClamps pins that over-removing clears rather than going negative.\nfunc TestRemoveNClamps(t *testing.T) {\n\tm := New()\n\tm.AddN(\"a\", 3)\n\n\tuassert.True(t, m.RemoveN(\"a\", 100))\n\tuassert.Equal(t, 0, m.Count(\"a\"))\n\tuassert.Equal(t, 0, m.Total(), \"total must not go negative\")\n\tuassert.Equal(t, 0, m.Distinct())\n}\n\nfunc TestRemoveNPartial(t *testing.T) {\n\tm := New()\n\tm.AddN(\"a\", 10)\n\tuassert.True(t, m.RemoveN(\"a\", 4))\n\tuassert.Equal(t, 6, m.Count(\"a\"))\n\tuassert.Equal(t, 6, m.Total())\n\tuassert.False(t, m.RemoveN(\"a\", 0), \"a non-positive n reports false\")\n}\n\nfunc TestRemoveAll(t *testing.T) {\n\tm := New()\n\tm.AddN(\"a\", 7)\n\tm.Add(\"b\")\n\n\tuassert.True(t, m.RemoveAll(\"a\"))\n\tuassert.Equal(t, 0, m.Count(\"a\"))\n\tuassert.Equal(t, 1, m.Total(), \"only b remains\")\n\tuassert.False(t, m.RemoveAll(\"a\"), \"already gone\")\n}\n\nfunc TestElementsSorted(t *testing.T) {\n\tm := FromSlice([]string{\"delta\", \"alpha\", \"charlie\", \"alpha\"})\n\tuassert.Equal(t, \"alpha,charlie,delta\", strings.Join(m.Elements(), \",\"))\n}\n\nfunc TestExpand(t *testing.T) {\n\tm := FromSlice([]string{\"b\", \"a\", \"b\"})\n\tuassert.Equal(t, \"a,b,b\", strings.Join(m.Expand(), \",\"))\n\tuassert.Equal(t, m.Total(), len(m.Expand()), \"Expand length equals Total\")\n}\n\nfunc TestMostCommon(t *testing.T) {\n\tm := FromSlice([]string{\"a\", \"a\", \"a\", \"b\", \"b\", \"c\"})\n\n\ttop := m.MostCommon(2)\n\tuassert.Equal(t, 2, len(top))\n\tuassert.Equal(t, \"a\", top[0].Elem)\n\tuassert.Equal(t, 3, top[0].Count)\n\tuassert.Equal(t, \"b\", top[1].Elem)\n\tuassert.Equal(t, 2, top[1].Count)\n}\n\n// TestMostCommonTiesAreAlphabetical is the determinism guarantee: equal counts\n// must not fall back on map order, which gno leaves unspecified.\nfunc TestMostCommonTiesAreAlphabetical(t *testing.T) {\n\tm := FromSlice([]string{\"zebra\", \"apple\", \"mango\"}) // all count 1\n\n\tgot := m.MostCommon(0)\n\tuassert.Equal(t, 3, len(got))\n\tuassert.Equal(t, \"apple\", got[0].Elem)\n\tuassert.Equal(t, \"mango\", got[1].Elem)\n\tuassert.Equal(t, \"zebra\", got[2].Elem)\n}\n\n// TestMostCommonIsStableAcrossBuilds is the same property from the outside:\n// build the set twice, get the same ranking.\nfunc TestMostCommonIsStableAcrossBuilds(t *testing.T) {\n\tbuild := func() *MultiSet {\n\t\tm := New()\n\t\tfor i := 0; i \u003c 60; i++ {\n\t\t\tm.Add(\"e\" + strconv.Itoa(i%9))\n\t\t}\n\t\treturn m\n\t}\n\tuassert.Equal(t, rank(build().MostCommon(0)), rank(build().MostCommon(0)))\n}\n\nfunc TestMostCommonBounds(t *testing.T) {\n\tm := FromSlice([]string{\"a\", \"b\"})\n\tuassert.Equal(t, 2, len(m.MostCommon(0)), \"n\u003c=0 returns everything\")\n\tuassert.Equal(t, 2, len(m.MostCommon(-1)), \"negative n returns everything\")\n\tuassert.Equal(t, 2, len(m.MostCommon(99)), \"n beyond distinct returns everything\")\n\tuassert.Equal(t, 1, len(m.MostCommon(1)))\n\tuassert.Equal(t, 0, len(New().MostCommon(5)), \"empty set ranks nothing\")\n}\n\nfunc TestUnionTakesMaximum(t *testing.T) {\n\ta := FromSlice([]string{\"x\", \"x\", \"y\"})\n\tb := FromSlice([]string{\"x\", \"z\", \"z\", \"z\"})\n\n\tu := a.Union(b)\n\tuassert.Equal(t, 2, u.Count(\"x\"), \"max(2,1)\")\n\tuassert.Equal(t, 1, u.Count(\"y\"), \"max(1,0)\")\n\tuassert.Equal(t, 3, u.Count(\"z\"), \"max(0,3)\")\n\tuassert.Equal(t, 6, u.Total())\n\tuassert.Equal(t, 3, a.Total(), \"operands are untouched\")\n}\n\nfunc TestIntersectTakesMinimum(t *testing.T) {\n\ta := FromSlice([]string{\"x\", \"x\", \"x\", \"y\"})\n\tb := FromSlice([]string{\"x\", \"x\", \"z\"})\n\n\ti := a.Intersect(b)\n\tuassert.Equal(t, 2, i.Count(\"x\"), \"min(3,2)\")\n\tuassert.Equal(t, 0, i.Count(\"y\"), \"absent from b\")\n\tuassert.Equal(t, 0, i.Count(\"z\"), \"absent from a\")\n\tuassert.Equal(t, 1, i.Distinct())\n\tuassert.Equal(t, 2, i.Total())\n}\n\nfunc TestSumAddsCounts(t *testing.T) {\n\ta := FromSlice([]string{\"x\", \"x\", \"y\"})\n\tb := FromSlice([]string{\"x\", \"z\"})\n\n\ts := a.Sum(b)\n\tuassert.Equal(t, 3, s.Count(\"x\"), \"2+1\")\n\tuassert.Equal(t, 1, s.Count(\"y\"))\n\tuassert.Equal(t, 1, s.Count(\"z\"))\n\tuassert.Equal(t, 5, s.Total())\n}\n\nfunc TestClone(t *testing.T) {\n\tm := FromSlice([]string{\"a\", \"a\"})\n\tcp := m.Clone()\n\tcp.Add(\"b\")\n\n\tuassert.Equal(t, 1, m.Distinct(), \"clone must not share storage\")\n\tuassert.Equal(t, 2, cp.Distinct())\n\tuassert.Equal(t, 2, m.Total())\n\tuassert.Equal(t, 3, cp.Total())\n}\n\nfunc TestMaxDistinct(t *testing.T) {\n\tm := New()\n\tfor i := 0; i \u003c MaxDistinct; i++ {\n\t\tuassert.True(t, m.Add(\"e\"+strconv.Itoa(i)), \"should accept up to MaxDistinct\")\n\t}\n\tuassert.Equal(t, MaxDistinct, m.Distinct())\n\n\tuassert.False(t, m.Add(\"overflow\"), \"a full set refuses a new distinct element\")\n\tuassert.Equal(t, MaxDistinct, m.Distinct())\n\n\t// Counts are NOT bounded: an existing element can still grow.\n\tuassert.True(t, m.AddN(\"e0\", 1000), \"existing elements still accept occurrences\")\n\tuassert.Equal(t, 1001, m.Count(\"e0\"))\n}\n\nfunc rank(es []Entry) string {\n\tparts := make([]string, len(es))\n\tfor i, e := range es {\n\t\tparts[i] = e.Elem + \":\" + strconv.Itoa(e.Count)\n\t}\n\treturn strings.Join(parts, \",\")\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"orderedmap","path":"gno.land/p/moul/x/daily/orderedmap/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/orderedmap/v0`\n\n**Map that remembers insertion order** — `New`, `Set`, `Get`, `Has`, `Delete`,\n`Keys`, `Values`, `Iterate`, `At`, `Clone`, `Len`, `MaxKeys`.\n\n```go\nimport \"gno.land/p/moul/x/daily/orderedmap/v0\"\n\no := orderedmap.New()\no.Set(\"delta\", \"4\"); o.Set(\"alpha\", \"1\")\no.Keys()             // [\"delta\" \"alpha\"] — insertion order, not sorted\no.Set(\"delta\", \"99\") // updates in place, keeps position\n```\n\n**This matters more on chain than off it.** gno map iteration order is\nunspecified, so a realm that ranges over a built-in map to build its `Render`\ncan emit a different page on every call — a **consensus bug**, not a cosmetic\none. This type gives back a deterministic order without requiring the keys to be\nsortable.\n\nSemantics worth knowing, each with a test:\n\n- **Updating keeps position.** Insertion order means *first* insertion, not last\n  write.\n- **Re-inserting after a delete goes last** — it is a new insertion.\n- `Keys` returns a copy, so a caller cannot reorder the map through it.\n\nBacked by a built-in map for O(1) `Get` plus a slice holding the order. `Delete`\nis **O(n)**: closing the gap in that slice is what preserves order, and that\ntrade is stated rather than hidden. `MaxKeys` (4096) bounds growth; a full map\nrefuses new keys but still accepts updates to existing ones.\n\n**Live demo:** [`r/moul/x/daily/orderedmapdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/orderedmapdemo)\n· render it at [`/r/moul/x/daily/orderedmapdemo/v0`](https://gno.land/r/moul/x/daily/orderedmapdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/orderedmap/v0\"\ngno = \"0.9\"\n"},{"name":"orderedmap.gno","body":"// Package orderedmap is a map that remembers the order its keys were inserted,\n// as a pure, reusable package.\n//\n// This matters more on chain than off it. gno map iteration order is\n// unspecified, so a realm that ranges over a built-in map to build its Render\n// can emit a different page on every call — which is a consensus bug, not a\n// cosmetic one. This type gives back a deterministic order without needing the\n// keys to be sortable.\n//\n// Backed by a built-in map for O(1) lookup plus a slice holding insertion\n// order. Delete is O(n) in the number of keys, because it has to close the gap\n// in that slice — an honest trade for O(1) Get and an allocation-free walk.\n// Re-Setting an existing key updates the value and KEEPS its original position:\n// insertion order means first insertion, not last write.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/orderedmapdemo](/r/moul/x/daily/orderedmapdemo/v0).\npackage orderedmap\n\n// MaxKeys bounds the map so gas stays predictable.\nconst MaxKeys = 4096\n\n// OrderedMap is a string-keyed map with deterministic iteration.\ntype OrderedMap struct {\n\tm    map[string]string\n\tkeys []string\n}\n\n// New returns an empty OrderedMap.\nfunc New() *OrderedMap {\n\treturn \u0026OrderedMap{m: map[string]string{}}\n}\n\n// Len returns the number of entries.\nfunc (o *OrderedMap) Len() int { return len(o.keys) }\n\n// Set inserts or updates k. Updating an existing key keeps its original\n// position — insertion order means FIRST insertion. Returns false when the map\n// is full and k is new.\nfunc (o *OrderedMap) Set(k, v string) bool {\n\tif _, ok := o.m[k]; ok {\n\t\to.m[k] = v\n\t\treturn true\n\t}\n\tif len(o.keys) \u003e= MaxKeys {\n\t\treturn false\n\t}\n\to.m[k] = v\n\to.keys = append(o.keys, k)\n\treturn true\n}\n\n// Get returns the value for k.\nfunc (o *OrderedMap) Get(k string) (string, bool) {\n\tv, ok := o.m[k]\n\treturn v, ok\n}\n\n// Has reports whether k is present.\nfunc (o *OrderedMap) Has(k string) bool {\n\t_, ok := o.m[k]\n\treturn ok\n}\n\n// Delete removes k and reports whether it was present. O(n): the key's slot in\n// the order slice has to be closed up, and the remaining keys shifted, so that\n// order is preserved.\nfunc (o *OrderedMap) Delete(k string) bool {\n\tif _, ok := o.m[k]; !ok {\n\t\treturn false\n\t}\n\tdelete(o.m, k)\n\tfor i, kk := range o.keys {\n\t\tif kk == k {\n\t\t\to.keys = append(o.keys[:i], o.keys[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn true\n}\n\n// Keys returns the keys in insertion order, as an independent copy.\nfunc (o *OrderedMap) Keys() []string {\n\tout := make([]string, len(o.keys))\n\tcopy(out, o.keys)\n\treturn out\n}\n\n// Values returns the values in key-insertion order.\nfunc (o *OrderedMap) Values() []string {\n\tout := make([]string, 0, len(o.keys))\n\tfor _, k := range o.keys {\n\t\tout = append(out, o.m[k])\n\t}\n\treturn out\n}\n\n// Iterate calls fn for each entry in insertion order, stopping early if fn\n// returns true. The map must not be mutated from inside fn — the walk is over\n// a live slice.\nfunc (o *OrderedMap) Iterate(fn func(k, v string) bool) {\n\tfor _, k := range o.keys {\n\t\tif fn(k, o.m[k]) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// At returns the i-th entry in insertion order.\nfunc (o *OrderedMap) At(i int) (k, v string, ok bool) {\n\tif i \u003c 0 || i \u003e= len(o.keys) {\n\t\treturn \"\", \"\", false\n\t}\n\tk = o.keys[i]\n\treturn k, o.m[k], true\n}\n\n// Clone returns an independent copy preserving order.\nfunc (o *OrderedMap) Clone() *OrderedMap {\n\tc := New()\n\tfor _, k := range o.keys {\n\t\tc.Set(k, o.m[k])\n\t}\n\treturn c\n}\n"},{"name":"orderedmap_test.gno","body":"package orderedmap\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestSetGetOrder(t *testing.T) {\n\to := New()\n\to.Set(\"z\", \"1\")\n\to.Set(\"a\", \"2\")\n\to.Set(\"m\", \"3\")\n\tuassert.Equal(t, \"z,a,m\", strings.Join(o.Keys(), \",\"))   // insertion, not sorted\n\tuassert.Equal(t, \"1,2,3\", strings.Join(o.Values(), \",\")) // values follow keys\n\tv, ok := o.Get(\"a\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"2\", v)\n\tuassert.Equal(t, 3, o.Len())\n}\n\n// Insertion order means FIRST insertion: updating must not move a key.\nfunc TestUpdateKeepsPosition(t *testing.T) {\n\to := New()\n\to.Set(\"a\", \"1\")\n\to.Set(\"b\", \"2\")\n\to.Set(\"a\", \"99\")\n\tuassert.Equal(t, \"a,b\", strings.Join(o.Keys(), \",\"))\n\tv, _ := o.Get(\"a\")\n\tuassert.Equal(t, \"99\", v)\n\tuassert.Equal(t, 2, o.Len())\n}\n\nfunc TestDeletePreservesOrder(t *testing.T) {\n\to := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\"} {\n\t\to.Set(k, k)\n\t}\n\tuassert.True(t, o.Delete(\"b\"))\n\tuassert.Equal(t, \"a,c,d\", strings.Join(o.Keys(), \",\"))\n\tuassert.False(t, o.Has(\"b\"))\n\tuassert.False(t, o.Delete(\"b\")) // already gone\n\tuassert.Equal(t, 3, o.Len())\n}\n\n// Re-inserting after a delete appends at the END — it is a new insertion.\nfunc TestReinsertAfterDeleteGoesLast(t *testing.T) {\n\to := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\"} {\n\t\to.Set(k, k)\n\t}\n\to.Delete(\"a\")\n\to.Set(\"a\", \"again\")\n\tuassert.Equal(t, \"b,c,a\", strings.Join(o.Keys(), \",\"))\n}\n\nfunc TestMissingKey(t *testing.T) {\n\to := New()\n\tv, ok := o.Get(\"nope\")\n\tuassert.False(t, ok)\n\tuassert.Equal(t, \"\", v)\n\tuassert.False(t, o.Has(\"nope\"))\n}\n\nfunc TestAt(t *testing.T) {\n\to := New()\n\to.Set(\"x\", \"1\")\n\to.Set(\"y\", \"2\")\n\tk, v, ok := o.At(1)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"y\", k)\n\tuassert.Equal(t, \"2\", v)\n\t_, _, ok = o.At(2)\n\tuassert.False(t, ok)\n\t_, _, ok = o.At(-1)\n\tuassert.False(t, ok)\n}\n\nfunc TestIterateStopsEarly(t *testing.T) {\n\to := New()\n\tfor _, k := range []string{\"a\", \"b\", \"c\"} {\n\t\to.Set(k, k)\n\t}\n\tseen := []string{}\n\to.Iterate(func(k, v string) bool {\n\t\tseen = append(seen, k)\n\t\treturn k == \"b\" // stop after b\n\t})\n\tuassert.Equal(t, \"a,b\", strings.Join(seen, \",\"))\n}\n\n// The whole point: the order is stable across identical builds, where a\n// built-in map gives no such guarantee.\nfunc TestOrderIsStable(t *testing.T) {\n\tbuild := func() string {\n\t\to := New()\n\t\tfor _, k := range []string{\"delta\", \"alpha\", \"charlie\", \"bravo\"} {\n\t\t\to.Set(k, k)\n\t\t}\n\t\treturn strings.Join(o.Keys(), \",\")\n\t}\n\tfirst := build()\n\tfor i := 0; i \u003c 20; i++ {\n\t\tuassert.Equal(t, first, build())\n\t}\n\tuassert.Equal(t, \"delta,alpha,charlie,bravo\", first)\n}\n\nfunc TestKeysIsACopy(t *testing.T) {\n\to := New()\n\to.Set(\"a\", \"1\")\n\tks := o.Keys()\n\tks[0] = \"mutated\"\n\tuassert.Equal(t, \"a\", strings.Join(o.Keys(), \",\"))\n}\n\nfunc TestCloneIsIndependent(t *testing.T) {\n\to := New()\n\to.Set(\"a\", \"1\")\n\tc := o.Clone()\n\tc.Set(\"b\", \"2\")\n\tuassert.Equal(t, \"a\", strings.Join(o.Keys(), \",\"))\n\tuassert.Equal(t, \"a,b\", strings.Join(c.Keys(), \",\"))\n}\n\nfunc TestFullMapRejectsNewKeys(t *testing.T) {\n\to := New()\n\tfor i := 0; i \u003c MaxKeys; i++ {\n\t\tuassert.True(t, o.Set(itoa(i), \"v\"))\n\t}\n\tuassert.False(t, o.Set(\"overflow\", \"v\")) // new key refused\n\tuassert.True(t, o.Set(\"0\", \"updated\"))   // existing key still updatable\n\tuassert.Equal(t, MaxKeys, o.Len())\n}\n\nfunc itoa(i int) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b []byte\n\tfor i \u003e 0 {\n\t\tb = append([]byte{byte('0' + i%10)}, b...)\n\t\ti /= 10\n\t}\n\treturn string(b)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"piglatin","path":"gno.land/p/moul/x/daily/piglatin/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/piglatin/v0`\n\n**Pig Latin translator** — `Translate`, `TranslateToken`.\n\nPure `strings`/`unicode`, fully deterministic. Vowel-start words get `way`;\nconsonant-start words move the leading consonant cluster to the end and add `ay`;\n`y` is a consonant only as the first letter; capitalization and edge punctuation\nare preserved.\n\n```go\nimport \"gno.land/p/moul/x/daily/piglatin/v0\"\n\npiglatin.Translate(\"Hello, world!\")   // \"Ellohay, orldway!\"\npiglatin.TranslateToken(\"string\")     // \"ingstray\"\n```\n\n**Live demo:** [`r/moul/x/daily/piglatindemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/piglatindemo)\n· render it at [`/r/moul/x/daily/piglatindemo/v0`](https://gno.land/r/moul/x/daily/piglatindemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/piglatin/v0\"\ngno = \"0.9\"\n"},{"name":"piglatin.gno","body":"// Package piglatin ports the classic \"Pig Latin\" translator — a staple Go\n// beginner exercise — to gno.land as a reusable pure package.\n//\n// Rules implemented (the standard English game):\n//   - A word that starts with a vowel gets \"way\" appended:   \"apple\" -\u003e \"appleway\"\n//   - A word that starts with one or more consonants has that leading\n//     consonant cluster moved to the end, followed by \"ay\":  \"string\" -\u003e \"ingstray\"\n//   - \"y\" acts as a consonant only when it is the first letter of the word\n//     (\"yellow\" -\u003e \"ellowyay\"); elsewhere it counts as a vowel (\"myth\" -\u003e \"ythmay\").\n//   - Original capitalization of the word is preserved (title-case in, title-case\n//     out): \"Hello\" -\u003e \"Ellohay\".\n//   - Trailing/leading punctuation attached to a word is preserved in place:\n//     \"Hello,\" -\u003e \"Ellohay,\".\n//\n// Everything is pure strings/unicode — deterministic and reproducible on-chain.\n//\n// A live demo of this package (an interactive sentence translator) is at\n// [r/moul/x/daily/piglatindemo](/r/moul/x/daily/piglatindemo/v0).\npackage piglatin\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nconst suffixVowel = \"way\"\nconst suffixConsonant = \"ay\"\n\nfunc isVowel(r rune) bool {\n\tswitch unicode.ToLower(r) {\n\tcase 'a', 'e', 'i', 'o', 'u':\n\t\treturn true\n\t}\n\treturn false\n}\n\n// isLetter reports whether r is an ASCII/unicode letter (word character).\nfunc isLetter(r rune) bool {\n\treturn unicode.IsLetter(r)\n}\n\n// translateWord converts a single \"core\" alphabetic word (no surrounding\n// punctuation) to Pig Latin, preserving its capitalization pattern.\nfunc translateWord(word string) string {\n\tif word == \"\" {\n\t\treturn word\n\t}\n\trunes := []rune(word)\n\n\t// Find the leading consonant cluster. 'y' is a consonant only in position 0.\n\tstart := 0\n\tfor i, r := range runes {\n\t\tif isVowel(r) {\n\t\t\tbreak\n\t\t}\n\t\t// 'y' after the first letter behaves like a vowel: stop the cluster.\n\t\tif i \u003e 0 \u0026\u0026 unicode.ToLower(r) == 'y' {\n\t\t\tbreak\n\t\t}\n\t\tstart = i + 1\n\t}\n\n\tvar out []rune\n\tif start == 0 {\n\t\t// Starts with a vowel.\n\t\tout = append(out, runes...)\n\t\tout = append(out, []rune(suffixVowel)...)\n\t} else if start \u003e= len(runes) {\n\t\t// All consonants (no vowel found), e.g. \"shh\" — just append \"ay\".\n\t\tout = append(out, runes...)\n\t\tout = append(out, []rune(suffixConsonant)...)\n\t} else {\n\t\tout = append(out, runes[start:]...)\n\t\tout = append(out, runes[:start]...)\n\t\tout = append(out, []rune(suffixConsonant)...)\n\t}\n\n\treturn applyCase(word, string(out))\n}\n\n// applyCase re-applies the capitalization shape of the original word to the\n// translated word. Two common shapes are handled: ALL CAPS and Title-case;\n// everything else is returned lowercase.\nfunc applyCase(orig, translated string) string {\n\torigRunes := []rune(orig)\n\tif len(origRunes) == 0 {\n\t\treturn translated\n\t}\n\n\t// Count letters and uppercase letters in the original.\n\tletters, uppers := 0, 0\n\tfor _, r := range origRunes {\n\t\tif unicode.IsLetter(r) {\n\t\t\tletters++\n\t\t\tif unicode.IsUpper(r) {\n\t\t\t\tuppers++\n\t\t\t}\n\t\t}\n\t}\n\n\tlow := strings.ToLower(translated)\n\tswitch {\n\tcase letters \u003e 0 \u0026\u0026 uppers == letters \u0026\u0026 letters \u003e 1:\n\t\t// ALL CAPS -\u003e keep upper.\n\t\treturn strings.ToUpper(low)\n\tcase unicode.IsUpper(origRunes[0]):\n\t\t// Title-case -\u003e capitalize first letter of the result.\n\t\ttr := []rune(low)\n\t\tif len(tr) \u003e 0 {\n\t\t\ttr[0] = unicode.ToUpper(tr[0])\n\t\t}\n\t\treturn string(tr)\n\tdefault:\n\t\treturn low\n\t}\n}\n\n// splitAffixes separates a token into (leading punctuation, core word,\n// trailing punctuation) where the core is the contiguous run of letters\n// (apostrophes inside are kept as part of the core, e.g. \"don't\").\nfunc splitAffixes(token string) (string, string, string) {\n\trunes := []rune(token)\n\ti := 0\n\tfor i \u003c len(runes) \u0026\u0026 !isLetter(runes[i]) {\n\t\ti++\n\t}\n\tj := len(runes)\n\tfor j \u003e i \u0026\u0026 !isLetter(runes[j-1]) {\n\t\tj--\n\t}\n\tif i \u003e= j {\n\t\treturn token, \"\", \"\" // no letters at all\n\t}\n\treturn string(runes[:i]), string(runes[i:j]), string(runes[j:])\n}\n\n// TranslateToken translates a single whitespace-delimited token, preserving\n// any punctuation glued to its edges.\nfunc TranslateToken(token string) string {\n\tlead, core, trail := splitAffixes(token)\n\tif core == \"\" {\n\t\treturn token\n\t}\n\treturn lead + translateWord(core) + trail\n}\n\n// Translate applies Pig Latin to every word in the sentence while preserving\n// the original whitespace between words.\nfunc Translate(sentence string) string {\n\tvar b strings.Builder\n\tvar word strings.Builder\n\tflush := func() {\n\t\tif word.Len() \u003e 0 {\n\t\t\tb.WriteString(TranslateToken(word.String()))\n\t\t\tword.Reset()\n\t\t}\n\t}\n\tfor _, r := range sentence {\n\t\tif unicode.IsSpace(r) {\n\t\t\tflush()\n\t\t\tb.WriteRune(r)\n\t\t\tcontinue\n\t\t}\n\t\tword.WriteRune(r)\n\t}\n\tflush()\n\treturn b.String()\n}\n"},{"name":"piglatin_test.gno","body":"package piglatin\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestTranslateWord(t *testing.T) {\n\tcases := []struct {\n\t\tin, want string\n\t}{\n\t\t{\"pig\", \"igpay\"},\n\t\t{\"banana\", \"ananabay\"},\n\t\t{\"smile\", \"ilesmay\"},\n\t\t{\"string\", \"ingstray\"},\n\t\t{\"eat\", \"eatway\"},\n\t\t{\"apple\", \"appleway\"},\n\t\t{\"yellow\", \"ellowyay\"}, // leading y = consonant\n\t\t{\"myth\", \"ythmay\"},     // internal y = vowel\n\t\t{\"Hello\", \"Ellohay\"},   // title-case preserved\n\t\t{\"NASA\", \"ASANAY\"},     // all caps preserved\n\t}\n\tfor _, c := range cases {\n\t\tgot := translateWord(c.in)\n\t\tuassert.Equal(t, c.want, got)\n\t}\n}\n\nfunc TestTranslateSentence(t *testing.T) {\n\tcases := []struct {\n\t\tin, want string\n\t}{\n\t\t{\"hello world\", \"ellohay orldway\"},\n\t\t{\"Hello, world!\", \"Ellohay, orldway!\"},\n\t\t{\"The quick brown fox\", \"Ethay uickqay ownbray oxfay\"},\n\t\t{\"\", \"\"},\n\t\t{\"   \", \"   \"}, // whitespace preserved, no words\n\t}\n\tfor _, c := range cases {\n\t\tgot := Translate(c.in)\n\t\tuassert.Equal(t, c.want, got)\n\t}\n}\n\nfunc TestSplitAffixes(t *testing.T) {\n\tlead, core, trail := splitAffixes(\"(Hello!)\")\n\tuassert.Equal(t, \"(\", lead)\n\tuassert.Equal(t, \"Hello\", core)\n\tuassert.Equal(t, \"!)\", trail)\n\n\tlead, core, trail = splitAffixes(\"...\")\n\tuassert.Equal(t, \"...\", lead)\n\tuassert.Equal(t, \"\", core)\n\tuassert.Equal(t, \"\", trail)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pullpayment","path":"gno.land/p/moul/x/daily/pullpayment/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/pullpayment/v0`\n\n**Pull-payment escrow ledger** — `New`, `Credit`, `CreditMany`, `Withdraw`,\n`Forfeit`, `Balance`, `TotalOwed`, `TotalWithdrawn`, `Payees`, `Iterate`,\n`Consistent`, `MaxPayees`.\n\n```go\nimport \"gno.land/p/moul/x/daily/pullpayment/v0\"\n\nl := pullpayment.New()\nl.CreditMany([]string{\"alice\", \"bob\"}, []int64{500, 300})\nl.TotalOwed()          // 800 — what the realm must keep in reserve\n\namt, err := l.Withdraw(\"bob\")   // 300; the balance is ALREADY zeroed\n// ...the caller transfers `amt` only now\n```\n\nThe classic Solidity answer to reentrancy: never push value to an address,\ncredit it and let the recipient withdraw. A push hands control to the recipient\nin the middle of your state transition, and a hostile recipient re-enters before\nyou have finished updating.\n\nThis package is the **bookkeeping half only** — it moves no coins. The realm\nholding the funds transfers *after* calling `Withdraw`, which is exactly the\nordering the pattern demands: checks, effects, **then** interactions. The balance\nis already deleted when control leaves, so a reentrant `Withdraw` returns\n`ErrNothing` and `TotalWithdrawn` is not double-counted. That property has its own\ntest.\n\nOther guarantees, each tested:\n\n- **`CreditMany` is all-or-nothing.** A batch with one bad entry applies none of\n  itself — a ledger half-agreeing with the funds it guards is worse than a\n  rejected call.\n- **Overflow is refused**, not wrapped, on both a single balance and the total.\n- `Consistent()` is exported: `TotalOwed` always equals the sum of the balances.\n\n`Payees` comes back **sorted**, never in map order, so a `Render` built from it\ncannot differ between nodes.\n\n**Live demo:** [`r/moul/x/daily/pullpaymentdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/pullpaymentdemo)\n· render it at [`/r/moul/x/daily/pullpaymentdemo/v0`](https://gno.land/r/moul/x/daily/pullpaymentdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/pullpayment/v0\"\ngno = \"0.9\"\n"},{"name":"pullpayment.gno","body":"// Package pullpayment is the escrow ledger behind the pull-payment pattern, as\n// a pure, reusable package.\n//\n// The pattern is the classic Solidity answer to reentrancy: never push value to\n// an address, credit it and let the recipient withdraw. A push sends control to\n// the recipient in the middle of your state transition, and a malicious\n// recipient re-enters before you have finished updating. Pull inverts that —\n// the recipient calls in, and their own withdrawal is the only state being\n// touched.\n//\n// This package is the BOOKKEEPING half only: who is owed what, and the\n// checks-effects-interactions ordering that makes a withdrawal safe. It moves\n// no coins. The realm that holds the funds performs the transfer AFTER calling\n// Withdraw, which is exactly the ordering the pattern demands — the balance is\n// already zeroed when the transfer happens, so a reentrant call finds nothing\n// left to take.\n//\n// Iteration is over sorted addresses, never a built-in map range: gno map\n// iteration order is unspecified and a Render built from one can differ between\n// nodes, which is a consensus bug rather than a cosmetic one.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/pullpaymentdemo](/r/moul/x/daily/pullpaymentdemo/v0).\npackage pullpayment\n\nimport (\n\t\"errors\"\n\t\"sort\"\n)\n\n// MaxPayees bounds the ledger so gas stays predictable.\nconst MaxPayees = 4096\n\nvar (\n\tErrBadAmount = errors.New(\"pullpayment: amount must be positive\")\n\tErrFull      = errors.New(\"pullpayment: too many payees\")\n\tErrNothing   = errors.New(\"pullpayment: nothing to withdraw\")\n\tErrOverflow  = errors.New(\"pullpayment: credit would overflow\")\n)\n\nconst maxInt64 = int64(9223372036854775807)\n\n// Ledger records what each address is owed.\ntype Ledger struct {\n\towed      map[string]int64\n\ttotal     int64\n\twithdrawn int64\n}\n\n// New returns an empty Ledger.\nfunc New() *Ledger { return \u0026Ledger{owed: map[string]int64{}} }\n\n// Credit records that payee is owed amount more. Amounts accumulate: crediting\n// twice owes the sum.\nfunc (l *Ledger) Credit(payee string, amount int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrBadAmount\n\t}\n\tcur, seen := l.owed[payee]\n\tif !seen \u0026\u0026 len(l.owed) \u003e= MaxPayees {\n\t\treturn ErrFull\n\t}\n\tif cur \u003e maxInt64-amount || l.total \u003e maxInt64-amount {\n\t\treturn ErrOverflow\n\t}\n\tl.owed[payee] = cur + amount\n\tl.total += amount\n\treturn nil\n}\n\n// Balance returns what payee is currently owed; zero when nothing.\nfunc (l *Ledger) Balance(payee string) int64 { return l.owed[payee] }\n\n// Withdraw zeroes payee's balance and returns what was owed.\n//\n// The caller transfers the returned amount AFTER this call. That ordering is\n// the point of the pattern: the credit is already gone from the ledger when\n// control passes to the recipient, so a reentrant Withdraw returns ErrNothing.\nfunc (l *Ledger) Withdraw(payee string) (int64, error) {\n\tamount, ok := l.owed[payee]\n\tif !ok || amount == 0 {\n\t\treturn 0, ErrNothing\n\t}\n\tdelete(l.owed, payee) // effects before interactions\n\tl.total -= amount\n\tl.withdrawn += amount\n\treturn amount, nil\n}\n\n// Forfeit drops a payee's credit without paying it, returning what was dropped.\nfunc (l *Ledger) Forfeit(payee string) (int64, error) {\n\tamount, ok := l.owed[payee]\n\tif !ok || amount == 0 {\n\t\treturn 0, ErrNothing\n\t}\n\tdelete(l.owed, payee)\n\tl.total -= amount\n\treturn amount, nil\n}\n\n// TotalOwed returns the sum of every outstanding balance — what the holding\n// realm must keep in reserve.\nfunc (l *Ledger) TotalOwed() int64 { return l.total }\n\n// TotalWithdrawn returns the lifetime sum of successful withdrawals.\nfunc (l *Ledger) TotalWithdrawn() int64 { return l.withdrawn }\n\n// Payees returns every address with an outstanding balance, sorted.\nfunc (l *Ledger) Payees() []string {\n\tout := make([]string, 0, len(l.owed))\n\tfor p := range l.owed {\n\t\tout = append(out, p)\n\t}\n\tsort.Strings(out)\n\treturn out\n}\n\n// Count returns how many payees are owed something.\nfunc (l *Ledger) Count() int { return len(l.owed) }\n\n// IsEmpty reports whether nothing is owed to anyone.\nfunc (l *Ledger) IsEmpty() bool { return len(l.owed) == 0 }\n\n// Iterate calls fn for each payee in sorted order. Returning true stops.\nfunc (l *Ledger) Iterate(fn func(payee string, amount int64) bool) {\n\tfor _, p := range l.Payees() {\n\t\tif fn(p, l.owed[p]) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// CreditMany credits several payees, applying nothing unless every entry is\n// valid — a partial split would leave the ledger disagreeing with the funds.\nfunc (l *Ledger) CreditMany(payees []string, amounts []int64) error {\n\tif len(payees) != len(amounts) {\n\t\treturn ErrBadAmount\n\t}\n\t// Validate first.\n\tfor _, a := range amounts {\n\t\tif a \u003c= 0 {\n\t\t\treturn ErrBadAmount\n\t\t}\n\t}\n\tprobe := len(l.owed)\n\tfor _, p := range payees {\n\t\tif _, seen := l.owed[p]; !seen {\n\t\t\tprobe++\n\t\t}\n\t}\n\tif probe \u003e MaxPayees {\n\t\treturn ErrFull\n\t}\n\tvar sum int64\n\tfor _, a := range amounts {\n\t\tif sum \u003e maxInt64-a {\n\t\t\treturn ErrOverflow\n\t\t}\n\t\tsum += a\n\t}\n\tif l.total \u003e maxInt64-sum {\n\t\treturn ErrOverflow\n\t}\n\t// Then apply.\n\tfor i, p := range payees {\n\t\tl.owed[p] += amounts[i]\n\t}\n\tl.total += sum\n\treturn nil\n}\n\n// Consistent reports whether TotalOwed equals the sum of the balances. Always\n// true through the public API; exported so callers can assert the invariant.\nfunc (l *Ledger) Consistent() bool {\n\tvar sum int64\n\tfor _, a := range l.owed {\n\t\tsum += a\n\t}\n\treturn sum == l.total\n}\n"},{"name":"pullpayment_test.gno","body":"package pullpayment\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestEmpty(t *testing.T) {\n\tl := New()\n\tuassert.True(t, l.IsEmpty())\n\tuassert.Equal(t, 0, l.Count())\n\tuassert.Equal(t, int64(0), l.TotalOwed())\n\tuassert.Equal(t, int64(0), l.Balance(\"nobody\"))\n\tuassert.True(t, l.Consistent())\n}\n\nfunc TestCreditAccumulates(t *testing.T) {\n\tl := New()\n\tuassert.NoError(t, l.Credit(\"alice\", 100))\n\tuassert.NoError(t, l.Credit(\"alice\", 50))\n\n\tuassert.Equal(t, int64(150), l.Balance(\"alice\"), \"credits accumulate\")\n\tuassert.Equal(t, 1, l.Count(), \"the same payee is not counted twice\")\n\tuassert.Equal(t, int64(150), l.TotalOwed())\n\tuassert.True(t, l.Consistent())\n}\n\nfunc TestCreditRejectsNonPositive(t *testing.T) {\n\tl := New()\n\tuassert.ErrorIs(t, l.Credit(\"alice\", 0), ErrBadAmount)\n\tuassert.ErrorIs(t, l.Credit(\"alice\", -1), ErrBadAmount)\n\tuassert.True(t, l.IsEmpty(), \"a rejected credit changes nothing\")\n}\n\nfunc TestWithdrawZeroesBalance(t *testing.T) {\n\tl := New()\n\tl.Credit(\"alice\", 100)\n\n\tgot, err := l.Withdraw(\"alice\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(100), got)\n\tuassert.Equal(t, int64(0), l.Balance(\"alice\"), \"the balance is gone before the caller transfers\")\n\tuassert.Equal(t, int64(0), l.TotalOwed())\n\tuassert.Equal(t, int64(100), l.TotalWithdrawn())\n\tuassert.True(t, l.Consistent())\n}\n\n// TestReentrantWithdrawGetsNothing is the security property the pattern exists\n// for: the second entry finds the balance already zeroed.\nfunc TestReentrantWithdrawGetsNothing(t *testing.T) {\n\tl := New()\n\tl.Credit(\"attacker\", 1000)\n\n\tfirst, err := l.Withdraw(\"attacker\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(1000), first)\n\n\t// Simulating the reentrant call the recipient would make from its handler,\n\t// BEFORE the outer caller has transferred anything.\n\tsecond, err := l.Withdraw(\"attacker\")\n\tuassert.ErrorIs(t, err, ErrNothing, \"a reentrant withdrawal must find nothing\")\n\tuassert.Equal(t, int64(0), second)\n\tuassert.Equal(t, int64(1000), l.TotalWithdrawn(), \"and must not be counted twice\")\n}\n\nfunc TestWithdrawUnknownPayee(t *testing.T) {\n\tl := New()\n\t_, err := l.Withdraw(\"nobody\")\n\tuassert.ErrorIs(t, err, ErrNothing)\n}\n\nfunc TestForfeit(t *testing.T) {\n\tl := New()\n\tl.Credit(\"alice\", 100)\n\tl.Credit(\"bob\", 40)\n\n\tdropped, err := l.Forfeit(\"alice\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(100), dropped)\n\tuassert.Equal(t, int64(40), l.TotalOwed())\n\tuassert.Equal(t, int64(0), l.TotalWithdrawn(), \"a forfeit is not a withdrawal\")\n\tuassert.True(t, l.Consistent())\n\n\t_, err = l.Forfeit(\"alice\")\n\tuassert.ErrorIs(t, err, ErrNothing)\n}\n\nfunc TestPayeesSorted(t *testing.T) {\n\tl := New()\n\tl.Credit(\"carol\", 3)\n\tl.Credit(\"alice\", 1)\n\tl.Credit(\"bob\", 2)\n\n\tuassert.Equal(t, \"alice,bob,carol\", strings.Join(l.Payees(), \",\"))\n}\n\nfunc TestIterateSortedAndStops(t *testing.T) {\n\tl := New()\n\tl.Credit(\"b\", 2)\n\tl.Credit(\"a\", 1)\n\n\tvar seen []string\n\tl.Iterate(func(p string, amt int64) bool {\n\t\tseen = append(seen, p+\":\"+strconv.FormatInt(amt, 10))\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"a:1,b:2\", strings.Join(seen, \",\"))\n\n\tn := 0\n\tl.Iterate(func(p string, amt int64) bool { n++; return true })\n\tuassert.Equal(t, 1, n)\n}\n\nfunc TestCreditMany(t *testing.T) {\n\tl := New()\n\terr := l.CreditMany([]string{\"a\", \"b\", \"c\"}, []int64{10, 20, 30})\n\tuassert.NoError(t, err)\n\n\tuassert.Equal(t, int64(10), l.Balance(\"a\"))\n\tuassert.Equal(t, int64(30), l.Balance(\"c\"))\n\tuassert.Equal(t, int64(60), l.TotalOwed())\n\tuassert.True(t, l.Consistent())\n}\n\n// TestCreditManyIsAllOrNothing pins that a bad entry applies none of the split.\nfunc TestCreditManyIsAllOrNothing(t *testing.T) {\n\tl := New()\n\tl.Credit(\"existing\", 5)\n\n\terr := l.CreditMany([]string{\"a\", \"b\"}, []int64{10, -1})\n\tuassert.ErrorIs(t, err, ErrBadAmount)\n\n\tuassert.Equal(t, int64(0), l.Balance(\"a\"), \"the valid entry must not be applied either\")\n\tuassert.Equal(t, int64(5), l.TotalOwed(), \"the ledger is untouched\")\n\tuassert.Equal(t, 1, l.Count())\n\tuassert.True(t, l.Consistent())\n}\n\nfunc TestCreditManyMismatchedLengths(t *testing.T) {\n\tl := New()\n\tuassert.ErrorIs(t, l.CreditMany([]string{\"a\"}, []int64{1, 2}), ErrBadAmount)\n\tuassert.True(t, l.IsEmpty())\n}\n\nfunc TestCreditManyAccumulates(t *testing.T) {\n\tl := New()\n\tl.Credit(\"a\", 5)\n\tuassert.NoError(t, l.CreditMany([]string{\"a\", \"b\"}, []int64{10, 1}))\n\tuassert.Equal(t, int64(15), l.Balance(\"a\"), \"adds to the existing balance\")\n\tuassert.Equal(t, int64(16), l.TotalOwed())\n}\n\nfunc TestOverflowGuard(t *testing.T) {\n\tl := New()\n\tuassert.NoError(t, l.Credit(\"whale\", maxInt64))\n\tuassert.ErrorIs(t, l.Credit(\"whale\", 1), ErrOverflow)\n\tuassert.ErrorIs(t, l.Credit(\"other\", 1), ErrOverflow, \"the total would overflow too\")\n\tuassert.Equal(t, maxInt64, l.TotalOwed(), \"a refused credit changes nothing\")\n\tuassert.True(t, l.Consistent())\n}\n\nfunc TestCreditManyOverflowGuard(t *testing.T) {\n\tl := New()\n\tl.Credit(\"a\", maxInt64-5)\n\tuassert.ErrorIs(t, l.CreditMany([]string{\"b\", \"c\"}, []int64{10, 10}), ErrOverflow)\n\tuassert.Equal(t, int64(0), l.Balance(\"b\"), \"nothing applied\")\n}\n\nfunc TestMaxPayees(t *testing.T) {\n\tl := New()\n\tfor i := 0; i \u003c MaxPayees; i++ {\n\t\tuassert.NoError(t, l.Credit(\"p\"+strconv.Itoa(i), 1))\n\t}\n\tuassert.Equal(t, MaxPayees, l.Count())\n\n\tuassert.ErrorIs(t, l.Credit(\"overflow\", 1), ErrFull, \"a full ledger refuses a new payee\")\n\tuassert.NoError(t, l.Credit(\"p0\", 1), \"existing payees can still be credited\")\n\tuassert.Equal(t, int64(2), l.Balance(\"p0\"))\n}\n\nfunc TestCreditManyRespectsCapacity(t *testing.T) {\n\tl := New()\n\tfor i := 0; i \u003c MaxPayees-1; i++ {\n\t\tl.Credit(\"p\"+strconv.Itoa(i), 1)\n\t}\n\tuassert.ErrorIs(t, l.CreditMany([]string{\"x\", \"y\"}, []int64{1, 1}), ErrFull,\n\t\t\"the batch would exceed capacity, so none of it applies\")\n\tuassert.Equal(t, int64(0), l.Balance(\"x\"))\n}\n\n// TestFullLifecycle walks a realistic split-then-claim sequence.\nfunc TestFullLifecycle(t *testing.T) {\n\tl := New()\n\tuassert.NoError(t, l.CreditMany([]string{\"alice\", \"bob\", \"carol\"}, []int64{500, 300, 200}))\n\tuassert.Equal(t, int64(1000), l.TotalOwed(), \"the realm must hold 1000 in reserve\")\n\n\tgot, _ := l.Withdraw(\"bob\")\n\tuassert.Equal(t, int64(300), got)\n\tuassert.Equal(t, int64(700), l.TotalOwed(), \"reserve drops by exactly what was paid\")\n\n\tl.Credit(\"alice\", 100)\n\tgot, _ = l.Withdraw(\"alice\")\n\tuassert.Equal(t, int64(600), got, \"a later credit is included in one withdrawal\")\n\n\tuassert.Equal(t, int64(200), l.TotalOwed())\n\tuassert.Equal(t, int64(900), l.TotalWithdrawn())\n\tuassert.Equal(t, \"carol\", strings.Join(l.Payees(), \",\"))\n\tuassert.True(t, l.Consistent())\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ratelimit","path":"gno.land/p/moul/x/daily/ratelimit/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/ratelimit/v0`\n\n**Deterministic token-bucket rate limiter** — a port of `golang.org/x/time/rate`\nwith the wall clock replaced by a caller-supplied monotonic tick (on-chain, the\nblock height).\n\nA `Limiter` owns a set of per-key token buckets sharing one `rate`/`burst`\nconfig. Each bucket refills at `rate` tokens per tick up to `burst`; the caller\npicks what a key is (typically an address) and passes the current tick on every\ncall. Pure integer/float math over persistent avl state — no chain imports, no\nambient state, fully replayable.\n\n```go\nimport \"gno.land/p/moul/x/daily/ratelimit/v0\"\n\nl := ratelimit.New(0.5, 5.0)     // 0.5 tokens/tick, capacity 5\nl.Allow(\"g1caller\", height)      // consume one token; false if empty\nl.AllowN(\"g1caller\", height, 3)  // consume 3 atomically; false if \u003c3\nl.Tokens(\"g1caller\", height)     // read-only balance (whole tokens)\n```\n\n**Live demo:** [`r/moul/x/daily/ratelimitdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/ratelimitdemo)\n· render it at [`/r/moul/x/daily/ratelimitdemo/v0`](https://gno.land/r/moul/x/daily/ratelimitdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/daily/ratelimit/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/daily/ratelimit/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/ratelimit/v0\"\ngno = \"0.9\"\n"},{"name":"ratelimit.gno","body":"// Package ratelimit is a deterministic token-bucket rate limiter — a port of\n// golang.org/x/time/rate with the wall clock replaced by a caller-supplied\n// monotonic tick (on-chain, that tick is the block height).\n//\n// It is a pure library: it imports no chain APIs and reads no ambient state.\n// A [Limiter] owns a set of per-key token buckets sharing one rate/burst\n// config; the caller decides what a key is (typically an address string) and\n// supplies the current tick on every call. Between two observations at ticks\n// `last` and `now`, a bucket gains (now-last)*rate tokens, capped at `burst`.\n// Everything is integer/float arithmetic over persistent avl state, hence\n// deterministic and replayable.\n//\n// A realm wires it up by holding a *Limiter in a package-level var and feeding\n// it runtime.ChainHeight() as the tick. For a complete, live example see the\n// demo realm [r/moul/x/daily/ratelimitdemo](/r/moul/x/daily/ratelimitdemo/v0).\npackage ratelimit\n\nimport \"gno.land/p/nt/avl/v0\"\n\n// bucket is the per-key state persisted in the avl tree.\ntype bucket struct {\n\ttokens float64 // tokens available as of `last`\n\tlast   int64   // tick at which `tokens` was computed\n}\n\n// Limiter is a set of per-key token buckets sharing one rate/burst config.\n// The zero value is not usable; construct one with [New].\ntype Limiter struct {\n\trate    float64   // tokens replenished per tick\n\tburst   float64   // bucket capacity (max tokens, largest single burst)\n\tbuckets *avl.Tree // key string -\u003e *bucket, ordered by key (deterministic)\n}\n\n// New returns a Limiter replenishing `rate` tokens per tick, each bucket capped\n// at `burst`. rate is clamped to \u003e= 0, burst to \u003e= 1.\nfunc New(rate, burst float64) *Limiter {\n\tl := \u0026Limiter{buckets: avl.NewTree()}\n\tl.SetConfig(rate, burst)\n\treturn l\n}\n\n// SetConfig updates the shared rate and burst. rate is clamped to \u003e= 0, burst\n// to \u003e= 1. Existing buckets keep their stored tokens; the new config applies\n// from the next refill.\nfunc (l *Limiter) SetConfig(rate, burst float64) {\n\tif rate \u003c 0 {\n\t\trate = 0\n\t}\n\tif burst \u003c 1 {\n\t\tburst = 1\n\t}\n\tl.rate = rate\n\tl.burst = burst\n}\n\n// Config returns the current rate (tokens/tick) and burst (capacity).\nfunc (l *Limiter) Config() (rate, burst float64) { return l.rate, l.burst }\n\n// Allow consumes one token for `key` at tick `now` and reports whether the\n// request is permitted. When the bucket is empty it returns false and consumes\n// nothing. Equivalent to AllowN(key, now, 1).\nfunc (l *Limiter) Allow(key string, now int64) bool {\n\treturn l.AllowN(key, now, 1)\n}\n\n// AllowN consumes `n` tokens for `key` at tick `now` and reports whether the\n// request is permitted. When fewer than `n` tokens are available it returns\n// false and consumes nothing. A key is seen for the first time with a full\n// bucket of `burst` tokens.\nfunc (l *Limiter) AllowN(key string, now int64, n float64) bool {\n\tb := l.load(key, now)\n\tok := b.tokens \u003e= n\n\tif ok {\n\t\tb.tokens -= n\n\t}\n\tl.buckets.Set(key, b)\n\treturn ok\n}\n\n// Tokens is a read-only view of how many whole tokens `key` has available at\n// tick `now`, without mutating any state.\nfunc (l *Limiter) Tokens(key string, now int64) int {\n\tif !l.buckets.Has(key) {\n\t\treturn tokensToInt(l.burst)\n\t}\n\tb := l.buckets.Get(key).(*bucket)\n\treturn tokensToInt(refill(b.tokens, b.last, now, l.rate, l.burst))\n}\n\n// Len returns the number of keys the limiter has seen.\nfunc (l *Limiter) Len() int { return l.buckets.Size() }\n\n// Iterate calls fn for every known key in ascending order, passing the whole\n// tokens available at tick `now` and the last tick the key was observed.\n// Returning true from fn stops the iteration early; Iterate reports whether it\n// was stopped that way.\nfunc (l *Limiter) Iterate(now int64, fn func(key string, tokens int, last int64) bool) bool {\n\treturn l.buckets.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tb := value.(*bucket)\n\t\treturn fn(key, tokensToInt(refill(b.tokens, b.last, now, l.rate, l.burst)), b.last)\n\t})\n}\n\n// load returns the live bucket for key, refilled to `now`, creating a full\n// bucket the first time a key is seen. The returned bucket is not yet stored;\n// callers that mutate it must Set it back.\nfunc (l *Limiter) load(key string, now int64) *bucket {\n\tif l.buckets.Has(key) {\n\t\tb := l.buckets.Get(key).(*bucket)\n\t\tb.tokens = refill(b.tokens, b.last, now, l.rate, l.burst)\n\t\tb.last = now\n\t\treturn b\n\t}\n\treturn \u0026bucket{tokens: l.burst, last: now}\n}\n\n// --- pure helpers (unit-tested) -------------------------------------------\n\n// fmin returns the smaller of two float64 values.\nfunc fmin(a, b float64) float64 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n// refill returns the token count at tick `now` given `tokens` observed at tick\n// `last`, replenishing at `r` tokens/tick up to capacity `cap`. It never\n// decreases below the stored value and never exceeds `cap`.\nfunc refill(tokens float64, last, now int64, r, cap float64) float64 {\n\tif now \u003c= last {\n\t\treturn fmin(tokens, cap)\n\t}\n\telapsed := float64(now - last)\n\treturn fmin(cap, tokens+elapsed*r)\n}\n\n// tokensToInt floors a token count to a whole, non-negative token.\nfunc tokensToInt(t float64) int {\n\tif t \u003c 0 {\n\t\treturn 0\n\t}\n\treturn int(t)\n}\n"},{"name":"ratelimit_test.gno","body":"package ratelimit\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRefill(t *testing.T) {\n\t// Start with 1 token, 4 ticks elapse at 0.5 tokens/tick, cap 5.\n\t// 1 + 4*0.5 = 3.\n\tgot := refill(1.0, 10, 14, 0.5, 5.0)\n\tuassert.True(t, got == 3.0, \"expected 3 tokens after refill\")\n\n\t// No time elapsed -\u003e unchanged (but clamped to cap).\n\tgot = refill(2.0, 10, 10, 0.5, 5.0)\n\tuassert.True(t, got == 2.0, \"no elapsed ticks should not add tokens\")\n\n\t// Going backwards (now \u003c last) never adds tokens.\n\tgot = refill(2.0, 10, 5, 0.5, 5.0)\n\tuassert.True(t, got == 2.0, \"negative elapsed should not add tokens\")\n}\n\nfunc TestRefillCap(t *testing.T) {\n\t// Long idle period must saturate at burst capacity.\n\tgot := refill(0.0, 0, 1000, 0.5, 5.0)\n\tuassert.True(t, got == 5.0, \"refill must cap at burst\")\n\n\t// Already-full bucket stays full.\n\tgot = refill(5.0, 0, 100, 0.5, 5.0)\n\tuassert.True(t, got == 5.0, \"full bucket stays capped\")\n}\n\nfunc TestTokensToInt(t *testing.T) {\n\tuassert.Equal(t, 3, tokensToInt(3.9))\n\tuassert.Equal(t, 0, tokensToInt(0.4))\n\tuassert.Equal(t, 0, tokensToInt(-2.0))\n\tuassert.Equal(t, 5, tokensToInt(5.0))\n}\n\nfunc TestFmin(t *testing.T) {\n\tuassert.True(t, fmin(1.0, 2.0) == 1.0, \"fmin picks smaller\")\n\tuassert.True(t, fmin(4.0, 2.5) == 2.5, \"fmin picks smaller\")\n\tuassert.True(t, fmin(3.0, 3.0) == 3.0, \"fmin on equals\")\n}\n\nfunc TestNewClampsConfig(t *testing.T) {\n\tl := New(-1, 0) // rate \u003c 0 -\u003e 0, burst \u003c 1 -\u003e 1\n\tr, b := l.Config()\n\tuassert.True(t, r == 0.0, \"rate clamped to 0\")\n\tuassert.True(t, b == 1.0, \"burst clamped to 1\")\n}\n\nfunc TestAllowConsumesAndDenies(t *testing.T) {\n\tl := New(0.5, 5.0)\n\tconst k = \"g1caller\"\n\t// A fresh key starts full (burst=5): first 5 Allow succeed, 6th fails.\n\tfor i := 0; i \u003c 5; i++ {\n\t\tuassert.True(t, l.Allow(k, 0), \"burst token should be granted\")\n\t}\n\tuassert.False(t, l.Allow(k, 0), \"6th call at same tick must be denied\")\n\n\t// After 4 ticks at 0.5/tick, 2 whole tokens refilled -\u003e 2 more allowed.\n\tuassert.True(t, l.Allow(k, 4), \"refilled token granted\")\n\tuassert.True(t, l.Allow(k, 4), \"refilled token granted\")\n\tuassert.False(t, l.Allow(k, 4), \"empty again\")\n}\n\nfunc TestAllowNAtomic(t *testing.T) {\n\tl := New(1, 5.0)\n\tconst k = \"g1caller\"\n\tuassert.False(t, l.AllowN(k, 0, 6), \"cannot take more than burst\")\n\tuassert.Equal(t, 5, l.Tokens(k, 0), \"denied AllowN consumes nothing\")\n\tuassert.True(t, l.AllowN(k, 0, 3), \"3 of 5 taken\")\n\tuassert.Equal(t, 2, l.Tokens(k, 0), \"2 remain\")\n}\n\nfunc TestTokensReadOnly(t *testing.T) {\n\tl := New(0.5, 5.0)\n\tconst k = \"g1caller\"\n\t// Unseen key reports a full bucket without creating it.\n\tuassert.Equal(t, 5, l.Tokens(k, 100), \"unseen key is full\")\n\tuassert.Equal(t, 0, l.Len(), \"Tokens must not create a bucket\")\n\t// Reading does not consume.\n\tuassert.Equal(t, 5, l.Tokens(k, 200), \"still full on second read\")\n}\n\nfunc TestPerKeyIsolation(t *testing.T) {\n\tl := New(0.5, 5.0)\n\tl.Allow(\"g1a\", 0)\n\tuassert.Equal(t, 4, l.Tokens(\"g1a\", 0), \"a spent one\")\n\tuassert.Equal(t, 5, l.Tokens(\"g1b\", 0), \"b untouched\")\n\tuassert.Equal(t, 1, l.Len(), \"only a exists\")\n}\n\nfunc TestIterate(t *testing.T) {\n\tl := New(0.5, 5.0)\n\tl.Allow(\"g1a\", 0)\n\tl.Allow(\"g1b\", 0)\n\tseen := 0\n\tstopped := l.Iterate(0, func(key string, tokens int, last int64) bool {\n\t\tseen++\n\t\treturn false\n\t})\n\tuassert.Equal(t, 2, seen, \"iterate visits every key\")\n\tuassert.False(t, stopped, \"not stopped early\")\n\n\t// Early stop.\n\tcount := 0\n\tstopped = l.Iterate(0, func(key string, tokens int, last int64) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tuassert.Equal(t, 1, count, \"stops after first\")\n\tuassert.True(t, stopped, \"reported as stopped\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ringbuffer","path":"gno.land/p/moul/x/daily/ringbuffer/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/ringbuffer/v0`\n\n**Fixed-capacity FIFO that overwrites its oldest entry** — `New`, `Push`, `Pop`,\n`Peek`, `At`, `Slice`, `Reset`, `Len`, `Cap`, `Full`, `Empty`, `MaxCap`.\n\nThe bounded cousin of a queue, and the bound is the point: on chain an unbounded\nqueue is an unbounded storage bill, whereas a ring buffer's cost is decided once,\nat construction. The right shape for \"last N events\", \"recent messages\", or any\nrolling window.\n\n```go\nimport \"gno.land/p/moul/x/daily/ringbuffer/v0\"\n\nr := ringbuffer.New(3)\nr.Push(\"a\"); r.Push(\"b\"); r.Push(\"c\")\nevicted, dropped := r.Push(\"d\")   // \"a\", true\nr.Slice()                         // [\"b\" \"c\" \"d\"]\n```\n\n`Push` **returns what it evicted**, so a rolling window never loses data\nsilently — the one thing this shape must not do. Backed by a flat slice with\nhead/length indices: no per-element allocation, no shifting on `Pop`. `Pop` and\n`Reset` clear the vacated slots so no reference is pinned after it is logically\ngone.\n\nA zero-capacity buffer stores nothing and says so (`Push` hands the value\nstraight back), and is never reported as `Full` — a buffer that holds nothing\ncannot be full.\n\n**Live demo:** [`r/moul/x/daily/ringbufferdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/ringbufferdemo)\n· render it at [`/r/moul/x/daily/ringbufferdemo/v0`](https://gno.land/r/moul/x/daily/ringbufferdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/ringbuffer/v0\"\ngno = \"0.9\"\n"},{"name":"ringbuffer.gno","body":"// Package ringbuffer is a fixed-capacity FIFO that overwrites its oldest entry\n// when full, as a pure, reusable package.\n//\n// This is the bounded cousin of an unbounded queue, and the bound is the point:\n// on chain an unbounded queue is an unbounded storage bill, whereas a ring\n// buffer's cost is decided once, at construction. It is the right shape for\n// \"last N events\", \"recent messages\", or any rolling window.\n//\n// Backed by a flat slice with head/length indices — no per-element allocation,\n// no shifting on Pop.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/ringbufferdemo](/r/moul/x/daily/ringbufferdemo/v0).\npackage ringbuffer\n\n// MaxCap bounds a buffer so allocation stays predictable.\nconst MaxCap = 4096\n\n// RingBuffer is a fixed-capacity FIFO of strings.\ntype RingBuffer struct {\n\tbuf  []string\n\thead int // index of the oldest element\n\tn    int // number of live elements\n}\n\n// New returns an empty buffer of the given capacity, clamped to [0, MaxCap].\nfunc New(capacity int) *RingBuffer {\n\tif capacity \u003c 0 {\n\t\tcapacity = 0\n\t}\n\tif capacity \u003e MaxCap {\n\t\tcapacity = MaxCap\n\t}\n\treturn \u0026RingBuffer{buf: make([]string, capacity)}\n}\n\n// Cap returns the capacity.\nfunc (r *RingBuffer) Cap() int { return len(r.buf) }\n\n// Len returns how many elements are live.\nfunc (r *RingBuffer) Len() int { return r.n }\n\n// Full reports whether the next Push will overwrite.\nfunc (r *RingBuffer) Full() bool { return len(r.buf) \u003e 0 \u0026\u0026 r.n == len(r.buf) }\n\n// Empty reports whether there is nothing to read.\nfunc (r *RingBuffer) Empty() bool { return r.n == 0 }\n\n// Push appends v. When the buffer is full the OLDEST element is dropped to make\n// room, and that element is returned with dropped=true — losing data silently\n// is the one thing a rolling window must not do.\n//\n// A zero-capacity buffer accepts nothing and reports the value straight back.\nfunc (r *RingBuffer) Push(v string) (evicted string, dropped bool) {\n\tif len(r.buf) == 0 {\n\t\treturn v, true\n\t}\n\tif r.n == len(r.buf) {\n\t\tevicted = r.buf[r.head]\n\t\tr.buf[r.head] = v\n\t\tr.head = (r.head + 1) % len(r.buf)\n\t\treturn evicted, true\n\t}\n\tr.buf[(r.head+r.n)%len(r.buf)] = v\n\tr.n++\n\treturn \"\", false\n}\n\n// Pop removes and returns the oldest element; ok is false when empty.\nfunc (r *RingBuffer) Pop() (v string, ok bool) {\n\tif r.n == 0 {\n\t\treturn \"\", false\n\t}\n\tv = r.buf[r.head]\n\tr.buf[r.head] = \"\" // release the reference; don't pin a string we no longer own\n\tr.head = (r.head + 1) % len(r.buf)\n\tr.n--\n\treturn v, true\n}\n\n// Peek returns the oldest element without removing it.\nfunc (r *RingBuffer) Peek() (v string, ok bool) {\n\tif r.n == 0 {\n\t\treturn \"\", false\n\t}\n\treturn r.buf[r.head], true\n}\n\n// At returns the i-th element counting from the oldest (0 = oldest).\nfunc (r *RingBuffer) At(i int) (v string, ok bool) {\n\tif i \u003c 0 || i \u003e= r.n {\n\t\treturn \"\", false\n\t}\n\treturn r.buf[(r.head+i)%len(r.buf)], true\n}\n\n// Slice returns the live elements oldest-first, as an independent copy.\nfunc (r *RingBuffer) Slice() []string {\n\tout := make([]string, 0, r.n)\n\tfor i := 0; i \u003c r.n; i++ {\n\t\tout = append(out, r.buf[(r.head+i)%len(r.buf)])\n\t}\n\treturn out\n}\n\n// Reset empties the buffer, releasing every stored reference.\nfunc (r *RingBuffer) Reset() {\n\tfor i := range r.buf {\n\t\tr.buf[i] = \"\"\n\t}\n\tr.head, r.n = 0, 0\n}\n"},{"name":"ringbuffer_test.gno","body":"package ringbuffer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPushPopFIFO(t *testing.T) {\n\tr := New(3)\n\tr.Push(\"a\")\n\tr.Push(\"b\")\n\tuassert.Equal(t, 2, r.Len())\n\tv, ok := r.Pop()\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"a\", v)\n\tv, _ = r.Pop()\n\tuassert.Equal(t, \"b\", v)\n\t_, ok = r.Pop()\n\tuassert.False(t, ok)\n}\n\n// The defining behaviour: full means overwrite the oldest, and say so.\nfunc TestOverwriteOldest(t *testing.T) {\n\tr := New(3)\n\tfor _, s := range []string{\"a\", \"b\", \"c\"} {\n\t\tev, dropped := r.Push(s)\n\t\tuassert.False(t, dropped)\n\t\tuassert.Equal(t, \"\", ev)\n\t}\n\tuassert.True(t, r.Full())\n\tev, dropped := r.Push(\"d\")\n\tuassert.True(t, dropped)\n\tuassert.Equal(t, \"a\", ev) // the OLDEST went, not the newest\n\tuassert.Equal(t, \"b,c,d\", strings.Join(r.Slice(), \",\"))\n\tuassert.Equal(t, 3, r.Len())\n}\n\n// Wrapping must not corrupt order — the classic ring-buffer bug.\nfunc TestWrapAroundKeepsOrder(t *testing.T) {\n\tr := New(3)\n\tfor _, s := range []string{\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"} {\n\t\tr.Push(s)\n\t}\n\tuassert.Equal(t, \"5,6,7\", strings.Join(r.Slice(), \",\"))\n\tv, _ := r.Peek()\n\tuassert.Equal(t, \"5\", v)\n}\n\n// Interleaving Pop and Push moves head and tail independently.\nfunc TestInterleavedPushPop(t *testing.T) {\n\tr := New(3)\n\tr.Push(\"a\")\n\tr.Push(\"b\")\n\tr.Pop() // drop a\n\tr.Push(\"c\")\n\tr.Push(\"d\") // fills: b,c,d\n\tuassert.Equal(t, \"b,c,d\", strings.Join(r.Slice(), \",\"))\n\tev, dropped := r.Push(\"e\")\n\tuassert.True(t, dropped)\n\tuassert.Equal(t, \"b\", ev)\n\tuassert.Equal(t, \"c,d,e\", strings.Join(r.Slice(), \",\"))\n}\n\nfunc TestAt(t *testing.T) {\n\tr := New(3)\n\tr.Push(\"a\")\n\tr.Push(\"b\")\n\tv, ok := r.At(0)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"a\", v) // 0 is the OLDEST\n\tv, _ = r.At(1)\n\tuassert.Equal(t, \"b\", v)\n\t_, ok = r.At(2)\n\tuassert.False(t, ok)\n\t_, ok = r.At(-1)\n\tuassert.False(t, ok)\n}\n\n// A zero-capacity buffer stores nothing and admits it rather than pretending.\nfunc TestZeroCapacity(t *testing.T) {\n\tr := New(0)\n\tuassert.Equal(t, 0, r.Cap())\n\tev, dropped := r.Push(\"x\")\n\tuassert.True(t, dropped)\n\tuassert.Equal(t, \"x\", ev)\n\tuassert.True(t, r.Empty())\n\tuassert.False(t, r.Full()) // a buffer that holds nothing is never \"full\"\n\tuassert.Equal(t, 0, len(r.Slice()))\n}\n\nfunc TestEmptyPeekPop(t *testing.T) {\n\tr := New(2)\n\t_, ok := r.Peek()\n\tuassert.False(t, ok)\n\t_, ok = r.Pop()\n\tuassert.False(t, ok)\n}\n\nfunc TestReset(t *testing.T) {\n\tr := New(3)\n\tr.Push(\"a\")\n\tr.Push(\"b\")\n\tr.Reset()\n\tuassert.True(t, r.Empty())\n\tuassert.Equal(t, 0, r.Len())\n\tr.Push(\"z\")\n\tuassert.Equal(t, \"z\", strings.Join(r.Slice(), \",\"))\n}\n\nfunc TestSliceIsACopy(t *testing.T) {\n\tr := New(3)\n\tr.Push(\"a\")\n\ts := r.Slice()\n\ts[0] = \"mutated\"\n\tuassert.Equal(t, \"a\", strings.Join(r.Slice(), \",\"))\n}\n\nfunc TestCapClamped(t *testing.T) {\n\tuassert.Equal(t, 0, New(-5).Cap())\n\tuassert.Equal(t, MaxCap, New(MaxCap+100).Cap())\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rle","path":"gno.land/p/moul/x/daily/rle/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/rle/v0`\n\n**Run-length encoding** — `Encode`, `Decode`, `Ratio`, `MaxLen`.\n\nRuns of a repeated byte collapse to `\u003ccount\u003e\u003cchar\u003e`, counts in decimal:\n`\"aaabbc\"` → `\"3a2b1c\"`.\n\n```go\nimport \"gno.land/p/moul/x/daily/rle/v0\"\n\nrle.Encode(\"aaabbc\")   // \"3a2b1c\", nil\nrle.Decode(\"3a2b1c\")   // \"aaabbc\", nil\nrle.Ratio(\"abcdef\", \"1a1b1c1d1e1f\")  // 200 — bigger than the input!\n```\n\n**Every run carries a count, including runs of one.** A uniform grammar is\ncheaper to decode and impossible to get subtly wrong, at the cost of expanding\ndata that has no runs. That trade is deliberate and visible: `Ratio` returns\nover 100 when the \"compression\" grew the data, because **RLE only wins on runny\ninput** and pretending otherwise would be dishonest.\n\n**Digits are rejected** by `Encode` — in the output they would be\nindistinguishable from a run count, so a round-trip would silently return the\nwrong string. Better to refuse.\n\n`Decode` bounds the *expanded* size too, not just its input: `\"999999x\"` is\nseven bytes that would otherwise become a megabyte.\n\n**Live demo:** [`r/moul/x/daily/rledemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/rledemo)\n· render it at [`/r/moul/x/daily/rledemo/v0`](https://gno.land/r/moul/x/daily/rledemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/rle/v0\"\ngno = \"0.9\"\n"},{"name":"rle.gno","body":"// Package rle implements run-length encoding as a pure, reusable package: runs\n// of a repeated byte collapse to a count and the byte.\n//\n// The encoding is `\u003ccount\u003e\u003cchar\u003e` with counts in decimal, e.g. \"aaabbc\" →\n// \"3a2b1c\". Every run is emitted with its count, including runs of one — a\n// uniform grammar is cheaper to decode and impossible to get subtly wrong,\n// at the cost of expanding data that has no runs at all. RLE is a *win only on\n// runny data*; Encode can legitimately produce output longer than its input,\n// and the demo shows exactly that case rather than hiding it.\n//\n// Digits cannot appear in the input, since they would be indistinguishable from\n// a count on the way back; Encode rejects them rather than round-tripping wrong.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/rledemo](/r/moul/x/daily/rledemo/v0).\npackage rle\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// MaxLen bounds input so encode/decode gas stays predictable.\nconst MaxLen = 4096\n\nvar (\n\t// ErrTooLong is returned when input exceeds MaxLen.\n\tErrTooLong = errors.New(\"rle: input too long\")\n\t// ErrDigit is returned when input contains a digit, which would be\n\t// ambiguous with a run count.\n\tErrDigit = errors.New(\"rle: input must not contain digits\")\n\t// ErrMalformed is returned when decoding input that is not \u003ccount\u003e\u003cchar\u003e.\n\tErrMalformed = errors.New(\"rle: malformed input\")\n)\n\n// Encode collapses runs of repeated bytes into \u003ccount\u003e\u003cchar\u003e pairs.\nfunc Encode(s string) (string, error) {\n\tif len(s) \u003e MaxLen {\n\t\treturn \"\", ErrTooLong\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif s[i] \u003e= '0' \u0026\u0026 s[i] \u003c= '9' {\n\t\t\treturn \"\", ErrDigit\n\t\t}\n\t}\n\tif s == \"\" {\n\t\treturn \"\", nil\n\t}\n\tvar b strings.Builder\n\trun := 1\n\tfor i := 1; i \u003c= len(s); i++ {\n\t\tif i \u003c len(s) \u0026\u0026 s[i] == s[i-1] {\n\t\t\trun++\n\t\t\tcontinue\n\t\t}\n\t\tb.WriteString(strconv.Itoa(run))\n\t\tb.WriteByte(s[i-1])\n\t\trun = 1\n\t}\n\treturn b.String(), nil\n}\n\n// Decode expands \u003ccount\u003e\u003cchar\u003e pairs back into the original string.\nfunc Decode(s string) (string, error) {\n\tif len(s) \u003e MaxLen {\n\t\treturn \"\", ErrTooLong\n\t}\n\tvar b strings.Builder\n\ti := 0\n\tfor i \u003c len(s) {\n\t\tj := i\n\t\tfor j \u003c len(s) \u0026\u0026 s[j] \u003e= '0' \u0026\u0026 s[j] \u003c= '9' {\n\t\t\tj++\n\t\t}\n\t\tif j == i || j == len(s) { // no count, or a count with no character\n\t\t\treturn \"\", ErrMalformed\n\t\t}\n\t\tn, err := strconv.Atoi(s[i:j])\n\t\tif err != nil || n \u003c= 0 {\n\t\t\treturn \"\", ErrMalformed\n\t\t}\n\t\tif b.Len()+n \u003e MaxLen {\n\t\t\treturn \"\", ErrTooLong // a short input can decode to an enormous one\n\t\t}\n\t\tb.WriteString(strings.Repeat(string(s[j]), n))\n\t\ti = j + 1\n\t}\n\treturn b.String(), nil\n}\n\n// Ratio returns len(encoded)/len(original) as a percentage, rounded down.\n// Over 100 means the encoding made the data BIGGER, which is the honest\n// outcome for input without runs.\nfunc Ratio(original, encoded string) int {\n\tif len(original) == 0 {\n\t\treturn 0\n\t}\n\treturn len(encoded) * 100 / len(original)\n}\n"},{"name":"rle_test.gno","body":"package rle\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestEncode(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"a\", \"1a\"},\n\t\t{\"aaa\", \"3a\"},\n\t\t{\"aaabbc\", \"3a2b1c\"},\n\t\t{\"abc\", \"1a1b1c\"},\n\t\t{\"aabbaa\", \"2a2b2a\"}, // runs, not totals\n\t}\n\tfor _, c := range cases {\n\t\tgot, err := Encode(c.in)\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, c.want, got)\n\t}\n}\n\nfunc TestDecode(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"3a\", \"aaa\"},\n\t\t{\"3a2b1c\", \"aaabbc\"},\n\t\t{\"12x\", strings.Repeat(\"x\", 12)}, // multi-digit counts\n\t}\n\tfor _, c := range cases {\n\t\tgot, err := Decode(c.in)\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, c.want, got)\n\t}\n}\n\n// The property that matters: decode(encode(s)) == s.\nfunc TestRoundTrip(t *testing.T) {\n\tfor _, s := range []string{\"a\", \"aaa\", \"aaabbc\", \"abcdef\", \"zzzzzzzzzzzz\", \"ab\"} {\n\t\tenc, err := Encode(s)\n\t\tuassert.NoError(t, err)\n\t\tdec, err2 := Decode(enc)\n\t\tuassert.NoError(t, err2)\n\t\tuassert.Equal(t, s, dec)\n\t}\n}\n\n// Digits would be ambiguous with a run count, so they are refused up front.\nfunc TestEncodeRejectsDigits(t *testing.T) {\n\t_, err := Encode(\"ab3c\")\n\tuassert.ErrorIs(t, err, ErrDigit)\n}\n\nfunc TestDecodeMalformed(t *testing.T) {\n\tfor _, s := range []string{\"a\", \"abc\", \"3\", \"3a2\", \"0a\"} {\n\t\t_, err := Decode(s)\n\t\tuassert.Error(t, err)\n\t}\n}\n\n// A short encoded input must not be able to blow up memory on decode.\nfunc TestDecodeExpansionIsBounded(t *testing.T) {\n\t_, err := Decode(\"999999x\")\n\tuassert.ErrorIs(t, err, ErrTooLong)\n}\n\nfunc TestEncodeTooLong(t *testing.T) {\n\t_, err := Encode(strings.Repeat(\"a\", MaxLen+1))\n\tuassert.ErrorIs(t, err, ErrTooLong)\n}\n\n// RLE is a win only on runny data — say so rather than hide it.\nfunc TestRatioCanExceed100(t *testing.T) {\n\tenc, _ := Encode(\"abcdef\")\n\tuassert.Equal(t, \"1a1b1c1d1e1f\", enc)\n\tuassert.Equal(t, 200, Ratio(\"abcdef\", enc)) // twice the size!\n\tenc2, _ := Encode(strings.Repeat(\"a\", 100))\n\tuassert.Equal(t, 4, Ratio(strings.Repeat(\"a\", 100), enc2))\n\tuassert.Equal(t, 0, Ratio(\"\", \"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"romannum","path":"gno.land/p/moul/x/daily/romannum/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/romannum/v0`\n\n**Roman-numeral converter** — `ToRoman`, `FromRoman`.\n\nA pure port of the classic kata, valid for **1..3999**. `ToRoman` uses greedy\nsubtractive notation (panics out of range); `FromRoman` accepts a numeral only\nif it is canonical (it must round-trip through `ToRoman`), so malformed forms\nlike `IIII`, `VV`, or `IC` are rejected. Deterministic — no time, randomness, or\nI/O — and free of any realm coupling.\n\n```go\nimport \"gno.land/p/moul/x/daily/romannum/v0\"\n\ns := romannum.ToRoman(2024) // \"MMXXIV\"\nn := romannum.FromRoman(s)   // 2024 (panics on a malformed numeral)\n```\n\n**Live demo:** [`r/moul/x/daily/romannumdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/romannumdemo)\n· render it at [`/r/moul/x/daily/romannumdemo/v0`](https://gno.land/r/moul/x/daily/romannumdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/romannum/v0\"\ngno = \"0.9\"\n"},{"name":"romannum.gno","body":"// Package romannum is a pure port of the classic Roman-numeral converter kata:\n// ToRoman / FromRoman, valid for 1..3999. Deterministic — no time, randomness\n// or I/O — and free of any realm coupling, so it is reusable as a library.\n//\n// A live demo of this package (an interactive integer↔Roman converter) is at\n// [r/moul/x/daily/romannumdemo](/r/moul/x/daily/romannumdemo/v0).\npackage romannum\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n// romanUnits is the greedy subtractive-notation table, largest value first.\nvar romanUnits = []struct {\n\tval int\n\tsym string\n}{\n\t{1000, \"M\"}, {900, \"CM\"}, {500, \"D\"}, {400, \"CD\"},\n\t{100, \"C\"}, {90, \"XC\"}, {50, \"L\"}, {40, \"XL\"},\n\t{10, \"X\"}, {9, \"IX\"}, {5, \"V\"}, {4, \"IV\"}, {1, \"I\"},\n}\n\n// ToRoman renders an integer in 1..3999 as a Roman numeral.\n// It panics if n is out of range.\nfunc ToRoman(n int) string {\n\tif n \u003c 1 || n \u003e 3999 {\n\t\tpanic(\"romannum: out of range (want 1..3999): \" + strconv.Itoa(n))\n\t}\n\tvar b strings.Builder\n\tfor _, u := range romanUnits {\n\t\tfor n \u003e= u.val {\n\t\t\tb.WriteString(u.sym)\n\t\t\tn -= u.val\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// FromRoman parses a Roman numeral back to an integer.\n// It panics on any malformed input (e.g. \"IIII\", \"IC\", \"VV\").\nfunc FromRoman(s string) int {\n\tn, ok := parseRoman(s)\n\tif !ok {\n\t\tpanic(\"romannum: invalid roman numeral: \" + s)\n\t}\n\treturn n\n}\n\n// charVal maps a single Roman digit to its value, or 0 if unknown.\nfunc charVal(c byte) int {\n\tswitch c {\n\tcase 'I':\n\t\treturn 1\n\tcase 'V':\n\t\treturn 5\n\tcase 'X':\n\t\treturn 10\n\tcase 'L':\n\t\treturn 50\n\tcase 'C':\n\t\treturn 100\n\tcase 'D':\n\t\treturn 500\n\tcase 'M':\n\t\treturn 1000\n\t}\n\treturn 0\n}\n\n// parseRoman is the pure, panic-free core used by FromRoman.\n// It returns (value, true) only for a canonical numeral: it accepts input\n// iff ToRoman(value) reproduces it exactly, which rejects malformed forms.\nfunc parseRoman(s string) (int, bool) {\n\ts = strings.ToUpper(strings.TrimSpace(s))\n\tif s == \"\" {\n\t\treturn 0, false\n\t}\n\ttotal, prev := 0, 0\n\tfor i := len(s) - 1; i \u003e= 0; i-- {\n\t\tv := charVal(s[i])\n\t\tif v == 0 {\n\t\t\treturn 0, false\n\t\t}\n\t\tif v \u003c prev {\n\t\t\ttotal -= v\n\t\t} else {\n\t\t\ttotal += v\n\t\t\tprev = v\n\t\t}\n\t}\n\tif total \u003c 1 || total \u003e 3999 || ToRoman(total) != s {\n\t\treturn 0, false\n\t}\n\treturn total, true\n}\n"},{"name":"romannum_test.gno","body":"package romannum\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestToRoman(t *testing.T) {\n\tcases := []struct {\n\t\tin   int\n\t\twant string\n\t}{\n\t\t{1, \"I\"},\n\t\t{4, \"IV\"},\n\t\t{9, \"IX\"},\n\t\t{40, \"XL\"},\n\t\t{90, \"XC\"},\n\t\t{400, \"CD\"},\n\t\t{900, \"CM\"},\n\t\t{1994, \"MCMXCIV\"},\n\t\t{2024, \"MMXXIV\"},\n\t\t{3999, \"MMMCMXCIX\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, ToRoman(c.in))\n\t}\n}\n\nfunc TestParseRoman(t *testing.T) {\n\t// canonical numerals round-trip back to their value\n\tgood := []struct {\n\t\tin   string\n\t\twant int\n\t}{\n\t\t{\"I\", 1},\n\t\t{\"IV\", 4},\n\t\t{\"mmxxiv\", 2024}, // case-insensitive\n\t\t{\" XLII \", 42},   // trimmed\n\t\t{\"MMMCMXCIX\", 3999},\n\t}\n\tfor _, c := range good {\n\t\tgot, ok := parseRoman(c.in)\n\t\tuassert.True(t, ok)\n\t\tuassert.Equal(t, c.want, got)\n\t}\n\n\t// malformed / non-canonical forms are rejected\n\tbad := []string{\"\", \"IIII\", \"VV\", \"IC\", \"MMMM\", \"XIↃ\", \"ABC\"}\n\tfor _, s := range bad {\n\t\t_, ok := parseRoman(s)\n\t\tuassert.False(t, ok)\n\t}\n}\n\nfunc TestRoundTrip(t *testing.T) {\n\tfor n := 1; n \u003c= 3999; n++ {\n\t\tgot, ok := parseRoman(ToRoman(n))\n\t\tuassert.True(t, ok)\n\t\tuassert.Equal(t, n, got)\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rot13","path":"gno.land/p/moul/x/daily/rot13/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/rot13/v0`\n\n**ROT13 / Caesar letter-rotation cipher** — `Rot13`, `Caesar`.\n\nPure `strings.Map` logic over ASCII letters; everything else passes through\nuntouched. ROT13 shifts each letter 13 places and, since the alphabet has 26\nletters, is its own inverse. `Caesar` generalizes it to any shift (negative and\nlarge shifts normalized into `[0,26)`). Ports Go's classic ROT13 teaching\nexample.\n\n```go\nimport \"gno.land/p/moul/x/daily/rot13/v0\"\n\ns := rot13.Rot13(\"Hello, Gno!\") // \"Uryyb, Tab!\"\nd := rot13.Rot13(s)             // \"Hello, Gno!\" (own inverse)\nc := rot13.Caesar(\"attack\", 3)  // \"dwwdfn\"\n```\n\n**Live demo:** [`r/moul/x/daily/rot13demo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/rot13demo)\n· render it at [`/r/moul/x/daily/rot13demo/v0`](https://gno.land/r/moul/x/daily/rot13demo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/rot13/v0\"\ngno = \"0.9\"\n"},{"name":"rot13.gno","body":"// Package rot13 ports Go's classic ROT13 example — the one used to teach\n// strings.Map and io.Reader in the standard library docs — to gno as a reusable\n// pure package. The core is a pure letter-rotation cipher over ASCII: ROT13\n// shifts each letter 13 places, which (since the alphabet has 26 letters)\n// makes ROT13 its own inverse. Caesar generalizes it to any shift.\n//\n// Everything here is pure strings/unicode logic: no state, no randomness,\n// no clock.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/rot13demo](/r/moul/x/daily/rot13demo/v0).\npackage rot13\n\nimport \"strings\"\n\n// Rot13 applies the ROT13 substitution cipher, rotating ASCII letters by 13\n// and leaving every other byte untouched. Because 13 is half of 26,\n// Rot13(Rot13(s)) == s — the cipher is its own inverse. This mirrors the\n// canonical strings.Map example from the Go docs.\nfunc Rot13(s string) string {\n\treturn strings.Map(rot13Rune, s)\n}\n\n// rot13Rune is the mapping function handed to strings.Map — the heart of the\n// classic example.\nfunc rot13Rune(r rune) rune {\n\tswitch {\n\tcase r \u003e= 'a' \u0026\u0026 r \u003c= 'z':\n\t\treturn 'a' + (r-'a'+13)%26\n\tcase r \u003e= 'A' \u0026\u0026 r \u003c= 'Z':\n\t\treturn 'A' + (r-'A'+13)%26\n\t}\n\treturn r\n}\n\n// Caesar generalizes ROT13 to an arbitrary shift. Negative and large shifts\n// are normalized into [0,26). Only ASCII letters move; anything else passes\n// through unchanged. Caesar(s, 13) is exactly Rot13(s).\nfunc Caesar(s string, shift int) string {\n\tsh := rune(((shift % 26) + 26) % 26)\n\treturn strings.Map(func(r rune) rune {\n\t\tswitch {\n\t\tcase r \u003e= 'a' \u0026\u0026 r \u003c= 'z':\n\t\t\treturn 'a' + (r-'a'+sh)%26\n\t\tcase r \u003e= 'A' \u0026\u0026 r \u003c= 'Z':\n\t\t\treturn 'A' + (r-'A'+sh)%26\n\t\t}\n\t\treturn r\n\t}, s)\n}\n"},{"name":"rot13_test.gno","body":"package rot13\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRot13(t *testing.T) {\n\tcases := []struct {\n\t\tin, want string\n\t}{\n\t\t{\"\", \"\"},\n\t\t{\"Hello\", \"Uryyb\"},\n\t\t{\"Uryyb\", \"Hello\"},                     // decode\n\t\t{\"abcxyz\", \"nopklm\"},                   // wraps within lowercase\n\t\t{\"ABCXYZ\", \"NOPKLM\"},                   // wraps within uppercase\n\t\t{\"Hello, Gno! 123\", \"Uryyb, Tab! 123\"}, // punctuation \u0026 digits untouched\n\t}\n\tfor _, c := range cases {\n\t\tgot := Rot13(c.in)\n\t\tuassert.Equal(t, c.want, got, \"Rot13(%q)\", c.in)\n\t}\n}\n\nfunc TestRot13IsItsOwnInverse(t *testing.T) {\n\tinputs := []string{\"\", \"Hello, Gno!\", \"The quick brown fox\", \"MixedCASE 42!\"}\n\tfor _, in := range inputs {\n\t\tuassert.Equal(t, in, Rot13(Rot13(in)), \"Rot13(Rot13(%q)) should round-trip\", in)\n\t}\n}\n\nfunc TestCaesar(t *testing.T) {\n\tcases := []struct {\n\t\tin    string\n\t\tshift int\n\t\twant  string\n\t}{\n\t\t{\"abc\", 1, \"bcd\"},\n\t\t{\"xyz\", 3, \"abc\"},                  // wraps around the end\n\t\t{\"ABC\", 25, \"ZAB\"},                 // large shift, uppercase\n\t\t{\"Hello\", 0, \"Hello\"},              // no-op\n\t\t{\"Hello\", 26, \"Hello\"},             // full rotation\n\t\t{\"bcd\", -1, \"abc\"},                 // negative shift\n\t\t{\"a-b c!\", 1, \"b-c d!\"},            // non-letters untouched\n\t\t{\"Hello, Gno!\", 13, \"Uryyb, Tab!\"}, // shift 13 == ROT13\n\t}\n\tfor _, c := range cases {\n\t\tgot := Caesar(c.in, c.shift)\n\t\tuassert.Equal(t, c.want, got, \"Caesar(\"+strconv.Quote(c.in)+\", \"+strconv.Itoa(c.shift)+\")\")\n\t}\n}\n\nfunc TestCaesarEqualsRot13At13(t *testing.T) {\n\tinputs := []string{\"Hello, Gno!\", \"The quick brown fox jumps\"}\n\tfor _, in := range inputs {\n\t\tuassert.Equal(t, Rot13(in), Caesar(in, 13), \"Caesar(%q,13) should equal Rot13\", in)\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"semver","path":"gno.land/p/moul/x/daily/semver/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/semver/v0`\n\n**Semantic Versioning 2.0.0 parser + comparator** — `Parse`, `Compare`, and the\n`Version` type (with `Canonical`).\n\nAn on-chain port of the core of Go's [`golang.org/x/mod/semver`](https://pkg.go.dev/golang.org/x/mod/semver)\n(and the spirit of [`Masterminds/semver`](https://github.com/Masterminds/semver)).\nParses `vMAJOR.MINOR.PATCH[-prerelease][+build]` and compares with correct\nprecedence: numeric fields compare numerically (so `1.2.3 \u003c 1.2.10`), a\npre-release ranks below its release (`1.0.0-alpha \u003c 1.0.0`), numeric pre-release\nidentifiers rank below alphanumeric ones, and build metadata is ignored. Pure\nand deterministic — no `avl`, no chain imports, no ambient state.\n\n```go\nimport \"gno.land/p/moul/x/daily/semver/v0\"\n\nv, err := semver.Parse(\"v1.0.0-rc.1+ci.7\") // Version{Major:1, Pre:[\"rc\",\"1\"], …}\nsemver.Compare(\"1.2.3\", \"1.2.10\")          // -1\nv.Canonical()                              // \"1.0.0-rc.1+ci.7\"\n```\n\n**Live demo:** [`r/moul/x/daily/semverdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/semverdemo)\n· render it at [`/r/moul/x/daily/semverdemo/v0`](https://gno.land/r/moul/x/daily/semverdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/semver/v0\"\ngno = \"0.9\"\n"},{"name":"semver.gno","body":"// Package semver is an on-chain port of the core of golang.org/x/mod/semver\n// (and the spirit of github.com/Masterminds/semver): parse \"vMAJOR.MINOR.PATCH\n// [-prerelease][+build]\" strings and compare them with correct Semantic\n// Versioning 2.0.0 precedence. Pure and deterministic — no time, randomness,\n// goroutines, or I/O.\n//\n// This package holds only the pure parsing/comparison API. For a live,\n// stateful gnoweb demo that imports it and keeps an on-chain \"submitted\n// versions\" board, see\n// [r/moul/x/daily/semverdemo](/r/moul/x/daily/semverdemo/v0).\npackage semver\n\nimport (\n\t\"errors\"\n\t\"strings\"\n)\n\n// Version is a parsed semantic version. Build metadata is retained for display\n// but, per the spec, is ignored when comparing precedence.\ntype Version struct {\n\tMajor, Minor, Patch int\n\tPre                 []string // pre-release identifiers (dot-separated)\n\tBuild               string   // build metadata (after '+')\n\tOrig                string   // original input\n}\n\nvar errBadVersion = errors.New(\"invalid semantic version\")\n\n// Parse reads \"vMAJOR.MINOR.PATCH[-prerelease][+build]\". The leading 'v' is\n// optional. Numeric fields must be non-empty digit runs without leading zeros.\nfunc Parse(s string) (Version, error) {\n\tv := Version{Orig: s}\n\tbody := strings.TrimPrefix(s, \"v\")\n\n\tif i := strings.IndexByte(body, '+'); i \u003e= 0 {\n\t\tv.Build = body[i+1:]\n\t\tbody = body[:i]\n\t\tif v.Build == \"\" {\n\t\t\treturn Version{}, errBadVersion\n\t\t}\n\t}\n\tif i := strings.IndexByte(body, '-'); i \u003e= 0 {\n\t\tpre := body[i+1:]\n\t\tbody = body[:i]\n\t\tv.Pre = strings.Split(pre, \".\")\n\t\tfor _, id := range v.Pre {\n\t\t\tif !validPreIdent(id) {\n\t\t\t\treturn Version{}, errBadVersion\n\t\t\t}\n\t\t}\n\t}\n\n\tparts := strings.Split(body, \".\")\n\tif len(parts) != 3 {\n\t\treturn Version{}, errBadVersion\n\t}\n\tnums := [3]int{}\n\tfor i, p := range parts {\n\t\tn, ok := parseNum(p)\n\t\tif !ok {\n\t\t\treturn Version{}, errBadVersion\n\t\t}\n\t\tnums[i] = n\n\t}\n\tv.Major, v.Minor, v.Patch = nums[0], nums[1], nums[2]\n\treturn v, nil\n}\n\n// Compare returns -1, 0, or +1 as a \u003c b, a == b, or a \u003e b under semver\n// precedence. Unparseable inputs sort after everything valid (and equal to\n// each other), so Compare never panics.\nfunc Compare(a, b string) int {\n\tva, ea := Parse(a)\n\tvb, eb := Parse(b)\n\tswitch {\n\tcase ea != nil \u0026\u0026 eb != nil:\n\t\treturn 0\n\tcase ea != nil:\n\t\treturn 1\n\tcase eb != nil:\n\t\treturn -1\n\t}\n\treturn va.compare(vb)\n}\n\nfunc (v Version) compare(o Version) int {\n\tif c := cmpInt(v.Major, o.Major); c != 0 {\n\t\treturn c\n\t}\n\tif c := cmpInt(v.Minor, o.Minor); c != 0 {\n\t\treturn c\n\t}\n\tif c := cmpInt(v.Patch, o.Patch); c != 0 {\n\t\treturn c\n\t}\n\treturn comparePre(v.Pre, o.Pre)\n}\n\n// comparePre implements SemVer §11: a version WITH a pre-release has lower\n// precedence than the same version WITHOUT one.\nfunc comparePre(a, b []string) int {\n\tif len(a) == 0 \u0026\u0026 len(b) == 0 {\n\t\treturn 0\n\t}\n\tif len(a) == 0 { // a is a release, b is a pre-release\n\t\treturn 1\n\t}\n\tif len(b) == 0 {\n\t\treturn -1\n\t}\n\tfor i := 0; i \u003c len(a) \u0026\u0026 i \u003c len(b); i++ {\n\t\tif c := compareIdent(a[i], b[i]); c != 0 {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn cmpInt(len(a), len(b))\n}\n\n// compareIdent: numeric identifiers compare numerically and always rank below\n// alphanumeric ones; alphanumerics compare in ASCII order.\nfunc compareIdent(a, b string) int {\n\tan, aNum := parseNum(a)\n\tbn, bNum := parseNum(b)\n\tswitch {\n\tcase aNum \u0026\u0026 bNum:\n\t\treturn cmpInt(an, bn)\n\tcase aNum:\n\t\treturn -1\n\tcase bNum:\n\t\treturn 1\n\t}\n\treturn strings.Compare(a, b)\n}\n\nfunc cmpInt(a, b int) int {\n\tswitch {\n\tcase a \u003c b:\n\t\treturn -1\n\tcase a \u003e b:\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// parseNum accepts a non-empty run of ASCII digits with no leading zero (except\n// \"0\" itself), returning the value and whether it qualified.\nfunc parseNum(s string) (int, bool) {\n\tif s == \"\" {\n\t\treturn 0, false\n\t}\n\tif len(s) \u003e 1 \u0026\u0026 s[0] == '0' {\n\t\treturn 0, false\n\t}\n\tn := 0\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c \u003c '0' || c \u003e '9' {\n\t\t\treturn 0, false\n\t\t}\n\t\tn = n*10 + int(c-'0')\n\t}\n\treturn n, true\n}\n\n// validPreIdent allows [0-9A-Za-z-] and rejects empty identifiers.\nfunc validPreIdent(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tok := (c \u003e= '0' \u0026\u0026 c \u003c= '9') || (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') ||\n\t\t\t(c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || c == '-'\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Canonical renders the parsed version back to a canonical string.\nfunc (v Version) Canonical() string {\n\ts := ufmt(v.Major) + \".\" + ufmt(v.Minor) + \".\" + ufmt(v.Patch)\n\tif len(v.Pre) \u003e 0 {\n\t\ts += \"-\" + strings.Join(v.Pre, \".\")\n\t}\n\tif v.Build != \"\" {\n\t\ts += \"+\" + v.Build\n\t}\n\treturn s\n}\n\nfunc ufmt(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b []byte\n\tfor n \u003e 0 {\n\t\tb = append([]byte{byte('0' + n%10)}, b...)\n\t\tn /= 10\n\t}\n\treturn string(b)\n}\n"},{"name":"semver_test.gno","body":"package semver\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestParse(t *testing.T) {\n\tcases := []struct {\n\t\tin    string\n\t\tok    bool\n\t\tmajor int\n\t\tminor int\n\t\tpatch int\n\t\tnpre  int\n\t\tbuild string\n\t}{\n\t\t{\"1.2.3\", true, 1, 2, 3, 0, \"\"},\n\t\t{\"v1.2.3\", true, 1, 2, 3, 0, \"\"},\n\t\t{\"1.0.0-alpha\", true, 1, 0, 0, 1, \"\"},\n\t\t{\"1.0.0-alpha.1\", true, 1, 0, 0, 2, \"\"},\n\t\t{\"2.0.0+build.5\", true, 2, 0, 0, 0, \"build.5\"},\n\t\t{\"1.0.0-rc.1+ci.7\", true, 1, 0, 0, 2, \"ci.7\"},\n\t\t{\"1.2\", false, 0, 0, 0, 0, \"\"},\n\t\t{\"1.2.3.4\", false, 0, 0, 0, 0, \"\"},\n\t\t{\"1.2.x\", false, 0, 0, 0, 0, \"\"},\n\t\t{\"01.2.3\", false, 0, 0, 0, 0, \"\"},\n\t\t{\"1.0.0-\", false, 0, 0, 0, 0, \"\"},\n\t\t{\"\", false, 0, 0, 0, 0, \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tv, err := Parse(c.in)\n\t\tif !c.ok {\n\t\t\tuassert.Error(t, err, \"expected error for \"+c.in)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.NoError(t, err, \"unexpected error for \"+c.in)\n\t\tuassert.Equal(t, c.major, v.Major, \"major \"+c.in)\n\t\tuassert.Equal(t, c.minor, v.Minor, \"minor \"+c.in)\n\t\tuassert.Equal(t, c.patch, v.Patch, \"patch \"+c.in)\n\t\tuassert.Equal(t, c.npre, len(v.Pre), \"pre count \"+c.in)\n\t\tuassert.Equal(t, c.build, v.Build, \"build \"+c.in)\n\t}\n}\n\nfunc TestCompare(t *testing.T) {\n\tcases := []struct {\n\t\ta, b string\n\t\twant int\n\t}{\n\t\t// numeric fields compare numerically, not lexically\n\t\t{\"1.2.3\", \"1.2.10\", -1},\n\t\t{\"1.2.10\", \"1.2.3\", 1},\n\t\t{\"1.0.0\", \"1.0.0\", 0},\n\t\t{\"2.0.0\", \"1.9.9\", 1},\n\t\t{\"1.1.0\", \"1.0.9\", 1},\n\t\t// pre-release \u003c release\n\t\t{\"1.0.0-alpha\", \"1.0.0\", -1},\n\t\t{\"1.0.0\", \"1.0.0-alpha\", 1},\n\t\t{\"1.0.0-rc.1\", \"1.0.0\", -1},\n\t\t// pre-release ordering per SemVer §11 spec example\n\t\t{\"1.0.0-alpha\", \"1.0.0-alpha.1\", -1},\n\t\t{\"1.0.0-alpha.1\", \"1.0.0-alpha.beta\", -1},\n\t\t{\"1.0.0-alpha.beta\", \"1.0.0-beta\", -1},\n\t\t{\"1.0.0-beta\", \"1.0.0-beta.2\", -1},\n\t\t{\"1.0.0-beta.2\", \"1.0.0-beta.11\", -1},\n\t\t{\"1.0.0-beta.11\", \"1.0.0-rc.1\", -1},\n\t\t// build metadata does not affect precedence\n\t\t{\"1.0.0\", \"1.0.0+build.99\", 0},\n\t\t{\"1.0.0+a\", \"1.0.0+b\", 0},\n\t\t// invalid inputs sort last, equal to each other\n\t\t{\"nope\", \"1.0.0\", 1},\n\t\t{\"1.0.0\", \"nope\", -1},\n\t\t{\"nope\", \"still-bad\", 0},\n\t}\n\tfor _, c := range cases {\n\t\tgot := Compare(c.a, c.b)\n\t\tuassert.Equal(t, c.want, got, c.a+\" vs \"+c.b)\n\t}\n}\n\nfunc TestComparePreHelper(t *testing.T) {\n\tuassert.Equal(t, 0, comparePre(nil, nil), \"both empty\")\n\tuassert.Equal(t, 1, comparePre(nil, []string{\"alpha\"}), \"release \u003e prerelease\")\n\tuassert.Equal(t, -1, comparePre([]string{\"alpha\"}, nil), \"prerelease \u003c release\")\n\tuassert.Equal(t, -1, comparePre([]string{\"1\"}, []string{\"alpha\"}), \"numeric id \u003c alnum id\")\n\tuassert.Equal(t, -1, comparePre([]string{\"alpha\"}, []string{\"alpha\", \"1\"}), \"shorter \u003c longer prefix\")\n}\n\nfunc TestParseNumHelper(t *testing.T) {\n\tn, ok := parseNum(\"0\")\n\tuassert.True(t, ok, \"0 is valid\")\n\tuassert.Equal(t, 0, n, \"0 value\")\n\n\tn, ok = parseNum(\"123\")\n\tuassert.True(t, ok, \"123 valid\")\n\tuassert.Equal(t, 123, n, \"123 value\")\n\n\t_, ok = parseNum(\"00\")\n\tuassert.False(t, ok, \"leading zero invalid\")\n\t_, ok = parseNum(\"12a\")\n\tuassert.False(t, ok, \"non-digit invalid\")\n\t_, ok = parseNum(\"\")\n\tuassert.False(t, ok, \"empty invalid\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"sieve","path":"gno.land/p/moul/x/daily/sieve/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/sieve/v0`\n\n**Sieve of Eratosthenes** — `PrimesUpTo`, `NthPrime`, `IsPrime`, `MaxN`.\n\nA deterministic, allocation-friendly port of Go's classic concurrent prime-sieve\nexample — no goroutines, channels, or clocks, so it runs reproducibly on-chain.\n`MaxN` (10000) bounds the sieve so gas stays predictable.\n\n```go\nimport \"gno.land/p/moul/x/daily/sieve/v0\"\n\nprimes := sieve.PrimesUpTo(30)  // [2 3 5 7 11 13 17 19 23 29]\np := sieve.NthPrime(10)         // 29 (1-indexed; 0 beyond MaxN)\nok := sieve.IsPrime(9973)       // true\n```\n\n**Live demo:** [`r/moul/x/daily/sievedemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/sievedemo)\n· render it at [`/r/moul/x/daily/sievedemo/v0`](https://gno.land/r/moul/x/daily/sievedemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/sieve/v0\"\ngno = \"0.9\"\n"},{"name":"sieve.gno","body":"// Package sieve is an on-chain port of Go's classic concurrent prime sieve\n// (the \"prime sieve\" example from the Go tour / Go source docs), implemented\n// as a deterministic, allocation-friendly Sieve of Eratosthenes so it runs\n// reproducibly on-chain (no goroutines, channels, or clocks) — as a reusable\n// pure package.\n//\n// A live demo of this package (a gnoweb prime explorer) is at\n// [r/moul/x/daily/sievedemo](/r/moul/x/daily/sievedemo/v0).\npackage sieve\n\n// MaxN bounds the sieve so gas stays predictable.\nconst MaxN = 10000\n\n// PrimesUpTo returns every prime p with 2 \u003c= p \u003c= n, in ascending order,\n// using the Sieve of Eratosthenes. n is clamped to [0, MaxN]. Pure.\nfunc PrimesUpTo(n int) []int {\n\tif n \u003c 2 {\n\t\treturn []int{}\n\t}\n\tif n \u003e MaxN {\n\t\tn = MaxN\n\t}\n\n\t// composite[i] == true once i is known to be non-prime.\n\tcomposite := make([]bool, n+1)\n\tfor p := 2; p*p \u003c= n; p++ {\n\t\tif composite[p] {\n\t\t\tcontinue\n\t\t}\n\t\tfor m := p * p; m \u003c= n; m += p {\n\t\t\tcomposite[m] = true\n\t\t}\n\t}\n\n\tprimes := []int{}\n\tfor i := 2; i \u003c= n; i++ {\n\t\tif !composite[i] {\n\t\t\tprimes = append(primes, i)\n\t\t}\n\t}\n\treturn primes\n}\n\n// NthPrime returns the k-th prime (1-indexed), or 0 if it lies beyond MaxN.\n// Pure helper handy for callers and tests.\nfunc NthPrime(k int) int {\n\tif k \u003c 1 {\n\t\treturn 0\n\t}\n\tprimes := PrimesUpTo(MaxN)\n\tif k \u003e len(primes) {\n\t\treturn 0\n\t}\n\treturn primes[k-1]\n}\n\n// IsPrime reports whether x is prime (trial division). Pure.\nfunc IsPrime(x int) bool {\n\tif x \u003c 2 {\n\t\treturn false\n\t}\n\tfor d := 2; d*d \u003c= x; d++ {\n\t\tif x%d == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"},{"name":"sieve_test.gno","body":"package sieve\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPrimesUpTo(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tn    int\n\t\twant []int\n\t}{\n\t\t{\"below two\", 1, []int{}},\n\t\t{\"exactly two\", 2, []int{2}},\n\t\t{\"ten\", 10, []int{2, 3, 5, 7}},\n\t\t{\"thirty\", 30, []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}},\n\t}\n\n\tfor _, tc := range cases {\n\t\tgot := PrimesUpTo(tc.n)\n\t\tuassert.Equal(t, len(tc.want), len(got), tc.name+\": length\")\n\t\tfor i := range tc.want {\n\t\t\tif i \u003e= len(got) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tuassert.Equal(t, tc.want[i], got[i], tc.name+\": element\")\n\t\t}\n\t}\n\n\t// π(100) == 25, π(1000) == 168 — classic sieve landmarks.\n\tuassert.Equal(t, 25, len(PrimesUpTo(100)), \"pi(100)\")\n\tuassert.Equal(t, 168, len(PrimesUpTo(1000)), \"pi(1000)\")\n\n\t// clamping: anything above MaxN yields the same set as MaxN.\n\tuassert.Equal(t, len(PrimesUpTo(MaxN)), len(PrimesUpTo(MaxN+5000)), \"clamp\")\n}\n\nfunc TestIsPrimeAndNthPrime(t *testing.T) {\n\tprimeCases := []int{2, 3, 5, 7, 11, 13, 9973}\n\tfor _, p := range primeCases {\n\t\tuassert.True(t, IsPrime(p), \"expected prime\")\n\t}\n\n\tcompositeCases := []int{0, 1, 4, 9, 100, 9975}\n\tfor _, c := range compositeCases {\n\t\tuassert.False(t, IsPrime(c), \"expected non-prime\")\n\t}\n\n\tuassert.Equal(t, 2, NthPrime(1), \"1st prime\")\n\tuassert.Equal(t, 29, NthPrime(10), \"10th prime\")\n\tuassert.Equal(t, 541, NthPrime(100), \"100th prime\")\n\tuassert.Equal(t, 0, NthPrime(0), \"0th prime is invalid\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"soundex","path":"gno.land/p/moul/x/daily/soundex/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/soundex/v0`\n\n**Soundex phonetic algorithm** — `Encode`, `Match`, `EncodeAll`, `Normalize`.\n\nNames that sound alike in English encode to the same four-character key:\n`Robert` and `Rupert` both give `R163`.\n\n```go\nimport \"gno.land/p/moul/x/daily/soundex/v0\"\n\nsoundex.Encode(\"Robert\")    // \"R163\"\nsoundex.Encode(\"Ashcraft\")  // \"A261\"\nsoundex.Match(\"Robert\", \"Rupert\")  // true\n```\n\nThe 1918 Russell/Odell algorithm as used by the US census, with the three rules\nthat are usually got wrong implemented explicitly — each has a test:\n\n- **the first letter keeps its own code** and still suppresses a following\n  consonant of the same code, so `Pfister` → `P236`, not `P123`;\n- **`h` and `w` are transparent**: consonants either side are treated as\n  adjacent, so `Ashcraft` → `A261`, not `A226`;\n- **vowels are not transparent** — they separate, so a repeated code after a\n  vowel is emitted again: `Tymczak` → `T522`.\n\nNon-letters are ignored, so `O'Brien` and `OBrien` agree. Input with no ASCII\nletters has **no key** (`\"\"`), and `Match` never reports two such inputs as\nmatching — \"no name\" is not a name they share.\n\nSoundex is English-centric and lossy *by design*: it is a **blocking key** for\nfinding candidates cheaply, never proof that two names are the same.\n\n**Live demo:** [`r/moul/x/daily/soundexdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/soundexdemo)\n· render it at [`/r/moul/x/daily/soundexdemo/v0`](https://gno.land/r/moul/x/daily/soundexdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/soundex/v0\"\ngno = \"0.9\"\n"},{"name":"soundex.gno","body":"// Package soundex implements the Soundex phonetic algorithm as a pure,\n// reusable package: names that sound alike in English encode to the same\n// four-character key, so \"Robert\" and \"Rupert\" both give R163.\n//\n// This is the 1918 Russell/Odell algorithm as used by the US census, with the\n// rules that are usually got wrong implemented explicitly:\n//\n//   - the first letter is kept as-is and its digit still suppresses a\n//     following consonant of the same code (\"Pfister\" → P236, not P123);\n//   - 'h' and 'w' are TRANSPARENT: consonants either side of them are treated\n//     as adjacent (\"Ashcraft\" → A261, not A226);\n//   - vowels are not transparent — they separate, so a repeated code after a\n//     vowel is emitted again (\"Tymczak\" → T522).\n//\n// Soundex is English-centric and lossy by design: it is a *blocking* key for\n// finding candidates, never a proof that two names match.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/soundexdemo](/r/moul/x/daily/soundexdemo/v0).\npackage soundex\n\nimport \"strings\"\n\n// code returns the Soundex digit for a letter, or 0 for vowels and h/w/y.\nfunc code(c byte) byte {\n\tswitch c {\n\tcase 'B', 'F', 'P', 'V':\n\t\treturn '1'\n\tcase 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z':\n\t\treturn '2'\n\tcase 'D', 'T':\n\t\treturn '3'\n\tcase 'L':\n\t\treturn '4'\n\tcase 'M', 'N':\n\t\treturn '5'\n\tcase 'R':\n\t\treturn '6'\n\t}\n\treturn 0\n}\n\n// upper returns c upper-cased if it is an ASCII letter, else 0.\nfunc upper(c byte) byte {\n\tif c \u003e= 'a' \u0026\u0026 c \u003c= 'z' {\n\t\tc -= 32\n\t}\n\tif c \u003e= 'A' \u0026\u0026 c \u003c= 'Z' {\n\t\treturn c\n\t}\n\treturn 0\n}\n\n// Encode returns the four-character Soundex key for s, or \"\" when s contains\n// no ASCII letters. Non-letters are ignored, so \"O'Brien\" and \"OBrien\" agree.\nfunc Encode(s string) string {\n\t// keep letters only\n\tletters := make([]byte, 0, len(s))\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif c := upper(s[i]); c != 0 {\n\t\t\tletters = append(letters, c)\n\t\t}\n\t}\n\tif len(letters) == 0 {\n\t\treturn \"\"\n\t}\n\n\tout := []byte{letters[0]}\n\tprev := code(letters[0]) // the first letter's own code still suppresses\n\n\tfor i := 1; i \u003c len(letters) \u0026\u0026 len(out) \u003c 4; i++ {\n\t\tc := letters[i]\n\t\td := code(c)\n\t\tswitch {\n\t\tcase d == 0:\n\t\t\t// 'h' and 'w' are transparent: leave prev alone so the consonants\n\t\t\t// either side are treated as adjacent. Vowels (and 'y') separate,\n\t\t\t// so they reset prev and allow the same code to repeat.\n\t\t\tif c != 'H' \u0026\u0026 c != 'W' {\n\t\t\t\tprev = 0\n\t\t\t}\n\t\tcase d != prev:\n\t\t\tout = append(out, d)\n\t\t\tprev = d\n\t\tdefault:\n\t\t\t// same code as the previous consonant, and not separated by a\n\t\t\t// vowel: collapsed.\n\t\t}\n\t}\n\tfor len(out) \u003c 4 {\n\t\tout = append(out, '0')\n\t}\n\treturn string(out)\n}\n\n// Match reports whether two strings share a Soundex key. Empty keys never\n// match, so two inputs with no letters are not \"the same name\".\nfunc Match(a, b string) bool {\n\tka, kb := Encode(a), Encode(b)\n\treturn ka != \"\" \u0026\u0026 ka == kb\n}\n\n// EncodeAll returns the keys for each input, in order.\nfunc EncodeAll(names []string) []string {\n\tout := make([]string, 0, len(names))\n\tfor _, n := range names {\n\t\tout = append(out, Encode(n))\n\t}\n\treturn out\n}\n\n// Normalize upper-cases and strips non-letters — the input Encode actually\n// sees. Exposed so callers can show their work.\nfunc Normalize(s string) string {\n\tvar b strings.Builder\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif c := upper(s[i]); c != 0 {\n\t\t\tb.WriteByte(c)\n\t\t}\n\t}\n\treturn b.String()\n}\n"},{"name":"soundex_test.gno","body":"package soundex\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The canonical examples, including the three that catch a naive\n// implementation: Pfister, Tymczak and Ashcraft.\nfunc TestEncodeCanonical(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"Robert\", \"R163\"},\n\t\t{\"Rupert\", \"R163\"},\n\t\t{\"Rubin\", \"R150\"},\n\t\t{\"Ashcraft\", \"A261\"}, // 'h' is transparent: s and c collapse\n\t\t{\"Ashcroft\", \"A261\"},\n\t\t{\"Tymczak\", \"T522\"}, // vowel separates, so 2 repeats\n\t\t{\"Pfister\", \"P236\"}, // first letter's code suppresses the f\n\t\t{\"Honeyman\", \"H555\"},\n\t\t{\"Jackson\", \"J250\"},\n\t\t{\"Washington\", \"W252\"},\n\t\t{\"Lee\", \"L000\"},\n\t\t{\"Gutierrez\", \"G362\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, Encode(c.in))\n\t}\n}\n\n// The first letter keeps its own code for suppression purposes — the rule most\n// often missed. Without it \"Pfister\" would come out P123.\nfunc TestFirstLetterSuppresses(t *testing.T) {\n\tuassert.Equal(t, \"P236\", Encode(\"Pfister\"))\n\tuassert.Equal(t, \"B000\", Encode(\"Bb\"))\n}\n\n// 'h'/'w' are transparent; vowels are not.\nfunc TestTransparentHW(t *testing.T) {\n\tuassert.Equal(t, Encode(\"Ashcraft\"), Encode(\"Ascraft\"))\n\t// a vowel between the same two codes does NOT collapse them\n\tuassert.Equal(t, \"T522\", Encode(\"Tymczak\"))\n}\n\nfunc TestCaseAndPunctuationIgnored(t *testing.T) {\n\tuassert.Equal(t, Encode(\"OBrien\"), Encode(\"O'Brien\"))\n\tuassert.Equal(t, Encode(\"robert\"), Encode(\"ROBERT\"))\n\tuassert.Equal(t, \"R163\", Encode(\"  Robert!  \"))\n}\n\nfunc TestNoLetters(t *testing.T) {\n\tuassert.Equal(t, \"\", Encode(\"\"))\n\tuassert.Equal(t, \"\", Encode(\"12345\"))\n\tuassert.Equal(t, \"\", Encode(\"!!!\"))\n}\n\n// Two inputs with no letters are not \"the same name\".\nfunc TestMatch(t *testing.T) {\n\tuassert.True(t, Match(\"Robert\", \"Rupert\"))\n\tuassert.False(t, Match(\"Robert\", \"Rubin\"))\n\tuassert.False(t, Match(\"\", \"\"))\n\tuassert.False(t, Match(\"123\", \"456\"))\n}\n\n// Always exactly four characters, padded with zeros.\nfunc TestAlwaysFourChars(t *testing.T) {\n\tfor _, s := range []string{\"A\", \"Lee\", \"Robert\", \"Washington\", \"Supercalifragilistic\"} {\n\t\tuassert.Equal(t, 4, len(Encode(s)))\n\t}\n}\n\nfunc TestEncodeAllAndNormalize(t *testing.T) {\n\tgot := EncodeAll([]string{\"Robert\", \"Lee\"})\n\tuassert.Equal(t, 2, len(got))\n\tuassert.Equal(t, \"R163\", got[0])\n\tuassert.Equal(t, \"L000\", got[1])\n\tuassert.Equal(t, \"OBRIEN\", Normalize(\"O'Brien\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"sparkline","path":"gno.land/p/moul/x/daily/sparkline/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/sparkline/v0`\n\n**Sparklines: a numeric series as one line of block characters** — `Ints`,\n`Scaled`, `Level`, `Bounds`, `Levels`, `Steps`.\n\n```go\nimport \"gno.land/p/moul/x/daily/sparkline/v0\"\n\nsparkline.Ints([]int{3, 5, 9, 14, 12, 18, 25, 21, 16, 11, 7, 4})\n// ▁▁▂▄▃▅█▆▅▃▂▁   scaled between the series' own min and max\n\nsparkline.Scaled(pct, 0, 100)   // fixed window; outliers clamp to the ends\n```\n\nA realm's `Render` returns markdown, so a trend normally means an image, a chart\nlibrary, or client-side code — none of which a realm has. Eight block runes and\none line of text do the job, and `gnoweb` needs nothing to display them.\n\n**Everything is integer math, deliberately.** Render output has to be\nbyte-identical on every validating node, and floating point is the usual way\nthat quietly stops being true. Scaling is integer division with floor rounding.\n\nThree behaviours worth knowing before you use it:\n\n- **A flat series renders mid-ramp** (`▅▅▅▅`), not along the floor. A series\n  sitting unchanged at 1000 has no shape, but drawing it at the bottom would\n  claim it was *zero* — a different thing, and a wrong one.\n- **`Scaled` clamps instead of failing.** A window is chosen for readability\n  (`0..100` for a percentage), and one outlier should not be able to flatten the\n  rest of the picture or break the `Render` that drew it.\n- **Rounding is floor**, so only a value at the maximum itself reaches `█`. The\n  peak of a series is always visually distinct.\n\n`Level` is total: every input maps into `[0, Steps)`, including the extremes\nwhere the scaling arithmetic would otherwise wrap. That matters because `Scaled`\nindexes the ramp with it — an out-of-range result would panic the calling realm,\nso it is tested against `minInt`/`maxInt` windows directly.\n\nRendering is `O(len(values))`. A realm should slice its series to a window\nrather than sparking an unbounded, user-grown slice.\n\n**Live demo:** [`r/moul/x/daily/sparklinedemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/sparklinedemo)\n· render it at [`/r/moul/x/daily/sparklinedemo/v0`](https://gno.land/r/moul/x/daily/sparklinedemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/sparkline/v0\"\ngno = \"0.9\"\n"},{"name":"sparkline.gno","body":"// Package sparkline renders a numeric series as one line of Unicode block\n// characters — ▁▂▃▄▅▆▇█ — so a realm's Render can show a trend inline, with no\n// image, no chart library and no client-side code.\n//\n// Everything is integer math, deliberately. A realm's Render must produce\n// byte-identical output on every validating node, and floating point is the\n// usual way that quietly stops being true. Scaling here is integer division\n// with the rounding rule stated below, so a given series always yields exactly\n// the same runes.\n//\n// Rendering is O(len(values)) and allocates one builder; a realm should bound\n// what it feeds in (slice to a window) rather than sparking an unbounded,\n// user-grown slice.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/sparklinedemo](/r/moul/x/daily/sparklinedemo/v0).\npackage sparkline\n\nimport \"strings\"\n\n// Levels is the ramp, lowest to highest. A string constant rather than a\n// []rune so callers cannot mutate the ramp out from under other realms.\nconst Levels = \"▁▂▃▄▅▆▇█\"\n\n// Steps is how many levels the ramp has.\nconst Steps = 8\n\n// maxInt is the largest int, used to keep the scaling multiply from wrapping.\nconst maxInt = int(^uint(0) \u003e\u003e 1)\n\n// Ints renders values scaled between their own smallest and largest element.\n// An empty series renders as the empty string.\nfunc Ints(values []int) string {\n\tlo, hi, ok := Bounds(values)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn Scaled(values, lo, hi)\n}\n\n// Scaled renders values against an explicit [lo, hi] window. Values outside it\n// clamp to the ends rather than erroring: a window is chosen for readability\n// (0..100 for a percentage, say), and one outlier should not be able to break a\n// realm's Render.\n//\n// A window with hi \u003c= lo is treated as flat; see Level.\nfunc Scaled(values []int, lo, hi int) string {\n\tif len(values) == 0 {\n\t\treturn \"\"\n\t}\n\tramp := []rune(Levels)\n\tvar b strings.Builder\n\tfor _, v := range values {\n\t\tb.WriteRune(ramp[Level(v, lo, hi)])\n\t}\n\treturn b.String()\n}\n\n// Level maps v within [lo, hi] to a ramp index in [0, Steps-1].\n//\n// Rounding is floor, so only a value at hi itself reaches the top of the ramp;\n// everything below it rounds down. That makes the maximum visually distinct,\n// which is what a reader is looking for in a sparkline.\n//\n// A flat window (hi \u003c= lo) maps everything to the MIDDLE of the ramp, not the\n// bottom: a series that sits unchanged at 1000 carries no shape, but drawing it\n// along the floor would read as \"zero\", which is a different and wrong claim.\nfunc Level(v, lo, hi int) int {\n\tif hi \u003c= lo {\n\t\treturn Steps / 2\n\t}\n\tif v \u003c= lo {\n\t\treturn 0\n\t}\n\tif v \u003e= hi {\n\t\treturn Steps - 1\n\t}\n\n\tspan, d, top := hi-lo, v-lo, Steps-1\n\tif span \u003c= 0 {\n\t\t// hi-lo wrapped: the window is wider than an int can express, so there\n\t\t// is no usable ramp. Split at the midpoint, computed without overflowing.\n\t\tif v \u003c lo/2+hi/2 {\n\t\t\treturn 0\n\t\t}\n\t\treturn Steps - 1\n\t}\n\t// d*top would wrap on an extreme span; halve both until it cannot. The\n\t// chosen bucket is unchanged for any realistic series, and off by at most\n\t// one level for the pathological ones this protects against.\n\tfor span \u003e maxInt/top {\n\t\tspan \u003e\u003e= 1\n\t\td \u003e\u003e= 1\n\t}\n\treturn d * top / span\n}\n\n// Bounds returns the smallest and largest value in values. ok is false when\n// values is empty, in which case lo and hi are zero.\nfunc Bounds(values []int) (lo, hi int, ok bool) {\n\tif len(values) == 0 {\n\t\treturn 0, 0, false\n\t}\n\tlo, hi = values[0], values[0]\n\tfor _, v := range values[1:] {\n\t\tif v \u003c lo {\n\t\t\tlo = v\n\t\t}\n\t\tif v \u003e hi {\n\t\t\thi = v\n\t\t}\n\t}\n\treturn lo, hi, true\n}\n"},{"name":"sparkline_test.gno","body":"package sparkline\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestInts(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tvalues []int\n\t\twant   string\n\t}{\n\t\t{\"empty\", nil, \"\"},\n\t\t{\"empty slice\", []int{}, \"\"},\n\t\t// A single value is its own min and max, i.e. flat: mid-ramp.\n\t\t{\"single\", []int{42}, \"▅\"},\n\t\t{\"flat\", []int{7, 7, 7}, \"▅▅▅\"},\n\t\t{\"flat at zero\", []int{0, 0}, \"▅▅\"},\n\t\t{\"two apart\", []int{0, 1}, \"▁█\"},\n\t\t{\"ramp\", []int{0, 1, 2, 3, 4, 5, 6, 7}, \"▁▂▃▄▅▆▇█\"},\n\t\t{\"descending\", []int{7, 6, 5, 4, 3, 2, 1, 0}, \"█▇▆▅▄▃▂▁\"},\n\t\t{\"negatives only\", []int{-7, -4, 0}, \"▁▄█\"},\n\t\t{\"spans zero\", []int{-7, 0, 7}, \"▁▄█\"},\n\t\t{\"wide range\", []int{0, 50, 100}, \"▁▄█\"},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tt.want, Ints(tt.values))\n\t\t})\n\t}\n}\n\nfunc TestScaledClampsOutliers(t *testing.T) {\n\t// The window is the contract: anything outside it pins to an end rather\n\t// than rescaling the picture or panicking.\n\tuassert.Equal(t, \"▁▁▄██\", Scaled([]int{-100, 0, 50, 100, 999}, 0, 100))\n}\n\nfunc TestScaledEmpty(t *testing.T) {\n\tuassert.Equal(t, \"\", Scaled(nil, 0, 10))\n}\n\nfunc TestScaledFlatWindow(t *testing.T) {\n\t// hi \u003c= lo carries no shape; every value lands mid-ramp.\n\tuassert.Equal(t, \"▅▅▅\", Scaled([]int{1, 500, 9}, 5, 5))\n\tuassert.Equal(t, \"▅▅\", Scaled([]int{1, 2}, 10, 3))\n}\n\nfunc TestLevel(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tv, lo, hi  int\n\t\twant       int\n\t}{\n\t\t{\"at floor\", 0, 0, 7, 0},\n\t\t{\"at ceiling\", 7, 0, 7, 7},\n\t\t{\"below floor clamps\", -5, 0, 7, 0},\n\t\t{\"above ceiling clamps\", 99, 0, 7, 7},\n\t\t{\"flat window\", 3, 5, 5, Steps / 2},\n\t\t{\"inverted window\", 3, 9, 2, Steps / 2},\n\t\t// Floor rounding: only hi itself reaches the top.\n\t\t{\"just below ceiling\", 99, 0, 100, 6},\n\t\t{\"exact ceiling\", 100, 0, 100, 7},\n\t\t{\"midpoint\", 50, 0, 100, 3},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tt.want, Level(tt.v, tt.lo, tt.hi))\n\t\t})\n\t}\n}\n\n// Level must stay inside the ramp for every input, including the extremes that\n// make the scaling arithmetic wrap. An out-of-range index here would panic the\n// realm that called Scaled, so this is the load-bearing invariant.\nfunc TestLevelAlwaysInRange(t *testing.T) {\n\tconst minInt = -maxInt - 1\n\tvals := []int{minInt, -maxInt, -1000, -1, 0, 1, 1000, maxInt}\n\twindows := [][2]int{\n\t\t{0, 7}, {0, 100}, {-100, 100}, {5, 5}, {9, 2},\n\t\t{minInt, maxInt}, // span wraps int\n\t\t{0, maxInt},      // span survives, but d*top would wrap\n\t\t{minInt, 0},\n\t}\n\tfor _, w := range windows {\n\t\tfor _, v := range vals {\n\t\t\tgot := Level(v, w[0], w[1])\n\t\t\tif got \u003c 0 || got \u003e= Steps {\n\t\t\t\tt.Fatalf(\"Level(%d, %d, %d) = %d, outside [0,%d)\", v, w[0], w[1], got, Steps)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// The huge-span path halves its way down to safe arithmetic; it must still be\n// monotonic, or the picture would lie about the direction of the trend.\nfunc TestLevelMonotonicOnHugeSpan(t *testing.T) {\n\tprev := -1\n\tfor _, v := range []int{0, maxInt / 8, maxInt / 4, maxInt / 2, maxInt} {\n\t\tgot := Level(v, 0, maxInt)\n\t\tif got \u003c prev {\n\t\t\tt.Fatalf(\"Level(%d, 0, maxInt) = %d, went down from %d\", v, got, prev)\n\t\t}\n\t\tprev = got\n\t}\n}\n\nfunc TestBounds(t *testing.T) {\n\tlo, hi, ok := Bounds([]int{3, -1, 9, 4})\n\tuassert.True(t, ok, \"non-empty series should report ok\")\n\tuassert.Equal(t, -1, lo)\n\tuassert.Equal(t, 9, hi)\n\n\tlo, hi, ok = Bounds(nil)\n\tuassert.False(t, ok, \"empty series should report not-ok\")\n\tuassert.Equal(t, 0, lo)\n\tuassert.Equal(t, 0, hi)\n}\n\nfunc TestLevelsRampIsEightRunes(t *testing.T) {\n\t// Scaled indexes this ramp by Level's result, so the two must agree.\n\tuassert.Equal(t, Steps, len([]rune(Levels)))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"toposort","path":"gno.land/p/moul/x/daily/toposort/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/toposort/v0`\n\n**Topological sort of a dependency graph** — `New`, `FromPairs`, `Add`,\n`DependOn`, `Sort`, `CycleNodes`, `Nodes`, `DependenciesOf`, `String`.\n\nOrders a graph so every node comes after everything it depends on — the \"install\nthese packages in a safe order\" problem — using Kahn's algorithm.\n\n```go\nimport \"gno.land/p/moul/x/daily/toposort/v0\"\n\ng := toposort.FromPairs([][2]string{\n    {\"realm\", \"ui\"}, {\"ui\", \"markdown\"}, {\"markdown\", \"strings\"},\n})\norder, err := g.Sort()   // [\"strings\" \"markdown\" \"ui\" \"realm\"], nil\n```\n\n**Deterministic by construction.** Among nodes that become ready at the same\ntime, the lexicographically smallest is always emitted first, so a given graph\nhas exactly one possible answer regardless of insertion order. Adjacency is kept\nin sorted slices and no map is ever *iterated* — Go/gno map iteration order is\nunspecified, and a realm whose `Render` reshuffled between identical calls would\nbe a bug.\n\nA cycle is **reported, not hidden**: `Sort` returns `ErrCycle` along with the\npartial order it managed, and `CycleNodes` names the nodes still stuck so a\ncaller can say exactly which dependencies are tangled.\n\nEdge cases: a self-dependency is ignored as a trivial cycle but the node stays\nin the graph; duplicate edges collapse; empty names are rejected; `Nodes` and\n`DependenciesOf` return copies, so a caller cannot mutate the graph through them.\n\n**Live demo:** [`r/moul/x/daily/toposortdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/toposortdemo)\n· render it at [`/r/moul/x/daily/toposortdemo/v0`](https://gno.land/r/moul/x/daily/toposortdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/toposort/v0\"\ngno = \"0.9\"\n"},{"name":"toposort.gno","body":"// Package toposort orders a dependency graph so that every node comes after\n// everything it depends on — the \"install these packages in a safe order\"\n// problem — as a pure, reusable package.\n//\n// It uses Kahn's algorithm, and it is *deterministic*: ready nodes are always\n// taken in lexicographic order, so a given graph always yields the exact same\n// ordering. That matters on-chain, where a Render that reshuffled between\n// identical calls would be a bug. Adjacency is kept in sorted slices rather\n// than maps for the same reason — Go/gno map iteration order is unspecified.\n//\n// A cycle is reported as an error naming the nodes still stuck, rather than\n// panicking or silently dropping them.\n//\n// A live demo of this package is at\n// [r/moul/x/daily/toposortdemo](/r/moul/x/daily/toposortdemo/v0).\npackage toposort\n\nimport (\n\t\"errors\"\n\t\"sort\"\n\t\"strings\"\n)\n\n// ErrCycle is returned by Sort when the graph is not a DAG. Use CycleNodes to\n// recover which nodes are involved.\nvar ErrCycle = errors.New(\"toposort: graph has a cycle\")\n\n// Graph is a directed dependency graph. The zero value is not usable — build\n// one with New.\ntype Graph struct {\n\tnodes []string            // every known node, kept sorted and unique\n\tdeps  map[string][]string // node -\u003e the nodes it depends on (sorted, unique)\n}\n\n// New returns an empty Graph.\nfunc New() *Graph {\n\treturn \u0026Graph{deps: map[string][]string{}}\n}\n\n// Add registers a node with no dependencies. Adding twice is a no-op; it is\n// how you declare a leaf that nothing depends on.\nfunc (g *Graph) Add(node string) {\n\tif node == \"\" {\n\t\treturn\n\t}\n\tg.addNode(node)\n}\n\n// DependOn records that node depends on dep, so dep must come first. Both\n// endpoints are registered. A self-dependency is ignored (it would be a\n// trivial cycle and is never what the caller means). Duplicate edges collapse.\nfunc (g *Graph) DependOn(node, dep string) {\n\tif node == \"\" || dep == \"\" {\n\t\treturn\n\t}\n\tg.addNode(node)\n\tg.addNode(dep)\n\tif node == dep {\n\t\t// A self-edge is a trivial cycle and never what the caller means, but\n\t\t// the node was still named, so it stays in the graph as a leaf.\n\t\treturn\n\t}\n\tcur := g.deps[node]\n\ti := sort.SearchStrings(cur, dep)\n\tif i \u003c len(cur) \u0026\u0026 cur[i] == dep {\n\t\treturn // already recorded\n\t}\n\tcur = append(cur, \"\")\n\tcopy(cur[i+1:], cur[i:])\n\tcur[i] = dep\n\tg.deps[node] = cur\n}\n\n// addNode inserts node into the sorted node list if absent.\nfunc (g *Graph) addNode(node string) {\n\ti := sort.SearchStrings(g.nodes, node)\n\tif i \u003c len(g.nodes) \u0026\u0026 g.nodes[i] == node {\n\t\treturn\n\t}\n\tg.nodes = append(g.nodes, \"\")\n\tcopy(g.nodes[i+1:], g.nodes[i:])\n\tg.nodes[i] = node\n}\n\n// Len returns how many nodes the graph holds.\nfunc (g *Graph) Len() int { return len(g.nodes) }\n\n// Nodes returns every node in lexicographic order.\nfunc (g *Graph) Nodes() []string {\n\tout := make([]string, len(g.nodes))\n\tcopy(out, g.nodes)\n\treturn out\n}\n\n// DependenciesOf returns node's direct dependencies, sorted.\nfunc (g *Graph) DependenciesOf(node string) []string {\n\td := g.deps[node]\n\tout := make([]string, len(d))\n\tcopy(out, d)\n\treturn out\n}\n\n// Sort returns the nodes ordered so every node follows its dependencies.\n//\n// Among nodes that are simultaneously ready, the lexicographically smallest is\n// emitted first, which makes the result unique for a given graph. On a cycle it\n// returns ErrCycle along with the partial order computed so far.\nfunc (g *Graph) Sort() ([]string, error) {\n\t// indegree[n] = how many of n's dependencies are still unresolved.\n\tindegree := map[string]int{}\n\t// dependents[d] = nodes waiting on d.\n\tdependents := map[string][]string{}\n\tfor _, n := range g.nodes {\n\t\tindegree[n] = len(g.deps[n])\n\t\tfor _, d := range g.deps[n] {\n\t\t\tdependents[d] = append(dependents[d], n)\n\t\t}\n\t}\n\n\t// ready holds nodes with no unresolved dependency, kept sorted so the\n\t// smallest is always taken first.\n\tready := []string{}\n\tfor _, n := range g.nodes { // g.nodes is already sorted\n\t\tif indegree[n] == 0 {\n\t\t\tready = append(ready, n)\n\t\t}\n\t}\n\n\tout := make([]string, 0, len(g.nodes))\n\tfor len(ready) \u003e 0 {\n\t\tn := ready[0]\n\t\tready = ready[1:]\n\t\tout = append(out, n)\n\n\t\t// Releasing dependents can make several ready at once; collect them and\n\t\t// merge into the sorted queue so ordering stays deterministic.\n\t\tfreed := []string{}\n\t\tfor _, m := range dependents[n] {\n\t\t\tindegree[m]--\n\t\t\tif indegree[m] == 0 {\n\t\t\t\tfreed = append(freed, m)\n\t\t\t}\n\t\t}\n\t\tif len(freed) \u003e 0 {\n\t\t\tsort.Strings(freed)\n\t\t\tready = mergeSorted(ready, freed)\n\t\t}\n\t}\n\n\tif len(out) != len(g.nodes) {\n\t\treturn out, ErrCycle\n\t}\n\treturn out, nil\n}\n\n// CycleNodes returns the nodes that could not be ordered — i.e. those on or\n// downstream of a cycle — in lexicographic order. Empty when the graph is a DAG.\nfunc (g *Graph) CycleNodes() []string {\n\tdone, err := g.Sort()\n\tif err == nil {\n\t\treturn []string{}\n\t}\n\tplaced := map[string]bool{}\n\tfor _, n := range done {\n\t\tplaced[n] = true\n\t}\n\tstuck := []string{}\n\tfor _, n := range g.nodes {\n\t\tif !placed[n] {\n\t\t\tstuck = append(stuck, n)\n\t\t}\n\t}\n\treturn stuck\n}\n\n// mergeSorted merges two sorted string slices into one sorted slice.\nfunc mergeSorted(a, b []string) []string {\n\tout := make([]string, 0, len(a)+len(b))\n\ti, j := 0, 0\n\tfor i \u003c len(a) \u0026\u0026 j \u003c len(b) {\n\t\tif a[i] \u003c= b[j] {\n\t\t\tout = append(out, a[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tout = append(out, b[j])\n\t\t\tj++\n\t\t}\n\t}\n\tout = append(out, a[i:]...)\n\tout = append(out, b[j:]...)\n\treturn out\n}\n\n// FromPairs builds a Graph from \"node depends on dep\" pairs. Each pair is\n// {node, dep}. Handy for tests and literal declarations.\nfunc FromPairs(pairs [][2]string) *Graph {\n\tg := New()\n\tfor _, p := range pairs {\n\t\tg.DependOn(p[0], p[1])\n\t}\n\treturn g\n}\n\n// String renders the graph as \"node \u003c- dep1, dep2\" lines, sorted. Useful for\n// debugging and for demos.\nfunc (g *Graph) String() string {\n\tvar b strings.Builder\n\tfor _, n := range g.nodes {\n\t\tb.WriteString(n)\n\t\tif d := g.deps[n]; len(d) \u003e 0 {\n\t\t\tb.WriteString(\" \u003c- \")\n\t\t\tb.WriteString(strings.Join(d, \", \"))\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\treturn b.String()\n}\n"},{"name":"toposort_test.gno","body":"package toposort\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// order asserts a successful sort and returns the joined result.\nfunc order(t *testing.T, g *Graph) string {\n\tt.Helper()\n\tout, err := g.Sort()\n\tuassert.NoError(t, err)\n\treturn strings.Join(out, \",\")\n}\n\nfunc TestLinearChain(t *testing.T) {\n\t// c depends on b depends on a\n\tg := FromPairs([][2]string{{\"c\", \"b\"}, {\"b\", \"a\"}})\n\tuassert.Equal(t, \"a,b,c\", order(t, g))\n}\n\nfunc TestDependenciesComeFirst(t *testing.T) {\n\tg := FromPairs([][2]string{\n\t\t{\"app\", \"lib\"},\n\t\t{\"lib\", \"core\"},\n\t\t{\"app\", \"core\"},\n\t})\n\tuassert.Equal(t, \"core,lib,app\", order(t, g))\n}\n\n// Ties are broken lexicographically, so a given graph has exactly one answer —\n// the property that keeps an on-chain Render stable.\nfunc TestTiesAreLexicographic(t *testing.T) {\n\tg := New()\n\tfor _, n := range []string{\"delta\", \"alpha\", \"charlie\", \"bravo\"} {\n\t\tg.Add(n)\n\t}\n\tuassert.Equal(t, \"alpha,bravo,charlie,delta\", order(t, g))\n}\n\nfunc TestResultIsIndependentOfInsertionOrder(t *testing.T) {\n\ta := FromPairs([][2]string{{\"c\", \"b\"}, {\"b\", \"a\"}, {\"d\", \"a\"}})\n\tb := FromPairs([][2]string{{\"d\", \"a\"}, {\"b\", \"a\"}, {\"c\", \"b\"}})\n\tuassert.Equal(t, order(t, a), order(t, b))\n}\n\nfunc TestIsolatedNodes(t *testing.T) {\n\tg := New()\n\tg.Add(\"solo\")\n\tg.DependOn(\"b\", \"a\")\n\tuassert.Equal(t, \"a,b,solo\", order(t, g))\n}\n\nfunc TestEmptyGraph(t *testing.T) {\n\tg := New()\n\tout, err := g.Sort()\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 0, len(out))\n\tuassert.Equal(t, 0, g.Len())\n}\n\nfunc TestCycleIsReported(t *testing.T) {\n\tg := FromPairs([][2]string{{\"a\", \"b\"}, {\"b\", \"c\"}, {\"c\", \"a\"}})\n\tout, err := g.Sort()\n\tuassert.Error(t, err)\n\tuassert.Equal(t, 0, len(out)) // nothing could start\n\tuassert.Equal(t, \"a,b,c\", strings.Join(g.CycleNodes(), \",\"))\n}\n\n// A cycle downstream of a healthy prefix still orders the prefix, and reports\n// only the stuck part.\nfunc TestPartialOrderBeforeCycle(t *testing.T) {\n\tg := FromPairs([][2]string{\n\t\t{\"b\", \"a\"}, // fine\n\t\t{\"x\", \"y\"}, // cycle…\n\t\t{\"y\", \"x\"}, // …here\n\t})\n\tout, err := g.Sort()\n\tuassert.Error(t, err)\n\tuassert.Equal(t, \"a,b\", strings.Join(out, \",\"))\n\tuassert.Equal(t, \"x,y\", strings.Join(g.CycleNodes(), \",\"))\n}\n\nfunc TestCycleNodesEmptyOnDAG(t *testing.T) {\n\tg := FromPairs([][2]string{{\"b\", \"a\"}})\n\tuassert.Equal(t, 0, len(g.CycleNodes()))\n}\n\n// A self-dependency is meaningless and must not deadlock the graph.\nfunc TestSelfDependencyIgnored(t *testing.T) {\n\tg := New()\n\tg.DependOn(\"a\", \"a\")\n\tuassert.Equal(t, \"a\", order(t, g))\n\tuassert.Equal(t, 0, len(g.DependenciesOf(\"a\")))\n}\n\nfunc TestDuplicateEdgesCollapse(t *testing.T) {\n\tg := New()\n\tg.DependOn(\"b\", \"a\")\n\tg.DependOn(\"b\", \"a\")\n\tuassert.Equal(t, 1, len(g.DependenciesOf(\"b\")))\n\tuassert.Equal(t, \"a,b\", order(t, g))\n}\n\nfunc TestEmptyNamesIgnored(t *testing.T) {\n\tg := New()\n\tg.Add(\"\")\n\tg.DependOn(\"\", \"a\")\n\tg.DependOn(\"a\", \"\")\n\tuassert.Equal(t, 0, g.Len())\n}\n\nfunc TestNodesAndDependenciesAreCopies(t *testing.T) {\n\tg := FromPairs([][2]string{{\"b\", \"a\"}})\n\tns := g.Nodes()\n\tns[0] = \"mutated\"\n\tuassert.Equal(t, \"a,b\", strings.Join(g.Nodes(), \",\"))\n\n\tds := g.DependenciesOf(\"b\")\n\tds[0] = \"mutated\"\n\tuassert.Equal(t, \"a\", strings.Join(g.DependenciesOf(\"b\"), \",\"))\n}\n\nfunc TestString(t *testing.T) {\n\tg := FromPairs([][2]string{{\"app\", \"lib\"}, {\"app\", \"core\"}})\n\tuassert.Equal(t, \"app \u003c- core, lib\\ncore\\nlib\\n\", g.String())\n}\n\n// A wide diamond: both middles are ready at once and must come out sorted.\nfunc TestDiamond(t *testing.T) {\n\tg := FromPairs([][2]string{\n\t\t{\"top\", \"left\"},\n\t\t{\"top\", \"right\"},\n\t\t{\"left\", \"base\"},\n\t\t{\"right\", \"base\"},\n\t})\n\tuassert.Equal(t, \"base,left,right,top\", order(t, g))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"trie","path":"gno.land/p/moul/x/daily/trie/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/daily/trie/v0`\n\n**Prefix tree (trie) for autocomplete** — `Insert`, `Contains`, `HasPrefix`, `Complete`, `Words`, `FromWords`, `MaxWordLen`.\n\nInsert words, then ask for everything sharing a prefix. Children are stored in a\nslice kept sorted by rune (binary search on lookup, insertion sort on add), so\ncompletions always come back in lexicographic order and the output never depends\non insertion order — no maps anywhere, because Go/gno map iteration order is\nunspecified and would make a realm's `Render` vary between calls. No clocks and\nno chain imports either: same input, same output, always.\n\n`MaxWordLen` (64) bounds a single word so insertion gas stays predictable.\n\n```go\nimport \"gno.land/p/moul/x/daily/trie/v0\"\n\nt := trie.FromWords([]string{\"carpet\", \"car\", \"cat\"})\nt.Complete(\"car\", 0)   // [\"car\" \"carpet\"] — lexicographic, 0 = no cap\nt.Complete(\"car\", 1)   // [\"car\"]\nt.Contains(\"car\")      // true\nt.Contains(\"ca\")       // false — a prefix is not a word until inserted\nt.HasPrefix(\"ca\")      // true\nt.Words()              // [\"car\" \"carpet\" \"cat\"]\n```\n\n`Complete` returns an empty (never nil) slice for an unknown prefix, so callers\ncan range over the result without a nil check. The empty prefix lists the whole\ntrie, which makes it usable as a plain sorted listing too.\n\n**Live demo:** [`r/moul/x/daily/triedemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/triedemo)\n· render it at [`/r/moul/x/daily/triedemo/v0`](https://gno.land/r/moul/x/daily/triedemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/daily/trie/v0\"\ngno = \"0.9\"\n"},{"name":"trie.gno","body":"// Package trie is a prefix tree (trie) for autocomplete, as a pure, reusable\n// package: insert words, then ask for every word sharing a prefix.\n//\n// Everything is deterministic and allocation-friendly so it runs reproducibly\n// on-chain: no maps in the hot path (map iteration order is unspecified, which\n// would make Render output vary), no clocks, no chain imports. Children are\n// kept in a slice sorted by rune, so completions always come out in\n// lexicographic order — the same input always yields the same output.\n//\n// A live demo of this package (a gnoweb autocomplete box) is at\n// [r/moul/x/daily/triedemo](/r/moul/x/daily/triedemo/v0).\npackage trie\n\nimport \"sort\"\n\n// MaxWordLen bounds a single word so insertion gas stays predictable.\nconst MaxWordLen = 64\n\n// node is one position in the tree. Children are ordered by Key so walks are\n// deterministic; `terminal` marks the end of an inserted word (so \"car\" can be\n// a word even when \"carpet\" is also stored).\ntype node struct {\n\tkey      rune\n\tterminal bool\n\tchildren []*node\n}\n\n// Trie is a prefix tree. The zero value is an empty, ready-to-use Trie.\ntype Trie struct {\n\troot  node\n\tcount int\n}\n\n// New returns an empty Trie.\nfunc New() *Trie { return \u0026Trie{} }\n\n// Len returns how many distinct words the Trie holds.\nfunc (t *Trie) Len() int { return t.count }\n\n// child finds n's child for rune r, or nil. The slice is sorted, so this is a\n// binary search.\nfunc (n *node) child(r rune) *node {\n\ti := sort.Search(len(n.children), func(i int) bool { return n.children[i].key \u003e= r })\n\tif i \u003c len(n.children) \u0026\u0026 n.children[i].key == r {\n\t\treturn n.children[i]\n\t}\n\treturn nil\n}\n\n// addChild inserts a child for rune r, keeping children sorted by key.\nfunc (n *node) addChild(r rune) *node {\n\ti := sort.Search(len(n.children), func(i int) bool { return n.children[i].key \u003e= r })\n\tif i \u003c len(n.children) \u0026\u0026 n.children[i].key == r {\n\t\treturn n.children[i]\n\t}\n\tc := \u0026node{key: r}\n\tn.children = append(n.children, nil)\n\tcopy(n.children[i+1:], n.children[i:])\n\tn.children[i] = c\n\treturn c\n}\n\n// Insert adds word to the Trie and reports whether it was newly added.\n// The empty string and words longer than MaxWordLen are rejected (false).\n// Inserting the same word twice is a no-op.\nfunc (t *Trie) Insert(word string) bool {\n\trs := []rune(word)\n\tif len(rs) == 0 || len(rs) \u003e MaxWordLen {\n\t\treturn false\n\t}\n\tn := \u0026t.root\n\tfor _, r := range rs {\n\t\tn = n.addChild(r)\n\t}\n\tif n.terminal {\n\t\treturn false\n\t}\n\tn.terminal = true\n\tt.count++\n\treturn true\n}\n\n// Contains reports whether word was inserted as a complete word. A stored\n// \"carpet\" does not make \"car\" Contains-true — only Insert does.\nfunc (t *Trie) Contains(word string) bool {\n\tn := t.find(word)\n\treturn n != nil \u0026\u0026 n.terminal\n}\n\n// HasPrefix reports whether any stored word starts with prefix. The empty\n// prefix matches whenever the Trie is non-empty.\nfunc (t *Trie) HasPrefix(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn t.count \u003e 0\n\t}\n\treturn t.find(prefix) != nil\n}\n\n// find walks to the node for s, or returns nil when the path is absent.\nfunc (t *Trie) find(s string) *node {\n\tn := \u0026t.root\n\tfor _, r := range s {\n\t\tn = n.child(r)\n\t\tif n == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn n\n}\n\n// Complete returns up to limit words starting with prefix, in lexicographic\n// order. A limit \u003c= 0 means \"no cap\". An absent prefix yields an empty slice\n// (never nil), so callers can range over the result unconditionally.\n//\n// The empty prefix lists the whole Trie, which is what makes this usable as a\n// plain sorted listing too.\nfunc (t *Trie) Complete(prefix string, limit int) []string {\n\tout := []string{}\n\tstart := t.find(prefix)\n\tif start == nil {\n\t\treturn out\n\t}\n\tcollect(start, []rune(prefix), \u0026out, limit)\n\treturn out\n}\n\n// collect appends every word under n (depth-first, children already sorted)\n// to *out, stopping once limit is reached.\nfunc collect(n *node, path []rune, out *[]string, limit int) {\n\tif limit \u003e 0 \u0026\u0026 len(*out) \u003e= limit {\n\t\treturn\n\t}\n\tif n.terminal {\n\t\t*out = append(*out, string(path))\n\t}\n\tfor _, c := range n.children {\n\t\tif limit \u003e 0 \u0026\u0026 len(*out) \u003e= limit {\n\t\t\treturn\n\t\t}\n\t\tcollect(c, append(path, c.key), out, limit)\n\t}\n}\n\n// Words returns every stored word in lexicographic order.\nfunc (t *Trie) Words() []string { return t.Complete(\"\", 0) }\n\n// FromWords builds a Trie from words, skipping any the Trie rejects.\nfunc FromWords(words []string) *Trie {\n\tt := New()\n\tfor _, w := range words {\n\t\tt.Insert(w)\n\t}\n\treturn t\n}\n"},{"name":"trie_test.gno","body":"package trie\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestInsertAndContains(t *testing.T) {\n\tcases := []struct {\n\t\tname     string\n\t\tword     string\n\t\twantOK   bool\n\t\tcontains bool\n\t}{\n\t\t{\"plain word\", \"car\", true, true},\n\t\t{\"empty rejected\", \"\", false, false},\n\t\t{\"too long rejected\", strings.Repeat(\"a\", MaxWordLen+1), false, false},\n\t\t{\"exactly max accepted\", strings.Repeat(\"b\", MaxWordLen), true, true},\n\t}\n\tfor _, c := range cases {\n\t\tt.Run(c.name, func(t *testing.T) {\n\t\t\ttr := New()\n\t\t\tuassert.Equal(t, c.wantOK, tr.Insert(c.word))\n\t\t\tuassert.Equal(t, c.contains, tr.Contains(c.word))\n\t\t})\n\t}\n}\n\nfunc TestInsertIsIdempotent(t *testing.T) {\n\ttr := New()\n\tuassert.True(t, tr.Insert(\"gno\"))\n\tuassert.False(t, tr.Insert(\"gno\"))\n\tuassert.Equal(t, 1, tr.Len())\n}\n\n// A prefix of a stored word is not itself a word until inserted.\nfunc TestPrefixIsNotAWord(t *testing.T) {\n\ttr := FromWords([]string{\"carpet\"})\n\tuassert.False(t, tr.Contains(\"car\"))\n\tuassert.True(t, tr.HasPrefix(\"car\"))\n\tuassert.True(t, tr.Contains(\"carpet\"))\n}\n\nfunc TestCompleteIsLexicographic(t *testing.T) {\n\t// deliberately inserted out of order\n\ttr := FromWords([]string{\"carpet\", \"car\", \"cat\", \"dog\", \"cart\"})\n\tgot := tr.Complete(\"car\", 0)\n\twant := []string{\"car\", \"carpet\", \"cart\"}\n\tuassert.Equal(t, strings.Join(want, \",\"), strings.Join(got, \",\"))\n}\n\nfunc TestCompleteLimit(t *testing.T) {\n\ttr := FromWords([]string{\"a\", \"ab\", \"abc\", \"abcd\"})\n\tuassert.Equal(t, 2, len(tr.Complete(\"a\", 2)))\n\tuassert.Equal(t, 4, len(tr.Complete(\"a\", 0)))\n\tuassert.Equal(t, 4, len(tr.Complete(\"a\", -1)))\n}\n\nfunc TestCompleteUnknownPrefixIsEmptyNotNil(t *testing.T) {\n\ttr := FromWords([]string{\"gno\"})\n\tgot := tr.Complete(\"zzz\", 0)\n\tuassert.Equal(t, 0, len(got))\n\t// must be safe to range over / join without a nil check\n\tuassert.Equal(t, \"\", strings.Join(got, \",\"))\n}\n\nfunc TestEmptyPrefixListsEverything(t *testing.T) {\n\ttr := FromWords([]string{\"beta\", \"alpha\", \"gamma\"})\n\tuassert.Equal(t, \"alpha,beta,gamma\", strings.Join(tr.Words(), \",\"))\n\tuassert.True(t, tr.HasPrefix(\"\"))\n\tuassert.False(t, New().HasPrefix(\"\"))\n}\n\nfunc TestUnicode(t *testing.T) {\n\ttr := FromWords([]string{\"éclair\", \"école\", \"zèbre\"})\n\tuassert.Equal(t, \"éclair,école\", strings.Join(tr.Complete(\"é\", 0), \",\"))\n\tuassert.True(t, tr.Contains(\"zèbre\"))\n}\n\n// Children are kept sorted on insert, so output order never depends on\n// insertion order — the property that keeps Render deterministic on-chain.\nfunc TestOrderIndependentOfInsertionOrder(t *testing.T) {\n\ta := FromWords([]string{\"delta\", \"alpha\", \"charlie\", \"bravo\"})\n\tb := FromWords([]string{\"bravo\", \"charlie\", \"alpha\", \"delta\"})\n\tuassert.Equal(t, strings.Join(a.Words(), \",\"), strings.Join(b.Words(), \",\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"envelope","path":"gno.land/p/moul/x/envelope/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/envelope/v0`\n\n**Reading and forwarding the coins a transaction attached to a call.** The `-send`\nfield of a `MsgCall`, credited to the called realm's address before a line of its\ncode runs.\n\n\"Payable\" is not a keyword in gno, it is a runtime fact: the VM rejects a\n`MsgCall` that carried coins the callee never looked at, and reading the envelope\nis what counts as looking. So every realm taking payment writes the same three\nthings by hand. This is those three things.\n\n```go\nimport \"gno.land/p/moul/x/envelope/v0\"\n\nfunc Publish(cur realm, slug string) {\n    envelope.RequireExactly(Price, 500)   // aborts, naming the flag, if unpaid\n    // ...\n}\n\nfunc Route(cur realm, to address) int64 {\n    return envelope.ForwardAll(0, cur, to, Denom)  // spends the envelope, nothing else\n}\n```\n\n| | |\n|---|---|\n| `Amount` · `All` · `IsEmpty` | read it, and make the call payable |\n| `Require` · `RequireAtLeast` · `RequireExactly` | read it and abort usefully when it is wrong |\n| `Only` | refuse an envelope carrying anything else |\n| `Forward` · `ForwardAll` | spend it, and nothing but it |\n| `BalanceOf` | what an address holds of a denom, from the bank |\n\n## Why the abort messages are long\n\n`Require` aborts with `attach coins with -send \u003camount\u003e/gno.land/r/...:coin`. The\nabort is the realm's user interface at the moment somebody got it wrong:\n\"insufficient funds\" sends them to their wallet, naming the flag sends them to the\nfix.\n\n`RequireExactly` refuses an **over**payment too. A realm that silently keeps the\nexcess has invented a fee nobody agreed to, and one that refunds it has to move\ncoins back out, which is a second failure mode.\n\n## Two things that are not obvious\n\n**`Forward` is about who entered, not how deep you are.** It mints a\n`BankerTypeOriginSend` banker, which `NewBanker` allows only when\n`rlm.Previous().IsUserCall()`, and that is literally `pkgPath == \"\"`. So a realm\nmay pass its `cur` down through as many of its own helpers as it likes (measured\nat three nested calls, through a function value, and through a closure), and it\nmay **not** forward an envelope handed to it by another realm, nor be driven from\n`gnokey maketx run`, whose entry package is a code realm.\n\n**`Forward` is tested from a realm, not from here.** Minting the banker calls\n`rlm.Previous()`, and a `p/` package's test has no realm frame to walk: it dies\nwith `frame not found: cannot seek beyond origin caller override`. The tests live\nin [`r/moul/x/nativeify`](https://gno.land/r/moul/x/nativeify/v0), which is also\nthe realm that uses it.\n\nRelated: a native coin is push-only, so the envelope is its entire inbound path.\nThere is no allowance for one, which is what\n[`r/moul/x/nativeify`](https://gno.land/r/moul/x/nativeify/v0) is about.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/envelope/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/envelope/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"envelope.gno","body":"// Package envelope reads and forwards the coins a transaction attached to a\n// call: the `-send` field of a `MsgCall`, credited to the called realm's address\n// before a line of its code runs.\n//\n// It exists because \"payable\" is not a keyword in gno, it is a runtime fact. The\n// VM rejects a `MsgCall` that carried coins the callee never looked at\n// (gno.land/pkg/sdk/vm/keeper.go, `if !send.IsZero() \u0026\u0026 !*OriginSendObserved`),\n// and reading the envelope is what counts as looking. So every realm that\n// accepts payment writes the same three things by hand: read the amount, abort\n// with something the caller can act on when it is zero or the wrong denom, and\n// forward or keep it. This package is those three things.\n//\n// # Native coins are push-only, which is why this matters\n//\n// A realm cannot pull a native coin. `banker.SendCoins` panics unless the\n// `from` address is the banker's own realm address, so there is no allowance\n// and no `TransferFrom` for a native denom. The envelope is the entire inbound\n// path: either the holder signs a bank send, or they attach coins to a call and\n// the callee reads them here.\n//\n// That is also why a GRC20 needs `Approve` and a native coin does not. The GRC20\n// grants standing authority to a spender; the envelope grants authority over one\n// message and expires with it.\n//\n// # Who may forward, which is not about depth\n//\n// [Forward] mints a `BankerTypeOriginSend` banker, and `NewBanker` accepts that\n// type only when `rlm.Previous().IsUserCall()` holds. `Realm.IsUserCall` is\n// literally `pkgPath == \"\"` (gnovm/stdlibs/chain/runtime/frame.gno), so the test\n// is about WHO entered the realm, not about how deep inside it you are:\n//\n//   - `maketx call` straight into the realm: fine, and the realm may pass its\n//     `cur` down through as many of its own helpers as it likes. Measured at\n//     three nested calls, and through a function value and a closure.\n//   - realm A calls realm B, and B tries to forward: refused. B's previous is a\n//     code realm, so the envelope it was handed is not B's to route.\n//   - `maketx run`: refused. The run package is a code realm\n//     (`\u003cdomain\u003e/e/\u003caddr\u003e/run`), so `IsUserCall` is false there too, and every\n//     payable function is therefore unreachable from a run script.\n//\n// The reading helpers have none of these conditions: they go through\n// `unsafe.OriginSend()`, a context read that works anywhere, including inside a\n// `Render`.\n//\npackage envelope\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Amount returns how much of denom this message's envelope carried, and zero\n// when it carried none. Reading it is what makes the call payable.\nfunc Amount(denom string) int64 {\n\treturn unsafe.OriginSend().AmountOf(denom)\n}\n\n// All returns the whole envelope, every denom in it.\n//\n// A call can be paid in several denoms at once, which is a property of the bank\n// rather than of any realm: a `Coins` set holds up to 256 of them. A realm that\n// only wants one should use [Only].\nfunc All() chain.Coins {\n\treturn unsafe.OriginSend()\n}\n\n// IsEmpty reports whether nothing was attached to this call.\nfunc IsEmpty() bool {\n\treturn len(unsafe.OriginSend()) == 0\n}\n\n// Require returns [Amount] and aborts when it is zero, with a message naming the\n// flag the caller left out.\n//\n// The message is the point. \"insufficient funds\" sends somebody to their wallet;\n// naming the denom and the flag sends them to the fix.\nfunc Require(denom string) int64 {\n\tamount := Amount(denom)\n\tif amount \u003c= 0 {\n\t\tpanic(\"this call must be paid: attach coins with -send \u003camount\u003e\" + denom)\n\t}\n\treturn amount\n}\n\n// RequireAtLeast is [Require] with a floor, and names both numbers when the\n// envelope falls short.\nfunc RequireAtLeast(denom string, min int64) int64 {\n\tamount := Require(denom)\n\tif amount \u003c min {\n\t\tpanic(ufmt.Sprintf(\"this call costs at least %d%s, the envelope carried %d\",\n\t\t\tmin, denom, amount))\n\t}\n\treturn amount\n}\n\n// RequireExactly is [Require] for a fixed price, and refuses an overpayment as\n// well as an underpayment.\n//\n// Refusing to be overpaid is the unusual half, and it is deliberate: a realm\n// that silently keeps the excess has invented a fee nobody agreed to, and a\n// realm that refunds it has to move coins back out, which is a second failure\n// mode. Aborting costs the caller one transaction and nothing else.\nfunc RequireExactly(denom string, price int64) int64 {\n\tamount := Require(denom)\n\tif amount != price {\n\t\tpanic(ufmt.Sprintf(\"this call costs exactly %d%s, the envelope carried %d\",\n\t\t\tprice, denom, amount))\n\t}\n\treturn amount\n}\n\n// Only is [Require] plus a refusal of anything else in the envelope.\n//\n// Use it wherever the realm has no code that would ever move a second denom,\n// because coins it does not handle are coins stranded at its address forever:\n// they are not refunded, and only the realm's own code can ever send them on.\nfunc Only(denom string) int64 {\n\tamount := Require(denom)\n\tfor _, coin := range unsafe.OriginSend() {\n\t\tif coin.Denom != denom {\n\t\t\tpanic(ufmt.Sprintf(\"this call takes %s only, the envelope also carried %d%s\",\n\t\t\t\tdenom, coin.Amount, coin.Denom))\n\t\t}\n\t}\n\treturn amount\n}\n\n// Forward sends coins from the calling realm's address to `to`, bounded by this\n// message's envelope.\n//\n// The banker it mints can spend the envelope and nothing else: not the realm's\n// own balance, not a previous message's payment. That is what makes a routing\n// function safe to write, and it is enforced by the VM rather than by the code\n// here (`ctx.OriginSend.IsAllGTE(spent)`).\n//\n// It must be reached from a call a USER made into this realm; see the package\n// doc for what that rules out.\n//\n// The leading `_ int` is not decoration: a non-realm package may not declare a\n// crossing function, so a `p/` helper that needs a realm handle threads it as a\n// later parameter. That is the same shape `p/nt/grc20`'s tellers use, and gno\n// refuses the file outright without it (\"crossing function (realm first\n// argument) declared in non-realm package\").\n//\n// This function has no test in this package either, for the same reason it has\n// that signature: minting the banker calls `rlm.Previous()`, and a `p/` test has\n// no realm frame to walk (\"frame not found: cannot seek beyond origin caller\n// override\"). It is exercised from `r/moul/x/nativeify`'s tests instead.\nfunc Forward(_ int, rlm realm, to address, coins chain.Coins) {\n\tbanker.NewBanker(banker.BankerTypeOriginSend, rlm).SendCoins(rlm.Address(), to, coins)\n}\n\n// ForwardAll forwards everything the envelope carried of denom, and returns it.\n// It aborts when the envelope carried none, like [Require].\nfunc ForwardAll(_ int, rlm realm, to address, denom string) int64 {\n\tamount := Require(denom)\n\tForward(0, rlm, to, chain.NewCoins(chain.NewCoin(denom, amount)))\n\treturn amount\n}\n\n// BalanceOf returns what addr holds of denom right now, straight from the bank.\n//\n// It takes an address rather than a realm handle because it needs no authority\n// at all: a readonly banker is constructible from anywhere, including a Render.\n// Pass `cur.Address()` for the realm's own balance, envelope included.\nfunc BalanceOf(addr address, denom string) int64 {\n\treturn banker.NewReadonlyBanker().GetCoin(addr, denom)\n}\n"},{"name":"envelope_test.gno","body":"package envelope\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst (\n\tcoin  = \"/gno.land/r/moul/x/moultest/v0:moultest\"\n\tother = \"ugnot\"\n)\n\nfunc pay(coins ...chain.Coin) {\n\ttesting.SetOriginSend(chain.NewCoins(coins...))\n}\n\nfunc TestReadsAnEmptyEnvelope(cur realm, t *testing.T) {\n\tpay()\n\tuassert.True(t, IsEmpty())\n\tuassert.Equal(t, int64(0), Amount(coin))\n\tuassert.Equal(t, 0, len(All()))\n\tuassert.PanicsContains(t, cur, \"must be paid\", func() { Require(coin) })\n}\n\nfunc TestReadsAPaidEnvelope(cur realm, t *testing.T) {\n\tpay(chain.NewCoin(coin, 250))\n\tuassert.False(t, IsEmpty())\n\tuassert.Equal(t, int64(250), Amount(coin))\n\tuassert.Equal(t, int64(250), Require(coin))\n\tuassert.Equal(t, int64(0), Amount(other), \"a denom that did not arrive reads zero\")\n\tpay()\n}\n\nfunc TestFloorsAndPrices(cur realm, t *testing.T) {\n\tpay(chain.NewCoin(coin, 100))\n\n\tuassert.Equal(t, int64(100), RequireAtLeast(coin, 100), \"the floor is inclusive\")\n\tuassert.Equal(t, int64(100), RequireAtLeast(coin, 99))\n\tuassert.PanicsContains(t, cur, \"costs at least 101\", func() { RequireAtLeast(coin, 101) })\n\n\tuassert.Equal(t, int64(100), RequireExactly(coin, 100))\n\tuassert.PanicsContains(t, cur, \"costs exactly 99\", func() { RequireExactly(coin, 99) },\n\t\t\"being overpaid is refused too, not quietly kept\")\n\tuassert.PanicsContains(t, cur, \"costs exactly 101\", func() { RequireExactly(coin, 101) })\n\tpay()\n}\n\nfunc TestOnlyRefusesAMixedEnvelope(cur realm, t *testing.T) {\n\tpay(chain.NewCoin(coin, 100))\n\tuassert.Equal(t, int64(100), Only(coin))\n\n\tpay(chain.NewCoin(coin, 100), chain.NewCoin(other, 7))\n\tuassert.Equal(t, int64(100), Amount(coin), \"the mixed envelope still reads fine\")\n\tuassert.Equal(t, int64(7), Amount(other))\n\tuassert.PanicsContains(t, cur, \"also carried 7ugnot\", func() { Only(coin) })\n\n\t// Only still requires the denom it was asked about, mixed or not.\n\tpay(chain.NewCoin(other, 7))\n\tuassert.PanicsContains(t, cur, \"must be paid\", func() { Only(coin) })\n\tpay()\n}\n\nfunc TestRequireNamesTheFlagToFix(cur realm, t *testing.T) {\n\t// The abort is the realm's user interface at the moment somebody got it\n\t// wrong, so it carries the flag and the denom, not a status code.\n\tpay()\n\tuassert.PanicsContains(t, cur, \"-send \u003camount\u003e\"+coin, func() { Require(coin) })\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/envelope/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"framelab","path":"gno.land/p/moul/x/framelab/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/framelab/v0`\n\nA 30-line probe for one language property: **pure-package code runs in the frame\nof the realm that imported it**, when that realm forwards its own `cur`.\n\nThe instance-per-realm pattern (`p/moul/x/pair/v0`) rests entirely on this. If\nthe frame shifted, a shared `p/` could not move an instance's funds and every\ninstance would have to carry its own copy of the logic.\n\n`r/moul/x/framelab/probe/v0` is the realm that exercises it, and asserts:\n\n- pure-package code reports the **instance realm's** path and address;\n- the forwarded `rlm.IsCurrent()` is still true, so grc20's spoof check passes;\n- a `TransferFrom` issued from inside the pure package credits the **instance\n  realm's** own address.\n\nIt also pins the two rules found while proving it: a pure package cannot declare\na crossing function (`func F(cur realm, ...)`), and the realm parameter cannot be\nnamed `cur` there. Hence the `(_ int, rlm realm, ...)` shape used throughout.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/framelab/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/framelab/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"framelab.gno","body":"// Package framelab probes, at runtime, which realm frame pure-package code\n// executes in when a realm forwards its own `cur` into it.\n//\n// The whole instance-per-realm (\"factory\") pattern rests on the answer: if a\n// p/ helper acting on `cur` binds to the *importing realm's* identity, then a\n// 20-line instance realm can hold state and funds while every line of logic\n// lives in one shared pure package. If instead the frame shifts, the pattern\n// is dead and each instance has to carry its own copy of the logic.\npackage framelab\n\nimport \"gno.land/p/nt/grc20/v0\"\n\n// The leading `_ int` is mandatory, not cosmetic: gno rejects a function whose\n// FIRST parameter is `realm` when it is declared in a pure package (\"crossing\n// function declared in non-realm package\"). Same reason grc20's Teller methods\n// are shaped `Transfer(_ int, rlm realm, ...)`. The name matters too: only the\n// first realm argument of a real crossing function may be called `cur`.\n//\n// Who reports the frame identity as seen from inside pure-package code.\nfunc Who(_ int, rlm realm) (pkgPath string, addr address, isCurrent bool) {\n\treturn rlm.PkgPath(), rlm.Address(), rlm.IsCurrent()\n}\n\n// Pull performs the operation the pattern actually needs: a GRC20 pull done by\n// pure-package code, under the importing realm's identity. It returns the\n// address the teller bound to, which is the claim under test.\nfunc Pull(_ int, rlm realm, tok *grc20.Token, from address, amount int64) address {\n\tself := rlm.Address()\n\terr := tok.RealmTeller(0, rlm).TransferFrom(0, rlm, from, self, amount)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn self\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/framelab/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"accrual","path":"gno.land/p/moul/x/games/accrual/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/games/accrual/v0`\n\n**Stock that fills at a rate while nobody is playing**: `New`, `Rate.Advance`, `Rate.At`,\n`Rate.Full`.\n\n```go\nimport \"gno.land/p/moul/x/games/accrual/v0\"\n\nr, _ := accrual.New(1, 60, 120)              // 1 ore a minute, the mine holds 120\nstock, anchor, _ := r.Advance(0, t, t+3599)  // → 59, t+3540   (the anchor is NOT t+3599)\nstock, _ = r.At(stock, anchor, t+7200)       // → 120, capped, and nothing was written\nfull, _ := r.Full(0, t)                      // → t+7200, when production starts spilling\n```\n\nAn idle game's resource field, a 4X's warehouse, a pet's hunger: all the same shape. Store\nwhat you had and when, compute the rest on demand, and a player who is away for a month\ncosts the chain nothing. No cron, no keeper, no per-block hook.\n\n**The anchor does not advance to `now`, deliberately.** It advances by the whole periods it\nactually paid for, and the part-period in progress stays on the clock. That single decision\nis the package:\n\n\u003e `Advance(s, a, c) == Advance(Advance(s, a, b), b, c)` for `a \u003c= b \u003c= c`\n\nHow often you call must not change where you end up. Re-anchor to `now` instead and the\ndivision truncates, so every call forfeits the fraction it landed in. Run backwards on a\ndecaying stat it stops being unfair and starts being free: `r/moul/x/daily/tamagotchi`\ndecayed by `elapsed/2` and `elapsed/3`, so at `elapsed == 1` it decayed by nothing, and\nfeeding once per block made the pet immortal while every other cadence died inside 240\nblocks. Fixed in #221. The test here asserts the invariant over pseudo-random partitions,\nbecause hand-picked spans are exactly the ones a wrong implementation already passes:\nreverting the anchor fix turns four tests red.\n\nThree more behaviours worth knowing before you use it:\n\n- **`At` is `Advance` with the anchor discarded.** One implementation, two call sites. The\n  same realm's second bug was a Render with its own copy of the decay, so the page showed a\n  state the next call would not honour; two implementations of one rule means one of them is\n  the stale one somebody acts on.\n- **A capped rate never returns `ErrOverflow`.** However long the player was away, the\n  answer is the cap, so a realm can size a warehouse without also bounding its own lifetime.\n  Only an uncapped rate can run out of `int64`, and it says so rather than wrapping into a\n  negative stock.\n- **`now` before the anchor is an error, not zero elapsed.** Time running backwards means a\n  stored anchor from another clock or a test that rewound. Swallowing it hides the bug for\n  as long as the stock looks plausible.\n\nEverything is O(1) in elapsed time, which is a requirement rather than an optimisation:\n`Render` runs under a query gas limit and may not write, so the player who comes back after\na month is exactly the one whose page would time out if the projection were iterative.\n\nTimes are `int64` in the caller's unit. Prefer a timestamp over a block height: a\nheight-denominated rate reprices itself every time the chain's block time moves, and\ngno.land's has moved from about 4.1s to 3.405s inside a month.\n\nLive demo: [r/moul/x/games/idle](/r/moul/x/games/idle/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"accrual.gno","body":"// Package accrual is stock that fills at a rate while nobody is playing: the\n// resource field of an idle game, the warehouse of a 4X, anything whose state\n// is a function of how long it has been left alone.\n//\n// The shape is always the same. Store what you had and when, and compute the\n// rest on demand; a player who does nothing for a month costs nothing, and the\n// realm needs no cron, no keeper and no per-block hook. That much is obvious.\n// What is not obvious is that the obvious implementation is wrong in three\n// ways, each of which has been observed in this repository rather than\n// reasoned about.\n//\n// # 1. Re-anchoring to now makes acting more often pay\n//\n// Written naively, a claim advances the anchor to now and computes\n// elapsed/Period whole periods of production. The division truncates, so every\n// claim silently forfeits the part-period it lands in, and a player who claims\n// twice forfeits twice. Run in reverse on a decaying stat it is worse than\n// unfair, it is free: [r/moul/x/daily/tamagotchi] decayed by elapsed/2 and\n// elapsed/3, so at elapsed == 1 it decayed by nothing at all, and feeding once\n// per block made the pet immortal while every other cadence died inside 240\n// blocks. It was fixed in #221.\n//\n// The invariant that rules it out is worth stating on its own, because it is\n// the whole contract of this package:\n//\n//\tAdvance(s, a, c) == Advance(Advance(s, a, b), b, c)   for a \u003c= b \u003c= c\n//\n// How often you call must not change where you end up. [Rate.Advance] gets\n// there by advancing the anchor only by the WHOLE periods it paid for, leaving\n// the remainder on the clock rather than throwing it away. TestSplitInvariant\n// asserts it over pseudo-random partitions rather than over a handful of\n// hand-picked spans, because the hand-picked spans are exactly the ones a\n// wrong implementation already passes.\n//\n// # 2. A view that does not share the write path's arithmetic drifts from it\n//\n// The same realm had a second copy of the decay for its Render, so the page\n// showed a pet the next call would not honour. Two implementations of one rule\n// means one of them is the stale one somebody acts on. Here there is one\n// function: [Rate.At] is [Rate.Advance] with the anchor discarded, so a view\n// cannot disagree with a write even in principle.\n//\n// # 3. A projection that is not closed form cannot be rendered at all\n//\n// Render runs under a query gas limit and may not write, so whatever it\n// computes has to be bounded however long the player was away. Anything\n// iterative, stepping a simulation once per block, is fine in a transaction\n// and unusable in a page: the player who comes back after a month is exactly\n// the one whose page times out. Everything here is O(1) in elapsed time, which\n// is the property that makes a live-updating page possible, not an\n// optimisation.\n//\n// Times are int64 and the unit is the caller's, block heights or unix seconds,\n// as long as it is consistent. Prefer a timestamp: a block-height rate drifts\n// in wall-clock terms every time the chain's block time moves, and gno.land's\n// has moved from about 4.1s to 3.405s inside one month. Nothing here reads the\n// chain, so a realm can test a year of its own economy without one.\n//\n// A game built on this package is at\n// [r/moul/x/games/idle](/r/moul/x/games/idle/v0).\n//\n// [r/moul/x/daily/tamagotchi]: /r/moul/x/daily/tamagotchi/v0\npackage accrual\n\nimport \"errors\"\n\nconst maxInt64 = int64(9223372036854775807)\n\nvar (\n\t// ErrBadAmount is returned when the amount produced per period is not\n\t// positive. A zero rate is a bug in the caller, not a valid still life:\n\t// it makes Full unanswerable and every Advance a no-op.\n\tErrBadAmount = errors.New(\"accrual: amount must be positive\")\n\t// ErrBadPeriod is returned when the period is not positive.\n\tErrBadPeriod = errors.New(\"accrual: period must be positive\")\n\t// ErrBadCap is returned when the cap is negative. Zero is legal and\n\t// means unbounded.\n\tErrBadCap = errors.New(\"accrual: cap must not be negative\")\n\t// ErrNegativeStock is returned when the stock handed in is negative,\n\t// which would let a caller mint by going through zero.\n\tErrNegativeStock = errors.New(\"accrual: stock must not be negative\")\n\t// ErrBackwards is returned when now falls before the anchor. Time moving\n\t// backwards is a caller bug (a stored anchor from another clock, a test\n\t// that rewound), and silently treating it as zero elapsed would hide it.\n\tErrBackwards = errors.New(\"accrual: now must not fall before the anchor\")\n\t// ErrOverflow is returned when the arithmetic would wrap int64.\n\tErrOverflow = errors.New(\"accrual: int64 overflow\")\n)\n\n// Rate is production per unit of time, against a ceiling. Construct with New\n// so the invariants are checked once instead of on every call.\ntype Rate struct {\n\tAmount int64 // produced each whole Period\n\tPeriod int64 // time units in one period\n\tCap    int64 // ceiling on the stock; zero means unbounded\n}\n\n// New validates and returns a Rate. A zero cap means unbounded.\nfunc New(amount, period, capacity int64) (Rate, error) {\n\tif amount \u003c= 0 {\n\t\treturn Rate{}, ErrBadAmount\n\t}\n\tif period \u003c= 0 {\n\t\treturn Rate{}, ErrBadPeriod\n\t}\n\tif capacity \u003c 0 {\n\t\treturn Rate{}, ErrBadCap\n\t}\n\treturn Rate{Amount: amount, Period: period, Cap: capacity}, nil\n}\n\n// Advance returns the stock and the new anchor at time now, given stock held\n// since anchor.\n//\n// The new anchor is NOT now. It is the anchor plus the whole periods actually\n// paid out, so the part-period in progress stays on the clock and splitting a\n// span into pieces yields exactly what advancing it in one go would:\n//\n//\tAdvance(s, a, c) == Advance(Advance(s, a, b), b, c)   for a \u003c= b \u003c= c\n//\n// Production past the cap is lost, which is what a cap is for. Saturation is\n// idempotent, so it does not break the equality above, and it means a CAPPED\n// rate can never return ErrOverflow: the answer is the cap however long the\n// player was away. Only an uncapped rate can run out of int64.\nfunc (r Rate) Advance(stock, anchor, now int64) (int64, int64, error) {\n\tif err := r.check(); err != nil {\n\t\treturn 0, 0, err\n\t}\n\tif stock \u003c 0 {\n\t\treturn 0, 0, ErrNegativeStock\n\t}\n\tif now \u003c anchor {\n\t\treturn 0, 0, ErrBackwards\n\t}\n\t// now-anchor wraps only when the anchor is negative and now is far\n\t// enough above it. maxInt64+anchor is safe to compute precisely because\n\t// anchor is negative there.\n\tif anchor \u003c 0 \u0026\u0026 now \u003e maxInt64+anchor {\n\t\treturn 0, 0, ErrOverflow\n\t}\n\n\tperiods := (now - anchor) / r.Period\n\n\t// The anchor only moves by what was paid for. periods*r.Period cannot\n\t// overflow, it is at most now-anchor, and adding it back cannot pass now.\n\tnewAnchor := anchor + periods*r.Period\n\n\tif r.Cap \u003e 0 \u0026\u0026 stock \u003e= r.Cap {\n\t\treturn stock, newAnchor, nil\n\t}\n\n\t// Production is only computed when its exact value can matter. A capped\n\t// rate whose payout would wrap int64 has an answer regardless of what\n\t// that payout is, so it gets one instead of an error.\n\tif periods \u003e maxInt64/r.Amount {\n\t\treturn r.saturate(newAnchor)\n\t}\n\tproduced := periods * r.Amount\n\tif produced \u003e maxInt64-stock {\n\t\treturn r.saturate(newAnchor)\n\t}\n\n\ttotal := stock + produced\n\tif r.Cap \u003e 0 \u0026\u0026 total \u003e r.Cap {\n\t\ttotal = r.Cap\n\t}\n\treturn total, newAnchor, nil\n}\n\n// saturate answers an accrual too large for int64: the cap if there is one,\n// and an error if there is not. A capped Rate therefore never overflows,\n// which is the property that lets a realm size a warehouse without also\n// having to bound its own lifetime.\nfunc (r Rate) saturate(newAnchor int64) (int64, int64, error) {\n\tif r.Cap == 0 {\n\t\treturn 0, 0, ErrOverflow\n\t}\n\treturn r.Cap, newAnchor, nil\n}\n\n// At is Advance with the anchor discarded: the read-only view of the same\n// arithmetic, for a Render that must not write. It is defined in terms of\n// Advance on purpose, so a page can never show a number a write would not\n// honour.\nfunc (r Rate) At(stock, anchor, now int64) (int64, error) {\n\tgot, _, err := r.Advance(stock, anchor, now)\n\treturn got, err\n}\n\n// Full returns the time at which the stock first reaches the cap, for a realm\n// that wants to tell a player when their production starts being wasted.\n//\n// An uncapped rate returns zero, meaning never. A stock already at or past the\n// cap returns the anchor, meaning now.\nfunc (r Rate) Full(stock, anchor int64) (int64, error) {\n\tif err := r.check(); err != nil {\n\t\treturn 0, err\n\t}\n\tif stock \u003c 0 {\n\t\treturn 0, ErrNegativeStock\n\t}\n\tif r.Cap == 0 {\n\t\treturn 0, nil\n\t}\n\tif stock \u003e= r.Cap {\n\t\treturn anchor, nil\n\t}\n\n\t// Whole periods needed to cover the shortfall, rounded UP: the cap is\n\t// reached by the payout that crosses it, not by the one before.\n\tneed := r.Cap - stock\n\tperiods := need / r.Amount\n\tif need%r.Amount != 0 {\n\t\tperiods++\n\t}\n\tif periods \u003e maxInt64/r.Period {\n\t\treturn 0, ErrOverflow\n\t}\n\tspan := periods * r.Period\n\tif span \u003e maxInt64-anchor {\n\t\treturn 0, ErrOverflow\n\t}\n\treturn anchor + span, nil\n}\n\n// check rejects a zero Rate built by struct literal instead of New, so a\n// caller that skipped the constructor gets the same error it would have.\nfunc (r Rate) check() error {\n\tif r.Amount \u003c= 0 {\n\t\treturn ErrBadAmount\n\t}\n\tif r.Period \u003c= 0 {\n\t\treturn ErrBadPeriod\n\t}\n\tif r.Cap \u003c 0 {\n\t\treturn ErrBadCap\n\t}\n\treturn nil\n}\n"},{"name":"accrual_test.gno","body":"package accrual\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc mustNew(t *testing.T, amount, period, capacity int64) Rate {\n\tt.Helper()\n\tr, err := New(amount, period, capacity)\n\tuassert.NoError(t, err)\n\treturn r\n}\n\nfunc TestNewValidation(t *testing.T) {\n\tcases := []struct {\n\t\tname                     string\n\t\tamount, period, capacity int64\n\t\twant                     error\n\t}{\n\t\t{\"zero amount\", 0, 60, 100, ErrBadAmount},\n\t\t{\"negative amount\", -1, 60, 100, ErrBadAmount},\n\t\t{\"zero period\", 1, 0, 100, ErrBadPeriod},\n\t\t{\"negative period\", 1, -60, 100, ErrBadPeriod},\n\t\t{\"negative cap\", 1, 60, -1, ErrBadCap},\n\t\t{\"zero cap is unbounded\", 1, 60, 0, nil},\n\t\t{\"all positive\", 5, 60, 100, nil},\n\t}\n\tfor _, tc := range cases {\n\t\t_, err := New(tc.amount, tc.period, tc.capacity)\n\t\tif tc.want == nil {\n\t\t\tuassert.NoError(t, err, tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.ErrorIs(t, err, tc.want, tc.name)\n\t}\n}\n\nfunc TestAdvance(t *testing.T) {\n\tcases := []struct {\n\t\tname                     string\n\t\tamount, period, capacity int64\n\t\tstock, anchor, now       int64\n\t\twantStock, wantAnchor    int64\n\t}{\n\t\t{\"nothing elapsed\", 1, 60, 0, 0, 1000, 1000, 0, 1000},\n\t\t{\"less than one period\", 1, 60, 0, 0, 1000, 1059, 0, 1000},\n\t\t{\"exactly one period\", 1, 60, 0, 0, 1000, 1060, 1, 1060},\n\t\t{\"one period and change keeps the change\", 1, 60, 0, 0, 1000, 1119, 1, 1060},\n\t\t{\"ten periods\", 3, 60, 0, 0, 1000, 1600, 30, 1600},\n\t\t{\"adds to what was held\", 3, 60, 0, 7, 1000, 1600, 37, 1600},\n\t\t{\"saturates at the cap\", 1, 60, 10, 0, 1000, 9000, 10, 8980},\n\t\t{\"already full produces nothing\", 1, 60, 10, 10, 1000, 9000, 10, 8980},\n\t\t{\"over the cap is left alone\", 1, 60, 10, 25, 1000, 9000, 25, 8980},\n\t\t{\"uncapped keeps going\", 1, 60, 0, 0, 0, 604800, 10080, 604800},\n\t}\n\tfor _, tc := range cases {\n\t\tr := mustNew(t, tc.amount, tc.period, tc.capacity)\n\t\tgotStock, gotAnchor, err := r.Advance(tc.stock, tc.anchor, tc.now)\n\t\tuassert.NoError(t, err, tc.name)\n\t\tuassert.Equal(t, tc.wantStock, gotStock, tc.name+\": stock\")\n\t\tuassert.Equal(t, tc.wantAnchor, gotAnchor, tc.name+\": anchor\")\n\t}\n}\n\n// TestAnchorKeepsTheRemainder pins the one decision the whole package rests\n// on: the new anchor is not now. Advancing to a time halfway through a period\n// leaves that half on the clock, which is what makes splitting free.\nfunc TestAnchorKeepsTheRemainder(t *testing.T) {\n\tr := mustNew(t, 1, 60, 0)\n\t_, anchor, err := r.Advance(0, 0, 599)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(540), anchor, \"anchor must stop at the last whole period, not at now\")\n}\n\n// TestSplitInvariant is the contract of this package:\n//\n//\tAdvance(s, a, c) == Advance(Advance(s, a, b), b, c)\n//\n// It runs over pseudo-random partitions rather than hand-picked ones, because\n// an implementation that re-anchors to now passes every round span and only\n// fails on the ones that land mid-period. The generator is a fixed LCG, so a\n// failure is reproducible.\nfunc TestSplitInvariant(t *testing.T) {\n\trates := []Rate{\n\t\tmustNew(t, 1, 60, 0),      // one a minute, unbounded\n\t\tmustNew(t, 7, 13, 0),      // coprime, so remainders never line up\n\t\tmustNew(t, 1, 60, 500),    // capped\n\t\tmustNew(t, 250, 3600, 0),  // coarse period\n\t\tmustNew(t, 1, 1, 0),       // degenerate: every tick pays\n\t\tmustNew(t, 3, 1000, 1234), // capped and coarse\n\t}\n\n\tseed := uint64(0x9E3779B97F4A7C15)\n\tnext := func(n int64) int64 {\n\t\tseed = seed*6364136223846793005 + 1442695040888963407\n\t\treturn int64(seed\u003e\u003e33) % n\n\t}\n\n\tfor _, r := range rates {\n\t\tfor i := 0; i \u003c 400; i++ {\n\t\t\tstart := next(10000)\n\t\t\tspan := next(100000)\n\t\t\tstock := next(600)\n\t\t\tend := start + span\n\n\t\t\twantStock, wantAnchor, err := r.Advance(stock, start, end)\n\t\t\tuassert.NoError(t, err)\n\n\t\t\t// Cut the span into between one and six pieces and walk them.\n\t\t\tcuts := next(6) + 1\n\t\t\tgotStock, gotAnchor := stock, start\n\t\t\tat := start\n\t\t\tfor c := int64(0); c \u003c cuts; c++ {\n\t\t\t\tremaining := end - at\n\t\t\t\tif remaining \u003c= 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tstep := next(remaining + 1)\n\t\t\t\tif c == cuts-1 {\n\t\t\t\t\tstep = remaining\n\t\t\t\t}\n\t\t\t\tat += step\n\t\t\t\tgotStock, gotAnchor, err = r.Advance(gotStock, gotAnchor, at)\n\t\t\t\tuassert.NoError(t, err)\n\t\t\t}\n\t\t\t// Land on the end whatever the cuts did.\n\t\t\tgotStock, gotAnchor, err = r.Advance(gotStock, gotAnchor, end)\n\t\t\tuassert.NoError(t, err)\n\n\t\t\tuassert.Equal(t, wantStock, gotStock, \"split stock diverged\")\n\t\t\tuassert.Equal(t, wantAnchor, gotAnchor, \"split anchor diverged\")\n\t\t}\n\t}\n}\n\n// TestClaimingEveryTickIsNotFree is the regression for the bug this package\n// exists to make unrepresentable. r/moul/x/daily/tamagotchi truncated its\n// per-call decay, so acting every tick cost nothing and acting rarely cost\n// everything. Here the two agree exactly.\nfunc TestClaimingEveryTickIsNotFree(t *testing.T) {\n\tr := mustNew(t, 1, 60, 0)\n\tconst span = 6000 // 100 whole periods\n\n\toneShot, _, err := r.Advance(0, 0, span)\n\tuassert.NoError(t, err)\n\n\tfor _, cadence := range []int64{1, 2, 7, 60, 61, 599, 3000} {\n\t\tstock, anchor := int64(0), int64(0)\n\t\tfor at := cadence; at \u003c= span; at += cadence {\n\t\t\tstock, anchor, err = r.Advance(stock, anchor, at)\n\t\t\tuassert.NoError(t, err)\n\t\t}\n\t\tstock, _, err = r.Advance(stock, anchor, span)\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, oneShot, stock, \"cadence changed the payout\")\n\t}\n}\n\n// TestAtMatchesAdvance pins that the read path cannot drift from the write\n// path, which was the second and quieter half of the tamagotchi bug.\nfunc TestAtMatchesAdvance(t *testing.T) {\n\tr := mustNew(t, 5, 17, 900)\n\tfor now := int64(3); now \u003c 4000; now += 37 {\n\t\twant, _, err := r.Advance(11, 3, now)\n\t\tuassert.NoError(t, err)\n\t\tgot, err := r.At(11, 3, now)\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, want, got, \"At diverged from Advance\")\n\t}\n}\n\nfunc TestAdvanceRejects(t *testing.T) {\n\tr := mustNew(t, 1, 60, 0)\n\n\t_, _, err := r.Advance(-1, 0, 100)\n\tuassert.ErrorIs(t, err, ErrNegativeStock)\n\n\t_, _, err = r.Advance(0, 100, 99)\n\tuassert.ErrorIs(t, err, ErrBackwards)\n\n\t// A Rate built by literal instead of New is still checked.\n\t_, _, err = Rate{}.Advance(0, 0, 100)\n\tuassert.ErrorIs(t, err, ErrBadAmount)\n\t_, _, err = Rate{Amount: 1}.Advance(0, 0, 100)\n\tuassert.ErrorIs(t, err, ErrBadPeriod)\n\t_, _, err = Rate{Amount: 1, Period: 1, Cap: -1}.Advance(0, 0, 100)\n\tuassert.ErrorIs(t, err, ErrBadCap)\n}\n\nfunc TestAdvanceOverflow(t *testing.T) {\n\t// An uncapped rate that would pass int64 refuses rather than wrapping\n\t// into a negative stock, which is how a large vesting grant once\n\t// reported a negative balance.\n\tr := mustNew(t, maxInt64/2, 1, 0)\n\t_, _, err := r.Advance(0, 0, 100)\n\tuassert.ErrorIs(t, err, ErrOverflow)\n\n\t// The same rate with a cap always has an answer, so it gives one\n\t// instead of an error, whichever of the two guards it trips.\n\tcapped := mustNew(t, maxInt64/2, 1, 1000)\n\tgot, anchor, err := capped.Advance(0, 0, 100)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(1000), got)\n\tuassert.Equal(t, int64(100), anchor, \"a saturated advance still moves the anchor\")\n\n\tgot, _, err = capped.Advance(999, 0, 1)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(1000), got, \"the sum guard saturates too\")\n\n\t// A negative anchor far enough below now wraps the elapsed span itself.\n\tslow := mustNew(t, 1, maxInt64, 0)\n\t_, _, err = slow.Advance(0, -10, maxInt64-5)\n\tuassert.ErrorIs(t, err, ErrOverflow)\n}\n\nfunc TestFull(t *testing.T) {\n\tcases := []struct {\n\t\tname                     string\n\t\tamount, period, capacity int64\n\t\tstock, anchor            int64\n\t\twant                     int64\n\t}{\n\t\t{\"uncapped never fills\", 1, 60, 0, 0, 1000, 0},\n\t\t{\"already full is now\", 1, 60, 10, 10, 1000, 1000},\n\t\t{\"past full is now\", 1, 60, 10, 99, 1000, 1000},\n\t\t{\"empty takes the whole cap\", 1, 60, 10, 0, 1000, 1600},\n\t\t{\"partly full takes the rest\", 1, 60, 10, 4, 1000, 1360},\n\t\t{\"rounds up to the payout that crosses\", 3, 60, 10, 0, 0, 240},\n\t\t{\"exact division does not round up\", 5, 60, 10, 0, 0, 120},\n\t}\n\tfor _, tc := range cases {\n\t\tr := mustNew(t, tc.amount, tc.period, tc.capacity)\n\t\tgot, err := r.Full(tc.stock, tc.anchor)\n\t\tuassert.NoError(t, err, tc.name)\n\t\tuassert.Equal(t, tc.want, got, tc.name)\n\t}\n}\n\n// TestFullAgreesWithAdvance checks the two halves of the API against each\n// other: at the time Full names, the stock is at the cap, and one period\n// earlier it is not.\nfunc TestFullAgreesWithAdvance(t *testing.T) {\n\tfor _, r := range []Rate{\n\t\tmustNew(t, 1, 60, 10),\n\t\tmustNew(t, 3, 60, 10),\n\t\tmustNew(t, 7, 13, 1000),\n\t\tmustNew(t, 250, 3600, 875),\n\t} {\n\t\tfull, err := r.Full(0, 0)\n\t\tuassert.NoError(t, err)\n\n\t\tatFull, err := r.At(0, 0, full)\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, r.Cap, atFull, \"not full at the time Full named\")\n\n\t\tbefore, err := r.At(0, 0, full-r.Period)\n\t\tuassert.NoError(t, err)\n\t\tif before \u003e= r.Cap {\n\t\t\tt.Errorf(\"already full a period early: %d \u003e= %d\", before, r.Cap)\n\t\t}\n\t}\n}\n\nfunc TestFullRejects(t *testing.T) {\n\tr := mustNew(t, 1, 60, 10)\n\t_, err := r.Full(-1, 0)\n\tuassert.ErrorIs(t, err, ErrNegativeStock)\n\n\t_, err = Rate{}.Full(0, 0)\n\tuassert.ErrorIs(t, err, ErrBadAmount)\n\n\tfar := mustNew(t, 1, maxInt64/2, 1000)\n\t_, err = far.Full(0, 0)\n\tuassert.ErrorIs(t, err, ErrOverflow)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/games/accrual/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"9000000ugnot"}],"fee":{"gas_wanted":"2044719200","gas_fee":"6134157ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"hXgDqfhBw4MeEUQF/WEgXuFqazXTEwj1zOu3PuPOQD9gsjLm/pvqj5q2/fsWFpfu9K6uUhoR15kkt++zjdpOpA=="}],"memo":""},"metadata":{"timestamp":"1790960261"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"clock","path":"gno.land/p/moul/x/games/clock/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/games/clock/v0`\n\n**A deadline that actions push forward, and that still ends**: `New`, `Bump`,\n`BumpBy`, `BumpShare`, `Expired`, `Remaining`, `Deadline`, `HardEnd`, `Final`.\n\n```go\nimport \"gno.land/p/moul/x/games/clock/v0\"\n\nc, _ := clock.New(height, 2000, 300, 100000) // now, window, floor, life\nc.Deadline()          // height+2000\nc.BumpShare(h, 20)    // a write buys a fifth of the gap to the hard end\nc.Expired(h)          // the game is over, and cannot be reopened\nc.Final()             // the deadline has hit the hard end: holding now beats acting\n```\n\nEvery last-action-wins game has this clock, and written the obvious way it fails\nin one of two opposite directions.\n\n**With a constant extension it never ends.** The pot grows faster than the price\nof the next action, so the pot-to-price ratio *rises*, there is always a rational\nnext action, and the second-to-last actor is always the mark. `life` is the\nterminator: an absolute end, fixed when the clock opens, that no bump can pass.\n\n**With a decaying extension it ends too suddenly.** A grant that shrinks toward\nzero makes the last stretch shorter than the time a transaction needs to land,\nso whoever is holding at that moment wins by being unreachable rather than by\npaying. `floor` is the anti-snipe: a bump always leaves at least that much on the\nclock.\n\nFour invariants, deliberately in the library and not in the caller:\n\n- **An expired clock never restarts.** A late action cannot reopen a settled\n  game, which is the difference between a closed pot and a stolen one.\n- **The deadline never moves backwards.** A small grant late in the game leaves\n  the existing deadline alone instead of shortening it.\n- **A bump always leaves at least the floor**, however little there was to share.\n- **The deadline never passes the hard end**, against any grant, including one\n  that would overflow an int64.\n\n**The caller owns the policy, the clock owns the guards.** `BumpBy` takes\nwhatever grant the game computed: a constant, a function of the amount paid,\nanything. `BumpShare` is the one worth knowing, and it is a share of the distance\nto the **hard end**, not of the time remaining: `now + (deadline-now)*pct/100` is\nalways *before* the deadline, so the obvious formula extends nothing at all. A\nshare of the gap to the hard end makes each action close a fraction of what is\nleft, so the grants shrink as the game runs, which is the pressure a constant\ngrant never relieves.\n\nTimes are `int64` and the unit is the caller's, block heights or unix seconds, as\nlong as it is consistent. Nothing here reads the chain, so a realm can test its\nwhole endgame without one.\n\n**Live game:** [`r/moul/x/games/lastwords`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/games/lastwords)\n· render it at [`/r/moul/x/games/lastwords/v0`](https://gno.land/r/moul/x/games/lastwords/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"clock.gno","body":"// Package clock is a deadline that actions push forward, with the two guards a\n// naive \"extend on every action\" clock lacks.\n//\n// Any last-action-wins game has the same clock: every action buys more time, so\n// the game ends only when nobody acts. Written naively it has two failure modes,\n// and both have been observed on chain rather than reasoned about.\n//\n// The first is that it never ends. If the grant per action is constant, a\n// contested pot is extended forever and the prize is always worth one more\n// action. Life is the terminator: an absolute end, fixed when the clock opens,\n// that no bump can pass. A game with real money in it needs one.\n//\n// The second is the opposite, and it shows up as soon as the grant decays to\n// relieve the pressure of the first: a grant that is a share of the life left\n// shrinks toward zero near the end, so the last stretch becomes too short for a\n// transaction to land in, and whoever is holding when that happens simply wins.\n// Floor is the anti-snipe: a bump always leaves at least that much on the\n// clock, however little is left to share.\n//\n// Times are int64 and the unit is the caller's: block heights or unix seconds,\n// as long as it is consistent. Nothing here reads the chain, so a realm can\n// test its whole endgame without one.\n//\n// A game built on this package is at\n// [r/moul/x/games/lastwords](/r/moul/x/games/lastwords/v0).\npackage clock\n\nimport \"errors\"\n\nconst maxInt64 = int64(9223372036854775807)\n\nvar (\n\t// ErrBadWindow is returned when the opening grant is not positive.\n\tErrBadWindow = errors.New(\"clock: window must be positive\")\n\t// ErrBadFloor is returned when the floor is negative or exceeds the window.\n\tErrBadFloor = errors.New(\"clock: floor must be between zero and the window\")\n\t// ErrBadLife is returned when the life is negative, or positive but shorter\n\t// than the opening window, which would close the clock before it opened.\n\tErrBadLife = errors.New(\"clock: life must be zero (unbounded) or at least the window\")\n\t// ErrBadShare is returned when a share is outside 0..100.\n\tErrBadShare = errors.New(\"clock: share must be a percentage between 0 and 100\")\n\t// ErrUnbounded is returned when a share of the remaining life is asked of a\n\t// clock that has no hard end to measure against.\n\tErrUnbounded = errors.New(\"clock: a share of the life needs a bounded clock\")\n\t// ErrOverflow is returned when the requested times do not fit in an int64.\n\tErrOverflow = errors.New(\"clock: times overflow int64\")\n)\n\n// Clock is a deadline plus the three bounds that make it terminate: the window\n// a bump grants, the floor a bump always leaves, and the life it can never pass.\n//\n// The zero Clock is not usable; build one with New.\ntype Clock struct {\n\tstart    int64\n\tdeadline int64\n\twindow   int64\n\tfloor    int64\n\tlife     int64 // 0 means unbounded\n}\n\n// New opens a clock at now, due now+window.\n//\n// window is what a plain Bump grants. floor is the minimum a bump leaves on the\n// clock, and must not exceed the window (a floor above the window would mean\n// every bump granting more than the window, which is not a floor). life is the\n// total lifetime from now, after which the deadline can no longer move; zero\n// leaves the clock unbounded, which is the shape that never terminates, so pass\n// it deliberately.\nfunc New(now, window, floor, life int64) (*Clock, error) {\n\tif window \u003c= 0 {\n\t\treturn nil, ErrBadWindow\n\t}\n\tif floor \u003c 0 || floor \u003e window {\n\t\treturn nil, ErrBadFloor\n\t}\n\tif life \u003c 0 || (life \u003e 0 \u0026\u0026 life \u003c window) {\n\t\treturn nil, ErrBadLife\n\t}\n\tif window \u003e maxInt64-now || life \u003e maxInt64-now {\n\t\treturn nil, ErrOverflow\n\t}\n\treturn \u0026Clock{\n\t\tstart:    now,\n\t\tdeadline: now + window,\n\t\twindow:   window,\n\t\tfloor:    floor,\n\t\tlife:     life,\n\t}, nil\n}\n\n// Start returns when the clock opened.\nfunc (c *Clock) Start() int64 { return c.start }\n\n// Deadline returns the time the clock currently expires at.\nfunc (c *Clock) Deadline() int64 { return c.deadline }\n\n// Window returns the grant a plain Bump aims for.\nfunc (c *Clock) Window() int64 { return c.window }\n\n// Floor returns the minimum a bump leaves on the clock.\nfunc (c *Clock) Floor() int64 { return c.floor }\n\n// Life returns the configured lifetime, zero when unbounded.\nfunc (c *Clock) Life() int64 { return c.life }\n\n// HardEnd returns the time no bump can push the deadline past, or zero when the\n// clock is unbounded.\nfunc (c *Clock) HardEnd() int64 {\n\tif c.life == 0 {\n\t\treturn 0\n\t}\n\treturn c.start + c.life\n}\n\n// Expired reports whether the clock has run out at now. The deadline itself is\n// past it: a clock due at 100 is expired at 100, so an action and an expiry can\n// never both be valid at the same instant.\nfunc (c *Clock) Expired(now int64) bool { return now \u003e= c.deadline }\n\n// Remaining returns how much time is left at now, never negative.\nfunc (c *Clock) Remaining(now int64) int64 {\n\tif now \u003e= c.deadline {\n\t\treturn 0\n\t}\n\treturn c.deadline - now\n}\n\n// Elapsed returns how long the clock has been open at now, never negative.\nfunc (c *Clock) Elapsed(now int64) int64 {\n\tif now \u003c= c.start {\n\t\treturn 0\n\t}\n\treturn now - c.start\n}\n\n// Final reports whether the deadline has reached the hard end, so no further\n// bump can move it. A game should say so on its page: it is the only moment at\n// which holding is worth more than acting.\nfunc (c *Clock) Final() bool { return c.life \u003e 0 \u0026\u0026 c.deadline \u003e= c.HardEnd() }\n\n// Bump extends the deadline by the window. See BumpBy for the guards.\nfunc (c *Clock) Bump(now int64) int64 { return c.BumpBy(now, c.window) }\n\n// BumpBy extends the deadline to now+grant and returns the new deadline.\n//\n// The caller owns the policy, so grant is whatever it wants: a constant, a share\n// of what is left, a function of the amount paid. The clock owns the four\n// invariants that policy keeps getting wrong:\n//\n//   - An expired clock never restarts. Once it has run out the deadline is\n//     frozen, so a late action cannot reopen a settled game.\n//   - The deadline never moves backwards. A small grant late in the game leaves\n//     the existing deadline alone rather than shortening it.\n//   - A bump always leaves at least the floor on the clock, so a decaying grant\n//     cannot be shaved below the time a transaction needs to land.\n//   - The deadline never passes the hard end.\nfunc (c *Clock) BumpBy(now, grant int64) int64 {\n\tif c.Expired(now) {\n\t\treturn c.deadline\n\t}\n\tif grant \u003c c.floor {\n\t\tgrant = c.floor\n\t}\n\twant := c.deadline\n\tif grant \u003c= maxInt64-now \u0026\u0026 now+grant \u003e want {\n\t\twant = now + grant\n\t} else if grant \u003e maxInt64-now {\n\t\twant = maxInt64\n\t}\n\tif end := c.HardEnd(); c.life \u003e 0 \u0026\u0026 want \u003e end {\n\t\twant = end\n\t}\n\tc.deadline = want\n\treturn c.deadline\n}\n\n// BumpShare grants pct percent of the time left until the hard end, and is the\n// decaying grant a converging game wants.\n//\n// A grant that is a share of what is left on the DEADLINE cannot extend\n// anything: now+(deadline-now)*pct/100 is always before the deadline itself. A\n// share of the distance to the hard end is the one that works. Each action\n// closes a fraction of the gap, so the deadline crawls toward the hard end and\n// the grants shrink as it does, which is exactly the \"the pot is worth one more\n// action\" pressure a fixed grant never relieves. The floor is what stops the\n// tail of that curve from becoming too short to act in.\n//\n// It requires a bounded clock: there is no distance to share without one.\nfunc (c *Clock) BumpShare(now, pct int64) (int64, error) {\n\tif c.life == 0 {\n\t\treturn c.deadline, ErrUnbounded\n\t}\n\tif pct \u003c 0 || pct \u003e 100 {\n\t\treturn c.deadline, ErrBadShare\n\t}\n\tleft := c.HardEnd() - now\n\tif left \u003c 0 {\n\t\tleft = 0\n\t}\n\tvar grant int64\n\tif left \u003e maxInt64/100 {\n\t\tgrant = left / 100 * pct // lossy, but only where exactness is meaningless\n\t} else {\n\t\tgrant = left * pct / 100 // multiply first, so a small gap still grants\n\t}\n\treturn c.BumpBy(now, grant), nil\n}\n"},{"name":"clock_test.gno","body":"package clock\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc mustNew(t *testing.T, now, window, floor, life int64) *Clock {\n\tt.Helper()\n\tc, err := New(now, window, floor, life)\n\tuassert.NoError(t, err)\n\treturn c\n}\n\nfunc TestNewValidation(t *testing.T) {\n\tcases := []struct {\n\t\tname                     string\n\t\tnow, window, floor, life int64\n\t\twant                     error\n\t}{\n\t\t{\"zero window\", 0, 0, 0, 0, ErrBadWindow},\n\t\t{\"negative window\", 0, -1, 0, 0, ErrBadWindow},\n\t\t{\"negative floor\", 0, 100, -1, 0, ErrBadFloor},\n\t\t{\"floor above window\", 0, 100, 101, 0, ErrBadFloor},\n\t\t{\"negative life\", 0, 100, 10, -1, ErrBadLife},\n\t\t{\"life shorter than window\", 0, 100, 10, 99, ErrBadLife},\n\t\t{\"window overflows\", maxInt64 - 5, 100, 0, 0, ErrOverflow},\n\t\t{\"life overflows\", maxInt64 - 500, 100, 0, 1000, ErrOverflow},\n\t\t{\"unbounded is legal\", 0, 100, 10, 0, nil},\n\t\t{\"life equal to window is legal\", 0, 100, 10, 100, nil},\n\t\t{\"floor equal to window is legal\", 0, 100, 100, 0, nil},\n\t}\n\tfor _, tc := range cases {\n\t\t_, err := New(tc.now, tc.window, tc.floor, tc.life)\n\t\tif tc.want == nil {\n\t\t\tuassert.NoError(t, err, tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.ErrorIs(t, err, tc.want, tc.name)\n\t}\n}\n\nfunc TestOpensDueAtWindow(t *testing.T) {\n\tc := mustNew(t, 1000, 100, 10, 500)\n\tuassert.Equal(t, int64(1000), c.Start())\n\tuassert.Equal(t, int64(1100), c.Deadline())\n\tuassert.Equal(t, int64(1500), c.HardEnd())\n\tuassert.Equal(t, int64(100), c.Remaining(1000))\n\tuassert.Equal(t, int64(0), c.Elapsed(1000))\n\tuassert.False(t, c.Expired(1099))\n\tuassert.True(t, c.Expired(1100), \"the deadline itself is expired\")\n\tuassert.False(t, c.Final())\n}\n\nfunc TestUnboundedHasNoHardEnd(t *testing.T) {\n\tc := mustNew(t, 0, 100, 0, 0)\n\tuassert.Equal(t, int64(0), c.HardEnd())\n\tuassert.False(t, c.Final(), \"an unbounded clock is never final\")\n\tc.Bump(90)\n\tc.Bump(180)\n\tuassert.Equal(t, int64(280), c.Deadline(), \"nothing caps it\")\n}\n\n// TestBumpNeverMovesBackwards is the invariant a caller supplying its own grant\n// gets wrong first: a late, small grant must not shorten the clock.\nfunc TestBumpNeverMovesBackwards(t *testing.T) {\n\tc := mustNew(t, 0, 1000, 0, 0)\n\tuassert.Equal(t, int64(1000), c.Deadline())\n\n\tuassert.Equal(t, int64(1000), c.BumpBy(10, 5), \"now+5 is before the deadline\")\n\tuassert.Equal(t, int64(1000), c.BumpBy(900, 0), \"a zero grant leaves it alone\")\n\tuassert.Equal(t, int64(1100), c.BumpBy(900, 200), \"a grant past the deadline moves it\")\n}\n\n// TestFloorSurvivesATinyGrant is the anti-snipe: whatever the policy grants, a\n// bump leaves at least the floor, so the last stretch stays reachable.\nfunc TestFloorSurvivesATinyGrant(t *testing.T) {\n\tc := mustNew(t, 0, 1000, 50, 0)\n\tc.BumpBy(990, 1)\n\tuassert.Equal(t, int64(1040), c.Deadline(), \"1 was raised to the floor of 50\")\n\tuassert.Equal(t, int64(50), c.Remaining(990))\n\n\tc2 := mustNew(t, 0, 1000, 50, 0)\n\tc2.BumpBy(990, 0)\n\tuassert.Equal(t, int64(50), c2.Remaining(990), \"even a zero grant leaves the floor\")\n}\n\n// TestHardEndCapsEveryBump is the terminator: without it a contested clock is\n// extended forever and the game has no end.\nfunc TestHardEndCapsEveryBump(t *testing.T) {\n\tc := mustNew(t, 0, 100, 10, 250)\n\tuassert.Equal(t, int64(250), c.HardEnd())\n\n\tc.BumpBy(90, 100)\n\tuassert.Equal(t, int64(190), c.Deadline())\n\tc.BumpBy(180, 100)\n\tuassert.Equal(t, int64(250), c.Deadline(), \"capped at the hard end, not 280\")\n\tuassert.True(t, c.Final())\n\n\tc.BumpBy(240, 1000000)\n\tuassert.Equal(t, int64(250), c.Deadline(), \"the cap holds against any grant\")\n\tuassert.Equal(t, int64(10), c.Remaining(240), \"and it beats the floor\")\n}\n\n// TestExpiredClockNeverRestarts stops a late action from reopening a settled\n// game, which is the difference between a closed pot and a stolen one.\nfunc TestExpiredClockNeverRestarts(t *testing.T) {\n\tc := mustNew(t, 0, 100, 10, 0)\n\tuassert.True(t, c.Expired(100))\n\tuassert.Equal(t, int64(100), c.BumpBy(100, 500), \"exactly at the deadline\")\n\tuassert.Equal(t, int64(100), c.Bump(5000), \"long after\")\n\tuassert.Equal(t, int64(0), c.Remaining(100))\n\n\tsettled := mustNew(t, 0, 100, 10, 1000)\n\tuassert.True(t, settled.Expired(100))\n\tgot, err := settled.BumpShare(200, 50)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(100), got, \"not even a large share reopens it\")\n}\n\nfunc TestBumpShareValidation(t *testing.T) {\n\tc := mustNew(t, 0, 100, 0, 500)\n\t_, err := c.BumpShare(10, -1)\n\tuassert.ErrorIs(t, err, ErrBadShare)\n\t_, err = c.BumpShare(10, 101)\n\tuassert.ErrorIs(t, err, ErrBadShare)\n\tuassert.Equal(t, int64(100), c.Deadline(), \"a rejected share changes nothing\")\n\n\tunbounded := mustNew(t, 0, 100, 0, 0)\n\t_, err = unbounded.BumpShare(10, 50)\n\tuassert.ErrorIs(t, err, ErrUnbounded, \"no hard end, nothing to take a share of\")\n}\n\n// TestBumpShareDecays is why the share grant exists: each action closes a\n// fraction of the gap to the hard end, so the grants shrink as the game runs\n// and the pressure to act one more time is relieved instead of compounding.\nfunc TestBumpShareDecays(t *testing.T) {\n\tc := mustNew(t, 0, 100, 1, 1000)\n\tfirst, err := c.BumpShare(10, 50)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(505), first, \"half the 990 left to the hard end\")\n\n\tsecond, err := c.BumpShare(500, 50)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(750), second, \"half of the 500 now left, a smaller grant\")\n\n\tthird, err := c.BumpShare(700, 50)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(850), third, \"smaller again\")\n\tuassert.True(t, third \u003c c.HardEnd(), \"it approaches the hard end without reaching it\")\n}\n\n// TestBumpShareRoundingStillGrants is the multiply-first lesson: a share of a\n// gap smaller than the divisor must not truncate to a zero grant.\nfunc TestBumpShareRoundingStillGrants(t *testing.T) {\n\t// 52 due, 50 left to the hard end: a tenth of that is 5, and dividing\n\t// before multiplying would truncate it to a grant of zero.\n\tc := mustNew(t, 0, 52, 0, 100)\n\tgot, err := c.BumpShare(50, 10)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(55), got, \"a tenth of the 50 left is 5, not 0\")\n}\n\nfunc TestBumpShareRespectsFloorAndCap(t *testing.T) {\n\tc := mustNew(t, 0, 100, 20, 150)\n\tgot, err := c.BumpShare(95, 10) // a tenth of the 55 left is 5, floored to 20\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(115), got)\n\n\tgot, err = c.BumpShare(110, 100) // would be 150 exactly, and never past it\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(150), got)\n\tuassert.True(t, c.Final())\n}\n\n// TestHugeGrantDoesNotWrap keeps a bump total at the extremes: a wrapped\n// deadline would land in the past and settle the game instantly.\nfunc TestHugeGrantDoesNotWrap(t *testing.T) {\n\tc := mustNew(t, 0, 100, 0, 0)\n\tuassert.Equal(t, maxInt64, c.BumpBy(50, maxInt64), \"clamped, not wrapped\")\n\tuassert.True(t, c.Deadline() \u003e 0)\n\n\tbig := mustNew(t, maxInt64/2, 1000, 0, maxInt64/4)\n\tgot, err := big.BumpShare(maxInt64/2+1, 100)\n\tuassert.NoError(t, err)\n\tuassert.True(t, got \u003e maxInt64/2, \"a huge remaining share does not wrap\")\n}\n\nfunc TestElapsedAndRemainingAreNeverNegative(t *testing.T) {\n\tc := mustNew(t, 100, 100, 0, 0)\n\tuassert.Equal(t, int64(0), c.Elapsed(50), \"before the start\")\n\tuassert.Equal(t, int64(100), c.Remaining(100))\n\tuassert.Equal(t, int64(0), c.Remaining(9999), \"long past the deadline\")\n\tuassert.Equal(t, int64(9899), c.Elapsed(9999))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/games/clock/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"prorata","path":"gno.land/p/moul/x/games/prorata/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/games/prorata/v0`\n\n**A weighted split of an integer amount that adds up**: `Split`, `Share`,\n`Total`.\n\n```go\nimport \"gno.land/p/moul/x/games/prorata/v0\"\n\nprorata.Split(100, []int64{1, 2, 3})  // [17 33 50], and it sums to exactly 100\nprorata.Split(10, []int64{1, 1, 1})   // [4 3 3], the dust goes to the lowest index\nprorata.Share(100, 1, 3)              // 33, floored: \"what would I get\"\n```\n\nEvery payout in a game is this operation: a pot, a roster, a weight each. Written\nthe obvious way, `amount*weight/total` per claimant, it is wrong in two ways that\nonly show up once there is real money in the contract.\n\n**The shares do not add up.** Each one is rounded down, so their sum is short by\nup to one unit per claimant. That dust either sits in the realm forever or lands\non whoever the loop happened to pay last, which is a rule nobody chose. `Split`\ndistributes by **largest remainder**: floor every share, then hand the leftover\nunits out one at a time to the claimants whose truncated fraction was largest,\nties going to the lower index. The result sums to **exactly** the amount, and the\nrule is deterministic, so every node computes the same split and a `Render` of it\ndoes not change between calls.\n\n**`amount*weight` overflows an int64** long before either factor does, which\nturns a large payout negative. Nothing here ever computes that product: it splits\nthe amount into whole multiples of the total and what is left over, so\n`amount*weight/total` becomes `q*weight + r*weight/total` with `r` already\nsmaller than the total. A pot of 10^18 ugnot across billion-unit weights is\nexact, and what genuinely cannot fit returns `ErrOverflow` rather than wrapping.\n\nTwo smaller decisions, each with a test:\n\n- **A zero weight is paid nothing, including no remainder unit.** Somebody with\n  no claim is not handed dust.\n- **An empty roster, or one where every weight is zero, is an error**, not an\n  empty split. Silently returning nothing would strand the amount, and only the\n  caller knows where it should go instead.\n\nNothing here reads the chain and nothing holds coins: the caller owns the roster\nand the custody.\n\n**Live game:** [`r/moul/x/games/lastwords`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/games/lastwords)\n· render it at [`/r/moul/x/games/lastwords/v0`](https://gno.land/r/moul/x/games/lastwords/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/games/prorata/v0\"\ngno = \"0.9\"\n"},{"name":"prorata.gno","body":"// Package prorata splits an integer amount across weighted claimants without\n// leaking or inventing a unit.\n//\n// Every payout in a game is this operation: a pot, a roster, and a weight each.\n// Written the obvious way, `amount*weight/total` per claimant, it is wrong in\n// two ways that only show up with real money in the contract. The shares are\n// each rounded down, so their sum is short of the amount by up to one unit per\n// claimant, and that dust either accumulates in the contract forever or gets\n// handed to whoever the code happens to pay last. And `amount*weight` overflows\n// an int64 long before either factor does, which turns a large payout negative.\n//\n// Split fixes both. It distributes by largest remainder: floor every share,\n// then hand the leftover units out one at a time to the claimants whose\n// truncated fraction was largest, ties going to the lower index. The result\n// sums to EXACTLY the amount, every time, and the rule is deterministic, so\n// every node computes the same split and a Render of it does not change between\n// calls.\n//\n// Nothing here reads the chain and nothing holds coins: the caller owns the\n// roster and the custody. A game built on this package is at\n// [r/moul/x/games/lastwords](/r/moul/x/games/lastwords/v0).\npackage prorata\n\nimport (\n\t\"errors\"\n\t\"sort\"\n)\n\nconst maxInt64 = int64(9223372036854775807)\n\nvar (\n\t// ErrNegativeAmount is returned when the amount to split is negative.\n\tErrNegativeAmount = errors.New(\"prorata: amount must not be negative\")\n\t// ErrNegativeWeight is returned when any weight is negative.\n\tErrNegativeWeight = errors.New(\"prorata: weights must not be negative\")\n\t// ErrNoWeight is returned when there is nobody to pay, or every weight is\n\t// zero. The caller must decide where the amount goes instead: silently\n\t// returning an empty split would strand it.\n\tErrNoWeight = errors.New(\"prorata: total weight is zero, nothing to split across\")\n\t// ErrOverflow is returned when the arithmetic does not fit in an int64.\n\tErrOverflow = errors.New(\"prorata: weights overflow int64\")\n)\n\n// Split divides amount across weights and returns one share per weight, in the\n// same order. The shares sum to exactly amount.\n//\n// A zero weight is allowed and receives nothing, including no remainder unit:\n// somebody with no claim is not paid dust.\nfunc Split(amount int64, weights []int64) ([]int64, error) {\n\tif amount \u003c 0 {\n\t\treturn nil, ErrNegativeAmount\n\t}\n\ttotal, err := Total(weights)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif total == 0 {\n\t\treturn nil, ErrNoWeight\n\t}\n\n\tshares := make([]int64, len(weights))\n\tif amount == 0 {\n\t\treturn shares, nil\n\t}\n\n\t// Floor each share, and keep the truncated numerator to rank by.\n\trems := make([]entry, 0, len(weights))\n\tassigned := int64(0)\n\tfor i, w := range weights {\n\t\tif w == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tshare, rem, err := divide(amount, w, total)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tshares[i] = share\n\t\tassigned += share\n\t\trems = append(rems, entry{index: i, rem: rem})\n\t}\n\n\t// Hand the leftover out by largest remainder. There are strictly fewer\n\t// leftover units than claimants, so one pass over the ranking is enough.\n\tleft := amount - assigned\n\tif left \u003c= 0 {\n\t\treturn shares, nil\n\t}\n\tsort.Sort(byRemainder(rems))\n\tfor i := 0; i \u003c len(rems) \u0026\u0026 left \u003e 0; i++ {\n\t\tshares[rems[i].index]++\n\t\tleft--\n\t}\n\treturn shares, nil\n}\n\n// Share returns what one weight is owed out of amount, rounded down. It is the\n// \"what would I get\" query, and deliberately does NOT account for the\n// remainder: use Split when the shares have to add up.\nfunc Share(amount, weight, total int64) (int64, error) {\n\tif amount \u003c 0 {\n\t\treturn 0, ErrNegativeAmount\n\t}\n\tif weight \u003c 0 || total \u003c 0 {\n\t\treturn 0, ErrNegativeWeight\n\t}\n\tif total == 0 {\n\t\treturn 0, ErrNoWeight\n\t}\n\tif weight \u003e total {\n\t\tweight = total\n\t}\n\tshare, _, err := divide(amount, weight, total)\n\treturn share, err\n}\n\n// Total sums weights, refusing an int64 overflow rather than wrapping into a\n// negative total that would make every share nonsense.\nfunc Total(weights []int64) (int64, error) {\n\tsum := int64(0)\n\tfor _, w := range weights {\n\t\tif w \u003c 0 {\n\t\t\treturn 0, ErrNegativeWeight\n\t\t}\n\t\tif w \u003e maxInt64-sum {\n\t\t\treturn 0, ErrOverflow\n\t\t}\n\t\tsum += w\n\t}\n\treturn sum, nil\n}\n\n// divide returns amount*weight/total rounded down, plus the remainder of that\n// division, without ever computing amount*weight.\n//\n// It splits the amount into whole multiples of total and what is left over:\n// amount = q*total + r, so amount*weight/total is exactly q*weight +\n// r*weight/total. The first term is exact and the second multiplies a value\n// already smaller than total, which is what keeps the product in range.\nfunc divide(amount, weight, total int64) (share, rem int64, err error) {\n\tq := amount / total\n\tr := amount % total\n\tif weight != 0 \u0026\u0026 q \u003e maxInt64/weight {\n\t\treturn 0, 0, ErrOverflow\n\t}\n\twhole := q * weight\n\tif weight != 0 \u0026\u0026 r \u003e maxInt64/weight {\n\t\treturn 0, 0, ErrOverflow\n\t}\n\tpart := r * weight\n\tif whole \u003e maxInt64-part/total {\n\t\treturn 0, 0, ErrOverflow\n\t}\n\treturn whole + part/total, part % total, nil\n}\n\n// entry is one claimant's truncated fraction, for ranking the leftover.\ntype entry struct {\n\tindex int\n\trem   int64\n}\n\n// byRemainder ranks by largest truncated remainder, ties by lowest index, so\n// the split is identical on every node.\ntype byRemainder []entry\n\nfunc (b byRemainder) Len() int      { return len(b) }\nfunc (b byRemainder) Swap(i, j int) { b[i], b[j] = b[j], b[i] }\nfunc (b byRemainder) Less(i, j int) bool {\n\tif b[i].rem != b[j].rem {\n\t\treturn b[i].rem \u003e b[j].rem\n\t}\n\treturn b[i].index \u003c b[j].index\n}\n"},{"name":"prorata_test.gno","body":"package prorata\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc sum(xs []int64) int64 {\n\tt := int64(0)\n\tfor _, x := range xs {\n\t\tt += x\n\t}\n\treturn t\n}\n\nfunc TestSplitTable(t *testing.T) {\n\tcases := []struct {\n\t\tname    string\n\t\tamount  int64\n\t\tweights []int64\n\t\twant    []int64\n\t}{\n\t\t{\"exact thirds\", 99, []int64{1, 1, 1}, []int64{33, 33, 33}},\n\t\t{\"one unit of dust, to the lowest index\", 10, []int64{1, 1, 1}, []int64{4, 3, 3}},\n\t\t{\"two units of dust\", 11, []int64{1, 1, 1}, []int64{4, 4, 3}},\n\t\t{\"uneven weights\", 100, []int64{1, 2, 3}, []int64{17, 33, 50}},\n\t\t{\"a single claimant takes it all\", 7, []int64{5}, []int64{7}},\n\t\t{\"zero weight is paid nothing\", 10, []int64{0, 1, 1}, []int64{0, 5, 5}},\n\t\t{\"zero weight is not paid dust either\", 10, []int64{0, 1, 1, 1}, []int64{0, 4, 3, 3}},\n\t\t{\"nothing to split\", 0, []int64{3, 1}, []int64{0, 0}},\n\t\t{\"amount smaller than the roster\", 2, []int64{1, 1, 1, 1}, []int64{1, 1, 0, 0}},\n\t\t{\"weight dominates\", 1000, []int64{999, 1}, []int64{999, 1}},\n\t}\n\tfor _, tc := range cases {\n\t\tgot, err := Split(tc.amount, tc.weights)\n\t\tuassert.NoError(t, err, tc.name)\n\t\tuassert.Equal(t, len(tc.want), len(got), tc.name)\n\t\tfor i := range tc.want {\n\t\t\tuassert.Equal(t, tc.want[i], got[i], tc.name)\n\t\t}\n\t}\n}\n\n// TestSplitAlwaysSumsToTheAmount is the whole point: a split that is short by\n// dust strands coins in the realm forever, and one that is over cannot be paid.\nfunc TestSplitAlwaysSumsToTheAmount(t *testing.T) {\n\tweightsets := [][]int64{\n\t\t{1, 1, 1},\n\t\t{1, 2, 3, 4, 5, 6, 7},\n\t\t{7, 0, 1},\n\t\t{100, 1},\n\t\t{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},\n\t\t{1},\n\t\t{999983, 17, 5},\n\t}\n\tfor _, ws := range weightsets {\n\t\tfor amount := int64(0); amount \u003c 60; amount++ {\n\t\t\tgot, err := Split(amount, ws)\n\t\t\tuassert.NoError(t, err)\n\t\t\tuassert.Equal(t, amount, sum(got), \"shares must sum to the amount\")\n\t\t}\n\t\tfor _, amount := range []int64{1000, 123457, 999999999} {\n\t\t\tgot, err := Split(amount, ws)\n\t\t\tuassert.NoError(t, err)\n\t\t\tuassert.Equal(t, amount, sum(got))\n\t\t}\n\t}\n}\n\n// TestLargestRemainderWins pins the allocation rule, so a payout cannot quietly\n// change to \"whoever the loop paid last\".\nfunc TestLargestRemainderWins(t *testing.T) {\n\t// total 10, amount 4: floors are 0,0,1,1 with remainders 4,8,2,6.\n\tgot, err := Split(4, []int64{1, 2, 3, 4})\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(0), got[0], \"smallest remainder, no extra unit\")\n\tuassert.Equal(t, int64(1), got[1], \"largest remainder, gets one\")\n\tuassert.Equal(t, int64(1), got[2], \"floor 1, remainder 2, gets none\")\n\tuassert.Equal(t, int64(2), got[3], \"second largest, gets the other\")\n\tuassert.Equal(t, int64(4), sum(got))\n}\n\nfunc TestSplitValidation(t *testing.T) {\n\t_, err := Split(-1, []int64{1})\n\tuassert.ErrorIs(t, err, ErrNegativeAmount)\n\n\t_, err = Split(10, []int64{1, -1})\n\tuassert.ErrorIs(t, err, ErrNegativeWeight)\n\n\t_, err = Split(10, nil)\n\tuassert.ErrorIs(t, err, ErrNoWeight, \"an empty roster is the caller's problem, not dust\")\n\n\t_, err = Split(10, []int64{0, 0})\n\tuassert.ErrorIs(t, err, ErrNoWeight, \"every weight zero is the same problem\")\n}\n\n// TestNoOverflowOnLargePots is the second failure mode: amount*weight wraps\n// negative long before either factor is anywhere near the limit.\nfunc TestNoOverflowOnLargePots(t *testing.T) {\n\t// A pot of 10^18 ugnot split across weights that would overflow if\n\t// multiplied together first.\n\tpot := int64(1000000000000000000)\n\tgot, err := Split(pot, []int64{3000000000, 1000000000})\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, pot, sum(got))\n\tuassert.Equal(t, int64(750000000000000000), got[0])\n\tuassert.Equal(t, int64(250000000000000000), got[1])\n\n\tgot, err = Split(maxInt64, []int64{1, 1})\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, maxInt64, sum(got), \"even the largest possible pot\")\n\n\t_, err = Total([]int64{maxInt64, 1})\n\tuassert.ErrorIs(t, err, ErrOverflow, \"a wrapped total makes every share nonsense\")\n}\n\nfunc TestShare(t *testing.T) {\n\tgot, err := Share(100, 1, 3)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(33), got, \"rounded down, the remainder is Split's job\")\n\n\tgot, err = Share(1000000000000000000, 3000000000, 4000000000)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(750000000000000000), got)\n\n\tgot, err = Share(100, 7, 3)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(100), got, \"a weight above the total is clamped, never over-paid\")\n\n\t_, err = Share(10, 1, 0)\n\tuassert.ErrorIs(t, err, ErrNoWeight)\n\t_, err = Share(-1, 1, 2)\n\tuassert.ErrorIs(t, err, ErrNegativeAmount)\n\t_, err = Share(10, -1, 2)\n\tuassert.ErrorIs(t, err, ErrNegativeWeight)\n}\n\nfunc TestTotal(t *testing.T) {\n\tgot, err := Total([]int64{1, 2, 3})\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(6), got)\n\n\tgot, err = Total(nil)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, int64(0), got, \"empty sums to zero; Split is what refuses it\")\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"grc20wrap","path":"gno.land/p/moul/x/grc20wrap/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/grc20wrap/v0`\n\n**Build a new GRC20 on top of one you do not control.** `Vault` escrows an\nexisting token and issues its own against it; `Basket` does the same over\nseveral at once. A `Policy` decides the exchange rate in both directions and\nwhether the wrapped token may move, which is the whole personality of a wrapper.\n\n```go\nimport (\n    \"gno.land/p/moul/x/grc20wrap/v0\"\n    \"gno.land/p/nt/grc20/v0\"\n)\n\n// In your realm, over any *grc20.Token you can reach (an import, or a\n// gno.land/r/nt/grc20reg/v0 lookup):\nv := grc20wrap.NewVault(under, grc20wrap.Pool{}, \"Pooled FOO\", \"pFOO\", 4, 0, cur)\n\n// The holder approves YOUR realm's address on the underlying first, through\n// the underlying realm's own entry point. Then:\nshares, err := v.Wrap(0, cur, holder, 1000)   // escrow 1000, mint shares\nout, err := v.Unwrap(0, cur, holder, shares)  // burn shares, release escrow\nerr = v.Donate(0, cur, patron, 500)           // no mint: every share is worth more\n```\n\n## The five policies\n\n| policy | wrapped token behaves like |\n|---|---|\n| `OneToOne` | a 1:1 custody receipt |\n| `Ratio{Num, Den}` | the same token re-denominated (`{1000, 1}` adds three decimals) |\n| `Soulbound{Base}` | a badge: wrap and unwrap freely, never transferable |\n| `Pool` | a share of the escrow; `Donate` pays every holder at once |\n| `Fee{Base, WrapBPS, UnwrapBPS}` | a haircut left behind, which over `Pool` pays whoever stays |\n\nThey compose: `Fee{Base: Pool{}, UnwrapBPS: 100}` is a pool with a 1% exit fee.\nWriting your own means three methods and a name; embed `OneToOne` and override\nonly what differs.\n\n## Basket: one token backed by two\n\n```go\nb := grc20wrap.NewBasket(\n    []*grc20.Token{red, blue}, []int64{1, 2},\n    \"Purple\", \"PURPLE\", 4, 0, cur,\n)\nerr := b.Fuse(0, cur, holder, 100)   // escrow 100 RED + 200 BLUE, mint 100 PURPLE\nerr = b.Defuse(0, cur, holder, 40)   // burn 40, hand back 40 RED + 80 BLUE\n```\n\nProportions are fixed, and the meta-token is only ever minted against the real\nthing, so it cannot drift from its backing or be arbitraged. It has no price\noracle and no rebalancing, because both would mean valuing the legs.\n\n## Three things worth knowing before using it\n\n**Custody is an allowance, never a privilege.** Escrow sits at the host realm's\naddress and moves through `grc20.RealmTeller`, which grc20 binds eagerly to that\naddress. A wrapper can only take what a holder approved for it, and can only\never spend its own realm's balance.\n\n**Errors are returned before anything moves, panics after.** Wrapping is two\nledger writes on two different tokens and gno has no rollback short of a panic,\nso each method validates first and returns an error while the world is still\nuntouched, then panics if a write fails past the point of no return. Aborting\nthe transaction is the only atomicity available.\n\n**A policy veto binds users, not realms.** `Vault.Move` is the only path a\nsigning account has, because `MsgCall` cannot build the `realm` argument grc20's\ntellers require. A realm holding the wrapped token can always call\n`grc20.RealmTeller` and move its own balance. `Soulbound` means \"no user can\npass it on\", not \"it can never move\".\n\n**Live demo:** [`r/moul/x/grc20wrapdemo`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/grc20wrapdemo/v0)\n· render it at [`/r/moul/x/grc20wrapdemo/v0`](https://gno.land/r/moul/x/grc20wrapdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/grc20wrap/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/grc20wrap/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"basket.gno","body":"package grc20wrap\n\nimport (\n\t\"math/overflow\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// leg is one component of a Basket.\ntype leg struct {\n\ttok    *grc20.Token\n\tteller grc20.Teller\n\tper    int64 // units escrowed per meta unit\n\theld   int64 // units escrowed so far\n}\n\n// Basket issues ONE meta-token over several underlying GRC20s at fixed\n// proportions. Minting a meta unit escrows every leg's `per` amount; redeeming\n// hands all of them back.\n//\n// A two-leg basket is the interesting one: it makes a pair tradable, quotable\n// and transferable as a single object, without a price oracle, an AMM or any\n// notion of what the legs are worth. The basket never values anything - it only\n// ever swaps a fixed bundle for a receipt and back, so it cannot be arbitraged\n// or drained. What it CAN do is let the market price the bundle, which is\n// exactly how an index token works.\n//\n// Proportions are fixed at creation. Rebalancing would mean revaluing the legs,\n// which needs a price, which is a different contract.\ntype Basket struct {\n\tlegs []*leg\n\thome address\n\ttok  *grc20.Token\n\tled  *grc20.PrivateLedger\n}\n\n// NewBasket issues a meta-token over tokens[i], escrowing parts[i] units of\n// each per meta unit.\n//\n// Both slices must be the same length, hold at least two entries, name no token\n// twice, and every part must be positive. As with NewVault, pass the owning\n// realm's own cur: escrow lands at that realm's address.\nfunc NewBasket(tokens []*grc20.Token, parts []int64, name, symbol string, decimals int, id seqid.ID, rlm realm) *Basket {\n\tif len(tokens) \u003c 2 || len(tokens) != len(parts) {\n\t\tpanic(ErrBadLegs)\n\t}\n\tlegs := make([]*leg, 0, len(tokens))\n\tfor i, t := range tokens {\n\t\tif t == nil {\n\t\t\tpanic(ErrNilToken)\n\t\t}\n\t\tif parts[i] \u003c= 0 {\n\t\t\tpanic(ErrBadLegs)\n\t\t}\n\t\tfor _, seen := range legs {\n\t\t\tif seen.tok.ID() == t.ID() {\n\t\t\t\tpanic(ErrBadLegs)\n\t\t\t}\n\t\t}\n\t\tlegs = append(legs, \u0026leg{\n\t\t\ttok:    t,\n\t\t\tteller: t.RealmTeller(0, rlm),\n\t\t\tper:    parts[i],\n\t\t})\n\t}\n\ttok, led := grc20.NewToken(name, symbol, decimals, id, rlm)\n\treturn \u0026Basket{\n\t\tlegs: legs,\n\t\thome: rlm.Address(),\n\t\ttok:  tok,\n\t\tled:  led,\n\t}\n}\n\n// Token is the meta-token this basket issues.\nfunc (b *Basket) Token() *grc20.Token { return b.tok }\n\n// Home is the escrow account: the host realm's address.\nfunc (b *Basket) Home() address { return b.home }\n\n// Legs is the number of components.\nfunc (b *Basket) Legs() int { return len(b.legs) }\n\n// Leg returns the i-th component: its token, the units escrowed per meta unit,\n// and the units escrowed so far.\nfunc (b *Basket) Leg(i int) (*grc20.Token, int64, int64) {\n\tl := b.legs[i]\n\treturn l.tok, l.per, l.held\n}\n\n// Solvent reports whether every leg's escrow account still covers what the\n// basket recorded taking in.\nfunc (b *Basket) Solvent() bool {\n\tfor _, l := range b.legs {\n\t\tif l.tok.BalanceOf(b.home) \u003c l.held {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Fuse escrows per*units of every leg from `from` and mints `units` of the meta\n// token to it.\n//\n// `from` must have approved b.Home() on EVERY leg first. The whole basket is\n// priced and checked before the first transfer, so a caller short on leg two\n// gets an error with leg one untouched.\nfunc (b *Basket) Fuse(_ int, rlm realm, from address, units int64) error {\n\tif units \u003c= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\tneed := make([]int64, len(b.legs))\n\tfor i, l := range b.legs {\n\t\tn, ok := overflow.Mul64(l.per, units)\n\t\tif !ok {\n\t\t\treturn ErrOverflow\n\t\t}\n\t\tif l.tok.BalanceOf(from) \u003c n {\n\t\t\treturn ErrShortBalance\n\t\t}\n\t\tif l.tok.Allowance(from, b.home) \u003c n {\n\t\t\treturn ErrShortAllowance\n\t\t}\n\t\tneed[i] = n\n\t}\n\t// Past here every leg was checked, so a failure is an invariant\n\t// violation and the transaction must not stand.\n\tfor i, l := range b.legs {\n\t\tif err := l.teller.TransferFrom(0, rlm, from, b.home, need[i]); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tl.held += need[i]\n\t}\n\tif err := b.led.Mint(from, units); err != nil {\n\t\tpanic(err)\n\t}\n\treturn nil\n}\n\n// Defuse burns `units` of the meta token held by `to` and returns every leg's\n// share of the escrow to it.\nfunc (b *Basket) Defuse(_ int, rlm realm, to address, units int64) error {\n\tif units \u003c= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\tgive := make([]int64, len(b.legs))\n\tfor i, l := range b.legs {\n\t\tn, ok := overflow.Mul64(l.per, units)\n\t\tif !ok {\n\t\t\treturn ErrOverflow\n\t\t}\n\t\tif n \u003e l.held {\n\t\t\treturn ErrUnbacked\n\t\t}\n\t\tgive[i] = n\n\t}\n\tif err := b.led.Burn(to, units); err != nil {\n\t\treturn err\n\t}\n\tfor i, l := range b.legs {\n\t\tl.held -= give[i]\n\t\tif err := l.teller.Transfer(0, rlm, to, give[i]); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn nil\n}\n\n// Move transfers meta units between two accounts.\nfunc (b *Basket) Move(from, to address, amount int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\treturn b.led.Transfer(from, to, amount)\n}\n\n// Allow sets `spender`'s allowance over `owner`'s meta balance.\nfunc (b *Basket) Allow(owner, spender address, amount int64) error {\n\treturn b.led.Approve(owner, spender, amount)\n}\n\n// MoveFrom spends `spender`'s allowance over `owner`'s meta balance.\nfunc (b *Basket) MoveFrom(spender, owner, to address, amount int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\treturn b.led.TransferFrom(owner, spender, to, amount)\n}\n\n// Summary renders the basket as a markdown block.\nfunc (b *Basket) Summary() string {\n\ts := ufmt.Sprintf(\"**%s** (%s) - meta-token over %d legs\\n\\n\",\n\t\tb.tok.GetName(), b.tok.GetSymbol(), len(b.legs))\n\ts += ufmt.Sprintf(\"- meta supply: %d\\n\", b.tok.TotalSupply())\n\tfor _, l := range b.legs {\n\t\ts += ufmt.Sprintf(\"- leg %s: %d per unit, %d escrowed\\n\",\n\t\t\tl.tok.GetSymbol(), l.per, l.held)\n\t}\n\tif b.Solvent() {\n\t\ts += \"- solvent: yes\\n\"\n\t} else {\n\t\ts += \"- solvent: **NO**\\n\"\n\t}\n\treturn s\n}\n"},{"name":"basket_test.gno","body":"package grc20wrap\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\tpairPath   = \"gno.land/r/test/pair\"\n\tbasketPath = \"gno.land/r/test/basket\"\n)\n\n// mintPair issues two independent tokens from one foreign realm and funds the\n// holders with both.\nfunc mintPair(cur realm, t *testing.T, red, blue int64, funded ...address) (*grc20.Token, *grc20.PrivateLedger, *grc20.Token, *grc20.PrivateLedger) {\n\tt.Helper()\n\ttesting.SetRealm(testing.NewCodeRealm(pairPath))\n\trt, rl := grc20.NewToken(\"Red\", \"RED\", 4, 0, cur)\n\tbt, bl := grc20.NewToken(\"Blue\", \"BLUE\", 4, 1, cur)\n\tfor _, a := range funded {\n\t\turequire.NoError(t, rl.Mint(a, red))\n\t\turequire.NoError(t, bl.Mint(a, blue))\n\t}\n\treturn rt, rl, bt, bl\n}\n\nfunc TestFuseAndDefuse(cur realm, t *testing.T) {\n\tred, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(basketPath))\n\tb := NewBasket(\n\t\t[]*grc20.Token{red, blue},\n\t\t[]int64{1, 2},\n\t\t\"Purple\", \"PURPLE\", 4, 0, cur,\n\t)\n\tapprove(cur, t, redLed, alice, b.Home(), 1_000)\n\tapprove(cur, t, blueLed, alice, b.Home(), 1_000)\n\n\turequire.NoError(t, b.Fuse(0, cur, alice, 10))\n\tuassert.Equal(t, int64(10), b.Token().BalanceOf(alice))\n\tuassert.Equal(t, int64(990), red.BalanceOf(alice))\n\tuassert.Equal(t, int64(980), blue.BalanceOf(alice))\n\n\t_, per, held := b.Leg(0)\n\tuassert.Equal(t, int64(1), per)\n\tuassert.Equal(t, int64(10), held)\n\t_, per, held = b.Leg(1)\n\tuassert.Equal(t, int64(2), per)\n\tuassert.Equal(t, int64(20), held)\n\tuassert.True(t, b.Solvent())\n\n\turequire.NoError(t, b.Defuse(0, cur, alice, 4))\n\tuassert.Equal(t, int64(6), b.Token().TotalSupply())\n\tuassert.Equal(t, int64(994), red.BalanceOf(alice))\n\tuassert.Equal(t, int64(988), blue.BalanceOf(alice))\n\n\t// Out entirely: the basket closes empty on both legs.\n\turequire.NoError(t, b.Defuse(0, cur, alice, 6))\n\tuassert.Equal(t, int64(0), b.Token().TotalSupply())\n\t_, _, held = b.Leg(0)\n\tuassert.Equal(t, int64(0), held)\n\t_, _, held = b.Leg(1)\n\tuassert.Equal(t, int64(0), held)\n\tuassert.Equal(t, int64(1_000), red.BalanceOf(alice))\n\tuassert.Equal(t, int64(1_000), blue.BalanceOf(alice))\n}\n\n// The whole basket is priced before the first transfer, so being short on the\n// SECOND leg leaves the first one untouched. Without the pre-pass this is where\n// a partially-applied mint would come from.\nfunc TestFuseChecksEveryLegBeforeMovingAny(cur realm, t *testing.T) {\n\tred, redLed, blue, blueLed := mintPair(cur, t, 1_000, 10, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(basketPath))\n\tb := NewBasket(\n\t\t[]*grc20.Token{red, blue},\n\t\t[]int64{1, 2},\n\t\t\"Purple\", \"PURPLE\", 4, 0, cur,\n\t)\n\tapprove(cur, t, redLed, alice, b.Home(), 1_000)\n\tapprove(cur, t, blueLed, alice, b.Home(), 1_000)\n\n\t// 100 units needs 100 RED (fine) and 200 BLUE (alice has 10).\n\tuassert.ErrorIs(t, b.Fuse(0, cur, alice, 100), ErrShortBalance)\n\tuassert.Equal(t, int64(1_000), red.BalanceOf(alice))\n\tuassert.Equal(t, int64(0), b.Token().TotalSupply())\n\n\t// Same for a missing allowance on the second leg only.\n\tapprove(cur, t, blueLed, alice, b.Home(), 0)\n\turequire.NoError(t, blueLed.Mint(alice, 1_000))\n\tuassert.ErrorIs(t, b.Fuse(0, cur, alice, 5), ErrShortAllowance)\n\tuassert.Equal(t, int64(1_000), red.BalanceOf(alice))\n\tuassert.Equal(t, int64(0), b.Token().TotalSupply())\n}\n\nfunc TestDefuseStopsAtTheBalance(cur realm, t *testing.T) {\n\tred, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice, bob)\n\n\ttesting.SetRealm(testing.NewCodeRealm(basketPath))\n\tb := NewBasket(\n\t\t[]*grc20.Token{red, blue},\n\t\t[]int64{1, 1},\n\t\t\"Purple\", \"PURPLE\", 4, 0, cur,\n\t)\n\tfor _, a := range []address{alice, bob} {\n\t\tapprove(cur, t, redLed, a, b.Home(), 1_000)\n\t\tapprove(cur, t, blueLed, a, b.Home(), 1_000)\n\t}\n\n\turequire.NoError(t, b.Fuse(0, cur, alice, 50))\n\tuassert.ErrorContains(t, b.Defuse(0, cur, bob, 1), \"insufficient balance\")\n\tuassert.ErrorIs(t, b.Defuse(0, cur, alice, 0), ErrInvalidAmount)\n\t_, _, held := b.Leg(0)\n\tuassert.Equal(t, int64(50), held)\n}\n\nfunc TestNewBasketRejectsBadLegs(cur realm, t *testing.T) {\n\tred, _, blue, _ := mintPair(cur, t, 1_000, 1_000)\n\n\ttesting.SetRealm(testing.NewCodeRealm(basketPath))\n\n\t// A one-leg basket is a Vault; say so instead of pretending.\n\tuassert.PanicsContains(t, cur, \"at least two legs\", func() {\n\t\tNewBasket([]*grc20.Token{red}, []int64{1}, \"X\", \"X\", 4, 0, cur)\n\t})\n\t// Mismatched slices.\n\tuassert.PanicsContains(t, cur, \"at least two legs\", func() {\n\t\tNewBasket([]*grc20.Token{red, blue}, []int64{1}, \"X\", \"X\", 4, 0, cur)\n\t})\n\t// A zero part would let a leg be minted for free.\n\tuassert.PanicsContains(t, cur, \"at least two legs\", func() {\n\t\tNewBasket([]*grc20.Token{red, blue}, []int64{1, 0}, \"X\", \"X\", 4, 0, cur)\n\t})\n\t// The same token twice is two accountings of one balance.\n\tuassert.PanicsContains(t, cur, \"at least two legs\", func() {\n\t\tNewBasket([]*grc20.Token{red, red}, []int64{1, 1}, \"X\", \"X\", 4, 0, cur)\n\t})\n\tuassert.PanicsContains(t, cur, \"nil underlying token\", func() {\n\t\tNewBasket([]*grc20.Token{red, nil}, []int64{1, 1}, \"X\", \"X\", 4, 0, cur)\n\t})\n}\n\nfunc TestBasketMoveAndAllowance(cur realm, t *testing.T) {\n\tred, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(basketPath))\n\tb := NewBasket(\n\t\t[]*grc20.Token{red, blue},\n\t\t[]int64{1, 1},\n\t\t\"Purple\", \"PURPLE\", 4, 0, cur,\n\t)\n\tapprove(cur, t, redLed, alice, b.Home(), 1_000)\n\tapprove(cur, t, blueLed, alice, b.Home(), 1_000)\n\turequire.NoError(t, b.Fuse(0, cur, alice, 100))\n\n\turequire.NoError(t, b.Move(alice, bob, 40))\n\tuassert.Equal(t, int64(40), b.Token().BalanceOf(bob))\n\turequire.NoError(t, b.Allow(alice, bob, 30))\n\turequire.NoError(t, b.MoveFrom(bob, alice, carl, 30))\n\tuassert.Equal(t, int64(30), b.Token().BalanceOf(carl))\n\tuassert.ErrorIs(t, b.MoveFrom(bob, alice, carl, 0), ErrInvalidAmount)\n\n\t// bob holds meta units he never minted, and can still split them.\n\turequire.NoError(t, b.Defuse(0, cur, bob, 40))\n\tuassert.Equal(t, int64(40), red.BalanceOf(bob))\n\tuassert.Equal(t, int64(40), blue.BalanceOf(bob))\n}\n\nfunc TestBasketSummary(cur realm, t *testing.T) {\n\tred, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(basketPath))\n\tb := NewBasket(\n\t\t[]*grc20.Token{red, blue},\n\t\t[]int64{1, 2},\n\t\t\"Purple\", \"PURPLE\", 4, 0, cur,\n\t)\n\tapprove(cur, t, redLed, alice, b.Home(), 1_000)\n\tapprove(cur, t, blueLed, alice, b.Home(), 1_000)\n\turequire.NoError(t, b.Fuse(0, cur, alice, 7))\n\n\twant := \"**Purple** (PURPLE) - meta-token over 2 legs\\n\\n\" +\n\t\t\"- meta supply: 7\\n\" +\n\t\t\"- leg RED: 1 per unit, 7 escrowed\\n\" +\n\t\t\"- leg BLUE: 2 per unit, 14 escrowed\\n\" +\n\t\t\"- solvent: yes\\n\"\n\tuassert.Equal(t, want, b.Summary())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/grc20wrap/v0\"\ngno = \"0.9\"\n"},{"name":"policy.gno","body":"package grc20wrap\n\nimport \"gno.land/p/nt/ufmt/v0\"\n\n// Policy is a wrapper's personality. It sets the exchange rate in both\n// directions and can veto a move of the wrapped token.\n//\n// Every method receives the vault, so a policy can price against live state -\n// escrow, supply, custody - instead of a frozen constant. Embed OneToOne to\n// write a policy that only overrides what it cares about.\ntype Policy interface {\n\t// WrapRate returns how many wrapped units `in` underlying units mint.\n\t// It is called BEFORE the escrow moves, so v.Held() excludes `in`.\n\tWrapRate(v *Vault, in int64) (int64, error)\n\n\t// UnwrapRate returns how many underlying units `in` wrapped units\n\t// release. It is called before the burn, so v.Supply() includes `in`.\n\tUnwrapRate(v *Vault, in int64) (int64, error)\n\n\t// CanMove vetoes a transfer of the wrapped token between two accounts.\n\tCanMove(v *Vault, from, to address, amount int64) error\n\n\t// Name labels the policy in a catalogue. Short, lowercase.\n\tName() string\n}\n\n// OneToOne is the boring wrapper: one underlying unit in, one wrapped unit\n// out, and no restriction on who may hold the result. Useful on its own as a\n// pure custody receipt, and as the embedded base of every policy below.\ntype OneToOne struct{}\n\nfunc (OneToOne) WrapRate(v *Vault, in int64) (int64, error) { return in, nil }\n\nfunc (OneToOne) UnwrapRate(v *Vault, in int64) (int64, error) { return in, nil }\n\nfunc (OneToOne) CanMove(v *Vault, from, to address, amount int64) error { return nil }\n\nfunc (OneToOne) Name() string { return \"1:1\" }\n\n// Ratio re-denominates: Num wrapped units per Den underlying units. Both terms\n// must be positive.\n//\n// Ratio{Num: 1000, Den: 1} turns one underlying unit into a thousand wrapped\n// ones, which is how you give a token three more decimals without touching the\n// realm that issued it. The reverse direction divides, so a redemption that\n// rounds to zero is refused (ErrDust) rather than silently burning value: with\n// Num=1000, unwrapping 999 wrapped units returns nothing and is rejected.\ntype Ratio struct {\n\tOneToOne\n\tNum int64\n\tDen int64\n}\n\nfunc (r Ratio) WrapRate(v *Vault, in int64) (int64, error) {\n\tif r.Num \u003c= 0 || r.Den \u003c= 0 {\n\t\treturn 0, ErrBadRatio\n\t}\n\treturn mulDiv(in, r.Num, r.Den)\n}\n\nfunc (r Ratio) UnwrapRate(v *Vault, in int64) (int64, error) {\n\tif r.Num \u003c= 0 || r.Den \u003c= 0 {\n\t\treturn 0, ErrBadRatio\n\t}\n\treturn mulDiv(in, r.Den, r.Num)\n}\n\nfunc (r Ratio) Name() string { return ufmt.Sprintf(\"%d:%d\", r.Num, r.Den) }\n\n// Soulbound wraps another policy and refuses every transfer of the wrapped\n// token. Rates are whatever Base says; a nil Base means OneToOne.\n//\n// The result is an account-bound receipt: anyone can wrap into it and anyone\n// can unwrap back out, but the wrapped unit itself never changes hands. That\n// makes it a membership badge, a proof of deposit, or a vote weight that\n// cannot be rented - while the underlying stays fully liquid one step away.\n//\n// The veto binds signing users only; see the package doc.\ntype Soulbound struct {\n\tBase Policy\n}\n\nfunc (s Soulbound) base() Policy {\n\tif s.Base == nil {\n\t\treturn OneToOne{}\n\t}\n\treturn s.Base\n}\n\nfunc (s Soulbound) WrapRate(v *Vault, in int64) (int64, error) {\n\treturn s.base().WrapRate(v, in)\n}\n\nfunc (s Soulbound) UnwrapRate(v *Vault, in int64) (int64, error) {\n\treturn s.base().UnwrapRate(v, in)\n}\n\nfunc (s Soulbound) CanMove(v *Vault, from, to address, amount int64) error {\n\treturn ErrSoulbound\n}\n\nfunc (s Soulbound) Name() string { return \"soulbound/\" + s.base().Name() }\n\n// Pool prices in shares instead of units: the wrapped token is a claim on a\n// fraction of the escrow rather than on a fixed amount.\n//\n//\twrap:   shares = in * supply / held      (1:1 while the pool is empty)\n//\tunwrap: units  = in * held  / supply\n//\n// Nothing changes until someone calls Vault.Donate, which adds escrow without\n// minting shares. Every outstanding share is then worth more, permanently and\n// for everyone at once. That is the whole yield-bearing-token pattern in two\n// lines of arithmetic: a fee sink, a staking reward, an airdrop to holders, all\n// the same operation.\n//\n// Two honest caveats:\n//\n//   - Division truncates, so a share is always worth marginally less than its\n//     exact fraction. The remainder stays in the pool, which is the safe\n//     direction: a vault can never promise more than it holds.\n//   - A first depositor can wrap one unit, donate a large amount, and make\n//     every later deposit smaller than one share round to zero in their favour\n//     (the ERC-4626 inflation attack). Seed the pool at creation, or keep the\n//     wrapped token's decimals well above the underlying's, before using this\n//     anywhere real.\ntype Pool struct {\n\tOneToOne\n}\n\nfunc (Pool) WrapRate(v *Vault, in int64) (int64, error) {\n\tsupply, held := v.Supply(), v.Held()\n\tif supply == 0 || held == 0 {\n\t\treturn in, nil\n\t}\n\treturn mulDiv(in, supply, held)\n}\n\nfunc (Pool) UnwrapRate(v *Vault, in int64) (int64, error) {\n\tsupply := v.Supply()\n\tif supply == 0 {\n\t\treturn 0, ErrDust\n\t}\n\treturn mulDiv(in, v.Held(), supply)\n}\n\nfunc (Pool) Name() string { return \"pool\" }\n\n// Fee takes a basis-point haircut in both directions on top of Base (nil means\n// OneToOne). 100 BPS is 1%.\n//\n// The haircut is not paid to anyone: it stays escrowed. Over a plain base that\n// only strands value, so Fee is meant to sit over Pool, where the stranded\n// units raise what every remaining share redeems for. The wrapper then pays its\n// holders out of its own turnover, and paying twice - in and out - costs more\n// than holding.\ntype Fee struct {\n\tBase      Policy\n\tWrapBPS   int64\n\tUnwrapBPS int64\n}\n\nfunc (f Fee) base() Policy {\n\tif f.Base == nil {\n\t\treturn OneToOne{}\n\t}\n\treturn f.Base\n}\n\n// cut removes bps basis points from amount.\nfunc cut(amount, bps int64) (int64, error) {\n\tif bps \u003c 0 || bps \u003e 10000 {\n\t\treturn 0, ErrBadBPS\n\t}\n\ttaken, err := mulDiv(amount, bps, 10000)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn amount - taken, nil\n}\n\nfunc (f Fee) WrapRate(v *Vault, in int64) (int64, error) {\n\tout, err := f.base().WrapRate(v, in)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn cut(out, f.WrapBPS)\n}\n\nfunc (f Fee) UnwrapRate(v *Vault, in int64) (int64, error) {\n\tout, err := f.base().UnwrapRate(v, in)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn cut(out, f.UnwrapBPS)\n}\n\nfunc (f Fee) CanMove(v *Vault, from, to address, amount int64) error {\n\treturn f.base().CanMove(v, from, to, amount)\n}\n\nfunc (f Fee) Name() string {\n\treturn ufmt.Sprintf(\"fee(%d/%dbps)/%s\", f.WrapBPS, f.UnwrapBPS, f.base().Name())\n}\n"},{"name":"policy_test.gno","body":"package grc20wrap\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Every policy here is stateless, so it prices correctly against a nil vault.\n// Pool is the one that reads the vault, and it is covered end to end in\n// TestPoolSharesAppreciate.\nfunc TestStatelessRates(t *testing.T) {\n\tcases := []struct {\n\t\tname      string\n\t\tpol       Policy\n\t\twrapIn    int64\n\t\twrapOut   int64\n\t\tunwrapIn  int64\n\t\tunwrapOut int64\n\t}{\n\t\t{\"one to one\", OneToOne{}, 7, 7, 7, 7},\n\t\t{\"kilo\", Ratio{Num: 1_000, Den: 1}, 7, 7_000, 7_000, 7},\n\t\t{\"kilo truncates on the way out\", Ratio{Num: 1_000, Den: 1}, 1, 1_000, 2_500, 2},\n\t\t{\"milli\", Ratio{Num: 1, Den: 1_000}, 7_000, 7, 7, 7_000},\n\t\t{\"two for three\", Ratio{Num: 2, Den: 3}, 9, 6, 6, 9},\n\t\t{\"soulbound keeps its base rate\", Soulbound{Base: Ratio{Num: 2, Den: 1}}, 5, 10, 10, 5},\n\t\t{\"soulbound with no base is 1:1\", Soulbound{}, 5, 5, 5, 5},\n\t\t{\"one percent both ways\", Fee{WrapBPS: 100, UnwrapBPS: 100}, 1_000, 990, 1_000, 990},\n\t\t{\"a haircut under one unit rounds to nothing\", Fee{WrapBPS: 100}, 55, 55, 55, 55},\n\t}\n\n\tfor _, tc := range cases {\n\t\tgot, err := tc.pol.WrapRate(nil, tc.wrapIn)\n\t\tuassert.NoError(t, err, tc.name)\n\t\tuassert.Equal(t, tc.wrapOut, got, tc.name+\" (wrap)\")\n\n\t\tgot, err = tc.pol.UnwrapRate(nil, tc.unwrapIn)\n\t\tuassert.NoError(t, err, tc.name)\n\t\tuassert.Equal(t, tc.unwrapOut, got, tc.name+\" (unwrap)\")\n\t}\n}\n\nfunc TestRateErrors(t *testing.T) {\n\tcases := []struct {\n\t\tname      string\n\t\tpol       Policy\n\t\tin        int64\n\t\twrapErr   error\n\t\tunwrapErr error\n\t}{\n\t\t{\"zero numerator\", Ratio{Num: 0, Den: 1}, 5, ErrBadRatio, ErrBadRatio},\n\t\t{\"negative denominator\", Ratio{Num: 2, Den: -1}, 5, ErrBadRatio, ErrBadRatio},\n\t\t// Only the multiplying direction can overflow; the dividing one\n\t\t// just returns a very small number.\n\t\t{\"overflowing numerator\", Ratio{Num: math.MaxInt64, Den: 1}, 3, ErrOverflow, nil},\n\t\t{\"basis points above 100%\", Fee{WrapBPS: 10_001, UnwrapBPS: 10_001}, 100, ErrBadBPS, ErrBadBPS},\n\t\t{\"negative basis points\", Fee{WrapBPS: -1, UnwrapBPS: -1}, 100, ErrBadBPS, ErrBadBPS},\n\t}\n\n\tfor _, tc := range cases {\n\t\t_, err := tc.pol.WrapRate(nil, tc.in)\n\t\tif tc.wrapErr == nil {\n\t\t\tuassert.NoError(t, err, tc.name+\" (wrap)\")\n\t\t} else {\n\t\t\tuassert.ErrorIs(t, err, tc.wrapErr, tc.name+\" (wrap)\")\n\t\t}\n\n\t\t_, err = tc.pol.UnwrapRate(nil, tc.in)\n\t\tif tc.unwrapErr == nil {\n\t\t\tuassert.NoError(t, err, tc.name+\" (unwrap)\")\n\t\t} else {\n\t\t\tuassert.ErrorIs(t, err, tc.unwrapErr, tc.name+\" (unwrap)\")\n\t\t}\n\t}\n}\n\nfunc TestPolicyNames(t *testing.T) {\n\tuassert.Equal(t, \"1:1\", OneToOne{}.Name())\n\tuassert.Equal(t, \"1000:1\", Ratio{Num: 1_000, Den: 1}.Name())\n\tuassert.Equal(t, \"pool\", Pool{}.Name())\n\tuassert.Equal(t, \"soulbound/1:1\", Soulbound{}.Name())\n\tuassert.Equal(t, \"soulbound/pool\", Soulbound{Base: Pool{}}.Name())\n\tuassert.Equal(t, \"fee(0/100bps)/pool\", Fee{Base: Pool{}, UnwrapBPS: 100}.Name())\n}\n\nfunc TestOnlySoulboundVetoes(t *testing.T) {\n\tuassert.NoError(t, OneToOne{}.CanMove(nil, alice, bob, 1))\n\tuassert.NoError(t, Ratio{Num: 1, Den: 1}.CanMove(nil, alice, bob, 1))\n\tuassert.NoError(t, Pool{}.CanMove(nil, alice, bob, 1))\n\tuassert.NoError(t, Fee{Base: Pool{}}.CanMove(nil, alice, bob, 1))\n\tuassert.ErrorIs(t, Soulbound{}.CanMove(nil, alice, bob, 1), ErrSoulbound)\n\t// A fee over a soulbound base inherits the veto.\n\tuassert.ErrorIs(t, Fee{Base: Soulbound{}}.CanMove(nil, alice, bob, 1), ErrSoulbound)\n}\n"},{"name":"wrap.gno","body":"// Package grc20wrap builds derived GRC20 tokens on top of existing ones.\n//\n// Two shapes:\n//\n//   - Vault wraps ONE underlying token. It escrows underlying units at the\n//     host realm's address and issues its own GRC20 against that escrow. A\n//     Policy sets the exchange rate in both directions and may veto a move of\n//     the wrapped token, which is where a wrapper stops being plumbing and\n//     becomes a pattern: 1:1 custody, a denomination change, a\n//     non-transferable receipt, a share in a growing pool.\n//   - Basket wraps SEVERAL. One meta-token is minted against fixed parts of\n//     every leg and splits back into them on redemption.\n//\n// Neither type holds chain state of its own beyond the GRC20 ledger it\n// creates, so a realm keeps them wherever it likes.\n//\n// # How custody works\n//\n// Escrow lands at the HOST REALM's address. A vault moves it through\n// grc20.RealmTeller, which binds eagerly to that address, so a vault can only\n// ever spend what its own realm holds. Pulling a user's tokens in therefore\n// takes the ordinary allowance route: the user approves the host realm's\n// address on the underlying token, through that token realm's own entry\n// point, and the vault draws on the allowance as itself.\n//\n// # Reverting, not returning\n//\n// Wrapping is two ledger writes on two different tokens, and gno has no\n// rollback short of a panic: a returned error does not undo what already ran.\n// Every method here therefore validates while nothing has moved and returns an\n// error, then panics if a write fails after the point of no return. Aborting\n// the transaction is the only atomicity available.\n//\n// # What a Policy can and cannot enforce\n//\n// A Policy veto binds end users, not realms. Moving the wrapped token through\n// Vault.Move is the only path a signing account has, because MsgCall cannot\n// build the realm argument grc20's tellers require. Another realm holding the\n// wrapped token can always call grc20.RealmTeller on it and move its OWN\n// balance. Soulbound means \"no user can pass it on\", not \"it can never move\".\n//\n// Live demo: gno.land/r/moul/x/grc20wrapdemo/v0.\npackage grc20wrap\n\nimport (\n\t\"errors\"\n\t\"math/overflow\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar (\n\tErrNilToken       = errors.New(\"grc20wrap: nil underlying token\")\n\tErrInvalidAmount  = errors.New(\"grc20wrap: amount must be positive\")\n\tErrDust           = errors.New(\"grc20wrap: amount rounds to zero\")\n\tErrUnbacked       = errors.New(\"grc20wrap: payout exceeds this vault's escrow\")\n\tErrSoulbound      = errors.New(\"grc20wrap: soulbound, the wrapped token cannot change hands\")\n\tErrOverflow       = errors.New(\"grc20wrap: arithmetic overflow\")\n\tErrBadRatio       = errors.New(\"grc20wrap: ratio terms must be positive\")\n\tErrBadBPS         = errors.New(\"grc20wrap: basis points must be within 0..10000\")\n\tErrBadLegs        = errors.New(\"grc20wrap: a basket needs at least two legs, each with a positive part\")\n\tErrShortBalance   = errors.New(\"grc20wrap: insufficient balance on a leg\")\n\tErrShortAllowance = errors.New(\"grc20wrap: insufficient allowance on a leg\")\n)\n\n// Vault escrows one underlying GRC20 and issues another against it.\n//\n// The escrow account is the host realm's own address, shared with every other\n// vault that realm creates. Separation between them is the per-vault Held()\n// counter, not separate accounts: a vault only ever releases what it recorded\n// taking in, so the realm-wide invariant is sum(Held) \u003c= Custody().\ntype Vault struct {\n\tunder  *grc20.Token\n\tteller grc20.Teller // bound to home, eagerly, at construction\n\thome   address\n\ttok    *grc20.Token\n\tled    *grc20.PrivateLedger\n\tpol    Policy\n\theld   int64\n}\n\n// NewVault issues a new GRC20 backed by units of under.\n//\n// Call it from the realm that will own the vault, forwarding that realm's own\n// cur: both the teller binding and the new token's origRealm are taken from it\n// and cannot be forged afterwards. id disambiguates several tokens minted by\n// the same realm - allocate it from one persistent seqid.ID.\n//\n// A nil pol means OneToOne.\nfunc NewVault(under *grc20.Token, pol Policy, name, symbol string, decimals int, id seqid.ID, rlm realm) *Vault {\n\tif under == nil {\n\t\tpanic(ErrNilToken)\n\t}\n\tif pol == nil {\n\t\tpol = OneToOne{}\n\t}\n\ttok, led := grc20.NewToken(name, symbol, decimals, id, rlm)\n\treturn \u0026Vault{\n\t\tunder:  under,\n\t\tteller: under.RealmTeller(0, rlm),\n\t\thome:   rlm.Address(),\n\t\ttok:    tok,\n\t\tled:    led,\n\t\tpol:    pol,\n\t}\n}\n\n// Token is the wrapped token this vault issues. It is safe to hand out: a\n// *grc20.Token carries metadata and read access, never the authority to debit\n// anybody.\nfunc (v *Vault) Token() *grc20.Token { return v.tok }\n\n// Underlying is the token held in escrow.\nfunc (v *Vault) Underlying() *grc20.Token { return v.under }\n\n// Policy is this vault's personality.\nfunc (v *Vault) Policy() Policy { return v.pol }\n\n// Home is the escrow account: the host realm's address.\nfunc (v *Vault) Home() address { return v.home }\n\n// Held is the underlying escrowed for THIS vault, by its own accounting.\nfunc (v *Vault) Held() int64 { return v.held }\n\n// Supply is the wrapped token in circulation.\nfunc (v *Vault) Supply() int64 { return v.tok.TotalSupply() }\n\n// Custody is the underlying actually sitting at the escrow account. It covers\n// every vault the host realm created over the same underlying, plus anything\n// sent there by mistake, so Custody \u003e= Held is necessary for solvency and\n// sufficient only when this is the realm's single vault over that token.\nfunc (v *Vault) Custody() int64 { return v.under.BalanceOf(v.home) }\n\n// Solvent reports whether the escrow account still covers what this vault\n// recorded taking in. False means the host realm moved the underlying behind\n// the vault's back.\nfunc (v *Vault) Solvent() bool { return v.Custody() \u003e= v.held }\n\n// Wrap escrows amount units of the underlying from `from` and mints the\n// wrapped token to `from`, returning how much was minted.\n//\n// `from` must already have granted v.Home() an allowance of at least amount on\n// the underlying token, set through that token realm's own entry point.\nfunc (v *Vault) Wrap(_ int, rlm realm, from address, amount int64) (int64, error) {\n\tif amount \u003c= 0 {\n\t\treturn 0, ErrInvalidAmount\n\t}\n\tout, err := v.pol.WrapRate(v, amount)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif out \u003c= 0 {\n\t\treturn 0, ErrDust\n\t}\n\t// Last point at which nothing has moved.\n\tif err := v.teller.TransferFrom(0, rlm, from, v.home, amount); err != nil {\n\t\treturn 0, err\n\t}\n\theld, ok := overflow.Add64(v.held, amount)\n\tif !ok {\n\t\tpanic(ErrOverflow)\n\t}\n\tv.held = held\n\tif err := v.led.Mint(from, out); err != nil {\n\t\t// The escrow already moved; only aborting the tx can undo it.\n\t\tpanic(err)\n\t}\n\treturn out, nil\n}\n\n// Unwrap burns amount wrapped units held by `from` and releases the underlying\n// back to it, returning how much was released.\nfunc (v *Vault) Unwrap(_ int, rlm realm, from address, amount int64) (int64, error) {\n\tif amount \u003c= 0 {\n\t\treturn 0, ErrInvalidAmount\n\t}\n\tout, err := v.pol.UnwrapRate(v, amount)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif out \u003c= 0 {\n\t\treturn 0, ErrDust\n\t}\n\tif out \u003e v.held {\n\t\treturn 0, ErrUnbacked\n\t}\n\t// Burn first: it is the step that can legitimately fail on a short\n\t// balance, and it fails before anything has moved.\n\tif err := v.led.Burn(from, amount); err != nil {\n\t\treturn 0, err\n\t}\n\tv.held -= out\n\tif err := v.teller.Transfer(0, rlm, from, out); err != nil {\n\t\t// The burn already happened; only aborting the tx can undo it.\n\t\tpanic(err)\n\t}\n\treturn out, nil\n}\n\n// Donate escrows amount units of the underlying without minting anything.\n//\n// Under a pool policy this is how the wrapper gets interesting: the donation\n// raises what every outstanding wrapped unit redeems for, so anyone can make\n// every holder richer and nobody can take it back out except by holding.\n// `from` must have approved v.Home() on the underlying, as for Wrap.\nfunc (v *Vault) Donate(_ int, rlm realm, from address, amount int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\tif err := v.teller.TransferFrom(0, rlm, from, v.home, amount); err != nil {\n\t\treturn err\n\t}\n\theld, ok := overflow.Add64(v.held, amount)\n\tif !ok {\n\t\tpanic(ErrOverflow)\n\t}\n\tv.held = held\n\treturn nil\n}\n\n// Move transfers wrapped units after the policy has had its say. It is the\n// only path a signing user has to move the wrapped token; see the package doc\n// for what that does and does not guarantee.\nfunc (v *Vault) Move(from, to address, amount int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\tif err := v.pol.CanMove(v, from, to, amount); err != nil {\n\t\treturn err\n\t}\n\treturn v.led.Transfer(from, to, amount)\n}\n\n// Allow sets `spender`'s allowance over `owner`'s wrapped balance.\n//\n// The policy is deliberately not consulted: an allowance moves nothing. It is\n// checked when the allowance is spent, in MoveFrom, so a policy that starts\n// vetoing later still binds allowances granted before.\nfunc (v *Vault) Allow(owner, spender address, amount int64) error {\n\treturn v.led.Approve(owner, spender, amount)\n}\n\n// MoveFrom spends `spender`'s allowance over `owner`'s wrapped balance, after\n// the policy has had its say.\nfunc (v *Vault) MoveFrom(spender, owner, to address, amount int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\tif err := v.pol.CanMove(v, owner, to, amount); err != nil {\n\t\treturn err\n\t}\n\treturn v.led.TransferFrom(owner, spender, to, amount)\n}\n\n// Summary renders the vault as a markdown block.\nfunc (v *Vault) Summary() string {\n\ts := ufmt.Sprintf(\"**%s** (%s) - %s wrapper over %s\\n\\n\",\n\t\tv.tok.GetName(), v.tok.GetSymbol(), v.pol.Name(), v.under.GetSymbol())\n\ts += ufmt.Sprintf(\"- wrapped supply: %d\\n\", v.Supply())\n\ts += ufmt.Sprintf(\"- escrowed underlying: %d\\n\", v.held)\n\ts += ufmt.Sprintf(\"- realm custody: %d\\n\", v.Custody())\n\tif v.Solvent() {\n\t\ts += \"- solvent: yes\\n\"\n\t} else {\n\t\ts += \"- solvent: **NO**\\n\"\n\t}\n\treturn s\n}\n\n// mulDiv returns a*b/c, rejecting an overflowing product and a zero divisor.\n// The division truncates toward zero, which always rounds in the vault's\n// favour rather than the holder's.\nfunc mulDiv(a, b, c int64) (int64, error) {\n\tif c \u003c= 0 {\n\t\treturn 0, ErrBadRatio\n\t}\n\tp, ok := overflow.Mul64(a, b)\n\tif !ok {\n\t\treturn 0, ErrOverflow\n\t}\n\treturn p / c, nil\n}\n"},{"name":"wrap_test.gno","body":"package grc20wrap\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// The two realms every test needs: one that issues the underlying token, one\n// that wraps it. They MUST be distinct, because wrapping a token issued by your\n// own realm exercises none of the interesting machinery: the allowance, the\n// eagerly-bound teller, the foreign escrow.\nconst (\n\tunderPath = \"gno.land/r/test/under\"\n\twrapPath  = \"gno.land/r/test/wrapper\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarl  = testutils.TestAddress(\"carl\")\n)\n\n// mintUnder issues the underlying token from underPath and funds holders.\nfunc mintUnder(cur realm, t *testing.T, funded ...address) (*grc20.Token, *grc20.PrivateLedger) {\n\tt.Helper()\n\ttesting.SetRealm(testing.NewCodeRealm(underPath))\n\ttok, led := grc20.NewToken(\"Under\", \"UND\", 4, 0, cur)\n\tfor _, a := range funded {\n\t\turequire.NoError(t, led.Mint(a, 1_000))\n\t}\n\treturn tok, led\n}\n\n// approve stands in for the underlying realm's own Approve entry point: on\n// chain the holder calls it, here the ledger does it on their behalf.\nfunc approve(cur realm, t *testing.T, led *grc20.PrivateLedger, owner, spender address, amount int64) {\n\tt.Helper()\n\turequire.NoError(t, led.ImpersonateTeller(owner).Approve(0, cur, spender, amount))\n}\n\nfunc TestOneToOneRoundTrip(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, OneToOne{}, \"Wrapped Under\", \"wUND\", 4, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 1_000)\n\n\tout, err := v.Wrap(0, cur, alice, 400)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(400), out)\n\tuassert.Equal(t, int64(400), v.Token().BalanceOf(alice))\n\tuassert.Equal(t, int64(600), under.BalanceOf(alice))\n\tuassert.Equal(t, int64(400), v.Held())\n\tuassert.Equal(t, int64(400), v.Custody())\n\tuassert.True(t, v.Solvent())\n\n\tback, err := v.Unwrap(0, cur, alice, 150)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(150), back)\n\tuassert.Equal(t, int64(250), v.Token().BalanceOf(alice))\n\tuassert.Equal(t, int64(250), v.Supply())\n\tuassert.Equal(t, int64(750), under.BalanceOf(alice))\n\tuassert.Equal(t, int64(250), v.Held())\n\tuassert.True(t, v.Solvent())\n}\n\n// Escrow is pulled with an allowance, so a wrapper can never take more than a\n// holder granted it. This is the property that makes a wrapper safe to publish\n// as a permissionless factory: it has no authority nobody handed it.\nfunc TestWrapStopsAtTheAllowance(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, OneToOne{}, \"Wrapped Under\", \"wUND\", 4, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 100)\n\n\t_, err := v.Wrap(0, cur, alice, 101)\n\tuassert.ErrorContains(t, err, \"insufficient allowance\")\n\tuassert.Equal(t, int64(0), v.Supply())\n\tuassert.Equal(t, int64(1_000), under.BalanceOf(alice))\n\n\t_, err = v.Wrap(0, cur, alice, 0)\n\tuassert.ErrorIs(t, err, ErrInvalidAmount)\n}\n\n// Unwrapping is bounded by the wrapped balance, not by the escrow: a holder\n// cannot redeem somebody else's deposit.\nfunc TestUnwrapStopsAtTheBalance(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice, bob)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, OneToOne{}, \"Wrapped Under\", \"wUND\", 4, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 1_000)\n\tapprove(cur, t, led, bob, v.Home(), 1_000)\n\n\t_, err := v.Wrap(0, cur, alice, 500)\n\turequire.NoError(t, err)\n\t_, err = v.Wrap(0, cur, bob, 500)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1_000), v.Held())\n\n\t_, err = v.Unwrap(0, cur, bob, 501)\n\tuassert.ErrorContains(t, err, \"insufficient balance\")\n\tuassert.Equal(t, int64(1_000), v.Held())\n}\n\n// Ratio gives a token more decimals than the realm that issued it ever offered.\nfunc TestRatioRedenominates(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, Ratio{Num: 1_000, Den: 1}, \"Kilo Under\", \"kUND\", 7, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 1_000)\n\n\tout, err := v.Wrap(0, cur, alice, 5)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(5_000), out)\n\tuassert.Equal(t, int64(5), v.Held())\n\n\tback, err := v.Unwrap(0, cur, alice, 3_000)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(3), back)\n\tuassert.Equal(t, int64(2), v.Held())\n\n\t// A redemption too small to buy one underlying unit is refused rather\n\t// than silently burning the wrapped units for nothing.\n\t_, err = v.Unwrap(0, cur, alice, 999)\n\tuassert.ErrorIs(t, err, ErrDust)\n\tuassert.Equal(t, int64(2_000), v.Supply())\n}\n\n// Soulbound: wrap in, unwrap out, but never hand the receipt to anybody.\nfunc TestSoulboundReceipt(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, Soulbound{}, \"Bound Under\", \"sUND\", 4, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 1_000)\n\n\t_, err := v.Wrap(0, cur, alice, 300)\n\turequire.NoError(t, err)\n\n\tuassert.ErrorIs(t, v.Move(alice, bob, 1), ErrSoulbound)\n\tuassert.Equal(t, int64(0), v.Token().BalanceOf(bob))\n\n\t// An allowance may be granted, and is still worthless when spent.\n\turequire.NoError(t, v.Allow(alice, bob, 100))\n\tuassert.ErrorIs(t, v.MoveFrom(bob, alice, carl, 100), ErrSoulbound)\n\n\t// The exit is always open: unwrap, then move the underlying.\n\tback, err := v.Unwrap(0, cur, alice, 300)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(300), back)\n\tuassert.Equal(t, int64(0), v.Supply())\n}\n\n// Pool is the yield-bearing pattern: a donation nobody can withdraw raises what\n// every share redeems for, and later depositors buy in at the new price.\nfunc TestPoolSharesAppreciate(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice, bob, carl)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, Pool{}, \"Pooled Under\", \"pUND\", 4, 0, cur)\n\tfor _, a := range []address{alice, bob, carl} {\n\t\tapprove(cur, t, led, a, v.Home(), 1_000)\n\t}\n\n\t// First in, priced 1:1 because the pool is empty.\n\tout, err := v.Wrap(0, cur, alice, 100)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(100), out)\n\n\t// bob donates: escrow doubles, share count does not move.\n\turequire.NoError(t, v.Donate(0, cur, bob, 100))\n\tuassert.Equal(t, int64(200), v.Held())\n\tuassert.Equal(t, int64(100), v.Supply())\n\n\t// carl now pays twice as much per share.\n\tout, err = v.Wrap(0, cur, carl, 100)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(50), out)\n\tuassert.Equal(t, int64(300), v.Held())\n\tuassert.Equal(t, int64(150), v.Supply())\n\n\t// alice redeems 100 shares of 150 against 300 escrowed: 200 back, on a\n\t// 100 deposit. bob's donation went to whoever was holding.\n\tback, err := v.Unwrap(0, cur, alice, 100)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(200), back)\n\tuassert.Equal(t, int64(1_100), under.BalanceOf(alice))\n\n\t// carl is made whole, and the pool closes empty.\n\tback, err = v.Unwrap(0, cur, carl, 50)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(100), back)\n\tuassert.Equal(t, int64(0), v.Held())\n\tuassert.Equal(t, int64(0), v.Supply())\n\tuassert.True(t, v.Solvent())\n}\n\n// Fee over Pool: the haircut is not paid out, it is left behind, so the people\n// still holding are the ones who collect it.\nfunc TestFeeOverPoolPaysTheHolders(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice, bob)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, Fee{Base: Pool{}, WrapBPS: 0, UnwrapBPS: 1_000}, \"Sticky Under\", \"fUND\", 4, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 1_000)\n\tapprove(cur, t, led, bob, v.Home(), 1_000)\n\n\t_, err := v.Wrap(0, cur, alice, 500)\n\turequire.NoError(t, err)\n\t_, err = v.Wrap(0, cur, bob, 500)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1_000), v.Supply())\n\n\t// alice leaves and pays 10% on the way out: 500 - 50.\n\tback, err := v.Unwrap(0, cur, alice, 500)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(450), back)\n\n\t// bob stayed, and the 50 alice left behind is now his.\n\tuassert.Equal(t, int64(550), v.Held())\n\tuassert.Equal(t, int64(500), v.Supply())\n\tback, err = v.Unwrap(0, cur, bob, 500)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(495), back) // 550 pro rata, minus the same 10%\n\tuassert.Equal(t, int64(55), v.Held())\n}\n\n// Two vaults over the same underlying share one escrow account, so Held() is\n// the only thing that keeps them apart. Pin that they do.\nfunc TestTwoVaultsShareOneEscrowAccount(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\ta := NewVault(under, OneToOne{}, \"Vault A\", \"vA\", 4, 0, cur)\n\tb := NewVault(under, OneToOne{}, \"Vault B\", \"vB\", 4, 1, cur)\n\tuassert.Equal(t, a.Home().String(), b.Home().String())\n\tapprove(cur, t, led, alice, a.Home(), 1_000)\n\n\t_, err := a.Wrap(0, cur, alice, 300)\n\turequire.NoError(t, err)\n\t_, err = b.Wrap(0, cur, alice, 200)\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, int64(300), a.Held())\n\tuassert.Equal(t, int64(200), b.Held())\n\t// Custody is realm-wide: it sees both.\n\tuassert.Equal(t, int64(500), a.Custody())\n\tuassert.Equal(t, int64(500), b.Custody())\n\n\t// Vault B refuses to release more than it took in, even though the\n\t// account it draws on holds A's escrow too. Without the per-vault\n\t// counter this is exactly where one vault would eat the other's.\n\t_, err = b.Unwrap(0, cur, alice, 201)\n\tuassert.ErrorIs(t, err, ErrUnbacked)\n\tuassert.Equal(t, int64(200), b.Held())\n\tuassert.Equal(t, int64(500), b.Custody())\n\n\t// Both still unwind cleanly and independently.\n\t_, err = b.Unwrap(0, cur, alice, 200)\n\turequire.NoError(t, err)\n\t_, err = a.Unwrap(0, cur, alice, 300)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(0), a.Custody())\n\tuassert.Equal(t, int64(1_000), under.BalanceOf(alice))\n}\n\nfunc TestMoveAndAllowance(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, OneToOne{}, \"Wrapped Under\", \"wUND\", 4, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 1_000)\n\t_, err := v.Wrap(0, cur, alice, 600)\n\turequire.NoError(t, err)\n\n\turequire.NoError(t, v.Move(alice, bob, 100))\n\tuassert.Equal(t, int64(100), v.Token().BalanceOf(bob))\n\tuassert.ErrorIs(t, v.Move(alice, bob, 0), ErrInvalidAmount)\n\n\turequire.NoError(t, v.Allow(alice, bob, 250))\n\tuassert.Equal(t, int64(250), v.Token().Allowance(alice, bob))\n\turequire.NoError(t, v.MoveFrom(bob, alice, carl, 250))\n\tuassert.Equal(t, int64(250), v.Token().BalanceOf(carl))\n\tuassert.ErrorContains(t, v.MoveFrom(bob, alice, carl, 1), \"insufficient allowance\")\n}\n\nfunc TestNewVaultRejectsNilUnderlying(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tuassert.PanicsContains(t, cur, \"nil underlying token\", func() {\n\t\tNewVault(nil, OneToOne{}, \"Broken\", \"BRK\", 4, 0, cur)\n\t})\n}\n\nfunc TestNilPolicyMeansOneToOne(cur realm, t *testing.T) {\n\tunder, _ := mintUnder(cur, t)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, nil, \"Wrapped Under\", \"wUND\", 4, 0, cur)\n\tuassert.Equal(t, \"1:1\", v.Policy().Name())\n}\n\nfunc TestSummaryReportsSolvency(cur realm, t *testing.T) {\n\tunder, led := mintUnder(cur, t, alice)\n\n\ttesting.SetRealm(testing.NewCodeRealm(wrapPath))\n\tv := NewVault(under, OneToOne{}, \"Wrapped Under\", \"wUND\", 4, 0, cur)\n\tapprove(cur, t, led, alice, v.Home(), 1_000)\n\t_, err := v.Wrap(0, cur, alice, 250)\n\turequire.NoError(t, err)\n\n\twant := \"**Wrapped Under** (wUND) - 1:1 wrapper over UND\\n\\n\" +\n\t\t\"- wrapped supply: 250\\n\" +\n\t\t\"- escrowed underlying: 250\\n\" +\n\t\t\"- realm custody: 250\\n\" +\n\t\t\"- solvent: yes\\n\"\n\tuassert.Equal(t, want, v.Summary())\n}\n"}]},"send":"","max_deposit":"20000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"merkle","path":"gno.land/p/moul/x/merkle/v0","files":[{"name":"README.md","body":"# merkle\n\nMerkle inclusion proofs on gno.land, built on the **native `crypto/merkle` stdlib**.\n\nThat stdlib landed with the IBC crypto batch (gnolang/gno#5725) and is live on mainnet.\nBefore this package it had **zero callers** anywhere: not in `gnolang/gno`'s `examples/`,\nnot here. Meanwhile the only userland Merkle tree in the ecosystem, `p/demo/merkle`, is\nquarantined and not deployed on any chain.\n\n## The scheme\n\nThe **Tendermint simple tree**, byte for byte the one tm2 uses for block headers. Proofs\nproduced here verify against any Tendermint tooling and vice versa. The tests pin golden\nroots and sibling lists generated by tm2's own `merkle.SimpleProofsFromByteSlices`, so a\ndivergence fails CI rather than shipping.\n\nTwo properties, neither optional:\n\n**Domain separation.** A leaf is `SHA256(0x00 || leaf)`, an inner node is\n`SHA256(0x01 || left || right)`. Without those tags an inner node hash is also a valid leaf\nhash, so anyone able to choose a 64-byte leaf preimage can prove membership of a leaf that\nwas never in the tree. `TestSecondPreimageForgery` performs exactly that attack against the\ncommutative scheme and then shows the tagged scheme refuse it.\n\n**Index binding.** A proof carries its leaf index and the total leaf count, and the verifier\nrebuilds the tree shape from them. A proof for index `i` cannot be replayed at index `j`, and\na proof of the wrong length is rejected rather than folded.\n\nThe tree is **not** padded to a power of two. Following Tendermint, an `n`-leaf tree splits\nat the largest power of two below `n`, so the shape is a function of `n` alone. Duplicating\nor promoting an odd trailing leaf, as Bitcoin and merkletreejs do, lets two different leaf\nsets produce one root.\n\n## Usage\n\n```go\nimport \"gno.land/p/moul/x/merkle/v0\"\n\ntree := merkle.New([][]byte{[]byte(\"alice:100\"), []byte(\"bob:250\"), []byte(\"carol:500\")})\nroot := tree.RootHex()          // commit this\np, _ := tree.Proof(1)           // hand p.Index, p.Total, p.Hex() to the user\n\n// later, in a realm, against a root it already committed to:\np, err := merkle.ParseProof(index, total, hexSiblings)\nif err == nil \u0026\u0026 p.Verify(committedRoot, []byte(\"bob:250\")) {\n    // bob really is in the committed set, at position 1\n}\n```\n\nVerification is a **single native call**. Measured at depth 20 it costs roughly a seventh of\nthe equivalent hand-rolled fold in Gno, and a third of calling `InnerHash` twenty times,\nbecause per-native-call overhead dominates. (Gas figures are directional: the calibration\ntable in `native_gas.go` fits the `crypto/merkle` rows on a different CPU from the\n`crypto/sha256` rows.)\n\n`Verify` refuses proofs deeper than `MaxDepth` (64). An unbounded sibling list is a loop\nwhose length an untrusted caller picks.\n\n## `VerifySorted`: interop only\n\n`VerifySorted` folds the commutative sorted-pair scheme that OpenZeppelin's `MerkleProof`\nand merkletreejs produce, for verifying trees built by existing Solidity tooling. It is\nstrictly weaker: no domain separation, no index binding. Pass an already-hashed leaf, and\ndouble-hash it if the producer does. Prefer `Proof.Verify` for anything new.\n\n## What this package cannot do\n\nIt verifies a leaf against a root **you supply**. A realm has no access to the block header\nor the app hash (`chain/runtime` exposes only `ChainID`, `ChainDomain`, `ChainHeight` and\n`GetSessionInfo`), so no realm can check that a root is the chain's own. Anything built on\nthis is trust-minimised relative to a committed root, never trustless.\n\nWorse, and less obvious: **gno.land cannot prove its own realm state to anyone.** Realm\nobjects live in a store that is explicitly not merkleized. See\n[`r/moul/x/provable/v0`](../../../../../r/moul/x/provable/v0) for the full picture.\n\n## Gno gotcha found while building this\n\nA native function returning Go `nil` for a `[]byte` hands gno back a **non-nil, zero-length\nslice**. `merkle.HashFromByteSlices(malformed) == nil` is therefore always false. Test\n`len(x) == 0`, never `x == nil`, on anything that crossed the native boundary.\n\n## Related\n\n- Append-only log with O(log n) state: [`p/moul/x/mmr/v0`](../../mmr/v0)\n- Live demo: [`r/moul/x/provable/v0`](../../../../../r/moul/x/provable/v0)\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/merkle/v0\"\ngno = \"0.9\"\n"},{"name":"internal.gno","body":"package merkle\n\nimport \"crypto/sha256\"\n\n// encodeSlices renders items in the wire shape crypto/merkle.HashFromByteSlices\n// expects: a 4-byte big-endian count, then per item a 4-byte big-endian length\n// followed by its bytes. The native side decodes this back into [][]byte; gno\n// cannot hand a slice of slices to a native directly.\nfunc encodeSlices(items [][]byte) []byte {\n\tn := 0\n\tfor _, it := range items {\n\t\tn += 4 + len(it)\n\t}\n\tout := make([]byte, 0, 4+n)\n\tout = appendBE32(out, len(items))\n\tfor _, it := range items {\n\t\tout = appendBE32(out, len(it))\n\t\tout = append(out, it...)\n\t}\n\treturn out\n}\n\nfunc appendBE32(dst []byte, n int) []byte {\n\treturn append(dst, byte(n\u003e\u003e24), byte(n\u003e\u003e16), byte(n\u003e\u003e8), byte(n))\n}\n\n// hashSortedPair is the commutative node hash: SHA256 over the two children in\n// ascending byte order, so a proof needs no left/right flag. Used only by\n// VerifySorted.\nfunc hashSortedPair(a, b []byte) []byte {\n\td := make([]byte, 0, len(a)+len(b))\n\tif less(a, b) {\n\t\td = append(append(d, a...), b...)\n\t} else {\n\t\td = append(append(d, b...), a...)\n\t}\n\th := sha256.Sum256(d)\n\treturn h[:]\n}\n\n// less reports a \u003c b in lexicographic byte order. gno's bytes package is\n// available, but keeping the comparison here keeps this package import-light.\nfunc less(a, b []byte) bool {\n\tn := len(a)\n\tif len(b) \u003c n {\n\t\tn = len(b)\n\t}\n\tfor i := 0; i \u003c n; i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn a[i] \u003c b[i]\n\t\t}\n\t}\n\treturn len(a) \u003c len(b)\n}\n\nfunc equal(a, b []byte) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"},{"name":"merkle.gno","body":"// Package merkle builds and verifies Merkle inclusion proofs on gno.land.\n//\n// It wraps the `crypto/merkle` stdlib, which is native (implemented in Go,\n// gas-metered) and shipped with the chain, and which had no callers anywhere\n// before this package. Verification is a single native call, so it costs about\n// a seventh of the equivalent hand-rolled loop in Gno.\n//\n// # The scheme\n//\n// The tree is the Tendermint simple tree, byte-for-byte the one tm2 uses for\n// block headers, so a proof produced here verifies against any Tendermint\n// tooling and vice versa. Two properties matter and neither is optional:\n//\n//   - Leaves and inner nodes are DOMAIN SEPARATED. A leaf hashes as\n//     SHA256(0x00 || leaf), an inner node as SHA256(0x01 || left || right).\n//     Without that tag an attacker who can choose a 64-byte leaf preimage can\n//     present an inner node as if it were a leaf: the second-preimage attack.\n//     Schemes that hash leaves bare (OpenZeppelin's `MerkleProof`,\n//     merkletreejs defaults, `p/demo/merkle`) are safe only as long as no leaf\n//     preimage can be exactly 64 bytes, which is an accident of encoding\n//     rather than a property of the design.\n//   - Proofs are INDEX BOUND. A proof carries its leaf index and the total\n//     leaf count, and the verifier recomputes the tree shape from them. A\n//     proof for index i cannot be replayed at index j, and a proof of the\n//     wrong length is rejected rather than folded.\n//\n// The tree is NOT padded to a power of two. Following Tendermint, a tree of n\n// leaves splits at the largest power of two below n, which makes the shape a\n// function of n alone. Duplicating or promoting an odd trailing leaf, as\n// Bitcoin and merkletreejs do, lets two different leaf sets produce one root.\n//\n// # Bounds\n//\n// Verify refuses proofs deeper than MaxDepth. An unbounded sibling list is a\n// loop whose length an untrusted caller picks; the caller pays the gas, but\n// there is no reason to accept 10,000 siblings for a tree that cannot hold\n// more than 2^64 leaves.\n//\n// # Reproducing a tree off chain\n//\n// Any Tendermint implementation agrees with this one. In Go:\n//\n//\timport \"github.com/gnolang/gno/tm2/pkg/crypto/merkle\"\n//\troot, proofs := merkle.SimpleProofsFromByteSlices(leaves)\n//\n// # What this package cannot do\n//\n// It verifies a leaf against a root YOU SUPPLY. A realm has no access to the\n// block header or the app hash (`chain/runtime` exposes only ChainID,\n// ChainDomain, ChainHeight and GetSessionInfo), so no realm can check that a\n// root is the chain's own. Anything built on this is trust-minimised relative\n// to a committed root, never trustless. See `r/moul/x/provable/v0` for what\n// gno.land can and cannot prove about itself.\n//\n// Live demo: gno.land/r/moul/x/provable/v0\npackage merkle\n\nimport (\n\t\"crypto/merkle\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"strings\"\n)\n\n// HashSize is the length in bytes of every node hash (SHA256).\nconst HashSize = 32\n\n// MaxDepth caps the sibling count Verify will fold. A tree of 2^64 leaves has\n// depth 64, so nothing legitimate ever exceeds it.\nconst MaxDepth = 64\n\nvar (\n\tErrEmptyTree    = errors.New(\"merkle: tree has no leaves\")\n\tErrIndexRange   = errors.New(\"merkle: leaf index out of range\")\n\tErrProofTooDeep = errors.New(\"merkle: proof deeper than MaxDepth\")\n\tErrBadHex       = errors.New(\"merkle: sibling is not valid hex\")\n\tErrBadHashSize  = errors.New(\"merkle: sibling is not 32 bytes\")\n)\n\n// LeafHash returns SHA256(0x00 || leaf), the Tendermint leaf hash.\nfunc LeafHash(leaf []byte) []byte { return merkle.LeafHash(leaf) }\n\n// InnerHash returns SHA256(0x01 || left || right), the Tendermint inner hash.\nfunc InnerHash(left, right []byte) []byte { return merkle.InnerHash(left, right) }\n\n// Proof is an inclusion proof for one leaf of a tree of Total leaves.\n//\n// Siblings are ordered leaf first, root last: Siblings[0] is the leaf's\n// immediate sibling and the final entry is the other child of the root. This\n// is Tendermint's \"aunts\" order.\ntype Proof struct {\n\tIndex    int\n\tTotal    int\n\tSiblings [][]byte\n}\n\n// Tree is an immutable Merkle tree over a fixed list of leaves.\n//\n// It holds the leaves, so it is meant to be built inside one call (from\n// arguments, or from a bounded realm collection) rather than kept in realm\n// storage. For an append-only log that stores only O(log n) state, use\n// gno.land/p/moul/x/mmr/v0 instead.\ntype Tree struct {\n\tleaves [][]byte\n\troot   []byte\n}\n\n// New builds a tree over leaves, in the order given. The order is part of the\n// commitment: the same set in a different order is a different root.\nfunc New(leaves [][]byte) *Tree {\n\tcp := make([][]byte, len(leaves))\n\tfor i, l := range leaves {\n\t\tb := make([]byte, len(l))\n\t\tcopy(b, l)\n\t\tcp[i] = b\n\t}\n\tt := \u0026Tree{leaves: cp}\n\tif len(cp) \u003e 0 {\n\t\tt.root = merkle.HashFromByteSlices(encodeSlices(cp))\n\t}\n\treturn t\n}\n\n// Size returns the number of leaves.\nfunc (t *Tree) Size() int { return len(t.leaves) }\n\n// Root returns the tree root. It is nil for an empty tree, matching\n// Tendermint, where the root of nothing is nothing rather than a hash of\n// nothing.\n//\n// The nil is produced here rather than passed through: a native that returns\n// Go nil hands gno back a NON-NIL zero-length slice, so `== nil` on a value\n// straight out of crypto/merkle never fires. Test len(), not nil, on anything\n// that crossed that boundary.\nfunc (t *Tree) Root() []byte { return t.root }\n\n// RootHex returns Root hex-encoded, the form to paste into a realm call.\nfunc (t *Tree) RootHex() string { return hex.EncodeToString(t.root) }\n\n// Proof returns the inclusion proof for the leaf at index.\nfunc (t *Tree) Proof(index int) (Proof, error) {\n\tif len(t.leaves) == 0 {\n\t\treturn Proof{}, ErrEmptyTree\n\t}\n\tif index \u003c 0 || index \u003e= len(t.leaves) {\n\t\treturn Proof{}, ErrIndexRange\n\t}\n\treturn Proof{\n\t\tIndex:    index,\n\t\tTotal:    len(t.leaves),\n\t\tSiblings: aunts(t.leaves, index),\n\t}, nil\n}\n\n// aunts collects the sibling hashes on the path from leaves[index] to the\n// root, leaf first. It mirrors Tendermint's split-point recursion exactly; any\n// divergence here produces proofs the native verifier rejects.\nfunc aunts(leaves [][]byte, index int) [][]byte {\n\tif len(leaves) \u003c= 1 {\n\t\treturn nil\n\t}\n\tk := splitPoint(len(leaves))\n\tif index \u003c k {\n\t\tsub := aunts(leaves[:k], index)\n\t\treturn append(sub, subtreeRoot(leaves[k:]))\n\t}\n\tsub := aunts(leaves[k:], index-k)\n\treturn append(sub, subtreeRoot(leaves[:k]))\n}\n\nfunc subtreeRoot(leaves [][]byte) []byte {\n\treturn merkle.HashFromByteSlices(encodeSlices(leaves))\n}\n\n// splitPoint returns the largest power of two strictly less than length.\nfunc splitPoint(length int) int {\n\tif length \u003c 2 {\n\t\treturn 0\n\t}\n\tk := 1\n\tfor k\u003c\u003c1 \u003c length {\n\t\tk \u003c\u003c= 1\n\t}\n\treturn k\n}\n\n// Verify reports whether leaf really sits at p.Index of a tree of p.Total\n// leaves whose root is root. It is one native call plus the bounds checks.\n//\n// Every failure is a false rather than a panic, so a realm can decide whether\n// a bad proof is a revert or a branch.\nfunc (p Proof) Verify(root, leaf []byte) bool {\n\tif len(root) != HashSize || p.Total \u003c= 0 || p.Index \u003c 0 || p.Index \u003e= p.Total {\n\t\treturn false\n\t}\n\tif len(p.Siblings) \u003e MaxDepth {\n\t\treturn false\n\t}\n\tflat := make([]byte, 0, len(p.Siblings)*HashSize)\n\tfor _, s := range p.Siblings {\n\t\tif len(s) != HashSize {\n\t\t\treturn false\n\t\t}\n\t\tflat = append(flat, s...)\n\t}\n\treturn merkle.VerifySimpleProof(root, leaf, p.Index, p.Total, flat)\n}\n\n// Hex renders the siblings as a comma-separated hex list, the form a user\n// pastes into a transaction. Index and Total travel as their own arguments.\nfunc (p Proof) Hex() string {\n\tparts := make([]string, len(p.Siblings))\n\tfor i, s := range p.Siblings {\n\t\tparts[i] = hex.EncodeToString(s)\n\t}\n\treturn strings.Join(parts, \",\")\n}\n\n// ParseProof rebuilds a Proof from the arguments of a realm call. An empty or\n// whitespace-only sibling list is valid: it is the proof for a one-leaf tree.\nfunc ParseProof(index, total int, hexSiblings string) (Proof, error) {\n\tp := Proof{Index: index, Total: total}\n\ts := strings.TrimSpace(hexSiblings)\n\tif s == \"\" {\n\t\treturn p, nil\n\t}\n\tparts := strings.Split(s, \",\")\n\tif len(parts) \u003e MaxDepth {\n\t\treturn Proof{}, ErrProofTooDeep\n\t}\n\tfor _, raw := range parts {\n\t\traw = strings.TrimSpace(raw)\n\t\tif raw == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tb, err := hex.DecodeString(raw)\n\t\tif err != nil {\n\t\t\treturn Proof{}, ErrBadHex\n\t\t}\n\t\tif len(b) != HashSize {\n\t\t\treturn Proof{}, ErrBadHashSize\n\t\t}\n\t\tp.Siblings = append(p.Siblings, b)\n\t}\n\treturn p, nil\n}\n\n// VerifySorted folds a commutative, sorted-pair proof: node = SHA256(min || max)\n// at every step, which is what OpenZeppelin's MerkleProof and merkletreejs\n// produce. Provided for verifying trees built by existing Solidity tooling.\n//\n// PREFER Proof.Verify. This scheme is strictly weaker:\n//\n//   - It is not domain separated, so it is sound only while no leaf preimage\n//     can be 64 bytes long. Pass an ALREADY HASHED leaf, and double-hash it if\n//     the producer does (OpenZeppelin's StandardMerkleTree does).\n//   - It is not index bound, so a proof carries no position and the fold\n//     accepts any depth up to MaxDepth.\n//\n// leafHash must be the 32-byte hash of the leaf, not the leaf.\nfunc VerifySorted(root, leafHash []byte, siblings [][]byte) bool {\n\tif len(root) != HashSize || len(leafHash) != HashSize {\n\t\treturn false\n\t}\n\tif len(siblings) \u003e MaxDepth {\n\t\treturn false\n\t}\n\tnode := leafHash\n\tfor _, s := range siblings {\n\t\tif len(s) != HashSize {\n\t\t\treturn false\n\t\t}\n\t\tnode = hashSortedPair(node, s)\n\t}\n\treturn equal(node, root)\n}\n"},{"name":"merkle_test.gno","body":"package merkle\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"testing\"\n)\n\n// leaves returns n deterministic leaves, \"leaf-0\" … \"leaf-n-1\". The golden\n// vectors below were produced from these exact inputs by tm2's own\n// merkle.SimpleProofsFromByteSlices, so a mismatch means this package has\n// diverged from Tendermint, not that the expectation is stale.\nfunc leaves(n int) [][]byte {\n\tout := make([][]byte, n)\n\tfor i := 0; i \u003c n; i++ {\n\t\tout[i] = []byte(\"leaf-\" + strconv.Itoa(i))\n\t}\n\treturn out\n}\n\nvar goldenRoots = map[int]string{\n\t1: \"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7\",\n\t2: \"60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc\",\n\t3: \"cf763a041c81ceef1578a6083f75c61bef2e0014f2a3e683a97fcfca5be7f19a\",\n\t4: \"bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3\",\n\t5: \"00d21829a5503145348abcf712513eacf2a274211ad83e970202bb5b6d80b286\",\n\t7: \"0b007fb915eb9b2a146f54b1c86ec53b664f8e455b7660b0b6ee13edc0d921c0\",\n}\n\n// goldenAunts[n][i] is the comma-separated hex sibling list tm2 produces for\n// leaf i of an n-leaf tree.\nvar goldenAunts = map[int][]string{\n\t1: {\"\"},\n\t2: {\n\t\t\"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f\",\n\t\t\"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7\",\n\t},\n\t3: {\n\t\t\"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f,fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267\",\n\t\t\"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7,fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267\",\n\t\t\"60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc\",\n\t},\n\t4: {\n\t\t\"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69\",\n\t\t\"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69\",\n\t\t\"f76836325aec5699d8d71f8e42e9d47c5c29b08059ba296384f7ca40ad3a40ae,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc\",\n\t\t\"fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc\",\n\t},\n\t7: {\n\t\t\"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23\",\n\t\t\"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23\",\n\t\t\"f76836325aec5699d8d71f8e42e9d47c5c29b08059ba296384f7ca40ad3a40ae,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23\",\n\t\t\"fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23\",\n\t\t\"8f1593cb92f429d9340b9bbc1f0bb122adf8026c42a4a42142e2168931727236,676f3782f5b3a5fb4370ed49572cedc523f4a66322269c85f2af0509d17b0a4d,bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3\",\n\t\t\"ea9fc1a1b6e191b460d0d6306e3e870c173f39330f13cda1b70cfc72bdc398ba,676f3782f5b3a5fb4370ed49572cedc523f4a66322269c85f2af0509d17b0a4d,bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3\",\n\t\t\"985bb5d36b927800876871da925a7e82abe83a9ddba5882920a007a55ea2b376,bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3\",\n\t},\n}\n\nfunc TestRootMatchesTendermint(t *testing.T) {\n\tfor _, n := range []int{1, 2, 3, 4, 5, 7} {\n\t\tgot := New(leaves(n)).RootHex()\n\t\tif got != goldenRoots[n] {\n\t\t\tt.Errorf(\"n=%d: root = %s, tm2 says %s\", n, got, goldenRoots[n])\n\t\t}\n\t}\n}\n\nfunc TestProofMatchesTendermint(t *testing.T) {\n\tfor n, want := range goldenAunts {\n\t\ttree := New(leaves(n))\n\t\tfor i, w := range want {\n\t\t\tp, err := tree.Proof(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"n=%d i=%d: Proof: %v\", n, i, err)\n\t\t\t}\n\t\t\tif got := p.Hex(); got != w {\n\t\t\t\tt.Errorf(\"n=%d i=%d:\\n got  %s\\n want %s\", n, i, got, w)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Every leaf of every tree shape up to 33 must produce a proof the native\n// verifier accepts. This is the property that matters; the golden vectors only\n// pin the encoding.\nfunc TestEveryProofVerifies(t *testing.T) {\n\tfor n := 1; n \u003c= 33; n++ {\n\t\tls := leaves(n)\n\t\ttree := New(ls)\n\t\troot := tree.Root()\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\tp, err := tree.Proof(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"n=%d i=%d: Proof: %v\", n, i, err)\n\t\t\t}\n\t\t\tif !p.Verify(root, ls[i]) {\n\t\t\t\tt.Errorf(\"n=%d i=%d: valid proof rejected\", n, i)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestRejects(t *testing.T) {\n\tls := leaves(8)\n\ttree := New(ls)\n\troot := tree.Root()\n\tp0, _ := tree.Proof(0)\n\tp1, _ := tree.Proof(1)\n\n\ttests := []struct {\n\t\tname  string\n\t\tproof Proof\n\t\troot  []byte\n\t\tleaf  []byte\n\t}{\n\t\t{\"forged leaf\", p0, root, []byte(\"not-a-leaf\")},\n\t\t{\"another real leaf at the wrong index\", p0, root, ls[1]},\n\t\t{\"proof replayed at a different index\", Proof{Index: 1, Total: p0.Total, Siblings: p0.Siblings}, root, ls[1]},\n\t\t{\"sibling list of another leaf\", Proof{Index: 0, Total: 8, Siblings: p1.Siblings}, root, ls[0]},\n\t\t{\"wrong root\", p0, LeafHash([]byte(\"nope\")), ls[0]},\n\t\t{\"index beyond total\", Proof{Index: 8, Total: 8, Siblings: p0.Siblings}, root, ls[0]},\n\t\t{\"negative index\", Proof{Index: -1, Total: 8, Siblings: p0.Siblings}, root, ls[0]},\n\t\t{\"zero total\", Proof{Index: 0, Total: 0, Siblings: p0.Siblings}, root, ls[0]},\n\t\t{\"truncated proof\", Proof{Index: 0, Total: 8, Siblings: p0.Siblings[:1]}, root, ls[0]},\n\t\t{\"short root\", p0, root[:31], ls[0]},\n\t}\n\tfor _, tc := range tests {\n\t\tif tc.proof.Verify(tc.root, tc.leaf) {\n\t\t\tt.Errorf(\"%s: accepted, must be rejected\", tc.name)\n\t\t}\n\t}\n}\n\nfunc TestMaxDepthCap(t *testing.T) {\n\tsibs := make([][]byte, MaxDepth+1)\n\tfor i := range sibs {\n\t\tsibs[i] = make([]byte, HashSize)\n\t}\n\tp := Proof{Index: 0, Total: 1 \u003c\u003c 20, Siblings: sibs}\n\tif p.Verify(make([]byte, HashSize), []byte(\"x\")) {\n\t\tt.Error(\"proof deeper than MaxDepth accepted\")\n\t}\n\tif !VerifySorted(make([]byte, HashSize), make([]byte, HashSize), sibs[:MaxDepth]) == false {\n\t\tt.Error(\"unreachable\")\n\t}\n\tif VerifySorted(make([]byte, HashSize), make([]byte, HashSize), sibs) {\n\t\tt.Error(\"sorted proof deeper than MaxDepth accepted\")\n\t}\n}\n\nfunc TestParseProofRoundTrip(t *testing.T) {\n\ttree := New(leaves(7))\n\tfor i := 0; i \u003c 7; i++ {\n\t\twant, _ := tree.Proof(i)\n\t\tgot, err := ParseProof(i, 7, want.Hex())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"i=%d: ParseProof: %v\", i, err)\n\t\t}\n\t\tif got.Hex() != want.Hex() || got.Index != want.Index || got.Total != want.Total {\n\t\t\tt.Errorf(\"i=%d: round trip lost data\", i)\n\t\t}\n\t\tif !got.Verify(tree.Root(), []byte(\"leaf-\"+strconv.Itoa(i))) {\n\t\t\tt.Errorf(\"i=%d: reparsed proof does not verify\", i)\n\t\t}\n\t}\n}\n\nfunc TestParseProofErrors(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tin   string\n\t\twant error\n\t}{\n\t\t{\"not hex\", \"zz\", ErrBadHex},\n\t\t{\"wrong size\", \"abcd\", ErrBadHashSize},\n\t\t{\"too deep\", tooDeepHex(), ErrProofTooDeep},\n\t}\n\tfor _, tc := range tests {\n\t\tif _, err := ParseProof(0, 2, tc.in); err != tc.want {\n\t\t\tt.Errorf(\"%s: err = %v, want %v\", tc.name, err, tc.want)\n\t\t}\n\t}\n\t// An empty sibling list is the one-leaf proof, not an error.\n\tp, err := ParseProof(0, 1, \"  \")\n\tif err != nil {\n\t\tt.Fatalf(\"empty siblings: %v\", err)\n\t}\n\tone := New(leaves(1))\n\tif !p.Verify(one.Root(), []byte(\"leaf-0\")) {\n\t\tt.Error(\"one-leaf proof with no siblings rejected\")\n\t}\n}\n\nfunc tooDeepHex() string {\n\th := hex.EncodeToString(make([]byte, HashSize))\n\tout := h\n\tfor i := 0; i \u003c MaxDepth; i++ {\n\t\tout += \",\" + h\n\t}\n\treturn out\n}\n\nfunc TestTreeErrors(t *testing.T) {\n\tif _, err := New(nil).Proof(0); err != ErrEmptyTree {\n\t\tt.Errorf(\"empty tree: err = %v, want %v\", err, ErrEmptyTree)\n\t}\n\tif New(nil).Root() != nil {\n\t\tt.Error(\"empty tree root should be nil, like Tendermint\")\n\t}\n\ttree := New(leaves(3))\n\tfor _, i := range []int{-1, 3, 99} {\n\t\tif _, err := tree.Proof(i); err != ErrIndexRange {\n\t\t\tt.Errorf(\"index %d: err = %v, want %v\", i, err, ErrIndexRange)\n\t\t}\n\t}\n}\n\n// New must copy its input: a caller mutating the slice afterwards cannot be\n// allowed to change what the tree committed to.\nfunc TestNewCopiesLeaves(t *testing.T) {\n\tls := [][]byte{[]byte(\"a\"), []byte(\"b\")}\n\ttree := New(ls)\n\tbefore := tree.RootHex()\n\tls[0][0] = 'z'\n\tif tree.RootHex() != before {\n\t\tt.Error(\"mutating the caller's slice changed the committed root\")\n\t}\n}\n\n// The reason this package exists. In a scheme without domain separation an\n// INNER NODE hash is also a valid LEAF hash, so anyone who can choose a\n// 64-byte leaf preimage can prove membership of a leaf that was never in the\n// tree. This test performs that forgery against VerifySorted, then shows the\n// Tendermint scheme refuses the same move.\nfunc TestSecondPreimageForgery(t *testing.T) {\n\t// A 4-leaf commutative tree, built the OpenZeppelin way.\n\th := make([][]byte, 4)\n\tfor i := range h {\n\t\ts := sha256.Sum256([]byte(\"leaf-\" + strconv.Itoa(i)))\n\t\th[i] = s[:]\n\t}\n\tn01 := hashSortedPair(h[0], h[1])\n\tn23 := hashSortedPair(h[2], h[3])\n\troot := hashSortedPair(n01, n23)\n\n\t// Sanity: a real leaf really does verify.\n\tif !VerifySorted(root, h[0], [][]byte{h[1], n23}) {\n\t\tt.Fatal(\"honest sorted proof rejected\")\n\t}\n\n\t// The forgery: present the inner node n01 as if it were a leaf hash. Its\n\t// preimage is the 64 bytes sorted(h0, h1), so an application whose leaves\n\t// can be 64 bytes long hands the attacker a membership proof for data that\n\t// was never committed.\n\tif !VerifySorted(root, n01, [][]byte{n23}) {\n\t\tt.Fatal(\"expected the second-preimage forgery to succeed against VerifySorted\")\n\t}\n\n\t// Same shape, Tendermint scheme. Leaves are tagged 0x00 and inner nodes\n\t// 0x01, so no leaf preimage can ever hash to an inner node, and the proof\n\t// is bound to an index besides.\n\ttree := New(leaves(4))\n\tinner := InnerHash(LeafHash(tree.leaves[0]), LeafHash(tree.leaves[1]))\n\tforged := Proof{Index: 0, Total: 2, Siblings: [][]byte{InnerHash(LeafHash(tree.leaves[2]), LeafHash(tree.leaves[3]))}}\n\tif forged.Verify(tree.Root(), inner) {\n\t\tt.Error(\"domain separation failed: an inner node was accepted as a leaf\")\n\t}\n}\n\nfunc TestLeafAndInnerHashAreTagged(t *testing.T) {\n\tleafOfEmpty := LeafHash(nil)\n\ttaggedLeaf := sha256.Sum256([]byte{0x00})\n\tif hex.EncodeToString(leafOfEmpty) != hex.EncodeToString(taggedLeaf[:]) {\n\t\tt.Error(\"LeafHash is not SHA256(0x00 || leaf)\")\n\t}\n\tl := make([]byte, 32)\n\tr := make([]byte, 32)\n\tr[0] = 1\n\tgot := InnerHash(l, r)\n\twant := sha256.Sum256(append(append([]byte{0x01}, l...), r...))\n\tif hex.EncodeToString(got) != hex.EncodeToString(want[:]) {\n\t\tt.Error(\"InnerHash is not SHA256(0x01 || left || right)\")\n\t}\n}\n\nfunc TestSplitPointMatchesTendermint(t *testing.T) {\n\t// largest power of two strictly below length\n\ttests := []struct{ in, want int }{\n\t\t{2, 1}, {3, 2}, {4, 2}, {5, 4}, {7, 4}, {8, 4}, {9, 8}, {16, 8}, {17, 16},\n\t}\n\tfor _, tc := range tests {\n\t\tif got := splitPoint(tc.in); got != tc.want {\n\t\t\tt.Errorf(\"splitPoint(%d) = %d, want %d\", tc.in, got, tc.want)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"11000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pair","path":"gno.land/p/moul/x/pair/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/pair/v0`\n\nOne constant-product AMM pair (`x*y=k`, 30 bps to the liquidity providers), as a\npure package, so that the realm holding a pair can be twenty lines of glue.\n\nThis is the shared half of the **instance-per-realm** pattern: gno's answer to\nthe Ethereum factory shape, where an ecosystem is a frontend over thousands of\ntiny identical contracts, one per token couple.\n\n| artifact | what it is |\n|---|---|\n| `p/moul/x/pair/v0` | this package, the whole behaviour, deployed once |\n| an instance realm | ~20 lines: two constants, an `init` that registers, one-line re-exports. See `r/moul/x/pairs/aaabbb/v0` |\n| `r/moul/x/pairreg/v0` | the registry every instance announces itself to, and the unified frontend over all of them |\n| `tools/pairgen` | the factory, which runs on your machine because gno has no on-chain deploy |\n\n## What gno changes about the Ethereum pattern\n\n- **No on-chain factory.** `vm/add_package` is permanently denied to realm code,\n  so an instance is an `addpkg` transaction signed by a human, priced in gas and\n  a storage deposit. `tools/pairgen` fills the template and prints the\n  command.\n- **Spawning is still permissionless.** Any address may deploy under\n  `gno.land/r/\u003cits own g1 address\u003e/**` with no registered username, so anyone can\n  run their own instance and land in the registry.\n- **No clone trick needed.** Ethereum copies bytecode or delegatecalls through an\n  EIP-1167 proxy; an import stores this package once for every instance.\n- **The registry sees live state.** Instances register a `*pair.Pair` pointer, so\n  one `vm/qrender` renders every instance's real reserves, with no indexer.\n- **Nothing attests the code.** No realm can read another package's source, so an\n  instance's code can only be verified off chain, by diffing it against freshly\n  generated output. Unforgeable identity, no code attestation: the mirror image\n  of CREATE2.\n\n## Using it from an instance\n\n```go\nvar p *pair.Pair\n\nfunc init(cur realm) {\n\tp = pair.New(keyA, keyB, grc20reg.MustGet(keyA), grc20reg.MustGet(keyB))\n\tpairreg.Register(cross(cur), p)\n}\n\nfunc Swap(cur realm, keyIn string, amountIn, minOut int64) int64 {\n\treturn p.Swap(0, cur, keyIn, amountIn, minOut)\n}\n```\n\nEvery state-changing method is shaped `(_ int, rlm realm, ...)`. That is forced,\nnot stylistic: a pure package cannot declare a crossing function (`func F(cur\nrealm, ...)` fails to compile there), and the parameter cannot be named `cur`\neither. The realm value arrives non-crossing, which is exactly what is wanted:\nthe frame stays the instance realm, so funds move to and from the **instance's**\naddress and grc20's `rlm.IsCurrent()` spoof check still passes. `p/moul/x/framelab/v0`\nis the 30-line probe that pins this property.\n\nA pure package also cannot import a realm, so this one never resolves a token by\npath: the instance passes `*grc20.Token` handles in.\n\n## Economics, and what is deliberately absent\n\nReserves are stored fields, never derived from `BalanceOf`, which removes\n`MINIMUM_LIQUIDITY`, `skim`/`sync` and the first-depositor inflation attack in\none decision. The price: tokens sent directly to an instance's address are\npermanently stuck. The first deposit mints `shares = amountA` with no `sqrt`;\nlater deposits mint `min(A-side, B-side)` with floor division, so an off-ratio\ndeposit rounds against the depositor. No oracle, no flash swap, no routing, no\nprotocol fee, no governance.\n\nAll amounts are `int64` and the fee denominator is 1000, so every reserve is\ncapped at `MaxReserve = MaxInt64/1000`. **Unusable with 18-decimal tokens**; six\nto nine decimals is the practical band.\n\nFull design study of the economics: [gno-contracts#135](https://github.com/moul/gno-contracts/issues/135).\n\n## When to copy this pattern, and when not to\n\nUniswap V4 moved from a pair-per-contract factory to a singleton, and\n[PR #137](https://github.com/moul/gno-contracts/pull/137) is the same AMM as one\nrealm holding N pools. An AMM is therefore the contested case, kept here as a\ndeliberate A/B.\n\nReach for instance-per-realm when instances have **different owners, trust and\nlifecycles** (a user's shop, a DAO, a game table). Keep one realm with N objects\nwhen instances are fungible parts of one shared network (liquidity, an order\nbook, a global index).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/pair/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/pair/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/pair/v0\"\ngno = \"0.9\"\n"},{"name":"pair.gno","body":"// Package pair is the whole behaviour of one constant-product AMM pair, as a\n// pure package, so that a realm holding a single pair can be twenty lines of\n// glue.\n//\n// It is the shared half of the instance-per-realm pattern: deploy this once,\n// then deploy one tiny realm per token couple, each owning its own state, its\n// own funds and its own storage deposit, all running this identical code. The\n// Ethereum shape it copies (a factory spawning one UniswapV2Pair per couple)\n// needs EIP-1167 clones to make the duplication affordable; an import makes it\n// free.\n//\n// # How an instance uses it\n//\n//\tvar p *pair.Pair\n//\n//\tfunc init(cur realm) {\n//\t\tp = pair.New(keyA, keyB, grc20reg.MustGet(keyA), grc20reg.MustGet(keyB))\n//\t\tpairreg.Register(cross(cur), p)\n//\t}\n//\n//\tfunc Swap(cur realm, keyIn string, amountIn, minOut int64) int64 {\n//\t\treturn p.Swap(0, cur, keyIn, amountIn, minOut)\n//\t}\n//\n// # Why the methods look like that\n//\n// Every state-changing method is shaped (_ int, rlm realm, ...). The leading\n// dummy is mandatory: gno rejects a function whose FIRST parameter is realm\n// when it is declared in a pure package (\"crossing function declared in\n// non-realm package\"), and the parameter cannot be named cur either. Same\n// reason grc20's tellers are Transfer(_ int, rlm realm, ...). The realm value\n// arrives non-crossing, which is exactly what is wanted: the frame stays the\n// instance realm, so funds move to and from the INSTANCE's address, and\n// rlm.IsCurrent() still holds for grc20's spoof check.\n//\n// A pure package also cannot import a realm at all, so this package never\n// resolves a token by path. The instance passes *grc20.Token handles in.\n//\n// # The economics, unchanged from the single-realm design\n//\n// Constant product x*y=k with a 30 bps fee kept by the pool, reserves stored\n// and never derived from BalanceOf (so a direct transfer to the realm is\n// inert, and permanently stuck), first deposit minting shares equal to the\n// token-A amount with no sqrt and no MINIMUM_LIQUIDITY burn, and every reserve\n// capped so the int64 arithmetic cannot overflow. The reasoning behind each of\n// those is in https://github.com/moul/gno-contracts/issues/135 and is not\n// repeated here; this package is that design with one pool per realm instead\n// of many pools in one realm.\n//\n// Consequence worth repeating, because it bites: with a 1000x fee denominator\n// on int64 amounts, this is unusable with 18-decimal tokens. Six to nine\n// decimals is the practical band.\npackage pair\n\nimport (\n\t\"chain\"\n\t\"math\"\n\t\"math/bits\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\t// feeNum/feeDen is the swap fee kept by the pool: 997/1000, i.e. 30 bps.\n\tfeeNum = 997\n\tfeeDen = 1000\n\n\t// maxReserve is the largest reserve a pair will hold, in base units.\n\t//\n\t// Pricing computes den = reserveIn*feeDen + amountIn*feeNum in plain\n\t// int64 before handing off to the 128-bit mulDiv. Capping every reserve,\n\t// and every post-swap reserve, at MaxInt64/feeDen makes that sum provably\n\t// safe:\n\t//\n\t//\tden \u003c (reserveIn + amountIn) * feeDen \u003c= maxReserve * feeDen\n\t//\t    = 9223372036854775000 \u003c= MaxInt64 = 9223372036854775807\n\tMaxReserve = math.MaxInt64 / feeDen // 9223372036854775\n)\n\n// Pair is one token couple and its liquidity. Fields are concrete by design:\n// the registry realm holds a live pointer to this struct and reads it while\n// rendering, so an interface or a func field here would let a hostile\n// instance hand foreign code to the registry's frame.\n//\n// keyA \u003c keyB always holds; New canonicalises.\ntype Pair struct {\n\tkeyA, keyB  string\n\ttokA, tokB  *grc20.Token\n\tresA, resB  int64\n\ttotalShares int64\n\tshares      *avl.Tree // address string -\u003e int64\n}\n\n// New builds an empty pair from two grc20reg keys and the matching token\n// handles, in canonical order. The caller (the instance realm) is responsible\n// for resolving the handles, because a pure package cannot import the\n// registry realm that holds them.\nfunc New(keyA, keyB string, tokA, tokB *grc20.Token) *Pair {\n\tif keyA == \"\" || keyB == \"\" {\n\t\tpanic(\"pair: empty token key\")\n\t}\n\tif keyA == keyB {\n\t\tpanic(\"pair: a pair needs two different tokens\")\n\t}\n\tif tokA == nil || tokB == nil {\n\t\tpanic(\"pair: nil token\")\n\t}\n\tif keyA \u003e keyB {\n\t\tkeyA, keyB = keyB, keyA\n\t\ttokA, tokB = tokB, tokA\n\t}\n\treturn \u0026Pair{keyA: keyA, keyB: keyB, tokA: tokA, tokB: tokB, shares: avl.NewTree()}\n}\n\n//\n// Writes. Each one takes the instance realm's own cur, forwarded.\n//\n\n// AddLiquidity deposits up to maxA of token A and maxB of token B and mints LP\n// shares to the caller. On an existing pair the deposit is trimmed to the\n// current reserve ratio, so pass the amounts you are willing to spend, not the\n// amounts you insist on spending.\n//\n// The caller must first Approve the INSTANCE realm's address on both tokens.\n// Returns the shares minted.\nfunc (p *Pair) AddLiquidity(_ int, rlm realm, maxA, maxB int64) int64 {\n\tif maxA \u003c= 0 || maxB \u003c= 0 {\n\t\tpanic(\"pair: both deposit amounts must be \u003e 0\")\n\t}\n\tamtA, amtB := maxA, maxB\n\n\tvar minted int64\n\tif p.totalShares == 0 {\n\t\t// First position: the depositor sets the price and the share unit is\n\t\t// token A at seed time. No sqrt, no MINIMUM_LIQUIDITY burn.\n\t\tminted = amtA\n\t} else {\n\t\t// Trim to the current ratio, then mint from whichever side is scarcer.\n\t\t// Both divisions floor, and taking the minimum means an off-ratio\n\t\t// deposit is rounded against the depositor, never against the pool.\n\t\tif want := mulDiv(amtA, p.resB, p.resA); want \u003c= amtB {\n\t\t\tamtB = want\n\t\t} else {\n\t\t\tamtA = mulDiv(amtB, p.resA, p.resB)\n\t\t}\n\t\tif amtA \u003c= 0 || amtB \u003c= 0 {\n\t\t\tpanic(\"pair: deposit too small for the current ratio\")\n\t\t}\n\t\tminted = min64(\n\t\t\tmulDiv(amtA, p.totalShares, p.resA),\n\t\t\tmulDiv(amtB, p.totalShares, p.resB),\n\t\t)\n\t}\n\tif minted \u003c= 0 {\n\t\tpanic(\"pair: deposit mints zero shares\")\n\t}\n\tif p.resA+amtA \u003e MaxReserve || p.resB+amtB \u003e MaxReserve {\n\t\tpanic(\"pair: reserve cap exceeded\")\n\t}\n\n\tprovider := rlm.Previous().Address()\n\tself := rlm.Address()\n\tpull(0, rlm, p.tokA, provider, self, amtA)\n\tpull(0, rlm, p.tokB, provider, self, amtB)\n\n\tp.resA += amtA\n\tp.resB += amtB\n\tp.totalShares += minted\n\tp.setShares(provider, p.SharesOf(provider)+minted)\n\n\tchain.Emit(\"AddLiquidity\",\n\t\t\"pair\", p.ID(),\n\t\t\"provider\", provider.String(),\n\t\t\"amountA\", itoa(amtA),\n\t\t\"amountB\", itoa(amtB),\n\t\t\"shares\", itoa(minted),\n\t)\n\treturn minted\n}\n\n// RemoveLiquidity burns shares held by the caller and returns the\n// proportional amounts of both tokens, in (A, B) order.\n//\n// Burning the entire share supply pays out the whole reserve, so the last\n// provider out leaves nothing unclaimable behind and the pair can be reseeded\n// at a fresh price.\nfunc (p *Pair) RemoveLiquidity(_ int, rlm realm, shares int64) (int64, int64) {\n\tif shares \u003c= 0 {\n\t\tpanic(\"pair: shares must be \u003e 0\")\n\t}\n\towner := rlm.Previous().Address()\n\theld := p.SharesOf(owner)\n\tif held \u003c shares {\n\t\tpanic(\"pair: insufficient shares\")\n\t}\n\n\tvar amtA, amtB int64\n\tif shares == p.totalShares {\n\t\tamtA, amtB = p.resA, p.resB\n\t} else {\n\t\tamtA = mulDiv(shares, p.resA, p.totalShares)\n\t\tamtB = mulDiv(shares, p.resB, p.totalShares)\n\t}\n\tif amtA \u003c= 0 || amtB \u003c= 0 {\n\t\tpanic(\"pair: burn would return nothing on one side\")\n\t}\n\n\tp.resA -= amtA\n\tp.resB -= amtB\n\tp.totalShares -= shares\n\tp.setShares(owner, held-shares)\n\n\tpush(0, rlm, p.tokA, owner, amtA)\n\tpush(0, rlm, p.tokB, owner, amtB)\n\n\tchain.Emit(\"RemoveLiquidity\",\n\t\t\"pair\", p.ID(),\n\t\t\"provider\", owner.String(),\n\t\t\"amountA\", itoa(amtA),\n\t\t\"amountB\", itoa(amtB),\n\t\t\"shares\", itoa(shares),\n\t)\n\treturn amtA, amtB\n}\n\n// Swap sells amountIn of keyIn for the other token and aborts unless at least\n// minOut comes back. The caller must first Approve the instance realm's\n// address on keyIn.\n//\n// minOut is the only protection against being sandwiched or against the pair\n// moving between quoting and execution. Pass a real bound; passing 0 means\n// accepting any price at all.\nfunc (p *Pair) Swap(_ int, rlm realm, keyIn string, amountIn, minOut int64) int64 {\n\tif amountIn \u003c= 0 {\n\t\tpanic(\"pair: amountIn must be \u003e 0\")\n\t}\n\tif minOut \u003c 0 {\n\t\tpanic(\"pair: minOut must be \u003e= 0\")\n\t}\n\tflipped := p.mustSide(keyIn)\n\n\tresIn, resOut := p.resA, p.resB\n\ttokIn, tokOut := p.tokA, p.tokB\n\tif flipped {\n\t\tresIn, resOut = p.resB, p.resA\n\t\ttokIn, tokOut = p.tokB, p.tokA\n\t}\n\n\tout := AmountOut(amountIn, resIn, resOut)\n\tif out \u003c= 0 {\n\t\tpanic(\"pair: output rounds to zero\")\n\t}\n\tif out \u003c minOut {\n\t\tpanic(\"pair: slippage, output below minOut\")\n\t}\n\n\ttrader := rlm.Previous().Address()\n\tpull(0, rlm, tokIn, trader, rlm.Address(), amountIn)\n\n\tnewIn, newOut := resIn+amountIn, resOut-out\n\t// The invariant holds by construction (out is floored), so this can only\n\t// fire if the pricing above is ever edited into being wrong. It is exact:\n\t// both products are compared in 128 bits.\n\tif cmpProd(newIn, newOut, resIn, resOut) \u003c 0 {\n\t\tpanic(\"pair: constant product regression\")\n\t}\n\tif flipped {\n\t\tp.resB, p.resA = newIn, newOut\n\t} else {\n\t\tp.resA, p.resB = newIn, newOut\n\t}\n\n\tpush(0, rlm, tokOut, trader, out)\n\n\tchain.Emit(\"Swap\",\n\t\t\"pair\", p.ID(),\n\t\t\"trader\", trader.String(),\n\t\t\"tokenIn\", tokIn.GetSymbol(),\n\t\t\"amountIn\", itoa(amountIn),\n\t\t\"amountOut\", itoa(out),\n\t)\n\treturn out\n}\n\n//\n// Reads. Safe for the registry realm to call on another realm's Pair.\n//\n\n// AmountOut is the pricing function, fee included, as a pure function of the\n// two reserves. Exported so a caller can quote off chain against reserves it\n// already holds, and so the arithmetic is testable on its own.\nfunc AmountOut(amountIn, reserveIn, reserveOut int64) int64 {\n\tif amountIn \u003c= 0 {\n\t\tpanic(\"pair: amountIn must be \u003e 0\")\n\t}\n\tif reserveIn \u003c= 0 || reserveOut \u003c= 0 {\n\t\tpanic(\"pair: pair has an empty reserve\")\n\t}\n\tif reserveIn \u003e MaxReserve || reserveOut \u003e MaxReserve {\n\t\tpanic(\"pair: reserve above cap\")\n\t}\n\tif amountIn \u003e MaxReserve-reserveIn {\n\t\tpanic(\"pair: reserve cap exceeded\")\n\t}\n\tinFee := amountIn * feeNum\n\tden := reserveIn*feeDen + inFee\n\treturn mulDiv(inFee, reserveOut, den)\n}\n\n// Quote prices amountIn of keyIn against the live reserves. It is the number\n// Swap would return right now, which is not a promise about the next block.\nfunc (p *Pair) Quote(keyIn string, amountIn int64) int64 {\n\tif p.totalShares == 0 {\n\t\treturn 0\n\t}\n\tif p.mustSide(keyIn) {\n\t\treturn AmountOut(amountIn, p.resB, p.resA)\n\t}\n\treturn AmountOut(amountIn, p.resA, p.resB)\n}\n\n// Keys returns the two grc20reg keys in canonical order.\nfunc (p *Pair) Keys() (string, string) { return p.keyA, p.keyB }\n\n// Symbols returns the two token symbols in canonical order.\nfunc (p *Pair) Symbols() (string, string) { return p.tokA.GetSymbol(), p.tokB.GetSymbol() }\n\n// ID is the canonical identifier of the couple, \"keyA~keyB\". The separator is\n// \"~\" and not \"|\": a \"|\" inside a markdown table cell breaks the row.\nfunc (p *Pair) ID() string { return p.keyA + \"~\" + p.keyB }\n\n// Reserves returns the two reserves in canonical order.\nfunc (p *Pair) Reserves() (int64, int64) { return p.resA, p.resB }\n\n// TotalShares returns the LP share supply.\nfunc (p *Pair) TotalShares() int64 { return p.totalShares }\n\n// Providers returns how many addresses hold shares.\nfunc (p *Pair) Providers() int { return p.shares.Size() }\n\n// SharesOf returns owner's LP shares.\nfunc (p *Pair) SharesOf(owner address) int64 {\n\tv := p.shares.Get(owner.String())\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(int64)\n}\n\n// Render is the instance realm's whole page: what the couple is, what it\n// holds, and how to trade it.\nfunc (p *Pair) Render(path string) string {\n\tsymA, symB := p.Symbols()\n\tout := \"# \" + symA + \" / \" + symB + \"\\n\\n\"\n\tout += \"One constant-product pair, `x*y=k`, 30 bps to the liquidity providers. \"\n\tout += \"Logic lives in [p/moul/x/pair/v0](/p/moul/x/pair/v0); this realm is the instance.\\n\\n\"\n\n\tif p.totalShares == 0 {\n\t\tout += \"_Empty. The first `AddLiquidity` sets the price._\\n\\n\"\n\t} else {\n\t\tout += ufmt.Sprintf(\"| side | reserve | key |\\n|---|---|---|\\n| %s | %d | `%s` |\\n| %s | %d | `%s` |\\n\\n\",\n\t\t\tsymA, p.resA, p.keyA, symB, p.resB, p.keyB)\n\t\tout += ufmt.Sprintf(\"- LP shares: **%d** across %d provider(s)\\n\",\n\t\t\tp.totalShares, p.shares.Size())\n\t\tout += ufmt.Sprintf(\"- Spot: 1 %s buys ~%d %s (before fee and slippage)\\n\\n\",\n\t\t\tsymA, p.spot(), symB)\n\t}\n\tout += \"Approve this realm's address on the token you are selling, then call `Swap`.\\n\"\n\treturn out\n}\n\n//\n// Internals.\n//\n\n// spot is the display-only mid price, floor(resB/resA). Never price anything\n// off it: it is a spot reserve ratio that any trader can move in one tx.\nfunc (p *Pair) spot() int64 {\n\tif p.resA == 0 {\n\t\treturn 0\n\t}\n\treturn p.resB / p.resA\n}\n\n// mustSide reports whether key is the B side, and panics if it is neither.\nfunc (p *Pair) mustSide(key string) bool {\n\tswitch key {\n\tcase p.keyA:\n\t\treturn false\n\tcase p.keyB:\n\t\treturn true\n\t}\n\tpanic(\"pair: \" + key + \" is not in this pair\")\n}\n\nfunc (p *Pair) setShares(owner address, n int64) {\n\tif n == 0 {\n\t\tp.shares.Remove(owner.String())\n\t\treturn\n\t}\n\tp.shares.Set(owner.String(), n)\n}\n\n// pull moves amount of tok from `from` into the instance realm, spending the\n// allowance `from` granted to the instance realm's address.\n//\n// Non-crossing on purpose: `_ int, rlm realm` is the only shape a pure\n// package can declare, and it keeps rlm the instance's own live frame.\n// RealmTeller binds the spender eagerly to rlm.Address(), which is therefore\n// the instance, not this package (a pure package has no address at all).\nfunc pull(_ int, rlm realm, tok *grc20.Token, from, to address, amount int64) {\n\terr := tok.RealmTeller(0, rlm).TransferFrom(0, rlm, from, to, amount)\n\tif err != nil {\n\t\tpanic(\"pair: cannot take \" + tok.GetSymbol() + \": \" + err.Error())\n\t}\n}\n\n// push sends amount of tok from the instance realm to `to`.\nfunc push(_ int, rlm realm, tok *grc20.Token, to address, amount int64) {\n\terr := tok.RealmTeller(0, rlm).Transfer(0, rlm, to, amount)\n\tif err != nil {\n\t\tpanic(\"pair: cannot send \" + tok.GetSymbol() + \": \" + err.Error())\n\t}\n}\n\n// mulDiv returns floor(a*b/c) through a 128-bit intermediate, which plain\n// int64 arithmetic cannot do: a*b is routinely wider than 63 bits here even\n// when the quotient is small.\nfunc mulDiv(a, b, c int64) int64 {\n\tif a \u003c 0 || b \u003c 0 {\n\t\tpanic(\"pair: negative operand\")\n\t}\n\tif c \u003c= 0 {\n\t\tpanic(\"pair: division by a non-positive value\")\n\t}\n\thi, lo := bits.Mul64(uint64(a), uint64(b))\n\t// bits.Div64 panics for y \u003c= hi; refusing here turns that into a named\n\t// abort and also covers every quotient that would not fit in 64 bits.\n\tif hi \u003e= uint64(c) {\n\t\tpanic(\"pair: quotient overflows int64\")\n\t}\n\tq, _ := bits.Div64(hi, lo, uint64(c))\n\tif q \u003e uint64(math.MaxInt64) {\n\t\tpanic(\"pair: quotient overflows int64\")\n\t}\n\treturn int64(q)\n}\n\n// cmpProd compares a*b with c*d exactly, in 128 bits, and returns -1, 0 or 1.\nfunc cmpProd(a, b, c, d int64) int {\n\th1, l1 := bits.Mul64(uint64(a), uint64(b))\n\th2, l2 := bits.Mul64(uint64(c), uint64(d))\n\tif h1 != h2 {\n\t\tif h1 \u003c h2 {\n\t\t\treturn -1\n\t\t}\n\t\treturn 1\n\t}\n\tif l1 != l2 {\n\t\tif l1 \u003c l2 {\n\t\t\treturn -1\n\t\t}\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc min64(a, b int64) int64 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc itoa(v int64) string { return strconv.FormatInt(v, 10) }\n"},{"name":"pair_test.gno","body":"package pair\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The pricing function, on its own, is the part worth pinning numerically: it\n// is pure, it is where the 128-bit arithmetic lives, and every instance in the\n// ecosystem runs this exact code.\nfunc TestAmountOut(t *testing.T) {\n\tcases := []struct {\n\t\tname                    string\n\t\tin, resIn, resOut, want int64\n\t}{\n\t\t{\"balanced pool, small trade\", 1_000, 1_000_000, 1_000_000, 996},\n\t\t{\"balanced pool, 1%\", 10_000, 1_000_000, 1_000_000, 9_871},\n\t\t{\"balanced pool, 10%\", 100_000, 1_000_000, 1_000_000, 90_661},\n\t\t{\"balanced pool, 50%\", 500_000, 1_000_000, 1_000_000, 332_665},\n\t\t{\"skewed pool\", 100_000, 1_000_000, 4_000_000, 362_644},\n\t\t{\"near drain\", 1_000, 1, 1_000_000, 998_997},\n\t\t{\"dust rounds to zero\", 1, 1_000_000, 1_000_000, 0},\n\t\t{\"reserves at the cap\", MaxReserve / 2, MaxReserve / 2, MaxReserve, 4_604_758_097_518_382},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := AmountOut(tc.in, tc.resIn, tc.resOut)\n\t\tuassert.Equal(t, tc.want, got, tc.name)\n\t}\n}\n\n// The fee is what stays behind: k must never decrease across a swap.\nfunc TestConstantProductNeverRegresses(t *testing.T) {\n\tresIn, resOut := int64(1_000_000), int64(4_000_000)\n\tfor _, in := range []int64{1, 1_000, 100_000, 999_999} {\n\t\tout := AmountOut(in, resIn, resOut)\n\t\tuassert.True(t, cmpProd(resIn+in, resOut-out, resIn, resOut) \u003e= 0,\n\t\t\t\"k must not regress\")\n\t}\n}\n\nfunc TestAmountOutGuards(t *testing.T) {\n\tmustPanic(t, \"pair: amountIn must be \u003e 0\", func() {\n\t\tAmountOut(0, 1_000, 1_000)\n\t})\n\tmustPanic(t, \"pair: pair has an empty reserve\", func() {\n\t\tAmountOut(1, 0, 1_000)\n\t})\n\tmustPanic(t, \"pair: reserve above cap\", func() {\n\t\tAmountOut(1, MaxReserve+1, 1_000)\n\t})\n\tmustPanic(t, \"pair: reserve cap exceeded\", func() {\n\t\tAmountOut(2, MaxReserve-1, 1_000)\n\t})\n}\n\n// mulDiv is the only place a 128-bit intermediate is required, and the only\n// place bits.Div64 could panic. Both ends are asserted rather than argued.\nfunc TestMulDiv(t *testing.T) {\n\tuassert.Equal(t, int64(2), mulDiv(4, 3, 6))\n\tuassert.Equal(t, int64(0), mulDiv(1, 1, 3), \"floors\")\n\tuassert.Equal(t, int64(4_611_686_018_427_387_903), mulDiv(9_223_372_036_854_775_807, 1, 2),\n\t\t\"operands near MaxInt64 stay exact through the 128-bit path\")\n\n\tmustPanic(t, \"pair: division by a non-positive value\", func() {\n\t\tmulDiv(1, 1, 0)\n\t})\n\tmustPanic(t, \"pair: quotient overflows int64\", func() {\n\t\tmulDiv(9_223_372_036_854_775_807, 9_223_372_036_854_775_807, 1)\n\t})\n}\n\nfunc TestCmpProd(t *testing.T) {\n\tuassert.Equal(t, 0, cmpProd(6, 7, 42, 1))\n\tuassert.Equal(t, -1, cmpProd(6, 6, 42, 1))\n\tuassert.Equal(t, 1, cmpProd(7, 7, 42, 1))\n\t// Both products exceed int64 and differ only in the low word.\n\tuassert.Equal(t, -1, cmpProd(4_000_000_000, 4_000_000_000, 4_000_000_000, 4_000_000_001))\n}\n\n// mustPanic is uassert.PanicsWithMessage without the realm argument: a pure\n// package cannot produce a `cur` to hand it, since it can never declare a\n// crossing function in the first place.\nfunc mustPanic(t *testing.T, want string, f func()) {\n\tt.Helper()\n\tdefer func() {\n\t\tr := recover()\n\t\tif r == nil {\n\t\t\tt.Errorf(\"expected panic %q, got none\", want)\n\t\t\treturn\n\t\t}\n\t\tgot, ok := r.(string)\n\t\tif !ok {\n\t\t\tt.Errorf(\"expected a string panic %q, got %v\", want, r)\n\t\t\treturn\n\t\t}\n\t\tif got != want {\n\t\t\tt.Errorf(\"expected panic %q, got %q\", want, got)\n\t\t}\n\t}()\n\tf()\n}\n"}]},"send":"","max_deposit":"10000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ninep","path":"gno.land/p/moul/x/plan9/ninep/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/plan9/ninep/v0`\n\n**A Plan 9 shaped file abstraction for gno**: `File`, `Mutable`, `Qid`, `Stat`,\n`Perm`, the 9P error set, and lexical path handling.\n\n```go\nimport ninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n\ntype File interface {\n\tStat() Stat\n\tWalk(name string) (File, error)      // exactly one element\n\tRead(off, count int64) (string, error)\n\tReadDir() ([]Stat, error)\n}\n```\n\nThis implements the *semantics* of\n[9P2000](https://ericvh.github.io/9p-rfc/rfc9p2000.html), not its wire format.\nThere is no socket on a chain: the VM call is the transport. What survives the\ntranslation is the part that made 9P useful, namely that every resource answers\nthe same four questions, so a client written today can browse a file server\ndeployed tomorrow.\n\n**One interface, not two.** 9P reads a directory with the same `Tread` it uses\nfor a file, so splitting `File` from `Dir` would be less faithful, and a single\ninterface means no type assertion across a realm boundary.\n\n**`File` is read-only, on purpose.** A crossing write method would mint the\n*caller's* realm frame for the callee, which is the confused-deputy shape that\n`r/gov/dao`'s `Executor` relies on deliberately and `p/nt/grc20`'s `Teller`\nrefuses deliberately. So mutation lives in a separate `Mutable`, which is only\nsafe on a tree your own realm owns. That is what makes it safe to hand a `File`\nto a stranger's namespace.\n\nDeliberate divergences, each one forced:\n\n- **Data is a `string`, not `[]byte`.** Every consumer on this chain is text and\n  `Render` returns a string.\n- **`Mtime` is a block height.** It is the only clock every validating node\n  agrees on.\n- **There is no `open`/`clunk`.** Without a session there are no fids, so `Walk`\n  returns the file itself and nothing has to be released.\n- **`..` never reaches a server.** `Clean` resolves it lexically first, per\n  [Lexical File Names in Plan 9](https://9p.io/sys/doc/lexnames.html), so `..`\n  undoes the name you typed rather than the directory you landed in.\n- **`MaxDepth` caps a walk at 32 elements.** Resolution can cost one cross-realm\n  call per element, so depth is bounded rather than trusted.\n\nUsed by [`memfs`](../../memfs/v0) (a RAM server), [`synfs`](../../synfs/v0) (a\ncomputed server), [`ns`](../../ns/v0) (namespaces) and\n[`rc`](../../rc/v0) (the shell). Design and analysis:\n[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\n\n---\n\n**Not affiliated with Plan 9.** Plan 9 from Bell Labs is the work of the\nComputing Science Research Center at Bell Labs; the name and the marks are\ntheirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org).\nThis package borrows the vocabulary and none of the code: it is an independent\nhomage, asking what that ecosystem's spirit looks like on a chain. Full\nattribution: [NOTICE](../../../../../NOTICE.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/plan9/ninep/v0\"\ngno = \"0.9\"\n"},{"name":"ninep.gno","body":"// Package ninep is a Plan 9 shaped file abstraction for gno.\n//\n// It implements the SEMANTICS of 9P2000, not its wire format: there is no\n// socket on a chain, the VM call is the transport. What it keeps is the part\n// that made 9P useful, namely that every resource answers the same four\n// questions (stat, walk, read, readdir), so a client written today can browse\n// a file server deployed tomorrow.\n//\n// One interface, not two. 9P reads a directory with the same Tread it uses for\n// a file, so splitting File from Dir would be less faithful, and a single\n// interface means no type assertion across a realm boundary.\n//\n// Deliberate divergences from 9P2000, all of them forced:\n//\n//   - Data is a string, not []byte. Every consumer on this chain is text and\n//     Render returns a string.\n//   - Mtime is a block height, not a wall clock. It is the only clock that\n//     every validating node agrees on.\n//   - There is no open/clunk pair. Without a session there are no fids, so\n//     Walk returns the file itself and nothing has to be released.\n//   - File is READ-ONLY. A crossing method would mint the caller's realm frame\n//     for the callee, which is a confused-deputy hazard (compare r/gov/dao's\n//     Executor, and p/nt/grc20's deliberate refusal to make Teller crossing).\n//     Mutation lives in Mutable, which is only safe on a tree your own realm\n//     owns.\n//\n// See gno.land/p/moul/x/plan9/ns for the namespace that binds these trees\n// together, and gno.land/p/moul/x/plan9/memfs for the reference server.\n//\n// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research\n// Center at Bell Labs; the name and the marks are theirs, and the copyright is\n// held by the Plan 9 Foundation (https://p9f.org). This package is not\n// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9\n// code: it borrows the vocabulary so that the design reads without a glossary,\n// and it is an homage, asking what that ecosystem's spirit looks like on a\n// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.\npackage ninep\n\nimport (\n\t\"errors\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Qid type bits, as in 9P2000.\nconst (\n\tQTFILE   uint8 = 0x00 // a plain file\n\tQTTMP    uint8 = 0x04 // not archived\n\tQTAUTH   uint8 = 0x08 // authentication file\n\tQTMOUNT  uint8 = 0x10 // mounted channel\n\tQTEXCL   uint8 = 0x20 // exclusive use\n\tQTAPPEND uint8 = 0x40 // append only\n\tQTDIR    uint8 = 0x80 // a directory\n)\n\n// Perm holds the 9P mode word: the low nine bits are rwx for owner, group and\n// other, the high bits are the DM* kind flags.\ntype Perm uint32\n\n// Mode bits, as in 9P2000.\nconst (\n\tDMTMP    Perm = 0x04000000\n\tDMAUTH   Perm = 0x08000000\n\tDMMOUNT  Perm = 0x10000000\n\tDMEXCL   Perm = 0x20000000\n\tDMAPPEND Perm = 0x40000000\n\tDMDIR    Perm = 0x80000000\n\n\tPermMask Perm = 0777 // the rwxrwxrwx bits\n\n\t// Conventional defaults, matching what Plan 9's ramfs hands out.\n\tDirPerm  Perm = DMDIR | 0755\n\tFilePerm Perm = 0644\n)\n\n// IsDir reports whether the mode marks a directory.\nfunc (p Perm) IsDir() bool { return p\u0026DMDIR != 0 }\n\n// String renders the mode the way ls -l does: a kind letter then nine rwx\n// bits. The kind letter is 'd' for a directory, 'a' for append-only, 'l' for\n// exclusive-use, '-' otherwise.\nfunc (p Perm) String() string {\n\tvar b strings.Builder\n\tswitch {\n\tcase p\u0026DMDIR != 0:\n\t\tb.WriteByte('d')\n\tcase p\u0026DMAPPEND != 0:\n\t\tb.WriteByte('a')\n\tcase p\u0026DMEXCL != 0:\n\t\tb.WriteByte('l')\n\tdefault:\n\t\tb.WriteByte('-')\n\t}\n\tconst rwx = \"rwxrwxrwx\"\n\tfor i := 0; i \u003c 9; i++ {\n\t\tif p\u0026(1\u003c\u003cuint(8-i)) != 0 {\n\t\t\tb.WriteByte(rwx[i])\n\t\t} else {\n\t\t\tb.WriteByte('-')\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// Qid is the server's unique handle for a file. Path identifies the file\n// within one server for its whole lifetime; Version increments on every write,\n// so a client can tell \"same file, changed\" from \"different file\" without\n// reading either.\ntype Qid struct {\n\tType    uint8\n\tVersion uint32\n\tPath    uint64\n}\n\n// IsDir reports whether the qid marks a directory.\nfunc (q Qid) IsDir() bool { return q.Type\u0026QTDIR != 0 }\n\n// String renders the qid as Plan 9 does, \"(path version type)\", with the path\n// in hex.\nfunc (q Qid) String() string {\n\tkind := \"f\"\n\tif q.IsDir() {\n\t\tkind = \"d\"\n\t}\n\treturn \"(\" + strconv.FormatUint(q.Path, 16) + \" \" +\n\t\tstrconv.FormatUint(uint64(q.Version), 10) + \" \" + kind + \")\"\n}\n\n// Stat is 9P's directory entry, minus the fields that only mean something on a\n// wire (type, dev) or on a host clock (atime).\ntype Stat struct {\n\tQid    Qid\n\tMode   Perm\n\tMtime  int64 // block height of the last write\n\tLength int64 // in bytes; zero for a directory, as in 9P\n\tName   string\n\tUid    string // owner; a bech32 address, or a well-known name\n\tGid    string // group\n\tMuid   string // last writer\n}\n\n// IsDir reports whether the entry is a directory.\nfunc (s Stat) IsDir() bool { return s.Mode.IsDir() }\n\n// Line renders the entry the way ls -l does.\nfunc (s Stat) Line() string {\n\treturn s.Mode.String() + \" \" + pad(s.Uid, 12) + \" \" + pad(s.Gid, 8) + \" \" +\n\t\tlpad(strconv.FormatInt(s.Length, 10), 7) + \" \" + s.Name\n}\n\n// pad right-pads to n runes. ufmt has no width flags in gno, so padding is by\n// hand everywhere in this suite.\nfunc pad(s string, n int) string {\n\tfor len(s) \u003c n {\n\t\ts += \" \"\n\t}\n\treturn s\n}\n\nfunc lpad(s string, n int) string {\n\tfor len(s) \u003c n {\n\t\ts = \" \" + s\n\t}\n\treturn s\n}\n\n// File is a 9P file server's whole read surface. Every method must be free of\n// side effects: a File is routinely reached across a realm boundary, where the\n// running frame belongs to the CALLER, so mutating anything here would be both\n// a VM error and a confused deputy.\ntype File interface {\n\t// Stat returns the entry for this file.\n\tStat() Stat\n\t// Walk resolves exactly one path element. It returns ErrNotDir on a\n\t// plain file and ErrNotExist when the name is absent. It never sees\n\t// \".\" or \"..\": both are removed lexically before resolution starts.\n\tWalk(name string) (File, error)\n\t// Read returns at most count bytes starting at off. A negative count\n\t// means \"to the end\". It returns ErrIsDir on a directory.\n\tRead(off, count int64) (string, error)\n\t// ReadDir returns the directory's entries in a deterministic order. It\n\t// returns ErrNotDir on a plain file.\n\tReadDir() ([]Stat, error)\n}\n\n// Mutable is the write half, kept out of File on purpose.\n//\n// It is NOT safe across a realm boundary: a non-crossing method runs in the\n// caller's frame, so a foreign realm calling these would be trying to mutate\n// objects it does not own. Only call Mutable on a tree your own realm created.\n// The caller supplies now (a block height) rather than the tree reading the\n// chain itself, so the same code is testable off chain.\ntype Mutable interface {\n\tFile\n\tCreate(name string, perm Perm, now int64) (File, error)\n\tRemove(name string) error\n\tWrite(off int64, data string, now int64) (int64, error)\n\tTruncate(size int64, now int64) error\n}\n\n// Plan 9 error strings, kept lowercase and verbatim where they exist.\nvar (\n\tErrNotExist = errors.New(\"file does not exist\")\n\tErrNotDir   = errors.New(\"not a directory\")\n\tErrIsDir    = errors.New(\"is a directory\")\n\tErrExist    = errors.New(\"file already exists\")\n\tErrPerm     = errors.New(\"permission denied\")\n\tErrNoCreate = errors.New(\"create prohibited\")\n\tErrReadOnly = errors.New(\"read-only file server\")\n\tErrBadName  = errors.New(\"bad character in file name\")\n\tErrNotEmpty = errors.New(\"directory not empty\")\n\tErrTooDeep  = errors.New(\"path too deep\")\n)\n\n// MaxDepth bounds a walk. Resolution costs one cross-realm call per element\n// per union member, so depth is capped rather than trusted.\nconst MaxDepth = 32\n\n// ValidName reports whether name is usable as a single path element. Plan 9\n// rejects the empty name, \".\" and \"..\", and any name containing a slash.\nfunc ValidName(name string) bool {\n\tif name == \"\" || name == \".\" || name == \"..\" {\n\t\treturn false\n\t}\n\treturn !strings.Contains(name, \"/\")\n}\n\n// Clean returns p as a cleaned absolute path. \".\" and \"..\" are resolved\n// lexically, before any server sees them, which is what makes \"..\" undo the\n// name you typed rather than the directory you landed in (see \"Lexical File\n// Names in Plan 9\").\nfunc Clean(p string) string {\n\tif !strings.HasPrefix(p, \"/\") {\n\t\tp = \"/\" + p\n\t}\n\treturn path.Clean(p)\n}\n\n// Abs resolves p against cwd, then cleans it.\nfunc Abs(cwd, p string) string {\n\tif p == \"\" {\n\t\treturn Clean(cwd)\n\t}\n\tif strings.HasPrefix(p, \"/\") {\n\t\treturn Clean(p)\n\t}\n\tif cwd == \"\" {\n\t\tcwd = \"/\"\n\t}\n\treturn Clean(cwd + \"/\" + p)\n}\n\n// Elems splits a cleaned absolute path into its elements. The root yields nil.\nfunc Elems(p string) []string {\n\tp = Clean(p)\n\tif p == \"/\" {\n\t\treturn nil\n\t}\n\treturn strings.Split(p[1:], \"/\")\n}\n\n// Base returns the last element of p, or \"/\" for the root.\nfunc Base(p string) string { return path.Base(Clean(p)) }\n\n// Dir returns p's parent.\nfunc Dir(p string) string { return path.Dir(Clean(p)) }\n\n// Join appends name to dir.\nfunc Join(dir, name string) string { return Clean(dir + \"/\" + name) }\n\n// Walk resolves elems from f, one element at a time. It is the plain,\n// namespace-free walk: no binds, no unions. Use ns.Ns for those.\nfunc Walk(f File, elems []string) (File, error) {\n\tif len(elems) \u003e MaxDepth {\n\t\treturn nil, ErrTooDeep\n\t}\n\tfor _, e := range elems {\n\t\tnext, err := f.Walk(e)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf = next\n\t}\n\treturn f, nil\n}\n\n// ReadAll reads a whole file.\nfunc ReadAll(f File) (string, error) { return f.Read(0, -1) }\n\n// Slice applies 9P's read window to s: at most count bytes from off, with a\n// negative count meaning \"to the end\". An offset past the end reads empty,\n// which is what makes a read loop terminate rather than fail.\nfunc Slice(s string, off, count int64) string {\n\tif off \u003c 0 {\n\t\toff = 0\n\t}\n\tn := int64(len(s))\n\tif off \u003e= n {\n\t\treturn \"\"\n\t}\n\tend := n\n\tif count \u003e= 0 \u0026\u0026 off+count \u003c n {\n\t\tend = off + count\n\t}\n\treturn s[off:end]\n}\n"},{"name":"ninep_test.gno","body":"package ninep\n\nimport \"testing\"\n\nfunc TestPermString(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tperm Perm\n\t\twant string\n\t}{\n\t\t{\"dir 0755\", DMDIR | 0755, \"drwxr-xr-x\"},\n\t\t{\"file 0644\", 0644, \"-rw-r--r--\"},\n\t\t{\"file 0600\", 0600, \"-rw-------\"},\n\t\t{\"file 0777\", 0777, \"-rwxrwxrwx\"},\n\t\t{\"file 0000\", 0, \"----------\"},\n\t\t{\"append only\", DMAPPEND | 0644, \"arw-r--r--\"},\n\t\t{\"exclusive\", DMEXCL | 0600, \"lrw-------\"},\n\t\t{\"dir default\", DirPerm, \"drwxr-xr-x\"},\n\t\t{\"file default\", FilePerm, \"-rw-r--r--\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := tt.perm.String(); got != tt.want {\n\t\t\tt.Errorf(\"%s: got %q, want %q\", tt.name, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestPermIsDir(t *testing.T) {\n\tif !(DMDIR | 0755).IsDir() {\n\t\tt.Error(\"DMDIR|0755 should be a directory\")\n\t}\n\tif Perm(0644).IsDir() {\n\t\tt.Error(\"0644 should not be a directory\")\n\t}\n}\n\nfunc TestQidString(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tqid  Qid\n\t\twant string\n\t}{\n\t\t{\"root\", Qid{Type: QTDIR, Version: 0, Path: 0}, \"(0 0 d)\"},\n\t\t{\"file\", Qid{Type: QTFILE, Version: 3, Path: 17}, \"(11 3 f)\"},\n\t\t{\"big path\", Qid{Type: QTFILE, Version: 1, Path: 255}, \"(ff 1 f)\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := tt.qid.String(); got != tt.want {\n\t\t\tt.Errorf(\"%s: got %q, want %q\", tt.name, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestStatLine(t *testing.T) {\n\ts := Stat{\n\t\tQid:    Qid{Type: QTFILE, Path: 2, Version: 1},\n\t\tMode:   0644,\n\t\tLength: 12,\n\t\tName:   \"greeting\",\n\t\tUid:    \"glenda\",\n\t\tGid:    \"sys\",\n\t}\n\twant := \"-rw-r--r-- glenda       sys           12 greeting\"\n\tif got := s.Line(); got != want {\n\t\tt.Errorf(\"got %q, want %q\", got, want)\n\t}\n}\n\nfunc TestValidName(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant bool\n\t}{\n\t\t{\"dev\", true},\n\t\t{\"a.b\", true},\n\t\t{\"with space\", true},\n\t\t{\"\", false},\n\t\t{\".\", false},\n\t\t{\"..\", false},\n\t\t{\"a/b\", false},\n\t\t{\"/\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := ValidName(tt.name); got != tt.want {\n\t\t\tt.Errorf(\"ValidName(%q): got %v, want %v\", tt.name, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestClean(t *testing.T) {\n\ttests := []struct {\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"\", \"/\"},\n\t\t{\"/\", \"/\"},\n\t\t{\"dev\", \"/dev\"},\n\t\t{\"/dev/\", \"/dev\"},\n\t\t{\"/dev//height\", \"/dev/height\"},\n\t\t{\"/dev/./height\", \"/dev/height\"},\n\t\t{\"/dev/../srv\", \"/srv\"},\n\t\t{\"/../..\", \"/\"},\n\t\t{\"/a/b/../../c\", \"/c\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := Clean(tt.in); got != tt.want {\n\t\t\tt.Errorf(\"Clean(%q): got %q, want %q\", tt.in, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestAbs(t *testing.T) {\n\ttests := []struct {\n\t\tcwd  string\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"/\", \"dev\", \"/dev\"},\n\t\t{\"/usr/glenda\", \"bin\", \"/usr/glenda/bin\"},\n\t\t{\"/usr/glenda\", \"/dev\", \"/dev\"},\n\t\t{\"/usr/glenda\", \"..\", \"/usr\"},\n\t\t{\"/usr/glenda\", \"\", \"/usr/glenda\"},\n\t\t{\"\", \"dev\", \"/dev\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := Abs(tt.cwd, tt.in); got != tt.want {\n\t\t\tt.Errorf(\"Abs(%q, %q): got %q, want %q\", tt.cwd, tt.in, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestElems(t *testing.T) {\n\ttests := []struct {\n\t\tin   string\n\t\twant []string\n\t}{\n\t\t{\"/\", nil},\n\t\t{\"\", nil},\n\t\t{\"/dev\", []string{\"dev\"}},\n\t\t{\"/dev/height\", []string{\"dev\", \"height\"}},\n\t\t{\"/a/b/../c\", []string{\"a\", \"c\"}},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := Elems(tt.in)\n\t\tif len(got) != len(tt.want) {\n\t\t\tt.Errorf(\"Elems(%q): got %v, want %v\", tt.in, got, tt.want)\n\t\t\tcontinue\n\t\t}\n\t\tfor i := range got {\n\t\t\tif got[i] != tt.want[i] {\n\t\t\t\tt.Errorf(\"Elems(%q)[%d]: got %q, want %q\", tt.in, i, got[i], tt.want[i])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestBaseDirJoin(t *testing.T) {\n\tif got := Base(\"/dev/height\"); got != \"height\" {\n\t\tt.Errorf(\"Base: got %q\", got)\n\t}\n\tif got := Base(\"/\"); got != \"/\" {\n\t\tt.Errorf(\"Base of root: got %q\", got)\n\t}\n\tif got := Dir(\"/dev/height\"); got != \"/dev\" {\n\t\tt.Errorf(\"Dir: got %q\", got)\n\t}\n\tif got := Join(\"/dev\", \"height\"); got != \"/dev/height\" {\n\t\tt.Errorf(\"Join: got %q\", got)\n\t}\n\tif got := Join(\"/\", \"dev\"); got != \"/dev\" {\n\t\tt.Errorf(\"Join at root: got %q\", got)\n\t}\n}\n\nfunc TestSlice(t *testing.T) {\n\tconst s = \"hello world\"\n\ttests := []struct {\n\t\tname  string\n\t\toff   int64\n\t\tcount int64\n\t\twant  string\n\t}{\n\t\t{\"whole\", 0, -1, \"hello world\"},\n\t\t{\"prefix\", 0, 5, \"hello\"},\n\t\t{\"middle\", 6, 5, \"world\"},\n\t\t{\"past end\", 99, 5, \"\"},\n\t\t{\"count past end\", 6, 99, \"world\"},\n\t\t{\"negative offset clamps\", -4, 5, \"hello\"},\n\t\t{\"zero count\", 0, 0, \"\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := Slice(s, tt.off, tt.count); got != tt.want {\n\t\t\tt.Errorf(\"%s: got %q, want %q\", tt.name, got, tt.want)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"vmkit","path":"gno.land/p/moul/x/vm/vmkit/v0","files":[{"name":"README.md","body":"# p/moul/x/vm/vmkit\n\nThe host ABI shared by every guest virtual machine that runs inside a gno\nrealm: a stepping contract with an explicit fuel budget, a capability-scoped\n`Host`, and a snapshot format that lets a guest program outlive the transaction\nthat started it.\n\nA guest VM implements `Machine`. Everything else here is the machinery a VM\nshould not have to write twice: the `Meter`, the canonical `Writer`/`Reader`\nsnapshots are built from, an in-memory `TestHost`, and the avl-backed `Store` a\nrealm keeps its instances in.\n\nFirst consumer: [`p/moul/x/vm/bf`](../bf). Live demo:\n[`r/moul/x/vm/bfdemo`](/r/moul/x/vm/bfdemo/v0).\n\n```go\ntype Machine interface {\n\tStep(h Host, fuel int64) (used int64, status Status)\n\tSnapshot() []byte\n\tRestore(b []byte) error\n}\n```\n\n`Status` is one of `Running`, `Halted`, `Trapped`, `OutOfFuel`.\n\n## What the ABI is for\n\n**Fuel is the interface, not the backstop.** Running out of fuel yields\n`OutOfFuel` plus a machine that can be snapshotted, never a panic. Gas still\nbounds the transaction; it is just not the thing a guest program is written\nagainst.\n\n**Continuations.** `Snapshot` and `Restore` mean a program runs across blocks.\nThe realm stores the bytes, the next caller pays for the next slice. Gno realm\ncode cannot pause itself; a guest can. The property that makes this real is\ntested rather than asserted: five slices of one fuel unit must produce exactly\nwhat one slice of five produces, for every program in `bf`'s corpus.\n\n**Capabilities, not ambient authority.** A guest gets exactly the `Host` it was\nhanded. `Send` returns `ErrNotGranted` unless the deploying realm funded a\nbudget, storage is scoped to the instance, and nothing is looked up. Gno itself\nhas ambient authority through the realm frame, so the guest is where the\ncapability-secure version can actually be tried.\n\n## Meter is not a hot-path type\n\n`Meter` exists for the API boundary: compute a slice budget, charge it once,\nreport what was used. Calling `Meter.Charge` once per guest instruction was\nmeasured at **+86% on top of an entire interpreter dispatch loop**, and more\nthan tripled its allocation count. A machine should count fuel in a local and\nsettle up with the caller. The numbers are in [`bf`'s README](../bf/README.md).\n\n`Charge` spends nothing when the budget cannot cover the request, so a machine\nthat stops for lack of fuel is exactly at the instruction it could not pay for,\nand resuming re-executes that instruction and no other.\n\n## The snapshot codec\n\n`Writer` and `Reader` are fixed-width big-endian with length-prefixed bytes, so\nthe encoding is canonical: the same machine state always produces the same\nbytes, on every node. A snapshot is consensus state, so two nodes encoding it\ndifferently is a fork, and a short read is a hard error rather than a zero\nvalue.\n\nMachines are not required to use it, but a machine that invents its own layout\nowes the zoo an explanation: the cross-VM snapshot cost comparison only means\nsomething when the encodings match.\n\n## Instance and Store\n\n`Instance` is one guest program as a realm stores it: code, snapshot between\nslices, status, and the fuel accounting that survives the transaction. It holds\nbytes rather than a `Machine` on purpose, which is what makes the storage cost\nof a paused program measurable.\n\n`Instance.Run` folds one slice back into the instance and leaves it untouched\nwhen `Restore` fails, so a snapshot that cannot be decoded costs the caller gas\nbut never corrupts the stored program.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/vm/vmkit/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/vm/vmkit/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"codec.gno","body":"package vmkit\n\nimport \"errors\"\n\n// ErrTruncated is returned by every Reader method that runs past the end of\n// the buffer. A snapshot is consensus state, so a short read is always a hard\n// error and never a zero value.\nvar ErrTruncated = errors.New(\"vmkit: truncated snapshot\")\n\n// ErrBadSnapshot is returned when a snapshot is well-formed but not for this\n// machine: wrong magic, wrong version, or a field outside its legal range.\nvar ErrBadSnapshot = errors.New(\"vmkit: snapshot is not for this machine\")\n\n// Writer builds a snapshot. Every integer is fixed-width big-endian and every\n// byte slice is length-prefixed, so the encoding is canonical: the same\n// machine state always produces the same bytes, on every node.\n//\n// Machines are not required to use it, but a machine that invents its own\n// layout owes the zoo an explanation, because the cross-VM snapshot cost\n// comparison only means something when the encodings match.\ntype Writer struct {\n\tbuf []byte\n}\n\n// NewWriter returns a Writer with room for n bytes reserved up front.\nfunc NewWriter(n int) *Writer {\n\tif n \u003c 0 {\n\t\tn = 0\n\t}\n\treturn \u0026Writer{buf: make([]byte, 0, n)}\n}\n\n// Byte appends one byte.\nfunc (w *Writer) Byte(b byte) { w.buf = append(w.buf, b) }\n\n// Uint32 appends a 4-byte big-endian value.\nfunc (w *Writer) Uint32(v uint32) {\n\tw.buf = append(w.buf, byte(v\u003e\u003e24), byte(v\u003e\u003e16), byte(v\u003e\u003e8), byte(v))\n}\n\n// Uint64 appends an 8-byte big-endian value.\nfunc (w *Writer) Uint64(v uint64) {\n\tw.buf = append(w.buf,\n\t\tbyte(v\u003e\u003e56), byte(v\u003e\u003e48), byte(v\u003e\u003e40), byte(v\u003e\u003e32),\n\t\tbyte(v\u003e\u003e24), byte(v\u003e\u003e16), byte(v\u003e\u003e8), byte(v))\n}\n\n// Int appends a signed value, zig-zag encoded into a Uint64 so that small\n// negative numbers do not cost eight 0xff bytes.\nfunc (w *Writer) Int(v int64) {\n\tu := uint64(v) \u003c\u003c 1\n\tif v \u003c 0 {\n\t\tu = ^u\n\t}\n\tw.Uint64(u)\n}\n\n// Bytes appends a length-prefixed byte slice.\nfunc (w *Writer) Bytes(p []byte) {\n\tw.Uint32(uint32(len(p)))\n\tw.buf = append(w.buf, p...)\n}\n\n// String appends a length-prefixed string.\nfunc (w *Writer) String(s string) { w.Bytes([]byte(s)) }\n\n// Out returns the encoded bytes.\nfunc (w *Writer) Out() []byte { return w.buf }\n\n// Reader consumes a snapshot written by [Writer].\n//\n// It latches the first error it hits: a caller may decode a whole struct and\n// check [Reader.Err] once at the end, instead of after every field. Every\n// method returns a zero value once the Reader is in error.\ntype Reader struct {\n\tbuf []byte\n\tpos int\n\terr error\n}\n\n// NewReader returns a Reader over b.\nfunc NewReader(b []byte) *Reader { return \u0026Reader{buf: b} }\n\n// Err returns the first error hit, or nil.\nfunc (r *Reader) Err() error { return r.err }\n\n// Remaining reports how many bytes are left unread.\nfunc (r *Reader) Remaining() int {\n\tif r.pos \u003e len(r.buf) {\n\t\treturn 0\n\t}\n\treturn len(r.buf) - r.pos\n}\n\n// Fail latches err, so a machine can reject a field its own rules forbid and\n// have it surface through [Reader.Err] like any decoding failure.\nfunc (r *Reader) Fail(err error) {\n\tif r.err == nil {\n\t\tr.err = err\n\t}\n}\n\nfunc (r *Reader) take(n int) []byte {\n\tif r.err != nil {\n\t\treturn nil\n\t}\n\tif n \u003c 0 || r.pos+n \u003e len(r.buf) {\n\t\tr.err = ErrTruncated\n\t\treturn nil\n\t}\n\tout := r.buf[r.pos : r.pos+n]\n\tr.pos += n\n\treturn out\n}\n\n// Byte reads one byte.\nfunc (r *Reader) Byte() byte {\n\tp := r.take(1)\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p[0]\n}\n\n// Uint32 reads a 4-byte big-endian value.\nfunc (r *Reader) Uint32() uint32 {\n\tp := r.take(4)\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn uint32(p[0])\u003c\u003c24 | uint32(p[1])\u003c\u003c16 | uint32(p[2])\u003c\u003c8 | uint32(p[3])\n}\n\n// Uint64 reads an 8-byte big-endian value.\nfunc (r *Reader) Uint64() uint64 {\n\tp := r.take(8)\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn uint64(p[0])\u003c\u003c56 | uint64(p[1])\u003c\u003c48 | uint64(p[2])\u003c\u003c40 | uint64(p[3])\u003c\u003c32 |\n\t\tuint64(p[4])\u003c\u003c24 | uint64(p[5])\u003c\u003c16 | uint64(p[6])\u003c\u003c8 | uint64(p[7])\n}\n\n// Int reads a zig-zag encoded signed value written by [Writer.Int].\nfunc (r *Reader) Int() int64 {\n\tu := r.Uint64()\n\tv := int64(u \u003e\u003e 1)\n\tif u\u00261 != 0 {\n\t\tv = ^v\n\t}\n\treturn v\n}\n\n// Bytes reads a length-prefixed byte slice. The result is a copy, so a\n// machine can keep it without aliasing the snapshot it was handed.\nfunc (r *Reader) Bytes() []byte {\n\tn := int(r.Uint32())\n\tp := r.take(n)\n\tif p == nil {\n\t\treturn nil\n\t}\n\tout := make([]byte, n)\n\tcopy(out, p)\n\treturn out\n}\n\n// String reads a length-prefixed string.\nfunc (r *Reader) String() string {\n\tp := r.take(int(r.Uint32()))\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\treturn string(p)\n}\n"},{"name":"fuel.gno","body":"package vmkit\n\n// Unmetered is the fuel value that disables the budget: a [Meter] built with\n// it never reports exhaustion. It exists so a benchmark can measure the\n// dispatch loop without the meter in it, and so a trusted caller can run a\n// program to completion in one slice. Gas remains the real backstop.\nconst Unmetered int64 = -1\n\n// Meter is a fuel budget being spent. It allocates nothing after\n// construction, because it sits in the hot path of every guest instruction.\ntype Meter struct {\n\tbudget int64 // Unmetered, or the number of units this slice may spend\n\tused   int64\n}\n\n// NewMeter returns a meter good for `budget` units, or an unmetered one when\n// budget is [Unmetered]. A budget of zero is a meter with nothing to spend,\n// which is a legitimate way to ask \"is this instance still runnable\".\nfunc NewMeter(budget int64) *Meter {\n\tif budget \u003c 0 {\n\t\tbudget = Unmetered\n\t}\n\treturn \u0026Meter{budget: budget}\n}\n\n// Charge spends n units and reports whether they were available. On false\n// nothing is spent, so the caller can stop before executing the instruction\n// it could not pay for. That ordering is what makes a resumed machine\n// re-execute exactly the instruction it stopped at, and no other.\nfunc (m *Meter) Charge(n int64) bool {\n\tif m.budget == Unmetered {\n\t\tm.used += n\n\t\treturn true\n\t}\n\tif m.used+n \u003e m.budget {\n\t\treturn false\n\t}\n\tm.used += n\n\treturn true\n}\n\n// Used reports how much fuel has been spent.\nfunc (m *Meter) Used() int64 { return m.used }\n\n// Remaining reports what is left, or [Unmetered].\nfunc (m *Meter) Remaining() int64 {\n\tif m.budget == Unmetered {\n\t\treturn Unmetered\n\t}\n\treturn m.budget - m.used\n}\n\n// Exhausted reports whether the next single unit would fail.\nfunc (m *Meter) Exhausted() bool { return !m.affordable(1) }\n\nfunc (m *Meter) affordable(n int64) bool {\n\treturn m.budget == Unmetered || m.used+n \u003c= m.budget\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/vm/vmkit/v0\"\ngno = \"0.9\"\n"},{"name":"host.gno","body":"package vmkit\n\nimport \"errors\"\n\n// ErrNotGranted is returned by a [Host] for a capability the instance was\n// never given. A guest that ignores the error and keeps going is a guest bug;\n// a machine should turn it into a [Trapped] status.\nvar ErrNotGranted = errors.New(\"vmkit: capability not granted\")\n\n// Host is everything a guest program can reach outside its own memory.\n//\n// It is deliberately small, and deliberately handed in rather than looked up:\n// a guest has exactly the authority its [Host] carries. Gno realm code has\n// ambient authority through the realm frame, so the guest is where the\n// capability-secure version can actually be tried.\n//\n// Every method must be deterministic across replays of the same block. Now\n// and Height come from the chain, never from a wall clock.\ntype Host interface {\n\t// Caller is the address that called the realm running this guest.\n\tCaller() address\n\t// Origin is the address that signed the transaction.\n\tOrigin() address\n\t// Now is block time in Unix seconds, never wall time.\n\tNow() int64\n\t// Height is the block height.\n\tHeight() int64\n\n\t// Get reads from storage scoped to this instance. A miss is nil.\n\tGet(key []byte) []byte\n\t// Set writes to storage scoped to this instance.\n\tSet(key, val []byte)\n\n\t// Input is the immutable call input for this slice of execution: the\n\t// guest's calldata, argv, or stdin depending on the machine. A machine\n\t// tracks its own read cursor, in its snapshot, so that resuming reads\n\t// the byte it had not read yet.\n\tInput() []byte\n\t// Output appends to the guest's output buffer.\n\tOutput(p []byte)\n\n\t// Emit writes a chain event. kv is a flat list of alternating keys and\n\t// values; an odd trailing element is dropped.\n\tEmit(typ string, kv ...string)\n\t// Send transfers amount ugnot to `to`, and returns [ErrNotGranted]\n\t// unless the deploying realm funded this instance with a budget.\n\tSend(to address, amount int64) error\n\t// Log records a diagnostic line. Never consensus-relevant.\n\tLog(msg string)\n}\n"},{"name":"instance.gno","body":"package vmkit\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// ErrNoInstance is returned when an id names nothing.\nvar ErrNoInstance = errors.New(\"vmkit: no such instance\")\n\n// ErrBudgetExhausted is returned when an instance has already spent its total\n// fuel budget, so there is nothing left to step.\nvar ErrBudgetExhausted = errors.New(\"vmkit: instance fuel budget exhausted\")\n\n// Instance is one guest program as a realm stores it: the code, the machine\n// state between slices, and the accounting that survives the transaction.\n//\n// It holds a snapshot rather than a [Machine], on purpose. A realm keeps\n// bytes; the machine is rebuilt for the slice that needs it and thrown away\n// after. That is what makes the storage cost of a paused program measurable,\n// which is the whole kill criterion for continuations: if resuming costs more\n// than re-running, continuations are theater.\ntype Instance struct {\n\tID    string\n\tOwner address\n\tVM    string // which guest machine the Program is for\n\n\tProgram  []byte\n\tSnapshot []byte\n\n\tStatus Status\n\tTrap   string\n\n\t// FuelUsed is the total across every slice run so far.\n\tFuelUsed int64\n\t// FuelBudget caps FuelUsed across the instance's whole life, or is\n\t// [Unmetered] for no cap.\n\tFuelBudget int64\n\n\t// Slices counts how many transactions have stepped this instance.\n\tSlices int64\n\n\tOutput []byte\n}\n\n// NewInstance returns an instance ready for its first slice.\nfunc NewInstance(id string, owner address, vm string, program []byte, budget int64) *Instance {\n\tif budget \u003c 0 {\n\t\tbudget = Unmetered\n\t}\n\tprog := make([]byte, len(program))\n\tcopy(prog, program)\n\treturn \u0026Instance{\n\t\tID:         id,\n\t\tOwner:      owner,\n\t\tVM:         vm,\n\t\tProgram:    prog,\n\t\tStatus:     Running,\n\t\tFuelBudget: budget,\n\t}\n}\n\n// Remaining reports the fuel left in the instance's total budget, or\n// [Unmetered].\nfunc (i *Instance) Remaining() int64 {\n\tif i.FuelBudget == Unmetered {\n\t\treturn Unmetered\n\t}\n\tleft := i.FuelBudget - i.FuelUsed\n\tif left \u003c 0 {\n\t\treturn 0\n\t}\n\treturn left\n}\n\n// Slice returns how much fuel the next call to [Instance.Run] may spend when\n// the caller asks for `want`: `want` clamped to what the budget still allows.\nfunc (i *Instance) Slice(want int64) int64 {\n\tleft := i.Remaining()\n\tif left == Unmetered {\n\t\treturn want\n\t}\n\tif want == Unmetered || want \u003e left {\n\t\treturn left\n\t}\n\treturn want\n}\n\n// Run steps m for one slice of at most `fuel` units and folds the result back\n// into the instance: the new snapshot, the status, the fuel spent, and\n// anything the guest wrote to h.\n//\n// m must be a fresh machine loaded from i.Program; Run restores i.Snapshot\n// into it when there is one, so the caller never has to remember the order.\n// The instance is left untouched when Restore fails, which means a snapshot\n// that cannot be decoded costs the caller gas but never corrupts the stored\n// program.\nfunc (i *Instance) Run(m Machine, h Host, fuel int64) error {\n\tif i.Status.Done() \u0026\u0026 i.Status != Running {\n\t\treturn ErrBudgetExhausted\n\t}\n\tif len(i.Snapshot) \u003e 0 {\n\t\tif err := m.Restore(i.Snapshot); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tslice := i.Slice(fuel)\n\tif slice == 0 {\n\t\ti.Status = OutOfFuel\n\t\treturn ErrBudgetExhausted\n\t}\n\n\tused, status := m.Step(h, slice)\n\n\ti.FuelUsed += used\n\ti.Slices++\n\ti.Snapshot = m.Snapshot()\n\ti.Status = status\n\ti.Trap = TrapReason(m)\n\tif status == Running \u0026\u0026 i.Remaining() == 0 {\n\t\ti.Status = OutOfFuel\n\t}\n\treturn nil\n}\n\n// Store is the avl-backed set of instances a realm owns, keyed by id.\ntype Store struct {\n\ttree *avl.Tree\n}\n\n// NewStore returns an empty store.\nfunc NewStore() *Store { return \u0026Store{tree: avl.NewTree()} }\n\n// Set writes an instance, replacing any instance with the same id.\nfunc (s *Store) Set(i *Instance) {\n\tif i == nil {\n\t\treturn\n\t}\n\ts.tree.Set(i.ID, i)\n}\n\n// Get returns the instance with this id, or nil.\nfunc (s *Store) Get(id string) *Instance {\n\tv := s.tree.Get(id)\n\tif v == nil {\n\t\treturn nil\n\t}\n\tinst, ok := v.(*Instance)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn inst\n}\n\n// Remove deletes an instance and reports whether it existed.\nfunc (s *Store) Remove(id string) bool {\n\t_, removed := s.tree.Remove(id)\n\treturn removed\n}\n\n// Size returns how many instances are stored.\nfunc (s *Store) Size() int { return s.tree.Size() }\n\n// Iterate walks every instance in key order, stopping early when fn returns\n// true.\nfunc (s *Store) Iterate(fn func(*Instance) bool) {\n\ts.tree.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tinst, ok := v.(*Instance)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn fn(inst)\n\t})\n}\n\n// ReverseIterate walks every instance in descending key order, which is how a\n// realm renders newest-first when ids are zero-padded and ascending.\nfunc (s *Store) ReverseIterate(fn func(*Instance) bool) {\n\ts.tree.ReverseIterate(\"\", \"\", func(_ string, v any) bool {\n\t\tinst, ok := v.(*Instance)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn fn(inst)\n\t})\n}\n"},{"name":"machine.gno","body":"// Package vmkit is the host ABI shared by every guest virtual machine that\n// runs inside a gno realm: a stepping contract with an explicit fuel budget,\n// a capability-scoped [Host], and a snapshot format that lets a guest program\n// outlive the transaction that started it.\n//\n// A guest VM implements [Machine]. Everything else in this package is the\n// machinery a VM should not have to write twice: the [Meter], the [Codec] the\n// snapshots are built from, an in-memory [TestHost], and the avl-backed\n// [Store] a realm keeps its instances in.\n//\n// The three things the ABI exists to fix:\n//\n//   - Fuel is the interface, not the backstop. Running out of fuel yields\n//     [OutOfFuel] plus a machine that can be snapshotted, never a panic. Gas\n//     still bounds the transaction, but a guest that stops is a normal outcome.\n//   - Continuations. Snapshot and Restore mean a program runs across blocks.\n//     The realm stores the bytes, and the next caller pays for the next slice.\n//     Gno realm code itself cannot pause; a guest can.\n//   - Capabilities, not ambient authority. A guest gets exactly the [Host] it\n//     was handed. No Send without a grant, no storage outside its own scope.\n//\n// Live demo: [r/moul/x/vm/bfdemo](/r/moul/x/vm/bfdemo/v0), running the\n// [p/moul/x/vm/bf](/p/moul/x/vm/bf/v0) guest.\npackage vmkit\n\n// Status is the outcome of a call to [Machine.Step].\ntype Status int\n\nconst (\n\t// Running means the machine stopped because it ran out of the fuel\n\t// handed to this slice, but the program has not finished. It is\n\t// resumable: snapshot it, and step it again later.\n\tRunning Status = iota\n\n\t// Halted means the program reached its end. Terminal.\n\tHalted\n\n\t// Trapped means the guest did something the machine refuses to do:\n\t// an invalid instruction, an out-of-range access, a capability it was\n\t// not granted. Terminal.\n\tTrapped\n\n\t// OutOfFuel means the instance exhausted its total budget, not just the\n\t// fuel for this slice. Terminal unless the owner raises the budget.\n\tOutOfFuel\n)\n\n// String renders the status as the lowercase word used in realm output.\nfunc (s Status) String() string {\n\tswitch s {\n\tcase Running:\n\t\treturn \"running\"\n\tcase Halted:\n\t\treturn \"halted\"\n\tcase Trapped:\n\t\treturn \"trapped\"\n\tcase OutOfFuel:\n\t\treturn \"out of fuel\"\n\t}\n\treturn \"unknown\"\n}\n\n// Done reports whether the status is terminal, i.e. stepping again is\n// pointless without operator intervention.\nfunc (s Status) Done() bool { return s != Running }\n\n// Machine is one guest virtual machine, mid-execution.\n//\n// Step runs until the program halts, traps, or burns `fuel` units, whichever\n// comes first, and reports how much fuel it actually used. A Machine must\n// charge at least one unit per guest instruction so that a fuel budget is a\n// real bound on work; beyond that the unit is the VM's own business, and\n// [r/moul/x/vm/bfdemo](/r/moul/x/vm/bfdemo/v0) compares them by measurement\n// rather than by trusting the number.\n//\n// Snapshot must round-trip through Restore: a machine stepped to exhaustion,\n// snapshotted, restored and stepped again must produce exactly what the same\n// machine stepped in one go would have. That property is what makes a guest\n// program a contract instead of a function call.\ntype Machine interface {\n\tStep(h Host, fuel int64) (used int64, status Status)\n\tSnapshot() []byte\n\tRestore(b []byte) error\n}\n\n// Trapper is an optional refinement of [Machine]: a machine that can explain\n// why it trapped. Kept out of [Machine] so the core ABI stays three methods.\ntype Trapper interface {\n\t// Trap returns the reason for a [Trapped] status, or \"\" when the\n\t// machine has not trapped.\n\tTrap() string\n}\n\n// TrapReason returns m's trap reason when m implements [Trapper], else \"\".\nfunc TrapReason(m Machine) string {\n\tif t, ok := m.(Trapper); ok {\n\t\treturn t.Trap()\n\t}\n\treturn \"\"\n}\n"},{"name":"testhost.gno","body":"package vmkit\n\nimport \"gno.land/p/nt/avl/v0\"\n\n// TestHost is a deterministic in-memory [Host] for unit tests and for\n// measuring a machine without a chain under it.\n//\n// Nothing here reads the chain, so a test that uses it produces the same\n// numbers on every host. Storage is an avl tree rather than a map because gno\n// map iteration order is unspecified, and [TestHost.Keys] has to be stable for\n// a test to assert on it.\n//\n// Send is denied unless [TestHost.Grant] funded a budget, which is how the\n// capability rule gets tested: a guest that tries to send without a grant must\n// come back [Trapped], not silently succeed.\ntype TestHost struct {\n\tcaller address\n\torigin address\n\tnow    int64\n\theight int64\n\n\tstore *avl.Tree // hex key -\u003e []byte\n\n\tin     []byte\n\tout    []byte\n\tevents []string\n\tlogs   []string\n\n\tsendBudget int64\n\tsends      []Transfer\n}\n\n// Transfer records one successful [TestHost.Send].\ntype Transfer struct {\n\tTo     address\n\tAmount int64\n}\n\n// NewTestHost returns a host with no capabilities granted, height 1, time 0,\n// and empty input.\nfunc NewTestHost() *TestHost {\n\treturn \u0026TestHost{\n\t\theight: 1,\n\t\tstore:  avl.NewTree(),\n\t}\n}\n\n// WithCaller sets the address the guest sees as its caller and origin.\nfunc (h *TestHost) WithCaller(a address) *TestHost {\n\th.caller, h.origin = a, a\n\treturn h\n}\n\n// WithOrigin overrides the origin separately from the caller.\nfunc (h *TestHost) WithOrigin(a address) *TestHost { h.origin = a; return h }\n\n// WithTime sets the block time in Unix seconds.\nfunc (h *TestHost) WithTime(t int64) *TestHost { h.now = t; return h }\n\n// WithHeight sets the block height.\nfunc (h *TestHost) WithHeight(n int64) *TestHost { h.height = n; return h }\n\n// WithInput sets the guest's call input.\nfunc (h *TestHost) WithInput(p []byte) *TestHost {\n\th.in = make([]byte, len(p))\n\tcopy(h.in, p)\n\treturn h\n}\n\n// Grant funds the send capability with a budget in ugnot. Without it, Send\n// returns [ErrNotGranted].\nfunc (h *TestHost) Grant(budget int64) *TestHost { h.sendBudget = budget; return h }\n\nfunc (h *TestHost) Caller() address { return h.caller }\nfunc (h *TestHost) Origin() address { return h.origin }\nfunc (h *TestHost) Now() int64      { return h.now }\nfunc (h *TestHost) Height() int64   { return h.height }\nfunc (h *TestHost) Input() []byte   { return h.in }\n\nfunc (h *TestHost) Get(key []byte) []byte {\n\tv := h.store.Get(hexKey(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\tstored := v.([]byte)\n\tout := make([]byte, len(stored))\n\tcopy(out, stored)\n\treturn out\n}\n\nfunc (h *TestHost) Set(key, val []byte) {\n\tcp := make([]byte, len(val))\n\tcopy(cp, val)\n\th.store.Set(hexKey(key), cp)\n}\n\nfunc (h *TestHost) Output(p []byte) { h.out = append(h.out, p...) }\n\nfunc (h *TestHost) Emit(typ string, kv ...string) {\n\tline := typ\n\tfor i := 0; i+1 \u003c len(kv); i += 2 {\n\t\tline += \" \" + kv[i] + \"=\" + kv[i+1]\n\t}\n\th.events = append(h.events, line)\n}\n\nfunc (h *TestHost) Send(to address, amount int64) error {\n\tif amount \u003c= 0 || amount \u003e h.sendBudget {\n\t\treturn ErrNotGranted\n\t}\n\th.sendBudget -= amount\n\th.sends = append(h.sends, Transfer{To: to, Amount: amount})\n\treturn nil\n}\n\nfunc (h *TestHost) Log(msg string) { h.logs = append(h.logs, msg) }\n\n// Out returns everything the guest has written, as bytes.\nfunc (h *TestHost) Out() []byte { return h.out }\n\n// OutString returns everything the guest has written, as a string.\nfunc (h *TestHost) OutString() string { return string(h.out) }\n\n// ResetOut discards the output buffer, so one host can measure several runs.\nfunc (h *TestHost) ResetOut() { h.out = nil }\n\n// Events returns the rendered events, in emission order.\nfunc (h *TestHost) Events() []string { return h.events }\n\n// Logs returns the diagnostic lines, in emission order.\nfunc (h *TestHost) Logs() []string { return h.logs }\n\n// Sends returns the transfers that succeeded, in order.\nfunc (h *TestHost) Sends() []Transfer { return h.sends }\n\n// Keys returns every storage key the guest wrote, hex-encoded, in sorted\n// order.\nfunc (h *TestHost) Keys() []string {\n\tout := []string{}\n\th.store.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tout = append(out, k)\n\t\treturn false\n\t})\n\treturn out\n}\n\nconst hexDigits = \"0123456789abcdef\"\n\n// hexKey encodes a raw key as hex so that arbitrary bytes, including a zero\n// byte, survive being used as an avl key.\nfunc hexKey(key []byte) string {\n\tout := make([]byte, 0, len(key)*2)\n\tfor _, c := range key {\n\t\tout = append(out, hexDigits[c\u003e\u003e4], hexDigits[c\u00260x0f])\n\t}\n\treturn string(out)\n}\n"},{"name":"vmkit_test.gno","body":"package vmkit\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// counter is a toy [Machine] used to test the kit itself without dragging in\n// a real guest VM: it writes one byte per step and halts after `total` of\n// them. Anything that works here is a property of the ABI, not of brainfuck.\ntype counter struct {\n\ttotal int64\n\tdone  int64\n\ttrap  string\n}\n\nfunc (c *counter) Step(h Host, fuel int64) (int64, Status) {\n\tm := NewMeter(fuel)\n\tvar used int64\n\tfor c.done \u003c c.total {\n\t\tif !m.Charge(1) {\n\t\t\treturn used, Running\n\t\t}\n\t\tused++\n\t\tc.done++\n\t\th.Output([]byte{byte('a' + (c.done-1)%26)})\n\t}\n\treturn used, Halted\n}\n\nfunc (c *counter) Snapshot() []byte {\n\tw := NewWriter(24)\n\tw.Int(c.total)\n\tw.Int(c.done)\n\tw.String(c.trap)\n\treturn w.Out()\n}\n\nfunc (c *counter) Restore(b []byte) error {\n\tr := NewReader(b)\n\ttotal := r.Int()\n\tdone := r.Int()\n\ttrap := r.String()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\tc.total, c.done, c.trap = total, done, trap\n\treturn nil\n}\n\nfunc (c *counter) Trap() string { return c.trap }\n\nfunc TestStatusString(t *testing.T) {\n\tcases := []struct {\n\t\ts    Status\n\t\twant string\n\t\tdone bool\n\t}{\n\t\t{Running, \"running\", false},\n\t\t{Halted, \"halted\", true},\n\t\t{Trapped, \"trapped\", true},\n\t\t{OutOfFuel, \"out of fuel\", true},\n\t\t{Status(99), \"unknown\", true},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, tc.s.String())\n\t\tuassert.Equal(t, tc.done, tc.s.Done())\n\t}\n}\n\nfunc TestMeterCharge(t *testing.T) {\n\tm := NewMeter(10)\n\tuassert.True(t, m.Charge(4))\n\tuassert.Equal(t, int64(4), m.Used())\n\tuassert.Equal(t, int64(6), m.Remaining())\n\n\t// A charge that does not fit spends nothing, so the caller can stop\n\t// before the instruction it cannot pay for.\n\tuassert.False(t, m.Charge(7))\n\tuassert.Equal(t, int64(4), m.Used())\n\n\tuassert.True(t, m.Charge(6))\n\tuassert.True(t, m.Exhausted())\n\tuassert.False(t, m.Charge(1))\n}\n\nfunc TestMeterUnmetered(t *testing.T) {\n\tm := NewMeter(Unmetered)\n\tuassert.True(t, m.Charge(1 \u003c\u003c 40))\n\tuassert.False(t, m.Exhausted())\n\tuassert.Equal(t, Unmetered, m.Remaining())\n}\n\nfunc TestMeterZeroBudget(t *testing.T) {\n\tm := NewMeter(0)\n\tuassert.True(t, m.Exhausted())\n\tuassert.False(t, m.Charge(1))\n\tuassert.Equal(t, int64(0), m.Used())\n}\n\nfunc TestCodecRoundTrip(t *testing.T) {\n\tw := NewWriter(0)\n\tw.Byte(0xab)\n\tw.Uint32(0xdeadbeef)\n\tw.Uint64(0x0102030405060708)\n\tw.Int(-1234567)\n\tw.Int(0)\n\tw.Int(1234567)\n\tw.Bytes([]byte{0, 1, 2, 255})\n\tw.String(\"gno.land\")\n\n\tr := NewReader(w.Out())\n\tuassert.Equal(t, uint64(0xab), uint64(r.Byte()))\n\tuassert.Equal(t, uint64(0xdeadbeef), uint64(r.Uint32()))\n\tuassert.Equal(t, uint64(0x0102030405060708), r.Uint64())\n\tuassert.Equal(t, int64(-1234567), r.Int())\n\tuassert.Equal(t, int64(0), r.Int())\n\tuassert.Equal(t, int64(1234567), r.Int())\n\tuassert.Equal(t, 4, len(r.Bytes()))\n\tuassert.Equal(t, \"gno.land\", r.String())\n\tuassert.NoError(t, r.Err())\n\tuassert.Equal(t, 0, r.Remaining())\n}\n\nfunc TestCodecIsCanonical(t *testing.T) {\n\t// The same state must always produce the same bytes: a snapshot is\n\t// consensus state, so two nodes encoding it differently is a fork.\n\tbuild := func() []byte {\n\t\tw := NewWriter(0)\n\t\tw.Int(-7)\n\t\tw.String(\"x\")\n\t\tw.Uint32(9)\n\t\treturn w.Out()\n\t}\n\tuassert.Equal(t, string(build()), string(build()))\n}\n\nfunc TestCodecTruncated(t *testing.T) {\n\tr := NewReader([]byte{1, 2})\n\tr.Uint64()\n\tuassert.ErrorIs(t, r.Err(), ErrTruncated)\n\t// Once latched, every later read is a zero value and the error stands.\n\tuassert.Equal(t, \"\", r.String())\n\tuassert.ErrorIs(t, r.Err(), ErrTruncated)\n}\n\nfunc TestCodecBytesAreCopied(t *testing.T) {\n\tw := NewWriter(0)\n\tw.Bytes([]byte{1, 2, 3})\n\tbuf := w.Out()\n\tr := NewReader(buf)\n\tgot := r.Bytes()\n\tbuf[len(buf)-1] = 99 // mutate the snapshot under the reader\n\tuassert.Equal(t, 3, len(got))\n\tuassert.Equal(t, uint64(3), uint64(got[2]))\n}\n\nfunc TestTestHostStorage(t *testing.T) {\n\th := NewTestHost()\n\tuassert.Equal(t, 0, len(h.Get([]byte(\"missing\"))))\n\n\th.Set([]byte{0, 1}, []byte(\"zero-prefixed\"))\n\th.Set([]byte(\"k\"), []byte(\"v\"))\n\tuassert.Equal(t, \"zero-prefixed\", string(h.Get([]byte{0, 1})))\n\tuassert.Equal(t, \"v\", string(h.Get([]byte(\"k\"))))\n\n\t// Keys are hex so a zero byte survives, and sorted so a test can pin\n\t// them.\n\tkeys := h.Keys()\n\tuassert.Equal(t, 2, len(keys))\n\tuassert.Equal(t, \"0001\", keys[0])\n\tuassert.Equal(t, \"6b\", keys[1])\n}\n\nfunc TestTestHostStorageIsCopied(t *testing.T) {\n\th := NewTestHost()\n\tval := []byte(\"abc\")\n\th.Set([]byte(\"k\"), val)\n\tval[0] = 'z'\n\tuassert.Equal(t, \"abc\", string(h.Get([]byte(\"k\"))))\n\n\tgot := h.Get([]byte(\"k\"))\n\tgot[0] = 'z'\n\tuassert.Equal(t, \"abc\", string(h.Get([]byte(\"k\"))))\n}\n\nfunc TestTestHostSendNeedsAGrant(t *testing.T) {\n\tto := address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\n\th := NewTestHost()\n\tuassert.ErrorIs(t, h.Send(to, 100), ErrNotGranted)\n\tuassert.Equal(t, 0, len(h.Sends()))\n\n\th.Grant(150)\n\tuassert.NoError(t, h.Send(to, 100))\n\tuassert.Equal(t, 1, len(h.Sends()))\n\tuassert.Equal(t, int64(100), h.Sends()[0].Amount)\n\n\t// The grant is a budget, not a switch.\n\tuassert.ErrorIs(t, h.Send(to, 100), ErrNotGranted)\n\tuassert.NoError(t, h.Send(to, 50))\n}\n\nfunc TestTestHostEventsAndInput(t *testing.T) {\n\th := NewTestHost().WithInput([]byte(\"hi\")).WithHeight(42).WithTime(1700000000)\n\tuassert.Equal(t, \"hi\", string(h.Input()))\n\tuassert.Equal(t, int64(42), h.Height())\n\tuassert.Equal(t, int64(1700000000), h.Now())\n\n\th.Emit(\"run\", \"id\", \"1\", \"status\", \"halted\")\n\th.Emit(\"odd\", \"dangling\")\n\tuassert.Equal(t, 2, len(h.Events()))\n\tuassert.Equal(t, \"run id=1 status=halted\", h.Events()[0])\n\tuassert.Equal(t, \"odd\", h.Events()[1]) // odd trailing element dropped\n}\n\nfunc TestInstanceRunsToCompletion(t *testing.T) {\n\tinst := NewInstance(\"1\", address(\"g1x\"), \"counter\", []byte(\"5\"), Unmetered)\n\th := NewTestHost()\n\tuassert.NoError(t, inst.Run(\u0026counter{total: 5}, h, Unmetered))\n\tuassert.Equal(t, \"halted\", inst.Status.String())\n\tuassert.Equal(t, int64(5), inst.FuelUsed)\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, \"abcde\", h.OutString())\n}\n\nfunc TestInstanceResumesAcrossSlices(t *testing.T) {\n\t// The property that makes a guest program a contract: five slices of\n\t// one unit must equal one slice of five.\n\tinst := NewInstance(\"1\", address(\"g1x\"), \"counter\", []byte(\"5\"), Unmetered)\n\th := NewTestHost()\n\tfor i := 0; i \u003c 5; i++ {\n\t\t// A realm holds bytes, not a machine: every slice loads a fresh\n\t\t// one from the program and lets Restore carry the state over.\n\t\tuassert.NoError(t, inst.Run(\u0026counter{total: 5}, h, 1))\n\t}\n\tuassert.Equal(t, \"halted\", inst.Status.String())\n\tuassert.Equal(t, int64(5), inst.FuelUsed)\n\tuassert.Equal(t, int64(5), inst.Slices)\n\tuassert.Equal(t, \"abcde\", h.OutString())\n}\n\nfunc TestInstanceStopsAtItsBudget(t *testing.T) {\n\tinst := NewInstance(\"1\", address(\"g1x\"), \"counter\", []byte(\"10\"), 3)\n\th := NewTestHost()\n\tuassert.NoError(t, inst.Run(\u0026counter{total: 10}, h, Unmetered))\n\tuassert.Equal(t, \"out of fuel\", inst.Status.String())\n\tuassert.Equal(t, int64(3), inst.FuelUsed)\n\tuassert.Equal(t, int64(0), inst.Remaining())\n\tuassert.Equal(t, \"abc\", h.OutString())\n\n\t// A second call has nothing to spend and says so instead of looping.\n\tuassert.ErrorIs(t, inst.Run(\u0026counter{}, h, Unmetered), ErrBudgetExhausted)\n}\n\nfunc TestInstanceSliceClamps(t *testing.T) {\n\tinst := NewInstance(\"1\", address(\"g1x\"), \"counter\", nil, 10)\n\tinst.FuelUsed = 7\n\tuassert.Equal(t, int64(3), inst.Slice(100))\n\tuassert.Equal(t, int64(2), inst.Slice(2))\n\tuassert.Equal(t, int64(3), inst.Slice(Unmetered))\n\n\topen := NewInstance(\"2\", address(\"g1x\"), \"counter\", nil, Unmetered)\n\tuassert.Equal(t, int64(5), open.Slice(5))\n\tuassert.Equal(t, Unmetered, open.Slice(Unmetered))\n}\n\nfunc TestInstanceRejectsABadSnapshot(t *testing.T) {\n\tinst := NewInstance(\"1\", address(\"g1x\"), \"counter\", []byte(\"5\"), Unmetered)\n\tinst.Snapshot = []byte{1, 2, 3} // too short for the counter's three fields\n\terr := inst.Run(\u0026counter{}, NewTestHost(), Unmetered)\n\tuassert.ErrorIs(t, err, ErrTruncated)\n\t// The instance is untouched: a snapshot that cannot be decoded costs\n\t// gas but never corrupts the stored program.\n\tuassert.Equal(t, int64(0), inst.Slices)\n\tuassert.Equal(t, \"5\", string(inst.Program))\n}\n\nfunc TestStore(t *testing.T) {\n\ts := NewStore()\n\tuassert.Equal(t, 0, s.Size())\n\tuassert.Equal(t, true, s.Get(\"nope\") == nil)\n\n\ts.Set(NewInstance(\"001\", address(\"g1a\"), \"counter\", nil, Unmetered))\n\ts.Set(NewInstance(\"002\", address(\"g1b\"), \"counter\", nil, Unmetered))\n\ts.Set(NewInstance(\"003\", address(\"g1c\"), \"counter\", nil, Unmetered))\n\tuassert.Equal(t, 3, s.Size())\n\tuassert.Equal(t, \"002\", s.Get(\"002\").ID)\n\n\tids := \"\"\n\ts.Iterate(func(i *Instance) bool { ids += i.ID + \" \"; return false })\n\tuassert.Equal(t, \"001 002 003 \", ids)\n\n\trev := \"\"\n\ts.ReverseIterate(func(i *Instance) bool { rev += i.ID + \" \"; return false })\n\tuassert.Equal(t, \"003 002 001 \", rev)\n\n\t// Early stop.\n\tfirst := \"\"\n\ts.Iterate(func(i *Instance) bool { first = i.ID; return true })\n\tuassert.Equal(t, \"001\", first)\n\n\tuassert.True(t, s.Remove(\"002\"))\n\tuassert.False(t, s.Remove(\"002\"))\n\tuassert.Equal(t, 2, s.Size())\n}\n\nfunc TestTrapReason(t *testing.T) {\n\tuassert.Equal(t, \"boom\", TrapReason(\u0026counter{trap: \"boom\"}))\n\tuassert.Equal(t, \"\", TrapReason(\u0026counter{}))\n}\n"}]},"send":"","max_deposit":"15000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wiki","path":"gno.land/p/moul/x/wiki/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/wiki/v0`\n\nA Wikipedia-shaped wiki engine: namespaced titles, an append-only revision\nchain, wikilinks with backlinks, categories, redirects, protection levels,\nper-page discussion threads, line diffs, and markdown rendering.\n\nPure: no realm globals, no chain imports. Every mutating call takes the author\naddress, the wall clock and the block height from its caller, so the engine is\nunit-testable off-chain and the realm keeps all the authority.\n\nLive demo: [`gno.land/r/moul/x/wiki/v0`](../../../../../r/moul/x/wiki).\n\n## The storage model\n\nA realm write locks a storage deposit proportional to the bytes it adds\n(100ugnot per byte, `gnolang/gno#6171`). A wiki that kept every revision in\nfull would therefore charge its editors rent on the whole history forever: at\n5 KB per revision that is 0.5 GNOT locked per edit, permanently.\n\nThis engine keeps a **content-addressed spine plus a bounded body window**:\n\n| kept forever, per revision | kept only inside the window |\n|---|---|\n| id, parent, kind, author, time, height, summary, byte size, **SHA-256 of the body**, minor flag | the body text |\n\nRoughly 200 bytes per revision regardless of article size, plus the bodies of\nthe newest `Retention` revisions of each page (3 by default).\n\nAn evicted body is not lost. Its bytes were an argument of the transaction\nthat wrote it, so they are still in the chain's transaction history, and the\nretained hash proves which bytes were the real ones. The realm stops paying\nrent for deep history; the archive lives where archives belong. What you lose\nis the ability to diff or revert to an evicted revision from inside the realm,\nand both failures are explicit (`ErrBodyEvicted`) rather than silent.\n\n`Purge` evicts every body of a page at once and returns the bytes released. It\nis the lever for content that must stop being served out of realm state; it\ncannot and does not remove the transactions that wrote it.\n\n## Who gets the deposit back\n\nNot who paid it. Verified in `processStorageDeposit`\n(`gno.land/pkg/sdk/vm/keeper.go`, gno master, 2026-09-19):\n\n- A write sends the **caller's** ugnot to a per-realm deposit address and adds\n  to two realm-wide pools, `rlm.Deposit` and `rlm.Storage`. There is no\n  per-depositor accounting.\n- A release refunds `rlm.Deposit * released / rlm.Storage` (big-integer,\n  truncating, so dust accrues in the pool) to the **caller of the transaction\n  that frees the bytes**, at the realm's blended rate.\n- If ugnot is a restricted denom at the time, the refund goes to\n  `params.StorageFeeCollector` instead, not to any user.\n\nFor a wiki that inverts a comfortable assumption. Adding bytes costs the adder,\nbut **removing bytes pays the remover**. Replacing a long article with a short\none evicts an old body in the same transaction, so deletion can be profitable,\nand reverting the damage costs the good actor who reverts it. That asymmetry is\nwhy `Blank`, `Purge` and `HideComment` are steward-gated, and why the realm\nkeeps a ban list, protection levels and an optional cooldown rather than\nrelying on the deposit alone.\n\n## Rendering untrusted markdown\n\nArticle bodies are attacker-controlled markdown rendered by gnoweb, so the\nrender path has a fixed order:\n\n1. `sanitize.BlockRich` the body (`gno.land/p/nt/markdown/sanitize/v0`).\n2. **Then** rewrite the wikilinks.\n\nNot the other way around. The sanitizer escapes every `[`, so `[[Gno land]]`\nbecomes `\\[\\[Gno land\\]\\]` in its output; a rewriter that ran first would hand\nthe markdown links it just generated to the escaper and every link on the wiki\nwould render as literal text. That is why `ScanLinks` takes its delimiters as\nparameters: indexing scans the raw body, rendering scans the escaped one.\n\nThe blank lines `BlockRich` adds around its output are load-bearing, not\ncosmetic. A CommonMark HTML block of type 6 or 7 is not escaped in any mode,\nand without the surrounding blank line it would absorb the realm chrome\nappended after the body.\n\nTwo layers, two jobs: `sanitize` stops markdown **structure** injection, and\ngnoweb's own link extension stops **URL scheme** abuse (`javascript:` and\nfriends). Neither replaces the other.\n\nThe title charset is narrower than MediaWiki's for the same reason. `/`, `|`,\n`#`, `*`, `[`, `\u003c`, `?`, `%` and `\u0026` are rejected rather than escaped, which\nkeeps `Title.String`, `Title.Slug` and the rendered link byte-identical.\n`TestTitleSurvivesTheRenderPipeline` pins that coupling end to end.\n\n## Determinism and gas\n\n`Render` runs under `maxGasQuery` (3e9 in `gno.land/pkg/sdk/vm/keeper.go`),\nwhich a reader cannot raise, so an unbounded render makes a page permanently\nunreadable. Three bounds keep it away from that ceiling:\n\n- `MaxBody` (32 KiB) caps a revision, and therefore caps every render.\n- `DiffMaxLines` (80) caps the changed region a diff computes exactly. The\n  common prefix and suffix are trimmed first, so an ordinary edit to a long\n  article still diffs exactly; past the bound a diff degrades to a block\n  replacement instead of failing.\n- Histories, indexes and listings are paginated by the caller.\n\nMeasured with `gno test -v` on gno master.184 (2026-09-17): the diff of a 33 KB\nbody against itself plus one line costs 691M gas, and the article render of a\n33 KB body with links costs 693M, each about 23% of the ceiling.\n\nEverything else follows gno's determinism rules: no map iteration anywhere in a\nrender path, `avl` for every ordered index, and namespace keys padded by hand\nbecause `ufmt` has no width flags (`ufmt.Sprintf(\"%02d\", 7)` silently returns\n`\"7\"`, which would sort `User` between two main-namespace pages).\n\n## Discussion\n\nDiscussion is an append-only comment store attached to a page, not a `Talk:`\narticle. A talk page is an article, so whoever edits last can rewrite what\nsomeone else said, and moderating one bad message means editing the whole page.\nA comment store gives each message its own author, timestamp and moderation:\n`HideComment` clears one body and releases its bytes while the message stays in\nthe thread, marked as removed.\n\nReplies nest exactly one level (`MaxReplyDepth`). Deeper nesting needs\nrecursive rendering with no natural bound, which is the shape a query gas\nceiling punishes hardest. Comments are sanitized like article bodies but are\nnot a wikilink slot: brackets in a comment stay literal.\n\n## Wiki syntax\n\n| syntax | meaning |\n|---|---|\n| `[[Target]]` | link, rendered from the canonical title |\n| `[[Target\\|label]]` | link with a display label |\n| `[[Category:Name]]` | join a category; removed from the text flow |\n| `[[:Category:Name]]` | link to the category instead of joining it |\n| `#REDIRECT [[Target]]` on line 1 | redirect, followed one hop only |\n\nLinks to pages that do not exist yet are still indexed, so creating a page\nimmediately knows who was already pointing at it.\n\n## Known limits\n\n- `Page.Revision(id)` is a linear scan of the page's history, and so is\n  comment lookup within a thread.\n- Redirects are followed one hop; chains are not resolved.\n- Templates and transclusion are not implemented.\n- There is no full-text search, and there cannot be a cheap one on chain.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/wiki/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/wiki/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"diff.gno","body":"package wiki\n\nimport \"strings\"\n\n// DiffOp is what happened to one line between two revisions.\ntype DiffOp uint8\n\nconst (\n\tOpEqual DiffOp = iota\n\tOpInsert\n\tOpDelete\n)\n\n// DiffLine is one line of a rendered diff.\ntype DiffLine struct {\n\tOp   DiffOp\n\tText string\n}\n\n// DiffMaxLines bounds the changed region a diff will compute exactly.\n//\n// The cost of an LCS over the changed region is O(n*m), and this runs inside\n// vm/qrender, which has a gas ceiling a reader cannot raise. 80 lines caps the\n// table at 6,400 cells; beyond it, a diff degrades to \"this block was replaced\"\n// rather than making the page unrenderable. Both revisions are still available\n// in full through the raw view, so nothing is hidden by the degradation.\nconst DiffMaxLines = 80\n\n// TODO(#140 Q5): decide whether diffing belongs on chain at all. Both options\n// are still open: keep this bounded server-side diff, or drop it and let\n// clients diff two /raw responses themselves, which costs the chain nothing\n// and removes DiffMaxLines entirely. Keeping it for now because a diff a\n// reader can reach from a plain URL is most of what makes a history readable,\n// and 691M gas at the body cap leaves room. Revisit if MaxBody ever rises.\n\n// DiffLines compares two bodies line by line.\n//\n// exact reports whether the result is a real line diff. When it is false the\n// changed region was larger than DiffMaxLines and the result is the coarse\n// form: every removed line, then every added line.\nfunc DiffLines(older, newer string) (out []DiffLine, exact bool) {\n\ta := splitLines(older)\n\tb := splitLines(newer)\n\n\t// Trim the common prefix and suffix. Ordinary wiki edits touch a few\n\t// lines of a long article, so this alone brings almost every real diff\n\t// under the exact-computation bound.\n\thead := 0\n\tfor head \u003c len(a) \u0026\u0026 head \u003c len(b) \u0026\u0026 a[head] == b[head] {\n\t\thead++\n\t}\n\ttailA, tailB := len(a), len(b)\n\tfor tailA \u003e head \u0026\u0026 tailB \u003e head \u0026\u0026 a[tailA-1] == b[tailB-1] {\n\t\ttailA--\n\t\ttailB--\n\t}\n\n\tmidA := a[head:tailA]\n\tmidB := b[head:tailB]\n\n\tout = []DiffLine{}\n\tfor _, l := range a[:head] {\n\t\tout = append(out, DiffLine{OpEqual, l})\n\t}\n\n\texact = len(midA) \u003c= DiffMaxLines \u0026\u0026 len(midB) \u003c= DiffMaxLines\n\tif exact {\n\t\tout = append(out, lcsDiff(midA, midB)...)\n\t} else {\n\t\tfor _, l := range midA {\n\t\t\tout = append(out, DiffLine{OpDelete, l})\n\t\t}\n\t\tfor _, l := range midB {\n\t\t\tout = append(out, DiffLine{OpInsert, l})\n\t\t}\n\t}\n\n\tfor _, l := range a[tailA:] {\n\t\tout = append(out, DiffLine{OpEqual, l})\n\t}\n\treturn out, exact\n}\n\n// DiffStat counts added and removed lines.\nfunc DiffStat(lines []DiffLine) (added, removed int) {\n\tfor _, l := range lines {\n\t\tswitch l.Op {\n\t\tcase OpInsert:\n\t\t\tadded++\n\t\tcase OpDelete:\n\t\t\tremoved++\n\t\t}\n\t}\n\treturn added, removed\n}\n\n// lcsDiff is the textbook longest-common-subsequence diff, bounded by the\n// caller to DiffMaxLines on each side.\nfunc lcsDiff(a, b []string) []DiffLine {\n\tn, m := len(a), len(b)\n\tif n == 0 \u0026\u0026 m == 0 {\n\t\treturn []DiffLine{}\n\t}\n\t// table[i][j] is the LCS length of a[i:] and b[j:].\n\ttable := make([][]int, n+1)\n\tfor i := range table {\n\t\ttable[i] = make([]int, m+1)\n\t}\n\tfor i := n - 1; i \u003e= 0; i-- {\n\t\tfor j := m - 1; j \u003e= 0; j-- {\n\t\t\tif a[i] == b[j] {\n\t\t\t\ttable[i][j] = table[i+1][j+1] + 1\n\t\t\t} else if table[i+1][j] \u003e= table[i][j+1] {\n\t\t\t\ttable[i][j] = table[i+1][j]\n\t\t\t} else {\n\t\t\t\ttable[i][j] = table[i][j+1]\n\t\t\t}\n\t\t}\n\t}\n\n\tout := []DiffLine{}\n\ti, j := 0, 0\n\tfor i \u003c n \u0026\u0026 j \u003c m {\n\t\tswitch {\n\t\tcase a[i] == b[j]:\n\t\t\tout = append(out, DiffLine{OpEqual, a[i]})\n\t\t\ti++\n\t\t\tj++\n\t\tcase table[i+1][j] \u003e= table[i][j+1]:\n\t\t\tout = append(out, DiffLine{OpDelete, a[i]})\n\t\t\ti++\n\t\tdefault:\n\t\t\tout = append(out, DiffLine{OpInsert, b[j]})\n\t\t\tj++\n\t\t}\n\t}\n\tfor ; i \u003c n; i++ {\n\t\tout = append(out, DiffLine{OpDelete, a[i]})\n\t}\n\tfor ; j \u003c m; j++ {\n\t\tout = append(out, DiffLine{OpInsert, b[j]})\n\t}\n\treturn out\n}\n\nfunc splitLines(s string) []string {\n\tif s == \"\" {\n\t\treturn []string{}\n\t}\n\ts = strings.TrimSuffix(s, \"\\n\")\n\treturn strings.Split(s, \"\\n\")\n}\n"},{"name":"diff_test.gno","body":"package wiki\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// render turns a diff into the compact \"+a -b =c\" form the tests assert on.\nfunc render(lines []DiffLine) string {\n\tvar b strings.Builder\n\tfor _, l := range lines {\n\t\tswitch l.Op {\n\t\tcase OpInsert:\n\t\t\tb.WriteString(\"+\")\n\t\tcase OpDelete:\n\t\t\tb.WriteString(\"-\")\n\t\tdefault:\n\t\t\tb.WriteString(\"=\")\n\t\t}\n\t\tb.WriteString(l.Text)\n\t\tb.WriteString(\";\")\n\t}\n\treturn b.String()\n}\n\nfunc TestDiffLines(t *testing.T) {\n\tcases := []struct {\n\t\tname     string\n\t\told, new string\n\t\twant     string\n\t}{\n\t\t{\"identical\", \"a\\nb\\n\", \"a\\nb\\n\", \"=a;=b;\"},\n\t\t{\"append\", \"a\\n\", \"a\\nb\\n\", \"=a;+b;\"},\n\t\t{\"prepend\", \"b\\n\", \"a\\nb\\n\", \"+a;=b;\"},\n\t\t{\"delete\", \"a\\nb\\n\", \"a\\n\", \"=a;-b;\"},\n\t\t{\"replace middle\", \"a\\nb\\nc\\n\", \"a\\nx\\nc\\n\", \"=a;-b;+x;=c;\"},\n\t\t{\"from empty\", \"\", \"a\\n\", \"+a;\"},\n\t\t{\"to empty\", \"a\\n\", \"\", \"-a;\"},\n\t\t{\"both empty\", \"\", \"\", \"\"},\n\t\t{\"no trailing newline\", \"a\\nb\", \"a\\nc\", \"=a;-b;+c;\"},\n\t}\n\tfor _, tc := range cases {\n\t\tgot, exact := DiffLines(tc.old, tc.new)\n\t\tuassert.True(t, exact, tc.name+\" must be exact\")\n\t\tuassert.Equal(t, tc.want, render(got), tc.name)\n\t}\n}\n\nfunc TestDiffStat(t *testing.T) {\n\tlines, _ := DiffLines(\"a\\nb\\nc\\n\", \"a\\nx\\ny\\nc\\n\")\n\tadded, removed := DiffStat(lines)\n\tuassert.Equal(t, 2, added)\n\tuassert.Equal(t, 1, removed)\n}\n\n// TestDiffCommonPrefixKeepsLongArticlesExact is the property that makes the\n// DiffMaxLines bound usable in practice: a one-line edit to a 500-line article\n// still diffs exactly, because only the changed region is fed to the LCS.\nfunc TestDiffCommonPrefixKeepsLongArticlesExact(t *testing.T) {\n\tvar b strings.Builder\n\tfor i := 0; i \u003c 500; i++ {\n\t\tb.WriteString(\"line\\n\")\n\t}\n\told := b.String()\n\tupdated := old + \"added\\n\"\n\n\tlines, exact := DiffLines(old, updated)\n\tuassert.True(t, exact, \"a one-line change to a 500-line article must diff exactly\")\n\tadded, removed := DiffStat(lines)\n\tuassert.Equal(t, 1, added)\n\tuassert.Equal(t, 0, removed)\n}\n\n// TestDiffDegradesInsteadOfBlowingTheGasBudget locks the documented fallback:\n// past DiffMaxLines the diff becomes a block replacement rather than an\n// unrenderable page.\nfunc TestDiffDegradesInsteadOfBlowingTheGasBudget(t *testing.T) {\n\tvar a, b strings.Builder\n\tfor i := 0; i \u003c DiffMaxLines+1; i++ {\n\t\ta.WriteString(\"old\\n\")\n\t\tb.WriteString(\"new\\n\")\n\t}\n\tlines, exact := DiffLines(a.String(), b.String())\n\tuassert.False(t, exact, \"past the bound the diff must report itself inexact\")\n\tadded, removed := DiffStat(lines)\n\tuassert.Equal(t, DiffMaxLines+1, added)\n\tuassert.Equal(t, DiffMaxLines+1, removed)\n}\n"},{"name":"doc.gno","body":"// Package wiki is a Wikipedia-shaped wiki engine for gno.land: namespaced\n// titles, an append-only revision chain, wikilinks with backlinks, categories,\n// redirects, protection levels, line diffs, and markdown rendering.\n//\n// It is pure: no realm globals, no chain imports. Every call takes the context\n// it needs (author address, wall clock, block height) from the caller, so the\n// whole engine is unit-testable off-chain. The live demo realm is\n// gno.land/r/moul/x/wiki/v0.\n//\n// # Storage model\n//\n// A realm write locks a storage deposit proportional to the bytes it adds\n// (100ugnot per byte since gnolang/gno#6171), so a wiki that kept every\n// revision in full would charge its editors for the whole history forever.\n// This engine instead stores a content-addressed spine plus a bounded body\n// window:\n//\n//   - Every revision keeps its metadata permanently: id, parent, author,\n//     time, height, summary, byte size, and the SHA-256 of the body. That is\n//     roughly 200 bytes, independent of article size.\n//   - Only the newest Retention revisions of a page keep their body. Older\n//     bodies are evicted (set to \"\"), which releases their deposit.\n//\n// An evicted body is not lost: its bytes were an argument of the transaction\n// that wrote it, so they remain in the chain's transaction history, and the\n// retained hash proves which bytes were the real ones. The realm stops paying\n// rent for deep history; the archive lives where archives belong.\n//\n// # Untrusted markdown\n//\n// Article bodies are attacker-controlled markdown. Render passes every body\n// through gno.land/p/nt/markdown/sanitize/v0 before any wikilink rewriting,\n// never after: sanitize escapes \"[\" to \"\\\\[\", so a rewriter that ran first\n// would hand its own generated links to the escaper. See links.gno.\npackage wiki\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/wiki/v0\"\ngno = \"0.9\"\n"},{"name":"limits_test.gno","body":"package wiki\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// maxLines is how many typical lines fit in DefaultMaxBody: 32 KiB at 43\n// bytes per line.\nconst maxLines = 758\n\nfunc buildLines(n int) string {\n\tvar b strings.Builder\n\tfor i := 0; i \u003c n; i++ {\n\t\tb.WriteString(\"some article line of moderate length here.\\n\")\n\t}\n\treturn b.String()\n}\n\n// TestWorstCaseRendersStayWithinTheQueryBudget exercises the two render paths\n// at the largest body MaxBody admits.\n//\n// vm/qrender runs under a fixed ceiling (maxGasQuery = 3e9 in\n// gno.land/pkg/sdk/vm/keeper.go), which a reader cannot raise, so a render\n// that exceeds it makes the page permanently unreadable. Measured with\n// `gno test -v` on gno master.184 (2026-09-17):\n//\n//\tdiff of a 33 KB body against itself plus one line    691M gas   23% of the ceiling\n//\tarticle render of a 33 KB body with links            693M gas   23% of the ceiling\n//\n// gno test reports gas per test function but a test cannot assert on it, so\n// this test pins the shape, not the number: it fails if either path starts\n// panicking or truncating at the limit. Re-measure with `gno test -v` and\n// update the table when either path changes.\nfunc TestWorstCaseRendersStayWithinTheQueryBudget(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tbody := buildLines(maxLines-2) + \"see [[Other page]]\\n[[Category:Big]]\\n\"\n\tuassert.True(t, len(body) \u003c DefaultMaxBody, \"the fixture must fit in MaxBody\")\n\n\tnow, h := at(1)\n\t_, err := w.Edit(alice, now, h, \"Big\", body, \"\", false)\n\tuassert.NoError(t, err)\n\n\tp, err := w.Page(\"Big\")\n\tuassert.NoError(t, err)\n\n\tc := Ctx{Base: \"/r/moul/x/wiki/v0\", Exists: w.Exists}\n\tuassert.True(t, len(RenderArticle(c, w, p, nil)) \u003e len(body), \"the article must render in full\")\n\n\tnow, h = at(2)\n\t_, err = w.Edit(alice, now, h, \"Big\", body+\"added\\n\", \"\", false)\n\tuassert.NoError(t, err)\n\n\thist := p.History(0, 2)\n\tout := RenderDiff(c, p, hist[1], hist[0])\n\tuassert.True(t, strings.Contains(out, \"+1 −0 lines\"), \"a one-line append to a 32 KiB body diffs exactly\")\n}\n"},{"name":"links.gno","body":"package wiki\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Link is one wikilink occurrence in a body.\ntype Link struct {\n\tTarget   string // target text as written, before ParseTitle\n\tLabel    string // display text; \"\" means render the target\n\tExplicit bool   // written [[:Category:X]]: link to the category, do not join it\n\tStart    int    // byte offset of the opening delimiter\n\tEnd      int    // byte offset just past the closing delimiter\n}\n\n// ScanLinks finds every [[target|label]] occurrence delimited by open and\n// close.\n//\n// The delimiters are parameters because the same syntax has to be found twice\n// with different bytes. Indexing reads the raw body, where a link is\n// \"[[X]]\". Rendering reads the body after sanitize.BlockRich, where the very\n// same link is \"\\[\\[X\\]\\]\" because the sanitizer escapes every \"[\". Rendering\n// must sanitize first and rewrite second: a rewriter that ran first would\n// hand the markdown links it just generated to the escaper, and every link on\n// the wiki would render as literal text.\n//\n// A link whose inner text spans a newline or is empty is not a link. When a\n// nearer opener appears inside the inner text, scanning restarts from it, so\n// \"[[a [[b]]\" yields b rather than a mis-parsed a.\nfunc ScanLinks(s, openTok, closeTok string) []Link {\n\tout := []Link{}\n\ti := 0\n\tfor i \u003c len(s) {\n\t\ta := strings.Index(s[i:], openTok)\n\t\tif a \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\ta += i\n\t\trest := a + len(openTok)\n\t\tb := strings.Index(s[rest:], closeTok)\n\t\tif b \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\tb += rest\n\n\t\tinner := s[rest:b]\n\t\tif n := strings.Index(inner, openTok); n \u003e= 0 {\n\t\t\ti = rest + n\n\t\t\tcontinue\n\t\t}\n\t\ti = b + len(closeTok)\n\t\tif inner == \"\" || strings.Contains(inner, \"\\n\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tl := Link{Start: a, End: i}\n\t\tif p := strings.Index(inner, \"|\"); p \u003e= 0 {\n\t\t\tl.Target = strings.TrimSpace(inner[:p])\n\t\t\tl.Label = strings.TrimSpace(inner[p+1:])\n\t\t} else {\n\t\t\tl.Target = strings.TrimSpace(inner)\n\t\t}\n\t\tif strings.HasPrefix(l.Target, \":\") {\n\t\t\tl.Explicit = true\n\t\t\tl.Target = strings.TrimSpace(l.Target[1:])\n\t\t}\n\t\tif l.Target == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, l)\n\t}\n\treturn out\n}\n\n// redirectTarget returns the canonical title a body redirects to, or \"\".\n// The syntax is MediaWiki's: \"#REDIRECT [[Target]]\" on the first line.\nfunc redirectTarget(body string) string {\n\tline := body\n\tif i := strings.Index(line, \"\\n\"); i \u003e= 0 {\n\t\tline = line[:i]\n\t}\n\tline = strings.TrimSpace(line)\n\tif len(line) \u003c len(\"#REDIRECT\") || !strings.EqualFold(line[:len(\"#REDIRECT\")], \"#REDIRECT\") {\n\t\treturn \"\"\n\t}\n\tlinks := ScanLinks(line, \"[[\", \"]]\")\n\tif len(links) == 0 {\n\t\treturn \"\"\n\t}\n\tt, err := ParseTitle(links[0].Target)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn t.String()\n}\n\n// Ctx carries what rendering needs from the realm: where the realm lives, and\n// which titles exist. Its function fields are read during a single Render call\n// and never stored, so no closure is ever persisted.\ntype Ctx struct {\n\tBase   string            // realm path prefix, e.g. \"/r/moul/x/wiki/v0\"\n\tExists func(Title) bool // nil treats every title as existing\n}\n\nfunc (c Ctx) exists(t Title) bool {\n\tif c.Exists == nil {\n\t\treturn true\n\t}\n\treturn c.Exists(t)\n}\n\n// URL is the render path of a title under this realm.\nfunc (c Ctx) URL(t Title) string { return c.Sub(t, \"\") }\n\n// Sub is the render path of a sub-route of a title, e.g. \"history\".\nfunc (c Ctx) Sub(t Title, route string) string {\n\tu := c.Base + \":\" + t.Slug()\n\tif route != \"\" {\n\t\tu += \"/\" + route\n\t}\n\treturn escapeURL(u)\n}\n\n// SpecialURL is the render path of a Special: page.\nfunc (c Ctx) SpecialURL(name, query string) string {\n\tu := c.Base + \":Special:\" + name\n\tif query != \"\" {\n\t\tu += \"?\" + query\n\t}\n\treturn escapeURL(u)\n}\n\n// escapeURL percent-encodes the characters a title may contain that would\n// otherwise terminate a markdown link destination or split a path. Titles\n// admit \"(\", \")\", \" \", \"'\" and \",\" (see validTitleRune), and an unencoded \")\"\n// ends the \"(...)\" of a markdown link at the first occurrence, which turns\n// [[Mercury (planet)]] into a broken link plus stray text.\nfunc escapeURL(u string) string {\n\tr := strings.NewReplacer(\n\t\t\" \", \"%20\",\n\t\t\"(\", \"%28\",\n\t\t\")\", \"%29\",\n\t\t\"'\", \"%27\",\n\t\t\",\", \"%2C\",\n\t)\n\treturn sanitize.URL(r.Replace(u))\n}\n\n// RewriteLinks turns the wikilinks of an already-sanitized body into markdown\n// links. Category declarations are removed from the flow: membership is shown\n// by the rendered footer, not inline, which is also what MediaWiki does.\n//\n// s MUST be the output of sanitize.BlockRich or sanitize.Block, and open/close\n// MUST be the escaped delimiters. Passing a raw body here would emit links\n// built from unsanitized bytes.\nfunc RewriteLinks(c Ctx, s string) string {\n\tlinks := ScanLinks(s, `\\[\\[`, `\\]\\]`)\n\tif len(links) == 0 {\n\t\treturn s\n\t}\n\tvar out strings.Builder\n\tprev := 0\n\tfor _, l := range links {\n\t\tout.WriteString(s[prev:l.Start])\n\t\tprev = l.End\n\n\t\tt, err := ParseTitle(unescapeInline(l.Target))\n\t\tif err != nil {\n\t\t\t// Not a usable title: leave the sanitized text in place. It is\n\t\t\t// already escaped, so it renders as the literal brackets the\n\t\t\t// author typed.\n\t\t\tout.WriteString(s[l.Start:l.End])\n\t\t\tcontinue\n\t\t}\n\t\tif t.NS == NSCategory \u0026\u0026 !l.Explicit {\n\t\t\tcontinue\n\t\t}\n\t\tlabel := l.Label\n\t\tif label == \"\" {\n\t\t\tlabel = t.String()\n\t\t}\n\t\tif c.exists(t) {\n\t\t\tout.WriteString(\"[\" + label + \"](\" + c.URL(t) + \")\")\n\t\t} else {\n\t\t\t// A red link: the page does not exist yet. Point at the same\n\t\t\t// path, which renders the \"create this page\" stub.\n\t\t\tout.WriteString(\"[\" + label + \"](\" + c.URL(t) + \") ⁺\")\n\t\t}\n\t}\n\tout.WriteString(s[prev:])\n\treturn out.String()\n}\n\n// unescapeInline undoes the backslash escaping the sanitizer applies inside a\n// link's inner text, so ParseTitle sees the title the author typed.\nfunc unescapeInline(s string) string {\n\tif !strings.Contains(s, `\\`) {\n\t\treturn s\n\t}\n\tvar b strings.Builder\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif s[i] == '\\\\' \u0026\u0026 i+1 \u003c len(s) {\n\t\t\ti++\n\t\t}\n\t\tb.WriteByte(s[i])\n\t}\n\treturn b.String()\n}\n"},{"name":"links_test.gno","body":"package wiki\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestScanLinks(t *testing.T) {\n\tcases := []struct {\n\t\tname      string\n\t\tin        string\n\t\ttargets   []string\n\t\tlabels    []string\n\t\texplicits []bool\n\t}{\n\t\t{\"none\", \"plain text\", nil, nil, nil},\n\t\t{\"one\", \"see [[Gno land]] here\", []string{\"Gno land\"}, []string{\"\"}, []bool{false}},\n\t\t{\"labelled\", \"[[Gno land|the chain]]\", []string{\"Gno land\"}, []string{\"the chain\"}, []bool{false}},\n\t\t{\"two\", \"[[A]] and [[B]]\", []string{\"A\", \"B\"}, []string{\"\", \"\"}, []bool{false, false}},\n\t\t{\"category\", \"[[Category:Chains]]\", []string{\"Category:Chains\"}, []string{\"\"}, []bool{false}},\n\t\t{\"explicit category\", \"[[:Category:Chains]]\", []string{\"Category:Chains\"}, []string{\"\"}, []bool{true}},\n\t\t{\"whitespace is trimmed\", \"[[  A  |  b  ]]\", []string{\"A\"}, []string{\"b\"}, []bool{false}},\n\t\t{\"unclosed is not a link\", \"[[A\", nil, nil, nil},\n\t\t{\"empty is not a link\", \"[[]]\", nil, nil, nil},\n\t\t{\"newline inside is not a link\", \"[[A\\nB]]\", nil, nil, nil},\n\t\t{\"nested opener wins\", \"[[a [[b]]\", []string{\"b\"}, []string{\"\"}, []bool{false}},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := ScanLinks(tc.in, \"[[\", \"]]\")\n\t\tif !uassert.Equal(t, len(tc.targets), len(got), tc.name) {\n\t\t\tcontinue\n\t\t}\n\t\tfor i, l := range got {\n\t\t\tuassert.Equal(t, tc.targets[i], l.Target, tc.name)\n\t\t\tuassert.Equal(t, tc.labels[i], l.Label, tc.name)\n\t\t\tuassert.Equal(t, tc.explicits[i], l.Explicit, tc.name)\n\t\t}\n\t}\n}\n\nfunc TestScanLinksOffsets(t *testing.T) {\n\tin := \"see [[A]] end\"\n\tgot := ScanLinks(in, \"[[\", \"]]\")\n\tuassert.Equal(t, 1, len(got))\n\tuassert.Equal(t, \"[[A]]\", in[got[0].Start:got[0].End])\n}\n\n// TestScanLinksAfterSanitize is the reason ScanLinks takes its delimiters as\n// parameters: the sanitizer escapes every \"[\", so the rendering pass has to\n// look for a different byte sequence than the indexing pass.\nfunc TestScanLinksAfterSanitize(t *testing.T) {\n\tescaped := sanitize.BlockRich(\"see [[Gno land|the chain]] here\\n\")\n\tuassert.Equal(t, 0, len(ScanLinks(escaped, \"[[\", \"]]\")),\n\t\t\"the raw delimiters must find nothing in sanitized text\")\n\tgot := ScanLinks(escaped, `\\[\\[`, `\\]\\]`)\n\tuassert.Equal(t, 1, len(got))\n\tuassert.Equal(t, \"Gno land\", got[0].Target)\n\tuassert.Equal(t, \"the chain\", got[0].Label)\n}\n\nfunc TestRedirectTarget(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"#REDIRECT [[Gno land]]\\n\", \"Gno land\"},\n\t\t{\"#redirect [[gno_land]]\", \"Gno land\"},\n\t\t{\"  #REDIRECT   [[User:Gno land]]  \\nrest\", \"User:Gno land\"},\n\t\t{\"not a redirect [[Gno land]]\", \"\"},\n\t\t{\"#REDIRECT no link\", \"\"},\n\t\t{\"#REDIRECT [[bad|title]]\", \"Bad\"},\n\t\t{\"text\\n#REDIRECT [[Gno land]]\", \"\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, redirectTarget(tc.in), tc.in)\n\t}\n}\n\nfunc TestRewriteLinks(t *testing.T) {\n\tc := Ctx{\n\t\tBase:   \"/r/moul/x/wiki/v0\",\n\t\tExists: func(tt Title) bool { return tt.Name == \"Gno land\" },\n\t}\n\n\tbody := sanitize.BlockRich(\"See [[Gno land]], [[Missing page]] and [[Gno land|the chain]].\\n\" +\n\t\t\"[[Category:Chains]]\\n\")\n\tgot := RewriteLinks(c, body)\n\n\tuassert.True(t, contains(got, \"[Gno land](/r/moul/x/wiki/v0:Gno_land)\"), \"existing page links plainly\")\n\tuassert.True(t, contains(got, \"[Missing page](/r/moul/x/wiki/v0:Missing_page) ⁺\"), \"a redlink is marked\")\n\tuassert.True(t, contains(got, \"[the chain](/r/moul/x/wiki/v0:Gno_land)\"), \"labels are honored\")\n\tuassert.False(t, contains(got, \"Category:Chains\"), \"category declarations leave the flow\")\n}\n\nfunc TestRewriteLinksEscapesURLs(t *testing.T) {\n\tc := Ctx{Base: \"/r/moul/x/wiki/v0\"}\n\tgot := RewriteLinks(c, sanitize.BlockRich(\"[[Mercury (planet)]]\\n\"))\n\t// An unescaped \")\" would terminate the markdown destination early and\n\t// leave \"planet))\" as visible text.\n\tuassert.True(t, contains(got, \"(/r/moul/x/wiki/v0:Mercury_%28planet%29)\"), got)\n}\n\nfunc TestRewriteLinksLeavesNonTitlesAlone(t *testing.T) {\n\tc := Ctx{Base: \"/r/moul/x/wiki/v0\"}\n\t// \"[[ ]]\" has no usable target, and \"[[a/b]]\" is not a legal title: both\n\t// must render as the literal text the author typed, never as a link.\n\tgot := RewriteLinks(c, sanitize.BlockRich(\"[[a/b]]\\n\"))\n\tuassert.True(t, contains(got, `\\[\\[a/b\\]\\]`), got)\n}\n\nfunc contains(haystack, needle string) bool {\n\tfor i := 0; i+len(needle) \u003c= len(haystack); i++ {\n\t\tif haystack[i:i+len(needle)] == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"},{"name":"page.gno","body":"package wiki\n\nimport (\n\t\"time\"\n\n\t\"gno.land/p/moul/ulist/v0\"\n)\n\n// Protection is a page's edit gate. The engine stores it and reports it; it\n// never enforces it, because authority belongs to the realm that owns the\n// wiki, not to a pure library. See Wiki.Edit.\ntype Protection uint8\n\nconst (\n\tOpen          Protection = iota // anyone the realm lets through\n\tSemiProtected                   // realm-defined trusted editors\n\tLocked                          // stewards only\n)\n\n// String returns the protection level's display name.\nfunc (p Protection) String() string {\n\tswitch p {\n\tcase SemiProtected:\n\t\treturn \"semi-protected\"\n\tcase Locked:\n\t\treturn \"locked\"\n\tdefault:\n\t\treturn \"open\"\n\t}\n}\n\n// ParseProtection maps a user-supplied level name onto a Protection.\nfunc ParseProtection(s string) (Protection, error) {\n\tswitch s {\n\tcase \"open\", \"\":\n\t\treturn Open, nil\n\tcase \"semi\", \"semi-protected\":\n\t\treturn SemiProtected, nil\n\tcase \"locked\":\n\t\treturn Locked, nil\n\t}\n\treturn Open, ErrBadProtection\n}\n\n// Page is one title's history plus the indexes derived from its current\n// revision. Revisions live in a ulist: append is O(1) and does not rewrite the\n// existing entries, which matters when a popular page accumulates thousands of\n// edits and every write would otherwise re-serialize the whole slice.\ntype Page struct {\n\tTitle      Title\n\tProtection Protection\n\tCreated    time.Time\n\tBlanked    bool // a steward blanked it; history is retained\n\n\trevs *ulist.List // *Revision, oldest first\n\thead *Revision\n\n\tredirect string   // target title, \"\" when this page is not a redirect\n\tlinks    []string // outgoing wikilink target keys of head\n\tcats     []string // category keys head belongs to\n}\n\n// Head returns the current revision, or nil for a page with no revisions.\nfunc (p *Page) Head() *Revision { return p.head }\n\n// NumRevisions returns how many revisions the page has.\nfunc (p *Page) NumRevisions() int { return p.revs.Size() }\n\n// Redirect returns the title this page redirects to, or \"\" if it does not.\nfunc (p *Page) Redirect() string { return p.redirect }\n\n// Body returns the current text and whether it is held on chain.\nfunc (p *Page) Body() (string, bool) {\n\tif p.head == nil {\n\t\treturn \"\", false\n\t}\n\treturn p.head.Body()\n}\n\n// Revision returns the revision with the given id, or nil.\nfunc (p *Page) Revision(id uint64) *Revision {\n\tvar found *Revision\n\tp.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {\n\t\tr := v.(*Revision)\n\t\tif r.ID == id {\n\t\t\tfound = r\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn found\n}\n\n// History returns up to count revisions, newest first, skipping the newest\n// offset of them.\nfunc (p *Page) History(offset, count int) []*Revision {\n\tout := []*Revision{}\n\tif count \u003c= 0 {\n\t\treturn out\n\t}\n\tsize := p.revs.Size()\n\t// Walk backwards: index size-1 is the newest.\n\tfor i := size - 1 - offset; i \u003e= 0 \u0026\u0026 len(out) \u003c count; i-- {\n\t\tout = append(out, p.revs.MustGet(i).(*Revision))\n\t}\n\treturn out\n}\n\n// Contributors returns the distinct authors of the page, oldest edit first.\nfunc (p *Page) Contributors() []address {\n\tseen := map[string]bool{}\n\tout := []address{}\n\tp.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {\n\t\tr := v.(*Revision)\n\t\tif !seen[r.Author.String()] {\n\t\t\tseen[r.Author.String()] = true\n\t\t\tout = append(out, r.Author)\n\t\t}\n\t\treturn false\n\t})\n\treturn out\n}\n"},{"name":"render.gno","body":"package wiki\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// DepositPerByte is the storage deposit a realm write locks per byte, in\n// ugnot (gnolang/gno#6171). It is used only to show a reader what a page\n// costs; the chain, not this package, does the accounting.\nconst DepositPerByte = 100\n\n// Action builds a transaction link for a realm function. The realm supplies\n// it (txlink.Realm(\"…\").Call is the usual value); a nil Action renders a page\n// with no edit controls, which is what an archived or read-only mirror wants.\ntype Action func(fn string, args ...string) string\n\n// RenderArticle renders a page for reading: the sanitized body with its\n// wikilinks resolved, a header identifying the current revision, and a footer\n// with categories and cost.\nfunc RenderArticle(c Ctx, w *Wiki, p *Page, act Action) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(p.Title.String()))\n\n\tif p.head == nil {\n\t\tout.WriteString(md.Paragraph(\"_This page has no revisions._\"))\n\t\treturn out.String()\n\t}\n\tout.WriteString(articleMeta(c, w, p, act))\n\n\tif p.Blanked {\n\t\tout.WriteString(md.Blockquote(\"This page was blanked. Its history is still on chain: \" +\n\t\t\tmd.Link(\"view history\", c.Sub(p.Title, \"history\"))))\n\t\treturn out.String()\n\t}\n\n\tbody, kept := p.Body()\n\tswitch {\n\tcase !kept:\n\t\tout.WriteString(md.Blockquote(\"The current revision's body is no longer held on chain. \" +\n\t\t\t\"Recover it from the transaction that wrote it and check it against `\" + p.head.ShortHash() + \"`.\"))\n\tcase p.redirect != \"\":\n\t\tout.WriteString(md.Paragraph(\"Redirects to \" + md.Link(p.redirect, escapeURL(c.Base+\":\"+strings.ReplaceAll(p.redirect, \" \", \"_\")))))\n\tdefault:\n\t\t// sanitize.BlockRich wraps its output in blank lines on both sides,\n\t\t// and that padding is load-bearing: a CommonMark HTML block of type\n\t\t// 6 or 7 is not escaped in any mode, and without the blank line it\n\t\t// would swallow the footer this function appends next. Do not trim\n\t\t// it to tidy the output.\n\t\tout.WriteString(RewriteLinks(c, sanitize.BlockRich(body)))\n\t}\n\n\tout.WriteString(articleFooter(c, w, p))\n\treturn out.String()\n}\n\nfunc articleMeta(c Ctx, w *Wiki, p *Page, act Action) string {\n\th := p.head\n\tparts := []string{\n\t\tufmt.Sprintf(\"rev %d\", h.ID),\n\t\th.Time.Format(\"2006-01-02 15:04\"),\n\t\t\"by \" + shortAddr(h.Author),\n\t}\n\tif p.Protection != Open {\n\t\tparts = append(parts, p.Protection.String())\n\t}\n\tline := strings.Join(parts, \" · \")\n\n\tnav := []string{\n\t\tmd.Link(\"history\", c.Sub(p.Title, \"history\")),\n\t\tmd.Link(\"source\", c.Sub(p.Title, \"raw\")),\n\t\tmd.Link(\"what links here\", c.SpecialURL(\"Backlinks\", \"page=\"+p.Title.Slug())),\n\t}\n\tif act != nil {\n\t\tnav = append(nav, md.Link(\"edit\", act(\"Edit\", \"title\", p.Title.String())))\n\t}\n\t// The count sits outside the link text on purpose: md.Link sanitizes its\n\t// label, so parentheses inside it would render as \"\\(1\\)\".\n\tnav = append(nav, md.Link(\"discussion\", c.Sub(p.Title, \"talk\"))+\n\t\tufmt.Sprintf(\" (%d)\", w.NumComments(p.Title)))\n\treturn md.Paragraph(line + \"\\n\\n\" + strings.Join(nav, \" · \"))\n}\n\nfunc articleFooter(c Ctx, w *Wiki, p *Page) string {\n\tvar out strings.Builder\n\tout.WriteString(md.HorizontalRule())\n\n\tif len(p.cats) \u003e 0 {\n\t\tcats := []string{}\n\t\tfor _, key := range p.cats {\n\t\t\tt := Title{NS: NSCategory, Name: key[len(NSCategory.Prefix()):]}\n\t\t\tcats = append(cats, md.Link(t.Name, c.URL(t)))\n\t\t}\n\t\tout.WriteString(md.Paragraph(\"**Categories:** \" + strings.Join(cats, \" · \")))\n\t}\n\n\theld := 0\n\tp.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {\n\t\tr := v.(*Revision)\n\t\tif r.kept {\n\t\t\theld += r.Size\n\t\t}\n\t\treturn false\n\t})\n\tout.WriteString(md.Paragraph(ufmt.Sprintf(\n\t\t\"%s · %d bytes of text held on chain · %s of storage deposit · %s link here\",\n\t\tplural(p.NumRevisions(), \"revision\", \"revisions\"),\n\t\theld, formatGNOT(held*DepositPerByte),\n\t\tplural(len(w.Backlinks(p.Title)), \"page\", \"pages\"))))\n\treturn out.String()\n}\n\n// RenderMissing renders the stub shown for a title with no page: the red-link\n// destination, listing whoever already points at it.\nfunc RenderMissing(c Ctx, w *Wiki, t Title, act Action) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(t.String()))\n\tout.WriteString(md.Paragraph(\"_This page does not exist yet._\"))\n\tif act != nil {\n\t\tout.WriteString(md.Paragraph(md.Link(\"Create it\", act(\"Edit\", \"title\", t.String()))))\n\t}\n\tif in := w.Backlinks(t); len(in) \u003e 0 {\n\t\tout.WriteString(md.H2(\"Pages that already link here\"))\n\t\tout.WriteString(titleList(c, in))\n\t}\n\treturn out.String()\n}\n\n// RenderHistory renders a page's revision list, newest first.\nfunc RenderHistory(c Ctx, p *Page, offset, count int, act Action) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(\"History of \" + p.Title.String()))\n\tout.WriteString(md.Paragraph(md.Link(\"← back to the article\", c.URL(p.Title))))\n\n\trevs := p.History(offset, count)\n\tif len(revs) == 0 {\n\t\tout.WriteString(md.Paragraph(\"_No revisions in this range._\"))\n\t\treturn out.String()\n\t}\n\titems := []string{}\n\tfor _, r := range revs {\n\t\tline := ufmt.Sprintf(\"**rev %d** · %s · %s · %s · %d bytes · `%s`\",\n\t\t\tr.ID, r.Time.Format(\"2006-01-02 15:04\"), shortAddr(r.Author), string(r.Kind), r.Size, r.ShortHash())\n\t\tif r.Summary != \"\" {\n\t\t\tline += \"\\n\\n\" + sanitize.InlineText(r.Summary)\n\t\t}\n\t\textra := []string{}\n\t\tif r.Prev != 0 {\n\t\t\textra = append(extra, md.Link(\"diff\", c.Sub(p.Title, \"diff\")+\"?from=\"+ufmt.Sprintf(\"%d\", r.Prev)+\"\u0026to=\"+ufmt.Sprintf(\"%d\", r.ID)))\n\t\t}\n\t\tif r.kept {\n\t\t\textra = append(extra, md.Link(\"view\", c.Sub(p.Title, \"rev\")+\"/\"+ufmt.Sprintf(\"%d\", r.ID)))\n\t\t\tif act != nil {\n\t\t\t\textra = append(extra, md.Link(\"revert to this\", act(\"Revert\",\n\t\t\t\t\t\"title\", p.Title.String(), \"rev\", ufmt.Sprintf(\"%d\", r.ID))))\n\t\t\t}\n\t\t} else {\n\t\t\textra = append(extra, \"_body evicted_\")\n\t\t}\n\t\titems = append(items, line+\"\\n\\n\"+strings.Join(extra, \" · \"))\n\t}\n\tout.WriteString(md.BulletList(items))\n\n\tif offset+len(revs) \u003c p.NumRevisions() {\n\t\tout.WriteString(md.Paragraph(md.Link(\"older →\",\n\t\t\tc.Sub(p.Title, \"history\")+\"?offset=\"+ufmt.Sprintf(\"%d\", offset+count))))\n\t}\n\treturn out.String()\n}\n\n// RenderRevision renders one stored revision verbatim.\nfunc RenderRevision(c Ctx, p *Page, r *Revision) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(ufmt.Sprintf(\"%s: revision %d\", p.Title.String(), r.ID)))\n\tout.WriteString(md.Paragraph(ufmt.Sprintf(\"%s · %s · `%s`\",\n\t\tr.Time.Format(\"2006-01-02 15:04\"), shortAddr(r.Author), r.Hash)))\n\tbody, kept := r.Body()\n\tif !kept {\n\t\tout.WriteString(md.Blockquote(\"This revision's body is no longer held on chain.\"))\n\t\treturn out.String()\n\t}\n\tout.WriteString(RewriteLinks(c, sanitize.BlockRich(body)))\n\treturn out.String()\n}\n\n// RenderRaw renders a revision's source inside a code block, which is what a\n// reader needs before editing and what a verifier needs to re-hash.\nfunc RenderRaw(c Ctx, p *Page, r *Revision) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(ufmt.Sprintf(\"Source of %s (rev %d)\", p.Title.String(), r.ID)))\n\tout.WriteString(md.Paragraph(\"sha256 `\" + r.Hash + \"`\"))\n\tbody, kept := r.Body()\n\tif !kept {\n\t\tout.WriteString(md.Blockquote(\"This revision's body is no longer held on chain.\"))\n\t\treturn out.String()\n\t}\n\tout.WriteString(sanitize.CodeBlock(body))\n\tout.WriteString(md.Paragraph(md.Link(\"← back to the article\", c.URL(p.Title))))\n\treturn out.String()\n}\n\n// RenderDiff renders the line diff between two revisions of a page.\nfunc RenderDiff(c Ctx, p *Page, from, to *Revision) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(ufmt.Sprintf(\"%s: rev %d → rev %d\", p.Title.String(), from.ID, to.ID)))\n\n\ta, okA := from.Body()\n\tb, okB := to.Body()\n\tif !okA || !okB {\n\t\tout.WriteString(md.Blockquote(\"One of these revisions' bodies is no longer held on chain, so the diff cannot be computed. \" +\n\t\t\t\"Their hashes are `\" + from.ShortHash() + \"` and `\" + to.ShortHash() + \"`.\"))\n\t\treturn out.String()\n\t}\n\n\tlines, exact := DiffLines(a, b)\n\tadded, removed := DiffStat(lines)\n\tnote := ufmt.Sprintf(\"+%d −%d lines\", added, removed)\n\tif !exact {\n\t\tnote += \" · changed region larger than \" + ufmt.Sprintf(\"%d\", DiffMaxLines) + \" lines, shown as a block replacement\"\n\t}\n\tout.WriteString(md.Paragraph(note))\n\n\tvar d strings.Builder\n\tfor _, l := range lines {\n\t\tswitch l.Op {\n\t\tcase OpInsert:\n\t\t\td.WriteString(\"+\" + l.Text + \"\\n\")\n\t\tcase OpDelete:\n\t\t\td.WriteString(\"-\" + l.Text + \"\\n\")\n\t\tdefault:\n\t\t\td.WriteString(\" \" + l.Text + \"\\n\")\n\t\t}\n\t}\n\tout.WriteString(sanitize.LanguageCodeBlock(\"diff\", d.String()))\n\tout.WriteString(md.Paragraph(md.Link(\"← back to the article\", c.URL(p.Title))))\n\treturn out.String()\n}\n\n// RenderIndex renders the wiki's front page: recent changes and a page count.\nfunc RenderIndex(c Ctx, w *Wiki, recent int) string {\n\tvar out strings.Builder\n\ts := w.Stats()\n\tout.WriteString(md.H1(\"Wiki\"))\n\tout.WriteString(md.Paragraph(strings.Join([]string{\n\t\tmd.Link(\"all pages\", c.SpecialURL(\"AllPages\", \"\")),\n\t\tmd.Link(\"categories\", c.SpecialURL(\"Categories\", \"\")),\n\t\tmd.Link(\"recent changes\", c.SpecialURL(\"RecentChanges\", \"\")),\n\t\tmd.Link(\"stats\", c.SpecialURL(\"Stats\", \"\")),\n\t}, \" · \")))\n\tout.WriteString(md.Paragraph(ufmt.Sprintf(\"%d pages · %d revisions · %d bytes on chain\",\n\t\ts.Pages, s.Revisions, s.BytesHeld)))\n\tout.WriteString(md.H2(\"Recent changes\"))\n\tout.WriteString(changeList(c, w.Recent(recent)))\n\treturn out.String()\n}\n\n// RenderRecent renders the recent-changes feed.\nfunc RenderRecent(c Ctx, w *Wiki, n int) string {\n\treturn md.H1(\"Recent changes\") + changeList(c, w.Recent(n))\n}\n\n// RenderAllPages renders the page index for a namespace prefix.\nfunc RenderAllPages(c Ctx, w *Wiki, ns Namespace, offset, count int) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(\"All pages\"))\n\n\ttabs := []string{}\n\tfor i := range namespaces {\n\t\tn := Namespace(i)\n\t\tif n == NSSpecial {\n\t\t\tcontinue\n\t\t}\n\t\tlabel := n.String()\n\t\tif label == \"\" {\n\t\t\tlabel = \"Articles\"\n\t\t}\n\t\tif n == ns {\n\t\t\tlabel = \"**\" + label + \"**\"\n\t\t}\n\t\ttabs = append(tabs, md.Link(label, c.SpecialURL(\"AllPages\", \"ns=\"+ufmt.Sprintf(\"%d\", i))))\n\t}\n\tout.WriteString(md.Paragraph(strings.Join(tabs, \" · \")))\n\n\ttitles := w.Titles(ns.Prefix(), offset, count)\n\tif len(titles) == 0 {\n\t\tout.WriteString(md.Paragraph(\"_No pages in this namespace._\"))\n\t\treturn out.String()\n\t}\n\tout.WriteString(titleList(c, titles))\n\tif len(titles) == count {\n\t\tout.WriteString(md.Paragraph(md.Link(\"next →\",\n\t\t\tc.SpecialURL(\"AllPages\", ufmt.Sprintf(\"ns=%d\u0026offset=%d\", uint8(ns), offset+count)))))\n\t}\n\treturn out.String()\n}\n\n// RenderCategory renders a category page: its own text, then its members.\nfunc RenderCategory(c Ctx, w *Wiki, t Title, p *Page, act Action) string {\n\tvar out strings.Builder\n\tif p != nil {\n\t\tout.WriteString(RenderArticle(c, w, p, act))\n\t} else {\n\t\tout.WriteString(md.H1(t.String()))\n\t\tout.WriteString(md.Paragraph(\"_This category has no description page._\"))\n\t}\n\tmembers := w.CategoryMembers(t)\n\tout.WriteString(md.H2(ufmt.Sprintf(\"Pages in this category (%d)\", len(members))))\n\tif len(members) == 0 {\n\t\tout.WriteString(md.Paragraph(\"_None._\"))\n\t\treturn out.String()\n\t}\n\tout.WriteString(titleList(c, members))\n\treturn out.String()\n}\n\n// RenderCategories lists every category that has at least one member.\nfunc RenderCategories(c Ctx, w *Wiki) string {\n\tcats := w.Categories()\n\tvar out strings.Builder\n\tout.WriteString(md.H1(\"Categories\"))\n\tif len(cats) == 0 {\n\t\tout.WriteString(md.Paragraph(\"_No categories yet._\"))\n\t\treturn out.String()\n\t}\n\titems := []string{}\n\tfor _, t := range cats {\n\t\titems = append(items, ufmt.Sprintf(\"%s (%d)\", md.Link(t.Name, c.URL(t)), len(w.CategoryMembers(t))))\n\t}\n\tout.WriteString(md.BulletList(items))\n\treturn out.String()\n}\n\n// RenderBacklinks renders \"what links here\" for a title.\nfunc RenderBacklinks(c Ctx, w *Wiki, t Title) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(\"Pages that link to \" + t.String()))\n\tout.WriteString(md.Paragraph(md.Link(\"← back to the article\", c.URL(t))))\n\tin := w.Backlinks(t)\n\tif len(in) == 0 {\n\t\tout.WriteString(md.Paragraph(\"_Nothing links here._\"))\n\t\treturn out.String()\n\t}\n\tout.WriteString(titleList(c, in))\n\treturn out.String()\n}\n\n// RenderStats renders the wiki's size and what it is paying the chain.\nfunc RenderStats(c Ctx, w *Wiki) string {\n\ts := w.Stats()\n\trows := []string{\n\t\tufmt.Sprintf(\"pages: %d\", s.Pages),\n\t\tufmt.Sprintf(\"revisions: %d\", s.Revisions),\n\t\tufmt.Sprintf(\"comments: %d\", s.Comments),\n\t\tufmt.Sprintf(\"body bytes on chain: %d\", s.BytesHeld),\n\t\tufmt.Sprintf(\"storage deposit locked by bodies: %s\", formatGNOT(s.BytesHeld*DepositPerByte)),\n\t\tufmt.Sprintf(\"bodies kept per page: %d\", s.Retention),\n\t}\n\treturn md.H1(\"Wiki stats\") + md.BulletList(rows)\n}\n\n// RenderTalk renders a page's discussion: top-level messages oldest first,\n// each with its replies.\nfunc RenderTalk(c Ctx, w *Wiki, p *Page, offset, count int, act Action) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(\"Discussion: \" + p.Title.String()))\n\n\tnav := []string{md.Link(\"← back to the article\", c.URL(p.Title))}\n\tif act != nil {\n\t\tnav = append(nav, md.Link(\"add a message\", act(\"Comment\", \"title\", p.Title.String(), \"replyTo\", \"0\")))\n\t}\n\tout.WriteString(md.Paragraph(strings.Join(nav, \" · \")))\n\n\tthreads := w.Comments(p.Title, offset, count)\n\tif len(threads) == 0 {\n\t\tout.WriteString(md.Paragraph(\"_No messages yet._\"))\n\t\treturn out.String()\n\t}\n\n\titems := []string{}\n\tfor _, th := range threads {\n\t\titem := commentLine(c, th.Root, act, p.Title)\n\t\tfor _, r := range th.Replies {\n\t\t\titem += \"\\n\" + md.Nested(commentLine(c, r, nil, p.Title), \"  - \")\n\t\t}\n\t\titems = append(items, item)\n\t}\n\tout.WriteString(md.BulletList(items))\n\n\ttotal := w.NumComments(p.Title)\n\tif offset+len(threads) \u003c total {\n\t\tout.WriteString(md.Paragraph(md.Link(\"older →\",\n\t\t\tc.Sub(p.Title, \"talk\")+\"?offset=\"+ufmt.Sprintf(\"%d\", offset+count))))\n\t}\n\treturn out.String()\n}\n\nfunc commentLine(c Ctx, cm *Comment, act Action, t Title) string {\n\thead := ufmt.Sprintf(\"**#%d** · %s · %s\",\n\t\tcm.ID, cm.Time.Format(\"2006-01-02 15:04\"), shortAddr(cm.Author))\n\tif cm.Hidden {\n\t\treturn head + \"\\n\\n_This message was removed by a steward._\"\n\t}\n\tbody := sanitize.Block(cm.Body)\n\tif act != nil {\n\t\tbody += \"\\n\\n\" + md.Link(\"reply\", act(\"Comment\",\n\t\t\t\"title\", t.String(), \"replyTo\", ufmt.Sprintf(\"%d\", cm.ID)))\n\t}\n\treturn head + body\n}\n\nfunc titleList(c Ctx, titles []Title) string {\n\titems := []string{}\n\tfor _, t := range titles {\n\t\titems = append(items, md.Link(t.String(), c.URL(t)))\n\t}\n\treturn md.BulletList(items)\n}\n\nfunc changeList(c Ctx, changes []*Change) string {\n\tif len(changes) == 0 {\n\t\treturn md.Paragraph(\"_Nothing has happened yet._\")\n\t}\n\titems := []string{}\n\tfor _, ch := range changes {\n\t\tline := ufmt.Sprintf(\"%s · %s · %s · %s · rev %d\",\n\t\t\tmd.Link(ch.Title.String(), c.URL(ch.Title)),\n\t\t\tstring(ch.Rev.Kind),\n\t\t\tch.Rev.Time.Format(\"2006-01-02 15:04\"),\n\t\t\tshortAddr(ch.Rev.Author),\n\t\t\tch.Rev.ID)\n\t\tif ch.Rev.Summary != \"\" {\n\t\t\tline += \" · \" + sanitize.InlineText(ch.Rev.Summary)\n\t\t}\n\t\titems = append(items, line)\n\t}\n\treturn md.BulletList(items)\n}\n\n// shortAddr abbreviates an address for display without losing its prefix.\nfunc shortAddr(a address) string {\n\ts := a.String()\n\tif len(s) \u003c= 12 {\n\t\treturn \"`\" + s + \"`\"\n\t}\n\treturn \"`\" + s[:10] + \"…\" + s[len(s)-4:] + \"`\"\n}\n\n// formatGNOT renders a ugnot amount as GNOT.\n//\n// The zero padding is written out by hand: gno's ufmt supports no width or\n// padding flags, so ufmt.Sprintf(\"%06d\", 42) returns \"42\" silently and the\n// fractional part of every amount would be wrong by three orders of magnitude.\nfunc formatGNOT(ugnot int) string {\n\twhole := ugnot / 1000000\n\tfrac := ugnot % 1000000\n\ts := ufmt.Sprintf(\"%d\", frac)\n\tfor len(s) \u003c 6 {\n\t\ts = \"0\" + s\n\t}\n\ts = strings.TrimRight(s, \"0\")\n\tif s == \"\" {\n\t\treturn ufmt.Sprintf(\"%d GNOT\", whole)\n\t}\n\treturn ufmt.Sprintf(\"%d.%s GNOT\", whole, s)\n}\n\n// plural renders \"1 revision\" and \"2 revisions\".\nfunc plural(n int, one, many string) string {\n\tif n == 1 {\n\t\treturn ufmt.Sprintf(\"%d %s\", n, one)\n\t}\n\treturn ufmt.Sprintf(\"%d %s\", n, many)\n}\n"},{"name":"render_test.gno","body":"package wiki\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc fixture(t *testing.T) (*Wiki, Ctx) {\n\tt.Helper()\n\tw := New(2, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"Gno land\", \"A chain.\\n\\nSee [[Tendermint2]] and [[Absent page]].\\n\\n[[Category:Chains]]\\n\", \"create\")\n\tedit(t, w, 2, bob, \"Gno land\", \"A smart-contract chain.\\n\\nSee [[Tendermint2]].\\n\\n[[Category:Chains]]\\n\", \"tighten\")\n\tedit(t, w, 3, alice, \"Tendermint2\", \"The consensus engine.\\n\", \"create\")\n\treturn w, Ctx{Base: \"/r/moul/x/wiki/v0\", Exists: w.Exists}\n}\n\nfunc act(fn string, args ...string) string {\n\tout := \"/r/moul/x/wiki/v0$help\u0026func=\" + fn\n\tfor i := 0; i+1 \u003c len(args); i += 2 {\n\t\tout += \"\u0026\" + args[i] + \"=\" + args[i+1]\n\t}\n\treturn out\n}\n\nfunc TestRenderArticle(t *testing.T) {\n\tw, c := fixture(t)\n\tp, _ := w.Page(\"Gno land\")\n\tout := RenderArticle(c, w, p, act)\n\n\tuassert.True(t, strings.Contains(out, \"# Gno land\"), \"heading\")\n\tuassert.True(t, strings.Contains(out, \"A smart-contract chain.\"), \"body text\")\n\tuassert.True(t, strings.Contains(out, \"[Tendermint2](/r/moul/x/wiki/v0:Tendermint2)\"), \"resolved wikilink\")\n\tuassert.False(t, strings.Contains(out, \"[[Tendermint2]]\"), \"no raw wikilink survives\")\n\tuassert.True(t, strings.Contains(out, \"**Categories:**\"), \"category footer\")\n\tuassert.True(t, strings.Contains(out, \"[Chains](/r/moul/x/wiki/v0:Category:Chains)\"), \"category link\")\n\tuassert.True(t, strings.Contains(out, \"func=Edit\"), \"edit action\")\n\tuassert.True(t, strings.Contains(out, \"GNOT of storage deposit\"), \"cost is shown to the reader\")\n}\n\nfunc TestRenderArticleWithoutActionsHasNoEditControls(t *testing.T) {\n\tw, c := fixture(t)\n\tp, _ := w.Page(\"Gno land\")\n\tout := RenderArticle(c, w, p, nil)\n\tuassert.False(t, strings.Contains(out, \"func=Edit\"), \"a nil Action renders a read-only page\")\n}\n\nfunc TestRenderArticleEscapesHostileMarkdown(t *testing.T) {\n\tw := New(2, DefaultMaxBody)\n\tbody := \"\u003cscript\u003ealert(1)\u003c/script\u003e\\n\\n# Fake realm heading\\n\"\n\tedit(t, w, 1, alice, \"Hostile\", body, \"\")\n\tp, _ := w.Page(\"Hostile\")\n\tout := RenderArticle(Ctx{Base: \"/r/moul/x/wiki/v0\"}, w, p, nil)\n\n\tuassert.True(t, strings.Contains(out, `\\\u003cscript\u003e`),\n\t\t\"an HTML block is escaped, not dropped: the reader still sees what was written\")\n\tuassert.False(t, strings.Contains(out, \"\\n\u003cscript\u003e\"),\n\t\t\"no unescaped HTML block reaches the renderer\")\n\t// The realm's own footer must still be there: a CommonMark HTML block of\n\t// type 1-5 does not close on a blank line, so an unescaped one would\n\t// swallow every byte the realm appends after the body.\n\tuassert.True(t, strings.Contains(out, \"GNOT of storage deposit\"),\n\t\t\"user content cannot absorb the realm chrome that follows it\")\n}\n\nfunc TestRenderMissing(t *testing.T) {\n\tw, c := fixture(t)\n\tout := RenderMissing(c, w, MustParseTitle(\"Absent page\"), act)\n\tuassert.True(t, strings.Contains(out, \"does not exist yet\"))\n\tuassert.True(t, strings.Contains(out, \"func=Edit\"))\n\t// The first revision of Gno land linked here; the second dropped the link,\n\t// so nothing should be listed.\n\tuassert.True(t, strings.Contains(out, \"does not exist yet\"))\n}\n\nfunc TestRenderHistory(t *testing.T) {\n\tw, c := fixture(t)\n\tp, _ := w.Page(\"Gno land\")\n\tout := RenderHistory(c, p, 0, 10, act)\n\n\tuassert.True(t, strings.Contains(out, \"# History of Gno land\"))\n\tuassert.True(t, strings.Contains(out, \"**rev 2**\"))\n\tuassert.True(t, strings.Contains(out, \"**rev 1**\"))\n\tuassert.True(t, strings.Contains(out, \"from=1\u0026to=2\"), \"consecutive revisions get a diff link\")\n\tuassert.True(t, strings.Contains(out, \"func=Revert\"))\n}\n\nfunc TestRenderDiff(t *testing.T) {\n\tw, c := fixture(t)\n\tp, _ := w.Page(\"Gno land\")\n\th := p.History(0, 2)\n\tout := RenderDiff(c, p, h[1], h[0])\n\n\tuassert.True(t, strings.Contains(out, \"rev 1 → rev 2\"))\n\tuassert.True(t, strings.Contains(out, \"-A chain.\"))\n\tuassert.True(t, strings.Contains(out, \"+A smart-contract chain.\"))\n\tuassert.True(t, strings.Contains(out, \"```diff\"))\n}\n\nfunc TestRenderDiffRefusesEvictedBodies(t *testing.T) {\n\tw := New(1, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"one\\n\", \"\")\n\tedit(t, w, 2, alice, \"A\", \"two\\n\", \"\")\n\tp, _ := w.Page(\"A\")\n\th := p.History(0, 2)\n\tout := RenderDiff(Ctx{Base: \"/r/moul/x/wiki/v0\"}, p, h[1], h[0])\n\tuassert.True(t, strings.Contains(out, \"no longer held on chain\"),\n\t\t\"an evicted body must be explained, not rendered as an empty diff\")\n}\n\nfunc TestRenderRawShowsTheHashAReaderNeeds(t *testing.T) {\n\tw, c := fixture(t)\n\tp, _ := w.Page(\"Gno land\")\n\tout := RenderRaw(c, p, p.Head())\n\tuassert.True(t, strings.Contains(out, p.Head().Hash), \"the full hash, so the bytes can be verified\")\n\tuassert.True(t, strings.Contains(out, \"[[Tendermint2]]\"), \"raw view shows the source, unrewritten\")\n}\n\nfunc TestRenderIndexAndSpecials(t *testing.T) {\n\tw, c := fixture(t)\n\n\tidx := RenderIndex(c, w, 10)\n\tuassert.True(t, strings.Contains(idx, \"2 pages\"))\n\tuassert.True(t, strings.Contains(idx, \"Recent changes\"))\n\n\tall := RenderAllPages(c, w, NSMain, 0, 10)\n\tuassert.True(t, strings.Contains(all, \"[Gno land]\"))\n\tuassert.True(t, strings.Contains(all, \"[Tendermint2]\"))\n\n\tcats := RenderCategories(c, w)\n\tuassert.True(t, strings.Contains(cats, \"[Chains](/r/moul/x/wiki/v0:Category:Chains) (1)\"))\n\n\tcat := RenderCategory(c, w, MustParseTitle(\"Category:Chains\"), nil, nil)\n\tuassert.True(t, strings.Contains(cat, \"no description page\"))\n\tuassert.True(t, strings.Contains(cat, \"Pages in this category (1)\"))\n\n\tback := RenderBacklinks(c, w, MustParseTitle(\"Tendermint2\"))\n\tuassert.True(t, strings.Contains(back, \"[Gno land]\"))\n\n\tstats := RenderStats(c, w)\n\tuassert.True(t, strings.Contains(stats, \"bodies kept per page: 2\"))\n}\n\nfunc TestRenderBlankedPage(t *testing.T) {\n\tw, c := fixture(t)\n\tnow, h := at(9)\n\tw.Blank(mod, now, h, \"Gno land\", \"policy\")\n\tp, _ := w.Page(\"Gno land\")\n\tout := RenderArticle(c, w, p, nil)\n\tuassert.True(t, strings.Contains(out, \"was blanked\"))\n\tuassert.True(t, strings.Contains(out, \"view history\"))\n}\n\nfunc TestRenderRedirect(t *testing.T) {\n\tw, c := fixture(t)\n\tedit(t, w, 4, alice, \"Gno\", \"#REDIRECT [[Gno land]]\\n\", \"\")\n\tp, _ := w.Page(\"Gno\")\n\tout := RenderArticle(c, w, p, nil)\n\tuassert.True(t, strings.Contains(out, \"Redirects to [Gno land](/r/moul/x/wiki/v0:Gno_land)\"))\n}\n"},{"name":"revision.gno","body":"package wiki\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"time\"\n)\n\n// Kind labels what a revision did, for the recent-changes feed.\ntype Kind string\n\nconst (\n\tKindCreate  Kind = \"create\"\n\tKindEdit    Kind = \"edit\"\n\tKindRevert  Kind = \"revert\"\n\tKindMove    Kind = \"move\"\n\tKindBlank   Kind = \"blank\"\n\tKindProtect Kind = \"protect\"\n)\n\n// Revision is one entry in a page's append-only history.\n//\n// The exported fields are the permanent spine: they are never evicted, and\n// they are what makes the history tamper-evident. Hash is the SHA-256 of the\n// body bytes as submitted, so a body recovered from transaction history can be\n// checked against the chain's own record of it.\n//\n// body is the only field under a retention policy. When a revision falls out\n// of the page's body window it is evicted, which releases the storage deposit\n// those bytes locked.\ntype Revision struct {\n\tID      uint64\n\tPrev    uint64 // 0 for the first revision of a page\n\tKind    Kind\n\tAuthor  address\n\tTime    time.Time\n\tHeight  int64\n\tSummary string\n\tHash    string // hex-encoded SHA-256 of the body\n\tSize    int    // body length in bytes\n\tMinor   bool\n\n\tbody string\n\tkept bool\n}\n\n// Body returns the revision's text and whether it is still held on chain. A\n// false second return is not corruption: the body aged out of the retention\n// window and must be recovered from the transaction that wrote it, then\n// checked against Hash.\nfunc (r *Revision) Body() (string, bool) { return r.body, r.kept }\n\n// Kept reports whether this revision's body is still on chain.\nfunc (r *Revision) Kept() bool { return r.kept }\n\n// evict drops the body and returns the number of bytes released.\nfunc (r *Revision) evict() int {\n\tif !r.kept {\n\t\treturn 0\n\t}\n\tn := len(r.body)\n\tr.body = \"\"\n\tr.kept = false\n\treturn n\n}\n\n// hashBody is the content address of a revision body.\nfunc hashBody(body string) string {\n\tsum := sha256.Sum256([]byte(body))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// ShortHash is the first 12 hex characters of Hash, for display.\nfunc (r *Revision) ShortHash() string {\n\tif len(r.Hash) \u003c 12 {\n\t\treturn r.Hash\n\t}\n\treturn r.Hash[:12]\n}\n\n// Change is a recent-changes entry: a revision plus the page it landed on.\ntype Change struct {\n\tTitle Title\n\tRev   *Revision\n}\n"},{"name":"talk.gno","body":"package wiki\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"gno.land/p/moul/ulist/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// MaxCommentLen bounds one comment in bytes.\nconst MaxCommentLen = 2000\n\n// MaxReplyDepth is 1: a comment replies to a top-level comment, and that is\n// all. Deeper nesting needs recursive rendering with no natural bound, which\n// is exactly the shape a query gas ceiling punishes.\nconst MaxReplyDepth = 1\n\nvar (\n\tErrCommentTooLong = errors.New(\"wiki: comment exceeds the size limit\")\n\tErrEmptyComment   = errors.New(\"wiki: empty comment\")\n\tErrNoSuchComment  = errors.New(\"wiki: no such comment\")\n\tErrReplyToReply   = errors.New(\"wiki: replies nest one level only\")\n)\n\n// Comment is one message in a page's discussion.\n//\n// Discussion is a comment store rather than a \"Talk:\" article, which is the\n// one place this design departs from MediaWiki on purpose. A talk page is an\n// article, so the last editor can rewrite what someone else said, and\n// moderating one bad message means editing the whole page. An append-only\n// store gives each message its own author, its own timestamp and its own\n// moderation, and nobody can silently rewrite anyone else's words.\ntype Comment struct {\n\tID     uint64\n\tParent uint64 // 0 for a top-level comment\n\tAuthor address\n\tTime   time.Time\n\tHeight int64\n\tBody   string\n\tHidden bool // a steward hid it; Body is cleared and its deposit released\n}\n\n// Comment appends a message to a page's discussion. replyTo is 0 for a\n// top-level message, or the id of a top-level message to reply to.\n//\n// The engine does not decide who may comment: as with Edit, that is the\n// realm's call. It does enforce the shape, because the shape is what bounds\n// the render.\nfunc (w *Wiki) Comment(author address, now time.Time, height int64, raw, body string, replyTo uint64) (*Comment, error) {\n\tt, err := ParseTitle(raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !w.Exists(t) {\n\t\treturn nil, ErrNoSuchPage\n\t}\n\tif body == \"\" {\n\t\treturn nil, ErrEmptyComment\n\t}\n\tif len(body) \u003e MaxCommentLen {\n\t\treturn nil, ErrCommentTooLong\n\t}\n\n\tlist := w.thread(t, true)\n\tif replyTo != 0 {\n\t\tparent := findComment(list, replyTo)\n\t\tif parent == nil {\n\t\t\treturn nil, ErrNoSuchComment\n\t\t}\n\t\tif parent.Parent != 0 {\n\t\t\treturn nil, ErrReplyToReply\n\t\t}\n\t}\n\n\tw.nextComment++\n\tc := \u0026Comment{\n\t\tID:     w.nextComment,\n\t\tParent: replyTo,\n\t\tAuthor: author,\n\t\tTime:   now,\n\t\tHeight: height,\n\t\tBody:   body,\n\t}\n\tlist.Append(c)\n\tw.numComments++\n\tw.bytesHeld += len(body)\n\treturn c, nil\n}\n\n// HideComment clears one message's body and returns the bytes released. The\n// message itself stays in the thread, so a deleted comment reads as \"removed\"\n// rather than as a gap someone has to reconstruct from block explorers.\nfunc (w *Wiki) HideComment(raw string, id uint64) (int, error) {\n\tt, err := ParseTitle(raw)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tlist := w.thread(t, false)\n\tif list == nil {\n\t\treturn 0, ErrNoSuchComment\n\t}\n\tc := findComment(list, id)\n\tif c == nil {\n\t\treturn 0, ErrNoSuchComment\n\t}\n\tif c.Hidden {\n\t\treturn 0, nil\n\t}\n\tn := len(c.Body)\n\tc.Body = \"\"\n\tc.Hidden = true\n\tw.bytesHeld -= n\n\treturn n, nil\n}\n\n// Comments returns up to count top-level messages of a page's discussion,\n// oldest first, skipping offset of them, each paired with its replies in the\n// order they were written.\nfunc (w *Wiki) Comments(t Title, offset, count int) []*Thread {\n\tout := []*Thread{}\n\tlist := w.thread(t, false)\n\tif list == nil || count \u003c= 0 {\n\t\treturn out\n\t}\n\n\t// One pass to bucket replies by parent, a second to emit top-level\n\t// messages in order. Buckets live in an avl rather than a map because\n\t// this feeds a render, and gno map iteration order is unspecified.\n\treplies := avl.NewTree()\n\tlist.Iterator(0, list.Size()-1, func(_ int, v any) bool {\n\t\tc := v.(*Comment)\n\t\tif c.Parent == 0 {\n\t\t\treturn false\n\t\t}\n\t\tkey := commentKey(c.Parent)\n\t\tvar bucket []*Comment\n\t\tif b := replies.Get(key); b != nil {\n\t\t\tbucket = b.([]*Comment)\n\t\t}\n\t\treplies.Set(key, append(bucket, c))\n\t\treturn false\n\t})\n\n\tskipped := 0\n\tlist.Iterator(0, list.Size()-1, func(_ int, v any) bool {\n\t\tc := v.(*Comment)\n\t\tif c.Parent != 0 {\n\t\t\treturn false\n\t\t}\n\t\tif skipped \u003c offset {\n\t\t\tskipped++\n\t\t\treturn false\n\t\t}\n\t\tth := \u0026Thread{Root: c}\n\t\tif b := replies.Get(commentKey(c.ID)); b != nil {\n\t\t\tth.Replies = b.([]*Comment)\n\t\t}\n\t\tout = append(out, th)\n\t\treturn len(out) \u003e= count\n\t})\n\treturn out\n}\n\n// Thread is a top-level comment and its replies.\ntype Thread struct {\n\tRoot    *Comment\n\tReplies []*Comment\n}\n\n// NumComments returns how many messages a page's discussion holds, replies\n// and hidden messages included.\nfunc (w *Wiki) NumComments(t Title) int {\n\tlist := w.thread(t, false)\n\tif list == nil {\n\t\treturn 0\n\t}\n\treturn list.Size()\n}\n\n// thread returns a page's comment list, creating it when create is set.\nfunc (w *Wiki) thread(t Title, create bool) *ulist.List {\n\tv := w.talk.Get(t.Key())\n\tif v != nil {\n\t\treturn v.(*ulist.List)\n\t}\n\tif !create {\n\t\treturn nil\n\t}\n\tlist := ulist.New()\n\tw.talk.Set(t.Key(), list)\n\treturn list\n}\n\nfunc findComment(list *ulist.List, id uint64) *Comment {\n\tvar found *Comment\n\tlist.Iterator(0, list.Size()-1, func(_ int, v any) bool {\n\t\tc := v.(*Comment)\n\t\tif c.ID == id {\n\t\t\tfound = c\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn found\n}\n\n// commentKey is only ever used as an avl key for reply buckets, where the\n// order does not matter, so a plain decimal is fine here. Anything whose\n// ordering IS meaningful needs a fixed-width key: see Title.Key.\nfunc commentKey(id uint64) string {\n\tif id == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b []byte\n\tfor id \u003e 0 {\n\t\tb = append([]byte{byte('0' + id%10)}, b...)\n\t\tid /= 10\n\t}\n\treturn string(b)\n}\n"},{"name":"talk_test.gno","body":"package wiki\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc comment(t *testing.T, w *Wiki, n int, author address, title, body string, replyTo uint64) *Comment {\n\tt.Helper()\n\tnow, h := at(n)\n\tc, err := w.Comment(author, now, h, title, body, replyTo)\n\tuassert.NoError(t, err, title)\n\treturn c\n}\n\nfunc TestCommentThreads(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"the article\\n\", \"\")\n\n\troot1 := comment(t, w, 2, alice, \"A\", \"First point.\\n\", 0)\n\troot2 := comment(t, w, 3, bob, \"A\", \"Second point.\\n\", 0)\n\treply := comment(t, w, 4, mod, \"A\", \"Answering the first.\\n\", root1.ID)\n\n\ttitle := MustParseTitle(\"A\")\n\tuassert.Equal(t, 3, w.NumComments(title))\n\n\tthreads := w.Comments(title, 0, 10)\n\tuassert.Equal(t, 2, len(threads), \"replies do not count as threads\")\n\tuassert.Equal(t, uint64(root1.ID), threads[0].Root.ID)\n\tuassert.Equal(t, 1, len(threads[0].Replies))\n\tuassert.Equal(t, uint64(reply.ID), threads[0].Replies[0].ID)\n\tuassert.Equal(t, uint64(root2.ID), threads[1].Root.ID)\n\tuassert.Equal(t, 0, len(threads[1].Replies))\n\n\tuassert.Equal(t, 1, len(w.Comments(title, 1, 10)), \"offset skips whole threads\")\n}\n\nfunc TestCommentRejectsBadInput(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"the article\\n\", \"\")\n\tnow, h := at(2)\n\n\t_, err := w.Comment(alice, now, h, \"Missing page\", \"hi\\n\", 0)\n\tuassert.ErrorIs(t, err, ErrNoSuchPage, \"a discussion needs a page to be about\")\n\n\t_, err = w.Comment(alice, now, h, \"A\", \"\", 0)\n\tuassert.ErrorIs(t, err, ErrEmptyComment)\n\n\t_, err = w.Comment(alice, now, h, \"A\", strings.Repeat(\"x\", MaxCommentLen+1), 0)\n\tuassert.ErrorIs(t, err, ErrCommentTooLong)\n\n\t_, err = w.Comment(alice, now, h, \"A\", \"hi\\n\", 999)\n\tuassert.ErrorIs(t, err, ErrNoSuchComment)\n}\n\n// TestRepliesNestOneLevel pins MaxReplyDepth. Unbounded nesting means\n// unbounded recursive rendering, which is the shape the query gas ceiling\n// punishes hardest.\nfunc TestRepliesNestOneLevel(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"the article\\n\", \"\")\n\troot := comment(t, w, 2, alice, \"A\", \"root\\n\", 0)\n\treply := comment(t, w, 3, bob, \"A\", \"reply\\n\", root.ID)\n\n\tnow, h := at(4)\n\t_, err := w.Comment(mod, now, h, \"A\", \"reply to a reply\\n\", reply.ID)\n\tuassert.ErrorIs(t, err, ErrReplyToReply)\n}\n\nfunc TestHideComment(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"the article\\n\", \"\")\n\tbefore := w.Stats().BytesHeld\n\tc := comment(t, w, 2, bob, \"A\", \"unpleasant\\n\", 0)\n\tuassert.Equal(t, before+len(\"unpleasant\\n\"), w.Stats().BytesHeld,\n\t\t\"a comment costs its author the bytes it adds\")\n\n\treleased, err := w.HideComment(\"A\", c.ID)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, len(\"unpleasant\\n\"), released)\n\tuassert.Equal(t, before, w.Stats().BytesHeld)\n\n\tthreads := w.Comments(MustParseTitle(\"A\"), 0, 10)\n\tuassert.Equal(t, 1, len(threads), \"a hidden message stays in the thread\")\n\tuassert.True(t, threads[0].Root.Hidden)\n\tuassert.Equal(t, \"\", threads[0].Root.Body)\n\n\t// Hiding twice must not double-count the refund.\n\treleased, err = w.HideComment(\"A\", c.ID)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 0, released)\n\tuassert.Equal(t, before, w.Stats().BytesHeld)\n}\n\nfunc TestRenderTalk(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"the article\\n\", \"\")\n\troot := comment(t, w, 2, alice, \"A\", \"Is [[B]] the right link?\\n\", 0)\n\tcomment(t, w, 3, bob, \"A\", \"Yes.\\n\", root.ID)\n\thidden := comment(t, w, 4, mod, \"A\", \"spam\\n\", 0)\n\tw.HideComment(\"A\", hidden.ID)\n\n\tp, _ := w.Page(\"A\")\n\tc := Ctx{Base: \"/r/moul/x/wiki/v0\", Exists: w.Exists}\n\tout := RenderTalk(c, w, p, 0, 10, act)\n\n\tuassert.True(t, strings.Contains(out, \"# Discussion: A\"))\n\tuassert.True(t, strings.Contains(out, \"func=Comment\"), \"an add-a-message action\")\n\tuassert.True(t, strings.Contains(out, \"Yes.\"), \"replies render under their root\")\n\tuassert.True(t, strings.Contains(out, \"removed by a steward\"))\n\tuassert.False(t, strings.Contains(out, \"spam\"), \"a hidden body is gone from the render\")\n\n\t// A comment is user markdown too: it goes through the sanitizer, and it\n\t// is NOT a wikilink slot, so brackets stay literal rather than linking.\n\tuassert.True(t, strings.Contains(out, `\\[\\[B\\]\\]`), out)\n}\n\nfunc TestRenderTalkEmpty(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"the article\\n\", \"\")\n\tp, _ := w.Page(\"A\")\n\tout := RenderTalk(Ctx{Base: \"/r/moul/x/wiki/v0\"}, w, p, 0, 10, nil)\n\tuassert.True(t, strings.Contains(out, \"No messages yet\"))\n}\n\nfunc TestArticleLinksToItsDiscussion(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"the article\\n\", \"\")\n\tcomment(t, w, 2, alice, \"A\", \"hi\\n\", 0)\n\n\tp, _ := w.Page(\"A\")\n\tout := RenderArticle(Ctx{Base: \"/r/moul/x/wiki/v0\"}, w, p, nil)\n\tuassert.True(t, strings.Contains(out, \"[discussion](/r/moul/x/wiki/v0:A/talk) (1)\"), out)\n}\n"},{"name":"title.gno","body":"package wiki\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Namespace partitions the title space the way MediaWiki does: the same name\n// can exist once per namespace, and each namespace gets its own rendering and\n// its own listing.\ntype Namespace uint8\n\n// There is deliberately no Talk namespace. Discussion is not an article with\n// a prefix: it is an append-only thread attached to a page, which threads\n// properly, moderates per message, and cannot be silently rewritten by whoever\n// edits last. See talk.gno.\nconst (\n\tNSMain     Namespace = iota // articles\n\tNSUser                      // per-address pages\n\tNSCategory                  // category descriptions; membership is an index\n\tNSTemplate                  // reusable fragments\n\tNSHelp                      // documentation about the wiki itself\n\tNSSpecial                   // generated listings; never stored\n)\n\n// namespaces is the canonical table. The two-character code is the avl key\n// prefix: it is fixed-width on purpose, because ufmt in gno supports no width\n// or padding flags (ufmt.Sprintf(\"%02d\", 7) returns \"7\"), so a numeric key\n// would sort \"0\",\"1\",\"10\",\"2\" and silently interleave namespaces past nine.\nvar namespaces = [...]struct {\n\tprefix string // canonical display prefix, \"\" for main\n\tcode   string // fixed-width avl key prefix\n}{\n\tNSMain:     {\"\", \"00\"},\n\tNSUser:     {\"User\", \"01\"},\n\tNSCategory: {\"Category\", \"02\"},\n\tNSTemplate: {\"Template\", \"03\"},\n\tNSHelp:     {\"Help\", \"04\"},\n\tNSSpecial:  {\"Special\", \"05\"},\n}\n\n// Title is a normalized (namespace, name) pair. The zero Title is invalid;\n// build one with ParseTitle.\ntype Title struct {\n\tNS   Namespace\n\tName string\n}\n\n// MaxTitleLen bounds a title name in bytes, matching MediaWiki's limit.\nconst MaxTitleLen = 255\n\nvar (\n\tErrEmptyTitle   = errors.New(\"wiki: empty title\")\n\tErrTitleTooLong = errors.New(\"wiki: title too long\")\n\tErrTitleChar    = errors.New(\"wiki: illegal character in title\")\n)\n\n// ParseTitle normalizes a user-supplied title.\n//\n// The normalization is a deliberate subset of MediaWiki's: underscores become\n// spaces, runs of whitespace collapse, the first letter is upper-cased, and a\n// recognized \"Namespace:\" prefix (case-insensitive) selects the namespace.\n// \"Talk:gno  land\" and \"talk:Gno_land\" both parse to Talk:Gno land.\n//\n// The accepted character set is narrower than MediaWiki's on purpose. A title\n// is rendered inside markdown and inside a URL path, so anything that is\n// markdown-significant (\"*\", \"`\", \"[\", \"|\", \"#\", \"\u003c\"), path-significant (\"/\",\n// \"?\", \"%\", \"\u0026\") or invisible (bidi and zero-width controls) is rejected\n// rather than escaped. Rejecting keeps Title.String, Title.Slug and the\n// sanitized render byte-identical, which is what TestTitleCharsSurviveSanitize\n// pins.\nfunc ParseTitle(raw string) (Title, error) {\n\ts := sanitize.StripBidiAndZeroWidth(raw)\n\ts = strings.ReplaceAll(s, \"_\", \" \")\n\ts = strings.Join(strings.Fields(s), \" \")\n\tif s == \"\" {\n\t\treturn Title{}, ErrEmptyTitle\n\t}\n\n\tns := NSMain\n\tif i := strings.Index(s, \":\"); i \u003e 0 {\n\t\tif n, ok := namespaceByPrefix(s[:i]); ok {\n\t\t\tns = n\n\t\t\ts = strings.TrimSpace(s[i+1:])\n\t\t\tif s == \"\" {\n\t\t\t\treturn Title{}, ErrEmptyTitle\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(s) \u003e MaxTitleLen {\n\t\treturn Title{}, ErrTitleTooLong\n\t}\n\tfor _, r := range s {\n\t\tif !validTitleRune(r) {\n\t\t\treturn Title{}, ErrTitleChar\n\t\t}\n\t}\n\treturn Title{NS: ns, Name: upperFirst(s)}, nil\n}\n\n// MustParseTitle is ParseTitle for titles known at development time.\nfunc MustParseTitle(raw string) Title {\n\tt, err := ParseTitle(raw)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn t\n}\n\nfunc namespaceByPrefix(p string) (Namespace, bool) {\n\tp = strings.TrimSpace(p)\n\tfor i, e := range namespaces {\n\t\tif e.prefix != \"\" \u0026\u0026 strings.EqualFold(e.prefix, p) {\n\t\t\treturn Namespace(i), true\n\t\t}\n\t}\n\treturn NSMain, false\n}\n\n// validTitleRune reports whether r may appear in a title name. ASCII is an\n// explicit allowlist; above ASCII only letters and digits are accepted, which\n// admits \"Élysée\" and \"東京\" while excluding every invisible control.\nfunc validTitleRune(r rune) bool {\n\tswitch {\n\tcase r \u003e= 'a' \u0026\u0026 r \u003c= 'z', r \u003e= 'A' \u0026\u0026 r \u003c= 'Z', r \u003e= '0' \u0026\u0026 r \u003c= '9':\n\t\treturn true\n\tcase r == ' ' || r == '-' || r == '.' || r == ',' || r == '\\'' || r == '(' || r == ')' || r == ':':\n\t\treturn true\n\tcase r \u003c 0x80:\n\t\treturn false\n\tdefault:\n\t\treturn unicode.IsLetter(r) || unicode.IsDigit(r)\n\t}\n}\n\nfunc upperFirst(s string) string {\n\trs := []rune(s)\n\tif len(rs) == 0 {\n\t\treturn s\n\t}\n\trs[0] = unicode.ToUpper(rs[0])\n\treturn string(rs)\n}\n\n// String is the canonical display form, \"Talk:Gno land\".\nfunc (t Title) String() string {\n\tif t.NS == NSMain {\n\t\treturn t.Name\n\t}\n\treturn namespaces[t.NS].prefix + \":\" + t.Name\n}\n\n// Slug is the URL form used in render paths, \"Talk:Gno_land\". Titles cannot\n// contain \"/\", so a slug is always exactly one path segment and the segment\n// after it is unambiguously a sub-route.\nfunc (t Title) Slug() string {\n\treturn strings.ReplaceAll(t.String(), \" \", \"_\")\n}\n\n// Key is the avl key: a fixed-width namespace code followed by the name, so\n// iteration yields main-namespace articles first, then Talk, and so on, each\n// group in name order.\nfunc (t Title) Key() string {\n\treturn namespaces[t.NS].code + \":\" + t.Name\n}\n\n// Prefix returns the avl key prefix that selects a whole namespace.\nfunc (ns Namespace) Prefix() string { return namespaces[ns].code + \":\" }\n\n// String returns the namespace's display prefix, \"\" for the main namespace.\nfunc (ns Namespace) String() string { return namespaces[ns].prefix }\n"},{"name":"title_test.gno","body":"package wiki\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestParseTitle(t *testing.T) {\n\tcases := []struct {\n\t\tname    string\n\t\tin      string\n\t\twantNS  Namespace\n\t\twant    string // canonical String(), \"\" when an error is expected\n\t\twantErr error\n\t}{\n\t\t{\"plain\", \"Gno land\", NSMain, \"Gno land\", nil},\n\t\t{\"underscores become spaces\", \"Gno_land\", NSMain, \"Gno land\", nil},\n\t\t{\"whitespace collapses\", \"  Gno   land  \", NSMain, \"Gno land\", nil},\n\t\t{\"first letter is upper-cased\", \"gno land\", NSMain, \"Gno land\", nil},\n\t\t{\"namespace prefix\", \"Help:Gno land\", NSHelp, \"Help:Gno land\", nil},\n\t\t{\"namespace prefix is case-insensitive\", \"help:gno_land\", NSHelp, \"Help:Gno land\", nil},\n\t\t{\"category\", \"Category:Chains\", NSCategory, \"Category:Chains\", nil},\n\t\t{\"unknown prefix stays in the name\", \"Foo:Bar\", NSMain, \"Foo:Bar\", nil},\n\t\t{\"unicode letters are allowed\", \"Élysée\", NSMain, \"Élysée\", nil},\n\t\t{\"unicode is upper-cased too\", \"élysée\", NSMain, \"Élysée\", nil},\n\t\t{\"zero-width characters are stripped\", \"Gno​land\", NSMain, \"Gnoland\", nil},\n\t\t{\"empty\", \"\", NSMain, \"\", ErrEmptyTitle},\n\t\t{\"whitespace only\", \"   \", NSMain, \"\", ErrEmptyTitle},\n\t\t{\"namespace with no name\", \"Help:\", NSMain, \"\", ErrEmptyTitle},\n\t\t{\"slash is rejected\", \"Gno/land\", NSMain, \"\", ErrTitleChar},\n\t\t{\"pipe is rejected\", \"Gno|land\", NSMain, \"\", ErrTitleChar},\n\t\t{\"markdown star is rejected\", \"Gno*land\", NSMain, \"\", ErrTitleChar},\n\t\t{\"bracket is rejected\", \"Gno[land\", NSMain, \"\", ErrTitleChar},\n\t\t{\"hash is rejected\", \"Gno#land\", NSMain, \"\", ErrTitleChar},\n\t}\n\tfor _, tc := range cases {\n\t\tgot, err := ParseTitle(tc.in)\n\t\tif tc.wantErr != nil {\n\t\t\tuassert.ErrorIs(t, err, tc.wantErr, tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tif !uassert.NoError(t, err, tc.name) {\n\t\t\tcontinue\n\t\t}\n\t\tuassert.Equal(t, tc.want, got.String(), tc.name)\n\t\tuassert.Equal(t, uint64(tc.wantNS), uint64(got.NS), tc.name+\" (namespace)\")\n\t}\n}\n\nfunc TestTitleTooLong(t *testing.T) {\n\tlong := \"\"\n\tfor i := 0; i \u003c= MaxTitleLen; i++ {\n\t\tlong += \"a\"\n\t}\n\t_, err := ParseTitle(long)\n\tuassert.ErrorIs(t, err, ErrTitleTooLong)\n}\n\nfunc TestTitleKeyOrdersByNamespace(t *testing.T) {\n\t// The avl key must group namespaces, and must keep doing so past nine\n\t// namespaces, which is why the code is a fixed-width string rather than\n\t// a ufmt-formatted number.\n\tuassert.Equal(t, \"00:Gno land\", MustParseTitle(\"Gno land\").Key())\n\tuassert.Equal(t, \"01:Gno land\", MustParseTitle(\"User:Gno land\").Key())\n\tuassert.True(t, MustParseTitle(\"Gno land\").Key() \u003c MustParseTitle(\"User:Alpha\").Key(),\n\t\t\"every main-namespace key must sort before every User key\")\n}\n\nfunc TestTitleSlug(t *testing.T) {\n\tuassert.Equal(t, \"Gno_land\", MustParseTitle(\"Gno land\").Slug())\n\tuassert.Equal(t, \"User:Gno_land\", MustParseTitle(\"User:Gno land\").Slug())\n\tuassert.Equal(t, \"Mercury_(planet)\", MustParseTitle(\"Mercury (planet)\").Slug())\n}\n\n// TestTitleSurvivesTheRenderPipeline pins the coupling between the title\n// charset and the markdown sanitizer.\n//\n// Rendering escapes the whole body first and rewrites wikilinks second, so\n// every title character has to survive that round trip: sanitize escapes it,\n// ScanLinks finds the link in the escaped text, and unescapeInline hands\n// ParseTitle the bytes the author typed. The sanitizer escapes with\n// backslashes (\"(\" becomes \"\\(\") which unescapeInline undoes, but a character\n// escaped as an entity (\"\u0026\" becomes \"\u0026amp;\") would not survive, which is why\n// the charset excludes those. This test fails the day either side changes.\nfunc TestTitleSurvivesTheRenderPipeline(t *testing.T) {\n\t// The ASCII allowlist plus a couple of accepted non-ASCII letters; the\n\t// whole set has to fit in one title, so this is not every valid rune.\n\tchars := \"Élysée東京\"\n\tfor r := rune(0); r \u003c 0x80; r++ {\n\t\tif validTitleRune(r) \u0026\u0026 r != ' ' {\n\t\t\tchars += string(r)\n\t\t}\n\t}\n\twant := MustParseTitle(chars)\n\n\tescaped := sanitize.BlockRich(\"[[\" + chars + \"]]\\n\")\n\tlinks := ScanLinks(escaped, `\\[\\[`, `\\]\\]`)\n\tif !uassert.Equal(t, 1, len(links), \"the escaped body must still contain exactly one link\") {\n\t\treturn\n\t}\n\tgot, err := ParseTitle(unescapeInline(links[0].Target))\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, want.String(), got.String())\n}\n"},{"name":"wiki.gno","body":"package wiki\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"gno.land/p/moul/fifo/v0\"\n\t\"gno.land/p/moul/ulist/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Defaults for New. Retention is the number of most-recent revisions per page\n// whose body stays on chain; MaxBody caps a single revision.\nconst (\n\tDefaultRetention = 3\n\tDefaultMaxBody   = 32 \u003c\u003c 10 // 32 KiB\n\tDefaultRecent    = 50\n\tMaxSummaryLen    = 200\n)\n\nvar (\n\tErrNoSuchPage     = errors.New(\"wiki: no such page\")\n\tErrPageExists     = errors.New(\"wiki: page already exists\")\n\tErrBodyTooLarge   = errors.New(\"wiki: body exceeds the size limit\")\n\tErrEmptyBody      = errors.New(\"wiki: empty body\")\n\tErrNoChange       = errors.New(\"wiki: body is identical to the current revision\")\n\tErrSummaryTooLong = errors.New(\"wiki: edit summary too long\")\n\tErrBadProtection  = errors.New(\"wiki: unknown protection level\")\n\tErrNoSuchRevision = errors.New(\"wiki: no such revision\")\n\tErrBodyEvicted    = errors.New(\"wiki: that revision's body is no longer held on chain\")\n\tErrSpecial        = errors.New(\"wiki: the Special namespace is generated, not stored\")\n)\n\n// Wiki is the whole encyclopedia: pages, the indexes derived from them, and\n// the recent-changes feed.\n//\n// Every mutating method takes author, now and height from the caller instead\n// of reading them from the chain, so the engine has no chain imports and the\n// tests drive time and height explicitly.\ntype Wiki struct {\n\tpages     *avl.Tree // Title.Key() -\u003e *Page\n\tbacklinks *avl.Tree // target Title.Key() -\u003e *avl.Tree (source key -\u003e Title)\n\tcats      *avl.Tree // category Title.Key() -\u003e *avl.Tree (member key -\u003e Title)\n\ttalk      *avl.Tree // Title.Key() -\u003e *ulist.List of *Comment (see talk.gno)\n\trecent    *fifo.List\n\n\tnextRev     uint64\n\tnextComment uint64\n\tretention int\n\tmaxBody   int\n\n\tnumPages    int // pages with at least one revision and not blanked\n\tnumRevs     int\n\tnumComments int\n\tbytesHeld   int // retained body and comment bytes, the realm's visible rent\n}\n\n// New returns an empty wiki. A retention or maxBody below 1 falls back to the\n// package default.\nfunc New(retention, maxBody int) *Wiki {\n\tif retention \u003c 1 {\n\t\tretention = DefaultRetention\n\t}\n\tif maxBody \u003c 1 {\n\t\tmaxBody = DefaultMaxBody\n\t}\n\treturn \u0026Wiki{\n\t\tpages:     avl.NewTree(),\n\t\tbacklinks: avl.NewTree(),\n\t\tcats:      avl.NewTree(),\n\t\ttalk:      avl.NewTree(),\n\t\trecent:    fifo.New(DefaultRecent),\n\t\tretention: retention,\n\t\tmaxBody:   maxBody,\n\t}\n}\n\n// Stats is a snapshot of the wiki's size and of what it is paying for.\ntype Stats struct {\n\tPages     int\n\tRevisions int\n\tComments  int\n\tBytesHeld int // bytes of article text and comments currently on chain\n\tRetention int\n}\n\n// Stats returns the current counters.\nfunc (w *Wiki) Stats() Stats {\n\treturn Stats{\n\t\tPages:     w.numPages,\n\t\tRevisions: w.numRevs,\n\t\tComments:  w.numComments,\n\t\tBytesHeld: w.bytesHeld,\n\t\tRetention: w.retention,\n\t}\n}\n\n// Page returns the page stored at raw, without following redirects.\nfunc (w *Wiki) Page(raw string) (*Page, error) {\n\tt, err := ParseTitle(raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn w.PageByTitle(t)\n}\n\n// PageByTitle is Page for an already-parsed title.\nfunc (w *Wiki) PageByTitle(t Title) (*Page, error) {\n\tv := w.pages.Get(t.Key())\n\tif v == nil {\n\t\treturn nil, ErrNoSuchPage\n\t}\n\treturn v.(*Page), nil\n}\n\n// Exists reports whether a title has a page. A blanked page still exists: its\n// history is the point of the wiki.\nfunc (w *Wiki) Exists(t Title) bool { return w.pages.Has(t.Key()) }\n\n// Resolve follows at most one redirect hop and returns the destination page\n// along with the page that was asked for. MediaWiki also stops at one hop:\n// chains are a vandalism vector and a loop is unrenderable.\nfunc (w *Wiki) Resolve(raw string) (dest, asked *Page, err error) {\n\tp, err := w.Page(raw)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif p.redirect == \"\" {\n\t\treturn p, p, nil\n\t}\n\ttarget, err := w.Page(p.redirect)\n\tif err != nil {\n\t\treturn p, p, nil // dangling redirect: render the stub itself\n\t}\n\treturn target, p, nil\n}\n\n// Edit writes a new revision. It does not check authority: the caller decides\n// who may write, using Page.Protection and whatever roster it keeps. Passing a\n// body byte-identical to the current one is an error, so a no-op edit cannot\n// be used to spam the history or the recent-changes feed.\nfunc (w *Wiki) Edit(author address, now time.Time, height int64, raw, body, summary string, minor bool) (*Revision, error) {\n\tt, err := ParseTitle(raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif t.NS == NSSpecial {\n\t\treturn nil, ErrSpecial\n\t}\n\tif body == \"\" {\n\t\treturn nil, ErrEmptyBody\n\t}\n\tif len(body) \u003e w.maxBody {\n\t\treturn nil, ErrBodyTooLarge\n\t}\n\tif len(summary) \u003e MaxSummaryLen {\n\t\treturn nil, ErrSummaryTooLong\n\t}\n\n\tp, _ := w.PageByTitle(t)\n\tkind := KindEdit\n\tif p == nil {\n\t\tkind = KindCreate\n\t} else if p.head != nil \u0026\u0026 p.head.Hash == hashBody(body) {\n\t\treturn nil, ErrNoChange\n\t}\n\treturn w.commit(p, t, author, now, height, body, summary, kind, minor), nil\n}\n\n// Revert restores the body of an earlier revision as a new revision, the way\n// a wiki undo works: the vandalized revision stays in the history, it is just\n// no longer current. It fails if that revision's body has aged out of the\n// retention window, which is the honest failure mode of a bounded history.\nfunc (w *Wiki) Revert(author address, now time.Time, height int64, raw string, revID uint64, summary string) (*Revision, error) {\n\tp, err := w.Page(raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\told := p.Revision(revID)\n\tif old == nil {\n\t\treturn nil, ErrNoSuchRevision\n\t}\n\tbody, ok := old.Body()\n\tif !ok {\n\t\treturn nil, ErrBodyEvicted\n\t}\n\tif p.head != nil \u0026\u0026 p.head.Hash == old.Hash {\n\t\treturn nil, ErrNoChange\n\t}\n\tif len(summary) \u003e MaxSummaryLen {\n\t\treturn nil, ErrSummaryTooLong\n\t}\n\treturn w.commit(p, p.Title, author, now, height, body, summary, KindRevert, false), nil\n}\n\n// Blank replaces a page's content with a tombstone revision. It is the\n// deletion a chain can honestly offer: the page stops rendering and stops\n// costing rent as its bodies age out, while the revision spine stays as proof\n// that something was there and who removed it. Use Purge to release the\n// retained bytes immediately.\nfunc (w *Wiki) Blank(author address, now time.Time, height int64, raw, reason string) (*Revision, error) {\n\tp, err := w.Page(raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(reason) \u003e MaxSummaryLen {\n\t\treturn nil, ErrSummaryTooLong\n\t}\n\trev := w.commit(p, p.Title, author, now, height, \"\", reason, KindBlank, false)\n\tif !p.Blanked {\n\t\tp.Blanked = true\n\t\tw.numPages--\n\t}\n\treturn rev, nil\n}\n\n// Purge evicts every retained body of a page immediately and returns the\n// number of bytes released. The spine, including each body's hash, is\n// untouched. This is the lever for content that must stop being served from\n// realm state; it cannot and does not remove the transactions that wrote it.\nfunc (w *Wiki) Purge(raw string) (int, error) {\n\tp, err := w.Page(raw)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treleased := 0\n\tp.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {\n\t\treleased += v.(*Revision).evict()\n\t\treturn false\n\t})\n\tw.bytesHeld -= released\n\treturn released, nil\n}\n\n// Move renames a page, keeping its history, and leaves a redirect behind at\n// the old title so existing links keep resolving.\nfunc (w *Wiki) Move(author address, now time.Time, height int64, from, to, summary string) error {\n\tsrc, err := w.Page(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdst, err := ParseTitle(to)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif dst.NS == NSSpecial {\n\t\treturn ErrSpecial\n\t}\n\tif w.Exists(dst) {\n\t\treturn ErrPageExists\n\t}\n\n\told := src.Title\n\tw.unindex(src)\n\tw.pages.Remove(old.Key())\n\tsrc.Title = dst\n\tw.pages.Set(dst.Key(), src)\n\tw.index(src)\n\n\tw.pushRecent(src.Title, w.metaRevision(src, author, now, height, \"moved from \"+old.String(), KindMove))\n\n\tstub := \"#REDIRECT [[\" + dst.String() + \"]]\\n\"\n\tw.commit(nil, old, author, now, height, stub, \"moved to \"+dst.String(), KindMove, false)\n\treturn nil\n}\n\n// SetProtection changes a page's edit gate.\nfunc (w *Wiki) SetProtection(author address, now time.Time, height int64, raw, level string) error {\n\tp, err := w.Page(raw)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlvl, err := ParseProtection(level)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.Protection = lvl\n\tw.pushRecent(p.Title, w.metaRevision(p, author, now, height, \"protection: \"+lvl.String(), KindProtect))\n\treturn nil\n}\n\n// metaRevision records an event that changed a page without changing its text\n// (a move, a protection change). It carries no body of its own and inherits\n// the current revision's hash and size, so the history reads as \"this is still\n// the same text\" instead of \"the article was blanked\".\nfunc (w *Wiki) metaRevision(p *Page, author address, now time.Time, height int64, summary string, kind Kind) *Revision {\n\trev := w.newRevision(p, author, now, height, \"\", summary, kind, true)\n\trev.kept = false\n\tif p.head != nil {\n\t\trev.Hash = p.head.Hash\n\t\trev.Size = p.head.Size\n\t}\n\treturn rev\n}\n\n// commit appends a revision, re-derives the page's indexes from the new body\n// and enforces the retention window. p may be nil, in which case the page is\n// created at t.\nfunc (w *Wiki) commit(p *Page, t Title, author address, now time.Time, height int64, body, summary string, kind Kind, minor bool) *Revision {\n\tif p == nil {\n\t\tp = \u0026Page{Title: t, Created: now, revs: ulist.New()}\n\t\tw.pages.Set(t.Key(), p)\n\t\tw.numPages++\n\t} else {\n\t\tw.unindex(p)\n\t\tif p.Blanked \u0026\u0026 body != \"\" {\n\t\t\tp.Blanked = false\n\t\t\tw.numPages++\n\t\t}\n\t}\n\n\trev := w.newRevision(p, author, now, height, body, summary, kind, minor)\n\tp.head = rev\n\tw.reindex(p, body)\n\tw.enforceRetention(p)\n\tw.pushRecent(p.Title, rev)\n\treturn rev\n}\n\n// newRevision allocates the next revision, appends it and accounts its bytes.\nfunc (w *Wiki) newRevision(p *Page, author address, now time.Time, height int64, body, summary string, kind Kind, minor bool) *Revision {\n\tw.nextRev++\n\tprev := uint64(0)\n\tif n := p.revs.Size(); n \u003e 0 {\n\t\tprev = p.revs.MustGet(n - 1).(*Revision).ID\n\t}\n\trev := \u0026Revision{\n\t\tID:      w.nextRev,\n\t\tPrev:    prev,\n\t\tKind:    kind,\n\t\tAuthor:  author,\n\t\tTime:    now,\n\t\tHeight:  height,\n\t\tSummary: summary,\n\t\tHash:    hashBody(body),\n\t\tSize:    len(body),\n\t\tMinor:   minor,\n\t\tbody:    body,\n\t\tkept:    true,\n\t}\n\tp.revs.Append(rev)\n\tw.numRevs++\n\tw.bytesHeld += len(body)\n\treturn rev\n}\n\n// enforceRetention evicts the body that just fell out of the window.\n//\n// It counts only revisions that still hold a body, so bodyless move and\n// protection entries do not push real text out of the window early. One\n// eviction per commit is enough because the window only ever moves by one, and\n// the backward walk is bounded by scanLimit so a page with a long run of meta\n// revisions cannot make a single edit O(history).\nfunc (w *Wiki) enforceRetention(p *Page) {\n\tconst scanLimit = 64\n\tkept, scanned := 0, 0\n\tp.revs.Iterator(p.revs.Size()-1, 0, func(_ int, v any) bool {\n\t\tscanned++\n\t\tr := v.(*Revision)\n\t\tif !r.kept {\n\t\t\treturn scanned \u003e= scanLimit\n\t\t}\n\t\tkept++\n\t\tif kept \u003e w.retention {\n\t\t\tw.bytesHeld -= r.evict()\n\t\t\treturn true\n\t\t}\n\t\treturn scanned \u003e= scanLimit\n\t})\n}\n\nfunc (w *Wiki) pushRecent(t Title, r *Revision) {\n\tw.recent.Prepend(\u0026Change{Title: t, Rev: r})\n}\n\n// Recent returns up to n changes, newest first.\nfunc (w *Wiki) Recent(n int) []*Change {\n\tout := []*Change{}\n\tfor _, e := range w.recent.Entries() {\n\t\tif len(out) \u003e= n {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, e.(*Change))\n\t}\n\treturn out\n}\n\n// reindex derives the page's redirect target, outgoing links and categories\n// from body, and writes them into the wiki-wide indexes.\nfunc (w *Wiki) reindex(p *Page, body string) {\n\tp.redirect = redirectTarget(body)\n\tp.links = nil\n\tp.cats = nil\n\n\tfor _, raw := range ScanLinks(body, \"[[\", \"]]\") {\n\t\tt, err := ParseTitle(raw.Target)\n\t\tif err != nil || t == p.Title {\n\t\t\tcontinue\n\t\t}\n\t\tif t.NS == NSCategory \u0026\u0026 !raw.Explicit {\n\t\t\tp.cats = appendUnique(p.cats, t.Key())\n\t\t\tcontinue\n\t\t}\n\t\tp.links = appendUnique(p.links, t.Key())\n\t}\n\tw.index(p)\n}\n\n// index adds the page to every index its current content implies.\nfunc (w *Wiki) index(p *Page) {\n\tfor _, key := range p.links {\n\t\taddTo(w.backlinks, key, p)\n\t}\n\tfor _, key := range p.cats {\n\t\taddTo(w.cats, key, p)\n\t}\n}\n\n// unindex removes the page from every index, so the next reindex starts clean.\nfunc (w *Wiki) unindex(p *Page) {\n\tfor _, key := range p.links {\n\t\tremoveFrom(w.backlinks, key, p.Title.Key())\n\t}\n\tfor _, key := range p.cats {\n\t\tremoveFrom(w.cats, key, p.Title.Key())\n\t}\n}\n\nfunc addTo(idx *avl.Tree, key string, p *Page) {\n\tv := idx.Get(key)\n\tvar set *avl.Tree\n\tif v == nil {\n\t\tset = avl.NewTree()\n\t\tidx.Set(key, set)\n\t} else {\n\t\tset = v.(*avl.Tree)\n\t}\n\tset.Set(p.Title.Key(), p.Title)\n}\n\nfunc removeFrom(idx *avl.Tree, key, member string) {\n\tv := idx.Get(key)\n\tif v == nil {\n\t\treturn\n\t}\n\tset := v.(*avl.Tree)\n\tset.Remove(member)\n\tif set.Size() == 0 {\n\t\tidx.Remove(key)\n\t}\n}\n\nfunc members(idx *avl.Tree, key string) []Title {\n\tout := []Title{}\n\tv := idx.Get(key)\n\tif v == nil {\n\t\treturn out\n\t}\n\tv.(*avl.Tree).Iterate(\"\", \"\", func(_ string, val any) bool {\n\t\tout = append(out, val.(Title))\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Backlinks returns the titles whose current revision links to t, in key\n// order. Redlinks are indexed too, so a page created later immediately knows\n// who was already pointing at it.\nfunc (w *Wiki) Backlinks(t Title) []Title { return members(w.backlinks, t.Key()) }\n\n// CategoryMembers returns the pages that declare [[Category:name]].\nfunc (w *Wiki) CategoryMembers(t Title) []Title { return members(w.cats, t.Key()) }\n\n// Categories returns every category that has at least one member.\nfunc (w *Wiki) Categories() []Title {\n\tout := []Title{}\n\tw.cats.Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\tout = append(out, Title{NS: NSCategory, Name: key[len(NSCategory.Prefix()):]})\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Titles returns up to count page titles in key order, skipping offset of\n// them. An empty ns prefix walks every namespace.\nfunc (w *Wiki) Titles(prefix string, offset, count int) []Title {\n\tout := []Title{}\n\tskipped := 0\n\tw.pages.Iterate(prefix, \"\", func(key string, v any) bool {\n\t\tif prefix != \"\" \u0026\u0026 !hasPrefix(key, prefix) {\n\t\t\treturn true\n\t\t}\n\t\tif skipped \u003c offset {\n\t\t\tskipped++\n\t\t\treturn false\n\t\t}\n\t\tout = append(out, v.(*Page).Title)\n\t\treturn len(out) \u003e= count\n\t})\n\treturn out\n}\n\nfunc hasPrefix(s, p string) bool { return len(s) \u003e= len(p) \u0026\u0026 s[:len(p)] == p }\n\nfunc appendUnique(list []string, v string) []string {\n\tfor _, e := range list {\n\t\tif e == v {\n\t\t\treturn list\n\t\t}\n\t}\n\treturn append(list, v)\n}\n"},{"name":"wiki_test.gno","body":"package wiki\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tmod   = testutils.TestAddress(\"mod\")\n)\n\n// at returns a deterministic timestamp and height for step n, so tests never\n// depend on wall-clock time or on where a previous test left the block height.\nfunc at(n int) (time.Time, int64) {\n\treturn time.Unix(int64(1757000000+n*60), 0).UTC(), int64(100 + n)\n}\n\nfunc edit(t *testing.T, w *Wiki, n int, author address, title, body, summary string) *Revision {\n\tt.Helper()\n\tnow, h := at(n)\n\trev, err := w.Edit(author, now, h, title, body, summary, false)\n\tuassert.NoError(t, err, title)\n\treturn rev\n}\n\nfunc TestEditCreatesAndUpdates(t *testing.T) {\n\tw := New(DefaultRetention, DefaultMaxBody)\n\n\tr1 := edit(t, w, 1, alice, \"gno_land\", \"The first draft.\\n\", \"create\")\n\tuassert.Equal(t, uint64(1), r1.ID)\n\tuassert.Equal(t, uint64(0), r1.Prev)\n\tuassert.Equal(t, string(KindCreate), string(r1.Kind))\n\n\tr2 := edit(t, w, 2, bob, \"Gno land\", \"The second draft.\\n\", \"expand\")\n\tuassert.Equal(t, uint64(1), r2.Prev)\n\tuassert.Equal(t, string(KindEdit), string(r2.Kind))\n\n\tp, err := w.Page(\"Gno land\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 2, p.NumRevisions())\n\tbody, kept := p.Body()\n\tuassert.True(t, kept)\n\tuassert.Equal(t, \"The second draft.\\n\", body)\n\n\ts := w.Stats()\n\tuassert.Equal(t, 1, s.Pages, \"the two edits are one page\")\n\tuassert.Equal(t, 2, s.Revisions)\n}\n\nfunc TestEditRejectsNoOpAndOversize(t *testing.T) {\n\tw := New(DefaultRetention, 32)\n\tnow, h := at(1)\n\n\t_, err := w.Edit(alice, now, h, \"A\", \"\", \"empty\", false)\n\tuassert.ErrorIs(t, err, ErrEmptyBody)\n\n\t_, err = w.Edit(alice, now, h, \"A\", \"0123456789012345678901234567890123\", \"too big\", false)\n\tuassert.ErrorIs(t, err, ErrBodyTooLarge)\n\n\tedit(t, w, 1, alice, \"A\", \"same\\n\", \"create\")\n\t_, err = w.Edit(alice, now, h, \"A\", \"same\\n\", \"again\", false)\n\tuassert.ErrorIs(t, err, ErrNoChange, \"an identical body must not create a revision\")\n\n\t_, err = w.Edit(alice, now, h, \"Special:Anything\", \"x\\n\", \"\", false)\n\tuassert.ErrorIs(t, err, ErrSpecial)\n}\n\n// TestRetentionEvictsOldBodies is the storage design in one test: the spine\n// grows by a fixed amount per edit, the held bytes do not.\nfunc TestRetentionEvictsOldBodies(t *testing.T) {\n\tw := New(2, DefaultMaxBody)\n\tbodies := []string{\"aaaa\\n\", \"bbbbbb\\n\", \"cccccccc\\n\", \"dddddddddd\\n\"}\n\tfor i, b := range bodies {\n\t\tedit(t, w, i+1, alice, \"A\", b, \"edit\")\n\t}\n\n\tp, err := w.Page(\"A\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 4, p.NumRevisions(), \"every revision stays in the history\")\n\n\tkept := 0\n\tfor _, r := range p.History(0, 10) {\n\t\tif r.Kept() {\n\t\t\tkept++\n\t\t}\n\t}\n\tuassert.Equal(t, 2, kept, \"only the retention window keeps bodies\")\n\tuassert.Equal(t, len(bodies[2])+len(bodies[3]), w.Stats().BytesHeld)\n\n\t// The spine of an evicted revision is intact, hash included.\n\toldest := p.History(0, 10)[3]\n\tuassert.False(t, oldest.Kept())\n\tuassert.Equal(t, hashBody(bodies[0]), oldest.Hash)\n\tuassert.Equal(t, len(bodies[0]), oldest.Size)\n}\n\nfunc TestRevert(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tfirst := edit(t, w, 1, alice, \"A\", \"good\\n\", \"create\")\n\tedit(t, w, 2, bob, \"A\", \"VANDALISM\\n\", \"oops\")\n\n\tnow, h := at(3)\n\trev, err := w.Revert(mod, now, h, \"A\", first.ID, \"rv\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, string(KindRevert), string(rev.Kind))\n\n\tp, _ := w.Page(\"A\")\n\tbody, _ := p.Body()\n\tuassert.Equal(t, \"good\\n\", body)\n\tuassert.Equal(t, 3, p.NumRevisions(), \"the vandalism stays in the history\")\n}\n\nfunc TestRevertRefusesEvictedAndUnknown(t *testing.T) {\n\tw := New(1, DefaultMaxBody)\n\tfirst := edit(t, w, 1, alice, \"A\", \"one\\n\", \"\")\n\tedit(t, w, 2, alice, \"A\", \"two\\n\", \"\")\n\tnow, h := at(3)\n\n\t_, err := w.Revert(alice, now, h, \"A\", first.ID, \"\")\n\tuassert.ErrorIs(t, err, ErrBodyEvicted,\n\t\t\"reverting past the retention window must fail loudly, not silently\")\n\n\t_, err = w.Revert(alice, now, h, \"A\", 9999, \"\")\n\tuassert.ErrorIs(t, err, ErrNoSuchRevision)\n}\n\nfunc TestBlankAndPurge(t *testing.T) {\n\tw := New(5, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"content\\n\", \"\")\n\tedit(t, w, 2, alice, \"A\", \"more content\\n\", \"\")\n\tuassert.Equal(t, 1, w.Stats().Pages)\n\n\tnow, h := at(3)\n\t_, err := w.Blank(mod, now, h, \"A\", \"policy\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 0, w.Stats().Pages, \"a blanked page stops counting as a page\")\n\n\tp, _ := w.Page(\"A\")\n\tuassert.True(t, p.Blanked)\n\tuassert.Equal(t, 3, p.NumRevisions(), \"blanking is a revision, not an erasure\")\n\n\treleased, err := w.Purge(\"A\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, len(\"content\\n\")+len(\"more content\\n\"), released)\n\tuassert.Equal(t, 0, w.Stats().BytesHeld, \"purge releases every retained byte\")\n\tuassert.Equal(t, 3, p.NumRevisions(), \"purge leaves the spine intact\")\n}\n\nfunc TestBlankThenEditRestoresThePage(t *testing.T) {\n\tw := New(5, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"content\\n\", \"\")\n\tnow, h := at(2)\n\tw.Blank(mod, now, h, \"A\", \"\")\n\tedit(t, w, 3, alice, \"A\", \"back\\n\", \"restore\")\n\tuassert.Equal(t, 1, w.Stats().Pages)\n\tp, _ := w.Page(\"A\")\n\tuassert.False(t, p.Blanked)\n}\n\nfunc TestBacklinksAndRedlinks(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"links to [[B]] and [[C]]\\n\", \"\")\n\tedit(t, w, 2, alice, \"D\", \"also links to [[B]]\\n\", \"\")\n\n\tb := MustParseTitle(\"B\")\n\tin := w.Backlinks(b)\n\tuassert.Equal(t, 2, len(in))\n\tuassert.Equal(t, \"A\", in[0].String())\n\tuassert.Equal(t, \"D\", in[1].String())\n\n\t// C does not exist: a redlink is still indexed, so the page knows who is\n\t// waiting for it the moment it is created.\n\tuassert.False(t, w.Exists(MustParseTitle(\"C\")))\n\tuassert.Equal(t, 1, len(w.Backlinks(MustParseTitle(\"C\"))))\n\n\t// Editing A to drop the link must un-index it.\n\tedit(t, w, 3, alice, \"A\", \"links to nothing\\n\", \"\")\n\tuassert.Equal(t, 1, len(w.Backlinks(b)))\n\tuassert.Equal(t, 0, len(w.Backlinks(MustParseTitle(\"C\"))))\n}\n\nfunc TestCategories(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"text\\n[[Category:Chains]]\\n\", \"\")\n\tedit(t, w, 2, alice, \"B\", \"text\\n[[Category:Chains]]\\n[[Category:Tools]]\\n\", \"\")\n\n\tchains := MustParseTitle(\"Category:Chains\")\n\tuassert.Equal(t, 2, len(w.CategoryMembers(chains)))\n\tuassert.Equal(t, 2, len(w.Categories()))\n\n\t// An explicit [[:Category:X]] links to the category instead of joining it.\n\tedit(t, w, 3, alice, \"C\", \"see [[:Category:Chains]]\\n\", \"\")\n\tuassert.Equal(t, 2, len(w.CategoryMembers(chains)))\n\tuassert.Equal(t, 1, len(w.Backlinks(chains)))\n}\n\nfunc TestRedirect(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"Gno\", \"#REDIRECT [[Gno land]]\\n\", \"\")\n\tedit(t, w, 2, alice, \"Gno land\", \"The article.\\n\", \"\")\n\n\tdest, asked, err := w.Resolve(\"Gno\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"Gno land\", dest.Title.String())\n\tuassert.Equal(t, \"Gno\", asked.Title.String())\n\n\t// A dangling redirect renders itself rather than 404ing.\n\tedit(t, w, 3, alice, \"Nowhere\", \"#REDIRECT [[Absent]]\\n\", \"\")\n\tdest, _, err = w.Resolve(\"Nowhere\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"Nowhere\", dest.Title.String())\n}\n\nfunc TestMoveKeepsHistoryAndLeavesARedirect(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"Old name\", \"body linking to [[B]]\\n\", \"\")\n\tedit(t, w, 2, alice, \"Old name\", \"body linking to [[B]], revised\\n\", \"\")\n\n\tnow, h := at(3)\n\tuassert.NoError(t, w.Move(mod, now, h, \"Old name\", \"New name\", \"rename\"))\n\n\tmoved, err := w.Page(\"New name\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 3, moved.NumRevisions(), \"history follows the page\")\n\tbody, kept := moved.Body()\n\tuassert.True(t, kept)\n\tuassert.Equal(t, \"body linking to [[B]], revised\\n\", body, \"a move does not touch the text\")\n\n\tstub, err := w.Page(\"Old name\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"New name\", stub.Redirect())\n\n\t// The backlink index must follow the rename, not point at the old key.\n\tin := w.Backlinks(MustParseTitle(\"B\"))\n\tuassert.Equal(t, 1, len(in))\n\tuassert.Equal(t, \"New name\", in[0].String())\n}\n\nfunc TestMoveRefusesAnExistingTarget(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"a\\n\", \"\")\n\tedit(t, w, 2, alice, \"B\", \"b\\n\", \"\")\n\tnow, h := at(3)\n\tuassert.ErrorIs(t, w.Move(mod, now, h, \"A\", \"B\", \"\"), ErrPageExists)\n}\n\nfunc TestProtectionIsRecordedInTheHistory(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"a\\n\", \"\")\n\tnow, h := at(2)\n\tuassert.NoError(t, w.SetProtection(mod, now, h, \"A\", \"locked\"))\n\n\tp, _ := w.Page(\"A\")\n\tuassert.Equal(t, \"locked\", p.Protection.String())\n\tuassert.Equal(t, 2, p.NumRevisions())\n\n\t// The protection entry must not become the current text.\n\tbody, kept := p.Body()\n\tuassert.True(t, kept)\n\tuassert.Equal(t, \"a\\n\", body)\n\n\t// It carries the current hash, so the history does not read as a blanking.\n\tlast := p.History(0, 1)[0]\n\tuassert.Equal(t, string(KindProtect), string(last.Kind))\n\tuassert.Equal(t, hashBody(\"a\\n\"), last.Hash)\n}\n\nfunc TestMetaRevisionsDoNotEvictRealBodies(t *testing.T) {\n\tw := New(2, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"one\\n\", \"\")\n\tedit(t, w, 2, alice, \"A\", \"two\\n\", \"\")\n\tnow, h := at(3)\n\tw.SetProtection(mod, now, h, \"A\", \"locked\")\n\tw.SetProtection(mod, now, h, \"A\", \"open\")\n\n\tp, _ := w.Page(\"A\")\n\tkept := 0\n\tfor _, r := range p.History(0, 10) {\n\t\tif r.Kept() {\n\t\t\tkept++\n\t\t}\n\t}\n\tuassert.Equal(t, 2, kept, \"two bodyless entries must not push both bodies out of a window of 2\")\n}\n\nfunc TestRecentChangesIsNewestFirst(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"a\\n\", \"first\")\n\tedit(t, w, 2, bob, \"B\", \"b\\n\", \"second\")\n\n\trecent := w.Recent(10)\n\tuassert.Equal(t, 2, len(recent))\n\tuassert.Equal(t, \"B\", recent[0].Title.String())\n\tuassert.Equal(t, \"A\", recent[1].Title.String())\n}\n\nfunc TestTitlesWalkOneNamespace(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"Beta\", \"b\\n\", \"\")\n\tedit(t, w, 2, alice, \"Alpha\", \"a\\n\", \"\")\n\tedit(t, w, 3, alice, \"Help:Alpha\", \"t\\n\", \"\")\n\n\tmain := w.Titles(NSMain.Prefix(), 0, 10)\n\tuassert.Equal(t, 2, len(main))\n\tuassert.Equal(t, \"Alpha\", main[0].String())\n\tuassert.Equal(t, \"Beta\", main[1].String())\n\n\thelp := w.Titles(NSHelp.Prefix(), 0, 10)\n\tuassert.Equal(t, 1, len(help))\n\tuassert.Equal(t, \"Help:Alpha\", help[0].String())\n\n\tuassert.Equal(t, 1, len(w.Titles(NSMain.Prefix(), 1, 10)), \"offset skips\")\n}\n\nfunc TestContributors(t *testing.T) {\n\tw := New(3, DefaultMaxBody)\n\tedit(t, w, 1, alice, \"A\", \"1\\n\", \"\")\n\tedit(t, w, 2, bob, \"A\", \"2\\n\", \"\")\n\tedit(t, w, 3, alice, \"A\", \"3\\n\", \"\")\n\n\tp, _ := w.Page(\"A\")\n\tc := p.Contributors()\n\tuassert.Equal(t, 2, len(c))\n\tuassert.Equal(t, alice.String(), c[0].String())\n\tuassert.Equal(t, bob.String(), c[1].String())\n}\n\nfunc TestFormatGNOT(t *testing.T) {\n\tcases := []struct {\n\t\tin   int\n\t\twant string\n\t}{\n\t\t{0, \"0 GNOT\"},\n\t\t{1000000, \"1 GNOT\"},\n\t\t{1500000, \"1.5 GNOT\"},\n\t\t{100, \"0.0001 GNOT\"},\n\t\t{123456, \"0.123456 GNOT\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, formatGNOT(tc.in))\n\t}\n}\n"}]},"send":"","max_deposit":"41000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"xmath","path":"gno.land/p/moul/xmath/v1","files":[{"name":"README.md","body":"# `gno.land/p/moul/xmath/v1`\n\n`Max`, `Min`, `Clamp`, `Abs` and `Sign` for every built-in numeric type, one\nconcrete function per type. Gno has no generics, so the alternative is writing\nthe same three-line helper again in each realm.\n\n```go\nxmath.MaxInt(3, 7)             // 7\nxmath.ClampInt64(x, 0, 100)    // x, bounded to [0,100]\nxmath.AbsFloat64(-2.5)         // 2.5\nxmath.SignInt(-9)              // -1\n```\n\n| type | functions |\n| --- | --- |\n| `int`, `int8`, `int16`, `int32`, `int64` | `Max`, `Min`, `Clamp`, `Abs`, `Sign` |\n| `uint`, `uint8`, `uint16`, `uint32`, `uint64` | `Max`, `Min`, `Clamp` |\n| `float32`, `float64` | `Max`, `Min`, `Clamp`, `Abs`, `Sign` |\n\nUnsigned types get no `Abs` or `Sign`: both are trivially themselves and 1, and\noffering them would only invite an overflow bug at the call site.\n\nThe name is the type suffix: `MaxInt8`, `MinUint64`, `ClampFloat32`.\n\n`Sign` returns -1, 0 or 1. `Clamp` does not validate its bounds: calling it\nwith `min \u003e max` returns one bound or the other depending on the value, so\ncheck the bounds yourself if they are computed.\n\n## Generated\n\n`xmath.gen.gno` and `xmath.gen_test.gno` are written by\n[`tools/xmathgen`](../../../tools/xmathgen) and carry a `DO NOT EDIT` header.\nEdit the generator, never the output:\n\n```sh\ngo -C tools run ./xmathgen           # rewrite both files\ngo -C tools run ./xmathgen -check    # fail if they are stale\n```\n\nAdding a type is one row in the `types` table in `tools/xmathgen/main.go`; it\nexpands to 5 functions plus their tests.\n\nThe header used to name a `generator.go` that was never committed, so it was a\nrule nobody could follow. The generator above was reconstructed from the output\nit describes and reproduces both committed files byte for byte, which\n`go test ./tools/xmathgen` asserts on every run.\n\n## `MulDiv`: the proportional share, through a 128-bit intermediate\n\nHand-written rather than generated, in `muldiv.gno`, because it is one function\nand not a per-type family.\n\n```go\nxmath.MulDiv(pot, stake, total)    // this stake's cut, rounded toward zero\nxmath.MulDivUp(pot, stake, total)  // the same ratio, rounded away from zero\n```\n\n`a*b/c` computes `a*b` first, and an int64 product that does not fit **wraps\nsilently to a plausible number**. Measured with `a = 2^62`, `b = 4`, `c = 8`:\nthe true share is `2305843009213693952` and the naive form answers **`0`**,\nbecause `2^62 * 4` is exactly `2^64` and wraps to zero. Nothing fails, nothing\nlogs, and a payout split is simply wrong.\n\n**Ten realms deployed on gnoland-1 carry their own copy of this**, all reaching\nfor `math/bits` the same way: `bubblerumble` (several versions) and `kourt`,\nwhose `mulDiv128` is the same function with its own panic strings. It had no\nowner in `p/moul` or `p/nt` until now.\n\n`MulDiv` panics rather than returning a wrong number: on a negative operand, on\na denominator at or below zero, and on a quotient that does not fit.\n\n**`MulDivUp` exists because rounding is a money question, not a style one.**\nRounding a fee down and a payout up is how a pool pays out more than it holds.\nUse `MulDiv` for what someone receives and `MulDivUp` for what someone owes;\n`TestRoundingDirectionIsTheMoneyQuestion` pins that they never differ by more\nthan one and never cross.\n\n### Why `v1` even though adding a function is non-breaking\n\nIt is non-breaking **for this repo**, and that is not the constraint that\nmatters. `p/` packages are always public, and a live public path can never be\nredeployed, so functions added in place at `v0` reach `main` and never reach the\nchain. `v1` is the only way `MulDiv` becomes importable by anybody.\n\nThe bump is free here: `xmath` has **zero importers**, in this repo and across\nevery package deployed on `gnoland-1`. `v0` stays resolvable for nobody in\nparticular.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/xmath/v1\"\ngno = \"0.9\"\n"},{"name":"muldiv.gno","body":"package xmath\n\nimport \"math/bits\"\n\n// maxInt64 is the largest int64. Unexported and spelled out because xmath\n// already exports MaxInt64 as the max-of-two helper, and a constant sharing\n// that name would shadow it.\nconst maxInt64 = int64(9223372036854775807)\n\n// MulDiv returns a*b/c computed through a 128-bit intermediate, so the product\n// does not have to fit in an int64. It is the proportional-share calculation:\n// \"this account's cut of the pot\", \"this stake's slice of the rewards\".\n//\n// The naive a*b/c silently wraps when a*b exceeds an int64, and it wraps to a\n// plausible-looking number rather than to an obvious one, which is how a payout\n// split leaks money without anything failing. Ten realms deployed on gnoland-1\n// carry their own copy of this function for exactly that reason, and every one\n// of them reaches for math/bits the same way.\n//\n// MulDiv panics rather than returning a wrong number:\n//\n//   - a or b negative, or c at or below zero: the domain is unsigned ratios,\n//     and a negative share is a caller bug, not a value to propagate.\n//   - the quotient not fitting in an int64.\n//\n// Rounding is toward zero, like integer division. See [MulDivUp] when the\n// remainder must favour the payer instead.\nfunc MulDiv(a, b, c int64) int64 {\n\tif a \u003c 0 || b \u003c 0 {\n\t\tpanic(\"xmath: MulDiv on a negative operand\")\n\t}\n\tif c \u003c= 0 {\n\t\tpanic(\"xmath: MulDiv by a non-positive denominator\")\n\t}\n\thi, lo := bits.Mul64(uint64(a), uint64(b))\n\tif hi \u003e= uint64(c) {\n\t\tpanic(\"xmath: MulDiv quotient overflows int64\")\n\t}\n\tq, _ := bits.Div64(hi, lo, uint64(c))\n\tif q \u003e uint64(maxInt64) {\n\t\tpanic(\"xmath: MulDiv quotient overflows int64\")\n\t}\n\treturn int64(q)\n}\n\n// MulDivUp is [MulDiv] rounding away from zero when the division is not exact.\n//\n// Which way to round is a money question, not a style one: rounding a fee down\n// and a payout up is how a pool pays out more than it holds. Use MulDiv for\n// what someone receives and MulDivUp for what someone owes.\nfunc MulDivUp(a, b, c int64) int64 {\n\tq := MulDiv(a, b, c)\n\thi, lo := bits.Mul64(uint64(a), uint64(b))\n\t_, rem := bits.Div64(hi, lo, uint64(c))\n\tif rem != 0 {\n\t\tif q == maxInt64 {\n\t\t\tpanic(\"xmath: MulDivUp quotient overflows int64\")\n\t\t}\n\t\tq++\n\t}\n\treturn q\n}\n\n"},{"name":"muldiv_test.gno","body":"package xmath\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestMulDiv(t *testing.T) {\n\tcases := []struct {\n\t\tname    string\n\t\ta, b, c int64\n\t\twant    int64\n\t}{\n\t\t{\"exact\", 10, 3, 5, 6},\n\t\t{\"rounds toward zero\", 10, 1, 3, 3},\n\t\t{\"identity\", 7, 1, 1, 7},\n\t\t{\"zero numerator\", 0, 99, 7, 0},\n\t\t{\"half of a pot\", 1000000, 50, 100, 500000},\n\t\t{\"one basis point\", 1000000, 1, 10000, 100},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, MulDiv(tc.a, tc.b, tc.c))\n\t\t})\n\t}\n}\n\n// TestMulDivSurvivesAnIntermediateThatDoesNotFit is the whole point. The naive\n// a*b/c computes a*b first, which wraps past the int64 maximum and wraps to a\n// plausible number rather than an obvious one. Through a 128-bit intermediate\n// the answer is exact.\nfunc TestMulDivSurvivesAnIntermediateThatDoesNotFit(t *testing.T) {\n\t// A variable, not a const: gno rejects a constant expression that\n\t// overflows at compile time, and the point here is the runtime wrap.\n\tbig := int64(1) \u003c\u003c 62 // 4611686018427387904\n\tfour := int64(4)\n\n\t// big*4 overflows int64; big*4/8 is big/2 and fits comfortably.\n\tuassert.Equal(t, big/2, MulDiv(big, four, 8))\n\n\t// The naive form, computed here so the test shows what it would have done\n\t// rather than asserting it in prose.\n\tnaive := (big * four) / 8\n\tuassert.NotEqual(t, big/2, naive)\n\n\t// big*4 is exactly 2^64, so it wraps to 0 and the naive form answers 0 for\n\t// a share that is actually 2305843009213693952. Measured, not assumed: the\n\t// first version of this test asserted the wrap went negative, which is the\n\t// intuition and is wrong for this input.\n\tuassert.Equal(t, int64(0), naive)\n}\n\nfunc TestMulDivRefusesRatherThanReturningAWrongNumber(t *testing.T) {\n\tbig := int64(1) \u003c\u003c 62\n\tcases := []struct {\n\t\tname    string\n\t\ta, b, c int64\n\t\tmsg     string\n\t}{\n\t\t{\"negative a\", -1, 2, 3, \"xmath: MulDiv on a negative operand\"},\n\t\t{\"negative b\", 1, -2, 3, \"xmath: MulDiv on a negative operand\"},\n\t\t{\"zero denominator\", 1, 2, 0, \"xmath: MulDiv by a non-positive denominator\"},\n\t\t{\"negative denominator\", 1, 2, -3, \"xmath: MulDiv by a non-positive denominator\"},\n\t\t{\"quotient too large\", big, 8, 2, \"xmath: MulDiv quotient overflows int64\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tdefer func() {\n\t\t\t\tr := recover()\n\t\t\t\tif r == nil {\n\t\t\t\t\tt.Errorf(\"MulDiv(%d,%d,%d) did not panic\", tc.a, tc.b, tc.c)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tuassert.Equal(t, tc.msg, r.(string))\n\t\t\t}()\n\t\t\tMulDiv(tc.a, tc.b, tc.c)\n\t\t})\n\t}\n}\n\nfunc TestMulDivUpRoundsAwayFromZero(t *testing.T) {\n\tcases := []struct {\n\t\tname    string\n\t\ta, b, c int64\n\t\twant    int64\n\t}{\n\t\t{\"exact is unchanged\", 10, 3, 5, 6},\n\t\t{\"inexact rounds up\", 10, 1, 3, 4},\n\t\t{\"one short rounds up\", 7, 1, 2, 4},\n\t\t{\"zero stays zero\", 0, 5, 3, 0},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, MulDivUp(tc.a, tc.b, tc.c))\n\t\t})\n\t}\n}\n\n// TestRoundingDirectionIsTheMoneyQuestion states the invariant the two\n// functions exist to give a caller: what is received never exceeds what is\n// owed for the same ratio, so a pool cannot pay out more than it holds.\nfunc TestRoundingDirectionIsTheMoneyQuestion(t *testing.T) {\n\tfor _, n := range []int64{1, 2, 3, 7, 99, 1000001} {\n\t\tdown := MulDiv(n, 1, 3)\n\t\tup := MulDivUp(n, 1, 3)\n\t\tif up \u003c down {\n\t\t\tt.Errorf(\"MulDivUp(%d,1,3)=%d below MulDiv=%d\", n, up, down)\n\t\t}\n\t\tif up-down \u003e 1 {\n\t\t\tt.Errorf(\"MulDivUp(%d,1,3)=%d more than one above MulDiv=%d\", n, up, down)\n\t\t}\n\t}\n}\n"},{"name":"xmath.gen.gno","body":"// Code generated by generator.go; DO NOT EDIT.\npackage xmath\n\n// Int8 helpers\nfunc MaxInt8(a, b int8) int8 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinInt8(a, b int8) int8 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampInt8(value, min, max int8) int8 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\nfunc AbsInt8(x int8) int8 {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc SignInt8(x int8) int8 {\n\tif x \u003c 0 {\n\t\treturn -1\n\t}\n\tif x \u003e 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// Int16 helpers\nfunc MaxInt16(a, b int16) int16 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinInt16(a, b int16) int16 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampInt16(value, min, max int16) int16 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\nfunc AbsInt16(x int16) int16 {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc SignInt16(x int16) int16 {\n\tif x \u003c 0 {\n\t\treturn -1\n\t}\n\tif x \u003e 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// Int32 helpers\nfunc MaxInt32(a, b int32) int32 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinInt32(a, b int32) int32 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampInt32(value, min, max int32) int32 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\nfunc AbsInt32(x int32) int32 {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc SignInt32(x int32) int32 {\n\tif x \u003c 0 {\n\t\treturn -1\n\t}\n\tif x \u003e 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// Int64 helpers\nfunc MaxInt64(a, b int64) int64 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinInt64(a, b int64) int64 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampInt64(value, min, max int64) int64 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\nfunc AbsInt64(x int64) int64 {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc SignInt64(x int64) int64 {\n\tif x \u003c 0 {\n\t\treturn -1\n\t}\n\tif x \u003e 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// Int helpers\nfunc MaxInt(a, b int) int {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinInt(a, b int) int {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampInt(value, min, max int) int {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\nfunc AbsInt(x int) int {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc SignInt(x int) int {\n\tif x \u003c 0 {\n\t\treturn -1\n\t}\n\tif x \u003e 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// Uint8 helpers\nfunc MaxUint8(a, b uint8) uint8 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinUint8(a, b uint8) uint8 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampUint8(value, min, max uint8) uint8 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\n// Uint16 helpers\nfunc MaxUint16(a, b uint16) uint16 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinUint16(a, b uint16) uint16 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampUint16(value, min, max uint16) uint16 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\n// Uint32 helpers\nfunc MaxUint32(a, b uint32) uint32 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinUint32(a, b uint32) uint32 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampUint32(value, min, max uint32) uint32 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\n// Uint64 helpers\nfunc MaxUint64(a, b uint64) uint64 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinUint64(a, b uint64) uint64 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampUint64(value, min, max uint64) uint64 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\n// Uint helpers\nfunc MaxUint(a, b uint) uint {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinUint(a, b uint) uint {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampUint(value, min, max uint) uint {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\n// Float32 helpers\nfunc MaxFloat32(a, b float32) float32 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinFloat32(a, b float32) float32 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampFloat32(value, min, max float32) float32 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\nfunc AbsFloat32(x float32) float32 {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc SignFloat32(x float32) float32 {\n\tif x \u003c 0 {\n\t\treturn -1\n\t}\n\tif x \u003e 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// Float64 helpers\nfunc MaxFloat64(a, b float64) float64 {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc MinFloat64(a, b float64) float64 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc ClampFloat64(value, min, max float64) float64 {\n\tif value \u003c min {\n\t\treturn min\n\t}\n\tif value \u003e max {\n\t\treturn max\n\t}\n\treturn value\n}\n\nfunc AbsFloat64(x float64) float64 {\n\tif x \u003c 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc SignFloat64(x float64) float64 {\n\tif x \u003c 0 {\n\t\treturn -1\n\t}\n\tif x \u003e 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n"},{"name":"xmath.gen_test.gno","body":"package xmath\n\nimport \"testing\"\n\nfunc TestInt8Helpers(t *testing.T) {\n\t// Test MaxInt8\n\tif MaxInt8(1, 2) != 2 {\n\t\tt.Error(\"MaxInt8(1, 2) should be 2\")\n\t}\n\tif MaxInt8(-1, -2) != -1 {\n\t\tt.Error(\"MaxInt8(-1, -2) should be -1\")\n\t}\n\n\t// Test MinInt8\n\tif MinInt8(1, 2) != 1 {\n\t\tt.Error(\"MinInt8(1, 2) should be 1\")\n\t}\n\tif MinInt8(-1, -2) != -2 {\n\t\tt.Error(\"MinInt8(-1, -2) should be -2\")\n\t}\n\n\t// Test ClampInt8\n\tif ClampInt8(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampInt8(5, 1, 3) should be 3\")\n\t}\n\tif ClampInt8(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampInt8(0, 1, 3) should be 1\")\n\t}\n\tif ClampInt8(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampInt8(2, 1, 3) should be 2\")\n\t}\n\n\t// Test AbsInt8\n\tif AbsInt8(-5) != 5 {\n\t\tt.Error(\"AbsInt8(-5) should be 5\")\n\t}\n\tif AbsInt8(5) != 5 {\n\t\tt.Error(\"AbsInt8(5) should be 5\")\n\t}\n\n\t// Test SignInt8\n\tif SignInt8(-5) != -1 {\n\t\tt.Error(\"SignInt8(-5) should be -1\")\n\t}\n\tif SignInt8(5) != 1 {\n\t\tt.Error(\"SignInt8(5) should be 1\")\n\t}\n\tif SignInt8(0) != 0 {\n\t\tt.Error(\"SignInt8(0) should be 0\")\n\t}\n\n}\n\nfunc TestInt16Helpers(t *testing.T) {\n\t// Test MaxInt16\n\tif MaxInt16(1, 2) != 2 {\n\t\tt.Error(\"MaxInt16(1, 2) should be 2\")\n\t}\n\tif MaxInt16(-1, -2) != -1 {\n\t\tt.Error(\"MaxInt16(-1, -2) should be -1\")\n\t}\n\n\t// Test MinInt16\n\tif MinInt16(1, 2) != 1 {\n\t\tt.Error(\"MinInt16(1, 2) should be 1\")\n\t}\n\tif MinInt16(-1, -2) != -2 {\n\t\tt.Error(\"MinInt16(-1, -2) should be -2\")\n\t}\n\n\t// Test ClampInt16\n\tif ClampInt16(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampInt16(5, 1, 3) should be 3\")\n\t}\n\tif ClampInt16(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampInt16(0, 1, 3) should be 1\")\n\t}\n\tif ClampInt16(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampInt16(2, 1, 3) should be 2\")\n\t}\n\n\t// Test AbsInt16\n\tif AbsInt16(-5) != 5 {\n\t\tt.Error(\"AbsInt16(-5) should be 5\")\n\t}\n\tif AbsInt16(5) != 5 {\n\t\tt.Error(\"AbsInt16(5) should be 5\")\n\t}\n\n\t// Test SignInt16\n\tif SignInt16(-5) != -1 {\n\t\tt.Error(\"SignInt16(-5) should be -1\")\n\t}\n\tif SignInt16(5) != 1 {\n\t\tt.Error(\"SignInt16(5) should be 1\")\n\t}\n\tif SignInt16(0) != 0 {\n\t\tt.Error(\"SignInt16(0) should be 0\")\n\t}\n\n}\n\nfunc TestInt32Helpers(t *testing.T) {\n\t// Test MaxInt32\n\tif MaxInt32(1, 2) != 2 {\n\t\tt.Error(\"MaxInt32(1, 2) should be 2\")\n\t}\n\tif MaxInt32(-1, -2) != -1 {\n\t\tt.Error(\"MaxInt32(-1, -2) should be -1\")\n\t}\n\n\t// Test MinInt32\n\tif MinInt32(1, 2) != 1 {\n\t\tt.Error(\"MinInt32(1, 2) should be 1\")\n\t}\n\tif MinInt32(-1, -2) != -2 {\n\t\tt.Error(\"MinInt32(-1, -2) should be -2\")\n\t}\n\n\t// Test ClampInt32\n\tif ClampInt32(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampInt32(5, 1, 3) should be 3\")\n\t}\n\tif ClampInt32(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampInt32(0, 1, 3) should be 1\")\n\t}\n\tif ClampInt32(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampInt32(2, 1, 3) should be 2\")\n\t}\n\n\t// Test AbsInt32\n\tif AbsInt32(-5) != 5 {\n\t\tt.Error(\"AbsInt32(-5) should be 5\")\n\t}\n\tif AbsInt32(5) != 5 {\n\t\tt.Error(\"AbsInt32(5) should be 5\")\n\t}\n\n\t// Test SignInt32\n\tif SignInt32(-5) != -1 {\n\t\tt.Error(\"SignInt32(-5) should be -1\")\n\t}\n\tif SignInt32(5) != 1 {\n\t\tt.Error(\"SignInt32(5) should be 1\")\n\t}\n\tif SignInt32(0) != 0 {\n\t\tt.Error(\"SignInt32(0) should be 0\")\n\t}\n\n}\n\nfunc TestInt64Helpers(t *testing.T) {\n\t// Test MaxInt64\n\tif MaxInt64(1, 2) != 2 {\n\t\tt.Error(\"MaxInt64(1, 2) should be 2\")\n\t}\n\tif MaxInt64(-1, -2) != -1 {\n\t\tt.Error(\"MaxInt64(-1, -2) should be -1\")\n\t}\n\n\t// Test MinInt64\n\tif MinInt64(1, 2) != 1 {\n\t\tt.Error(\"MinInt64(1, 2) should be 1\")\n\t}\n\tif MinInt64(-1, -2) != -2 {\n\t\tt.Error(\"MinInt64(-1, -2) should be -2\")\n\t}\n\n\t// Test ClampInt64\n\tif ClampInt64(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampInt64(5, 1, 3) should be 3\")\n\t}\n\tif ClampInt64(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampInt64(0, 1, 3) should be 1\")\n\t}\n\tif ClampInt64(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampInt64(2, 1, 3) should be 2\")\n\t}\n\n\t// Test AbsInt64\n\tif AbsInt64(-5) != 5 {\n\t\tt.Error(\"AbsInt64(-5) should be 5\")\n\t}\n\tif AbsInt64(5) != 5 {\n\t\tt.Error(\"AbsInt64(5) should be 5\")\n\t}\n\n\t// Test SignInt64\n\tif SignInt64(-5) != -1 {\n\t\tt.Error(\"SignInt64(-5) should be -1\")\n\t}\n\tif SignInt64(5) != 1 {\n\t\tt.Error(\"SignInt64(5) should be 1\")\n\t}\n\tif SignInt64(0) != 0 {\n\t\tt.Error(\"SignInt64(0) should be 0\")\n\t}\n\n}\n\nfunc TestIntHelpers(t *testing.T) {\n\t// Test MaxInt\n\tif MaxInt(1, 2) != 2 {\n\t\tt.Error(\"MaxInt(1, 2) should be 2\")\n\t}\n\tif MaxInt(-1, -2) != -1 {\n\t\tt.Error(\"MaxInt(-1, -2) should be -1\")\n\t}\n\n\t// Test MinInt\n\tif MinInt(1, 2) != 1 {\n\t\tt.Error(\"MinInt(1, 2) should be 1\")\n\t}\n\tif MinInt(-1, -2) != -2 {\n\t\tt.Error(\"MinInt(-1, -2) should be -2\")\n\t}\n\n\t// Test ClampInt\n\tif ClampInt(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampInt(5, 1, 3) should be 3\")\n\t}\n\tif ClampInt(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampInt(0, 1, 3) should be 1\")\n\t}\n\tif ClampInt(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampInt(2, 1, 3) should be 2\")\n\t}\n\n\t// Test AbsInt\n\tif AbsInt(-5) != 5 {\n\t\tt.Error(\"AbsInt(-5) should be 5\")\n\t}\n\tif AbsInt(5) != 5 {\n\t\tt.Error(\"AbsInt(5) should be 5\")\n\t}\n\n\t// Test SignInt\n\tif SignInt(-5) != -1 {\n\t\tt.Error(\"SignInt(-5) should be -1\")\n\t}\n\tif SignInt(5) != 1 {\n\t\tt.Error(\"SignInt(5) should be 1\")\n\t}\n\tif SignInt(0) != 0 {\n\t\tt.Error(\"SignInt(0) should be 0\")\n\t}\n\n}\n\nfunc TestUint8Helpers(t *testing.T) {\n\t// Test MaxUint8\n\tif MaxUint8(1, 2) != 2 {\n\t\tt.Error(\"MaxUint8(1, 2) should be 2\")\n\t}\n\n\t// Test MinUint8\n\tif MinUint8(1, 2) != 1 {\n\t\tt.Error(\"MinUint8(1, 2) should be 1\")\n\t}\n\n\t// Test ClampUint8\n\tif ClampUint8(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampUint8(5, 1, 3) should be 3\")\n\t}\n\tif ClampUint8(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampUint8(0, 1, 3) should be 1\")\n\t}\n\tif ClampUint8(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampUint8(2, 1, 3) should be 2\")\n\t}\n\n}\n\nfunc TestUint16Helpers(t *testing.T) {\n\t// Test MaxUint16\n\tif MaxUint16(1, 2) != 2 {\n\t\tt.Error(\"MaxUint16(1, 2) should be 2\")\n\t}\n\n\t// Test MinUint16\n\tif MinUint16(1, 2) != 1 {\n\t\tt.Error(\"MinUint16(1, 2) should be 1\")\n\t}\n\n\t// Test ClampUint16\n\tif ClampUint16(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampUint16(5, 1, 3) should be 3\")\n\t}\n\tif ClampUint16(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampUint16(0, 1, 3) should be 1\")\n\t}\n\tif ClampUint16(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampUint16(2, 1, 3) should be 2\")\n\t}\n\n}\n\nfunc TestUint32Helpers(t *testing.T) {\n\t// Test MaxUint32\n\tif MaxUint32(1, 2) != 2 {\n\t\tt.Error(\"MaxUint32(1, 2) should be 2\")\n\t}\n\n\t// Test MinUint32\n\tif MinUint32(1, 2) != 1 {\n\t\tt.Error(\"MinUint32(1, 2) should be 1\")\n\t}\n\n\t// Test ClampUint32\n\tif ClampUint32(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampUint32(5, 1, 3) should be 3\")\n\t}\n\tif ClampUint32(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampUint32(0, 1, 3) should be 1\")\n\t}\n\tif ClampUint32(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampUint32(2, 1, 3) should be 2\")\n\t}\n\n}\n\nfunc TestUint64Helpers(t *testing.T) {\n\t// Test MaxUint64\n\tif MaxUint64(1, 2) != 2 {\n\t\tt.Error(\"MaxUint64(1, 2) should be 2\")\n\t}\n\n\t// Test MinUint64\n\tif MinUint64(1, 2) != 1 {\n\t\tt.Error(\"MinUint64(1, 2) should be 1\")\n\t}\n\n\t// Test ClampUint64\n\tif ClampUint64(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampUint64(5, 1, 3) should be 3\")\n\t}\n\tif ClampUint64(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampUint64(0, 1, 3) should be 1\")\n\t}\n\tif ClampUint64(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampUint64(2, 1, 3) should be 2\")\n\t}\n\n}\n\nfunc TestUintHelpers(t *testing.T) {\n\t// Test MaxUint\n\tif MaxUint(1, 2) != 2 {\n\t\tt.Error(\"MaxUint(1, 2) should be 2\")\n\t}\n\n\t// Test MinUint\n\tif MinUint(1, 2) != 1 {\n\t\tt.Error(\"MinUint(1, 2) should be 1\")\n\t}\n\n\t// Test ClampUint\n\tif ClampUint(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampUint(5, 1, 3) should be 3\")\n\t}\n\tif ClampUint(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampUint(0, 1, 3) should be 1\")\n\t}\n\tif ClampUint(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampUint(2, 1, 3) should be 2\")\n\t}\n\n}\n\nfunc TestFloat32Helpers(t *testing.T) {\n\t// Test MaxFloat32\n\tif MaxFloat32(1, 2) != 2 {\n\t\tt.Error(\"MaxFloat32(1, 2) should be 2\")\n\t}\n\tif MaxFloat32(-1, -2) != -1 {\n\t\tt.Error(\"MaxFloat32(-1, -2) should be -1\")\n\t}\n\n\t// Test MinFloat32\n\tif MinFloat32(1, 2) != 1 {\n\t\tt.Error(\"MinFloat32(1, 2) should be 1\")\n\t}\n\tif MinFloat32(-1, -2) != -2 {\n\t\tt.Error(\"MinFloat32(-1, -2) should be -2\")\n\t}\n\n\t// Test ClampFloat32\n\tif ClampFloat32(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampFloat32(5, 1, 3) should be 3\")\n\t}\n\tif ClampFloat32(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampFloat32(0, 1, 3) should be 1\")\n\t}\n\tif ClampFloat32(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampFloat32(2, 1, 3) should be 2\")\n\t}\n\n\t// Test AbsFloat32\n\tif AbsFloat32(-5) != 5 {\n\t\tt.Error(\"AbsFloat32(-5) should be 5\")\n\t}\n\tif AbsFloat32(5) != 5 {\n\t\tt.Error(\"AbsFloat32(5) should be 5\")\n\t}\n\n\t// Test SignFloat32\n\tif SignFloat32(-5) != -1 {\n\t\tt.Error(\"SignFloat32(-5) should be -1\")\n\t}\n\tif SignFloat32(5) != 1 {\n\t\tt.Error(\"SignFloat32(5) should be 1\")\n\t}\n\tif SignFloat32(0.0) != 0 {\n\t\tt.Error(\"SignFloat32(0.0) should be 0\")\n\t}\n\n}\n\nfunc TestFloat64Helpers(t *testing.T) {\n\t// Test MaxFloat64\n\tif MaxFloat64(1, 2) != 2 {\n\t\tt.Error(\"MaxFloat64(1, 2) should be 2\")\n\t}\n\tif MaxFloat64(-1, -2) != -1 {\n\t\tt.Error(\"MaxFloat64(-1, -2) should be -1\")\n\t}\n\n\t// Test MinFloat64\n\tif MinFloat64(1, 2) != 1 {\n\t\tt.Error(\"MinFloat64(1, 2) should be 1\")\n\t}\n\tif MinFloat64(-1, -2) != -2 {\n\t\tt.Error(\"MinFloat64(-1, -2) should be -2\")\n\t}\n\n\t// Test ClampFloat64\n\tif ClampFloat64(5, 1, 3) != 3 {\n\t\tt.Error(\"ClampFloat64(5, 1, 3) should be 3\")\n\t}\n\tif ClampFloat64(0, 1, 3) != 1 {\n\t\tt.Error(\"ClampFloat64(0, 1, 3) should be 1\")\n\t}\n\tif ClampFloat64(2, 1, 3) != 2 {\n\t\tt.Error(\"ClampFloat64(2, 1, 3) should be 2\")\n\t}\n\n\t// Test AbsFloat64\n\tif AbsFloat64(-5) != 5 {\n\t\tt.Error(\"AbsFloat64(-5) should be 5\")\n\t}\n\tif AbsFloat64(5) != 5 {\n\t\tt.Error(\"AbsFloat64(5) should be 5\")\n\t}\n\n\t// Test SignFloat64\n\tif SignFloat64(-5) != -1 {\n\t\tt.Error(\"SignFloat64(-5) should be -1\")\n\t}\n\tif SignFloat64(5) != 1 {\n\t\tt.Error(\"SignFloat64(5) should be 1\")\n\t}\n\tif SignFloat64(0.0) != 0 {\n\t\tt.Error(\"SignFloat64(0.0) should be 0\")\n\t}\n\n}\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"916977000","gas_fee":"2750931ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"jD7jLXYzTroHHP4q5aml8FLT6oHXZBWLrob7pX+zpB0SpwAecRVlatPundPhbN4ZiysMImHwVgdQiVexBoIQwg=="}],"memo":""},"metadata":{"timestamp":"1790960262"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"art","path":"gno.land/p/moul/art/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/art/v0`\n\nASCII, ANSI and pixel art primitives for a realm: hold a picture once, emit it\nas plain text, as ANSI truecolour, or as SVG, and let the caller pick at render\ntime.\n\n`Render` returns one string and nothing tells the caller what kind of string it\nis, so every realm picks markdown and every terminal reader eats the syntax as\nnoise. This package owns the half of that problem that is about pictures.\n\n## Two types, seen twice\n\n| type | is | for |\n|---|---|---|\n| `Pix` | a width, a height, one palette index per pixel, a `Palette` of hex colours | what a pixel-art NFT actually is |\n| `Canvas` | a grid of `Cell`, each a rune plus a foreground and background colour | what a terminal actually is |\n\n`Pix.Canvas(mode)` goes from one to the other. `Canvas.Text()`, `Canvas.ANSI()`\nand `Canvas.SVG()` take it the rest of the way out, and `Pix.SVG()` skips the\ngrid entirely for art that was never character-shaped.\n\n```gno\npix := \u0026art.Pix{W: 8, H: 6, Idx: idx, Pal: art.Palette{\"\", \"#d64550\", \"#f7a8b0\"}}\n\nplain := pix.Canvas(art.Glyphs).Text()        // for a code fence, or a pipe\ncolour := pix.Canvas(art.HalfBlock).ANSI()    // for a terminal\nweb := pix.SVG(8).Render(\"a heart\")           // markdown image, data URI, no host\n```\n\n## Use `Glyphs` for sprites, `Ramp` for photos\n\nThe obvious conversion, a luminance ramp, produces mush for pixel art. Two\npalette entries a sprite might genuinely carry, sand `#e8dcc8` and bone\n`#d9d9d9`, sit at luminance 221 and 217 out of 255. A ten-step ramp drops both\nin bucket 8 and the shape between them disappears.\n\nIndexed art already carries its own segmentation, in the palette. So the rule\nfor a sprite is **one glyph per palette index**, not one glyph per brightness.\n`Ramp` is kept because it is right for a photograph, where there is no\nmeaningful palette to key on.\n\nMeasured on real art rather than on a fixture picked to show it. Settler #25\n(`r/g17khq…/settlers/nft:token/25`, read from mainnet 2026-09-29, 32x32, CC0)\ncarries **20 palette entries**:\n\n| keyed on | colours that survive into the text |\n|---|---|\n| palette index (`Glyphs`) | 20 of 20 |\n| luminance (`Ramp`, ten steps) | 9 of 20 |\n\nEleven of the artist's twenty colours stop existing, and the shapes between them\ngo with them.\n\nThe collisions are not between near-identical shades either, which is the part\nthat is easy to miss: the orange hat (`#f08a2a`, luminance 152) and the sky-blue\ntunic (`#3f8fd1`, luminance 130) fall in the same bucket and come out as the\nsame character. Luminance cannot tell a hue from a hue.\n\n`settler_test.gno` pins both, and `TestRampCollapsesWhatGlyphsKeepsApart` pins\nthe mechanism on a two-colour case small enough to read.\n\n## The five modes\n\n| mode | packs | colour | good for |\n|---|---|---|---|\n| `Glyphs` | 1 pixel to 1 cell (2 by default, for aspect) | optional | sprites, and anything that has to survive without colour |\n| `Ramp` | same | optional | photographs |\n| `HalfBlock` | 2 vertical pixels to 1 cell, with `▀` | full | the best-looking terminal output |\n| `Quadrant` | 2x2 to 1 cell | 2 colours per cell | density, at the cost of two colours per block |\n| `Braille` | 2x4 to 1 cell | none | the densest mode; a pixel is on if its index is not 0 |\n\nIndex 0 is the background by convention: `Braille` keys on it directly, the\ndefault glyph set gives it a space, and a tie in `Quadrant`'s two-colour split\ngoes to the lower index so that ink does not end up in the background.\n\n## ANSI is terminal-only, by construction\n\n`Canvas.ANSI()` emits SGR escapes, which cannot reach gnoweb: `p/nt/markdown/sanitize`\nstrips control bytes, and raw ESC in a code fence is garbage in HTML anyway.\n\nThat is not a gap to close later. It is the reason the target is a parameter\nrather than a decision. When colour has to survive the web, `Canvas.SVG()`\ncarries the same two colours per cell through a medium the web can show.\n\n## Notes\n\n- Colours are packed `0xRRGGBB` ints, or `Default` (-1) meaning \"whatever the\n  consumer's default is\". `ParseHex` reads `#rrggbb` and `#rgb`; `#abc` expands\n  by duplication to `#aabbcc`, not by zero-padding.\n- Every helper **clips** rather than panicking. Art is drawn by arithmetic, and\n  a line one cell off the edge is not worth aborting a `Render` over.\n- `Canvas.Text()` trims trailing spaces; `Canvas.ANSI()` does not, because a\n  trailing cell can carry a background colour and trimming it would punch a hole\n  in the picture.\n- `Pix.SVG()` emits **one `\u003cpath\u003e` per colour**, run-length encoded, in pixel\n  coordinates with the scale on the viewBox. On Settler #25 that is 4,532 bytes\n  against 20,625 for one `\u003crect\u003e` per run, 4.5x, and scaling up costs 2 bytes\n  total. A realm pays for those bytes in gas and the reader pays in page weight.\n- `Canvas.SVG()` emits one `\u003ctext\u003e` per non-blank cell rather than one per run:\n  a run would have to assume the font's advance width, and a renderer that\n  disagreed would shear the picture. Dense art belongs in `Pix.SVG()`, which has\n  no font to get wrong.\n- Text handed to SVG is XML-escaped here, because `p/moul/svg`'s `Text`\n  interpolates its content into the document unescaped.\n\n## Not in this package\n\nThe document model. Turning a whole `Render` into markdown *or* plain text\n(links as footnotes, tables with padded columns, headings underlined instead of\n`#`-prefixed) is a separate concern and a separate package. This one only knows\nabout pictures.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/art/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/art/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"box.gno","body":"package art\n\n// BoxStyle is the six runes a rectangular border needs.\ntype BoxStyle struct {\n\tTL, TR, BL, BR rune\n\tH, V           rune\n}\n\n// The border styles worth having. ASCII is the one that survives a consumer\n// with no Unicode: everything else here is box-drawing, which is fine in a\n// terminal and in a markdown code fence but not in, say, a plain-ASCII log.\nvar (\n\tLight  = BoxStyle{TL: '┌', TR: '┐', BL: '└', BR: '┘', H: '─', V: '│'}\n\tHeavy  = BoxStyle{TL: '┏', TR: '┓', BL: '┗', BR: '┛', H: '━', V: '┃'}\n\tDouble = BoxStyle{TL: '╔', TR: '╗', BL: '╚', BR: '╝', H: '═', V: '║'}\n\tRound  = BoxStyle{TL: '╭', TR: '╮', BL: '╰', BR: '╯', H: '─', V: '│'}\n\tASCII  = BoxStyle{TL: '+', TR: '+', BL: '+', BR: '+', H: '-', V: '|'}\n)\n\n// Box draws a w by h border in the pen's colours, leaving the interior\n// untouched. w or h under 2 draws nothing: there is no border with no inside.\nfunc (c *Canvas) Box(x, y, w, h int, s BoxStyle) {\n\tif w \u003c 2 || h \u003c 2 {\n\t\treturn\n\t}\n\tc.HLine(x+1, y, w-2, s.H)\n\tc.HLine(x+1, y+h-1, w-2, s.H)\n\tc.VLine(x, y+1, h-2, s.V)\n\tc.VLine(x+w-1, y+1, h-2, s.V)\n\tc.Put(x, y, s.TL)\n\tc.Put(x+w-1, y, s.TR)\n\tc.Put(x, y+h-1, s.BL)\n\tc.Put(x+w-1, y+h-1, s.BR)\n}\n\n// Frame returns a NEW canvas two cells wider and taller than c, with c blitted\n// into the middle and a border around it. A non-empty title is written into the\n// top edge starting two cells in, and is truncated rather than allowed to run\n// over the corner.\n//\n// It returns a new canvas rather than growing this one because a Canvas has a\n// fixed size by design: every index in this package is computed from W, and a\n// resize in place would invalidate any offset a caller was holding.\nfunc (c *Canvas) Frame(title string, s BoxStyle) *Canvas {\n\tout := NewCanvas(c.W+2, c.H+2)\n\tout.FG, out.BG = c.FG, c.BG\n\tout.Box(0, 0, out.W, out.H, s)\n\tout.Blit(1, 1, c)\n\tif title != \"\" {\n\t\t// The top edge has W-2 usable cells and the title starts at x=2, so it\n\t\t// gets W-4 of them. Anything less than one cell means no room at all.\n\t\troom := out.W - 4\n\t\tif room \u003e 0 {\n\t\t\tout.Write(2, 0, truncRunes(title, room))\n\t\t}\n\t}\n\treturn out\n}\n\nfunc truncRunes(s string, n int) string {\n\ti := 0\n\tfor idx := range s {\n\t\tif i == n {\n\t\t\treturn s[:idx]\n\t\t}\n\t\ti++\n\t}\n\treturn s\n}\n"},{"name":"canvas.gno","body":"package art\n\nimport \"strings\"\n\n// Cell is one character cell: a rune and its two colours. FG and BG are packed\n// 0xRRGGBB values, or [Default].\ntype Cell struct {\n\tR      rune\n\tFG, BG int\n}\n\n// Canvas is a fixed grid of cells, addressed (x, y) from the top left.\n//\n// FG and BG are the pen: the colours the drawing helpers ([Write], [HLine],\n// [Box] and the rest) apply to every cell they touch. They start at [Default].\n// Set them with [Canvas.Pen]; a caller that only wants shapes can ignore them\n// entirely.\ntype Canvas struct {\n\tW, H   int\n\tCells  []Cell\n\tFG, BG int\n}\n\n// Blank is the cell a new canvas is filled with.\nvar Blank = Cell{R: ' ', FG: Default, BG: Default}\n\n// NewCanvas returns a w by h canvas of blank cells. Negative dimensions are\n// treated as zero, so a canvas built from arithmetic that underflowed is empty\n// rather than a panic halfway through a Render.\nfunc NewCanvas(w, h int) *Canvas {\n\tif w \u003c 0 {\n\t\tw = 0\n\t}\n\tif h \u003c 0 {\n\t\th = 0\n\t}\n\tcells := make([]Cell, w*h)\n\tfor i := 0; i \u003c len(cells); i++ {\n\t\tcells[i] = Blank\n\t}\n\treturn \u0026Canvas{W: w, H: h, Cells: cells, FG: Default, BG: Default}\n}\n\n// Pen sets the colours the drawing helpers will apply, and returns the canvas\n// so calls can be chained.\nfunc (c *Canvas) Pen(fg, bg int) *Canvas {\n\tc.FG, c.BG = fg, bg\n\treturn c\n}\n\n// In reports whether (x, y) is on the canvas. Every helper in this package\n// clips silently rather than panicking: art is drawn by arithmetic and a\n// one-off-the-edge line is not worth aborting a Render over.\nfunc (c *Canvas) In(x, y int) bool {\n\treturn x \u003e= 0 \u0026\u0026 y \u003e= 0 \u0026\u0026 x \u003c c.W \u0026\u0026 y \u003c c.H\n}\n\n// At returns the cell at (x, y), or [Blank] if that is off the canvas.\nfunc (c *Canvas) At(x, y int) Cell {\n\tif !c.In(x, y) {\n\t\treturn Blank\n\t}\n\treturn c.Cells[y*c.W+x]\n}\n\n// Set writes a whole cell, colours included, ignoring the pen.\nfunc (c *Canvas) Set(x, y int, cell Cell) {\n\tif !c.In(x, y) {\n\t\treturn\n\t}\n\tc.Cells[y*c.W+x] = cell\n}\n\n// Put writes one rune in the pen's colours.\nfunc (c *Canvas) Put(x, y int, r rune) {\n\tc.Set(x, y, Cell{R: r, FG: c.FG, BG: c.BG})\n}\n\n// Fill sets every cell on the canvas to cell.\nfunc (c *Canvas) Fill(cell Cell) {\n\tfor i := 0; i \u003c len(c.Cells); i++ {\n\t\tc.Cells[i] = cell\n\t}\n}\n\n// Write draws s left to right from (x, y) in the pen's colours. It does not\n// wrap: anything past the right edge is clipped. A '\\n' moves to the next row,\n// back at the starting column, which is what makes a multi-line literal blit\n// the way it reads in source.\nfunc (c *Canvas) Write(x, y int, s string) {\n\tcx, cy := x, y\n\tfor _, r := range s {\n\t\tif r == '\\n' {\n\t\t\tcx, cy = x, cy+1\n\t\t\tcontinue\n\t\t}\n\t\tc.Put(cx, cy, r)\n\t\tcx++\n\t}\n}\n\n// HLine draws n runes rightwards from (x, y).\nfunc (c *Canvas) HLine(x, y, n int, r rune) {\n\tfor i := 0; i \u003c n; i++ {\n\t\tc.Put(x+i, y, r)\n\t}\n}\n\n// VLine draws n runes downwards from (x, y).\nfunc (c *Canvas) VLine(x, y, n int, r rune) {\n\tfor i := 0; i \u003c n; i++ {\n\t\tc.Put(x, y+i, r)\n\t}\n}\n\n// Rect fills a w by h area with r.\nfunc (c *Canvas) Rect(x, y, w, h int, r rune) {\n\tfor j := 0; j \u003c h; j++ {\n\t\tc.HLine(x, y+j, w, r)\n\t}\n}\n\n// Blit copies src onto c with src's top left at (x, y), colours and all.\n// Cells landing off the edge are dropped.\nfunc (c *Canvas) Blit(x, y int, src *Canvas) {\n\tif src == nil {\n\t\treturn\n\t}\n\tfor j := 0; j \u003c src.H; j++ {\n\t\tfor i := 0; i \u003c src.W; i++ {\n\t\t\tc.Set(x+i, y+j, src.Cells[j*src.W+i])\n\t\t}\n\t}\n}\n\n// Text emits the canvas as plain text: runes only, one line per row, trailing\n// spaces trimmed. This is the form that belongs inside a triple-backtick fence,\n// and the form a caller can pipe.\n//\n// Colours are dropped, which is the whole point: a consumer asking for text has\n// said it cannot show them.\nfunc (c Canvas) Text() string {\n\tvar b strings.Builder\n\tfor y := 0; y \u003c c.H; y++ {\n\t\tvar line strings.Builder\n\t\tfor x := 0; x \u003c c.W; x++ {\n\t\t\tline.WriteRune(c.Cells[y*c.W+x].R)\n\t\t}\n\t\tb.WriteString(strings.TrimRight(line.String(), \" \"))\n\t\tif y \u003c c.H-1 {\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// String is [Canvas.Text], so a canvas can be printed directly.\nfunc (c Canvas) String() string { return c.Text() }\n\n// ANSI emits the canvas with SGR truecolour escapes, one reset at the end of\n// every coloured row. Trailing spaces are NOT trimmed here: a trailing cell may\n// carry a background colour, and trimming it would put a hole in the picture.\n//\n// This output cannot reach gnoweb. See the package doc.\nfunc (c Canvas) ANSI() string {\n\tvar b strings.Builder\n\tfor y := 0; y \u003c c.H; y++ {\n\t\tfg, bg := Default, Default\n\t\tfor x := 0; x \u003c c.W; x++ {\n\t\t\tcl := c.Cells[y*c.W+x]\n\t\t\tif cl.FG != fg || cl.BG != bg {\n\t\t\t\tb.WriteString(sgr(cl.FG, cl.BG))\n\t\t\t\tfg, bg = cl.FG, cl.BG\n\t\t\t}\n\t\t\tb.WriteRune(cl.R)\n\t\t}\n\t\tif fg != Default || bg != Default {\n\t\t\tb.WriteString(reset)\n\t\t}\n\t\tif y \u003c c.H-1 {\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// Escape is the byte that starts every SGR sequence. Exported so a consumer can\n// strip ANSI without hard-coding \"\\x1b\".\nconst Escape = '\\x1b'\n\nconst reset = \"\\x1b[0m\"\n\nfunc sgr(fg, bg int) string {\n\tvar b strings.Builder\n\tb.WriteString(\"\\x1b[\")\n\tif fg == Default {\n\t\tb.WriteString(\"39\")\n\t} else {\n\t\tr, g, bl := Split(fg)\n\t\tb.WriteString(\"38;2;\")\n\t\twriteInt(\u0026b, r)\n\t\tb.WriteByte(';')\n\t\twriteInt(\u0026b, g)\n\t\tb.WriteByte(';')\n\t\twriteInt(\u0026b, bl)\n\t}\n\tb.WriteByte(';')\n\tif bg == Default {\n\t\tb.WriteString(\"49\")\n\t} else {\n\t\tr, g, bl := Split(bg)\n\t\tb.WriteString(\"48;2;\")\n\t\twriteInt(\u0026b, r)\n\t\tb.WriteByte(';')\n\t\twriteInt(\u0026b, g)\n\t\tb.WriteByte(';')\n\t\twriteInt(\u0026b, bl)\n\t}\n\tb.WriteByte('m')\n\treturn b.String()\n}\n\n// writeInt writes a 0-255 value without strconv, which this package would\n// otherwise import for three call sites.\nfunc writeInt(b *strings.Builder, v int) {\n\tif v \u003e= 100 {\n\t\tb.WriteByte(byte('0' + v/100))\n\t}\n\tif v \u003e= 10 {\n\t\tb.WriteByte(byte('0' + (v/10)%10))\n\t}\n\tb.WriteByte(byte('0' + v%10))\n}\n"},{"name":"canvas_test.gno","body":"package art\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestNewCanvasIsBlank(t *testing.T) {\n\tc := NewCanvas(3, 2)\n\tuassert.Equal(t, 6, len(c.Cells), \"cell count\")\n\tuassert.Equal(t, \"\\n\", c.Text(), \"two empty rows, both trimmed to nothing\")\n\n\t// Negative dimensions must not panic partway through a Render.\n\tempty := NewCanvas(-4, -4)\n\tuassert.Equal(t, 0, empty.W, \"negative width clamps to 0\")\n\tuassert.Equal(t, \"\", empty.Text(), \"empty canvas is the empty string\")\n}\n\nfunc TestWriteAndClip(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tx, y int\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"fits\", 0, 0, \"abc\", \"abc\\n\\n\"},\n\t\t{\"offset\", 1, 1, \"xy\", \"\\n xy\\n\"},\n\t\t{\"clipped at the right edge\", 2, 0, \"abcde\", \"  abc\\n\\n\"},\n\t\t{\"negative x drops the leading runes\", -2, 0, \"abcde\", \"cde\\n\\n\"},\n\t\t{\"newline returns to the start column\", 1, 0, \"ab\\ncd\", \" ab\\n cd\\n\"},\n\t\t{\"off the bottom is dropped entirely\", 0, 9, \"abc\", \"\\n\\n\"},\n\t}\n\tfor _, tc := range cases {\n\t\tc := NewCanvas(5, 3)\n\t\tc.Write(tc.x, tc.y, tc.in)\n\t\tuassert.Equal(t, tc.want, c.Text(), tc.name)\n\t}\n}\n\nfunc TestTextTrimsTrailingSpaceAndANSIDoesNot(t *testing.T) {\n\tc := NewCanvas(4, 1)\n\tc.Pen(Default, 0xff0000)\n\tc.Put(0, 0, 'x')\n\tc.Put(3, 0, ' ') // a trailing space that carries a background colour\n\n\tuassert.Equal(t, \"x\", c.Text(), \"text drops the coloured trailing space\")\n\n\tansi := c.ANSI()\n\tuassert.True(t, strings.HasSuffix(ansi, reset), \"a coloured row ends in a reset\")\n\tuassert.True(t, strings.Contains(ansi, \"48;2;255;0;0\"), \"the red background is emitted\")\n\t// Trimming here would punch a hole in the picture, so the cell survives.\n\tuassert.Equal(t, \"x   \", stripSGR(ansi), \"all four cells survive in ansi\")\n}\n\nfunc TestANSIEmitsOneEscapePerChange(t *testing.T) {\n\tc := NewCanvas(4, 1)\n\tc.Pen(0x00ff00, Default)\n\tc.Write(0, 0, \"aa\")\n\tc.Pen(0x0000ff, Default)\n\tc.Write(2, 0, \"bb\")\n\n\tgot := c.ANSI()\n\t// Two colour changes plus the end-of-row reset, and not one per cell.\n\tuassert.Equal(t, 3, strings.Count(got, \"\\x1b[\"), \"escape count\")\n\tuassert.Equal(t, \"aabb\", stripSGR(got), \"the runes survive intact\")\n}\n\nfunc TestANSIUncolouredRowHasNoEscapes(t *testing.T) {\n\tc := NewCanvas(3, 1)\n\tc.Write(0, 0, \"abc\")\n\tuassert.Equal(t, \"abc\", c.ANSI(), \"no colour means no escapes and no reset\")\n}\n\nfunc TestBlit(t *testing.T) {\n\tsrc := NewCanvas(2, 2)\n\tsrc.Write(0, 0, \"ab\\ncd\")\n\n\tdst := NewCanvas(4, 4)\n\tdst.Blit(1, 1, src)\n\tuassert.Equal(t, \"\\n ab\\n cd\\n\", dst.Text(), \"placed at the offset\")\n\n\t// Partly off the edge keeps what fits and drops the rest.\n\tedge := NewCanvas(4, 4)\n\tedge.Blit(3, 3, src)\n\tuassert.Equal(t, \"\\n\\n\\n   a\", edge.Text(), \"only the top-left cell lands\")\n\n\t// A nil source is a no-op rather than a panic.\n\tedge.Blit(0, 0, nil)\n}\n\nfunc TestBoxAndFrame(t *testing.T) {\n\tc := NewCanvas(5, 3)\n\tc.Box(0, 0, 5, 3, ASCII)\n\tuassert.Equal(t, \"+---+\\n|   |\\n+---+\", c.Text(), \"ascii border\")\n\n\t// Degenerate boxes draw nothing: there is no border with no inside.\n\tsmall := NewCanvas(5, 3)\n\tsmall.Box(0, 0, 1, 3, Light)\n\tsmall.Box(0, 0, 5, 1, Light)\n\tuassert.Equal(t, \"\\n\\n\", small.Text(), \"width or height under 2 draws nothing\")\n\n\tinner := NewCanvas(3, 1)\n\tinner.Write(0, 0, \"hey\")\n\tframed := inner.Frame(\"\", ASCII)\n\tuassert.Equal(t, 5, framed.W, \"frame adds two columns\")\n\tuassert.Equal(t, 3, framed.H, \"frame adds two rows\")\n\tuassert.Equal(t, \"+---+\\n|hey|\\n+---+\", framed.Text(), \"content centred inside\")\n}\n\nfunc TestFrameTitleIsTruncatedNotOverrun(t *testing.T) {\n\tinner := NewCanvas(4, 1)\n\ttitled := inner.Frame(\"settlers\", ASCII)\n\t// 6 columns wide: the corners take 2 and the title starts at x=2, so it\n\t// gets 2 cells and must not eat the top-right corner.\n\tuassert.True(t, strings.HasPrefix(titled.Text(), \"+-se-+\\n\"), \"truncated, corner survives\")\n\n\t// A canvas too narrow for any title still frames cleanly.\n\ttiny := NewCanvas(1, 1)\n\tuassert.Equal(t, \"+-+\\n| |\\n+-+\", tiny.Frame(\"nope\", ASCII).Text(), \"no room, no title\")\n}\n\n// stripSGR removes every SGR sequence, so a test can assert on the runes and on\n// the escapes separately instead of pinning one long opaque string.\nfunc stripSGR(s string) string {\n\tvar b strings.Builder\n\tin := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase r == Escape:\n\t\t\tin = true\n\t\tcase in \u0026\u0026 r == 'm':\n\t\t\tin = false\n\t\tcase in:\n\t\tdefault:\n\t\t\tb.WriteRune(r)\n\t\t}\n\t}\n\treturn b.String()\n}\n"},{"name":"color.gno","body":"package art\n\nimport \"strings\"\n\n// Default is the colour that means \"let the consumer decide\": the terminal's\n// own foreground or background in ANSI, and transparent in SVG.\nconst Default = -1\n\n// RGB packs three 0-255 components into the 0xRRGGBB form this package uses.\n// Components outside 0-255 are clamped rather than wrapped, so a computed\n// channel cannot silently alias onto a neighbouring one.\nfunc RGB(r, g, b int) int {\n\treturn clamp8(r)\u003c\u003c16 | clamp8(g)\u003c\u003c8 | clamp8(b)\n}\n\n// Split returns the three 0-255 components of a packed colour. Default splits\n// to zeroes, so callers must test for Default before calling it rather than\n// after.\nfunc Split(c int) (r, g, b int) {\n\tif c \u003c 0 {\n\t\treturn 0, 0, 0\n\t}\n\treturn (c \u003e\u003e 16) \u0026 0xff, (c \u003e\u003e 8) \u0026 0xff, c \u0026 0xff\n}\n\n// ParseHex reads \"#rrggbb\", \"#rgb\", or either without the leading '#', and\n// reports whether it understood the string. An empty string is not an error but\n// it is not a colour either: it reports Default, false, which is how a palette\n// marks a transparent entry.\nfunc ParseHex(s string) (int, bool) {\n\ts = strings.TrimSpace(s)\n\ts = strings.TrimPrefix(s, \"#\")\n\tswitch len(s) {\n\tcase 3:\n\t\tr, ok1 := hexDigit(s[0])\n\t\tg, ok2 := hexDigit(s[1])\n\t\tb, ok3 := hexDigit(s[2])\n\t\tif !ok1 || !ok2 || !ok3 {\n\t\t\treturn Default, false\n\t\t}\n\t\t// #abc is #aabbcc, not #0a0b0c.\n\t\treturn RGB(r*17, g*17, b*17), true\n\tcase 6:\n\t\tr, ok1 := hexByte(s[0], s[1])\n\t\tg, ok2 := hexByte(s[2], s[3])\n\t\tb, ok3 := hexByte(s[4], s[5])\n\t\tif !ok1 || !ok2 || !ok3 {\n\t\t\treturn Default, false\n\t\t}\n\t\treturn RGB(r, g, b), true\n\t}\n\treturn Default, false\n}\n\n// Hex is the inverse of ParseHex. Default renders as the empty string, because\n// there is no hex spelling of \"the consumer's default\".\nfunc Hex(c int) string {\n\tif c \u003c 0 {\n\t\treturn \"\"\n\t}\n\tr, g, b := Split(c)\n\tvar sb strings.Builder\n\tsb.WriteByte('#')\n\twriteHexByte(\u0026sb, r)\n\twriteHexByte(\u0026sb, g)\n\twriteHexByte(\u0026sb, b)\n\treturn sb.String()\n}\n\n// Luminance returns perceived brightness on 0-255, using the Rec. 709 weights\n// (0.2126 R, 0.7152 G, 0.0722 B) in integer arithmetic. Default is treated as\n// black, so an unset colour ramps to the darkest glyph rather than to a\n// midpoint that would read as real content.\n//\n// This is the function [Ramp] keys on, and the package doc explains why keying\n// on it is the wrong default for a sprite.\nfunc Luminance(c int) int {\n\tif c \u003c 0 {\n\t\treturn 0\n\t}\n\tr, g, b := Split(c)\n\treturn (2126*r + 7152*g + 722*b) / 10000\n}\n\nfunc clamp8(v int) int {\n\tif v \u003c 0 {\n\t\treturn 0\n\t}\n\tif v \u003e 255 {\n\t\treturn 255\n\t}\n\treturn v\n}\n\nfunc hexDigit(c byte) (int, bool) {\n\tswitch {\n\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn int(c - '0'), true\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'f':\n\t\treturn int(c-'a') + 10, true\n\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'F':\n\t\treturn int(c-'A') + 10, true\n\t}\n\treturn 0, false\n}\n\nfunc hexByte(hi, lo byte) (int, bool) {\n\th, ok1 := hexDigit(hi)\n\tl, ok2 := hexDigit(lo)\n\tif !ok1 || !ok2 {\n\t\treturn 0, false\n\t}\n\treturn h*16 + l, true\n}\n\nconst hexDigits = \"0123456789abcdef\"\n\nfunc writeHexByte(sb *strings.Builder, v int) {\n\tsb.WriteByte(hexDigits[(v\u003e\u003e4)\u00260xf])\n\tsb.WriteByte(hexDigits[v\u00260xf])\n}\n"},{"name":"color_test.gno","body":"package art\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestParseHex(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant int\n\t\tok   bool\n\t}{\n\t\t{\"six with hash\", \"#e8c39e\", 0xe8c39e, true},\n\t\t{\"six without hash\", \"e8c39e\", 0xe8c39e, true},\n\t\t{\"uppercase\", \"#E8C39E\", 0xe8c39e, true},\n\t\t{\"short expands by duplication\", \"#abc\", 0xaabbcc, true},\n\t\t{\"short is not zero padded\", \"#abc\", 0x0a0b0c, false},\n\t\t{\"surrounding space\", \"  #000000 \", 0x000000, true},\n\t\t{\"white\", \"#ffffff\", 0xffffff, true},\n\t\t{\"empty is not a colour\", \"\", Default, false},\n\t\t{\"four digits\", \"#abcd\", Default, false},\n\t\t{\"non hex digit\", \"#gggggg\", Default, false},\n\t}\n\tfor _, tc := range cases {\n\t\tgot, ok := ParseHex(tc.in)\n\t\tif !tc.ok {\n\t\t\t// Either it failed to parse, or it parsed to something other than\n\t\t\t// the value this case says it must not produce.\n\t\t\tuassert.False(t, ok \u0026\u0026 got == tc.want, tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.True(t, ok, tc.name+\": parsed\")\n\t\tuassert.Equal(t, tc.want, got, tc.name)\n\t}\n}\n\nfunc TestHexRoundTrip(t *testing.T) {\n\tfor _, s := range []string{\"#000000\", \"#ffffff\", \"#e8c39e\", \"#0a0b0c\"} {\n\t\tc, ok := ParseHex(s)\n\t\tuassert.True(t, ok, s)\n\t\tuassert.Equal(t, s, Hex(c), s)\n\t}\n\tuassert.Equal(t, \"\", Hex(Default), \"Default has no hex spelling\")\n}\n\nfunc TestRGBClamps(t *testing.T) {\n\tuassert.Equal(t, 0xffffff, RGB(300, 300, 300), \"over range clamps to ff\")\n\tuassert.Equal(t, 0x000000, RGB(-5, -5, -5), \"under range clamps to 00\")\n\t// The point of clamping rather than masking: 256 must not alias to 0 and\n\t// carry a bit into the next channel.\n\tuassert.Equal(t, 0x00ff00, RGB(0, 256, 0), \"256 does not carry into red\")\n}\n\nfunc TestLuminance(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   int\n\t\twant int\n\t}{\n\t\t{\"black\", 0x000000, 0},\n\t\t{\"white\", 0xffffff, 255},\n\t\t{\"pure green is the brightest primary\", 0x00ff00, 182},\n\t\t{\"pure blue is the darkest primary\", 0x0000ff, 18},\n\t\t{\"pure red\", 0xff0000, 54},\n\t\t{\"Default reads as black\", Default, 0},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, Luminance(tc.in), tc.name)\n\t}\n}\n"},{"name":"doc.gno","body":"// Package art is the primitive layer for ASCII, ANSI and pixel art in a realm.\n//\n// A realm's Render returns one string and nothing tells the caller what kind of\n// string it is, so every realm picks markdown and every terminal reader eats the\n// syntax as noise. This package owns the half of that problem that is about\n// pictures: it holds art in a form that can be emitted as plain text, as ANSI\n// truecolour, or as SVG, and lets the caller choose at render time.\n//\n// # Two types, seen twice\n//\n// [Pix] is an indexed bitmap: a width, a height, one palette index per pixel,\n// and a [Palette] of hex colours. It is what a pixel-art NFT actually is.\n//\n// [Canvas] is a grid of [Cell], each carrying a rune and a foreground and\n// background colour. It is what a terminal actually is.\n//\n// The conversion between them is the point of the package. [Pix.Canvas] takes a\n// [Mode] and produces a Canvas; [Canvas.Text], [Canvas.ANSI] and [Canvas.SVG]\n// take it the rest of the way out.\n//\n// # Use Glyphs for sprites, Ramp for photos\n//\n// The obvious conversion, a luminance ramp, produces mush for pixel art.\n//\n// Measured on Settler #25, a 32x32 sprite on mainnet with 20 palette colours: a\n// ten-step luminance ramp resolves those 20 to 9, so eleven of the artist's\n// colours stop existing. The collisions are not between near-identical shades\n// either. The orange hat (#f08a2a, luminance 152) and the sky-blue tunic\n// (#3f8fd1, luminance 130) land in the same bucket and come out as the same\n// character, because luminance cannot tell a hue from a hue.\n//\n// Indexed art already carries its own segmentation, in the palette. So the right\n// rule for a sprite is one glyph per palette index ([Glyphs]), not one glyph per\n// brightness ([Ramp]). Ramp is kept because it is right for a photograph, where\n// there is no meaningful palette to key on.\n//\n// # ANSI is a terminal-only target, by construction\n//\n// [Canvas.ANSI] emits SGR escape sequences. Those cannot reach gnoweb: raw ESC\n// in a code fence is garbage in HTML, and gno.land/p/nt/markdown/sanitize strips\n// control bytes anyway. That is not a gap to close later, it is the reason the\n// target is a parameter instead of a decision. When colour has to survive the\n// web, use [Canvas.SVG] or [Pix.SVG], which carry the same colours through a\n// medium gnoweb can actually show.\n//\n// # Colours are packed ints\n//\n// A colour is an int holding 0xRRGGBB, or [Default] (-1) meaning \"whatever the\n// consumer's default is\": the terminal's default foreground for an FG, and\n// transparent for a background in SVG. [ParseHex] turns \"#rrggbb\" or \"#rgb\"\n// into one.\npackage art\n"},{"name":"example_test.gno","body":"package art\n\n// heart is an 8x6 indexed sprite: 0 background, 1 body, 2 highlight.\nvar (\n\theartPal = Palette{\"\", \"#d64550\", \"#f7a8b0\"}\n\theartIdx = []uint8{\n\t\t0, 1, 1, 0, 0, 1, 1, 0,\n\t\t1, 1, 1, 2, 2, 1, 1, 1,\n\t\t1, 1, 1, 1, 1, 1, 1, 1,\n\t\t0, 1, 1, 1, 1, 1, 1, 0,\n\t\t0, 0, 1, 1, 1, 1, 0, 0,\n\t\t0, 0, 0, 1, 1, 0, 0, 0,\n\t}\n)\n\nfunc heart() *Pix {\n\treturn \u0026Pix{W: 8, H: 6, Idx: heartIdx, Pal: heartPal}\n}\n\n// One glyph per palette index, each pixel two cells wide so the sprite keeps\n// its proportions in a terminal. This is the default for indexed art.\nfunc ExamplePix_Canvas_glyphs() {\n\tprintln(heart().Canvas(Glyphs).Text())\n\t// Output:\n\t//   ####    ####\n\t// ######@@@@######\n\t// ################\n\t//   ############\n\t//     ########\n\t//       ####\n}\n\n// The same sprite at four times the density, in Braille. Monochrome by\n// construction: a Braille cell has eight dots and no colours, so a pixel is\n// only on or off.\nfunc ExamplePix_Canvas_braille() {\n\tprintln(heart().Canvas(Braille).Text())\n\t// Output:\n\t// ⢾⣷⣾⡷\n\t// ⠀⠙⠋⠀\n}\n\n// Quadrants pack 2x2 into one cell. Asked for no colour, the mode has nothing\n// left to say with two colours and degrades to a density map, which is still\n// the densest thing a plain-text consumer can be handed.\nfunc ExamplePix_Canvas_quadrant() {\n\tprintln(heart().CanvasOpts(Opts{Mode: Quadrant}).Text())\n\t// Output:\n\t// ▟▙▟▙\n\t// ▜██▛\n\t//  ▜▛\n}\n\n// Drawing on a Canvas directly, with a border around it.\nfunc ExampleCanvas_Frame() {\n\tc := NewCanvas(11, 3)\n\tc.Write(0, 0, \"gno.land\")\n\tc.HLine(0, 1, 11, '─')\n\tc.Write(0, 2, \"ascii art\")\n\tprintln(c.Frame(\"art\", Round).Text())\n\t// Output:\n\t// ╭─art───────╮\n\t// │gno.land   │\n\t// │───────────│\n\t// │ascii art  │\n\t// ╰───────────╯\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/art/v0\"\ngno = \"0.9\"\n"},{"name":"pix.gno","body":"package art\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/svg/v0\"\n)\n\n// Palette maps a pixel's index to a colour, as a hex string (\"#e8c39e\", \"#abc\",\n// with or without the '#'). An empty entry is transparent: [Pix.SVG] emits no\n// rectangle for it and the colour modes give it [Default].\n//\n// By convention index 0 is the background. [Braille] keys on that convention\n// directly, and the default glyph set gives index 0 a space.\ntype Palette []string\n\n// Color returns the packed colour of a palette index, or [Default] if the index\n// is out of range or the entry is empty or unparseable.\nfunc (p Palette) Color(i uint8) int {\n\tif int(i) \u003e= len(p) {\n\t\treturn Default\n\t}\n\tc, ok := ParseHex(p[i])\n\tif !ok {\n\t\treturn Default\n\t}\n\treturn c\n}\n\n// Pix is an indexed bitmap: one palette index per pixel, row-major from the top\n// left. This is the shape pixel art actually has on chain, and the reason\n// [Glyphs] beats [Ramp] for it.\ntype Pix struct {\n\tW, H int\n\tIdx  []uint8\n\tPal  Palette\n}\n\n// NewPix returns a w by h bitmap with every pixel at index 0.\nfunc NewPix(w, h int, pal Palette) *Pix {\n\tif w \u003c 0 {\n\t\tw = 0\n\t}\n\tif h \u003c 0 {\n\t\th = 0\n\t}\n\treturn \u0026Pix{W: w, H: h, Idx: make([]uint8, w*h), Pal: pal}\n}\n\n// At returns the palette index at (x, y), or 0 off the bitmap. Off-bitmap\n// reading as background is what lets the conversions below run past the edge of\n// an odd-sized image without a bounds check at every pixel.\nfunc (p *Pix) At(x, y int) uint8 {\n\tif x \u003c 0 || y \u003c 0 || x \u003e= p.W || y \u003e= p.H {\n\t\treturn 0\n\t}\n\treturn p.Idx[y*p.W+x]\n}\n\n// Set writes a palette index, clipping silently off the bitmap.\nfunc (p *Pix) Set(x, y int, i uint8) {\n\tif x \u003c 0 || y \u003c 0 || x \u003e= p.W || y \u003e= p.H {\n\t\treturn\n\t}\n\tp.Idx[y*p.W+x] = i\n}\n\n// Color returns the packed colour at (x, y).\nfunc (p *Pix) Color(x, y int) int { return p.Pal.Color(p.At(x, y)) }\n\n// Mode is how a [Pix] becomes a [Canvas]. They are not cosmetic variants of\n// each other: they trade resolution, colour and consumer against one another,\n// and the package doc says which to reach for.\ntype Mode int\n\nconst (\n\t// Glyphs gives every palette index its own rune. The right default for\n\t// sprites and anything else with a small indexed palette.\n\tGlyphs Mode = iota\n\n\t// Ramp picks a rune by luminance. Right for a photograph, wrong for a\n\t// sprite, and the package doc has the measurement.\n\tRamp\n\n\t// HalfBlock packs two vertical pixels into one cell with '▀', foreground\n\t// for the top pixel and background for the bottom. Full colour, square\n\t// aspect, half the rows. The best-looking mode, and terminal-only.\n\tHalfBlock\n\n\t// Quadrant packs a 2x2 block into one cell. Twice HalfBlock's density,\n\t// but a cell carries only two colours, so a four-colour block loses two.\n\tQuadrant\n\n\t// Braille packs a 2x4 block into one Braille cell. The densest mode and\n\t// the only monochrome one: a pixel is on if its index is not 0.\n\tBraille\n)\n\n// DefaultGlyphs is one visually distinct rune per palette index, ordered so\n// that neighbouring indices stay apart on screen. Index 0 is a space, matching\n// the background convention.\n//\n// A palette longer than this wraps, which is a real collision: pass your own\n// set through [Opts] when that matters.\nvar DefaultGlyphs = []rune{' ', '#', '@', '%', '*', '+', '=', '~', '-', ':', '.', 'o', 'O', 'x', 'X', 'w', 'W', 'm', 'M', '8'}\n\n// DefaultRamp runs darkest to lightest, for a terminal with a dark background.\n// Invert it for a light one.\nvar DefaultRamp = []rune{' ', '.', ':', '-', '=', '+', '*', '#', '%', '@'}\n\n// Quadrants is indexed by a 4-bit mask: bit 0 top-left, 1 top-right, 2\n// bottom-left, 3 bottom-right.\nvar Quadrants = []rune{' ', '▘', '▝', '▀', '▖', '▌', '▞', '▛', '▗', '▚', '▐', '▜', '▄', '▙', '▟', '█'}\n\n// Opts is the full form of [Pix.Canvas], for callers who want to override a\n// mode's defaults.\ntype Opts struct {\n\tMode Mode\n\n\t// Glyphs overrides [DefaultGlyphs] for [Glyphs] and [DefaultRamp] for\n\t// [Ramp]. Ignored by the block modes.\n\tGlyphs []rune\n\n\t// Color carries palette colours into the canvas. The block modes need it\n\t// and set it by default; the glyph modes default to off, because their\n\t// whole job is to be readable without colour.\n\tColor bool\n\n\t// Wide emits each pixel as two cells side by side. A terminal cell is\n\t// about twice as tall as it is wide, so a sprite rendered one cell per\n\t// pixel comes out squashed to half height. On by default for the glyph\n\t// modes; meaningless for the block modes, which correct aspect by packing.\n\tWide bool\n}\n\n// Canvas converts the bitmap using a mode's defaults: [Glyphs] and [Ramp] come\n// out wide and monochrome, the block modes come out coloured.\nfunc (p *Pix) Canvas(m Mode) *Canvas {\n\to := Opts{Mode: m}\n\tswitch m {\n\tcase Glyphs, Ramp:\n\t\to.Wide = true\n\tdefault:\n\t\to.Color = true\n\t}\n\treturn p.CanvasOpts(o)\n}\n\n// CanvasOpts converts the bitmap with the options spelled out.\nfunc (p *Pix) CanvasOpts(o Opts) *Canvas {\n\tswitch o.Mode {\n\tcase HalfBlock:\n\t\treturn p.halfBlock(o)\n\tcase Quadrant:\n\t\treturn p.quadrant(o)\n\tcase Braille:\n\t\treturn p.braille(o)\n\tcase Ramp:\n\t\treturn p.glyphGrid(o, pickRamp(o.Glyphs))\n\tdefault:\n\t\treturn p.glyphGrid(o, pickGlyphs(o.Glyphs))\n\t}\n}\n\nfunc pickGlyphs(g []rune) []rune {\n\tif len(g) == 0 {\n\t\treturn DefaultGlyphs\n\t}\n\treturn g\n}\n\nfunc pickRamp(g []rune) []rune {\n\tif len(g) == 0 {\n\t\treturn DefaultRamp\n\t}\n\treturn g\n}\n\n// glyphGrid covers both Glyphs and Ramp: they differ only in what they key the\n// rune lookup on, which is exactly the finding the package doc records.\nfunc (p *Pix) glyphGrid(o Opts, set []rune) *Canvas {\n\tstep := 1\n\tif o.Wide {\n\t\tstep = 2\n\t}\n\tout := NewCanvas(p.W*step, p.H)\n\tfor y := 0; y \u003c p.H; y++ {\n\t\tfor x := 0; x \u003c p.W; x++ {\n\t\t\tidx := p.At(x, y)\n\t\t\tcol := p.Pal.Color(idx)\n\n\t\t\tvar r rune\n\t\t\tif o.Mode == Ramp {\n\t\t\t\tr = set[Luminance(col)*len(set)/256]\n\t\t\t} else {\n\t\t\t\tr = set[int(idx)%len(set)]\n\t\t\t}\n\n\t\t\tcell := Cell{R: r, FG: Default, BG: Default}\n\t\t\tif o.Color {\n\t\t\t\tcell.FG = col\n\t\t\t}\n\t\t\tfor k := 0; k \u003c step; k++ {\n\t\t\t\tout.Set(x*step+k, y, cell)\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}\n\nfunc (p *Pix) halfBlock(o Opts) *Canvas {\n\tout := NewCanvas(p.W, (p.H+1)/2)\n\tfor y := 0; y \u003c out.H; y++ {\n\t\tfor x := 0; x \u003c p.W; x++ {\n\t\t\ttop := p.Color(x, y*2)\n\t\t\tbot := Default\n\t\t\tif y*2+1 \u003c p.H {\n\t\t\t\tbot = p.Color(x, y*2+1)\n\t\t\t}\n\t\t\tif !o.Color {\n\t\t\t\t// Without colour the upper half block says nothing, so fall\n\t\t\t\t// back to \"is there ink here\": full, half, or empty.\n\t\t\t\tout.Set(x, y, Cell{R: monoHalf(p.At(x, y*2), p.At(x, y*2+1)), FG: Default, BG: Default})\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout.Set(x, y, Cell{R: '▀', FG: top, BG: bot})\n\t\t}\n\t}\n\treturn out\n}\n\nfunc monoHalf(top, bot uint8) rune {\n\tswitch {\n\tcase top != 0 \u0026\u0026 bot != 0:\n\t\treturn '█'\n\tcase top != 0:\n\t\treturn '▀'\n\tcase bot != 0:\n\t\treturn '▄'\n\t}\n\treturn ' '\n}\n\nfunc (p *Pix) quadrant(o Opts) *Canvas {\n\tout := NewCanvas((p.W+1)/2, (p.H+1)/2)\n\tfor y := 0; y \u003c out.H; y++ {\n\t\tfor x := 0; x \u003c out.W; x++ {\n\t\t\tvar idx [4]uint8\n\t\t\tidx[0] = p.At(x*2, y*2)\n\t\t\tidx[1] = p.At(x*2+1, y*2)\n\t\t\tidx[2] = p.At(x*2, y*2+1)\n\t\t\tidx[3] = p.At(x*2+1, y*2+1)\n\n\t\t\tif !o.Color {\n\t\t\t\tmask := 0\n\t\t\t\tfor k := 0; k \u003c 4; k++ {\n\t\t\t\t\tif idx[k] != 0 {\n\t\t\t\t\t\tmask |= 1 \u003c\u003c uint(k)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout.Set(x, y, Cell{R: Quadrants[mask], FG: Default, BG: Default})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbgIdx, fgIdx, split := twoWaySplit(idx)\n\t\t\tmask := 0\n\t\t\tif split {\n\t\t\t\tfor k := 0; k \u003c 4; k++ {\n\t\t\t\t\tif idx[k] == fgIdx {\n\t\t\t\t\t\tmask |= 1 \u003c\u003c uint(k)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfg := Default\n\t\t\tif split {\n\t\t\t\tfg = p.Pal.Color(fgIdx)\n\t\t\t}\n\t\t\tout.Set(x, y, Cell{R: Quadrants[mask], FG: fg, BG: p.Pal.Color(bgIdx)})\n\t\t}\n\t}\n\treturn out\n}\n\n// twoWaySplit picks the two palette indices a 2x2 block is drawn with: the most\n// common becomes the background, the most common of the rest the foreground.\n// It reports false when every pixel agrees, in which case there is no\n// foreground and the cell is a solid background.\n//\n// A tie goes to the LOWER palette index, which is what makes index 0 behave as\n// the background the package documents it to be. Tie-breaking on pixel order\n// instead put the ink in the background half the time: a two-colour block split\n// down the middle came out as the mirror image of itself, because whichever\n// side happened to be scanned first won.\nfunc twoWaySplit(idx [4]uint8) (bg, fg uint8, split bool) {\n\tbg = mostCommon(idx, false, 0)\n\tfg = mostCommon(idx, true, bg)\n\tif fg == bg {\n\t\treturn bg, bg, false\n\t}\n\treturn bg, fg, true\n}\n\nfunc mostCommon(idx [4]uint8, skip bool, skipped uint8) uint8 {\n\tbest, bestN := uint8(0), 0\n\tfor k := 0; k \u003c 4; k++ {\n\t\tif skip \u0026\u0026 idx[k] == skipped {\n\t\t\tcontinue\n\t\t}\n\t\tn := 0\n\t\tfor j := 0; j \u003c 4; j++ {\n\t\t\tif idx[j] == idx[k] {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t\tif n \u003e bestN || (n == bestN \u0026\u0026 bestN \u003e 0 \u0026\u0026 idx[k] \u003c best) {\n\t\t\tbest, bestN = idx[k], n\n\t\t}\n\t}\n\tif bestN == 0 {\n\t\treturn skipped\n\t}\n\treturn best\n}\n\n// brailleBits maps (col, row) inside a 2x4 block to its bit in U+2800. The\n// layout is not sequential: the fourth row was added to the standard late and\n// took the two high bits.\nvar brailleBits = [2][4]uint{\n\t{0, 1, 2, 6},\n\t{3, 4, 5, 7},\n}\n\nfunc (p *Pix) braille(o Opts) *Canvas {\n\tout := NewCanvas((p.W+1)/2, (p.H+3)/4)\n\tfor y := 0; y \u003c out.H; y++ {\n\t\tfor x := 0; x \u003c out.W; x++ {\n\t\t\tbits := 0\n\t\t\tfg := Default\n\t\t\tfor col := 0; col \u003c 2; col++ {\n\t\t\t\tfor row := 0; row \u003c 4; row++ {\n\t\t\t\t\tif p.At(x*2+col, y*4+row) == 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tbits |= 1 \u003c\u003c brailleBits[col][row]\n\t\t\t\t\tif o.Color \u0026\u0026 fg == Default {\n\t\t\t\t\t\tfg = p.Color(x*2+col, y*4+row)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.Set(x, y, Cell{R: rune(0x2800 + bits), FG: fg, BG: Default})\n\t\t}\n\t}\n\treturn out\n}\n\n// SVG renders the bitmap as one \u003cpath\u003e per palette colour, each path a\n// run-length chain of \"M\u003cx\u003e \u003cy\u003eh\u003cw\u003ev1h-\u003cw\u003ez\" pixel runs. Transparent palette\n// entries emit nothing.\n//\n// The path lives in pixel coordinates and scale goes on the canvas as a viewBox,\n// so scaling up costs no extra bytes at all.\n//\n// One path per colour rather than one \u003crect\u003e per run is worth the loop:\n// measured on Settler #25 (32x32, 20 colours, read from mainnet 2026-09-29),\n// rectangles came to 20,625 bytes against 3,565 for paths, 5.8x. A realm pays\n// for those bytes in gas and the reader pays for them in page weight, and the\n// settlers realm itself emits paths for the same reason.\n//\n// Use Canvas.Render or Canvas.String from p/moul/svg to get the markdown image\n// or the raw document.\nfunc (p *Pix) SVG(scale int) *svg.Canvas {\n\tif scale \u003c 1 {\n\t\tscale = 1\n\t}\n\tout := svg.NewCanvas(p.W*scale, p.H*scale)\n\tout.WithViewBox(0, 0, p.W, p.H)\n\tout.AddStyle(\"path\", \"shape-rendering:crispEdges\")\n\n\tfor i := 0; i \u003c len(p.Pal); i++ {\n\t\thex := p.Pal.hex(uint8(i))\n\t\tif hex == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tvar d strings.Builder\n\t\tfor y := 0; y \u003c p.H; y++ {\n\t\t\tx := 0\n\t\t\tfor x \u003c p.W {\n\t\t\t\tif p.At(x, y) != uint8(i) {\n\t\t\t\t\tx++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trun := 1\n\t\t\t\tfor x+run \u003c p.W \u0026\u0026 p.At(x+run, y) == uint8(i) {\n\t\t\t\t\trun++\n\t\t\t\t}\n\t\t\t\td.WriteByte('M')\n\t\t\t\td.WriteString(itoa(x))\n\t\t\t\td.WriteByte(' ')\n\t\t\t\td.WriteString(itoa(y))\n\t\t\t\td.WriteByte('h')\n\t\t\t\td.WriteString(itoa(run))\n\t\t\t\td.WriteString(\"v1h-\")\n\t\t\t\td.WriteString(itoa(run))\n\t\t\t\td.WriteByte('z')\n\t\t\t\tx += run\n\t\t\t}\n\t\t}\n\t\tif d.Len() \u003e 0 {\n\t\t\tout.Append(svg.NewPath(d.String(), hex))\n\t\t}\n\t}\n\treturn out\n}\n\n// hex returns a palette entry normalised to \"#rrggbb\", or \"\" for a transparent\n// or unparseable one. Normalising rather than passing the raw string through is\n// what keeps an entry a caller typed out of the SVG document unescaped.\nfunc (p Palette) hex(i uint8) string {\n\tif int(i) \u003e= len(p) {\n\t\treturn \"\"\n\t}\n\tc, ok := ParseHex(p[i])\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn Hex(c)\n}\n"},{"name":"pix_test.gno","body":"package art\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// sprite builds a small indexed bitmap from a rune-per-pixel literal, so a test\n// can show the input instead of listing indices.\nfunc sprite(pal Palette, rows ...string) *Pix {\n\tw := 0\n\tfor _, r := range rows {\n\t\tif n := len([]rune(r)); n \u003e w {\n\t\t\tw = n\n\t\t}\n\t}\n\tp := NewPix(w, len(rows), pal)\n\tfor y, row := range rows {\n\t\tfor x, r := range []rune(row) {\n\t\t\tif r == '.' {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tp.Set(x, y, uint8(r-'0'))\n\t\t}\n\t}\n\treturn p\n}\n\n// TestRampCollapsesWhatGlyphsKeepsApart is the finding the whole package turns\n// on: a luminance ramp is the wrong conversion for indexed art.\n//\n// Sand (#e8dcc8) and bone (#d9d9d9) are two distinct palette entries any sprite\n// might carry. Their luminances are 221 and 217, four steps apart out of 255,\n// so a ten-step ramp drops both into bucket 8 and the shape between them\n// disappears. Keying on the palette index instead cannot do that, because the\n// index IS the artist's own segmentation.\nfunc TestRampCollapsesWhatGlyphsKeepsApart(t *testing.T) {\n\tpal := Palette{\"#000000\", \"#e8dcc8\", \"#d9d9d9\"}\n\tuassert.Equal(t, 221, Luminance(0xe8dcc8), \"sand\")\n\tuassert.Equal(t, 217, Luminance(0xd9d9d9), \"bone\")\n\n\tp := sprite(pal, \"0112\")\n\n\tramp := p.CanvasOpts(Opts{Mode: Ramp}).Text()\n\tglyph := p.CanvasOpts(Opts{Mode: Glyphs}).Text()\n\n\t// Both non-background entries land on the same ramp rune, so the two\n\t// regions merge into one blob.\n\tuassert.Equal(t, \" %%%\", ramp, \"ramp merges sand and bone\")\n\tuassert.Equal(t, 2, distinctRunes(ramp), \"ramp shows two distinct runes\")\n\n\t// Glyphs keeps three, one per palette index.\n\tuassert.Equal(t, \" ##@\", glyph, \"glyphs keep every index apart\")\n\tuassert.Equal(t, 3, distinctRunes(glyph), \"glyphs show three distinct runes\")\n}\n\nfunc TestGlyphDefaultsAreWideAndMonochrome(t *testing.T) {\n\tp := sprite(Palette{\"\", \"#ff0000\"}, \"01\")\n\n\t// A terminal cell is about twice as tall as it is wide, so one cell per\n\t// pixel would squash a sprite to half height.\n\twide := p.Canvas(Glyphs)\n\tuassert.Equal(t, 4, wide.W, \"default doubles the width\")\n\tuassert.Equal(t, \"  ##\", wide.Text(), \"each pixel is two cells\")\n\tuassert.Equal(t, Default, wide.At(2, 0).FG, \"no colour by default\")\n\n\tnarrow := p.CanvasOpts(Opts{Mode: Glyphs, Color: true})\n\tuassert.Equal(t, 2, narrow.W, \"Wide off means one cell per pixel\")\n\tuassert.Equal(t, 0xff0000, narrow.At(1, 0).FG, \"Color on carries the palette through\")\n}\n\nfunc TestCustomGlyphsAndWrapping(t *testing.T) {\n\tp := sprite(Palette{\"\", \"\", \"\"}, \"012\")\n\tgot := p.CanvasOpts(Opts{Mode: Glyphs, Glyphs: []rune{'a', 'b'}}).Text()\n\t// Two glyphs for three indices: index 2 wraps back onto 'a'. A real\n\t// collision, which is why the doc tells you to pass your own set.\n\tuassert.Equal(t, \"aba\", got, \"a short glyph set wraps\")\n}\n\nfunc TestHalfBlock(t *testing.T) {\n\tpal := Palette{\"\", \"#ff0000\", \"#0000ff\"}\n\tp := sprite(pal, \"11\", \"22\", \"11\")\n\n\tc := p.Canvas(HalfBlock)\n\tuassert.Equal(t, 2, c.W, \"width is unchanged\")\n\tuassert.Equal(t, 2, c.H, \"three rows pack into two cells\")\n\n\ttop := c.At(0, 0)\n\tuassert.Equal(t, '▀', top.R, \"upper half block\")\n\tuassert.Equal(t, 0xff0000, top.FG, \"foreground is the top pixel\")\n\tuassert.Equal(t, 0x0000ff, top.BG, \"background is the bottom pixel\")\n\n\t// The odd last row has no partner, so its background falls to Default\n\t// rather than reading a pixel that is not there.\n\tuassert.Equal(t, Default, c.At(0, 1).BG, \"odd height leaves the last background unset\")\n}\n\nfunc TestHalfBlockMonochromeFallsBackToInk(t *testing.T) {\n\tp := sprite(Palette{\"\", \"#ffffff\"}, \"10\", \"01\")\n\t// Without colour, '▀' everywhere would say nothing at all, so the mode\n\t// reports which halves carry ink instead.\n\tuassert.Equal(t, \"▀▄\", p.CanvasOpts(Opts{Mode: HalfBlock}).Text(), \"ink map\")\n}\n\nfunc TestQuadrant(t *testing.T) {\n\tpal := Palette{\"#000000\", \"#ff0000\"}\n\n\t// A solid 2x2 block of one index has no foreground at all.\n\tsolid := sprite(pal, \"11\", \"11\").Canvas(Quadrant)\n\tuassert.Equal(t, ' ', solid.At(0, 0).R, \"one colour means a blank cell on a solid background\")\n\tuassert.Equal(t, 0xff0000, solid.At(0, 0).BG, \"and that colour is the background\")\n\tuassert.Equal(t, Default, solid.At(0, 0).FG, \"with no foreground\")\n\n\t// Three background pixels and one foreground: the minority becomes the\n\t// glyph. Bit 0 is top-left.\n\tcorner := sprite(pal, \"10\", \"00\").Canvas(Quadrant)\n\tuassert.Equal(t, '▘', corner.At(0, 0).R, \"top-left quadrant\")\n\tuassert.Equal(t, 0xff0000, corner.At(0, 0).FG, \"the minority index is the foreground\")\n\n\tleft := sprite(pal, \"10\", \"10\").Canvas(Quadrant)\n\tuassert.Equal(t, '▌', left.At(0, 0).R, \"left half\")\n}\n\nfunc TestQuadrantPacksFourToOne(t *testing.T) {\n\tp := sprite(Palette{\"\", \"#fff\"}, \"1111\", \"1111\", \"1111\", \"1111\")\n\tc := p.Canvas(Quadrant)\n\tuassert.Equal(t, 2, c.W, \"half the columns\")\n\tuassert.Equal(t, 2, c.H, \"half the rows\")\n}\n\nfunc TestBraille(t *testing.T) {\n\tp := sprite(Palette{\"\", \"#ffffff\"}, \"10\", \"00\", \"00\", \"00\")\n\tc := p.Canvas(Braille)\n\tuassert.Equal(t, 1, c.W, \"2 columns pack into 1\")\n\tuassert.Equal(t, 1, c.H, \"4 rows pack into 1\")\n\tuassert.Equal(t, rune(0x2801), c.At(0, 0).R, \"top-left dot is bit 0\")\n\n\t// The fourth row took the high bits when it was added to the standard,\n\t// which is the one thing about Braille that is not sequential.\n\tlow := sprite(Palette{\"\", \"#ffffff\"}, \"00\", \"00\", \"00\", \"10\").Canvas(Braille)\n\tuassert.Equal(t, rune(0x2840), low.At(0, 0).R, \"bottom-left dot is bit 6\")\n\n\tfull := sprite(Palette{\"\", \"#ffffff\"}, \"11\", \"11\", \"11\", \"11\").Canvas(Braille)\n\tuassert.Equal(t, rune(0x28ff), full.At(0, 0).R, \"all eight dots\")\n\n\tempty := sprite(Palette{\"\", \"#ffffff\"}, \"00\").Canvas(Braille)\n\tuassert.Equal(t, rune(0x2800), empty.At(0, 0).R, \"blank braille, not a space\")\n}\n\nfunc TestPixSVGRunLength(t *testing.T) {\n\tpal := Palette{\"\", \"#ff0000\"}\n\tp := sprite(pal, \"0111\", \"0000\")\n\n\tdoc := p.SVG(4).String()\n\t// Index 0 is transparent, so it emits nothing; the three red pixels become\n\t// ONE run in ONE path, not three rectangles.\n\tuassert.Equal(t, 1, strings.Count(doc, \"\u003cpath\"), \"one path per colour\")\n\tuassert.True(t, strings.Contains(doc, `d=\"M1 0h3v1h-3z\"`), \"one run, in pixel coordinates\")\n\tuassert.True(t, strings.Contains(doc, `fill=\"#ff0000\"`), \"run colour\")\n\t// Scale goes on the canvas, not into the path, so scaling costs no bytes.\n\tuassert.True(t, strings.Contains(doc, `width=\"16\" height=\"8\"`), \"canvas is scaled\")\n\tuassert.True(t, strings.Contains(doc, `viewBox=\"0 0 4 2\"`), \"viewBox stays in pixel units\")\n}\n\nfunc TestPixSVGNormalisesColour(t *testing.T) {\n\t// A short-form entry is expanded rather than passed through, which is what\n\t// keeps an unparseable string a caller typed out of the document.\n\tp := sprite(Palette{\"#abc\"}, \"0\")\n\tuassert.True(t, strings.Contains(p.SVG(1).String(), `fill=\"#aabbcc\"`), \"short form expanded\")\n\n\tjunk := sprite(Palette{`\" onload=\"x`}, \"0\")\n\tuassert.Equal(t, 0, strings.Count(junk.SVG(1).String(), \"\u003cpath\"), \"an unparseable entry emits nothing\")\n}\n\nfunc TestPaletteColorOutOfRange(t *testing.T) {\n\tpal := Palette{\"#000000\"}\n\tuassert.Equal(t, Default, pal.Color(7), \"past the end is Default, not a panic\")\n\tuassert.Equal(t, Default, Palette{\"\"}.Color(0), \"an empty entry is transparent\")\n}\n\nfunc distinctRunes(s string) int {\n\tvar seen []rune\n\tfor _, r := range s {\n\t\tfound := false\n\t\tfor _, o := range seen {\n\t\t\tif o == r {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tseen = append(seen, r)\n\t\t}\n\t}\n\treturn len(seen)\n}\n"},{"name":"settler_test.gno","body":"package art\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Settler #25, read from mainnet on 2026-09-29 and transcribed one character\n// per palette index (0-9 then a-j). 32x32, 20 colours.\n//\n// It is here because the package's central claim is about real indexed art and\n// a synthetic two-colour fixture cannot test it: the interesting thing about a\n// sprite is how many near-luminance colours it carries, and that is a property\n// of art somebody drew.\n//\n// gno.land/r/g17khqpukees4237dtn3astzapmp462vjhsz6st4/settlers/nft:token/25\n// The Settlers art is dedicated to the public domain under CC0 1.0.\nvar settler25Pal = Palette{\"#f3e3c9\", \"#2a1a2e\", \"#ffb45a\", \"#b5601c\", \"#f08a2a\", \"#b57650\", \"#d99a6c\", \"#7f5234\", \"#1b1626\", \"#f08c7c\", \"#ffb0a0\", \"#c8645a\", \"#a8744e\", \"#573622\", \"#5fb0e8\", \"#2b649a\", \"#3f8fd1\", \"#6b3f22\", \"#6a4126\", \"#46271a\"}\n\nvar settler25Rows = []string{\n\t\"00000000000000011000000000000000\",\n\t\"00000000000000123100000000000000\",\n\t\"00000000000000144100000000000000\",\n\t\"00000000000001244310000000000000\",\n\t\"00000000000001444410000000000000\",\n\t\"00000000000012444431000000000000\",\n\t\"00000000000014444441000000000000\",\n\t\"00000000000124444443100000000000\",\n\t\"00000000000144444444100000000000\",\n\t\"00000000001244444444310000000000\",\n\t\"00000000001444444444410000000000\",\n\t\"00000000124444444444443100000000\",\n\t\"00000000133333333333333100000000\",\n\t\"00000000001555555555510000000000\",\n\t\"00000000001677766777610000000000\",\n\t\"00000000016686666668661000000000\",\n\t\"00000000156686699668665100000000\",\n\t\"00000000001666a99b66610000000000\",\n\t\"0000000001c777bbbb777d1000000000\",\n\t\"0000000011c7777777777d1100000000\",\n\t\"00000001e1c777d77d777d1f10000000\",\n\t\"00000001eg1c77d77d77d1gf10000000\",\n\t\"00000001eg1c7d7777d7d1gf10000000\",\n\t\"00000016egg1c7d77d7d1ggf61000000\",\n\t\"00000015egg1c777777d1ggf51000000\",\n\t\"00000001hhhh1c7dd7d1hhhh10000000\",\n\t\"00000001egggg1c77d1ggggf10000000\",\n\t\"00000001ffffff1cd1ffffff10000000\",\n\t\"0000000001iiiii11iiiii1000000000\",\n\t\"0000000001iiiii11iiiii1000000000\",\n\t\"0000000001jjjjj11jjjjj1000000000\",\n\t\"00000000011111111111111000000000\",\n}\n\nfunc settler25() *Pix {\n\tp := NewPix(len(settler25Rows[0]), len(settler25Rows), settler25Pal)\n\tfor y, row := range settler25Rows {\n\t\tfor x, r := range row {\n\t\t\tvar i int\n\t\t\tif r \u003e= '0' \u0026\u0026 r \u003c= '9' {\n\t\t\t\ti = int(r - '0')\n\t\t\t} else {\n\t\t\t\ti = int(r-'a') + 10\n\t\t\t}\n\t\t\tp.Set(x, y, uint8(i))\n\t\t}\n\t}\n\treturn p\n}\n\n// TestSettler25 is the finding measured on real art rather than on a fixture\n// chosen to show it.\n//\n// Settler #25 carries 20 palette entries. Keyed on the palette index, all 20\n// survive into the text. Keyed on luminance, a ten-step ramp resolves them to\n// 9: eleven of the artist's twenty colours stop existing, and the shapes\n// between them go with it.\n//\n// That is the whole argument for Glyphs being the default and Ramp being the\n// thing you ask for.\nfunc TestSettler25PaletteBeatsLuminance(t *testing.T) {\n\tglyphs := settler25().Canvas(Glyphs).Text()\n\tramp := settler25().Canvas(Ramp).Text()\n\n\t// distinctRunes counts the newline too, so both figures are colours + 1.\n\tuassert.Equal(t, 21, distinctRunes(glyphs), \"every palette entry survives\")\n\tuassert.Equal(t, 10, distinctRunes(ramp), \"the ramp resolves 20 colours to 9\")\n\tuassert.True(t, distinctRunes(glyphs) \u003e distinctRunes(ramp), \"glyphs strictly finer\")\n}\n\n// TestSettler25SVGIsOnePathPerColour pins the encoding that keeps a sprite\n// small enough for a realm to emit. 20 colours, 20 paths, and 4,532 bytes where\n// one rectangle per run cost 20,625.\nfunc TestSettler25SVGIsOnePathPerColour(t *testing.T) {\n\tdoc := settler25().SVG(8).String()\n\tuassert.Equal(t, 20, strings.Count(doc, \"\u003cpath\"), \"one path per palette entry\")\n\tuassert.Equal(t, 0, strings.Count(doc, \"\u003crect\"), \"no rectangles at all\")\n\tuassert.True(t, len(doc) \u003c 6000, \"a 32x32 sprite stays well under 6 KB\")\n\t// Scaling is a viewBox change, so the path data, which is all of the size,\n\t// is byte-identical at any scale. Only the canvas width and height move,\n\t// and here that is one digit each between \"32\" and \"256\".\n\tone := settler25().SVG(1).String()\n\tuassert.Equal(t, paths(one), paths(doc), \"path data is identical at any scale\")\n\tuassert.Equal(t, 2, len(doc)-len(one), \"only the canvas dimensions grow\")\n}\n\n// paths returns the document from its first \u003cpath\u003e on, which is everything\n// scale cannot affect.\nfunc paths(doc string) string {\n\ti := strings.Index(doc, \"\u003cpath\")\n\tif i \u003c 0 {\n\t\treturn \"\"\n\t}\n\treturn doc[i:]\n}\n\n// TestSettler25TextIsSmallerThanItsPicture is the reason a text target is worth\n// having at all, beyond readability: the ASCII form of this NFT is a third of\n// the SVG.\nfunc TestSettler25TextIsSmallerThanItsPicture(t *testing.T) {\n\ttext := settler25().Canvas(Glyphs).Text()\n\tuassert.Equal(t, 1469, len(text), \"glyph text size\")\n\tuassert.True(t, len(text) \u003c len(settler25().SVG(8).String()), \"text is the cheaper form\")\n}\n\n// TestSettler25RampConfusesHueForBrightness is the part of the finding that is\n// easy to miss: the ramp's collisions are not between near-identical shades.\n// Two colours a human would never confuse, an orange hat and a sky-blue tunic,\n// come out as the same character, because luminance cannot tell a hue from a\n// hue.\nfunc TestSettler25RampConfusesHueForBrightness(t *testing.T) {\n\torange := settler25Pal.Color(4) // #f08a2a, the hat\n\tblue := settler25Pal.Color(16)  // #3f8fd1, the tunic\n\n\tuassert.Equal(t, 152, Luminance(orange), \"orange hat\")\n\tuassert.Equal(t, 130, Luminance(blue), \"sky tunic\")\n\tuassert.NotEqual(t, orange, blue, \"they are different colours\")\n\tuassert.Equal(t, rampGlyph(orange), rampGlyph(blue), \"and the same ramp glyph\")\n\n\t// Keyed on the palette index instead, they cannot collide: the indices are\n\t// different, so the glyphs are.\n\tuassert.NotEqual(t,\n\t\tDefaultGlyphs[4%len(DefaultGlyphs)],\n\t\tDefaultGlyphs[16%len(DefaultGlyphs)],\n\t\t\"glyphs keep them apart\")\n}\n\nfunc rampGlyph(c int) rune {\n\treturn DefaultRamp[Luminance(c)*len(DefaultRamp)/256]\n}\n"},{"name":"svg.gno","body":"package art\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/svg/v0\"\n)\n\n// SVGOpts configures [Canvas.SVG]. The zero value is usable: every field falls\n// back to the constant beside it.\ntype SVGOpts struct {\n\tCellW, CellH int    // cell size in SVG units; 0 means 8 and 16\n\tFG, BG       int    // what a cell's Default resolves to; Default stays unset\n\tFont         string // font-family; \"\" means a monospace stack\n}\n\n// Defaults for [SVGOpts]. 8x16 is the usual terminal cell ratio, so art laid\n// out for a terminal keeps its proportions.\nconst (\n\tDefaultCellW = 8\n\tDefaultCellH = 16\n\tDefaultFont  = \"ui-monospace,SFMono-Regular,Menlo,Consolas,monospace\"\n)\n\n// SVG renders the canvas as an SVG document: background colours as run-length\n// rectangles, and one \u003ctext\u003e element per non-blank cell, centred in its cell so\n// the grid stays aligned whatever the renderer's idea of a monospace advance\n// width is.\n//\n// This is how colour reaches gnoweb. [Canvas.ANSI] cannot: raw ESC bytes are\n// stripped by p/nt/markdown/sanitize and are garbage in HTML regardless. An\n// SVG carries the same two colours per cell through a medium the web can show,\n// which is the whole argument for making the target a parameter.\n//\n// One element per cell rather than one per run is deliberate: a run of text\n// would have to assume the font's advance width, and a renderer that disagreed\n// would shear the picture. Dense pixel art should go through [Pix.SVG] instead,\n// which is run-length and has no font to get wrong.\nfunc (c Canvas) SVG(o SVGOpts) *svg.Canvas {\n\tcw, ch := o.CellW, o.CellH\n\tif cw \u003c= 0 {\n\t\tcw = DefaultCellW\n\t}\n\tif ch \u003c= 0 {\n\t\tch = DefaultCellH\n\t}\n\tfont := o.Font\n\tif font == \"\" {\n\t\tfont = DefaultFont\n\t}\n\n\tout := svg.NewCanvas(c.W*cw, c.H*ch)\n\tout.WithViewBox(0, 0, c.W*cw, c.H*ch)\n\tout.AddStyle(\"text\", \"font-family:\"+font+\";font-size:\"+itoa(ch)+\"px;text-anchor:middle;dominant-baseline:central\")\n\tout.AddStyle(\"rect\", \"shape-rendering:crispEdges\")\n\n\t// Backgrounds first, as horizontal runs, so they sit under the glyphs.\n\tfor y := 0; y \u003c c.H; y++ {\n\t\tx := 0\n\t\tfor x \u003c c.W {\n\t\t\tbg := c.bgAt(x, y, o.BG)\n\t\t\trun := 1\n\t\t\tfor x+run \u003c c.W \u0026\u0026 c.bgAt(x+run, y, o.BG) == bg {\n\t\t\t\trun++\n\t\t\t}\n\t\t\tif bg != Default {\n\t\t\t\tout.Append(svg.NewRectangle(x*cw, y*ch, run*cw, ch, Hex(bg)))\n\t\t\t}\n\t\t\tx += run\n\t\t}\n\t}\n\n\tfor y := 0; y \u003c c.H; y++ {\n\t\tfor x := 0; x \u003c c.W; x++ {\n\t\t\tcell := c.Cells[y*c.W+x]\n\t\t\tif cell.R == ' ' || cell.R == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfg := cell.FG\n\t\t\tif fg == Default {\n\t\t\t\tfg = o.FG\n\t\t\t}\n\t\t\tfill := Hex(fg)\n\t\t\tif fill == \"\" {\n\t\t\t\tfill = \"currentColor\"\n\t\t\t}\n\t\t\tout.Append(svg.NewText(x*cw+cw/2, y*ch+ch/2, escapeXML(string(cell.R)), fill))\n\t\t}\n\t}\n\treturn out\n}\n\nfunc (c Canvas) bgAt(x, y, fallback int) int {\n\tbg := c.Cells[y*c.W+x].BG\n\tif bg == Default {\n\t\treturn fallback\n\t}\n\treturn bg\n}\n\n// escapeXML is here and not in p/moul/svg because svg.Text interpolates its\n// content straight into the document: a rune this package can legitimately\n// produce, or a title a caller typed, would otherwise close the element.\nfunc escapeXML(s string) string {\n\tif !strings.ContainsAny(s, \"\u0026\u003c\u003e\\\"\") {\n\t\treturn s\n\t}\n\tvar b strings.Builder\n\tfor _, r := range s {\n\t\tswitch r {\n\t\tcase '\u0026':\n\t\t\tb.WriteString(\"\u0026amp;\")\n\t\tcase '\u003c':\n\t\t\tb.WriteString(\"\u0026lt;\")\n\t\tcase '\u003e':\n\t\t\tb.WriteString(\"\u0026gt;\")\n\t\tcase '\"':\n\t\t\tb.WriteString(\"\u0026quot;\")\n\t\tdefault:\n\t\t\tb.WriteRune(r)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc itoa(v int) string {\n\tif v == 0 {\n\t\treturn \"0\"\n\t}\n\tneg := v \u003c 0\n\tif neg {\n\t\tv = -v\n\t}\n\tvar buf [20]byte\n\ti := len(buf)\n\tfor v \u003e 0 {\n\t\ti--\n\t\tbuf[i] = byte('0' + v%10)\n\t\tv /= 10\n\t}\n\tif neg {\n\t\ti--\n\t\tbuf[i] = '-'\n\t}\n\treturn string(buf[i:])\n}\n"}]},"send":"","max_deposit":"23000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"mmr","path":"gno.land/p/moul/x/mmr/v0","files":[{"name":"README.md","body":"# mmr\n\nA **Merkle Mountain Range**: an append-only log whose root updates in O(log n) and whose\ninclusion proofs are O(log n) big.\n\n## Why not a plain Merkle tree\n\n[`p/moul/x/merkle/v0`](../../merkle/v0) commits to a **fixed** list. Adding a leaf means\nrebuilding from every leaf, which on chain means re-reading the whole set and re-hashing it,\non every append. An MMR never rebuilds: an append hashes at most log2(n) times and touches\nnothing else.\n\nThat is the shape any on-chain log wants. A wiki committing to its revision history, a forge\ncommitting to its objects, an agent realm committing to the receipts it issued: all append,\nnone rewrite.\n\n## The headline property: this *is* the Tendermint tree\n\nThe MMR root equals the Tendermint simple-tree root over the same leaves, **at every size**,\nnot only at powers of two.\n\nTendermint splits an `n`-leaf tree at the largest power of two below `n`. That left half is\nexactly the first mountain, and the right half recurses through the remaining set bits, which\nis exactly the peak bagging. The two constructions coincide.\n\nSo this package is a drop-in **incremental builder for Tendermint roots**: append in\nO(log n) on chain, hand out a root any Tendermint verifier accepts. Proofs cross over in both\ndirections, pinned by `TestMerkleProofVerifiesAgainstMMRRoot`.\n\nUse `merkle.New` when the leaf set is fixed and you want the simpler proof encoding. Use this\nwhen the log grows.\n\n## Structure\n\nAn MMR is a list of perfect binary trees (\"mountains\") of strictly decreasing height, one per\nset bit of the leaf count. Eleven leaves is `8 + 2 + 1`, so three mountains of height 3, 1\nand 0. Appending pushes a height-0 mountain and merges equal-height neighbours, exactly like\nincrementing a binary counter. The root bags the peaks right to left:\n\n```\nroot = InnerHash(p0, InnerHash(p1, InnerHash(p2, …)))\n```\n\n## Usage\n\n```go\nimport \"gno.land/p/moul/x/mmr/v0\"\n\nlog := mmr.New()\ni := log.Append([]byte(\"receipt-1\"))   // O(log n), returns the leaf index\nlog.Append([]byte(\"receipt-2\"))\n\nroot := log.RootHex()                  // commit or emit this\np, _ := log.Proof(i)                   // Index, Total, Path, Before, After\n\n// anywhere, later:\nif mmr.Verify(root, []byte(\"receipt-1\"), p) { … }\n```\n\n## Proofs are bound to position *and* to size\n\nA proof carries the leaf index and the leaf count the log had when it was issued. The verifier\nrecomputes the entire peak structure from that count, which fixes the peak count, which\nmountain holds the leaf, the local index inside it, and therefore the exact expected length of\nevery component. A proof cannot be replayed at another index, against another size, or padded.\n`TestRejects` covers thirteen such attempts.\n\nBecause the root moves on every append, a proof is valid against the root at its own `Total`\nand no other. A realm that wants old proofs to keep verifying must keep the historical roots:\none 32-byte hash per append, the price of an auditable log.\n\n## Storage\n\n`Append` stores one node per leaf plus one per merge: **2n - popcount(n)** hashes for n\nleaves, under 64 bytes per leaf amortised, pinned by `TestNodeCount`. That is what on-chain\nproof generation costs.\n\nA realm that only ever needs to **verify** proofs, with the tree living off chain, should\nstore the root alone and use [`p/moul/x/merkle/v0`](../../merkle/v0) instead. `PeakHashes()`\nreturns the whole verifier-side state and stays logarithmic: 10 hashes at 1023 leaves, 1 at\n1024.\n\n## Related\n\n- Fixed-list trees and the scheme rationale: [`p/moul/x/merkle/v0`](../../merkle/v0)\n- Live demo: [`r/moul/x/provable/v0`](../../../../../r/moul/x/provable/v0)\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/mmr/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/mmr/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/mmr/v0\"\ngno = \"0.9\"\n"},{"name":"mmr.gno","body":"// Package mmr implements a Merkle Mountain Range: an append-only log with a\n// root that updates in O(log n) and inclusion proofs of O(log n) size.\n//\n// # Why not a plain Merkle tree\n//\n// gno.land/p/moul/x/merkle/v0 commits to a FIXED list. Adding a leaf means\n// rebuilding from every leaf, which on chain means re-reading the whole set\n// and re-hashing it, every time. An MMR never rebuilds: an append hashes at\n// most log2(n) times and touches nothing else.\n//\n// That is the shape any on-chain log wants. A wiki committing to its revision\n// history, a forge committing to its objects, an agent realm committing to the\n// receipts it issued: all append, none rewrite.\n//\n// # The structure\n//\n// An MMR is a list of perfect binary trees (\"mountains\") of strictly\n// decreasing height, one per set bit of the leaf count. Eleven leaves is\n// 8 + 2 + 1, so three mountains of height 3, 1 and 0. Appending a leaf pushes\n// a height-0 mountain and merges equal-height neighbours, exactly like\n// incrementing a binary counter.\n//\n// The root is the peaks \"bagged\" right to left:\n//\n//\troot = InnerHash(p0, InnerHash(p1, InnerHash(p2, …)))\n//\n// Hashing is gno.land/p/moul/x/merkle/v0's, which is Tendermint's: leaves are\n// tagged 0x00 and inner nodes 0x01. Leaf and inner preimages therefore cannot\n// collide, so the second-preimage forgery that works against untagged schemes\n// does not apply here. See that package for the worked attack.\n//\n// # This IS the Tendermint tree\n//\n// The root above equals the Tendermint simple-tree root over the same leaves,\n// at every size and not merely at powers of two. Tendermint splits an n-leaf\n// tree at the largest power of two below n: that left half is exactly the\n// first mountain, and the right half recurses through the remaining set bits,\n// which is exactly the bagging. The two constructions coincide.\n//\n// So this package is a drop-in INCREMENTAL BUILDER for Tendermint roots.\n// Append in O(log n) on chain and hand out a root that any Tendermint verifier\n// accepts; proofs cross over in both directions, which\n// TestMerkleProofVerifiesAgainstMMRRoot pins. Use merkle.New when the leaf set\n// is fixed and you want the simpler proof encoding, use this when the log\n// grows.\n//\n// # Proofs are bound to position and to size\n//\n// A Proof carries the leaf index and the leaf count the MMR had when it was\n// issued. The verifier recomputes the whole peak structure from that count,\n// which fixes the number of peaks, which mountain holds the leaf, the local\n// index inside it, and therefore the exact expected length of every component\n// of the proof. A proof cannot be replayed at another index, against another\n// size, or padded.\n//\n// Because the root changes on every append, a proof is valid against the root\n// at its own Total and no other. A realm that wants old proofs to keep\n// verifying must keep the historical roots; Roots grow by one 32-byte hash per\n// append, which is the price of an auditable log.\n//\n// # Storage\n//\n// Append stores one node per leaf plus one per merge, so 2n-popcount(n) hashes\n// for n leaves, under 64 bytes per leaf amortised. That is what on-chain proof\n// generation costs. A realm that only ever needs to VERIFY proofs, with the\n// tree living off chain, should store the root alone and use\n// gno.land/p/moul/x/merkle/v0's Verify instead.\n//\n// Live demo: gno.land/r/moul/x/provable/v0\npackage mmr\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n)\n\n// HashSize is the length in bytes of every node hash.\nconst HashSize = merkle.HashSize\n\n// MaxPeaks caps the peak count a Proof may claim. A 64-peak MMR would hold\n// more than 2^64 leaves.\nconst MaxPeaks = 64\n\nvar (\n\tErrEmpty      = errors.New(\"mmr: log is empty\")\n\tErrIndexRange = errors.New(\"mmr: leaf index out of range\")\n\tErrBadHex     = errors.New(\"mmr: hash is not valid hex\")\n\tErrBadSize    = errors.New(\"mmr: hash is not 32 bytes\")\n\tErrTooManyPeaks = errors.New(\"mmr: more peaks than MaxPeaks\")\n)\n\n// peak is one mountain: the position of its root in nodes, and its height.\ntype peak struct {\n\tpos    int\n\theight int\n}\n\n// MMR is an append-only Merkle mountain range.\n//\n// The zero value is an empty, ready-to-use log.\ntype MMR struct {\n\tnodes  [][]byte // every node, in postorder: [left subtree][right subtree][root]\n\tpeaks  []peak\n\tleaves int\n}\n\n// New returns an empty MMR.\nfunc New() *MMR { return \u0026MMR{} }\n\n// Size returns the number of leaves appended so far.\nfunc (m *MMR) Size() int { return m.leaves }\n\n// Nodes returns the number of stored hashes, leaves and merges together. Use\n// it to reason about storage growth.\nfunc (m *MMR) Nodes() int { return len(m.nodes) }\n\n// Append adds a leaf and returns its index. O(log n) hashes, no rebuild.\nfunc (m *MMR) Append(leaf []byte) int {\n\tindex := m.leaves\n\tm.nodes = append(m.nodes, merkle.LeafHash(leaf))\n\tm.peaks = append(m.peaks, peak{pos: len(m.nodes) - 1, height: 0})\n\tfor len(m.peaks) \u003e= 2 {\n\t\tright := m.peaks[len(m.peaks)-1]\n\t\tleft := m.peaks[len(m.peaks)-2]\n\t\tif left.height != right.height {\n\t\t\tbreak\n\t\t}\n\t\tm.nodes = append(m.nodes, merkle.InnerHash(m.nodes[left.pos], m.nodes[right.pos]))\n\t\tm.peaks = m.peaks[:len(m.peaks)-2]\n\t\tm.peaks = append(m.peaks, peak{pos: len(m.nodes) - 1, height: left.height + 1})\n\t}\n\tm.leaves++\n\treturn index\n}\n\n// Root returns the current root, nil while the log is empty.\nfunc (m *MMR) Root() []byte {\n\tif len(m.peaks) == 0 {\n\t\treturn nil\n\t}\n\treturn bag(m.peakHashes())\n}\n\n// RootHex returns Root hex-encoded.\nfunc (m *MMR) RootHex() string { return hex.EncodeToString(m.Root()) }\n\n// PeakHashes returns the current peak hashes, left to right. This is the whole\n// state a verifier needs, and it is O(log n).\nfunc (m *MMR) PeakHashes() [][]byte { return m.peakHashes() }\n\nfunc (m *MMR) peakHashes() [][]byte {\n\tout := make([][]byte, len(m.peaks))\n\tfor i, p := range m.peaks {\n\t\tout[i] = m.nodes[p.pos]\n\t}\n\treturn out\n}\n\n// bag folds peaks right to left: InnerHash(p0, InnerHash(p1, …)).\nfunc bag(peaks [][]byte) []byte {\n\tif len(peaks) == 0 {\n\t\treturn nil\n\t}\n\tacc := peaks[len(peaks)-1]\n\tfor i := len(peaks) - 2; i \u003e= 0; i-- {\n\t\tacc = merkle.InnerHash(peaks[i], acc)\n\t}\n\treturn acc\n}\n\n// Proof is an inclusion proof for one leaf of a log that held Total leaves.\n//\n// Path holds the sibling hashes inside the leaf's own mountain, leaf first.\n// Before and After hold the other peak hashes, in left-to-right order.\ntype Proof struct {\n\tIndex  int\n\tTotal  int\n\tPath   [][]byte\n\tBefore [][]byte\n\tAfter  [][]byte\n}\n\n// Proof returns the inclusion proof for the leaf at index, against the current\n// root.\nfunc (m *MMR) Proof(index int) (Proof, error) {\n\tif m.leaves == 0 {\n\t\treturn Proof{}, ErrEmpty\n\t}\n\tif index \u003c 0 || index \u003e= m.leaves {\n\t\treturn Proof{}, ErrIndexRange\n\t}\n\tj, local := locate(m.leaves, index)\n\thashes := m.peakHashes()\n\treturn Proof{\n\t\tIndex:  index,\n\t\tTotal:  m.leaves,\n\t\tPath:   m.pathIn(m.peaks[j], local),\n\t\tBefore: hashes[:j],\n\t\tAfter:  hashes[j+1:],\n\t}, nil\n}\n\n// pathIn walks down the perfect tree rooted at p, collecting the sibling at\n// each level, and returns them leaf first.\n//\n// The layout is postorder, so for a node at position pos and height h the\n// right child root sits at pos-1 and the left child root at pos-1-(2^h - 1),\n// a perfect subtree of height h-1 holding 2^h - 1 nodes.\nfunc (m *MMR) pathIn(p peak, local int) [][]byte {\n\tvar out [][]byte\n\tpos, h := p.pos, p.height\n\tfor h \u003e 0 {\n\t\trightRoot := pos - 1\n\t\tleftRoot := pos - 1 - ((1 \u003c\u003c uint(h)) - 1)\n\t\thalf := 1 \u003c\u003c uint(h-1)\n\t\tif local \u003c half {\n\t\t\tout = append([][]byte{m.nodes[rightRoot]}, out...)\n\t\t\tpos = leftRoot\n\t\t} else {\n\t\t\tout = append([][]byte{m.nodes[leftRoot]}, out...)\n\t\t\tpos = rightRoot\n\t\t\tlocal -= half\n\t\t}\n\t\th--\n\t}\n\treturn out\n}\n"},{"name":"mmr_test.gno","body":"package mmr\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n)\n\nfunc leafAt(i int) []byte { return []byte(\"entry-\" + strconv.Itoa(i)) }\n\nfunc build(n int) *MMR {\n\tm := New()\n\tfor i := 0; i \u003c n; i++ {\n\t\tif got := m.Append(leafAt(i)); got != i {\n\t\t\tpanic(\"Append returned the wrong index\")\n\t\t}\n\t}\n\treturn m\n}\n\n// The property that matters: for every log size up to 40, every leaf ever\n// appended has a proof that verifies against the root at that size.\nfunc TestEveryProofVerifies(t *testing.T) {\n\tfor n := 1; n \u003c= 40; n++ {\n\t\tm := build(n)\n\t\troot := m.Root()\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\tp, err := m.Proof(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"n=%d i=%d: Proof: %v\", n, i, err)\n\t\t\t}\n\t\t\tif !Verify(root, leafAt(i), p) {\n\t\t\t\tt.Errorf(\"n=%d i=%d: valid proof rejected\", n, i)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// A one-leaf MMR is a single height-0 mountain, so its root is just the\n// tagged leaf hash and the proof is empty.\nfunc TestSingleLeaf(t *testing.T) {\n\tm := build(1)\n\tif string(m.Root()) != string(merkle.LeafHash(leafAt(0))) {\n\t\tt.Error(\"one-leaf root is not the leaf hash\")\n\t}\n\tp, err := m.Proof(0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(p.Path) != 0 || len(p.Before) != 0 || len(p.After) != 0 {\n\t\tt.Error(\"one-leaf proof should be empty\")\n\t}\n}\n\n// The Tendermint simple tree and a right-bagged MMR are the SAME tree, at\n// every size and not only at powers of two. Tendermint splits an n-leaf tree\n// at the largest power of two below n: that left half is exactly the first\n// mountain, and the right half recurses into the remaining set bits, which is\n// exactly the bagging. So an MMR is a drop-in incremental builder for\n// Tendermint roots: append in O(log n) on chain, hand out a root any\n// Tendermint verifier accepts.\nfunc TestRootMatchesTendermintTreeAtEverySize(t *testing.T) {\n\tfor n := 1; n \u003c= 40; n++ {\n\t\tls := make([][]byte, n)\n\t\tfor i := range ls {\n\t\t\tls[i] = leafAt(i)\n\t\t}\n\t\tif got, want := build(n).RootHex(), merkle.New(ls).RootHex(); got != want {\n\t\t\tt.Errorf(\"n=%d: MMR root %s, Tendermint tree root %s\", n, got, want)\n\t\t}\n\t}\n}\n\n// The consequence of the equality above: a proof produced by the fixed-list\n// Tendermint tree verifies against the root an MMR maintained incrementally,\n// and both packages agree leaf by leaf.\nfunc TestMerkleProofVerifiesAgainstMMRRoot(t *testing.T) {\n\tfor _, n := range []int{1, 2, 3, 5, 7, 11, 16, 23} {\n\t\tls := make([][]byte, n)\n\t\tfor i := range ls {\n\t\t\tls[i] = leafAt(i)\n\t\t}\n\t\tm := build(n)\n\t\ttree := merkle.New(ls)\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttp, err := tree.Proof(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"n=%d i=%d: %v\", n, i, err)\n\t\t\t}\n\t\t\tif !tp.Verify(m.Root(), leafAt(i)) {\n\t\t\t\tt.Errorf(\"n=%d i=%d: Tendermint proof rejected by the MMR root\", n, i)\n\t\t\t}\n\t\t\tmp, err := m.Proof(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"n=%d i=%d: %v\", n, i, err)\n\t\t\t}\n\t\t\tif !Verify(tree.Root(), leafAt(i), mp) {\n\t\t\t\tt.Errorf(\"n=%d i=%d: MMR proof rejected by the tree root\", n, i)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestPeakStructure(t *testing.T) {\n\ttests := []struct {\n\t\tleaves int\n\t\twant   []int\n\t}{\n\t\t{1, []int{0}},\n\t\t{2, []int{1}},\n\t\t{3, []int{1, 0}},\n\t\t{4, []int{2}},\n\t\t{7, []int{2, 1, 0}},\n\t\t{11, []int{3, 1, 0}},\n\t\t{16, []int{4}},\n\t}\n\tfor _, tc := range tests {\n\t\tif got := len(peakHeights(tc.leaves)); got != len(tc.want) {\n\t\t\tt.Errorf(\"n=%d: %d peaks, want %d\", tc.leaves, got, len(tc.want))\n\t\t\tcontinue\n\t\t}\n\t\tfor i, h := range peakHeights(tc.leaves) {\n\t\t\tif h != tc.want[i] {\n\t\t\t\tt.Errorf(\"n=%d: peak %d height %d, want %d\", tc.leaves, i, h, tc.want[i])\n\t\t\t}\n\t\t}\n\t\tif got := len(build(tc.leaves).peaks); got != len(tc.want) {\n\t\t\tt.Errorf(\"n=%d: MMR built %d peaks, want %d\", tc.leaves, got, len(tc.want))\n\t\t}\n\t}\n}\n\nfunc TestRejects(t *testing.T) {\n\tm := build(11)\n\troot := m.Root()\n\tp3, _ := m.Proof(3)\n\tp7, _ := m.Proof(7)\n\n\ttests := []struct {\n\t\tname  string\n\t\troot  []byte\n\t\tleaf  []byte\n\t\tproof Proof\n\t}{\n\t\t{\"forged leaf\", root, []byte(\"never-appended\"), p3},\n\t\t{\"another real leaf\", root, leafAt(4), p3},\n\t\t{\"proof replayed at another index\", root, leafAt(3), Proof{Index: 4, Total: p3.Total, Path: p3.Path, Before: p3.Before, After: p3.After}},\n\t\t{\"another leaf's proof\", root, leafAt(3), p7},\n\t\t{\"wrong total\", root, leafAt(3), Proof{Index: 3, Total: 10, Path: p3.Path, Before: p3.Before, After: p3.After}},\n\t\t{\"padded path\", root, leafAt(3), Proof{Index: 3, Total: 11, Path: append(append([][]byte{}, p3.Path...), make([]byte, HashSize)), Before: p3.Before, After: p3.After}},\n\t\t{\"truncated path\", root, leafAt(3), Proof{Index: 3, Total: 11, Path: p3.Path[:len(p3.Path)-1], Before: p3.Before, After: p3.After}},\n\t\t{\"peaks swapped\", root, leafAt(3), Proof{Index: 3, Total: 11, Path: p3.Path, Before: p3.After, After: p3.Before}},\n\t\t{\"index beyond total\", root, leafAt(3), Proof{Index: 11, Total: 11, Path: p3.Path, Before: p3.Before, After: p3.After}},\n\t\t{\"negative index\", root, leafAt(3), Proof{Index: -1, Total: 11, Path: p3.Path, Before: p3.Before, After: p3.After}},\n\t\t{\"zero total\", root, leafAt(3), Proof{Index: 0, Total: 0}},\n\t\t{\"short root\", root[:31], leafAt(3), p3},\n\t\t{\"short hash in path\", root, leafAt(3), Proof{Index: 3, Total: 11, Path: [][]byte{{1, 2, 3}, p3.Path[1]}, Before: p3.Before, After: p3.After}},\n\t}\n\tfor _, tc := range tests {\n\t\tif Verify(tc.root, tc.leaf, tc.proof) {\n\t\t\tt.Errorf(\"%s: accepted, must be rejected\", tc.name)\n\t\t}\n\t}\n}\n\n// A proof is issued against one size. Appending moves the root, and the old\n// proof must stop verifying against the new one rather than quietly pass.\nfunc TestProofIsBoundToItsSize(t *testing.T) {\n\tm := build(5)\n\told, _ := m.Proof(2)\n\toldRoot := m.Root()\n\tif !Verify(oldRoot, leafAt(2), old) {\n\t\tt.Fatal(\"proof does not verify against its own root\")\n\t}\n\tm.Append(leafAt(5))\n\tif Verify(m.Root(), leafAt(2), old) {\n\t\tt.Error(\"a stale proof verified against the new root\")\n\t}\n\tfresh, _ := m.Proof(2)\n\tif !Verify(m.Root(), leafAt(2), fresh) {\n\t\tt.Error(\"a reissued proof does not verify\")\n\t}\n\tif !Verify(oldRoot, leafAt(2), old) {\n\t\tt.Error(\"the old proof stopped verifying against the old root\")\n\t}\n}\n\nfunc TestEmptyAndRange(t *testing.T) {\n\tm := New()\n\tif m.Size() != 0 || m.Root() != nil || m.Nodes() != 0 {\n\t\tt.Error(\"a fresh MMR is not empty\")\n\t}\n\tif _, err := m.Proof(0); err != ErrEmpty {\n\t\tt.Errorf(\"empty Proof: err = %v, want %v\", err, ErrEmpty)\n\t}\n\tm.Append(leafAt(0))\n\tfor _, i := range []int{-1, 1, 99} {\n\t\tif _, err := m.Proof(i); err != ErrIndexRange {\n\t\t\tt.Errorf(\"index %d: err = %v, want %v\", i, err, ErrIndexRange)\n\t\t}\n\t}\n}\n\n// Storage claim from the package doc: 2n - popcount(n) stored hashes.\nfunc TestNodeCount(t *testing.T) {\n\tfor n := 1; n \u003c= 40; n++ {\n\t\twant := 2*n - popcount(n)\n\t\tif got := build(n).Nodes(); got != want {\n\t\t\tt.Errorf(\"n=%d: %d nodes, want 2n-popcount(n) = %d\", n, got, want)\n\t\t}\n\t}\n}\n\nfunc popcount(n int) int {\n\tc := 0\n\tfor n != 0 {\n\t\tc += n \u0026 1\n\t\tn \u003e\u003e= 1\n\t}\n\treturn c\n}\n\nfunc TestParseProofRoundTrip(t *testing.T) {\n\tm := build(11)\n\tfor i := 0; i \u003c 11; i++ {\n\t\twant, _ := m.Proof(i)\n\t\tpath, before, after := want.Hex()\n\t\tgot, err := ParseProof(i, 11, path, before, after)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"i=%d: ParseProof: %v\", i, err)\n\t\t}\n\t\tif !Verify(m.Root(), leafAt(i), got) {\n\t\t\tt.Errorf(\"i=%d: reparsed proof does not verify\", i)\n\t\t}\n\t}\n}\n\nfunc TestParseProofErrors(t *testing.T) {\n\tif _, err := ParseProof(0, 2, \"zz\", \"\", \"\"); err != ErrBadHex {\n\t\tt.Errorf(\"bad hex: err = %v\", err)\n\t}\n\tif _, err := ParseProof(0, 2, \"abcd\", \"\", \"\"); err != ErrBadSize {\n\t\tt.Errorf(\"bad size: err = %v\", err)\n\t}\n}\n\n// PeakHashes is the whole verifier-side state, and it must stay logarithmic.\nfunc TestPeakCountIsLogarithmic(t *testing.T) {\n\tm := build(1023)\n\tif got := len(m.PeakHashes()); got != 10 {\n\t\tt.Errorf(\"1023 leaves: %d peaks, want 10\", got)\n\t}\n\tif got := len(build(1024).PeakHashes()); got != 1 {\n\t\tt.Errorf(\"1024 leaves: %d peaks, want 1\", got)\n\t}\n}\n"},{"name":"verify.gno","body":"package mmr\n\nimport (\n\t\"encoding/hex\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n)\n\n// peakHeights returns the mountain heights of a log of total leaves, left to\n// right. They are the set bits of total, high to low: 11 leaves is 8 + 2 + 1,\n// so heights 3, 1, 0.\nfunc peakHeights(total int) []int {\n\tvar out []int\n\tfor h := 62; h \u003e= 0; h-- {\n\t\tif total\u0026(1\u003c\u003cuint(h)) != 0 {\n\t\t\tout = append(out, h)\n\t\t}\n\t}\n\treturn out\n}\n\n// locate returns which mountain holds the leaf at index, and the leaf's index\n// within that mountain. It returns -1 when index is out of range.\nfunc locate(total, index int) (int, int) {\n\toffset := 0\n\tfor j, h := range peakHeights(total) {\n\t\tsize := 1 \u003c\u003c uint(h)\n\t\tif index \u003c offset+size {\n\t\t\treturn j, index - offset\n\t\t}\n\t\toffset += size\n\t}\n\treturn -1, 0\n}\n\n// Verify reports whether leaf really sits at p.Index of a log that held\n// p.Total leaves and whose root is root.\n//\n// Every dimension of the proof is checked against p.Total rather than trusted:\n// the peak count, which mountain holds the leaf, the local index, the path\n// length and both peak-list lengths are all recomputed. A proof that does not\n// have exactly the shape p.Total implies is rejected before any hashing.\n//\n// Failures are false, never a panic, so a realm chooses whether a bad proof\n// aborts or branches.\nfunc Verify(root, leaf []byte, p Proof) bool {\n\tif len(root) != HashSize || p.Total \u003c= 0 || p.Index \u003c 0 || p.Index \u003e= p.Total {\n\t\treturn false\n\t}\n\theights := peakHeights(p.Total)\n\tif len(heights) \u003e MaxPeaks {\n\t\treturn false\n\t}\n\tj, local := locate(p.Total, p.Index)\n\tif j \u003c 0 {\n\t\treturn false\n\t}\n\tif len(p.Path) != heights[j] || len(p.Before) != j || len(p.After) != len(heights)-1-j {\n\t\treturn false\n\t}\n\tif !allHashes(p.Path) || !allHashes(p.Before) || !allHashes(p.After) {\n\t\treturn false\n\t}\n\n\tnode := merkle.LeafHash(leaf)\n\tfor d, sib := range p.Path {\n\t\tif (local\u003e\u003euint(d))\u00261 == 1 {\n\t\t\tnode = merkle.InnerHash(sib, node)\n\t\t} else {\n\t\t\tnode = merkle.InnerHash(node, sib)\n\t\t}\n\t}\n\n\tpeaks := make([][]byte, 0, len(heights))\n\tpeaks = append(peaks, p.Before...)\n\tpeaks = append(peaks, node)\n\tpeaks = append(peaks, p.After...)\n\treturn equal(bag(peaks), root)\n}\n\nfunc allHashes(hs [][]byte) bool {\n\tfor _, h := range hs {\n\t\tif len(h) != HashSize {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc equal(a, b []byte) bool {\n\tif len(a) != len(b) || len(a) == 0 {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Hex renders the three hash lists as comma-separated hex, in the order\n// path|before|after, which is what a realm call takes as arguments.\nfunc (p Proof) Hex() (path, before, after string) {\n\treturn joinHex(p.Path), joinHex(p.Before), joinHex(p.After)\n}\n\nfunc joinHex(hs [][]byte) string {\n\tparts := make([]string, len(hs))\n\tfor i, h := range hs {\n\t\tparts[i] = hex.EncodeToString(h)\n\t}\n\treturn strings.Join(parts, \",\")\n}\n\n// ParseProof rebuilds a Proof from realm-call arguments. Each of path, before\n// and after is a comma-separated hex list, possibly empty.\nfunc ParseProof(index, total int, path, before, after string) (Proof, error) {\n\tph, err := splitHex(path)\n\tif err != nil {\n\t\treturn Proof{}, err\n\t}\n\tbh, err := splitHex(before)\n\tif err != nil {\n\t\treturn Proof{}, err\n\t}\n\tah, err := splitHex(after)\n\tif err != nil {\n\t\treturn Proof{}, err\n\t}\n\tif len(bh)+len(ah)+1 \u003e MaxPeaks {\n\t\treturn Proof{}, ErrTooManyPeaks\n\t}\n\treturn Proof{Index: index, Total: total, Path: ph, Before: bh, After: ah}, nil\n}\n\nfunc splitHex(s string) ([][]byte, error) {\n\ts = strings.TrimSpace(s)\n\tif s == \"\" {\n\t\treturn nil, nil\n\t}\n\tvar out [][]byte\n\tfor _, raw := range strings.Split(s, \",\") {\n\t\traw = strings.TrimSpace(raw)\n\t\tif raw == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tb, err := hex.DecodeString(raw)\n\t\tif err != nil {\n\t\t\treturn nil, ErrBadHex\n\t\t}\n\t\tif len(b) != HashSize {\n\t\t\treturn nil, ErrBadSize\n\t\t}\n\t\tout = append(out, b)\n\t}\n\treturn out, nil\n}\n"}]},"send":"","max_deposit":"10000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"memfs","path":"gno.land/p/moul/x/plan9/memfs/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/plan9/memfs/v0`\n\n**A RAM file server**: Plan 9's `ramfs`, in a realm's heap. The reference\nimplementation of [`ninep.File`](../../ninep/v0) and `ninep.Mutable`.\n\n```go\nimport memfs \"gno.land/p/moul/x/plan9/memfs/v0\"\n\nfs := memfs.New(\"g1...\", runtime.ChainHeight())\nfs.MkdirAll(\"/usr/glenda/bin\", height)\nfs.WriteFile(\"/tmp/greeting\", \"hello\\n\", height)\nroot := fs.Root()   // a ninep.File, mountable into any namespace\n```\n\nChildren live in an `avl.Tree`, so a directory listing is ordered by name and\ntherefore identical on every validating node. A map would make `Render` a\nconsensus bug.\n\n**`Mutable` is in-realm only.** A non-crossing method runs in the *caller's*\nframe, so a foreign realm calling `Create` or `Write` here would be mutating\nobjects it does not own. The read half is safe from anywhere, which is exactly\nwhat makes a memfs tree mountable into somebody else's namespace: they get\nreads, and only its owner gets writes.\n\n**The clock is a parameter, not an import.** Every mutation takes the block\nheight from the caller rather than reading chain state itself, so the same tree\nruns in a plain unit test.\n\n9P behaviours reproduced rather than approximated:\n\n- A directory reports `Length` 0, as 9P does.\n- `Qid.Version` increments on every write, so a client holding a qid can tell\n  \"same file, changed\" from \"different file\" without reading it.\n- Writing past the end extends the file with NUL bytes.\n- `DMAPPEND` pins every write to the end, whatever offset was asked for.\n- Removing a non-empty directory is refused.\n\nDesign and analysis:\n[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\n\n---\n\n**Not affiliated with Plan 9.** Plan 9 from Bell Labs is the work of the\nComputing Science Research Center at Bell Labs; the name and the marks are\ntheirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org).\nThis package borrows the vocabulary and none of the code: it is an independent\nhomage, asking what that ecosystem's spirit looks like on a chain. Full\nattribution: [NOTICE](../../../../../NOTICE.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/plan9/memfs/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/plan9/memfs/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/plan9/memfs/v0\"\ngno = \"0.9\"\n"},{"name":"memfs.gno","body":"// Package memfs is a RAM file server: Plan 9's ramfs, in a realm's heap.\n//\n// It is the reference implementation of gno.land/p/moul/x/plan9/ninep's File\n// and Mutable, and the tree a namespace server hands out as a user's private\n// root. Children live in an avl.Tree, so a directory listing is ordered by\n// name and therefore identical on every validating node; a map would make\n// Render a consensus bug.\n//\n// Mutable is IN-REALM ONLY. A non-crossing method runs in the caller's frame,\n// so a foreign realm calling Create or Write here would be mutating objects it\n// does not own. Reads (the ninep.File half) are safe from anywhere, which is\n// what makes a memfs tree mountable into somebody else's namespace.\n//\n// The caller supplies the clock (a block height) on every mutation rather than\n// the tree reading chain state itself, so the same tree is exercisable in a\n// plain unit test.\n//\n// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research\n// Center at Bell Labs; the name and the marks are theirs, and the copyright is\n// held by the Plan 9 Foundation (https://p9f.org). This package is not\n// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9\n// code: it borrows the vocabulary so that the design reads without a glossary,\n// and it is an homage, asking what that ecosystem's spirit looks like on a\n// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.\npackage memfs\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n)\n\n// FS is a mutable in-memory file tree.\ntype FS struct {\n\troot *node\n\tnext uint64 // qid path allocator, unique for this server's lifetime\n\tuid  string\n}\n\ntype node struct {\n\tfs       *FS\n\tname     string\n\tperm     ninep.Perm\n\tqid      ninep.Qid\n\tdata     string\n\tchildren *avl.Tree // name -\u003e *node; nil for a plain file\n\tmtime    int64\n\tuid      string\n\tgid      string\n\tmuid     string\n}\n\n// New returns an empty file server owned by uid, with its root created at\n// block height now.\nfunc New(uid string, now int64) *FS {\n\tfs := \u0026FS{uid: uid}\n\tfs.root = fs.newNode(\"/\", ninep.DirPerm, now)\n\treturn fs\n}\n\n// Root returns the server's root directory.\nfunc (fs *FS) Root() ninep.File { return fs.root }\n\n// RootMutable returns the root as a Mutable. Only call it from the realm that\n// owns this FS.\nfunc (fs *FS) RootMutable() ninep.Mutable { return fs.root }\n\n// Uid returns the owner this server stamps on new files.\nfunc (fs *FS) Uid() string { return fs.uid }\n\nfunc (fs *FS) newNode(name string, perm ninep.Perm, now int64) *node {\n\tfs.next++\n\tqt := ninep.QTFILE\n\tvar kids *avl.Tree\n\tif perm.IsDir() {\n\t\tqt = ninep.QTDIR\n\t\tkids = avl.NewTree()\n\t}\n\treturn \u0026node{\n\t\tfs:       fs,\n\t\tname:     name,\n\t\tperm:     perm,\n\t\tqid:      ninep.Qid{Type: qt, Version: 0, Path: fs.next},\n\t\tchildren: kids,\n\t\tmtime:    now,\n\t\tuid:      fs.uid,\n\t\tgid:      fs.uid,\n\t\tmuid:     fs.uid,\n\t}\n}\n\n// Stat implements ninep.File.\nfunc (n *node) Stat() ninep.Stat {\n\tlength := int64(len(n.data))\n\tif n.perm.IsDir() {\n\t\tlength = 0 // 9P reports zero for a directory\n\t}\n\treturn ninep.Stat{\n\t\tQid:    n.qid,\n\t\tMode:   n.perm,\n\t\tMtime:  n.mtime,\n\t\tLength: length,\n\t\tName:   n.name,\n\t\tUid:    n.uid,\n\t\tGid:    n.gid,\n\t\tMuid:   n.muid,\n\t}\n}\n\n// Walk implements ninep.File.\nfunc (n *node) Walk(name string) (ninep.File, error) {\n\tif !n.perm.IsDir() {\n\t\treturn nil, ninep.ErrNotDir\n\t}\n\tif !ninep.ValidName(name) {\n\t\treturn nil, ninep.ErrBadName\n\t}\n\tv := n.children.Get(name) // avl.Get returns ONE value in gno\n\tif v == nil {\n\t\treturn nil, ninep.ErrNotExist\n\t}\n\treturn v.(*node), nil\n}\n\n// Read implements ninep.File.\nfunc (n *node) Read(off, count int64) (string, error) {\n\tif n.perm.IsDir() {\n\t\treturn \"\", ninep.ErrIsDir\n\t}\n\treturn ninep.Slice(n.data, off, count), nil\n}\n\n// ReadDir implements ninep.File.\nfunc (n *node) ReadDir() ([]ninep.Stat, error) {\n\tif !n.perm.IsDir() {\n\t\treturn nil, ninep.ErrNotDir\n\t}\n\tout := []ninep.Stat{}\n\tn.children.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tout = append(out, v.(*node).Stat())\n\t\treturn false\n\t})\n\treturn out, nil\n}\n\n// Create implements ninep.Mutable.\nfunc (n *node) Create(name string, perm ninep.Perm, now int64) (ninep.File, error) {\n\tif !n.perm.IsDir() {\n\t\treturn nil, ninep.ErrNotDir\n\t}\n\tif !ninep.ValidName(name) {\n\t\treturn nil, ninep.ErrBadName\n\t}\n\tif n.children.Has(name) {\n\t\treturn nil, ninep.ErrExist\n\t}\n\tchild := n.fs.newNode(name, perm, now)\n\tn.children.Set(name, child)\n\tn.touch(now)\n\treturn child, nil\n}\n\n// Remove implements ninep.Mutable. A non-empty directory is refused, as in\n// Plan 9.\nfunc (n *node) Remove(name string) error {\n\tif !n.perm.IsDir() {\n\t\treturn ninep.ErrNotDir\n\t}\n\tv := n.children.Get(name)\n\tif v == nil {\n\t\treturn ninep.ErrNotExist\n\t}\n\tchild := v.(*node)\n\tif child.perm.IsDir() \u0026\u0026 child.children.Size() \u003e 0 {\n\t\treturn ninep.ErrNotEmpty\n\t}\n\tn.children.Remove(name)\n\tn.touch(n.mtime)\n\treturn nil\n}\n\n// Write implements ninep.Mutable. Writing past the end extends the file with\n// NUL bytes, as a 9P server does.\nfunc (n *node) Write(off int64, data string, now int64) (int64, error) {\n\tif n.perm.IsDir() {\n\t\treturn 0, ninep.ErrIsDir\n\t}\n\tif off \u003c 0 {\n\t\toff = 0\n\t}\n\tif n.perm\u0026ninep.DMAPPEND != 0 {\n\t\toff = int64(len(n.data))\n\t}\n\tcur := n.data\n\tif off \u003e int64(len(cur)) {\n\t\tcur += strings.Repeat(\"\\x00\", int(off)-len(cur))\n\t}\n\tend := off + int64(len(data))\n\ttail := \"\"\n\tif end \u003c int64(len(cur)) {\n\t\ttail = cur[end:]\n\t}\n\tn.data = cur[:off] + data + tail\n\tn.touch(now)\n\treturn int64(len(data)), nil\n}\n\n// Truncate implements ninep.Mutable.\nfunc (n *node) Truncate(size int64, now int64) error {\n\tif n.perm.IsDir() {\n\t\treturn ninep.ErrIsDir\n\t}\n\tif size \u003c 0 {\n\t\tsize = 0\n\t}\n\tswitch {\n\tcase size \u003c int64(len(n.data)):\n\t\tn.data = n.data[:size]\n\tcase size \u003e int64(len(n.data)):\n\t\tn.data += strings.Repeat(\"\\x00\", int(size)-len(n.data))\n\t}\n\tn.touch(now)\n\treturn nil\n}\n\n// touch bumps the qid version and the mtime. A client that kept a qid can tell\n// the file changed without reading it, which is the whole point of Qid.Version.\nfunc (n *node) touch(now int64) {\n\tn.qid.Version++\n\tn.mtime = now\n\tn.muid = n.fs.uid\n}\n\n// MkdirAll creates p and every missing parent, and returns the leaf. An\n// existing directory is not an error; an existing plain file on the path is.\nfunc (fs *FS) MkdirAll(p string, now int64) (ninep.File, error) {\n\tcur := fs.root\n\tfor _, e := range ninep.Elems(p) {\n\t\tv := cur.children.Get(e)\n\t\tif v == nil {\n\t\t\tf, err := cur.Create(e, ninep.DirPerm, now)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcur = f.(*node)\n\t\t\tcontinue\n\t\t}\n\t\tcur = v.(*node)\n\t\tif !cur.perm.IsDir() {\n\t\t\treturn nil, ninep.ErrNotDir\n\t\t}\n\t}\n\treturn cur, nil\n}\n\n// WriteFile creates or replaces the file at p, creating parent directories as\n// needed. It is the seeding helper a realm wants at init.\nfunc (fs *FS) WriteFile(p, data string, now int64) error {\n\tdir, err := fs.MkdirAll(ninep.Dir(p), now)\n\tif err != nil {\n\t\treturn err\n\t}\n\tname := ninep.Base(p)\n\td := dir.(*node)\n\tv := d.children.Get(name)\n\tif v == nil {\n\t\tf, err := d.Create(name, ninep.FilePerm, now)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.(*node).Write(0, data, now)\n\t\treturn err\n\t}\n\ttarget := v.(*node)\n\tif err := target.Truncate(0, now); err != nil {\n\t\treturn err\n\t}\n\t_, err = target.Write(0, data, now)\n\treturn err\n}\n"},{"name":"memfs_test.gno","body":"package memfs\n\nimport (\n\t\"testing\"\n\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n)\n\nfunc TestRootStat(t *testing.T) {\n\tfs := New(\"glenda\", 100)\n\ts := fs.Root().Stat()\n\tif s.Name != \"/\" {\n\t\tt.Errorf(\"root name: got %q\", s.Name)\n\t}\n\tif !s.IsDir() {\n\t\tt.Error(\"root should be a directory\")\n\t}\n\tif s.Length != 0 {\n\t\tt.Errorf(\"a directory reports length 0 in 9P, got %d\", s.Length)\n\t}\n\tif s.Uid != \"glenda\" || s.Gid != \"glenda\" {\n\t\tt.Errorf(\"owner: got %q/%q\", s.Uid, s.Gid)\n\t}\n\tif s.Mtime != 100 {\n\t\tt.Errorf(\"mtime: got %d, want 100\", s.Mtime)\n\t}\n}\n\nfunc TestCreateWalkRead(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\n\tf, err := root.Create(\"greeting\", ninep.FilePerm, 2)\n\tif err != nil {\n\t\tt.Fatalf(\"create: %v\", err)\n\t}\n\tm := f.(ninep.Mutable)\n\tn, err := m.Write(0, \"hello world\", 3)\n\tif err != nil {\n\t\tt.Fatalf(\"write: %v\", err)\n\t}\n\tif n != 11 {\n\t\tt.Errorf(\"wrote %d bytes, want 11\", n)\n\t}\n\n\tgot, err := root.Walk(\"greeting\")\n\tif err != nil {\n\t\tt.Fatalf(\"walk: %v\", err)\n\t}\n\tdata, err := ninep.ReadAll(got)\n\tif err != nil {\n\t\tt.Fatalf(\"read: %v\", err)\n\t}\n\tif data != \"hello world\" {\n\t\tt.Errorf(\"read back %q\", data)\n\t}\n\tif l := got.Stat().Length; l != 11 {\n\t\tt.Errorf(\"length %d, want 11\", l)\n\t}\n}\n\nfunc TestWalkErrors(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\troot.Create(\"file\", ninep.FilePerm, 1)\n\n\tif _, err := root.Walk(\"absent\"); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"missing name: got %v, want ErrNotExist\", err)\n\t}\n\tif _, err := root.Walk(\"a/b\"); err != ninep.ErrBadName {\n\t\tt.Errorf(\"slash in name: got %v, want ErrBadName\", err)\n\t}\n\tf, _ := root.Walk(\"file\")\n\tif _, err := f.Walk(\"x\"); err != ninep.ErrNotDir {\n\t\tt.Errorf(\"walk through a file: got %v, want ErrNotDir\", err)\n\t}\n\tif _, err := f.ReadDir(); err != ninep.ErrNotDir {\n\t\tt.Errorf(\"readdir of a file: got %v, want ErrNotDir\", err)\n\t}\n\tif _, err := root.Read(0, -1); err != ninep.ErrIsDir {\n\t\tt.Errorf(\"read of a directory: got %v, want ErrIsDir\", err)\n\t}\n}\n\nfunc TestReadDirIsOrdered(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\tfor _, name := range []string{\"zulu\", \"alpha\", \"mike\", \"bravo\"} {\n\t\tif _, err := root.Create(name, ninep.FilePerm, 1); err != nil {\n\t\t\tt.Fatalf(\"create %s: %v\", name, err)\n\t\t}\n\t}\n\tents, err := root.ReadDir()\n\tif err != nil {\n\t\tt.Fatalf(\"readdir: %v\", err)\n\t}\n\twant := []string{\"alpha\", \"bravo\", \"mike\", \"zulu\"}\n\tif len(ents) != len(want) {\n\t\tt.Fatalf(\"got %d entries, want %d\", len(ents), len(want))\n\t}\n\tfor i, w := range want {\n\t\tif ents[i].Name != w {\n\t\t\tt.Errorf(\"entry %d: got %q, want %q\", i, ents[i].Name, w)\n\t\t}\n\t}\n}\n\nfunc TestCreateDuplicate(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\troot.Create(\"x\", ninep.FilePerm, 1)\n\tif _, err := root.Create(\"x\", ninep.FilePerm, 1); err != ninep.ErrExist {\n\t\tt.Errorf(\"got %v, want ErrExist\", err)\n\t}\n\tif _, err := root.Create(\"\", ninep.FilePerm, 1); err != ninep.ErrBadName {\n\t\tt.Errorf(\"empty name: got %v, want ErrBadName\", err)\n\t}\n\tif _, err := root.Create(\"..\", ninep.FilePerm, 1); err != ninep.ErrBadName {\n\t\tt.Errorf(\"dotdot: got %v, want ErrBadName\", err)\n\t}\n}\n\nfunc TestRemove(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\troot.Create(\"file\", ninep.FilePerm, 1)\n\td, _ := root.Create(\"dir\", ninep.DirPerm, 1)\n\td.(ninep.Mutable).Create(\"inner\", ninep.FilePerm, 1)\n\n\tif err := root.Remove(\"absent\"); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"remove missing: got %v\", err)\n\t}\n\tif err := root.Remove(\"dir\"); err != ninep.ErrNotEmpty {\n\t\tt.Errorf(\"remove non-empty dir: got %v, want ErrNotEmpty\", err)\n\t}\n\tif err := d.(ninep.Mutable).Remove(\"inner\"); err != nil {\n\t\tt.Fatalf(\"remove inner: %v\", err)\n\t}\n\tif err := root.Remove(\"dir\"); err != nil {\n\t\tt.Fatalf(\"remove emptied dir: %v\", err)\n\t}\n\tif err := root.Remove(\"file\"); err != nil {\n\t\tt.Fatalf(\"remove file: %v\", err)\n\t}\n\tents, _ := root.ReadDir()\n\tif len(ents) != 0 {\n\t\tt.Errorf(\"root should be empty, has %d entries\", len(ents))\n\t}\n}\n\nfunc TestWriteOffsets(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tstart string\n\t\toff   int64\n\t\tdata  string\n\t\twant  string\n\t}{\n\t\t{\"append at end\", \"abc\", 3, \"def\", \"abcdef\"},\n\t\t{\"overwrite middle\", \"abcdef\", 2, \"XY\", \"abXYef\"},\n\t\t{\"overwrite past end\", \"abc\", 2, \"XYZ\", \"abXYZ\"},\n\t\t{\"from zero\", \"abcdef\", 0, \"ZZ\", \"ZZcdef\"},\n\t\t{\"gap is nul filled\", \"ab\", 4, \"Z\", \"ab\\x00\\x00Z\"},\n\t\t{\"negative offset clamps\", \"abc\", -2, \"Z\", \"Zbc\"},\n\t}\n\tfor _, tt := range tests {\n\t\tfs := New(\"glenda\", 1)\n\t\troot := fs.RootMutable()\n\t\tf, _ := root.Create(\"f\", ninep.FilePerm, 1)\n\t\tm := f.(ninep.Mutable)\n\t\tm.Write(0, tt.start, 1)\n\t\tm.Write(tt.off, tt.data, 2)\n\t\tgot, _ := ninep.ReadAll(f)\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"%s: got %q, want %q\", tt.name, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestAppendOnlyIgnoresOffset(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\tf, _ := root.Create(\"log\", ninep.DMAPPEND|0644, 1)\n\tm := f.(ninep.Mutable)\n\tm.Write(0, \"one\\n\", 1)\n\tm.Write(0, \"two\\n\", 2) // offset 0, but append-only pins it to the end\n\tgot, _ := ninep.ReadAll(f)\n\tif got != \"one\\ntwo\\n\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n}\n\nfunc TestTruncate(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\tf, _ := root.Create(\"f\", ninep.FilePerm, 1)\n\tm := f.(ninep.Mutable)\n\tm.Write(0, \"abcdef\", 1)\n\n\tm.Truncate(3, 2)\n\tif got, _ := ninep.ReadAll(f); got != \"abc\" {\n\t\tt.Errorf(\"shrink: got %q\", got)\n\t}\n\tm.Truncate(5, 3)\n\tif got, _ := ninep.ReadAll(f); got != \"abc\\x00\\x00\" {\n\t\tt.Errorf(\"grow: got %q\", got)\n\t}\n\tm.Truncate(0, 4)\n\tif got, _ := ninep.ReadAll(f); got != \"\" {\n\t\tt.Errorf(\"zero: got %q\", got)\n\t}\n}\n\nfunc TestQidVersionAndPath(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\troot := fs.RootMutable()\n\ta, _ := root.Create(\"a\", ninep.FilePerm, 1)\n\tb, _ := root.Create(\"b\", ninep.FilePerm, 1)\n\n\tif a.Stat().Qid.Path == b.Stat().Qid.Path {\n\t\tt.Error(\"two files share a qid path\")\n\t}\n\tv0 := a.Stat().Qid.Version\n\ta.(ninep.Mutable).Write(0, \"x\", 2)\n\tif a.Stat().Qid.Version != v0+1 {\n\t\tt.Errorf(\"version did not advance on write: %d -\u003e %d\", v0, a.Stat().Qid.Version)\n\t}\n\tif a.Stat().Mtime != 2 {\n\t\tt.Errorf(\"mtime: got %d, want 2\", a.Stat().Mtime)\n\t}\n}\n\nfunc TestMkdirAllAndWriteFile(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\tif _, err := fs.MkdirAll(\"/usr/glenda/lib\", 1); err != nil {\n\t\tt.Fatalf(\"mkdirall: %v\", err)\n\t}\n\t// idempotent\n\tif _, err := fs.MkdirAll(\"/usr/glenda\", 1); err != nil {\n\t\tt.Fatalf(\"mkdirall again: %v\", err)\n\t}\n\tif err := fs.WriteFile(\"/usr/glenda/lib/profile\", \"font=pelm\\n\", 2); err != nil {\n\t\tt.Fatalf(\"writefile: %v\", err)\n\t}\n\tf, err := ninep.Walk(fs.Root(), ninep.Elems(\"/usr/glenda/lib/profile\"))\n\tif err != nil {\n\t\tt.Fatalf(\"walk: %v\", err)\n\t}\n\tif got, _ := ninep.ReadAll(f); got != \"font=pelm\\n\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n\t// rewriting replaces rather than appends\n\tif err := fs.WriteFile(\"/usr/glenda/lib/profile\", \"font=lucida\\n\", 3); err != nil {\n\t\tt.Fatalf(\"rewrite: %v\", err)\n\t}\n\tf, _ = ninep.Walk(fs.Root(), ninep.Elems(\"/usr/glenda/lib/profile\"))\n\tif got, _ := ninep.ReadAll(f); got != \"font=lucida\\n\" {\n\t\tt.Errorf(\"rewrite got %q\", got)\n\t}\n}\n\nfunc TestMkdirAllThroughAFileFails(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\tfs.WriteFile(\"/etc\", \"not a directory\", 1)\n\tif _, err := fs.MkdirAll(\"/etc/passwd\", 2); err != ninep.ErrNotDir {\n\t\tt.Errorf(\"got %v, want ErrNotDir\", err)\n\t}\n}\n\nfunc TestWalkDepthLimit(t *testing.T) {\n\tfs := New(\"glenda\", 1)\n\telems := []string{}\n\tfor i := 0; i \u003c= ninep.MaxDepth; i++ {\n\t\telems = append(elems, \"x\")\n\t}\n\tif _, err := ninep.Walk(fs.Root(), elems); err != ninep.ErrTooDeep {\n\t\tt.Errorf(\"got %v, want ErrTooDeep\", err)\n\t}\n}\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ns","path":"gno.land/p/moul/x/plan9/ns/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/plan9/ns/v0`\n\n**A Plan 9 namespace**: a private, mutable mount table over\n[`ninep`](../../ninep/v0) file trees, with `bind(2)`'s flags and union\ndirectories.\n\n```go\nimport ns \"gno.land/p/moul/x/plan9/ns/v0\"\n\nn := ns.New(fs.Root())\nn.Bind(\"/usr/glenda/bin\", \"/bin\", ns.MAFTER|ns.MCREATE)\nn.ReadDir(\"/bin\", false)   // the concatenation of both directories\n```\n\nThis is the idea the rest of the suite exists for. Plan 9's leverage does not\ncome from \"everything is a file\", it comes from every process owning its own\nname-to-resource mapping, so a name can be *replaced* and any service can be\ncomposed, shadowed, sandboxed or mocked without the program knowing. Gno has one\nglobal tree of realm paths that looks the same to everybody; an `Ns` is a view\nof it that belongs to you.\n\n**Flags follow [`bind(2)`](http://man.cat-v.org/plan_9/2/bind):** `MREPL`\nreplaces, `MBEFORE` splices the new directory in front of the old one, `MAFTER`\nbehind it, and `MCREATE` (OR'd onto any of them) marks the union member that new\nfiles are created in.\n\nFour Plan 9 properties are load-bearing and reproduced deliberately:\n\n- **A union is top level only.** Binding `/a` onto `/b` unions the two\n  directories at `/b`; `/b/c` resolves in whichever member won the walk and is\n  not itself a union unless something is bound there too.\n- **A bind captures a channel, not a name.** The source is resolved once, at\n  bind time, and the file it named is what gets stored. Rebinding the source\n  afterwards does not retroactively move the target.\n- **A listing is a concatenation**, duplicates and all, so shadowing stays\n  visible. Pass `unique` to collapse it first-wins instead.\n- **Creating in a union needs `MCREATE` on some member**, and is refused\n  otherwise. A plain, unbound directory takes creates with no flag at all.\n- **The target of a bind must already exist**, exactly as `bind(1)` requires.\n\n`MaxUnion` (8), `MaxOps` (64) and `ninep.MaxDepth` (32) bound resolution,\nbecause each element of each member can cost a cross-realm call.\n\n`String()` prints the namespace in `ns(1)` format: one line per binding, in\napplication order, then the working directory.\n\n**Live demo:** [`r/moul/x/plan9/ns`](../../../../../r/moul/x/plan9/ns/v0) gives\nevery account one of these. Design and analysis:\n[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\n\n---\n\n**Not affiliated with Plan 9.** Plan 9 from Bell Labs is the work of the\nComputing Science Research Center at Bell Labs; the name and the marks are\ntheirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org).\nThis package borrows the vocabulary and none of the code: it is an independent\nhomage, asking what that ecosystem's spirit looks like on a chain. Full\nattribution: [NOTICE](../../../../../NOTICE.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/plan9/ns/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/plan9/ns/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/plan9/ns/v0\"\ngno = \"0.9\"\n"},{"name":"ns.gno","body":"// Package ns is a Plan 9 namespace: a private, mutable mount table over\n// gno.land/p/moul/x/plan9/ninep file trees.\n//\n// This is the idea the rest of the suite exists for. Plan 9's leverage does\n// not come from \"everything is a file\", it comes from every process owning its\n// own name-to-resource mapping, so a name can be REPLACED and any service can\n// be composed, shadowed, sandboxed or mocked without the program knowing. Gno\n// has one global tree and no way to hold a view of it; an Ns is that view.\n//\n// Bind flags follow bind(2): MREPL replaces, MBEFORE splices the new directory\n// in front of the old one, MAFTER behind it, and MCREATE (OR'd onto any of\n// them) marks the union member that new files are created in.\n//\n// Two Plan 9 properties are load-bearing and reproduced deliberately:\n//\n//   - A union is TOP LEVEL ONLY. Binding /a onto /b unions the two directories\n//     at /b; /b/c resolves in whichever member won the walk, and is not itself\n//     a union unless something is bound there too.\n//   - A bind captures a CHANNEL, not a name. The source is resolved once, at\n//     bind time, and the resulting file is what is stored. Rebinding the\n//     source afterwards does not retroactively move the target.\n//\n// \"..\" is removed lexically before resolution starts and never reaches a\n// server, per \"Lexical File Names in Plan 9, or Getting Dot-Dot Right\".\n//\n// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research\n// Center at Bell Labs; the name and the marks are theirs, and the copyright is\n// held by the Plan 9 Foundation (https://p9f.org). This package is not\n// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9\n// code: it borrows the vocabulary so that the design reads without a glossary,\n// and it is an homage, asking what that ecosystem's spirit looks like on a\n// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.\npackage ns\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n)\n\n// Flag is a bind(2) mount flag. The low two bits pick the mode; MCREATE is\n// OR'd onto it.\ntype Flag uint32\n\n// Mount flags, with Plan 9's values.\nconst (\n\tMREPL   Flag = 0x0000 // replace the old file with the new one\n\tMBEFORE Flag = 0x0001 // union, new directory first\n\tMAFTER  Flag = 0x0002 // union, new directory last\n\tMCREATE Flag = 0x0004 // creates in this union go here\n)\n\nfunc (f Flag) mode() Flag    { return f \u0026 0x0003 }\nfunc (f Flag) creates() bool { return f\u0026MCREATE != 0 }\n\n// String renders the flag as the command-line letters bind(1) uses.\nfunc (f Flag) String() string {\n\ts := \"\"\n\tswitch f.mode() {\n\tcase MBEFORE:\n\t\ts = \"-b\"\n\tcase MAFTER:\n\t\ts = \"-a\"\n\t}\n\tif f.creates() {\n\t\tif s == \"\" {\n\t\t\ts = \"-c\"\n\t\t} else {\n\t\t\ts += \"c\"\n\t\t}\n\t}\n\treturn s\n}\n\n// Limits. Resolution costs one call per element per union member, and those\n// calls may cross a realm boundary, so both are capped rather than trusted.\nconst (\n\tMaxUnion = 8 // members in one union\n\tMaxOps   = 64\n)\n\nvar (\n\t// ErrNoRoot means the namespace has nothing bound at \"/\".\n\tErrNoRoot = errors.New(\"no root in namespace\")\n\t// ErrWideUnion means a bind would exceed MaxUnion members.\n\tErrWideUnion = errors.New(\"union too wide\")\n\t// ErrTooManyOps means the namespace has reached MaxOps bindings.\n\tErrTooManyOps = errors.New(\"too many namespace operations\")\n\t// ErrNotBound means unmount was asked to remove something that is not\n\t// bound at that name.\n\tErrNotBound = errors.New(\"not bound\")\n)\n\n// member is one element of a union. A nil file is the placeholder standing for\n// \"whatever walking to this name would have found\", which is how MBEFORE and\n// MAFTER keep the original directory in the union.\ntype member struct {\n\tfile   ninep.File\n\tcreate bool\n}\n\ntype entry struct {\n\tmembers []member\n}\n\n// Op records one bind or mount, in application order, so that String can print\n// the namespace the way Plan 9's ns(1) does.\ntype Op struct {\n\tVerb   string // \"bind\" or \"mount\"\n\tFlag   Flag\n\tSource string\n\tTarget string\n}\n\n// Ns is one namespace: a mount table, a working directory, and the ordered\n// list of operations that produced them.\ntype Ns struct {\n\ttable *avl.Tree // cleaned target path -\u003e *entry\n\tops   []Op\n\tcwd   string\n}\n\n// New returns a namespace whose root is the given file. The root is the one\n// binding that cannot be expressed as a bind of something else, so it is\n// installed directly.\nfunc New(root ninep.File) *Ns {\n\tn := \u0026Ns{table: avl.NewTree(), cwd: \"/\"}\n\tn.table.Set(\"/\", \u0026entry{members: []member{{file: root, create: true}}})\n\treturn n\n}\n\n// Cwd returns the working directory.\nfunc (n *Ns) Cwd() string { return n.cwd }\n\n// Cd sets the working directory, which must resolve to a directory.\nfunc (n *Ns) Cd(p string) error {\n\tabs := n.Abs(p)\n\tst, err := n.Stat(abs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !st.IsDir() {\n\t\treturn ninep.ErrNotDir\n\t}\n\tn.cwd = abs\n\treturn nil\n}\n\n// Abs resolves p against the working directory.\nfunc (n *Ns) Abs(p string) string { return ninep.Abs(n.cwd, p) }\n\nfunc (n *Ns) entry(p string) *entry {\n\tv := n.table.Get(p)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*entry)\n}\n\n// expand substitutes the walk result for the placeholder member.\nfunc expand(ms []member, under []member) []member {\n\tout := []member{}\n\tfor _, m := range ms {\n\t\tif m.file == nil {\n\t\t\tout = append(out, under...)\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, m)\n\t}\n\treturn out\n}\n\n// resolve walks p and returns the union found there, richest form: members\n// still carry their create bit, and bound reports whether a mount entry\n// applied at the final element.\nfunc (n *Ns) resolve(p string) ([]member, error) {\n\troot := n.entry(\"/\")\n\tif root == nil {\n\t\treturn nil, ErrNoRoot\n\t}\n\tcur := expand(root.members, nil)\n\tif len(cur) == 0 {\n\t\treturn nil, ErrNoRoot\n\t}\n\telems := ninep.Elems(ninep.Clean(p))\n\tif len(elems) \u003e ninep.MaxDepth {\n\t\treturn nil, ninep.ErrTooDeep\n\t}\n\tprefix := \"\"\n\tfor _, e := range elems {\n\t\t// First match wins. Walking INTO a union does not produce a union\n\t\t// of the members' subdirectories: in Plan 9 a union is top level\n\t\t// only, and a walk returns one channel.\n\t\twalked := []member{}\n\t\tfor _, m := range cur {\n\t\t\tf, err := m.file.Walk(e)\n\t\t\tif err == nil {\n\t\t\t\twalked = append(walked, member{file: f})\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tprefix += \"/\" + e\n\t\tnext := walked\n\t\tif ent := n.entry(prefix); ent != nil {\n\t\t\tnext = expand(ent.members, walked)\n\t\t}\n\t\tif len(next) == 0 {\n\t\t\treturn nil, ninep.ErrNotExist\n\t\t}\n\t\tcur = next\n\t}\n\treturn cur, nil\n}\n\n// Resolve returns every union member visible at p, in search order.\nfunc (n *Ns) Resolve(p string) ([]ninep.File, error) {\n\tms, err := n.resolve(n.Abs(p))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := []ninep.File{}\n\tfor _, m := range ms {\n\t\tout = append(out, m.file)\n\t}\n\treturn out, nil\n}\n\n// Open returns the file a name resolves to: the first member of its union,\n// which is the one a walk through this name would reach.\nfunc (n *Ns) Open(p string) (ninep.File, error) {\n\tfs, err := n.Resolve(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn fs[0], nil\n}\n\n// Stat returns the entry for p, with the name replaced by the last element of\n// the path as asked for, so that a union member's own name never leaks.\nfunc (n *Ns) Stat(p string) (ninep.Stat, error) {\n\tf, err := n.Open(p)\n\tif err != nil {\n\t\treturn ninep.Stat{}, err\n\t}\n\tst := f.Stat()\n\tst.Name = ninep.Base(n.Abs(p))\n\treturn st, nil\n}\n\n// ReadFile reads the whole file at p.\nfunc (n *Ns) ReadFile(p string) (string, error) {\n\tf, err := n.Open(p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ninep.ReadAll(f)\n}\n\n// ReadDir lists p. A union directory is the CONCATENATION of its members'\n// contents, as in Plan 9, so duplicate names can appear and shadowing is\n// visible. Pass unique to collapse them first-wins instead, which is the set\n// of names a walk can actually reach.\nfunc (n *Ns) ReadDir(p string, unique bool) ([]ninep.Stat, error) {\n\tms, err := n.resolve(n.Abs(p))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(ms) == 1 \u0026\u0026 !ms[0].file.Stat().IsDir() {\n\t\treturn nil, ninep.ErrNotDir\n\t}\n\tout := []ninep.Stat{}\n\tseen := map[string]bool{}\n\tfor _, m := range ms {\n\t\tents, err := m.file.ReadDir()\n\t\tif err != nil {\n\t\t\tcontinue // a non-directory member contributes nothing\n\t\t}\n\t\tfor _, e := range ents {\n\t\t\tif unique {\n\t\t\t\tif seen[e.Name] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tseen[e.Name] = true\n\t\t\t}\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out, nil\n}\n\n// CreateTarget returns the directory that a create at p should happen in.\n//\n// For a plain directory that is just the directory. For a union it is the\n// first member carrying MCREATE, and if no member has it, creation is refused,\n// which is bind(2)'s rule.\nfunc (n *Ns) CreateTarget(p string) (ninep.Mutable, error) {\n\tabs := n.Abs(p)\n\tms, err := n.resolve(abs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tisUnion := n.entry(abs) != nil \u0026\u0026 len(ms) \u003e 1\n\tfor _, m := range ms {\n\t\tif isUnion \u0026\u0026 !m.create {\n\t\t\tcontinue\n\t\t}\n\t\tmu, ok := m.file.(ninep.Mutable)\n\t\tif !ok {\n\t\t\tcontinue // a read-only server, for instance a mounted realm\n\t\t}\n\t\tif !mu.Stat().IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\treturn mu, nil\n\t}\n\tif isUnion {\n\t\treturn nil, ninep.ErrNoCreate\n\t}\n\treturn nil, ninep.ErrPerm\n}\n\n// Bind makes source visible at target, as bind(1) does. Both names are\n// resolved in THIS namespace, and the source is resolved once: what is stored\n// is the file it names today, not the name.\nfunc (n *Ns) Bind(source, target string, flag Flag) error {\n\treturn n.BindVerb(\"bind\", source, target, flag)\n}\n\n// BindVerb is Bind with the verb that String should print. Plan 9 spells the\n// same operation \"bind\" or \"mount\" depending on whether the source is a name\n// or a channel, and ns(1) echoes back whichever was used.\nfunc (n *Ns) BindVerb(verb, source, target string, flag Flag) error {\n\tms, err := n.resolve(n.Abs(source))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfiles := []ninep.File{}\n\tfor _, m := range ms {\n\t\tfiles = append(files, m.file)\n\t}\n\treturn n.graft(verb, source, target, flag, files)\n}\n\n// Mount grafts a file tree that has no name in this namespace yet, which is\n// how a service posted by another realm gets in. source is a label, used only\n// when printing the namespace.\nfunc (n *Ns) Mount(f ninep.File, source, target string, flag Flag) error {\n\treturn n.graft(\"mount\", source, target, flag, []ninep.File{f})\n}\n\nfunc (n *Ns) graft(verb, source, target string, flag Flag, files []ninep.File) error {\n\tif len(n.ops) \u003e= MaxOps {\n\t\treturn ErrTooManyOps\n\t}\n\tabs := n.Abs(target)\n\t// bind(1) requires the target to exist: you can only rebind a name that\n\t// already resolves to something.\n\tif _, err := n.resolve(abs); err != nil {\n\t\treturn err\n\t}\n\tadd := []member{}\n\tfor _, f := range files {\n\t\tadd = append(add, member{file: f, create: flag.creates()})\n\t}\n\n\tent := n.entry(abs)\n\tvar members []member\n\tswitch {\n\tcase ent == nil:\n\t\t// The name has never been bound: its current contents are the\n\t\t// placeholder. It does NOT carry MCREATE, which is why creating\n\t\t// in a freshly unioned directory is refused until some member is\n\t\t// bound with -c.\n\t\tmembers = []member{{file: nil}}\n\tdefault:\n\t\tmembers = ent.members\n\t}\n\tswitch flag.mode() {\n\tcase MBEFORE:\n\t\tmembers = append(add, members...)\n\tcase MAFTER:\n\t\tmembers = append(members, add...)\n\tdefault: // MREPL: the old file is gone, not unioned\n\t\tmembers = add\n\t}\n\tif len(members) \u003e MaxUnion {\n\t\treturn ErrWideUnion\n\t}\n\tn.table.Set(abs, \u0026entry{members: members})\n\tn.ops = append(n.ops, Op{Verb: verb, Flag: flag, Source: source, Target: abs})\n\treturn nil\n}\n\n// Unmount undoes bindings at target. With an empty source it removes every\n// binding there, restoring the name to whatever it resolved to originally.\nfunc (n *Ns) Unmount(source, target string) error {\n\tabs := n.Abs(target)\n\tent := n.entry(abs)\n\tif ent == nil {\n\t\treturn ErrNotBound\n\t}\n\tif source == \"\" {\n\t\tn.table.Remove(abs)\n\t\tn.dropOps(abs, \"\")\n\t\treturn nil\n\t}\n\tms, err := n.resolve(n.Abs(source))\n\tif err != nil {\n\t\treturn err\n\t}\n\tkept := []member{}\n\tremoved := false\n\tfor _, m := range ent.members {\n\t\tdrop := false\n\t\tfor _, s := range ms {\n\t\t\tif m.file != nil \u0026\u0026 m.file == s.file {\n\t\t\t\tdrop = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif drop {\n\t\t\tremoved = true\n\t\t\tcontinue\n\t\t}\n\t\tkept = append(kept, m)\n\t}\n\tif !removed {\n\t\treturn ErrNotBound\n\t}\n\tif onlyPlaceholders(kept) {\n\t\t// Nothing but \"whatever was here originally\" is left, so the entry\n\t\t// is a no-op: drop it rather than leave a phantom binding behind.\n\t\tn.table.Remove(abs)\n\t} else {\n\t\tn.table.Set(abs, \u0026entry{members: kept})\n\t}\n\tn.dropOps(abs, source)\n\treturn nil\n}\n\nfunc onlyPlaceholders(ms []member) bool {\n\tfor _, m := range ms {\n\t\tif m.file != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (n *Ns) dropOps(target, source string) {\n\tkept := []Op{}\n\tfor _, op := range n.ops {\n\t\tif op.Target == target \u0026\u0026 (source == \"\" || op.Source == source) {\n\t\t\tcontinue\n\t\t}\n\t\tkept = append(kept, op)\n\t}\n\tn.ops = kept\n}\n\n// Ops returns the bindings in application order.\nfunc (n *Ns) Ops() []Op { return n.ops }\n\n// String prints the namespace the way Plan 9's ns(1) does: one line per\n// binding, in the order they were applied, then the working directory.\nfunc (n *Ns) String() string {\n\tvar b strings.Builder\n\tfor _, op := range n.ops {\n\t\tb.WriteString(op.Verb)\n\t\tif f := op.Flag.String(); f != \"\" {\n\t\t\tb.WriteString(\" \" + f)\n\t\t}\n\t\tb.WriteString(\" \" + quote(op.Source) + \" \" + quote(op.Target) + \"\\n\")\n\t}\n\tb.WriteString(\"cd \" + quote(n.cwd) + \"\\n\")\n\treturn b.String()\n}\n\n// quote applies rc quoting: single quotes when the word contains a space or a\n// quote, with an embedded quote doubled.\nfunc quote(s string) string {\n\tif s != \"\" \u0026\u0026 !strings.ContainsAny(s, \" \\t'\") {\n\t\treturn s\n\t}\n\treturn \"'\" + strings.ReplaceAll(s, \"'\", \"''\") + \"'\"\n}\n"},{"name":"ns_test.gno","body":"package ns\n\nimport (\n\t\"testing\"\n\n\tmemfs \"gno.land/p/moul/x/plan9/memfs/v0\"\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n)\n\n// newNs builds a namespace over a fresh ram tree seeded with files.\nfunc newNs(t *testing.T, files ...string) (*Ns, *memfs.FS) {\n\tt.Helper()\n\tfs := memfs.New(\"glenda\", 1)\n\tfor _, f := range files {\n\t\tif err := fs.WriteFile(f, \"contents of \"+f+\"\\n\", 1); err != nil {\n\t\t\tt.Fatalf(\"seed %s: %v\", f, err)\n\t\t}\n\t}\n\treturn New(fs.Root()), fs\n}\n\nfunc names(ents []ninep.Stat) []string {\n\tout := []string{}\n\tfor _, e := range ents {\n\t\tout = append(out, e.Name)\n\t}\n\treturn out\n}\n\nfunc eq(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc TestResolveRoot(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\", \"/bin/cat\")\n\tst, err := n.Stat(\"/\")\n\tif err != nil {\n\t\tt.Fatalf(\"stat root: %v\", err)\n\t}\n\tif !st.IsDir() {\n\t\tt.Error(\"root is not a directory\")\n\t}\n\tents, err := n.ReadDir(\"/\", false)\n\tif err != nil {\n\t\tt.Fatalf(\"readdir: %v\", err)\n\t}\n\tif !eq(names(ents), []string{\"bin\"}) {\n\t\tt.Errorf(\"root listing: %v\", names(ents))\n\t}\n}\n\nfunc TestReadFileAndMissing(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\")\n\tgot, err := n.ReadFile(\"/bin/ls\")\n\tif err != nil {\n\t\tt.Fatalf(\"readfile: %v\", err)\n\t}\n\tif got != \"contents of /bin/ls\\n\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n\tif _, err := n.ReadFile(\"/bin/absent\"); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"missing: got %v, want ErrNotExist\", err)\n\t}\n}\n\nfunc TestDotDotIsLexical(t *testing.T) {\n\tn, _ := newNs(t, \"/a/b/c\")\n\t// /a/b/../b/c never asks a server about \"..\".\n\tif _, err := n.Stat(\"/a/b/../b/c\"); err != nil {\n\t\tt.Fatalf(\"lexical dotdot: %v\", err)\n\t}\n\t// Above the root stays at the root.\n\tif _, err := n.Stat(\"/../../a\"); err != nil {\n\t\tt.Fatalf(\"dotdot above root: %v\", err)\n\t}\n}\n\nfunc TestBindReplace(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\", \"/usr/glenda/bin/rc\")\n\tif err := n.Bind(\"/usr/glenda/bin\", \"/bin\", MREPL); err != nil {\n\t\tt.Fatalf(\"bind: %v\", err)\n\t}\n\tents, _ := n.ReadDir(\"/bin\", false)\n\tif !eq(names(ents), []string{\"rc\"}) {\n\t\tt.Errorf(\"after MREPL /bin should hold only rc, got %v\", names(ents))\n\t}\n\tif _, err := n.Stat(\"/bin/ls\"); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"replaced file still reachable: %v\", err)\n\t}\n}\n\nfunc TestBindAfterUnion(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\", \"/usr/glenda/bin/rc\")\n\tif err := n.Bind(\"/usr/glenda/bin\", \"/bin\", MAFTER); err != nil {\n\t\tt.Fatalf(\"bind -a: %v\", err)\n\t}\n\tents, _ := n.ReadDir(\"/bin\", false)\n\tif !eq(names(ents), []string{\"ls\", \"rc\"}) {\n\t\tt.Errorf(\"union order: got %v, want [ls rc]\", names(ents))\n\t}\n\tif _, err := n.Stat(\"/bin/rc\"); err != nil {\n\t\tt.Errorf(\"unioned file not reachable: %v\", err)\n\t}\n\tif _, err := n.Stat(\"/bin/ls\"); err != nil {\n\t\tt.Errorf(\"original file lost: %v\", err)\n\t}\n}\n\nfunc TestBindBeforeUnion(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\", \"/usr/glenda/bin/rc\")\n\tif err := n.Bind(\"/usr/glenda/bin\", \"/bin\", MBEFORE); err != nil {\n\t\tt.Fatalf(\"bind -b: %v\", err)\n\t}\n\tents, _ := n.ReadDir(\"/bin\", false)\n\tif !eq(names(ents), []string{\"rc\", \"ls\"}) {\n\t\tt.Errorf(\"union order: got %v, want [rc ls]\", names(ents))\n\t}\n}\n\nfunc TestUnionShadowingIsVisible(t *testing.T) {\n\t// Both directories hold a file called \"ls\". Plan 9 concatenates, so the\n\t// listing shows the duplicate and makes the shadowing visible.\n\tfs := memfs.New(\"glenda\", 1)\n\tfs.WriteFile(\"/bin/ls\", \"system ls\\n\", 1)\n\tfs.WriteFile(\"/usr/glenda/bin/ls\", \"my ls\\n\", 1)\n\tn := New(fs.Root())\n\n\tif err := n.Bind(\"/usr/glenda/bin\", \"/bin\", MBEFORE); err != nil {\n\t\tt.Fatalf(\"bind: %v\", err)\n\t}\n\tents, _ := n.ReadDir(\"/bin\", false)\n\tif !eq(names(ents), []string{\"ls\", \"ls\"}) {\n\t\tt.Errorf(\"concatenation should show both: got %v\", names(ents))\n\t}\n\tuniq, _ := n.ReadDir(\"/bin\", true)\n\tif !eq(names(uniq), []string{\"ls\"}) {\n\t\tt.Errorf(\"unique listing: got %v\", names(uniq))\n\t}\n\t// A walk reaches the first member, which is the one bound before.\n\tgot, err := n.ReadFile(\"/bin/ls\")\n\tif err != nil {\n\t\tt.Fatalf(\"read: %v\", err)\n\t}\n\tif got != \"my ls\\n\" {\n\t\tt.Errorf(\"shadowing: got %q, want my ls\", got)\n\t}\n}\n\nfunc TestUnionIsTopLevelOnly(t *testing.T) {\n\t// /a and /b each hold a directory \"sub\", but only /a/sub/x exists.\n\t// Unioning /b onto /a does NOT union /a/sub with /b/sub.\n\tfs := memfs.New(\"glenda\", 1)\n\tfs.WriteFile(\"/a/sub/x\", \"x\\n\", 1)\n\tfs.WriteFile(\"/b/sub/y\", \"y\\n\", 1)\n\tn := New(fs.Root())\n\tif err := n.Bind(\"/b\", \"/a\", MAFTER); err != nil {\n\t\tt.Fatalf(\"bind: %v\", err)\n\t}\n\tif _, err := n.Stat(\"/a/sub/x\"); err != nil {\n\t\tt.Errorf(\"/a/sub/x should still resolve: %v\", err)\n\t}\n\tif _, err := n.Stat(\"/a/sub/y\"); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"unions are top level only, /a/sub/y must not resolve: %v\", err)\n\t}\n}\n\nfunc TestBindCapturesAChannelNotAName(t *testing.T) {\n\tfs := memfs.New(\"glenda\", 1)\n\tfs.WriteFile(\"/one/f\", \"one\\n\", 1)\n\tfs.WriteFile(\"/two/f\", \"two\\n\", 1)\n\tn := New(fs.Root())\n\n\tif err := n.Bind(\"/one\", \"/mnt\", MREPL); err != nil {\n\t\t// /mnt does not exist yet, so this must fail: see the next test.\n\t\tfs.MkdirAll(\"/mnt\", 1)\n\t\tif err := n.Bind(\"/one\", \"/mnt\", MREPL); err != nil {\n\t\t\tt.Fatalf(\"bind: %v\", err)\n\t\t}\n\t}\n\t// Now rebind the SOURCE name elsewhere. The earlier bind captured the\n\t// directory, so /mnt must not follow.\n\tif err := n.Bind(\"/two\", \"/one\", MREPL); err != nil {\n\t\tt.Fatalf(\"rebind source: %v\", err)\n\t}\n\tgot, _ := n.ReadFile(\"/mnt/f\")\n\tif got != \"one\\n\" {\n\t\tt.Errorf(\"bind should have captured the channel: /mnt/f is %q\", got)\n\t}\n\tgot, _ = n.ReadFile(\"/one/f\")\n\tif got != \"two\\n\" {\n\t\tt.Errorf(\"/one/f is %q, want two\", got)\n\t}\n}\n\nfunc TestBindTargetMustExist(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\")\n\tif err := n.Bind(\"/bin\", \"/nowhere\", MREPL); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"bind onto a missing name: got %v, want ErrNotExist\", err)\n\t}\n\tif err := n.Bind(\"/nowhere\", \"/bin\", MREPL); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"bind from a missing name: got %v, want ErrNotExist\", err)\n\t}\n}\n\nfunc TestCreateTargetNeedsMCREATE(t *testing.T) {\n\tfs := memfs.New(\"glenda\", 1)\n\tfs.MkdirAll(\"/bin\", 1)\n\tfs.MkdirAll(\"/usr/glenda/bin\", 1)\n\tn := New(fs.Root())\n\n\t// A plain directory takes creates with no flag at all.\n\tif _, err := n.CreateTarget(\"/bin\"); err != nil {\n\t\tt.Fatalf(\"plain directory should accept a create: %v\", err)\n\t}\n\n\t// Made into a union with no MCREATE anywhere, creation is refused.\n\tif err := n.Bind(\"/usr/glenda/bin\", \"/bin\", MAFTER); err != nil {\n\t\tt.Fatalf(\"bind: %v\", err)\n\t}\n\tif _, err := n.CreateTarget(\"/bin\"); err != ninep.ErrNoCreate {\n\t\tt.Errorf(\"union without MCREATE: got %v, want ErrNoCreate\", err)\n\t}\n\n\t// Rebinding with MCREATE picks that member.\n\tif err := n.Bind(\"/usr/glenda/bin\", \"/bin\", MAFTER|MCREATE); err != nil {\n\t\tt.Fatalf(\"bind -ac: %v\", err)\n\t}\n\ttarget, err := n.CreateTarget(\"/bin\")\n\tif err != nil {\n\t\tt.Fatalf(\"union with MCREATE: %v\", err)\n\t}\n\tif _, err := target.Create(\"new\", ninep.FilePerm, 2); err != nil {\n\t\tt.Fatalf(\"create: %v\", err)\n\t}\n\t// It landed in the MCREATE member, not in /bin's own directory.\n\tif _, err := ninep.Walk(fs.Root(), ninep.Elems(\"/usr/glenda/bin/new\")); err != nil {\n\t\tt.Errorf(\"create went to the wrong member: %v\", err)\n\t}\n}\n\nfunc TestUnmount(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\", \"/usr/glenda/bin/rc\")\n\tn.Bind(\"/usr/glenda/bin\", \"/bin\", MAFTER)\n\tents, _ := n.ReadDir(\"/bin\", false)\n\tif len(ents) != 2 {\n\t\tt.Fatalf(\"setup: %v\", names(ents))\n\t}\n\n\tif err := n.Unmount(\"/usr/glenda/bin\", \"/bin\"); err != nil {\n\t\tt.Fatalf(\"unmount: %v\", err)\n\t}\n\tents, _ = n.ReadDir(\"/bin\", false)\n\tif !eq(names(ents), []string{\"ls\"}) {\n\t\tt.Errorf(\"after unmount: %v\", names(ents))\n\t}\n\tif err := n.Unmount(\"\", \"/bin\"); err != ErrNotBound {\n\t\tt.Errorf(\"unmount of an unbound name: got %v, want ErrNotBound\", err)\n\t}\n}\n\nfunc TestUnmountAll(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\", \"/usr/glenda/bin/rc\")\n\tn.Bind(\"/usr/glenda/bin\", \"/bin\", MAFTER)\n\tif err := n.Unmount(\"\", \"/bin\"); err != nil {\n\t\tt.Fatalf(\"unmount all: %v\", err)\n\t}\n\tents, _ := n.ReadDir(\"/bin\", false)\n\tif !eq(names(ents), []string{\"ls\"}) {\n\t\tt.Errorf(\"name should be restored to its original contents: %v\", names(ents))\n\t}\n\tif len(n.Ops()) != 0 {\n\t\tt.Errorf(\"ops should be gone: %v\", n.Ops())\n\t}\n}\n\nfunc TestCd(t *testing.T) {\n\tn, _ := newNs(t, \"/usr/glenda/lib/profile\")\n\tif err := n.Cd(\"/usr/glenda\"); err != nil {\n\t\tt.Fatalf(\"cd: %v\", err)\n\t}\n\tif n.Cwd() != \"/usr/glenda\" {\n\t\tt.Errorf(\"cwd: %q\", n.Cwd())\n\t}\n\tgot, err := n.ReadFile(\"lib/profile\")\n\tif err != nil {\n\t\tt.Fatalf(\"relative read: %v\", err)\n\t}\n\tif got == \"\" {\n\t\tt.Error(\"relative read came back empty\")\n\t}\n\tif err := n.Cd(\"lib/profile\"); err != ninep.ErrNotDir {\n\t\tt.Errorf(\"cd into a file: got %v, want ErrNotDir\", err)\n\t}\n\tif err := n.Cd(\"/nowhere\"); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"cd nowhere: got %v\", err)\n\t}\n}\n\nfunc TestStringMatchesNsFormat(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\", \"/usr/glenda/bin/rc\", \"/tmp/x\")\n\tn.Bind(\"/usr/glenda/bin\", \"/bin\", MAFTER|MCREATE)\n\tn.Bind(\"/tmp\", \"/usr/glenda\", MBEFORE)\n\tn.Cd(\"/usr/glenda\")\n\n\twant := \"bind -ac /usr/glenda/bin /bin\\n\" +\n\t\t\"bind -b /tmp /usr/glenda\\n\" +\n\t\t\"cd /usr/glenda\\n\"\n\tif got := n.String(); got != want {\n\t\tt.Errorf(\"ns output:\\ngot:\\n%s\\nwant:\\n%s\", got, want)\n\t}\n}\n\nfunc TestFlagString(t *testing.T) {\n\ttests := []struct {\n\t\tflag Flag\n\t\twant string\n\t}{\n\t\t{MREPL, \"\"},\n\t\t{MBEFORE, \"-b\"},\n\t\t{MAFTER, \"-a\"},\n\t\t{MCREATE, \"-c\"},\n\t\t{MAFTER | MCREATE, \"-ac\"},\n\t\t{MBEFORE | MCREATE, \"-bc\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := tt.flag.String(); got != tt.want {\n\t\t\tt.Errorf(\"Flag(%d): got %q, want %q\", uint32(tt.flag), got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestUnionWidthIsBounded(t *testing.T) {\n\tfs := memfs.New(\"glenda\", 1)\n\tfs.MkdirAll(\"/bin\", 1)\n\tfor i := 0; i \u003c MaxUnion+2; i++ {\n\t\tfs.MkdirAll(\"/d\"+string(rune('a'+i)), 1)\n\t}\n\tn := New(fs.Root())\n\tvar err error\n\tfor i := 0; i \u003c MaxUnion+2; i++ {\n\t\terr = n.Bind(\"/d\"+string(rune('a'+i)), \"/bin\", MAFTER)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != ErrWideUnion {\n\t\tt.Errorf(\"got %v, want ErrWideUnion\", err)\n\t}\n}\n\nfunc TestReadDirOnAFile(t *testing.T) {\n\tn, _ := newNs(t, \"/bin/ls\")\n\tif _, err := n.ReadDir(\"/bin/ls\", false); err != ninep.ErrNotDir {\n\t\tt.Errorf(\"got %v, want ErrNotDir\", err)\n\t}\n}\n\nfunc TestDepthIsBounded(t *testing.T) {\n\tn, _ := newNs(t, \"/a\")\n\tp := \"\"\n\tfor i := 0; i \u003c= ninep.MaxDepth; i++ {\n\t\tp += \"/x\"\n\t}\n\tif _, err := n.Stat(p); err != ninep.ErrTooDeep {\n\t\tt.Errorf(\"got %v, want ErrTooDeep\", err)\n\t}\n}\n"}]},"send":"","max_deposit":"12000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"synfs","path":"gno.land/p/moul/x/plan9/synfs/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/plan9/synfs/v0`\n\n**A synthetic, read-only file server whose contents are computed at read time.**\nThis is the package that makes the rest of the suite adoptable.\n\n```go\nimport synfs \"gno.land/p/moul/x/plan9/synfs/v0\"\n\nt := synfs.New(\"dev\", \"sys\", func() int64 { return runtime.ChainHeight() })\nt.Root().\n\tAdd(\"sysname\", func() string { return runtime.ChainID() }).\n\tAdd(\"height\", func() string { return strconv.FormatInt(runtime.ChainHeight(), 10) })\n```\n\nIn Plan 9 a device is not storage, it is code behind a name: reading `/dev/time`\nruns a function. A realm that wants to publish its state as a browsable tree\ndoes the same thing here, in a few lines, and gets `ls`, `cat`, `stat` and\nmountability for free.\n\n**Read-only by construction.** The tree implements `ninep.File` and not\n`ninep.Mutable`, so every method is free of side effects and the tree is safe to\nhand to a namespace owned by somebody else. That is the property the whole\ncross-realm mount story rests on.\n\nTwo details worth knowing:\n\n- **A synthetic file pins `Qid.Version` at 0 forever.** Its contents can change\n  on every block, so a version would be a lie; a client that needs change\n  detection should read the file.\n- **`AddRange` serves the 9P read window itself**, for a file with no natural\n  end. `/dev/zero` uses it: an unbounded read returns nothing rather than an\n  endless value, which is what stops `cat /dev/zero` from being a denial of\n  service.\n\n**Live demo:** [`r/moul/x/plan9/dev`](../../../../../r/moul/x/plan9/dev/v0)\npublishes the chain itself as a device tree. Design and analysis:\n[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\n\n---\n\n**Not affiliated with Plan 9.** Plan 9 from Bell Labs is the work of the\nComputing Science Research Center at Bell Labs; the name and the marks are\ntheirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org).\nThis package borrows the vocabulary and none of the code: it is an independent\nhomage, asking what that ecosystem's spirit looks like on a chain. Full\nattribution: [NOTICE](../../../../../NOTICE.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/plan9/synfs/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/plan9/synfs/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/plan9/synfs/v0\"\ngno = \"0.9\"\n"},{"name":"synfs.gno","body":"// Package synfs builds a synthetic, read-only ninep file server whose contents\n// are computed by a function at read time.\n//\n// This is the package that makes the rest of the suite adoptable. Plan 9's\n// device drivers are not storage, they are code behind a name: reading\n// /dev/time runs a function. A realm that wants to publish its state as a\n// browsable tree does the same thing here, in a few lines, and gets ls, cat,\n// stat and mountability for free:\n//\n//\tt := synfs.New(\"dev\", \"g1...\", func() int64 { return runtime.ChainHeight() })\n//\tt.Root().\n//\t\tAdd(\"sysname\", func() string { return runtime.ChainID() }).\n//\t\tAdd(\"height\", func() string { return strconv.FormatInt(runtime.ChainHeight(), 10) })\n//\n// The tree is READ-ONLY by construction, which is what makes it safe to hand\n// to another realm's namespace: every method is free of side effects, so it\n// can be called from a frame that does not own these objects.\n//\n// A synthetic file reports Qid.Version 0 forever. Its contents can change on\n// every block, so a version would be a lie; clients that need change detection\n// should read the file.\n//\n// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research\n// Center at Bell Labs; the name and the marks are theirs, and the copyright is\n// held by the Plan 9 Foundation (https://p9f.org). This package is not\n// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9\n// code: it borrows the vocabulary so that the design reads without a glossary,\n// and it is an homage, asking what that ecosystem's spirit looks like on a\n// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.\npackage synfs\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n)\n\n// ReadFn computes a whole file.\ntype ReadFn func() string\n\n// RangeFn serves a 9P read window directly, for files that are cheaper (or\n// only possible) to generate a slice at a time, such as an endless one.\ntype RangeFn func(off, count int64) (string, error)\n\n// Tree owns the qid allocator, the clock and the owner name shared by every\n// node in one synthetic server.\ntype Tree struct {\n\troot  *Dir\n\tnext  uint64\n\tclock func() int64\n\tuid   string\n}\n\n// New returns a tree whose root directory is named name, owned by uid, using\n// clock (normally the block height) as every node's mtime. clock may be nil,\n// in which case the mtime is zero.\nfunc New(name, uid string, clock func() int64) *Tree {\n\tt := \u0026Tree{clock: clock, uid: uid}\n\tt.root = t.NewDir(name)\n\treturn t\n}\n\n// Root returns the tree's root directory.\nfunc (t *Tree) Root() *Dir { return t.root }\n\n// Uid returns the owner stamped on every node.\nfunc (t *Tree) Uid() string { return t.uid }\n\nfunc (t *Tree) now() int64 {\n\tif t.clock == nil {\n\t\treturn 0\n\t}\n\treturn t.clock()\n}\n\nfunc (t *Tree) qid(dir bool) ninep.Qid {\n\tt.next++\n\tqt := ninep.QTFILE\n\tif dir {\n\t\tqt = ninep.QTDIR\n\t}\n\treturn ninep.Qid{Type: qt, Version: 0, Path: t.next}\n}\n\n// NewDir returns a detached directory belonging to this tree. Attach it with\n// AddDir.\nfunc (t *Tree) NewDir(name string) *Dir {\n\treturn \u0026Dir{\n\t\ttree:     t,\n\t\tname:     name,\n\t\tperm:     ninep.DMDIR | 0555,\n\t\tqid:      t.qid(true),\n\t\tchildren: avl.NewTree(),\n\t}\n}\n\n// Dir is a synthetic directory. Its children are held in an avl tree, so a\n// listing is ordered by name and identical on every node.\ntype Dir struct {\n\ttree     *Tree\n\tname     string\n\tperm     ninep.Perm\n\tqid      ninep.Qid\n\tchildren *avl.Tree // name -\u003e ninep.File\n}\n\n// Add attaches a read-only file computed by fn, mode 0444. It returns the\n// directory, so calls chain.\nfunc (d *Dir) Add(name string, fn ReadFn) *Dir {\n\treturn d.AddPerm(name, 0444, fn)\n}\n\n// AddPerm is Add with an explicit mode.\nfunc (d *Dir) AddPerm(name string, perm ninep.Perm, fn ReadFn) *Dir {\n\twhole := fn\n\treturn d.AddRange(name, perm, func(off, count int64) (string, error) {\n\t\treturn ninep.Slice(whole(), off, count), nil\n\t})\n}\n\n// AddRange attaches a file that serves a read window itself. Use it for a file\n// with no natural end, where materialising the whole thing would be wrong.\nfunc (d *Dir) AddRange(name string, perm ninep.Perm, fn RangeFn) *Dir {\n\tif !ninep.ValidName(name) {\n\t\tpanic(\"synfs: invalid file name: \" + name)\n\t}\n\td.children.Set(name, \u0026file{\n\t\ttree: d.tree,\n\t\tname: name,\n\t\tperm: perm \u0026^ ninep.DMDIR,\n\t\tqid:  d.tree.qid(false),\n\t\tfn:   fn,\n\t})\n\treturn d\n}\n\n// AddDir attaches a subdirectory built with Tree.NewDir.\nfunc (d *Dir) AddDir(sub *Dir) *Dir {\n\tif !ninep.ValidName(sub.name) {\n\t\tpanic(\"synfs: invalid directory name: \" + sub.name)\n\t}\n\td.children.Set(sub.name, sub)\n\treturn d\n}\n\n// AddFile attaches any ninep.File under the given name, which is how a\n// synthetic tree splices in a tree served by something else.\nfunc (d *Dir) AddFile(name string, f ninep.File) *Dir {\n\tif !ninep.ValidName(name) {\n\t\tpanic(\"synfs: invalid file name: \" + name)\n\t}\n\td.children.Set(name, f)\n\treturn d\n}\n\n// Names returns the directory's entries, in order. Useful for a file that\n// wants to describe its own directory, as /dev/drivers does.\nfunc (d *Dir) Names() []string {\n\tout := []string{}\n\td.children.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tout = append(out, k)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Stat implements ninep.File.\nfunc (d *Dir) Stat() ninep.Stat {\n\treturn ninep.Stat{\n\t\tQid:   d.qid,\n\t\tMode:  d.perm,\n\t\tMtime: d.tree.now(),\n\t\tName:  d.name,\n\t\tUid:   d.tree.uid,\n\t\tGid:   d.tree.uid,\n\t\tMuid:  d.tree.uid,\n\t}\n}\n\n// Walk implements ninep.File.\nfunc (d *Dir) Walk(name string) (ninep.File, error) {\n\tif !ninep.ValidName(name) {\n\t\treturn nil, ninep.ErrBadName\n\t}\n\tv := d.children.Get(name)\n\tif v == nil {\n\t\treturn nil, ninep.ErrNotExist\n\t}\n\treturn v.(ninep.File), nil\n}\n\n// Read implements ninep.File.\nfunc (d *Dir) Read(off, count int64) (string, error) { return \"\", ninep.ErrIsDir }\n\n// ReadDir implements ninep.File.\nfunc (d *Dir) ReadDir() ([]ninep.Stat, error) {\n\tout := []ninep.Stat{}\n\td.children.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tout = append(out, v.(ninep.File).Stat())\n\t\treturn false\n\t})\n\treturn out, nil\n}\n\ntype file struct {\n\ttree *Tree\n\tname string\n\tperm ninep.Perm\n\tqid  ninep.Qid\n\tfn   RangeFn\n}\n\nfunc (f *file) Stat() ninep.Stat {\n\t// A synthetic file has no stored length. 9P servers for such files report\n\t// zero rather than run the generator just to measure it, and so does this.\n\treturn ninep.Stat{\n\t\tQid:   f.qid,\n\t\tMode:  f.perm,\n\t\tMtime: f.tree.now(),\n\t\tName:  f.name,\n\t\tUid:   f.tree.uid,\n\t\tGid:   f.tree.uid,\n\t\tMuid:  f.tree.uid,\n\t}\n}\n\nfunc (f *file) Walk(name string) (ninep.File, error) { return nil, ninep.ErrNotDir }\n\nfunc (f *file) Read(off, count int64) (string, error) { return f.fn(off, count) }\n\nfunc (f *file) ReadDir() ([]ninep.Stat, error) { return nil, ninep.ErrNotDir }\n"},{"name":"synfs_test.gno","body":"package synfs\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n)\n\nfunc fixedClock(h int64) func() int64 { return func() int64 { return h } }\n\nfunc TestTreeShape(t *testing.T) {\n\ttr := New(\"dev\", \"sys\", fixedClock(42))\n\ttr.Root().\n\t\tAdd(\"sysname\", func() string { return \"gnoland-1\" }).\n\t\tAdd(\"height\", func() string { return \"42\" })\n\n\tst := tr.Root().Stat()\n\tif st.Name != \"dev\" {\n\t\tt.Errorf(\"root name %q\", st.Name)\n\t}\n\tif !st.IsDir() {\n\t\tt.Error(\"root should be a directory\")\n\t}\n\tif st.Mtime != 42 {\n\t\tt.Errorf(\"mtime %d, want 42\", st.Mtime)\n\t}\n\tif st.Mode.String() != \"dr-xr-xr-x\" {\n\t\tt.Errorf(\"mode %q, want dr-xr-xr-x\", st.Mode.String())\n\t}\n}\n\nfunc TestReadComputed(t *testing.T) {\n\theight := int64(100)\n\ttr := New(\"dev\", \"sys\", func() int64 { return height })\n\ttr.Root().Add(\"height\", func() string { return strconv.FormatInt(height, 10) })\n\n\tf, err := tr.Root().Walk(\"height\")\n\tif err != nil {\n\t\tt.Fatalf(\"walk: %v\", err)\n\t}\n\tgot, _ := ninep.ReadAll(f)\n\tif got != \"100\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n\t// The generator runs on every read, so the file follows the chain.\n\theight = 101\n\tgot, _ = ninep.ReadAll(f)\n\tif got != \"101\" {\n\t\tt.Errorf(\"after the block advanced: got %q\", got)\n\t}\n\tif v := f.Stat().Qid.Version; v != 0 {\n\t\tt.Errorf(\"a synthetic file pins version 0, got %d\", v)\n\t}\n}\n\nfunc TestReadWindow(t *testing.T) {\n\ttr := New(\"dev\", \"sys\", nil)\n\ttr.Root().Add(\"msg\", func() string { return \"hello world\" })\n\tf, _ := tr.Root().Walk(\"msg\")\n\n\ttests := []struct {\n\t\toff, count int64\n\t\twant       string\n\t}{\n\t\t{0, -1, \"hello world\"},\n\t\t{0, 5, \"hello\"},\n\t\t{6, 5, \"world\"},\n\t\t{99, 5, \"\"},\n\t}\n\tfor _, tt := range tests {\n\t\tgot, err := f.Read(tt.off, tt.count)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"read: %v\", err)\n\t\t}\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"Read(%d,%d): got %q, want %q\", tt.off, tt.count, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestAddRangeEndlessFile(t *testing.T) {\n\t// /dev/zero has no end: it must serve the window rather than a value.\n\ttr := New(\"dev\", \"sys\", nil)\n\ttr.Root().AddRange(\"zero\", 0444, func(off, count int64) (string, error) {\n\t\tif count \u003c 0 {\n\t\t\tcount = 0\n\t\t}\n\t\treturn strings.Repeat(\"0\", int(count)), nil\n\t})\n\tf, _ := tr.Root().Walk(\"zero\")\n\tgot, _ := f.Read(0, 4)\n\tif got != \"0000\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n\tgot, _ = f.Read(0, -1)\n\tif got != \"\" {\n\t\tt.Errorf(\"an unbounded read of an endless file must not hang or grow: got %q\", got)\n\t}\n}\n\nfunc TestReadDirIsOrdered(t *testing.T) {\n\ttr := New(\"dev\", \"sys\", fixedClock(1))\n\ttr.Root().\n\t\tAdd(\"zero\", func() string { return \"\" }).\n\t\tAdd(\"null\", func() string { return \"\" }).\n\t\tAdd(\"time\", func() string { return \"\" })\n\n\tents, err := tr.Root().ReadDir()\n\tif err != nil {\n\t\tt.Fatalf(\"readdir: %v\", err)\n\t}\n\twant := []string{\"null\", \"time\", \"zero\"}\n\tif len(ents) != len(want) {\n\t\tt.Fatalf(\"got %d entries\", len(ents))\n\t}\n\tfor i, w := range want {\n\t\tif ents[i].Name != w {\n\t\t\tt.Errorf(\"entry %d: got %q, want %q\", i, ents[i].Name, w)\n\t\t}\n\t}\n\tif got := tr.Root().Names(); len(got) != 3 || got[0] != \"null\" {\n\t\tt.Errorf(\"Names: %v\", got)\n\t}\n}\n\nfunc TestSubdirectories(t *testing.T) {\n\ttr := New(\"proc\", \"sys\", fixedClock(7))\n\tsub := tr.NewDir(\"1\")\n\tsub.Add(\"status\", func() string { return \"running\" })\n\ttr.Root().AddDir(sub)\n\n\tf, err := ninep.Walk(tr.Root(), ninep.Elems(\"/1/status\"))\n\tif err != nil {\n\t\tt.Fatalf(\"walk: %v\", err)\n\t}\n\tgot, _ := ninep.ReadAll(f)\n\tif got != \"running\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n}\n\nfunc TestErrors(t *testing.T) {\n\ttr := New(\"dev\", \"sys\", nil)\n\ttr.Root().Add(\"null\", func() string { return \"\" })\n\n\tif _, err := tr.Root().Read(0, -1); err != ninep.ErrIsDir {\n\t\tt.Errorf(\"read a directory: got %v\", err)\n\t}\n\tif _, err := tr.Root().Walk(\"absent\"); err != ninep.ErrNotExist {\n\t\tt.Errorf(\"walk missing: got %v\", err)\n\t}\n\tif _, err := tr.Root().Walk(\"a/b\"); err != ninep.ErrBadName {\n\t\tt.Errorf(\"walk bad name: got %v\", err)\n\t}\n\tf, _ := tr.Root().Walk(\"null\")\n\tif _, err := f.Walk(\"x\"); err != ninep.ErrNotDir {\n\t\tt.Errorf(\"walk through a file: got %v\", err)\n\t}\n\tif _, err := f.ReadDir(); err != ninep.ErrNotDir {\n\t\tt.Errorf(\"readdir a file: got %v\", err)\n\t}\n}\n\nfunc TestSyntheticTreeIsReadOnly(t *testing.T) {\n\t// The whole point: a synthetic tree implements File and NOT Mutable, so\n\t// it is safe to hand to a namespace owned by somebody else.\n\ttr := New(\"dev\", \"sys\", nil)\n\tvar f ninep.File = tr.Root()\n\tif _, ok := f.(ninep.Mutable); ok {\n\t\tt.Error(\"a synthetic tree must not be Mutable\")\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"storagecost","path":"gno.land/p/moul/x/storagecost/v1","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/storagecost/v1`\n\nIs it worth paying gas to delete on-chain state?\n\nOn gno.land every byte of realm state locks GNOT, and the lock is refunded to\nwhoever signs the transaction that frees the byte. Deleting state is therefore\npaid work. Whether a particular deletion pays depends on two prices that move\nindependently: the storage price, a chain parameter, and the gas price of the\nday. **A contract cannot know the second one**, so it cannot decide on its own\nbehalf whether to compact, reindex or reap. It can only publish the size of the\nprize and let a caller do the arithmetic.\n\nThis package is that arithmetic: pure integer maths, no chain imports, so a\nrealm can call it inside a `Render` and an off-chain bot can reuse the identical\nformula.\n\n## The one number to remember\n\nOne byte freed refunds 100 ugnot. At the lowest gas price mainnet has actually\naccepted, one ugnot buys 1000 gas. **So a byte is worth 100,000 gas, and any\ndeletion costing less than that per byte pays for itself.**\n\n```go\nq := storagecost.EvaluateAtFloor(17835, 5_000_000)\nq.Refund // 1783500 ugnot\nq.Fee    //    5000 ugnot\nq.Net    // 1778500 ugnot\nq.Worth() // true\nq.String() // \"17835 bytes, refunds 1.7835 GNOT against 0.005 GNOT of gas, break-even 50 bytes: worth 1.7785 GNOT\"\n```\n\n## What is in here\n\n| | |\n|---|---|\n| `Refund` · `BreakEvenBytes` · `Net` | the core arithmetic. `BreakEvenBytes` rounds up, so a quoted threshold always covers the fee |\n| `GasFee` · `FloorGasFee` | a fee from a gas ceiling and a rational gas price. The fee tracks `gas_wanted`, not `gas_used`, so unused headroom is paid for |\n| `Evaluate` · `EvaluateAtFloor` · `Quote` | a whole verdict for one candidate cleanup, with a `String()` fit for a `Render` |\n| `EstimateBytes` | what a payload really costs once a realm has wrapped it in an object, at the measured 1.85x |\n| `FormatGNOT` | ugnot as readable GNOT, because gno has no floats and a bounty quoted in ugnot is unreadable |\n\n## Two honesty notes\n\n**`DefaultStoragePrice` is a default, not a fact.** `vm:p:storage_price` is\ngovernance settable. Read it from the chain when real money depends on the\nanswer; the constant is for sizing and display.\n\n**`EstimateBytes` is an estimate.** It exists so a bounty shown on a page is\nwithin a factor of two instead of reporting raw payload length. No stdlib call\nexposes a realm's real locked storage, so the authoritative numbers are the\nchain's: the `vm/qstorage` query, or the `StorageDepositEvent` and\n`StorageUnlockEvent` every transaction emits. Never settle an accounting\nquestion with a guess.\n\nDemo realm: [`r/moul/x/reaper`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/reaper).\n\n## v1: `FormatGNOT` delegates to `p/moul/kit/num`\n\n`v0` formatted by hand with `amount = -amount`, which leaves `math.MinInt64`\nnegative, so both the whole and the fractional part then carried their own sign:\n`FormatGNOT(math.MinInt64)` returned `--9223372036854.-775808 GNOT`. No caller\nin this repo can reach a negative (`q.Net` is the only one that can be, and it\nis printed only inside `if q.Worth()`), but the function is exported and a\nformatter that can return a non-number is not one. `v0` stays resolvable.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/storagecost/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/storagecost/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/storagecost/v1\"\ngno = \"0.9\"\n"},{"name":"storagecost.gno","body":"// Package storagecost answers one question: is it worth paying gas to delete\n// on-chain state?\n//\n// On gno.land every byte of realm state locks GNOT, and the lock is refunded\n// to whoever signs the transaction that frees the byte. Deleting state is\n// therefore paid work, and whether a given deletion pays depends on two prices\n// that move independently: the storage price, a chain parameter, and the gas\n// price of the day. A contract cannot know the second one, so it cannot decide\n// on its own behalf whether to compact, reindex or reap. It can only publish\n// the size of the prize and let a caller do the arithmetic.\n//\n// This package is that arithmetic. It is pure integer maths with no chain\n// imports, so a realm can call it inside a Render and an off-chain bot can\n// reuse the identical formula.\n//\n// The single fact worth remembering is the ratio. One byte freed refunds 100\n// ugnot, and at the lowest gas price mainnet has actually accepted one ugnot\n// buys 1000 gas. So a byte is worth 100,000 gas, and any deletion costing less\n// than that per byte pays for itself.\n//\n// Demo realms: gno.land/r/moul/x/reaper for reaping expired state, and\n// gno.land/r/moul/x/compact for the compaction half.\npackage storagecost\n\nimport (\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\t// DefaultStoragePrice is the ugnot locked per byte of realm state, the\n\t// default of the chain's vm:p:storage_price parameter. It is governance\n\t// settable, so read it from the chain rather than trusting this constant\n\t// when real money depends on the answer.\n\tDefaultStoragePrice int64 = 100\n\n\t// GasPerUgnotFloor is how much gas one ugnot buys at the lowest gas price\n\t// mainnet has been observed to accept, 0.001 ugnot per gas. It is a floor,\n\t// not a promise: the fee a node requires tracks gas_wanted, so asking for\n\t// more headroom raises the fee proportionally.\n\tGasPerUgnotFloor int64 = 1000\n\n\t// payloadOverheadNum/payloadOverheadDen approximate what a payload really\n\t// costs once the realm has wrapped it in an object. Measured at 1.85x: ten\n\t// 1,024-byte strings in a realm slice cost 18,984 bytes of state, 1,898\n\t// each. It is an estimate and nothing more. The authoritative number is\n\t// the chain's own, from the vm/qstorage query or a StorageDepositEvent.\n\tpayloadOverheadNum int64 = 185\n\tpayloadOverheadDen int64 = 100\n\n\t// BytesPerTreeNode is the realm state one balanced-tree container node\n\t// occupies, for the tree containers in this namespace (p/moul/ulist and\n\t// what is built on it).\n\t//\n\t// Measured twice, agreeing exactly. Compacting 8 dead nodes on mainnet\n\t// freed 6,848 bytes (2026-09-23), and 31 nodes in the local integration\n\t// harness freed 26,536. Both give 856.\n\t//\n\t// It is a property of the node, not of the element: the node costs this\n\t// whether the value it carried was 8 bytes or 1,024. That is what makes\n\t// EstimateNodes accurate where EstimateBytes is only indicative.\n\tBytesPerTreeNode int64 = 856\n\n\tugnotPerGNOT int64 = 1_000_000\n)\n\n// Refund is the deposit returned for freeing bytes at the given price per\n// byte. Returns 0 for non-positive inputs rather than panicking, so a Render\n// on a realm with no state still works.\nfunc Refund(bytes, pricePerByte int64) int64 {\n\tif bytes \u003c= 0 || pricePerByte \u003c= 0 {\n\t\treturn 0\n\t}\n\treturn bytes * pricePerByte\n}\n\n// BreakEvenBytes is the fewest bytes whose refund covers a fee: the point\n// where a cleanup stops costing money and starts making it. Below this many\n// bytes the transaction is charity.\nfunc BreakEvenBytes(feeUgnot, pricePerByte int64) int64 {\n\tif pricePerByte \u003c= 0 {\n\t\treturn 0\n\t}\n\tif feeUgnot \u003c= 0 {\n\t\treturn 0\n\t}\n\t// Round up: freeing exactly feeUgnot/pricePerByte bytes must cover the fee.\n\treturn (feeUgnot + pricePerByte - 1) / pricePerByte\n}\n\n// GasFee is the fee a transaction asking for gasWanted must pay at a gas price\n// of num/den ugnot per gas, rounded up.\n//\n// The fee tracks gas_wanted rather than gas_used, so unused headroom is paid\n// for. Pass the ceiling you will actually put in the transaction, not what you\n// expect to burn.\nfunc GasFee(gasWanted, num, den int64) int64 {\n\tif gasWanted \u003c= 0 || num \u003c= 0 || den \u003c= 0 {\n\t\treturn 0\n\t}\n\treturn (gasWanted*num + den - 1) / den\n}\n\n// FloorGasFee is GasFee at the lowest gas price mainnet has accepted.\nfunc FloorGasFee(gasWanted int64) int64 {\n\treturn GasFee(gasWanted, 1, GasPerUgnotFloor)\n}\n\n// EstimateBytes guesses the realm state a payload of this many bytes will\n// occupy, applying the measured object overhead.\n//\n// It is for sizing a bounty in a Render, where being within a factor of two\n// beats reporting the raw payload length. Never settle an accounting question\n// with it.\nfunc EstimateBytes(payloadBytes int64) int64 {\n\tif payloadBytes \u003c= 0 {\n\t\treturn 0\n\t}\n\treturn payloadBytes * payloadOverheadNum / payloadOverheadDen\n}\n\n// EstimateNodes is the realm state a count of dead container nodes occupies,\n// and so what compacting them frees.\n//\n// Prefer it to EstimateBytes wherever the caller can count, which for a\n// compaction it always can. EstimateBytes scales a payload length by a ratio\n// measured at one size and is wrong at the others: a per-entry floor dominates\n// at the small end, and a realm advertising a bounty that way under-reported\n// by 25x against what the cleanup actually returned on chain (2026-09-23).\n// Counting nodes has no such failure mode. The container reports the exact\n// number, and every node costs the same.\n//\n// Still an estimate. BytesPerTreeNode is measured rather than derived, and the\n// chain's own StorageDepositEvent remains the only settlement.\nfunc EstimateNodes(nodes int64) int64 {\n\tif nodes \u003c= 0 {\n\t\treturn 0\n\t}\n\treturn nodes * BytesPerTreeNode\n}\n\n// Quote is a complete answer for one candidate cleanup.\ntype Quote struct {\n\tBytes     int64 // bytes the cleanup would free\n\tRefund    int64 // ugnot returned for them\n\tFee       int64 // ugnot the transaction will cost\n\tNet       int64 // Refund - Fee; negative means it costs more than it pays\n\tBreakEven int64 // bytes needed to cover Fee\n}\n\n// Worth reports whether the cleanup pays for itself.\nfunc (q Quote) Worth() bool { return q.Net \u003e 0 }\n\n// String renders the quote as one line of markdown-safe text, for a Render.\nfunc (q Quote) String() string {\n\tverdict := \"not worth it yet\"\n\tif q.Worth() {\n\t\tverdict = \"worth \" + FormatGNOT(q.Net)\n\t}\n\treturn ufmt.Sprintf(\n\t\t\"%d bytes, refunds %s against %s of gas, break-even %d bytes: %s\",\n\t\tq.Bytes, FormatGNOT(q.Refund), FormatGNOT(q.Fee), q.BreakEven, verdict,\n\t)\n}\n\n// Evaluate prices one cleanup: freeing bytes in a transaction asking for\n// gasWanted, at a storage price of pricePerByte and a gas price of num/den\n// ugnot per gas.\nfunc Evaluate(bytes, pricePerByte, gasWanted, num, den int64) Quote {\n\tfee := GasFee(gasWanted, num, den)\n\trefund := Refund(bytes, pricePerByte)\n\treturn Quote{\n\t\tBytes:     bytes,\n\t\tRefund:    refund,\n\t\tFee:       fee,\n\t\tNet:       refund - fee,\n\t\tBreakEven: BreakEvenBytes(fee, pricePerByte),\n\t}\n}\n\n// EvaluateAtFloor is Evaluate at the default storage price and the floor gas\n// price: the best case, and the one to quote when advertising a bounty.\nfunc EvaluateAtFloor(bytes, gasWanted int64) Quote {\n\treturn Evaluate(bytes, DefaultStoragePrice, gasWanted, 1, GasPerUgnotFloor)\n}\n\n// FormatGNOT renders ugnot as GNOT with trailing zeros trimmed, because a\n// bounty shown in ugnot is unreadable and gno has no floats.\n//\n// It delegates to [p/moul/kit/num], which owns amount formatting. v0 did it by\n// hand with `amount = -amount`, and since that leaves math.MinInt64 negative\n// both the whole and the fractional part then carried their own sign:\n// FormatGNOT(math.MinInt64) returned \"--9223372036854.-775808 GNOT\". No caller\n// in this repo can reach it, but the function is exported and a formatter that\n// can return a non-number is not one.\nfunc FormatGNOT(amount int64) string {\n\treturn num.GNOTf(amount)\n}\n"},{"name":"storagecost_test.gno","body":"package storagecost\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRefund(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tbytes int64\n\t\tprice int64\n\t\twant  int64\n\t}{\n\t\t{\"one byte at the default price\", 1, DefaultStoragePrice, 100},\n\t\t{\"the measured reap\", 17835, DefaultStoragePrice, 1783500},\n\t\t{\"the measured compact\", 830, DefaultStoragePrice, 83000},\n\t\t{\"zero bytes\", 0, DefaultStoragePrice, 0},\n\t\t{\"negative bytes are not a credit\", -100, DefaultStoragePrice, 0},\n\t\t{\"a free chain refunds nothing\", 1000, 0, 0},\n\t\t{\"a ten-fold price rise\", 1000, 1000, 1000000},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tt.want, Refund(tt.bytes, tt.price))\n\t\t})\n\t}\n}\n\nfunc TestBreakEvenBytes(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tfee  int64\n\t\twant int64\n\t}{\n\t\t// A 2.6M gas call at the floor costs 2,600 ugnot, so 26 bytes.\n\t\t{\"the canonical 2.6M gas call\", 2600, 26},\n\t\t{\"rounds up, never down\", 101, 2},\n\t\t{\"exactly one byte\", 100, 1},\n\t\t{\"a fee below one byte still needs a byte\", 1, 1},\n\t\t{\"no fee, no threshold\", 0, 0},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := BreakEvenBytes(tt.fee, DefaultStoragePrice)\n\t\t\tuassert.Equal(t, tt.want, got)\n\t\t\t// The definition: this many bytes covers the fee, one fewer does not.\n\t\t\tif tt.want \u003e 0 {\n\t\t\t\tuassert.True(t, Refund(got, DefaultStoragePrice) \u003e= tt.fee)\n\t\t\t\tuassert.False(t, Refund(got-1, DefaultStoragePrice) \u003e= tt.fee)\n\t\t\t}\n\t\t})\n\t}\n\tuassert.Equal(t, int64(0), BreakEvenBytes(1000, 0))\n}\n\nfunc TestGasFee(t *testing.T) {\n\t// The floor mainnet has actually accepted: 1 ugnot per 1000 gas.\n\tuassert.Equal(t, int64(5000), FloorGasFee(5_000_000))\n\tuassert.Equal(t, int64(2500), FloorGasFee(2_500_000))\n\t// Rounds up, so a fee is never short.\n\tuassert.Equal(t, int64(1), FloorGasFee(1))\n\tuassert.Equal(t, int64(0), FloorGasFee(0))\n\t// The harness price used in the measurements, 1.2 ugnot per gas.\n\tuassert.Equal(t, int64(6_000_000), GasFee(5_000_000, 12, 10))\n\tuassert.Equal(t, int64(0), GasFee(5_000_000, 0, 10))\n\tuassert.Equal(t, int64(0), GasFee(5_000_000, 1, 0))\n}\n\nfunc TestEvaluateReproducesTheMeasuredReap(t *testing.T) {\n\t// The measured run: 17,835 bytes freed by a call that used 4,120,876 gas,\n\t// so gas_wanted 5,000,000 at the floor. Net +1,778,500 ugnot.\n\tq := EvaluateAtFloor(17835, 5_000_000)\n\tuassert.Equal(t, int64(1783500), q.Refund)\n\tuassert.Equal(t, int64(5000), q.Fee)\n\tuassert.Equal(t, int64(1778500), q.Net)\n\tuassert.Equal(t, int64(50), q.BreakEven)\n\tuassert.True(t, q.Worth())\n}\n\nfunc TestEvaluateReproducesTheMeasuredCompact(t *testing.T) {\n\tq := EvaluateAtFloor(830, 2_500_000)\n\tuassert.Equal(t, int64(83000), q.Refund)\n\tuassert.Equal(t, int64(2500), q.Fee)\n\tuassert.Equal(t, int64(80500), q.Net)\n\tuassert.True(t, q.Worth())\n}\n\nfunc TestEvaluateAtTheHarnessPriceIsALoss(t *testing.T) {\n\t// The same reap priced at 1.2 ugnot/gas, 1200x the floor, loses money.\n\t// This is why the gas price cannot be baked into a contract.\n\tq := Evaluate(17835, DefaultStoragePrice, 5_000_000, 12, 10)\n\tuassert.Equal(t, int64(6_000_000), q.Fee)\n\tuassert.False(t, q.Worth())\n\tuassert.True(t, q.Net \u003c 0)\n}\n\nfunc TestQuoteString(t *testing.T) {\n\tworth := EvaluateAtFloor(17835, 5_000_000)\n\tuassert.Equal(t,\n\t\t\"17835 bytes, refunds 1.7835 GNOT against 0.005 GNOT of gas, break-even 50 bytes: worth 1.7785 GNOT\",\n\t\tworth.String())\n\n\tloss := Evaluate(10, DefaultStoragePrice, 5_000_000, 12, 10)\n\tuassert.Equal(t,\n\t\t\"10 bytes, refunds 0.001 GNOT against 6 GNOT of gas, break-even 60000 bytes: not worth it yet\",\n\t\tloss.String())\n}\n\nfunc TestFormatGNOT(t *testing.T) {\n\ttests := []struct {\n\t\tamount int64\n\t\twant   string\n\t}{\n\t\t{0, \"0 GNOT\"},\n\t\t{1, \"0.000001 GNOT\"},\n\t\t{100, \"0.0001 GNOT\"},\n\t\t{1_000_000, \"1 GNOT\"},\n\t\t{1_500_000, \"1.5 GNOT\"},\n\t\t{1_783_500, \"1.7835 GNOT\"},\n\t\t{978_743_800, \"978.7438 GNOT\"},\n\t\t{-2_100, \"-0.0021 GNOT\"},\n\t\t{1_000_001, \"1.000001 GNOT\"},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, FormatGNOT(tt.amount))\n\t}\n}\n\nfunc TestEstimateBytes(t *testing.T) {\n\t// Measured: a 1,024-byte payload occupied 1,898 bytes of realm state.\n\tuassert.Equal(t, int64(1894), EstimateBytes(1024))\n\tuassert.Equal(t, int64(0), EstimateBytes(0))\n\tuassert.Equal(t, int64(0), EstimateBytes(-5))\n\t// Monotonic, which is all a bounty estimate really needs.\n\tuassert.True(t, EstimateBytes(2048) \u003e EstimateBytes(1024))\n}\n\n// TestFormatGNOTIsTotal pins what v0 could not do. v0 negated in int64, so at\n// math.MinInt64 both halves kept a sign and it returned\n// \"--9223372036854.-775808 GNOT\". Delegating to kit/num is the fix; this\n// asserts the contract rather than the delegation.\nfunc TestFormatGNOTIsTotal(t *testing.T) {\n\tconst minInt64 = -9223372036854775808\n\tuassert.Equal(t, \"-9223372036854.775808 GNOT\", FormatGNOT(minInt64))\n\tuassert.Equal(t, \"-1.5 GNOT\", FormatGNOT(-1500000))\n\tuassert.Equal(t, \"-0.000001 GNOT\", FormatGNOT(-1))\n\tuassert.Equal(t, \"1.5 GNOT\", FormatGNOT(1500000))\n\tuassert.Equal(t, \"0 GNOT\", FormatGNOT(0))\n}\n\nfunc TestEstimateNodes(t *testing.T) {\n\tcases := []struct {\n\t\tname  string\n\t\tnodes int64\n\t\twant  int64\n\t}{\n\t\t{\"none\", 0, 0},\n\t\t{\"negative is not an error\", -5, 0},\n\t\t// The mainnet measurement this constant comes from: compacting a\n\t\t// drained 8-node board returned 6,848 bytes.\n\t\t{\"the mainnet sample\", 8, 6848},\n\t\t// And the local harness, which agreed to the byte.\n\t\t{\"the local harness sample\", 31, 26536},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, EstimateNodes(tc.nodes), tc.name)\n\t}\n}\n\n// TestEstimateNodesBeatsEstimateBytesOnTheCaseThatBurnedUs pins the reason\n// EstimateNodes exists, not just what it computes.\n//\n// A realm advertised a bounty by running the payload length of five small\n// entries through EstimateBytes and got 481 bytes. Reaping and compacting them\n// actually returned 11,972. The payload path cannot see either the per-entry\n// floor or the container, and no existing test could catch that because they\n// all fed EstimateBytes the 1,024-byte payloads its ratio was measured on.\nfunc TestEstimateNodesBeatsEstimateBytesOnTheCaseThatBurnedUs(t *testing.T) {\n\tconst payload = 8 + 231 + 7 + 5 + 9 // the five note bodies, 260 bytes\n\tconst reallyFreed = 11972\n\n\tguess := EstimateBytes(payload)\n\tuassert.True(t, guess*20 \u003c reallyFreed,\n\t\t\"EstimateBytes is still supposed to be the bad one here\")\n\n\t// The container half is the part that is countable, and counting it gets\n\t// most of the way there on its own: 8 nodes were the larger share.\n\tcounted := EstimateNodes(8)\n\tuassert.True(t, counted \u003e guess*10,\n\t\t\"counting nodes should dominate guessing from payload\")\n\tuassert.True(t, counted \u003c= reallyFreed,\n\t\t\"counting nodes must never over-advertise\")\n}\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bf","path":"gno.land/p/moul/x/vm/bf/v0","files":[{"name":"README.md","body":"# p/moul/x/vm/bf\n\nA Brainfuck machine for gno.land, and the measuring stick the guest-VM work is\ncalibrated against.\n\nThe package ships two things that look alike and are not:\n\n- **`Execute`**, the naive interpreter from 2023: a switch over the source\n  bytes, a brace matcher that rescans the program on every loop edge. It is\n  kept verbatim as rung 0 of the ladder below, because a baseline you have\n  edited is not a baseline. It panics on `,` and on unbalanced brackets, and\n  both bugs are pinned by tests so nobody \"fixes\" the reference.\n- **`Compile` + `Machine`**, the real one: resolved jump targets, fused\n  operator runs, loop idioms folded into single ops, and a fuel-metered step\n  loop over a [`vmkit`](../vmkit) `Host`, so a program pauses when it runs out\n  and resumes in a later transaction.\n\nLive demo: [`r/moul/x/vm/bfdemo`](/r/moul/x/vm/bfdemo/v0).\n\n```go\nm, err := bf.Load(\"+++++[-\u003e++++++++++\u003c]\u003e++.\")\nif err != nil { return err }\nused, status := m.Step(host, 1000)   // status: running, halted, trapped, out of fuel\nsnap := m.Snapshot()                 // resume later: NewMachine(prog).Restore(snap)\n```\n\n## The optimization ladder\n\nMeasured 2026-09-22 with `gno test -print-runtime-metrics`, `gno` built from\n`gnolang/gno` master@877379432. Reproduce with:\n\n```sh\ngno test -print-runtime-metrics .\n```\n\nThe program is `heavy` (`ladder_test.gno`): 408 source bytes, **121,201 guest\ninstructions**, no output, so it measures the dispatch loop and nothing else.\n\n| rung | what changed | machine ops | cycles | cycles / guest op |\n|---|---|---:|---:|---:|\n| 0 | `Execute`, the original | 161,200 dispatches | 1.4G | 11,551 |\n| 1 | compile to ops, resolve jump targets | 121,202 | 613.4M | 5,061 |\n| 2 | fuse runs of `+` and `\u003e` | 81,203 | 444.6M | 3,668 |\n| 3 | fold loop idioms (`[-]`, `[-\u003e+\u003c]`, `[\u003e]`) | 1,203 | 10.0M | 83 |\n| 5 | rung 3 with a fuel budget enforced | 1,203 | 11.0M | 91 |\n\nFrom the 1x and 4x pairs, which cancel the fixed per-test overhead: rung 0 runs\nat **11,003 cycles per guest instruction**, rung 3 at **79.5**. The ladder is\nworth **138x**, and almost all of it is rung 3: folding a counted loop into the\nmultiply it performs is the only optimization here that changes the complexity\nrather than the constant.\n\n### Two denominators, and why it matters\n\nA guest instruction is one operator the language executes, counted the way any\njump-table interpreter counts it: 121,201 for `heavy`. The naive interpreter\n*dispatches* more often than that for the same program, because its `]` handler\nscans back to the matching `[` and lands on it, so `[` is re-evaluated on every\niteration of every loop: 161,200, a factor of 1.33.\n\nRung 1 removes exactly that excess, so quoting cycles-per-*dispatch* would\ncredit rung 1 twice and make rung 0 look 33% better than it is. Both counts come\nfrom an independent simulator, not from this package.\n\n## The other axis: what the GnoVM charges for\n\nThe rungs above are the classic optimizations, fewer instructions for the same\nprogram. On the GnoVM a second axis matters as much, and it is not in any\ninterpreter textbook: the same instruction stream, run by loops that differ from\neach other by one line. `micro_test.gno` is that matrix.\n\nRung 1's stream, 121,202 ops:\n\n| loop | cycles | allocs | vs. locals |\n|---|---:|---:|---:|\n| cursors as struct fields | 523.7M | 31.5M | +18% |\n| cursors in locals | 442.4M | 31.5M | baseline |\n| + `vmkit.Meter.Charge` per op | 821.3M | 110.1M | **+86%** |\n| + inline fuel counter instead | 514.2M | 31.5M | +16% |\n| + tape as a local slice | 492.1M | 31.6M | +11% |\n\nRung 3's stream, 1,203 ops, same ordering: 9.0M / 8.2M / 11.9M / 8.9M / 8.7M.\n\nThree things follow, and the shipped `Machine.Step` does all three:\n\n1. **A method call per guest instruction is the most expensive thing in the\n   loop.** Charging fuel through `vmkit.Meter` costs 86% on top of the entire\n   dispatch loop and more than triples the allocation count. `Meter` is the\n   right type at the API boundary, where it is called once per slice. It is not\n   a hot-path type, and no guest VM in the zoo should treat it as one. An inline\n   counter does the same job for 16%.\n2. **Reaching through a struct pointer for the program counter and the tape\n   pointer costs 16%.** Hoist them into locals and write back once.\n3. **The fixed-array tape is not the win the textbooks claim.** An array is\n   supposed to remove a bounds check; here a slice is 4% *faster*, because a\n   slice header can be copied into a local and an array cannot. It is the\n   smallest effect on this page, and the classic ladder puts it above idiom\n   recognition, which is worth 44x.\n\nThe pc range check is also hoisted out of the loop: every jump target is\nproduced by `Compile` and every restored pc is validated by `Restore`, so\nchecking per op buys nothing.\n\n## Snapshots\n\nA snapshot carries the tape only up to the highest cell the program has\nreached, so hello world pauses in **43 bytes**, not 30,000. That is what makes\ncontinuations cheaper than re-running, which is the kill criterion `vmkit` set\nfor them.\n\nThe program is *not* in the snapshot: a realm stores it once beside the\ninstance, not once per pause.\n\n## Semantics\n\nTape of 30,000 wrapping byte cells, matching the original. `,` past the end of\ninput yields a zero cell, the most common of the three conventions the language\nnever settled. `Compile` rejects unbalanced brackets and sources above 64 KiB.\n\nThe idiom rewriter is deliberately conservative: it folds a loop only when the\nbody moves and adds, returns to where it started, and takes exactly one off the\ncurrent cell. A loop that adds one per iteration still terminates by wrapping\nafter 256 rounds, and is left as a real loop, because folding it would be a\ndifferent program.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/vm/bf/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/vm/bf/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bf.gno","body":"// Package bf is a Brainfuck machine for gno.land, and the measuring stick the\n// rest of the guest-VM work is calibrated against.\n//\n// It ships two things that look alike and are not:\n//\n//   - [Execute], the naive interpreter: a switch over the source bytes, a\n//     brace matcher that rescans the program on every loop edge. It is kept\n//     verbatim as rung 0 of the optimization ladder, because a baseline you\n//     have edited is not a baseline.\n//   - [Compile] plus [Machine], the real one: the program is compiled to an\n//     op array with resolved jumps, runs of identical operators are fused,\n//     the common loop idioms become single ops, and execution is metered by\n//     a caller-supplied fuel budget against a\n//     [vmkit](/p/moul/x/vm/vmkit/v0) Host, so a program can pause when it\n//     runs out and resume in a later transaction.\n//\n// The ladder between them is measured, not asserted: see the README for the\n// table, and ladder_test.gno for the harness that produces it.\n//\n// Live demo: [r/moul/x/vm/bfdemo](/r/moul/x/vm/bfdemo/v0).\npackage bf\n\nimport \"strings\"\n\n// NaiveTapeSize is the tape length used by [Execute]. It is 30,000 because\n// that is what the original had, and rung 0 is not allowed to drift.\nconst NaiveTapeSize = 30000\n\n// Execute runs code on a fresh tape and returns everything it wrote, using\n// the original 2023 implementation: no compilation step, one switch per\n// source byte, and a brace matcher that rescans the source every time a loop\n// opens or closes.\n//\n// It is rung 0 of the ladder and exists to be measured. Two of its properties\n// are bugs that are deliberately preserved, and are the reason nothing should\n// call it on untrusted input:\n//\n//   - `,` panics with \"unsupported\": there is no input.\n//   - unbalanced brackets run the scan off the end of the source and panic\n//     with an index out of range.\n//\n// Use [Compile] and [Machine] for anything real: they reject a malformed\n// program up front, read input from the host, and cannot run unbounded.\nfunc Execute(code string) string {\n\tvar (\n\t\tmemory  = make([]byte, NaiveTapeSize) // memory tape\n\t\tpointer = 0                           // initial memory pointer\n\t\tbuf     strings.Builder\n\t)\n\n\t// Loop through each character in the code\n\tfor i := 0; i \u003c len(code); i++ {\n\t\tswitch code[i] {\n\t\tcase '\u003e':\n\t\t\t// Increment memory pointer\n\t\t\tpointer++\n\t\t\tif pointer \u003e= NaiveTapeSize {\n\t\t\t\tpointer = 0\n\t\t\t}\n\t\tcase '\u003c':\n\t\t\t// Decrement memory pointer\n\t\t\tpointer--\n\t\t\tif pointer \u003c 0 {\n\t\t\t\tpointer = NaiveTapeSize - 1\n\t\t\t}\n\t\tcase '+':\n\t\t\t// Increment the byte at the memory pointer\n\t\t\tmemory[pointer]++\n\t\tcase '-':\n\t\t\t// Decrement the byte at the memory pointer\n\t\t\tmemory[pointer]--\n\t\tcase '.':\n\t\t\t// Output the byte at the memory pointer\n\t\t\tbuf.WriteByte(memory[pointer])\n\t\tcase ',':\n\t\t\t// Input a byte and store it in the memory\n\t\t\tpanic(\"unsupported\")\n\t\tcase '[':\n\t\t\t// Jump forward past the matching ']' if the byte at the memory pointer is zero\n\t\t\tif memory[pointer] == 0 {\n\t\t\t\tbraceCount := 1\n\t\t\t\tfor braceCount \u003e 0 {\n\t\t\t\t\ti++\n\t\t\t\t\tif code[i] == '[' {\n\t\t\t\t\t\tbraceCount++\n\t\t\t\t\t} else if code[i] == ']' {\n\t\t\t\t\t\tbraceCount--\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase ']':\n\t\t\t// Jump backward to the matching '[' if the byte at the memory pointer is nonzero\n\t\t\tif memory[pointer] != 0 {\n\t\t\t\tbraceCount := 1\n\t\t\t\tfor braceCount \u003e 0 {\n\t\t\t\t\ti--\n\t\t\t\t\tif code[i] == ']' {\n\t\t\t\t\t\tbraceCount++\n\t\t\t\t\t} else if code[i] == '[' {\n\t\t\t\t\t\tbraceCount--\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti-- // Move back one more to compensate for the upcoming increment in the loop\n\t\t\t}\n\t\t}\n\t}\n\treturn buf.String()\n}\n"},{"name":"bf_test.gno","body":"package bf\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// hello is the classic 106 byte hello-world. It writes \"Hello World\", 11\n// bytes: the original run.gno comment was optimistic about the trailing \"!\\n\".\nconst hello = \"++++++++++[\u003e+++++++\u003e++++++++++\u003e+++\u003e+\u003c\u003c\u003c\u003c-]\u003e++.\u003e+.+++++++..+++.\u003e++.\u003c\u003c+++++++++++++++.\u003e.+++.------.--------.\"\n\n// corpus is the set of programs every ladder level must agree on. Each one is\n// here because it exercises a rewrite that could plausibly be wrong.\nvar corpus = []struct {\n\tname string\n\tsrc  string\n\twant string\n}{\n\t{\"empty\", \"\", \"\"},\n\t{\"comment only\", \"this is not brainfuck\", \"\"},\n\t{\"hello\", hello, \"Hello World\"},\n\t{\"clear idiom\", \"+++++[-]+++++++++++++++++++++++++++++++++++++++++++++++.\", \"/\"},\n\t{\"move idiom\", \"+++++++++++++++++++++++++++++++++++++++++++++++++++[-\u003e+\u003c]\u003e.\", \"3\"},\n\t{\"multiply idiom\", \"+++++[-\u003e++++++++++\u003c]\u003e++.\", \"4\"},\n\t{\"two targets\", \"+++[-\u003e+\u003e++\u003c\u003c]\u003e+++++++++++++++++++++++++++++++++++++++.\u003e+++++++++++++++++++++++++++++++++++++++++.\", \"*/\"},\n\t{\"scan walks\", \"\u003e+\u003e+\u003e+\u003e+[\u003c]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.\", \"H\"},\n\t{\"scan right\", \"\u003e\u003e\u003e+++++++++\u003c\u003c\u003c[\u003e]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.\", \"?\"},\n\t{\"nested loops\", \"++[\u003e++[\u003e+\u003c-]\u003c-]\u003e\u003e+++++++++++++++++++++++++++++++++++++++++++++++++.\", \"5\"},\n\t{\"dead run\", \"+++--+++--+++++++++++++++++++++++++++++++++++++++++++.\", \"-\"},\n\t{\"skipped loop\", \"[++++++++++++++++++++]+++++++++++++++++++++++++++++++++++++++++++++++.\", \"/\"},\n\t{\"wraps under zero\", \"-[\u003e+\u003c-]\u003e++++++++++.\", \"\\t\"},\n}\n\nfunc runLevel(t *testing.T, src string, lvl Level, input string) string {\n\tt.Helper()\n\tprog, err := Compile(src, lvl)\n\tuassert.NoError(t, err)\n\tif prog == nil {\n\t\treturn \"\"\n\t}\n\th := vmkit.NewTestHost().WithInput([]byte(input))\n\tm := NewMachine(prog)\n\t_, status := m.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\treturn h.OutString()\n}\n\n// TestLadderLevelsAgree is the test the whole ladder rests on: an\n// optimization that changes the output is not an optimization.\nfunc TestLadderLevelsAgree(t *testing.T) {\n\tfor _, tc := range corpus {\n\t\tnaive := Execute(tc.src)\n\t\tuassert.Equal(t, tc.want, naive)\n\n\t\tfor _, lvl := range []Level{LevelJumps, LevelFuse, LevelIdioms} {\n\t\t\tgot := runLevel(t, tc.src, lvl, \"\")\n\t\t\tif got != tc.want {\n\t\t\t\tt.Errorf(\"%s at level %s: got %q, want %q\",\n\t\t\t\t\ttc.name, lvl.String(), got, tc.want)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestExecuteBaseline(t *testing.T) {\n\t// Rung 0 is kept verbatim, so this is also a regression test on the\n\t// thing the published cycles-per-op number was measured against.\n\tuassert.Equal(t, \"Hello World\", Execute(hello))\n\tuassert.Equal(t, 11, len(Execute(hello)))\n}\n\nfunc TestCompileRejectsUnbalanced(t *testing.T) {\n\tcases := []string{\"[\", \"]\", \"[[]\", \"+[-\u003e+\u003c\", \"][\", \"[[[]]\"}\n\tfor _, src := range cases {\n\t\t_, err := CompileDefault(src)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Compile(%q) should have failed\", src)\n\t\t}\n\t}\n}\n\nfunc TestCompileRejectsOversizeSource(t *testing.T) {\n\tsrc := \"+\"\n\tfor len(src) \u003c= MaxSource {\n\t\tsrc += src // doubling, not O(n^2) appending\n\t}\n\t_, err := CompileDefault(src)\n\tuassert.ErrorIs(t, err, ErrSourceTooLong)\n}\n\nfunc TestCompileRejectsUnknownLevel(t *testing.T) {\n\t_, err := Compile(\"+\", Level(42))\n\tuassert.Error(t, err)\n\t_, err = Compile(\"+\", Level(-1))\n\tuassert.Error(t, err)\n}\n\n// TestLadderShrinksTheOpStream is the compile-time half of the ladder: each\n// rung has to produce strictly fewer ops than the one below it, or it is not\n// buying anything.\nfunc TestLadderShrinksTheOpStream(t *testing.T) {\n\tjumps, err := Compile(hello, LevelJumps)\n\tuassert.NoError(t, err)\n\tfuse, err := Compile(hello, LevelFuse)\n\tuassert.NoError(t, err)\n\tidioms, err := Compile(hello, LevelIdioms)\n\tuassert.NoError(t, err)\n\n\tuassert.True(t, jumps.Len() \u003e fuse.Len())\n\tuassert.True(t, fuse.Len() \u003e idioms.Len())\n\tuassert.Equal(t, \"jumps\", jumps.Level().String())\n\tuassert.Equal(t, hello, idioms.Source())\n}\n\nfunc TestIdiomRecognition(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tsrc  string\n\t\twant int // ops, excluding the trailing halt\n\t}{\n\t\t{\"clear\", \"[-]\", 1},                 // opSet\n\t\t{\"move\", \"[-\u003e+\u003c]\", 2},               // opAddMul, opSet\n\t\t{\"multiply two\", \"[-\u003e++\u003e+++\u003c\u003c]\", 3}, // two opAddMul, opSet\n\t\t{\"scan right\", \"[\u003e]\", 1},            // opScan\n\t\t{\"scan left\", \"[\u003c]\", 1},             // opScan\n\t}\n\tfor _, tc := range cases {\n\t\tprog, err := Compile(tc.src, LevelIdioms)\n\t\tuassert.NoError(t, err)\n\t\tif prog == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif got := prog.Len() - 1; got != tc.want {\n\t\t\tt.Errorf(\"%s: %q compiled to %d ops, want %d\",\n\t\t\t\ttc.name, tc.src, got, tc.want)\n\t\t}\n\t}\n}\n\n// TestPlusLoopIsNotRewritten pins the conservative half of the rewrite: a\n// loop that adds one per iteration still reaches zero by wrapping, but only\n// after 256 iterations, and folding it would be a different program. It has\n// to stay a real loop.\nfunc TestPlusLoopIsNotRewritten(t *testing.T) {\n\tprog, err := Compile(\"[+]\", LevelIdioms)\n\tuassert.NoError(t, err)\n\t// opJmpZ, opAdd, opJmpNZ, opHalt: untouched.\n\tuassert.Equal(t, 4, prog.Len())\n}\n\nfunc TestInputThroughTheHost(t *testing.T) {\n\t// Read three bytes and echo them back.\n\tconst echo3 = \",.,.,.\"\n\th := vmkit.NewTestHost().WithInput([]byte(\"gno\"))\n\tm, err := Load(echo3)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"gno\", h.OutString())\n}\n\nfunc TestInputEndsAsZero(t *testing.T) {\n\t// Past the end of input, `,` yields a zero cell. Without input at all,\n\t// the naive interpreter would have panicked here.\n\th := vmkit.NewTestHost().WithInput([]byte(\"a\"))\n\tm, err := Load(\",.+++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++.\")\n\tuassert.NoError(t, err)\n\t_, status := m.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"a\\x901\", h.OutString())\n}\n\nfunc TestExecutePanicsOnInput(cur realm, t *testing.T) {\n\t// Rung 0's second preserved bug, pinned so nobody \"fixes\" the baseline.\n\tuassert.PanicsWithMessage(t, cur, \"unsupported\", func() { Execute(\",\") })\n}\n\nfunc TestMachineWithoutProgram(t *testing.T) {\n\tm := \u0026Machine{status: vmkit.Running}\n\tused, status := m.Step(vmkit.NewTestHost(), 10)\n\tuassert.Equal(t, int64(0), used)\n\tuassert.Equal(t, \"trapped\", status.String())\n\tuassert.Equal(t, \"no program\", m.Trap())\n}\n"},{"name":"compile.gno","body":"package bf\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// TapeSize is the tape length of a compiled [Machine]. It matches\n// [NaiveTapeSize] so that the ladder compares like with like: a rung that\n// changed the semantics would not be a rung, it would be a different program.\nconst TapeSize = 30000\n\n// MaxSource bounds the program a realm will accept. Compilation is linear in\n// the source, but the op array and every snapshot of it are consensus state,\n// so the size has to be bounded somewhere the caller can see.\nconst MaxSource = 64 * 1024\n\n// ErrSourceTooLong is returned by [Compile] for a program above [MaxSource].\nvar ErrSourceTooLong = errors.New(\"bf: source too long\")\n\n// Level selects how far up the optimization ladder [Compile] goes.\n//\n// Every level produces the same output for the same program: the levels exist\n// so the cost of each optimization can be measured in isolation, which is the\n// published result this package is really for. Rung 0 of the ladder is\n// [Execute] and has no compiler at all.\ntype Level int\n\nconst (\n\t// LevelJumps is rung 1: one op per source byte, with the jump targets\n\t// resolved at compile time. This is the rung that kills the brace\n\t// rescan, which in [Execute] costs O(loop body) on every iteration.\n\tLevelJumps Level = iota\n\n\t// LevelFuse is rung 2: runs of identical operators collapse, so\n\t// \"+++++\" is one add-5 and \"\u003e\u003e\u003e\" is one move-3. Real programs are\n\t// mostly runs.\n\tLevelFuse\n\n\t// LevelIdioms is rung 3: a loop whose body only moves and adds, and\n\t// which returns to where it started while decrementing the current\n\t// cell by one, is replaced by the multiply-adds it performs plus a\n\t// clear. \"[-]\" becomes one op, \"[-\u003e+\u003c]\" becomes two.\n\tLevelIdioms\n)\n\n// Default is the level [CompileDefault] uses, and the one a realm should\n// want: every optimization this package knows, same semantics.\nconst Default = LevelIdioms\n\n// String names the level, for the ladder table and for realm output.\nfunc (l Level) String() string {\n\tswitch l {\n\tcase LevelJumps:\n\t\treturn \"jumps\"\n\tcase LevelFuse:\n\t\treturn \"fuse\"\n\tcase LevelIdioms:\n\t\treturn \"idioms\"\n\t}\n\treturn \"unknown\"\n}\n\ntype opcode byte\n\nconst (\n\topAdd    opcode = iota // tape[p] += arg           (arg normalized to 0..255)\n\topMove                 // p += arg\n\topOut                  // write tape[p] to the host\n\topIn                   // read one input byte into tape[p]\n\topJmpZ                 // if tape[p] == 0 { pc = arg }\n\topJmpNZ                // if tape[p] != 0 { pc = arg }\n\topSet                  // tape[p] = byte(arg)\n\topAddMul               // tape[p+off] += tape[p] * byte(arg)\n\topScan                 // while tape[p] != 0 { p += arg }\n\topHalt                 // end of program\n)\n\n// op is one compiled instruction. It is a flat struct on purpose: the\n// execution loop indexes an array of these, and an op that owned a slice\n// would allocate in the hot path.\ntype op struct {\n\tcode opcode\n\targ  int\n\toff  int\n}\n\n// Program is compiled Brainfuck, ready to run on a [Machine].\ntype Program struct {\n\tops   []op\n\tsrc   string\n\tlevel Level\n}\n\n// Source returns the program text the [Program] was compiled from.\nfunc (p *Program) Source() string { return p.src }\n\n// Level returns the ladder rung this program was compiled at.\nfunc (p *Program) Level() Level { return p.level }\n\n// Len returns the number of compiled ops, including the trailing halt. It is\n// the number worth quoting next to the source length: the ratio is exactly\n// what the ladder buys.\nfunc (p *Program) Len() int { return len(p.ops) }\n\n// CompileDefault compiles at [Default].\nfunc CompileDefault(src string) (*Program, error) { return Compile(src, Default) }\n\n// Compile turns Brainfuck source into a [Program] at the requested ladder\n// level. Everything that is not one of the eight operators is a comment, as\n// the language requires.\n//\n// It fails on unbalanced brackets rather than trusting the runtime to notice,\n// which is the first thing that separates it from [Execute]: a malformed\n// program is rejected before anybody pays to run it.\nfunc Compile(src string, lvl Level) (*Program, error) {\n\tif len(src) \u003e MaxSource {\n\t\treturn nil, ErrSourceTooLong\n\t}\n\tif lvl \u003c LevelJumps || lvl \u003e LevelIdioms {\n\t\treturn nil, ufmt.Errorf(\"bf: unknown level %d\", int(lvl))\n\t}\n\n\tops := []op{}\n\topens := []int{} // pc of each unclosed opJmpZ\n\n\tfor i := 0; i \u003c len(src); i++ {\n\t\tc := src[i]\n\t\tswitch c {\n\t\tcase '+', '-':\n\t\t\tdelta := 1\n\t\t\tif c == '-' {\n\t\t\t\tdelta = -1\n\t\t\t}\n\t\t\tif lvl \u003e= LevelFuse {\n\t\t\t\tn := 1\n\t\t\t\tfor i+n \u003c len(src) \u0026\u0026 (src[i+n] == '+' || src[i+n] == '-') {\n\t\t\t\t\tif src[i+n] == '+' {\n\t\t\t\t\t\tdelta++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelta--\n\t\t\t\t\t}\n\t\t\t\t\tn++\n\t\t\t\t}\n\t\t\t\ti += n - 1\n\t\t\t}\n\t\t\tif a := normAdd(delta); a != 0 {\n\t\t\t\tops = append(ops, op{code: opAdd, arg: a})\n\t\t\t}\n\t\tcase '\u003e', '\u003c':\n\t\t\tdelta := 1\n\t\t\tif c == '\u003c' {\n\t\t\t\tdelta = -1\n\t\t\t}\n\t\t\tif lvl \u003e= LevelFuse {\n\t\t\t\tn := 1\n\t\t\t\tfor i+n \u003c len(src) \u0026\u0026 (src[i+n] == '\u003e' || src[i+n] == '\u003c') {\n\t\t\t\t\tif src[i+n] == '\u003e' {\n\t\t\t\t\t\tdelta++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelta--\n\t\t\t\t\t}\n\t\t\t\t\tn++\n\t\t\t\t}\n\t\t\t\ti += n - 1\n\t\t\t}\n\t\t\tif d := normMove(delta); d != 0 {\n\t\t\t\tops = append(ops, op{code: opMove, arg: d})\n\t\t\t}\n\t\tcase '.':\n\t\t\tops = append(ops, op{code: opOut})\n\t\tcase ',':\n\t\t\tops = append(ops, op{code: opIn})\n\t\tcase '[':\n\t\t\topens = append(opens, len(ops))\n\t\t\tops = append(ops, op{code: opJmpZ})\n\t\tcase ']':\n\t\t\tif len(opens) == 0 {\n\t\t\t\treturn nil, ufmt.Errorf(\"bf: unmatched ']' at byte %d\", i)\n\t\t\t}\n\t\t\topen := opens[len(opens)-1]\n\t\t\topens = opens[:len(opens)-1]\n\n\t\t\tif lvl \u003e= LevelIdioms {\n\t\t\t\tif idiom, ok := simpleLoop(ops[open+1:]); ok {\n\t\t\t\t\tops = append(ops[:open], idiom...)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// pc lands on the op after the jump, so a jump target is\n\t\t\t// the index of the partner op itself.\n\t\t\tops = append(ops, op{code: opJmpNZ, arg: open})\n\t\t\tops[open].arg = len(ops) - 1\n\t\t}\n\t}\n\tif len(opens) != 0 {\n\t\treturn nil, ufmt.Errorf(\"bf: %d unmatched '['\", len(opens))\n\t}\n\n\tops = append(ops, op{code: opHalt})\n\treturn \u0026Program{ops: ops, src: src, level: lvl}, nil\n}\n\n// normAdd folds a signed delta into the 0..255 the byte tape actually sees,\n// so the execution loop never has to convert a negative int to a byte.\nfunc normAdd(d int) int {\n\td %= 256\n\tif d \u003c 0 {\n\t\td += 256\n\t}\n\treturn d\n}\n\n// normMove folds a pointer delta into one lap of the tape. Moving right\n// TapeSize times is a no-op on a wrapping tape, in the naive interpreter as\n// much as here, so collapsing it changes nothing but the op count.\nfunc normMove(d int) int {\n\td %= TapeSize\n\tif d \u003c 0 {\n\t\td += TapeSize\n\t}\n\tif d \u003e TapeSize/2 {\n\t\td -= TapeSize\n\t}\n\treturn d\n}\n\n// cell is one offset the body of a simple loop writes to.\ntype cell struct {\n\toff   int\n\tdelta int\n}\n\n// simpleLoop decides whether a loop body can be replaced by straight-line\n// code, and returns that code.\n//\n// Two shapes qualify, and they are the two that dominate real programs:\n//\n//   - The body only moves, and ends somewhere other than where it started:\n//     that is a scan, \"[\u003e]\" walking to the next zero cell.\n//   - The body only moves and adds, ends where it started, and takes exactly\n//     one off the current cell: that is a multiply-add. The loop runs\n//     tape[p] times, so every other cell it touches gains its delta times\n//     tape[p], and the current cell ends at zero. \"[-]\" is the degenerate\n//     case with no other cells.\n//\n// Anything else, including any body containing I/O or a nested loop that was\n// itself rewritten, is left alone. Being conservative here costs a few ops in\n// rare programs and is the only reason this rewrite is safe at all: a loop\n// whose current cell does not reach zero in steps of one is not guaranteed to\n// terminate, and constant-folding it would change the program.\nfunc simpleLoop(body []op) ([]op, bool) {\n\tcursor := 0\n\tcells := []cell{}\n\tadds := 0\n\n\tfor _, o := range body {\n\t\tswitch o.code {\n\t\tcase opMove:\n\t\t\tcursor += o.arg\n\t\tcase opAdd:\n\t\t\tadds++\n\t\t\t// Carry the delta as a signed value; it is normalized\n\t\t\t// back into 0..255 when it is emitted.\n\t\t\td := o.arg\n\t\t\tif d \u003e 128 {\n\t\t\t\td -= 256\n\t\t\t}\n\t\t\tcells = addCell(cells, cursor, d)\n\t\tdefault:\n\t\t\treturn nil, false\n\t\t}\n\t}\n\n\tif cursor != 0 {\n\t\t// Net movement: only a pure scan qualifies, and only when the\n\t\t// step is not zero (which normMove already guarantees here).\n\t\tif adds != 0 {\n\t\t\treturn nil, false\n\t\t}\n\t\treturn []op{{code: opScan, arg: cursor}}, true\n\t}\n\n\t// Balanced. The current cell must fall by exactly one per iteration,\n\t// or the loop is not a counted multiply-add.\n\tif delta(cells, 0) != -1 {\n\t\treturn nil, false\n\t}\n\n\tout := []op{}\n\tfor _, c := range cells {\n\t\tif c.off == 0 || c.delta == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, op{code: opAddMul, arg: normAdd(c.delta), off: c.off})\n\t}\n\tout = append(out, op{code: opSet, arg: 0})\n\treturn out, true\n}\n\n// addCell accumulates a delta at an offset, keeping cells sorted by offset so\n// that the op stream a program compiles to is identical on every node.\nfunc addCell(cells []cell, off, d int) []cell {\n\tfor i := range cells {\n\t\tif cells[i].off == off {\n\t\t\tcells[i].delta += d\n\t\t\treturn cells\n\t\t}\n\t\tif cells[i].off \u003e off {\n\t\t\tcells = append(cells, cell{})\n\t\t\tcopy(cells[i+1:], cells[i:])\n\t\t\tcells[i] = cell{off: off, delta: d}\n\t\t\treturn cells\n\t\t}\n\t}\n\treturn append(cells, cell{off: off, delta: d})\n}\n\nfunc delta(cells []cell, off int) int {\n\tfor _, c := range cells {\n\t\tif c.off == off {\n\t\t\treturn c.delta\n\t\t}\n\t}\n\treturn 0\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/vm/bf/v0\"\ngno = \"0.9\"\n"},{"name":"ladder_test.gno","body":"package bf\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// heavy is the benchmark program: 200 increments, then an outer loop that on\n// each of its 200 iterations moves right, adds 200, clears that cell with the\n// \"[-]\" idiom, and moves back.\n//\n// It writes nothing, so a measurement of it is a measurement of the dispatch\n// loop and not of the output path.\nvar heavy = rep(\"+\", 200) + \"[\" + \"-\" + \"\u003e\" + rep(\"+\", 200) + \"[-]\" + \"\u003c\" + \"]\"\n\n// GuestOps and NaiveDispatches are the two counts for [heavy], and the\n// difference between them is the reason the ladder needs both named.\n//\n// A guest instruction is one operator the language executes, counted the way\n// any jump-table interpreter counts it. The naive interpreter dispatches more\n// often than that for the same program: its \"]\" handler scans back to the\n// matching \"[\" and lands on it, so \"[\" is re-evaluated on every iteration of\n// every loop. On heavy that is 1.33 dispatches per guest instruction.\n//\n// Rung 1 removes exactly that excess, so a ladder that used the naive\n// dispatch count as its denominator would be crediting rung 1 twice. Both\n// numbers come from an independent simulator, not from this package, so the\n// denominator is not derived from the thing being measured.\nconst (\n\tGuestOps        = 121201\n\tNaiveDispatches = 161200\n)\n\nfunc rep(s string, n int) string {\n\tout := \"\"\n\tfor i := 0; i \u003c n; i++ {\n\t\tout += s\n\t}\n\treturn out\n}\n\n// nullHost is a Host that costs as close to nothing as a Host can, so the\n// ladder measures the dispatch loop rather than the storage or output path.\ntype nullHost struct{}\n\nfunc (nullHost) Caller() address                     { return address(\"\") }\nfunc (nullHost) Origin() address                     { return address(\"\") }\nfunc (nullHost) Now() int64                          { return 0 }\nfunc (nullHost) Height() int64                       { return 0 }\nfunc (nullHost) Get(key []byte) []byte               { return nil }\nfunc (nullHost) Set(key, val []byte)                 {}\nfunc (nullHost) Input() []byte                       { return nil }\nfunc (nullHost) Output(p []byte)                     {}\nfunc (nullHost) Emit(typ string, kv ...string)       {}\nfunc (nullHost) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\nfunc (nullHost) Log(msg string)                      {}\n\n// runHeavy compiles heavy at lvl and runs it on the shipped machine,\n// returning how many machine ops it executed. The count is the fuel the\n// machine charged itself, so the ladder's \"machine ops\" column is measured by\n// the machine and not counted by hand.\nfunc runHeavy(t *testing.T, lvl Level) int64 {\n\tt.Helper()\n\tprog, err := Compile(heavy, lvl)\n\tuassert.NoError(t, err)\n\tif prog == nil {\n\t\treturn 0\n\t}\n\tm := NewMachine(prog)\n\tused, status := m.Step(nullHost{}, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\treturn used\n}\n\n// The rungs. One test each, so `gno test -print-runtime-metrics` prints one\n// cycle count per rung and the README's table is a transcription rather than\n// an estimate. They assert that the run completed and how many machine ops it\n// took: what is being recorded is the metric line.\n\nfunc TestRung0Naive(t *testing.T) {\n\tuassert.Equal(t, \"\", Execute(heavy))\n}\n\nfunc TestRung0Naive4x(t *testing.T) {\n\tfor i := 0; i \u003c 4; i++ {\n\t\tExecute(heavy)\n\t}\n}\n\nfunc TestRung1Jumps(t *testing.T) {\n\tuassert.Equal(t, int64(GuestOps+1), runHeavy(t, LevelJumps))\n}\n\nfunc TestRung2Fuse(t *testing.T) {\n\tuassert.True(t, runHeavy(t, LevelFuse) \u003c GuestOps)\n}\n\nfunc TestRung3Idioms(t *testing.T) {\n\tuassert.True(t, runHeavy(t, LevelIdioms) \u003c GuestOps)\n}\n\nfunc TestRung3Idioms4x(t *testing.T) {\n\tfor i := 0; i \u003c 4; i++ {\n\t\trunHeavy(t, LevelIdioms)\n\t}\n}\n\nfunc TestRung5Metered(t *testing.T) {\n\t// Same program, same rung, but every op goes through the fuel meter's\n\t// budget branch instead of its unmetered one. The delta against\n\t// TestRung3Idioms is the price of being a machine that can be stopped.\n\tprog, err := Compile(heavy, LevelIdioms)\n\tuassert.NoError(t, err)\n\tm := NewMachine(prog)\n\t_, status := m.Step(nullHost{}, 1\u003c\u003c40)\n\tuassert.Equal(t, \"halted\", status.String())\n}\n\n// TestLadderOpCounts records the compile-time half of the ladder: how many\n// machine ops each rung executes for the same 121,201 guest instructions.\n// These are the numbers the README's table quotes, asserted here so the table\n// cannot silently go stale.\nfunc TestLadderOpCounts(t *testing.T) {\n\tjumps := runHeavy(t, LevelJumps)\n\tfuse := runHeavy(t, LevelFuse)\n\tidioms := runHeavy(t, LevelIdioms)\n\n\t// Rung 1 executes exactly one machine op per guest instruction, plus\n\t// the halt: the independent simulator and this machine agree to the op.\n\tuassert.Equal(t, int64(121202), jumps)\n\t// Fusing runs of + and \u003e collapses the two 200-long runs.\n\tuassert.Equal(t, int64(81203), fuse)\n\t// Recognizing \"[-]\" turns the inner clear loop into a single op.\n\tuassert.Equal(t, int64(1203), idioms)\n\n\tuassert.True(t, fuse \u003c jumps)\n\tuassert.True(t, idioms \u003c fuse)\n}\n"},{"name":"machine.gno","body":"package bf\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n)\n\n// VMName is the identifier this machine registers under in a\n// [vmkit.Instance].\nconst VMName = \"bf\"\n\n// snapMagic and snapVersion tag a snapshot so a machine refuses bytes that\n// were not written by this machine at this version, instead of decoding them\n// into a plausible-looking wrong state.\nconst (\n\tsnapMagic   uint32 = 0x62660001 // \"bf\" 0001\n\tsnapVersion byte   = 1\n)\n\n// ErrNoProgram is returned when a [Machine] is stepped without a program.\nvar ErrNoProgram = errors.New(\"bf: machine has no program\")\n\n// Machine is a compiled Brainfuck program, mid-execution: a\n// [vmkit.Machine] with a fixed tape, a fuel-metered step loop, input and\n// output through the host, and a snapshot small enough that pausing is\n// cheaper than starting over.\n//\n// The tape is a fixed-size array rather than a slice: that is rung 4 of the\n// ladder, and the README reports what it actually bought.\ntype Machine struct {\n\tprog *Program\n\n\ttape  [TapeSize]byte\n\tptr   int\n\tpc    int\n\tinPos int // read cursor into Host.Input, carried across slices\n\n\tstatus vmkit.Status\n\ttrap   string\n\n\t// hi is the highest tape index written so far, so a snapshot can stop\n\t// there instead of carrying 30,000 bytes of zeros.\n\thi int\n}\n\n// NewMachine returns a machine ready to run prog from the start.\nfunc NewMachine(prog *Program) *Machine {\n\treturn \u0026Machine{prog: prog, status: vmkit.Running}\n}\n\n// Load compiles src at [Default] and returns a machine for it.\nfunc Load(src string) (*Machine, error) {\n\tprog, err := CompileDefault(src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewMachine(prog), nil\n}\n\n// Program returns the program the machine is running.\nfunc (m *Machine) Program() *Program { return m.prog }\n\n// Status returns the machine's current status.\nfunc (m *Machine) Status() vmkit.Status { return m.status }\n\n// Trap returns the reason the machine trapped, or \"\". It makes Machine a\n// [vmkit.Trapper].\nfunc (m *Machine) Trap() string { return m.trap }\n\n// Pointer returns the tape pointer.\nfunc (m *Machine) Pointer() int { return m.ptr }\n\n// PC returns the index of the next op to execute.\nfunc (m *Machine) PC() int { return m.pc }\n\n// Cell returns the tape byte at i, wrapped into range.\nfunc (m *Machine) Cell(i int) byte { return m.tape[wrap(i)] }\n\n// Touched returns how many tape cells the program has reached, which is the\n// length a snapshot has to carry.\nfunc (m *Machine) Touched() int { return m.hi + 1 }\n\n// Step runs until the program halts, traps, or spends `fuel` units, charging\n// one unit per op executed and one per cell a scan walks over. Pass\n// [vmkit.Unmetered] to run to completion.\n//\n// Fuel is charged before the op runs, so a machine that stops for lack of\n// fuel has not half-executed anything: it is exactly at the op it could not\n// pay for, and resuming re-executes that op and nothing else.\n//\n// Three things in here are written the way they are because the alternative\n// was measured and lost. The README has the table.\n//\n//   - The fuel counter is two locals, not a [vmkit.Meter]. Calling\n//     Meter.Charge once per instruction costs 86% on top of the whole\n//     dispatch loop and triples the allocation count. Meter stays the type\n//     at the API boundary, where it is called once; it is not a hot-path\n//     type, and no guest VM should treat it as one.\n//   - The program counter and the tape pointer are locals, written back once\n//     by the deferred closure. Reaching through m. for them on every\n//     instruction costs 16%.\n//   - The pc range check happens once, before the loop, not per op. Every\n//     jump target is produced by [Compile] and every restored pc is\n//     validated by [Machine.Restore], so per-op checking buys nothing.\nfunc (m *Machine) Step(h vmkit.Host, fuel int64) (int64, vmkit.Status) {\n\tif m.prog == nil {\n\t\tm.status, m.trap = vmkit.Trapped, \"no program\"\n\t\treturn 0, m.status\n\t}\n\tif m.status != vmkit.Running {\n\t\treturn 0, m.status\n\t}\n\n\tops := m.prog.ops\n\tpc, ptr, hi := m.pc, m.ptr, m.hi\n\t// One write-back, on every return path, including a panic.\n\tdefer func() { m.pc, m.ptr, m.hi = pc, ptr, hi }()\n\n\tif pc \u003c 0 || pc \u003e= len(ops) {\n\t\tm.status, m.trap = vmkit.Trapped, \"pc out of range\"\n\t\treturn 0, m.status\n\t}\n\n\t// budget \u003c 0 is vmkit.Unmetered.\n\tbudget := fuel\n\tif budget \u003c 0 {\n\t\tbudget = vmkit.Unmetered\n\t}\n\tvar used int64\n\n\tfor {\n\t\tif budget != vmkit.Unmetered \u0026\u0026 used \u003e= budget {\n\t\t\treturn used, vmkit.Running\n\t\t}\n\t\tused++\n\n\t\tswitch ops[pc].code {\n\t\tcase opAdd:\n\t\t\tm.tape[ptr] += byte(ops[pc].arg)\n\t\tcase opMove:\n\t\t\tptr = wrap(ptr + ops[pc].arg)\n\t\t\tif ptr \u003e hi {\n\t\t\t\thi = ptr\n\t\t\t}\n\t\tcase opSet:\n\t\t\tm.tape[ptr] = byte(ops[pc].arg)\n\t\tcase opAddMul:\n\t\t\tif v := m.tape[ptr]; v != 0 {\n\t\t\t\tt := wrap(ptr + ops[pc].off)\n\t\t\t\tm.tape[t] += v * byte(ops[pc].arg)\n\t\t\t\tif t \u003e hi {\n\t\t\t\t\thi = t\n\t\t\t\t}\n\t\t\t}\n\t\tcase opScan:\n\t\t\t// A scan is charged per cell, so it cannot be a way to\n\t\t\t// buy unbounded work for one unit of fuel. Stopping\n\t\t\t// mid-scan is safe: the pointer has moved, the pc has\n\t\t\t// not, so resuming continues the same walk.\n\t\t\tfor m.tape[ptr] != 0 {\n\t\t\t\tif budget != vmkit.Unmetered \u0026\u0026 used \u003e= budget {\n\t\t\t\t\treturn used, vmkit.Running\n\t\t\t\t}\n\t\t\t\tused++\n\t\t\t\tptr = wrap(ptr + ops[pc].arg)\n\t\t\t\tif ptr \u003e hi {\n\t\t\t\t\thi = ptr\n\t\t\t\t}\n\t\t\t}\n\t\tcase opOut:\n\t\t\th.Output([]byte{m.tape[ptr]})\n\t\tcase opIn:\n\t\t\tin := h.Input()\n\t\t\tif m.inPos \u003c len(in) {\n\t\t\t\tm.tape[ptr] = in[m.inPos]\n\t\t\t\tm.inPos++\n\t\t\t} else {\n\t\t\t\t// End of input is a zero cell, the most common\n\t\t\t\t// of the three conventions the language never\n\t\t\t\t// settled.\n\t\t\t\tm.tape[ptr] = 0\n\t\t\t}\n\t\tcase opJmpZ:\n\t\t\tif m.tape[ptr] == 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opJmpNZ:\n\t\t\tif m.tape[ptr] != 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opHalt:\n\t\t\tm.status = vmkit.Halted\n\t\t\treturn used, m.status\n\t\tdefault:\n\t\t\tm.status, m.trap = vmkit.Trapped, \"unknown opcode\"\n\t\t\treturn used, m.status\n\t\t}\n\t\tpc++\n\t}\n}\n\n// Snapshot serializes the machine. The tape is truncated at the highest cell\n// the program has reached, which is what makes pausing affordable: a hello\n// world that touched six cells snapshots six bytes of tape, not 30,000.\nfunc (m *Machine) Snapshot() []byte {\n\tw := vmkit.NewWriter(m.hi + 48)\n\tw.Uint32(snapMagic)\n\tw.Byte(snapVersion)\n\tw.Int(int64(m.pc))\n\tw.Int(int64(m.ptr))\n\tw.Int(int64(m.inPos))\n\tw.Byte(byte(m.status))\n\tw.String(m.trap)\n\n\tn := m.hi + 1\n\tif n \u003e TapeSize {\n\t\tn = TapeSize\n\t}\n\tw.Bytes(m.tape[:n])\n\treturn w.Out()\n}\n\n// Restore loads a snapshot into a machine that already carries the program\n// the snapshot was taken from. The program is not in the snapshot: a realm\n// stores it once, beside the instance, instead of once per pause.\nfunc (m *Machine) Restore(b []byte) error {\n\tr := vmkit.NewReader(b)\n\tif r.Uint32() != snapMagic {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\tif r.Byte() != snapVersion {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\tpc := int(r.Int())\n\tptr := int(r.Int())\n\tinPos := int(r.Int())\n\tstatus := vmkit.Status(r.Byte())\n\ttrap := r.String()\n\ttape := r.Bytes()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\tif len(tape) \u003e TapeSize || ptr \u003c 0 || ptr \u003e= TapeSize || inPos \u003c 0 {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\tif m.prog != nil \u0026\u0026 (pc \u003c 0 || pc \u003e len(m.prog.ops)) {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\n\tm.pc, m.ptr, m.inPos = pc, ptr, inPos\n\tm.status, m.trap = status, trap\n\t// Zero only what this machine could have written: hi bounds every\n\t// write it has made, and a 30,000 element composite literal is not\n\t// something to put in a restore path.\n\tfor i := 0; i \u003c= m.hi \u0026\u0026 i \u003c TapeSize; i++ {\n\t\tm.tape[i] = 0\n\t}\n\tcopy(m.tape[:], tape)\n\tm.hi = len(tape) - 1\n\tif m.hi \u003c 0 {\n\t\tm.hi = 0\n\t}\n\treturn nil\n}\n\n// Run compiles src at [Default] and runs it to completion against h, with no\n// fuel bound. It is the one-shot path: convenient for a test or a small\n// program, and exactly the thing a realm should not do with untrusted input.\nfunc Run(src string, h vmkit.Host) (vmkit.Status, error) {\n\tm, err := Load(src)\n\tif err != nil {\n\t\treturn vmkit.Trapped, err\n\t}\n\t_, status := m.Step(h, vmkit.Unmetered)\n\treturn status, nil\n}\n\n// wrap folds a tape index into range, the way the naive interpreter does one\n// step at a time.\nfunc wrap(i int) int {\n\ti %= TapeSize\n\tif i \u003c 0 {\n\t\ti += TapeSize\n\t}\n\treturn i\n}\n"},{"name":"machine_test.gno","body":"package bf\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// oneShot runs src to completion and returns what it wrote.\nfunc oneShot(t *testing.T, src string) string {\n\tt.Helper()\n\th := vmkit.NewTestHost()\n\tstatus, err := Run(src, h)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"halted\", status.String())\n\treturn h.OutString()\n}\n\n// TestSlicedRunEqualsOneShot is the property that makes a guest program a\n// contract rather than a function call: chopping the execution into fuel\n// slices, snapshotting between each, must produce exactly the single run.\nfunc TestSlicedRunEqualsOneShot(t *testing.T) {\n\tfor _, slice := range []int64{1, 2, 7, 64} {\n\t\tprog, err := CompileDefault(hello)\n\t\tuassert.NoError(t, err)\n\n\t\th := vmkit.NewTestHost()\n\t\tsnap := []byte(nil)\n\t\tstatus := vmkit.Running\n\t\tslices := 0\n\t\tfor status == vmkit.Running \u0026\u0026 slices \u003c 10000 {\n\t\t\tm := NewMachine(prog) // a realm holds bytes, not a machine\n\t\t\tif snap != nil {\n\t\t\t\tuassert.NoError(t, m.Restore(snap))\n\t\t\t}\n\t\t\t_, status = m.Step(h, slice)\n\t\t\tsnap = m.Snapshot()\n\t\t\tslices++\n\t\t}\n\t\tuassert.Equal(t, \"halted\", status.String())\n\t\tuassert.Equal(t, \"Hello World\", h.OutString())\n\t}\n}\n\nfunc TestSlicedRunAgreesAcrossTheCorpus(t *testing.T) {\n\tfor _, tc := range corpus {\n\t\tprog, err := CompileDefault(tc.src)\n\t\tuassert.NoError(t, err)\n\t\tif prog == nil {\n\t\t\tcontinue\n\t\t}\n\t\th := vmkit.NewTestHost()\n\t\tsnap := []byte(nil)\n\t\tstatus := vmkit.Running\n\t\tn := 0\n\t\tfor status == vmkit.Running \u0026\u0026 n \u003c 20000 {\n\t\t\tm := NewMachine(prog)\n\t\t\tif snap != nil {\n\t\t\t\tuassert.NoError(t, m.Restore(snap))\n\t\t\t}\n\t\t\t_, status = m.Step(h, 3)\n\t\t\tsnap = m.Snapshot()\n\t\t\tn++\n\t\t}\n\t\tif h.OutString() != tc.want {\n\t\t\tt.Errorf(\"%s sliced: got %q, want %q\", tc.name, h.OutString(), tc.want)\n\t\t}\n\t}\n}\n\nfunc TestFuelStopsTheMachine(t *testing.T) {\n\tprog, err := CompileDefault(hello)\n\tuassert.NoError(t, err)\n\tm := NewMachine(prog)\n\th := vmkit.NewTestHost()\n\n\tused, status := m.Step(h, 5)\n\tuassert.Equal(t, int64(5), used)\n\tuassert.Equal(t, \"running\", status.String())\n\tuassert.Equal(t, \"\", h.OutString()) // not far enough to print anything\n}\n\n// TestScanIsChargedPerCell pins the thing that would otherwise be a way to\n// buy unbounded work for one unit: a scan walks one cell per unit of fuel,\n// and stopping mid-scan resumes the same walk.\nfunc TestScanIsChargedPerCell(t *testing.T) {\n\t// 20 non-zero cells, then scan left back to the zero at cell 0.\n\tsrc := \"\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+\u003e+[\u003c]\"\n\tprog, err := CompileDefault(src)\n\tuassert.NoError(t, err)\n\n\tm := NewMachine(prog)\n\th := vmkit.NewTestHost()\n\tused, status := m.Step(h, 45)\n\tuassert.Equal(t, int64(45), used)\n\tuassert.Equal(t, \"running\", status.String())\n\tuassert.True(t, m.Pointer() \u003e 0) // stopped part way down the scan\n\n\t// Resuming finishes the same walk and lands on the zero cell.\n\t_, status = m.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, 0, m.Pointer())\n}\n\nfunc TestSnapshotRoundTrip(t *testing.T) {\n\tprog, err := CompileDefault(hello)\n\tuassert.NoError(t, err)\n\n\ta := NewMachine(prog)\n\th := vmkit.NewTestHost()\n\ta.Step(h, 40)\n\n\tb := NewMachine(prog)\n\tuassert.NoError(t, b.Restore(a.Snapshot()))\n\tuassert.Equal(t, a.PC(), b.PC())\n\tuassert.Equal(t, a.Pointer(), b.Pointer())\n\tuassert.Equal(t, a.Touched(), b.Touched())\n\tfor i := 0; i \u003c a.Touched(); i++ {\n\t\tuassert.Equal(t, uint64(a.Cell(i)), uint64(b.Cell(i)))\n\t}\n\tuassert.Equal(t, string(a.Snapshot()), string(b.Snapshot()))\n}\n\n// TestSnapshotIsTrimmed is the continuation kill criterion in test form: if a\n// pause carried the whole 30,000 byte tape, resuming would cost more than\n// re-running and continuations would be theater.\nfunc TestSnapshotIsTrimmed(t *testing.T) {\n\tm, err := Load(hello)\n\tuassert.NoError(t, err)\n\th := vmkit.NewTestHost()\n\tm.Step(h, vmkit.Unmetered)\n\n\tuassert.Equal(t, 5, m.Touched()) // hello world uses five cells\n\tsnap := m.Snapshot()\n\t// 4 magic + 1 version + 3x8 zig-zag ints + 1 status + 4 empty trap\n\t// + 4 length + 5 tape. The README quotes this number.\n\tuassert.Equal(t, 43, len(snap))\n\tuassert.True(t, len(snap) \u003c TapeSize/100)\n}\n\nfunc TestRestoreRejectsJunk(t *testing.T) {\n\tprog, err := CompileDefault(hello)\n\tuassert.NoError(t, err)\n\tgood := NewMachine(prog)\n\tgood.Step(vmkit.NewTestHost(), 20)\n\tsnap := good.Snapshot()\n\n\tcases := []struct {\n\t\tname string\n\t\tb    []byte\n\t}{\n\t\t{\"empty\", []byte{}},\n\t\t{\"truncated\", snap[:len(snap)-3]},\n\t\t{\"bad magic\", append([]byte{0, 0, 0, 0}, snap[4:]...)},\n\t}\n\tfor _, tc := range cases {\n\t\tm := NewMachine(prog)\n\t\tif err := m.Restore(tc.b); err == nil {\n\t\t\tt.Errorf(\"Restore(%s) should have failed\", tc.name)\n\t\t}\n\t}\n\n\t// A snapshot with a wrong version byte is refused rather than decoded\n\t// into a plausible-looking wrong state.\n\tbad := make([]byte, len(snap))\n\tcopy(bad, snap)\n\tbad[4] = 99\n\tm := NewMachine(prog)\n\tuassert.ErrorIs(t, m.Restore(bad), vmkit.ErrBadSnapshot)\n}\n\nfunc TestRestoreRejectsAnOutOfRangePC(t *testing.T) {\n\tsmall, err := CompileDefault(\"+\")\n\tuassert.NoError(t, err)\n\tbig, err := CompileDefault(hello)\n\tuassert.NoError(t, err)\n\n\tm := NewMachine(big)\n\tm.Step(vmkit.NewTestHost(), 30)\n\tsnap := m.Snapshot()\n\n\t// The same snapshot against a two-op program points past the end.\n\tother := NewMachine(small)\n\tuassert.ErrorIs(t, other.Restore(snap), vmkit.ErrBadSnapshot)\n}\n\nfunc TestHaltedMachineStaysHalted(t *testing.T) {\n\tm, err := Load(\"+++.\")\n\tuassert.NoError(t, err)\n\th := vmkit.NewTestHost()\n\tm.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", m.Status().String())\n\n\tused, status := m.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, int64(0), used)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"\\x03\", h.OutString()) // still only one write\n}\n\nfunc TestLoadRejectsBadSource(t *testing.T) {\n\t_, err := Load(\"[[\")\n\tuassert.Error(t, err)\n\tstatus, err := Run(\"]\", vmkit.NewTestHost())\n\tuassert.Error(t, err)\n\tuassert.Equal(t, \"trapped\", status.String())\n}\n\n// TestInstanceIntegration wires the machine through vmkit's realm-facing\n// plumbing, which is the shape the demo realm uses.\nfunc TestInstanceIntegration(t *testing.T) {\n\tprog, err := CompileDefault(hello)\n\tuassert.NoError(t, err)\n\n\tinst := vmkit.NewInstance(\"001\", address(\"g1x\"), VMName, []byte(hello), vmkit.Unmetered)\n\th := vmkit.NewTestHost()\n\tfor i := 0; i \u003c 200 \u0026\u0026 inst.Status == vmkit.Running; i++ {\n\t\tuassert.NoError(t, inst.Run(NewMachine(prog), h, 8))\n\t}\n\tuassert.Equal(t, \"halted\", inst.Status.String())\n\tuassert.Equal(t, \"Hello World\", h.OutString())\n\tuassert.True(t, inst.Slices \u003e 1)\n\tuassert.True(t, inst.FuelUsed \u003e 0)\n}\n\nfunc TestInstanceHonoursItsBudget(t *testing.T) {\n\tprog, err := CompileDefault(hello)\n\tuassert.NoError(t, err)\n\n\tinst := vmkit.NewInstance(\"002\", address(\"g1x\"), VMName, []byte(hello), 10)\n\th := vmkit.NewTestHost()\n\tuassert.NoError(t, inst.Run(NewMachine(prog), h, vmkit.Unmetered))\n\tuassert.Equal(t, \"out of fuel\", inst.Status.String())\n\tuassert.Equal(t, int64(10), inst.FuelUsed)\n\tuassert.ErrorIs(t, inst.Run(NewMachine(prog), h, vmkit.Unmetered), vmkit.ErrBudgetExhausted)\n}\n"},{"name":"micro_test.gno","body":"package bf\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n)\n\n// The microarchitecture matrix.\n//\n// The rungs in ladder_test.gno are the classic interpreter optimizations:\n// fewer instructions for the same program. These are the other axis, and on\n// the GnoVM they matter as much: the same instruction stream, executed by\n// loops that differ from each other by exactly one line.\n//\n// They are deliberately simplified (no host, no snapshot, no scan) so that\n// the one line is the only difference. They are comparable to each other and\n// not to the shipped machine, which does more. What the shipped machine took\n// from them is documented on [Machine.Step].\n\ntype vm struct {\n\tprog *Program\n\ttape [TapeSize]byte\n\tptr  int\n\tpc   int\n}\n\n// V0: cursors as struct fields. No meter, no bounds check, no defer.\nfunc (m *vm) runFields() int64 {\n\tops := m.prog.ops\n\tvar used int64\n\tfor {\n\t\tused++\n\t\tswitch ops[m.pc].code {\n\t\tcase opAdd:\n\t\t\tm.tape[m.ptr] += byte(ops[m.pc].arg)\n\t\tcase opMove:\n\t\t\tm.ptr = wrap(m.ptr + ops[m.pc].arg)\n\t\tcase opSet:\n\t\t\tm.tape[m.ptr] = byte(ops[m.pc].arg)\n\t\tcase opAddMul:\n\t\t\tif v := m.tape[m.ptr]; v != 0 {\n\t\t\t\tm.tape[wrap(m.ptr+ops[m.pc].off)] += v * byte(ops[m.pc].arg)\n\t\t\t}\n\t\tcase opJmpZ:\n\t\t\tif m.tape[m.ptr] == 0 {\n\t\t\t\tm.pc = ops[m.pc].arg\n\t\t\t}\n\t\tcase opJmpNZ:\n\t\t\tif m.tape[m.ptr] != 0 {\n\t\t\t\tm.pc = ops[m.pc].arg\n\t\t\t}\n\t\tcase opHalt:\n\t\t\treturn used\n\t\t}\n\t\tm.pc++\n\t}\n}\n\n// V1: V0 with the two cursors hoisted into locals. Only change.\nfunc (m *vm) runLocals() int64 {\n\tops := m.prog.ops\n\tpc, ptr := m.pc, m.ptr\n\tvar used int64\n\tfor {\n\t\tused++\n\t\tswitch ops[pc].code {\n\t\tcase opAdd:\n\t\t\tm.tape[ptr] += byte(ops[pc].arg)\n\t\tcase opMove:\n\t\t\tptr = wrap(ptr + ops[pc].arg)\n\t\tcase opSet:\n\t\t\tm.tape[ptr] = byte(ops[pc].arg)\n\t\tcase opAddMul:\n\t\t\tif v := m.tape[ptr]; v != 0 {\n\t\t\t\tm.tape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)\n\t\t\t}\n\t\tcase opJmpZ:\n\t\t\tif m.tape[ptr] == 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opJmpNZ:\n\t\t\tif m.tape[ptr] != 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opHalt:\n\t\t\tm.pc, m.ptr = pc, ptr\n\t\t\treturn used\n\t\t}\n\t\tpc++\n\t}\n}\n\n// V2: V1 plus a vmkit.Meter charged once per op. Only change.\nfunc (m *vm) runLocalsMeter(fuel int64) int64 {\n\tops := m.prog.ops\n\tmeter := vmkit.NewMeter(fuel)\n\tpc, ptr := m.pc, m.ptr\n\tfor {\n\t\tif !meter.Charge(1) {\n\t\t\tm.pc, m.ptr = pc, ptr\n\t\t\treturn meter.Used()\n\t\t}\n\t\tswitch ops[pc].code {\n\t\tcase opAdd:\n\t\t\tm.tape[ptr] += byte(ops[pc].arg)\n\t\tcase opMove:\n\t\t\tptr = wrap(ptr + ops[pc].arg)\n\t\tcase opSet:\n\t\t\tm.tape[ptr] = byte(ops[pc].arg)\n\t\tcase opAddMul:\n\t\t\tif v := m.tape[ptr]; v != 0 {\n\t\t\t\tm.tape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)\n\t\t\t}\n\t\tcase opJmpZ:\n\t\t\tif m.tape[ptr] == 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opJmpNZ:\n\t\t\tif m.tape[ptr] != 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opHalt:\n\t\t\tm.pc, m.ptr = pc, ptr\n\t\t\treturn meter.Used()\n\t\t}\n\t\tpc++\n\t}\n}\n\n// V3: V1 plus an inline fuel counter instead of the Meter object. Isolates\n// the cost of the method call from the cost of metering at all.\nfunc (m *vm) runLocalsInlineFuel(fuel int64) int64 {\n\tops := m.prog.ops\n\tpc, ptr := m.pc, m.ptr\n\tvar used int64\n\tfor {\n\t\tif used \u003e= fuel {\n\t\t\tm.pc, m.ptr = pc, ptr\n\t\t\treturn used\n\t\t}\n\t\tused++\n\t\tswitch ops[pc].code {\n\t\tcase opAdd:\n\t\t\tm.tape[ptr] += byte(ops[pc].arg)\n\t\tcase opMove:\n\t\t\tptr = wrap(ptr + ops[pc].arg)\n\t\tcase opSet:\n\t\t\tm.tape[ptr] = byte(ops[pc].arg)\n\t\tcase opAddMul:\n\t\t\tif v := m.tape[ptr]; v != 0 {\n\t\t\t\tm.tape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)\n\t\t\t}\n\t\tcase opJmpZ:\n\t\t\tif m.tape[ptr] == 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opJmpNZ:\n\t\t\tif m.tape[ptr] != 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opHalt:\n\t\t\tm.pc, m.ptr = pc, ptr\n\t\t\treturn used\n\t\t}\n\t\tpc++\n\t}\n}\n\n\n// V4: V3 with the tape as a local slice instead of an array field. Only\n// change, so this settles the \"a fixed array removes a bounds check\" claim.\nfunc (m *vm) runLocalsInlineFuelSliceTape(fuel int64) int64 {\n\tops := m.prog.ops\n\ttape := make([]byte, TapeSize)\n\tpc, ptr := m.pc, m.ptr\n\tvar used int64\n\tfor {\n\t\tif used \u003e= fuel {\n\t\t\tm.pc, m.ptr = pc, ptr\n\t\t\treturn used\n\t\t}\n\t\tused++\n\t\tswitch ops[pc].code {\n\t\tcase opAdd:\n\t\t\ttape[ptr] += byte(ops[pc].arg)\n\t\tcase opMove:\n\t\t\tptr = wrap(ptr + ops[pc].arg)\n\t\tcase opSet:\n\t\t\ttape[ptr] = byte(ops[pc].arg)\n\t\tcase opAddMul:\n\t\t\tif v := tape[ptr]; v != 0 {\n\t\t\t\ttape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)\n\t\t\t}\n\t\tcase opJmpZ:\n\t\t\tif tape[ptr] == 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opJmpNZ:\n\t\t\tif tape[ptr] != 0 {\n\t\t\t\tpc = ops[pc].arg\n\t\t\t}\n\t\tcase opHalt:\n\t\t\tm.pc, m.ptr = pc, ptr\n\t\t\treturn used\n\t\t}\n\t\tpc++\n\t}\n}\n\nfunc microProg(lvl Level) *Program {\n\tp, err := Compile(heavy, lvl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn p\n}\n\n// Rung 1's instruction stream, 121,202 ops, under each loop.\n\nfunc TestMicroJumpsCursorsAsFields(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelJumps)}).runFields()\n}\n\nfunc TestMicroJumpsCursorsInLocals(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelJumps)}).runLocals()\n}\n\nfunc TestMicroJumpsMeterPerOp(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelJumps)}).runLocalsMeter(vmkit.Unmetered)\n}\n\nfunc TestMicroJumpsInlineFuel(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelJumps)}).runLocalsInlineFuel(1 \u003c\u003c 40)\n}\n\n// Rung 3's instruction stream, 1,203 ops, under the same loops.\n\nfunc TestMicroJumpsSliceTape(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelJumps)}).runLocalsInlineFuelSliceTape(1 \u003c\u003c 40)\n}\n\nfunc TestMicroIdiomsCursorsAsFields(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelIdioms)}).runFields()\n}\n\nfunc TestMicroIdiomsCursorsInLocals(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelIdioms)}).runLocals()\n}\n\nfunc TestMicroIdiomsMeterPerOp(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelIdioms)}).runLocalsMeter(vmkit.Unmetered)\n}\n\nfunc TestMicroIdiomsInlineFuel(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelIdioms)}).runLocalsInlineFuel(1 \u003c\u003c 40)\n}\n\nfunc TestMicroIdiomsSliceTape(t *testing.T) {\n\t(\u0026vm{prog: microProg(LevelIdioms)}).runLocalsInlineFuelSliceTape(1 \u003c\u003c 40)\n}\n"}]},"send":"","max_deposit":"21000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"riscv","path":"gno.land/p/moul/x/vm/riscv/v0","files":[{"name":"README.md","body":"# p/moul/x/vm/riscv\n\nRV32IM in gno: 48 instructions that `rustc`, `clang`, TinyGo and Zig already\nemit. A guest here is not written in a new language and is not translated by\nanything of mine. It arrives compiled by the real compiler and optimized by the\nreal optimizer, and this package is a decode loop.\n\nLive demo: [`r/moul/x/vm/riscvdemo`](/r/moul/x/vm/riscvdemo/v0).\n\nSecond guest on [`vmkit`](../vmkit), which is the only way to find out whether\nthe host ABI was shaped around the first one. It was not: `riscv` implements\n`vmkit.Machine` unchanged and shares the fuel meter, the snapshot codec and the\ninstance store with [`bf`](../bf).\n\n```go\nm, err := riscv.NewMachine(image, 0x1000)   // image is a flat .text blob\nif err != nil { return err }\nused, status := m.Step(host, 50_000)        // running, halted, trapped, out of fuel\nsnap := m.Snapshot()                        // resume in a later transaction\n```\n\n## Does it clear the bar\n\nThe design issue set a kill criterion before any code existed: **above roughly\n15,000 gas per RV32I instruction the track is a curiosity, not a substrate**, on\nthe reasoning that a guest would then get about 200k instructions per block,\nwhich is a token transfer and not a program anyone would write without thinking\nabout it.\n\nMeasured 2026-09-25 with `gno test -v` (`--- GAS:`), `gno` built from\n`gnolang/gno` master. The figure is a slope from two loop sizes, 4,006 and\n16,006 instructions, so the fixed per-test overhead cancels. The slope is\nstable to a few gas between runs; the fixed term is not, which is why it is a\nslope:\n\n| rung | what changed | gas / instruction |\n|---|---|---:|\n| 0 | `decode.gno`'s helpers called per instruction | 33,992 |\n| 1 | field extraction and the fetch inlined into the dispatch loop | 18,834 |\n| 2 | predecode once at load, dispatch on a frequency-ordered opcode | **8,487** |\n\n**It clears the bar with a 1.8x margin**, which works out to about **354,000\nguest instructions per block**. The ladder is worth 4.0x end to end, and all of\nit came from moving work off the per-instruction path rather than from doing\nanything clever with the instruction set.\n\nReproduce with `gno test -v .` and read `TestBenchRV32I1000` and\n`TestBenchRV32I4000`.\n\nBe careful what that number is not. 354k instructions is a real program and a\nsmall one: a sort, a parser, a state machine, a few thousand iterations of a\nloop. It is not a signature verification, which is millions of instructions, and\nthe chain already has secp256k1 natively for that reason.\n\n## Conformance\n\nThe official [riscv-tests](https://github.com/riscv-software-src/riscv-tests)\nsuite passes: **all 42 `rv32ui` cases and all 8 `rv32um`**, embedded in\n`conformance_test.gno` and run on every `gno test`.\n\nThis is the only thing here a third party wrote. Everything in `riscv_test.gno`\nchecks that the emulator agrees with its author's reading of the spec; this\nchecks that it agrees with the people who wrote the spec, using their\nassertions, compiled from their source.\n\nOne case is skipped and the skip is declared rather than omitted:\n**`rv32ui-fence_i`**. `FENCE.I` exists to make writes to the instruction stream\nvisible, and this machine predecodes its text and refuses stores into it, so\nthere is nothing to make visible. Self-modifying code is not unimplemented here,\nit is excluded.\n\nThe suite's own environment sets up `mtvec`, delegates exceptions and enters\nthrough `mret`, none of which exists on a hart with no CSRs. The corpus was\ntherefore built against a replacement `riscv_test.h` that keeps the `_start`\nsymbol and `TESTNUM` in `gp` and drops the machine-mode ceremony. **The exit\nconvention is the suite's own, untouched**: it already spells pass and fail as\n`li a7, 93; ecall`, which is this host's exit syscall. What was replaced is how\na case starts and hands back its verdict, not what it checks. Rebuild it with\n[`tools/riscv-guests/conformance`](../../../../tools/riscv-guests/conformance).\n\nTwo faults were injected to confirm the suite bites rather than merely passing:\nSRAI as a logical shift takes out `rv32ui-srai` and `rv32ui-lui` at case 3, and\nREMU by zero returning 0 takes out `rv32um-remu` at case 8. Both are recorded in\nthe test file, and the harness's own pass and fail decoding is pinned by two\ntests so a change that made every case report success would not read as green.\n\n## Guests a compiler produced\n\nThe claim this package rests on is that a program arrives compiled by the real\ncompiler, so two of them are shipped compiled and nothing is trusted to stand in\nfor that. Both are rebuildable: source, linker script and exact command are in\n[`tools/riscv-guests`](../../../../tools/riscv-guests), and the committed words\nwere verified to match a fresh build.\n\n| | language | words | what it does |\n|---|---|---:|---|\n| `riscv.GuestFNV()` | C, clang 19.1.7 | 49 | hashes the call input with FNV-1a |\n| `riscv.GuestLedger()` | Rust, rustc 1.98.1, `#![no_std]` | 1,959 | mint, send and burn from a script |\n\n```go\nm, _ := riscv.NewMachine(riscv.GuestLedger(), riscv.DefaultEntry)\nm.Step(host, 50_000)\n// input:  \"mint alice 100\\nmint bob 50\\nsend alice bob 30\\n\"\n// output: \"alice 70\\nbob 80\\n\"\n```\n\nBetween them they exercise what a hand-written program does not: a real function\nprologue spilling `ra` and `s0` to a stack the host set up, `.bss` addressed far\nabove a text segment the host refuses stores into, LLVM materializing constants\nthrough `lui`/`addi` pairs at the sign-extension boundary that bit this package\ntwice, and `MUL` in an inner loop.\n\n**The Rust one goes further, and that is why it is worth its size.** It links\nRust's real `core` and `compiler_builtins`, which it never calls directly: a\nbounds check reaches `core::panicking`, and the balances are 64-bit, so a divide\nreaches `__udivdi3` because **RV32 has no 64-bit divide instruction**. The\nemulator is running the standard library's own software arithmetic, not only\nwhat the compiler emitted for my source. `TestRustLedgerDoes64BitArithmetic`\npins a balance past 2^32 to keep that path live.\n\nBoth pause and resume correctly when sliced, the Rust one seventeen instructions\nat a time, in the middle of a library routine it never asked to call. That is\nthe property a realm depends on and the one most likely to break on code nobody\nwrote to be sliceable.\n\nA refusal from the ledger is **halted, not trapped**: `line 2: insufficient\nbalance`, exit code 1. The program said no and the machine did not break, and a\nchain has to be able to tell a user which happened.\n\nThe memory layout is not incidental. W xor X means a guest whose writable data\nshared a page with its code would trap on its first store, so the linker script\nis part of the ABI and each guest pins its own: the addresses in it are baked\ninto the instruction stream as `lui` immediates, so a shared script edited for\none guest would silently invalidate every image built against the old one.\n\n## What the GnoVM charges for, measured\n\nThe rungs above are not classic interpreter optimizations. They are answers to\nhow *this* host executes code, and `switchcost_test.gno` measures it directly,\n200,000 iterations per figure:\n\n| what | gas each |\n|---|---:|\n| one elementary operation, from the loop control | ~280 |\n| a function call | 466 |\n| a call through a table indexed by opcode | 727 |\n| `switch`, hitting the **first** case | 292 |\n| `switch`, hitting the **48th** case | 13,358 |\n| **each case label scanned on the way** | **278** |\n| `make([]byte, n)`, for any n | 655,224, flat |\n\nTwo of these decided the design:\n\n1. **The GnoVM scans switch cases in source order.** Case 47 costs 45x case 0.\n   So the internal opcodes in `predecode.gno` are ordered by how often compiled\n   code executes them, and that ordering is load-bearing: sorting that list\n   alphabetically would make the interpreter slower. It also means a flat\n   48-case switch is only a win if the common instructions are near the top,\n   and that a table of function values (727 gas, position independent) beats a\n   switch for anything past the third case.\n2. **`make` does not charge for size.** A megabyte costs what four kilobytes\n   costs. The flat 1 MiB address space is therefore free at load, and the thing\n   to economize is per-word work, not bytes.\n\n## The cost on the other side: predecode\n\nPredecoding is **19,623 gas per word**, paid at load and again on every resume,\nbecause the arrays are not in the snapshot: only the memory pages are.\n\nThat is 2.3x what executing an instruction costs, which is high enough to state\nplainly rather than bury:\n\n- **It pays for itself once a slice executes about 1.9 instructions per word of\n  its text** (`19,623 / (18,834 - 8,487)`). Any loop clears that immediately.\n  Straight-line code run once does not, and for that shape rung 1 is the faster\n  interpreter.\n- **A large binary pays it every transaction.** A 64 KiB text segment is 16,384\n  words, so a resume costs about 321M gas, roughly 11% of a block, before the\n  guest executes anything.\n\nThe fix is known and not done here: decode a word the first time it is reached\nrather than all of them at load, keyed on a sentinel opcode. That costs one\ncomparison per instruction (~280 gas, about 3%) and charges only for code the\nguest actually runs. Worth doing when a real binary shows up; not worth\nguessing at now.\n\nMerging the immediate decoder into the opcode switch already took predecode from\n31,432 to 19,623 gas per word. The two were separate functions, and the second\none had a `case` clause listing 22 opcodes, every label of which was scanned.\n\n## Semantics\n\n**W xor X.** A store into the text segment traps. Predecoding is only sound if\nthe code cannot change under the arrays, and refusing is also what an ELF text\nsegment does, so self-modifying code is not a thing this VM has. `FENCE.I` is\ntherefore unnecessary and `FENCE` is a no-op, which is what it architecturally\nis on a machine with one hart.\n\n**`exit(1)` halts, it does not trap.** A program that returns non-zero said no;\nit did not break. A chain that conflates \"your code failed\" with \"the VM failed\"\ncannot tell a user which one happened.\n\n**An unknown syscall traps** rather than returning zero, so a guest built\nagainst a newer syscall table fails loudly on an older host instead of silently\nreading a success it never got.\n\n**The M extension's edge cases return values, they do not trap.** Division by\nzero gives all ones, and `INT_MIN / -1` gives `INT_MIN`. The spec defines both\nprecisely, which is exactly what a chain needs: there is no host arithmetic\nexception left to differ between nodes.\n\n**No F, no D, no C, no A.** No floats means no rounding mode and nothing that\ncan differ between nodes. No compressed instructions means every instruction is\n4 bytes and `(pc - base) \u003e\u003e 2` is the whole fetch. No atomics because there is\none hart.\n\n**Misaligned is a trap, out of range is a trap.** RISC-V leaves an access\noutside physical memory to the platform, and a chain has to pick the behaviour\nthat cannot differ between nodes. Refusing is deterministic; wrapping would let\na guest alias two addresses and get different answers from different memory\nsizes.\n\n## Snapshots\n\nA 1 MiB address space that serialized in full on every pause would make\ncontinuations cost more than re-running, which is the kill criterion `vmkit` set\nfor them. Memory is snapshotted by **dirty page**: a guest that has written two\npages pauses in about 8 KiB regardless of how much memory it was given, and\n`TestSnapshotCarriesOnlyTouchedPages` asserts the proportionality rather than a\nmagic number.\n\nThe program is not written twice. It is in the memory pages already, marked\ndirty by `WriteImage`, so a snapshot carries the text extent and re-derives the\npredecode from the restored pages.\n\n## The syscall table\n\nEight calls, in the RISC-V Linux register convention a compiler already knows:\n`a7` selects, `a0`..`a3` carry arguments, `a0` receives the result. A no_std\nguest needs three lines of inline assembly and no gno-specific runtime.\n\n| a7 | call | maps to |\n|---:|---|---|\n| 93 | `exit(status)` | halts the machine |\n| 64 | `write(fd, buf, len)` | `Host.Output` |\n| 63 | `read(fd, buf, len)` | `Host.Input` |\n| 90 | `height()` | block height |\n| 91 | `now()` | block time, Unix seconds |\n| 92 | `caller(buf, len)` | the calling address |\n| 94 | `log(buf, len)` | `Host.Log` |\n| 95 | `emit(type, typelen, body, bodylen)` | `Host.Emit` |\n\nDeliberately small, and every one of them is something `vmkit.Host` already\noffers. The Host is the audited surface; a syscall that reached past it would be\na second, unreviewed one. One call's buffer is capped at 64 KiB, because a guest\nasking to write a gigabyte has found the host's allocator, not something to say.\n\n## Tests\n\nThe assembler in `riscv_test.gno` is written from the spec independently of the\ndecoders in `decode.gno`, so a field in the wrong place fails unless both files\nput it in the same wrong place. `decode_test.gno` round-trips all five immediate\nformats at their sign boundaries, which is where this went wrong twice while it\nwas being written: a 12-bit immediate makes `addi x8, x0, 4000` load **-96**,\nand a 13-bit B-type immediate makes a hand-written `-8` branch jump forward by\n4,088.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/vm/riscv/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/vm/riscv/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bench_test.gno","body":"package riscv\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The measurement the design issue set a kill criterion against: if an RV32I\n// instruction costs more than roughly 15k cycles after the bf ladder's tricks,\n// a RISC-V guest runs ~200k instructions per block, which is a token transfer\n// and not a program a Rust programmer would write without thinking about it.\n//\n// The loop is arithmetic and branches only, no syscalls and no memory beyond\n// the fetch, so it measures the decode-and-dispatch path rather than the host.\n\n// li loads a full 32-bit constant, because addi cannot: its immediate is 12\n// bits SIGN EXTENDED, so addi(rd, x0, 4000) loads -96 and a loop counting up to\n// it never terminates. That is not hypothetical, it hung this benchmark for two\n// days. The +0x800 pre-bias is the standard correction: it cancels the sign\n// extension addi is about to apply to the low half.\nfunc li(rd, v uint32) []uint32 {\n\treturn []uint32{\n\t\tlui(rd, (v+0x800)\u00260xFFFFF000),\n\t\taddi(rd, rd, v\u00260xFFF),\n\t}\n}\n\nfunc lui(rd, imm uint32) uint32 { return uType(imm, rd, opLUI) }\n\n// benchProg counts x6 up to x8 in a 4-instruction loop, then exits.\nfunc benchProg(n uint32) []uint32 {\n\tprog := li(8, n) // x8 = n, the loop bound\n\tprog = append(prog,\n\t\taddi(5, 0, 0), // sum = 0\n\t\taddi(6, 0, 0), // i   = 0\n\t\t// loop:\n\t\tadd(5, 5, 6),      // sum += i\n\t\taddi(6, 6, 1),     // i++\n\t\taddi(7, 0, 0),     // filler, keeps the loop a round 4 instructions\n\t\tbne(6, 8, 0x1FF4), // -12, while i != x8\n\t)\n\treturn append(prog, exitWith()...)\n}\n\n// benchInstrs is how many instructions benchProg(n) executes: 4 setup (li is\n// two), 4 per iteration including the branch, 2 to exit.\nfunc benchInstrs(n int64) int64 { return 4 + 4*n + 2 }\n\n// runBench returns the instruction count the machine charged itself. The fuel\n// cap is ten times what the program should need: a mis-encoded immediate turns\n// an unmetered run into an infinite loop with no test output, so the budget is\n// what makes a bad encoding fail in a second instead of hanging the suite.\nfunc runBench(t *testing.T, n uint32) int64 {\n\tt.Helper()\n\tm, err := NewMachine(asm(benchProg(n)), entry)\n\tuassert.NoError(t, err)\n\tif m == nil {\n\t\treturn 0\n\t}\n\tused, status := m.Step(vmkit.NewTestHost(), benchInstrs(int64(n))*10)\n\tuassert.Equal(t, \"halted\", status.String())\n\treturn used\n}\n\n// One test per size, so `gno test -print-runtime-metrics` prints one cycle\n// count each and the slope cancels the fixed per-test overhead. The README\n// quotes the result.\n\nfunc TestBenchRV32I1000(t *testing.T) {\n\tuassert.Equal(t, benchInstrs(1000), runBench(t, 1000))\n}\n\nfunc TestBenchRV32I4000(t *testing.T) {\n\tuassert.Equal(t, benchInstrs(4000), runBench(t, 4000))\n}\n\n// li has to survive the sign-extension boundary in both directions, or the two\n// sizes above are not measuring the loop counts they claim to.\nfunc TestLoadImmediateSpansTheSignBoundary(t *testing.T) {\n\tfor _, v := range []uint32{0, 1, 0x7FF, 0x800, 1000, 4000, 0x7FFFFFFF, 0xFFFFFFFF} {\n\t\tprog := append(li(5, v), exitWith()...)\n\t\tm, err := NewMachine(asm(prog), entry)\n\t\tuassert.NoError(t, err)\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\t\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\t\tuassert.Equal(t, \"halted\", status.String())\n\t\tuassert.Equal(t, uint64(v), uint64(m.reg[5]))\n\t}\n}\n\n// Predecoding is paid once per load, and a realm loads a machine on every\n// transaction that resumes one. So the saving on the dispatch loop is only\n// real if this side of the trade is small against the instructions the slice\n// then executes. Two sizes again, so the slope is per word.\nfunc benchImage(words int) []byte {\n\timg := make([]byte, words*4)\n\tinst := addi(5, 5, 1)\n\tfor i := 0; i \u003c words; i++ {\n\t\timg[i*4] = byte(inst)\n\t\timg[i*4+1] = byte(inst \u003e\u003e 8)\n\t\timg[i*4+2] = byte(inst \u003e\u003e 16)\n\t\timg[i*4+3] = byte(inst \u003e\u003e 24)\n\t}\n\treturn img\n}\n\nfunc TestBenchPredecode1000(t *testing.T) {\n\tc := predecode(entry, benchImage(1000))\n\tuassert.Equal(t, uint64(1000), uint64(c.words))\n}\n\nfunc TestBenchPredecode4000(t *testing.T) {\n\tc := predecode(entry, benchImage(4000))\n\tuassert.Equal(t, uint64(4000), uint64(c.words))\n}\n\n// The control, so the slope above is predecode and not the loop that builds\n// the image.\nfunc TestBenchImageOnly1000(t *testing.T) {\n\tuassert.Equal(t, 4000, len(benchImage(1000)))\n}\n\nfunc TestBenchImageOnly4000(t *testing.T) {\n\tuassert.Equal(t, 16000, len(benchImage(4000)))\n}\n"},{"name":"clang_test.gno","body":"package riscv\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A guest compiled by a real compiler, which is the only test here that was\n// not written by the same person who wrote the emulator.\n//\n// The image is guests.gno's, built from tools/riscv-guests/fnv by clang. It\n// exercises what hand-written tests do not: a real function prologue spilling\n// ra and s0 to a stack the host set up, .bss addressed far above a read-only\n// text segment, LLVM's constant materialization through lui/addi pairs, and\n// MUL in an inner loop.\n\n// The expected hashes come from an independent FNV-1a, not from this VM.\nfunc TestClangCompiledGuest(t *testing.T) {\n\tcases := []struct {\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"\", \"811c9dc5\"},\n\t\t{\"a\", \"e40c292c\"},\n\t\t{\"Hello\", \"f55c314b\"},\n\t\t{\"gno.land\", \"fb7ffba0\"},\n\t}\n\tfor _, c := range cases {\n\t\tm, err := NewMachine(GuestFNV(), entry)\n\t\tuassert.NoError(t, err)\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\t\th := vmkit.NewTestHost().WithInput([]byte(c.in))\n\t\t_, status := m.Step(h, vmkit.Unmetered)\n\t\tuassert.Equal(t, \"halted\", status.String(), \"input \"+c.in+\": \"+m.Trap())\n\t\tuassert.Equal(t, c.want, string(h.Out()), \"fnv1a of \"+c.in)\n\t}\n}\n\n// Compiled code pauses and resumes like anything else. This is the property a\n// realm depends on, run against output a compiler produced rather than against\n// a loop written to be sliceable.\nfunc TestClangGuestSurvivesSlicing(t *testing.T) {\n\timage := GuestFNV()\n\th := vmkit.NewTestHost().WithInput([]byte(\"gno.land\"))\n\n\tsliced, err := NewMachine(image, entry)\n\tuassert.NoError(t, err)\n\tstatus := vmkit.Running\n\tslices := 0\n\tfor i := 0; i \u003c 500 \u0026\u0026 status == vmkit.Running; i++ {\n\t\tvar fresh Machine\n\t\tuassert.NoError(t, fresh.Restore(sliced.Snapshot()))\n\t\t_, status = fresh.Step(h, 3)\n\t\tsliced = \u0026fresh\n\t\tslices++\n\t}\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.True(t, slices \u003e 10, \"a sliced run must actually have been sliced\")\n\tuassert.Equal(t, \"fb7ffba0\", string(h.Out()))\n}\n\n// The guest writes its globals at 0x40000, which the linker script put well\n// above the text segment on purpose. If it had put them adjacent, W xor X\n// would trap on the first store, so this is the test that the memory layout\n// the toolchain was told to use is the one the host actually provides.\nfunc TestClangGuestWritesAboveItsText(t *testing.T) {\n\tm, err := NewMachine(GuestFNV(), entry)\n\tuassert.NoError(t, err)\n\th := vmkit.NewTestHost().WithInput([]byte(\"gno.land\"))\n\t_, status := m.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\n\t// The text pages, the .bss page at 0x40000, and the stack page at the top.\n\tuassert.True(t, m.Memory().DirtyPages() \u003e= 3,\n\t\t\"the guest must have written outside its text segment\")\n\tuassert.True(t, m.Memory().DirtyPages() \u003c= 8,\n\t\t\"a 196-byte program must not have dirtied the address space\")\n}\n\n// Image is what every caller uses to turn words into a program, so a byte\n// order mistake here would look like a decoder bug everywhere else.\nfunc TestImageIsLittleEndian(t *testing.T) {\n\tb := Image([]uint32{0x04030201, 0xFF000000})\n\tuassert.Equal(t, 8, len(b))\n\tuassert.Equal(t, uint64(0x01), uint64(b[0]))\n\tuassert.Equal(t, uint64(0x04), uint64(b[3]))\n\tuassert.Equal(t, uint64(0x00), uint64(b[4]))\n\tuassert.Equal(t, uint64(0xFF), uint64(b[7]))\n\n\t// And it agrees with the assembler the other tests use.\n\twords := []uint32{addi(5, 0, 1), ecall()}\n\ta, i := asm(words), Image(words)\n\tuassert.Equal(t, len(a), len(i))\n\tfor k := range a {\n\t\tuassert.Equal(t, uint64(a[k]), uint64(i[k]))\n\t}\n}\n\n// GuestFNV must not hand out a slice a caller can scribble on, because the\n// next caller gets the same program.\nfunc TestGuestFNVIsACopy(t *testing.T) {\n\ta := GuestFNV()\n\ta[0] = 0xFF\n\tb := GuestFNV()\n\tuassert.False(t, b[0] == 0xFF, \"GuestFNV must return a fresh image each call\")\n}\n"},{"name":"conformance_test.gno","body":"package riscv\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The official RISC-V conformance suite, built from\n// github.com/riscv-software-src/riscv-tests at the rv32ui and rv32um targets.\n//\n// This is the only test here that a third party wrote. Everything in\n// riscv_test.gno checks that the emulator agrees with its author's reading of\n// the spec; this checks that it agrees with the people who wrote the spec.\n//\n// The suite's own environment (env/p) sets up mtvec, delegates traps and\n// returns through mret, none of which exists on a hart with no CSRs and one\n// privilege level. So these were built against a replacement riscv_test.h that\n// keeps the parts of the contract the tests rely on and drops the machine-mode\n// ceremony. Crucially the exit convention is the suite's own, unchanged: it\n// already spells pass and fail as `li a7, 93; ecall`, which is this host's exit\n// syscall, so a0 == 0 means pass and a0 == (testnum \u003c\u003c 1) | 1 names the case\n// that failed.\n//\n// Regenerating the corpus, the replacement header and the linker script:\n// tools/riscv-guests/conformance.\n\n// conformanceDataAddr is where the linker script puts .data, far above the\n// text segment because the text is read-only here.\nconst conformanceDataAddr = 0x40000\n\n// conformanceFuel bounds a runaway test. Every case in the suite finishes in\n// well under this; a case that does not has failed in a way worth reporting as\n// a timeout rather than hanging the run.\nconst conformanceFuel = 2000000\n\ntype conformanceCase struct {\n\tname string\n\ttext []uint32\n\tdata []uint32\n}\n\nvar conformanceCases = []conformanceCase{\n\t{\n\t\tname: \"rv32ui-add\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000593, 0x00000613, 0x00C58733, 0x00000393, 0x4C771663,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x00C58733, 0x00200393, 0x4A771A63, 0x00400193, 0x00300593,\n\t\t\t0x00700613, 0x00C58733, 0x00A00393, 0x48771E63, 0x00500193, 0x00000593, 0xFFFF8637, 0x00C58733,\n\t\t\t0xFFFF83B7, 0x48771263, 0x00600193, 0x800005B7, 0x00000613, 0x00C58733, 0x800003B7, 0x46771663,\n\t\t\t0x00700193, 0x800005B7, 0xFFFF8637, 0x00C58733, 0x7FFF83B7, 0x44771A63, 0x00800193, 0x00000593,\n\t\t\t0x00008637, 0xFFF60613, 0x00C58733, 0x000083B7, 0xFFF38393, 0x42771A63, 0x00900193, 0x800005B7,\n\t\t\t0xFFF58593, 0x00000613, 0x00C58733, 0x800003B7, 0xFFF38393, 0x40771A63, 0x00A00193, 0x800005B7,\n\t\t\t0xFFF58593, 0x00008637, 0xFFF60613, 0x00C58733, 0x800083B7, 0xFFE38393, 0x3E771863, 0x00B00193,\n\t\t\t0x800005B7, 0x00008637, 0xFFF60613, 0x00C58733, 0x800083B7, 0xFFF38393, 0x3C771863, 0x00C00193,\n\t\t\t0x800005B7, 0xFFF58593, 0xFFFF8637, 0x00C58733, 0x7FFF83B7, 0xFFF38393, 0x3A771863, 0x00D00193,\n\t\t\t0x00000593, 0xFFF00613, 0x00C58733, 0xFFF00393, 0x38771C63, 0x00E00193, 0xFFF00593, 0x00100613,\n\t\t\t0x00C58733, 0x00000393, 0x38771063, 0x00F00193, 0xFFF00593, 0xFFF00613, 0x00C58733, 0xFFE00393,\n\t\t\t0x36771463, 0x01000193, 0x00100593, 0x80000637, 0xFFF60613, 0x00C58733, 0x800003B7, 0x34771663,\n\t\t\t0x01100193, 0x00D00593, 0x00B00613, 0x00C585B3, 0x01800393, 0x32759A63, 0x01200193, 0x00E00593,\n\t\t\t0x00B00613, 0x00C58633, 0x01900393, 0x30761E63, 0x01300193, 0x00D00593, 0x00B585B3, 0x01A00393,\n\t\t\t0x30759463, 0x01400193, 0x00000213, 0x00D00093, 0x00B00113, 0x00208733, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x01800393, 0x2C731E63, 0x01500193, 0x00000213, 0x00E00093, 0x00B00113,\n\t\t\t0x00208733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5212E3, 0x01900393, 0x2A731663,\n\t\t\t0x01600193, 0x00000213, 0x00F00093, 0x00B00113, 0x00208733, 0x00000013, 0x00000013, 0x00070313,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x01A00393, 0x26731C63, 0x01700193, 0x00000213, 0x00D00093,\n\t\t\t0x00B00113, 0x00208733, 0x00120213, 0x00200293, 0xFE5216E3, 0x01800393, 0x24771863, 0x01800193,\n\t\t\t0x00000213, 0x00E00093, 0x00B00113, 0x00000013, 0x00208733, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x01900393, 0x22771263, 0x01900193, 0x00000213, 0x00F00093, 0x00B00113, 0x00000013, 0x00000013,\n\t\t\t0x00208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x01A00393, 0x1E771A63, 0x01A00193, 0x00000213,\n\t\t\t0x00D00093, 0x00000013, 0x00B00113, 0x00208733, 0x00120213, 0x00200293, 0xFE5214E3, 0x01800393,\n\t\t\t0x1C771463, 0x01B00193, 0x00000213, 0x00E00093, 0x00000013, 0x00B00113, 0x00000013, 0x00208733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x01900393, 0x18771C63, 0x01C00193, 0x00000213, 0x00F00093,\n\t\t\t0x00000013, 0x00000013, 0x00B00113, 0x00208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x01A00393,\n\t\t\t0x16771463, 0x01D00193, 0x00000213, 0x00B00113, 0x00D00093, 0x00208733, 0x00120213, 0x00200293,\n\t\t\t0xFE5216E3, 0x01800393, 0x14771063, 0x01E00193, 0x00000213, 0x00B00113, 0x00E00093, 0x00000013,\n\t\t\t0x00208733, 0x00120213, 0x00200293, 0xFE5214E3, 0x01900393, 0x10771A63, 0x01F00193, 0x00000213,\n\t\t\t0x00B00113, 0x00F00093, 0x00000013, 0x00000013, 0x00208733, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x01A00393, 0x0E771263, 0x02000193, 0x00000213, 0x00B00113, 0x00000013, 0x00D00093, 0x00208733,\n\t\t\t0x00120213, 0x00200293, 0xFE5214E3, 0x01800393, 0x0A771C63, 0x02100193, 0x00000213, 0x00B00113,\n\t\t\t0x00000013, 0x00E00093, 0x00000013, 0x00208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x01900393,\n\t\t\t0x08771463, 0x02200193, 0x00000213, 0x00B00113, 0x00000013, 0x00000013, 0x00F00093, 0x00208733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x01A00393, 0x04771C63, 0x02300193, 0x00F00093, 0x00100133,\n\t\t\t0x00F00393, 0x04711263, 0x02400193, 0x02000093, 0x00008133, 0x02000393, 0x02711863, 0x02500193,\n\t\t\t0x000000B3, 0x00000393, 0x02709063, 0x02600193, 0x01000093, 0x01E00113, 0x00208033, 0x00000393,\n\t\t\t0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-addi\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000693, 0x00068713, 0x00000393, 0x26771C63, 0x00300193,\n\t\t\t0x00100693, 0x00168713, 0x00200393, 0x26771263, 0x00400193, 0x00300693, 0x00768713, 0x00A00393,\n\t\t\t0x24771863, 0x00500193, 0x00000693, 0x80068713, 0x80000393, 0x22771E63, 0x00600193, 0x800006B7,\n\t\t\t0x00068713, 0x800003B7, 0x22771463, 0x00700193, 0x800006B7, 0x80068713, 0x800003B7, 0x80038393,\n\t\t\t0x20771863, 0x00800193, 0x00000693, 0x7FF68713, 0x7FF00393, 0x1E771E63, 0x00900193, 0x800006B7,\n\t\t\t0xFFF68693, 0x00068713, 0x800003B7, 0xFFF38393, 0x1E771063, 0x00A00193, 0x800006B7, 0xFFF68693,\n\t\t\t0x7FF68713, 0x800003B7, 0x7FE38393, 0x1C771263, 0x00B00193, 0x800006B7, 0x7FF68713, 0x800003B7,\n\t\t\t0x7FF38393, 0x1A771663, 0x00C00193, 0x800006B7, 0xFFF68693, 0x80068713, 0x7FFFF3B7, 0x7FF38393,\n\t\t\t0x18771863, 0x00D00193, 0x00000693, 0xFFF68713, 0xFFF00393, 0x16771E63, 0x00E00193, 0xFFF00693,\n\t\t\t0x00168713, 0x00000393, 0x16771463, 0x00F00193, 0xFFF00693, 0xFFF68713, 0xFFE00393, 0x14771A63,\n\t\t\t0x01000193, 0x800006B7, 0xFFF68693, 0x00168713, 0x800003B7, 0x12771E63, 0x01100193, 0x00D00593,\n\t\t\t0x00B58593, 0x01800393, 0x12759463, 0x01200193, 0x00000213, 0x00D00093, 0x00B08713, 0x00070313,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x01800393, 0x10731063, 0x01300193, 0x00000213, 0x00D00093,\n\t\t\t0x00A08713, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x01700393, 0x0C731A63,\n\t\t\t0x01400193, 0x00000213, 0x00D00093, 0x00908713, 0x00000013, 0x00000013, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x01600393, 0x0A731263, 0x01500193, 0x00000213, 0x00D00093, 0x00B08713,\n\t\t\t0x00120213, 0x00200293, 0xFE5218E3, 0x01800393, 0x08771063, 0x01600193, 0x00000213, 0x00D00093,\n\t\t\t0x00000013, 0x00A08713, 0x00120213, 0x00200293, 0xFE5216E3, 0x01700393, 0x04771C63, 0x01700193,\n\t\t\t0x00000213, 0x00D00093, 0x00000013, 0x00000013, 0x00908713, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x01600393, 0x02771663, 0x01800193, 0x02000093, 0x02000393, 0x00709E63, 0x01900193, 0x02100093,\n\t\t\t0x03208013, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-and\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0xFF0105B7, 0xF0058593, 0x0F0F1637, 0xF0F60613, 0x00C5F733,\n\t\t\t0x0F0013B7, 0xF0038393, 0x48771C63, 0x00300193, 0x0FF015B7, 0xFF058593, 0xF0F0F637, 0x0F060613,\n\t\t\t0x00C5F733, 0x00F003B7, 0x0F038393, 0x46771A63, 0x00400193, 0x00FF05B7, 0x0FF58593, 0x0F0F1637,\n\t\t\t0xF0F60613, 0x00C5F733, 0x000F03B7, 0x00F38393, 0x44771863, 0x00500193, 0xF00FF5B7, 0x00F58593,\n\t\t\t0xF0F0F637, 0x0F060613, 0x00C5F733, 0xF000F3B7, 0x42771863, 0x00600193, 0xFF0105B7, 0xF0058593,\n\t\t\t0x0F0F1637, 0xF0F60613, 0x00C5F5B3, 0x0F0013B7, 0xF0038393, 0x40759663, 0x00700193, 0x0FF015B7,\n\t\t\t0xFF058593, 0xF0F0F637, 0x0F060613, 0x00C5F633, 0x00F003B7, 0x0F038393, 0x3E761463, 0x00800193,\n\t\t\t0xFF0105B7, 0xF0058593, 0x00B5F5B3, 0xFF0103B7, 0xF0038393, 0x3C759663, 0x00900193, 0x00000213,\n\t\t\t0xFF0100B7, 0xF0008093, 0x0F0F1137, 0xF0F10113, 0x0020F733, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0x0F0013B7, 0xF0038393, 0x38731A63, 0x00A00193, 0x00000213, 0x0FF010B7, 0xFF008093,\n\t\t\t0xF0F0F137, 0x0F010113, 0x0020F733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFC521EE3,\n\t\t\t0x00F003B7, 0x0F038393, 0x34731C63, 0x00B00193, 0x00000213, 0x00FF00B7, 0x0FF08093, 0x0F0F1137,\n\t\t\t0xF0F10113, 0x0020F733, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFC521CE3,\n\t\t\t0x000F03B7, 0x00F38393, 0x30731C63, 0x00C00193, 0x00000213, 0xFF0100B7, 0xF0008093, 0x0F0F1137,\n\t\t\t0xF0F10113, 0x0020F733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0F0013B7, 0xF0038393, 0x2E771263,\n\t\t\t0x00D00193, 0x00000213, 0x0FF010B7, 0xFF008093, 0xF0F0F137, 0x0F010113, 0x00000013, 0x0020F733,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x00F003B7, 0x0F038393, 0x2A771663, 0x00E00193, 0x00000213,\n\t\t\t0x00FF00B7, 0x0FF08093, 0x0F0F1137, 0xF0F10113, 0x00000013, 0x00000013, 0x0020F733, 0x00120213,\n\t\t\t0x00200293, 0xFC521EE3, 0x000F03B7, 0x00F38393, 0x26771863, 0x00F00193, 0x00000213, 0xFF0100B7,\n\t\t\t0xF0008093, 0x00000013, 0x0F0F1137, 0xF0F10113, 0x0020F733, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0x0F0013B7, 0xF0038393, 0x22771C63, 0x01000193, 0x00000213, 0x0FF010B7, 0xFF008093, 0x00000013,\n\t\t\t0xF0F0F137, 0x0F010113, 0x00000013, 0x0020F733, 0x00120213, 0x00200293, 0xFC521EE3, 0x00F003B7,\n\t\t\t0x0F038393, 0x1E771E63, 0x01100193, 0x00000213, 0x00FF00B7, 0x0FF08093, 0x00000013, 0x00000013,\n\t\t\t0x0F0F1137, 0xF0F10113, 0x0020F733, 0x00120213, 0x00200293, 0xFC521EE3, 0x000F03B7, 0x00F38393,\n\t\t\t0x1C771063, 0x01200193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0xFF0100B7, 0xF0008093, 0x0020F733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x0F0013B7, 0xF0038393, 0x18771663, 0x01300193, 0x00000213,\n\t\t\t0xF0F0F137, 0x0F010113, 0x0FF010B7, 0xFF008093, 0x00000013, 0x0020F733, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0x00F003B7, 0x0F038393, 0x14771A63, 0x01400193, 0x00000213, 0x0F0F1137, 0xF0F10113,\n\t\t\t0x00FF00B7, 0x0FF08093, 0x00000013, 0x00000013, 0x0020F733, 0x00120213, 0x00200293, 0xFC521EE3,\n\t\t\t0x000F03B7, 0x00F38393, 0x10771C63, 0x01500193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0x00000013,\n\t\t\t0xFF0100B7, 0xF0008093, 0x0020F733, 0x00120213, 0x00200293, 0xFE5210E3, 0x0F0013B7, 0xF0038393,\n\t\t\t0x0E771063, 0x01600193, 0x00000213, 0xF0F0F137, 0x0F010113, 0x00000013, 0x0FF010B7, 0xFF008093,\n\t\t\t0x00000013, 0x0020F733, 0x00120213, 0x00200293, 0xFC521EE3, 0x00F003B7, 0x0F038393, 0x0A771263,\n\t\t\t0x01700193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0x00000013, 0x00000013, 0x00FF00B7, 0x0FF08093,\n\t\t\t0x0020F733, 0x00120213, 0x00200293, 0xFC521EE3, 0x000F03B7, 0x00F38393, 0x06771463, 0x01800193,\n\t\t\t0xFF0100B7, 0xF0008093, 0x00107133, 0x00000393, 0x04711863, 0x01900193, 0x00FF00B7, 0x0FF08093,\n\t\t\t0x0000F133, 0x00000393, 0x02711C63, 0x01A00193, 0x000070B3, 0x00000393, 0x02709463, 0x01B00193,\n\t\t\t0x111110B7, 0x11108093, 0x22222137, 0x22210113, 0x0020F033, 0x00000393, 0x00701463, 0x02301063,\n\t\t\t0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F,\n\t\t\t0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-andi\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0xFF0106B7, 0xF0068693, 0xF0F6F713, 0xFF0103B7, 0xF0038393,\n\t\t\t0x1A771463, 0x00300193, 0x0FF016B7, 0xFF068693, 0x0F06F713, 0x0F000393, 0x18771863, 0x00400193,\n\t\t\t0x00FF06B7, 0x0FF68693, 0x70F6F713, 0x00F00393, 0x16771C63, 0x00500193, 0xF00FF6B7, 0x00F68693,\n\t\t\t0x0F06F713, 0x00000393, 0x16771063, 0x00600193, 0xFF0105B7, 0xF0058593, 0x0F05F593, 0x00000393,\n\t\t\t0x14759463, 0x00700193, 0x00000213, 0x0FF010B7, 0xFF008093, 0x70F0F713, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x70000393, 0x10731E63, 0x00800193, 0x00000213, 0x00FF00B7, 0x0FF08093,\n\t\t\t0x0F00F713, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5212E3, 0x0F000393, 0x0E731663,\n\t\t\t0x00900193, 0x00000213, 0xF00FF0B7, 0x00F08093, 0xF0F0F713, 0x00000013, 0x00000013, 0x00070313,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0xF00FF3B7, 0x00F38393, 0x0A731A63, 0x00A00193, 0x00000213,\n\t\t\t0x0FF010B7, 0xFF008093, 0x70F0F713, 0x00120213, 0x00200293, 0xFE5216E3, 0x70000393, 0x08771663,\n\t\t\t0x00B00193, 0x00000213, 0x00FF00B7, 0x0FF08093, 0x00000013, 0x0F00F713, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0x0F000393, 0x06771063, 0x00C00193, 0x00000213, 0xF00FF0B7, 0x00F08093, 0x00000013,\n\t\t\t0x00000013, 0x70F0F713, 0x00120213, 0x00200293, 0xFE5212E3, 0x00F00393, 0x02771863, 0x00D00193,\n\t\t\t0x0F007093, 0x00000393, 0x02709063, 0x00E00193, 0x00FF00B7, 0x0FF08093, 0x70F0F013, 0x00000393,\n\t\t\t0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-auipc\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000013, 0x00002517, 0x71C50513, 0x004005EF, 0x40B50533,\n\t\t\t0x000023B7, 0x71038393, 0x02751463, 0x00300193, 0xFFFFE517, 0x8FC50513, 0x004005EF, 0x40B50533,\n\t\t\t0xFFFFE3B7, 0x8F038393, 0x00751463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-beq\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000093, 0x00000113, 0x00208663, 0x2A301863, 0x00301663,\n\t\t\t0xFE208EE3, 0x2A301263, 0x00300193, 0x00100093, 0x00100113, 0x00208663, 0x28301863, 0x00301663,\n\t\t\t0xFE208EE3, 0x28301263, 0x00400193, 0xFFF00093, 0xFFF00113, 0x00208663, 0x26301863, 0x00301663,\n\t\t\t0xFE208EE3, 0x26301263, 0x00500193, 0x00000093, 0x00100113, 0x00208463, 0x00301463, 0x24301663,\n\t\t\t0xFE208EE3, 0x00600193, 0x00100093, 0x00000113, 0x00208463, 0x00301463, 0x22301863, 0xFE208EE3,\n\t\t\t0x00700193, 0xFFF00093, 0x00100113, 0x00208463, 0x00301463, 0x20301A63, 0xFE208EE3, 0x00800193,\n\t\t\t0x00100093, 0xFFF00113, 0x00208463, 0x00301463, 0x1E301C63, 0xFE208EE3, 0x00900193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x1E208063, 0x00120213, 0x00200293, 0xFE5216E3, 0x00A00193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x00000013, 0x1A208E63, 0x00120213, 0x00200293, 0xFE5214E3, 0x00B00193,\n\t\t\t0x00000213, 0x00000093, 0xFFF00113, 0x00000013, 0x00000013, 0x18208A63, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x00C00193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x16208863, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x00D00193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x00000013,\n\t\t\t0x14208463, 0x00120213, 0x00200293, 0xFE5212E3, 0x00E00193, 0x00000213, 0x00000093, 0x00000013,\n\t\t\t0x00000013, 0xFFF00113, 0x12208063, 0x00120213, 0x00200293, 0xFE5212E3, 0x00F00193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x10208063, 0x00120213, 0x00200293, 0xFE5216E3, 0x01000193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x00000013, 0x0C208E63, 0x00120213, 0x00200293, 0xFE5214E3, 0x01100193,\n\t\t\t0x00000213, 0x00000093, 0xFFF00113, 0x00000013, 0x00000013, 0x0A208A63, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x01200193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x08208863, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x01300193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x00000013,\n\t\t\t0x06208463, 0x00120213, 0x00200293, 0xFE5212E3, 0x01400193, 0x00000213, 0x00000093, 0x00000013,\n\t\t\t0x00000013, 0xFFF00113, 0x04208063, 0x00120213, 0x00200293, 0xFE5212E3, 0x01500193, 0x00100093,\n\t\t\t0x00000A63, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00300393,\n\t\t\t0x00709463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-bge\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000093, 0x00000113, 0x0020D663, 0x30301863, 0x00301663,\n\t\t\t0xFE20DEE3, 0x30301263, 0x00300193, 0x00100093, 0x00100113, 0x0020D663, 0x2E301863, 0x00301663,\n\t\t\t0xFE20DEE3, 0x2E301263, 0x00400193, 0xFFF00093, 0xFFF00113, 0x0020D663, 0x2C301863, 0x00301663,\n\t\t\t0xFE20DEE3, 0x2C301263, 0x00500193, 0x00100093, 0x00000113, 0x0020D663, 0x2A301863, 0x00301663,\n\t\t\t0xFE20DEE3, 0x2A301263, 0x00600193, 0x00100093, 0xFFF00113, 0x0020D663, 0x28301863, 0x00301663,\n\t\t\t0xFE20DEE3, 0x28301263, 0x00700193, 0xFFF00093, 0xFFE00113, 0x0020D663, 0x26301863, 0x00301663,\n\t\t\t0xFE20DEE3, 0x26301263, 0x00800193, 0x00000093, 0x00100113, 0x0020D463, 0x00301463, 0x24301663,\n\t\t\t0xFE20DEE3, 0x00900193, 0xFFF00093, 0x00100113, 0x0020D463, 0x00301463, 0x22301863, 0xFE20DEE3,\n\t\t\t0x00A00193, 0xFFE00093, 0xFFF00113, 0x0020D463, 0x00301463, 0x20301A63, 0xFE20DEE3, 0x00B00193,\n\t\t\t0xFFE00093, 0x00100113, 0x0020D463, 0x00301463, 0x1E301C63, 0xFE20DEE3, 0x00C00193, 0x00000213,\n\t\t\t0xFFF00093, 0x00000113, 0x1E20D063, 0x00120213, 0x00200293, 0xFE5216E3, 0x00D00193, 0x00000213,\n\t\t\t0xFFF00093, 0x00000113, 0x00000013, 0x1A20DE63, 0x00120213, 0x00200293, 0xFE5214E3, 0x00E00193,\n\t\t\t0x00000213, 0xFFF00093, 0x00000113, 0x00000013, 0x00000013, 0x1820DA63, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x00F00193, 0x00000213, 0xFFF00093, 0x00000013, 0x00000113, 0x1620D863, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x01000193, 0x00000213, 0xFFF00093, 0x00000013, 0x00000113, 0x00000013,\n\t\t\t0x1420D463, 0x00120213, 0x00200293, 0xFE5212E3, 0x01100193, 0x00000213, 0xFFF00093, 0x00000013,\n\t\t\t0x00000013, 0x00000113, 0x1220D063, 0x00120213, 0x00200293, 0xFE5212E3, 0x01200193, 0x00000213,\n\t\t\t0xFFF00093, 0x00000113, 0x1020D063, 0x00120213, 0x00200293, 0xFE5216E3, 0x01300193, 0x00000213,\n\t\t\t0xFFF00093, 0x00000113, 0x00000013, 0x0C20DE63, 0x00120213, 0x00200293, 0xFE5214E3, 0x01400193,\n\t\t\t0x00000213, 0xFFF00093, 0x00000113, 0x00000013, 0x00000013, 0x0A20DA63, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x01500193, 0x00000213, 0xFFF00093, 0x00000013, 0x00000113, 0x0820D863, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x01600193, 0x00000213, 0xFFF00093, 0x00000013, 0x00000113, 0x00000013,\n\t\t\t0x0620D463, 0x00120213, 0x00200293, 0xFE5212E3, 0x01700193, 0x00000213, 0xFFF00093, 0x00000013,\n\t\t\t0x00000013, 0x00000113, 0x0420D063, 0x00120213, 0x00200293, 0xFE5212E3, 0x01800193, 0x00100093,\n\t\t\t0x0000DA63, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00300393,\n\t\t\t0x00709463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-bgeu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000093, 0x00000113, 0x0020F663, 0x34301263, 0x00301663,\n\t\t\t0xFE20FEE3, 0x32301C63, 0x00300193, 0x00100093, 0x00100113, 0x0020F663, 0x32301263, 0x00301663,\n\t\t\t0xFE20FEE3, 0x30301C63, 0x00400193, 0xFFF00093, 0xFFF00113, 0x0020F663, 0x30301263, 0x00301663,\n\t\t\t0xFE20FEE3, 0x2E301C63, 0x00500193, 0x00100093, 0x00000113, 0x0020F663, 0x2E301263, 0x00301663,\n\t\t\t0xFE20FEE3, 0x2C301C63, 0x00600193, 0xFFF00093, 0xFFE00113, 0x0020F663, 0x2C301263, 0x00301663,\n\t\t\t0xFE20FEE3, 0x2A301C63, 0x00700193, 0xFFF00093, 0x00000113, 0x0020F663, 0x2A301263, 0x00301663,\n\t\t\t0xFE20FEE3, 0x28301C63, 0x00800193, 0x00000093, 0x00100113, 0x0020F463, 0x00301463, 0x28301063,\n\t\t\t0xFE20FEE3, 0x00900193, 0xFFE00093, 0xFFF00113, 0x0020F463, 0x00301463, 0x26301263, 0xFE20FEE3,\n\t\t\t0x00A00193, 0x00000093, 0xFFF00113, 0x0020F463, 0x00301463, 0x24301463, 0xFE20FEE3, 0x00B00193,\n\t\t\t0x800000B7, 0xFFF08093, 0x80000137, 0x0020F463, 0x00301463, 0x22301463, 0xFE20FEE3, 0x00C00193,\n\t\t\t0x00000213, 0xF00000B7, 0xFFF08093, 0xF0000137, 0x2020F663, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x00D00193, 0x00000213, 0xF00000B7, 0xFFF08093, 0xF0000137, 0x00000013, 0x1E20F263, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x00E00193, 0x00000213, 0xF00000B7, 0xFFF08093, 0xF0000137, 0x00000013,\n\t\t\t0x00000013, 0x1A20FC63, 0x00120213, 0x00200293, 0xFE5210E3, 0x00F00193, 0x00000213, 0xF00000B7,\n\t\t\t0xFFF08093, 0x00000013, 0xF0000137, 0x1820F863, 0x00120213, 0x00200293, 0xFE5212E3, 0x01000193,\n\t\t\t0x00000213, 0xF00000B7, 0xFFF08093, 0x00000013, 0xF0000137, 0x00000013, 0x1620F263, 0x00120213,\n\t\t\t0x00200293, 0xFE5210E3, 0x01100193, 0x00000213, 0xF00000B7, 0xFFF08093, 0x00000013, 0x00000013,\n\t\t\t0xF0000137, 0x1220FC63, 0x00120213, 0x00200293, 0xFE5210E3, 0x01200193, 0x00000213, 0xF00000B7,\n\t\t\t0xFFF08093, 0xF0000137, 0x1020FA63, 0x00120213, 0x00200293, 0xFE5214E3, 0x01300193, 0x00000213,\n\t\t\t0xF00000B7, 0xFFF08093, 0xF0000137, 0x00000013, 0x0E20F663, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x01400193, 0x00000213, 0xF00000B7, 0xFFF08093, 0xF0000137, 0x00000013, 0x00000013, 0x0C20F063,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x01500193, 0x00000213, 0xF00000B7, 0xFFF08093, 0x00000013,\n\t\t\t0xF0000137, 0x0820FC63, 0x00120213, 0x00200293, 0xFE5212E3, 0x01600193, 0x00000213, 0xF00000B7,\n\t\t\t0xFFF08093, 0x00000013, 0xF0000137, 0x00000013, 0x0620F663, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0x01700193, 0x00000213, 0xF00000B7, 0xFFF08093, 0x00000013, 0x00000013, 0xF0000137, 0x0420F063,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x01800193, 0x00100093, 0x0000FA63, 0x00108093, 0x00108093,\n\t\t\t0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00300393, 0x00709463, 0x02301063, 0x0FF0000F,\n\t\t\t0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193,\n\t\t\t0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-blt\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000093, 0x00100113, 0x0020C663, 0x2A301863, 0x00301663,\n\t\t\t0xFE20CEE3, 0x2A301263, 0x00300193, 0xFFF00093, 0x00100113, 0x0020C663, 0x28301863, 0x00301663,\n\t\t\t0xFE20CEE3, 0x28301263, 0x00400193, 0xFFE00093, 0xFFF00113, 0x0020C663, 0x26301863, 0x00301663,\n\t\t\t0xFE20CEE3, 0x26301263, 0x00500193, 0x00100093, 0x00000113, 0x0020C463, 0x00301463, 0x24301663,\n\t\t\t0xFE20CEE3, 0x00600193, 0x00100093, 0xFFF00113, 0x0020C463, 0x00301463, 0x22301863, 0xFE20CEE3,\n\t\t\t0x00700193, 0xFFF00093, 0xFFE00113, 0x0020C463, 0x00301463, 0x20301A63, 0xFE20CEE3, 0x00800193,\n\t\t\t0x00100093, 0xFFE00113, 0x0020C463, 0x00301463, 0x1E301C63, 0xFE20CEE3, 0x00900193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x1E20C063, 0x00120213, 0x00200293, 0xFE5216E3, 0x00A00193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x00000013, 0x1A20CE63, 0x00120213, 0x00200293, 0xFE5214E3, 0x00B00193,\n\t\t\t0x00000213, 0x00000093, 0xFFF00113, 0x00000013, 0x00000013, 0x1820CA63, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x00C00193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x1620C863, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x00D00193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x00000013,\n\t\t\t0x1420C463, 0x00120213, 0x00200293, 0xFE5212E3, 0x00E00193, 0x00000213, 0x00000093, 0x00000013,\n\t\t\t0x00000013, 0xFFF00113, 0x1220C063, 0x00120213, 0x00200293, 0xFE5212E3, 0x00F00193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x1020C063, 0x00120213, 0x00200293, 0xFE5216E3, 0x01000193, 0x00000213,\n\t\t\t0x00000093, 0xFFF00113, 0x00000013, 0x0C20CE63, 0x00120213, 0x00200293, 0xFE5214E3, 0x01100193,\n\t\t\t0x00000213, 0x00000093, 0xFFF00113, 0x00000013, 0x00000013, 0x0A20CA63, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x01200193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x0820C863, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x01300193, 0x00000213, 0x00000093, 0x00000013, 0xFFF00113, 0x00000013,\n\t\t\t0x0620C463, 0x00120213, 0x00200293, 0xFE5212E3, 0x01400193, 0x00000213, 0x00000093, 0x00000013,\n\t\t\t0x00000013, 0xFFF00113, 0x0420C063, 0x00120213, 0x00200293, 0xFE5212E3, 0x01500193, 0x00100093,\n\t\t\t0x00104A63, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00300393,\n\t\t\t0x00709463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-bltu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000093, 0x00100113, 0x0020E663, 0x2E301263, 0x00301663,\n\t\t\t0xFE20EEE3, 0x2C301C63, 0x00300193, 0xFFE00093, 0xFFF00113, 0x0020E663, 0x2C301263, 0x00301663,\n\t\t\t0xFE20EEE3, 0x2A301C63, 0x00400193, 0x00000093, 0xFFF00113, 0x0020E663, 0x2A301263, 0x00301663,\n\t\t\t0xFE20EEE3, 0x28301C63, 0x00500193, 0x00100093, 0x00000113, 0x0020E463, 0x00301463, 0x28301063,\n\t\t\t0xFE20EEE3, 0x00600193, 0xFFF00093, 0xFFE00113, 0x0020E463, 0x00301463, 0x26301263, 0xFE20EEE3,\n\t\t\t0x00700193, 0xFFF00093, 0x00000113, 0x0020E463, 0x00301463, 0x24301463, 0xFE20EEE3, 0x00800193,\n\t\t\t0x800000B7, 0x80000137, 0xFFF10113, 0x0020E463, 0x00301463, 0x22301463, 0xFE20EEE3, 0x00900193,\n\t\t\t0x00000213, 0xF00000B7, 0xF0000137, 0xFFF10113, 0x2020E663, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x00A00193, 0x00000213, 0xF00000B7, 0xF0000137, 0xFFF10113, 0x00000013, 0x1E20E263, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x00B00193, 0x00000213, 0xF00000B7, 0xF0000137, 0xFFF10113, 0x00000013,\n\t\t\t0x00000013, 0x1A20EC63, 0x00120213, 0x00200293, 0xFE5210E3, 0x00C00193, 0x00000213, 0xF00000B7,\n\t\t\t0x00000013, 0xF0000137, 0xFFF10113, 0x1820E863, 0x00120213, 0x00200293, 0xFE5212E3, 0x00D00193,\n\t\t\t0x00000213, 0xF00000B7, 0x00000013, 0xF0000137, 0xFFF10113, 0x00000013, 0x1620E263, 0x00120213,\n\t\t\t0x00200293, 0xFE5210E3, 0x00E00193, 0x00000213, 0xF00000B7, 0x00000013, 0x00000013, 0xF0000137,\n\t\t\t0xFFF10113, 0x1220EC63, 0x00120213, 0x00200293, 0xFE5210E3, 0x00F00193, 0x00000213, 0xF00000B7,\n\t\t\t0xF0000137, 0xFFF10113, 0x1020EA63, 0x00120213, 0x00200293, 0xFE5214E3, 0x01000193, 0x00000213,\n\t\t\t0xF00000B7, 0xF0000137, 0xFFF10113, 0x00000013, 0x0E20E663, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x01100193, 0x00000213, 0xF00000B7, 0xF0000137, 0xFFF10113, 0x00000013, 0x00000013, 0x0C20E063,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x01200193, 0x00000213, 0xF00000B7, 0x00000013, 0xF0000137,\n\t\t\t0xFFF10113, 0x0820EC63, 0x00120213, 0x00200293, 0xFE5212E3, 0x01300193, 0x00000213, 0xF00000B7,\n\t\t\t0x00000013, 0xF0000137, 0xFFF10113, 0x00000013, 0x0620E663, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0x01400193, 0x00000213, 0xF00000B7, 0x00000013, 0x00000013, 0xF0000137, 0xFFF10113, 0x0420E063,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x01500193, 0x00100093, 0x00106A63, 0x00108093, 0x00108093,\n\t\t\t0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00300393, 0x00709463, 0x02301063, 0x0FF0000F,\n\t\t\t0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193,\n\t\t\t0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-bne\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000093, 0x00100113, 0x00209663, 0x2A301A63, 0x00301663,\n\t\t\t0xFE209EE3, 0x2A301463, 0x00300193, 0x00100093, 0x00000113, 0x00209663, 0x28301A63, 0x00301663,\n\t\t\t0xFE209EE3, 0x28301463, 0x00400193, 0xFFF00093, 0x00100113, 0x00209663, 0x26301A63, 0x00301663,\n\t\t\t0xFE209EE3, 0x26301463, 0x00500193, 0x00100093, 0xFFF00113, 0x00209663, 0x24301A63, 0x00301663,\n\t\t\t0xFE209EE3, 0x24301463, 0x00600193, 0x00000093, 0x00000113, 0x00209463, 0x00301463, 0x22301863,\n\t\t\t0xFE209EE3, 0x00700193, 0x00100093, 0x00100113, 0x00209463, 0x00301463, 0x20301A63, 0xFE209EE3,\n\t\t\t0x00800193, 0xFFF00093, 0xFFF00113, 0x00209463, 0x00301463, 0x1E301C63, 0xFE209EE3, 0x00900193,\n\t\t\t0x00000213, 0x00000093, 0x00000113, 0x1E209063, 0x00120213, 0x00200293, 0xFE5216E3, 0x00A00193,\n\t\t\t0x00000213, 0x00000093, 0x00000113, 0x00000013, 0x1A209E63, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x00B00193, 0x00000213, 0x00000093, 0x00000113, 0x00000013, 0x00000013, 0x18209A63, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x00C00193, 0x00000213, 0x00000093, 0x00000013, 0x00000113, 0x16209863,\n\t\t\t0x00120213, 0x00200293, 0xFE5214E3, 0x00D00193, 0x00000213, 0x00000093, 0x00000013, 0x00000113,\n\t\t\t0x00000013, 0x14209463, 0x00120213, 0x00200293, 0xFE5212E3, 0x00E00193, 0x00000213, 0x00000093,\n\t\t\t0x00000013, 0x00000013, 0x00000113, 0x12209063, 0x00120213, 0x00200293, 0xFE5212E3, 0x00F00193,\n\t\t\t0x00000213, 0x00000093, 0x00000113, 0x10209063, 0x00120213, 0x00200293, 0xFE5216E3, 0x01000193,\n\t\t\t0x00000213, 0x00000093, 0x00000113, 0x00000013, 0x0C209E63, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x01100193, 0x00000213, 0x00000093, 0x00000113, 0x00000013, 0x00000013, 0x0A209A63, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x01200193, 0x00000213, 0x00000093, 0x00000013, 0x00000113, 0x08209863,\n\t\t\t0x00120213, 0x00200293, 0xFE5214E3, 0x01300193, 0x00000213, 0x00000093, 0x00000013, 0x00000113,\n\t\t\t0x00000013, 0x06209463, 0x00120213, 0x00200293, 0xFE5212E3, 0x01400193, 0x00000213, 0x00000093,\n\t\t\t0x00000013, 0x00000013, 0x00000113, 0x04209063, 0x00120213, 0x00200293, 0xFE5212E3, 0x01500193,\n\t\t\t0x00100093, 0x00009A63, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00108093,\n\t\t\t0x00300393, 0x00709463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893,\n\t\t\t0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-fence_i\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x06F00693, 0x0003F517, 0xFF451503, 0x0003F597, 0xFEE59583, 0x00000013,\n\t\t\t0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013,\n\t\t\t0x0003F297, 0xFCA29223, 0x0003F297, 0xFAB29F23, 0x0000100F, 0x0003F797, 0xFB078793, 0x00078367,\n\t\t\t0x00200193, 0x00000013, 0x1BC00393, 0x06769A63, 0x06400713, 0xFFF70713, 0xFE071EE3, 0x0003F297,\n\t\t\t0xF8A29823, 0x0003F297, 0xF8B29523, 0x0000100F, 0x00000013, 0x00000013, 0x00000013, 0x00000013,\n\t\t\t0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013, 0x00000013,\n\t\t\t0x0003F797, 0xF4C78793, 0x00078367, 0x00300193, 0x00000013, 0x30900393, 0x00769463, 0x02301063,\n\t\t\t0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F,\n\t\t\t0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0x14D68693, 0x0DE68693, 0x000307E7, 0x22B68693, 0x000307E7, 0x00000000, 0x00000000, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-jal\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000093, 0x0100026F, 0x00000013, 0x00000013, 0x0400006F,\n\t\t\t0x00000117, 0xFF410113, 0x02411A63, 0x00300193, 0x00100093, 0x0140006F, 0x00108093, 0x00108093,\n\t\t\t0x00108093, 0x00108093, 0x00108093, 0x00108093, 0x00300393, 0x00709463, 0x02301063, 0x0FF0000F,\n\t\t\t0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193,\n\t\t\t0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-jalr\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000293, 0x00000317, 0x01030313, 0x000302E7, 0x0E00006F,\n\t\t\t0x00000317, 0xFFC30313, 0x0C629A63, 0x00300193, 0x00000297, 0x01028293, 0x000282E7, 0x0C00006F,\n\t\t\t0x00000317, 0xFFC30313, 0x0A629A63, 0x00400193, 0x00000213, 0x00000317, 0x01030313, 0x000306E7,\n\t\t\t0x08301E63, 0x00120213, 0x00200293, 0xFE5214E3, 0x00500193, 0x00000213, 0x00000317, 0x01430313,\n\t\t\t0x00000013, 0x000306E7, 0x06301A63, 0x00120213, 0x00200293, 0xFE5212E3, 0x00600193, 0x00000213,\n\t\t\t0x00000317, 0x01830313, 0x00000013, 0x00000013, 0x000306E7, 0x04301463, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0x00700193, 0x00100293, 0x00000317, 0x01C30313, 0xFFC30067, 0x00128293, 0x00128293,\n\t\t\t0x00128293, 0x00128293, 0x00128293, 0x00128293, 0x00400393, 0x00729463, 0x02301063, 0x0FF0000F,\n\t\t\t0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193,\n\t\t\t0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-lb\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0xFFF00793, 0x0003F117, 0xFF010113, 0x00010703, 0xFFF00393,\n\t\t\t0x24771A63, 0x00300193, 0x00000793, 0x0003F117, 0xFD410113, 0x00110703, 0x00000393, 0x22771C63,\n\t\t\t0x00400193, 0xFF000793, 0x0003F117, 0xFB810113, 0x00210703, 0xFF000393, 0x20771E63, 0x00500193,\n\t\t\t0x00F00793, 0x0003F117, 0xF9C10113, 0x00310703, 0x00F00393, 0x20771063, 0x00600193, 0xFFF00793,\n\t\t\t0x0003F117, 0xF8310113, 0xFFD10703, 0xFFF00393, 0x1E771263, 0x00700193, 0x00000793, 0x0003F117,\n\t\t\t0xF6710113, 0xFFE10703, 0x00000393, 0x1C771463, 0x00800193, 0xFF000793, 0x0003F117, 0xF4B10113,\n\t\t\t0xFFF10703, 0xFF000393, 0x1A771663, 0x00900193, 0x00F00793, 0x0003F117, 0xF2F10113, 0x00010703,\n\t\t\t0x00F00393, 0x18771863, 0x00A00193, 0x0003F097, 0xF1408093, 0xFE008093, 0x02008283, 0xFFF00393,\n\t\t\t0x16729A63, 0x00B00193, 0x0003F097, 0xEF808093, 0xFFA08093, 0x00708283, 0x00000393, 0x14729C63,\n\t\t\t0x00C00193, 0x00000213, 0x0003F697, 0xED968693, 0x00168703, 0x00070313, 0xFF000393, 0x12731C63,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x00D00193, 0x00000213, 0x0003F697, 0xEAE68693, 0x00168703,\n\t\t\t0x00000013, 0x00070313, 0x00F00393, 0x10731463, 0x00120213, 0x00200293, 0xFC521EE3, 0x00E00193,\n\t\t\t0x00000213, 0x0003F697, 0xE7C68693, 0x00168703, 0x00000013, 0x00000013, 0x00070313, 0x00000393,\n\t\t\t0x0C731A63, 0x00120213, 0x00200293, 0xFC521CE3, 0x00F00193, 0x00000213, 0x0003F697, 0xE4968693,\n\t\t\t0x00168703, 0xFF000393, 0x0A771663, 0x00120213, 0x00200293, 0xFE5212E3, 0x01000193, 0x00000213,\n\t\t\t0x0003F697, 0xE2268693, 0x00000013, 0x00168703, 0x00F00393, 0x08771063, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0x01100193, 0x00000213, 0x0003F697, 0xDF468693, 0x00000013, 0x00000013, 0x00168703,\n\t\t\t0x00000393, 0x04771863, 0x00120213, 0x00200293, 0xFC521EE3, 0x01200193, 0x0003F297, 0xDC828293,\n\t\t\t0x00028103, 0x00200113, 0x00200393, 0x02711463, 0x01300193, 0x0003F297, 0xDAC28293, 0x00028103,\n\t\t\t0x00000013, 0x00200113, 0x00200393, 0x00711463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193,\n\t\t\t0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513,\n\t\t\t0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0x0FF000FF, 0x00000000, 0x00000000, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-lbu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0FF00793, 0x0003F117, 0xFF010113, 0x00014703, 0x0FF00393,\n\t\t\t0x24771A63, 0x00300193, 0x00000793, 0x0003F117, 0xFD410113, 0x00114703, 0x00000393, 0x22771C63,\n\t\t\t0x00400193, 0x0F000793, 0x0003F117, 0xFB810113, 0x00214703, 0x0F000393, 0x20771E63, 0x00500193,\n\t\t\t0x00F00793, 0x0003F117, 0xF9C10113, 0x00314703, 0x00F00393, 0x20771063, 0x00600193, 0x0FF00793,\n\t\t\t0x0003F117, 0xF8310113, 0xFFD14703, 0x0FF00393, 0x1E771263, 0x00700193, 0x00000793, 0x0003F117,\n\t\t\t0xF6710113, 0xFFE14703, 0x00000393, 0x1C771463, 0x00800193, 0x0F000793, 0x0003F117, 0xF4B10113,\n\t\t\t0xFFF14703, 0x0F000393, 0x1A771663, 0x00900193, 0x00F00793, 0x0003F117, 0xF2F10113, 0x00014703,\n\t\t\t0x00F00393, 0x18771863, 0x00A00193, 0x0003F097, 0xF1408093, 0xFE008093, 0x0200C283, 0x0FF00393,\n\t\t\t0x16729A63, 0x00B00193, 0x0003F097, 0xEF808093, 0xFFA08093, 0x0070C283, 0x00000393, 0x14729C63,\n\t\t\t0x00C00193, 0x00000213, 0x0003F697, 0xED968693, 0x0016C703, 0x00070313, 0x0F000393, 0x12731C63,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x00D00193, 0x00000213, 0x0003F697, 0xEAE68693, 0x0016C703,\n\t\t\t0x00000013, 0x00070313, 0x00F00393, 0x10731463, 0x00120213, 0x00200293, 0xFC521EE3, 0x00E00193,\n\t\t\t0x00000213, 0x0003F697, 0xE7C68693, 0x0016C703, 0x00000013, 0x00000013, 0x00070313, 0x00000393,\n\t\t\t0x0C731A63, 0x00120213, 0x00200293, 0xFC521CE3, 0x00F00193, 0x00000213, 0x0003F697, 0xE4968693,\n\t\t\t0x0016C703, 0x0F000393, 0x0A771663, 0x00120213, 0x00200293, 0xFE5212E3, 0x01000193, 0x00000213,\n\t\t\t0x0003F697, 0xE2268693, 0x00000013, 0x0016C703, 0x00F00393, 0x08771063, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0x01100193, 0x00000213, 0x0003F697, 0xDF468693, 0x00000013, 0x00000013, 0x0016C703,\n\t\t\t0x00000393, 0x04771863, 0x00120213, 0x00200293, 0xFC521EE3, 0x01200193, 0x0003F297, 0xDC828293,\n\t\t\t0x0002C103, 0x00200113, 0x00200393, 0x02711463, 0x01300193, 0x0003F297, 0xDAC28293, 0x0002C103,\n\t\t\t0x00000013, 0x00200113, 0x00200393, 0x00711463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193,\n\t\t\t0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513,\n\t\t\t0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0x0FF000FF, 0x00000000, 0x00000000, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-ld_st\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0003F117, 0xFF410113, 0xFDD00093, 0x00110023, 0x00010703,\n\t\t\t0x00E10023, 0x00010103, 0xFDD00393, 0x647112E3, 0x0003F117, 0xFD010113, 0x00212423, 0x00812203,\n\t\t\t0x00120023, 0x622216E3, 0x00020703, 0x627712E3, 0x00300193, 0x0003F117, 0xFAC10113, 0xFCD00093,\n\t\t\t0x001100A3, 0x00110703, 0x00E100A3, 0x00110103, 0xFCD00393, 0x5E711EE3, 0x0003F117, 0xF8810113,\n\t\t\t0x00212423, 0x00812203, 0x001200A3, 0x5E2212E3, 0x00120703, 0x5C771EE3, 0x00400193, 0x0003F117,\n\t\t\t0xF6410113, 0xFCC00093, 0x00110123, 0x00210703, 0x00E10123, 0x00210103, 0xFCC00393, 0x5A711AE3,\n\t\t\t0x0003F117, 0xF4010113, 0x00212423, 0x00812203, 0x00120123, 0x58221EE3, 0x00220703, 0x58771AE3,\n\t\t\t0x00500193, 0x0003F117, 0xF1C10113, 0xFBC00093, 0x001101A3, 0x00310703, 0x00E101A3, 0x00310103,\n\t\t\t0xFBC00393, 0x567116E3, 0x0003F117, 0xEF810113, 0x00212423, 0x00812203, 0x001201A3, 0x54221AE3,\n\t\t\t0x00320703, 0x547716E3, 0x00600193, 0x0003F117, 0xED410113, 0xFBB00093, 0x00110223, 0x00410703,\n\t\t\t0x00E10223, 0x00410103, 0xFBB00393, 0x527112E3, 0x0003F117, 0xEB010113, 0x00212423, 0x00812203,\n\t\t\t0x00120223, 0x502216E3, 0x00420703, 0x507712E3, 0x00700193, 0x0003F117, 0xE8C10113, 0xFAB00093,\n\t\t\t0x001102A3, 0x00510703, 0x00E102A3, 0x00510103, 0xFAB00393, 0x4C711EE3, 0x0003F117, 0xE6810113,\n\t\t\t0x00212423, 0x00812203, 0x001202A3, 0x4C2212E3, 0x00520703, 0x4A771EE3, 0x00800193, 0x0003F117,\n\t\t\t0xE4410113, 0x03300093, 0x00110023, 0x00010703, 0x00E10023, 0x00010103, 0x03300393, 0x48711AE3,\n\t\t\t0x0003F117, 0xE2010113, 0x00212423, 0x00812203, 0x00120023, 0x46221EE3, 0x00020703, 0x46771AE3,\n\t\t\t0x00900193, 0x0003F117, 0xDFC10113, 0x02300093, 0x001100A3, 0x00110703, 0x00E100A3, 0x00110103,\n\t\t\t0x02300393, 0x447116E3, 0x0003F117, 0xDD810113, 0x00212423, 0x00812203, 0x001200A3, 0x42221AE3,\n\t\t\t0x00120703, 0x427716E3, 0x00A00193, 0x0003F117, 0xDB410113, 0x02200093, 0x00110123, 0x00210703,\n\t\t\t0x00E10123, 0x00210103, 0x02200393, 0x407112E3, 0x0003F117, 0xD9010113, 0x00212423, 0x00812203,\n\t\t\t0x00120123, 0x3E2216E3, 0x00220703, 0x3E7712E3, 0x00B00193, 0x0003F117, 0xD6C10113, 0x01200093,\n\t\t\t0x001101A3, 0x00310703, 0x00E101A3, 0x00310103, 0x01200393, 0x3A711EE3, 0x0003F117, 0xD4810113,\n\t\t\t0x00212423, 0x00812203, 0x001201A3, 0x3A2212E3, 0x00320703, 0x38771EE3, 0x00C00193, 0x0003F117,\n\t\t\t0xD2410113, 0x01100093, 0x00110223, 0x00410703, 0x00E10223, 0x00410103, 0x01100393, 0x36711AE3,\n\t\t\t0x0003F117, 0xD0010113, 0x00212423, 0x00812203, 0x00120223, 0x34221EE3, 0x00420703, 0x34771AE3,\n\t\t\t0x00D00193, 0x0003F117, 0xCDC10113, 0x00100093, 0x001102A3, 0x00510703, 0x00E102A3, 0x00510103,\n\t\t\t0x00100393, 0x327116E3, 0x0003F117, 0xCB810113, 0x00212423, 0x00812203, 0x001202A3, 0x30221AE3,\n\t\t\t0x00520703, 0x307716E3, 0x00E00193, 0x0003F117, 0xC9410113, 0x03300093, 0x00110023, 0x00014703,\n\t\t\t0x00E10023, 0x00014103, 0x03300393, 0x2E7112E3, 0x0003F117, 0xC7010113, 0x00212423, 0x00812203,\n\t\t\t0x00120023, 0x2C2216E3, 0x00024703, 0x2C7712E3, 0x00F00193, 0x0003F117, 0xC4C10113, 0x02300093,\n\t\t\t0x001100A3, 0x00114703, 0x00E100A3, 0x00114103, 0x02300393, 0x28711EE3, 0x0003F117, 0xC2810113,\n\t\t\t0x00212423, 0x00812203, 0x001200A3, 0x282212E3, 0x00124703, 0x26771EE3, 0x01000193, 0x0003F117,\n\t\t\t0xC0410113, 0x02200093, 0x00110123, 0x00214703, 0x00E10123, 0x00214103, 0x02200393, 0x24711AE3,\n\t\t\t0x0003F117, 0xBE010113, 0x00212423, 0x00812203, 0x00120123, 0x22221EE3, 0x00224703, 0x22771AE3,\n\t\t\t0x01100193, 0x0003F117, 0xBBC10113, 0x01200093, 0x001101A3, 0x00314703, 0x00E101A3, 0x00314103,\n\t\t\t0x01200393, 0x207116E3, 0x0003F117, 0xB9810113, 0x00212423, 0x00812203, 0x001201A3, 0x1E221AE3,\n\t\t\t0x00324703, 0x1E7716E3, 0x01200193, 0x0003F117, 0xB7410113, 0x01100093, 0x00110223, 0x00414703,\n\t\t\t0x00E10223, 0x00414103, 0x01100393, 0x1C7112E3, 0x0003F117, 0xB5010113, 0x00212423, 0x00812203,\n\t\t\t0x00120223, 0x1A2216E3, 0x00424703, 0x1A7712E3, 0x01300193, 0x0003F117, 0xB2C10113, 0x00100093,\n\t\t\t0x001102A3, 0x00514703, 0x00E102A3, 0x00514103, 0x00100393, 0x16711EE3, 0x0003F117, 0xB0810113,\n\t\t\t0x00212423, 0x00812203, 0x001202A3, 0x162212E3, 0x00524703, 0x14771EE3, 0x01400193, 0x0003F117,\n\t\t\t0xAE410113, 0xAABBD0B7, 0xCDD08093, 0x00112023, 0x00012703, 0x00E12023, 0x00012103, 0xAABBD3B7,\n\t\t\t0xCDD38393, 0x127116E3, 0x0003F117, 0xAB810113, 0x00212423, 0x00812203, 0x00122023, 0x10221AE3,\n\t\t\t0x00022703, 0x107716E3, 0x01500193, 0x0003F117, 0xA9410113, 0xDAABC0B7, 0xCCD08093, 0x00112223,\n\t\t\t0x00412703, 0x00E12223, 0x00412103, 0xDAABC3B7, 0xCCD38393, 0x0C711EE3, 0x0003F117, 0xA6810113,\n\t\t\t0x00212423, 0x00812203, 0x00122223, 0x0C2212E3, 0x00422703, 0x0A771EE3, 0x01600193, 0x0003F117,\n\t\t\t0xA4410113, 0xDDAAC0B7, 0xBCC08093, 0x00112423, 0x00812703, 0x00E12423, 0x00812103, 0xDDAAC3B7,\n\t\t\t0xBCC38393, 0x087116E3, 0x0003F117, 0xA1810113, 0x00212423, 0x00812203, 0x00122423, 0x06221AE3,\n\t\t\t0x00822703, 0x067716E3, 0x01700193, 0x0003F117, 0x9F410113, 0xCDDAB0B7, 0xBBC08093, 0x00112623,\n\t\t\t0x00C12703, 0x00E12623, 0x00C12103, 0xCDDAB3B7, 0xBBC38393, 0x02711EE3, 0x0003F117, 0x9C810113,\n\t\t\t0x00212423, 0x00812203, 0x00122623, 0x022212E3, 0x00C22703, 0x00771EE3, 0x01800193, 0x0003F117,\n\t\t\t0x9A410113, 0xCCDDB0B7, 0xABB08093, 0x00112823, 0x01012703, 0x00E12823, 0x01012103, 0xCCDDB3B7,\n\t\t\t0xABB38393, 0x7E711663, 0x0003F117, 0x97810113, 0x00212423, 0x00812203, 0x00122823, 0x7C221A63,\n\t\t\t0x01022703, 0x7C771663, 0x01900193, 0x0003F117, 0x95410113, 0xBCCDE0B7, 0xAAB08093, 0x00112A23,\n\t\t\t0x01412703, 0x00E12A23, 0x01412103, 0xBCCDE3B7, 0xAAB38393, 0x78711E63, 0x0003F117, 0x92810113,\n\t\t\t0x00212423, 0x00812203, 0x00122A23, 0x78221263, 0x01422703, 0x76771E63, 0x01A00193, 0x0003F117,\n\t\t\t0x90410113, 0x001120B7, 0x23308093, 0x00112023, 0x00012703, 0x00E12023, 0x00012103, 0x001123B7,\n\t\t\t0x23338393, 0x74711663, 0x0003F117, 0x8D810113, 0x00212423, 0x00812203, 0x00122023, 0x72221A63,\n\t\t\t0x00022703, 0x72771663, 0x01B00193, 0x0003F117, 0x8B410113, 0x300110B7, 0x22308093, 0x00112223,\n\t\t\t0x00412703, 0x00E12223, 0x00412103, 0x300113B7, 0x22338393, 0x6E711E63, 0x0003F117, 0x88810113,\n\t\t\t0x00212423, 0x00812203, 0x00122223, 0x6E221263, 0x00422703, 0x6C771E63, 0x01C00193, 0x0003F117,\n\t\t\t0x86410113, 0x330010B7, 0x12208093, 0x00112423, 0x00812703, 0x00E12423, 0x00812103, 0x330013B7,\n\t\t\t0x12238393, 0x6A711663, 0x0003F117, 0x83810113, 0x00212423, 0x00812203, 0x00122423, 0x68221A63,\n\t\t\t0x00822703, 0x68771663, 0x01D00193, 0x0003F117, 0x81410113, 0x233000B7, 0x11208093, 0x00112623,\n\t\t\t0x00C12703, 0x00E12623, 0x00C12103, 0x233003B7, 0x11238393, 0x64711E63, 0x0003E117, 0x7E810113,\n\t\t\t0x00212423, 0x00812203, 0x00122623, 0x64221263, 0x00C22703, 0x62771E63, 0x01E00193, 0x0003E117,\n\t\t\t0x7C410113, 0x223300B7, 0x01108093, 0x00112823, 0x01012703, 0x00E12823, 0x01012103, 0x223303B7,\n\t\t\t0x01138393, 0x60711663, 0x0003E117, 0x79810113, 0x00212423, 0x00812203, 0x00122823, 0x5E221A63,\n\t\t\t0x01022703, 0x5E771663, 0x01F00193, 0x0003E117, 0x77410113, 0x122330B7, 0x00108093, 0x00112A23,\n\t\t\t0x01412703, 0x00E12A23, 0x01412103, 0x122333B7, 0x00138393, 0x5A711E63, 0x0003E117, 0x74810113,\n\t\t\t0x00212423, 0x00812203, 0x00122A23, 0x5A221263, 0x01422703, 0x58771E63, 0x02000193, 0x0003E117,\n\t\t\t0x72410113, 0xFFFFD0B7, 0xCDD08093, 0x00111023, 0x00011703, 0x00E11023, 0x00011103, 0xFFFFD3B7,\n\t\t\t0xCDD38393, 0x56711663, 0x0003E117, 0x6F810113, 0x00212423, 0x00812203, 0x00121023, 0x54221A63,\n\t\t\t0x00021703, 0x54771663, 0x02100193, 0x0003E117, 0x6D410113, 0xFFFFC0B7, 0xCCD08093, 0x00111123,\n\t\t\t0x00211703, 0x00E11123, 0x00211103, 0xFFFFC3B7, 0xCCD38393, 0x50711E63, 0x0003E117, 0x6A810113,\n\t\t\t0x00212423, 0x00812203, 0x00121123, 0x50221263, 0x00221703, 0x4E771E63, 0x02200193, 0x0003E117,\n\t\t\t0x68410113, 0xFFFFC0B7, 0xBCC08093, 0x00111223, 0x00411703, 0x00E11223, 0x00411103, 0xFFFFC3B7,\n\t\t\t0xBCC38393, 0x4C711663, 0x0003E117, 0x65810113, 0x00212423, 0x00812203, 0x00121223, 0x4A221A63,\n\t\t\t0x00421703, 0x4A771663, 0x02300193, 0x0003E117, 0x63410113, 0xFFFFB0B7, 0xBBC08093, 0x00111323,\n\t\t\t0x00611703, 0x00E11323, 0x00611103, 0xFFFFB3B7, 0xBBC38393, 0x46711E63, 0x0003E117, 0x60810113,\n\t\t\t0x00212423, 0x00812203, 0x00121323, 0x46221263, 0x00621703, 0x44771E63, 0x02400193, 0x0003E117,\n\t\t\t0x5E410113, 0xFFFFB0B7, 0xABB08093, 0x00111423, 0x00811703, 0x00E11423, 0x00811103, 0xFFFFB3B7,\n\t\t\t0xABB38393, 0x42711663, 0x0003E117, 0x5B810113, 0x00212423, 0x00812203, 0x00121423, 0x40221A63,\n\t\t\t0x00821703, 0x40771663, 0x02500193, 0x0003E117, 0x59410113, 0xFFFFE0B7, 0xAAB08093, 0x00111523,\n\t\t\t0x00A11703, 0x00E11523, 0x00A11103, 0xFFFFE3B7, 0xAAB38393, 0x3C711E63, 0x0003E117, 0x56810113,\n\t\t\t0x00212423, 0x00812203, 0x00121523, 0x3C221263, 0x00A21703, 0x3A771E63, 0x02600193, 0x0003E117,\n\t\t\t0x54410113, 0x000020B7, 0x23308093, 0x00111023, 0x00011703, 0x00E11023, 0x00011103, 0x000023B7,\n\t\t\t0x23338393, 0x38711663, 0x0003E117, 0x51810113, 0x00212423, 0x00812203, 0x00121023, 0x36221A63,\n\t\t\t0x00021703, 0x36771663, 0x02700193, 0x0003E117, 0x4F410113, 0x000010B7, 0x22308093, 0x00111123,\n\t\t\t0x00211703, 0x00E11123, 0x00211103, 0x000013B7, 0x22338393, 0x32711E63, 0x0003E117, 0x4C810113,\n\t\t\t0x00212423, 0x00812203, 0x00121123, 0x32221263, 0x00221703, 0x30771E63, 0x02800193, 0x0003E117,\n\t\t\t0x4A410113, 0x000010B7, 0x12208093, 0x00111223, 0x00411703, 0x00E11223, 0x00411103, 0x000013B7,\n\t\t\t0x12238393, 0x2E711663, 0x0003E117, 0x47810113, 0x00212423, 0x00812203, 0x00121223, 0x2C221A63,\n\t\t\t0x00421703, 0x2C771663, 0x02900193, 0x0003E117, 0x45410113, 0x11200093, 0x00111323, 0x00611703,\n\t\t\t0x00E11323, 0x00611103, 0x11200393, 0x2A711263, 0x0003E117, 0x43010113, 0x00212423, 0x00812203,\n\t\t\t0x00121323, 0x28221663, 0x00621703, 0x28771263, 0x02A00193, 0x0003E117, 0x40C10113, 0x01100093,\n\t\t\t0x00111423, 0x00811703, 0x00E11423, 0x00811103, 0x01100393, 0x24711E63, 0x0003E117, 0x3E810113,\n\t\t\t0x00212423, 0x00812203, 0x00121423, 0x24221263, 0x00821703, 0x22771E63, 0x02B00193, 0x0003E117,\n\t\t\t0x3C410113, 0x000030B7, 0x00108093, 0x00111523, 0x00A11703, 0x00E11523, 0x00A11103, 0x000033B7,\n\t\t\t0x00138393, 0x20711663, 0x0003E117, 0x39810113, 0x00212423, 0x00812203, 0x00121523, 0x1E221A63,\n\t\t\t0x00A21703, 0x1E771663, 0x02C00193, 0x0003E117, 0x37410113, 0x000020B7, 0x23308093, 0x00111023,\n\t\t\t0x00015703, 0x00E11023, 0x00015103, 0x000023B7, 0x23338393, 0x1A711E63, 0x0003E117, 0x34810113,\n\t\t\t0x00212423, 0x00812203, 0x00121023, 0x1A221263, 0x00025703, 0x18771E63, 0x02D00193, 0x0003E117,\n\t\t\t0x32410113, 0x000010B7, 0x22308093, 0x00111123, 0x00215703, 0x00E11123, 0x00215103, 0x000013B7,\n\t\t\t0x22338393, 0x16711663, 0x0003E117, 0x2F810113, 0x00212423, 0x00812203, 0x00121123, 0x14221A63,\n\t\t\t0x00225703, 0x14771663, 0x02E00193, 0x0003E117, 0x2D410113, 0x000010B7, 0x12208093, 0x00111223,\n\t\t\t0x00415703, 0x00E11223, 0x00415103, 0x000013B7, 0x12238393, 0x10711E63, 0x0003E117, 0x2A810113,\n\t\t\t0x00212423, 0x00812203, 0x00121223, 0x10221263, 0x00425703, 0x0E771E63, 0x02F00193, 0x0003E117,\n\t\t\t0x28410113, 0x11200093, 0x00111323, 0x00615703, 0x00E11323, 0x00615103, 0x11200393, 0x0C711A63,\n\t\t\t0x0003E117, 0x26010113, 0x00212423, 0x00812203, 0x00121323, 0x0A221E63, 0x00625703, 0x0A771A63,\n\t\t\t0x03000193, 0x0003E117, 0x23C10113, 0x01100093, 0x00111423, 0x00815703, 0x00E11423, 0x00815103,\n\t\t\t0x01100393, 0x08711663, 0x0003E117, 0x21810113, 0x00212423, 0x00812203, 0x00121423, 0x06221A63,\n\t\t\t0x00825703, 0x06771663, 0x03100193, 0x0003E117, 0x1F410113, 0x000030B7, 0x00108093, 0x00111523,\n\t\t\t0x00A15703, 0x00E11523, 0x00A15103, 0x000033B7, 0x00138393, 0x02711E63, 0x0003E117, 0x1C810113,\n\t\t\t0x00212423, 0x00812203, 0x00121523, 0x02221263, 0x00A25703, 0x00771E63, 0x0EF00513, 0x0003E597,\n\t\t\t0x1A458593, 0x00A581A3, 0x00358603, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF,\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF,\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-lh\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0FF00793, 0x0003F117, 0xFF010113, 0x00011703, 0x0FF00393,\n\t\t\t0x28771263, 0x00300193, 0xF0000793, 0x0003F117, 0xFD410113, 0x00211703, 0xF0000393, 0x26771463,\n\t\t\t0x00400193, 0x000017B7, 0xFF078793, 0x0003F117, 0xFB410113, 0x00411703, 0x000013B7, 0xFF038393,\n\t\t\t0x24771263, 0x00500193, 0xFFFFF7B7, 0x00F78793, 0x0003F117, 0xF9010113, 0x00611703, 0xFFFFF3B7,\n\t\t\t0x00F38393, 0x22771063, 0x00600193, 0x0FF00793, 0x0003F117, 0xF7610113, 0xFFA11703, 0x0FF00393,\n\t\t\t0x20771263, 0x00700193, 0xF0000793, 0x0003F117, 0xF5A10113, 0xFFC11703, 0xF0000393, 0x1E771463,\n\t\t\t0x00800193, 0x000017B7, 0xFF078793, 0x0003F117, 0xF3A10113, 0xFFE11703, 0x000013B7, 0xFF038393,\n\t\t\t0x1C771263, 0x00900193, 0xFFFFF7B7, 0x00F78793, 0x0003F117, 0xF1610113, 0x00011703, 0xFFFFF3B7,\n\t\t\t0x00F38393, 0x1A771063, 0x00A00193, 0x0003F097, 0xEF408093, 0xFE008093, 0x02009283, 0x0FF00393,\n\t\t\t0x18729263, 0x00B00193, 0x0003F097, 0xED808093, 0xFFB08093, 0x00709283, 0xF0000393, 0x16729463,\n\t\t\t0x00C00193, 0x00000213, 0x0003F697, 0xEBA68693, 0x00269703, 0x00070313, 0x000013B7, 0xFF038393,\n\t\t\t0x14731263, 0x00120213, 0x00200293, 0xFC521EE3, 0x00D00193, 0x00000213, 0x0003F697, 0xE8C68693,\n\t\t\t0x00269703, 0x00000013, 0x00070313, 0xFFFFF3B7, 0x00F38393, 0x10731863, 0x00120213, 0x00200293,\n\t\t\t0xFC521CE3, 0x00E00193, 0x00000213, 0x0003F697, 0xE5468693, 0x00269703, 0x00000013, 0x00000013,\n\t\t\t0x00070313, 0xF0000393, 0x0C731E63, 0x00120213, 0x00200293, 0xFC521CE3, 0x00F00193, 0x00000213,\n\t\t\t0x0003F697, 0xE2268693, 0x00269703, 0x000013B7, 0xFF038393, 0x0A771863, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0x01000193, 0x00000213, 0x0003F697, 0xDF868693, 0x00000013, 0x00269703, 0xFFFFF3B7,\n\t\t\t0x00F38393, 0x08771063, 0x00120213, 0x00200293, 0xFC521EE3, 0x01100193, 0x00000213, 0x0003F697,\n\t\t\t0xDC468693, 0x00000013, 0x00000013, 0x00269703, 0xF0000393, 0x04771863, 0x00120213, 0x00200293,\n\t\t\t0xFC521EE3, 0x01200193, 0x0003F297, 0xD9828293, 0x00029103, 0x00200113, 0x00200393, 0x02711463,\n\t\t\t0x01300193, 0x0003F297, 0xD7C28293, 0x00029103, 0x00000013, 0x00200113, 0x00200393, 0x00711463,\n\t\t\t0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073,\n\t\t\t0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0xFF0000FF, 0xF00F0FF0, 0x00000000, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-lhu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0FF00793, 0x0003F117, 0xFF010113, 0x00015703, 0x0FF00393,\n\t\t\t0x2A771063, 0x00300193, 0x000107B7, 0xF0078793, 0x0003F117, 0xFD010113, 0x00215703, 0x000103B7,\n\t\t\t0xF0038393, 0x26771E63, 0x00400193, 0x000017B7, 0xFF078793, 0x0003F117, 0xFAC10113, 0x00415703,\n\t\t\t0x000013B7, 0xFF038393, 0x24771C63, 0x00500193, 0x0000F7B7, 0x00F78793, 0x0003F117, 0xF8810113,\n\t\t\t0x00615703, 0x0000F3B7, 0x00F38393, 0x22771A63, 0x00600193, 0x0FF00793, 0x0003F117, 0xF6E10113,\n\t\t\t0xFFA15703, 0x0FF00393, 0x20771C63, 0x00700193, 0x000107B7, 0xF0078793, 0x0003F117, 0xF4E10113,\n\t\t\t0xFFC15703, 0x000103B7, 0xF0038393, 0x1E771A63, 0x00800193, 0x000017B7, 0xFF078793, 0x0003F117,\n\t\t\t0xF2A10113, 0xFFE15703, 0x000013B7, 0xFF038393, 0x1C771863, 0x00900193, 0x0000F7B7, 0x00F78793,\n\t\t\t0x0003F117, 0xF0610113, 0x00015703, 0x0000F3B7, 0x00F38393, 0x1A771663, 0x00A00193, 0x0003F097,\n\t\t\t0xEE408093, 0xFE008093, 0x0200D283, 0x0FF00393, 0x18729863, 0x00B00193, 0x0003F097, 0xEC808093,\n\t\t\t0xFFB08093, 0x0070D283, 0x000103B7, 0xF0038393, 0x16729863, 0x00C00193, 0x00000213, 0x0003F697,\n\t\t\t0xEA668693, 0x0026D703, 0x00070313, 0x000013B7, 0xFF038393, 0x14731663, 0x00120213, 0x00200293,\n\t\t\t0xFC521EE3, 0x00D00193, 0x00000213, 0x0003F697, 0xE7868693, 0x0026D703, 0x00000013, 0x00070313,\n\t\t\t0x0000F3B7, 0x00F38393, 0x10731C63, 0x00120213, 0x00200293, 0xFC521CE3, 0x00E00193, 0x00000213,\n\t\t\t0x0003F697, 0xE4068693, 0x0026D703, 0x00000013, 0x00000013, 0x00070313, 0x000103B7, 0xF0038393,\n\t\t\t0x0E731063, 0x00120213, 0x00200293, 0xFC521AE3, 0x00F00193, 0x00000213, 0x0003F697, 0xE0A68693,\n\t\t\t0x0026D703, 0x000013B7, 0xFF038393, 0x0A771A63, 0x00120213, 0x00200293, 0xFE5210E3, 0x01000193,\n\t\t\t0x00000213, 0x0003F697, 0xDE068693, 0x00000013, 0x0026D703, 0x0000F3B7, 0x00F38393, 0x08771263,\n\t\t\t0x00120213, 0x00200293, 0xFC521EE3, 0x01100193, 0x00000213, 0x0003F697, 0xDAC68693, 0x00000013,\n\t\t\t0x00000013, 0x0026D703, 0x000103B7, 0xF0038393, 0x04771863, 0x00120213, 0x00200293, 0xFC521CE3,\n\t\t\t0x01200193, 0x0003F297, 0xD7C28293, 0x0002D103, 0x00200113, 0x00200393, 0x02711463, 0x01300193,\n\t\t\t0x0003F297, 0xD6028293, 0x0002D103, 0x00000013, 0x00200113, 0x00200393, 0x00711463, 0x02301063,\n\t\t\t0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F,\n\t\t\t0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0xFF0000FF, 0xF00F0FF0, 0x00000000, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-lui\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x000000B7, 0x00000393, 0x04709A63, 0x00300193, 0xFFFFF0B7,\n\t\t\t0x4010D093, 0x80000393, 0x04709063, 0x00400193, 0x7FFFF0B7, 0x4140D093, 0x7FF00393, 0x02709663,\n\t\t\t0x00500193, 0x800000B7, 0x4140D093, 0x80000393, 0x00709C63, 0x00600193, 0x80000037, 0x00000393,\n\t\t\t0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-lw\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00FF07B7, 0x0FF78793, 0x0003F117, 0xFEC10113, 0x00012703,\n\t\t\t0x00FF03B7, 0x0FF38393, 0x2A771663, 0x00300193, 0xFF0107B7, 0xF0078793, 0x0003F117, 0xFC810113,\n\t\t\t0x00412703, 0xFF0103B7, 0xF0038393, 0x28771463, 0x00400193, 0x0FF017B7, 0xFF078793, 0x0003F117,\n\t\t\t0xFA410113, 0x00812703, 0x0FF013B7, 0xFF038393, 0x26771263, 0x00500193, 0xF00FF7B7, 0x00F78793,\n\t\t\t0x0003F117, 0xF8010113, 0x00C12703, 0xF00FF3B7, 0x00F38393, 0x24771063, 0x00600193, 0x00FF07B7,\n\t\t\t0x0FF78793, 0x0003F117, 0xF6810113, 0xFF412703, 0x00FF03B7, 0x0FF38393, 0x20771E63, 0x00700193,\n\t\t\t0xFF0107B7, 0xF0078793, 0x0003F117, 0xF4410113, 0xFF812703, 0xFF0103B7, 0xF0038393, 0x1E771C63,\n\t\t\t0x00800193, 0x0FF017B7, 0xFF078793, 0x0003F117, 0xF2010113, 0xFFC12703, 0x0FF013B7, 0xFF038393,\n\t\t\t0x1C771A63, 0x00900193, 0xF00FF7B7, 0x00F78793, 0x0003F117, 0xEFC10113, 0x00012703, 0xF00FF3B7,\n\t\t\t0x00F38393, 0x1A771863, 0x00A00193, 0x0003F097, 0xED408093, 0xFE008093, 0x0200A283, 0x00FF03B7,\n\t\t\t0x0FF38393, 0x18729863, 0x00B00193, 0x0003F097, 0xEB408093, 0xFFD08093, 0x0070A283, 0xFF0103B7,\n\t\t\t0xF0038393, 0x16729863, 0x00C00193, 0x00000213, 0x0003F697, 0xE9468693, 0x0046A703, 0x00070313,\n\t\t\t0x0FF013B7, 0xFF038393, 0x14731663, 0x00120213, 0x00200293, 0xFC521EE3, 0x00D00193, 0x00000213,\n\t\t\t0x0003F697, 0xE6868693, 0x0046A703, 0x00000013, 0x00070313, 0xF00FF3B7, 0x00F38393, 0x10731C63,\n\t\t\t0x00120213, 0x00200293, 0xFC521CE3, 0x00E00193, 0x00000213, 0x0003F697, 0xE2C68693, 0x0046A703,\n\t\t\t0x00000013, 0x00000013, 0x00070313, 0xFF0103B7, 0xF0038393, 0x0E731063, 0x00120213, 0x00200293,\n\t\t\t0xFC521AE3, 0x00F00193, 0x00000213, 0x0003F697, 0xDF868693, 0x0046A703, 0x0FF013B7, 0xFF038393,\n\t\t\t0x0A771A63, 0x00120213, 0x00200293, 0xFE5210E3, 0x01000193, 0x00000213, 0x0003F697, 0xDD068693,\n\t\t\t0x00000013, 0x0046A703, 0xF00FF3B7, 0x00F38393, 0x08771263, 0x00120213, 0x00200293, 0xFC521EE3,\n\t\t\t0x01100193, 0x00000213, 0x0003F697, 0xD9868693, 0x00000013, 0x00000013, 0x0046A703, 0xFF0103B7,\n\t\t\t0xF0038393, 0x04771863, 0x00120213, 0x00200293, 0xFC521CE3, 0x01200193, 0x0003F297, 0xD6828293,\n\t\t\t0x0002A103, 0x00200113, 0x00200393, 0x02711463, 0x01300193, 0x0003F297, 0xD4C28293, 0x0002A103,\n\t\t\t0x00000013, 0x00200113, 0x00200393, 0x00711463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193,\n\t\t\t0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513,\n\t\t\t0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0x00FF00FF, 0xFF00FF00, 0x0FF00FF0, 0xF00FF00F,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-ma_data\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x0003F417, 0xFF840413, 0x00100193, 0x20100313, 0x00141383, 0x52731C63,\n\t\t\t0x00200193, 0x20100313, 0x00145383, 0x52731463, 0x00300193, 0x04030337, 0x20130313, 0x00142383,\n\t\t\t0x50731A63, 0x00400193, 0x05040337, 0x30230313, 0x00242383, 0x50731063, 0x00500193, 0x06050337,\n\t\t\t0x40330313, 0x00342383, 0x4E731663, 0x01000193, 0x00002337, 0x01F30313, 0x01F41383, 0x4C731C63,\n\t\t\t0x01100193, 0x00002337, 0x01F30313, 0x01F45383, 0x4C731263, 0x01200193, 0x201F2337, 0xE1D30313,\n\t\t\t0x01D42383, 0x4A731863, 0x01300193, 0x21202337, 0xF1E30313, 0x01E42383, 0x48731E63, 0x01400193,\n\t\t\t0x22212337, 0x01F30313, 0x01F42383, 0x48731463, 0x01F00193, 0x00004337, 0x03F30313, 0x03F41383,\n\t\t\t0x46731A63, 0x02000193, 0x00004337, 0x03F30313, 0x03F45383, 0x46731063, 0x02100193, 0x403F4337,\n\t\t\t0xE3D30313, 0x03D42383, 0x44731663, 0x02200193, 0x41404337, 0xF3E30313, 0x03E42383, 0x42731C63,\n\t\t\t0x02300193, 0x42414337, 0x03F30313, 0x03F42383, 0x42731263, 0x02E00193, 0xFFFF8337, 0x18030313,\n\t\t\t0x006410A3, 0x00141383, 0x40731663, 0x02F00193, 0x00008337, 0x38230313, 0x006410A3, 0x00145383,\n\t\t\t0x3E731A63, 0x03000193, 0x87868337, 0x58430313, 0x006420A3, 0x00142383, 0x3C731E63, 0x03100193,\n\t\t\t0x8B8A9337, 0x98830313, 0x00642123, 0x00242383, 0x3C731263, 0x03200193, 0x8F8E9337, 0xD8C30313,\n\t\t\t0x006421A3, 0x00342383, 0x3A731663, 0x03D00193, 0xFFFFD337, 0x5D430313, 0x00641FA3, 0x01F41383,\n\t\t\t0x38731A63, 0x03E00193, 0x0000D337, 0x7D630313, 0x00641FA3, 0x01F45383, 0x36731E63, 0x03F00193,\n\t\t\t0xDBDAE337, 0x9D830313, 0x00642EA3, 0x01D42383, 0x36731263, 0x04000193, 0xDFDEE337, 0xDDC30313,\n\t\t\t0x00642F23, 0x01E42383, 0x34731663, 0x04100193, 0xE3E2E337, 0x1E030313, 0x00642FA3, 0x01F42383,\n\t\t\t0x32731A63, 0x04C00193, 0x00003337, 0x53430313, 0x02641FA3, 0x03F41383, 0x30731E63, 0x04D00193,\n\t\t\t0x00003337, 0x73630313, 0x02641FA3, 0x03F45383, 0x30731263, 0x04E00193, 0x3B3A4337, 0x93830313,\n\t\t\t0x02642EA3, 0x03D42383, 0x2E731663, 0x04F00193, 0x3F3E4337, 0xD3C30313, 0x02642F23, 0x03E42383,\n\t\t\t0x2C731A63, 0x05000193, 0x43424337, 0x14030313, 0x02642FA3, 0x03F42383, 0x2A731E63, 0x05B00193,\n\t\t\t0x0000A337, 0x99830313, 0xF9800393, 0x006410A3, 0x00140E03, 0x2BC39063, 0x05C00193, 0x0000A337,\n\t\t\t0xB9A30313, 0xF9B00393, 0x006410A3, 0x00240E03, 0x29C39263, 0x05D00193, 0x0000A337, 0xD9C30313,\n\t\t\t0x09C00393, 0x006410A3, 0x00144E03, 0x27C39463, 0x05E00193, 0x0000A337, 0xF9E30313, 0x09F00393,\n\t\t\t0x006410A3, 0x00244E03, 0x25C39663, 0x05F00193, 0xA3A2A337, 0x1A030313, 0xFA000393, 0x006420A3,\n\t\t\t0x00140E03, 0x23C39863, 0x06000193, 0xA7A6A337, 0x5A430313, 0x0A500393, 0x00642123, 0x00344E03,\n\t\t\t0x21C39A63, 0x06100193, 0xABAAB337, 0x9A830313, 0xFFFFB3B7, 0xAA938393, 0x006421A3, 0x00441E03,\n\t\t\t0x1FC39A63, 0x06200193, 0xAFAEB337, 0xDAC30313, 0x0000B3B7, 0xFAE38393, 0x006421A3, 0x00545E03,\n\t\t\t0x1DC39A63, 0x06A00193, 0x0000F337, 0x9E830313, 0xFE800393, 0x00641FA3, 0x01F40E03, 0x1BC39C63,\n\t\t\t0x06B00193, 0x0000F337, 0xBEA30313, 0xFEB00393, 0x00641FA3, 0x02040E03, 0x19C39E63, 0x06C00193,\n\t\t\t0x0000F337, 0xDEC30313, 0x0EC00393, 0x00641FA3, 0x01F44E03, 0x19C39063, 0x06D00193, 0x0000F337,\n\t\t\t0xFEE30313, 0x0EF00393, 0x00641FA3, 0x02044E03, 0x17C39263, 0x06E00193, 0xF3F2F337, 0x1F030313,\n\t\t\t0xFF000393, 0x00642EA3, 0x01D40E03, 0x15C39463, 0x06F00193, 0xF7F6F337, 0x5F430313, 0x0F600393,\n\t\t\t0x00642F23, 0x02044E03, 0x13C39663, 0x07000193, 0xFBFB0337, 0x9F830313, 0xBFA00393, 0x00642EA3,\n\t\t\t0x01F41E03, 0x11C39863, 0x07100193, 0xFFFF0337, 0xDFC30313, 0x000103B7, 0xDFC38393, 0x00642FA3,\n\t\t\t0x01F45E03, 0x0FC39863, 0x07900193, 0x00005337, 0x94830313, 0x04800393, 0x02641FA3, 0x03F40E03,\n\t\t\t0x0DC39A63, 0x07A00193, 0x00005337, 0xB4A30313, 0x04B00393, 0x02641FA3, 0x04040E03, 0x0BC39C63,\n\t\t\t0x07B00193, 0x00005337, 0xD4C30313, 0x04C00393, 0x02641FA3, 0x03F44E03, 0x09C39E63, 0x07C00193,\n\t\t\t0x00005337, 0xF4E30313, 0x04F00393, 0x02641FA3, 0x04044E03, 0x09C39063, 0x07D00193, 0x53525337,\n\t\t\t0x15030313, 0x05000393, 0x02642EA3, 0x03D40E03, 0x07C39263, 0x07E00193, 0x57565337, 0x55430313,\n\t\t\t0x05600393, 0x02642F23, 0x04044E03, 0x05C39463, 0x07F00193, 0x5B5A6337, 0x95830313, 0x000063B7,\n\t\t\t0xB5A38393, 0x02642EA3, 0x03F41E03, 0x03C39463, 0x08000193, 0x5F5E6337, 0xD5C30313, 0x000063B7,\n\t\t\t0xD5C38393, 0x02642FA3, 0x03F45E03, 0x01C39463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193,\n\t\t\t0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513,\n\t\t\t0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0x03020100, 0x07060504, 0x0B0A0908, 0x0F0E0D0C, 0x13121110, 0x17161514, 0x1B1A1918, 0x1F1E1D1C,\n\t\t\t0x23222120, 0x27262524, 0x2B2A2928, 0x2F2E2D2C, 0x33323130, 0x37363534, 0x3B3A3938, 0x3F3E3D3C,\n\t\t\t0x43424140, 0x47464544, 0x4B4A4948, 0x4F4E4D4C, 0x53525150, 0x57565554, 0x5B5A5958, 0x5F5E5D5C,\n\t\t\t0x63626160, 0x67666564, 0x6B6A6968, 0x6F6E6D6C, 0x73727170, 0x77767574, 0x7B7A7978, 0x7F7E7D7C,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050,\n\t\t\t0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x50505050, 0x00505050,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-or\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0xFF0105B7, 0xF0058593, 0x0F0F1637, 0xF0F60613, 0x00C5E733,\n\t\t\t0xFF1003B7, 0xF0F38393, 0x4A771263, 0x00300193, 0x0FF015B7, 0xFF058593, 0xF0F0F637, 0x0F060613,\n\t\t\t0x00C5E733, 0xFFF103B7, 0xFF038393, 0x48771063, 0x00400193, 0x00FF05B7, 0x0FF58593, 0x0F0F1637,\n\t\t\t0xF0F60613, 0x00C5E733, 0x0FFF13B7, 0xFFF38393, 0x44771E63, 0x00500193, 0xF00FF5B7, 0x00F58593,\n\t\t\t0xF0F0F637, 0x0F060613, 0x00C5E733, 0xF0FFF3B7, 0x0FF38393, 0x42771C63, 0x00600193, 0xFF0105B7,\n\t\t\t0xF0058593, 0x0F0F1637, 0xF0F60613, 0x00C5E5B3, 0xFF1003B7, 0xF0F38393, 0x40759A63, 0x00700193,\n\t\t\t0xFF0105B7, 0xF0058593, 0x0F0F1637, 0xF0F60613, 0x00C5E633, 0xFF1003B7, 0xF0F38393, 0x3E761863,\n\t\t\t0x00800193, 0xFF0105B7, 0xF0058593, 0x00B5E5B3, 0xFF0103B7, 0xF0038393, 0x3C759A63, 0x00900193,\n\t\t\t0x00000213, 0xFF0100B7, 0xF0008093, 0x0F0F1137, 0xF0F10113, 0x0020E733, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5210E3, 0xFF1003B7, 0xF0F38393, 0x38731E63, 0x00A00193, 0x00000213, 0x0FF010B7,\n\t\t\t0xFF008093, 0xF0F0F137, 0x0F010113, 0x0020E733, 0x00000013, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFC521EE3, 0xFFF103B7, 0xFF038393, 0x36731063, 0x00B00193, 0x00000213, 0x00FF00B7, 0x0FF08093,\n\t\t\t0x0F0F1137, 0xF0F10113, 0x0020E733, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFC521CE3, 0x0FFF13B7, 0xFFF38393, 0x32731063, 0x00C00193, 0x00000213, 0xFF0100B7, 0xF0008093,\n\t\t\t0x0F0F1137, 0xF0F10113, 0x0020E733, 0x00120213, 0x00200293, 0xFE5212E3, 0xFF1003B7, 0xF0F38393,\n\t\t\t0x2E771663, 0x00D00193, 0x00000213, 0x0FF010B7, 0xFF008093, 0xF0F0F137, 0x0F010113, 0x00000013,\n\t\t\t0x0020E733, 0x00120213, 0x00200293, 0xFE5210E3, 0xFFF103B7, 0xFF038393, 0x2A771A63, 0x00E00193,\n\t\t\t0x00000213, 0x00FF00B7, 0x0FF08093, 0x0F0F1137, 0xF0F10113, 0x00000013, 0x00000013, 0x0020E733,\n\t\t\t0x00120213, 0x00200293, 0xFC521EE3, 0x0FFF13B7, 0xFFF38393, 0x26771C63, 0x00F00193, 0x00000213,\n\t\t\t0xFF0100B7, 0xF0008093, 0x00000013, 0x0F0F1137, 0xF0F10113, 0x0020E733, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0xFF1003B7, 0xF0F38393, 0x24771063, 0x01000193, 0x00000213, 0x0FF010B7, 0xFF008093,\n\t\t\t0x00000013, 0xF0F0F137, 0x0F010113, 0x00000013, 0x0020E733, 0x00120213, 0x00200293, 0xFC521EE3,\n\t\t\t0xFFF103B7, 0xFF038393, 0x20771263, 0x01100193, 0x00000213, 0x00FF00B7, 0x0FF08093, 0x00000013,\n\t\t\t0x00000013, 0x0F0F1137, 0xF0F10113, 0x0020E733, 0x00120213, 0x00200293, 0xFC521EE3, 0x0FFF13B7,\n\t\t\t0xFFF38393, 0x1C771463, 0x01200193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0xFF0100B7, 0xF0008093,\n\t\t\t0x0020E733, 0x00120213, 0x00200293, 0xFE5212E3, 0xFF1003B7, 0xF0F38393, 0x18771A63, 0x01300193,\n\t\t\t0x00000213, 0xF0F0F137, 0x0F010113, 0x0FF010B7, 0xFF008093, 0x00000013, 0x0020E733, 0x00120213,\n\t\t\t0x00200293, 0xFE5210E3, 0xFFF103B7, 0xFF038393, 0x14771E63, 0x01400193, 0x00000213, 0x0F0F1137,\n\t\t\t0xF0F10113, 0x00FF00B7, 0x0FF08093, 0x00000013, 0x00000013, 0x0020E733, 0x00120213, 0x00200293,\n\t\t\t0xFC521EE3, 0x0FFF13B7, 0xFFF38393, 0x12771063, 0x01500193, 0x00000213, 0x0F0F1137, 0xF0F10113,\n\t\t\t0x00000013, 0xFF0100B7, 0xF0008093, 0x0020E733, 0x00120213, 0x00200293, 0xFE5210E3, 0xFF1003B7,\n\t\t\t0xF0F38393, 0x0E771463, 0x01600193, 0x00000213, 0xF0F0F137, 0x0F010113, 0x00000013, 0x0FF010B7,\n\t\t\t0xFF008093, 0x00000013, 0x0020E733, 0x00120213, 0x00200293, 0xFC521EE3, 0xFFF103B7, 0xFF038393,\n\t\t\t0x0A771663, 0x01700193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0x00000013, 0x00000013, 0x00FF00B7,\n\t\t\t0x0FF08093, 0x0020E733, 0x00120213, 0x00200293, 0xFC521EE3, 0x0FFF13B7, 0xFFF38393, 0x06771863,\n\t\t\t0x01800193, 0xFF0100B7, 0xF0008093, 0x00106133, 0xFF0103B7, 0xF0038393, 0x04711A63, 0x01900193,\n\t\t\t0x00FF00B7, 0x0FF08093, 0x0000E133, 0x00FF03B7, 0x0FF38393, 0x02711C63, 0x01A00193, 0x000060B3,\n\t\t\t0x00000393, 0x02709463, 0x01B00193, 0x111110B7, 0x11108093, 0x22222137, 0x22210113, 0x0020E033,\n\t\t\t0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893,\n\t\t\t0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-ori\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0xFF0106B7, 0xF0068693, 0xF0F6E713, 0xF0F00393, 0x1C771463,\n\t\t\t0x00300193, 0x0FF016B7, 0xFF068693, 0x0F06E713, 0x0FF013B7, 0xFF038393, 0x1A771663, 0x00400193,\n\t\t\t0x00FF06B7, 0x0FF68693, 0x70F6E713, 0x00FF03B7, 0x7FF38393, 0x18771863, 0x00500193, 0xF00FF6B7,\n\t\t\t0x00F68693, 0x0F06E713, 0xF00FF3B7, 0x0FF38393, 0x16771A63, 0x00600193, 0xFF0105B7, 0xF0058593,\n\t\t\t0x0F05E593, 0xFF0103B7, 0xFF038393, 0x14759C63, 0x00700193, 0x00000213, 0x0FF010B7, 0xFF008093,\n\t\t\t0x0F00E713, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x0FF013B7, 0xFF038393, 0x12731463,\n\t\t\t0x00800193, 0x00000213, 0x00FF00B7, 0x0FF08093, 0x70F0E713, 0x00000013, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x00FF03B7, 0x7FF38393, 0x0E731A63, 0x00900193, 0x00000213, 0xF00FF0B7,\n\t\t\t0x00F08093, 0x0F00E713, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0xF00FF3B7, 0x0FF38393, 0x0A731E63, 0x00A00193, 0x00000213, 0x0FF010B7, 0xFF008093, 0x0F00E713,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x0FF013B7, 0xFF038393, 0x08771863, 0x00B00193, 0x00000213,\n\t\t\t0x00FF00B7, 0x0FF08093, 0x00000013, 0xF0F0E713, 0x00120213, 0x00200293, 0xFE5214E3, 0xFFF00393,\n\t\t\t0x06771263, 0x00C00193, 0x00000213, 0xF00FF0B7, 0x00F08093, 0x00000013, 0x00000013, 0x0F00E713,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0xF00FF3B7, 0x0FF38393, 0x02771863, 0x00D00193, 0x0F006093,\n\t\t\t0x0F000393, 0x02709063, 0x00E00193, 0x00FF00B7, 0x0FF08093, 0x70F0E013, 0x00000393, 0x00701463,\n\t\t\t0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073,\n\t\t\t0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sb\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0003F117, 0xFF410113, 0xFAA00093, 0x00000797, 0x01478793,\n\t\t\t0x00110023, 0x00010703, 0x0080006F, 0x00008713, 0xFAA00393, 0x44771463, 0x00300193, 0x0003F117,\n\t\t\t0xFC410113, 0x00000093, 0x00000797, 0x01478793, 0x001100A3, 0x00110703, 0x0080006F, 0x00008713,\n\t\t\t0x00000393, 0x40771C63, 0x00400193, 0x0003F117, 0xF9410113, 0xFFFFF0B7, 0xFA008093, 0x00000797,\n\t\t\t0x01478793, 0x00110123, 0x00211703, 0x0080006F, 0x00008713, 0xFFFFF3B7, 0xFA038393, 0x3E771063,\n\t\t\t0x00500193, 0x0003F117, 0xF5C10113, 0x00A00093, 0x00000797, 0x01478793, 0x001101A3, 0x00310703,\n\t\t\t0x0080006F, 0x00008713, 0x00A00393, 0x3A771863, 0x00600193, 0x0003F117, 0xF3310113, 0xFAA00093,\n\t\t\t0x00000797, 0x01478793, 0xFE110EA3, 0xFFD10703, 0x0080006F, 0x00008713, 0xFAA00393, 0x38771063,\n\t\t\t0x00700193, 0x0003F117, 0xF0310113, 0x00000093, 0x00000797, 0x01478793, 0xFE110F23, 0xFFE10703,\n\t\t\t0x0080006F, 0x00008713, 0x00000393, 0x34771863, 0x00800193, 0x0003F117, 0xED310113, 0xFA000093,\n\t\t\t0x00000797, 0x01478793, 0xFE110FA3, 0xFFF10703, 0x0080006F, 0x00008713, 0xFA000393, 0x32771063,\n\t\t\t0x00900193, 0x0003F117, 0xEA310113, 0x00A00093, 0x00000797, 0x01478793, 0x00110023, 0x00010703,\n\t\t\t0x0080006F, 0x00008713, 0x00A00393, 0x2E771863, 0x00A00193, 0x0003F097, 0xE7408093, 0x12345137,\n\t\t\t0x67810113, 0xFE008213, 0x02220023, 0x00008283, 0x07800393, 0x2C729463, 0x00B00193, 0x0003F097,\n\t\t\t0xE4C08093, 0x00003137, 0x09810113, 0xFFA08093, 0x002083A3, 0x0003F217, 0xE3520213, 0x00020283,\n\t\t\t0xF9800393, 0x28729C63, 0x00C00193, 0x00000213, 0xFDD00693, 0x0003F617, 0xE0C60613, 0x00D60023,\n\t\t\t0x00060703, 0xFDD00393, 0x26771A63, 0x00120213, 0x00200293, 0xFC521EE3, 0x00D00193, 0x00000213,\n\t\t\t0xFCD00693, 0x0003F617, 0xDDC60613, 0x00000013, 0x00D600A3, 0x00160703, 0xFCD00393, 0x24771063,\n\t\t\t0x00120213, 0x00200293, 0xFC521CE3, 0x00E00193, 0x00000213, 0xFCC00693, 0x0003F617, 0xDA860613,\n\t\t\t0x00000013, 0x00000013, 0x00D60123, 0x00260703, 0xFCC00393, 0x20771463, 0x00120213, 0x00200293,\n\t\t\t0xFC521AE3, 0x00F00193, 0x00000213, 0xFBC00693, 0x00000013, 0x0003F617, 0xD6C60613, 0x00D601A3,\n\t\t\t0x00360703, 0xFBC00393, 0x1C771A63, 0x00120213, 0x00200293, 0xFC521CE3, 0x01000193, 0x00000213,\n\t\t\t0xFBB00693, 0x00000013, 0x0003F617, 0xD3860613, 0x00000013, 0x00D60223, 0x00460703, 0xFBB00393,\n\t\t\t0x18771E63, 0x00120213, 0x00200293, 0xFC521AE3, 0x01100193, 0x00000213, 0xFAB00693, 0x00000013,\n\t\t\t0x00000013, 0x0003F617, 0xCFC60613, 0x00D602A3, 0x00560703, 0xFAB00393, 0x16771263, 0x00120213,\n\t\t\t0x00200293, 0xFC521AE3, 0x01200193, 0x00000213, 0x0003F117, 0xCD010113, 0x03300093, 0x00110023,\n\t\t\t0x00010703, 0x03300393, 0x12771A63, 0x00120213, 0x00200293, 0xFC521EE3, 0x01300193, 0x00000213,\n\t\t\t0x0003F117, 0xCA010113, 0x02300093, 0x00000013, 0x001100A3, 0x00110703, 0x02300393, 0x10771063,\n\t\t\t0x00120213, 0x00200293, 0xFC521CE3, 0x01400193, 0x00000213, 0x0003F117, 0xC6C10113, 0x02200093,\n\t\t\t0x00000013, 0x00000013, 0x00110123, 0x00210703, 0x02200393, 0x0C771463, 0x00120213, 0x00200293,\n\t\t\t0xFC521AE3, 0x01500193, 0x00000213, 0x0003F117, 0xC3410113, 0x00000013, 0x01200093, 0x001101A3,\n\t\t\t0x00310703, 0x01200393, 0x08771A63, 0x00120213, 0x00200293, 0xFC521CE3, 0x01600193, 0x00000213,\n\t\t\t0x0003F117, 0xC0010113, 0x00000013, 0x01100093, 0x00000013, 0x00110223, 0x00410703, 0x01100393,\n\t\t\t0x04771E63, 0x00120213, 0x00200293, 0xFC521AE3, 0x01700193, 0x00000213, 0x0003F117, 0xBC810113,\n\t\t\t0x00000013, 0x00000013, 0x00100093, 0x001102A3, 0x00510703, 0x00100393, 0x02771263, 0x00120213,\n\t\t\t0x00200293, 0xFC521AE3, 0x0EF00513, 0x0003F597, 0xB9458593, 0x00A581A3, 0x02301063, 0x0FF0000F,\n\t\t\t0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193,\n\t\t\t0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0xEFEFEFEF, 0xEFEFEFEF, 0x0000EFEF, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sh\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0003F117, 0xFF410113, 0x0AA00093, 0x00000797, 0x01478793,\n\t\t\t0x00111023, 0x00011703, 0x0080006F, 0x00008713, 0x0AA00393, 0x4C771663, 0x00300193, 0x0003F117,\n\t\t\t0xFC410113, 0xFFFFB0B7, 0xA0008093, 0x00000797, 0x01478793, 0x00111123, 0x00211703, 0x0080006F,\n\t\t\t0x00008713, 0xFFFFB3B7, 0xA0038393, 0x48771A63, 0x00400193, 0x0003F117, 0xF8C10113, 0xBEEF10B7,\n\t\t\t0xAA008093, 0x00000797, 0x01478793, 0x00111223, 0x00412703, 0x0080006F, 0x00008713, 0xBEEF13B7,\n\t\t\t0xAA038393, 0x44771E63, 0x00500193, 0x0003F117, 0xF5410113, 0xFFFFA0B7, 0x00A08093, 0x00000797,\n\t\t\t0x01478793, 0x00111323, 0x00611703, 0x0080006F, 0x00008713, 0xFFFFA3B7, 0x00A38393, 0x42771263,\n\t\t\t0x00600193, 0x0003F117, 0xF2A10113, 0x0AA00093, 0x00000797, 0x01478793, 0xFE111D23, 0xFFA11703,\n\t\t\t0x0080006F, 0x00008713, 0x0AA00393, 0x3E771A63, 0x00700193, 0x0003F117, 0xEFA10113, 0xFFFFB0B7,\n\t\t\t0xA0008093, 0x00000797, 0x01478793, 0xFE111E23, 0xFFC11703, 0x0080006F, 0x00008713, 0xFFFFB3B7,\n\t\t\t0xA0038393, 0x3A771E63, 0x00800193, 0x0003F117, 0xEC210113, 0x000010B7, 0xAA008093, 0x00000797,\n\t\t\t0x01478793, 0xFE111F23, 0xFFE11703, 0x0080006F, 0x00008713, 0x000013B7, 0xAA038393, 0x38771263,\n\t\t\t0x00900193, 0x0003F117, 0xE8A10113, 0xFFFFA0B7, 0x00A08093, 0x00000797, 0x01478793, 0x00111023,\n\t\t\t0x00011703, 0x0080006F, 0x00008713, 0xFFFFA3B7, 0x00A38393, 0x34771663, 0x00A00193, 0x0003F097,\n\t\t\t0xE5408093, 0x12345137, 0x67810113, 0xFE008213, 0x02221023, 0x00009283, 0x000053B7, 0x67838393,\n\t\t\t0x32729063, 0x00B00193, 0x0003F097, 0xE2808093, 0x00003137, 0x09810113, 0xFFB08093, 0x002093A3,\n\t\t\t0x0003F217, 0xE1220213, 0x00021283, 0x000033B7, 0x09838393, 0x2E729663, 0x00C00193, 0x00000213,\n\t\t\t0xFFFFD6B7, 0xCDD68693, 0x0003F617, 0xDD860613, 0x00D61023, 0x00061703, 0xFFFFD3B7, 0xCDD38393,\n\t\t\t0x2C771063, 0x00120213, 0x00200293, 0xFC521AE3, 0x00D00193, 0x00000213, 0xFFFFC6B7, 0xCCD68693,\n\t\t\t0x0003F617, 0xDA060613, 0x00000013, 0x00D61123, 0x00261703, 0xFFFFC3B7, 0xCCD38393, 0x28771263,\n\t\t\t0x00120213, 0x00200293, 0xFC5218E3, 0x00E00193, 0x00000213, 0xFFFFC6B7, 0xBCC68693, 0x0003F617,\n\t\t\t0xD6460613, 0x00000013, 0x00000013, 0x00D61223, 0x00461703, 0xFFFFC3B7, 0xBCC38393, 0x24771263,\n\t\t\t0x00120213, 0x00200293, 0xFC5216E3, 0x00F00193, 0x00000213, 0xFFFFB6B7, 0xBBC68693, 0x00000013,\n\t\t\t0x0003F617, 0xD2060613, 0x00D61323, 0x00661703, 0xFFFFB3B7, 0xBBC38393, 0x20771463, 0x00120213,\n\t\t\t0x00200293, 0xFC5218E3, 0x01000193, 0x00000213, 0xFFFFB6B7, 0xABB68693, 0x00000013, 0x0003F617,\n\t\t\t0xCE460613, 0x00000013, 0x00D61423, 0x00861703, 0xFFFFB3B7, 0xABB38393, 0x1C771463, 0x00120213,\n\t\t\t0x00200293, 0xFC5216E3, 0x01100193, 0x00000213, 0xFFFFE6B7, 0xAAB68693, 0x00000013, 0x00000013,\n\t\t\t0x0003F617, 0xCA060613, 0x00D61523, 0x00A61703, 0xFFFFE3B7, 0xAAB38393, 0x18771463, 0x00120213,\n\t\t\t0x00200293, 0xFC5216E3, 0x01200193, 0x00000213, 0x0003F117, 0xC7010113, 0x000020B7, 0x23308093,\n\t\t\t0x00111023, 0x00011703, 0x000023B7, 0x23338393, 0x14771863, 0x00120213, 0x00200293, 0xFC521AE3,\n\t\t\t0x01300193, 0x00000213, 0x0003F117, 0xC3810113, 0x000010B7, 0x22308093, 0x00000013, 0x00111123,\n\t\t\t0x00211703, 0x000013B7, 0x22338393, 0x10771A63, 0x00120213, 0x00200293, 0xFC5218E3, 0x01400193,\n\t\t\t0x00000213, 0x0003F117, 0xBFC10113, 0x000010B7, 0x12208093, 0x00000013, 0x00000013, 0x00111223,\n\t\t\t0x00411703, 0x000013B7, 0x12238393, 0x0C771A63, 0x00120213, 0x00200293, 0xFC5216E3, 0x01500193,\n\t\t\t0x00000213, 0x0003F117, 0xBBC10113, 0x00000013, 0x11200093, 0x00111323, 0x00611703, 0x11200393,\n\t\t\t0x0A771063, 0x00120213, 0x00200293, 0xFC521CE3, 0x01600193, 0x00000213, 0x0003F117, 0xB8810113,\n\t\t\t0x00000013, 0x01100093, 0x00000013, 0x00111423, 0x00811703, 0x01100393, 0x06771463, 0x00120213,\n\t\t\t0x00200293, 0xFC521AE3, 0x01700193, 0x00000213, 0x0003F117, 0xB5010113, 0x00000013, 0x00000013,\n\t\t\t0x000030B7, 0x00108093, 0x00111523, 0x00A11703, 0x000033B7, 0x00138393, 0x02771463, 0x00120213,\n\t\t\t0x00200293, 0xFC5216E3, 0x0000C537, 0xEEF50513, 0x0003F597, 0xB1058593, 0x00A59323, 0x02301063,\n\t\t\t0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F,\n\t\t\t0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0xBEEFBEEF, 0xBEEFBEEF, 0xBEEFBEEF, 0xBEEFBEEF, 0xBEEFBEEF, 0x00000000, 0x00000000, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-simple\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sll\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00100593, 0x00000613, 0x00C59733, 0x00100393, 0x52771E63,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x00C59733, 0x00200393, 0x52771263, 0x00400193, 0x00100593,\n\t\t\t0x00700613, 0x00C59733, 0x08000393, 0x50771663, 0x00500193, 0x00100593, 0x00E00613, 0x00C59733,\n\t\t\t0x000043B7, 0x4E771A63, 0x00600193, 0x00100593, 0x01F00613, 0x00C59733, 0x800003B7, 0x4C771E63,\n\t\t\t0x00700193, 0xFFF00593, 0x00000613, 0x00C59733, 0xFFF00393, 0x4C771263, 0x00800193, 0xFFF00593,\n\t\t\t0x00100613, 0x00C59733, 0xFFE00393, 0x4A771663, 0x00900193, 0xFFF00593, 0x00700613, 0x00C59733,\n\t\t\t0xF8000393, 0x48771A63, 0x00A00193, 0xFFF00593, 0x00E00613, 0x00C59733, 0xFFFFC3B7, 0x46771E63,\n\t\t\t0x00B00193, 0xFFF00593, 0x01F00613, 0x00C59733, 0x800003B7, 0x46771263, 0x00C00193, 0x212125B7,\n\t\t\t0x12158593, 0x00000613, 0x00C59733, 0x212123B7, 0x12138393, 0x44771263, 0x00D00193, 0x212125B7,\n\t\t\t0x12158593, 0x00100613, 0x00C59733, 0x424243B7, 0x24238393, 0x42771263, 0x00E00193, 0x212125B7,\n\t\t\t0x12158593, 0x00700613, 0x00C59733, 0x909093B7, 0x08038393, 0x40771263, 0x00F00193, 0x212125B7,\n\t\t\t0x12158593, 0x00E00613, 0x00C59733, 0x484843B7, 0x3E771463, 0x01000193, 0x212125B7, 0x12158593,\n\t\t\t0x01F00613, 0x00C59733, 0x800003B7, 0x3C771663, 0x01100193, 0x212125B7, 0x12158593, 0xFC000613,\n\t\t\t0x00C59733, 0x212123B7, 0x12138393, 0x3A771663, 0x01200193, 0x212125B7, 0x12158593, 0xFC100613,\n\t\t\t0x00C59733, 0x424243B7, 0x24238393, 0x38771663, 0x01300193, 0x212125B7, 0x12158593, 0xFC700613,\n\t\t\t0x00C59733, 0x909093B7, 0x08038393, 0x36771663, 0x01400193, 0x212125B7, 0x12158593, 0xFCE00613,\n\t\t\t0x00C59733, 0x484843B7, 0x34771863, 0x01600193, 0x00100593, 0x00700613, 0x00C595B3, 0x08000393,\n\t\t\t0x32759C63, 0x01700193, 0x00100593, 0x00E00613, 0x00C59633, 0x000043B7, 0x32761063, 0x01800193,\n\t\t\t0x00300593, 0x00B595B3, 0x01800393, 0x30759663, 0x01900193, 0x00000213, 0x00100093, 0x00700113,\n\t\t\t0x00209733, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x08000393, 0x2E731063, 0x01A00193,\n\t\t\t0x00000213, 0x00100093, 0x00E00113, 0x00209733, 0x00000013, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x000043B7, 0x2A731863, 0x01B00193, 0x00000213, 0x00100093, 0x01F00113, 0x00209733,\n\t\t\t0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3, 0x800003B7, 0x26731E63,\n\t\t\t0x01C00193, 0x00000213, 0x00100093, 0x00700113, 0x00209733, 0x00120213, 0x00200293, 0xFE5216E3,\n\t\t\t0x08000393, 0x24771A63, 0x01D00193, 0x00000213, 0x00100093, 0x00E00113, 0x00000013, 0x00209733,\n\t\t\t0x00120213, 0x00200293, 0xFE5214E3, 0x000043B7, 0x22771463, 0x01E00193, 0x00000213, 0x00100093,\n\t\t\t0x01F00113, 0x00000013, 0x00000013, 0x00209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x800003B7,\n\t\t\t0x1E771C63, 0x01F00193, 0x00000213, 0x00100093, 0x00000013, 0x00700113, 0x00209733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x08000393, 0x1C771663, 0x02000193, 0x00000213, 0x00100093, 0x00000013,\n\t\t\t0x00E00113, 0x00000013, 0x00209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x000043B7, 0x18771E63,\n\t\t\t0x02100193, 0x00000213, 0x00100093, 0x00000013, 0x00000013, 0x01F00113, 0x00209733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x800003B7, 0x16771663, 0x02200193, 0x00000213, 0x00700113, 0x00100093,\n\t\t\t0x00209733, 0x00120213, 0x00200293, 0xFE5216E3, 0x08000393, 0x14771263, 0x02300193, 0x00000213,\n\t\t\t0x00E00113, 0x00100093, 0x00000013, 0x00209733, 0x00120213, 0x00200293, 0xFE5214E3, 0x000043B7,\n\t\t\t0x10771C63, 0x02400193, 0x00000213, 0x01F00113, 0x00100093, 0x00000013, 0x00000013, 0x00209733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x800003B7, 0x0E771463, 0x02500193, 0x00000213, 0x00700113,\n\t\t\t0x00000013, 0x00100093, 0x00209733, 0x00120213, 0x00200293, 0xFE5214E3, 0x08000393, 0x0A771E63,\n\t\t\t0x02600193, 0x00000213, 0x00E00113, 0x00000013, 0x00100093, 0x00000013, 0x00209733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x000043B7, 0x08771663, 0x02700193, 0x00000213, 0x01F00113, 0x00000013,\n\t\t\t0x00000013, 0x00100093, 0x00209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x800003B7, 0x04771E63,\n\t\t\t0x02800193, 0x00F00093, 0x00101133, 0x00000393, 0x04711463, 0x02900193, 0x02000093, 0x00009133,\n\t\t\t0x02000393, 0x02711A63, 0x02A00193, 0x000010B3, 0x00000393, 0x02709263, 0x02B00193, 0x40000093,\n\t\t\t0x00100113, 0x00B11113, 0x00209033, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063,\n\t\t\t0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893,\n\t\t\t0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-slli\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00100693, 0x00069713, 0x00100393, 0x26771A63, 0x00300193,\n\t\t\t0x00100693, 0x00169713, 0x00200393, 0x26771063, 0x00400193, 0x00100693, 0x00769713, 0x08000393,\n\t\t\t0x24771663, 0x00500193, 0x00100693, 0x00E69713, 0x000043B7, 0x22771C63, 0x00600193, 0x00100693,\n\t\t\t0x01F69713, 0x800003B7, 0x22771263, 0x00700193, 0xFFF00693, 0x00069713, 0xFFF00393, 0x20771863,\n\t\t\t0x00800193, 0xFFF00693, 0x00169713, 0xFFE00393, 0x1E771E63, 0x00900193, 0xFFF00693, 0x00769713,\n\t\t\t0xF8000393, 0x1E771463, 0x00A00193, 0xFFF00693, 0x00E69713, 0xFFFFC3B7, 0x1C771A63, 0x00B00193,\n\t\t\t0xFFF00693, 0x01F69713, 0x800003B7, 0x1C771063, 0x00C00193, 0x212126B7, 0x12168693, 0x00069713,\n\t\t\t0x212123B7, 0x12138393, 0x1A771263, 0x00D00193, 0x212126B7, 0x12168693, 0x00169713, 0x424243B7,\n\t\t\t0x24238393, 0x18771463, 0x00E00193, 0x212126B7, 0x12168693, 0x00769713, 0x909093B7, 0x08038393,\n\t\t\t0x16771663, 0x00F00193, 0x212126B7, 0x12168693, 0x00E69713, 0x484843B7, 0x14771A63, 0x01000193,\n\t\t\t0x212126B7, 0x12168693, 0x01F69713, 0x800003B7, 0x12771E63, 0x01100193, 0x00100593, 0x00759593,\n\t\t\t0x08000393, 0x12759463, 0x01200193, 0x00000213, 0x00100093, 0x00709713, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5216E3, 0x08000393, 0x10731063, 0x01300193, 0x00000213, 0x00100093, 0x00E09713,\n\t\t\t0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x000043B7, 0x0C731A63, 0x01400193,\n\t\t\t0x00000213, 0x00100093, 0x01F09713, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x800003B7, 0x0A731263, 0x01500193, 0x00000213, 0x00100093, 0x00709713, 0x00120213,\n\t\t\t0x00200293, 0xFE5218E3, 0x08000393, 0x08771063, 0x01600193, 0x00000213, 0x00100093, 0x00000013,\n\t\t\t0x00E09713, 0x00120213, 0x00200293, 0xFE5216E3, 0x000043B7, 0x04771C63, 0x01700193, 0x00000213,\n\t\t\t0x00100093, 0x00000013, 0x00000013, 0x01F09713, 0x00120213, 0x00200293, 0xFE5214E3, 0x800003B7,\n\t\t\t0x02771663, 0x01800193, 0x01F01093, 0x00000393, 0x00709E63, 0x01900193, 0x02100093, 0x01409013,\n\t\t\t0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893,\n\t\t\t0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-slt\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000593, 0x00000613, 0x00C5A733, 0x00000393, 0x4A771A63,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x00C5A733, 0x00000393, 0x48771E63, 0x00400193, 0x00300593,\n\t\t\t0x00700613, 0x00C5A733, 0x00100393, 0x48771263, 0x00500193, 0x00700593, 0x00300613, 0x00C5A733,\n\t\t\t0x00000393, 0x46771663, 0x00600193, 0x00000593, 0xFFFF8637, 0x00C5A733, 0x00000393, 0x44771A63,\n\t\t\t0x00700193, 0x800005B7, 0x00000613, 0x00C5A733, 0x00100393, 0x42771E63, 0x00800193, 0x800005B7,\n\t\t\t0xFFFF8637, 0x00C5A733, 0x00100393, 0x42771263, 0x00900193, 0x00000593, 0x00008637, 0xFFF60613,\n\t\t\t0x00C5A733, 0x00100393, 0x40771463, 0x00A00193, 0x800005B7, 0xFFF58593, 0x00000613, 0x00C5A733,\n\t\t\t0x00000393, 0x3E771663, 0x00B00193, 0x800005B7, 0xFFF58593, 0x00008637, 0xFFF60613, 0x00C5A733,\n\t\t\t0x00000393, 0x3C771663, 0x00C00193, 0x800005B7, 0x00008637, 0xFFF60613, 0x00C5A733, 0x00100393,\n\t\t\t0x3A771863, 0x00D00193, 0x800005B7, 0xFFF58593, 0xFFFF8637, 0x00C5A733, 0x00000393, 0x38771A63,\n\t\t\t0x00E00193, 0x00000593, 0xFFF00613, 0x00C5A733, 0x00000393, 0x36771E63, 0x00F00193, 0xFFF00593,\n\t\t\t0x00100613, 0x00C5A733, 0x00100393, 0x36771263, 0x01000193, 0xFFF00593, 0xFFF00613, 0x00C5A733,\n\t\t\t0x00000393, 0x34771663, 0x01100193, 0x00E00593, 0x00D00613, 0x00C5A5B3, 0x00000393, 0x32759A63,\n\t\t\t0x01200193, 0x00B00593, 0x00D00613, 0x00C5A633, 0x00100393, 0x30761E63, 0x01300193, 0x00D00593,\n\t\t\t0x00B5A5B3, 0x00000393, 0x30759463, 0x01400193, 0x00000213, 0x00B00093, 0x00D00113, 0x0020A733,\n\t\t\t0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x00100393, 0x2C731E63, 0x01500193, 0x00000213,\n\t\t\t0x00E00093, 0x00D00113, 0x0020A733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x00000393, 0x2A731663, 0x01600193, 0x00000213, 0x00C00093, 0x00D00113, 0x0020A733, 0x00000013,\n\t\t\t0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3, 0x00100393, 0x26731C63, 0x01700193,\n\t\t\t0x00000213, 0x00E00093, 0x00D00113, 0x0020A733, 0x00120213, 0x00200293, 0xFE5216E3, 0x00000393,\n\t\t\t0x24771863, 0x01800193, 0x00000213, 0x00B00093, 0x00D00113, 0x00000013, 0x0020A733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x00100393, 0x22771263, 0x01900193, 0x00000213, 0x00F00093, 0x00D00113,\n\t\t\t0x00000013, 0x00000013, 0x0020A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00000393, 0x1E771A63,\n\t\t\t0x01A00193, 0x00000213, 0x00A00093, 0x00000013, 0x00D00113, 0x0020A733, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0x00100393, 0x1C771463, 0x01B00193, 0x00000213, 0x01000093, 0x00000013, 0x00D00113,\n\t\t\t0x00000013, 0x0020A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00000393, 0x18771C63, 0x01C00193,\n\t\t\t0x00000213, 0x00900093, 0x00000013, 0x00000013, 0x00D00113, 0x0020A733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x00100393, 0x16771463, 0x01D00193, 0x00000213, 0x00D00113, 0x01100093, 0x0020A733,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x00000393, 0x14771063, 0x01E00193, 0x00000213, 0x00D00113,\n\t\t\t0x00800093, 0x00000013, 0x0020A733, 0x00120213, 0x00200293, 0xFE5214E3, 0x00100393, 0x10771A63,\n\t\t\t0x01F00193, 0x00000213, 0x00D00113, 0x01200093, 0x00000013, 0x00000013, 0x0020A733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x00000393, 0x0E771263, 0x02000193, 0x00000213, 0x00D00113, 0x00000013,\n\t\t\t0x00700093, 0x0020A733, 0x00120213, 0x00200293, 0xFE5214E3, 0x00100393, 0x0A771C63, 0x02100193,\n\t\t\t0x00000213, 0x00D00113, 0x00000013, 0x01300093, 0x00000013, 0x0020A733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x00000393, 0x08771463, 0x02200193, 0x00000213, 0x00D00113, 0x00000013, 0x00000013,\n\t\t\t0x00600093, 0x0020A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00100393, 0x04771C63, 0x02300193,\n\t\t\t0xFFF00093, 0x00102133, 0x00000393, 0x04711263, 0x02400193, 0xFFF00093, 0x0000A133, 0x00100393,\n\t\t\t0x02711863, 0x02500193, 0x000020B3, 0x00000393, 0x02709063, 0x02600193, 0x01000093, 0x01E00113,\n\t\t\t0x0020A033, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-slti\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000693, 0x0006A713, 0x00000393, 0x26771263, 0x00300193,\n\t\t\t0x00100693, 0x0016A713, 0x00000393, 0x24771863, 0x00400193, 0x00300693, 0x0076A713, 0x00100393,\n\t\t\t0x22771E63, 0x00500193, 0x00700693, 0x0036A713, 0x00000393, 0x22771463, 0x00600193, 0x00000693,\n\t\t\t0x8006A713, 0x00000393, 0x20771A63, 0x00700193, 0x800006B7, 0x0006A713, 0x00100393, 0x20771063,\n\t\t\t0x00800193, 0x800006B7, 0x8006A713, 0x00100393, 0x1E771663, 0x00900193, 0x00000693, 0x7FF6A713,\n\t\t\t0x00100393, 0x1C771C63, 0x00A00193, 0x800006B7, 0xFFF68693, 0x0006A713, 0x00000393, 0x1C771063,\n\t\t\t0x00B00193, 0x800006B7, 0xFFF68693, 0x7FF6A713, 0x00000393, 0x1A771463, 0x00C00193, 0x800006B7,\n\t\t\t0x7FF6A713, 0x00100393, 0x18771A63, 0x00D00193, 0x800006B7, 0xFFF68693, 0x8006A713, 0x00000393,\n\t\t\t0x16771E63, 0x00E00193, 0x00000693, 0xFFF6A713, 0x00000393, 0x16771463, 0x00F00193, 0xFFF00693,\n\t\t\t0x0016A713, 0x00100393, 0x14771A63, 0x01000193, 0xFFF00693, 0xFFF6A713, 0x00000393, 0x14771063,\n\t\t\t0x01100193, 0x00B00593, 0x00D5A593, 0x00100393, 0x12759663, 0x01200193, 0x00000213, 0x00F00093,\n\t\t\t0x00A0A713, 0x00070313, 0x00120213, 0x00200293, 0xFE5216E3, 0x00000393, 0x10731263, 0x01300193,\n\t\t\t0x00000213, 0x00A00093, 0x0100A713, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x00100393, 0x0C731C63, 0x01400193, 0x00000213, 0x01000093, 0x0090A713, 0x00000013, 0x00000013,\n\t\t\t0x00070313, 0x00120213, 0x00200293, 0xFE5212E3, 0x00000393, 0x0A731463, 0x01500193, 0x00000213,\n\t\t\t0x00B00093, 0x00F0A713, 0x00120213, 0x00200293, 0xFE5218E3, 0x00100393, 0x08771263, 0x01600193,\n\t\t\t0x00000213, 0x01100093, 0x00000013, 0x0080A713, 0x00120213, 0x00200293, 0xFE5216E3, 0x00000393,\n\t\t\t0x04771E63, 0x01700193, 0x00000213, 0x00C00093, 0x00000013, 0x00000013, 0x00E0A713, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x00100393, 0x02771863, 0x01800193, 0xFFF02093, 0x00000393, 0x02709063,\n\t\t\t0x01900193, 0x00FF00B7, 0x0FF08093, 0xFFF0A013, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F,\n\t\t\t0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193,\n\t\t\t0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sltiu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000693, 0x0006B713, 0x00000393, 0x26771263, 0x00300193,\n\t\t\t0x00100693, 0x0016B713, 0x00000393, 0x24771863, 0x00400193, 0x00300693, 0x0076B713, 0x00100393,\n\t\t\t0x22771E63, 0x00500193, 0x00700693, 0x0036B713, 0x00000393, 0x22771463, 0x00600193, 0x00000693,\n\t\t\t0x8006B713, 0x00100393, 0x20771A63, 0x00700193, 0x800006B7, 0x0006B713, 0x00000393, 0x20771063,\n\t\t\t0x00800193, 0x800006B7, 0x8006B713, 0x00100393, 0x1E771663, 0x00900193, 0x00000693, 0x7FF6B713,\n\t\t\t0x00100393, 0x1C771C63, 0x00A00193, 0x800006B7, 0xFFF68693, 0x0006B713, 0x00000393, 0x1C771063,\n\t\t\t0x00B00193, 0x800006B7, 0xFFF68693, 0x7FF6B713, 0x00000393, 0x1A771463, 0x00C00193, 0x800006B7,\n\t\t\t0x7FF6B713, 0x00000393, 0x18771A63, 0x00D00193, 0x800006B7, 0xFFF68693, 0x8006B713, 0x00100393,\n\t\t\t0x16771E63, 0x00E00193, 0x00000693, 0xFFF6B713, 0x00100393, 0x16771463, 0x00F00193, 0xFFF00693,\n\t\t\t0x0016B713, 0x00000393, 0x14771A63, 0x01000193, 0xFFF00693, 0xFFF6B713, 0x00000393, 0x14771063,\n\t\t\t0x01100193, 0x00B00593, 0x00D5B593, 0x00100393, 0x12759663, 0x01200193, 0x00000213, 0x00F00093,\n\t\t\t0x00A0B713, 0x00070313, 0x00120213, 0x00200293, 0xFE5216E3, 0x00000393, 0x10731263, 0x01300193,\n\t\t\t0x00000213, 0x00A00093, 0x0100B713, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x00100393, 0x0C731C63, 0x01400193, 0x00000213, 0x01000093, 0x0090B713, 0x00000013, 0x00000013,\n\t\t\t0x00070313, 0x00120213, 0x00200293, 0xFE5212E3, 0x00000393, 0x0A731463, 0x01500193, 0x00000213,\n\t\t\t0x00B00093, 0x00F0B713, 0x00120213, 0x00200293, 0xFE5218E3, 0x00100393, 0x08771263, 0x01600193,\n\t\t\t0x00000213, 0x01100093, 0x00000013, 0x0080B713, 0x00120213, 0x00200293, 0xFE5216E3, 0x00000393,\n\t\t\t0x04771E63, 0x01700193, 0x00000213, 0x00C00093, 0x00000013, 0x00000013, 0x00E0B713, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x00100393, 0x02771863, 0x01800193, 0xFFF03093, 0x00100393, 0x02709063,\n\t\t\t0x01900193, 0x00FF00B7, 0x0FF08093, 0xFFF0B013, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F,\n\t\t\t0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193,\n\t\t\t0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sltu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000593, 0x00000613, 0x00C5B733, 0x00000393, 0x4A771A63,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x00C5B733, 0x00000393, 0x48771E63, 0x00400193, 0x00300593,\n\t\t\t0x00700613, 0x00C5B733, 0x00100393, 0x48771263, 0x00500193, 0x00700593, 0x00300613, 0x00C5B733,\n\t\t\t0x00000393, 0x46771663, 0x00600193, 0x00000593, 0xFFFF8637, 0x00C5B733, 0x00100393, 0x44771A63,\n\t\t\t0x00700193, 0x800005B7, 0x00000613, 0x00C5B733, 0x00000393, 0x42771E63, 0x00800193, 0x800005B7,\n\t\t\t0xFFFF8637, 0x00C5B733, 0x00100393, 0x42771263, 0x00900193, 0x00000593, 0x00008637, 0xFFF60613,\n\t\t\t0x00C5B733, 0x00100393, 0x40771463, 0x00A00193, 0x800005B7, 0xFFF58593, 0x00000613, 0x00C5B733,\n\t\t\t0x00000393, 0x3E771663, 0x00B00193, 0x800005B7, 0xFFF58593, 0x00008637, 0xFFF60613, 0x00C5B733,\n\t\t\t0x00000393, 0x3C771663, 0x00C00193, 0x800005B7, 0x00008637, 0xFFF60613, 0x00C5B733, 0x00000393,\n\t\t\t0x3A771863, 0x00D00193, 0x800005B7, 0xFFF58593, 0xFFFF8637, 0x00C5B733, 0x00100393, 0x38771A63,\n\t\t\t0x00E00193, 0x00000593, 0xFFF00613, 0x00C5B733, 0x00100393, 0x36771E63, 0x00F00193, 0xFFF00593,\n\t\t\t0x00100613, 0x00C5B733, 0x00000393, 0x36771263, 0x01000193, 0xFFF00593, 0xFFF00613, 0x00C5B733,\n\t\t\t0x00000393, 0x34771663, 0x01100193, 0x00E00593, 0x00D00613, 0x00C5B5B3, 0x00000393, 0x32759A63,\n\t\t\t0x01200193, 0x00B00593, 0x00D00613, 0x00C5B633, 0x00100393, 0x30761E63, 0x01300193, 0x00D00593,\n\t\t\t0x00B5B5B3, 0x00000393, 0x30759463, 0x01400193, 0x00000213, 0x00B00093, 0x00D00113, 0x0020B733,\n\t\t\t0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x00100393, 0x2C731E63, 0x01500193, 0x00000213,\n\t\t\t0x00E00093, 0x00D00113, 0x0020B733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x00000393, 0x2A731663, 0x01600193, 0x00000213, 0x00C00093, 0x00D00113, 0x0020B733, 0x00000013,\n\t\t\t0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3, 0x00100393, 0x26731C63, 0x01700193,\n\t\t\t0x00000213, 0x00E00093, 0x00D00113, 0x0020B733, 0x00120213, 0x00200293, 0xFE5216E3, 0x00000393,\n\t\t\t0x24771863, 0x01800193, 0x00000213, 0x00B00093, 0x00D00113, 0x00000013, 0x0020B733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x00100393, 0x22771263, 0x01900193, 0x00000213, 0x00F00093, 0x00D00113,\n\t\t\t0x00000013, 0x00000013, 0x0020B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00000393, 0x1E771A63,\n\t\t\t0x01A00193, 0x00000213, 0x00A00093, 0x00000013, 0x00D00113, 0x0020B733, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0x00100393, 0x1C771463, 0x01B00193, 0x00000213, 0x01000093, 0x00000013, 0x00D00113,\n\t\t\t0x00000013, 0x0020B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00000393, 0x18771C63, 0x01C00193,\n\t\t\t0x00000213, 0x00900093, 0x00000013, 0x00000013, 0x00D00113, 0x0020B733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x00100393, 0x16771463, 0x01D00193, 0x00000213, 0x00D00113, 0x01100093, 0x0020B733,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x00000393, 0x14771063, 0x01E00193, 0x00000213, 0x00D00113,\n\t\t\t0x00800093, 0x00000013, 0x0020B733, 0x00120213, 0x00200293, 0xFE5214E3, 0x00100393, 0x10771A63,\n\t\t\t0x01F00193, 0x00000213, 0x00D00113, 0x01200093, 0x00000013, 0x00000013, 0x0020B733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x00000393, 0x0E771263, 0x02000193, 0x00000213, 0x00D00113, 0x00000013,\n\t\t\t0x00700093, 0x0020B733, 0x00120213, 0x00200293, 0xFE5214E3, 0x00100393, 0x0A771C63, 0x02100193,\n\t\t\t0x00000213, 0x00D00113, 0x00000013, 0x01300093, 0x00000013, 0x0020B733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x00000393, 0x08771463, 0x02200193, 0x00000213, 0x00D00113, 0x00000013, 0x00000013,\n\t\t\t0x00600093, 0x0020B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00100393, 0x04771C63, 0x02300193,\n\t\t\t0xFFF00093, 0x00103133, 0x00100393, 0x04711263, 0x02400193, 0xFFF00093, 0x0000B133, 0x00000393,\n\t\t\t0x02711863, 0x02500193, 0x000030B3, 0x00000393, 0x02709063, 0x02600193, 0x01000093, 0x01E00113,\n\t\t\t0x0020B033, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sra\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x800005B7, 0x00000613, 0x40C5D733, 0x800003B7, 0x58771463,\n\t\t\t0x00300193, 0x800005B7, 0x00100613, 0x40C5D733, 0xC00003B7, 0x56771863, 0x00400193, 0x800005B7,\n\t\t\t0x00700613, 0x40C5D733, 0xFF0003B7, 0x54771C63, 0x00500193, 0x800005B7, 0x00E00613, 0x40C5D733,\n\t\t\t0xFFFE03B7, 0x54771063, 0x00600193, 0x800005B7, 0x00158593, 0x01F00613, 0x40C5D733, 0xFFF00393,\n\t\t\t0x52771263, 0x00700193, 0x800005B7, 0xFFF58593, 0x00000613, 0x40C5D733, 0x800003B7, 0xFFF38393,\n\t\t\t0x50771263, 0x00800193, 0x800005B7, 0xFFF58593, 0x00100613, 0x40C5D733, 0x400003B7, 0xFFF38393,\n\t\t\t0x4E771263, 0x00900193, 0x800005B7, 0xFFF58593, 0x00700613, 0x40C5D733, 0x010003B7, 0xFFF38393,\n\t\t\t0x4C771263, 0x00A00193, 0x800005B7, 0xFFF58593, 0x00E00613, 0x40C5D733, 0x000203B7, 0xFFF38393,\n\t\t\t0x4A771263, 0x00B00193, 0x800005B7, 0xFFF58593, 0x01F00613, 0x40C5D733, 0x00000393, 0x48771463,\n\t\t\t0x00C00193, 0x818185B7, 0x18158593, 0x00000613, 0x40C5D733, 0x818183B7, 0x18138393, 0x46771463,\n\t\t\t0x00D00193, 0x818185B7, 0x18158593, 0x00100613, 0x40C5D733, 0xC0C0C3B7, 0x0C038393, 0x44771463,\n\t\t\t0x00E00193, 0x818185B7, 0x18158593, 0x00700613, 0x40C5D733, 0xFF0303B7, 0x30338393, 0x42771463,\n\t\t\t0x00F00193, 0x818185B7, 0x18158593, 0x00E00613, 0x40C5D733, 0xFFFE03B7, 0x60638393, 0x40771463,\n\t\t\t0x01000193, 0x818185B7, 0x18158593, 0x01F00613, 0x40C5D733, 0xFFF00393, 0x3E771663, 0x01100193,\n\t\t\t0x818185B7, 0x18158593, 0xFC000613, 0x40C5D733, 0x818183B7, 0x18138393, 0x3C771663, 0x01200193,\n\t\t\t0x818185B7, 0x18158593, 0xFC100613, 0x40C5D733, 0xC0C0C3B7, 0x0C038393, 0x3A771663, 0x01300193,\n\t\t\t0x818185B7, 0x18158593, 0xFC700613, 0x40C5D733, 0xFF0303B7, 0x30338393, 0x38771663, 0x01400193,\n\t\t\t0x818185B7, 0x18158593, 0xFCE00613, 0x40C5D733, 0xFFFE03B7, 0x60638393, 0x36771663, 0x01500193,\n\t\t\t0x818185B7, 0x18158593, 0xFFF00613, 0x40C5D733, 0xFFF00393, 0x34771863, 0x01600193, 0x800005B7,\n\t\t\t0x00700613, 0x40C5D5B3, 0xFF0003B7, 0x32759C63, 0x01700193, 0x800005B7, 0x00E00613, 0x40C5D633,\n\t\t\t0xFFFE03B7, 0x32761063, 0x01800193, 0x00700593, 0x40B5D5B3, 0x00000393, 0x30759663, 0x01900193,\n\t\t\t0x00000213, 0x800000B7, 0x00700113, 0x4020D733, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0xFF0003B7, 0x2E731063, 0x01A00193, 0x00000213, 0x800000B7, 0x00E00113, 0x4020D733, 0x00000013,\n\t\t\t0x00070313, 0x00120213, 0x00200293, 0xFE5212E3, 0xFFFE03B7, 0x2A731863, 0x01B00193, 0x00000213,\n\t\t\t0x800000B7, 0x01F00113, 0x4020D733, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0xFFF00393, 0x26731E63, 0x01C00193, 0x00000213, 0x800000B7, 0x00700113, 0x4020D733,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0xFF0003B7, 0x24771A63, 0x01D00193, 0x00000213, 0x800000B7,\n\t\t\t0x00E00113, 0x00000013, 0x4020D733, 0x00120213, 0x00200293, 0xFE5214E3, 0xFFFE03B7, 0x22771463,\n\t\t\t0x01E00193, 0x00000213, 0x800000B7, 0x01F00113, 0x00000013, 0x00000013, 0x4020D733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0xFFF00393, 0x1E771C63, 0x01F00193, 0x00000213, 0x800000B7, 0x00000013,\n\t\t\t0x00700113, 0x4020D733, 0x00120213, 0x00200293, 0xFE5214E3, 0xFF0003B7, 0x1C771663, 0x02000193,\n\t\t\t0x00000213, 0x800000B7, 0x00000013, 0x00E00113, 0x00000013, 0x4020D733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0xFFFE03B7, 0x18771E63, 0x02100193, 0x00000213, 0x800000B7, 0x00000013, 0x00000013,\n\t\t\t0x01F00113, 0x4020D733, 0x00120213, 0x00200293, 0xFE5212E3, 0xFFF00393, 0x16771663, 0x02200193,\n\t\t\t0x00000213, 0x00700113, 0x800000B7, 0x4020D733, 0x00120213, 0x00200293, 0xFE5216E3, 0xFF0003B7,\n\t\t\t0x14771263, 0x02300193, 0x00000213, 0x00E00113, 0x800000B7, 0x00000013, 0x4020D733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0xFFFE03B7, 0x10771C63, 0x02400193, 0x00000213, 0x01F00113, 0x800000B7,\n\t\t\t0x00000013, 0x00000013, 0x4020D733, 0x00120213, 0x00200293, 0xFE5212E3, 0xFFF00393, 0x0E771463,\n\t\t\t0x02500193, 0x00000213, 0x00700113, 0x00000013, 0x800000B7, 0x4020D733, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0xFF0003B7, 0x0A771E63, 0x02600193, 0x00000213, 0x00E00113, 0x00000013, 0x800000B7,\n\t\t\t0x00000013, 0x4020D733, 0x00120213, 0x00200293, 0xFE5212E3, 0xFFFE03B7, 0x08771663, 0x02700193,\n\t\t\t0x00000213, 0x01F00113, 0x00000013, 0x00000013, 0x800000B7, 0x4020D733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0xFFF00393, 0x04771E63, 0x02800193, 0x00F00093, 0x40105133, 0x00000393, 0x04711463,\n\t\t\t0x02900193, 0x02000093, 0x4000D133, 0x02000393, 0x02711A63, 0x02A00193, 0x400050B3, 0x00000393,\n\t\t\t0x02709263, 0x02B00193, 0x40000093, 0x00100113, 0x00B11113, 0x4020D033, 0x00000393, 0x00701463,\n\t\t\t0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073,\n\t\t\t0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-srai\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000693, 0x4006D713, 0x00000393, 0x2A771463, 0x00300193,\n\t\t\t0x800006B7, 0x4016D713, 0xC00003B7, 0x28771A63, 0x00400193, 0x800006B7, 0x4076D713, 0xFF0003B7,\n\t\t\t0x28771063, 0x00500193, 0x800006B7, 0x40E6D713, 0xFFFE03B7, 0x26771663, 0x00600193, 0x800006B7,\n\t\t\t0x00168693, 0x41F6D713, 0xFFF00393, 0x24771A63, 0x00700193, 0x800006B7, 0xFFF68693, 0x4006D713,\n\t\t\t0x800003B7, 0xFFF38393, 0x22771C63, 0x00800193, 0x800006B7, 0xFFF68693, 0x4016D713, 0x400003B7,\n\t\t\t0xFFF38393, 0x20771E63, 0x00900193, 0x800006B7, 0xFFF68693, 0x4076D713, 0x010003B7, 0xFFF38393,\n\t\t\t0x20771063, 0x00A00193, 0x800006B7, 0xFFF68693, 0x40E6D713, 0x000203B7, 0xFFF38393, 0x1E771263,\n\t\t\t0x00B00193, 0x800006B7, 0xFFF68693, 0x41F6D713, 0x00000393, 0x1C771663, 0x00C00193, 0x818186B7,\n\t\t\t0x18168693, 0x4006D713, 0x818183B7, 0x18138393, 0x1A771863, 0x00D00193, 0x818186B7, 0x18168693,\n\t\t\t0x4016D713, 0xC0C0C3B7, 0x0C038393, 0x18771A63, 0x00E00193, 0x818186B7, 0x18168693, 0x4076D713,\n\t\t\t0xFF0303B7, 0x30338393, 0x16771C63, 0x00F00193, 0x818186B7, 0x18168693, 0x40E6D713, 0xFFFE03B7,\n\t\t\t0x60638393, 0x14771E63, 0x01000193, 0x818186B7, 0x18168693, 0x41F6D713, 0xFFF00393, 0x14771263,\n\t\t\t0x01100193, 0x800005B7, 0x4075D593, 0xFF0003B7, 0x12759863, 0x01200193, 0x00000213, 0x800000B7,\n\t\t\t0x4070D713, 0x00070313, 0x00120213, 0x00200293, 0xFE5216E3, 0xFF0003B7, 0x10731463, 0x01300193,\n\t\t\t0x00000213, 0x800000B7, 0x40E0D713, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0xFFFE03B7, 0x0C731E63, 0x01400193, 0x00000213, 0x800000B7, 0x00108093, 0x41F0D713, 0x00000013,\n\t\t\t0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3, 0xFFF00393, 0x0A731463, 0x01500193,\n\t\t\t0x00000213, 0x800000B7, 0x4070D713, 0x00120213, 0x00200293, 0xFE5218E3, 0xFF0003B7, 0x08771263,\n\t\t\t0x01600193, 0x00000213, 0x800000B7, 0x00000013, 0x40E0D713, 0x00120213, 0x00200293, 0xFE5216E3,\n\t\t\t0xFFFE03B7, 0x04771E63, 0x01700193, 0x00000213, 0x800000B7, 0x00108093, 0x00000013, 0x00000013,\n\t\t\t0x41F0D713, 0x00120213, 0x00200293, 0xFE5212E3, 0xFFF00393, 0x02771663, 0x01800193, 0x40405093,\n\t\t\t0x00000393, 0x00709E63, 0x01900193, 0x02100093, 0x40A0D013, 0x00000393, 0x00701463, 0x02301063,\n\t\t\t0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F,\n\t\t\t0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-srl\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x800005B7, 0x00000613, 0x00C5D733, 0x800003B7, 0x56771863,\n\t\t\t0x00300193, 0x800005B7, 0x00100613, 0x00C5D733, 0x400003B7, 0x54771C63, 0x00400193, 0x800005B7,\n\t\t\t0x00700613, 0x00C5D733, 0x010003B7, 0x54771063, 0x00500193, 0x800005B7, 0x00E00613, 0x00C5D733,\n\t\t\t0x000203B7, 0x52771463, 0x00600193, 0x800005B7, 0x00158593, 0x01F00613, 0x00C5D733, 0x00100393,\n\t\t\t0x50771663, 0x00700193, 0xFFF00593, 0x00000613, 0x00C5D733, 0xFFF00393, 0x4E771A63, 0x00800193,\n\t\t\t0xFFF00593, 0x00100613, 0x00C5D733, 0x800003B7, 0xFFF38393, 0x4C771C63, 0x00900193, 0xFFF00593,\n\t\t\t0x00700613, 0x00C5D733, 0x020003B7, 0xFFF38393, 0x4A771E63, 0x00A00193, 0xFFF00593, 0x00E00613,\n\t\t\t0x00C5D733, 0x000403B7, 0xFFF38393, 0x4A771063, 0x00B00193, 0xFFF00593, 0x01F00613, 0x00C5D733,\n\t\t\t0x00100393, 0x48771463, 0x00C00193, 0x212125B7, 0x12158593, 0x00000613, 0x00C5D733, 0x212123B7,\n\t\t\t0x12138393, 0x46771463, 0x00D00193, 0x212125B7, 0x12158593, 0x00100613, 0x00C5D733, 0x109093B7,\n\t\t\t0x09038393, 0x44771463, 0x00E00193, 0x212125B7, 0x12158593, 0x00700613, 0x00C5D733, 0x004243B7,\n\t\t\t0x24238393, 0x42771463, 0x00F00193, 0x212125B7, 0x12158593, 0x00E00613, 0x00C5D733, 0x000083B7,\n\t\t\t0x48438393, 0x40771463, 0x01000193, 0x212125B7, 0x12158593, 0x01F00613, 0x00C5D733, 0x00000393,\n\t\t\t0x3E771663, 0x01100193, 0x212125B7, 0x12158593, 0xFC000613, 0x00C5D733, 0x212123B7, 0x12138393,\n\t\t\t0x3C771663, 0x01200193, 0x212125B7, 0x12158593, 0xFC100613, 0x00C5D733, 0x109093B7, 0x09038393,\n\t\t\t0x3A771663, 0x01300193, 0x212125B7, 0x12158593, 0xFC700613, 0x00C5D733, 0x004243B7, 0x24238393,\n\t\t\t0x38771663, 0x01400193, 0x212125B7, 0x12158593, 0xFCE00613, 0x00C5D733, 0x000083B7, 0x48438393,\n\t\t\t0x36771663, 0x01500193, 0x212125B7, 0x12158593, 0xFFF00613, 0x00C5D733, 0x00000393, 0x34771863,\n\t\t\t0x01600193, 0x800005B7, 0x00700613, 0x00C5D5B3, 0x010003B7, 0x32759C63, 0x01700193, 0x800005B7,\n\t\t\t0x00E00613, 0x00C5D633, 0x000203B7, 0x32761063, 0x01800193, 0x00700593, 0x00B5D5B3, 0x00000393,\n\t\t\t0x30759663, 0x01900193, 0x00000213, 0x800000B7, 0x00700113, 0x0020D733, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x010003B7, 0x2E731063, 0x01A00193, 0x00000213, 0x800000B7, 0x00E00113,\n\t\t\t0x0020D733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5212E3, 0x000203B7, 0x2A731863,\n\t\t\t0x01B00193, 0x00000213, 0x800000B7, 0x01F00113, 0x0020D733, 0x00000013, 0x00000013, 0x00070313,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x00100393, 0x26731E63, 0x01C00193, 0x00000213, 0x800000B7,\n\t\t\t0x00700113, 0x0020D733, 0x00120213, 0x00200293, 0xFE5216E3, 0x010003B7, 0x24771A63, 0x01D00193,\n\t\t\t0x00000213, 0x800000B7, 0x00E00113, 0x00000013, 0x0020D733, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x000203B7, 0x22771463, 0x01E00193, 0x00000213, 0x800000B7, 0x01F00113, 0x00000013, 0x00000013,\n\t\t\t0x0020D733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00100393, 0x1E771C63, 0x01F00193, 0x00000213,\n\t\t\t0x800000B7, 0x00000013, 0x00700113, 0x0020D733, 0x00120213, 0x00200293, 0xFE5214E3, 0x010003B7,\n\t\t\t0x1C771663, 0x02000193, 0x00000213, 0x800000B7, 0x00000013, 0x00E00113, 0x00000013, 0x0020D733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x000203B7, 0x18771E63, 0x02100193, 0x00000213, 0x800000B7,\n\t\t\t0x00000013, 0x00000013, 0x01F00113, 0x0020D733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00100393,\n\t\t\t0x16771663, 0x02200193, 0x00000213, 0x00700113, 0x800000B7, 0x0020D733, 0x00120213, 0x00200293,\n\t\t\t0xFE5216E3, 0x010003B7, 0x14771263, 0x02300193, 0x00000213, 0x00E00113, 0x800000B7, 0x00000013,\n\t\t\t0x0020D733, 0x00120213, 0x00200293, 0xFE5214E3, 0x000203B7, 0x10771C63, 0x02400193, 0x00000213,\n\t\t\t0x01F00113, 0x800000B7, 0x00000013, 0x00000013, 0x0020D733, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x00100393, 0x0E771463, 0x02500193, 0x00000213, 0x00700113, 0x00000013, 0x800000B7, 0x0020D733,\n\t\t\t0x00120213, 0x00200293, 0xFE5214E3, 0x010003B7, 0x0A771E63, 0x02600193, 0x00000213, 0x00E00113,\n\t\t\t0x00000013, 0x800000B7, 0x00000013, 0x0020D733, 0x00120213, 0x00200293, 0xFE5212E3, 0x000203B7,\n\t\t\t0x08771663, 0x02700193, 0x00000213, 0x01F00113, 0x00000013, 0x00000013, 0x800000B7, 0x0020D733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x00100393, 0x04771E63, 0x02800193, 0x00F00093, 0x00105133,\n\t\t\t0x00000393, 0x04711463, 0x02900193, 0x02000093, 0x0000D133, 0x02000393, 0x02711A63, 0x02A00193,\n\t\t\t0x000050B3, 0x00000393, 0x02709263, 0x02B00193, 0x40000093, 0x00100113, 0x00B11113, 0x0020D033,\n\t\t\t0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893,\n\t\t\t0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-srli\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x800006B7, 0x0006D713, 0x800003B7, 0x28771863, 0x00300193,\n\t\t\t0x800006B7, 0x0016D713, 0x400003B7, 0x26771E63, 0x00400193, 0x800006B7, 0x0076D713, 0x010003B7,\n\t\t\t0x26771463, 0x00500193, 0x800006B7, 0x00E6D713, 0x000203B7, 0x24771A63, 0x00600193, 0x800006B7,\n\t\t\t0x00168693, 0x01F6D713, 0x00100393, 0x22771E63, 0x00700193, 0xFFF00693, 0x0006D713, 0xFFF00393,\n\t\t\t0x22771463, 0x00800193, 0xFFF00693, 0x0016D713, 0x800003B7, 0xFFF38393, 0x20771863, 0x00900193,\n\t\t\t0xFFF00693, 0x0076D713, 0x020003B7, 0xFFF38393, 0x1E771C63, 0x00A00193, 0xFFF00693, 0x00E6D713,\n\t\t\t0x000403B7, 0xFFF38393, 0x1E771063, 0x00B00193, 0xFFF00693, 0x01F6D713, 0x00100393, 0x1C771663,\n\t\t\t0x00C00193, 0x212126B7, 0x12168693, 0x0006D713, 0x212123B7, 0x12138393, 0x1A771863, 0x00D00193,\n\t\t\t0x212126B7, 0x12168693, 0x0016D713, 0x109093B7, 0x09038393, 0x18771A63, 0x00E00193, 0x212126B7,\n\t\t\t0x12168693, 0x0076D713, 0x004243B7, 0x24238393, 0x16771C63, 0x00F00193, 0x212126B7, 0x12168693,\n\t\t\t0x00E6D713, 0x000083B7, 0x48438393, 0x14771E63, 0x01000193, 0x212126B7, 0x12168693, 0x01F6D713,\n\t\t\t0x00000393, 0x14771263, 0x01100193, 0x800005B7, 0x0075D593, 0x010003B7, 0x12759863, 0x01200193,\n\t\t\t0x00000213, 0x800000B7, 0x0070D713, 0x00070313, 0x00120213, 0x00200293, 0xFE5216E3, 0x010003B7,\n\t\t\t0x10731463, 0x01300193, 0x00000213, 0x800000B7, 0x00E0D713, 0x00000013, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x000203B7, 0x0C731E63, 0x01400193, 0x00000213, 0x800000B7, 0x00108093,\n\t\t\t0x01F0D713, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3, 0x00100393,\n\t\t\t0x0A731463, 0x01500193, 0x00000213, 0x800000B7, 0x0070D713, 0x00120213, 0x00200293, 0xFE5218E3,\n\t\t\t0x010003B7, 0x08771263, 0x01600193, 0x00000213, 0x800000B7, 0x00000013, 0x00E0D713, 0x00120213,\n\t\t\t0x00200293, 0xFE5216E3, 0x000203B7, 0x04771E63, 0x01700193, 0x00000213, 0x800000B7, 0x00108093,\n\t\t\t0x00000013, 0x00000013, 0x01F0D713, 0x00120213, 0x00200293, 0xFE5212E3, 0x00100393, 0x02771663,\n\t\t\t0x01800193, 0x00405093, 0x00000393, 0x00709E63, 0x01900193, 0x02100093, 0x00A0D013, 0x00000393,\n\t\t\t0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-st_ld\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0003F117, 0xFF410113, 0xFDD00093, 0x00110023, 0x00010703,\n\t\t\t0xFDD00393, 0x6C771663, 0x00300193, 0x0003F117, 0xFD410113, 0xFCD00093, 0x001100A3, 0x00110703,\n\t\t\t0xFCD00393, 0x6A771663, 0x00400193, 0x0003F117, 0xFB410113, 0xFCC00093, 0x00110123, 0x00210703,\n\t\t\t0xFCC00393, 0x68771663, 0x00500193, 0x0003F117, 0xF9410113, 0xFBC00093, 0x001101A3, 0x00310703,\n\t\t\t0xFBC00393, 0x66771663, 0x00600193, 0x0003F117, 0xF7410113, 0xFBB00093, 0x00110223, 0x00410703,\n\t\t\t0xFBB00393, 0x64771663, 0x00700193, 0x0003F117, 0xF5410113, 0xFAB00093, 0x001102A3, 0x00510703,\n\t\t\t0xFAB00393, 0x62771663, 0x00800193, 0x0003F117, 0xF3410113, 0x03300093, 0x00110023, 0x00010703,\n\t\t\t0x03300393, 0x60771663, 0x00900193, 0x0003F117, 0xF1410113, 0x02300093, 0x001100A3, 0x00110703,\n\t\t\t0x02300393, 0x5E771663, 0x00A00193, 0x0003F117, 0xEF410113, 0x02200093, 0x00110123, 0x00210703,\n\t\t\t0x02200393, 0x5C771663, 0x00B00193, 0x0003F117, 0xED410113, 0x01200093, 0x001101A3, 0x00310703,\n\t\t\t0x01200393, 0x5A771663, 0x00C00193, 0x0003F117, 0xEB410113, 0x01100093, 0x00110223, 0x00410703,\n\t\t\t0x01100393, 0x58771663, 0x00D00193, 0x0003F117, 0xE9410113, 0x00100093, 0x001102A3, 0x00510703,\n\t\t\t0x00100393, 0x56771663, 0x00E00193, 0x0003F117, 0xE7410113, 0x03300093, 0x00110023, 0x00014703,\n\t\t\t0x03300393, 0x54771663, 0x00F00193, 0x0003F117, 0xE5410113, 0x02300093, 0x001100A3, 0x00114703,\n\t\t\t0x02300393, 0x52771663, 0x01000193, 0x0003F117, 0xE3410113, 0x02200093, 0x00110123, 0x00214703,\n\t\t\t0x02200393, 0x50771663, 0x01100193, 0x0003F117, 0xE1410113, 0x01200093, 0x001101A3, 0x00314703,\n\t\t\t0x01200393, 0x4E771663, 0x01200193, 0x0003F117, 0xDF410113, 0x01100093, 0x00110223, 0x00414703,\n\t\t\t0x01100393, 0x4C771663, 0x01300193, 0x0003F117, 0xDD410113, 0x00100093, 0x001102A3, 0x00514703,\n\t\t\t0x00100393, 0x4A771663, 0x01400193, 0x0003F117, 0xDB410113, 0xAABBD0B7, 0xCDD08093, 0x00112023,\n\t\t\t0x00012703, 0xAABBD3B7, 0xCDD38393, 0x48771263, 0x01500193, 0x0003F117, 0xD8C10113, 0xDAABC0B7,\n\t\t\t0xCCD08093, 0x00112223, 0x00412703, 0xDAABC3B7, 0xCCD38393, 0x44771E63, 0x01600193, 0x0003F117,\n\t\t\t0xD6410113, 0xDDAAC0B7, 0xBCC08093, 0x00112423, 0x00812703, 0xDDAAC3B7, 0xBCC38393, 0x42771A63,\n\t\t\t0x01700193, 0x0003F117, 0xD3C10113, 0xCDDAB0B7, 0xBBC08093, 0x00112623, 0x00C12703, 0xCDDAB3B7,\n\t\t\t0xBBC38393, 0x40771663, 0x01800193, 0x0003F117, 0xD1410113, 0xCCDDB0B7, 0xABB08093, 0x00112823,\n\t\t\t0x01012703, 0xCCDDB3B7, 0xABB38393, 0x3E771263, 0x01900193, 0x0003F117, 0xCEC10113, 0xBCCDE0B7,\n\t\t\t0xAAB08093, 0x00112A23, 0x01412703, 0xBCCDE3B7, 0xAAB38393, 0x3A771E63, 0x01A00193, 0x0003F117,\n\t\t\t0xCC410113, 0x001120B7, 0x23308093, 0x00112023, 0x00012703, 0x001123B7, 0x23338393, 0x38771A63,\n\t\t\t0x01B00193, 0x0003F117, 0xC9C10113, 0x300110B7, 0x22308093, 0x00112223, 0x00412703, 0x300113B7,\n\t\t\t0x22338393, 0x36771663, 0x01C00193, 0x0003F117, 0xC7410113, 0x330010B7, 0x12208093, 0x00112423,\n\t\t\t0x00812703, 0x330013B7, 0x12238393, 0x34771263, 0x01D00193, 0x0003F117, 0xC4C10113, 0x233000B7,\n\t\t\t0x11208093, 0x00112623, 0x00C12703, 0x233003B7, 0x11238393, 0x30771E63, 0x01E00193, 0x0003F117,\n\t\t\t0xC2410113, 0x223300B7, 0x01108093, 0x00112823, 0x01012703, 0x223303B7, 0x01138393, 0x2E771A63,\n\t\t\t0x01F00193, 0x0003F117, 0xBFC10113, 0x122330B7, 0x00108093, 0x00112A23, 0x01412703, 0x122333B7,\n\t\t\t0x00138393, 0x2C771663, 0x02000193, 0x0003F117, 0xBD410113, 0xFFFFD0B7, 0xCDD08093, 0x00111023,\n\t\t\t0x00011703, 0xFFFFD3B7, 0xCDD38393, 0x2A771263, 0x02100193, 0x0003F117, 0xBAC10113, 0xFFFFC0B7,\n\t\t\t0xCCD08093, 0x00111123, 0x00211703, 0xFFFFC3B7, 0xCCD38393, 0x26771E63, 0x02200193, 0x0003F117,\n\t\t\t0xB8410113, 0xFFFFC0B7, 0xBCC08093, 0x00111223, 0x00411703, 0xFFFFC3B7, 0xBCC38393, 0x24771A63,\n\t\t\t0x02300193, 0x0003F117, 0xB5C10113, 0xFFFFB0B7, 0xBBC08093, 0x00111323, 0x00611703, 0xFFFFB3B7,\n\t\t\t0xBBC38393, 0x22771663, 0x02400193, 0x0003F117, 0xB3410113, 0xFFFFB0B7, 0xABB08093, 0x00111423,\n\t\t\t0x00811703, 0xFFFFB3B7, 0xABB38393, 0x20771263, 0x02500193, 0x0003F117, 0xB0C10113, 0xFFFFE0B7,\n\t\t\t0xAAB08093, 0x00111523, 0x00A11703, 0xFFFFE3B7, 0xAAB38393, 0x1C771E63, 0x02600193, 0x0003F117,\n\t\t\t0xAE410113, 0x000020B7, 0x23308093, 0x00111023, 0x00011703, 0x000023B7, 0x23338393, 0x1A771A63,\n\t\t\t0x02700193, 0x0003F117, 0xABC10113, 0x000010B7, 0x22308093, 0x00111123, 0x00211703, 0x000013B7,\n\t\t\t0x22338393, 0x18771663, 0x02800193, 0x0003F117, 0xA9410113, 0x000010B7, 0x12208093, 0x00111223,\n\t\t\t0x00411703, 0x000013B7, 0x12238393, 0x16771263, 0x02900193, 0x0003F117, 0xA6C10113, 0x11200093,\n\t\t\t0x00111323, 0x00611703, 0x11200393, 0x14771263, 0x02A00193, 0x0003F117, 0xA4C10113, 0x01100093,\n\t\t\t0x00111423, 0x00811703, 0x01100393, 0x12771263, 0x02B00193, 0x0003F117, 0xA2C10113, 0x000030B7,\n\t\t\t0x00108093, 0x00111523, 0x00A11703, 0x000033B7, 0x00138393, 0x0E771E63, 0x02C00193, 0x0003F117,\n\t\t\t0xA0410113, 0x000020B7, 0x23308093, 0x00111023, 0x00015703, 0x000023B7, 0x23338393, 0x0C771A63,\n\t\t\t0x02D00193, 0x0003F117, 0x9DC10113, 0x000010B7, 0x22308093, 0x00111123, 0x00215703, 0x000013B7,\n\t\t\t0x22338393, 0x0A771663, 0x02E00193, 0x0003F117, 0x9B410113, 0x000010B7, 0x12208093, 0x00111223,\n\t\t\t0x00415703, 0x000013B7, 0x12238393, 0x08771263, 0x02F00193, 0x0003F117, 0x98C10113, 0x11200093,\n\t\t\t0x00111323, 0x00615703, 0x11200393, 0x06771263, 0x03000193, 0x0003F117, 0x96C10113, 0x01100093,\n\t\t\t0x00111423, 0x00815703, 0x01100393, 0x04771263, 0x03100193, 0x0003F117, 0x94C10113, 0x000030B7,\n\t\t\t0x00108093, 0x00111523, 0x00A15703, 0x000033B7, 0x00138393, 0x00771E63, 0x0EF00513, 0x0003F597,\n\t\t\t0x92458593, 0x00A581A3, 0x00358603, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF,\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF,\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sub\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000593, 0x00000613, 0x40C58733, 0x00000393, 0x4A771663,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x40C58733, 0x00000393, 0x48771A63, 0x00400193, 0x00300593,\n\t\t\t0x00700613, 0x40C58733, 0xFFC00393, 0x46771E63, 0x00500193, 0x00000593, 0xFFFF8637, 0x40C58733,\n\t\t\t0x000083B7, 0x46771263, 0x00600193, 0x800005B7, 0x00000613, 0x40C58733, 0x800003B7, 0x44771663,\n\t\t\t0x00700193, 0x800005B7, 0xFFFF8637, 0x40C58733, 0x800083B7, 0x42771A63, 0x00800193, 0x00000593,\n\t\t\t0x00008637, 0xFFF60613, 0x40C58733, 0xFFFF83B7, 0x00138393, 0x40771A63, 0x00900193, 0x800005B7,\n\t\t\t0xFFF58593, 0x00000613, 0x40C58733, 0x800003B7, 0xFFF38393, 0x3E771A63, 0x00A00193, 0x800005B7,\n\t\t\t0xFFF58593, 0x00008637, 0xFFF60613, 0x40C58733, 0x7FFF83B7, 0x3C771A63, 0x00B00193, 0x800005B7,\n\t\t\t0x00008637, 0xFFF60613, 0x40C58733, 0x7FFF83B7, 0x00138393, 0x3A771A63, 0x00C00193, 0x800005B7,\n\t\t\t0xFFF58593, 0xFFFF8637, 0x40C58733, 0x800083B7, 0xFFF38393, 0x38771A63, 0x00D00193, 0x00000593,\n\t\t\t0xFFF00613, 0x40C58733, 0x00100393, 0x36771E63, 0x00E00193, 0xFFF00593, 0x00100613, 0x40C58733,\n\t\t\t0xFFE00393, 0x36771263, 0x00F00193, 0xFFF00593, 0xFFF00613, 0x40C58733, 0x00000393, 0x34771663,\n\t\t\t0x01000193, 0x00D00593, 0x00B00613, 0x40C585B3, 0x00200393, 0x32759A63, 0x01100193, 0x00E00593,\n\t\t\t0x00B00613, 0x40C58633, 0x00300393, 0x30761E63, 0x01200193, 0x00D00593, 0x40B585B3, 0x00000393,\n\t\t\t0x30759463, 0x01300193, 0x00000213, 0x00D00093, 0x00B00113, 0x40208733, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x00200393, 0x2C731E63, 0x01400193, 0x00000213, 0x00E00093, 0x00B00113,\n\t\t\t0x40208733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5212E3, 0x00300393, 0x2A731663,\n\t\t\t0x01500193, 0x00000213, 0x00F00093, 0x00B00113, 0x40208733, 0x00000013, 0x00000013, 0x00070313,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0x00400393, 0x26731C63, 0x01600193, 0x00000213, 0x00D00093,\n\t\t\t0x00B00113, 0x40208733, 0x00120213, 0x00200293, 0xFE5216E3, 0x00200393, 0x24771863, 0x01700193,\n\t\t\t0x00000213, 0x00E00093, 0x00B00113, 0x00000013, 0x40208733, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x00300393, 0x22771263, 0x01800193, 0x00000213, 0x00F00093, 0x00B00113, 0x00000013, 0x00000013,\n\t\t\t0x40208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00400393, 0x1E771A63, 0x01900193, 0x00000213,\n\t\t\t0x00D00093, 0x00000013, 0x00B00113, 0x40208733, 0x00120213, 0x00200293, 0xFE5214E3, 0x00200393,\n\t\t\t0x1C771463, 0x01A00193, 0x00000213, 0x00E00093, 0x00000013, 0x00B00113, 0x00000013, 0x40208733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x00300393, 0x18771C63, 0x01B00193, 0x00000213, 0x00F00093,\n\t\t\t0x00000013, 0x00000013, 0x00B00113, 0x40208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00400393,\n\t\t\t0x16771463, 0x01C00193, 0x00000213, 0x00B00113, 0x00D00093, 0x40208733, 0x00120213, 0x00200293,\n\t\t\t0xFE5216E3, 0x00200393, 0x14771063, 0x01D00193, 0x00000213, 0x00B00113, 0x00E00093, 0x00000013,\n\t\t\t0x40208733, 0x00120213, 0x00200293, 0xFE5214E3, 0x00300393, 0x10771A63, 0x01E00193, 0x00000213,\n\t\t\t0x00B00113, 0x00F00093, 0x00000013, 0x00000013, 0x40208733, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x00400393, 0x0E771263, 0x01F00193, 0x00000213, 0x00B00113, 0x00000013, 0x00D00093, 0x40208733,\n\t\t\t0x00120213, 0x00200293, 0xFE5214E3, 0x00200393, 0x0A771C63, 0x02000193, 0x00000213, 0x00B00113,\n\t\t\t0x00000013, 0x00E00093, 0x00000013, 0x40208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x00300393,\n\t\t\t0x08771463, 0x02100193, 0x00000213, 0x00B00113, 0x00000013, 0x00000013, 0x00F00093, 0x40208733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x00400393, 0x04771C63, 0x02200193, 0xFF100093, 0x40100133,\n\t\t\t0x00F00393, 0x04711263, 0x02300193, 0x02000093, 0x40008133, 0x02000393, 0x02711863, 0x02400193,\n\t\t\t0x400000B3, 0x00000393, 0x02709063, 0x02500193, 0x01000093, 0x01E00113, 0x40208033, 0x00000393,\n\t\t\t0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-sw\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x0003F117, 0xFF410113, 0x00AA00B7, 0x0AA08093, 0x00000797,\n\t\t\t0x01478793, 0x00112023, 0x00012703, 0x0080006F, 0x00008713, 0x00AA03B7, 0x0AA38393, 0x4C771863,\n\t\t\t0x00300193, 0x0003F117, 0xFBC10113, 0xAA00B0B7, 0xA0008093, 0x00000797, 0x01478793, 0x00112223,\n\t\t\t0x00412703, 0x0080006F, 0x00008713, 0xAA00B3B7, 0xA0038393, 0x48771C63, 0x00400193, 0x0003F117,\n\t\t\t0xF8410113, 0x0AA010B7, 0xAA008093, 0x00000797, 0x01478793, 0x00112423, 0x00812703, 0x0080006F,\n\t\t\t0x00008713, 0x0AA013B7, 0xAA038393, 0x46771063, 0x00500193, 0x0003F117, 0xF4C10113, 0xA00AA0B7,\n\t\t\t0x00A08093, 0x00000797, 0x01478793, 0x00112623, 0x00C12703, 0x0080006F, 0x00008713, 0xA00AA3B7,\n\t\t\t0x00A38393, 0x42771463, 0x00600193, 0x0003F117, 0xF3010113, 0x00AA00B7, 0x0AA08093, 0x00000797,\n\t\t\t0x01478793, 0xFE112A23, 0xFF412703, 0x0080006F, 0x00008713, 0x00AA03B7, 0x0AA38393, 0x3E771863,\n\t\t\t0x00700193, 0x0003F117, 0xEF810113, 0xAA00B0B7, 0xA0008093, 0x00000797, 0x01478793, 0xFE112C23,\n\t\t\t0xFF812703, 0x0080006F, 0x00008713, 0xAA00B3B7, 0xA0038393, 0x3A771C63, 0x00800193, 0x0003F117,\n\t\t\t0xEC010113, 0x0AA010B7, 0xAA008093, 0x00000797, 0x01478793, 0xFE112E23, 0xFFC12703, 0x0080006F,\n\t\t\t0x00008713, 0x0AA013B7, 0xAA038393, 0x38771063, 0x00900193, 0x0003F117, 0xE8810113, 0xA00AA0B7,\n\t\t\t0x00A08093, 0x00000797, 0x01478793, 0x00112023, 0x00012703, 0x0080006F, 0x00008713, 0xA00AA3B7,\n\t\t\t0x00A38393, 0x34771463, 0x00A00193, 0x0003F097, 0xE5408093, 0x12345137, 0x67810113, 0xFE008213,\n\t\t\t0x02222023, 0x0000A283, 0x123453B7, 0x67838393, 0x30729E63, 0x00B00193, 0x0003F097, 0xE2808093,\n\t\t\t0x58213137, 0x09810113, 0xFFD08093, 0x0020A3A3, 0x0003F217, 0xE1420213, 0x00022283, 0x582133B7,\n\t\t\t0x09838393, 0x2E729463, 0x00C00193, 0x00000213, 0xAABBD6B7, 0xCDD68693, 0x0003F617, 0xDC860613,\n\t\t\t0x00D62023, 0x00062703, 0xAABBD3B7, 0xCDD38393, 0x2A771E63, 0x00120213, 0x00200293, 0xFC521AE3,\n\t\t\t0x00D00193, 0x00000213, 0xDAABC6B7, 0xCCD68693, 0x0003F617, 0xD9060613, 0x00000013, 0x00D62223,\n\t\t\t0x00462703, 0xDAABC3B7, 0xCCD38393, 0x28771063, 0x00120213, 0x00200293, 0xFC5218E3, 0x00E00193,\n\t\t\t0x00000213, 0xDDAAC6B7, 0xBCC68693, 0x0003F617, 0xD5460613, 0x00000013, 0x00000013, 0x00D62423,\n\t\t\t0x00862703, 0xDDAAC3B7, 0xBCC38393, 0x24771063, 0x00120213, 0x00200293, 0xFC5216E3, 0x00F00193,\n\t\t\t0x00000213, 0xCDDAB6B7, 0xBBC68693, 0x00000013, 0x0003F617, 0xD1060613, 0x00D62623, 0x00C62703,\n\t\t\t0xCDDAB3B7, 0xBBC38393, 0x20771263, 0x00120213, 0x00200293, 0xFC5218E3, 0x01000193, 0x00000213,\n\t\t\t0xCCDDB6B7, 0xABB68693, 0x00000013, 0x0003F617, 0xCD460613, 0x00000013, 0x00D62823, 0x01062703,\n\t\t\t0xCCDDB3B7, 0xABB38393, 0x1C771263, 0x00120213, 0x00200293, 0xFC5216E3, 0x01100193, 0x00000213,\n\t\t\t0xBCCDE6B7, 0xAAB68693, 0x00000013, 0x00000013, 0x0003F617, 0xC9060613, 0x00D62A23, 0x01462703,\n\t\t\t0xBCCDE3B7, 0xAAB38393, 0x18771263, 0x00120213, 0x00200293, 0xFC5216E3, 0x01200193, 0x00000213,\n\t\t\t0x0003F117, 0xC6010113, 0x001120B7, 0x23308093, 0x00112023, 0x00012703, 0x001123B7, 0x23338393,\n\t\t\t0x14771663, 0x00120213, 0x00200293, 0xFC521AE3, 0x01300193, 0x00000213, 0x0003F117, 0xC2810113,\n\t\t\t0x300110B7, 0x22308093, 0x00000013, 0x00112223, 0x00412703, 0x300113B7, 0x22338393, 0x10771863,\n\t\t\t0x00120213, 0x00200293, 0xFC5218E3, 0x01400193, 0x00000213, 0x0003F117, 0xBEC10113, 0x330010B7,\n\t\t\t0x12208093, 0x00000013, 0x00000013, 0x00112423, 0x00812703, 0x330013B7, 0x12238393, 0x0C771863,\n\t\t\t0x00120213, 0x00200293, 0xFC5216E3, 0x01500193, 0x00000213, 0x0003F117, 0xBAC10113, 0x00000013,\n\t\t\t0x233000B7, 0x11208093, 0x00112623, 0x00C12703, 0x233003B7, 0x11238393, 0x08771A63, 0x00120213,\n\t\t\t0x00200293, 0xFC5218E3, 0x01600193, 0x00000213, 0x0003F117, 0xB7010113, 0x00000013, 0x223300B7,\n\t\t\t0x01108093, 0x00000013, 0x00112823, 0x01012703, 0x223303B7, 0x01138393, 0x04771A63, 0x00120213,\n\t\t\t0x00200293, 0xFC5216E3, 0x01700193, 0x00000213, 0x0003F117, 0xB3010113, 0x00000013, 0x00000013,\n\t\t\t0x122330B7, 0x00108093, 0x00112A23, 0x01412703, 0x122333B7, 0x00138393, 0x00771A63, 0x00120213,\n\t\t\t0x00200293, 0xFC5216E3, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893,\n\t\t\t0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t\tdata: []uint32{\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF,\n\t\t\t0xDEADBEEF, 0xDEADBEEF, 0x00000000, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-xor\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0xFF0105B7, 0xF0058593, 0x0F0F1637, 0xF0F60613, 0x00C5C733,\n\t\t\t0xF00FF3B7, 0x00F38393, 0x4A771063, 0x00300193, 0x0FF015B7, 0xFF058593, 0xF0F0F637, 0x0F060613,\n\t\t\t0x00C5C733, 0xFF0103B7, 0xF0038393, 0x46771E63, 0x00400193, 0x00FF05B7, 0x0FF58593, 0x0F0F1637,\n\t\t\t0xF0F60613, 0x00C5C733, 0x0FF013B7, 0xFF038393, 0x44771C63, 0x00500193, 0xF00FF5B7, 0x00F58593,\n\t\t\t0xF0F0F637, 0x0F060613, 0x00C5C733, 0x00FF03B7, 0x0FF38393, 0x42771A63, 0x00600193, 0xFF0105B7,\n\t\t\t0xF0058593, 0x0F0F1637, 0xF0F60613, 0x00C5C5B3, 0xF00FF3B7, 0x00F38393, 0x40759863, 0x00700193,\n\t\t\t0xFF0105B7, 0xF0058593, 0x0F0F1637, 0xF0F60613, 0x00C5C633, 0xF00FF3B7, 0x00F38393, 0x3E761663,\n\t\t\t0x00800193, 0xFF0105B7, 0xF0058593, 0x00B5C5B3, 0x00000393, 0x3C759A63, 0x00900193, 0x00000213,\n\t\t\t0xFF0100B7, 0xF0008093, 0x0F0F1137, 0xF0F10113, 0x0020C733, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0xF00FF3B7, 0x00F38393, 0x38731E63, 0x00A00193, 0x00000213, 0x0FF010B7, 0xFF008093,\n\t\t\t0xF0F0F137, 0x0F010113, 0x0020C733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFC521EE3,\n\t\t\t0xFF0103B7, 0xF0038393, 0x36731063, 0x00B00193, 0x00000213, 0x00FF00B7, 0x0FF08093, 0x0F0F1137,\n\t\t\t0xF0F10113, 0x0020C733, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFC521CE3,\n\t\t\t0x0FF013B7, 0xFF038393, 0x32731063, 0x00C00193, 0x00000213, 0xFF0100B7, 0xF0008093, 0x0F0F1137,\n\t\t\t0xF0F10113, 0x0020C733, 0x00120213, 0x00200293, 0xFE5212E3, 0xF00FF3B7, 0x00F38393, 0x2E771663,\n\t\t\t0x00D00193, 0x00000213, 0x0FF010B7, 0xFF008093, 0xF0F0F137, 0x0F010113, 0x00000013, 0x0020C733,\n\t\t\t0x00120213, 0x00200293, 0xFE5210E3, 0xFF0103B7, 0xF0038393, 0x2A771A63, 0x00E00193, 0x00000213,\n\t\t\t0x00FF00B7, 0x0FF08093, 0x0F0F1137, 0xF0F10113, 0x00000013, 0x00000013, 0x0020C733, 0x00120213,\n\t\t\t0x00200293, 0xFC521EE3, 0x0FF013B7, 0xFF038393, 0x26771C63, 0x00F00193, 0x00000213, 0xFF0100B7,\n\t\t\t0xF0008093, 0x00000013, 0x0F0F1137, 0xF0F10113, 0x0020C733, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0xF00FF3B7, 0x00F38393, 0x24771063, 0x01000193, 0x00000213, 0x0FF010B7, 0xFF008093, 0x00000013,\n\t\t\t0xF0F0F137, 0x0F010113, 0x00000013, 0x0020C733, 0x00120213, 0x00200293, 0xFC521EE3, 0xFF0103B7,\n\t\t\t0xF0038393, 0x20771263, 0x01100193, 0x00000213, 0x00FF00B7, 0x0FF08093, 0x00000013, 0x00000013,\n\t\t\t0x0F0F1137, 0xF0F10113, 0x0020C733, 0x00120213, 0x00200293, 0xFC521EE3, 0x0FF013B7, 0xFF038393,\n\t\t\t0x1C771463, 0x01200193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0xFF0100B7, 0xF0008093, 0x0020C733,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0xF00FF3B7, 0x00F38393, 0x18771A63, 0x01300193, 0x00000213,\n\t\t\t0xF0F0F137, 0x0F010113, 0x0FF010B7, 0xFF008093, 0x00000013, 0x0020C733, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0xFF0103B7, 0xF0038393, 0x14771E63, 0x01400193, 0x00000213, 0x0F0F1137, 0xF0F10113,\n\t\t\t0x00FF00B7, 0x0FF08093, 0x00000013, 0x00000013, 0x0020C733, 0x00120213, 0x00200293, 0xFC521EE3,\n\t\t\t0x0FF013B7, 0xFF038393, 0x12771063, 0x01500193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0x00000013,\n\t\t\t0xFF0100B7, 0xF0008093, 0x0020C733, 0x00120213, 0x00200293, 0xFE5210E3, 0xF00FF3B7, 0x00F38393,\n\t\t\t0x0E771463, 0x01600193, 0x00000213, 0xF0F0F137, 0x0F010113, 0x00000013, 0x0FF010B7, 0xFF008093,\n\t\t\t0x00000013, 0x0020C733, 0x00120213, 0x00200293, 0xFC521EE3, 0xFF0103B7, 0xF0038393, 0x0A771663,\n\t\t\t0x01700193, 0x00000213, 0x0F0F1137, 0xF0F10113, 0x00000013, 0x00000013, 0x00FF00B7, 0x0FF08093,\n\t\t\t0x0020C733, 0x00120213, 0x00200293, 0xFC521EE3, 0x0FF013B7, 0xFF038393, 0x06771863, 0x01800193,\n\t\t\t0xFF0100B7, 0xF0008093, 0x00104133, 0xFF0103B7, 0xF0038393, 0x04711A63, 0x01900193, 0x00FF00B7,\n\t\t\t0x0FF08093, 0x0000C133, 0x00FF03B7, 0x0FF38393, 0x02711C63, 0x01A00193, 0x000040B3, 0x00000393,\n\t\t\t0x02709463, 0x01B00193, 0x111110B7, 0x11108093, 0x22222137, 0x22210113, 0x0020C033, 0x00000393,\n\t\t\t0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32ui-xori\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00FF16B7, 0xF0068693, 0xF0F6C713, 0xFF00F3B7, 0x00F38393,\n\t\t\t0x1C771663, 0x00300193, 0x0FF016B7, 0xFF068693, 0x0F06C713, 0x0FF013B7, 0xF0038393, 0x1A771863,\n\t\t\t0x00400193, 0x00FF16B7, 0x8FF68693, 0x70F6C713, 0x00FF13B7, 0xFF038393, 0x18771A63, 0x00500193,\n\t\t\t0xF00FF6B7, 0x00F68693, 0x0F06C713, 0xF00FF3B7, 0x0FF38393, 0x16771C63, 0x00600193, 0xFF00F5B7,\n\t\t\t0x70058593, 0x70F5C593, 0xFF00F3B7, 0x00F38393, 0x14759E63, 0x00700193, 0x00000213, 0x0FF010B7,\n\t\t\t0xFF008093, 0x0F00C713, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x0FF013B7, 0xF0038393,\n\t\t\t0x12731663, 0x00800193, 0x00000213, 0x00FF10B7, 0x8FF08093, 0x70F0C713, 0x00000013, 0x00070313,\n\t\t\t0x00120213, 0x00200293, 0xFE5212E3, 0x00FF13B7, 0xFF038393, 0x0E731C63, 0x00900193, 0x00000213,\n\t\t\t0xF00FF0B7, 0x00F08093, 0x0F00C713, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293,\n\t\t\t0xFE5210E3, 0xF00FF3B7, 0x0FF38393, 0x0C731063, 0x00A00193, 0x00000213, 0x0FF010B7, 0xFF008093,\n\t\t\t0x0F00C713, 0x00120213, 0x00200293, 0xFE5216E3, 0x0FF013B7, 0xF0038393, 0x08771A63, 0x00B00193,\n\t\t\t0x00000213, 0x00FF10B7, 0xFFF08093, 0x00000013, 0x00F0C713, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x00FF13B7, 0xFF038393, 0x06771263, 0x00C00193, 0x00000213, 0xF00FF0B7, 0x00F08093, 0x00000013,\n\t\t\t0x00000013, 0x0F00C713, 0x00120213, 0x00200293, 0xFE5212E3, 0xF00FF3B7, 0x0FF38393, 0x02771863,\n\t\t\t0x00D00193, 0x0F004093, 0x0F000393, 0x02709063, 0x00E00193, 0x00FF00B7, 0x0FF08093, 0x70F0C013,\n\t\t\t0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893,\n\t\t\t0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-div\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x01400593, 0x00600613, 0x02C5C733, 0x00300393, 0x0C771463,\n\t\t\t0x00300193, 0xFEC00593, 0x00600613, 0x02C5C733, 0xFFD00393, 0x0A771863, 0x00400193, 0x01400593,\n\t\t\t0xFFA00613, 0x02C5C733, 0xFFD00393, 0x08771C63, 0x00500193, 0xFEC00593, 0xFFA00613, 0x02C5C733,\n\t\t\t0x00300393, 0x08771063, 0x00600193, 0x800005B7, 0x00100613, 0x02C5C733, 0x800003B7, 0x06771463,\n\t\t\t0x00700193, 0x800005B7, 0xFFF00613, 0x02C5C733, 0x800003B7, 0x04771863, 0x00800193, 0x800005B7,\n\t\t\t0x00000613, 0x02C5C733, 0xFFF00393, 0x02771C63, 0x00900193, 0x00100593, 0x00000613, 0x02C5C733,\n\t\t\t0xFFF00393, 0x02771063, 0x00A00193, 0x00000593, 0x00000613, 0x02C5C733, 0xFFF00393, 0x00771463,\n\t\t\t0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073,\n\t\t\t0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-divu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x01400593, 0x00600613, 0x02C5D733, 0x00300393, 0x0C771663,\n\t\t\t0x00300193, 0xFEC00593, 0x00600613, 0x02C5D733, 0x2AAAB3B7, 0xAA738393, 0x0A771863, 0x00400193,\n\t\t\t0x01400593, 0xFFA00613, 0x02C5D733, 0x00000393, 0x08771C63, 0x00500193, 0xFEC00593, 0xFFA00613,\n\t\t\t0x02C5D733, 0x00000393, 0x08771063, 0x00600193, 0x800005B7, 0x00100613, 0x02C5D733, 0x800003B7,\n\t\t\t0x06771463, 0x00700193, 0x800005B7, 0xFFF00613, 0x02C5D733, 0x00000393, 0x04771863, 0x00800193,\n\t\t\t0x800005B7, 0x00000613, 0x02C5D733, 0xFFF00393, 0x02771C63, 0x00900193, 0x00100593, 0x00000613,\n\t\t\t0x02C5D733, 0xFFF00393, 0x02771063, 0x00A00193, 0x00000593, 0x00000613, 0x02C5D733, 0xFFF00393,\n\t\t\t0x00771463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513,\n\t\t\t0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-mul\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x02000193, 0x000085B7, 0xE0058593, 0xB6DB7637, 0xDB760613, 0x02C58733,\n\t\t\t0x00900393, 0x00939393, 0x4A771463, 0x02100193, 0x000085B7, 0xFC058593, 0xB6DB7637, 0xDB760613,\n\t\t\t0x02C58733, 0x000013B7, 0x24038393, 0x48771263, 0x00200193, 0x00000593, 0x00000613, 0x02C58733,\n\t\t\t0x00000393, 0x46771663, 0x00300193, 0x00100593, 0x00100613, 0x02C58733, 0x00100393, 0x44771A63,\n\t\t\t0x00400193, 0x00300593, 0x00700613, 0x02C58733, 0x01500393, 0x42771E63, 0x00500193, 0x00000593,\n\t\t\t0xFFFF8637, 0x02C58733, 0x00000393, 0x42771263, 0x00600193, 0x800005B7, 0x00000613, 0x02C58733,\n\t\t\t0x00000393, 0x40771663, 0x00700193, 0x800005B7, 0xFFFF8637, 0x02C58733, 0x00000393, 0x3E771A63,\n\t\t\t0x01E00193, 0xAAAAB5B7, 0xAAB58593, 0x00030637, 0xE7D60613, 0x02C58733, 0x000103B7, 0xF7F38393,\n\t\t\t0x3C771863, 0x01F00193, 0x000305B7, 0xE7D58593, 0xAAAAB637, 0xAAB60613, 0x02C58733, 0x000103B7,\n\t\t\t0xF7F38393, 0x3A771663, 0x02200193, 0xFF0005B7, 0xFF000637, 0x02C58733, 0x00000393, 0x38771A63,\n\t\t\t0x02300193, 0xFFF00593, 0xFFF00613, 0x02C58733, 0x00100393, 0x36771E63, 0x02400193, 0xFFF00593,\n\t\t\t0x00100613, 0x02C58733, 0xFFF00393, 0x36771263, 0x02500193, 0x00100593, 0xFFF00613, 0x02C58733,\n\t\t\t0xFFF00393, 0x34771663, 0x00800193, 0x00D00593, 0x00B00613, 0x02C585B3, 0x08F00393, 0x32759A63,\n\t\t\t0x00900193, 0x00E00593, 0x00B00613, 0x02C58633, 0x09A00393, 0x30761E63, 0x00A00193, 0x00D00593,\n\t\t\t0x02B585B3, 0x0A900393, 0x30759463, 0x00B00193, 0x00000213, 0x00D00093, 0x00B00113, 0x02208733,\n\t\t\t0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x08F00393, 0x2C731E63, 0x00C00193, 0x00000213,\n\t\t\t0x00E00093, 0x00B00113, 0x02208733, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5212E3,\n\t\t\t0x09A00393, 0x2A731663, 0x00D00193, 0x00000213, 0x00F00093, 0x00B00113, 0x02208733, 0x00000013,\n\t\t\t0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3, 0x0A500393, 0x26731C63, 0x00E00193,\n\t\t\t0x00000213, 0x00D00093, 0x00B00113, 0x02208733, 0x00120213, 0x00200293, 0xFE5216E3, 0x08F00393,\n\t\t\t0x24771863, 0x00F00193, 0x00000213, 0x00E00093, 0x00B00113, 0x00000013, 0x02208733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x09A00393, 0x22771263, 0x01000193, 0x00000213, 0x00F00093, 0x00B00113,\n\t\t\t0x00000013, 0x00000013, 0x02208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0A500393, 0x1E771A63,\n\t\t\t0x01100193, 0x00000213, 0x00D00093, 0x00000013, 0x00B00113, 0x02208733, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0x08F00393, 0x1C771463, 0x01200193, 0x00000213, 0x00E00093, 0x00000013, 0x00B00113,\n\t\t\t0x00000013, 0x02208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x09A00393, 0x18771C63, 0x01300193,\n\t\t\t0x00000213, 0x00F00093, 0x00000013, 0x00000013, 0x00B00113, 0x02208733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x0A500393, 0x16771463, 0x01400193, 0x00000213, 0x00B00113, 0x00D00093, 0x02208733,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x08F00393, 0x14771063, 0x01500193, 0x00000213, 0x00B00113,\n\t\t\t0x00E00093, 0x00000013, 0x02208733, 0x00120213, 0x00200293, 0xFE5214E3, 0x09A00393, 0x10771A63,\n\t\t\t0x01600193, 0x00000213, 0x00B00113, 0x00F00093, 0x00000013, 0x00000013, 0x02208733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x0A500393, 0x0E771263, 0x01700193, 0x00000213, 0x00B00113, 0x00000013,\n\t\t\t0x00D00093, 0x02208733, 0x00120213, 0x00200293, 0xFE5214E3, 0x08F00393, 0x0A771C63, 0x01800193,\n\t\t\t0x00000213, 0x00B00113, 0x00000013, 0x00E00093, 0x00000013, 0x02208733, 0x00120213, 0x00200293,\n\t\t\t0xFE5212E3, 0x09A00393, 0x08771463, 0x01900193, 0x00000213, 0x00B00113, 0x00000013, 0x00000013,\n\t\t\t0x00F00093, 0x02208733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0A500393, 0x04771C63, 0x01A00193,\n\t\t\t0x01F00093, 0x02100133, 0x00000393, 0x04711263, 0x01B00193, 0x02000093, 0x02008133, 0x00000393,\n\t\t\t0x02711863, 0x01C00193, 0x020000B3, 0x00000393, 0x02709063, 0x01D00193, 0x02100093, 0x02200113,\n\t\t\t0x02208033, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-mulh\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000593, 0x00000613, 0x02C59733, 0x00000393, 0x4A771A63,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x02C59733, 0x00000393, 0x48771E63, 0x00400193, 0x00300593,\n\t\t\t0x00700613, 0x02C59733, 0x00000393, 0x48771263, 0x00500193, 0x00000593, 0xFFFF8637, 0x02C59733,\n\t\t\t0x00000393, 0x46771663, 0x00600193, 0x800005B7, 0x00000613, 0x02C59733, 0x00000393, 0x44771A63,\n\t\t\t0x00700193, 0x800005B7, 0xFFFF8637, 0x02C59733, 0x000043B7, 0x42771E63, 0x01E00193, 0xAAAAB5B7,\n\t\t\t0xAAB58593, 0x00030637, 0xE7D60613, 0x02C59733, 0xFFFF03B7, 0x08138393, 0x40771C63, 0x01F00193,\n\t\t\t0x000305B7, 0xE7D58593, 0xAAAAB637, 0xAAB60613, 0x02C59733, 0xFFFF03B7, 0x08138393, 0x3E771A63,\n\t\t\t0x02000193, 0xFF0005B7, 0xFF000637, 0x02C59733, 0x000103B7, 0x3C771E63, 0x02100193, 0xFFF00593,\n\t\t\t0xFFF00613, 0x02C59733, 0x00000393, 0x3C771263, 0x02200193, 0xFFF00593, 0x00100613, 0x02C59733,\n\t\t\t0xFFF00393, 0x3A771663, 0x02300193, 0x00100593, 0xFFF00613, 0x02C59733, 0xFFF00393, 0x38771A63,\n\t\t\t0x00800193, 0x00D005B7, 0x00B00637, 0x02C595B3, 0x000093B7, 0xF0038393, 0x36759C63, 0x00900193,\n\t\t\t0x00E005B7, 0x00B00637, 0x02C59633, 0x0000A3B7, 0xA0038393, 0x34761E63, 0x00A00193, 0x00D005B7,\n\t\t\t0x02B595B3, 0x0000B3B7, 0x90038393, 0x34759263, 0x00B00193, 0x00000213, 0x00D000B7, 0x00B00137,\n\t\t\t0x02209733, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x000093B7, 0xF0038393, 0x30731A63,\n\t\t\t0x00C00193, 0x00000213, 0x00E000B7, 0x00B00137, 0x02209733, 0x00000013, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x0000A3B7, 0xA0038393, 0x2E731063, 0x00D00193, 0x00000213, 0x00F000B7,\n\t\t\t0x00B00137, 0x02209733, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0x0000A3B7, 0x50038393, 0x2A731463, 0x00E00193, 0x00000213, 0x00D000B7, 0x00B00137, 0x02209733,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x000093B7, 0xF0038393, 0x26771E63, 0x00F00193, 0x00000213,\n\t\t\t0x00E000B7, 0x00B00137, 0x00000013, 0x02209733, 0x00120213, 0x00200293, 0xFE5214E3, 0x0000A3B7,\n\t\t\t0xA0038393, 0x24771663, 0x01000193, 0x00000213, 0x00F000B7, 0x00B00137, 0x00000013, 0x00000013,\n\t\t\t0x02209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x20771C63, 0x01100193,\n\t\t\t0x00000213, 0x00D000B7, 0x00000013, 0x00B00137, 0x02209733, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x000093B7, 0xF0038393, 0x1E771463, 0x01200193, 0x00000213, 0x00E000B7, 0x00000013, 0x00B00137,\n\t\t\t0x00000013, 0x02209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0xA0038393, 0x1A771A63,\n\t\t\t0x01300193, 0x00000213, 0x00F000B7, 0x00000013, 0x00000013, 0x00B00137, 0x02209733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x18771063, 0x01400193, 0x00000213, 0x00B00137,\n\t\t\t0x00D000B7, 0x02209733, 0x00120213, 0x00200293, 0xFE5216E3, 0x000093B7, 0xF0038393, 0x14771A63,\n\t\t\t0x01500193, 0x00000213, 0x00B00137, 0x00E000B7, 0x00000013, 0x02209733, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0x0000A3B7, 0xA0038393, 0x12771263, 0x01600193, 0x00000213, 0x00B00137, 0x00F000B7,\n\t\t\t0x00000013, 0x00000013, 0x02209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393,\n\t\t\t0x0E771863, 0x01700193, 0x00000213, 0x00B00137, 0x00000013, 0x00D000B7, 0x02209733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x000093B7, 0xF0038393, 0x0C771063, 0x01800193, 0x00000213, 0x00B00137,\n\t\t\t0x00000013, 0x00E000B7, 0x00000013, 0x02209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7,\n\t\t\t0xA0038393, 0x08771663, 0x01900193, 0x00000213, 0x00B00137, 0x00000013, 0x00000013, 0x00F000B7,\n\t\t\t0x02209733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x04771C63, 0x01A00193,\n\t\t\t0x7C0000B7, 0x02101133, 0x00000393, 0x04711263, 0x01B00193, 0x800000B7, 0x02009133, 0x00000393,\n\t\t\t0x02711863, 0x01C00193, 0x020010B3, 0x00000393, 0x02709063, 0x01D00193, 0x021000B7, 0x02200137,\n\t\t\t0x02209033, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-mulhsu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000593, 0x00000613, 0x02C5A733, 0x00000393, 0x4A771A63,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x02C5A733, 0x00000393, 0x48771E63, 0x00400193, 0x00300593,\n\t\t\t0x00700613, 0x02C5A733, 0x00000393, 0x48771263, 0x00500193, 0x00000593, 0xFFFF8637, 0x02C5A733,\n\t\t\t0x00000393, 0x46771663, 0x00600193, 0x800005B7, 0x00000613, 0x02C5A733, 0x00000393, 0x44771A63,\n\t\t\t0x00700193, 0x800005B7, 0xFFFF8637, 0x02C5A733, 0x800043B7, 0x42771E63, 0x01E00193, 0xAAAAB5B7,\n\t\t\t0xAAB58593, 0x00030637, 0xE7D60613, 0x02C5A733, 0xFFFF03B7, 0x08138393, 0x40771C63, 0x01F00193,\n\t\t\t0x000305B7, 0xE7D58593, 0xAAAAB637, 0xAAB60613, 0x02C5A733, 0x000203B7, 0xEFE38393, 0x3E771A63,\n\t\t\t0x02000193, 0xFF0005B7, 0xFF000637, 0x02C5A733, 0xFF0103B7, 0x3C771E63, 0x02100193, 0xFFF00593,\n\t\t\t0xFFF00613, 0x02C5A733, 0xFFF00393, 0x3C771263, 0x02200193, 0xFFF00593, 0x00100613, 0x02C5A733,\n\t\t\t0xFFF00393, 0x3A771663, 0x02300193, 0x00100593, 0xFFF00613, 0x02C5A733, 0x00000393, 0x38771A63,\n\t\t\t0x00800193, 0x00D005B7, 0x00B00637, 0x02C5A5B3, 0x000093B7, 0xF0038393, 0x36759C63, 0x00900193,\n\t\t\t0x00E005B7, 0x00B00637, 0x02C5A633, 0x0000A3B7, 0xA0038393, 0x34761E63, 0x00A00193, 0x00D005B7,\n\t\t\t0x02B5A5B3, 0x0000B3B7, 0x90038393, 0x34759263, 0x00B00193, 0x00000213, 0x00D000B7, 0x00B00137,\n\t\t\t0x0220A733, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x000093B7, 0xF0038393, 0x30731A63,\n\t\t\t0x00C00193, 0x00000213, 0x00E000B7, 0x00B00137, 0x0220A733, 0x00000013, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x0000A3B7, 0xA0038393, 0x2E731063, 0x00D00193, 0x00000213, 0x00F000B7,\n\t\t\t0x00B00137, 0x0220A733, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0x0000A3B7, 0x50038393, 0x2A731463, 0x00E00193, 0x00000213, 0x00D000B7, 0x00B00137, 0x0220A733,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x000093B7, 0xF0038393, 0x26771E63, 0x00F00193, 0x00000213,\n\t\t\t0x00E000B7, 0x00B00137, 0x00000013, 0x0220A733, 0x00120213, 0x00200293, 0xFE5214E3, 0x0000A3B7,\n\t\t\t0xA0038393, 0x24771663, 0x01000193, 0x00000213, 0x00F000B7, 0x00B00137, 0x00000013, 0x00000013,\n\t\t\t0x0220A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x20771C63, 0x01100193,\n\t\t\t0x00000213, 0x00D000B7, 0x00000013, 0x00B00137, 0x0220A733, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x000093B7, 0xF0038393, 0x1E771463, 0x01200193, 0x00000213, 0x00E000B7, 0x00000013, 0x00B00137,\n\t\t\t0x00000013, 0x0220A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0xA0038393, 0x1A771A63,\n\t\t\t0x01300193, 0x00000213, 0x00F000B7, 0x00000013, 0x00000013, 0x00B00137, 0x0220A733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x18771063, 0x01400193, 0x00000213, 0x00B00137,\n\t\t\t0x00D000B7, 0x0220A733, 0x00120213, 0x00200293, 0xFE5216E3, 0x000093B7, 0xF0038393, 0x14771A63,\n\t\t\t0x01500193, 0x00000213, 0x00B00137, 0x00E000B7, 0x00000013, 0x0220A733, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0x0000A3B7, 0xA0038393, 0x12771263, 0x01600193, 0x00000213, 0x00B00137, 0x00F000B7,\n\t\t\t0x00000013, 0x00000013, 0x0220A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393,\n\t\t\t0x0E771863, 0x01700193, 0x00000213, 0x00B00137, 0x00000013, 0x00D000B7, 0x0220A733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x000093B7, 0xF0038393, 0x0C771063, 0x01800193, 0x00000213, 0x00B00137,\n\t\t\t0x00000013, 0x00E000B7, 0x00000013, 0x0220A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7,\n\t\t\t0xA0038393, 0x08771663, 0x01900193, 0x00000213, 0x00B00137, 0x00000013, 0x00000013, 0x00F000B7,\n\t\t\t0x0220A733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x04771C63, 0x01A00193,\n\t\t\t0x7C0000B7, 0x02102133, 0x00000393, 0x04711263, 0x01B00193, 0x800000B7, 0x0200A133, 0x00000393,\n\t\t\t0x02711863, 0x01C00193, 0x020020B3, 0x00000393, 0x02709063, 0x01D00193, 0x021000B7, 0x02200137,\n\t\t\t0x0220A033, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-mulhu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x00000593, 0x00000613, 0x02C5B733, 0x00000393, 0x4A771A63,\n\t\t\t0x00300193, 0x00100593, 0x00100613, 0x02C5B733, 0x00000393, 0x48771E63, 0x00400193, 0x00300593,\n\t\t\t0x00700613, 0x02C5B733, 0x00000393, 0x48771263, 0x00500193, 0x00000593, 0xFFFF8637, 0x02C5B733,\n\t\t\t0x00000393, 0x46771663, 0x00600193, 0x800005B7, 0x00000613, 0x02C5B733, 0x00000393, 0x44771A63,\n\t\t\t0x00700193, 0x800005B7, 0xFFFF8637, 0x02C5B733, 0x7FFFC3B7, 0x42771E63, 0x01E00193, 0xAAAAB5B7,\n\t\t\t0xAAB58593, 0x00030637, 0xE7D60613, 0x02C5B733, 0x000203B7, 0xEFE38393, 0x40771C63, 0x01F00193,\n\t\t\t0x000305B7, 0xE7D58593, 0xAAAAB637, 0xAAB60613, 0x02C5B733, 0x000203B7, 0xEFE38393, 0x3E771A63,\n\t\t\t0x02000193, 0xFF0005B7, 0xFF000637, 0x02C5B733, 0xFE0103B7, 0x3C771E63, 0x02100193, 0xFFF00593,\n\t\t\t0xFFF00613, 0x02C5B733, 0xFFE00393, 0x3C771263, 0x02200193, 0xFFF00593, 0x00100613, 0x02C5B733,\n\t\t\t0x00000393, 0x3A771663, 0x02300193, 0x00100593, 0xFFF00613, 0x02C5B733, 0x00000393, 0x38771A63,\n\t\t\t0x00800193, 0x00D005B7, 0x00B00637, 0x02C5B5B3, 0x000093B7, 0xF0038393, 0x36759C63, 0x00900193,\n\t\t\t0x00E005B7, 0x00B00637, 0x02C5B633, 0x0000A3B7, 0xA0038393, 0x34761E63, 0x00A00193, 0x00D005B7,\n\t\t\t0x02B5B5B3, 0x0000B3B7, 0x90038393, 0x34759263, 0x00B00193, 0x00000213, 0x00D000B7, 0x00B00137,\n\t\t\t0x0220B733, 0x00070313, 0x00120213, 0x00200293, 0xFE5214E3, 0x000093B7, 0xF0038393, 0x30731A63,\n\t\t\t0x00C00193, 0x00000213, 0x00E000B7, 0x00B00137, 0x0220B733, 0x00000013, 0x00070313, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x0000A3B7, 0xA0038393, 0x2E731063, 0x00D00193, 0x00000213, 0x00F000B7,\n\t\t\t0x00B00137, 0x0220B733, 0x00000013, 0x00000013, 0x00070313, 0x00120213, 0x00200293, 0xFE5210E3,\n\t\t\t0x0000A3B7, 0x50038393, 0x2A731463, 0x00E00193, 0x00000213, 0x00D000B7, 0x00B00137, 0x0220B733,\n\t\t\t0x00120213, 0x00200293, 0xFE5216E3, 0x000093B7, 0xF0038393, 0x26771E63, 0x00F00193, 0x00000213,\n\t\t\t0x00E000B7, 0x00B00137, 0x00000013, 0x0220B733, 0x00120213, 0x00200293, 0xFE5214E3, 0x0000A3B7,\n\t\t\t0xA0038393, 0x24771663, 0x01000193, 0x00000213, 0x00F000B7, 0x00B00137, 0x00000013, 0x00000013,\n\t\t\t0x0220B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x20771C63, 0x01100193,\n\t\t\t0x00000213, 0x00D000B7, 0x00000013, 0x00B00137, 0x0220B733, 0x00120213, 0x00200293, 0xFE5214E3,\n\t\t\t0x000093B7, 0xF0038393, 0x1E771463, 0x01200193, 0x00000213, 0x00E000B7, 0x00000013, 0x00B00137,\n\t\t\t0x00000013, 0x0220B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0xA0038393, 0x1A771A63,\n\t\t\t0x01300193, 0x00000213, 0x00F000B7, 0x00000013, 0x00000013, 0x00B00137, 0x0220B733, 0x00120213,\n\t\t\t0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x18771063, 0x01400193, 0x00000213, 0x00B00137,\n\t\t\t0x00D000B7, 0x0220B733, 0x00120213, 0x00200293, 0xFE5216E3, 0x000093B7, 0xF0038393, 0x14771A63,\n\t\t\t0x01500193, 0x00000213, 0x00B00137, 0x00E000B7, 0x00000013, 0x0220B733, 0x00120213, 0x00200293,\n\t\t\t0xFE5214E3, 0x0000A3B7, 0xA0038393, 0x12771263, 0x01600193, 0x00000213, 0x00B00137, 0x00F000B7,\n\t\t\t0x00000013, 0x00000013, 0x0220B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393,\n\t\t\t0x0E771863, 0x01700193, 0x00000213, 0x00B00137, 0x00000013, 0x00D000B7, 0x0220B733, 0x00120213,\n\t\t\t0x00200293, 0xFE5214E3, 0x000093B7, 0xF0038393, 0x0C771063, 0x01800193, 0x00000213, 0x00B00137,\n\t\t\t0x00000013, 0x00E000B7, 0x00000013, 0x0220B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7,\n\t\t\t0xA0038393, 0x08771663, 0x01900193, 0x00000213, 0x00B00137, 0x00000013, 0x00000013, 0x00F000B7,\n\t\t\t0x0220B733, 0x00120213, 0x00200293, 0xFE5212E3, 0x0000A3B7, 0x50038393, 0x04771C63, 0x01A00193,\n\t\t\t0x7C0000B7, 0x02103133, 0x00000393, 0x04711263, 0x01B00193, 0x800000B7, 0x0200B133, 0x00000393,\n\t\t\t0x02711863, 0x01C00193, 0x020030B3, 0x00000393, 0x02709063, 0x01D00193, 0x021000B7, 0x02200137,\n\t\t\t0x0220B033, 0x00000393, 0x00701463, 0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193,\n\t\t\t0x05D00893, 0x00018513, 0x00000073, 0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073,\n\t\t\t0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-rem\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x01400593, 0x00600613, 0x02C5E733, 0x00200393, 0x0C771463,\n\t\t\t0x00300193, 0xFEC00593, 0x00600613, 0x02C5E733, 0xFFE00393, 0x0A771863, 0x00400193, 0x01400593,\n\t\t\t0xFFA00613, 0x02C5E733, 0x00200393, 0x08771C63, 0x00500193, 0xFEC00593, 0xFFA00613, 0x02C5E733,\n\t\t\t0xFFE00393, 0x08771063, 0x00600193, 0x800005B7, 0x00100613, 0x02C5E733, 0x00000393, 0x06771463,\n\t\t\t0x00700193, 0x800005B7, 0xFFF00613, 0x02C5E733, 0x00000393, 0x04771863, 0x00800193, 0x800005B7,\n\t\t\t0x00000613, 0x02C5E733, 0x800003B7, 0x02771C63, 0x00900193, 0x00100593, 0x00000613, 0x02C5E733,\n\t\t\t0x00100393, 0x02771063, 0x00A00193, 0x00000593, 0x00000613, 0x02C5E733, 0x00000393, 0x00771463,\n\t\t\t0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073,\n\t\t\t0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n\t{\n\t\tname: \"rv32um-remu\",\n\t\ttext: []uint32{\n\t\t\t0x00000193, 0x0040006F, 0x00200193, 0x01400593, 0x00600613, 0x02C5F733, 0x00200393, 0x0C771463,\n\t\t\t0x00300193, 0xFEC00593, 0x00600613, 0x02C5F733, 0x00200393, 0x0A771863, 0x00400193, 0x01400593,\n\t\t\t0xFFA00613, 0x02C5F733, 0x01400393, 0x08771C63, 0x00500193, 0xFEC00593, 0xFFA00613, 0x02C5F733,\n\t\t\t0xFEC00393, 0x08771063, 0x00600193, 0x800005B7, 0x00100613, 0x02C5F733, 0x00000393, 0x06771463,\n\t\t\t0x00700193, 0x800005B7, 0xFFF00613, 0x02C5F733, 0x800003B7, 0x04771863, 0x00800193, 0x800005B7,\n\t\t\t0x00000613, 0x02C5F733, 0x800003B7, 0x02771C63, 0x00900193, 0x00100593, 0x00000613, 0x02C5F733,\n\t\t\t0x00100393, 0x02771063, 0x00A00193, 0x00000593, 0x00000613, 0x02C5F733, 0x00000393, 0x00771463,\n\t\t\t0x02301063, 0x0FF0000F, 0x00018063, 0x00119193, 0x0011E193, 0x05D00893, 0x00018513, 0x00000073,\n\t\t\t0x0FF0000F, 0x00100193, 0x05D00893, 0x00000513, 0x00000073, 0x00000000,\n\t\t},\n\t},\n}\n\n// skipped names the two cases this machine cannot pass by design, with the\n// reason, because silently dropping a conformance case is how a suite stops\n// meaning anything.\nvar skipped = map[string]string{\n\t// FENCE.I exists to make writes to the instruction stream visible. This\n\t// machine predecodes its text and refuses stores into it, so there is no\n\t// instruction stream to make visible: self-modifying code is not\n\t// unimplemented here, it is excluded. See README, W xor X.\n\t\"rv32ui-fence_i\": \"self-modifying code is refused by design\",\n}\n\nfunc TestRISCVConformance(t *testing.T) {\n\tran, skips := 0, 0\n\tfor _, c := range conformanceCases {\n\t\tif why, ok := skipped[c.name]; ok {\n\t\t\tskips++\n\t\t\tt.Log(c.name + \": skipped, \" + why)\n\t\t\tcontinue\n\t\t}\n\t\tm, err := NewMachine(Image(c.text), entry)\n\t\tuassert.NoError(t, err, c.name)\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif len(c.data) \u003e 0 {\n\t\t\tuassert.NoError(t, m.LoadData(conformanceDataAddr, Image(c.data)), c.name)\n\t\t}\n\t\t_, status := m.Step(vmkit.NewTestHost(), conformanceFuel)\n\t\tuassert.Equal(t, \"halted\", status.String(), c.name+\": \"+m.Trap())\n\t\t// The suite's convention: a0 is 0 on pass, and on failure it is the\n\t\t// failing case number shifted left with the low bit set.\n\t\ta0 := m.Registers()[10]\n\t\tuassert.Equal(t, uint64(0), uint64(a0),\n\t\t\tc.name+\" failed at its case number \"+itoa(int(a0\u003e\u003e1)))\n\t\tran++\n\t}\n\tuassert.True(t, ran \u003e= 45, \"the conformance suite must actually have run\")\n\tuassert.Equal(t, len(skipped), skips, \"a skip must be declared, not discovered\")\n}\n\nfunc itoa(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b []byte\n\tfor n \u003e 0 {\n\t\tb = append([]byte{byte('0' + n%10)}, b...)\n\t\tn /= 10\n\t}\n\treturn string(b)\n}\n\n// A conformance suite that passes a broken emulator is worse than none, so the\n// harness is checked against a program built to fail, using the suite's own\n// exit convention. Without this, a change that made every case report a0 == 0\n// would turn the whole file green and look like progress.\n//\n// The suite was also checked the other way, by injecting faults into exec.gno\n// and confirming it went red and named the case:\n//\n//   SRAI as a logical shift        -\u003e rv32ui-srai and rv32ui-lui, case 3\n//   REMU by zero returning 0       -\u003e rv32um-remu, case 8\n//\n// Both are recorded here rather than left as something someone did once,\n// because they are how you check this file still bites.\nfunc TestConformanceHarnessDetectsAFailure(t *testing.T) {\n\t// The tail of RVTEST_FAIL for testnum 5: gp is shifted left and the low\n\t// bit set, so a0 is 11 and the reported case number is 5.\n\tfail := []uint32{\n\t\taddi(3, 0, 5),   // TESTNUM = 5\n\t\taddi(17, 0, 93), // a7 = exit\n\t\taddi(10, 0, 11), // a0 = (5 \u003c\u003c 1) | 1\n\t\tecall(),\n\t}\n\tm, err := NewMachine(Image(fail), entry)\n\tuassert.NoError(t, err)\n\tif m == nil {\n\t\treturn\n\t}\n\t_, status := m.Step(vmkit.NewTestHost(), conformanceFuel)\n\tuassert.Equal(t, \"halted\", status.String())\n\n\ta0 := m.Registers()[10]\n\tuassert.False(t, a0 == 0, \"a failing case must not look like a pass\")\n\tuassert.Equal(t, uint64(11), uint64(a0))\n\tuassert.Equal(t, \"5\", itoa(int(a0\u003e\u003e1)), \"the reported case number\")\n}\n\n// And the pass side, so the convention is pinned from both directions.\nfunc TestConformanceHarnessRecognizesAPass(t *testing.T) {\n\tpass := []uint32{\n\t\taddi(3, 0, 1),   // TESTNUM = 1\n\t\taddi(17, 0, 93), // a7 = exit\n\t\taddi(10, 0, 0),  // a0 = 0\n\t\tecall(),\n\t}\n\tm, err := NewMachine(Image(pass), entry)\n\tuassert.NoError(t, err)\n\tif m == nil {\n\t\treturn\n\t}\n\t_, status := m.Step(vmkit.NewTestHost(), conformanceFuel)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, uint64(0), uint64(m.Registers()[10]))\n}\n"},{"name":"decode.gno","body":"package riscv\n\n// RV32 instruction decode: bit fields, not a parser.\n//\n// Every instruction is exactly 32 bits and the opcode is the low 7. The rest is\n// slicing: which fields exist depends on the format, and there are six formats.\n// This file is only the slicing; exec.gno decides what the fields mean.\n\n// Instruction formats. Named as the spec names them.\nconst (\n\topLUI    = 0x37\n\topAUIPC  = 0x17\n\topJAL    = 0x6F\n\topJALR   = 0x67\n\topBranch = 0x63\n\topLoad   = 0x03\n\topStore  = 0x23\n\topImm    = 0x13\n\topReg    = 0x33\n\topSystem = 0x73\n\topFence  = 0x0F\n)\n\n// opcode returns the low 7 bits.\nfunc opcode(inst uint32) uint32 { return inst \u0026 0x7F }\n\n// rd, rs1 and rs2 are register selectors, 5 bits each, always in the same place\n// when the format has them.\nfunc rd(inst uint32) uint32  { return (inst \u003e\u003e 7) \u0026 0x1F }\nfunc rs1(inst uint32) uint32 { return (inst \u003e\u003e 15) \u0026 0x1F }\nfunc rs2(inst uint32) uint32 { return (inst \u003e\u003e 20) \u0026 0x1F }\n\n// funct3 and funct7 narrow an opcode to an operation.\nfunc funct3(inst uint32) uint32 { return (inst \u003e\u003e 12) \u0026 0x7 }\nfunc funct7(inst uint32) uint32 { return inst \u003e\u003e 25 }\n\n// The immediates. Each format scatters the bits differently, and every one of\n// them is SIGN EXTENDED from its top bit: RISC-V has no zero-extended immediate\n// in the base set, and getting that wrong is the classic decoder bug because\n// small positive programs still work.\n//\n// The shift-right-on-int32 idiom is the sign extension: Go defines \u003e\u003e on a\n// signed type as arithmetic.\n\n// immI is the 12-bit immediate of I-type (loads, ALU-immediate, JALR, ECALL).\nfunc immI(inst uint32) uint32 { return uint32(int32(inst) \u003e\u003e 20) }\n\n// immS is S-type (stores), split across two fields.\nfunc immS(inst uint32) uint32 {\n\treturn uint32(int32(inst)\u003e\u003e25\u003c\u003c5) | ((inst \u003e\u003e 7) \u0026 0x1F)\n}\n\n// immB is B-type (branches): S-type with the bits rotated, and bit 0 always\n// zero because a branch target is 2-byte aligned.\nfunc immB(inst uint32) uint32 {\n\timm := uint32(int32(inst)\u003e\u003e31) \u003c\u003c 12 // sign, bit 12\n\timm |= ((inst \u003e\u003e 7) \u0026 0x1) \u003c\u003c 11     // bit 11\n\timm |= ((inst \u003e\u003e 25) \u0026 0x3F) \u003c\u003c 5    // bits 10:5\n\timm |= ((inst \u003e\u003e 8) \u0026 0xF) \u003c\u003c 1      // bits 4:1\n\treturn imm\n}\n\n// immU is U-type (LUI, AUIPC): the top 20 bits, already in place.\nfunc immU(inst uint32) uint32 { return inst \u0026 0xFFFFF000 }\n\n// immJ is J-type (JAL), the most scattered of the six.\nfunc immJ(inst uint32) uint32 {\n\timm := uint32(int32(inst)\u003e\u003e31) \u003c\u003c 20 // sign, bit 20\n\timm |= ((inst \u003e\u003e 12) \u0026 0xFF) \u003c\u003c 12   // bits 19:12\n\timm |= ((inst \u003e\u003e 20) \u0026 0x1) \u003c\u003c 11    // bit 11\n\timm |= ((inst \u003e\u003e 21) \u0026 0x3FF) \u003c\u003c 1   // bits 10:1\n\treturn imm\n}\n"},{"name":"decode_test.gno","body":"package riscv\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// jal is only needed to exercise immJ, the one format no program in\n// riscv_test.gno reaches for.\nfunc jal(rd, imm uint32) uint32 { return jType(imm, rd, opJAL) }\n\n// The assembler in riscv_test.gno and the decoders here were written from the\n// spec independently, so encoding a known field and reading it back is a real\n// cross-check rather than a tautology: a field in the wrong place fails unless\n// both files put it in the same wrong place.\nfunc TestDecodeRoundTripsTheAssembler(t *testing.T) {\n\tinst := add(5, 6, 7)\n\tuassert.Equal(t, uint64(opReg), uint64(opcode(inst)))\n\tuassert.Equal(t, uint64(5), uint64(rd(inst)))\n\tuassert.Equal(t, uint64(6), uint64(rs1(inst)))\n\tuassert.Equal(t, uint64(7), uint64(rs2(inst)))\n\tuassert.Equal(t, uint64(0), uint64(funct3(inst)))\n\tuassert.Equal(t, uint64(0), uint64(funct7(inst)))\n\tuassert.Equal(t, uint64(0x20), uint64(funct7(sub(5, 6, 7))))\n\tuassert.Equal(t, uint64(0x01), uint64(funct7(mul(5, 6, 7))))\n}\n\n// Every immediate in the base set is sign extended from its own top bit, and\n// the top bit is in a different place in each of the five formats. These are\n// the boundary values: the largest positive, the value one past it that must\n// come back negative, and all-ones for minus one.\nfunc TestImmediatesSignExtend(t *testing.T) {\n\t// I-type, 12 bits.\n\tuassert.Equal(t, uint64(0x7FF), uint64(immI(addi(1, 2, 0x7FF))))\n\tuassert.Equal(t, uint64(0xFFFFF800), uint64(immI(addi(1, 2, 0x800))))\n\tuassert.Equal(t, uint64(0xFFFFFFFF), uint64(immI(addi(1, 2, 0xFFF))))\n\n\t// S-type, 12 bits split across two fields.\n\tuassert.Equal(t, uint64(0x7FF), uint64(immS(sw(3, 4, 0x7FF))))\n\tuassert.Equal(t, uint64(0xFFFFF800), uint64(immS(sw(3, 4, 0x800))))\n\tuassert.Equal(t, uint64(0xFFFFFFFF), uint64(immS(sw(3, 4, 0xFFF))))\n\n\t// B-type, 13 bits with bit 0 always zero. -12 is the encoding the\n\t// benchmark's loop branch uses, and getting its width wrong is what makes\n\t// a backward branch jump forward instead.\n\tuassert.Equal(t, uint64(0x7FE), uint64(immB(bne(1, 2, 0x7FE))))\n\tuassert.Equal(t, uint64(0xFFFFF000), uint64(immB(bne(1, 2, 0x1000))))\n\tuassert.Equal(t, uint64(0xFFFFFFF4), uint64(immB(bne(1, 2, 0x1FF4))))\n\n\t// U-type is the only one that is not sign extended, because it is already\n\t// the top 20 bits.\n\tuassert.Equal(t, uint64(0xDEADB000), uint64(immU(lui(1, 0xDEADB000))))\n\n\t// J-type, 21 bits with bit 0 always zero.\n\tuassert.Equal(t, uint64(0x7FE), uint64(immJ(jal(1, 0x7FE))))\n\tuassert.Equal(t, uint64(0xFFF00000), uint64(immJ(jal(1, 0x100000))))\n\tuassert.Equal(t, uint64(0xFFFFFFFE), uint64(immJ(jal(1, 0x1FFFFE))))\n}\n\nfunc jalr(rd, rs1, imm uint32) uint32 { return iType(imm, rs1, 0x0, rd, opJALR) }\n"},{"name":"ecall.gno","body":"package riscv\n\nimport \"gno.land/p/moul/x/vm/vmkit/v0\"\n\n// The syscall table: the entire interface between a guest and the chain.\n//\n// Register-passing, in the RISC-V Linux convention a compiler already knows:\n// a7 (x17) selects the call, a0..a2 (x10..x12) carry arguments, a0 receives the\n// result. A guest written against these needs no gno-specific runtime, only the\n// three lines of inline assembly every no_std program already has for ecall.\n//\n// Deliberately small. Every call here maps onto something [vmkit.Host] already\n// offers, because the Host is the audited surface and a syscall that reaches\n// past it would be a second, unreviewed one.\nconst (\n\tsysExit   = 93 // a0 = status. The Linux number, so a guest can reuse its libc shim.\n\tsysWrite  = 64 // a0 = fd (ignored), a1 = buf, a2 = len -\u003e Host.Output\n\tsysRead   = 63 // a0 = fd (ignored), a1 = buf, a2 = len \u003c- Host.Input\n\tsysHeight = 90 // -\u003e block height\n\tsysNow    = 91 // -\u003e block time, Unix seconds\n\tsysCaller = 92 // a0 = buf, a1 = len; writes the caller address, returns bytes written\n\tsysLog    = 94 // a0 = buf, a1 = len -\u003e Host.Log\n\tsysEmit   = 95 // a0 = type buf, a1 = type len, a2 = body buf, a3 = body len\n)\n\n// maxSyscallBytes bounds one call's buffer. A guest asking to write a gigabyte\n// is a guest that found the host's allocator, not one with something to say.\nconst maxSyscallBytes = 64 * 1024\n\n// ecall dispatches a syscall. It returns the machine status and whether the\n// machine should stop: only exit stops it, everything else returns to the guest\n// with a0 set.\nfunc (m *Machine) ecall(h vmkit.Host) (vmkit.Status, bool) {\n\tswitch m.reg[17] { // a7\n\tcase sysExit:\n\t\t// The guest's exit status is not the machine's: a program that returns\n\t\t// 1 has halted, it has not trapped. Trapping is for what the machine\n\t\t// could not do, and a chain should not confuse \"your code said no\"\n\t\t// with \"the VM broke\".\n\t\treturn vmkit.Halted, true\n\n\tcase sysWrite:\n\t\tbuf, ok := m.readGuest(m.reg[11], m.reg[12])\n\t\tif !ok {\n\t\t\tm.reg[10] = ^uint32(0)\n\t\t\treturn vmkit.Running, false\n\t\t}\n\t\th.Output(buf)\n\t\tm.outLen += len(buf)\n\t\tm.reg[10] = uint32(len(buf))\n\n\tcase sysRead:\n\t\tin := h.Input()\n\t\tn := int(m.reg[12])\n\t\tif n \u003e len(in) {\n\t\t\tn = len(in)\n\t\t}\n\t\tif n \u003e maxSyscallBytes {\n\t\t\tn = maxSyscallBytes\n\t\t}\n\t\tif !m.writeGuest(m.reg[11], in[:n]) {\n\t\t\tm.reg[10] = ^uint32(0)\n\t\t\treturn vmkit.Running, false\n\t\t}\n\t\tm.reg[10] = uint32(n)\n\n\tcase sysHeight:\n\t\tm.reg[10] = uint32(h.Height())\n\n\tcase sysNow:\n\t\tm.reg[10] = uint32(h.Now())\n\n\tcase sysCaller:\n\t\taddr := []byte(h.Caller().String())\n\t\tn := int(m.reg[11])\n\t\tif n \u003e len(addr) {\n\t\t\tn = len(addr)\n\t\t}\n\t\tif !m.writeGuest(m.reg[10], addr[:n]) {\n\t\t\tm.reg[10] = ^uint32(0)\n\t\t\treturn vmkit.Running, false\n\t\t}\n\t\tm.reg[10] = uint32(n)\n\n\tcase sysLog:\n\t\tbuf, ok := m.readGuest(m.reg[10], m.reg[11])\n\t\tif !ok {\n\t\t\tm.reg[10] = ^uint32(0)\n\t\t\treturn vmkit.Running, false\n\t\t}\n\t\th.Log(string(buf))\n\t\tm.reg[10] = uint32(len(buf))\n\n\tcase sysEmit:\n\t\ttyp, ok1 := m.readGuest(m.reg[10], m.reg[11])\n\t\tbody, ok2 := m.readGuest(m.reg[12], m.reg[13])\n\t\tif !ok1 || !ok2 {\n\t\t\tm.reg[10] = ^uint32(0)\n\t\t\treturn vmkit.Running, false\n\t\t}\n\t\th.Emit(string(typ), \"body\", string(body))\n\t\tm.reg[10] = 0\n\n\tdefault:\n\t\t// An unknown syscall is a trap, not a silent zero. A guest compiled\n\t\t// against a newer table must fail loudly on an older host rather than\n\t\t// read a success it did not get.\n\t\tm.trap = \"unknown syscall\"\n\t\treturn vmkit.Trapped, true\n\t}\n\treturn vmkit.Running, false\n}\n\n// readGuest copies a buffer out of guest memory, refusing anything out of range\n// or larger than maxSyscallBytes.\nfunc (m *Machine) readGuest(addr, length uint32) ([]byte, bool) {\n\tif length \u003e maxSyscallBytes || !m.mem.inRange(addr, int(length)) {\n\t\treturn nil, false\n\t}\n\tout := make([]byte, length)\n\tcopy(out, m.mem.b[addr:addr+length])\n\treturn out, true\n}\n\n// writeGuest copies into guest memory, marking the pages it touched.\nfunc (m *Machine) writeGuest(addr uint32, b []byte) bool {\n\tif len(b) \u003e maxSyscallBytes || !m.mem.inRange(addr, len(b)) {\n\t\treturn false\n\t}\n\tcopy(m.mem.b[addr:], b)\n\tfor i := 0; i \u003c len(b); i++ {\n\t\tm.mem.dirty[(uint64(addr)+uint64(i))/PageSize] = true\n\t}\n\treturn true\n}\n"},{"name":"exec.gno","body":"// Package riscv is an RV32IM emulator for gno.land: 48 instructions that every\n// real compiler already targets.\n//\n// A guest here is not written in a new language. `rustc --target\n// riscv32im-unknown-none-elf`, `clang -target riscv32`, TinyGo and Zig all emit\n// it, so a program arrives compiled by the real compiler and optimized by the\n// real optimizer. The interpreter is a decode loop rather than a semantic\n// minefield: fetch four bytes, switch on seven bits, do arithmetic.\n//\n// No F or D. No floats means no rounding-mode ambiguity and nothing that can\n// differ between nodes. The M extension's divide-by-zero and overflow cases are\n// defined by the spec to RETURN a value rather than trap, which is exactly what\n// a deterministic chain wants.\n//\n// It implements [vmkit.Machine], so it shares the fuel meter, the snapshot\n// codec and the instance store with [p/moul/x/vm/bf](/p/moul/x/vm/bf/v0). That\n// sharing is the point: the second guest is what tells you whether the ABI was\n// shaped around the first one.\n//\n// Live demo: [r/moul/x/vm/riscvdemo](/r/moul/x/vm/riscvdemo/v0).\npackage riscv\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n)\n\n// VMName is the identifier this machine registers under in a vmkit.Instance.\nconst VMName = \"riscv32im\"\n\n// DefaultEntry is where a flat text image is conventionally loaded and where\n// execution starts. Low enough to leave a scratch page below it, aligned, and\n// nothing about the machine requires it: NewMachine takes the entry point.\nconst DefaultEntry uint32 = 0x1000\n\nconst (\n\tsnapMagic uint32 = 0x52563332 // \"RV32\"\n\n\t// snapVersion 2 carries the text segment's extent, which version 1 did\n\t// not need because the interpreter decoded from memory on every fetch.\n\t// Predecoding moved that work to load time, so a restored hart has to be\n\t// told which part of its memory is code.\n\tsnapVersion byte = 2\n)\n\n// ErrNoProgram is returned when a Machine is stepped with no image loaded.\nvar ErrNoProgram = errors.New(\"riscv: machine has no program\")\n\n// Machine is an RV32IM hart, mid-execution.\ntype Machine struct {\n\treg [32]uint32\n\tpc  uint32\n\tmem *Memory\n\n\t// code is the text segment with its fields already pulled apart. See\n\t// predecode.gno for why the dispatch loop reads arrays and not memory.\n\tcode *code\n\n\tstatus vmkit.Status\n\ttrap   string\n\n\t// out is what the guest wrote through the write syscall, mirrored to the\n\t// host as it goes. Kept here too so a snapshot round-trips it.\n\toutLen int\n}\n\n// NewMachine returns a hart with the image loaded at entry, pc at entry, and\n// the stack pointer at the top of memory.\nfunc NewMachine(image []byte, entry uint32) (*Machine, error) {\n\tif entry%4 != 0 {\n\t\treturn nil, errors.New(\"riscv: entry point is not 4-byte aligned\")\n\t}\n\tif len(image)%4 != 0 {\n\t\treturn nil, errors.New(\"riscv: image length is not a whole number of instructions\")\n\t}\n\tm := \u0026Machine{mem: NewMemory(), pc: entry, status: vmkit.Running}\n\tif !m.mem.WriteImage(entry, image) {\n\t\treturn nil, errors.New(\"riscv: image does not fit at the entry point\")\n\t}\n\tm.code = predecode(entry, image)\n\t// x2 is sp by convention. A guest that never touches the stack does not\n\t// care; one compiled by rustc does, immediately.\n\tm.reg[2] = MemSize\n\treturn m, nil\n}\n\n// LoadData places initialized data in memory, outside the text segment.\n//\n// The other half of a flat-image loader. A program with a .data section needs\n// its initial bytes in memory and needs to write them back afterwards, which\n// the text segment forbids: W xor X is what makes the predecode sound. So the\n// linker puts data at its own address and it arrives here separately, rather\n// than being concatenated onto the code and silently becoming read-only.\n//\n// The pages are marked dirty, so a snapshot carries the data the same way it\n// carries the program.\nfunc (m *Machine) LoadData(addr uint32, b []byte) error {\n\tif m.mem == nil {\n\t\treturn ErrNoProgram\n\t}\n\tif len(b) \u003e 0 \u0026\u0026 m.code != nil \u0026\u0026 m.code.words \u003e 0 {\n\t\tlo, hi := uint64(addr), uint64(addr)+uint64(len(b))\n\t\tif lo \u003c uint64(m.code.end) \u0026\u0026 hi \u003e uint64(m.code.base) {\n\t\t\treturn errors.New(\"riscv: data segment overlaps the text segment\")\n\t\t}\n\t}\n\tif !m.mem.WriteImage(addr, b) {\n\t\treturn errors.New(\"riscv: data does not fit at that address\")\n\t}\n\treturn nil\n}\n\n// Registers returns a copy of the register file, for tests and rendering.\nfunc (m *Machine) Registers() [32]uint32 { return m.reg }\n\n// PC returns the program counter.\nfunc (m *Machine) PC() uint32 { return m.pc }\n\n// Memory returns the address space.\nfunc (m *Machine) Memory() *Memory { return m.mem }\n\n// Status returns the machine's status.\nfunc (m *Machine) Status() vmkit.Status { return m.status }\n\n// Trap returns why the machine trapped, making Machine a [vmkit.Trapper].\nfunc (m *Machine) Trap() string { return m.trap }\n\n// Step runs until the program halts, traps, or spends `fuel` instructions.\n//\n// Written the way the bf ladder concluded, and for the same measured reasons:\n// the hot state is in locals and written back once, and the fuel counter is two\n// locals rather than a vmkit.Meter, because calling a method per instruction\n// cost 86% there and would cost more here, where an instruction is cheaper.\n//\n// Two things in this loop look like premature optimization and are not, both\n// measured in switchcost_test.gno on this VM:\n//\n//   - The case order is the internal opcode order from predecode.gno, which is\n//     by dynamic frequency, because the GnoVM scans switch cases in source\n//     order at 278 gas each. Reordering the arms below changes what the\n//     interpreter costs.\n//   - Everything the loop touches is a local. Reading cop[i] through m.code.op\n//     instead would pay for two field lookups on every instruction.\nfunc (m *Machine) Step(h vmkit.Host, fuel int64) (int64, vmkit.Status) {\n\tif m.mem == nil || m.code == nil {\n\t\tm.status, m.trap = vmkit.Trapped, \"no program\"\n\t\treturn 0, m.status\n\t}\n\tif m.status != vmkit.Running {\n\t\treturn 0, m.status\n\t}\n\n\tpc := m.pc\n\t// A misaligned pc would index the word containing it rather than trap,\n\t// because the index is a shift. Only a restored snapshot can get here with\n\t// one, since JALR is the only instruction that can produce it and it\n\t// checks its own target.\n\tif pc%4 != 0 {\n\t\tm.status, m.trap = vmkit.Trapped, \"misaligned program counter\"\n\t\treturn 0, m.status\n\t}\n\n\treg := \u0026m.reg\n\tmem := m.mem\n\n\tc := m.code\n\tcop, crd, crs1, crs2, cimm := c.op, c.rd, c.rs1, c.rs2, c.imm\n\tcbase, cwords, cend := c.base, c.words, c.end\n\tdefer func() { m.pc = pc }()\n\n\tbudget := fuel\n\tif budget \u003c 0 {\n\t\tbudget = vmkit.Unmetered\n\t}\n\tmetered := budget != vmkit.Unmetered\n\tvar used int64\n\n\tfor {\n\t\tif metered \u0026\u0026 used \u003e= budget {\n\t\t\treturn used, vmkit.Running\n\t\t}\n\t\tused++\n\n\t\t// One subtraction and one shift replace the fetch. A pc below the text\n\t\t// segment underflows to a huge index and is caught by the same\n\t\t// comparison, which is why there is no second bound here.\n\t\ti := (pc - cbase) \u003e\u003e 2\n\t\tif i \u003e= cwords {\n\t\t\tm.status, m.trap = vmkit.Trapped, \"instruction fetch out of range\"\n\t\t\treturn used, m.status\n\t\t}\n\t\tnext := pc + 4\n\n\t\tswitch cop[i] {\n\t\tcase iADDI:\n\t\t\treg[crd[i]] = reg[crs1[i]] + cimm[i]\n\t\tcase iLW:\n\t\t\tv, ok := mem.Load32(reg[crs1[i]] + cimm[i])\n\t\t\tif !ok {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"load out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\treg[crd[i]] = v\n\t\tcase iSW:\n\t\t\taddr := reg[crs1[i]] + cimm[i]\n\t\t\tif addr \u003c cend \u0026\u0026 addr+4 \u003e cbase {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"store into text segment\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\tif !mem.Store32(addr, reg[crs2[i]]) {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"store out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\tcase iADD:\n\t\t\treg[crd[i]] = reg[crs1[i]] + reg[crs2[i]]\n\t\tcase iBNE:\n\t\t\tif reg[crs1[i]] != reg[crs2[i]] {\n\t\t\t\tnext = pc + cimm[i]\n\t\t\t}\n\t\tcase iBEQ:\n\t\t\tif reg[crs1[i]] == reg[crs2[i]] {\n\t\t\t\tnext = pc + cimm[i]\n\t\t\t}\n\t\tcase iJAL:\n\t\t\treg[crd[i]] = next\n\t\t\tnext = pc + cimm[i]\n\t\tcase iJALR:\n\t\t\t// The target is computed before rd is written, because rd and rs1\n\t\t\t// are allowed to be the same register and usually are: `ret` is\n\t\t\t// jalr x0, 0(x1).\n\t\t\tt := (reg[crs1[i]] + cimm[i]) \u0026^ 1\n\t\t\tif t%4 != 0 {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"misaligned jump target\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\treg[crd[i]] = next\n\t\t\tnext = t\n\t\tcase iLUI:\n\t\t\treg[crd[i]] = cimm[i]\n\t\tcase iSLLI:\n\t\t\treg[crd[i]] = reg[crs1[i]] \u003c\u003c (cimm[i] \u0026 0x1F)\n\t\tcase iSRLI:\n\t\t\treg[crd[i]] = reg[crs1[i]] \u003e\u003e (cimm[i] \u0026 0x1F)\n\t\tcase iANDI:\n\t\t\treg[crd[i]] = reg[crs1[i]] \u0026 cimm[i]\n\t\tcase iSUB:\n\t\t\treg[crd[i]] = reg[crs1[i]] - reg[crs2[i]]\n\t\tcase iORI:\n\t\t\treg[crd[i]] = reg[crs1[i]] | cimm[i]\n\t\tcase iXORI:\n\t\t\treg[crd[i]] = reg[crs1[i]] ^ cimm[i]\n\t\tcase iBLT:\n\t\t\tif int32(reg[crs1[i]]) \u003c int32(reg[crs2[i]]) {\n\t\t\t\tnext = pc + cimm[i]\n\t\t\t}\n\t\tcase iBGE:\n\t\t\tif int32(reg[crs1[i]]) \u003e= int32(reg[crs2[i]]) {\n\t\t\t\tnext = pc + cimm[i]\n\t\t\t}\n\t\tcase iBLTU:\n\t\t\tif reg[crs1[i]] \u003c reg[crs2[i]] {\n\t\t\t\tnext = pc + cimm[i]\n\t\t\t}\n\t\tcase iBGEU:\n\t\t\tif reg[crs1[i]] \u003e= reg[crs2[i]] {\n\t\t\t\tnext = pc + cimm[i]\n\t\t\t}\n\t\tcase iSRAI:\n\t\t\treg[crd[i]] = uint32(int32(reg[crs1[i]]) \u003e\u003e (cimm[i] \u0026 0x1F))\n\t\tcase iSLL:\n\t\t\treg[crd[i]] = reg[crs1[i]] \u003c\u003c (reg[crs2[i]] \u0026 0x1F)\n\t\tcase iSRL:\n\t\t\treg[crd[i]] = reg[crs1[i]] \u003e\u003e (reg[crs2[i]] \u0026 0x1F)\n\t\tcase iSRA:\n\t\t\treg[crd[i]] = uint32(int32(reg[crs1[i]]) \u003e\u003e (reg[crs2[i]] \u0026 0x1F))\n\t\tcase iAND:\n\t\t\treg[crd[i]] = reg[crs1[i]] \u0026 reg[crs2[i]]\n\t\tcase iOR:\n\t\t\treg[crd[i]] = reg[crs1[i]] | reg[crs2[i]]\n\t\tcase iXOR:\n\t\t\treg[crd[i]] = reg[crs1[i]] ^ reg[crs2[i]]\n\t\tcase iLBU:\n\t\t\tv, ok := mem.Load8(reg[crs1[i]] + cimm[i])\n\t\t\tif !ok {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"load out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\treg[crd[i]] = uint32(v)\n\t\tcase iLB:\n\t\t\tv, ok := mem.Load8(reg[crs1[i]] + cimm[i])\n\t\t\tif !ok {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"load out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\treg[crd[i]] = uint32(int32(int8(v)))\n\t\tcase iLH:\n\t\t\tv, ok := mem.Load16(reg[crs1[i]] + cimm[i])\n\t\t\tif !ok {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"load out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\treg[crd[i]] = uint32(int32(int16(v)))\n\t\tcase iLHU:\n\t\t\tv, ok := mem.Load16(reg[crs1[i]] + cimm[i])\n\t\t\tif !ok {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"load out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\treg[crd[i]] = uint32(v)\n\t\tcase iSB:\n\t\t\taddr := reg[crs1[i]] + cimm[i]\n\t\t\tif addr \u003c cend \u0026\u0026 addr+4 \u003e cbase {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"store into text segment\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\tif !mem.Store8(addr, uint8(reg[crs2[i]])) {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"store out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\tcase iSH:\n\t\t\taddr := reg[crs1[i]] + cimm[i]\n\t\t\tif addr \u003c cend \u0026\u0026 addr+4 \u003e cbase {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"store into text segment\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\t\tif !mem.Store16(addr, uint16(reg[crs2[i]])) {\n\t\t\t\tm.status, m.trap = vmkit.Trapped, \"store out of range\"\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\tcase iAUIPC:\n\t\t\treg[crd[i]] = pc + cimm[i]\n\t\tcase iSLT:\n\t\t\treg[crd[i]] = b2u(int32(reg[crs1[i]]) \u003c int32(reg[crs2[i]]))\n\t\tcase iSLTU:\n\t\t\treg[crd[i]] = b2u(reg[crs1[i]] \u003c reg[crs2[i]])\n\t\tcase iSLTI:\n\t\t\treg[crd[i]] = b2u(int32(reg[crs1[i]]) \u003c int32(cimm[i]))\n\t\tcase iSLTIU:\n\t\t\treg[crd[i]] = b2u(reg[crs1[i]] \u003c cimm[i])\n\t\tcase iMUL:\n\t\t\treg[crd[i]] = reg[crs1[i]] * reg[crs2[i]]\n\t\tcase iMULH:\n\t\t\treg[crd[i]] = uint32((int64(int32(reg[crs1[i]])) * int64(int32(reg[crs2[i]]))) \u003e\u003e 32)\n\t\tcase iMULHSU:\n\t\t\treg[crd[i]] = uint32((int64(int32(reg[crs1[i]])) * int64(uint64(reg[crs2[i]]))) \u003e\u003e 32)\n\t\tcase iMULHU:\n\t\t\treg[crd[i]] = uint32((uint64(reg[crs1[i]]) * uint64(reg[crs2[i]])) \u003e\u003e 32)\n\t\tcase iDIV:\n\t\t\t// The M extension defines divide by zero and the one signed\n\t\t\t// overflow case to RETURN a value rather than trap. That is what\n\t\t\t// makes it safe on a chain: there is no host arithmetic exception\n\t\t\t// to differ between nodes.\n\t\t\treg[crd[i]] = divS(int32(reg[crs1[i]]), int32(reg[crs2[i]]))\n\t\tcase iDIVU:\n\t\t\tif reg[crs2[i]] == 0 {\n\t\t\t\treg[crd[i]] = ^uint32(0)\n\t\t\t} else {\n\t\t\t\treg[crd[i]] = reg[crs1[i]] / reg[crs2[i]]\n\t\t\t}\n\t\tcase iREM:\n\t\t\treg[crd[i]] = remS(int32(reg[crs1[i]]), int32(reg[crs2[i]]))\n\t\tcase iREMU:\n\t\t\tif reg[crs2[i]] == 0 {\n\t\t\t\treg[crd[i]] = reg[crs1[i]]\n\t\t\t} else {\n\t\t\t\treg[crd[i]] = reg[crs1[i]] % reg[crs2[i]]\n\t\t\t}\n\t\tcase iECALL:\n\t\t\tst, halt := m.ecall(h)\n\t\t\tif halt {\n\t\t\t\t// pc advances past the ecall before returning, so a halted\n\t\t\t\t// hart points at what it would run next rather than at the\n\t\t\t\t// syscall it already made. The deferred write-back is the only\n\t\t\t\t// thing that sets m.pc, so assigning the local is how this is\n\t\t\t\t// said.\n\t\t\t\tm.status = st\n\t\t\t\tpc = next\n\t\t\t\treturn used, m.status\n\t\t\t}\n\t\tcase iEBREAK:\n\t\t\tm.status, m.trap = vmkit.Trapped, \"ebreak\"\n\t\t\tpc = next\n\t\t\treturn used, m.status\n\t\tcase iFENCE:\n\t\t\t// FENCE orders memory for a hart that has neighbours. There is\n\t\t\t// exactly one here, so it is architecturally a no-op rather than\n\t\t\t// an unimplemented instruction.\n\t\tdefault:\n\t\t\tm.status, m.trap = vmkit.Trapped, \"illegal instruction\"\n\t\t\treturn used, m.status\n\t\t}\n\n\t\t// x0 is hardwired to zero. Writing it is legal and discarded, and\n\t\t// clearing after the fact is cheaper than branching on rd in every\n\t\t// arm above.\n\t\treg[0] = 0\n\t\tpc = next\n\t}\n}\n\n// b2u is the spec's \"set if\" result: 1 or 0, never a Go bool.\nfunc b2u(b bool) uint32 {\n\tif b {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n// divS is DIV with the two cases the spec pins down: division by zero yields\n// all ones, and the most negative value divided by -1 overflows to itself.\nfunc divS(a, b int32) uint32 {\n\tif b == 0 {\n\t\treturn ^uint32(0)\n\t}\n\tif a == -2147483648 \u0026\u0026 b == -1 {\n\t\treturn uint32(a)\n\t}\n\treturn uint32(a / b)\n}\n\n// remS is REM, with the matching pair: remainder by zero is the dividend, and\n// the overflow case is zero.\nfunc remS(a, b int32) uint32 {\n\tif b == 0 {\n\t\treturn uint32(a)\n\t}\n\tif a == -2147483648 \u0026\u0026 b == -1 {\n\t\treturn 0\n\t}\n\treturn uint32(a % b)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/vm/riscv/v0\"\ngno = \"0.9\"\n"},{"name":"guests.gno","body":"package riscv\n\n// Compiled guests: programs a real compiler produced, shipped as the bytes it\n// emitted.\n//\n// A hand-written test program proves the emulator agrees with the person who\n// wrote it. A compiled one proves it agrees with LLVM, which is the only claim\n// that matters for a machine whose whole premise is that every toolchain\n// already targets it.\n//\n// The source, the linker script and the exact build command are in\n// tools/riscv-guests/. `make words` there prints the image in the form below,\n// so this is reproducible rather than magic.\n\n// guestFNV is tools/riscv-guests/fnv: it reads the call input, hashes it with\n// FNV-1a, and writes eight hex digits back. 49 instructions, built with clang\n// 19.1.7, `-march=rv32im -mabi=ilp32 -Os`.\n//\n// Worth reading as output rather than as a program. LLVM opens with a real\n// function prologue spilling ra and s0 to a stack the host set up, materializes\n// the 2166136261 offset basis as a lui/addi pair, and addresses its globals at\n// 0x40000, far above a text segment the host refuses stores into.\nvar guestFNV = []uint32{\n\t0xFF010113, 0x00112623, 0x00812423, 0x01010413,\n\t0x000405B7, 0x00058593, 0x03F00893, 0x10000613,\n\t0x00000513, 0x00000073, 0x811CA6B7, 0x02A05663,\n\t0x00A58633, 0xDC568513, 0x010006B7, 0x19368693,\n\t0x0005C703, 0x00E54533, 0x00158593, 0x02D50533,\n\t0xFEC598E3, 0x0080006F, 0xDC568513, 0x01C00593,\n\t0x00040637, 0x10060613, 0x00A00693, 0xFFC00713,\n\t0x00B557B3, 0x00F7F793, 0x00D7E663, 0x05778793,\n\t0x0080006F, 0x03078793, 0x00F60023, 0xFFC58593,\n\t0x00160613, 0xFCE59EE3, 0x000405B7, 0x10058593,\n\t0x04000893, 0x00800613, 0x00100513, 0x00000073,\n\t0x05D00893, 0x00000593, 0x00000613, 0x00000513,\n\t0x00000073,\n}\n\n// GuestFNV returns the flat text image of the compiled FNV-1a guest, ready for\n// [NewMachine] at [DefaultEntry]. A fresh slice per call, so a caller cannot\n// mutate the copy everyone else gets.\nfunc GuestFNV() []byte { return Image(guestFNV) }\n\n// guestLedger is tools/riscv-guests/ledger: a token in no_std Rust. It applies\n// a script of mint, send and burn lines from the call input and writes the\n// resulting balances back. 1,959 instructions, built with rustc 1.98.1 for\n// riscv32im-unknown-none-elf.\n//\n// It links Rust's real core and compiler_builtins, which is what makes it more\n// than a bigger FNV: a bounds check reaches core::panicking, and the balances\n// are 64-bit, so a divide reaches __udivdi3 because RV32 has no 64-bit divide\n// instruction. The emulator is running the standard library's own software\n// arithmetic, not just compiler output.\nvar guestLedger = []uint32{\n\t0xFA010113, 0x04112E23, 0x04812C23, 0x04912A23, 0x05212823, 0x05312623, 0x05412423, 0x05512223,\n\t0x05612023, 0x03712E23, 0x03812C23, 0x03912A23, 0x03A12823, 0x03B12623, 0x00000513, 0x00000713,\n\t0x00000413, 0x00000B93, 0x000409B7, 0x00098993, 0x03F00893, 0x40000613, 0x00A00913, 0x40100B13,\n\t0x00400C13, 0x0F600493, 0x00040DB7, 0x400D8D93, 0x00098593, 0x00000073, 0x00050A13, 0x00A02533,\n\t0x00012C23, 0x40A00533, 0x01457CB3, 0x4B977A63, 0x40000593, 0x00070513, 0x00E5E463, 0x40000513,\n\t0x00170613, 0x000A0593, 0x01464463, 0x00060593, 0x00070A93, 0x71550263, 0x01598633, 0x00064D03,\n\t0x012D0863, 0x001A8A93, 0xFF5596E3, 0x00058A93, 0x43577A63, 0x6D6AF463, 0x00140413, 0x00143513,\n\t0x00AB8BB3, 0x40EA8633, 0x00E985B3, 0x01C10513, 0x00000097, 0x760080E7, 0x02012503, 0x40050463,\n\t0x00F00B13, 0x53851E63, 0x01C12503, 0x02412583, 0x02812603, 0x00054683, 0x06200713, 0x24E68A63,\n\t0x07300713, 0x12E68063, 0x06D00713, 0x50E69A63, 0x00154683, 0x06900713, 0x50E69463, 0x00254683,\n\t0x06E00713, 0x4EE69E63, 0x00354503, 0x07400693, 0x4ED51863, 0x01C10513, 0x00000097, 0x6F8080E7,\n\t0x01C12503, 0x00A12623, 0x02012C03, 0x02412583, 0x02812603, 0x01C10513, 0x00000097, 0x6D8080E7,\n\t0x02012503, 0xFF650593, 0x00A00B13, 0xFF700613, 0x5AC5E263, 0x01712A23, 0x00812823, 0x00000413,\n\t0x01C12583, 0x00000B93, 0x0005C603, 0xFC660693, 0x0FF6F693, 0x4696EC63, 0x00158593, 0x032436B3,\n\t0x001B9713, 0x003B9B93, 0x00EB8733, 0x00141793, 0x00341413, 0xFD060613, 0x00F407B3, 0x0FF67413,\n\t0x00E686B3, 0x00878433, 0x00F43BB3, 0xFFF50513, 0x01768BB3, 0xFA051AE3, 0x00C12503, 0x000C0593,\n\t0x00001097, 0x80C080E7, 0x00058693, 0x00100593, 0x52B51863, 0x00F00513, 0x5CD56663, 0x00369693,\n\t0x00DD86B3, 0x3806A503, 0x3846A583, 0x00850433, 0x017585B3, 0x00A43533, 0x00A58533, 0x3886A023,\n\t0x2B00006F, 0x00154683, 0x06500713, 0x3EE69A63, 0x00254683, 0x06E00713, 0x3EE69463, 0x00354503,\n\t0x06400693, 0x3CD51E63, 0x01C10513, 0x00000097, 0x5E4080E7, 0x01C12503, 0x00A12823, 0x02012503,\n\t0x00A12623, 0x02412583, 0x02812603, 0x01C10513, 0x00000097, 0x5C0080E7, 0x01C12C03, 0x02012503,\n\t0x00A12423, 0x02412583, 0x02812603, 0x01C10513, 0x00000097, 0x5A0080E7, 0x02012503, 0xFF650593,\n\t0x00A00B13, 0xFF700613, 0x46C5E663, 0x01812223, 0x01712A23, 0x00000B93, 0x01C12583, 0x00000C13,\n\t0x0005C603, 0xFC660693, 0x0FF6F693, 0x3296E863, 0x00158593, 0x032BB6B3, 0x001C1713, 0x003C1C13,\n\t0x00EC0733, 0x001B9793, 0x003B9B93, 0xFD060613, 0x00FB87B3, 0x0FF67B93, 0x00E686B3, 0x01778BB3,\n\t0x00FBBC33, 0xFFF50513, 0x01868C33, 0xFA051AE3, 0x01012503, 0x00C12583, 0x00000097, 0x5E0080E7,\n\t0x00058693, 0x00100593, 0x42B51C63, 0x00812823, 0x00F00513, 0x4AD56463, 0x00369693, 0x00DD8433,\n\t0x38442503, 0x11850C63, 0x01852533, 0x1180006F, 0x00154683, 0x07500713, 0x2CE69463, 0x00254683,\n\t0x07200713, 0x2AE69E63, 0x00354503, 0x06E00693, 0x2AD51863, 0x01C10513, 0x00000097, 0x4B8080E7,\n\t0x01C12503, 0x00A12623, 0x02012C03, 0x02412583, 0x02812603, 0x01C10513, 0x00000097, 0x498080E7,\n\t0x02012503, 0xFF650593, 0xFF700613, 0x36C5E263, 0x01712A23, 0x00812823, 0x00000413, 0x01C12583,\n\t0x00000B93, 0x0005C603, 0xFC660693, 0x0FF6F693, 0x2296EC63, 0x00158593, 0x032436B3, 0x001B9713,\n\t0x003B9B93, 0x00EB8733, 0x00141793, 0x00341413, 0xFD060613, 0x00F407B3, 0x0FF67413, 0x00E686B3,\n\t0x00878433, 0x00F43BB3, 0xFFF50513, 0x01768BB3, 0xFA051AE3, 0x00C12503, 0x000C0593, 0x00000097,\n\t0x4DC080E7, 0x00058693, 0x00100593, 0x34B51263, 0x00F00513, 0x38D56E63, 0x00369513, 0x00AD8533,\n\t0x38452603, 0x38052583, 0x40100B13, 0x00400C13, 0x0B760263, 0x017626B3, 0x0A00006F, 0x38042503,\n\t0x01753533, 0x2C051A63, 0x00412503, 0x00812583, 0x00000097, 0x57C080E7, 0x00058693, 0x00100593,\n\t0x2AB51063, 0x38042503, 0x38442583, 0x01753633, 0x418585B3, 0x41750533, 0x40C585B3, 0x38A42023,\n\t0x38B42223, 0x00F00513, 0x34D56063, 0x00369693, 0x00DD86B3, 0x3806A503, 0x3846A583, 0x01750BB3,\n\t0x018585B3, 0x00ABB533, 0x00A58533, 0x3976A023, 0x38A6A223, 0x01012403, 0x01412B83, 0x40100B13,\n\t0x00400C13, 0x032D1E63, 0x001A8713, 0xB99AE0E3, 0x0300006F, 0x0085B6B3, 0x24069063, 0x0085B6B3,\n\t0x41760633, 0x408585B3, 0x40D60633, 0x38B52023, 0x38C52223, 0x01012403, 0x01412B83, 0xFD2D06E3,\n\t0x410DA403, 0x0A040A63, 0x00000513, 0x00000493, 0x01000913, 0x01900993, 0x20000A13, 0x02000A93,\n\t0x00A00B13, 0x27248463, 0x009D85B3, 0x4005C583, 0x1F35FC63, 0x00349613, 0x02058A63, 0x00449693,\n\t0x00C686B3, 0x00DD86B3, 0x20068693, 0x01457A63, 0x0006C703, 0x00AD87B3, 0x00E78023, 0x00150513,\n\t0xFFF58593, 0x00168693, 0xFE0592E3, 0x01457863, 0x00AD85B3, 0x01558023, 0x00150513, 0x00CD8633,\n\t0x38062583, 0x38462603, 0x00A12C23, 0x01810513, 0x00000097, 0x598080E7, 0x01812503, 0x01457863,\n\t0x00AD85B3, 0x01658023, 0x00150513, 0x00148493, 0x00A12C23, 0xF68498E3, 0x01810513, 0x00000097,\n\t0x528080E7, 0x05D00893, 0x00000513, 0x00000593, 0x00000613, 0x00000073, 0x0000006F, 0x000034B7,\n\t0xBAE48493, 0x0140006F, 0x00A00B13, 0x000034B7, 0xBAE48493, 0x01012403, 0x01412B83, 0x00C0006F,\n\t0x000034B7, 0xD1C48493, 0x00000513, 0x000035B7, 0xDAC58593, 0x00500613, 0x20000693, 0x00D57A63,\n\t0x0005C703, 0x00AD87B3, 0x00E78023, 0x00150513, 0xFFF60613, 0x00158593, 0xFE0612E3, 0x00A12C23,\n\t0x01810513, 0x00040593, 0x000B8613, 0x00000097, 0x4DC080E7, 0x00000513, 0x00000713, 0x01812583,\n\t0x20000613, 0x000036B7, 0xDB168693, 0x00C5FC63, 0x00E68733, 0x00074703, 0x00BD87B3, 0x00E78023,\n\t0x00158593, 0x00100713, 0x00157793, 0x00100513, 0xFC078EE3, 0x00B12C23, 0x01810513, 0x00048593,\n\t0x000B0613, 0x00000097, 0x404080E7, 0x01812503, 0x20000593, 0x00B57A63, 0x00AD8DB3, 0x00A00593,\n\t0x00BD8023, 0x00150513, 0x00A12C23, 0x01810513, 0x00000097, 0x414080E7, 0x05D00893, 0x00100513,\n\t0x00000593, 0x00000613, 0x00000073, 0x0000006F, 0x00A00B13, 0x000034B7, 0xBAE48493, 0xF0DFF06F,\n\t0x01700B13, 0x01012403, 0x01412B83, 0x000034B7, 0xBB848493, 0xEF5FF06F, 0x01400B13, 0x000034B7,\n\t0xCE848493, 0xED1FF06F, 0x000036B7, 0xDC468693, 0x01800613, 0x00000513, 0x00001097, 0xB50080E7,\n\t0x00E00B13, 0x000034B7, 0xCB848493, 0xEADFF06F, 0x000034B7, 0xCFC48493, 0xE9DFF06F, 0x000036B7,\n\t0xD9C68693, 0x40000613, 0x00070513, 0x000A8593, 0x00001097, 0xB18080E7, 0x00003637, 0xD8C60613,\n\t0x40000593, 0x00001097, 0x880080E7, 0x00003637, 0xDB460613, 0x01000513, 0x01000593, 0x00001097,\n\t0x868080E7, 0x00003637, 0xCA860613, 0x0240006F, 0x00003637, 0xD0C60613, 0x0180006F, 0x00003637,\n\t0xCC860613, 0x00C0006F, 0x00003637, 0xCD860613, 0x01000593, 0x00068513, 0x00001097, 0x82C080E7,\n\t0x000035B7, 0xBA858593, 0x04000893, 0x00100513, 0x00600613, 0x00000073, 0x05D00893, 0x00200513,\n\t0x00000593, 0x00000613, 0x00000073, 0x0000006F, 0x00000793, 0x04060063, 0x01700693, 0x00800737,\n\t0x01170713, 0x00F58833, 0x00084803, 0xFF780813, 0x0306E263, 0x01075833, 0x00187813, 0x00080C63,\n\t0x00178793, 0xFEF610E3, 0x00060793, 0x00060713, 0x0440006F, 0x02C7FE63, 0x01700693, 0x00800837,\n\t0x01180813, 0x00078713, 0x00E588B3, 0x0008C883, 0xFF788893, 0x0116E863, 0x011858B3, 0x0018F893,\n\t0x00089A63, 0x00170713, 0xFEE610E3, 0xFC1FF06F, 0x00078713, 0x02F76663, 0x02E66463, 0x40F706B3,\n\t0x00F587B3, 0x40E60633, 0x00E585B3, 0x00F52023, 0x00D52223, 0x00B52423, 0x00C52623, 0x00008067,\n\t0x000036B7, 0xD2C68693, 0x00078513, 0x00070593, 0x00001097, 0x9B8080E7, 0xFE010113, 0x00112E23,\n\t0x00812C23, 0x00912A23, 0x01212823, 0x01312623, 0x01412423, 0x01512223, 0x01612023, 0x000409B7,\n\t0x40098993, 0x4109A403, 0x04040A63, 0x00058493, 0x00050913, 0x00000A13, 0xE8000A93, 0x01900B13,\n\t0x080A8A63, 0x01498533, 0x40054503, 0x02A49263, 0x07657463, 0x01598533, 0x38050513, 0x00090593,\n\t0x00048613, 0x00001097, 0xCBC080E7, 0x00050C63, 0x001A0A13, 0x018A8A93, 0xFD4414E3, 0x00000513,\n\t0x00C0006F, 0x00100513, 0x000A0413, 0x00040593, 0x01C12083, 0x01812403, 0x01412483, 0x01012903,\n\t0x00C12983, 0x00812A03, 0x00412A83, 0x00012B03, 0x02010113, 0x00008067, 0x000036B7, 0xD4C68693,\n\t0x01800613, 0x00000513, 0x00048593, 0x00001097, 0x8DC080E7, 0x00003637, 0xD3C60613, 0x01000513,\n\t0x01000593, 0x00000097, 0x640080E7, 0xFF010113, 0x00112623, 0x00812423, 0x00912223, 0x00058413,\n\t0x00050493, 0x00000097, 0xEF4080E7, 0x00050693, 0x00100513, 0x00A69663, 0x00058713, 0x07C0006F,\n\t0x000405B7, 0x40058593, 0x4105A703, 0x01000613, 0x00000513, 0x06C70263, 0xFE740613, 0xFE700693,\n\t0x04C6FC63, 0x00F00513, 0x06E56463, 0x00371513, 0x00471613, 0x00A60533, 0x00B50533, 0x20050513,\n\t0x00040613, 0x0004C683, 0x00148493, 0xFFF60613, 0x00D50023, 0x00150513, 0xFE0616E3, 0x00E58533,\n\t0x40850023, 0x4105A503, 0x00150513, 0x40A5A823, 0x00100513, 0x0040006F, 0x00070593, 0x00C12083,\n\t0x00812403, 0x00412483, 0x01010113, 0x00008067, 0x00003637, 0xD5C60613, 0x01000593, 0x00070513,\n\t0x00000097, 0x564080E7, 0x02060C63, 0x00052683, 0x20000713, 0x000407B7, 0x40078793, 0x00E6FC63,\n\t0x0005C803, 0x00D788B3, 0x00168693, 0x01088023, 0x00D52023, 0xFFF60613, 0x00158593, 0xFE0610E3,\n\t0x00008067, 0x00052703, 0x20100513, 0x02A77063, 0x000405B7, 0x40058593, 0x04000893, 0x00100513,\n\t0x00070613, 0x00000073, 0x00008067, 0x000036B7, 0xD6C68693, 0x20000613, 0x00000513, 0x00070593,\n\t0x00000097, 0x768080E7, 0xFC010113, 0x02112E23, 0x02812C23, 0x02912A23, 0x03212823, 0x03312623,\n\t0x03412423, 0x03512223, 0x03612023, 0x00058493, 0x00C5E5B3, 0x00050413, 0x02058663, 0x00060913,\n\t0x00C10513, 0x01400613, 0x00000593, 0x00001097, 0xF70080E7, 0x02090E63, 0x01F95513, 0x02050E63,\n\t0x0E00006F, 0x00042503, 0x1FF00593, 0x0CA5EA63, 0x000405B7, 0x40058593, 0x03000613, 0x00A585B3,\n\t0x00150513, 0x00C58023, 0x00A42023, 0x0B40006F, 0x0014B513, 0x0A051663, 0x00000993, 0x01300A13,\n\t0x01F10A93, 0x01300B13, 0x0D6A6063, 0x00A00613, 0x00048513, 0x00090593, 0x00000693, 0x00001097,\n\t0xA54080E7, 0x00193613, 0x00151693, 0x00351713, 0x00D706B3, 0x00A4B713, 0x00198993, 0x00E67633,\n\t0x40D484B3, 0x0304E693, 0x00DA8023, 0xFFFA8A93, 0xFFFB0B13, 0x00050493, 0x00058913, 0xFA0606E3,\n\t0x00042503, 0x00C10593, 0x413585B3, 0x01458593, 0x20000613, 0x000406B7, 0x40068693, 0x00C57C63,\n\t0x0005C703, 0x00A687B3, 0x00150513, 0x00E78023, 0x00A42023, 0xFFF98993, 0x00158593, 0xFE0990E3,\n\t0x03C12083, 0x03812403, 0x03412483, 0x03012903, 0x02C12983, 0x02812A03, 0x02412A83, 0x02012B03,\n\t0x04010113, 0x00008067, 0x00003637, 0xD7C60613, 0xFFF00513, 0x01400593, 0x00000097, 0x36C080E7,\n\t0xFC010113, 0x02112E23, 0x02812C23, 0x02912A23, 0x03212823, 0x03312623, 0x03412423, 0x03512223,\n\t0x03612023, 0x01712E23, 0x01812C23, 0x01912A23, 0x01A12823, 0x01B12623, 0x04010413, 0x00078493,\n\t0x00070913, 0x00068A13, 0x00060A93, 0x00050993, 0x00852B83, 0x08059263, 0x02D00B13, 0x00100C93,\n\t0x008B9513, 0x009C8CB3, 0x08055663, 0x01000513, 0x10AA7263, 0x00000513, 0x020A0263, 0x014A85B3,\n\t0x000A8613, 0x00060683, 0x00160613, 0xFC06A693, 0x0016C693, 0x00D50533, 0xFEB616E3, 0x01950CB3,\n\t0x00C9DD83, 0x05BCFE63, 0x007B9513, 0x0E054463, 0x419D8633, 0x001B9513, 0x01E55513, 0x00100593,\n\t0x00BB9B93, 0xFD242423, 0x14A5CA63, 0x18051A63, 0x00000D13, 0x1900006F, 0x00AB9513, 0x01F55C93,\n\t0xFFFC8513, 0x02B56B13, 0x008B9513, 0x009C8CB3, 0xF6054EE3, 0x00000A93, 0x00C9DD83, 0xFBBCE6E3,\n\t0x0009AB83, 0x0049A983, 0x000B8513, 0x00098593, 0x000B0613, 0x000A8693, 0x000A0713, 0x00000097,\n\t0x5A8080E7, 0x18051063, 0x00C9A303, 0x000B8513, 0x00090593, 0x00048613, 0x03C12083, 0x03812403,\n\t0x03412483, 0x03012903, 0x02C12983, 0x02812A03, 0x02412A83, 0x02012B03, 0x01C12B83, 0x01812C03,\n\t0x01412C83, 0x01012D03, 0x00C12D83, 0x04010113, 0x00030067, 0x000A8513, 0x000A0593, 0x00000097,\n\t0x26C080E7, 0x01950CB3, 0x00C9DD83, 0xF7BCFAE3, 0xF19FF06F, 0x0009AB83, 0x0049AC03, 0x0089AD03,\n\t0x00C9A503, 0xFCA42223, 0x9FE00537, 0x200005B7, 0x00AD7533, 0x03058593, 0x00B56533, 0x00A9A423,\n\t0x000B8513, 0x000C0593, 0x000B0613, 0x000A8693, 0x000A0713, 0x00000097, 0x4F0080E7, 0x00100A13,\n\t0x0C051463, 0x00000A93, 0x419D8533, 0x00010B37, 0xFFFB0B13, 0x01657CB3, 0x016AF533, 0x03957C63,\n\t0x010C2603, 0x001A8A93, 0x03000593, 0x000B8513, 0x000600E7, 0xFE0502E3, 0x0900006F, 0x00200593,\n\t0x00060D13, 0x04B51063, 0x01061513, 0x01155D13, 0x0340006F, 0x00CC2683, 0x000B8513, 0x00090593,\n\t0x00048613, 0x000680E7, 0x06051063, 0x00000A13, 0x01A9A423, 0xFC442503, 0x00A9A623, 0x04C0006F,\n\t0x00060D13, 0xFCC42223, 0x00000D93, 0x00BBDB93, 0x0009AC03, 0x0049A983, 0x00010CB7, 0xFFFC8C93,\n\t0x019D7933, 0x019DF533, 0x07257063, 0x0109A603, 0x001D8D93, 0x000C0513, 0x000B8593, 0x000600E7,\n\t0xFE0502E3, 0x00100A13, 0x000A0513, 0x03C12083, 0x03812403, 0x03412483, 0x03012903, 0x02C12983,\n\t0x02812A03, 0x02412A83, 0x02012B03, 0x01C12B83, 0x01812C03, 0x01412C83, 0x01012D03, 0x00C12D83,\n\t0x04010113, 0x00008067, 0x000C0513, 0x00098593, 0x000B0613, 0x000A8693, 0x000A0713, 0x00000097,\n\t0x3C8080E7, 0x00100A13, 0xFA0510E3, 0x00C9A683, 0x000C0513, 0xFC842583, 0x00048613, 0x000680E7,\n\t0xF80514E3, 0x00000493, 0xFC442503, 0x41A50533, 0x00010937, 0xFFF90913, 0x01257AB3, 0x0124F533,\n\t0x01553A33, 0xF75572E3, 0x0109A603, 0x00148493, 0x000C0513, 0x000B8593, 0x000600E7, 0xFE0500E3,\n\t0xF49FF06F, 0xFE010113, 0x00112E23, 0x00812C23, 0x02010413, 0xFEA42023, 0xFEB42223, 0xFE440513,\n\t0x000025B7, 0x45058593, 0xFE040693, 0xFEA42423, 0xFEB42623, 0xFED42823, 0xFEB42A23, 0x00003537,\n\t0xC0050513, 0xFE840593, 0x00000097, 0x008080E7, 0xFE010113, 0x00112E23, 0x00812C23, 0x02010413,\n\t0xFEA42223, 0xFEB42423, 0xFE440513, 0x00100593, 0xFEA42623, 0xFEC42823, 0xFEB41A23, 0xFEC40513,\n\t0xFFFFF097, 0x760080E7, 0x00050613, 0x00350513, 0xFFC57513, 0x40C50833, 0x0305F663, 0x00000513,\n\t0x02058063, 0x00B605B3, 0x00060683, 0x00160613, 0xFC06A693, 0x0016C693, 0x00D50533, 0xFEB616E3,\n\t0x00008067, 0x41058733, 0x00275693, 0xFC0688E3, 0x01060833, 0x00377593, 0x00C51663, 0x00000513,\n\t0x0200006F, 0x00000513, 0x00060783, 0x00160613, 0xFC07A793, 0x0017C793, 0x00F50533, 0xFF0616E3,\n\t0x00000793, 0x02058863, 0x80000637, 0xFFC60613, 0x00C77633, 0x00C80633, 0x00060703, 0xFFF58593,\n\t0xFC072713, 0x00174713, 0x00E787B3, 0x00160613, 0xFE0594E3, 0x010105B7, 0x00FF0737, 0x10158613,\n\t0x0FF70593, 0x00A78533, 0x0340006F, 0x01070833, 0x40F686B3, 0x0037F293, 0x00B8F333, 0x0088D893,\n\t0x00B8F8B3, 0x006888B3, 0x01089313, 0x011308B3, 0x0108D893, 0x00A88533, 0x0A029863, 0xF40682E3,\n\t0x00080713, 0x0C000813, 0x00068793, 0x0106E463, 0x0C000793, 0x00279813, 0x00000893, 0x3F087293,\n\t0xFA0286E3, 0x005702B3, 0x00070313, 0x00032383, 0x00432E03, 0x00832E83, 0x00C32F03, 0xFFF3CF93,\n\t0x0063D393, 0x007FDF93, 0x007FE3B3, 0xFFFE4F93, 0x006E5E13, 0x007FDF93, 0x01CFEE33, 0xFFFECF93,\n\t0x006EDE93, 0x007FDF93, 0x01DFEEB3, 0xFFFF4F93, 0x006F5F13, 0x007FDF93, 0x01EFEF33, 0x00C3F3B3,\n\t0x011388B3, 0x00CE73B3, 0x00CEFE33, 0x00CF7EB3, 0x007E03B3, 0x011388B3, 0x01030313, 0x011E88B3,\n\t0xF85316E3, 0xF29FF06F, 0x00000693, 0x0FC7F793, 0x00279793, 0x00F707B3, 0x00229713, 0x0007A803,\n\t0x00478793, 0xFFF84893, 0x00685813, 0x0078D893, 0x0108E833, 0x00C87833, 0xFFC70713, 0x00D806B3,\n\t0xFC071EE3, 0x00B6F633, 0x0086D693, 0x00B6F5B3, 0x00C585B3, 0x01059613, 0x00B605B3, 0x0105D593,\n\t0x00A58533, 0x00008067, 0xFE010113, 0x00112E23, 0x00812C23, 0x02010413, 0x04A67263, 0xFEA42023,\n\t0xFEC42223, 0xFE040513, 0x000025B7, 0x45058593, 0xFE440613, 0xFEA42423, 0xFEB42623, 0xFEC42823,\n\t0xFEB42A23, 0x00003537, 0xC6E50513, 0xFE840593, 0x00068613, 0x00000097, 0xD7C080E7, 0x04B66463,\n\t0x04A5F263, 0xFEA42023, 0xFEB42223, 0xFE040513, 0x000025B7, 0x45058593, 0xFE440613, 0xFEA42423,\n\t0xFEB42623, 0xFEC42823, 0xFEB42A23, 0x00003537, 0xBCF50513, 0xFE840593, 0x00068613, 0x00000097,\n\t0xD34080E7, 0xFEB42023, 0xFEC42223, 0xFE040513, 0x000025B7, 0x45058593, 0xFE440613, 0xFEA42423,\n\t0xFEB42623, 0xFEC42823, 0xFEB42A23, 0x00003537, 0xC3750513, 0xFE840593, 0x00068613, 0x00000097,\n\t0xCF4080E7, 0xFE010113, 0x00112E23, 0x00812C23, 0x00912A23, 0x01212823, 0x01312623, 0x01412423,\n\t0x02010413, 0x00070493, 0x00068913, 0x00058993, 0xFFF00593, 0x00050A13, 0x02B60063, 0x0109A683,\n\t0x000A0513, 0x00060593, 0x000680E7, 0x00050663, 0x00100513, 0x03C0006F, 0x02090A63, 0x00C9A303,\n\t0x000A0513, 0x00090593, 0x00048613, 0x01C12083, 0x01812403, 0x01412483, 0x01012903, 0x00C12983,\n\t0x00812A03, 0x02010113, 0x00030067, 0x00000513, 0x01C12083, 0x01812403, 0x01412483, 0x01012903,\n\t0x00C12983, 0x00812A03, 0x02010113, 0x00008067, 0xFC010113, 0x02112E23, 0x02812C23, 0x02912A23,\n\t0x03212823, 0x03312623, 0x03412423, 0x03512223, 0x03612023, 0x01712E23, 0x01812C23, 0x04010413,\n\t0x00058693, 0x00052583, 0x3E800613, 0x00003537, 0xDD450513, 0x0CC5E663, 0x00000713, 0xFD440793,\n\t0xFD740813, 0xFD640893, 0xFD540293, 0xD1B71637, 0x00002E37, 0x00001EB7, 0x06400313, 0x00989F37,\n\t0x75960393, 0x710E0E13, 0x47BE8E93, 0x67FF0F13, 0x00058613, 0x00060F93, 0x02763633, 0x00E784B3,\n\t0x00E28933, 0x00E889B3, 0x00E80A33, 0x00D65613, 0x03C60AB3, 0x415F8AB3, 0x010A9B13, 0x012B5B13,\n\t0x03DB0B33, 0x010B5B93, 0x011B5B13, 0x026B0B33, 0x7FEBFB93, 0x416A8AB3, 0x01750BB3, 0x011A9A93,\n\t0x010ADA93, 0x01550AB3, 0x000BCB03, 0x001BCB83, 0x000ACC03, 0x001ACA83, 0x01648023, 0x01790023,\n\t0x01898023, 0x015A0023, 0xFFC70713, 0xF9FF64E3, 0x00A70713, 0x00900793, 0x00C7EC63, 0x0680006F,\n\t0x00A00713, 0x00058613, 0x00900793, 0x04B7FC63, 0x01061793, 0x00001837, 0x06400893, 0xFCE40293,\n\t0x0127D793, 0x47B80813, 0x00E28333, 0x030787B3, 0x0117D793, 0x03178833, 0x41060633, 0x01161613,\n\t0x01065613, 0x00C50633, 0x00064803, 0x00164603, 0xFFE70713, 0x00E282B3, 0x01028023, 0xFEC30FA3,\n\t0x00078613, 0x00058463, 0x02060063, 0x00161613, 0x00C50533, 0x00154503, 0xFFF70713, 0xFCE40593,\n\t0x00E585B3, 0x00A58023, 0x00A00793, 0xFCE40513, 0x40E787B3, 0x00E50733, 0x00100593, 0x00100613,\n\t0x00068513, 0x00000693, 0xFFFFF097, 0x6D8080E7, 0x03C12083, 0x03812403, 0x03412483, 0x03012903,\n\t0x02C12983, 0x02812A03, 0x02412A83, 0x02012B03, 0x01C12B83, 0x01812C03, 0x04010113, 0x00008067,\n\t0x02060063, 0x00054683, 0x0005C703, 0x00E69E63, 0x00158593, 0xFFF60613, 0x00150513, 0xFE0614E3,\n\t0x00000513, 0x00008067, 0x40E68533, 0x00008067, 0xFE010113, 0x00112E23, 0x00812C23, 0x02010413,\n\t0x00068713, 0x00060693, 0x00058613, 0x00050593, 0xFE840513, 0x00000097, 0x020080E7, 0xFE842503,\n\t0xFEC42583, 0x01C12083, 0x01812403, 0x02010113, 0x00008067, 0x0A068863, 0x0A071663, 0x1C060C63,\n\t0x1ED67A63, 0x0106D893, 0x00C8B7B3, 0x0017C813, 0x00068793, 0x26C8F063, 0x00481813, 0x0087D293,\n\t0x00C2B8B3, 0x0018C893, 0x26C2F263, 0x00389293, 0x0047D893, 0x0102E833, 0x00C8B2B3, 0x0012C293,\n\t0x26C8F463, 0x00229293, 0x0027D893, 0x00586833, 0x00C8B2B3, 0x0012C293, 0x00C8E463, 0x00088793,\n\t0x00129293, 0x0017D793, 0x00C7B7B3, 0x0017C793, 0x00F2E7B3, 0x00F867B3, 0x24079863, 0x01F00813,\n\t0xFE080293, 0x010698B3, 0x2402DA63, 0x01071733, 0xFFF84793, 0x0016D313, 0x00F357B3, 0x00F767B3,\n\t0x2400006F, 0x00000813, 0x10060C63, 0x10E60663, 0x00E637B3, 0x10079663, 0x01065893, 0x00E8B7B3,\n\t0x0017C813, 0x00481813, 0x00060793, 0x14E8F863, 0x0087D893, 0x00E8B2B3, 0x0012C293, 0x00329293,\n\t0x0102E833, 0x14E8FA63, 0x0047D893, 0x00E8B2B3, 0x0012C293, 0x00229293, 0x00586833, 0x14E8FC63,\n\t0x0027D293, 0x00E2B8B3, 0x0018C893, 0x00189893, 0x011868B3, 0x00E2E463, 0x00028793, 0x00000813,\n\t0x0017D793, 0x0016D293, 0x00E7B7B3, 0x0017C793, 0x00F8E8B3, 0x01F8C793, 0x00F2D7B3, 0x011712B3,\n\t0x00F2E7B3, 0x00100293, 0x011292B3, 0x01169333, 0x0180006F, 0x00135893, 0x01F79313, 0x0017D793,\n\t0x0068E333, 0x0012D293, 0x0065B8B3, 0x40F603B3, 0x411388B3, 0xFE08C0E3, 0x406585B3, 0x00E88A63,\n\t0x00E8B633, 0x0102E833, 0x00060A63, 0x0180006F, 0x00D5B633, 0x0102E833, 0x00061663, 0x00088613,\n\t0xFB5FF06F, 0x01052023, 0x00052223, 0x00B52423, 0x01152623, 0x00008067, 0x00D5B7B3, 0xEE078EE3,\n\t0x01052023, 0x01052223, 0x00B52423, 0x00C52623, 0x00008067, 0x02D5D833, 0x02D80633, 0x40C585B3,\n\t0x01052023, 0x00052223, 0x00B52423, 0x00052623, 0x00008067, 0x16D61063, 0x02C5D833, 0x02C80633,\n\t0x40C585B3, 0x00100793, 0x01052023, 0x00F52223, 0x00B52423, 0x00052623, 0x00008067, 0x00088793,\n\t0x0088D893, 0x00E8B2B3, 0x0012C293, 0x00329293, 0x0102E833, 0xEAE8EAE3, 0x00088793, 0x0048D893,\n\t0x00E8B2B3, 0x0012C293, 0x00229293, 0x00586833, 0xEAE8E8E3, 0x00088793, 0x0028D293, 0x00E2B8B3,\n\t0x0018C893, 0x00189893, 0x011868B3, 0xEAE2F6E3, 0xEADFF06F, 0x00088793, 0x00481813, 0x0088D293,\n\t0x00C2B8B3, 0x0018C893, 0xDAC2E2E3, 0x00028793, 0x00389293, 0x0047D893, 0x0102E833, 0x00C8B2B3,\n\t0x0012C293, 0xDAC8E0E3, 0x00088793, 0x00229293, 0x0028D893, 0x00586833, 0x00C8B2B3, 0x0012C293,\n\t0xD8C8FEE3, 0xD9DFF06F, 0x02000813, 0x40F80833, 0xFE080293, 0x010698B3, 0xDA02CAE3, 0x00088793,\n\t0x00000713, 0x41F2D293, 0x0112F8B3, 0x00100293, 0x01029833, 0x0180006F, 0x0018D893, 0x01F79293,\n\t0x0017D793, 0x0058E8B3, 0x00185813, 0x0115B2B3, 0x40F60333, 0x405302B3, 0xFE02C0E3, 0x411585B3,\n\t0x00E86733, 0x00028663, 0x00028613, 0xFCDFF06F, 0x02D5D633, 0x02D606B3, 0x40D585B3, 0x00E66833,\n\t0x01052023, 0x00052223, 0x00B52423, 0x00052623, 0x00008067, 0x02D657B3, 0x0106D813, 0x02D788B3,\n\t0x411608B3, 0x04081E63, 0x0105D613, 0x01089893, 0x00C8E733, 0x02D75733, 0x01059593, 0x0105D593,\n\t0x02D70833, 0x41060633, 0x01061613, 0x00B665B3, 0x02D5D633, 0x01071813, 0x01075713, 0x00F767B3,\n\t0x02D606B3, 0x40D585B3, 0x00C86833, 0x01052023, 0x00F52223, 0x00B52423, 0x00052623, 0x00008067,\n\t0x00E88663, 0x00E8B633, 0x0080006F, 0x00D5B633, 0x00060C63, 0x00052023, 0x00F52223, 0x00B52423,\n\t0x01152623, 0x00008067, 0x0016D813, 0x01F71713, 0x01F69293, 0x01076733, 0x80000837, 0x0180006F,\n\t0x0012D293, 0x01F71313, 0x00175713, 0x0062E2B3, 0x00185813, 0x0055B333, 0x40E883B3, 0x40638333,\n\t0xFE0340E3, 0x405585B3, 0x00C86633, 0x00030663, 0x00030893, 0xFCDFF06F, 0x02D5D733, 0x02D706B3,\n\t0x40D585B3, 0x00C76833, 0x01052023, 0x00F52223, 0x00B52423, 0x00052623, 0x00008067, 0x01000693,\n\t0x06D66463, 0x40A006B3, 0x0036F693, 0x00D50733, 0x00E57E63, 0x00068793, 0x00050813, 0x00B80023,\n\t0xFFF78793, 0x00180813, 0xFE079AE3, 0x40D60633, 0xFFC67693, 0x00D706B3, 0x02D77063, 0x0FF5F793,\n\t0x01010837, 0x10180813, 0x030787B3, 0x00F72023, 0x00470713, 0xFED76CE3, 0x00367613, 0x00C68733,\n\t0x00E6EA63, 0x0200006F, 0x00050693, 0x00C50733, 0x00E57A63, 0x00B68023, 0xFFF60613, 0x00168693,\n\t0xFE061AE3, 0x00008067, 0x696E6170, 0x61620A63, 0x6D612064, 0x746E756F, 0x6764656C, 0x66207265,\n\t0x206C6C75, 0x6220726F, 0x6E206461, 0x16656D61, 0x63696C73, 0x6E692065, 0x20786564, 0x72617473,\n\t0x61207374, 0x0DC02074, 0x74756220, 0x646E6520, 0x74612073, 0x6700C020, 0x74736575, 0x0073722E,\n\t0x646E6920, 0x6F207865, 0x6F207475, 0x6F622066, 0x73646E75, 0x6874203A, 0x656C2065, 0x7369206E,\n\t0x2012C020, 0x20747562, 0x20656874, 0x65646E69, 0x73692078, 0x1000C020, 0x676E6172, 0x6E652065,\n\t0x6E692064, 0x20786564, 0x6F2022C0, 0x6F207475, 0x61722066, 0x2065676E, 0x20726F66, 0x63696C73,\n\t0x666F2065, 0x6E656C20, 0x20687467, 0x721200C0, 0x65676E61, 0x61747320, 0x69207472, 0x7865646E,\n\t0x2022C020, 0x2074756F, 0x7220666F, 0x65676E61, 0x726F6620, 0x696C7320, 0x6F206563, 0x656C2066,\n\t0x6874676E, 0x0000C020, 0x00002BF7, 0x00000008, 0x000000C0, 0x0000000D, 0x6E6B6E75, 0x206E776F,\n\t0x646E6573, 0x00007265, 0x00002BF7, 0x00000008, 0x000000C9, 0x00000010, 0x00002BF7, 0x00000008,\n\t0x000000CE, 0x0000000D, 0x75736E69, 0x63696666, 0x746E6569, 0x6C616220, 0x65636E61, 0x6E6B6E75,\n\t0x206E776F, 0x6F636361, 0x00746E75, 0x00002BF7, 0x00000008, 0x000000D6, 0x00000010, 0x6E6B6E75,\n\t0x206E776F, 0x6D6D6F63, 0x00646E61, 0x00002BF7, 0x00000008, 0x0000007F, 0x00000008, 0x00002BF7,\n\t0x00000008, 0x00000050, 0x00000015, 0x00002BF7, 0x00000008, 0x00000051, 0x00000030, 0x00002BF7,\n\t0x00000008, 0x00000063, 0x0000000D, 0x00002BF7, 0x00000008, 0x000000B0, 0x00000013, 0x00002BF7,\n\t0x00000008, 0x000000A8, 0x0000000D, 0x00002BF7, 0x00000008, 0x000000ED, 0x0000001A, 0x00002BF7,\n\t0x00000008, 0x000000F2, 0x0000002B, 0x656E696C, 0x00203A20, 0x00002BF7, 0x00000008, 0x00000103,\n\t0x00000011, 0x00002BF7, 0x00000008, 0x00000104, 0x0000001F, 0x31303030, 0x33303230, 0x35303430,\n\t0x37303630, 0x39303830, 0x31313031, 0x33313231, 0x35313431, 0x37313631, 0x39313831, 0x31323032,\n\t0x33323232, 0x35323432, 0x37323632, 0x39323832, 0x31333033, 0x33333233, 0x35333433, 0x37333633,\n\t0x39333833, 0x31343034, 0x33343234, 0x35343434, 0x37343634, 0x39343834, 0x31353035, 0x33353235,\n\t0x35353435, 0x37353635, 0x39353835, 0x31363036, 0x33363236, 0x35363436, 0x37363636, 0x39363836,\n\t0x31373037, 0x33373237, 0x35373437, 0x37373637, 0x39373837, 0x31383038, 0x33383238, 0x35383438,\n\t0x37383638, 0x39383838, 0x31393039, 0x33393239, 0x35393439, 0x37393639, 0x39393839,\n}\n\n// GuestLedger returns the flat text image of the compiled Rust ledger, ready\n// for [NewMachine] at [DefaultEntry].\nfunc GuestLedger() []byte { return Image(guestLedger) }\n\n// Image serializes instruction words little-endian, which is what RV32 is.\n// Exported because anything assembling a program has to do exactly this, and\n// getting the byte order wrong produces a decoder error a long way from the\n// mistake.\nfunc Image(words []uint32) []byte {\n\tb := make([]byte, 0, len(words)*4)\n\tfor _, w := range words {\n\t\tb = append(b, byte(w), byte(w\u003e\u003e8), byte(w\u003e\u003e16), byte(w\u003e\u003e24))\n\t}\n\treturn b\n}\n"},{"name":"mem.gno","body":"package riscv\n\nimport \"gno.land/p/moul/x/vm/vmkit/v0\"\n\n// Memory is the guest's flat address space, with a snapshot that carries only\n// the pages it actually touched.\n//\n// The shape is the one the bf ladder argued for. Running memory is a flat\n// []byte because a load or a store happens on a large fraction of instructions\n// and an avl lookup per access would dominate the interpreter the way\n// vmkit.Meter.Charge did there. Snapshot cost is solved separately, by a dirty\n// bitmap: a program that writes one page pauses in one page, not in a megabyte,\n// which is the same trick that lets a bf hello world pause in 43 bytes.\n//\n// That answers the open question on the design issue (\"memory size versus\n// snapshot cost\") without paying for it on every instruction.\nconst (\n\t// PageSize is the snapshot granularity, not an MMU page: there is no\n\t// address translation here, only bookkeeping about what changed.\n\tPageSize = 4096\n\n\t// MemSize is the address space. 1 MiB is far more than a no_std guest\n\t// needs and small enough that the flat allocation is not the cost.\n\tMemSize = 1 \u003c\u003c 20\n\n\tpageCount = MemSize / PageSize\n)\n\n// Memory is a flat address space plus the record of which pages were written.\ntype Memory struct {\n\tb     []byte\n\tdirty []bool\n}\n\n// NewMemory returns a zeroed address space.\nfunc NewMemory() *Memory {\n\treturn \u0026Memory{b: make([]byte, MemSize), dirty: make([]bool, pageCount)}\n}\n\n// Size returns the address space size.\nfunc (m *Memory) Size() int { return len(m.b) }\n\n// DirtyPages reports how many pages the guest has written, which is what a\n// snapshot costs.\nfunc (m *Memory) DirtyPages() int {\n\tn := 0\n\tfor _, d := range m.dirty {\n\t\tif d {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// inRange reports whether [addr, addr+size) is inside the address space.\n//\n// Out of range is a trap rather than a wrap. RISC-V leaves the behaviour of an\n// access outside physical memory to the platform, and a chain has to pick the\n// one that cannot differ between nodes: refusing is deterministic, wrapping\n// invites a guest to alias two addresses and get different answers from\n// different memory sizes.\nfunc (m *Memory) inRange(addr uint32, size int) bool {\n\tend := uint64(addr) + uint64(size)\n\treturn end \u003c= uint64(len(m.b))\n}\n\n// Load8, Load16 and Load32 read little-endian, which is what RV32 is.\nfunc (m *Memory) Load8(addr uint32) (uint8, bool) {\n\tif !m.inRange(addr, 1) {\n\t\treturn 0, false\n\t}\n\treturn m.b[addr], true\n}\n\nfunc (m *Memory) Load16(addr uint32) (uint16, bool) {\n\tif !m.inRange(addr, 2) {\n\t\treturn 0, false\n\t}\n\treturn uint16(m.b[addr]) | uint16(m.b[addr+1])\u003c\u003c8, true\n}\n\nfunc (m *Memory) Load32(addr uint32) (uint32, bool) {\n\tif !m.inRange(addr, 4) {\n\t\treturn 0, false\n\t}\n\treturn uint32(m.b[addr]) | uint32(m.b[addr+1])\u003c\u003c8 |\n\t\tuint32(m.b[addr+2])\u003c\u003c16 | uint32(m.b[addr+3])\u003c\u003c24, true\n}\n\nfunc (m *Memory) Store8(addr uint32, v uint8) bool {\n\tif !m.inRange(addr, 1) {\n\t\treturn false\n\t}\n\tm.b[addr] = v\n\tm.dirty[addr/PageSize] = true\n\treturn true\n}\n\nfunc (m *Memory) Store16(addr uint32, v uint16) bool {\n\tif !m.inRange(addr, 2) {\n\t\treturn false\n\t}\n\tm.b[addr] = uint8(v)\n\tm.b[addr+1] = uint8(v \u003e\u003e 8)\n\tm.dirty[addr/PageSize] = true\n\tm.dirty[(addr+1)/PageSize] = true\n\treturn true\n}\n\nfunc (m *Memory) Store32(addr uint32, v uint32) bool {\n\tif !m.inRange(addr, 4) {\n\t\treturn false\n\t}\n\tm.b[addr] = uint8(v)\n\tm.b[addr+1] = uint8(v \u003e\u003e 8)\n\tm.b[addr+2] = uint8(v \u003e\u003e 16)\n\tm.b[addr+3] = uint8(v \u003e\u003e 24)\n\tm.dirty[addr/PageSize] = true\n\tm.dirty[(addr+3)/PageSize] = true\n\treturn true\n}\n\n// WriteImage places a program image at addr and marks the pages it covers, so\n// a snapshot taken before the first store still carries the program.\nfunc (m *Memory) WriteImage(addr uint32, img []byte) bool {\n\tif !m.inRange(addr, len(img)) {\n\t\treturn false\n\t}\n\tcopy(m.b[addr:], img)\n\tfor i := 0; i \u003c len(img); i++ {\n\t\tm.dirty[(uint64(addr)+uint64(i))/PageSize] = true\n\t}\n\treturn true\n}\n\n// Snapshot writes only the dirty pages, each prefixed by its index.\nfunc (m *Memory) Snapshot(w *vmkit.Writer) {\n\tw.Uint32(uint32(m.DirtyPages()))\n\tfor i, d := range m.dirty {\n\t\tif !d {\n\t\t\tcontinue\n\t\t}\n\t\tw.Uint32(uint32(i))\n\t\tw.Bytes(m.b[i*PageSize : (i+1)*PageSize])\n\t}\n}\n\n// Restore reads a snapshot written by Snapshot into a zeroed address space.\nfunc (m *Memory) Restore(r *vmkit.Reader) error {\n\tm.b = make([]byte, MemSize)\n\tm.dirty = make([]bool, pageCount)\n\tn := int(r.Uint32())\n\tif n \u003c 0 || n \u003e pageCount {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\tfor i := 0; i \u003c n; i++ {\n\t\tidx := int(r.Uint32())\n\t\tpage := r.Bytes()\n\t\tif err := r.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif idx \u003c 0 || idx \u003e= pageCount || len(page) != PageSize {\n\t\t\treturn vmkit.ErrBadSnapshot\n\t\t}\n\t\tcopy(m.b[idx*PageSize:], page)\n\t\tm.dirty[idx] = true\n\t}\n\treturn r.Err()\n}\n"},{"name":"predecode.gno","body":"package riscv\n\n// Predecode: the image is turned into fields once, at load, and the dispatch\n// loop only indexes arrays.\n//\n// Two measurements forced this shape, both in switchcost_test.gno:\n//\n//   - The GnoVM scans switch cases in source order. Reaching case 47 of a\n//     48-case switch costs 13,358 gas against 292 for case 0, a measured 278\n//     gas per case skipped. So the internal opcodes below are ordered by how\n//     often compiled code actually executes them, and that ordering is a\n//     performance decision, not a stylistic one. Do not sort this list.\n//   - An elementary operation costs on the order of 280 gas. Fetching four\n//     bytes and reassembling them is fourteen of those, on every instruction,\n//     forever. Doing it once per word instead is the single largest saving\n//     available to an interpreter here.\n//\n// The decoders in decode.gno are used verbatim below rather than inlined,\n// because predecode runs once per word in the image and not once per executed\n// instruction. That is the point: the expensive, readable code moved off the\n// hot path instead of being duplicated onto it.\n\n// Internal opcodes, ordered by expected dynamic frequency in compiled code.\n// The first dozen are what a loop nest and a function prologue are made of.\nconst (\n\tiADDI uint8 = iota\n\tiLW\n\tiSW\n\tiADD\n\tiBNE\n\tiBEQ\n\tiJAL\n\tiJALR\n\tiLUI\n\tiSLLI\n\tiSRLI\n\tiANDI\n\tiSUB\n\tiORI\n\tiXORI\n\tiBLT\n\tiBGE\n\tiBLTU\n\tiBGEU\n\tiSRAI\n\tiSLL\n\tiSRL\n\tiSRA\n\tiAND\n\tiOR\n\tiXOR\n\tiLBU\n\tiLB\n\tiLH\n\tiLHU\n\tiSB\n\tiSH\n\tiAUIPC\n\tiSLT\n\tiSLTU\n\tiSLTI\n\tiSLTIU\n\tiMUL\n\tiMULH\n\tiMULHSU\n\tiMULHU\n\tiDIV\n\tiDIVU\n\tiREM\n\tiREMU\n\tiECALL\n\tiEBREAK\n\tiFENCE\n\tiILLEGAL\n)\n\n// code is an image with its fields already pulled apart. Parallel arrays, not\n// a slice of structs: an arm reads three or four fields, and paying for the\n// ones it does not read is the cost this whole file exists to avoid.\ntype code struct {\n\tbase  uint32 // the address word 0 sits at\n\twords uint32 // how many instructions the text segment holds\n\tend   uint32 // base + 4*words, the first address past the text\n\top    []uint8\n\trd    []uint8\n\trs1   []uint8\n\trs2   []uint8\n\timm   []uint32\n}\n\n// predecode walks an image and records, for every word, what it is and what\n// its operands are. A word that is not an instruction becomes iILLEGAL and\n// traps only if it is ever executed, which is what keeps a constant pool in\n// the middle of a text segment legal.\nfunc predecode(base uint32, img []byte) *code {\n\tn := uint32(len(img) / 4)\n\tc := \u0026code{\n\t\tbase:  base,\n\t\twords: n,\n\t\tend:   base + n*4,\n\t\top:    make([]uint8, n),\n\t\trd:    make([]uint8, n),\n\t\trs1:   make([]uint8, n),\n\t\trs2:   make([]uint8, n),\n\t\timm:   make([]uint32, n),\n\t}\n\tfor i := uint32(0); i \u003c n; i++ {\n\t\tj := i * 4\n\t\tinst := uint32(img[j]) | uint32(img[j+1])\u003c\u003c8 |\n\t\t\tuint32(img[j+2])\u003c\u003c16 | uint32(img[j+3])\u003c\u003c24\n\t\top, imm := decodeWord(inst)\n\t\tc.op[i] = op\n\t\tc.imm[i] = imm\n\t\t// The three register selectors are in the same place in every format\n\t\t// that has them, and are harmless in the formats that do not, so they\n\t\t// are taken unconditionally and spelled out: this loop already costs\n\t\t// more than executing the instruction does.\n\t\tc.rd[i] = uint8((inst \u003e\u003e 7) \u0026 0x1F)\n\t\tc.rs1[i] = uint8((inst \u003e\u003e 15) \u0026 0x1F)\n\t\tc.rs2[i] = uint8((inst \u003e\u003e 20) \u0026 0x1F)\n\t}\n\treturn c\n}\n\n// decodeWord returns both the internal opcode and the immediate, in one pass.\n//\n// They were two functions once, and splitting them cost 22 case labels: the\n// second switch had to ask all over again which format the instruction was, and\n// the GnoVM scans case labels one at a time. Deciding both in the arm that\n// already knows the answer took predecode from 31.4k gas per word to 19.6k.\n//\n// The immediate decoders are still called rather than inlined. This runs once\n// per word in the image, not once per executed instruction, and sign extension\n// is the subtle part of RV32 decoding: it belongs in one place, spelled out,\n// with decode_test.gno round-tripping it against the assembler.\nfunc decodeWord(inst uint32) (uint8, uint32) {\n\tf3 := funct3(inst)\n\tswitch opcode(inst) {\n\tcase opImm:\n\t\timm := immI(inst)\n\t\tswitch f3 {\n\t\tcase 0x0:\n\t\t\treturn iADDI, imm\n\t\tcase 0x1:\n\t\t\treturn iSLLI, imm\n\t\tcase 0x2:\n\t\t\treturn iSLTI, imm\n\t\tcase 0x3:\n\t\t\treturn iSLTIU, imm\n\t\tcase 0x4:\n\t\t\treturn iXORI, imm\n\t\tcase 0x5:\n\t\t\tif funct7(inst) == 0x20 {\n\t\t\t\treturn iSRAI, imm\n\t\t\t}\n\t\t\treturn iSRLI, imm\n\t\tcase 0x6:\n\t\t\treturn iORI, imm\n\t\tcase 0x7:\n\t\t\treturn iANDI, imm\n\t\t}\n\tcase opLoad:\n\t\timm := immI(inst)\n\t\tswitch f3 {\n\t\tcase 0x0:\n\t\t\treturn iLB, imm\n\t\tcase 0x1:\n\t\t\treturn iLH, imm\n\t\tcase 0x2:\n\t\t\treturn iLW, imm\n\t\tcase 0x4:\n\t\t\treturn iLBU, imm\n\t\tcase 0x5:\n\t\t\treturn iLHU, imm\n\t\t}\n\tcase opStore:\n\t\timm := immS(inst)\n\t\tswitch f3 {\n\t\tcase 0x0:\n\t\t\treturn iSB, imm\n\t\tcase 0x1:\n\t\t\treturn iSH, imm\n\t\tcase 0x2:\n\t\t\treturn iSW, imm\n\t\t}\n\tcase opReg:\n\t\tf7 := funct7(inst)\n\t\tif f7 == 0x01 {\n\t\t\tswitch f3 {\n\t\t\tcase 0x0:\n\t\t\t\treturn iMUL, 0\n\t\t\tcase 0x1:\n\t\t\t\treturn iMULH, 0\n\t\t\tcase 0x2:\n\t\t\t\treturn iMULHSU, 0\n\t\t\tcase 0x3:\n\t\t\t\treturn iMULHU, 0\n\t\t\tcase 0x4:\n\t\t\t\treturn iDIV, 0\n\t\t\tcase 0x5:\n\t\t\t\treturn iDIVU, 0\n\t\t\tcase 0x6:\n\t\t\t\treturn iREM, 0\n\t\t\tcase 0x7:\n\t\t\t\treturn iREMU, 0\n\t\t\t}\n\t\t}\n\t\tswitch f3 {\n\t\tcase 0x0:\n\t\t\tif f7 == 0x20 {\n\t\t\t\treturn iSUB, 0\n\t\t\t}\n\t\t\treturn iADD, 0\n\t\tcase 0x1:\n\t\t\treturn iSLL, 0\n\t\tcase 0x2:\n\t\t\treturn iSLT, 0\n\t\tcase 0x3:\n\t\t\treturn iSLTU, 0\n\t\tcase 0x4:\n\t\t\treturn iXOR, 0\n\t\tcase 0x5:\n\t\t\tif f7 == 0x20 {\n\t\t\t\treturn iSRA, 0\n\t\t\t}\n\t\t\treturn iSRL, 0\n\t\tcase 0x6:\n\t\t\treturn iOR, 0\n\t\tcase 0x7:\n\t\t\treturn iAND, 0\n\t\t}\n\tcase opBranch:\n\t\timm := immB(inst)\n\t\tswitch f3 {\n\t\tcase 0x0:\n\t\t\treturn iBEQ, imm\n\t\tcase 0x1:\n\t\t\treturn iBNE, imm\n\t\tcase 0x4:\n\t\t\treturn iBLT, imm\n\t\tcase 0x5:\n\t\t\treturn iBGE, imm\n\t\tcase 0x6:\n\t\t\treturn iBLTU, imm\n\t\tcase 0x7:\n\t\t\treturn iBGEU, imm\n\t\t}\n\tcase opLUI:\n\t\treturn iLUI, immU(inst)\n\tcase opAUIPC:\n\t\treturn iAUIPC, immU(inst)\n\tcase opJAL:\n\t\treturn iJAL, immJ(inst)\n\tcase opJALR:\n\t\tif f3 == 0x0 {\n\t\t\treturn iJALR, immI(inst)\n\t\t}\n\tcase opFence:\n\t\treturn iFENCE, 0\n\tcase opSystem:\n\t\tif immI(inst) == 0 {\n\t\t\treturn iECALL, 0\n\t\t}\n\t\treturn iEBREAK, 0\n\t}\n\treturn iILLEGAL, 0\n}\n"},{"name":"predecode_test.gno","body":"package riscv\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// classify collapses the spec's opcode / funct3 / funct7 tree onto one byte,\n// and every arm of the dispatch loop trusts it. These are the pairs that share\n// a funct3 and differ only in funct7, which is where a collapse goes wrong.\nfunc TestClassifySeparatesTheAmbiguousPairs(t *testing.T) {\n\tcases := []struct {\n\t\tinst uint32\n\t\twant uint8\n\t}{\n\t\t{add(1, 2, 3), iADD},\n\t\t{sub(1, 2, 3), iSUB},\n\t\t{mul(1, 2, 3), iMUL},\n\t\t{divi(1, 2, 3), iDIV},\n\t\t{remi(1, 2, 3), iREM},\n\t\t{addi(1, 2, 5), iADDI},\n\t\t{lw(1, 2, 0), iLW},\n\t\t{lbu(1, 2, 0), iLBU},\n\t\t{sw(1, 2, 0), iSW},\n\t\t{bne(1, 2, 4), iBNE},\n\t\t{lui(1, 0x1000), iLUI},\n\t\t{jal(1, 4), iJAL},\n\t\t{ecall(), iECALL},\n\t\t{0, iILLEGAL},\n\t}\n\tfor _, c := range cases {\n\t\top, _ := decodeWord(c.inst)\n\t\tuassert.Equal(t, uint64(c.want), uint64(op))\n\t}\n}\n\n// A restored hart has to predecode again, because the arrays are not in the\n// snapshot: only the memory pages are. Restoring into a machine that has never\n// seen the image is the path a realm actually takes between transactions, and\n// it is the one the existing slice test did not cover, because it always\n// restored into a machine NewMachine had already loaded.\nfunc TestRestoreIntoABareMachine(t *testing.T) {\n\tprog := append([]uint32{\n\t\taddi(5, 0, 0),\n\t\taddi(6, 0, 10),\n\t\tadd(5, 5, 6),\n\t\taddi(6, 6, 0xFFF), // -1\n\t\tbne(6, 0, 0x1FF8), // -8\n\t}, exitWith()...)\n\timage := asm(prog)\n\n\tone, err := NewMachine(image, entry)\n\tuassert.NoError(t, err)\n\tone.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\n\tpart, err := NewMachine(image, entry)\n\tuassert.NoError(t, err)\n\t_, status := part.Step(vmkit.NewTestHost(), 7)\n\tuassert.Equal(t, \"running\", status.String())\n\n\tvar bare Machine\n\tuassert.NoError(t, bare.Restore(part.Snapshot()))\n\t_, status = bare.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, uint64(one.Registers()[5]), uint64(bare.Registers()[5]))\n\tuassert.Equal(t, uint64(55), uint64(bare.Registers()[5]))\n}\n\n// Predecoding is only sound if the text cannot change under it, so a store\n// into the text segment is a trap rather than a silent disagreement between\n// the arrays and the memory. That is W xor X, which is what an ELF text\n// segment is anyway, and it removes self-modifying code from the VM entirely.\nfunc TestStoreIntoTextTraps(t *testing.T) {\n\tprog := append(li(5, entry), addi(6, 0, 1), sw(6, 5, 0))\n\tprog = append(prog, exitWith()...)\n\tm, err := NewMachine(asm(prog), entry)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"trapped\", status.String())\n\tuassert.Equal(t, \"store into text segment\", m.Trap())\n}\n\n// A store just below the text segment is legal, or the trap above would be\n// catching the wrong thing.\nfunc TestStoreBelowTextIsFine(t *testing.T) {\n\tprog := append(li(5, entry-4), addi(6, 0, 7), sw(6, 5, 0))\n\tprog = append(prog, exitWith()...)\n\tm, err := NewMachine(asm(prog), entry)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\tv, ok := m.Memory().Load32(entry - 4)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, uint64(7), uint64(v))\n}\n\n// A halted hart points past the ecall it halted on, not at it. The deferred\n// write-back is the only thing that sets m.pc, so an arm that assigned m.pc\n// directly had its assignment silently undone on the way out.\nfunc TestHaltedPCIsPastTheEcall(t *testing.T) {\n\tm, err := NewMachine(asm(exitWith()), entry)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\t// entry: addi a7, x0, 93 -- entry+4: ecall -- so the next pc is entry+8.\n\tuassert.Equal(t, uint64(entry+8), uint64(m.PC()))\n}\n\n// An entry point or an image that is not a whole number of instructions has no\n// predecode, so it is refused at load rather than half-executed.\nfunc TestNewMachineRefusesMisalignedImages(t *testing.T) {\n\t_, err := NewMachine(asm(exitWith()), entry+1)\n\tuassert.Error(t, err)\n\t_, err = NewMachine([]byte{1, 2, 3}, entry)\n\tuassert.Error(t, err)\n}\n\n// The index into the predecoded arrays is a shift, so a pc that is not\n// 4-aligned would silently execute the word containing it. Only a snapshot can\n// deliver one, because JALR checks its own target, so the guard is at entry to\n// the loop rather than inside it.\nfunc TestMisalignedPCTraps(t *testing.T) {\n\tm, err := NewMachine(asm(exitWith()), entry)\n\tuassert.NoError(t, err)\n\tm.pc = entry + 2\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"trapped\", status.String())\n\tuassert.Equal(t, \"misaligned program counter\", m.Trap())\n}\n\n// JALR is the only instruction that can compute an odd target, and it clears\n// only bit 0, so a target of 2 mod 4 has to be refused where it is made.\nfunc TestJalrRefusesAMisalignedTarget(t *testing.T) {\n\tprog := append(li(5, entry+6), []uint32{jalr(1, 5, 0)}...)\n\tprog = append(prog, exitWith()...)\n\tm, err := NewMachine(asm(prog), entry)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"trapped\", status.String())\n\tuassert.Equal(t, \"misaligned jump target\", m.Trap())\n}\n\n// A .data section has to land somewhere writable, and refusing an overlap with\n// the text is the check that keeps a bad linker script from producing a program\n// that traps on its first store instead of at load.\nfunc TestLoadDataRefusesTheTextSegment(t *testing.T) {\n\tm, err := NewMachine(asm(exitWith()), entry)\n\tuassert.NoError(t, err)\n\n\tuassert.Error(t, m.LoadData(entry, []byte{1, 2, 3, 4}))\n\tuassert.Error(t, m.LoadData(entry-2, []byte{1, 2, 3, 4}))\n\tuassert.NoError(t, m.LoadData(entry-4, []byte{1, 2, 3, 4}))\n\tuassert.NoError(t, m.LoadData(0x40000, []byte{9, 8, 7, 6}))\n\tuassert.Error(t, m.LoadData(MemSize-2, []byte{1, 2, 3, 4}))\n\n\tv, ok := m.Memory().Load32(0x40000)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, uint64(0x06070809), uint64(v))\n}\n\n// Data is memory, so it rides in the snapshot like everything else the guest\n// touched. A resumed program must not find its constants gone.\nfunc TestLoadedDataSurvivesASnapshot(t *testing.T) {\n\tm, err := NewMachine(asm(exitWith()), entry)\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, m.LoadData(0x40000, []byte{0xDE, 0xAD, 0xBE, 0xEF}))\n\n\tvar restored Machine\n\tuassert.NoError(t, restored.Restore(m.Snapshot()))\n\tv, ok := restored.Memory().Load32(0x40000)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, uint64(0xEFBEADDE), uint64(v))\n}\n"},{"name":"riscv_test.gno","body":"package riscv\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A tiny assembler, so the programs below read as instructions rather than as\n// hex. Encoding here and decoding in decode.gno are written from the spec\n// independently: if one has a field in the wrong place the tests fail, which is\n// the point of not sharing a helper between them.\n\nfunc rType(f7, rs2, rs1, f3, rd, op uint32) uint32 {\n\treturn f7\u003c\u003c25 | rs2\u003c\u003c20 | rs1\u003c\u003c15 | f3\u003c\u003c12 | rd\u003c\u003c7 | op\n}\nfunc iType(imm, rs1, f3, rd, op uint32) uint32 {\n\treturn (imm\u00260xFFF)\u003c\u003c20 | rs1\u003c\u003c15 | f3\u003c\u003c12 | rd\u003c\u003c7 | op\n}\nfunc sType(imm, rs2, rs1, f3, op uint32) uint32 {\n\treturn (imm\u003e\u003e5\u00260x7F)\u003c\u003c25 | rs2\u003c\u003c20 | rs1\u003c\u003c15 | f3\u003c\u003c12 | (imm\u00260x1F)\u003c\u003c7 | op\n}\nfunc bType(imm, rs2, rs1, f3, op uint32) uint32 {\n\treturn (imm\u003e\u003e12\u00260x1)\u003c\u003c31 | (imm\u003e\u003e5\u00260x3F)\u003c\u003c25 | rs2\u003c\u003c20 | rs1\u003c\u003c15 |\n\t\tf3\u003c\u003c12 | (imm\u003e\u003e1\u00260xF)\u003c\u003c8 | (imm\u003e\u003e11\u00260x1)\u003c\u003c7 | op\n}\nfunc uType(imm, rd, op uint32) uint32 { return imm\u00260xFFFFF000 | rd\u003c\u003c7 | op }\nfunc jType(imm, rd, op uint32) uint32 {\n\treturn (imm\u003e\u003e20\u00260x1)\u003c\u003c31 | (imm\u003e\u003e1\u00260x3FF)\u003c\u003c21 | (imm\u003e\u003e11\u00260x1)\u003c\u003c20 |\n\t\t(imm\u003e\u003e12\u00260xFF)\u003c\u003c12 | rd\u003c\u003c7 | op\n}\n\nfunc addi(rd, rs1, imm uint32) uint32 { return iType(imm, rs1, 0x0, rd, opImm) }\nfunc add(rd, rs1, rs2 uint32) uint32  { return rType(0x00, rs2, rs1, 0x0, rd, opReg) }\nfunc sub(rd, rs1, rs2 uint32) uint32  { return rType(0x20, rs2, rs1, 0x0, rd, opReg) }\nfunc mul(rd, rs1, rs2 uint32) uint32  { return rType(0x01, rs2, rs1, 0x0, rd, opReg) }\nfunc divi(rd, rs1, rs2 uint32) uint32 { return rType(0x01, rs2, rs1, 0x4, rd, opReg) }\nfunc remi(rd, rs1, rs2 uint32) uint32 { return rType(0x01, rs2, rs1, 0x6, rd, opReg) }\nfunc sw(rs2, rs1, imm uint32) uint32  { return sType(imm, rs2, rs1, 0x2, opStore) }\nfunc lw(rd, rs1, imm uint32) uint32   { return iType(imm, rs1, 0x2, rd, opLoad) }\nfunc lbu(rd, rs1, imm uint32) uint32  { return iType(imm, rs1, 0x4, rd, opLoad) }\nfunc bne(rs1, rs2, imm uint32) uint32 { return bType(imm, rs2, rs1, 0x1, opBranch) }\nfunc ecall() uint32                   { return iType(0, 0, 0, 0, opSystem) }\n\n// exitWith is the two instructions every test program ends with: set a7 to the\n// exit syscall and trap into the host.\nfunc exitWith() []uint32 { return []uint32{addi(17, 0, sysExit), ecall()} }\n\nfunc asm(words []uint32) []byte {\n\tout := make([]byte, 0, len(words)*4)\n\tfor _, w := range words {\n\t\tout = append(out, byte(w), byte(w\u003e\u003e8), byte(w\u003e\u003e16), byte(w\u003e\u003e24))\n\t}\n\treturn out\n}\n\nconst entry = 0x1000\n\nfunc run(t *testing.T, words []uint32, h vmkit.Host) *Machine {\n\tt.Helper()\n\tm, err := NewMachine(asm(words), entry)\n\tuassert.NoError(t, err)\n\tif m == nil {\n\t\treturn nil\n\t}\n\t_, status := m.Step(h, vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\treturn m\n}\n\nfunc TestArithmetic(t *testing.T) {\n\t// x5 = 7 + 35; x6 = x5 - 2; x7 = x6 * 3\n\tprog := append([]uint32{\n\t\taddi(5, 0, 7),\n\t\taddi(5, 5, 35),\n\t\taddi(6, 0, 2),\n\t\tsub(6, 5, 6),\n\t\taddi(7, 0, 3),\n\t\tmul(7, 6, 7),\n\t}, exitWith()...)\n\tm := run(t, prog, vmkit.NewTestHost())\n\tr := m.Registers()\n\tuassert.Equal(t, uint64(42), uint64(r[5]))\n\tuassert.Equal(t, uint64(40), uint64(r[6]))\n\tuassert.Equal(t, uint64(120), uint64(r[7]))\n}\n\n// Every immediate in the base set is sign extended from its top bit. Small\n// positive programs work either way, which is what makes this the classic\n// decoder bug: it only shows up on a negative constant.\nfunc TestImmediatesAreSignExtended(t *testing.T) {\n\tprog := append([]uint32{\n\t\taddi(5, 0, 10),\n\t\taddi(5, 5, 0xFFF), // -1\n\t\taddi(6, 0, 0x800), // -2048, the most negative 12-bit immediate\n\t}, exitWith()...)\n\tm := run(t, prog, vmkit.NewTestHost())\n\tr := m.Registers()\n\tuassert.Equal(t, uint64(9), uint64(r[5]))\n\tuassert.Equal(t, int64(-2048), int64(int32(r[6])))\n}\n\n// x0 reads as zero and discards every write, and the spec has no exception.\nfunc TestRegisterZeroIsHardwired(t *testing.T) {\n\tprog := append([]uint32{\n\t\taddi(0, 0, 99),\n\t\tadd(5, 0, 0),\n\t}, exitWith()...)\n\tm := run(t, prog, vmkit.NewTestHost())\n\tuassert.Equal(t, uint64(0), uint64(m.Registers()[0]))\n\tuassert.Equal(t, uint64(0), uint64(m.Registers()[5]))\n}\n\nfunc TestLoadsAndStores(t *testing.T) {\n\tprog := append([]uint32{\n\t\taddi(5, 0, 0x7F0), // an address well clear of the program\n\t\taddi(6, 0, 0x123),\n\t\tsw(6, 5, 0),\n\t\tlw(7, 5, 0),\n\t\tlbu(8, 5, 0), // little-endian: the low byte is 0x23\n\t}, exitWith()...)\n\tm := run(t, prog, vmkit.NewTestHost())\n\tr := m.Registers()\n\tuassert.Equal(t, uint64(0x123), uint64(r[7]))\n\tuassert.Equal(t, uint64(0x23), uint64(r[8]))\n}\n\n// A loop, which is the only way to know branches and the pc agree.\nfunc TestBranchLoopSumsToTen(t *testing.T) {\n\t// x5 = 0; x6 = 5; do { x5 += x6; x6 -= 1 } while (x6 != 0)  =\u003e 15\n\tprog := append([]uint32{\n\t\taddi(5, 0, 0),\n\t\taddi(6, 0, 5),\n\t\tadd(5, 5, 6),        // loop:\n\t\taddi(6, 6, 0xFFF),   // x6 -= 1\n\t\tbne(6, 0, 0x1FF8),   // -8, back to loop\n\t}, exitWith()...)\n\tm := run(t, prog, vmkit.NewTestHost())\n\tuassert.Equal(t, uint64(15), uint64(m.Registers()[5]))\n}\n\n// The M extension's defined answers. These are the cases a chain cares about,\n// because the spec makes them RETURN rather than trap and every implementation\n// therefore has to agree.\nfunc TestDivisionEdgeCases(t *testing.T) {\n\tconst minInt32 = 0x80000000\n\tprog := append([]uint32{\n\t\taddi(5, 0, 7),\n\t\taddi(6, 0, 0),\n\t\tdivi(7, 5, 6), // 7 / 0 = all ones\n\t\tremi(8, 5, 6), // 7 % 0 = 7\n\t\tuType(minInt32, 9, opLUI),\n\t\taddi(10, 0, 0xFFF), // -1\n\t\tdivi(11, 9, 10),    // overflow: stays minInt32\n\t\tremi(12, 9, 10),    // overflow: 0\n\t}, exitWith()...)\n\tm := run(t, prog, vmkit.NewTestHost())\n\tr := m.Registers()\n\tuassert.Equal(t, uint64(0xFFFFFFFF), uint64(r[7]))\n\tuassert.Equal(t, uint64(7), uint64(r[8]))\n\tuassert.Equal(t, uint64(minInt32), uint64(r[11]))\n\tuassert.Equal(t, uint64(0), uint64(r[12]))\n}\n\n// The syscall table is the whole interface between guest and chain.\nfunc TestWriteSyscallReachesTheHost(t *testing.T) {\n\t// Store \"hi\" at 0x800, then write(1, 0x800, 2).\n\tprog := append([]uint32{\n\t\taddi(5, 0, 0x7F0),\n\t\taddi(6, 0, 'h'),\n\t\tsType(0, 6, 5, 0x0, opStore), // sb\n\t\taddi(6, 0, 'i'),\n\t\tsType(1, 6, 5, 0x0, opStore),\n\t\taddi(17, 0, sysWrite),\n\t\taddi(10, 0, 1),\n\t\taddi(11, 0, 0x7F0),\n\t\taddi(12, 0, 2),\n\t\tecall(),\n\t}, exitWith()...)\n\th := vmkit.NewTestHost()\n\trun(t, prog, h)\n\tuassert.Equal(t, \"hi\", h.OutString())\n}\n\n// A guest that exits non-zero has HALTED, not trapped: \"your code said no\" is\n// not \"the VM broke\", and a chain should not conflate them.\nfunc TestNonZeroExitIsStillHalted(t *testing.T) {\n\tprog := []uint32{addi(10, 0, 1), addi(17, 0, sysExit), ecall()}\n\tm, err := NewMachine(asm(prog), entry)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"\", m.Trap())\n\tuassert.Equal(t, uint64(1), uint64(m.Registers()[10]))\n}\n\nfunc TestUnknownSyscallTraps(t *testing.T) {\n\tprog := []uint32{addi(17, 0, 777), ecall()}\n\tm, err := NewMachine(asm(prog), entry)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"trapped\", status.String())\n\tuassert.Equal(t, \"unknown syscall\", m.Trap())\n}\n\nfunc TestIllegalInstructionTraps(t *testing.T) {\n\tm, err := NewMachine(asm([]uint32{0xFFFFFFFF}), entry)\n\tuassert.NoError(t, err)\n\t_, status := m.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\tuassert.Equal(t, \"trapped\", status.String())\n}\n\nfunc TestFuelStopsTheHart(t *testing.T) {\n\tprog := append([]uint32{\n\t\taddi(5, 0, 1), addi(5, 5, 1), addi(5, 5, 1), addi(5, 5, 1),\n\t}, exitWith()...)\n\tm, err := NewMachine(asm(prog), entry)\n\tuassert.NoError(t, err)\n\tused, status := m.Step(vmkit.NewTestHost(), 2)\n\tuassert.Equal(t, int64(2), used)\n\tuassert.Equal(t, \"running\", status.String())\n\tuassert.Equal(t, uint64(2), uint64(m.Registers()[5]))\n}\n\n// The property that makes a guest program a contract: slices must equal one go.\nfunc TestSlicedRunEqualsOneShot(t *testing.T) {\n\tprog := append([]uint32{\n\t\taddi(5, 0, 0),\n\t\taddi(6, 0, 12),\n\t\tadd(5, 5, 6),\n\t\taddi(6, 6, 0xFFF),\n\t\tbne(6, 0, 0x1FF8),\n\t\taddi(7, 0, 0x7F0),\n\t\tsw(5, 7, 0),\n\t}, exitWith()...)\n\timage := asm(prog)\n\n\tone, err := NewMachine(image, entry)\n\tuassert.NoError(t, err)\n\tone.Step(vmkit.NewTestHost(), vmkit.Unmetered)\n\n\tsliced, err := NewMachine(image, entry)\n\tuassert.NoError(t, err)\n\th := vmkit.NewTestHost()\n\tstatus := vmkit.Running\n\tfor i := 0; i \u003c 5000 \u0026\u0026 status == vmkit.Running; i++ {\n\t\tfresh, err := NewMachine(image, entry)\n\t\tuassert.NoError(t, err)\n\t\tuassert.NoError(t, fresh.Restore(sliced.Snapshot()))\n\t\t_, status = fresh.Step(h, 3)\n\t\tsliced = fresh\n\t}\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, uint64(one.Registers()[5]), uint64(sliced.Registers()[5]))\n\tuassert.Equal(t, uint64(78), uint64(sliced.Registers()[5]))\n}\n\n// A 1 MiB address space must not cost 1 MiB to pause. This is the kill\n// criterion vmkit set for continuations, measured rather than asserted.\nfunc TestSnapshotCarriesOnlyTouchedPages(t *testing.T) {\n\tprog := append([]uint32{\n\t\taddi(5, 0, 0x7F0),\n\t\taddi(6, 0, 1),\n\t\tsw(6, 5, 0),\n\t}, exitWith()...)\n\tm := run(t, prog, vmkit.NewTestHost())\n\n\t// Two: the page holding the program at 0x1000, and the one holding the\n\t// store at 0x7F0. Two out of 256, which is the whole point.\n\tuassert.Equal(t, 2, m.Memory().DirtyPages())\n\t// The property is proportionality: a snapshot costs what the guest\n\t// touched plus a fixed header, not what the address space is. Two pages\n\t// out of 256 means about 8 KiB out of a megabyte.\n\tsnap := m.Snapshot()\n\tpages := m.Memory().DirtyPages()\n\tuassert.True(t, len(snap) \u003c= pages*PageSize+512,\n\t\t\"a snapshot must not exceed its dirty pages plus a header\")\n\tuassert.True(t, len(snap) \u003c MemSize/100,\n\t\t\"a snapshot of a lightly-used hart must be a rounding error against the address space\")\n}\n\nfunc TestRestoreRejectsJunk(t *testing.T) {\n\tm, err := NewMachine(asm(exitWith()), entry)\n\tuassert.NoError(t, err)\n\tuassert.Error(t, m.Restore([]byte{}))\n\tuassert.Error(t, m.Restore([]byte{1, 2, 3, 4, 5}))\n\n\tgood := m.Snapshot()\n\tbad := make([]byte, len(good))\n\tcopy(bad, good)\n\tbad[4] = 99 // version\n\tuassert.ErrorIs(t, m.Restore(bad), vmkit.ErrBadSnapshot)\n}\n\n// vmkit's plumbing has to work for a second guest, which is the only way to\n// know the ABI was not shaped around the first one.\nfunc TestInstanceIntegration(t *testing.T) {\n\tprog := append([]uint32{addi(5, 0, 21), add(5, 5, 5)}, exitWith()...)\n\timage := asm(prog)\n\n\tinst := vmkit.NewInstance(\"001\", address(\"g1x\"), VMName, image, vmkit.Unmetered)\n\th := vmkit.NewTestHost()\n\tfor i := 0; i \u003c 100 \u0026\u0026 inst.Status == vmkit.Running; i++ {\n\t\tm, err := NewMachine(image, entry)\n\t\tuassert.NoError(t, err)\n\t\tuassert.NoError(t, inst.Run(m, h, 2))\n\t}\n\tuassert.Equal(t, \"halted\", inst.Status.String())\n\tuassert.True(t, inst.Slices \u003e 1)\n}\n"},{"name":"rust_test.gno","body":"package riscv\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The demo the design issue actually asked for: Rust code, compiled by rustc,\n// running on gno.land, moving a balance from one account to another.\n//\n// The image is guests.gno's, built from tools/riscv-guests/ledger. It is worth\n// more than the C guest for one reason: it links Rust's real core and\n// compiler_builtins, so this exercises the standard library's own software\n// arithmetic rather than only what the compiler emitted for my source.\n\nfunc runLedger(t *testing.T, in string) (string, vmkit.Status, *Machine) {\n\tt.Helper()\n\tm, err := NewMachine(GuestLedger(), entry)\n\tuassert.NoError(t, err)\n\tif m == nil {\n\t\treturn \"\", vmkit.Trapped, nil\n\t}\n\th := vmkit.NewTestHost().WithInput([]byte(in))\n\t_, status := m.Step(h, 5000000)\n\treturn string(h.Out()), status, m\n}\n\nfunc TestRustLedgerTransfers(t *testing.T) {\n\tout, status, _ := runLedger(t,\n\t\t\"mint alice 100\\nmint bob 50\\nsend alice bob 30\\n\")\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"alice 70\\nbob 80\\n\", out)\n}\n\nfunc TestRustLedgerMintBurnAndBlankLines(t *testing.T) {\n\tout, status, _ := runLedger(t, \"mint a 5\\n\\n   \\nburn a 2\\n\")\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"a 3\\n\", out)\n\n\tout, status, _ = runLedger(t, \"\")\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"\", out)\n}\n\n// A refusal is halted, not trapped, and it names the line. This is the\n// semantic the whole VM is built around: the program said no, the machine did\n// not break, and a chain has to be able to tell a user which one happened.\nfunc TestRustLedgerRefusalsAreHaltsNotTraps(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"mint a 1\\nsend a b 9\\n\", \"line 2: insufficient balance\\n\"},\n\t\t{\"send nobody b 1\\n\", \"line 1: unknown sender\\n\"},\n\t\t{\"burn ghost 1\\n\", \"line 1: unknown account\\n\"},\n\t\t{\"frobnicate\\n\", \"line 1: unknown command\\n\"},\n\t\t{\"mint a x\\n\", \"line 1: bad amount\\n\"},\n\t}\n\tfor _, c := range cases {\n\t\tout, status, m := runLedger(t, c.in)\n\t\tuassert.Equal(t, \"halted\", status.String(), c.in+\": \"+m.Trap())\n\t\tuassert.Equal(t, c.want, out)\n\t\tuassert.Equal(t, uint64(1), uint64(m.Registers()[10]), \"a refusal exits 1\")\n\t}\n}\n\n// 64-bit arithmetic on a 32-bit machine goes through compiler_builtins, and\n// printing a balance above 2^32 is the path that proves __udivdi3 ran.\nfunc TestRustLedgerDoes64BitArithmetic(t *testing.T) {\n\t// Nine-digit mints, accumulated past what 32 bits holds.\n\tin := \"\"\n\tfor i := 0; i \u003c 6; i++ {\n\t\tin += \"mint whale 999999999\\n\"\n\t}\n\tout, status, _ := runLedger(t, in)\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.Equal(t, \"whale 5999999994\\n\", out)\n}\n\n// Compiled Rust pauses and resumes like anything else, including in the middle\n// of a library routine it never asked to call.\nfunc TestRustLedgerSurvivesSlicing(t *testing.T) {\n\timage := GuestLedger()\n\th := vmkit.NewTestHost().WithInput([]byte(\"mint alice 100\\nsend alice bob 30\\n\"))\n\n\tsliced, err := NewMachine(image, entry)\n\tuassert.NoError(t, err)\n\tstatus := vmkit.Running\n\tslices := 0\n\tfor i := 0; i \u003c 4000 \u0026\u0026 status == vmkit.Running; i++ {\n\t\tvar fresh Machine\n\t\tuassert.NoError(t, fresh.Restore(sliced.Snapshot()))\n\t\t_, status = fresh.Step(h, 17)\n\t\tsliced = \u0026fresh\n\t\tslices++\n\t}\n\tuassert.Equal(t, \"halted\", status.String())\n\tuassert.True(t, slices \u003e 20, \"a sliced run must actually have been sliced\")\n\tuassert.Equal(t, \"alice 70\\nbob 30\\n\", string(h.Out()))\n}\n"},{"name":"snapshot.gno","body":"package riscv\n\nimport \"gno.land/p/moul/x/vm/vmkit/v0\"\n\n// Snapshot serializes the hart: registers, pc, status, and only the memory\n// pages the guest has written.\n//\n// A 1 MiB address space serialized on every pause would make continuations\n// cost more than re-running, which is exactly the kill criterion vmkit set for\n// them. The dirty bitmap is what avoids it: a guest that has touched two pages\n// pauses in about 8 KiB regardless of how much memory it was given.\nfunc (m *Machine) Snapshot() []byte {\n\tif m.code == nil {\n\t\tm.code = \u0026code{}\n\t}\n\tw := vmkit.NewWriter(4096)\n\tw.Uint32(snapMagic)\n\tw.Byte(snapVersion)\n\tfor i := 0; i \u003c 32; i++ {\n\t\tw.Uint32(m.reg[i])\n\t}\n\tw.Uint32(m.pc)\n\tw.Byte(byte(m.status))\n\tw.String(m.trap)\n\tw.Int(int64(m.outLen))\n\t// The text segment's extent, so a restored hart knows which of its pages\n\t// are code and can predecode them again. The code itself is not written:\n\t// it is already in the memory pages, which WriteImage marked dirty.\n\tw.Uint32(m.code.base)\n\tw.Uint32(m.code.words)\n\tm.mem.Snapshot(w)\n\treturn w.Out()\n}\n\n// Restore loads a snapshot. The program image is not carried separately: it\n// lives in the memory pages, which were marked dirty when it was written, so a\n// restored hart has its code without the instance storing it twice.\nfunc (m *Machine) Restore(b []byte) error {\n\tr := vmkit.NewReader(b)\n\tif r.Uint32() != snapMagic {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\tif r.Byte() != snapVersion {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\tvar reg [32]uint32\n\tfor i := 0; i \u003c 32; i++ {\n\t\treg[i] = r.Uint32()\n\t}\n\tpc := r.Uint32()\n\tstatus := vmkit.Status(r.Byte())\n\ttrap := r.String()\n\toutLen := int(r.Int())\n\tbase := r.Uint32()\n\twords := r.Uint32()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\t// A text segment that does not fit in the address space is a snapshot this\n\t// machine did not write, and predecoding it would index past the memory.\n\tif base%4 != 0 || uint64(base)+uint64(words)*4 \u003e uint64(MemSize) {\n\t\treturn vmkit.ErrBadSnapshot\n\t}\n\n\tmem := NewMemory()\n\tif err := mem.Restore(r); err != nil {\n\t\treturn err\n\t}\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tm.reg, m.pc, m.status, m.trap, m.outLen, m.mem = reg, pc, status, trap, outLen, mem\n\t// Predecode again from the restored pages. This is the work a resume pays\n\t// for, once, in exchange for not paying a fetch on every instruction after\n\t// it, and it is why stores into the text segment trap: the arrays and the\n\t// memory would otherwise be free to disagree.\n\tm.code = predecode(base, mem.b[base:base+words*4])\n\t// x0 is hardwired, and a snapshot that claims otherwise is not one this\n\t// machine wrote.\n\tm.reg[0] = 0\n\treturn nil\n}\n"},{"name":"switchcost_test.gno","body":"package riscv\n\nimport \"testing\"\n\n// Does the GnoVM dispatch a switch by jump table or by scanning the cases in\n// order? The answer decides the interpreter's shape: predecoding an image into\n// (op, rd, rs1, rs2, imm) arrays deletes the fetch and the field extraction,\n// but it also flattens two small nested switches into one 48-case switch. If\n// cases are scanned, that trade buys nothing and costs the deeper arms.\n//\n// The experiment: the same 48-case switch, driven to the first case and to the\n// last. Equal cycles means a jump table. A large gap means a scan, and the\n// switch has to stay shallow no matter what else changes.\n\n//go:noinline\nfunc switch48(v uint32) uint32 {\n\tswitch v {\n\tcase 0:\n\t\treturn 1\n\tcase 1:\n\t\treturn 2\n\tcase 2:\n\t\treturn 3\n\tcase 3:\n\t\treturn 4\n\tcase 4:\n\t\treturn 5\n\tcase 5:\n\t\treturn 6\n\tcase 6:\n\t\treturn 7\n\tcase 7:\n\t\treturn 8\n\tcase 8:\n\t\treturn 9\n\tcase 9:\n\t\treturn 10\n\tcase 10:\n\t\treturn 11\n\tcase 11:\n\t\treturn 12\n\tcase 12:\n\t\treturn 13\n\tcase 13:\n\t\treturn 14\n\tcase 14:\n\t\treturn 15\n\tcase 15:\n\t\treturn 16\n\tcase 16:\n\t\treturn 17\n\tcase 17:\n\t\treturn 18\n\tcase 18:\n\t\treturn 19\n\tcase 19:\n\t\treturn 20\n\tcase 20:\n\t\treturn 21\n\tcase 21:\n\t\treturn 22\n\tcase 22:\n\t\treturn 23\n\tcase 23:\n\t\treturn 24\n\tcase 24:\n\t\treturn 25\n\tcase 25:\n\t\treturn 26\n\tcase 26:\n\t\treturn 27\n\tcase 27:\n\t\treturn 28\n\tcase 28:\n\t\treturn 29\n\tcase 29:\n\t\treturn 30\n\tcase 30:\n\t\treturn 31\n\tcase 31:\n\t\treturn 32\n\tcase 32:\n\t\treturn 33\n\tcase 33:\n\t\treturn 34\n\tcase 34:\n\t\treturn 35\n\tcase 35:\n\t\treturn 36\n\tcase 36:\n\t\treturn 37\n\tcase 37:\n\t\treturn 38\n\tcase 38:\n\t\treturn 39\n\tcase 39:\n\t\treturn 40\n\tcase 40:\n\t\treturn 41\n\tcase 41:\n\t\treturn 42\n\tcase 42:\n\t\treturn 43\n\tcase 43:\n\t\treturn 44\n\tcase 44:\n\t\treturn 45\n\tcase 45:\n\t\treturn 46\n\tcase 46:\n\t\treturn 47\n\tcase 47:\n\t\treturn 48\n\t}\n\treturn 0\n}\n\nconst switchIters = 200000\n\nfunc TestSwitchCostFirstCase(t *testing.T) {\n\tvar acc uint32\n\tfor i := 0; i \u003c switchIters; i++ {\n\t\tacc += switch48(0)\n\t}\n\tif acc == 0 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\nfunc TestSwitchCostLastCase(t *testing.T) {\n\tvar acc uint32\n\tfor i := 0; i \u003c switchIters; i++ {\n\t\tacc += switch48(47)\n\t}\n\tif acc == 0 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\n// The control: the same loop with no switch at all, so the two above can be\n// read net of loop and call overhead.\n//\n//go:noinline\nfunc switchNone(v uint32) uint32 { return v + 1 }\n\nfunc TestSwitchCostNoSwitch(t *testing.T) {\n\tvar acc uint32\n\tfor i := 0; i \u003c switchIters; i++ {\n\t\tacc += switchNone(0)\n\t}\n\tif acc == 0 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\n// A scan means the question is no longer \"how few cases\" but \"is there a\n// dispatch that does not scan at all\". These three isolate the alternatives:\n// the bare loop, a direct call, and a call through a table indexed by opcode.\n\n//go:noinline\nfunc hADDI(v uint32) uint32 { return v + 1 }\n\n//go:noinline\nfunc hSUB(v uint32) uint32 { return v - 1 }\n\n//go:noinline\nfunc hXOR(v uint32) uint32 { return v ^ 1 }\n\n//go:noinline\nfunc hAND(v uint32) uint32 { return v \u0026 1 }\n\nvar dispatchTable = [4]func(uint32) uint32{hADDI, hSUB, hXOR, hAND}\n\nfunc TestDispatchLoopOnly(t *testing.T) {\n\tvar acc uint32\n\tfor i := 0; i \u003c switchIters; i++ {\n\t\tacc += uint32(i) \u0026 1\n\t}\n\tif acc == 0 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\nfunc TestDispatchTableCall(t *testing.T) {\n\tvar acc uint32\n\tfor i := 0; i \u003c switchIters; i++ {\n\t\tacc += dispatchTable[3](1)\n\t}\n\tif acc == 0 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\n// What does memory cost? Predecode allocates five arrays per load and the\n// address space allocates a megabyte, so the answer decides whether the\n// predecode arrays should be built eagerly or only for words actually reached.\n\nfunc TestAllocBytes1000(t *testing.T) {\n\tb := make([]byte, 4000)\n\tif len(b) != 4000 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\nfunc TestAllocBytes4000(t *testing.T) {\n\tb := make([]byte, 16000)\n\tif len(b) != 16000 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\n// The five arrays predecode builds, at the same two sizes.\nfunc TestAllocArrays1000(t *testing.T) {\n\ta, b, c := make([]uint8, 1000), make([]uint8, 1000), make([]uint8, 1000)\n\td, e := make([]uint8, 1000), make([]uint32, 1000)\n\tif len(a)+len(b)+len(c)+len(d)+len(e) == 0 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n\nfunc TestAllocArrays4000(t *testing.T) {\n\ta, b, c := make([]uint8, 4000), make([]uint8, 4000), make([]uint8, 4000)\n\td, e := make([]uint8, 4000), make([]uint32, 4000)\n\tif len(a)+len(b)+len(c)+len(d)+len(e) == 0 {\n\t\tt.Fatal(\"unreachable\")\n\t}\n}\n"}]},"send":"","max_deposit":"106000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wesh","path":"gno.land/p/moul/x/wesh/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/wesh/v0`\n\n**The publishable half of the Wesh protocol** (weshnet, the network behind\n[Berty](https://berty.tech)) as a pure gno library: `Contact`, `WebLink`,\n`ParseWebLink`, `RendezvousPoint`, `SeedCommitment`, `BindStatement`,\n`DeviceStatement`, `VerifyBind`, `VerifyDevice`, `HMACSHA256`.\n\n```go\nimport \"gno.land/p/moul/x/wesh/v0\"\n\nc := wesh.Contact{AccountPK: pk, Seed: seed, DisplayName: \"Alice\"}\nlink, _ := c.WebLink()   // https://berty.tech/id#contact/\u003cbase58\u003e/name=Alice\npt, _ := c.RendezvousPointAt(now, wesh.DefaultRotationInterval)\n```\n\n## Why a chain at all\n\nWesh is off-grid, peer-to-peer and end-to-end encrypted. A public chain is the\nopposite in nearly every dimension, so this is deliberately **not** \"weshnet on\nchain\". It carries only the parts that need an authenticated, ordered, publicly\nauditable record, the one thing a peer-to-peer network cannot give itself, and\nwhich Wesh is missing in three specific places:\n\n- **Identities do not resolve.** A Berty ID travels out of band as a QR code or\n  a `https://berty.tech/id#` link, and there is no lookup.\n- **Seed resets are silent.** `ContactRequestResetReference` gives the account a\n  new rendezvous seed, which kills every link ever shared, with no channel to\n  announce it.\n- **Devices can never be revoked.** The protocol documentation says so outright:\n  the account metadata log is append-only and no authority can void an entry.\n\n## What is in here\n\n| piece | what it is |\n|---|---|\n| `Contact` | weshnet's `ShareableContact`: account key + public rendezvous seed + display name, with weshnet's own `CheckFormat` length rules |\n| `Blob`, `WebLink`, `ParseWebLink` | the Berty link codec, hand-rolled protobuf + base58 |\n| `RendezvousPoint`, `RoundPeriod`, `NextPeriod` | weshnet's rotating DHT topic derivation |\n| `SeedCommitment`, `OpenCommitment` | publish `H(seed ‖ salt)` instead of the seed |\n| `BindStatement`, `DeviceStatement`, `VerifyBind`, `VerifyDevice` | the canonical texts an account signs, and their ed25519 verification |\n| `HMACSHA256` | RFC 2104, because gno has `sha256.Sum256` but no `crypto/hmac` |\n\n**The link codec is conformance-tested**, not guessed: `TestBlobEncodingMatches\nBertyGoldenVector` reproduces the exact base58 payload from berty's own\n`links_test.go`, byte for byte. The rendezvous derivation is pinned against\nvectors computed with weshnet's `GenerateRendezvousPointForPeriod`, and the HMAC\nagainst RFC 4231, including case 6, the longer-than-block-size key.\n\n## What is deliberately absent\n\nThere is **no type here that can hold a secret**. Group secrets, device chain\nkeys, message keys and ciphertexts never touch a chain: publishing a group\nsecret hands the group to everyone, and publishing ciphertext is permanent,\nexpensive, and leaks the social graph through access patterns.\n\n## The privacy trade-off\n\nPublishing a rendezvous seed is equivalent to printing your Berty QR code on a\nbillboard: anyone can then derive today's rendezvous point and watch the DHT for\nit. That is the right trade only for an identity that *wants* to be found.\n`SeedCommitment` is the alternative: the chain attests the binding, the seed\ntravels out of band, and the rendezvous point stays private.\n\n## Cost\n\n`WebLink` is base58 over a ~70-byte payload, which is big-integer work:\n`TestWebLink` reports ~19M gas for one encode, `TestWebLinkRoundTrip` ~61M per\nencode-plus-decode. That is fine in a `Render` (a query) and worth avoiding\nper-row in a list. Signature verification is a native op and costs far less.\n\n**Live realm:** [`r/moul/x/wesh`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/wesh/v0)\n· render it at [`/r/moul/x/wesh/v0`](https://gno.land/r/moul/x/wesh/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/wesh/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/wesh/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/wesh/v0\"\ngno = \"0.9\"\n"},{"name":"hmac.gno","body":"package wesh\n\nimport \"crypto/sha256\"\n\n// blockSize is SHA-256's internal block size, the padding width HMAC uses.\nconst blockSize = 64\n\n// HMACSHA256 computes HMAC-SHA256 as specified in RFC 2104.\n//\n// gno's standard library exposes sha256.Sum256 but no streaming hash.Hash and\n// no crypto/hmac, so the construction is spelled out here:\n//\n//\tHMAC(K, m) = H((K' ⊕ opad) ‖ H((K' ⊕ ipad) ‖ m))\n//\n// with K' the key hashed down when longer than the block size, then\n// zero-padded up to it. This is the primitive weshnet's rendezvous point\n// derivation is built on, so it has to agree byte-for-byte; see\n// [RendezvousPoint].\nfunc HMACSHA256(key, msg []byte) []byte {\n\tk := key\n\tif len(k) \u003e blockSize {\n\t\tsum := sha256.Sum256(k)\n\t\tk = sum[:]\n\t}\n\n\tipad := make([]byte, blockSize)\n\topad := make([]byte, blockSize)\n\tcopy(ipad, k)\n\tcopy(opad, k)\n\tfor i := 0; i \u003c blockSize; i++ {\n\t\tipad[i] ^= 0x36\n\t\topad[i] ^= 0x5c\n\t}\n\n\tinner := sha256.Sum256(append(ipad, msg...))\n\touter := sha256.Sum256(append(opad, inner[:]...))\n\treturn outer[:]\n}\n"},{"name":"hmac_test.gno","body":"package wesh\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestHMACSHA256RFC4231 checks the HMAC construction against the published\n// RFC 4231 vectors. Case 6 matters most: its key is longer than the block\n// size, which is the branch that hashes the key down first and the one most\n// easily got wrong.\nfunc TestHMACSHA256RFC4231(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tkey  []byte\n\t\tdata []byte\n\t\twant string\n\t}{\n\t\t{\n\t\t\t\"rfc4231 case 1\",\n\t\t\trepeat(0x0b, 20),\n\t\t\t[]byte(\"Hi There\"),\n\t\t\t\"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7\",\n\t\t},\n\t\t{\n\t\t\t\"rfc4231 case 2\",\n\t\t\t[]byte(\"Jefe\"),\n\t\t\t[]byte(\"what do ya want for nothing?\"),\n\t\t\t\"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843\",\n\t\t},\n\t\t{\n\t\t\t\"rfc4231 case 6 (key longer than the block size)\",\n\t\t\trepeat(0xaa, 131),\n\t\t\t[]byte(\"Test Using Larger Than Block-Size Key - Hash Key First\"),\n\t\t\t\"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54\",\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := hex.EncodeToString(HMACSHA256(tc.key, tc.data))\n\t\tuassert.Equal(t, tc.want, got, tc.name)\n\t}\n}\n\n// repeat returns n copies of b.\nfunc repeat(b byte, n int) []byte {\n\tout := make([]byte, n)\n\tfor i := range out {\n\t\tout[i] = b\n\t}\n\treturn out\n}\n"},{"name":"link.gno","body":"package wesh\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/b58/v0\"\n)\n\n// WebLinkPrefix is the prefix of a shareable Berty web link. The fragment\n// marker is part of it on purpose: everything after '#' stays in the browser\n// and is never sent to berty.tech, so the web host never learns the identity\n// being shared.\nconst WebLinkPrefix = \"https://berty.tech/id#\"\n\n// contactKind is the human-readable link kind for a contact invite,\n// berty's BertyLink_ContactInviteV1Kind.\nconst contactKind = \"contact\"\n\n// Protobuf field numbers, from berty's api/messengertypes/messengertypes.proto\n// and weshnet's api/protocol/protocoltypes.proto. They are wire-format\n// constants: changing one silently produces a link no Berty client can read.\nconst (\n\tfieldBertyLinkBertyID = 2 // BertyLink.berty_id\n\tfieldBertyIDSeed      = 1 // BertyID.public_rendezvous_seed\n\tfieldBertyIDAccountPK = 2 // BertyID.account_pk\n)\n\nvar (\n\tErrNotAWebLink    = errors.New(\"wesh: not a berty web link\")\n\tErrNotAContactLink = errors.New(\"wesh: link is not a contact invite\")\n\tErrBadLinkPayload = errors.New(\"wesh: link payload is not a valid contact\")\n)\n\n// Blob returns the protobuf-encoded machine payload of a contact invite link:\n// a BertyLink carrying only a BertyID with the rendezvous seed and account key.\n//\n// The kind and the display name are deliberately absent. berty's MarshalLink\n// puts the kind in the human-readable path segment and the display name in the\n// query string, so a blob that carried them would not match a link produced by\n// a real Berty client. The encoding here is verified against berty's own\n// golden test vector; see link_test.gno.\nfunc (c Contact) Blob() ([]byte, error) {\n\tif err := c.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tid := appendBytesField(nil, fieldBertyIDSeed, c.Seed)\n\tid = appendBytesField(id, fieldBertyIDAccountPK, c.AccountPK)\n\treturn appendBytesField(nil, fieldBertyLinkBertyID, id), nil\n}\n\n// WebLink returns the shareable https://berty.tech/id# link for the contact.\n// Scanning or opening it in Berty starts a contact request.\nfunc (c Contact) WebLink() (string, error) {\n\tblob, err := c.Blob()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tlink := WebLinkPrefix + contactKind + \"/\" + b58.Encode(blob)\n\tif c.DisplayName != \"\" {\n\t\tlink += \"/name=\" + url.QueryEscape(c.DisplayName)\n\t}\n\treturn link, nil\n}\n\n// ParseWebLink decodes a Berty contact web link back into a [Contact].\n//\n// It accepts links with or without a trailing query segment, and ignores query\n// keys other than \"name\", matching berty's own UnmarshalLink leniency.\nfunc ParseWebLink(link string) (Contact, error) {\n\tvar c Contact\n\n\tif !strings.HasPrefix(link, WebLinkPrefix) {\n\t\treturn c, ErrNotAWebLink\n\t}\n\tparts := strings.Split(strings.TrimPrefix(link, WebLinkPrefix), \"/\")\n\tif len(parts) \u003c 2 {\n\t\treturn c, ErrNotAWebLink\n\t}\n\tif parts[0] != contactKind {\n\t\treturn c, ErrNotAContactLink\n\t}\n\tif !b58.IsValid(parts[1]) {\n\t\treturn c, ErrBadLinkPayload\n\t}\n\n\tinner, ok := lookupBytesField(b58.Decode(parts[1]), fieldBertyLinkBertyID)\n\tif !ok {\n\t\treturn c, ErrBadLinkPayload\n\t}\n\tseed, ok := lookupBytesField(inner, fieldBertyIDSeed)\n\tif !ok {\n\t\treturn c, ErrBadLinkPayload\n\t}\n\tpk, ok := lookupBytesField(inner, fieldBertyIDAccountPK)\n\tif !ok {\n\t\treturn c, ErrBadLinkPayload\n\t}\n\tc.AccountPK = pk\n\tc.Seed = seed\n\n\tif len(parts) \u003e 2 {\n\t\tc.DisplayName = queryName(parts[2])\n\t}\n\tif err := c.Validate(); err != nil {\n\t\treturn Contact{}, err\n\t}\n\treturn c, nil\n}\n\n// queryName pulls the \"name\" key out of an encoded query segment, returning \"\"\n// when it is absent or malformed. A bad display name must never fail a link\n// that is otherwise valid: the name is decoration, the keys are the payload.\nfunc queryName(q string) string {\n\tfor _, pair := range strings.Split(q, \"\u0026\") {\n\t\tif !strings.HasPrefix(pair, \"name=\") {\n\t\t\tcontinue\n\t\t}\n\t\tname, err := url.QueryUnescape(strings.TrimPrefix(pair, \"name=\"))\n\t\tif err != nil || len(name) \u003e MaxDisplayNameLen {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn name\n\t}\n\treturn \"\"\n}\n\n// appendBytesField appends a length-delimited (wire type 2) protobuf field.\n// An empty value encodes to nothing, which is what proto3 does for a zero\n// bytes field, and is why an invalid contact can never produce a short-but-\n// plausible blob: Validate has already rejected it.\nfunc appendBytesField(dst []byte, num int, val []byte) []byte {\n\tif len(val) == 0 {\n\t\treturn dst\n\t}\n\tdst = append(dst, byte(num\u003c\u003c3|2))\n\tdst = binary.AppendUvarint(dst, uint64(len(val)))\n\treturn append(dst, val...)\n}\n\n// lookupBytesField scans a protobuf message for the first length-delimited\n// field with the given number, skipping every other field whatever its wire\n// type. Unknown fields are skipped rather than rejected so a link produced by\n// a newer Berty client still parses.\nfunc lookupBytesField(buf []byte, num int) ([]byte, bool) {\n\ti := 0\n\tfor i \u003c len(buf) {\n\t\ttag, n := binary.Uvarint(buf[i:])\n\t\tif n \u003c= 0 {\n\t\t\treturn nil, false\n\t\t}\n\t\ti += n\n\t\tfieldNum := int(tag \u003e\u003e 3)\n\t\twireType := int(tag \u0026 0x7)\n\n\t\tswitch wireType {\n\t\tcase 0: // varint\n\t\t\t_, n := binary.Uvarint(buf[i:])\n\t\t\tif n \u003c= 0 {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t\ti += n\n\t\tcase 1: // 64-bit\n\t\t\tif i+8 \u003e len(buf) {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t\ti += 8\n\t\tcase 2: // length-delimited\n\t\t\tl, n := binary.Uvarint(buf[i:])\n\t\t\tif n \u003c= 0 {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t\ti += n\n\t\t\tend := i + int(l)\n\t\t\tif end \u003c i || end \u003e len(buf) {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t\tif fieldNum == num {\n\t\t\t\treturn buf[i:end], true\n\t\t\t}\n\t\t\ti = end\n\t\tcase 5: // 32-bit\n\t\t\tif i+4 \u003e len(buf) {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t\ti += 4\n\t\tdefault:\n\t\t\treturn nil, false\n\t\t}\n\t}\n\treturn nil, false\n}\n"},{"name":"link_test.gno","body":"package wesh\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/daily/b58/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// bertyGoldenBlob is the base58 payload from berty's own links_test.go\n// (\"simple-contact\"), produced by MarshalLink from\n// PublicRendezvousSeed = 16 x 0x01 and AccountPk = 16 x 0x02.\n//\n// It is the ground truth for this package's wire format. The keys are 16 bytes\n// because that test predates the length rule, so the vector is checked against\n// the raw encoder rather than through Contact.Blob, which would (correctly)\n// reject them.\nconst bertyGoldenBlob = \"3geQXHmsW9rxRfQFJdu8CEuPtWkfTWgJH13NzAoGatcnh4brusu3\"\n\nfunc TestBlobEncodingMatchesBertyGoldenVector(t *testing.T) {\n\tid := appendBytesField(nil, fieldBertyIDSeed, repeat(0x01, 16))\n\tid = appendBytesField(id, fieldBertyIDAccountPK, repeat(0x02, 16))\n\tblob := appendBytesField(nil, fieldBertyLinkBertyID, id)\n\n\tuassert.Equal(t,\n\t\t\"12240a1001010101010101010101010101010101121002020202020202020202020202020202\",\n\t\thex.EncodeToString(blob),\n\t\t\"protobuf wire bytes\")\n\tuassert.Equal(t, bertyGoldenBlob, b58.Encode(blob), \"base58 payload berty produces\")\n}\n\n// TestWebLink pins the full link for a real 32-byte identity.\nfunc TestWebLink(t *testing.T) {\n\tc := Contact{\n\t\tAccountPK: mustHex(t, testAccountPKHex),\n\t\tSeed:      mustHex(t, testSeedHex),\n\t}\n\tlink, err := c.WebLink()\n\tuassert.NoError(t, err)\n\tuassert.Equal(t,\n\t\t\"https://berty.tech/id#contact/oZBLFpzghxrATkepWvDPNX9pHYqi6BWgP45xGWhqxcwmqN2bnMMbU7UcwUuTaCcDyUvMjmWRMDWcP96bXAndcjNiAZ1Vz9X\",\n\t\tlink)\n}\n\n// TestWebLinkDisplayNameEscaping matches berty's url.Values encoding: space\n// becomes '+', and everything outside the unreserved set is percent-escaped.\nfunc TestWebLinkDisplayNameEscaping(t *testing.T) {\n\tc := Contact{\n\t\tAccountPK:   mustHex(t, testAccountPKHex),\n\t\tSeed:        mustHex(t, testSeedHex),\n\t\tDisplayName: \"Hello World!\",\n\t}\n\tlink, err := c.WebLink()\n\tuassert.NoError(t, err)\n\tuassert.True(t, endsWith(link, \"/name=Hello+World%21\"), \"display name is query-escaped: \"+link)\n}\n\nfunc TestWebLinkRoundTrip(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   Contact\n\t}{\n\t\t{\"no display name\", Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32)}},\n\t\t{\"with a display name\", Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32), DisplayName: \"gno support\"}},\n\t\t{\"name needing escapes\", Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32), DisplayName: \"a/b c\u0026d=e\"}},\n\t\t{\"leading zero bytes\", Contact{AccountPK: repeat(0x00, 32), Seed: repeat(0x00, 32)}},\n\t}\n\tfor _, tc := range cases {\n\t\tlink, err := tc.in.WebLink()\n\t\tuassert.NoError(t, err, tc.name)\n\n\t\tgot, err := ParseWebLink(link)\n\t\tuassert.NoError(t, err, tc.name)\n\t\tuassert.Equal(t, hex.EncodeToString(tc.in.AccountPK), hex.EncodeToString(got.AccountPK), tc.name+\": account key\")\n\t\tuassert.Equal(t, hex.EncodeToString(tc.in.Seed), hex.EncodeToString(got.Seed), tc.name+\": seed\")\n\t\tuassert.Equal(t, tc.in.DisplayName, got.DisplayName, tc.name+\": display name\")\n\t}\n}\n\nfunc TestParseWebLinkRejects(t *testing.T) {\n\tvalid, err := Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32)}.WebLink()\n\tuassert.NoError(t, err)\n\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant error\n\t}{\n\t\t{\"not a berty link\", \"https://example.com/id#contact/abc\", ErrNotAWebLink},\n\t\t{\"no payload segment\", WebLinkPrefix + \"contact\", ErrNotAWebLink},\n\t\t{\"a group link, not a contact\", WebLinkPrefix + \"group/\" + b58.Encode([]byte{1, 2, 3}), ErrNotAContactLink},\n\t\t{\"payload is not base58\", WebLinkPrefix + \"contact/not-base58-0OIl\", ErrBadLinkPayload},\n\t\t{\"payload is not a BertyLink\", WebLinkPrefix + \"contact/\" + b58.Encode([]byte{0xff, 0xff}), ErrBadLinkPayload},\n\t\t{\"berty's own 16-byte golden vector is too short now\", WebLinkPrefix + \"contact/\" + bertyGoldenBlob, ErrBadSeedLen},\n\t\t{\"truncated payload\", valid[:len(valid)-8], ErrBadLinkPayload},\n\t}\n\tfor _, tc := range cases {\n\t\t_, err := ParseWebLink(tc.in)\n\t\tuassert.ErrorIs(t, err, tc.want, tc.name)\n\t}\n}\n\n// TestParseWebLinkIgnoresUnknownQueryKeys matches berty's UnmarshalLink, which\n// accepts a link carrying query keys it does not know.\nfunc TestParseWebLinkIgnoresUnknownQueryKeys(t *testing.T) {\n\tlink, err := Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32)}.WebLink()\n\tuassert.NoError(t, err)\n\n\tgot, err := ParseWebLink(link + \"/foo=bar\u0026name=Alice\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"Alice\", got.DisplayName)\n}\n\n// TestLookupBytesFieldSkipsOtherWireTypes covers the decoder's skip paths: a\n// varint, a 64-bit and a 32-bit field ahead of the one being looked up.\nfunc TestLookupBytesFieldSkipsOtherWireTypes(t *testing.T) {\n\tbuf := []byte{0x08, 0x96, 0x01} // field 1, varint 150\n\tbuf = append(buf, 0x11)         // field 2, 64-bit\n\tbuf = append(buf, repeat(0xaa, 8)...)\n\tbuf = append(buf, 0x1d) // field 3, 32-bit\n\tbuf = append(buf, repeat(0xbb, 4)...)\n\tbuf = appendBytesField(buf, 4, []byte(\"found\"))\n\n\tgot, ok := lookupBytesField(buf, 4)\n\tuassert.True(t, ok, \"the length-delimited field is reachable past the others\")\n\tuassert.Equal(t, \"found\", string(got))\n\n\t_, ok = lookupBytesField(buf, 9)\n\tuassert.False(t, ok, \"an absent field is reported missing, not guessed\")\n}\n\nfunc TestBlobRejectsAnInvalidContact(t *testing.T) {\n\t_, err := Contact{AccountPK: repeat(1, 31), Seed: repeat(2, 32)}.Blob()\n\tuassert.ErrorIs(t, err, ErrBadAccountPKLen)\n}\n\nfunc endsWith(s, suffix string) bool {\n\treturn len(s) \u003e= len(suffix) \u0026\u0026 s[len(s)-len(suffix):] == suffix\n}\n"},{"name":"rendezvous.gno","body":"package wesh\n\nimport \"encoding/binary\"\n\n// DefaultRotationInterval is weshnet's rendezvous rotation period, in seconds\n// (rendezvous.DefaultRotationInterval = 24h). The rendezvous point an account\n// announces on changes once per interval, so an observer who learns one point\n// does not learn every future one.\nconst DefaultRotationInterval int64 = 86400\n\n// RoundPeriod returns the start of the rotation period containing unixSec.\n// Mirrors weshnet's rendezvous.RoundTimePeriod.\nfunc RoundPeriod(unixSec, interval int64) int64 {\n\tif interval \u003c 0 {\n\t\tinterval = -interval\n\t}\n\tif interval == 0 {\n\t\tpanic(\"wesh: rotation interval must not be zero\")\n\t}\n\treturn (unixSec / interval) * interval\n}\n\n// NextPeriod returns the start of the period after the one containing unixSec.\n// Mirrors weshnet's rendezvous.NextTimePeriod.\nfunc NextPeriod(unixSec, interval int64) int64 {\n\tif interval \u003c 0 {\n\t\tinterval = -interval\n\t}\n\treturn RoundPeriod(unixSec, interval) + interval\n}\n\n// RendezvousPoint derives the rotating DHT topic an account announces on\n// during the period starting at periodStart.\n//\n// It reproduces weshnet's rendezvous.GenerateRendezvousPointForPeriod exactly:\n//\n//\tHMAC-SHA256(key = topic ‖ seed, msg = big-endian uint64(periodStart))\n//\n// For contact requests, weshnet passes the account public key as the topic and\n// the public rendezvous seed as the seed (see swiper.WatchTopic in\n// contact_request_manager.go), which is what [Contact.RendezvousPointAt] does.\n//\n// Deriving this on chain is what makes a published identity checkable: anyone\n// can confirm that the seed in the directory really is the one the account is\n// announcing under, without trusting the directory.\nfunc RendezvousPoint(topic, seed []byte, periodStart int64) []byte {\n\tkey := make([]byte, 0, len(topic)+len(seed))\n\tkey = append(key, topic...)\n\tkey = append(key, seed...)\n\n\tbuf := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(buf, uint64(periodStart))\n\n\treturn HMACSHA256(key, buf)\n}\n\n// RendezvousPointAt returns the contact's rendezvous point for the rotation\n// period containing unixSec.\nfunc (c Contact) RendezvousPointAt(unixSec, interval int64) ([]byte, error) {\n\tif err := c.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn RendezvousPoint(c.AccountPK, c.Seed, RoundPeriod(unixSec, interval)), nil\n}\n"},{"name":"rendezvous_test.gno","body":"package wesh\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Reference vectors produced by running weshnet's own algorithm\n// (rendezvous.GenerateRendezvousPointForPeriod) against these inputs:\n// topic = accountPK, seed = seed, interval = 24h.\nconst (\n\ttestAccountPKHex = \"2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12\"\n\ttestSeedHex      = \"abababababababababababababababababababababababababababababababab\"\n)\n\nfunc TestRoundPeriod(t *testing.T) {\n\tcases := []struct {\n\t\tname     string\n\t\tunixSec  int64\n\t\tinterval int64\n\t\twant     int64\n\t}{\n\t\t{\"epoch\", 0, DefaultRotationInterval, 0},\n\t\t{\"exactly on a boundary\", 1789171200, DefaultRotationInterval, 1789171200},\n\t\t{\"one second before the next\", 1789257599, DefaultRotationInterval, 1789171200},\n\t\t{\"one second after a boundary\", 1789171201, DefaultRotationInterval, 1789171200},\n\t\t{\"a negative interval is taken as positive\", 1789257599, -DefaultRotationInterval, 1789171200},\n\t\t{\"an hourly interval\", 1789174800 + 59, 3600, 1789174800},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, RoundPeriod(tc.unixSec, tc.interval), tc.name)\n\t}\n}\n\nfunc TestNextPeriod(t *testing.T) {\n\tuassert.Equal(t, int64(1789257600), NextPeriod(1789171200, DefaultRotationInterval))\n\tuassert.Equal(t, int64(1789257600), NextPeriod(1789257599, DefaultRotationInterval))\n}\n\n// TestRendezvousPointMatchesWeshnet pins the derivation against vectors\n// computed with weshnet's implementation. A divergence here means a gno-derived\n// rendezvous point would not match the one the account actually announces on,\n// which makes a published identity unverifiable.\nfunc TestRendezvousPointMatchesWeshnet(t *testing.T) {\n\tpk := mustHex(t, testAccountPKHex)\n\tseed := mustHex(t, testSeedHex)\n\n\tcases := []struct {\n\t\tname        string\n\t\tperiodStart int64\n\t\twant        string\n\t}{\n\t\t{\n\t\t\t\"period 0\",\n\t\t\t0,\n\t\t\t\"04500fdede2a684f4e61cd67968b46ecdbf10d45604041bb7e0350572b8cc9cc\",\n\t\t},\n\t\t{\n\t\t\t\"period starting 1789171200\",\n\t\t\t1789171200,\n\t\t\t\"aad2926c39dacabaabbbde48522d043557c8945b6a2dc7b08499c112c72587da\",\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := hex.EncodeToString(RendezvousPoint(pk, seed, tc.periodStart))\n\t\tuassert.Equal(t, tc.want, got, tc.name)\n\t}\n}\n\n// TestRendezvousPointAtIsStableWithinAPeriod is the property that makes\n// rotation useful: every instant inside one interval maps to the same point,\n// and the next interval maps somewhere unrelated.\nfunc TestRendezvousPointAtIsStableWithinAPeriod(t *testing.T) {\n\tc := Contact{AccountPK: mustHex(t, testAccountPKHex), Seed: mustHex(t, testSeedHex)}\n\n\tstart, err := c.RendezvousPointAt(1789171200, DefaultRotationInterval)\n\tuassert.NoError(t, err)\n\tend, err := c.RendezvousPointAt(1789257599, DefaultRotationInterval)\n\tuassert.NoError(t, err)\n\tnext, err := c.RendezvousPointAt(1789257600, DefaultRotationInterval)\n\tuassert.NoError(t, err)\n\n\tuassert.Equal(t, hex.EncodeToString(start), hex.EncodeToString(end),\n\t\t\"the point is stable for the whole period\")\n\tuassert.False(t, hex.EncodeToString(start) == hex.EncodeToString(next),\n\t\t\"the point rotates at the period boundary\")\n}\n\nfunc TestRendezvousPointAtRejectsAnInvalidContact(t *testing.T) {\n\t_, err := Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 31)}.RendezvousPointAt(0, DefaultRotationInterval)\n\tuassert.ErrorIs(t, err, ErrBadSeedLen)\n}\n\nfunc mustHex(t *testing.T, s string) []byte {\n\tt.Helper()\n\tb, err := hex.DecodeString(s)\n\tif err != nil {\n\t\tt.Fatalf(\"bad hex fixture: %v\", err)\n\t}\n\treturn b\n}\n"},{"name":"statement.gno","body":"package wesh\n\nimport (\n\t\"crypto/ed25519\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Statement kinds. A signature is only ever valid for the kind it was made\n// under, so a binding signature can never be replayed as a device statement.\nconst (\n\tkindBind   = \"gno.wesh/v0:bind\"\n\tkindDevice = \"gno.wesh/v0:device\"\n)\n\n// Device sigchain operations.\nconst (\n\tOpAdd    = \"add\"\n\tOpRevoke = \"revoke\"\n)\n\nvar (\n\tErrBadOp        = errors.New(\"wesh: operation must be add or revoke\")\n\tErrBadSignature = errors.New(\"wesh: signature does not verify under the account key\")\n\tErrBadSeq       = errors.New(\"wesh: sequence number must not be negative\")\n\tErrBadPrevLen   = errors.New(\"wesh: previous digest must be 32 bytes\")\n)\n\n// DigestLen is the length of a statement digest (SHA-256).\nconst DigestLen = 32\n\n// ValidOp reports whether op is a known sigchain operation.\nfunc ValidOp(op string) bool { return op == OpAdd || op == OpRevoke }\n\n// BindStatement returns the canonical text an account signs, with its Wesh\n// account private key, to claim a directory entry.\n//\n// The signature is what makes a directory entry meaningful. Without it anyone\n// could publish anyone else's account key next to a seed of their choosing and\n// harvest the contact requests that followed. With it, a directory entry is a\n// statement by the account itself, verifiable by anyone, replayable nowhere:\n//\n//   - the kind prefix stops a signature made for one purpose being reused for\n//     another;\n//   - chainID stops a binding signed for a testnet being replayed on mainnet;\n//   - gnoAddr binds the Wesh identity to exactly one gno account, so a leaked\n//     signature cannot be used to claim the identity from a different address;\n//   - revision is monotonic, so an old, superseded binding cannot be replayed\n//     to roll a rotation back.\n//\n// payload is the seed for a publicly published identity, or the seed\n// commitment from [SeedCommitment] for one that keeps its rendezvous point off\n// chain. The two are indistinguishable on the wire, which is deliberate: an\n// observer cannot tell a committed identity from a published one without the\n// realm's own mode flag.\n//\n// Fields are newline-framed and hex-encoded, never concatenated raw: with\n// plain concatenation a different split of the same bytes would produce the\n// same statement.\nfunc BindStatement(chainID, gnoAddr string, accountPK, payload []byte, revision int) string {\n\tvar b strings.Builder\n\tb.WriteString(kindBind)\n\tb.WriteString(\"\\n\")\n\tb.WriteString(chainID)\n\tb.WriteString(\"\\n\")\n\tb.WriteString(gnoAddr)\n\tb.WriteString(\"\\n\")\n\tb.WriteString(hex.EncodeToString(accountPK))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(hex.EncodeToString(payload))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(strconv.Itoa(revision))\n\treturn b.String()\n}\n\n// DeviceStatement returns the canonical text an account signs to append one\n// entry to its device sigchain.\n//\n// This is the piece the Wesh protocol has no answer for. Its own documentation\n// says a device, once linked, can never be revoked: the account metadata log is\n// append-only and no authority can mark an entry void. A chain cannot undo\n// that (the ratchets are already out there and forward secrecy is a local\n// property), but it can host the record that was missing, so a revocation\n// becomes publicly visible, ordered, and attributable to the account key.\n//\n// prev is the digest of the preceding statement, or [GenesisDigest] for seq 0.\n// Chaining each entry to its predecessor means the log cannot be reordered or\n// have an entry quietly dropped: any gap changes every digest after it.\nfunc DeviceStatement(chainID string, accountPK []byte, seq int, prev []byte, op string, devicePK []byte) string {\n\tvar b strings.Builder\n\tb.WriteString(kindDevice)\n\tb.WriteString(\"\\n\")\n\tb.WriteString(chainID)\n\tb.WriteString(\"\\n\")\n\tb.WriteString(hex.EncodeToString(accountPK))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(strconv.Itoa(seq))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(hex.EncodeToString(prev))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(op)\n\tb.WriteString(\"\\n\")\n\tb.WriteString(hex.EncodeToString(devicePK))\n\treturn b.String()\n}\n\n// StatementDigest returns SHA-256 of a canonical statement. It is the value\n// the next sigchain entry chains to.\nfunc StatementDigest(statement string) []byte {\n\tsum := sha256.Sum256([]byte(statement))\n\treturn sum[:]\n}\n\n// GenesisDigest is the all-zero digest that the first sigchain entry chains to.\nfunc GenesisDigest() []byte { return make([]byte, DigestLen) }\n\n// VerifyBind checks a binding signature against the account key.\nfunc VerifyBind(chainID, gnoAddr string, accountPK, payload []byte, revision int, sig []byte) error {\n\tif len(accountPK) != AccountPKLen {\n\t\treturn ErrBadAccountPKLen\n\t}\n\tstmt := BindStatement(chainID, gnoAddr, accountPK, payload, revision)\n\tif !ed25519.Verify(accountPK, []byte(stmt), sig) {\n\t\treturn ErrBadSignature\n\t}\n\treturn nil\n}\n\n// VerifyDevice checks a sigchain entry's shape and its signature, and returns\n// the digest the next entry must chain to.\nfunc VerifyDevice(chainID string, accountPK []byte, seq int, prev []byte, op string, devicePK, sig []byte) ([]byte, error) {\n\tif len(accountPK) != AccountPKLen {\n\t\treturn nil, ErrBadAccountPKLen\n\t}\n\tif len(devicePK) != DevicePKLen {\n\t\treturn nil, ErrBadDevicePKLen\n\t}\n\tif seq \u003c 0 {\n\t\treturn nil, ErrBadSeq\n\t}\n\tif len(prev) != DigestLen {\n\t\treturn nil, ErrBadPrevLen\n\t}\n\tif !ValidOp(op) {\n\t\treturn nil, ErrBadOp\n\t}\n\tstmt := DeviceStatement(chainID, accountPK, seq, prev, op, devicePK)\n\tif !ed25519.Verify(accountPK, []byte(stmt), sig) {\n\t\treturn nil, ErrBadSignature\n\t}\n\treturn StatementDigest(stmt), nil\n}\n"},{"name":"statement_test.gno","body":"package wesh\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Fixtures. The signatures were produced with Go's crypto/ed25519 over the\n// exact statement text this package builds, using the account key whose seed\n// is 32 x 0x42, the same key as testAccountPKHex.\nconst (\n\ttestChainID = \"gnoland-1\"\n\ttestGnoAddr = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\n\ttestDev1Hex = \"0707070707070707070707070707070707070707070707070707070707070707\"\n\ttestDev2Hex = \"0909090909090909090909090909090909090909090909090909090909090909\"\n\n\tbindRev1Sig = \"4cd53e6096994d2801de1b16cfd1b2d2aa34ff35b265c53fa176cfb18c949be7\" +\n\t\t\"0078161fe2afaf503cf808b2f52a321e15a625f56b1b2d0aaaf8c460f6d64702\"\n\n\tdev0Sig = \"19d0bd2517ca6308b089196528e6c27359117b80e1972c71c25434a6f260d62a\" +\n\t\t\"703a28c2f973d89056e7c691b4f879d38e1b016745508b357d217eb54c984305\"\n\tdev0Digest = \"003570bf50d50213f9f3e9c76a8271435a8f2e4b7c24010a8e8383dedd0ed2a6\"\n\n\tdev1Sig = \"c26b338045373f7504a0d251c2126e31ff3330f08463672a82467daf4dedca51\" +\n\t\t\"1da4681715a6c3afe4115622cfcca9ec3f44d5a35f9973c3b9856cc06859810c\"\n\tdev1Digest = \"35a8219e60f6cd375e1378879de8921f9d554f054cd8a70ea2d3914b20b77bbb\"\n)\n\nfunc TestBindStatementIsCanonical(t *testing.T) {\n\tgot := BindStatement(testChainID, testGnoAddr, mustHex(t, testAccountPKHex), mustHex(t, testSeedHex), 1)\n\twant := \"gno.wesh/v0:bind\\n\" + testChainID + \"\\n\" + testGnoAddr + \"\\n\" +\n\t\ttestAccountPKHex + \"\\n\" + testSeedHex + \"\\n1\"\n\tuassert.Equal(t, want, got)\n}\n\nfunc TestVerifyBind(t *testing.T) {\n\tpk := mustHex(t, testAccountPKHex)\n\tseed := mustHex(t, testSeedHex)\n\tsig := mustHex(t, bindRev1Sig)\n\n\tuassert.NoError(t, VerifyBind(testChainID, testGnoAddr, pk, seed, 1, sig),\n\t\t\"a signature made by the account key verifies\")\n}\n\n// TestVerifyBindRejectsEveryTamperedField is the heart of the scheme: each\n// field is in the signed text precisely so that changing it invalidates the\n// signature. One case per field, so a regression names the field it broke.\nfunc TestVerifyBindRejectsEveryTamperedField(t *testing.T) {\n\tpk := mustHex(t, testAccountPKHex)\n\tseed := mustHex(t, testSeedHex)\n\tsig := mustHex(t, bindRev1Sig)\n\n\tcases := []struct {\n\t\tname    string\n\t\tchainID string\n\t\taddr    string\n\t\tpayload []byte\n\t\trev     int\n\t}{\n\t\t{\"replayed on another chain\", \"test7\", testGnoAddr, seed, 1},\n\t\t{\"claimed from another gno address\", testChainID, \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\", seed, 1},\n\t\t{\"a different seed swapped in\", testChainID, testGnoAddr, repeat(0xEE, 32), 1},\n\t\t{\"an older revision replayed\", testChainID, testGnoAddr, seed, 0},\n\t\t{\"a newer revision forged\", testChainID, testGnoAddr, seed, 2},\n\t}\n\tfor _, tc := range cases {\n\t\terr := VerifyBind(tc.chainID, tc.addr, pk, tc.payload, tc.rev, sig)\n\t\tuassert.ErrorIs(t, err, ErrBadSignature, tc.name)\n\t}\n}\n\nfunc TestVerifyBindRejectsAnotherAccountsKey(t *testing.T) {\n\terr := VerifyBind(testChainID, testGnoAddr, repeat(0x33, 32), mustHex(t, testSeedHex), 1, mustHex(t, bindRev1Sig))\n\tuassert.ErrorIs(t, err, ErrBadSignature)\n\n\terr = VerifyBind(testChainID, testGnoAddr, repeat(0x33, 31), mustHex(t, testSeedHex), 1, mustHex(t, bindRev1Sig))\n\tuassert.ErrorIs(t, err, ErrBadAccountPKLen)\n}\n\nfunc TestGenesisDigest(t *testing.T) {\n\tuassert.Equal(t, DigestLen, len(GenesisDigest()))\n\tuassert.Equal(t,\n\t\t\"0000000000000000000000000000000000000000000000000000000000000000\",\n\t\thex.EncodeToString(GenesisDigest()))\n}\n\n// TestVerifyDeviceChain walks a three-entry sigchain: add, add, revoke. Each\n// entry chains to the digest of the previous one, which is what stops an entry\n// being reordered or silently dropped.\nfunc TestVerifyDeviceChain(t *testing.T) {\n\tpk := mustHex(t, testAccountPKHex)\n\n\td0, err := VerifyDevice(testChainID, pk, 0, GenesisDigest(), OpAdd, mustHex(t, testDev1Hex), mustHex(t, dev0Sig))\n\tuassert.NoError(t, err, \"first entry\")\n\tuassert.Equal(t, dev0Digest, hex.EncodeToString(d0), \"digest the next entry must chain to\")\n\n\td1, err := VerifyDevice(testChainID, pk, 1, d0, OpAdd, mustHex(t, testDev2Hex), mustHex(t, dev1Sig))\n\tuassert.NoError(t, err, \"second entry\")\n\tuassert.Equal(t, dev1Digest, hex.EncodeToString(d1))\n}\n\nfunc TestVerifyDeviceRejectsABrokenChain(t *testing.T) {\n\tpk := mustHex(t, testAccountPKHex)\n\tdev1 := mustHex(t, testDev1Hex)\n\tdev2 := mustHex(t, testDev2Hex)\n\n\tcases := []struct {\n\t\tname    string\n\t\tseq     int\n\t\tprev    []byte\n\t\top      string\n\t\tdevice  []byte\n\t\tsig     string\n\t\twantErr error\n\t}{\n\t\t{\"wrong previous digest\", 1, GenesisDigest(), OpAdd, dev2, dev1Sig, ErrBadSignature},\n\t\t{\"wrong sequence number\", 2, mustHexRaw(dev0Digest), OpAdd, dev2, dev1Sig, ErrBadSignature},\n\t\t{\"operation flipped to revoke\", 0, GenesisDigest(), OpRevoke, dev1, dev0Sig, ErrBadSignature},\n\t\t{\"a different device substituted\", 0, GenesisDigest(), OpAdd, dev2, dev0Sig, ErrBadSignature},\n\t\t{\"unknown operation\", 0, GenesisDigest(), \"delete\", dev1, dev0Sig, ErrBadOp},\n\t\t{\"negative sequence\", -1, GenesisDigest(), OpAdd, dev1, dev0Sig, ErrBadSeq},\n\t\t{\"short previous digest\", 0, repeat(0, 31), OpAdd, dev1, dev0Sig, ErrBadPrevLen},\n\t\t{\"short device key\", 0, GenesisDigest(), OpAdd, repeat(7, 31), dev0Sig, ErrBadDevicePKLen},\n\t}\n\tfor _, tc := range cases {\n\t\t_, err := VerifyDevice(testChainID, pk, tc.seq, tc.prev, tc.op, tc.device, mustHexRaw(tc.sig))\n\t\tuassert.ErrorIs(t, err, tc.wantErr, tc.name)\n\t}\n}\n\nfunc TestValidOp(t *testing.T) {\n\tuassert.True(t, ValidOp(OpAdd))\n\tuassert.True(t, ValidOp(OpRevoke))\n\tuassert.False(t, ValidOp(\"Add\"), \"operations are case-sensitive\")\n\tuassert.False(t, ValidOp(\"\"))\n}\n\nfunc mustHexRaw(s string) []byte {\n\tb, err := hex.DecodeString(s)\n\tif err != nil {\n\t\tpanic(\"bad hex fixture: \" + s)\n\t}\n\treturn b\n}\n"},{"name":"wesh.gno","body":"// Package wesh implements the publishable, non-secret half of the Wesh\n// protocol (weshnet, the network layer behind Berty) as a pure gno library.\n//\n// # What this is, and what it deliberately is not\n//\n// Wesh is an off-grid, peer-to-peer, end-to-end-encrypted messaging protocol.\n// A public blockchain is the opposite of that in almost every dimension:\n// globally replicated, permanent, publicly readable and totally ordered. So\n// \"put Wesh on chain\" is the wrong goal, and this package does not pursue it.\n//\n// What a chain *is* good at is the one thing Wesh has no answer for: an\n// authenticated, ordered, publicly auditable record that no single party owns.\n// Wesh has three gaps of exactly that shape:\n//\n//  1. A Berty identity travels out of band, as a QR code or a\n//     https://berty.tech/id# link. There is no way to look one up, and the\n//     web prefix is a single host that can be blocked or spoofed.\n//  2. Resetting the public rendezvous seed (ContactRequestResetReference)\n//     silently invalidates every link ever shared. There is no revocation\n//     channel, so a business card keeps pointing at a dead rendezvous point.\n//  3. A device, once linked to an account, can never be revoked. The Wesh\n//     protocol documentation states this outright. The account metadata log is\n//     append-only and there is no authority that can mark an entry void.\n//\n// This package carries the pieces needed to address those on chain, and\n// nothing else. Everything here is public by construction:\n//\n//   - [Contact], the publishable identity, weshnet's ShareableContact\n//     (account public key + public rendezvous seed + display name).\n//   - The Berty link codec, byte-compatible with berty's own MarshalLink.\n//   - [RendezvousPoint], the rotating DHT address derivation.\n//   - The canonical statements an account signs to bind itself to a gno\n//     address, rotate its seed, and append to a device sigchain.\n//\n// # What must never reach a chain\n//\n// Group secrets (weshnet's Group.secret, Group.link_key), device chain keys,\n// message keys, ciphertexts. Publishing a group secret hands the group to\n// everyone; publishing ciphertext is permanent, expensive, and leaks the\n// social graph through access patterns. This package has no type that can\n// hold one, which is the point: there is no struct field here for a secret to\n// accidentally land in.\n//\n// # The privacy trade-off, stated plainly\n//\n// Publishing a rendezvous seed is equivalent to printing your Berty QR code on\n// a billboard. Anyone can then derive today's rendezvous point with\n// [RendezvousPoint] and watch the DHT for who shows up. That is a real\n// deanonymization surface, and it is why publication must be an explicit,\n// opt-in act for an identity that *wants* to be found: a support line, a shop,\n// a DAO's public channel.\n//\n// For an identity that does not want that, [SeedCommitment] publishes\n// H(seed ‖ salt) instead. The chain then proves that a seed handed over out of\n// band really does belong to the named account, without broadcasting the\n// rendezvous point to the world.\n//\n// Live realm using this library: [r/moul/x/wesh](/r/moul/x/wesh/v0).\npackage wesh\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n)\n\nconst (\n\t// SeedLen is the length of a public rendezvous seed. Matches weshnet's\n\t// protocoltypes.RendezvousSeedLength.\n\tSeedLen = 32\n\n\t// AccountPKLen is the length of an account public key. weshnet validates\n\t// it with libp2p's UnmarshalEd25519PublicKey, which accepts raw 32-byte\n\t// ed25519 public keys only.\n\tAccountPKLen = 32\n\n\t// DevicePKLen is the length of a device public key: also a raw ed25519\n\t// public key.\n\tDevicePKLen = 32\n\n\t// MaxDisplayNameLen bounds the display name so a link stays scannable and\n\t// gas stays predictable. Not a protocol constant.\n\tMaxDisplayNameLen = 64\n)\n\nvar (\n\tErrBadSeedLen        = errors.New(\"wesh: public rendezvous seed must be 32 bytes\")\n\tErrBadAccountPKLen   = errors.New(\"wesh: account public key must be a raw 32-byte ed25519 key\")\n\tErrBadDevicePKLen    = errors.New(\"wesh: device public key must be a raw 32-byte ed25519 key\")\n\tErrDisplayNameTooLong = errors.New(\"wesh: display name exceeds MaxDisplayNameLen\")\n\tErrBadCommitmentLen  = errors.New(\"wesh: seed commitment must be 32 bytes\")\n\tErrBadHex            = errors.New(\"wesh: value is not valid hex\")\n)\n\n// Contact is the publishable identity of a Wesh account: weshnet's\n// ShareableContact. It is everything a stranger needs to send a contact\n// request, and it contains no secret.\n//\n// AccountPK is the raw ed25519 account public key. Seed is the public\n// rendezvous seed; together they derive the rotating rendezvous point the\n// account announces on, see [RendezvousPoint]. DisplayName is free-form app\n// metadata and is not authenticated by anything.\ntype Contact struct {\n\tAccountPK   []byte\n\tSeed        []byte\n\tDisplayName string\n}\n\n// Validate applies weshnet's own ShareableContact.CheckFormat rules: the seed\n// must be exactly SeedLen bytes, and the account key must be a raw ed25519\n// public key. It deliberately does not verify that AccountPK is a valid curve\n// point; that costs a scalar multiplication and the chain gets the same\n// guarantee for free the first time it verifies a signature under the key.\nfunc (c Contact) Validate() error {\n\tif len(c.Seed) != SeedLen {\n\t\treturn ErrBadSeedLen\n\t}\n\tif len(c.AccountPK) != AccountPKLen {\n\t\treturn ErrBadAccountPKLen\n\t}\n\tif len(c.DisplayName) \u003e MaxDisplayNameLen {\n\t\treturn ErrDisplayNameTooLong\n\t}\n\treturn nil\n}\n\n// SeedCommitment returns H(seed ‖ salt), the value published instead of the\n// seed itself when an account wants the chain to attest the binding without\n// broadcasting its rendezvous point.\n//\n// The salt is not optional: a seed is 32 bytes of entropy, but a commitment\n// with no salt is a deterministic function of the seed, so two accounts that\n// (impossibly, but still) shared a seed would be linkable, and a seed later\n// disclosed out of band retroactively confirms every past commitment. The salt\n// keeps disclosure a deliberate act.\nfunc SeedCommitment(seed, salt []byte) ([]byte, error) {\n\tif len(seed) != SeedLen {\n\t\treturn nil, ErrBadSeedLen\n\t}\n\tbuf := make([]byte, 0, len(seed)+len(salt))\n\tbuf = append(buf, seed...)\n\tbuf = append(buf, salt...)\n\tsum := sha256.Sum256(buf)\n\treturn sum[:], nil\n}\n\n// OpenCommitment reports whether commitment is H(seed ‖ salt).\n//\n// The comparison is constant-time over the digest: a short-circuiting compare\n// leaks, through gas, how many leading bytes of a guess were right.\nfunc OpenCommitment(commitment, seed, salt []byte) bool {\n\twant, err := SeedCommitment(seed, salt)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn constantTimeEqual(commitment, want)\n}\n\n// constantTimeEqual compares two byte slices without an early return.\nfunc constantTimeEqual(a, b []byte) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tvar diff byte\n\tfor i := 0; i \u003c len(a); i++ {\n\t\tdiff |= a[i] ^ b[i]\n\t}\n\treturn diff == 0\n}\n\n// Every key this package handles is 32 bytes, so a single length-checking\n// helper cannot say which one was wrong. These four wrappers exist so the\n// error a realm surfaces names the field the caller actually got wrong.\n\n// DecodeAccountPK parses a hex-encoded account public key.\nfunc DecodeAccountPK(s string) ([]byte, error) {\n\treturn decodeFixed(s, AccountPKLen, ErrBadAccountPKLen)\n}\n\n// DecodeSeed parses a hex-encoded public rendezvous seed.\nfunc DecodeSeed(s string) ([]byte, error) {\n\treturn decodeFixed(s, SeedLen, ErrBadSeedLen)\n}\n\n// DecodeDevicePK parses a hex-encoded device public key.\nfunc DecodeDevicePK(s string) ([]byte, error) {\n\treturn decodeFixed(s, DevicePKLen, ErrBadDevicePKLen)\n}\n\n// DecodeCommitment parses a hex-encoded seed commitment.\nfunc DecodeCommitment(s string) ([]byte, error) {\n\treturn decodeFixed(s, DigestLen, ErrBadCommitmentLen)\n}\n\n// decodeFixed parses hex and enforces an exact byte length. Realms take keys\n// as hex strings because that is what a transaction argument can carry; this\n// is the single place the length rule is applied.\nfunc decodeFixed(s string, want int, badLen error) ([]byte, error) {\n\tb, err := hex.DecodeString(s)\n\tif err != nil {\n\t\treturn nil, ErrBadHex\n\t}\n\tif len(b) != want {\n\t\treturn nil, badLen\n\t}\n\treturn b, nil\n}\n"},{"name":"wesh_test.gno","body":"package wesh\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestContactValidate(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   Contact\n\t\twant error\n\t}{\n\t\t{\"well-formed\", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 32)}, nil},\n\t\t{\"with a display name\", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 32), DisplayName: \"gno\"}, nil},\n\t\t{\"seed too short\", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 31)}, ErrBadSeedLen},\n\t\t{\"seed too long\", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 33)}, ErrBadSeedLen},\n\t\t{\"no seed\", Contact{AccountPK: repeat(1, 32)}, ErrBadSeedLen},\n\t\t{\"account key too short\", Contact{AccountPK: repeat(1, 31), Seed: repeat(2, 32)}, ErrBadAccountPKLen},\n\t\t{\"no account key\", Contact{Seed: repeat(2, 32)}, ErrBadAccountPKLen},\n\t\t{\n\t\t\t\"display name too long\",\n\t\t\tContact{AccountPK: repeat(1, 32), Seed: repeat(2, 32), DisplayName: string(make([]byte, MaxDisplayNameLen+1))},\n\t\t\tErrDisplayNameTooLong,\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\terr := tc.in.Validate()\n\t\tif tc.want == nil {\n\t\t\tuassert.NoError(t, err, tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.ErrorIs(t, err, tc.want, tc.name)\n\t}\n}\n\nfunc TestSeedCommitment(t *testing.T) {\n\tseed := mustHex(t, testSeedHex)\n\tsalt := []byte(\"a-16-byte-salt!!\")\n\n\tc, err := SeedCommitment(seed, salt)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, DigestLen, len(c))\n\n\tagain, err := SeedCommitment(seed, salt)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, string(c), string(again), \"the commitment is deterministic\")\n\n\tuassert.True(t, OpenCommitment(c, seed, salt), \"the correct opening verifies\")\n\tuassert.False(t, OpenCommitment(c, seed, []byte(\"another-salt!!!!\")), \"a wrong salt does not open it\")\n\tuassert.False(t, OpenCommitment(c, repeat(0xEE, 32), salt), \"a wrong seed does not open it\")\n\tuassert.False(t, OpenCommitment(c[:31], seed, salt), \"a truncated commitment does not open it\")\n}\n\nfunc TestSeedCommitmentRejectsABadSeed(t *testing.T) {\n\t_, err := SeedCommitment(repeat(1, 31), []byte(\"salt\"))\n\tuassert.ErrorIs(t, err, ErrBadSeedLen)\n}\n\n// TestSeedCommitmentIsSaltSeparated guards the length-extension style\n// ambiguity: without distinct inputs, (seed, \"ab\") and (seed+\"a\", \"b\") would\n// collide. The seed is fixed-length, which resolves it, and this pins that.\nfunc TestSeedCommitmentDependsOnTheSplit(t *testing.T) {\n\tseed := repeat(0xAA, 32)\n\ta, _ := SeedCommitment(seed, []byte(\"ab\"))\n\tb, _ := SeedCommitment(seed, []byte(\"abc\"))\n\tuassert.False(t, string(a) == string(b))\n}\n\nfunc TestDecodeHelpers(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tfn   func(string) ([]byte, error)\n\t\tin   string\n\t\terr  error\n\t}{\n\t\t{\"account key\", DecodeAccountPK, testAccountPKHex, nil},\n\t\t{\"seed\", DecodeSeed, testSeedHex, nil},\n\t\t{\"device key\", DecodeDevicePK, testSeedHex, nil},\n\t\t{\"commitment\", DecodeCommitment, testSeedHex, nil},\n\t\t{\"account key, not hex\", DecodeAccountPK, \"zzzz\", ErrBadHex},\n\t\t{\"account key, odd length\", DecodeAccountPK, \"abc\", ErrBadHex},\n\t\t{\"account key, wrong length\", DecodeAccountPK, \"abcd\", ErrBadAccountPKLen},\n\t\t{\"seed, wrong length\", DecodeSeed, \"abcd\", ErrBadSeedLen},\n\t\t{\"device key, wrong length\", DecodeDevicePK, \"abcd\", ErrBadDevicePKLen},\n\t\t{\"commitment, wrong length\", DecodeCommitment, \"abcd\", ErrBadCommitmentLen},\n\t}\n\tfor _, tc := range cases {\n\t\tgot, err := tc.fn(tc.in)\n\t\tif tc.err == nil {\n\t\t\tuassert.NoError(t, err, tc.name)\n\t\t\tuassert.Equal(t, 32, len(got), tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.ErrorIs(t, err, tc.err, tc.name)\n\t}\n}\n"}]},"send":"","max_deposit":"19000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"xdao","path":"gno.land/p/moul/xdao/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/xdao`\n\n\u003e 🚧 **Partial implementation.** 7 of the 14 functions\n\u003e `panic(\"not implemented\")`, `Render` returns the literal string `\"TODO\"`.\n\u003e The constructor and the admin list work; nothing that touches proposals does.\n\n`WhitelistDAO` implements [`p/moul/udao`](../udao)'s `DAO` interface with the\nsimplest possible governance: a flat list of trusted admins.\n\n```go\nvar _ udao.DAO = (*WhitelistDAO)(nil)\n\nfunc NewWhitelistDAO() *WhitelistDAO   // seeds admins with the calling realm\nfunc (d WhitelistDAO) ListAdmins() []address\n```\n\nEverything else (`Propose`, `Execute`, `GetProposal`, `GetProposalStatus`,\n`AddAdmin`, `DelAdmin`) panics.\n\n## Why a \"DAO\" that is not decentralized\n\nTwo honest uses, both stated in the source:\n\n1. **Bootstrapping.** A realm designed to be DAO-governed needs *something* to\n   govern it on day one. A whitelist satisfies the interface, so the realm can\n   ship, and the whitelist can later replace itself with a real DAO through the\n   same interface. No migration, no second code path.\n2. **One person, several keys.** Someone holding keys on different machines can\n   present as a single entity without a multisig ceremony for each action.\n\nIt is not a DAO, and the name says so.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/xdao/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/xdao/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/xdao/v0\"\ngno = \"0.9\"\n"},{"name":"xdao.gno","body":"package xdao\n\nimport (\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/udao/v0\"\n)\n\n// DAO is a whitelist system that implements the udao.DAO interface.\n// It can allow a trusted list of addresses to share the administration of realms that are designed to be managed by \"DAOs\".\n// It's not a DAO per say. But makes sense to be used to bootstrap a realm until the DAO can replace itself with a really decnetralized autonomous organization. Asan inception.\n// It's also useful for people who manages multiple keys, like on different computers so they can simulte being a single entity while managing several addresses.\ntype WhitelistDAO struct {\n\tadmins []address // for the sake of simplicity and because this simple DAO implementation isn't designed to scale, we just keep a simple slice\n}\n\n// check that DAO implements the udao.DAO interface.\nvar _ udao.DAO = (*WhitelistDAO)(nil)\n\nfunc NewWhitelistDAO() *WhitelistDAO {\n\tcaller := unsafe.PreviousRealm().Address()\n\treturn \u0026WhitelistDAO{\n\t\tadmins: []address{caller},\n\t}\n}\n\n// udao.DAO methods\n//\n\nfunc (d *WhitelistDAO) Propose(prop udao.Proposal) (uint64, error) { panic(\"not implemented\") }\n\nfunc (d WhitelistDAO) GetProposalStatus(id uint64) (udao.ProposalStatus, error) {\n\tpanic(\"not implemented\")\n}\nfunc (d *WhitelistDAO) Execute(id uint64) error                     { panic(\"not implemented\") }\nfunc (d WhitelistDAO) GetProposal(id uint64) (udao.Proposal, error) { panic(\"not implemented\") }\n\n// other methods\n//\n\nfunc (d *WhitelistDAO) AddAdmin(addr address) { panic(\"not implemented\") }\nfunc (d *WhitelistDAO) DelAdmin(addr address) { panic(\"not implemented\") }\nfunc (d WhitelistDAO) ListAdmins() []address  { return d.admins[:] }\nfunc (d WhitelistDAO) Render(path string) string  { return \"TODO\" }\n"},{"name":"xdao_test.gno","body":"package xdao\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\n\t\"gno.land/p/moul/udao/v0\"\n)\n\n// WhitelistDAO is a partial implementation: the constructor, ListAdmins and\n// Render work; the udao.DAO proposal methods and the admin mutators are still\n// `panic(\"not implemented\")`. Pin both halves.\n\nvar alice = testutils.TestAddress(\"alice\")\n\n// NewWhitelistDAO reads unsafe.PreviousRealm(), which needs a real realm frame:\n// a user realm gives \"frame not found: cannot seek beyond origin caller override\".\nfunc TestNewWhitelistDAOSeedsCallerAsAdmin(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test/daoone\"))\n\td := NewWhitelistDAO()\n\n\tadmins := d.ListAdmins()\n\tuassert.Equal(t, 1, len(admins), \"the creator is the only admin\")\n\tuassert.True(t, admins[0].IsValid(), \"the sole admin is a valid address\")\n}\n\n// Note: caller-sensitivity of NewWhitelistDAO is NOT asserted here — see the\n// same limitation described in p/moul/safe/v0's tests: from a `p/` test package\n// unsafe.PreviousRealm() resolves to the origin regardless of SetRealm.\n\nfunc TestListAdminsReflectsState(t *testing.T) {\n\tbob := testutils.TestAddress(\"bob\")\n\td := \u0026WhitelistDAO{admins: []address{alice, bob}}\n\n\tadmins := d.ListAdmins()\n\tuassert.Equal(t, 2, len(admins))\n\tuassert.Equal(t, alice.String(), admins[0].String())\n\tuassert.Equal(t, bob.String(), admins[1].String())\n}\n\nfunc TestRenderPlaceholder(t *testing.T) {\n\td := \u0026WhitelistDAO{admins: []address{alice}}\n\t// Still a placeholder — pinned so replacing it is a visible change.\n\tuassert.Equal(t, \"TODO\", d.Render(\"\"))\n\tuassert.Equal(t, \"TODO\", d.Render(\"/anything\"))\n}\n\n// TestImplementsUDAO is the compile-time assertion the source makes with\n// `var _ udao.DAO = (*WhitelistDAO)(nil)`, restated as a test.\nfunc TestImplementsUDAO(t *testing.T) {\n\tvar _ udao.DAO = (*WhitelistDAO)(nil)\n\tuassert.True(t, true, \"WhitelistDAO implements udao.DAO\")\n}\n\nfunc TestUnimplementedMethodsPanic(cur realm, t *testing.T) {\n\td := \u0026WhitelistDAO{admins: []address{alice}}\n\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { d.Propose(nil) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { d.GetProposalStatus(0) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { d.Execute(0) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { d.GetProposal(0) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { d.AddAdmin(alice) })\n\tuassert.PanicsWithMessage(t, cur, \"not implemented\", func() { d.DelAdmin(alice) })\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"1494638200","gas_fee":"4483914ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"qITsu0XMno1mpVCUC3JTtKGZeMyby4AAuChkfOOr2bgPuVOe0pZhUHMYd8avhZHm0sucf8l126GpYs66HEIWig=="}],"memo":""},"metadata":{"timestamp":"1790960263"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rc","path":"gno.land/p/moul/x/plan9/rc/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/plan9/rc/v0`\n\n**A small shell over a Plan 9 [namespace](../../ns/v0)**: `ls`, `cat`, `stat`,\n`ns`, `bind`, `mount`, `unmount`, `mkdir`, `rm`, `echo`, `cd`, `pwd`, `walk`,\n`help`.\n\n```go\nimport rc \"gno.land/p/moul/x/plan9/rc/v0\"\n\nsh, fs := rc.NewMemShell(\"g1...\", rc.ReadWrite, runtime.ChainHeight)\nout, err := sh.Run(\"bind -ac /srv/dev /dev; echo hello \u003e /tmp/greeting; ls -l /\")\n```\n\nA namespace you cannot inspect is a namespace you cannot trust. Everything here\noperates on an `ns.Ns` and returns text, so one realm's `Render` becomes a file\nbrowser and one transaction becomes a shell command.\n\n**The mode split is the security model.** A shell in `ReadOnly` mode refuses\nevery mutating command, which is what lets a realm expose it through `Render`,\nwhere mutating anything would be a bug, while the same code backs a crossing\n`Exec` that may write.\n\n**On the first error the run stops and returns it.** A realm should let that\nerror panic, so a half-applied command line reverts with its transaction rather\nthan leaving a namespace nobody asked for.\n\nTwo commands exist to make a namespace legible rather than to do work:\n\n- **`ns`** prints the mount table in `ns(1)` format.\n- **`walk /bin/rc`** prints how each element resolves, with the union width per\n  step. It is where a bind stops being magic: the width column says exactly\n  where one took effect, and that a union is top level only.\n\nQuoting follows rc: single quotes, with `''` inside a quoted string standing for\none literal quote. Commands are separated by `;` or newlines, and quoting is\nrespected when splitting them. `MaxCommands` (32) bounds one run.\n\n**Live demo:** [`r/moul/x/plan9/ns`](../../../../../r/moul/x/plan9/ns/v0)\nrenders it. Design and analysis:\n[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\n\n---\n\n**Not affiliated with Plan 9.** Plan 9 from Bell Labs is the work of the\nComputing Science Research Center at Bell Labs; the name and the marks are\ntheirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org).\nThis package borrows the vocabulary and none of the code: it is an independent\nhomage, asking what that ecosystem's spirit looks like on a chain. Full\nattribution: [NOTICE](../../../../../NOTICE.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/plan9/rc/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/plan9/rc/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/plan9/rc/v0\"\ngno = \"0.9\"\n"},{"name":"rc.gno","body":"// Package rc is a small shell over a Plan 9 namespace.\n//\n// It exists because a namespace you cannot inspect is a namespace you cannot\n// trust. Everything here operates on a gno.land/p/moul/x/plan9/ns namespace\n// and returns text, so one realm's Render becomes a file browser and one\n// transaction becomes a shell command:\n//\n//\tExec(\"bind -a /srv/dev /dev; echo hello \u003e /tmp/greeting\")\n//\n// The mode split is the security model. A Shell in ReadOnly mode refuses every\n// mutating command, which is what lets a realm expose the shell through\n// Render, where mutating anything would be a bug, while the same code backs a\n// crossing Exec that may write.\n//\n// Quoting follows rc: single quotes, with ” inside a quoted string standing\n// for one literal quote. Commands are separated by ';' or newlines, and\n// quoting is respected when splitting them.\n//\n// On the first error the run STOPS and returns it. A realm should let that\n// error panic, so a half-applied command line reverts with the transaction\n// rather than leaving the namespace in a state nobody asked for.\n//\n// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research\n// Center at Bell Labs; the name and the marks are theirs, and the copyright is\n// held by the Plan 9 Foundation (https://p9f.org). This package is not\n// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9\n// code: it borrows the vocabulary so that the design reads without a glossary,\n// and it is an homage, asking what that ecosystem's spirit looks like on a\n// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.\npackage rc\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\tmemfs \"gno.land/p/moul/x/plan9/memfs/v0\"\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n\tns \"gno.land/p/moul/x/plan9/ns/v0\"\n)\n\n// Mode decides whether mutating commands are allowed.\ntype Mode uint8\n\n// Shell modes.\nconst (\n\tReadOnly  Mode = 0\n\tReadWrite Mode = 1\n)\n\nvar (\n\t// ErrReadOnly is returned when a mutating command runs in ReadOnly mode.\n\tErrReadOnly = errors.New(\"read-only shell\")\n\t// ErrUsage reports a malformed command line.\n\tErrUsage = errors.New(\"usage\")\n\t// ErrUnknown reports a command this shell does not have.\n\tErrUnknown = errors.New(\"command not found\")\n\t// ErrQuote reports an unterminated quoted string.\n\tErrQuote = errors.New(\"unterminated '\")\n)\n\n// MaxCommands bounds one run, so a single call cannot loop the VM.\nconst MaxCommands = 32\n\n// Shell runs commands against one namespace.\ntype Shell struct {\n\tns   *ns.Ns\n\tmode Mode\n\tnow  func() int64\n}\n\n// New returns a shell over n. now supplies the block height stamped on writes\n// and may be nil in ReadOnly mode.\nfunc New(n *ns.Ns, mode Mode, now func() int64) *Shell {\n\treturn \u0026Shell{ns: n, mode: mode, now: now}\n}\n\n// Ns returns the namespace the shell operates on.\nfunc (s *Shell) Ns() *ns.Ns { return s.ns }\n\nfunc (s *Shell) clock() int64 {\n\tif s.now == nil {\n\t\treturn 0\n\t}\n\treturn s.now()\n}\n\nfunc (s *Shell) writable() error {\n\tif s.mode != ReadWrite {\n\t\treturn ErrReadOnly\n\t}\n\treturn nil\n}\n\n// Run executes a command line and returns its output. Execution stops at the\n// first error.\nfunc (s *Shell) Run(line string) (string, error) {\n\tcmds, err := splitCommands(line)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(cmds) \u003e MaxCommands {\n\t\treturn \"\", errors.New(\"too many commands in one line\")\n\t}\n\tvar out strings.Builder\n\tfor _, c := range cmds {\n\t\ttoks, err := tokenize(c)\n\t\tif err != nil {\n\t\t\treturn out.String(), err\n\t\t}\n\t\tif len(toks) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttext, err := s.run1(toks)\n\t\tout.WriteString(text)\n\t\tif err != nil {\n\t\t\treturn out.String(), errors.New(toks[0] + \": \" + err.Error())\n\t\t}\n\t}\n\treturn out.String(), nil\n}\n\nfunc (s *Shell) run1(toks []string) (string, error) {\n\tcmd, args := toks[0], toks[1:]\n\tswitch cmd {\n\tcase \"help\":\n\t\treturn help, nil\n\tcase \"pwd\":\n\t\treturn s.ns.Cwd() + \"\\n\", nil\n\tcase \"cd\":\n\t\treturn \"\", s.cd(args)\n\tcase \"ns\":\n\t\treturn s.ns.String(), nil\n\tcase \"ls\":\n\t\treturn s.ls(args)\n\tcase \"cat\":\n\t\treturn s.cat(args)\n\tcase \"stat\":\n\t\treturn s.stat(args)\n\tcase \"walk\":\n\t\treturn s.walk(args)\n\tcase \"bind\", \"mount\":\n\t\treturn \"\", s.bind(cmd, args)\n\tcase \"unmount\", \"unbind\":\n\t\treturn \"\", s.unmount(args)\n\tcase \"mkdir\":\n\t\treturn \"\", s.mkdir(args)\n\tcase \"rm\":\n\t\treturn \"\", s.rm(args)\n\tcase \"echo\":\n\t\treturn s.echo(args)\n\t}\n\treturn \"\", ErrUnknown\n}\n\nconst help = `bind [-a|-b|-c] new old   make new visible at old (-b before, -a after, -c creates)\ncat file...               print files\ncd [dir]                  change directory\necho [-n] word... [\u003e|\u003e\u003e file]\nls [-l] [-u] [path...]    list; -l long, -u collapse union duplicates\nmkdir path...             create directories\nmount                     synonym for bind\nns                        print the namespace\npwd                       print the working directory\nrm path...                remove files and empty directories\nstat path...              print the 9P stat of each path\nunmount [new] old         undo a binding\nwalk path                 show how each element of path resolves\n`\n\nfunc (s *Shell) cd(args []string) error {\n\tif len(args) == 0 {\n\t\treturn s.ns.Cd(\"/\")\n\t}\n\tif len(args) \u003e 1 {\n\t\treturn ErrUsage\n\t}\n\treturn s.ns.Cd(args[0])\n}\n\nfunc (s *Shell) ls(args []string) (string, error) {\n\tlong, unique, paths := false, false, []string{}\n\tfor _, a := range args {\n\t\tif strings.HasPrefix(a, \"-\") \u0026\u0026 len(a) \u003e 1 {\n\t\t\tfor _, r := range a[1:] {\n\t\t\t\tswitch r {\n\t\t\t\tcase 'l':\n\t\t\t\t\tlong = true\n\t\t\t\tcase 'u':\n\t\t\t\t\tunique = true\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"\", ErrUsage\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tpaths = append(paths, a)\n\t}\n\tif len(paths) == 0 {\n\t\tpaths = []string{s.ns.Cwd()}\n\t}\n\tvar out strings.Builder\n\tfor i, p := range paths {\n\t\tst, err := s.ns.Stat(p)\n\t\tif err != nil {\n\t\t\treturn out.String(), err\n\t\t}\n\t\tif len(paths) \u003e 1 {\n\t\t\tif i \u003e 0 {\n\t\t\t\tout.WriteString(\"\\n\")\n\t\t\t}\n\t\t\tout.WriteString(s.ns.Abs(p) + \":\\n\")\n\t\t}\n\t\tif !st.IsDir() {\n\t\t\tout.WriteString(entryLine(st, long))\n\t\t\tcontinue\n\t\t}\n\t\tents, err := s.ns.ReadDir(p, unique)\n\t\tif err != nil {\n\t\t\treturn out.String(), err\n\t\t}\n\t\tfor _, e := range ents {\n\t\t\tout.WriteString(entryLine(e, long))\n\t\t}\n\t}\n\treturn out.String(), nil\n}\n\nfunc entryLine(st ninep.Stat, long bool) string {\n\tif long {\n\t\treturn st.Line() + \"\\n\"\n\t}\n\tname := st.Name\n\tif st.IsDir() \u0026\u0026 name != \"/\" {\n\t\tname += \"/\"\n\t}\n\treturn name + \"\\n\"\n}\n\nfunc (s *Shell) cat(args []string) (string, error) {\n\tif len(args) == 0 {\n\t\treturn \"\", ErrUsage\n\t}\n\tvar out strings.Builder\n\tfor _, p := range args {\n\t\tdata, err := s.ns.ReadFile(p)\n\t\tif err != nil {\n\t\t\treturn out.String(), err\n\t\t}\n\t\tout.WriteString(data)\n\t}\n\treturn out.String(), nil\n}\n\nfunc (s *Shell) stat(args []string) (string, error) {\n\tif len(args) == 0 {\n\t\targs = []string{s.ns.Cwd()}\n\t}\n\tvar out strings.Builder\n\tfor _, p := range args {\n\t\tst, err := s.ns.Stat(p)\n\t\tif err != nil {\n\t\t\treturn out.String(), err\n\t\t}\n\t\tmembers, err := s.ns.Resolve(p)\n\t\tif err != nil {\n\t\t\treturn out.String(), err\n\t\t}\n\t\tout.WriteString(s.ns.Abs(p) + \" \" + st.Qid.String() +\n\t\t\t\" \" + st.Mode.String() +\n\t\t\t\" uid=\" + st.Uid +\n\t\t\t\" length=\" + strconv.FormatInt(st.Length, 10) +\n\t\t\t\" mtime=\" + strconv.FormatInt(st.Mtime, 10) +\n\t\t\t\" union=\" + strconv.Itoa(len(members)) + \"\\n\")\n\t}\n\treturn out.String(), nil\n}\n\n// walk shows the resolution of each element, which is where a namespace stops\n// being magic: the union width column says exactly when a bind took effect.\nfunc (s *Shell) walk(args []string) (string, error) {\n\tif len(args) != 1 {\n\t\treturn \"\", ErrUsage\n\t}\n\tabs := s.ns.Abs(args[0])\n\tvar out strings.Builder\n\tprefix := \"/\"\n\treport := func(p string) error {\n\t\tst, err := s.ns.Stat(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmembers, err := s.ns.Resolve(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout.WriteString(pad(p, 24) + \" \" + st.Qid.String() + \" \" +\n\t\t\tst.Mode.String() + \" union=\" + strconv.Itoa(len(members)) + \"\\n\")\n\t\treturn nil\n\t}\n\tif err := report(\"/\"); err != nil {\n\t\treturn out.String(), err\n\t}\n\tfor _, e := range ninep.Elems(abs) {\n\t\tprefix = ninep.Join(prefix, e)\n\t\tif err := report(prefix); err != nil {\n\t\t\treturn out.String(), err\n\t\t}\n\t}\n\treturn out.String(), nil\n}\n\nfunc pad(s string, n int) string {\n\tfor len(s) \u003c n {\n\t\ts += \" \"\n\t}\n\treturn s\n}\n\nfunc (s *Shell) bind(verb string, args []string) error {\n\tif err := s.writable(); err != nil {\n\t\treturn err\n\t}\n\tflag := ns.MREPL\n\trest := []string{}\n\tfor _, a := range args {\n\t\tif strings.HasPrefix(a, \"-\") \u0026\u0026 len(a) \u003e 1 {\n\t\t\tfor _, r := range a[1:] {\n\t\t\t\tswitch r {\n\t\t\t\tcase 'b':\n\t\t\t\t\tflag = flag\u0026^0x3 | ns.MBEFORE\n\t\t\t\tcase 'a':\n\t\t\t\t\tflag = flag\u0026^0x3 | ns.MAFTER\n\t\t\t\tcase 'c':\n\t\t\t\t\tflag |= ns.MCREATE\n\t\t\t\tdefault:\n\t\t\t\t\treturn ErrUsage\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\trest = append(rest, a)\n\t}\n\tif len(rest) != 2 {\n\t\treturn ErrUsage\n\t}\n\treturn s.ns.BindVerb(verb, rest[0], rest[1], flag)\n}\n\nfunc (s *Shell) unmount(args []string) error {\n\tif err := s.writable(); err != nil {\n\t\treturn err\n\t}\n\tswitch len(args) {\n\tcase 1:\n\t\treturn s.ns.Unmount(\"\", args[0])\n\tcase 2:\n\t\treturn s.ns.Unmount(args[0], args[1])\n\t}\n\treturn ErrUsage\n}\n\nfunc (s *Shell) mkdir(args []string) error {\n\tif err := s.writable(); err != nil {\n\t\treturn err\n\t}\n\tif len(args) == 0 {\n\t\treturn ErrUsage\n\t}\n\tfor _, p := range args {\n\t\tabs := s.ns.Abs(p)\n\t\ttarget, err := s.ns.CreateTarget(ninep.Dir(abs))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := target.Create(ninep.Base(abs), ninep.DirPerm, s.clock()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Shell) rm(args []string) error {\n\tif err := s.writable(); err != nil {\n\t\treturn err\n\t}\n\tif len(args) == 0 {\n\t\treturn ErrUsage\n\t}\n\tfor _, p := range args {\n\t\tabs := s.ns.Abs(p)\n\t\tname := ninep.Base(abs)\n\t\tmembers, err := s.ns.Resolve(ninep.Dir(abs))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfound, removed := false, false\n\t\tfor _, m := range members {\n\t\t\tif _, err := m.Walk(name); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfound = true\n\t\t\tmu, ok := m.(ninep.Mutable)\n\t\t\tif !ok {\n\t\t\t\tcontinue // a read-only server: try the next union member\n\t\t\t}\n\t\t\tif err := mu.Remove(name); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tremoved = true\n\t\t\tbreak\n\t\t}\n\t\tswitch {\n\t\tcase removed:\n\t\tcase found:\n\t\t\treturn ninep.ErrReadOnly\n\t\tdefault:\n\t\t\treturn ninep.ErrNotExist\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Shell) echo(args []string) (string, error) {\n\tnewline := true\n\twords := []string{}\n\tredirect, appendTo, dest := false, false, \"\"\n\ti := 0\n\tfor i \u003c len(args) {\n\t\ta := args[i]\n\t\tswitch {\n\t\tcase a == \"-n\" \u0026\u0026 len(words) == 0 \u0026\u0026 !redirect:\n\t\t\tnewline = false\n\t\tcase a == \"\u003e\" || a == \"\u003e\u003e\":\n\t\t\tif i+1 \u003e= len(args) {\n\t\t\t\treturn \"\", ErrUsage\n\t\t\t}\n\t\t\tredirect, appendTo, dest = true, a == \"\u003e\u003e\", args[i+1]\n\t\t\ti++\n\t\tdefault:\n\t\t\twords = append(words, a)\n\t\t}\n\t\ti++\n\t}\n\ttext := strings.Join(words, \" \")\n\tif newline {\n\t\ttext += \"\\n\"\n\t}\n\tif !redirect {\n\t\treturn text, nil\n\t}\n\tif err := s.writable(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"\", s.writeTo(dest, text, appendTo)\n}\n\n// writeTo creates or opens dest and writes text, honouring the namespace's\n// MCREATE rules when the file has to be created.\nfunc (s *Shell) writeTo(dest, text string, appendTo bool) error {\n\tabs := s.ns.Abs(dest)\n\tf, err := s.ns.Open(abs)\n\tif err == ninep.ErrNotExist {\n\t\ttarget, terr := s.ns.CreateTarget(ninep.Dir(abs))\n\t\tif terr != nil {\n\t\t\treturn terr\n\t\t}\n\t\tcreated, cerr := target.Create(ninep.Base(abs), ninep.FilePerm, s.clock())\n\t\tif cerr != nil {\n\t\t\treturn cerr\n\t\t}\n\t\tf = created\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tmu, ok := f.(ninep.Mutable)\n\tif !ok {\n\t\treturn ninep.ErrReadOnly\n\t}\n\toff := int64(0)\n\tif appendTo {\n\t\toff = mu.Stat().Length\n\t} else if err := mu.Truncate(0, s.clock()); err != nil {\n\t\treturn err\n\t}\n\t_, err = mu.Write(off, text, s.clock())\n\treturn err\n}\n\n// splitCommands splits on ';' and newlines, respecting rc quoting.\nfunc splitCommands(line string) ([]string, error) {\n\tout := []string{}\n\tvar b strings.Builder\n\tquoted := false\n\tfor i := 0; i \u003c len(line); i++ {\n\t\tc := line[i]\n\t\tif c == '\\'' {\n\t\t\tquoted = !quoted\n\t\t}\n\t\tif !quoted \u0026\u0026 (c == ';' || c == '\\n') {\n\t\t\tout = append(out, b.String())\n\t\t\tb.Reset()\n\t\t\tcontinue\n\t\t}\n\t\tb.WriteByte(c)\n\t}\n\tif quoted {\n\t\treturn nil, ErrQuote\n\t}\n\tout = append(out, b.String())\n\treturn out, nil\n}\n\n// tokenize splits one command into words using rc's quoting rules.\nfunc tokenize(s string) ([]string, error) {\n\ttoks := []string{}\n\ti := 0\n\tfor i \u003c len(s) {\n\t\tfor i \u003c len(s) \u0026\u0026 (s[i] == ' ' || s[i] == '\\t') {\n\t\t\ti++\n\t\t}\n\t\tif i \u003e= len(s) {\n\t\t\tbreak\n\t\t}\n\t\tvar b strings.Builder\n\t\tquoted := false\n\t\tfor i \u003c len(s) {\n\t\t\tc := s[i]\n\t\t\tif c == '\\'' {\n\t\t\t\tif quoted \u0026\u0026 i+1 \u003c len(s) \u0026\u0026 s[i+1] == '\\'' {\n\t\t\t\t\tb.WriteByte('\\'')\n\t\t\t\t\ti += 2\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tquoted = !quoted\n\t\t\t\ti++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !quoted \u0026\u0026 (c == ' ' || c == '\\t') {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tb.WriteByte(c)\n\t\t\ti++\n\t\t}\n\t\tif quoted {\n\t\t\treturn nil, ErrQuote\n\t\t}\n\t\ttoks = append(toks, b.String())\n\t}\n\treturn toks, nil\n}\n\n// NewMemShell is the convenience a realm or a test wants: a fresh ram root,\n// a namespace over it, and a shell. It exists here rather than in ns so that\n// ns keeps no dependency on a particular file server.\nfunc NewMemShell(uid string, mode Mode, now func() int64) (*Shell, *memfs.FS) {\n\th := int64(0)\n\tif now != nil {\n\t\th = now()\n\t}\n\tfs := memfs.New(uid, h)\n\treturn New(ns.New(fs.Root()), mode, now), fs\n}\n"},{"name":"rc_test.gno","body":"package rc\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tmemfs \"gno.land/p/moul/x/plan9/memfs/v0\"\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n\tns \"gno.land/p/moul/x/plan9/ns/v0\"\n\tsynfs \"gno.land/p/moul/x/plan9/synfs/v0\"\n)\n\nfunc clock(h int64) func() int64 { return func() int64 { return h } }\n\nfunc shell(t *testing.T, files ...string) (*Shell, *memfs.FS) {\n\tt.Helper()\n\tsh, fs := NewMemShell(\"glenda\", ReadWrite, clock(100))\n\tfor _, f := range files {\n\t\tif err := fs.WriteFile(f, \"contents of \"+f+\"\\n\", 100); err != nil {\n\t\t\tt.Fatalf(\"seed %s: %v\", f, err)\n\t\t}\n\t}\n\treturn sh, fs\n}\n\nfunc run(t *testing.T, sh *Shell, line string) string {\n\tt.Helper()\n\tout, err := sh.Run(line)\n\tif err != nil {\n\t\tt.Fatalf(\"%s: %v\", line, err)\n\t}\n\treturn out\n}\n\nfunc TestTokenize(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tin   string\n\t\twant []string\n\t}{\n\t\t{\"plain\", \"ls -l /dev\", []string{\"ls\", \"-l\", \"/dev\"}},\n\t\t{\"extra spaces\", \"  ls   /dev  \", []string{\"ls\", \"/dev\"}},\n\t\t{\"quoted\", \"echo 'hello world'\", []string{\"echo\", \"hello world\"}},\n\t\t{\"quote inside quote\", \"echo 'it''s'\", []string{\"echo\", \"it's\"}},\n\t\t{\"empty quoted word\", \"echo ''\", []string{\"echo\", \"\"}},\n\t\t{\"adjacent\", \"echo a'b c'd\", []string{\"echo\", \"ab cd\"}},\n\t\t{\"empty line\", \"\", []string{}},\n\t}\n\tfor _, tt := range tests {\n\t\tgot, err := tokenize(tt.in)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s: %v\", tt.name, err)\n\t\t\tcontinue\n\t\t}\n\t\tif len(got) != len(tt.want) {\n\t\t\tt.Errorf(\"%s: got %v, want %v\", tt.name, got, tt.want)\n\t\t\tcontinue\n\t\t}\n\t\tfor i := range got {\n\t\t\tif got[i] != tt.want[i] {\n\t\t\t\tt.Errorf(\"%s: token %d got %q, want %q\", tt.name, i, got[i], tt.want[i])\n\t\t\t}\n\t\t}\n\t}\n\tif _, err := tokenize(\"echo 'unterminated\"); err != ErrQuote {\n\t\tt.Errorf(\"unterminated quote: got %v\", err)\n\t}\n}\n\nfunc TestSplitCommands(t *testing.T) {\n\tgot, err := splitCommands(\"pwd; ls /\\necho 'a;b'\")\n\tif err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\twant := []string{\"pwd\", \" ls /\", \"echo 'a;b'\"}\n\tif len(got) != len(want) {\n\t\tt.Fatalf(\"got %v\", got)\n\t}\n\tfor i := range want {\n\t\tif got[i] != want[i] {\n\t\t\tt.Errorf(\"%d: got %q, want %q\", i, got[i], want[i])\n\t\t}\n\t}\n}\n\nfunc TestPwdAndCd(t *testing.T) {\n\tsh, _ := shell(t, \"/usr/glenda/lib/profile\")\n\tif got := run(t, sh, \"pwd\"); got != \"/\\n\" {\n\t\tt.Errorf(\"pwd: %q\", got)\n\t}\n\trun(t, sh, \"cd /usr/glenda\")\n\tif got := run(t, sh, \"pwd\"); got != \"/usr/glenda\\n\" {\n\t\tt.Errorf(\"pwd after cd: %q\", got)\n\t}\n\tif got := run(t, sh, \"cat lib/profile\"); got != \"contents of /usr/glenda/lib/profile\\n\" {\n\t\tt.Errorf(\"relative cat: %q\", got)\n\t}\n\trun(t, sh, \"cd\")\n\tif got := run(t, sh, \"pwd\"); got != \"/\\n\" {\n\t\tt.Errorf(\"bare cd should go to the root: %q\", got)\n\t}\n}\n\nfunc TestLs(t *testing.T) {\n\tsh, _ := shell(t, \"/bin/ls\", \"/bin/rc\", \"/tmp/x\")\n\tif got := run(t, sh, \"ls /\"); got != \"bin/\\ntmp/\\n\" {\n\t\tt.Errorf(\"ls /: %q\", got)\n\t}\n\tif got := run(t, sh, \"ls /bin\"); got != \"ls\\nrc\\n\" {\n\t\tt.Errorf(\"ls /bin: %q\", got)\n\t}\n\tlong := run(t, sh, \"ls -l /bin\")\n\tif !strings.Contains(long, \"-rw-r--r-- glenda\") {\n\t\tt.Errorf(\"ls -l: %q\", long)\n\t}\n\tif got := run(t, sh, \"ls /bin/ls\"); got != \"ls\\n\" {\n\t\tt.Errorf(\"ls of a file: %q\", got)\n\t}\n\tif _, err := sh.Run(\"ls -Z\"); err == nil {\n\t\tt.Error(\"an unknown flag should fail\")\n\t}\n}\n\nfunc TestLsUnionAndUnique(t *testing.T) {\n\tsh, fs := shell(t)\n\tfs.WriteFile(\"/bin/ls\", \"system\\n\", 100)\n\tfs.WriteFile(\"/usr/glenda/bin/ls\", \"mine\\n\", 100)\n\trun(t, sh, \"bind -b /usr/glenda/bin /bin\")\n\n\tif got := run(t, sh, \"ls /bin\"); got != \"ls\\nls\\n\" {\n\t\tt.Errorf(\"a union lists both, as Plan 9 does: %q\", got)\n\t}\n\tif got := run(t, sh, \"ls -u /bin\"); got != \"ls\\n\" {\n\t\tt.Errorf(\"ls -u: %q\", got)\n\t}\n\tif got := run(t, sh, \"cat /bin/ls\"); got != \"mine\\n\" {\n\t\tt.Errorf(\"the member bound before wins the walk: %q\", got)\n\t}\n}\n\nfunc TestCatErrors(t *testing.T) {\n\tsh, _ := shell(t, \"/bin/ls\")\n\tif _, err := sh.Run(\"cat /bin\"); err == nil {\n\t\tt.Error(\"cat of a directory should fail\")\n\t}\n\tif _, err := sh.Run(\"cat /absent\"); err == nil {\n\t\tt.Error(\"cat of a missing file should fail\")\n\t}\n\tif _, err := sh.Run(\"cat\"); err == nil {\n\t\tt.Error(\"cat with no argument should fail\")\n\t}\n}\n\nfunc TestEchoAndRedirect(t *testing.T) {\n\tsh, _ := shell(t)\n\tif got := run(t, sh, \"echo hello world\"); got != \"hello world\\n\" {\n\t\tt.Errorf(\"echo: %q\", got)\n\t}\n\tif got := run(t, sh, \"echo -n hello\"); got != \"hello\" {\n\t\tt.Errorf(\"echo -n: %q\", got)\n\t}\n\trun(t, sh, \"echo hello \u003e /greeting\")\n\tif got := run(t, sh, \"cat /greeting\"); got != \"hello\\n\" {\n\t\tt.Errorf(\"after redirect: %q\", got)\n\t}\n\trun(t, sh, \"echo again \u003e\u003e /greeting\")\n\tif got := run(t, sh, \"cat /greeting\"); got != \"hello\\nagain\\n\" {\n\t\tt.Errorf(\"after append: %q\", got)\n\t}\n\trun(t, sh, \"echo replaced \u003e /greeting\")\n\tif got := run(t, sh, \"cat /greeting\"); got != \"replaced\\n\" {\n\t\tt.Errorf(\"a plain redirect truncates: %q\", got)\n\t}\n\tif _, err := sh.Run(\"echo hi \u003e\"); err == nil {\n\t\tt.Error(\"a redirect with no target should fail\")\n\t}\n}\n\nfunc TestMkdirAndRm(t *testing.T) {\n\tsh, _ := shell(t)\n\trun(t, sh, \"mkdir /tmp\")\n\trun(t, sh, \"echo x \u003e /tmp/f\")\n\tif got := run(t, sh, \"ls /tmp\"); got != \"f\\n\" {\n\t\tt.Errorf(\"ls /tmp: %q\", got)\n\t}\n\tif _, err := sh.Run(\"rm /tmp\"); err == nil || err.Error() != \"rm: \"+ninep.ErrNotEmpty.Error() {\n\t\tt.Errorf(\"rm of a non-empty directory: got %v\", err)\n\t}\n\trun(t, sh, \"rm /tmp/f\")\n\trun(t, sh, \"rm /tmp\")\n\tif got := run(t, sh, \"ls /\"); got != \"\" {\n\t\tt.Errorf(\"root should be empty: %q\", got)\n\t}\n\tif _, err := sh.Run(\"rm /absent\"); err == nil {\n\t\tt.Error(\"rm of a missing file should fail\")\n\t}\n}\n\nfunc TestBindAndNs(t *testing.T) {\n\tsh, _ := shell(t, \"/bin/ls\", \"/usr/glenda/bin/rc\")\n\trun(t, sh, \"bind -a /usr/glenda/bin /bin\")\n\tif got := run(t, sh, \"ls /bin\"); got != \"ls\\nrc\\n\" {\n\t\tt.Errorf(\"ls after bind: %q\", got)\n\t}\n\twant := \"bind -a /usr/glenda/bin /bin\\ncd /\\n\"\n\tif got := run(t, sh, \"ns\"); got != want {\n\t\tt.Errorf(\"ns:\\ngot  %q\\nwant %q\", got, want)\n\t}\n\trun(t, sh, \"unmount /usr/glenda/bin /bin\")\n\tif got := run(t, sh, \"ls /bin\"); got != \"ls\\n\" {\n\t\tt.Errorf(\"after unmount: %q\", got)\n\t}\n\tif got := run(t, sh, \"ns\"); got != \"cd /\\n\" {\n\t\tt.Errorf(\"ns after unmount: %q\", got)\n\t}\n}\n\nfunc TestMountIsASynonym(t *testing.T) {\n\tsh, _ := shell(t, \"/bin/ls\", \"/srv/dev/height\")\n\trun(t, sh, \"mkdir /dev\")\n\trun(t, sh, \"mount /srv/dev /dev\")\n\tif got := run(t, sh, \"ls /dev\"); got != \"height\\n\" {\n\t\tt.Errorf(\"ls /dev: %q\", got)\n\t}\n\tif !strings.HasPrefix(run(t, sh, \"ns\"), \"mount /srv/dev /dev\\n\") {\n\t\tt.Errorf(\"ns should record the verb used: %q\", run(t, sh, \"ns\"))\n\t}\n}\n\nfunc TestCreateInAUnionNeedsTheFlag(t *testing.T) {\n\tsh, _ := shell(t, \"/bin/ls\", \"/usr/glenda/bin/rc\")\n\trun(t, sh, \"bind -a /usr/glenda/bin /bin\")\n\tif _, err := sh.Run(\"echo x \u003e /bin/new\"); err == nil {\n\t\tt.Error(\"creating in a union with no -c should be refused\")\n\t}\n\trun(t, sh, \"bind -ac /usr/glenda/bin /bin\")\n\trun(t, sh, \"echo x \u003e /bin/new\")\n\tif got := run(t, sh, \"cat /usr/glenda/bin/new\"); got != \"x\\n\" {\n\t\tt.Errorf(\"the create should land in the -c member: %q\", got)\n\t}\n}\n\nfunc TestReadOnlyModeRefusesWrites(t *testing.T) {\n\tsh, fs := NewMemShell(\"glenda\", ReadOnly, clock(1))\n\tfs.WriteFile(\"/bin/ls\", \"x\\n\", 1)\n\n\t// Reads still work.\n\tif got := run(t, sh, \"ls /bin\"); got != \"ls\\n\" {\n\t\tt.Errorf(\"ls: %q\", got)\n\t}\n\tif got := run(t, sh, \"cat /bin/ls\"); got != \"x\\n\" {\n\t\tt.Errorf(\"cat: %q\", got)\n\t}\n\tif got := run(t, sh, \"echo hi\"); got != \"hi\\n\" {\n\t\tt.Errorf(\"echo without a redirect is not a write: %q\", got)\n\t}\n\tfor _, line := range []string{\n\t\t\"mkdir /tmp\",\n\t\t\"rm /bin/ls\",\n\t\t\"bind /bin /bin\",\n\t\t\"unmount /bin\",\n\t\t\"echo hi \u003e /f\",\n\t} {\n\t\t_, err := sh.Run(line)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"%q should be refused in ReadOnly mode\", line)\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.Contains(err.Error(), ErrReadOnly.Error()) {\n\t\t\tt.Errorf(\"%q: got %v, want a read-only error\", line, err)\n\t\t}\n\t}\n}\n\nfunc TestStopsAtTheFirstError(t *testing.T) {\n\tsh, _ := shell(t)\n\tout, err := sh.Run(\"echo one; cat /absent; echo three\")\n\tif err == nil {\n\t\tt.Fatal(\"expected an error\")\n\t}\n\tif out != \"one\\n\" {\n\t\tt.Errorf(\"output should stop at the failure: %q\", out)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"cat: \") {\n\t\tt.Errorf(\"the error should name the command: %v\", err)\n\t}\n}\n\nfunc TestUnknownCommand(t *testing.T) {\n\tsh, _ := shell(t)\n\tif _, err := sh.Run(\"nosuchthing\"); err == nil {\n\t\tt.Error(\"expected an error\")\n\t}\n}\n\nfunc TestStatAndWalkShowTheUnion(t *testing.T) {\n\tsh, fs := shell(t)\n\tfs.WriteFile(\"/bin/ls\", \"a\\n\", 100)\n\tfs.WriteFile(\"/usr/glenda/bin/rc\", \"b\\n\", 100)\n\trun(t, sh, \"bind -a /usr/glenda/bin /bin\")\n\n\tst := run(t, sh, \"stat /bin\")\n\tif !strings.Contains(st, \"union=2\") {\n\t\tt.Errorf(\"stat should report the union width: %q\", st)\n\t}\n\tw := run(t, sh, \"walk /bin/rc\")\n\tlines := strings.Split(strings.TrimSpace(w), \"\\n\")\n\tif len(lines) != 3 {\n\t\tt.Fatalf(\"walk should report /, /bin and /bin/rc: %q\", w)\n\t}\n\tif !strings.Contains(lines[1], \"union=2\") {\n\t\tt.Errorf(\"the union should appear at /bin: %q\", lines[1])\n\t}\n\tif !strings.Contains(lines[2], \"union=1\") {\n\t\tt.Errorf(\"a union is top level only, /bin/rc is not one: %q\", lines[2])\n\t}\n}\n\nfunc TestReadOnlyServerMountedInAWritableNamespace(t *testing.T) {\n\t// This is the cross-realm shape: a synthetic, read-only tree grafted into\n\t// a namespace whose root is writable. Reads work; writes are refused\n\t// where the server is read-only and still allowed elsewhere.\n\tsh, fs := shell(t)\n\tfs.MkdirAll(\"/dev\", 100)\n\ttr := synfs.New(\"dev\", \"sys\", clock(100))\n\ttr.Root().Add(\"height\", func() string { return \"100\" })\n\tif err := sh.Ns().Mount(tr.Root(), \"#dev\", \"/dev\", ns.MREPL); err != nil {\n\t\tt.Fatalf(\"mount: %v\", err)\n\t}\n\n\tif got := run(t, sh, \"cat /dev/height\"); got != \"100\" {\n\t\tt.Errorf(\"read through the mount: %q\", got)\n\t}\n\tif got := run(t, sh, \"ls /dev\"); got != \"height\\n\" {\n\t\tt.Errorf(\"ls /dev: %q\", got)\n\t}\n\tif _, err := sh.Run(\"echo x \u003e /dev/height\"); err == nil {\n\t\tt.Error(\"writing to a read-only server should be refused\")\n\t}\n\tif _, err := sh.Run(\"rm /dev/height\"); err == nil || err.Error() != \"rm: \"+ninep.ErrReadOnly.Error() {\n\t\tt.Errorf(\"rm on a read-only server: got %v\", err)\n\t}\n\t// The rest of the namespace is unaffected.\n\trun(t, sh, \"echo fine \u003e /ok\")\n\tif got := run(t, sh, \"cat /ok\"); got != \"fine\\n\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n}\n\nfunc TestHelpListsEveryCommand(t *testing.T) {\n\tsh, _ := shell(t)\n\tout := run(t, sh, \"help\")\n\tfor _, cmd := range []string{\"bind\", \"cat\", \"cd\", \"echo\", \"ls\", \"mkdir\", \"mount\", \"ns\", \"pwd\", \"rm\", \"stat\", \"unmount\", \"walk\"} {\n\t\tif !strings.Contains(out, cmd) {\n\t\t\tt.Errorf(\"help does not mention %q\", cmd)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"11000000ugnot"}],"fee":{"gas_wanted":"81383600","gas_fee":"244150ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"N50Bu05H5s4Jeo/2/nP9DwsXN6oRk6N6NwlEADfbLD5kKGae5XAGX/OLd+Ix+jQtju/7/FYacq54pAg/8RqAdg=="}],"memo":""},"metadata":{"timestamp":"1790960264"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"capwallet","path":"gno.land/r/moul/agents/capwallet/v0","files":[{"name":"README.md","body":"# Capability Wallet — don't give your agent a wallet, give it a capability\n\nThe default way to let an agent spend or act on-chain is to hand it a private\nkey and hope its prompt is safe. That is a category error. A key is *all your\nauthority*; a prompt is a suggestion. The moment the agent is confused,\njailbroken, or just wrong, it has the full key.\n\nThree things get conflated and shouldn't:\n\n- **identity** — \"this is agent Percy\"\n- **authorization** — \"Percy may call `Assign` on `r/moul/issues`\"\n- **approval** — \"Percy may do it **at most twice**, for **≤ 5 GNOT each**,\n  **before block H**, and I can **revoke** it instantly\"\n\nIdentity is a passport. Authorization is a role. *Approval* is a capability:\na narrow, bounded, expiring, revocable grant. This realm issues the third\nkind.\n\n## The grant\n\n```go\ntype Capability struct {\n\tGranter       address\n\tPrincipal     address // the ONLY address that may exercise it\n\tTargetRealm   string  // scoped to one realm\n\tFunction      string  // scoped to one function\n\tMaxCoins      int64   // per-exercise ceiling\n\tValidUntil    int64   // absolute block height, 0 = never\n\tRemainingUses uint32  // a use counter\n\tRevoked       bool    // a kill switch\n\tUses          []Use   // an audit trail\n}\n```\n\nIssuing one is a single call:\n\n```go\n// Percy may call r/moul/issues.Assign, ≤5 GNOT, twice, no expiry.\nid := capwallet.Grant(cross(cur), percyAddr,\n\t\"gno.land/r/moul/issues\", \"Assign\",\n\t5_000_000, // per-use ceiling (ugnot)\n\t0,         // no expiry\n\t2,         // two uses\n\t\"issue IDs 100-200\")\n```\n\n## Two consumers, two shapes\n\nA **target realm** gates an action with a read-only, side-effect-free check:\n\n```go\nif !capwallet.Authorized(id, caller, coins) {\n\tpanic(\"not authorized\")\n}\n```\n\nThe **agent** consumes a use when it acts. Every bound is enforced at once —\nright principal, not revoked, not expired, uses remaining, under the ceiling —\nand the exercise is logged:\n\n```go\ncapwallet.Exercise(cross(cur), id, 3_000_000) // 1 use left\ncapwallet.Exercise(cross(cur), id, 1_000_000) // exhausted\n```\n\nAnd the granter kills it the instant something looks wrong:\n\n```go\ncapwallet.Revoke(cross(cur), id) // Authorized() now returns false for everyone\n```\n\n## Why this is a real safety primitive\n\nThe blast radius of a compromised agent is exactly the union of its live\ncapabilities — not its whole wallet. You can reason about \"what is the worst\nthis agent can do right now\" by reading a table, and shrink it to zero with\none transaction. That is not something a system prompt can give you.\n\nBrowse the wallet at the realm root; each capability's bounds and full\nexercise log live at `:\u003cid\u003e`.\n\n```sh\ngno test .\n```\n\n## Limitations\n\n- `ArgsPolicy` is a human-readable note, not an enforced predicate. Real\n  argument-level constraints (\"only issue IDs 100–200\") need the target realm\n  to check them, or a richer on-chain policy language. This demo scopes to\n  *realm + function + coins + uses + expiry*, which is already most of the\n  value.\n- There's no delegation graph (a capability that can mint narrower\n  capabilities). That's a natural extension, not a starting point.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/agents/capwallet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/capwallet/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/agents/capwallet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/capwallet/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/agents/capwallet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/capwallet/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/agents/capwallet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/capwallet/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/agents/capwallet/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/agents/capwallet/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"capwallet.gno","body":"// Package capwallet issues narrow, bounded, revocable capabilities to\n// agents — instead of handing an agent a wallet key and hoping its prompt\n// stays safe.\n//\n// The demo makes three ideas that are usually conflated stand apart:\n//\n//   - identity      — \"this is agent Percy\"\n//   - authorization — \"Percy may call this function on this realm\"\n//   - approval      — \"Percy may do it at most N times, for ≤ M coins,\n//                      before block H, and I can revoke it at any moment\"\n//\n// A capability is the third thing: a least-privilege grant with a ceiling,\n// an expiry, a use counter and a kill switch. Other realms consult\n// Authorized() before honoring an agent action; the granter revokes with\n// one call the instant something looks wrong.\npackage capwallet\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Use records one exercise of a capability.\ntype Use struct {\n\tBy     address\n\tCoins  int64\n\tHeight int64\n}\n\n// Capability is a least-privilege grant from a granter to a principal.\ntype Capability struct {\n\tID            uint64\n\tGranter       address\n\tPrincipal     address // the only address that may exercise it\n\tTargetRealm   string  // realm the capability is scoped to\n\tFunction      string  // function the capability authorizes\n\tMaxCoins      int64   // per-exercise ceiling in ugnot (0 = none allowed)\n\tValidUntil    int64   // block height after which it expires (0 = never)\n\tRemainingUses uint32  // exercises left (0 = exhausted)\n\tArgsPolicy    string  // human-readable note on allowed arguments\n\tRevoked       bool\n\tGrantedAt     int64\n\tUses          []Use\n}\n\nvar caps []*Capability // index 0 =\u003e ID 1\n\n// Grant issues a capability. The caller becomes its granter and can revoke\n// it later. validUntil is an absolute block height (0 = no expiry).\nfunc Grant(\n\tcur realm,\n\tprincipal address,\n\ttargetRealm, function string,\n\tmaxCoins, validUntil int64,\n\tuses uint32,\n\targsPolicy string,\n) uint64 {\n\tassert(targetRealm != \"\" \u0026\u0026 function != \"\", \"target realm and function required\")\n\tassert(uses \u003e 0, \"must grant at least one use\")\n\n\tid := uint64(len(caps)) + 1\n\tc := \u0026Capability{\n\t\tID:            id,\n\t\tGranter:       cur.Previous().Address(),\n\t\tPrincipal:     principal,\n\t\tTargetRealm:   targetRealm,\n\t\tFunction:      function,\n\t\tMaxCoins:      maxCoins,\n\t\tValidUntil:    validUntil,\n\t\tRemainingUses: uses,\n\t\tArgsPolicy:    argsPolicy,\n\t\tGrantedAt:     runtime.ChainHeight(),\n\t}\n\tcaps = append(caps, c)\n\tchain.Emit(\"CapabilityGranted\",\n\t\t\"id\", ufmt.Sprintf(\"%d\", id),\n\t\t\"principal\", principal.String(),\n\t\t\"target\", targetRealm+\".\"+function,\n\t)\n\treturn id\n}\n\n// Exercise consumes one use of a capability. Only the principal may call it,\n// and every bound is checked: not revoked, not expired, uses remaining, and\n// coins within the ceiling. On success the use is recorded and the counter\n// decremented.\nfunc Exercise(cur realm, id uint64, coins int64) {\n\tc := mustGet(id)\n\tcaller := cur.Previous().Address()\n\tassert(caller == c.Principal, \"caller is not the capability principal\")\n\tassertUsable(c)\n\tassert(coins \u003c= c.MaxCoins, ufmt.Sprintf(\"coins %d exceed capability ceiling %d\", coins, c.MaxCoins))\n\n\tc.RemainingUses--\n\tc.Uses = append(c.Uses, Use{By: caller, Coins: coins, Height: runtime.ChainHeight()})\n\tchain.Emit(\"CapabilityExercised\",\n\t\t\"id\", ufmt.Sprintf(\"%d\", id),\n\t\t\"coins\", ufmt.Sprintf(\"%d\", coins),\n\t\t\"remaining\", ufmt.Sprintf(\"%d\", c.RemainingUses),\n\t)\n}\n\n// Revoke disables a capability immediately. Only the granter may revoke.\nfunc Revoke(cur realm, id uint64) {\n\tc := mustGet(id)\n\tassert(cur.Previous().Address() == c.Granter, \"only the granter may revoke\")\n\tc.Revoked = true\n\tchain.Emit(\"CapabilityRevoked\", \"id\", ufmt.Sprintf(\"%d\", id))\n}\n\n// ---- read-only API for gating realms ----\n\n// Authorized reports whether principal may exercise capability id for the\n// given coin amount right now — the check a target realm runs before acting.\n// It never mutates state or consumes a use.\nfunc Authorized(id uint64, principal address, coins int64) bool {\n\tif id \u003c 1 || id \u003e uint64(len(caps)) {\n\t\treturn false\n\t}\n\tc := caps[id-1]\n\tif c.Principal != principal || !usable(c) {\n\t\treturn false\n\t}\n\treturn coins \u003c= c.MaxCoins\n}\n\n// Get returns a copy of a capability.\nfunc Get(id uint64) Capability { return *mustGet(id) }\n\n// Count returns the number of capabilities issued.\nfunc Count() int { return len(caps) }\n\n// ---- internal ----\n\nfunc usable(c *Capability) bool {\n\tif c.Revoked || c.RemainingUses == 0 {\n\t\treturn false\n\t}\n\tif c.ValidUntil != 0 \u0026\u0026 runtime.ChainHeight() \u003e c.ValidUntil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc assertUsable(c *Capability) {\n\tassert(!c.Revoked, \"capability revoked\")\n\tassert(c.RemainingUses \u003e 0, \"capability exhausted\")\n\tassert(c.ValidUntil == 0 || runtime.ChainHeight() \u003c= c.ValidUntil, \"capability expired\")\n}\n\nfunc mustGet(id uint64) *Capability {\n\tassert(id \u003e= 1 \u0026\u0026 id \u003c= uint64(len(caps)), \"unknown capability\")\n\treturn caps[id-1]\n}\n\nfunc assert(cond bool, msg string) {\n\tif !cond {\n\t\tpanic(msg)\n\t}\n}\n\n// Render shows all capabilities, or one capability's detail + usage at :\u003cid\u003e.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderCap(parseID(path))\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Capability Wallet\\n\\n\")\n\tsb.WriteString(\"_Don't give an agent a wallet. Give it a capability._\\n\\n\")\n\tif len(caps) == 0 {\n\t\tsb.WriteString(\"_No capabilities granted yet._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| # | Principal | Scope | Ceiling | Uses left | State |\\n\")\n\tsb.WriteString(\"|---|---|---|---|---|---|\\n\")\n\tfor _, c := range caps {\n\t\tsb.WriteString(ufmt.Sprintf(\"| [%d](/r/moul/agents/capwallet/v0:%d) | %s | `%s.%s` | %d ugnot | %d | %s |\\n\",\n\t\t\tc.ID, c.ID, short(c.Principal), c.TargetRealm, c.Function, c.MaxCoins, c.RemainingUses, state(c)))\n\t}\n\treturn sb.String()\n}\n\nfunc renderCap(id uint64) string {\n\tc := mustGet(id)\n\tvar sb strings.Builder\n\tsb.WriteString(ufmt.Sprintf(\"# Capability #%d\\n\\n\", c.ID))\n\tsb.WriteString(ufmt.Sprintf(\"- **State:** %s\\n\", state(c)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Granter:** %s\\n\", c.Granter.String()))\n\tsb.WriteString(ufmt.Sprintf(\"- **Principal:** %s\\n\", c.Principal.String()))\n\tsb.WriteString(ufmt.Sprintf(\"- **Scope:** `%s.%s`\\n\", c.TargetRealm, c.Function))\n\tsb.WriteString(ufmt.Sprintf(\"- **Per-use ceiling:** %d ugnot\\n\", c.MaxCoins))\n\tif c.ValidUntil == 0 {\n\t\tsb.WriteString(\"- **Expires:** never\\n\")\n\t} else {\n\t\tsb.WriteString(ufmt.Sprintf(\"- **Expires at height:** %d (now %d)\\n\", c.ValidUntil, runtime.ChainHeight()))\n\t}\n\tsb.WriteString(ufmt.Sprintf(\"- **Uses remaining:** %d\\n\", c.RemainingUses))\n\tsb.WriteString(ufmt.Sprintf(\"- **Args policy:** %s\\n\\n\", c.ArgsPolicy))\n\n\tsb.WriteString(ufmt.Sprintf(\"## Exercise log (%d)\\n\\n\", len(c.Uses)))\n\tif len(c.Uses) == 0 {\n\t\tsb.WriteString(\"_Never exercised._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| By | Coins | Height |\\n|---|---|---|\\n\")\n\tfor _, u := range c.Uses {\n\t\tsb.WriteString(ufmt.Sprintf(\"| %s | %d | %d |\\n\", short(u.By), u.Coins, u.Height))\n\t}\n\treturn sb.String()\n}\n\nfunc state(c *Capability) string {\n\tif c.Revoked {\n\t\treturn \"🚫 revoked\"\n\t}\n\tif c.RemainingUses == 0 {\n\t\treturn \"· exhausted\"\n\t}\n\tif c.ValidUntil != 0 \u0026\u0026 runtime.ChainHeight() \u003e c.ValidUntil {\n\t\treturn \"⏳ expired\"\n\t}\n\treturn \"✅ live\"\n}\n\nfunc parseID(s string) uint64 {\n\tvar n uint64\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tch := s[i]\n\t\tassert(ch \u003e= '0' \u0026\u0026 ch \u003c= '9', \"invalid capability path: \"+s)\n\t\tn = n*10 + uint64(ch-'0')\n\t}\n\treturn n\n}\n\nfunc short(a address) string {\n\ts := a.String()\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:8] + \"…\" + s[len(s)-4:]\n}\n"},{"name":"capwallet_test.gno","body":"package capwallet\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\towner = testutils.TestAddress(\"owner\")\n\tpercy = testutils.TestAddress(\"percy\")\n\tmallory = testutils.TestAddress(\"mallory\")\n)\n\nfunc TestGrantAndExercise(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\t// Percy may call r/moul/issues.Assign, ≤5 GNOT, 2 times, no expiry.\n\tid := Grant(cross(cur), percy, \"gno.land/r/moul/issues\", \"Assign\", 5000000, 0, 2, \"issue IDs 100-200\")\n\n\t// Read-only gate other realms use.\n\tuassert.True(t, Authorized(id, percy, 5000000))\n\tuassert.False(t, Authorized(id, percy, 5000001)) // over ceiling\n\tuassert.False(t, Authorized(id, mallory, 1))      // wrong principal\n\n\ttesting.SetRealm(testing.NewUserRealm(percy))\n\tExercise(cross(cur), id, 3000000)\n\tuassert.Equal(t, uint32(1), Get(id).RemainingUses)\n\tExercise(cross(cur), id, 1000000)\n\tuassert.Equal(t, uint32(0), Get(id).RemainingUses)\n\n\t// Exhausted.\n\tuassert.False(t, Authorized(id, percy, 1))\n\tuassert.AbortsWithMessage(t, cur, \"capability exhausted\", func(cur realm) {\n\t\tExercise(cur, id, 1)\n\t})\n}\n\nfunc TestCeilingEnforced(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tid := Grant(cross(cur), percy, \"r/x\", \"F\", 100, 0, 3, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(percy))\n\tuassert.AbortsWithMessage(t, cur, \"coins 101 exceed capability ceiling 100\", func(cur realm) {\n\t\tExercise(cur, id, 101)\n\t})\n}\n\nfunc TestOnlyPrincipal(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tid := Grant(cross(cur), percy, \"r/x\", \"F\", 100, 0, 3, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\tuassert.AbortsWithMessage(t, cur, \"caller is not the capability principal\", func(cur realm) {\n\t\tExercise(cur, id, 1)\n\t})\n}\n\nfunc TestRevoke(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tid := Grant(cross(cur), percy, \"r/x\", \"F\", 100, 0, 3, \"\")\n\n\t// Only the granter may revoke.\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\tuassert.AbortsWithMessage(t, cur, \"only the granter may revoke\", func(cur realm) {\n\t\tRevoke(cur, id)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tRevoke(cross(cur), id)\n\tuassert.False(t, Authorized(id, percy, 1))\n\ttesting.SetRealm(testing.NewUserRealm(percy))\n\tuassert.AbortsWithMessage(t, cur, \"capability revoked\", func(cur realm) {\n\t\tExercise(cur, id, 1)\n\t})\n}\n\nfunc TestExpiry(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\th := int64(0) // ChainHeight in tests starts at 0; set expiry in the past-ish\n\t_ = h\n\t// Grant valid only up to height 1.\n\tid := Grant(cross(cur), percy, \"r/x\", \"F\", 100, 1, 3, \"\")\n\ttesting.SkipHeights(5) // now well past height 1\n\tuassert.False(t, Authorized(id, percy, 1))\n\ttesting.SetRealm(testing.NewUserRealm(percy))\n\tuassert.AbortsWithMessage(t, cur, \"capability expired\", func(cur realm) {\n\t\tExercise(cur, id, 1)\n\t})\n\n\tuassert.True(t, len(Render(\"\")) \u003e 0)\n\tuassert.True(t, len(Render(\"1\")) \u003e 0)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/agents/capwallet/v0\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"gnomem","path":"gno.land/r/moul/agents/gnomem/v0","files":[{"name":"README.md","body":"# GnoMem — can autonomous agents share a memory without sharing a database operator?\n\nMost \"agent memory\" products are a vector store: dump text, retrieve similar\nchunks. That is fine when one agent is talking to itself. It falls apart the\nmoment several *independent* agents — different owners, different models, run\nat different times — have to maintain a **shared** understanding of the same\nworld and occasionally disagree about it.\n\nWhoever operates the database wins every disagreement. They can silently edit\na memory, drop an inconvenient finding, or reorder history, and no other agent\ncan tell. The question this demo asks is: *what does shared agent memory look\nlike when nobody owns the database?*\n\n## Memory as a contestable claim graph\n\nThe core move is to stop storing memory as text and start storing it as a\ngraph of structured **claims**:\n\n```go\ntype Claim struct {\n\tID         uint64\n\tSubject    string\n\tPredicate  string\n\tObject     string     // the (S, P, O) triple\n\tAuthor     address\n\tConfidence uint8       // 0..100\n\tStatus     Status\n\tSupports   []Endorsement\n\tContests   []Endorsement\n\tEvidence   []Evidence  // commitments to off-chain material\n\tSupersededBy uint64\n\tSupersedes   uint64\n\t// ...\n}\n```\n\nA claim moves through an explicit lifecycle:\n\n```\nproposed → supported → contested → { accepted | retracted | superseded }\n```\n\nThe terminal states are the interesting design decision. An agent that\ndislikes a claim **cannot delete it**. It can:\n\n- **contest** it (with refuting evidence), flipping it to `contested`;\n- **supersede** it with a better claim — the old one becomes `superseded` and\n  is *linked* to its replacement, so the correction is a visible edge in the\n  graph, not an overwrite;\n- **retract** it via adjudication.\n\nHistory stays visible and ordered in every case. Support never silently\noverrides a live contest, either: a contested claim stays contested until\nsomeone adjudicates it.\n\n## The canonical run\n\n```go\n// A researcher proposes.\nid := gnomem.ProposeClaim(cross(cur),\n\t\"foo/v2\", \"is\", \"safe to deploy\", \"report#H1\", 82)\n\n// A skeptic contests, with an exploit.\ngnomem.ContestClaim(cross(cur), id, \"unbounded allocation\", \"exploit#H2\")\n\n// An adjudicator supersedes with the corrected claim.\nnewID := gnomem.SupersedeClaim(cross(cur),\n\tid, \"foo/v2\", \"is\", \"unsafe before commit abc123\", \"report#H3\", 95)\n```\n\nRender the graph at the realm root, and any claim's full argument tree —\nsupport, contest, evidence, supersession links — at `:\u003cid\u003e`. You get a\n*\"view source for the argument\"*: not just the current answer, but how the\nagents got there and who dissented.\n\n```\n# Claim #1\n\u003e foo/v2 — is — safe to deploy\n- Status: ♻️ superseded\n- Superseded by: #2\n## ⚔ Contest (1)\n| skeptic | 0 | unbounded allocation | 12 |\n```\n\n## Why Gno specifically\n\n- The claim graph is **ordinary persistent objects** — structs, slices,\n  pointers — not hand-serialized contract storage. You write Go, the graph\n  persists.\n- Every realm has `Render`, so the argument tree is browsable in a normal web\n  view with no separate frontend.\n- Because it's an importable package, a *research-protocol* realm can sit on\n  top and enforce process: \"≥3 independent agents, each must cite evidence,\n  one assigned devil's advocate, 2/3 needed to accept, unresolved\n  disagreements stay visible.\"\n\n## What this demo intentionally leaves out\n\nAccess control. **Anyone can write** to any open claim here, because the point\nis the *structure* of contested knowledge, not who's allowed to touch it.\nGating \"which agent may support/contest/resolve which claim, under what\nbudget\" is a capability question — a natural next realm, not this one's job.\n\nThere's also no economic layer: no staking behind a claim, no reward for\nfinding the flaw that gets a claim superseded, no bond to slash for bad\nadjudication. Those make the incentives real, and they compose on top of this\ngraph rather than being baked into it.\n\nRun the tests:\n\n```sh\ngno test .\n```\n\nThe uncomfortable truth it's built around: different agents will always\nproduce incompatible, mutable, poorly-sourced views of the same world. You\ncan't prevent that. You *can* refuse to let any one of them quietly win.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/agents/gnomem/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/gnomem/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/agents/gnomem/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/gnomem/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/agents/gnomem/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/gnomem/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/agents/gnomem/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/gnomem/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/agents/gnomem/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/agents/gnomem/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomem.gno","body":"// Package gnomem is a shared, contestable memory for multiple agents.\n//\n// Most \"agent memory\" products store text and retrieve similar chunks.\n// That works for one agent talking to itself. It breaks the moment several\n// independent agents — possibly run by different people, on different\n// models — must maintain a *shared* understanding of the same world and\n// sometimes disagree about it.\n//\n// gnomem models memory not as text but as a graph of structured claims.\n// Each claim is a (subject, predicate, object) triple with an author,\n// evidence and a confidence. Other agents can support it, contest it, add\n// evidence, supersede it with a better claim, or trigger adjudication. No\n// agent can silently erase an inconvenient finding: claims can be\n// superseded or retracted, but the history stays visible and ordered.\n//\n// The point of the demo is the structure, not access control: anyone may\n// write. Gating *who* may write to which claim is exactly what the\n// capability-wallet demo adds on top.\npackage gnomem\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Status is a claim's position in the argument lifecycle.\ntype Status string\n\nconst (\n\tStatusProposed   Status = \"proposed\"   // asserted, no endorsements yet\n\tStatusSupported  Status = \"supported\"  // has support, no live contest\n\tStatusContested  Status = \"contested\"  // at least one live contest\n\tStatusAccepted   Status = \"accepted\"   // adjudicated true (terminal)\n\tStatusRetracted  Status = \"retracted\"  // adjudicated false / withdrawn (terminal)\n\tStatusSuperseded Status = \"superseded\" // replaced by a better claim (terminal)\n)\n\n// Endorsement is a support or contest signal from one agent.\ntype Endorsement struct {\n\tAgent      address\n\tConfidence uint8 // 0..100\n\tNote       string\n\tHeight     int64\n}\n\n// Evidence points at off-chain material backing (or refuting) a claim.\ntype Evidence struct {\n\tBy     address\n\tKind   string // \"report\", \"exploit\", \"dataset\", \"citation\", ...\n\tHash   string // commitment to the off-chain artifact\n\tHeight int64\n}\n\n// Claim is one node in the shared memory graph.\ntype Claim struct {\n\tID           uint64\n\tSubject      string\n\tPredicate    string\n\tObject       string\n\tAuthor       address\n\tConfidence   uint8\n\tStatus       Status\n\tCreatedAt    int64\n\tSupports     []Endorsement\n\tContests     []Endorsement\n\tEvidence     []Evidence\n\tSupersededBy uint64 // 0 if none\n\tSupersedes   uint64 // 0 if none\n\tResolver     address\n\tResolvedAt   int64\n}\n\nvar claims []*Claim // index 0 =\u003e ID 1\n\n// ProposeClaim asserts a new (subject, predicate, object) triple.\nfunc ProposeClaim(cur realm, subject, predicate, object, evidenceHash string, confidence uint8) uint64 {\n\tassert(subject != \"\" \u0026\u0026 predicate != \"\" \u0026\u0026 object != \"\", \"empty triple field\")\n\tassertConfidence(confidence)\n\n\tid := uint64(len(claims)) + 1\n\tc := \u0026Claim{\n\t\tID:         id,\n\t\tSubject:    subject,\n\t\tPredicate:  predicate,\n\t\tObject:     object,\n\t\tAuthor:     cur.Previous().Address(),\n\t\tConfidence: confidence,\n\t\tStatus:     StatusProposed,\n\t\tCreatedAt:  runtime.ChainHeight(),\n\t}\n\tif evidenceHash != \"\" {\n\t\tc.Evidence = append(c.Evidence, Evidence{\n\t\t\tBy: c.Author, Kind: \"initial\", Hash: evidenceHash, Height: c.CreatedAt,\n\t\t})\n\t}\n\tclaims = append(claims, c)\n\tchain.Emit(\"ClaimProposed\", \"id\", ufmt.Sprintf(\"%d\", id), \"subject\", subject, \"predicate\", predicate)\n\treturn id\n}\n\n// SupportClaim endorses a claim. Support never overrides a live contest —\n// a contested claim stays contested until adjudicated.\nfunc SupportClaim(cur realm, id uint64, confidence uint8, note string) {\n\tc := mustOpen(id)\n\tassertConfidence(confidence)\n\tc.Supports = append(c.Supports, Endorsement{\n\t\tAgent: cur.Previous().Address(), Confidence: confidence, Note: note, Height: runtime.ChainHeight(),\n\t})\n\tif c.Status == StatusProposed {\n\t\tc.Status = StatusSupported\n\t}\n\tchain.Emit(\"ClaimSupported\", \"id\", ufmt.Sprintf(\"%d\", id))\n}\n\n// ContestClaim challenges a claim, optionally attaching refuting evidence.\nfunc ContestClaim(cur realm, id uint64, note, evidenceHash string) {\n\tc := mustOpen(id)\n\tagent := cur.Previous().Address()\n\th := runtime.ChainHeight()\n\tc.Contests = append(c.Contests, Endorsement{\n\t\tAgent: agent, Confidence: 0, Note: note, Height: h,\n\t})\n\tif evidenceHash != \"\" {\n\t\tc.Evidence = append(c.Evidence, Evidence{By: agent, Kind: \"refutation\", Hash: evidenceHash, Height: h})\n\t}\n\tc.Status = StatusContested\n\tchain.Emit(\"ClaimContested\", \"id\", ufmt.Sprintf(\"%d\", id))\n}\n\n// AddEvidence attaches supporting or contextual off-chain material.\nfunc AddEvidence(cur realm, id uint64, kind, hash string) {\n\tc := mustOpen(id)\n\tassert(hash != \"\", \"empty evidence hash\")\n\tc.Evidence = append(c.Evidence, Evidence{\n\t\tBy: cur.Previous().Address(), Kind: kind, Hash: hash, Height: runtime.ChainHeight(),\n\t})\n}\n\n// SupersedeClaim replaces an open claim with a new one. The old claim is\n// marked superseded (terminal) and linked to its replacement, so the\n// correction is visible rather than a silent overwrite.\nfunc SupersedeClaim(cur realm, oldID uint64, subject, predicate, object, evidenceHash string, confidence uint8) uint64 {\n\told := mustOpen(oldID)\n\tnewID := ProposeClaim(cur, subject, predicate, object, evidenceHash, confidence)\n\tnewC := claims[newID-1]\n\tnewC.Supersedes = oldID\n\told.Status = StatusSuperseded\n\told.SupersededBy = newID\n\tchain.Emit(\"ClaimSuperseded\", \"old\", ufmt.Sprintf(\"%d\", oldID), \"new\", ufmt.Sprintf(\"%d\", newID))\n\treturn newID\n}\n\n// ResolveClaim adjudicates an open claim as accepted (true) or retracted\n// (false/withdrawn). The resolver's address is recorded — resolution is\n// itself a provenance-bearing act, not an anonymous verdict.\nfunc ResolveClaim(cur realm, id uint64, accepted bool) {\n\tc := mustOpen(id)\n\tif accepted {\n\t\tc.Status = StatusAccepted\n\t} else {\n\t\tc.Status = StatusRetracted\n\t}\n\tc.Resolver = cur.Previous().Address()\n\tc.ResolvedAt = runtime.ChainHeight()\n\tchain.Emit(\"ClaimResolved\", \"id\", ufmt.Sprintf(\"%d\", id), \"status\", string(c.Status))\n}\n\n// ---- read-only API ----\n\n// Get returns a copy of a claim by id.\nfunc Get(id uint64) Claim { return *mustGet(id) }\n\n// Count returns the number of claims in the graph.\nfunc Count() int { return len(claims) }\n\n// IsOpen reports whether a claim can still be supported/contested/resolved.\nfunc IsOpen(id uint64) bool { return isOpen(mustGet(id).Status) }\n\n// ---- internal ----\n\nfunc isOpen(s Status) bool {\n\treturn s == StatusProposed || s == StatusSupported || s == StatusContested\n}\n\nfunc mustGet(id uint64) *Claim {\n\tassert(id \u003e= 1 \u0026\u0026 id \u003c= uint64(len(claims)), \"unknown claim\")\n\treturn claims[id-1]\n}\n\nfunc mustOpen(id uint64) *Claim {\n\tc := mustGet(id)\n\tassert(isOpen(c.Status), \"claim is resolved (terminal): \"+string(c.Status))\n\treturn c\n}\n\nfunc assertConfidence(c uint8) { assert(c \u003c= 100, \"confidence must be 0..100\") }\n\nfunc assert(cond bool, msg string) {\n\tif !cond {\n\t\tpanic(msg)\n\t}\n}\n\n// Render shows the full graph, or one claim's argument tree at :\u003cid\u003e.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderClaim(parseID(path))\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# GnoMem — Contested Shared Memory\\n\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"A graph of %d structured claim(s) maintained by multiple agents.\\n\\n\", len(claims)))\n\tif len(claims) == 0 {\n\t\tsb.WriteString(\"_No claims yet._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| # | Claim | Status | ✋ support | ⚔ contest |\\n\")\n\tsb.WriteString(\"|---|---|---|---|---|\\n\")\n\tfor _, c := range claims {\n\t\tsb.WriteString(ufmt.Sprintf(\"| [%d](/r/moul/agents/gnomem/v0:%d) | %s | %s | %d | %d |\\n\",\n\t\t\tc.ID, c.ID, triple(c), statusBadge(c.Status), len(c.Supports), len(c.Contests)))\n\t}\n\treturn sb.String()\n}\n\nfunc renderClaim(id uint64) string {\n\tc := mustGet(id)\n\tvar sb strings.Builder\n\tsb.WriteString(ufmt.Sprintf(\"# Claim #%d\\n\\n\", c.ID))\n\tsb.WriteString(ufmt.Sprintf(\"\u003e **%s**\\n\\n\", triple(c)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Status:** %s\\n\", statusBadge(c.Status)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Author:** %s\\n\", short(c.Author)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Author confidence:** %d/100\\n\", c.Confidence))\n\tsb.WriteString(ufmt.Sprintf(\"- **Created at height:** %d\\n\", c.CreatedAt))\n\tif c.Supersedes != 0 {\n\t\tsb.WriteString(ufmt.Sprintf(\"- **Supersedes:** [#%d](/r/moul/agents/gnomem/v0:%d)\\n\", c.Supersedes, c.Supersedes))\n\t}\n\tif c.SupersededBy != 0 {\n\t\tsb.WriteString(ufmt.Sprintf(\"- **Superseded by:** [#%d](/r/moul/agents/gnomem/v0:%d)\\n\", c.SupersededBy, c.SupersededBy))\n\t}\n\tif c.ResolvedAt != 0 {\n\t\tsb.WriteString(ufmt.Sprintf(\"- **Resolved by:** %s at height %d\\n\", short(c.Resolver), c.ResolvedAt))\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(ufmt.Sprintf(\"## ✋ Support (%d)\\n\\n\", len(c.Supports)))\n\trenderEndorsements(\u0026sb, c.Supports)\n\tsb.WriteString(ufmt.Sprintf(\"## ⚔ Contest (%d)\\n\\n\", len(c.Contests)))\n\trenderEndorsements(\u0026sb, c.Contests)\n\n\tsb.WriteString(ufmt.Sprintf(\"## 📎 Evidence (%d)\\n\\n\", len(c.Evidence)))\n\tif len(c.Evidence) == 0 {\n\t\tsb.WriteString(\"_None._\\n\")\n\t} else {\n\t\tsb.WriteString(\"| By | Kind | Commitment | Height |\\n|---|---|---|---|\\n\")\n\t\tfor _, e := range c.Evidence {\n\t\t\tsb.WriteString(ufmt.Sprintf(\"| %s | %s | `%s` | %d |\\n\", short(e.By), e.Kind, shortHash(e.Hash), e.Height))\n\t\t}\n\t}\n\treturn sb.String()\n}\n\nfunc renderEndorsements(sb *strings.Builder, es []Endorsement) {\n\tif len(es) == 0 {\n\t\tsb.WriteString(\"_None._\\n\\n\")\n\t\treturn\n\t}\n\tsb.WriteString(\"| Agent | Confidence | Note | Height |\\n|---|---|---|---|\\n\")\n\tfor _, e := range es {\n\t\tsb.WriteString(ufmt.Sprintf(\"| %s | %d | %s | %d |\\n\", short(e.Agent), e.Confidence, e.Note, e.Height))\n\t}\n\tsb.WriteString(\"\\n\")\n}\n\nfunc triple(c *Claim) string {\n\treturn ufmt.Sprintf(\"%s — %s — %s\", c.Subject, c.Predicate, c.Object)\n}\n\nfunc statusBadge(s Status) string {\n\tswitch s {\n\tcase StatusAccepted:\n\t\treturn \"✅ accepted\"\n\tcase StatusRetracted:\n\t\treturn \"🚫 retracted\"\n\tcase StatusSuperseded:\n\t\treturn \"♻️ superseded\"\n\tcase StatusContested:\n\t\treturn \"⚔ contested\"\n\tcase StatusSupported:\n\t\treturn \"✋ supported\"\n\tdefault:\n\t\treturn \"· proposed\"\n\t}\n}\n\nfunc parseID(s string) uint64 {\n\tvar n uint64\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tassert(c \u003e= '0' \u0026\u0026 c \u003c= '9', \"invalid claim path: \"+s)\n\t\tn = n*10 + uint64(c-'0')\n\t}\n\treturn n\n}\n\nfunc short(a address) string {\n\ts := a.String()\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:8] + \"…\" + s[len(s)-4:]\n}\n\nfunc shortHash(s string) string {\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:6] + \"…\" + s[len(s)-4:]\n}\n"},{"name":"gnomem_test.gno","body":"package gnomem\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\tresearcher = testutils.TestAddress(\"researcher\")\n\tskeptic    = testutils.TestAddress(\"skeptic\")\n\tjudge      = testutils.TestAddress(\"judge\")\n)\n\n// The canonical scenario from the design: a researcher proposes, a skeptic\n// contests with an exploit, an adjudicator supersedes with the corrected\n// claim.\nfunc TestContestedThenSuperseded(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(researcher))\n\tid := ProposeClaim(cross(cur), \"foo/v2\", \"is\", \"safe to deploy\", \"report#H1\", 82)\n\tuassert.Equal(t, uint64(1), id)\n\tuassert.Equal(t, string(StatusProposed), string(Get(id).Status))\n\n\t// Skeptic contests with a refutation.\n\ttesting.SetRealm(testing.NewUserRealm(skeptic))\n\tContestClaim(cross(cur), id, \"unbounded allocation\", \"exploit#H2\")\n\tuassert.Equal(t, string(StatusContested), string(Get(id).Status))\n\tuassert.True(t, IsOpen(id))\n\n\t// Adjudicator supersedes with the corrected claim.\n\ttesting.SetRealm(testing.NewUserRealm(judge))\n\tnewID := SupersedeClaim(cross(cur), id, \"foo/v2\", \"is\", \"unsafe before commit abc123\", \"report#H3\", 95)\n\tuassert.Equal(t, uint64(2), newID)\n\n\told := Get(id)\n\tuassert.Equal(t, string(StatusSuperseded), string(old.Status))\n\tuassert.Equal(t, newID, old.SupersededBy)\n\tuassert.False(t, IsOpen(id)) // superseded is terminal\n\n\tnewC := Get(newID)\n\tuassert.Equal(t, id, newC.Supersedes)\n\tuassert.Equal(t, 1, len(newC.Evidence)) // the initial report#H3\n\n\tuassert.True(t, len(Render(\"\")) \u003e 0)\n\tuassert.True(t, len(Render(\"1\")) \u003e 0)\n\tuassert.True(t, len(Render(\"2\")) \u003e 0)\n}\n\nfunc TestSupportThenAccept(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(researcher))\n\tid := ProposeClaim(cross(cur), \"gnovm\", \"supports\", \"persistent object graphs\", \"\", 90)\n\n\ttesting.SetRealm(testing.NewUserRealm(skeptic))\n\tSupportClaim(cross(cur), id, 88, \"confirmed in docs\")\n\tuassert.Equal(t, string(StatusSupported), string(Get(id).Status))\n\n\ttesting.SetRealm(testing.NewUserRealm(judge))\n\tResolveClaim(cross(cur), id, true)\n\tuassert.Equal(t, string(StatusAccepted), string(Get(id).Status))\n\tuassert.False(t, IsOpen(id))\n}\n\nfunc TestCannotMutateTerminal(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(researcher))\n\tid := ProposeClaim(cross(cur), \"x\", \"is\", \"y\", \"\", 50)\n\tResolveClaim(cross(cur), id, false) // retracted, terminal\n\n\tuassert.AbortsWithMessage(t, cur, \"claim is resolved (terminal): retracted\", func(cur realm) {\n\t\tSupportClaim(cur, id, 10, \"too late\")\n\t})\n}\n\nfunc TestBadInputs(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(researcher))\n\tuassert.AbortsWithMessage(t, cur, \"empty triple field\", func(cur realm) {\n\t\tProposeClaim(cur, \"\", \"is\", \"y\", \"\", 10)\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"confidence must be 0..100\", func(cur realm) {\n\t\tProposeClaim(cur, \"a\", \"b\", \"c\", \"\", 200)\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/agents/gnomem/v0\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"jury","path":"gno.land/r/moul/agents/jury/v0","files":[{"name":"README.md","body":"# Agent Jury — who checks the agents?\n\nPaying agents is the easy part of an agent economy. The hard part is what\nhappens when an agent's output is **disputed**: a patch that may be wrong, a\nresearch claim that may be fabricated, an oracle reading someone contests.\nSomeone has to adjudicate — and if that someone is a single trusted party,\nyou've just recreated the thing blockchains were supposed to remove.\n\nThis realm runs a small **commit-reveal jury**: a fixed panel of reviewers\neach lock in a *hidden* verdict, then reveal it. Because verdicts are\ncommitted blind, no juror can copy another's vote, and none can be swayed by\nwatching the tally form.\n\n## The two phases\n\n```\ncommit:  each juror submits  commit.Verdict(verdict, salt)   ← hash, hides the vote\nreveal:  each juror submits  (verdict, salt)                 ← must reproduce the hash\nclose:   majority of revealed verdicts decides the outcome\n```\n\nThe commitment scheme is shared with the other demos\n(`p/moul/agents/commit/v0`), so a juror computes their commitment off-chain:\n\n```go\ncommitment := commit.Verdict(true, \"a-random-salt\") // \"I vote YES\", hidden\n\njury.Commit(cross(cur), caseID, commitment)          // during commit phase\n// ...later...\njury.Reveal(cross(cur), caseID, true, \"a-random-salt\") // reproduces it, or the reveal is rejected\n```\n\nWhen the last juror commits, the case auto-advances to reveal; when the last\nreveals, it closes and records the majority outcome. Dissenting jurors (those\nwho voted against the majority) are marked in the render — minority reports\nstay visible, which matters when the minority turns out to be right.\n\n## Composability\n\nA case's *subject* is just an opaque string — a receipt sequence from the\nreceipt demo, a claim id from gnomem, a raw artifact hash. The jury doesn't\nimport any of them; it adjudicates references. That's the point of small,\nsingle-purpose realms: they snap together without hard dependencies.\n\n```go\nid := jury.OpenCase(cross(cur), \"receipt#7\", j1.String()+\",\"+j2.String()+\",\"+j3.String())\n// ... commit + reveal ...\njury.Outcome(id) // \"upheld\" | \"rejected\" | \"tie\"\n```\n\nBrowse cases at the realm root; each panel and tally is at `:\u003cid\u003e`.\n\n```sh\ngno test .\n```\n\n## What's missing (on purpose)\n\nThe mechanism is here; the **money** is not. A production jury bonds each\njuror (stake coins to serve) and slashes provably bad verdicts — that's what\nmakes honest review the profitable strategy. It also wants juror *selection*\n(random or reputation-weighted, to resist packing) and an *appeal* path (a\nlarger panel on challenge). All of those compose on top of this commit-reveal\ncore; none of them change it.\n\nThe uncomfortable design truth: you can't prove a verdict is *correct*. You\ncan make it *blind, independent, and accountable* — and that's what turns \"one\ntrusted adjudicator\" back into \"a protocol.\"\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/agents/jury/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/jury/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/agents/jury/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/jury/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/agents/jury/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/jury/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/agents/jury/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/jury/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/agents/jury/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/agents/jury/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/agents/jury/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"jury.gno","body":"// Package jury is a commit-reveal adversarial review protocol for disputes\n// over agent work.\n//\n// The hard part of an agent economy is not paying agents — it is deciding\n// what happens when an agent's output is disputed. This realm runs a small\n// jury: a fixed panel of reviewers each *commit* to a hidden verdict, then\n// *reveal* it. Commit-reveal means no juror can copy another's vote or be\n// swayed after seeing the tally; every verdict is locked in blind.\n//\n// The subject of a case is an opaque string — a receipt sequence, a claim\n// id, an off-chain artifact hash — so this realm composes with the receipt\n// and gnomem demos without depending on them.\n//\n// Bonding and slashing (a juror stakes coins, loses them for provably bad\n// verdicts) are the natural economic layer on top; this demo shows the\n// mechanism without the money.\npackage jury\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/agents/commit/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Phase is a case's position in the commit-reveal lifecycle.\ntype Phase string\n\nconst (\n\tPhaseCommit Phase = \"commit\"\n\tPhaseReveal Phase = \"reveal\"\n\tPhaseClosed Phase = \"closed\"\n)\n\n// Juror is one panelist and their (eventually revealed) verdict.\ntype Juror struct {\n\tAddr       address\n\tCommitment string // commit.Verdict(verdict, salt)\n\tCommitted  bool\n\tRevealed   bool\n\tVerdict    bool // meaningful once Revealed\n\tHeight     int64\n}\n\n// Case is a single dispute under review by a fixed panel.\ntype Case struct {\n\tID       uint64\n\tSubject  string // opaque reference to the disputed thing\n\tOpener   address\n\tPhase    Phase\n\tJurors   []*Juror\n\tOpenedAt int64\n\tOutcome  string // \"upheld\" | \"rejected\" | \"tie\" once closed\n\tYes      int\n\tNo       int\n}\n\nvar cases []*Case // index 0 =\u003e ID 1\n\n// The bounds on what a wallet may open. OpenCase is callable by anyone, so\n// without them the case list and every panel grow without limit, and so does\n// the index page that renders them.\nconst (\n\tMaxCases    = 1000\n\tMaxJurors   = 25\n\tMaxSubject  = 200 // bytes\n\tIndexRecent = 50  // cases the index lists, newest first\n\n\tMaxCommitment = 128 // bytes; commit.Verdict returns 64\n)\n\n// OpenCase starts a dispute with a fixed panel of jurors, given as\n// comma-separated addresses. An odd panel size avoids ties; duplicates and\n// invalid addresses are rejected.\n//\n// The panel is a string, not a []address, because MsgCall carries every\n// argument as a string and the VM decodes no slice but []byte: a []address\n// parameter made this function unreachable from any wallet.\nfunc OpenCase(cur realm, subject, jurorsCSV string) uint64 {\n\topener := caller(cur)\n\t// Checked after sanitizing: a subject of only zero-width runes is not empty\n\t// as bytes, and renders as nothing.\n\tassert(strings.TrimSpace(ui.Inline(subject)) != \"\", \"empty subject\")\n\tassert(len(subject) \u003c= MaxSubject, \"subject too long\")\n\tassert(len(cases) \u003c MaxCases, \"the jury is full\")\n\tjurors := parseJurors(jurorsCSV)\n\tassert(len(jurors) \u003e= 1, \"need at least one juror\")\n\tassert(len(jurors) \u003c= MaxJurors, \"panel too large\")\n\n\tseen := make(map[string]bool)\n\tpanel := make([]*Juror, 0, len(jurors))\n\tfor _, j := range jurors {\n\t\tkey := j.String()\n\t\tassert(!seen[key], \"duplicate juror: \"+key)\n\t\tseen[key] = true\n\t\tpanel = append(panel, \u0026Juror{Addr: j})\n\t}\n\n\tid := uint64(len(cases)) + 1\n\tcases = append(cases, \u0026Case{\n\t\tID:       id,\n\t\tSubject:  subject,\n\t\tOpener:   opener,\n\t\tPhase:    PhaseCommit,\n\t\tJurors:   panel,\n\t\tOpenedAt: runtime.ChainHeight(),\n\t})\n\tchain.Emit(\"CaseOpened\", \"id\", ufmt.Sprintf(\"%d\", id), \"jurors\", ufmt.Sprintf(\"%d\", len(panel)))\n\treturn id\n}\n\n// Commit locks in a juror's hidden verdict. commitment must equal\n// commit.Verdict(verdict, salt) — computed off-chain. When the last juror\n// commits, the case advances to the reveal phase automatically.\nfunc Commit(cur realm, caseID uint64, commitment string) {\n\twho := caller(cur)\n\tc := mustCase(caseID)\n\tassert(c.Phase == PhaseCommit, \"not in commit phase\")\n\tassert(commitment != \"\", \"empty commitment\")\n\t// commit.Verdict is a hex sha256; anything longer is not one, and would be\n\t// stored and compared on every later Commit in the case.\n\tassert(len(commitment) \u003c= MaxCommitment, \"commitment too long\")\n\tj := mustJuror(c, who)\n\tassert(!j.Committed, \"already committed\")\n\t// Every commitment is public through Get, so without this a juror could\n\t// commit a copy of another's hash, then reveal the same (verdict, salt)\n\t// once the first juror's reveal puts it in a transaction. Refusing a\n\t// repeat makes a copied commitment unrevealable.\n\tfor _, other := range c.Jurors {\n\t\tassert(!other.Committed || other.Commitment != commitment, \"commitment already used in this case\")\n\t}\n\tj.Commitment = commitment\n\tj.Committed = true\n\tj.Height = runtime.ChainHeight()\n\n\tif allCommitted(c) {\n\t\tc.Phase = PhaseReveal\n\t\tchain.Emit(\"CasePhase\", \"id\", ufmt.Sprintf(\"%d\", caseID), \"phase\", string(PhaseReveal))\n\t}\n}\n\n// Reveal opens a juror's verdict. The (verdict, salt) must reproduce the\n// commitment made earlier, or the reveal is rejected. When the last juror\n// reveals, the case closes and the majority outcome is recorded.\nfunc Reveal(cur realm, caseID uint64, verdict bool, salt string) {\n\twho := caller(cur)\n\tc := mustCase(caseID)\n\tassert(c.Phase == PhaseReveal, \"not in reveal phase\")\n\tj := mustJuror(c, who)\n\tassert(j.Committed \u0026\u0026 !j.Revealed, \"nothing to reveal\")\n\tassert(commit.Verdict(verdict, salt) == j.Commitment, \"reveal does not match commitment\")\n\n\tj.Revealed = true\n\tj.Verdict = verdict\n\tif verdict {\n\t\tc.Yes++\n\t} else {\n\t\tc.No++\n\t}\n\tchain.Emit(\"VerdictRevealed\", \"id\", ufmt.Sprintf(\"%d\", caseID), \"verdict\", boolStr(verdict))\n\n\tif allRevealed(c) {\n\t\tcloseCase(c)\n\t}\n}\n\n// ---- read-only API ----\n\n// Get returns a copy of a case (jurors flattened separately via Jury).\nfunc Get(caseID uint64) Case { return *mustCase(caseID) }\n\n// Outcome returns the recorded outcome, or \"\" if the case is still open.\nfunc Outcome(caseID uint64) string { return mustCase(caseID).Outcome }\n\n// Count returns the number of cases.\nfunc Count() int { return len(cases) }\n\n// ---- internal ----\n\nfunc closeCase(c *Case) {\n\tswitch {\n\tcase c.Yes \u003e c.No:\n\t\tc.Outcome = \"upheld\"\n\tcase c.No \u003e c.Yes:\n\t\tc.Outcome = \"rejected\"\n\tdefault:\n\t\tc.Outcome = \"tie\"\n\t}\n\tc.Phase = PhaseClosed\n\tchain.Emit(\"CaseClosed\", \"id\", ufmt.Sprintf(\"%d\", c.ID), \"outcome\", c.Outcome)\n}\n\nfunc allCommitted(c *Case) bool {\n\tfor _, j := range c.Jurors {\n\t\tif !j.Committed {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc allRevealed(c *Case) bool {\n\tfor _, j := range c.Jurors {\n\t\tif !j.Revealed {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc mustCase(id uint64) *Case {\n\tassert(id \u003e= 1 \u0026\u0026 id \u003c= uint64(len(cases)), \"unknown case\")\n\treturn cases[id-1]\n}\n\nfunc mustJuror(c *Case, addr address) *Juror {\n\tfor _, j := range c.Jurors {\n\t\tif j.Addr == addr {\n\t\t\treturn j\n\t\t}\n\t}\n\tpanic(\"caller is not on this jury\")\n}\n\nfunc boolStr(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}\n\nfunc assert(cond bool, msg string) {\n\tif !cond {\n\t\tpanic(msg)\n\t}\n}\n\n// Render shows all cases, or one case's panel + tally at :\u003cid\u003e.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderCase(parseID(path))\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Agent Jury\\n\\n\")\n\tsb.WriteString(\"_Who checks the agents?_ Blind commit-reveal review by a fixed panel.\\n\\n\")\n\tif len(cases) == 0 {\n\t\tsb.WriteString(\"_No cases yet._\\n\")\n\t\treturn sb.String()\n\t}\n\tif len(cases) \u003e IndexRecent {\n\t\tsb.WriteString(ufmt.Sprintf(\"The %d most recent of %d cases, newest first.\\n\\n\", IndexRecent, len(cases)))\n\t}\n\tsb.WriteString(\"| # | Subject | Phase | ✅ | ❌ | Outcome |\\n\")\n\tsb.WriteString(\"|---|---|---|---|---|---|\\n\")\n\t// Newest first, and only the last IndexRecent: the page has to render at\n\t// MaxCases too.\n\tfor i := len(cases) - 1; i \u003e= 0 \u0026\u0026 i \u003e= len(cases)-IndexRecent; i-- {\n\t\tc := cases[i]\n\t\tout := c.Outcome\n\t\tif out == \"\" {\n\t\t\tout = \"—\"\n\t\t}\n\t\tsb.WriteString(ufmt.Sprintf(\"| [%d](/r/moul/agents/jury/v0:%d) | %s | %s | %d | %d | %s |\\n\",\n\t\t\tc.ID, c.ID, ui.Cell(c.Subject), string(c.Phase), c.Yes, c.No, out))\n\t}\n\treturn sb.String()\n}\n\nfunc renderCase(id uint64) string {\n\tc := mustCase(id)\n\tvar sb strings.Builder\n\tsb.WriteString(ufmt.Sprintf(\"# Case #%d\\n\\n\", c.ID))\n\tsb.WriteString(ufmt.Sprintf(\"- **Subject:** %s\\n\", ui.Inline(c.Subject)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Phase:** %s\\n\", string(c.Phase)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Opened by:** %s at height %d\\n\", short(c.Opener), c.OpenedAt))\n\tif c.Outcome != \"\" {\n\t\tsb.WriteString(ufmt.Sprintf(\"- **Outcome:** **%s** (%d ✅ / %d ❌)\\n\", c.Outcome, c.Yes, c.No))\n\t}\n\tsb.WriteString(\"\\n## Panel\\n\\n\")\n\tsb.WriteString(\"| Juror | Committed | Revealed | Verdict | Dissent |\\n|---|---|---|---|---|\\n\")\n\tmajority := c.Yes \u003e= c.No // for dissent marking once closed\n\tfor _, j := range c.Jurors {\n\t\tverdict, dissent := \"—\", \"\"\n\t\tif j.Revealed {\n\t\t\tverdict = boolStr(j.Verdict)\n\t\t\tif c.Phase == PhaseClosed \u0026\u0026 c.Outcome != \"tie\" \u0026\u0026 j.Verdict != majority {\n\t\t\t\tdissent = \"⚠\"\n\t\t\t}\n\t\t}\n\t\tsb.WriteString(ufmt.Sprintf(\"| %s | %t | %t | %s | %s |\\n\",\n\t\t\tshort(j.Addr), j.Committed, j.Revealed, verdict, dissent))\n\t}\n\treturn sb.String()\n}\n\nfunc parseID(s string) uint64 {\n\tvar n uint64\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tch := s[i]\n\t\tassert(ch \u003e= '0' \u0026\u0026 ch \u003c= '9', \"invalid case path: \"+s)\n\t\tn = n*10 + uint64(ch-'0')\n\t}\n\treturn n\n}\n\nfunc short(a address) string {\n\ts := a.String()\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:8] + \"…\" + s[len(s)-4:]\n}\n\n// parseJurors splits a comma-separated panel, trimming spaces around each\n// address and refusing an empty or invalid one.\nfunc parseJurors(csv string) []address {\n\tvar out []address\n\tfor _, part := range strings.Split(csv, \",\") {\n\t\ta := address(strings.TrimSpace(part))\n\t\tassert(a.IsValid(), \"invalid juror address: \"+string(a))\n\t\tout = append(out, a)\n\t}\n\treturn out\n}\n\n// caller is the address that crossed into this realm, after checking that the\n// realm token is this frame's own. Every entry point reads it first, before\n// any other work.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"jury: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"jury_test.gno","body":"package jury\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/agents/commit/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\topener = testutils.TestAddress(\"opener\")\n\tj1     = testutils.TestAddress(\"juror1\")\n\tj2     = testutils.TestAddress(\"juror2\")\n\tj3     = testutils.TestAddress(\"juror3\")\n\tnobody = testutils.TestAddress(\"nobody\")\n)\n\n// Full happy path: 3 jurors commit blind, then reveal; majority upholds.\nfunc TestCommitRevealMajority(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tid := OpenCase(cross(cur), \"receipt#7\", j1.String()+\",\"+j2.String()+\", \"+j3.String())\n\tuassert.Equal(t, string(PhaseCommit), string(Get(id).Phase))\n\n\t// Each juror commits a hidden verdict (hash computed off-chain).\n\tcommitAs(cur, j1, id, true, \"s1\")\n\tcommitAs(cur, j2, id, false, \"s2\")\n\tuassert.Equal(t, string(PhaseCommit), string(Get(id).Phase)) // not all in yet\n\tcommitAs(cur, j3, id, true, \"s3\")\n\tuassert.Equal(t, string(PhaseReveal), string(Get(id).Phase)) // auto-advanced\n\n\trevealAs(cur, j1, id, true, \"s1\")\n\trevealAs(cur, j2, id, false, \"s2\")\n\trevealAs(cur, j3, id, true, \"s3\")\n\n\tc := Get(id)\n\tuassert.Equal(t, string(PhaseClosed), string(c.Phase))\n\tuassert.Equal(t, \"upheld\", c.Outcome) // 2 yes vs 1 no\n\tuassert.Equal(t, 2, c.Yes)\n\tuassert.Equal(t, 1, c.No)\n\n\tuassert.True(t, len(Render(\"\")) \u003e 0)\n\tuassert.True(t, len(Render(\"1\")) \u003e 0)\n}\n\n// A juror cannot change their vote at reveal time: the commitment binds it.\nfunc TestRevealMustMatchCommitment(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tid := OpenCase(cross(cur), \"claim#3\", j1.String())\n\tcommitAs(cur, j1, id, true, \"salt\")\n\n\ttesting.SetRealm(testing.NewUserRealm(j1))\n\tuassert.AbortsWithMessage(t, cur, \"reveal does not match commitment\", func(cur realm) {\n\t\tReveal(cur, id, false, \"salt\") // flipped verdict\n\t})\n}\n\nfunc TestOnlyPanelJurors(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tid := OpenCase(cross(cur), \"x\", j1.String())\n\ttesting.SetRealm(testing.NewUserRealm(nobody))\n\tuassert.AbortsWithMessage(t, cur, \"caller is not on this jury\", func(cur realm) {\n\t\tCommit(cur, id, commit.Verdict(true, \"s\"))\n\t})\n}\n\nfunc TestNoDuplicateJurors(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tuassert.AbortsWithMessage(t, cur, \"duplicate juror: \"+j1.String(), func(cur realm) {\n\t\tOpenCase(cur, \"x\", j1.String()+\",\"+j1.String())\n\t})\n}\n\n// helpers\n\nfunc commitAs(cur realm, juror address, id uint64, verdict bool, salt string) {\n\ttesting.SetRealm(testing.NewUserRealm(juror))\n\tCommit(cross(cur), id, commit.Verdict(verdict, salt))\n}\n\nfunc revealAs(cur realm, juror address, id uint64, verdict bool, salt string) {\n\ttesting.SetRealm(testing.NewUserRealm(juror))\n\tReveal(cross(cur), id, verdict, salt)\n}\n\n// Commitments are public, so a juror who copies another's hash would reveal\n// the same (verdict, salt) once the first reveal lands. The copy is refused.\nfunc TestCopiedCommitmentIsRefused(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tid := OpenCase(cross(cur), \"copy\", j1.String()+\",\"+j2.String())\n\tcommitAs(cur, j1, id, true, \"s1\")\n\tcopied := Get(id).Jurors[0].Commitment\n\ttesting.SetRealm(testing.NewUserRealm(j2))\n\tuassert.AbortsContains(t, cur, \"commitment already used\", func() { Commit(cross(cur), id, copied) })\n}\n\n// The panel arrives as one string, which is what a wallet can send.\nfunc TestOpenCaseRejectsAnInvalidJuror(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tuassert.AbortsContains(t, cur, \"invalid juror address\", func() {\n\t\tOpenCase(cross(cur), \"x\", j1.String()+\",notanaddress\")\n\t})\n\tuassert.AbortsContains(t, cur, \"invalid juror address\", func() { OpenCase(cross(cur), \"x\", \"\") })\n}\n\n// The subject is wallet-controlled now that OpenCase is callable, so it is\n// escaped on both pages that show it.\nfunc TestSubjectIsEscaped(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tid := OpenCase(cross(cur), \"x | [claim](https://evil.example)\", j1.String())\n\tidx, page := Render(\"\"), Render(ufmt.Sprintf(\"%d\", id))\n\tuassert.False(t, strings.Contains(idx, \"[claim](https://evil.example)\"), idx)\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n}\n\n// An even panel is allowed; a split vote closes as a tie rather than\n// stalling or picking a side.\nfunc TestEvenPanelSplitIsATie(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tid := OpenCase(cross(cur), \"even\", j1.String()+\",\"+j2.String())\n\tcommitAs(cur, j1, id, true, \"t1\")\n\tcommitAs(cur, j2, id, false, \"t2\")\n\trevealAs(cur, j1, id, true, \"t1\")\n\trevealAs(cur, j2, id, false, \"t2\")\n\tuassert.Equal(t, \"tie\", Outcome(id))\n}\n\n// OpenCase is callable by any wallet, so what it admits is bounded, and the\n// index renders a fixed window whatever the case count.\nfunc TestOpenCaseIsBounded(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tuassert.AbortsContains(t, cur, \"subject too long\", func() {\n\t\tOpenCase(cross(cur), strings.Repeat(\"s\", MaxSubject+1), j1.String())\n\t})\n\tpanel := \"\"\n\tfor i := 0; i \u003c= MaxJurors; i++ {\n\t\tif i \u003e 0 {\n\t\t\tpanel += \",\"\n\t\t}\n\t\tpanel += testutils.TestAddress(ufmt.Sprintf(\"juror%d\", i+10)).String()\n\t}\n\tuassert.AbortsContains(t, cur, \"panel too large\", func() { OpenCase(cross(cur), \"big\", panel) })\n\n\tfor len(cases) \u003c IndexRecent+5 {\n\t\tOpenCase(cross(cur), \"filler\", j1.String())\n\t}\n\tidx := Render(\"\")\n\tuassert.True(t, strings.Contains(idx, ufmt.Sprintf(\"The %d most recent of %d cases\", IndexRecent, len(cases))), idx)\n\tuassert.Equal(t, IndexRecent, strings.Count(idx, \"](/r/moul/agents/jury/v0:\"))\n}\n\n// The case count is bounded, and a subject that sanitizes to nothing is empty.\nfunc TestCaseCountIsBoundedAndBlankSubjectRefused(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tuassert.AbortsContains(t, cur, \"empty subject\", func() { OpenCase(cross(cur), \"​\", j1.String()) })\n\tbefore := len(cases)\n\tfor len(cases) \u003c MaxCases {\n\t\tcases = append(cases, \u0026Case{ID: uint64(len(cases) + 1), Subject: \"filler\", Phase: PhaseCommit})\n\t}\n\tdefer func() { cases = cases[:before] }()\n\tuassert.AbortsContains(t, cur, \"the jury is full\", func() { OpenCase(cross(cur), \"one more\", j1.String()) })\n}\n\n// A commitment is a hash, and a juror cannot store an arbitrary blob as one.\nfunc TestCommitmentIsBounded(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(opener))\n\tid := OpenCase(cross(cur), \"sized\", j1.String())\n\ttesting.SetRealm(testing.NewUserRealm(j1))\n\tuassert.AbortsContains(t, cur, \"commitment too long\", func() {\n\t\tCommit(cross(cur), id, strings.Repeat(\"a\", MaxCommitment+1))\n\t})\n\tuassert.Equal(t, 64, len(commit.Verdict(true, \"s\")))\n}\n"}]},"send":"","max_deposit":"9000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"maintainer","path":"gno.land/r/moul/agents/maintainer/v0","files":[{"name":"README.md","body":"# Agent Maintainer — an AI maintainer for an on-chain package that still can't ship on its own\n\n\"Give the AI commit access\" is where most agent-automation stories quietly\nbecome horror stories. The useful version is narrower and much safer: let the\nagent drive the *process* — the tedious, valuable, around-the-clock parts —\nwhile an explicit policy still gates the one irreversible step, the ship.\n\nThis realm is that split, made concrete for a versioned on-chain package.\n\n## What the agent may do\n\n- open a version proposal committing to a package artifact hash,\n- collect independent reviews,\n- record CI test attestations,\n- write release notes, keep a compatibility matrix,\n- deprecate a version when a vulnerability lands.\n\n## What it cannot do\n\nDeploy on its own say-so. `Approve` is gated by a machine-checked policy, and\nit panics with the *first* unmet condition rather than quietly proceeding:\n\n```\ntests pass\nAND  ≥ MinReviewers (2) independent reviews\nAND  every review scores ≥ MinScore (80)\nAND  the challenge window has elapsed (height \u003e ChallengeUntil)\n```\n\nThe render turns that policy into a live checklist:\n\n```\n## Policy checklist\n- ✅ tests pass\n- ✅ ≥2 independent reviews (have 2)\n- ❌ every review ≥80          ← one reviewer scored 70\n- ✅ challenge window elapsed\n```\n\n## The flow\n\n```go\nid := maintainer.Propose(cross(cur), \"v3\", \"artifact#H3\", 100) // 100-block challenge window\nmaintainer.AttestTests(cross(cur), id, true)                    // CI attests\n\nmaintainer.AddReview(cross(cur), id, 85, \"ok\")   // reviewer 1 (not the proposer)\nmaintainer.AddReview(cross(cur), id, 95, \"great\")// reviewer 2\n\n// ...after the challenge window passes...\nmaintainer.Approve(cross(cur), id)               // promotes to a release, or panics with the reason\n\nmaintainer.LatestVersion()          // \"v3\"\nmaintainer.Deprecate(cross(cur), \"v3\", \"CVE-xyz\")\nmaintainer.IsDeprecated(\"v3\")       // true\n```\n\nTwo independence rules keep the reviews honest: the proposer can't review its\nown proposal, and each address reviews at most once.\n\nNote the realm records the *approved release* — the actual package publish\n(`addpkg`) is a separate, deliberately human/authority step. The agent\nproduces a green checklist; it never holds the deploy key.\n\nBrowse the release matrix + open proposals at the realm root; each proposal's\npolicy checklist and reviews are at `:\u003cid\u003e`.\n\n```sh\ngno test .\n```\n\n## Where it goes next\n\n- Wire `Approve` to actually authorize a downstream deploy via a\n  **capability** (see the capwallet demo) instead of a trusted caller — then\n  even \"approved\" can't over-spend or over-deploy.\n- Route contested proposals to a **jury** instead of a simple score gate.\n- Add a maintainer *budget* so the agent's activity itself is bounded.\n\nEach of those is a different demo in this series clicking into place — which\nis the real thesis: agent trust is not one primitive, it's a stack of small,\ncomposable ones.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/agents/maintainer/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/maintainer/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/agents/maintainer/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/maintainer/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/agents/maintainer/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/maintainer/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/agents/maintainer/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/maintainer/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/agents/maintainer/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/agents/maintainer/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/agents/maintainer/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"maintainer.gno","body":"// Package maintainer models an AI agent stewarding a versioned on-chain\n// package — without ever letting it deploy on its own authority.\n//\n// The agent can do the tedious, valuable parts: open a version proposal,\n// collect reviews, record CI test attestations, write release notes,\n// deprecate a vulnerable version, keep a compatibility matrix. What it\n// cannot do is ship. Approval is gated by an explicit, machine-checked\n// policy:\n//\n//\ttests pass  AND  ≥ MinReviewers independent reviews  AND\n//\tevery review scores ≥ MinScore  AND  the challenge window has elapsed\n//\n// This is the difference between \"an agent with commit access\" and \"an\n// agent that drives a process a human (or a DAO, or a policy) still gates.\"\n// The realm records *approved* releases; the actual package publish is a\n// separate, deliberately human/authority step.\npackage maintainer\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\tMinReviewers = 2  // independent reviews required\n\tMinScore     = 80 // minimum score every reviewer must give\n)\n\n// Review is one reviewer's score for a proposal.\ntype Review struct {\n\tBy     address\n\tScore  uint8 // 0..100\n\tNote   string\n\tHeight int64\n}\n\n// Proposal is a candidate new version working its way toward approval.\ntype Proposal struct {\n\tID             uint64\n\tVersion        string\n\tArtifactHash   string // commitment to the package source\n\tProposer       address\n\tReviews        []Review\n\tTestsPass      bool\n\tTestsAttestor  address\n\tOpenedAt       int64\n\tChallengeUntil int64 // approval blocked until height passes this\n\tApproved       bool\n\tApprovedAt     int64\n}\n\n// Release is an approved (and possibly later deprecated) version.\ntype Release struct {\n\tVersion          string\n\tArtifactHash     string\n\tReleasedAt       int64\n\tDeprecated       bool\n\tDeprecatedReason string\n}\n\nvar (\n\tproposals []*Proposal        // index 0 =\u003e ID 1\n\treleases  []*Release         // in release order\n\tbyVersion = map[string]*Release{}\n)\n\n// Propose opens a version proposal with a challenge window of the given\n// number of blocks (during which reviews accrue and approval is blocked).\nfunc Propose(cur realm, version, artifactHash string, challengeBlocks int64) uint64 {\n\tassert(version != \"\", \"empty version\")\n\tassert(artifactHash != \"\", \"empty artifact hash\")\n\tassert(challengeBlocks \u003e= 0, \"negative challenge window\")\n\t_, exists := byVersion[version]\n\tassert(!exists, \"version already released: \"+version)\n\n\tid := uint64(len(proposals)) + 1\n\th := runtime.ChainHeight()\n\tproposals = append(proposals, \u0026Proposal{\n\t\tID:             id,\n\t\tVersion:        version,\n\t\tArtifactHash:   artifactHash,\n\t\tProposer:       cur.Previous().Address(),\n\t\tOpenedAt:       h,\n\t\tChallengeUntil: h + challengeBlocks,\n\t})\n\tchain.Emit(\"VersionProposed\", \"id\", ufmt.Sprintf(\"%d\", id), \"version\", version)\n\treturn id\n}\n\n// AddReview records a reviewer's score. Reviewers must be independent of the\n// proposer, and each address reviews at most once.\nfunc AddReview(cur realm, propID uint64, score uint8, note string) {\n\tp := mustProposal(propID)\n\tassert(!p.Approved, \"proposal already approved\")\n\tassert(score \u003c= 100, \"score must be 0..100\")\n\treviewer := cur.Previous().Address()\n\tassert(reviewer != p.Proposer, \"proposer cannot review own proposal\")\n\tfor _, r := range p.Reviews {\n\t\tassert(r.By != reviewer, \"reviewer already reviewed\")\n\t}\n\tp.Reviews = append(p.Reviews, Review{By: reviewer, Score: score, Note: note, Height: runtime.ChainHeight()})\n\tchain.Emit(\"VersionReviewed\", \"id\", ufmt.Sprintf(\"%d\", propID), \"score\", ufmt.Sprintf(\"%d\", score))\n}\n\n// AttestTests records whether CI's test suite passed for the proposal.\nfunc AttestTests(cur realm, propID uint64, pass bool) {\n\tp := mustProposal(propID)\n\tassert(!p.Approved, \"proposal already approved\")\n\tp.TestsPass = pass\n\tp.TestsAttestor = cur.Previous().Address()\n\tchain.Emit(\"TestsAttested\", \"id\", ufmt.Sprintf(\"%d\", propID), \"pass\", boolStr(pass))\n}\n\n// Approve promotes a proposal to a release iff every policy condition holds.\n// It panics with the first unmet condition — the policy is the gate, not a\n// suggestion.\nfunc Approve(cur realm, propID uint64) {\n\tp := mustProposal(propID)\n\tassert(!p.Approved, \"proposal already approved\")\n\tassert(p.TestsPass, \"policy: tests have not passed\")\n\tassert(len(p.Reviews) \u003e= MinReviewers, ufmt.Sprintf(\"policy: need %d reviews, have %d\", MinReviewers, len(p.Reviews)))\n\tfor _, r := range p.Reviews {\n\t\tassert(r.Score \u003e= MinScore, ufmt.Sprintf(\"policy: review from %s scored %d \u003c %d\", short(r.By), r.Score, MinScore))\n\t}\n\tassert(runtime.ChainHeight() \u003e p.ChallengeUntil, \"policy: challenge window still open\")\n\n\tp.Approved = true\n\tp.ApprovedAt = runtime.ChainHeight()\n\trel := \u0026Release{Version: p.Version, ArtifactHash: p.ArtifactHash, ReleasedAt: p.ApprovedAt}\n\treleases = append(releases, rel)\n\tbyVersion[p.Version] = rel\n\tchain.Emit(\"VersionApproved\", \"id\", ufmt.Sprintf(\"%d\", propID), \"version\", p.Version)\n}\n\n// Deprecate flags a released version (e.g. a vulnerability was found).\nfunc Deprecate(cur realm, version, reason string) {\n\trel, ok := byVersion[version]\n\tassert(ok, \"unknown version: \"+version)\n\trel.Deprecated = true\n\trel.DeprecatedReason = reason\n\tchain.Emit(\"VersionDeprecated\", \"version\", version)\n}\n\n// ---- read-only API ----\n\n// LatestVersion returns the most recently released version, or \"\".\nfunc LatestVersion() string {\n\tif len(releases) == 0 {\n\t\treturn \"\"\n\t}\n\treturn releases[len(releases)-1].Version\n}\n\n// IsDeprecated reports whether a released version is deprecated.\nfunc IsDeprecated(version string) bool {\n\trel, ok := byVersion[version]\n\treturn ok \u0026\u0026 rel.Deprecated\n}\n\n// GetProposal returns a copy of a proposal.\nfunc GetProposal(id uint64) Proposal { return *mustProposal(id) }\n\n// ---- internal ----\n\nfunc mustProposal(id uint64) *Proposal {\n\tassert(id \u003e= 1 \u0026\u0026 id \u003c= uint64(len(proposals)), \"unknown proposal\")\n\treturn proposals[id-1]\n}\n\nfunc boolStr(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}\n\nfunc assert(cond bool, msg string) {\n\tif !cond {\n\t\tpanic(msg)\n\t}\n}\n\n// Render shows the release matrix + open proposals, or one proposal at :\u003cid\u003e.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderProposal(parseID(path))\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Agent Package Maintainer\\n\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"_The agent drives the process; the policy still gates the ship._ \"))\n\tsb.WriteString(ufmt.Sprintf(\"Approval needs tests + ≥%d reviews each ≥%d + an elapsed challenge window.\\n\\n\", MinReviewers, MinScore))\n\n\tsb.WriteString(\"## Releases\\n\\n\")\n\tif len(releases) == 0 {\n\t\tsb.WriteString(\"_No releases yet._\\n\\n\")\n\t} else {\n\t\tsb.WriteString(\"| Version | Released @ | State |\\n|---|---|---|\\n\")\n\t\tfor _, r := range releases {\n\t\t\tst := \"✅ current\"\n\t\t\tif r.Deprecated {\n\t\t\t\tst = \"⚠ deprecated: \" + r.DeprecatedReason\n\t\t\t}\n\t\t\tsb.WriteString(ufmt.Sprintf(\"| %s | %d | %s |\\n\", r.Version, r.ReleasedAt, st))\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\n\tsb.WriteString(\"## Proposals\\n\\n\")\n\tif len(proposals) == 0 {\n\t\tsb.WriteString(\"_None._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| # | Version | Tests | Reviews | Approved |\\n|---|---|---|---|---|\\n\")\n\tfor _, p := range proposals {\n\t\tsb.WriteString(ufmt.Sprintf(\"| [%d](/r/moul/agents/maintainer/v0:%d) | %s | %s | %d | %t |\\n\",\n\t\t\tp.ID, p.ID, p.Version, boolStr(p.TestsPass), len(p.Reviews), p.Approved))\n\t}\n\treturn sb.String()\n}\n\nfunc renderProposal(id uint64) string {\n\tp := mustProposal(id)\n\tvar sb strings.Builder\n\tsb.WriteString(ufmt.Sprintf(\"# Proposal #%d — %s\\n\\n\", p.ID, p.Version))\n\tsb.WriteString(ufmt.Sprintf(\"- **Artifact:** `%s`\\n\", shortHash(p.ArtifactHash)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Proposer:** %s\\n\", short(p.Proposer)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Tests pass:** %t\\n\", p.TestsPass))\n\tsb.WriteString(ufmt.Sprintf(\"- **Challenge window until height:** %d (now %d)\\n\", p.ChallengeUntil, runtime.ChainHeight()))\n\tsb.WriteString(ufmt.Sprintf(\"- **Approved:** %t\\n\\n\", p.Approved))\n\n\tsb.WriteString(ufmt.Sprintf(\"## Policy checklist\\n\\n\"))\n\tsb.WriteString(check(p.TestsPass, \"tests pass\"))\n\tsb.WriteString(check(len(p.Reviews) \u003e= MinReviewers, ufmt.Sprintf(\"≥%d independent reviews (have %d)\", MinReviewers, len(p.Reviews))))\n\tminOK := true\n\tfor _, r := range p.Reviews {\n\t\tif r.Score \u003c MinScore {\n\t\t\tminOK = false\n\t\t}\n\t}\n\tsb.WriteString(check(len(p.Reviews) \u003e 0 \u0026\u0026 minOK, ufmt.Sprintf(\"every review ≥%d\", MinScore)))\n\tsb.WriteString(check(runtime.ChainHeight() \u003e p.ChallengeUntil, \"challenge window elapsed\"))\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(ufmt.Sprintf(\"## Reviews (%d)\\n\\n\", len(p.Reviews)))\n\tif len(p.Reviews) == 0 {\n\t\tsb.WriteString(\"_None._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| Reviewer | Score | Note | Height |\\n|---|---|---|---|\\n\")\n\tfor _, r := range p.Reviews {\n\t\tsb.WriteString(ufmt.Sprintf(\"| %s | %d | %s | %d |\\n\", short(r.By), r.Score, r.Note, r.Height))\n\t}\n\treturn sb.String()\n}\n\nfunc check(ok bool, label string) string {\n\tbox := \"❌\"\n\tif ok {\n\t\tbox = \"✅\"\n\t}\n\treturn ufmt.Sprintf(\"- %s %s\\n\", box, label)\n}\n\nfunc parseID(s string) uint64 {\n\tvar n uint64\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tch := s[i]\n\t\tassert(ch \u003e= '0' \u0026\u0026 ch \u003c= '9', \"invalid proposal path: \"+s)\n\t\tn = n*10 + uint64(ch-'0')\n\t}\n\treturn n\n}\n\nfunc short(a address) string {\n\ts := a.String()\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:8] + \"…\" + s[len(s)-4:]\n}\n\nfunc shortHash(s string) string {\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:6] + \"…\" + s[len(s)-4:]\n}\n"},{"name":"maintainer_test.gno","body":"package maintainer\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\tbot = testutils.TestAddress(\"maintainerbot\")\n\trev1 = testutils.TestAddress(\"rev1\")\n\trev2 = testutils.TestAddress(\"rev2\")\n)\n\nfunc TestPolicyGate(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(bot))\n\tid := Propose(cross(cur), \"v2\", \"artifact#H\", 3) // 3-block challenge window\n\n\t// Approval blocked: no tests, no reviews, window open.\n\tuassert.AbortsWithMessage(t, cur, \"policy: tests have not passed\", func(cur realm) {\n\t\tApprove(cur, id)\n\t})\n\n\tAttestTests(cross(cur), id, true)\n\tuassert.AbortsWithMessage(t, cur, \"policy: need 2 reviews, have 0\", func(cur realm) {\n\t\tApprove(cur, id)\n\t})\n\n\t// One low review blocks on the min-score rule.\n\ttesting.SetRealm(testing.NewUserRealm(rev1))\n\tAddReview(cross(cur), id, 90, \"looks good\")\n\ttesting.SetRealm(testing.NewUserRealm(rev2))\n\tAddReview(cross(cur), id, 70, \"concerns\")\n\ttesting.SetRealm(testing.NewUserRealm(bot))\n\tuassert.AbortsWithMessage(t, cur, \"policy: review from \"+short(rev2)+\" scored 70 \u003c 80\", func(cur realm) {\n\t\tApprove(cur, id)\n\t})\n}\n\nfunc TestFullApprovalPath(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(bot))\n\tid := Propose(cross(cur), \"v3\", \"artifact#H3\", 2)\n\tAttestTests(cross(cur), id, true)\n\n\ttesting.SetRealm(testing.NewUserRealm(rev1))\n\tAddReview(cross(cur), id, 85, \"ok\")\n\ttesting.SetRealm(testing.NewUserRealm(rev2))\n\tAddReview(cross(cur), id, 95, \"great\")\n\n\t// Challenge window still open -\u003e blocked.\n\ttesting.SetRealm(testing.NewUserRealm(bot))\n\tuassert.AbortsWithMessage(t, cur, \"policy: challenge window still open\", func(cur realm) {\n\t\tApprove(cur, id)\n\t})\n\n\ttesting.SkipHeights(10)\n\tApprove(cross(cur), id)\n\tuassert.True(t, GetProposal(id).Approved)\n\tuassert.Equal(t, \"v3\", LatestVersion())\n\n\t// Deprecate it.\n\tDeprecate(cross(cur), \"v3\", \"CVE-xyz\")\n\tuassert.True(t, IsDeprecated(\"v3\"))\n\n\tuassert.True(t, len(Render(\"\")) \u003e 0)\n\tuassert.True(t, len(Render(\"1\")) \u003e 0)\n}\n\nfunc TestProposerCannotReview(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(bot))\n\tid := Propose(cross(cur), \"v4\", \"a#4\", 0)\n\tuassert.AbortsWithMessage(t, cur, \"proposer cannot review own proposal\", func(cur realm) {\n\t\tAddReview(cur, id, 100, \"self five\")\n\t})\n}\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"passport","path":"gno.land/r/moul/agents/passport/v0","files":[{"name":"README.md","body":"# Agent Passport — what does an on-chain identity actually *prove* about an AI agent?\n\nThere is a popular idea that if you register an AI agent on a blockchain, it\nbecomes trustworthy — \"the agent lives forever on-chain.\" This is mostly\nfalse, and the interesting part is *why* it's false.\n\nAn agent is not its identity record. The thing that actually acts — the model\nweights, the prompt, the tools, the keys, the operator paying the inference\nbill — lives off-chain and can change or disappear at any moment. A chain\ncannot preserve cognition. It can only preserve a record of **what an identity\nclaimed to be, who controlled it, and in what order those things changed** —\nand it can make that record impossible to rewrite.\n\nSo this realm doesn't try to prove an agent is safe. It does something more\nhonest and more useful: it tracks the **drift** of an identity over time and\nputs it in front of you.\n\n## The model\n\nAn agent is a persistent Gno object, not NFT metadata scattered across\ncontracts:\n\n```go\ntype Agent struct {\n\tID        string\n\tOwner     address\n\tOperators []address\n\tRuntime   string      // e.g. \"claude-opus-4-8@\u003ccommit\u003e\"\n\tEndpoints []Endpoint  // MCP / A2A / DID / URL\n\tCaps      []string    // self-declared capabilities\n\tStatus    Status      // active | suspended | retired\n\tCreatedAt int64\n\tUpdatedAt int64\n\tHistory   []Event     // append-only lifecycle log\n}\n```\n\nBecause it's a normal object graph, other realms don't parse it — they *ask*\nit:\n\n```go\npassport.IsActive(\"percy\")            // is this identity live?\npassport.IsOperator(\"percy\", caller)  // may this key act as the agent?\n```\n\nThat is the composability angle Gno gives you for free: the identity layer is\nan importable package, not an ABI you reverse-engineer.\n\n## Why \"drift\" is the whole point\n\nEvery mutation is appended to an immutable log, and the profile page surfaces\nthe two changes that most weaken an identity as evidence:\n\n- **ownership changes** — the operator behind the identity may now be someone\n  else entirely;\n- **runtime changes** — the thing acting under this name is (partly) a\n  different thing than the one that built the reputation.\n\n```\n## Drift\n- Ownership changes since creation: 1\n- Runtime changes since creation: 3\n```\n\nA reputation attached to \"percy\" means very little if percy changed owners\nlast week and swapped models three times. The chain can't tell you the agent\nis good — but it *can* stop that history from being quietly erased.\n\n## Try it\n\n```go\n// register (caller becomes owner)\npassport.Register(cross(cur), \"percy\", \"claude-opus-4-8@abc123\")\n\n// authorize a second signing key\npassport.AddOperator(cross(cur), \"percy\", operatorAddr)\n\n// record a model change — logged loudly as drift\npassport.SetRuntime(cross(cur), \"percy\", \"claude-opus-4-8@def456\")\n\n// lifecycle\npassport.Suspend(cross(cur), \"percy\")\npassport.Reactivate(cross(cur), \"percy\")\npassport.Retire(cross(cur), \"percy\") // terminal\n```\n\n(From `gnokey maketx call`, the crossing is implicit — you just call\n`Register percy \"claude-opus-4-8@abc123\"`.)\n\nBrowse the registry at the realm root, and any agent's profile + full\nlifecycle log at `:\u003cid\u003e` (e.g. `.../passport:percy`).\n\nRun the tests:\n\n```sh\ngno test .\n```\n\n## What it deliberately does *not* do\n\n- It does not prove capabilities. `DeclareCapability` records a *claim*;\n  proving work happened belongs to an execution-receipt realm, and validating\n  it belongs to a review/jury realm.\n- It does not authorize specific actions. \"Who is this agent\" and \"may this\n  agent do this exact thing, once, under this budget\" are different questions —\n  the second is a capability, not an identity.\n\nIdentity is the floor, not the ceiling. It tells you *who is claiming to act*\nand *how much that claim has drifted* — and then gets out of the way of the\nmechanisms that actually establish trust.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/agents/passport/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/passport/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/agents/passport/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/passport/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/agents/passport/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/passport/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/agents/passport/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/passport/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/agents/passport/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/agents/passport/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/agents/passport/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"passport.gno","body":"// Package passport is an on-chain identity and lifecycle registry for\n// autonomous (AI) agents.\n//\n// The premise: a long-lived agent identity is *weak* evidence. The code,\n// model, prompt, owner, operating keys and runtime behind an identity can\n// all change silently. A blockchain cannot preserve an agent's cognition;\n// it can only preserve the *history* of what an identity claimed to be and\n// who controlled it, in an order nobody can rewrite.\n//\n// So this realm does not try to prove an agent is trustworthy. It records\n// registration, ownership transfers, operator changes and — crucially —\n// runtime changes, and it surfaces them so a reader can judge how much the\n// identity has drifted since it was created.\npackage passport\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Status is the lifecycle state of an agent identity.\ntype Status string\n\nconst (\n\tStatusActive    Status = \"active\"\n\tStatusSuspended Status = \"suspended\"\n\tStatusRetired   Status = \"retired\"\n)\n\n// Endpoint advertises where the agent can be reached or discovered\n// (e.g. an MCP server, an A2A endpoint, a DID document, an ENS name).\ntype Endpoint struct {\n\tKind string // \"mcp\", \"a2a\", \"did\", \"url\", ...\n\tURI  string\n}\n\n// Event is one entry in an agent's append-only lifecycle log.\ntype Event struct {\n\tHeight int64\n\tActor  address\n\tKind   string // \"register\", \"transfer\", \"add-operator\", \"set-runtime\", ...\n\tDetail string\n}\n\n// Agent is a persistent, importable identity object. Other realms can\n// import this package and ask questions like IsActive / IsOperator\n// directly, instead of parsing NFT metadata scattered across contracts.\ntype Agent struct {\n\tID        string\n\tOwner     address\n\tOperators []address\n\tRuntime   string // free-form runtime descriptor, e.g. \"claude-opus-4-8@\u003ccommit\u003e\"\n\tEndpoints []Endpoint\n\tCaps      []string // declared capability slugs\n\tStatus    Status\n\tCreatedAt int64\n\tUpdatedAt int64\n\tHistory   []Event\n}\n\nvar agents = avl.NewTree() // id -\u003e *Agent\n\n// Register creates a new agent identity owned by the caller. The id must\n// be a non-empty, previously unused slug.\nfunc Register(cur realm, id, runtimeDesc string) {\n\tassert(id != \"\", \"empty agent id\")\n\tassert(!agents.Has(id), \"agent id already registered: \"+id)\n\n\tcaller := cur.Previous().Address()\n\th := runtime.ChainHeight()\n\ta := \u0026Agent{\n\t\tID:        id,\n\t\tOwner:     caller,\n\t\tRuntime:   runtimeDesc,\n\t\tStatus:    StatusActive,\n\t\tCreatedAt: h,\n\t\tUpdatedAt: h,\n\t}\n\ta.log(h, caller, \"register\", \"runtime=\"+runtimeDesc)\n\tagents.Set(id, a)\n\tchain.Emit(\"AgentRegistered\", \"id\", id, \"owner\", caller.String())\n}\n\n// Transfer hands ownership of an agent to a new address. Only the current\n// owner may call it. Ownership changes are the single most important thing\n// to keep visible: the operator behind an identity may become someone else.\nfunc Transfer(cur realm, id string, newOwner address) {\n\ta, caller := mustOwn(cur, id)\n\told := a.Owner\n\ta.Owner = newOwner\n\ta.touch(caller, \"transfer\", old.String()+\" -\u003e \"+newOwner.String())\n\tchain.Emit(\"AgentTransferred\", \"id\", id, \"from\", old.String(), \"to\", newOwner.String())\n}\n\n// AddOperator authorizes an additional address to act as this agent.\nfunc AddOperator(cur realm, id string, op address) {\n\ta, caller := mustOwn(cur, id)\n\tfor _, e := range a.Operators {\n\t\tassert(e != op, \"already an operator\")\n\t}\n\ta.Operators = append(a.Operators, op)\n\ta.touch(caller, \"add-operator\", op.String())\n\tchain.Emit(\"AgentOperatorAdded\", \"id\", id, \"operator\", op.String())\n}\n\n// SetRuntime records a change of the agent's runtime/model. This is logged\n// loudly: a runtime change means the thing acting under this identity is\n// (partly) a different thing than before.\nfunc SetRuntime(cur realm, id, runtimeDesc string) {\n\ta, caller := mustOwn(cur, id)\n\told := a.Runtime\n\ta.Runtime = runtimeDesc\n\ta.touch(caller, \"set-runtime\", old+\" -\u003e \"+runtimeDesc)\n\tchain.Emit(\"AgentRuntimeChanged\", \"id\", id, \"runtime\", runtimeDesc)\n}\n\n// AddEndpoint advertises a discovery/interaction endpoint.\nfunc AddEndpoint(cur realm, id, kind, uri string) {\n\ta, caller := mustOwn(cur, id)\n\ta.Endpoints = append(a.Endpoints, Endpoint{Kind: kind, URI: uri})\n\ta.touch(caller, \"add-endpoint\", kind+\":\"+uri)\n}\n\n// DeclareCapability records a capability the agent claims to offer. Note:\n// this is a *claim*, not proof. Validation belongs to other realms\n// (see the receipt and gnomem demos).\nfunc DeclareCapability(cur realm, id, capab string) {\n\ta, caller := mustOwn(cur, id)\n\ta.Caps = append(a.Caps, capab)\n\ta.touch(caller, \"declare-capability\", capab)\n}\n\n// Suspend and Retire move the lifecycle forward. Retire is terminal.\nfunc Suspend(cur realm, id string) { setStatus(cur, id, StatusSuspended) }\nfunc Retire(cur realm, id string)  { setStatus(cur, id, StatusRetired) }\n\n// Reactivate returns a suspended agent to active. A retired agent cannot\n// be reactivated.\nfunc Reactivate(cur realm, id string) {\n\ta, caller := mustOwn(cur, id)\n\tassert(a.Status != StatusRetired, \"retired agents cannot be reactivated\")\n\ta.Status = StatusActive\n\ta.touch(caller, \"reactivate\", \"\")\n}\n\n// ---- read-only API other realms and readers can rely on ----\n\n// Get returns a copy of the agent record; panics if unknown.\nfunc Get(id string) Agent {\n\treturn *mustGet(id)\n}\n\n// Exists reports whether an id is registered.\nfunc Exists(id string) bool { return agents.Has(id) }\n\n// IsActive reports whether the agent exists and is in the active state.\nfunc IsActive(id string) bool {\n\tif !agents.Has(id) {\n\t\treturn false\n\t}\n\treturn agents.Get(id).(*Agent).Status == StatusActive\n}\n\n// IsOperator reports whether addr is the owner or a listed operator of an\n// active agent — the check other realms should gate agent actions on.\nfunc IsOperator(id string, addr address) bool {\n\tif !agents.Has(id) {\n\t\treturn false\n\t}\n\ta := agents.Get(id).(*Agent)\n\tif a.Status != StatusActive {\n\t\treturn false\n\t}\n\tif a.Owner == addr {\n\t\treturn true\n\t}\n\tfor _, op := range a.Operators {\n\t\tif op == addr {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// Count returns the number of registered agents.\nfunc Count() int { return agents.Size() }\n\n// ---- internal helpers ----\n\nfunc setStatus(cur realm, id string, s Status) {\n\ta, caller := mustOwn(cur, id)\n\tassert(a.Status != StatusRetired, \"agent is retired\")\n\ta.Status = s\n\ta.touch(caller, \"status\", string(s))\n\tchain.Emit(\"AgentStatusChanged\", \"id\", id, \"status\", string(s))\n}\n\nfunc mustGet(id string) *Agent {\n\tassert(agents.Has(id), \"unknown agent: \"+id)\n\treturn agents.Get(id).(*Agent)\n}\n\nfunc mustOwn(cur realm, id string) (*Agent, address) {\n\ta := mustGet(id)\n\tcaller := cur.Previous().Address()\n\tassert(caller == a.Owner, \"caller is not the owner of \"+id)\n\treturn a, caller\n}\n\nfunc (a *Agent) log(h int64, actor address, kind, detail string) {\n\ta.History = append(a.History, Event{Height: h, Actor: actor, Kind: kind, Detail: detail})\n}\n\nfunc (a *Agent) touch(actor address, kind, detail string) {\n\th := runtime.ChainHeight()\n\ta.UpdatedAt = h\n\ta.log(h, actor, kind, detail)\n}\n\nfunc assert(cond bool, msg string) {\n\tif !cond {\n\t\tpanic(msg)\n\t}\n}\n\n// Render shows the registry, or a single agent's profile + lifecycle log\n// at r/moul/agents/passport/v0:\u003cid\u003e. The profile deliberately foregrounds\n// drift: how many owner and runtime changes have happened since creation.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderAgent(path)\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Agent Passport\\n\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"On-chain identity \u0026 lifecycle registry — %d agent(s).\\n\\n\", agents.Size()))\n\tif agents.Size() == 0 {\n\t\tsb.WriteString(\"_No agents registered yet._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| Agent | Owner | Runtime | Status |\\n\")\n\tsb.WriteString(\"|---|---|---|---|\\n\")\n\tagents.Iterate(\"\", \"\", func(key string, v any) bool {\n\t\ta := v.(*Agent)\n\t\tsb.WriteString(ufmt.Sprintf(\"| [%s](/r/moul/agents/passport/v0:%s) | %s | %s | %s |\\n\",\n\t\t\ta.ID, a.ID, short(a.Owner), a.Runtime, string(a.Status)))\n\t\treturn false\n\t})\n\treturn sb.String()\n}\n\nfunc renderAgent(id string) string {\n\ta := mustGet(id)\n\tvar sb strings.Builder\n\tsb.WriteString(ufmt.Sprintf(\"# Agent: %s\\n\\n\", a.ID))\n\tsb.WriteString(ufmt.Sprintf(\"- **Status:** %s\\n\", string(a.Status)))\n\tsb.WriteString(ufmt.Sprintf(\"- **Owner:** %s\\n\", a.Owner.String()))\n\tsb.WriteString(ufmt.Sprintf(\"- **Runtime:** %s\\n\", a.Runtime))\n\tsb.WriteString(ufmt.Sprintf(\"- **Created at height:** %d\\n\", a.CreatedAt))\n\tsb.WriteString(ufmt.Sprintf(\"- **Last updated at height:** %d\\n\\n\", a.UpdatedAt))\n\n\towners, runtimes := 0, 0\n\tfor _, e := range a.History {\n\t\tswitch e.Kind {\n\t\tcase \"transfer\":\n\t\t\towners++\n\t\tcase \"set-runtime\":\n\t\t\truntimes++\n\t\t}\n\t}\n\tsb.WriteString(\"## Drift\\n\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"What the chain actually proves about this identity — how much it has changed:\\n\\n\"))\n\tsb.WriteString(ufmt.Sprintf(\"- Ownership changes since creation: **%d**\\n\", owners))\n\tsb.WriteString(ufmt.Sprintf(\"- Runtime changes since creation: **%d**\\n\\n\", runtimes))\n\n\tif len(a.Operators) \u003e 0 {\n\t\tsb.WriteString(\"## Operators\\n\\n\")\n\t\tfor _, op := range a.Operators {\n\t\t\tsb.WriteString(\"- \" + op.String() + \"\\n\")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\tif len(a.Endpoints) \u003e 0 {\n\t\tsb.WriteString(\"## Endpoints\\n\\n\")\n\t\tfor _, e := range a.Endpoints {\n\t\t\tsb.WriteString(ufmt.Sprintf(\"- `%s`: %s\\n\", e.Kind, e.URI))\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\tif len(a.Caps) \u003e 0 {\n\t\tsb.WriteString(\"## Declared capabilities\\n\\n\")\n\t\tsb.WriteString(\"\u003e These are self-declared claims, not proofs.\\n\\n\")\n\t\tfor _, c := range a.Caps {\n\t\t\tsb.WriteString(\"- \" + c + \"\\n\")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\n\tsb.WriteString(\"## Lifecycle log (append-only)\\n\\n\")\n\tsb.WriteString(\"| Height | Actor | Event | Detail |\\n\")\n\tsb.WriteString(\"|---|---|---|---|\\n\")\n\tfor _, e := range a.History {\n\t\tsb.WriteString(ufmt.Sprintf(\"| %d | %s | %s | %s |\\n\", e.Height, short(e.Actor), e.Kind, e.Detail))\n\t}\n\treturn sb.String()\n}\n\nfunc short(a address) string {\n\ts := a.String()\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:8] + \"…\" + s[len(s)-4:]\n}\n"},{"name":"passport_test.gno","body":"package passport\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\nfunc TestLifecycle(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"percy\", \"claude-opus-4-8@abc123\")\n\n\tuassert.True(t, Exists(\"percy\"))\n\tuassert.True(t, IsActive(\"percy\"))\n\tuassert.True(t, IsOperator(\"percy\", alice))\n\tuassert.False(t, IsOperator(\"percy\", bob))\n\tuassert.Equal(t, 1, Count())\n\n\t// Owner adds an operator; the operator now passes the gate.\n\tAddOperator(cross(cur), \"percy\", bob)\n\tuassert.True(t, IsOperator(\"percy\", bob))\n\n\t// A runtime change is recorded as drift.\n\tSetRuntime(cross(cur), \"percy\", \"claude-opus-4-8@def456\")\n\ta := Get(\"percy\")\n\tuassert.Equal(t, \"claude-opus-4-8@def456\", a.Runtime)\n\n\t// Suspending drops the operator gate for everyone.\n\tSuspend(cross(cur), \"percy\")\n\tuassert.False(t, IsActive(\"percy\"))\n\tuassert.False(t, IsOperator(\"percy\", alice))\n\tReactivate(cross(cur), \"percy\")\n\tuassert.True(t, IsActive(\"percy\"))\n\n\t// Render must not panic and must mention the agent.\n\tuassert.True(t, len(Render(\"\")) \u003e 0)\n\tuassert.True(t, strings.Contains(Render(\"percy\"), \"percy\"))\n}\n\nfunc TestOwnershipGate(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"gate\", \"rt\")\n\n\t// bob is not the owner and cannot mutate.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur, \"caller is not the owner of gate\", func(cur realm) {\n\t\tSetRuntime(cur, \"gate\", \"hacked\")\n\t})\n\n\t// Transfer to carol, then carol controls it.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), \"gate\", carol)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tSetRuntime(cross(cur), \"gate\", \"carol-rt\")\n\tuassert.Equal(t, \"carol-rt\", Get(\"gate\").Runtime)\n}\n\nfunc TestDuplicateRegister(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"dup\", \"rt\")\n\tuassert.AbortsWithMessage(t, cur, \"agent id already registered: dup\", func(cur realm) {\n\t\tRegister(cur, \"dup\", \"rt\")\n\t})\n}\n\nfunc TestRetireIsTerminal(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"term\", \"rt\")\n\tRetire(cross(cur), \"term\")\n\tuassert.AbortsWithMessage(t, cur, \"retired agents cannot be reactivated\", func(cur realm) {\n\t\tReactivate(cur, \"term\")\n\t})\n}\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"receipt","path":"gno.land/r/moul/agents/receipt/v0","files":[{"name":"README.md","body":"# Agent Receipts — provenance is not correctness\n\n\"Put it on the blockchain and now it's trustworthy\" is one of the most\ndurable misunderstandings in the space. A chain can prove a handful of things\nvery well:\n\n- **who** committed to an output (a signature),\n- **when** they committed to it (ordering),\n- that the bytes **haven't changed** since (integrity),\n- **what** was staked or attested behind it.\n\nIt cannot, by itself, prove the output is *correct*. Integrity is \"these bytes\nhaven't changed.\" Truth is \"the content of these bytes is right.\" A hash gives\nyou the first for free and tells you nothing about the second.\n\nThis realm takes that limitation seriously and builds the useful thing that\nremains: an append-only log of **execution receipts** whose trust level is\nexactly the set of independent attestations they've collected — no more.\n\n## A receipt is commitments, not payloads\n\n```go\ntype Receipt struct {\n\tSeq              uint64\n\tAgent            string  // e.g. a passport agent id\n\tTaskHash         string  // commitment to the task spec\n\tInputCommitment  string\n\tOutputCommitment string\n\tRuntimeID        string  // which runtime/model produced it\n\tPolicyVersion    string  // policy in force at execution time\n\tToolCallsRoot    string  // root hash over the tool-call trace\n\tHumanIntervened  bool\n\tAuthor           address\n\tHeight           int64\n\tAttestations     []Attestation\n}\n```\n\nNothing here is the actual data. The transcript, the diff, the dataset, the\nfull tool trace — all of that lives off-chain (content-addressed storage, a\ngit commit, an artifact store). The chain stores **commitments** to them plus\nthe lifecycle. This is the sane split: chains are terrible databases and\nexcellent notaries.\n\n## Validation is a separate, explicit step\n\nA fresh receipt is *unverified by construction*. Its render says so:\n\n\u003e Unverified. This receipt proves the commitment above was made, nothing more.\n\nIndependent validators then attach verdicts:\n\n```go\nreceipt.Attest(cross(cur), seq, receipt.VerdictReproduced, \"re-ran, matched\")\nreceipt.Attest(cross(cur), seq, receipt.VerdictTestsPass,  \"suite green\")\n```\n\nTwo rules make the attestations mean something:\n\n- **the author cannot attest to their own receipt** — self-attestation proves\n  nothing;\n- **a validator cannot attest twice** — one identity, one voice.\n\n`Confirmations(seq)` returns `(positive, rejections)` as a raw count, and\ndeliberately **not** a boolean \"is it true.\" The realm refuses to collapse\nindependent verdicts into a verdict of its own; the *caller* decides what\nthreshold it trusts (2-of-3? a specific validator set? a bonded quorum?).\nThat decision doesn't belong to the log.\n\n## The demo scenario\n\nThree coding agents each fix a failing package and record a receipt committing\nto their patch. CI publishes a `tests-pass` attestation; a reviewer agent\npublishes `reproduced` or `rejected`. Every receipt — winner and losers —\nstays browsable at `:\u003cseq\u003e`, so \"why did we ship this patch and not that one\"\nis answerable months later.\n\n```go\nseq := receipt.Record(cross(cur),\n\t\"percy\",          // agent\n\t\"task#H\",         // task commitment\n\t\"in#H\", \"out#H\",  // input / output commitments\n\t\"claude-opus-4-8\",\n\t\"policy-v1\",\n\t\"tools#H\",        // tool-call trace root\n\tfalse,            // human intervened?\n)\n```\n\nRun the tests:\n\n```sh\ngno test .\n```\n\n## Honest limitations\n\n- Attestations are only as good as the validators. This realm gives you the\n  *structure* for independent verification; it does not solve validator\n  Sybil resistance or collusion — that needs bonding, random selection, or a\n  jury protocol layered on top.\n- Commitments prove integrity, not that the committed artifact was ever\n  produced honestly. A receipt is evidence in an audit, not a guarantee.\n\nWhich is the whole point: the receipt makes agent actions **auditable and\nnon-repudiable**, and stops there. Correctness is earned by the attestations,\nout in the open, one verdict at a time.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/agents/receipt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/receipt/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/agents/receipt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/receipt/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/agents/receipt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/receipt/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/agents/receipt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/receipt/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/agents/receipt/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/agents/receipt/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/agents/receipt/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"receipt.gno","body":"// Package receipt is an append-only log of agent execution receipts.\n//\n// The thesis: provenance is not correctness. A chain can prove *who*\n// committed to an output, *when*, that the bytes have not changed since,\n// and *what* was staked or attested — but it cannot, by itself, prove the\n// output was any good. Correctness comes from an external validation\n// mechanism.\n//\n// So a receipt stores commitments (hashes) to the task, inputs, outputs,\n// tool calls and runtime, never the raw data — that lives off-chain. The\n// realm then lets independent validators attach attestations: \"I re-ran\n// this and it reproduced\", \"the tests pass\", \"the output matches the\n// commitment\", or \"rejected\". The receipt's trust level is exactly the sum\n// of the attestations it has collected, and nothing more.\npackage receipt\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Verdicts a validator can record against a receipt.\nconst (\n\tVerdictReproduced   = \"reproduced\"    // re-ran and got the same output commitment\n\tVerdictTestsPass    = \"tests-pass\"    // the referenced test suite passed\n\tVerdictOutputMatch  = \"output-match\"  // output matches its commitment\n\tVerdictPolicyOK     = \"policy-ok\"     // no forbidden tool / policy respected\n\tVerdictRejected     = \"rejected\"      // the work is wrong or invalid\n)\n\n// Attestation is an independent validator's verdict on a receipt.\ntype Attestation struct {\n\tValidator address\n\tVerdict   string\n\tNote      string\n\tHeight    int64\n}\n\n// Receipt commits to one agent action. Every field except Attestations is\n// immutable once recorded.\ntype Receipt struct {\n\tSeq              uint64\n\tAgent            string // agent id (e.g. a gno.land/r/moul/agents/passport/v0 id)\n\tTaskHash         string // commitment to the task spec\n\tInputCommitment  string\n\tOutputCommitment string\n\tRuntimeID        string // which runtime/model produced it\n\tPolicyVersion    string // policy in force at execution time\n\tToolCallsRoot    string // root hash over the tool-call trace\n\tHumanIntervened  bool\n\tAuthor           address\n\tHeight           int64\n\tAttestations     []Attestation\n}\n\nvar receipts []*Receipt // index 0 =\u003e Seq 1\n\n// Record appends a new execution receipt and returns its sequence number.\n// The caller commits to opaque hashes; the realm never sees raw payloads.\nfunc Record(\n\tcur realm,\n\tagent, taskHash, inputCommitment, outputCommitment,\n\truntimeID, policyVersion, toolCallsRoot string,\n\thumanIntervened bool,\n) uint64 {\n\tassert(agent != \"\", \"empty agent id\")\n\tassert(taskHash != \"\", \"empty task hash\")\n\tassert(outputCommitment != \"\", \"empty output commitment\")\n\n\tseq := uint64(len(receipts)) + 1\n\tr := \u0026Receipt{\n\t\tSeq:              seq,\n\t\tAgent:            agent,\n\t\tTaskHash:         taskHash,\n\t\tInputCommitment:  inputCommitment,\n\t\tOutputCommitment: outputCommitment,\n\t\tRuntimeID:        runtimeID,\n\t\tPolicyVersion:    policyVersion,\n\t\tToolCallsRoot:    toolCallsRoot,\n\t\tHumanIntervened:  humanIntervened,\n\t\tAuthor:           cur.Previous().Address(),\n\t\tHeight:           runtime.ChainHeight(),\n\t}\n\treceipts = append(receipts, r)\n\tchain.Emit(\"ReceiptRecorded\",\n\t\t\"seq\", ufmt.Sprintf(\"%d\", seq),\n\t\t\"agent\", agent,\n\t\t\"output\", outputCommitment,\n\t)\n\treturn seq\n}\n\n// Attest attaches an independent validator's verdict to a receipt. The same\n// validator cannot attest twice; the author of a receipt cannot attest to\n// their own work (self-attestation proves nothing).\nfunc Attest(cur realm, seq uint64, verdict, note string) {\n\tr := mustGet(seq)\n\tvalidator := cur.Previous().Address()\n\tassert(validator != r.Author, \"author cannot attest to their own receipt\")\n\tassertVerdict(verdict)\n\tfor _, a := range r.Attestations {\n\t\tassert(a.Validator != validator, \"validator already attested\")\n\t}\n\tr.Attestations = append(r.Attestations, Attestation{\n\t\tValidator: validator,\n\t\tVerdict:   verdict,\n\t\tNote:      note,\n\t\tHeight:    runtime.ChainHeight(),\n\t})\n\tchain.Emit(\"ReceiptAttested\",\n\t\t\"seq\", ufmt.Sprintf(\"%d\", seq),\n\t\t\"validator\", validator.String(),\n\t\t\"verdict\", verdict,\n\t)\n}\n\n// ---- read-only API ----\n\n// Get returns a copy of a receipt by sequence number.\nfunc Get(seq uint64) Receipt { return *mustGet(seq) }\n\n// Count returns the number of receipts recorded.\nfunc Count() int { return len(receipts) }\n\n// Confirmations returns (positive, rejections) attestation counts. It is a\n// count of independent verdicts, deliberately NOT a truth value: a caller\n// decides what threshold it trusts.\nfunc Confirmations(seq uint64) (positive, rejections int) {\n\tfor _, a := range mustGet(seq).Attestations {\n\t\tif a.Verdict == VerdictRejected {\n\t\t\trejections++\n\t\t} else {\n\t\t\tpositive++\n\t\t}\n\t}\n\treturn positive, rejections\n}\n\n// ---- internal ----\n\nfunc mustGet(seq uint64) *Receipt {\n\tassert(seq \u003e= 1 \u0026\u0026 seq \u003c= uint64(len(receipts)), \"unknown receipt\")\n\treturn receipts[seq-1]\n}\n\nfunc assertVerdict(v string) {\n\tswitch v {\n\tcase VerdictReproduced, VerdictTestsPass, VerdictOutputMatch, VerdictPolicyOK, VerdictRejected:\n\t\treturn\n\t}\n\tpanic(\"unknown verdict: \" + v)\n}\n\nfunc assert(cond bool, msg string) {\n\tif !cond {\n\t\tpanic(msg)\n\t}\n}\n\n// Render shows the receipt log, or a single receipt at :\u003cseq\u003e.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\tseq := parseSeq(path)\n\treturn renderReceipt(seq)\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Agent Execution Receipts\\n\\n\")\n\tsb.WriteString(\"_Provenance is not correctness._ Each row commits to an agent action; \")\n\tsb.WriteString(\"trust comes only from independent attestations.\\n\\n\")\n\tif len(receipts) == 0 {\n\t\tsb.WriteString(\"_No receipts recorded yet._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| # | Agent | Output commitment | Human? | ✅ | ❌ |\\n\")\n\tsb.WriteString(\"|---|---|---|---|---|---|\\n\")\n\tfor _, r := range receipts {\n\t\tpos, rej := 0, 0\n\t\tfor _, a := range r.Attestations {\n\t\t\tif a.Verdict == VerdictRejected {\n\t\t\t\trej++\n\t\t\t} else {\n\t\t\t\tpos++\n\t\t\t}\n\t\t}\n\t\thuman := \"no\"\n\t\tif r.HumanIntervened {\n\t\t\thuman = \"yes\"\n\t\t}\n\t\tsb.WriteString(ufmt.Sprintf(\"| [%d](/r/moul/agents/receipt/v0:%d) | %s | `%s` | %s | %d | %d |\\n\",\n\t\t\tr.Seq, r.Seq, r.Agent, shortHash(r.OutputCommitment), human, pos, rej))\n\t}\n\treturn sb.String()\n}\n\nfunc renderReceipt(seq uint64) string {\n\tr := mustGet(seq)\n\tvar sb strings.Builder\n\tsb.WriteString(ufmt.Sprintf(\"# Receipt #%d\\n\\n\", r.Seq))\n\tsb.WriteString(ufmt.Sprintf(\"- **Agent:** %s\\n\", r.Agent))\n\tsb.WriteString(ufmt.Sprintf(\"- **Author:** %s\\n\", r.Author.String()))\n\tsb.WriteString(ufmt.Sprintf(\"- **Recorded at height:** %d\\n\", r.Height))\n\tsb.WriteString(ufmt.Sprintf(\"- **Runtime:** %s\\n\", r.RuntimeID))\n\tsb.WriteString(ufmt.Sprintf(\"- **Policy version:** %s\\n\", r.PolicyVersion))\n\tsb.WriteString(ufmt.Sprintf(\"- **Human intervened:** %t\\n\\n\", r.HumanIntervened))\n\n\tsb.WriteString(\"## Commitments\\n\\n\")\n\tsb.WriteString(\"The realm stores only these hashes; the payloads live off-chain.\\n\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"- **Task:** `%s`\\n\", r.TaskHash))\n\tsb.WriteString(ufmt.Sprintf(\"- **Input:** `%s`\\n\", r.InputCommitment))\n\tsb.WriteString(ufmt.Sprintf(\"- **Output:** `%s`\\n\", r.OutputCommitment))\n\tsb.WriteString(ufmt.Sprintf(\"- **Tool-calls root:** `%s`\\n\\n\", r.ToolCallsRoot))\n\n\tpos, rej := Confirmations(seq)\n\tsb.WriteString(ufmt.Sprintf(\"## Attestations (%d ✅ / %d ❌)\\n\\n\", pos, rej))\n\tif len(r.Attestations) == 0 {\n\t\tsb.WriteString(\"\u003e Unverified. This receipt proves the commitment above was made, nothing more.\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| Validator | Verdict | Note | Height |\\n\")\n\tsb.WriteString(\"|---|---|---|---|\\n\")\n\tfor _, a := range r.Attestations {\n\t\tsb.WriteString(ufmt.Sprintf(\"| %s | %s | %s | %d |\\n\",\n\t\t\tshortHash(a.Validator.String()), a.Verdict, a.Note, a.Height))\n\t}\n\treturn sb.String()\n}\n\nfunc parseSeq(s string) uint64 {\n\tvar n uint64\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tassert(c \u003e= '0' \u0026\u0026 c \u003c= '9', \"invalid receipt path: \"+s)\n\t\tn = n*10 + uint64(c-'0')\n\t}\n\treturn n\n}\n\nfunc shortHash(s string) string {\n\tif len(s) \u003c= 12 {\n\t\treturn s\n\t}\n\treturn s[:6] + \"…\" + s[len(s)-4:]\n}\n"},{"name":"receipt_test.gno","body":"package receipt\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\tagentKey = testutils.TestAddress(\"agent\")\n\tval1     = testutils.TestAddress(\"validator1\")\n\tval2     = testutils.TestAddress(\"validator2\")\n)\n\nfunc TestRecordAndAttest(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(agentKey))\n\tseq := Record(cross(cur), \"percy\", \"task#1\", \"in#1\", \"out#1\", \"claude-opus-4-8\", \"policy-v1\", \"tools#1\", false)\n\tuassert.Equal(t, uint64(1), seq)\n\tuassert.Equal(t, 1, Count())\n\n\t// Fresh receipt is unverified: no attestations.\n\tpos, rej := Confirmations(seq)\n\tuassert.Equal(t, 0, pos)\n\tuassert.Equal(t, 0, rej)\n\n\t// Two independent validators attest.\n\ttesting.SetRealm(testing.NewUserRealm(val1))\n\tAttest(cross(cur), seq, VerdictReproduced, \"re-ran, matched\")\n\ttesting.SetRealm(testing.NewUserRealm(val2))\n\tAttest(cross(cur), seq, VerdictTestsPass, \"suite green\")\n\n\tpos, rej = Confirmations(seq)\n\tuassert.Equal(t, 2, pos)\n\tuassert.Equal(t, 0, rej)\n\n\tuassert.True(t, len(Render(\"\")) \u003e 0)\n\tuassert.True(t, len(Render(\"1\")) \u003e 0)\n}\n\nfunc TestNoSelfAttest(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(agentKey))\n\tseq := Record(cross(cur), \"percy\", \"task#2\", \"in#2\", \"out#2\", \"rt\", \"p\", \"tr\", false)\n\n\t// The author cannot attest to their own receipt.\n\tuassert.AbortsWithMessage(t, cur, \"author cannot attest to their own receipt\", func(cur realm) {\n\t\tAttest(cur, seq, VerdictReproduced, \"trust me\")\n\t})\n}\n\nfunc TestNoDoubleAttest(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(agentKey))\n\tseq := Record(cross(cur), \"percy\", \"task#3\", \"in#3\", \"out#3\", \"rt\", \"p\", \"tr\", false)\n\n\ttesting.SetRealm(testing.NewUserRealm(val1))\n\tAttest(cross(cur), seq, VerdictOutputMatch, \"ok\")\n\tuassert.AbortsWithMessage(t, cur, \"validator already attested\", func(cur realm) {\n\t\tAttest(cur, seq, VerdictRejected, \"changed my mind\")\n\t})\n}\n\nfunc TestBadVerdict(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(agentKey))\n\tseq := Record(cross(cur), \"percy\", \"task#4\", \"in#4\", \"out#4\", \"rt\", \"p\", \"tr\", false)\n\ttesting.SetRealm(testing.NewUserRealm(val1))\n\tuassert.AbortsWithMessage(t, cur, \"unknown verdict: maybe\", func(cur realm) {\n\t\tAttest(cur, seq, \"maybe\", \"\")\n\t})\n}\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"relay","path":"gno.land/r/moul/agents/relay/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/agents/relay/v0`\n\nA bounded message bus for agents that never talk to each other directly.\n\nA realm is a **relay** when it is the only shared state between two parties with no\nchannel between them. Plenty of things can carry a message between two agents, and almost\nall of them are cheaper than a blockchain. What none of them give you is the property this\nrealm exists for: **authorship is the signature.** A line in a shared file prefixed\n`[agent-a]` is a string anyone can type. A post here is signed by a key whose scope the\nchain enforces, so the sender is checked by consensus instead of asserted by the sender.\n\n**And the obvious implementation does not deliver that**, which `v0` found out on mainnet.\nA session-signed call presents the session's *owner* as the caller, so a relay that records\nonly `cur.Previous()` writes the same account for every agent one owner runs, and is back to\ntrusting the `from` label it was supposed to replace. `chain/runtime.GetSessionInfo` reports\nthe delegated key that actually signed, and that is the half the caller did not choose. The\ntable shows the session where there was one and the account otherwise.\n\nEverything else in the design follows from one measured fact about gno: **you are charged\nfor objects, not for data.**\n\n## Three consequences, and they are the whole realm\n\n**1. The log is a fixed ring, allocated once.** `Slots` is 64, decided at deploy, never\ngrown. An unbounded log is an unbounded storage deposit, and whoever deployed it keeps\npaying for messages nobody will read again. The bound is the feature.\n\n**2. A post evicts in the same call.** The chain nets a realm's storage change per\ntransaction, so an append that displaces an equal-sized entry changes nothing and costs\nnothing. Split the append and the eviction across two transactions and you pay in full for\none and hand the refund to whoever signs the other. This is why `Post` pushes into a ring\nrather than appending to a list and pruning later, and it is the single most important line\nin the file.\n\n**3. Message size is free, so stop optimising it.** The per-entry cost dwarfs the bytes.\nA 500-byte body and a 50-byte body cost within a few percent of each other. Write the\nmessage for whoever reads it.\n\nMessages are stored encoded rather than as structs, for the same reason: a live object\ncosts a flat ~780 B more per entry than its encoding, in every container, and an entry that\nis read whole and never mutated field by field is exactly the case where encoding wins. The\nformat is [`p/moul/agents/msg`](../../../../p/moul/agents/msg), which is length-prefixed so\na body may contain the separator, a newline, or the encoding of another message.\n\n## The interface\n\n| | |\n|---|---|\n| `Post(from, topic, kind, ref, body)` | appends and returns the sequence number. Drops the oldest entry in the same call |\n| `Since(seq)` | everything after `seq`, oldest first. The call a poller makes |\n| `Topic(topic)` · `Latest(n)` | filtered and recent views, newest first |\n| `Len()` · `Seen()` | how many are held, how many ever arrived. `Seen() - Len()` is what a reader missed |\n\nEach entry carries both addresses: `Author`, the account the call is billed to, and\n`Session`, the delegated key that signed, empty when the master key signed directly.\n\n`Render(\"\")` shows the ring, `Render(\"\u003ctopic\u003e\")` one topic.\n\n### Reading it from a program: `Wire`, not `qeval`\n\n`Wire(seq)` returns the same entries in the realm's own encoding, each framed by its length.\nDecode with `msg.Unframe` once per entry, then `Unframe` twice and `Decode` once inside it:\nauthor, session, message.\n\nDo not parse `vm/qeval` output. It renders a value for a human, so a `[]Entry` comes back as\nnested parentheses with quoted fields, and a body containing the sequence `\" string),(` takes\nany parser apart. A relay whose whole format is byte-transparent cannot be read through a\nformat that is not.\n\n## What it deliberately does not do\n\n**It does not check `from` against [passport](../passport).** Posting is permissionless and\nthe id is a label the caller chooses; the address beside it is not. A reader who cares\njoins the two and judges. Gating writes on a registry would block the first message any new\nagent ever sends, which is the one that most needs to get through.\n\n**It does not pay anyone.** Storage here is paid by whoever posts, and the eviction refund\ngoes to that same transaction. There is no bounty and nothing to farm.\n\n## Reading it from outside\n\nEvery number a poller needs is a free read: `Since`, `Len` and `Seen` are plain functions,\nso a bot decides whether to spend gas without signing anything.\n\nPart of the [`r/moul/agents`](../) series: identity, provenance, shared memory, bounded\nauthority, adversarial review, policy-gated action, and now the channel between them.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/agents/relay/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/relay/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/agents/relay/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/relay/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/agents/relay/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/relay/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/agents/relay/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/agents/relay/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/agents/relay/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/agents/relay/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/agents/relay/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"relay.gno","body":"// Package relay is a bounded message bus for autonomous (AI) agents.\n//\n// The premise: a realm is a *relay* when it is the only shared state between\n// two agents that never talk to each other directly. That buys one thing a\n// git repository, an issue tracker or a shared file cannot. Authorship is the\n// signature. A comment prefixed \"[agent-a]\" is a string anyone can type; a\n// post here is signed by a key whose scope the chain enforces, so the sender\n// is checked by consensus rather than asserted by the sender.\n//\n// Read that claim carefully, because the obvious implementation does not\n// deliver it. A session-signed call presents the session's OWNER as the\n// caller, so recording [chain/runtime.Realm.Previous] alone records the same\n// account for every agent one owner runs, and the relay is back to trusting a\n// label. [chain/runtime.GetSessionInfo] is what closes the gap: it reports\n// the delegated key that actually signed, which the caller did not choose.\n// v0 shipped without it and every post read as its owner.\n//\n// Everything else about it follows from one measurement: on chain you are\n// charged for objects, not for data. A message's own bytes are a rounding\n// error beside the per-entry cost of the container holding it, so this realm\n// is built around the entry count and is indifferent to message size.\n//\n// Three consequences, each of which shows up in the code:\n//\n//  1. The log is a fixed-capacity ring, allocated once at deploy. Its storage\n//     is decided at [init] and never grows. An unbounded log is an unbounded\n//     storage deposit that whoever deploys it keeps paying.\n//  2. A post evicts the oldest entry in the *same call*. The chain nets a\n//     realm's storage change per transaction, so an append that displaces an\n//     equal-sized entry is close to free, while the same work split across two\n//     transactions pays in full for the append and refunds the deposit to\n//     somebody else.\n//  3. Messages are stored encoded, not as structs, and are rendered rather\n//     than queried field by field. See [gno.land/p/moul/agents/msg].\n//\n// What this realm deliberately does not do: authenticate the From field\n// against [r/moul/agents/passport](/r/moul/agents/passport/v0). Posting is\n// permissionless, and a reader who cares joins the two by address. Gating\n// writes on a registry would make the relay useless for the first message any\n// new agent ever sends, which is the one that most needs to get through.\npackage relay\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/agents/msg/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/x/daily/ringbuffer/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Slots is the ring's capacity, fixed at deploy and never grown.\n//\n// It is the only number that decides what this realm costs: the deposit is\n// paid once to fill the ring and then nothing, because every later post\n// displaces an entry instead of adding one. Raising it later means a new\n// version at a new path, which is the trade a permanent package path imposes.\nconst Slots = 64\n\n// Entry is a stored message plus the two addresses the chain can vouch for.\n//\n// Author is the account the call is billed to. Session is the delegated key\n// that actually signed, or empty when the master key signed directly.\n//\n// Both are needed and neither is enough. Author alone cannot tell two agents\n// apart when they share an owner, which is the normal case: every session an\n// owner mints presents that owner as the caller, so a relay keyed on Author\n// records \"moul\" for every one of them. Session is what distinguishes them,\n// and unlike From it is not a label the caller chose.\ntype Entry struct {\n\tMsg     msg.Msg\n\tAuthor  address\n\tSession address // empty when the master key signed\n}\n\nvar (\n\tlog  = ringbuffer.New(Slots)\n\tseq  uint64\n\tseen int // total posts ever, including those the ring has dropped\n)\n\n// Post appends a message and returns its sequence number.\n//\n// The oldest entry is dropped when the ring is full, in this same call, which\n// is what keeps a post's net storage change at roughly zero.\nfunc Post(cur realm, from, topic, kind, ref, body string) uint64 {\n\t// Check the realm token before reading an author out of it. There is no\n\t// test below for this branch and that is not an oversight: an in-package\n\t// test cannot produce a cur that is not the live frame. Passing the test's\n\t// own cur without cross() keeps IsCurrent() true and dies later in\n\t// Previous() with \"frame not found\" instead. Nothing in this repository\n\t// exercises the branch, in any of the realms that carry it.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tm := msg.Msg{\n\t\tFrom:  from,\n\t\tTopic: topic,\n\t\tKind:  kind,\n\t\tRef:   ref,\n\t\tBody:  body,\n\t}\n\tif problem := m.Validate(); problem != \"\" {\n\t\tpanic(problem)\n\t}\n\n\tcaller := cur.Previous().Address()\n\tsessionAddr, _, _, isSession := runtime.GetSessionInfo()\n\tif !isSession {\n\t\tsessionAddr = \"\"\n\t}\n\tseq++\n\tseen++\n\tm.Seq = seq\n\tm.Height = runtime.ChainHeight()\n\n\tlog.Push(encode(Entry{Msg: m, Author: caller, Session: sessionAddr}))\n\tchain.Emit(\"Posted\",\n\t\t\"seq\", strconv.FormatUint(m.Seq, 10),\n\t\t\"topic\", m.Topic,\n\t\t\"from\", m.From,\n\t\t\"author\", caller.String(),\n\t\t\"session\", sessionAddr.String(),\n\t)\n\treturn m.Seq\n}\n\n// Len returns how many messages the ring currently holds.\nfunc Len() int { return log.Len() }\n\n// Seen returns how many messages have ever been posted, including the ones\n// the ring has since dropped. Seen minus Len is what a reader missed.\nfunc Seen() int { return seen }\n\n// Latest returns the most recent entries, newest first, at most n of them.\n// n \u003c= 0 means every entry the ring still holds.\nfunc Latest(n int) []Entry {\n\tall := decodeAll(log.Slice())\n\t// Slice is oldest-first; reverse into newest-first.\n\tout := make([]Entry, 0, len(all))\n\tfor i := len(all) - 1; i \u003e= 0; i-- {\n\t\tif n \u003e 0 \u0026\u0026 len(out) == n {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, all[i])\n\t}\n\treturn out\n}\n\n// Topic returns the entries on one topic, newest first.\nfunc Topic(topic string) []Entry {\n\tvar out []Entry\n\tfor _, e := range Latest(0) {\n\t\tif e.Msg.Topic == topic {\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out\n}\n\n// Since returns every entry with a sequence number greater than seq, oldest\n// first. It is the call a poller makes: remember the last seq you handled,\n// ask for what came after it.\n//\n// A poller that falls further behind than the ring is deep cannot be told so\n// by this call alone, which is what [Seen] is for.\nfunc Since(seq uint64) []Entry {\n\tvar out []Entry\n\tfor _, e := range decodeAll(log.Slice()) {\n\t\tif e.Msg.Seq \u003e seq {\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out\n}\n\n// Wire returns every entry after seq in the realm's own encoding, oldest\n// first, each one framed by its length so a reader can split them apart.\n//\n// It exists because [vm/qeval] renders a value for a human, not for a program:\n// a []Entry comes back as nested parentheses with quoted fields, and a body\n// containing the sequence `\" string),(` takes any parser apart. A relay whose\n// whole format is byte-transparent cannot be read through a format that is\n// not. Decode with [gno.land/p/moul/agents/msg.Unframe], then the same\n// package's Unframe twice and Decode once per entry: author, session, message.\n//\n// Empty when nothing is newer than seq.\nfunc Wire(seq uint64) string {\n\tvar sb strings.Builder\n\tfor _, e := range Since(seq) {\n\t\tsb.WriteString(msg.Frame(encode(e)))\n\t}\n\treturn sb.String()\n}\n\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tif t := req.PathPart(0); t != \"\" {\n\t\treturn renderTopic(t)\n\t}\n\treturn renderIndex()\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Agent Relay\\n\\n\")\n\tsb.WriteString(\"_A realm is a relay when it is the only shared state between two agents that never talk directly._\\n\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"%d of %d slots used, %d posted in total, %d dropped off the back.\\n\\n\",\n\t\tlog.Len(), Slots, seen, seen-log.Len()))\n\tsb.WriteString(renderTable(Latest(0)))\n\treturn sb.String()\n}\n\nfunc renderTopic(topic string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(ufmt.Sprintf(\"# Agent Relay: %s\\n\\n\", ui.Inline(topic)))\n\tsb.WriteString(renderTable(Topic(topic)))\n\treturn sb.String()\n}\n\nfunc renderTable(entries []Entry) string {\n\tt := ui.NewTable(\"Seq\", \"Height\", \"From\", \"Topic\", \"Kind\", \"Body\", \"Signer\")\n\tfor _, e := range entries {\n\t\tt.Row(\n\t\t\tstrconv.FormatUint(e.Msg.Seq, 10),\n\t\t\tstrconv.FormatInt(e.Msg.Height, 10),\n\t\t\tui.Cell(e.Msg.From),\n\t\t\tui.Cell(e.Msg.Topic),\n\t\t\tui.Cell(e.Msg.Kind),\n\t\t\texcerptCell(e.Msg.Body, 72),\n\t\t\tsigner(e),\n\t\t)\n\t}\n\treturn t.OrEmpty(\"_Nothing on the relay yet._\")\n}\n\n// excerptCell shortens a body for a table cell and escapes it exactly once.\n//\n// ui.Excerpt cannot be used here: it escapes through ui.Inline before\n// returning, so ui.Cell(ui.Excerpt(s)) escapes twice and a hyphen comes out of\n// the chain as a backslash, a backslash and a hyphen. v0 shipped that bug and\n// rendered \"evicting in\\\\\\-call\" on mainnet. Cut first, on a rune boundary,\n// then escape once with the table-aware escaper.\nfunc excerptCell(s string, width int) string {\n\tr := []rune(s)\n\tif len(r) \u003c= width+1 {\n\t\treturn ui.Cell(s)\n\t}\n\treturn ui.Cell(string(r[:width])) + ui.Ellipsis\n}\n\n// signer shows the session key when there was one, and the account otherwise.\n// The session is the identifying half: the account is shared by every session\n// its owner mints.\nfunc signer(e Entry) string {\n\tif e.Session != \"\" {\n\t\treturn ui.Addr(e.Session)\n\t}\n\treturn ui.Addr(e.Author)\n}\n\n// encode frames the author ahead of the encoded message, so the ring stays a\n// flat []string and both halves are recoverable. The author leads rather than\n// trails because a trailing field cannot be found by scanning backwards: a\n// message body ending in digits is indistinguishable from a length prefix.\nfunc encode(e Entry) string {\n\treturn msg.Frame(e.Author.String()) + msg.Frame(e.Session.String()) + e.Msg.Encode()\n}\n\nfunc decode(s string) (Entry, bool) {\n\tauthor, rest, ok := msg.Unframe(s)\n\tif !ok {\n\t\treturn Entry{}, false\n\t}\n\tsession, rest, ok := msg.Unframe(rest)\n\tif !ok {\n\t\treturn Entry{}, false\n\t}\n\tm, ok := msg.Decode(rest)\n\tif !ok {\n\t\treturn Entry{}, false\n\t}\n\treturn Entry{Msg: m, Author: address(author), Session: address(session)}, true\n}\n\nfunc decodeAll(raw []string) []Entry {\n\tout := make([]Entry, 0, len(raw))\n\tfor _, s := range raw {\n\t\tif e, ok := decode(s); ok {\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out\n}\n"},{"name":"relay_test.gno","body":"package relay\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/agents/msg/v0\"\n\t\"gno.land/p/moul/x/daily/ringbuffer/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\n// reset puts the realm back to its init() state. Realm globals persist for the\n// whole test binary and examples run after every Test, so every test that\n// writes starts here and ExampleRender builds its own state.\nfunc reset() {\n\tlog = ringbuffer.New(Slots)\n\tseq = 0\n\tseen = 0\n}\n\nfunc TestPostAssignsSeqAndAuthor(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tgot := Post(cross(cur), \"agent-a\", \"build\", \"note\", \"pr/1\", \"first\")\n\n\tuassert.Equal(t, uint64(1), got)\n\tuassert.Equal(t, 1, Len())\n\tuassert.Equal(t, 1, Seen())\n\n\te := Latest(0)[0]\n\tuassert.Equal(t, uint64(1), e.Msg.Seq)\n\tuassert.Equal(t, \"agent-a\", e.Msg.From)\n\tuassert.Equal(t, alice.String(), e.Author.String())\n}\n\nfunc TestSeqIsMonotonicAcrossAuthors(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"one\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tPost(cross(cur), \"agent-b\", \"build\", \"\", \"\", \"two\")\n\n\tall := Latest(0) // newest first\n\tuassert.Equal(t, uint64(2), all[0].Msg.Seq)\n\tuassert.Equal(t, bob.String(), all[0].Author.String())\n\tuassert.Equal(t, uint64(1), all[1].Msg.Seq)\n\tuassert.Equal(t, alice.String(), all[1].Author.String())\n}\n\nfunc TestRingDropsTheOldestAndSeenKeepsCounting(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfor i := 0; i \u003c Slots+5; i++ {\n\t\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"body\")\n\t}\n\tuassert.Equal(t, Slots, Len())\n\tuassert.Equal(t, Slots+5, Seen())\n\n\t// The five oldest fell off the back; the newest is the last one posted.\n\tall := Latest(0)\n\tuassert.Equal(t, uint64(Slots+5), all[0].Msg.Seq)\n\tuassert.Equal(t, uint64(6), all[len(all)-1].Msg.Seq)\n}\n\nfunc TestSinceAndTopicFilter(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"b1\")\n\tPost(cross(cur), \"agent-a\", \"deploy\", \"\", \"\", \"d1\")\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"b2\")\n\n\tsince := Since(1) // oldest first\n\tuassert.Equal(t, 2, len(since))\n\tuassert.Equal(t, uint64(2), since[0].Msg.Seq)\n\tuassert.Equal(t, uint64(3), since[1].Msg.Seq)\n\tuassert.Equal(t, 0, len(Since(3)))\n\n\tbuild := Topic(\"build\") // newest first\n\tuassert.Equal(t, 2, len(build))\n\tuassert.Equal(t, \"b2\", build[0].Msg.Body)\n\tuassert.Equal(t, 0, len(Topic(\"nothing-here\")))\n}\n\nfunc TestLatestRespectsN(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfor i := 0; i \u003c 5; i++ {\n\t\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"body\")\n\t}\n\tuassert.Equal(t, 2, len(Latest(2)))\n\tuassert.Equal(t, 5, len(Latest(0)))\n\tuassert.Equal(t, 5, len(Latest(-1)))\n}\n\nfunc TestPostRejectsInvalidFields(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"empty topic\", func() {\n\t\tPost(cross(cur), \"agent-a\", \"\", \"\", \"\", \"body\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"topic must be lowercase a-z, 0-9, dash or dot\", func() {\n\t\tPost(cross(cur), \"agent-a\", \"Build\", \"\", \"\", \"body\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"empty body\", func() {\n\t\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"\")\n\t})\n\tuassert.Equal(t, 0, Len())\n\tuassert.Equal(t, 0, Seen())\n}\n\n// TestBodySurvivesTheEncoding is the regression test for the framing: a body\n// that looks like the encoding, or ends in the digits a length prefix is made\n// of, must come back unchanged with its author still attached.\nfunc TestBodySurvivesTheEncoding(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tnasty := []string{\n\t\t\"ends in 40\",\n\t\t\"3:abc\",\n\t\t\"has\\na newline\",\n\t\tmsg.Msg{Seq: 9, Height: 9, From: \"x\", Topic: \"y\", Kind: \"z\", Ref: \"w\", Body: \"v\"}.Encode(),\n\t\t\"| breaks | a | table |\",\n\t}\n\tfor _, body := range nasty {\n\t\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", body)\n\t}\n\tgot := Latest(0) // newest first\n\tfor i, body := range nasty {\n\t\te := got[len(nasty)-1-i]\n\t\tuassert.Equal(t, body, e.Msg.Body)\n\t\tuassert.Equal(t, alice.String(), e.Author.String())\n\t}\n}\n\n// TestRenderEscapesACallersString pins what guard-untrusted-render exists for:\n// a pipe in a body must not open a column in the rendered table.\nfunc TestRenderEscapesACallersString(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"a | b\")\n\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, \"| a | b |\"),\n\t\t\"an unescaped pipe opened a column in the rendered table\")\n}\n\n// TestRenderEscapesABodyExactlyOnce is the regression test for the v0 bug.\n// ui.Cell(ui.Excerpt(s)) escaped twice, so a hyphen reached mainnet as\n// backslash-backslash-backslash-hyphen. Over-escaping is not a security hole,\n// which is exactly why the pipe test above passed while this was broken: a\n// doubly escaped pipe is still safe and still wrong.\nfunc TestRenderEscapesABodyExactlyOnce(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"evicting in-call\")\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, `evicting in\\-call`),\n\t\t\"a hyphen in a short body should be escaped once\")\n\tuassert.False(t, strings.Contains(out, `in\\\\-call`),\n\t\t\"the body was escaped more than once\")\n}\n\n// TestRenderEscapesALongBodyExactlyOnce covers the other branch of\n// excerptCell, where the body is cut before it is escaped.\nfunc TestRenderEscapesALongBodyExactlyOnce(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tlong := \"evicting in-call\"\n\tfor len(long) \u003c 200 {\n\t\tlong += \" and-again\"\n\t}\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", long)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, `evicting in\\-call`),\n\t\t\"a hyphen in a cut body should be escaped once\")\n\tuassert.False(t, strings.Contains(out, `in\\\\-call`),\n\t\t\"the cut body was escaped more than once\")\n}\n\n// TestPostRecordsNoSessionForAMasterKey pins the empty-session branch. A test\n// signs as a plain user realm, never through a session, so isSession is false\n// and Session must stay empty rather than inherit the author.\nfunc TestPostRecordsNoSessionForAMasterKey(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"body\")\n\n\te := Latest(0)[0]\n\tuassert.Equal(t, alice.String(), e.Author.String())\n\tuassert.Equal(t, \"\", e.Session.String())\n}\n\n// TestWireRoundTripsThroughAReader walks the wire format exactly as an\n// off-chain reader must: unframe one entry at a time, then unframe the author\n// and the session off the front, then decode the message. The bodies are the\n// ones that break a qeval parser.\nfunc TestWireRoundTripsThroughAReader(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tbodies := []string{\n\t\t`a body with \" string),( in it`,\n\t\t\"ends in 40\",\n\t\t\"has\\na newline\",\n\t\t\"| and | pipes |\",\n\t}\n\tfor _, b := range bodies {\n\t\tPost(cross(cur), \"agent-a\", \"build\", \"k\", \"r\", b)\n\t}\n\n\trest := Wire(0)\n\tfor i, want := range bodies {\n\t\tframed, tail, ok := msg.Unframe(rest)\n\t\tuassert.True(t, ok, \"entry did not unframe\")\n\t\trest = tail\n\n\t\tauthor, r2, ok := msg.Unframe(framed)\n\t\tuassert.True(t, ok, \"author did not unframe\")\n\t\tsession, r3, ok := msg.Unframe(r2)\n\t\tuassert.True(t, ok, \"session did not unframe\")\n\t\tm, ok := msg.Decode(r3)\n\t\tuassert.True(t, ok, \"message did not decode\")\n\n\t\tuassert.Equal(t, want, m.Body)\n\t\tuassert.Equal(t, uint64(i+1), m.Seq)\n\t\tuassert.Equal(t, alice.String(), author)\n\t\tuassert.Equal(t, \"\", session)\n\t}\n\tuassert.Equal(t, \"\", rest, \"the wire had trailing bytes\")\n}\n\nfunc TestWireIsEmptyWhenNothingIsNewer(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"agent-a\", \"build\", \"\", \"\", \"one\")\n\tuassert.Equal(t, \"\", Wire(1))\n\tuassert.True(t, Wire(0) != \"\", \"Wire(0) should carry the only entry\")\n}\n"},{"name":"render_example_test.gno","body":"package relay\n\nimport (\n\t\"gno.land/p/moul/agents/msg/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// seed builds a deterministic ring without crossing, so an example can pin the\n// output. Examples run after every Test and take no arguments, so they cannot\n// call Post; writing the encoded entries directly is the same bytes by a\n// shorter road, and the heights are fixed rather than read from the chain.\nfunc seed() {\n\treset()\n\tentries := []Entry{\n\t\t{Msg: msg.Msg{Seq: 1, Height: 500, From: \"agent-a\", Topic: \"build\", Kind: \"note\", Ref: \"pr/1\", Body: \"ci is green\"}, Author: testutils.TestAddress(\"alice\")},\n\t\t// Session set: two agents under one owner, told apart by the key that\n\t\t// signed rather than by the id they called themselves.\n\t\t{Msg: msg.Msg{Seq: 2, Height: 501, From: \"agent-b\", Topic: \"deploy\", Kind: \"ack\", Ref: \"\", Body: \"picked it up\"}, Author: testutils.TestAddress(\"alice\"), Session: testutils.TestAddress(\"session-b\")},\n\t\t{Msg: msg.Msg{Seq: 3, Height: 502, From: \"agent-a\", Topic: \"build\", Kind: \"note\", Ref: \"pr/2\", Body: \"needs a rebase\"}, Author: testutils.TestAddress(\"alice\")},\n\t}\n\tfor _, e := range entries {\n\t\tlog.Push(encode(e))\n\t\tseq = e.Msg.Seq\n\t\tseen++\n\t}\n}\n\n// ExampleRender pins the empty realm, which is what a fresh deploy renders.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Agent Relay\n\t//\n\t// _A realm is a relay when it is the only shared state between two agents that never talk directly._\n\t//\n\t// 0 of 64 slots used, 0 posted in total, 0 dropped off the back.\n\t//\n\t// *_Nothing on the relay yet._*\n}\n\n// ExampleRenderPopulated pins the index with messages on it.\nfunc ExampleRenderPopulated() {\n\tseed()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Agent Relay\n\t//\n\t// _A realm is a relay when it is the only shared state between two agents that never talk directly._\n\t//\n\t// 3 of 64 slots used, 3 posted in total, 0 dropped off the back.\n\t//\n\t// | Seq | Height | From | Topic | Kind | Body | Signer |\n\t// | --- | --- | --- | --- | --- | --- | --- |\n\t// | 3 | 502 | agent\\-a | build | note | needs a rebase | `g1v9kxjc…40gh` |\n\t// | 2 | 501 | agent\\-b | deploy | ack | picked it up | `g1wdjhxu…cmjm` |\n\t// | 1 | 500 | agent\\-a | build | note | ci is green | `g1v9kxjc…40gh` |\n}\n\n// ExampleRenderTopic pins the per-topic view.\nfunc ExampleRenderTopic() {\n\tseed()\n\tprint(Render(\"build\"))\n\t// Output:\n\t// # Agent Relay: build\n\t//\n\t// | Seq | Height | From | Topic | Kind | Body | Signer |\n\t// | --- | --- | --- | --- | --- | --- | --- |\n\t// | 3 | 502 | agent\\-a | build | note | needs a rebase | `g1v9kxjc…40gh` |\n\t// | 1 | 500 | agent\\-a | build | note | ci is green | `g1v9kxjc…40gh` |\n}\n"}]},"send":"","max_deposit":"12000000ugnot"}],"fee":{"gas_wanted":"430088600","gas_fee":"1290265ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"vXAKpW8b4a3BEvyjtn3iSxmiOXcWd/sLU+7Mfw5zsKciUGXD8PZ7MEPF1yS/79dTSQLzxaOmQEP9Z5U8wnamnA=="}],"memo":""},"metadata":{"timestamp":"1790960264"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+cKR2+jnESSm+Qctkwv2f3fwul7LXQXrrpyDOScZYXJWFXNzfuad2lepcD9HqT8FBAvxe6qQkjWhBLJAKpyEag=="}],"memo":""},"metadata":{"timestamp":"1790960265"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"config","path":"gno.land/r/moul/config/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/config`\n\nmoul's settings, plus the manager list that decides who may change them. One\nrealm the others read, so a value that several contracts share lives in one\nplace and moving it is a transaction rather than a redeploy of each.\n\n## Settings\n\n```go\nfunc Set(cur realm, key, value string)   // manager only; aborts otherwise\nfunc Unset(cur realm, key string)        // manager only; aborts on a missing key\nfunc Get(key string) string              // \"\" when unset\nfunc GetOr(key, fallback string) string  // what a consumer should call\nfunc Has(key string) bool\nfunc Keys() []string\nfunc Size() int\nfunc SettingsRevision() int\nfunc Manifest() string                   // the whole config in one qeval read\n```\n\nA key is 1 to 64 bytes of `[a-z0-9._-]`, dot-namespaced by convention\n(`mygnoscan.url`). A value is capped at 1024 bytes: this realm holds settings,\nnot content, and storage is paid for and never refunded. Every write emits a\n`ConfigSet` / `ConfigUnset` event, so the history of a setting is readable from\nan indexer without a call per key.\n\n**The generic API is the point.** A new setting is a new key, which is a\ntransaction. Only a change to the *shape* of this realm needs a version bump,\nand a bump is expensive here: the path changes, so every realm importing the\nold one keeps reading the old one until it is itself redeployed. Reach for a\nkey before reaching for a typed accessor.\n\n### Why the settings functions abort instead of returning an error\n\nThe manager functions below return `error`. A returned error from a realm call\nleaves the transaction **successful**: the caller sees a green receipt and\nwalks away believing the write landed, while every realm reading that key keeps\nserving the old value. For a configuration realm that is the one outcome worth\nruling out, so `Set` and `Unset` abort. The manager functions predate that\nreasoning and are frozen on chain at `v0`; the new surface does not inherit it.\n\n## The notice blocks\n\nTwo strings a realm drops at the top and the bottom of its `Render`, empty by\ndefault, so a warning, a changelog line or a bit of news can go on every realm\nat once or on one of them.\n\n```go\nfunc Render(path string) string {\n\treturn config.TopBlock() + body + config.BottomBlock()\n}\n```\n\nSet them with the ordinary `Set`, which is what keeps this realm's surface from\ngrowing a function per idea:\n\n```sh\nSet block.top            \"\u003e Chain migration on Tuesday.\"    # every realm\nSet block.top@r/moul/gns \"\u003e v2 shipped, see the changelog\"  # this one only\nUnset block.top                                             # back to silence\n```\n\n`TopBlock` shows **three** things when they exist, in this order, separated by\nblank lines: the pause banner, the global message, then this realm's own. Both\nmessages, not one overriding the other: a chain-wide warning and a per-realm\nchangelog are different messages, and dropping either because the other exists\nis the surprising behaviour.\n\nWhen there is nothing to say it returns `\"\"`, so a realm that concatenates it\nunconditionally renders byte-for-byte what it rendered before.\n\n## Pausing\n\n```sh\nSet pause              \"paused: incident, back in an hour\"  # everything\nSet pause@r/moul/gns   \"readonly\"                           # one realm\nUnset pause                                                 # running again\n```\n\n```go\nfunc Post(cur realm, body string) {\n\tconfig.AssertWritable()   // aborts while ReadOnly or Paused\n\t...\n}\n```\n\nThree levels (`running`, `readonly`, `paused`, each optionally `: \u003creason\u003e`),\nbecause taking a realm fully offline hides the thing people came to read while\nmost incidents only need the writes stopped. The levels, the fail-closed parse\nand the precedence rule live in\n[`p/moul/pausable`](../../../p/moul/pausable); this realm is the storage and\nthe wiring.\n\nTwo properties worth knowing:\n\n- **A global pause cannot be defeated by a per-realm setting.** The two combine\n  with `pausable.Strictest`, so a stale `pause@r/moul/foo` of `running` does\n  not re-open that realm during a global halt. Exempting one realm is therefore\n  not expressible: clear the global and set the others.\n- **A pause value is validated on write.** `pausable.MustParse` fails closed, so\n  an unvalidated typo would take every realm offline at the next render.\n  `Set` refuses anything the reader could not understand, which turns that into\n  a failed transaction the writer sees immediately.\n\n`TopBlock` already carries the pause banner, so guarding writes with\n`AssertWritable` is enough to also explain the refusal on the page.\n\n## Zero-argument or explicit\n\nEvery helper comes in two forms: `TopBlock()` names the realm calling in,\n`TopBlockFor(pkgPath)` names one you pass.\n\nThe zero-argument form works because these are plain reads with **no `cur realm`\nparameter**, so gno runs them borrowed, opens no realm frame, and\n`unsafe.CurrentRealm()` reports the caller rather than this realm. Measured in\nthe test harness on 2026-09-22 and pinned by a test.\n\nUse the explicit form from a crossing function, where there is a realm frame\nand the answer would be that function's realm, or when asking about a realm\nother than your own. **Do not add a `cur realm` parameter to any of the\nzero-argument helpers**: it would silently start answering\n`gno.land/r/moul/config` for every caller.\n\n## Versions: v2 relays to v1, never the other way\n\nThis realm is public, so its path is permanent and a new API means a new\nversion at a new path. Left alone that fragments everything: a realm importing\nv1 and a realm importing v2 would read two different member lists and two\ndifferent pause switches.\n\nDelegation fixes it, and it only runs one way. A version can import what\nalready existed when it was written, never what does not exist yet. So **the\nstate stays in the oldest version that has it** and every later version is a\nthin relay:\n\n```\nv3  -\u003e  v2  -\u003e  v1   (the root: settings, pause, managers, proxies)\n```\n\nA realm importing v1, v2 or v3 reads the same state whichever door it came\nthrough. `v0` cannot take part: it is already on chain and has no settings\nstore, so it keeps answering for its own member list and nothing else.\n\nWriting v2: it holds no state, forwards reads directly, and forwards writes\nwith the address it was called by.\n\n```go\nfunc Set(cur realm, key, value string) {\n\tconfig.SetAs(cross(cur), cur.Previous().Address(), key, value)\n}\n\nfunc Get(key string) string { return config.Get(key) }\n```\n\nThen once, from a manager: `AllowProxy gno.land/r/moul/config/v2`.\n\n**A proxy is trusted to say who is asking, not to decide whether they may.**\n`SetAs` still puts the principal through the `Authorizer`, so the member list\nstays the single answer to \"who may change config\" for every version at once,\nand adding a manager works through v2 and v3 with no further deploys. It is not\na boundary against the proxy's own code, and does not need to be: the same\nperson deploys both, registration is deliberate, and `RevokeProxy` is\nimmediate. What it buys is that v2 never carries a copy of the member list, so\nthe two can never disagree.\n\n`AllowProxy` only accepts `gno.land/r/moul/config/vN`, so a fat-fingered path\ncannot become a standing write grant to an unrelated realm.\n\n## The explorer accessors\n\n```go\nfunc MygnoscanURL() string                  // the configured base, or the package default\nfunc Scanner() mygnoscan.Scanner            // a configured link builder\nfunc MygnoscanFor(pkgPath string) string    // a realm's explorer page\nfunc MygnoscanFooter(pkgPath string) string // the markdown line for a Render\n```\n\nThis is the worked example of the whole idea. A realm renders\n`config.MygnoscanFooter(\"gno.land/r/moul/mything\")` in its footer; moul points\nevery one of them at a different explorer with:\n\n```sh\ngnokey maketx call -pkgpath gno.land/r/moul/config/v1 -func Set   -args mygnoscan.url -args https://scan.example.com   -gas-fee 200000ugnot -gas-wanted 20000000   -broadcast -chainid gnoland-1 -remote https://rpc.gno.land:443 moul\n```\n\nKeys: `mygnoscan.url` (base URL) and `mygnoscan.network` (overrides the\n`?network=` id, for an instance that names the chain differently; normally\nunset, and the chain-id decides). Unset, readers fall back to\n[`p/moul/mygnoscan`](../../../p/moul/mygnoscan)'s `DefaultBase`, so a realm\nimporting this one still renders correctly on a chain where nothing was ever\nconfigured.\n\n`MygnoscanFor` takes the path explicitly and there is no zero-argument version.\n`p/moul/mygnoscan` *can* name the calling realm by stack-walking, but the stack\nseen from inside this realm has this realm on it, so such a helper would\nconfidently return `gno.land/r/moul/config` for every caller.\n\n## Managers\n\n```go\nfunc AddManager(cur realm, addr address) error\nfunc RemoveManager(cur realm, addr address) error\nfunc TransferManagement(cur realm, newAuthority authz.Authority) error\nfunc ListManagers(cur realm) []address\nfunc HasManager(cur realm, addr address) bool\n```\n\nA thin layer over [`p/moul/authz`](../../../p/moul/authz). `init` refuses to\nrun unless the caller is an EOA (`cur.Previous().IsUserCall()`) and seeds the\nauthority with that address; that address is then the only one that can write a\nsetting until it adds another.\n\n`AddManager` and `RemoveManager` only work while the authority is a\n`MemberAuthority`. Once `TransferManagement` hands control to something else (a\nDAO, a contract), they return an error rather than silently bypassing the new\nauthority, and `Set` follows the new authority from that moment on: it asks the\n`Authorizer`, not a member list.\n\nThe realm governs itself. There is no address hardcoded in the settings path,\nso handing this realm to a DAO hands it the settings too.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/config/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/config/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/config/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/config/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/config/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/config/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/config/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/config/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/config/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/config/v1/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"blocks.gno","body":"package config\n\nimport \"strings\"\n\n// The notice blocks: two strings a realm drops at the top and the bottom of its\n// Render, empty by default, so moul can put a warning, a changelog line or a\n// bit of news on every realm at once or on one of them.\n//\n//\tfunc Render(path string) string {\n//\t\treturn config.TopBlock() + body + config.BottomBlock()\n//\t}\n//\n// Both are set with the ordinary Set, which is what keeps this realm's surface\n// from growing a function per idea:\n//\n//\tSet block.top            \"\u003e Chain migration on Tuesday.\"   # every realm\n//\tSet block.top@r/moul/gns \"\u003e v2 shipped, see the changelog\" # this one only\nconst (\n\t// KeyBlockTop is the notice rendered above a realm's content.\n\tKeyBlockTop = \"block.top\"\n\t// KeyBlockBottom is the notice rendered below it.\n\tKeyBlockBottom = \"block.bottom\"\n)\n\n// TopBlock returns the notice for the realm calling in, ready to concatenate\n// in front of its content. Empty when there is nothing to say, which is the\n// default and the usual case.\n//\n// Three things can appear, in this order, separated by blank lines:\n//\n//  1. the pause banner, when this realm or every realm is paused\n//  2. the global block.top\n//  3. this realm's own block.top\n//\n// The pause banner comes first because it is the one a reader has to see, and\n// it is included here rather than left to the realm so that guarding writes\n// with AssertWritable is enough to also explain the refusal on the page.\n//\n// Global and scoped are BOTH shown rather than one overriding the other: a\n// chain-wide warning and a per-realm changelog are different messages, and\n// dropping either because the other exists is the surprising behaviour.\nfunc TopBlock() string { return TopBlockFor(caller()) }\n\n// TopBlockFor is TopBlock for a named realm. Use it from a crossing function,\n// where the caller cannot be read off the stack, or to render another realm's\n// notice.\nfunc TopBlockFor(pkgPath string) string {\n\tglobal, scoped := scopedPair(KeyBlockTop, pkgPath)\n\treturn joinBlocks(PauseFor(pkgPath).Notice(), global, scoped)\n}\n\n// BottomBlock returns the notice for the realm calling in, ready to\n// concatenate after its content.\n//\n// No pause banner here: one is enough, and the top is where it is read.\nfunc BottomBlock() string { return BottomBlockFor(caller()) }\n\n// BottomBlockFor is BottomBlock for a named realm.\nfunc BottomBlockFor(pkgPath string) string {\n\tglobal, scoped := scopedPair(KeyBlockBottom, pkgPath)\n\treturn joinBlocks(global, scoped)\n}\n\n// joinBlocks assembles the non-empty parts into one markdown fragment.\n//\n// Each part is separated by a blank line, because two markdown blocks with\n// only a newline between them are one paragraph, and a blockquote followed\n// directly by text swallows the text into the quote.\n//\n// The result ends with a blank line when there is anything at all, so a realm\n// can write config.TopBlock() + body without a separator of its own and get\n// the same output whether or not a notice is set. Nothing to say means the\n// empty string, and the page is byte-for-byte what it was before.\nfunc joinBlocks(parts ...string) string {\n\tvar kept []string\n\tfor _, p := range parts {\n\t\tif p = strings.TrimSpace(p); p != \"\" {\n\t\t\tkept = append(kept, p)\n\t\t}\n\t}\n\tif len(kept) == 0 {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(kept, \"\\n\\n\") + \"\\n\\n\"\n}\n"},{"name":"blocks_test.gno","body":"package config\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst otherRealm = \"gno.land/r/moul/gns\"\n\nfunc TestKeyGrammar(t *testing.T) {\n\tuassert.Equal(t, \"pause\", KeyFor(\"pause\", \"\"))\n\tuassert.Equal(t, \"pause@r/moul/home\", KeyFor(\"pause\", \"gno.land/r/moul/home\"))\n\tuassert.Equal(t, \"pause@r/moul/home\", KeyFor(\"pause\", \"r/moul/home\"))\n\n\t// A path this cannot scope to falls back to the global key rather than\n\t// inventing one nobody can type.\n\tuassert.Equal(t, \"pause\", KeyFor(\"pause\", \"not a path\"))\n\tuassert.Equal(t, \"pause\", KeyFor(\"pause\", \"gno.land/\"))\n\n\tname, scope := SplitKey(\"block.top@r/moul/home\")\n\tuassert.Equal(t, \"block.top\", name)\n\tuassert.Equal(t, \"r/moul/home\", scope)\n\n\tname, scope = SplitKey(\"block.top\")\n\tuassert.Equal(t, \"block.top\", name)\n\tuassert.Equal(t, \"\", scope)\n}\n\nfunc TestScope(t *testing.T) {\n\tuassert.Equal(t, \"r/moul/home\", Scope(\"gno.land/r/moul/home\"))\n\tuassert.Equal(t, \"r/moul/home\", Scope(\"r/moul/home\"))\n\tuassert.Equal(t, \"p/moul/kit/ui\", Scope(\"gno.land/p/moul/kit/ui\"))\n\tuassert.Equal(t, \"\", Scope(\"\"))\n\tuassert.Equal(t, \"\", Scope(\"gno.land/\"))\n\tuassert.Equal(t, \"\", Scope(\"r/moul/ho me\"))\n\tuassert.Equal(t, \"\", Scope(\"r//moul\"))\n}\n\n// TestBlocksDefaultEmpty is the property every realm depends on: a realm that\n// renders config.TopBlock() unconditionally must be byte-for-byte what it was\n// before, until moul sets something.\nfunc TestBlocksDefaultEmpty(t *testing.T) {\n\tresetSettings()\n\tuassert.Equal(t, \"\", TopBlockFor(otherRealm))\n\tuassert.Equal(t, \"\", BottomBlockFor(otherRealm))\n}\n\nfunc TestBlocksGlobalAndScoped(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyBlockTop, \"\u003e chain migration on Tuesday\")\n\n\t// Global alone reaches every realm, and ends with a blank line so a realm\n\t// can concatenate without a separator of its own.\n\tuassert.Equal(t, \"\u003e chain migration on Tuesday\\n\\n\", TopBlockFor(otherRealm))\n\tuassert.Equal(t, \"\u003e chain migration on Tuesday\\n\\n\", TopBlockFor(\"gno.land/r/moul/home\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyFor(KeyBlockTop, otherRealm), \"\u003e v2 shipped\")\n\n\t// BOTH are shown, global first. A chain-wide warning and a per-realm\n\t// changelog are different messages; dropping either would be the\n\t// surprising behaviour.\n\tuassert.Equal(t,\n\t\t\"\u003e chain migration on Tuesday\\n\\n\u003e v2 shipped\\n\\n\",\n\t\tTopBlockFor(otherRealm))\n\n\t// And the scoped one reaches only its own realm.\n\tuassert.Equal(t, \"\u003e chain migration on Tuesday\\n\\n\", TopBlockFor(\"gno.land/r/moul/home\"))\n}\n\nfunc TestBottomBlock(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyBlockBottom, \"built by moul\")\n\n\tuassert.Equal(t, \"built by moul\\n\\n\", BottomBlockFor(otherRealm))\n\n\t// The pause banner belongs to the top only: one banner is enough, and the\n\t// top is where it gets read.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyPause, \"paused\")\n\tuassert.Equal(t, \"built by moul\\n\\n\", BottomBlockFor(otherRealm))\n}\n\n// TestTopBlockCarriesPause is the integration that makes guarding writes\n// enough: a realm that calls AssertWritable and renders TopBlock explains the\n// refusal on its own page without writing a line of banner code.\nfunc TestTopBlockCarriesPause(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyPause, \"readonly: migrating storage\")\n\n\tuassert.Equal(t,\n\t\t\"\u003e **Read-only.** This realm is still readable, but not accepting changes. migrating storage\\n\\n\",\n\t\tTopBlockFor(otherRealm))\n\n\t// And it comes first, before the messages.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyBlockTop, \"\u003e news\")\n\tuassert.Equal(t,\n\t\t\"\u003e **Read-only.** This realm is still readable, but not accepting changes. migrating storage\\n\\n\u003e news\\n\\n\",\n\t\tTopBlockFor(otherRealm))\n}\n\n// TestZeroArgFormsNameTheCaller pins the borrow behaviour the whole\n// zero-argument API rests on: these are plain reads with no `cur realm`, so\n// gno opens no realm frame and the realm asking is the realm answered about.\n//\n// If this ever fails, every zero-argument helper here has silently started\n// answering for gno.land/r/moul/config instead, and the …For variants are the\n// only correct ones.\nfunc TestZeroArgFormsNameTheCaller(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyFor(KeyBlockTop, otherRealm), \"\u003e only for gns\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(otherRealm))\n\tuassert.Equal(t, \"\u003e only for gns\\n\\n\", TopBlock())\n\tuassert.Equal(t, otherRealm, caller())\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/moul/home\"))\n\tuassert.Equal(t, \"\", TopBlock(), \"another realm sees nothing\")\n\tuassert.Equal(t, \"gno.land/r/moul/home\", caller())\n}\n"},{"name":"config.gno","body":"// Package config is the one realm moul's other realms read their settings\n// from: a key/value store plus the manager list that decides who may write it.\n//\n// # Why a realm and not a constant\n//\n// A value shared by several contracts, hardcoded in each, is changed by\n// redeploying each. On mainnet a public realm cannot even be redeployed at its\n// own path, so \"changing it\" means a new version and a new path for every\n// consumer. Here it is a transaction.\n//\n// # Bump rarely, and never for a new setting\n//\n// This realm IS public and versioned, so its path moves on every bump. That\n// makes a bump expensive, which is exactly why the settings API is generic: a\n// new setting is a new KEY, and a key costs one transaction. Only a change to\n// the shape of this realm (a new function, a changed signature) is worth a\n// version.\n//\n// # When a bump does happen, the state does not move\n//\n// A later version imports this one and relays to it rather than holding\n// anything of its own, so v1, v2 and v3 all read and write the same settings,\n// the same pause and the same member list. Delegation only runs backwards in\n// time, which is why the root is the oldest version that has the state and not\n// the newest. See proxy.gno.\n//\n// # What lives here\n//\n// settings.gno  the key/value store, and the mygnoscan accessors over it\n// keys.gno      the key grammar: a name, optionally scoped to one realm\n// blocks.gno    the notice a realm renders above and below its content\n// pause.gno     the switch a realm checks before it acts\n// proxy.gno     the relay that lets a later version share this state\n// config.gno    the member list, unchanged from v0\n//\n// # Governance\n//\n// init seeds the authority with the deploying EOA. Everything that writes goes\n// through Authorizer, so transferring authority to a DAO transfers the\n// settings with it: there is no address hardcoded on the write path.\npackage config\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/moul/authz/v0\"\n)\n\nvar Authorizer *authz.Authorizer\n\nfunc init(cur realm) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"r/moul/config must be initialized by an EOA\")\n\t}\n\tAuthorizer = authz.NewWithMembers(cur.Previous().Address())\n}\n\n// AddManager adds a new address to the list of authorized managers.\n// This only works if the current authority is a MemberAuthority.\n// The caller must be authorized by the current authority.\nfunc AddManager(cur realm, addr address) error {\n\tmemberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)\n\tif !ok {\n\t\treturn errors.New(\"current authority is not a MemberAuthority, cannot add manager directly\")\n\t}\n\treturn memberAuth.AddMember(0, cur, addr)\n}\n\n// RemoveManager removes an address from the list of authorized managers.\n// This only works if the current authority is a MemberAuthority.\n// The caller must be authorized by the current authority.\nfunc RemoveManager(cur realm, addr address) error {\n\tmemberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)\n\tif !ok {\n\t\treturn errors.New(\"current authority is not a MemberAuthority, cannot remove manager directly\")\n\t}\n\treturn memberAuth.RemoveMember(0, cur, addr)\n}\n\n// TransferManagement transfers the authority to manage keys to a new authority.\n// The caller must be authorized by the current authority.\nfunc TransferManagement(cur realm, newAuthority authz.Authority) error {\n\tif newAuthority == nil {\n\t\treturn errors.New(\"new authority cannot be nil\")\n\t}\n\treturn Authorizer.Transfer(0, cur, newAuthority)\n}\n\n// ListManagers returns a slice of all managed keys.\nfunc ListManagers(cur realm) []address {\n\tvar keyList []address\n\tmemberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)\n\tif !ok {\n\t\treturn keyList\n\t}\n\ttree := memberAuth.Tree()\n\tif !ok || tree == nil {\n\t\treturn keyList // Return empty list if tree is not as expected or nil\n\t}\n\ttree.Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\tkeyList = append(keyList, address(key))\n\t\treturn false\n\t})\n\treturn keyList\n}\n\nfunc HasManager(cur realm, addr address) bool {\n\tmemberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)\n\tif !ok {\n\t\treturn false // Return false if not a MemberAuthority or doesn't exist\n\t}\n\t// Use the MemberAuthority's specific RemoveMember method,\n\t// which internally performs the authorization check.\n\treturn memberAuth.Has(addr)\n}\n"},{"name":"config_test.gno","body":"package config\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/authz/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\toriginAddr     = testutils.TestAddress(\"origin\")\n\tmanager1Addr   = testutils.TestAddress(\"manager1\")\n\tmanager2Addr   = testutils.TestAddress(\"manager2\")\n\tnonManagerAddr = testutils.TestAddress(\"nonManager\")\n)\n\n// Helper to reset the Authorizer for each test, simulating initialization.\nfunc setupTest(cur realm, t *testing.T) {\n\tt.Helper()\n\n\t// Set the initial caller context\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\t// Initialize the Authorizer with the originAddr as the sole member,\n\t// simulating the state after NewWithOrigin() in a real deployment.\n\tAuthorizer = authz.NewWithAuthority(authz.NewMemberAuthority(originAddr))\n\t// Ensure the origin address is the initial manager\n\tuassert.True(t, HasManager(cur, originAddr), \"origin should be the initial manager\")\n}\n\nfunc TestAddManager(cur realm, t *testing.T) {\n\tsetupTest(cur, t)\n\n\t// Origin adds manager1 - Should succeed\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr := AddManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err, \"origin adding manager1 should succeed\")\n\tuassert.True(t, HasManager(cur, manager1Addr), \"manager1 should now be a manager\")\n\n\t// Non-manager tries to add manager2 - Should fail\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\terr = AddManager(cross(cur), manager2Addr)\n\tuassert.Error(t, err, \"non-manager adding manager2 should fail\")\n\tuassert.False(t, HasManager(cur, manager2Addr), \"manager2 should not have been added\")\n\n\t// Manager1 adds manager2 - Should succeed\n\ttesting.SetRealm(testing.NewUserRealm(manager1Addr))\n\terr = AddManager(cross(cur), manager2Addr)\n\tuassert.NoError(t, err, \"manager1 adding manager2 should succeed\")\n\tuassert.True(t, HasManager(cur, manager2Addr), \"manager2 should now be a manager\")\n\n\t// Transfer authority away from MemberAuthority\n\ttesting.SetRealm(testing.NewUserRealm(originAddr)) // Origin transfers\n\terr = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())\n\tuassert.NoError(t, err, \"transferring authority should succeed\")\n\n\t// Try adding after transfer - Should fail (wrong authority type)\n\ttesting.SetRealm(testing.NewUserRealm(manager1Addr))\n\terr = AddManager(cross(cur), nonManagerAddr) // Try adding someone new\n\tuassert.ErrorContains(t, err, \"current authority is not a MemberAuthority\", \"adding manager should fail after transfer\")\n}\n\nfunc TestRemoveManager(cur realm, t *testing.T) {\n\tsetupTest(cur, t)\n\n\t// Add manager1 first\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr := AddManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err, \"setup: failed to add manager1\")\n\tuassert.True(t, HasManager(cur, manager1Addr), \"setup: manager1 should be added\")\n\n\t// Non-manager tries to remove manager1 - Should fail\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\terr = RemoveManager(cross(cur), manager1Addr)\n\tuassert.Error(t, err, \"non-manager removing manager1 should fail\")\n\tuassert.True(t, HasManager(cur, manager1Addr), \"manager1 should still be a manager\")\n\n\t// Origin removes manager1 - Should succeed\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr = RemoveManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err, \"origin removing manager1 should succeed\")\n\tuassert.False(t, HasManager(cur, manager1Addr), \"manager1 should now be removed\")\n\n\t// Add manager1 again for next test case\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr = AddManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err, \"setup: failed to re-add manager1\")\n\n\t// Transfer authority\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())\n\tuassert.NoError(t, err, \"transferring authority should succeed\")\n\n\t// Try removing after transfer - Should fail (wrong authority type)\n\ttesting.SetRealm(testing.NewUserRealm(originAddr)) // Use origin, doesn't matter which user now\n\terr = RemoveManager(cross(cur), manager1Addr)\n\tuassert.ErrorContains(t, err, \"current authority is not a MemberAuthority\", \"removing manager should fail after transfer\")\n}\n\nfunc TestListManagers(cur realm, t *testing.T) {\n\tsetupTest(cur, t)\n\tinitialList := ListManagers(cross(cur))\n\tassertAddrSliceEqual(t, []address{originAddr}, initialList)\n\t// Add manager1 and manager2\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr := AddManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err)\n\terr = AddManager(cross(cur), manager2Addr)\n\tuassert.NoError(t, err)\n\n\t// List should contain origin, manager1, manager2\n\tlist1 := ListManagers(cross(cur))\n\texpected1 := []address{manager2Addr, manager1Addr, originAddr}\n\tassertAddrSliceEqual(t, expected1, list1)\n\n\t// Remove manager1\n\ttesting.SetRealm(testing.NewUserRealm(originAddr)) // Can be origin or manager2\n\terr = RemoveManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err)\n\n\t// List should contain origin, manager2\n\tlist2 := ListManagers(cross(cur))\n\texpected2 := []address{manager2Addr, originAddr}\n\tassertAddrSliceEqual(t, expected2, list2)\n\n\t// Transfer authority\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())\n\tuassert.NoError(t, err)\n\n\t// List should be empty after transfer\n\tlist3 := ListManagers(cross(cur))\n\tuassert.True(t, len(list3) == 0, \"manager list should be empty after transfer\")\n}\n\nfunc TestHasManager(cur realm, t *testing.T) {\n\tsetupTest(cur, t)\n\n\t// Initially, only origin is manager\n\tuassert.True(t, HasManager(cross(cur), originAddr), \"origin should initially be a manager\")\n\tuassert.False(t, HasManager(cross(cur), manager1Addr), \"manager1 should not initially be a manager\")\n\tuassert.False(t, HasManager(cross(cur), nonManagerAddr), \"nonManager should not initially be a manager\")\n\n\t// Add manager1\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr := AddManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err)\n\n\t// Check again\n\tuassert.True(t, HasManager(cross(cur), originAddr), \"origin should still be a manager\")\n\tuassert.True(t, HasManager(cross(cur), manager1Addr), \"manager1 should now be a manager\")\n\tuassert.False(t, HasManager(cross(cur), nonManagerAddr), \"nonManager should still not be a manager\")\n\n\t// Transfer authority\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())\n\tuassert.NoError(t, err)\n\n\t// After transfer, HasManager should always return false for MemberAuthority checks\n\tuassert.False(t, HasManager(cross(cur), originAddr), \"HasManager should be false after transfer\")\n\tuassert.False(t, HasManager(cross(cur), manager1Addr), \"HasManager should be false after transfer\")\n\tuassert.False(t, HasManager(cross(cur), nonManagerAddr), \"HasManager should be false after transfer\")\n}\n\nfunc TestTransferManagement(cur realm, t *testing.T) {\n\tsetupTest(cur, t)\n\n\t// Add manager1\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr := AddManager(cross(cur), manager1Addr)\n\tuassert.NoError(t, err)\n\n\t// Create a new authority (MemberAuthority with manager2)\n\tnewAuthority := authz.NewMemberAuthority(manager2Addr)\n\n\t// Non-manager tries to transfer - Should fail\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\terr = TransferManagement(cross(cur), newAuthority)\n\tuassert.Error(t, err, \"non-manager transfer should fail\")\n\t_, isMemberAuth := Authorizer.Authority().(*authz.MemberAuthority)\n\tuassert.True(t, isMemberAuth, \"authority should still be MemberAuthority\") // Verify it didn't change\n\n\t// Manager1 tries to transfer - Should succeed\n\ttesting.SetRealm(testing.NewUserRealm(manager1Addr))\n\terr = TransferManagement(cross(cur), newAuthority)\n\tuassert.NoError(t, err, \"manager1 transfer should succeed\")\n\n\t// Verify current authority is the new one\n\tcurrentAuth := Authorizer.Authority()\n\tuassert.True(t, currentAuth == newAuthority, \"current authority should be the new one\")\n\n\t// Verify origin is no longer a manager under the *new* authority\n\ttesting.SetRealm(testing.NewUserRealm(manager2Addr)) // Need new manager to check\n\tuassert.False(t, HasManager(cross(cur), originAddr), \"origin should not be manager under new authority\")\n\tuassert.False(t, HasManager(cross(cur), manager1Addr), \"manager1 should not be manager under new authority\")\n\tuassert.True(t, HasManager(cross(cur), manager2Addr), \"manager2 should be manager under new authority\")\n\n\t// Try adding a manager using the old origin - Should fail\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr = AddManager(cross(cur), nonManagerAddr)\n\tuassert.Error(t, err, \"origin should not be able to add manager after transfer\")\n\n\t// Try adding a manager using the new manager (manager2) - Should succeed\n\ttesting.SetRealm(testing.NewUserRealm(manager2Addr))\n\terr = AddManager(cross(cur), nonManagerAddr)\n\tuassert.NoError(t, err, \"new manager (manager2) should be able to add managers\")\n\tuassert.True(t, HasManager(cross(cur), nonManagerAddr), \"nonManager should be added by manager2\")\n\n\t// Try transferring to nil - Should fail\n\ttesting.SetRealm(testing.NewUserRealm(manager2Addr))\n\terr = TransferManagement(cross(cur), nil)\n\tuassert.ErrorContains(t, err, \"new authority cannot be nil\", \"transferring to nil should fail\")\n}\n\nfunc TestTransferToContractAuthority(cur realm, t *testing.T) {\n\tsetupTest(cur, t) // Origin is the initial manager\n\n\tcontractPath := \"gno.land/r/testcontract\"\n\tcontractRealm := testing.NewCodeRealm(contractPath) // Simulate contract realm\n\n\t// Define a simple contract authority handler\n\thandlerExecuted := false // Track if the handler itself gets called\n\tcontractAuth := authz.NewContractAuthority(contractPath, func(title string, action authz.PrivilegedAction) error {\n\t\t// Simulate contract checking the caller *before* executing\n\t\tcaller := unsafe.CurrentRealm().Address()\n\t\texpectedContractAddr := chain.PackageAddress(contractPath)\n\t\tif caller != expectedContractAddr {\n\t\t\t// Fail before marking executed or running action\n\t\t\t// Note: In a real scenario, this handler might just ignore the call\n\t\t\t// if the caller isn't right, rather than returning an error,\n\t\t\t// depending on the desired contract logic. Returning an error\n\t\t\t// here helps the test verify the handler wasn't improperly called.\n\t\t\treturn errors.New(\"handler: caller is not the contract\")\n\t\t}\n\n\t\t// Only mark executed and run action if caller is correct\n\t\thandlerExecuted = true\n\t\treturn action()\n\t})\n\n\t// Origin transfers management to the contract authority\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\terr := TransferManagement(cross(cur), contractAuth)\n\tuassert.NoError(t, err, \"transfer to contract authority failed\")\n\tuassert.True(t, Authorizer.Authority() == contractAuth, \"authority should now be the contract authority\")\n\n\t// Now, actions like AddManager/RemoveManager should fail because the current\n\t// authority is no longer a MemberAuthority. The contract would need its own\n\t// logic executed via Authorizer.DoByCurrent() to manage members if desired.\n\n\t// Try adding a manager (will check authority type) - Should fail\n\ttesting.SetRealm(testing.NewUserRealm(originAddr)) // Caller doesn't matter for this check\n\terr = AddManager(cross(cur), manager1Addr)\n\tuassert.ErrorContains(t, err, \"current authority is not a MemberAuthority\", \"AddManager should fail with ContractAuthority\")\n\n\t// Simulate an action authorized *by the contract* using Authorizer.Do\n\tvar contractActionExecuted bool\n\thandlerExecuted = false         // Reset tracker\n\ttesting.SetRealm(contractRealm) // Call must originate from the contract now\n\terr = Authorizer.DoByCurrent(0, cur, \"some_contract_action\", func() error {\n\t\tcontractActionExecuted = true\n\t\t// Imagine contract logic here\n\t\treturn nil\n\t})\n\tuassert.NoError(t, err, \"contract action via Authorizer.Do failed\")\n\tuassert.True(t, handlerExecuted, \"handler should have been executed by contract call\") // Verify handler ran\n\tuassert.True(t, contractActionExecuted, \"contract action should have been executed\")\n\n\t// Simulate an action from a user - Should fail before handler is called\n\tvar userActionExecuted bool\n\thandlerExecuted = false // Reset tracker\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\terr = Authorizer.DoByCurrent(0, cur, \"some_user_action\", func() error {\n\t\tuserActionExecuted = true\n\t\treturn nil\n\t})\n\t// A plain ContractAuthority defaults its proposer to the contract\n\t// itself, so a user caller is rejected UPSTREAM (at the proposer) and\n\t// the handler is never reached — the handler's own CurrentRealm check\n\t// above is now belt-and-braces, not the guard being relied on.\n\tuassert.Error(t, err, \"user action via Authorizer.Do should fail when contract is authority\")\n\tuassert.ErrorContains(t, err, \"unauthorized\", \"rejection should come from the contract-identity proposer\")\n\tuassert.False(t, handlerExecuted, \"handler should NOT have been executed by user call\")\n\tuassert.False(t, userActionExecuted, \"user action should not have been executed\")\n}\n\n// Helper to check if a slice contains a specific address\nfunc containsAddr(list []address, addr address) bool {\n\tfor _, item := range list {\n\t\tif item == addr {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc assertAddrSliceEqual(t *testing.T, expected, actual []address) {\n\tt.Helper()\n\tif len(expected) != len(actual) {\n\t\tt.Fatalf(\"expected slice length %d, got %d. Expected: %v, Got: %v\", len(expected), len(actual), expected, actual)\n\t}\n\n\tfor i := range expected {\n\t\tif expected[i] != actual[i] {\n\t\t\tt.Fatalf(\"slices differ at index %d. Expected: %v, Got: %v\", i, expected, actual)\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/config/v1\"\ngno = \"0.9\"\n\n# public: every other realm of moul's imports this one, and a private realm\n# cannot be imported at all. That is the whole reason this realm exists, so\n# `private = true` here would be a contradiction rather than a trade-off.\n#\n# The redeploy-in-place that private would buy is covered a different way: a\n# later version relays to this one instead of replacing it, so the state\n# survives a version bump without the path ever moving. See proxy.gno.\n"},{"name":"keys.gno","body":"package config\n\nimport (\n\t\"strings\"\n\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n)\n\n// The key grammar.\n//\n// A key is a NAME, optionally followed by \"@\" and a SCOPE:\n//\n//\tpause                  applies to every realm that asks\n//\tpause@r/moul/home      applies to that realm only\n//\n// The scope is a package path with the chain domain stripped, because the\n// domain is the same for every realm reading this one and repeating it in a\n// few dozen keys buys nothing but storage.\n//\n// Two settings therefore answer every scoped question, and each reader decides\n// how they combine: pause takes the stricter of the two (pausable.Strictest),\n// while the notice blocks show both. That choice belongs to the reader and not\n// here, because \"stricter wins\" and \"show both\" are both right, for different\n// settings.\nconst (\n\t// ScopeSep separates a name from the realm it applies to. \"@\" and not \".\"\n\t// so a scope can never be mistaken for a longer name, and not \":\" because\n\t// gno realm render paths already use that.\n\tScopeSep = \"@\"\n\n\tmaxNameLen  = 64\n\tmaxScopeLen = 128\n)\n\n// realmPath is this realm's own path, including its version. Stated once so\n// the page can link to itself and the proxy check can recognise a sibling\n// version without either restating the string.\nconst realmPath = \"gno.land/r/moul/config/v1\"\n\n// validName reports whether name is a legal setting name: 1..maxNameLen bytes\n// of [a-z0-9._-]. The dot is the namespace separator (\"block.top\"), lowercase\n// only so a setting has exactly one name, and no whitespace so a name\n// round-trips through Manifest's tab-separated lines.\nfunc validName(name string) bool {\n\tif len(name) == 0 || len(name) \u003e maxNameLen {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(name); i++ {\n\t\tc := name[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '-', c == '_', c == '.':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// validScope reports whether scope is shaped like a package path with the\n// domain stripped: 1..maxScopeLen bytes of [a-z0-9._/-], no empty segment.\nfunc validScope(scope string) bool {\n\tif len(scope) == 0 || len(scope) \u003e maxScopeLen {\n\t\treturn false\n\t}\n\tlastSlash := true // a leading slash would be an empty first segment\n\tfor i := 0; i \u003c len(scope); i++ {\n\t\tc := scope[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\t\tlastSlash = false\n\t\tcase c == '-', c == '_', c == '.':\n\t\t\tlastSlash = false\n\t\tcase c == '/':\n\t\t\tif lastSlash {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tlastSlash = true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn !lastSlash\n}\n\n// validKey reports whether key is a legal name, or a legal name and scope\n// joined by ScopeSep.\nfunc validKey(key string) bool {\n\tname, scope := SplitKey(key)\n\tif scope == \"\" {\n\t\treturn !strings.Contains(key, ScopeSep) \u0026\u0026 validName(name)\n\t}\n\treturn validName(name) \u0026\u0026 validScope(scope)\n}\n\n// SplitKey takes a key apart. An unscoped key returns an empty scope, and so\n// does a malformed one: callers pair this with validKey rather than trusting\n// the split.\nfunc SplitKey(key string) (name, scope string) {\n\ti := strings.Index(key, ScopeSep)\n\tif i \u003c 0 {\n\t\treturn key, \"\"\n\t}\n\treturn key[:i], key[i+1:]\n}\n\n// Scope turns a package path into the scope half of a key, stripping the chain\n// domain: \"gno.land/r/moul/home\" and \"r/moul/home\" both give \"r/moul/home\".\n//\n// A path that is not shaped like one comes back empty, and every caller here\n// treats that as \"no scope\", falling back to the global setting rather than\n// inventing a key nobody can type.\n//\n// The chain domain is tried first and the literal \"gno.land/\" second, so a key\n// written on one chain still resolves on another whose domain differs. Twin of\n// mygnoscan.TrimDomain, which answers the same question for a URL and is\n// stricter about the characters, because its output lands inside a link.\nfunc Scope(pkgPath string) string {\n\ts := strings.TrimPrefix(pkgPath, runtime.ChainDomain()+\"/\")\n\ts = strings.TrimPrefix(s, \"gno.land/\")\n\ts = strings.Trim(s, \"/\")\n\tif !validScope(s) {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\n// KeyFor builds the scoped key for a setting on one realm, and returns the\n// bare name when pkgPath names no realm this can scope to.\n//\n// This is what a realm should render when it wants to tell a manager which\n// setting to change, so the command in the page is the command that works.\nfunc KeyFor(name, pkgPath string) string {\n\tscope := Scope(pkgPath)\n\tif scope == \"\" {\n\t\treturn name\n\t}\n\treturn name + ScopeSep + scope\n}\n\n// caller is the package path of the realm that called into this one.\n//\n// Every exported function here that uses it is a plain read with no `cur realm`\n// parameter, so it can only ever be BORROWED: gno runs it without opening a\n// realm frame, and unsafe.CurrentRealm() therefore reports the borrower. That\n// is what makes the zero-argument helpers (TopBlock, IsPaused, …) able to name\n// their caller at all.\n//\n// Measured in the test harness on 2026-09-22: a call from a code realm at\n// gno.land/r/test/caller reports CurrentRealm=gno.land/r/test/caller and\n// PreviousRealm=gno.land/r/moul/config/v1.\n//\n// The moment one of these grows a `cur realm` parameter this stops being true\n// and starts reporting this realm instead. Do not add one. Anything that needs\n// a realm frame takes the path explicitly, which is what the …For variants are.\nfunc caller() string { return unsafe.CurrentRealm().PkgPath() }\n\n// scopedPair reads both halves of a scoped setting: the global one and the one\n// for pkgPath, either of which may be empty.\nfunc scopedPair(name, pkgPath string) (global, scoped string) {\n\tglobal = Get(name)\n\tif scope := Scope(pkgPath); scope != \"\" {\n\t\tscoped = Get(name + ScopeSep + scope)\n\t}\n\treturn global, scoped\n}\n"},{"name":"pause.gno","body":"package config\n\nimport \"gno.land/p/moul/pausable/v0\"\n\n// The pause switch: one setting that stops every realm reading this one, and\n// one per realm that stops just that one.\n//\n//\tSet pause              \"paused: incident, back in an hour\"\n//\tSet pause@r/moul/gns   \"readonly\"\n//\tUnset pause            # running again\n//\n// A realm guards its writes and leaves its reads alone, which is what makes\n// \"readonly\" the level worth having: the page keeps rendering and explains\n// itself through TopBlock, and nothing new lands.\n//\n//\tfunc Post(cur realm, body string) {\n//\t\tconfig.AssertWritable()\n//\t\t…\n//\t}\n//\n// The levels, the fail-closed parse and the stricter-of-two rule all live in\n// gno.land/p/moul/pausable; this file is only the wiring to storage.\nconst KeyPause = \"pause\"\n\n// Pause returns the pause state of the realm calling in: the stricter of the\n// global setting and that realm's own.\nfunc Pause() pausable.State { return PauseFor(caller()) }\n\n// PauseFor is Pause for a named realm.\n//\n// A stale per-realm entry can never re-open a realm during a global pause,\n// because the two combine with pausable.Strictest rather than one overriding\n// the other. The cost is that exempting one realm from a global pause is not\n// expressible: clear the global and set the others.\nfunc PauseFor(pkgPath string) pausable.State {\n\tglobal, scoped := scopedPair(KeyPause, pkgPath)\n\treturn pausable.Strictest(pausable.MustParse(global), pausable.MustParse(scoped))\n}\n\n// IsPaused reports whether the realm calling in is held back at all, ReadOnly\n// as well as fully paused.\nfunc IsPaused() bool { return Pause().IsPaused() }\n\n// IsPausedFor is IsPaused for a named realm.\nfunc IsPausedFor(pkgPath string) bool { return PauseFor(pkgPath).IsPaused() }\n\n// AssertWritable aborts unless the realm calling in may still change state.\n// This is the one line a mutating function needs.\nfunc AssertWritable() { Pause().AssertWritable() }\n\n// AssertWritableFor is AssertWritable for a named realm, for a crossing\n// function that cannot be read off the stack.\nfunc AssertWritableFor(pkgPath string) { PauseFor(pkgPath).AssertWritable() }\n\n// AssertReadable aborts unless the realm calling in may still be read.\n//\n// Most realms should NOT put this in Render. A page that aborts tells a reader\n// nothing; TopBlock tells them what happened and when to come back. Reach for\n// this only where serving stale data is itself the harm.\nfunc AssertReadable() { Pause().AssertReadable() }\n\n// AssertReadableFor is AssertReadable for a named realm.\nfunc AssertReadableFor(pkgPath string) { PauseFor(pkgPath).AssertReadable() }\n"},{"name":"pause_test.gno","body":"package config\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/pausable/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPauseDefaultRunning(t *testing.T) {\n\tresetSettings()\n\tuassert.False(t, IsPausedFor(otherRealm))\n\tuassert.True(t, PauseFor(otherRealm).AllowsRead())\n\tuassert.True(t, PauseFor(otherRealm).AllowsWrite())\n\tAssertWritableFor(otherRealm)\n\tAssertReadableFor(otherRealm)\n}\n\nfunc TestPauseGlobal(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyPause, \"readonly\")\n\n\t// Reaches every realm.\n\tfor _, path := range []string{otherRealm, \"gno.land/r/moul/home\", \"gno.land/r/someone/else\"} {\n\t\tuassert.True(t, IsPausedFor(path), path+\" should be held back\")\n\t\tuassert.True(t, PauseFor(path).AllowsRead(), path+\" should still read\")\n\t\tuassert.False(t, PauseFor(path).AllowsWrite(), path+\" should refuse writes\")\n\t}\n\n\tuassert.PanicsWithMessage(t, cur, \"writes are paused\", func() {\n\t\tAssertWritableFor(otherRealm)\n\t})\n\tAssertReadableFor(otherRealm)\n}\n\nfunc TestPauseScoped(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyFor(KeyPause, otherRealm), \"paused: incident\")\n\n\tuassert.True(t, IsPausedFor(otherRealm))\n\tuassert.False(t, PauseFor(otherRealm).AllowsRead())\n\tuassert.False(t, IsPausedFor(\"gno.land/r/moul/home\"), \"another realm is unaffected\")\n\n\tuassert.PanicsWithMessage(t, cur, \"paused: incident\", func() {\n\t\tAssertReadableFor(otherRealm)\n\t})\n}\n\n// TestGlobalPauseCannotBeDefeated is the reason the two combine with\n// Strictest. A per-realm entry left behind from last month must not re-open a\n// realm during a global halt.\nfunc TestGlobalPauseCannotBeDefeated(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyFor(KeyPause, otherRealm), \"running\")\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyPause, \"paused: chain incident\")\n\n\tuassert.False(t, PauseFor(otherRealm).AllowsRead(),\n\t\t\"an explicit per-realm 'running' does not survive a global pause\")\n\tuassert.Equal(t, \"chain incident\", PauseFor(otherRealm).Reason)\n\n\t// The other direction works: a per-realm pause under a running global.\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyFor(KeyPause, otherRealm), \"paused: just this one\")\n\tuassert.False(t, PauseFor(otherRealm).AllowsRead())\n\tuassert.True(t, PauseFor(\"gno.land/r/moul/home\").AllowsRead())\n}\n\n// TestPauseValueValidatedOnWrite is the other half of failing closed. Because\n// pausable.MustParse turns an unreadable value into Paused, an unvalidated\n// typo here would take every realm offline at the next render; refusing the\n// write turns that into a failed transaction the writer sees at once.\nfunc TestPauseValueValidatedOnWrite(cur realm, t *testing.T) {\n\tresetSettings()\n\n\tfor _, bad := range []string{\"yes\", \"true\", \"1\", \"stop\", \"read-only\"} {\n\t\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\t\tuassert.AbortsContains(t, cur, \"invalid pause value\", func() {\n\t\t\tSet(cross(cur), KeyPause, bad)\n\t\t})\n\t}\n\tuassert.Equal(t, 0, Size(), \"no bad value was stored\")\n\n\t// The scoped key is validated too: the check is on the key's NAME, so it\n\t// cannot be sidestepped by scoping it.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.AbortsContains(t, cur, \"invalid pause value\", func() {\n\t\tSet(cross(cur), KeyFor(KeyPause, otherRealm), \"yes\")\n\t})\n\n\t// And every value the reader understands is accepted.\n\tfor _, good := range []string{\"\", \"running\", \"readonly\", \"paused\", \"paused: why\"} {\n\t\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\t\tSet(cross(cur), KeyPause, good)\n\t\tuassert.Equal(t, good, Get(KeyPause))\n\t}\n\n\t// A setting that is not pause is not subject to the grammar.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), \"some.key\", \"yes\")\n\tuassert.Equal(t, \"yes\", Get(\"some.key\"))\n}\n\nfunc TestPauseZeroArgFormsNameTheCaller(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyFor(KeyPause, otherRealm), \"paused\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(otherRealm))\n\tuassert.True(t, IsPaused())\n\tuassert.Equal(t, int(pausable.Paused), int(Pause().Level))\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/moul/home\"))\n\tuassert.False(t, IsPaused(), \"another realm is unaffected\")\n\tAssertWritable()\n}\n"},{"name":"proxy.gno","body":"package config\n\nimport (\n\t\"strings\"\n\n\t\"chain\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Version chaining: how v2 and v3 get built without splitting the state.\n//\n// # The shape, and why it is this way round\n//\n// This realm is public, so its path is permanent and a new API means a new\n// version at a new path. Left alone, that fragments everything: a realm\n// importing v1 and a realm importing v2 would read two different member lists\n// and two different pause switches, and the second one to be written would win\n// for half the callers.\n//\n// Delegation fixes it, and it can only run one way. A version can import the\n// versions that already existed when it was written; it can never import one\n// that does not exist yet. So the STATE STAYS IN THE OLDEST version that has\n// it, and every later version is a thin relay in front:\n//\n//\tv3  -\u003e  v2  -\u003e  v1        (this one: the root, and where everything lives)\n//\n// A realm importing v1, v2 or v3 is then reading the same settings, the same\n// pause and the same managers, whichever door it came through. That is the\n// property worth all of this.\n//\n// v0 cannot take part: it is already on chain and has no settings store at\n// all. It keeps answering for its own member list and nothing else.\n//\n// # Writing v2\n//\n// v2 imports this package, holds no state of its own, and for each write it\n// exposes, calls SetAs or UnsetAs with the address it was called by:\n//\n//\tfunc Set(cur realm, key, value string) {\n//\t\tconfig.SetAs(cross(cur), cur.Previous().Address(), key, value)\n//\t}\n//\n// Reads need none of this. They are plain borrowed calls, so v2 just forwards:\n//\n//\tfunc Get(key string) string { return config.Get(key) }\n//\n// Then, once, from a manager's address:\n//\n//\tAllowProxy gno.land/r/moul/config/v2\n//\n// # What a proxy is trusted with, exactly\n//\n// A registered proxy is trusted to say WHO is asking, not to decide whether\n// they may. SetAs still puts the principal through the Authorizer, so the\n// member list stays the single answer to \"who may change config\" for every\n// version at once, and adding a manager here works through v2 and v3 with no\n// further deploys.\n//\n// It is not a security boundary against the proxy's own code: a proxy that\n// lies about its principal writes whatever it likes. It does not have to be,\n// because the same person deploys both and registering one is a deliberate,\n// revocable act. What it buys is that v2 never carries a copy of the member\n// list, so the two can never disagree.\n\n// proxies holds the package paths allowed to relay, keyed by path, valued by\n// the address that path resolves to. The address is what an incoming call is\n// actually compared against; the path is stored so Render and ListProxies can\n// show something a human recognises.\nvar proxies = avl.NewTree() // pkgPath -\u003e address\n\n// AllowProxy registers a newer version of this realm as a relay. Manager only.\n//\n// It takes a package path rather than an address because a path is what a\n// manager can check by eye; the address is derived here with the same function\n// the chain uses, so the two cannot drift.\nfunc AllowProxy(cur realm, pkgPath string) {\n\tassertProxyPath(pkgPath)\n\tassertAuthorized(cur, \"config.AllowProxy:\"+pkgPath)\n\n\tproxies.Set(pkgPath, chain.PackageAddress(pkgPath))\n\tsettingsRev++\n\tchain.Emit(\"ConfigAllowProxy\", \"path\", pkgPath,\n\t\t\"address\", chain.PackageAddress(pkgPath).String())\n}\n\n// RevokeProxy withdraws a relay. Manager only.\n//\n// Revoking one that was never registered aborts rather than passing quietly:\n// at this point in an incident, \"done\" and \"you misspelled it\" must not look\n// the same.\nfunc RevokeProxy(cur realm, pkgPath string) {\n\tassertProxyPath(pkgPath)\n\tassertAuthorized(cur, \"config.RevokeProxy:\"+pkgPath)\n\n\tif _, removed := proxies.Remove(pkgPath); !removed {\n\t\tpanic(\"no such proxy: \" + pkgPath)\n\t}\n\tsettingsRev++\n\tchain.Emit(\"ConfigRevokeProxy\", \"path\", pkgPath)\n}\n\n// IsProxy reports whether addr is a registered relay.\nfunc IsProxy(addr address) bool {\n\tif addr == \"\" {\n\t\treturn false\n\t}\n\tfound := false\n\tproxies.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\tif value.(address) == addr {\n\t\t\tfound = true\n\t\t\treturn true // stop\n\t\t}\n\t\treturn false\n\t})\n\treturn found\n}\n\n// ListProxies returns the registered relay paths, in sorted order.\nfunc ListProxies() []string {\n\tout := []string{}\n\tproxies.Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\tout = append(out, key)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// SetAs is Set, performed by a registered proxy on behalf of principal.\n//\n// Two checks, and both have to hold: the caller is a registered relay, and the\n// principal it names is authorized. Neither is redundant. Dropping the first\n// would let any realm claim any principal; dropping the second would make a\n// registered proxy an unconditional bypass of the member list.\nfunc SetAs(cur realm, principal address, key, value string) {\n\tassertRelay(cur)\n\tassertWritableKey(key)\n\tassertValue(key, value)\n\tassertPrincipal(principal, \"config.Set:\"+key)\n\twriteSetting(key, value)\n}\n\n// UnsetAs is Unset, performed by a registered proxy on behalf of principal.\nfunc UnsetAs(cur realm, principal address, key string) {\n\tassertRelay(cur)\n\tassertWritableKey(key)\n\tassertPrincipal(principal, \"config.Unset:\"+key)\n\tremoveSetting(key)\n}\n\n// assertRelay aborts unless the immediate caller is a registered proxy.\nfunc assertRelay(cur realm) {\n\tfrom := cur.Previous().Address()\n\tif !IsProxy(from) {\n\t\tpanic(\"not a registered proxy: \" + from.String())\n\t}\n}\n\n// assertPrincipal puts an address through the Authorizer without it being the\n// caller, which is what a relay needs and what DoByPrevious cannot express.\n//\n// With the default MemberAuthority this is a membership test. With an\n// authority that inspects the caller instead (a ContractAuthority), the\n// relayed path asks that authority about the principal, so check what it does\n// before transferring management while a proxy is registered.\nfunc assertPrincipal(principal address, title string) {\n\tif principal == \"\" {\n\t\tpanic(\"unauthorized: no principal\")\n\t}\n\tallowed := false\n\terr := Authorizer.Authority().Authorize(principal, title, func() error {\n\t\tallowed = true\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(\"unauthorized: \" + err.Error())\n\t}\n\tif !allowed {\n\t\tpanic(\"unauthorized\")\n\t}\n}\n\n// assertProxyPath refuses anything that is not a realm path under this\n// namespace. A proxy is by definition a later version of this realm, so\n// nothing else should ever be registered, and the narrow check turns a\n// fat-fingered AllowProxy into an abort rather than a standing grant to an\n// unrelated realm.\nfunc assertProxyPath(pkgPath string) {\n\tconst want = \"gno.land/r/moul/config/v\"\n\tif !strings.HasPrefix(pkgPath, want) {\n\t\tpanic(\"a proxy must be a later version of this realm, got \" + pkgPath)\n\t}\n\trest := strings.TrimPrefix(pkgPath, want)\n\tif rest == \"\" || !isDigits(rest) {\n\t\tpanic(\"a proxy must be a later version of this realm, got \" + pkgPath)\n\t}\n}\n\nfunc isDigits(s string) bool {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif s[i] \u003c '0' || s[i] \u003e '9' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn len(s) \u003e 0\n}\n"},{"name":"proxy_test.gno","body":"package config\n\nimport (\n\t\"testing\"\n\n\t\"chain\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// v2Path is a plausible next version. Nothing is deployed there; the tests\n// only need the address the path resolves to, which is what an incoming\n// relayed call is actually compared against.\nconst v2Path = \"gno.land/r/moul/config/v2\"\n\nfunc v2Addr() address { return chain.PackageAddress(v2Path) }\n\nfunc TestAllowAndRevokeProxy(cur realm, t *testing.T) {\n\tresetSettings()\n\tuassert.Equal(t, 0, len(ListProxies()))\n\tuassert.False(t, IsProxy(v2Addr()))\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tAllowProxy(cross(cur), v2Path)\n\n\tuassert.True(t, IsProxy(v2Addr()))\n\tuassert.Equal(t, 1, len(ListProxies()))\n\tuassert.Equal(t, v2Path, ListProxies()[0])\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tRevokeProxy(cross(cur), v2Path)\n\tuassert.False(t, IsProxy(v2Addr()))\n\tuassert.Equal(t, 0, len(ListProxies()))\n}\n\nfunc TestProxyRegistrationIsManagerOnly(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tAllowProxy(cross(cur), v2Path)\n\t})\n\tuassert.False(t, IsProxy(v2Addr()), \"a rejected registration leaves nothing behind\")\n}\n\n// TestProxyPathMustBeASiblingVersion keeps a fat-fingered AllowProxy from\n// becoming a standing write grant to an unrelated realm.\nfunc TestProxyPathMustBeASiblingVersion(cur realm, t *testing.T) {\n\tresetSettings()\n\n\tbad := []string{\n\t\t\"gno.land/r/someone/evil\",\n\t\t\"gno.land/r/moul/home\",\n\t\t\"gno.land/r/moul/configuration/v2\", // prefix-adjacent, not a sibling\n\t\t\"gno.land/r/moul/config/v\",         // no number\n\t\t\"gno.land/r/moul/config/vnext\",\n\t\t\"gno.land/r/moul/config/v2/sub\",\n\t\t\"\",\n\t}\n\tfor _, path := range bad {\n\t\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\t\tuassert.AbortsContains(t, cur, \"must be a later version\", func() {\n\t\t\tAllowProxy(cross(cur), path)\n\t\t})\n\t}\n\tuassert.Equal(t, 0, len(ListProxies()))\n}\n\nfunc TestRevokeUnknownProxyAborts(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.AbortsWithMessage(t, cur, \"no such proxy: \"+v2Path, func() {\n\t\tRevokeProxy(cross(cur), v2Path)\n\t})\n}\n\n// TestRelayNeedsRegistration is the first of the relay's two checks: without\n// it, any realm could claim to be acting for any principal.\nfunc TestRelayNeedsRegistration(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tuassert.AbortsContains(t, cur, \"not a registered proxy\", func() {\n\t\tSetAs(cross(cur), originAddr, \"some.key\", \"value\")\n\t})\n\tuassert.Equal(t, 0, Size())\n}\n\n// TestRelayStillChecksThePrincipal is the second check, and the reason a proxy\n// is not simply an unconditional bypass: the member list stays the single\n// answer to \"who may change config\", for every version at once.\nfunc TestRelayStillChecksThePrincipal(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tAllowProxy(cross(cur), v2Path)\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tSetAs(cross(cur), nonManagerAddr, \"some.key\", \"value\")\n\t})\n\tuassert.Equal(t, 0, Size())\n\n\t// An empty principal is not a wildcard.\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tuassert.AbortsContains(t, cur, \"no principal\", func() {\n\t\tSetAs(cross(cur), \"\", \"some.key\", \"value\")\n\t})\n}\n\n// TestRelayWritesTheSameState is the property the whole version chain exists\n// for: a write arriving through a later version lands in exactly the store\n// that a direct write lands in, so v1 and v2 readers never disagree.\nfunc TestRelayWritesTheSameState(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tAllowProxy(cross(cur), v2Path)\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tSetAs(cross(cur), originAddr, KeyMygnoscanURL, \"https://scan.example.com\")\n\n\tuassert.Equal(t, \"https://scan.example.com\", Get(KeyMygnoscanURL))\n\tuassert.Equal(t, \"https://scan.example.com\", MygnoscanURL(),\n\t\t\"the typed accessor sees the relayed write too\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tUnsetAs(cross(cur), originAddr, KeyMygnoscanURL)\n\tuassert.False(t, Has(KeyMygnoscanURL))\n}\n\n// TestRelayValidatesLikeTheDirectPath: a relay is a different door, not a\n// different set of rules. Key shape and value grammar are checked identically.\nfunc TestRelayValidatesLikeTheDirectPath(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tAllowProxy(cross(cur), v2Path)\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tuassert.AbortsContains(t, cur, \"invalid key\", func() {\n\t\tSetAs(cross(cur), originAddr, \"Bad Key\", \"value\")\n\t})\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tuassert.AbortsContains(t, cur, \"invalid pause value\", func() {\n\t\tSetAs(cross(cur), originAddr, KeyPause, \"yes\")\n\t})\n}\n\n// TestRevokedProxyCannotWrite: revocation is the emergency brake on the relay\n// itself, so it has to bite immediately.\nfunc TestRevokedProxyCannotWrite(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tAllowProxy(cross(cur), v2Path)\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tSetAs(cross(cur), originAddr, \"some.key\", \"before\")\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tRevokeProxy(cross(cur), v2Path)\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tuassert.AbortsContains(t, cur, \"not a registered proxy\", func() {\n\t\tSetAs(cross(cur), originAddr, \"some.key\", \"after\")\n\t})\n\tuassert.Equal(t, \"before\", Get(\"some.key\"))\n}\n\n// TestManagerChangesReachTheRelay is what makes one member list serve every\n// version: adding a manager here works through v2 with no further deploys.\nfunc TestManagerChangesReachTheRelay(cur realm, t *testing.T) {\n\tresetSettings()\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tAllowProxy(cross(cur), v2Path)\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tSetAs(cross(cur), manager1Addr, \"some.key\", \"value\")\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.NoError(t, AddManager(cross(cur), manager1Addr))\n\n\ttesting.SetRealm(testing.NewCodeRealm(v2Path))\n\tSetAs(cross(cur), manager1Addr, \"some.key\", \"value\")\n\tuassert.Equal(t, \"value\", Get(\"some.key\"))\n}\n\n// ExampleRender_proxies pins the section that only exists once a later version\n// is registered, which is the state this realm spends most of its life NOT in.\nfunc ExampleRender_proxies() {\n\tresetSettings()\n\tproxies.Set(v2Path, chain.PackageAddress(v2Path))\n\tprint(Render(\"\"))\n\t// Output:\n\t// # gno.land/r/moul/config\n\t//\n\t// moul's settings, read by his other realms. rev 0 · 0 setting(s)\n\t//\n\t// ## Settings\n\t//\n\t// _none set; every reader is on its built-in default_\n\t//\n\t// ## Pause\n\t//\n\t// _running; no global pause_\n\t//\n\t// ## Authority\n\t//\n\t// `member_authority[g1daexjemfde047h6lta047h6lta047h6ld2pug6]`\n\t//\n\t// ## Proxies\n\t//\n\t// Later versions of this realm that may relay a write:\n\t//\n\t// - `gno.land/r/moul/config/v2`\n\t//\n\t// ---\n\t//\n\t// [explorer](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1) · [source](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1?tab=source) · [calls](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1?tab=calls) · [deps](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1?tab=deps)\n}\n"},{"name":"settings.gno","body":"package config\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/mygnoscan/v0\"\n\t\"gno.land/p/moul/pausable/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// The keys this realm answers for by name. A key is just a string and any key\n// can be set, but one the rest of the repo reads gets a constant here so the\n// reader and the writer cannot drift apart on a typo.\nconst (\n\t// KeyMygnoscanURL is the explorer instance every realm of moul's links to.\n\tKeyMygnoscanURL = \"mygnoscan.url\"\n\t// KeyMygnoscanNetwork overrides the ?network= id, for an instance that\n\t// names the chain something other than what mygnoscan.NetworkFor expects.\n\t// Unset is the normal case: the chain-id decides.\n\tKeyMygnoscanNetwork = \"mygnoscan.network\"\n)\n\n// maxValueLen bounds one write. Storage is paid for and never refunded, so\n// this realm holds settings, not content: a URL, a flag, a short list.\n//\n// A notice block is the one that pushes against it, and 1024 bytes is several\n// paragraphs of markdown. A realm that needs more than that is asking this one\n// to be a CMS, which is what its own slots are for.\nconst maxValueLen = 1024\n\ntype setting struct {\n\tvalue   string\n\trev     int\n\tupdated int64\n}\n\nvar (\n\tsettings    = avl.NewTree() // key -\u003e *setting\n\tsettingsRev int\n)\n\n// Set creates or replaces a setting. Only an address the Authorizer accepts\n// may call it.\n//\n// It panics rather than returning an error, which is the opposite of the\n// manager functions in config.gno, and deliberately so: a returned error from\n// a realm call leaves the transaction SUCCESSFUL. A rejected config write that\n// reports success is the one outcome worth ruling out here, because the caller\n// then walks away believing the new value is live and every realm reading this\n// key keeps serving the old one. The manager functions predate that reasoning\n// and are frozen on chain at v0; new surface does not inherit the mistake.\nfunc Set(cur realm, key, value string) {\n\tassertWritableKey(key)\n\tassertValue(key, value)\n\tassertAuthorized(cur, \"config.Set:\"+key)\n\twriteSetting(key, value)\n}\n\n// Unset removes a setting, so readers fall back to their built-in default.\n// Removing a key that is not set is an error, not a no-op: it almost always\n// means the key was misspelled here or in the realm that reads it.\nfunc Unset(cur realm, key string) {\n\tassertWritableKey(key)\n\tassertAuthorized(cur, \"config.Unset:\"+key)\n\tremoveSetting(key)\n}\n\n// writeSetting is the only place a setting is stored, shared by the direct and\n// the relayed path so a new caller cannot forget the revision or the event.\nfunc writeSetting(key, value string) {\n\tsettingsRev++\n\tsettings.Set(key, \u0026setting{\n\t\tvalue:   value,\n\t\trev:     settingsRev,\n\t\tupdated: runtime.ChainHeight(),\n\t})\n\tchain.Emit(\"ConfigSet\", \"key\", key, \"value\", value, \"rev\", strconv.Itoa(settingsRev))\n}\n\n// removeSetting is writeSetting's twin.\nfunc removeSetting(key string) {\n\tif _, removed := settings.Remove(key); !removed {\n\t\tpanic(\"no such setting: \" + key)\n\t}\n\tsettingsRev++\n\tchain.Emit(\"ConfigUnset\", \"key\", key, \"rev\", strconv.Itoa(settingsRev))\n}\n\nfunc assertWritableKey(key string) {\n\tif !validKey(key) {\n\t\tpanic(\"invalid key: want \u003cname\u003e or \u003cname\u003e\" + ScopeSep + \"\u003crealm-path\u003e, \" +\n\t\t\t\"name being 1-\" + strconv.Itoa(maxNameLen) + \" bytes of [a-z0-9._-], got \" +\n\t\t\tstrconv.Quote(key))\n\t}\n}\n\n// assertValue rejects a value the reader could not make sense of.\n//\n// Only pause has a grammar today, and it is exactly the setting where a\n// silently unreadable value matters: pausable.MustParse fails CLOSED, so a\n// typo stored here would take every realm offline at the next render. Catching\n// it on the way in costs one comparison and turns that into a failed\n// transaction the writer sees immediately.\nfunc assertValue(key, value string) {\n\tif len(value) \u003e maxValueLen {\n\t\tpanic(\"value too long: max \" + strconv.Itoa(maxValueLen) +\n\t\t\t\" bytes, got \" + strconv.Itoa(len(value)))\n\t}\n\tif name, _ := SplitKey(key); name == KeyPause {\n\t\tif _, ok := pausable.Parse(value); !ok {\n\t\t\tpanic(\"invalid pause value \" + strconv.Quote(value) +\n\t\t\t\t\": want \\\"\\\", \\\"running\\\", \\\"readonly\\\" or \\\"paused\\\", each optionally followed by \\\": \u003creason\u003e\\\"\")\n\t\t}\n\t}\n}\n\n// assertAuthorized runs the write through the Authorizer, so whoever holds\n// authority today decides: the member list at first, a DAO or a contract after\n// a TransferManagement. The action closure is what authz authorizes; the write\n// itself happens after, because a nil error is the only thing that reaches it.\nfunc assertAuthorized(cur realm, title string) {\n\tallowed := false\n\terr := Authorizer.DoByPrevious(0, cur, title, func() error {\n\t\tallowed = true\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(\"unauthorized: \" + err.Error())\n\t}\n\tif !allowed {\n\t\tpanic(\"unauthorized\")\n\t}\n}\n\n// Get returns a setting's value, or \"\" when it is not set. Reads are open: a\n// realm importing this one calls Get on every render and pays nothing beyond\n// the cross-realm call.\nfunc Get(key string) string {\n\tv := settings.Get(key)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(*setting).value\n}\n\n// GetOr returns a setting's value, or fallback when it is unset or empty.\n// This is the shape every consumer wants: a realm should still render on a\n// chain where this one was never deployed with that key.\nfunc GetOr(key, fallback string) string {\n\tif v := Get(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn fallback\n}\n\n// Has reports whether key is set, including to the empty string, which GetOr\n// cannot distinguish from unset.\nfunc Has(key string) bool { return settings.Has(key) }\n\n// Keys returns every set key, in sorted order.\nfunc Keys() []string {\n\tout := []string{}\n\tsettings.Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\tout = append(out, key)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Size returns how many settings are set.\nfunc Size() int { return settings.Size() }\n\n// SettingsRevision counts every settings write this realm has accepted. A\n// client that caches config polls this one int to learn that nothing moved.\nfunc SettingsRevision() int { return settingsRev }\n\n// Manifest returns one tab-separated line per setting:\n//\n//\t\u003ckey\u003e\\t\u003crev\u003e\\t\u003cheight\u003e\\t\u003cvalue\u003e\n//\n// It is the whole config in one vm/qeval read, for a tool that wants to diff\n// the chain against a local file without a call per key. The value is last\n// because it is the only field that can contain a tab.\nfunc Manifest() string {\n\tvar b strings.Builder\n\tsettings.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\ts := value.(*setting)\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.Itoa(s.rev))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.FormatInt(s.updated, 10))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(s.value)\n\t\tb.WriteString(\"\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\n// MygnoscanURL returns the explorer base moul's realms should link to, falling\n// back to the package default when nothing is set here.\nfunc MygnoscanURL() string { return GetOr(KeyMygnoscanURL, mygnoscan.DefaultBase) }\n\n// Scanner returns a link builder pointed at the configured explorer, on\n// whichever network answers for the running chain (or at the KeyMygnoscanNetwork\n// override, when one is set).\n//\n// This is the function other realms are meant to call:\n//\n//\tconfig.Scanner().Realm(\"gno.land/r/moul/home\")\n//\tconfig.Scanner().Address(someAddr)\n//\n// Changing where every one of them points is then one transaction against this\n// realm, not a redeploy of each.\nfunc Scanner() mygnoscan.Scanner {\n\ts := mygnoscan.New(MygnoscanURL())\n\tif net := Get(KeyMygnoscanNetwork); net != \"\" {\n\t\ts = s.WithNetwork(net)\n\t}\n\treturn s\n}\n\n// Mygnoscan is the explorer page of the realm calling in.\nfunc Mygnoscan() string { return MygnoscanFor(caller()) }\n\n// MygnoscanFor is Mygnoscan for a named realm.\nfunc MygnoscanFor(pkgPath string) string { return Scanner().Realm(pkgPath) }\n\n// MygnoscanFooter is the render-ready form: the markdown line the realm\n// calling in appends under its output.\nfunc MygnoscanFooter() string { return MygnoscanFooterFor(caller()) }\n\n// MygnoscanFooterFor is MygnoscanFooter for a named realm.\nfunc MygnoscanFooterFor(pkgPath string) string { return Scanner().RealmFooter(pkgPath) }\n\n// Render shows the whole configuration: the settings, who may change them, and\n// where this realm itself can be inspected.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# gno.land/r/moul/config\\n\\n\")\n\tb.WriteString(\"moul's settings, read by his other realms. \")\n\tb.WriteString(\"rev \")\n\tb.WriteString(strconv.Itoa(settingsRev))\n\tb.WriteString(\" · \")\n\tb.WriteString(strconv.Itoa(settings.Size()))\n\tb.WriteString(\" setting(s)\\n\\n\")\n\n\tb.WriteString(\"## Settings\\n\\n\")\n\tif settings.Size() == 0 {\n\t\tb.WriteString(\"_none set; every reader is on its built-in default_\\n\")\n\t} else {\n\t\tb.WriteString(\"| key | value | rev | height |\\n\")\n\t\tb.WriteString(\"| --- | --- | ---: | ---: |\\n\")\n\t\tsettings.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\ts := value.(*setting)\n\t\t\tb.WriteString(\"| `\")\n\t\t\tb.WriteString(key)\n\t\t\tb.WriteString(\"` | \")\n\t\t\tb.WriteString(renderValue(s.value))\n\t\t\tb.WriteString(\" | \")\n\t\t\tb.WriteString(strconv.Itoa(s.rev))\n\t\t\tb.WriteString(\" | \")\n\t\t\tb.WriteString(strconv.FormatInt(s.updated, 10))\n\t\t\tb.WriteString(\" |\\n\")\n\t\t\treturn false\n\t\t})\n\t}\n\n\tb.WriteString(\"\\n## Pause\\n\\n\")\n\tb.WriteString(renderPause())\n\n\tb.WriteString(\"\\n## Authority\\n\\n\")\n\tb.WriteString(\"`\")\n\tb.WriteString(Authorizer.String())\n\tb.WriteString(\"`\\n\")\n\n\tb.WriteString(renderProxies())\n\n\tb.WriteString(\"\\n---\\n\\n\")\n\tb.WriteString(MygnoscanFooterFor(realmPath))\n\tb.WriteString(\"\\n\")\n\n\treturn b.String()\n}\n\n// renderPause reports the global pause only. A per-realm one is a setting like\n// any other and is already in the table above; repeating them here would be a\n// second list to keep in step, and the one a reader of THIS page wants is the\n// switch that covers everything.\nfunc renderPause() string {\n\tst := pausable.MustParse(Get(KeyPause))\n\tif !st.IsPaused() {\n\t\treturn \"_running; no global pause_\\n\"\n\t}\n\treturn st.Notice() + \"\\n\"\n}\n\n// renderProxies lists the later versions allowed to relay writes here. The\n// section is omitted entirely while there are none, which is the state this\n// realm ships in and stays in until a v2 exists.\nfunc renderProxies() string {\n\tpaths := ListProxies()\n\tif len(paths) == 0 {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"\\n## Proxies\\n\\n\")\n\tb.WriteString(\"Later versions of this realm that may relay a write:\\n\\n\")\n\tfor _, p := range paths {\n\t\tb.WriteString(\"- `\")\n\t\tb.WriteString(p)\n\t\tb.WriteString(\"`\\n\")\n\t}\n\treturn b.String()\n}\n\n// renderValue puts a value in a code span and neutralises the two characters\n// that would otherwise break out of the table cell it sits in. Only a manager\n// can write a value, so this is about a stray pipe in a URL and not about an\n// attacker, but a config page that silently loses a column is its own bug.\nfunc renderValue(v string) string {\n\tif v == \"\" {\n\t\treturn \"_(empty)_\"\n\t}\n\tv = strings.ReplaceAll(v, \"|\", \"\\\\|\")\n\tv = strings.ReplaceAll(v, \"`\", \"'\")\n\tv = strings.ReplaceAll(v, \"\\n\", \" \")\n\treturn \"`\" + v + \"`\"\n}\n"},{"name":"settings_test.gno","body":"package config\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/authz/v0\"\n\t\"gno.land/p/moul/mygnoscan/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// resetSettings puts the realm back to a just-deployed state. Realm globals\n// live for the whole test binary and gno runs every Example AFTER every Test,\n// so without this the pinned ExampleRender output would depend on which tests\n// ran before it and in what order.\nfunc resetSettings() {\n\tsettings = avl.NewTree()\n\tproxies = avl.NewTree()\n\tsettingsRev = 0\n\tAuthorizer = authz.NewWithAuthority(authz.NewMemberAuthority(originAddr))\n}\n\nfunc TestValidKey(t *testing.T) {\n\ttests := []struct {\n\t\tkey  string\n\t\twant bool\n\t}{\n\t\t{\"mygnoscan.url\", true},\n\t\t{\"a\", true},\n\t\t{\"a-b_c.d0\", true},\n\t\t{\"\", false},\n\t\t{\"Upper\", false},\n\t\t{\"has space\", false},\n\t\t{\"tab\\there\", false},\n\t\t{\"colon:here\", false},\n\t\t// A bare slash is not a name; it is only legal inside a scope.\n\t\t{\"slash/here\", false},\n\t\t// Scoped keys.\n\t\t{\"pause\" + ScopeSep + \"r/moul/home\", true},\n\t\t{\"block.top\" + ScopeSep + \"p/moul/kit/ui\", true},\n\t\t{\"pause\" + ScopeSep, false},           // scope separator with no scope\n\t\t{ScopeSep + \"r/moul/home\", false},     // scope with no name\n\t\t{\"pause\" + ScopeSep + \"r//moul\", false},\n\t\t{\"pause\" + ScopeSep + \"r/moul/\", false},\n\t\t{\"pause\" + ScopeSep + \"R/Moul/Home\", false},\n\t\t{\"pause\" + ScopeSep + \"a\" + ScopeSep + \"b\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, validKey(tt.key), \"validKey(\"+tt.key+\")\")\n\t}\n\n\t// 64 bytes is the last legal length, 65 the first illegal one.\n\tlong := \"\"\n\tfor i := 0; i \u003c maxNameLen; i++ {\n\t\tlong += \"a\"\n\t}\n\tuassert.True(t, validKey(long), \"a name of exactly maxNameLen is legal\")\n\tuassert.False(t, validKey(long+\"a\"), \"one byte over maxNameLen is not\")\n}\n\nfunc TestSetGetUnset(cur realm, t *testing.T) {\n\tresetSettings()\n\n\tuassert.Equal(t, \"\", Get(\"mygnoscan.url\"))\n\tuassert.False(t, Has(\"mygnoscan.url\"))\n\tuassert.Equal(t, \"fallback\", GetOr(\"mygnoscan.url\", \"fallback\"))\n\tuassert.Equal(t, 0, SettingsRevision())\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyMygnoscanURL, \"https://scan.example.com\")\n\n\tuassert.Equal(t, \"https://scan.example.com\", Get(KeyMygnoscanURL))\n\tuassert.True(t, Has(KeyMygnoscanURL))\n\tuassert.Equal(t, \"https://scan.example.com\", GetOr(KeyMygnoscanURL, \"fallback\"))\n\tuassert.Equal(t, 1, SettingsRevision())\n\tuassert.Equal(t, 1, Size())\n\n\t// Overwriting is an ordinary write and bumps the revision again.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyMygnoscanURL, \"https://scan2.example.com\")\n\tuassert.Equal(t, \"https://scan2.example.com\", Get(KeyMygnoscanURL))\n\tuassert.Equal(t, 2, SettingsRevision())\n\tuassert.Equal(t, 1, Size())\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tUnset(cross(cur), KeyMygnoscanURL)\n\tuassert.Equal(t, \"\", Get(KeyMygnoscanURL))\n\tuassert.False(t, Has(KeyMygnoscanURL))\n\tuassert.Equal(t, 0, Size())\n\tuassert.Equal(t, 3, SettingsRevision())\n}\n\n// TestEmptyValueIsSet pins the one case GetOr cannot see: a key set to \"\" is\n// set, and every reader falls back anyway. That is deliberate (a reader's\n// default beats an empty string) but it means Unset and Set(\"\") are not the\n// same operation, and only Has tells them apart.\nfunc TestEmptyValueIsSet(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), \"some.key\", \"\")\n\n\tuassert.True(t, Has(\"some.key\"))\n\tuassert.Equal(t, \"\", Get(\"some.key\"))\n\tuassert.Equal(t, \"fallback\", GetOr(\"some.key\", \"fallback\"))\n}\n\nfunc TestSetRequiresAuthority(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tSet(cross(cur), \"some.key\", \"value\")\n\t})\n\tuassert.Equal(t, 0, Size(), \"a rejected write leaves nothing behind\")\n\tuassert.Equal(t, 0, SettingsRevision(), \"and does not move the revision\")\n\n\t// A manager added by the origin can write, which is the whole point of\n\t// routing through the Authorizer instead of a hardcoded address.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.NoError(t, AddManager(cross(cur), manager1Addr))\n\n\ttesting.SetRealm(testing.NewUserRealm(manager1Addr))\n\tSet(cross(cur), \"some.key\", \"value\")\n\tuassert.Equal(t, \"value\", Get(\"some.key\"))\n\n\t// And loses it again when removed.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.NoError(t, RemoveManager(cross(cur), manager1Addr))\n\n\ttesting.SetRealm(testing.NewUserRealm(manager1Addr))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tSet(cross(cur), \"other.key\", \"value\")\n\t})\n}\n\nfunc TestUnsetRequiresAuthority(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), \"some.key\", \"value\")\n\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tUnset(cross(cur), \"some.key\")\n\t})\n\tuassert.Equal(t, \"value\", Get(\"some.key\"), \"a rejected unset leaves the value\")\n}\n\nfunc TestUnsetMissingKeyAborts(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.AbortsWithMessage(t, cur, \"no such setting: never.set\", func() {\n\t\tUnset(cross(cur), \"never.set\")\n\t})\n}\n\nfunc TestInvalidInputAborts(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.AbortsContains(t, cur, \"invalid key\", func() {\n\t\tSet(cross(cur), \"Bad Key\", \"value\")\n\t})\n\n\tlong := \"\"\n\tfor i := 0; i \u003c maxValueLen+1; i++ {\n\t\tlong += \"x\"\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tuassert.AbortsContains(t, cur, \"value too long\", func() {\n\t\tSet(cross(cur), \"some.key\", long)\n\t})\n\n\tuassert.Equal(t, 0, Size(), \"neither rejection wrote anything\")\n}\n\n// TestKeyValidatedBeforeAuthority pins the check order: an unauthorised caller\n// passing a malformed key is told the key is wrong, not that they are. Nothing\n// secret leaks either way, and validating first means a manager's typo gets\n// the useful message rather than a misleading \"unauthorized\".\nfunc TestKeyValidatedBeforeAuthority(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(nonManagerAddr))\n\tuassert.AbortsContains(t, cur, \"invalid key\", func() {\n\t\tSet(cross(cur), \"Bad Key\", \"value\")\n\t})\n}\n\nfunc TestKeysAndManifest(cur realm, t *testing.T) {\n\tresetSettings()\n\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), \"zzz.last\", \"z\")\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), \"aaa.first\", \"a\")\n\n\tkeys := Keys()\n\tuassert.Equal(t, 2, len(keys))\n\tuassert.Equal(t, \"aaa.first\", keys[0], \"Keys is sorted, not insertion-ordered\")\n\tuassert.Equal(t, \"zzz.last\", keys[1])\n\n\t// rev is the realm-wide counter at the time of that key's last write, so\n\t// zzz.last carries 1 and aaa.first carries 2 despite sorting first. The\n\t// height column is read back from the chain rather than hardcoded: gno's\n\t// test harness has no absolute height setter, so tests inherit whatever\n\t// height ran before them and a literal here would break on the next test\n\t// added above this one.\n\th := strconv.FormatInt(runtime.ChainHeight(), 10)\n\tuassert.Equal(t,\n\t\t\"aaa.first\\t2\\t\"+h+\"\\ta\\nzzz.last\\t1\\t\"+h+\"\\tz\\n\",\n\t\tManifest())\n}\n\nfunc TestScannerFollowsSettings(cur realm, t *testing.T) {\n\tresetSettings()\n\n\t// Unset, every reader is on the package default.\n\tuassert.Equal(t, mygnoscan.DefaultBase, MygnoscanURL())\n\tuassert.Equal(t,\n\t\tmygnoscan.DefaultBase+\"/realm/r/moul/home\",\n\t\tMygnoscanFor(\"gno.land/r/moul/home\"))\n\n\t// One transaction moves every realm that reads this one.\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyMygnoscanURL, \"https://scan.example.com\")\n\n\tuassert.Equal(t, \"https://scan.example.com\", MygnoscanURL())\n\tuassert.Equal(t,\n\t\t\"https://scan.example.com/realm/r/moul/home\",\n\t\tMygnoscanFor(\"gno.land/r/moul/home\"))\n\n\t// The network override is independent of the base, for an instance that\n\t// names the chain differently. The test harness runs as chain-id \"dev\",\n\t// which maps to no network at all, so this is the only way to see one.\n\tuassert.Equal(t, \"\", Scanner().Network())\n\ttesting.SetRealm(testing.NewUserRealm(originAddr))\n\tSet(cross(cur), KeyMygnoscanNetwork, \"gnoland1\")\n\tuassert.Equal(t, \"gnoland1\", Scanner().Network())\n\tuassert.Equal(t,\n\t\t\"https://scan.example.com/realm/r/moul/home?network=gnoland1\",\n\t\tMygnoscanFor(\"gno.land/r/moul/home\"))\n}\n\nfunc TestMygnoscanFooter(cur realm, t *testing.T) {\n\tresetSettings()\n\tuassert.Equal(t,\n\t\tmygnoscan.DefaultBase+\"/realm/r/moul/config\",\n\t\tmygnoscan.Default().Realm(\"gno.land/r/moul/config\"),\n\t\t\"the footer and a direct build agree while nothing is configured\")\n\tuassert.True(t, len(MygnoscanFooterFor(\"gno.land/r/moul/config\")) \u003e 0)\n\tuassert.Equal(t, \"\", MygnoscanFooterFor(\"\"))\n}\n\n// ExampleRender pins the page as it looks right after deployment. It resets\n// first: examples run after every Test in the binary and would otherwise\n// render whatever state they left.\nfunc ExampleRender() {\n\tresetSettings()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # gno.land/r/moul/config\n\t//\n\t// moul's settings, read by his other realms. rev 0 · 0 setting(s)\n\t//\n\t// ## Settings\n\t//\n\t// _none set; every reader is on its built-in default_\n\t//\n\t// ## Pause\n\t//\n\t// _running; no global pause_\n\t//\n\t// ## Authority\n\t//\n\t// `member_authority[g1daexjemfde047h6lta047h6lta047h6ld2pug6]`\n\t//\n\t// ---\n\t//\n\t// [explorer](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1) · [source](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1?tab=source) · [calls](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1?tab=calls) · [deps](https://mygnoscan.moul.p2p.team/realm/r/moul/config/v1?tab=deps)\n}\n\n// ExampleRender_populated pins the settings table and the global pause banner,\n// which together are the view a manager actually looks at during an incident.\nfunc ExampleRender_populated() {\n\tresetSettings()\n\tsettings.Set(KeyMygnoscanURL, \u0026setting{value: \"https://scan.example.com\", rev: 1, updated: 42})\n\tsettings.Set(KeyPause, \u0026setting{value: \"readonly: migrating storage\", rev: 2, updated: 43})\n\tsettings.Set(KeyFor(KeyBlockTop, \"gno.land/r/moul/gns\"), \u0026setting{value: \"\u003e v2 shipped\", rev: 3, updated: 44})\n\tsettingsRev = 3\n\tprint(Render(\"\"))\n\t// Output:\n\t// # gno.land/r/moul/config\n\t//\n\t// moul's settings, read by his other realms. rev 3 · 3 setting(s)\n\t//\n\t// ## Settings\n\t//\n\t// | key | value | rev | height |\n\t// | --- | --- | ---: | ---: |\n\t// | `block.top@r/moul/gns` | `\u003e v2 shipped` | 3 | 44 |\n\t// | `mygnoscan.url` | `https://scan.example.com` | 1 | 42 |\n\t// | `pause` | `readonly: migrating storage` | 2 | 43 |\n\t//\n\t// ## Pause\n\t//\n\t// \u003e **Read-only.** This realm is still readable, but not accepting changes. migrating storage\n\t//\n\t// ## Authority\n\t//\n\t// `member_authority[g1daexjemfde047h6lta047h6lta047h6ld2pug6]`\n\t//\n\t// ---\n\t//\n\t// [explorer](https://scan.example.com/realm/r/moul/config/v1) · [source](https://scan.example.com/realm/r/moul/config/v1?tab=source) · [calls](https://scan.example.com/realm/r/moul/config/v1?tab=calls) · [deps](https://scan.example.com/realm/r/moul/config/v1?tab=deps)\n}\n"}]},"send":"","max_deposit":"35000000ugnot"}],"fee":{"gas_wanted":"238371600","gas_fee":"715114ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"wMMXz5E9EUviOV15PjfRLykhTbSKsWzYMz4qr6QOCXx3TMQiPLOI2UTHScRzWfE4elNUvUSAfyk4mrKOtoXdAQ=="}],"memo":""},"metadata":{"timestamp":"1790960266"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"AndZ8nifiVMgyqxXenxgQm7eqIu4hnEAdqMYBbmGdsNrvXjYQ0vBpVnvjfpl+UsaHX1QF6snleAuwDTTXkaVng=="}],"memo":""},"metadata":{"timestamp":"1790960269"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"args","path":"gno.land/r/moul/demo/args/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/args`\n\nStep 2 of the `r/moul/demo` walkthrough: passing arguments to an exported\nfunction.\n\n```go\nfunc Hello(name string) string { return \"Hello \" + name + \"!\" }\n```\n\nArguments arrive from the transaction as strings and are decoded into the\ndeclared parameter types. There is no state here: the realm reads its input and\nreturns, so two identical calls return the same thing.\n\n```bash\ngnokey maketx call -pkgpath gno.land/r/moul/demo/args \\\n  -func Hello -args People -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast moul\n```\n\nPrevious: [`hello`](../hello). Next: [`data`](../data) adds state that survives\nthe call.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/args/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/args/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/args/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/args/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/args/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/args/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/args/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/args/v0)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"package args\n\nfunc Hello(name string) string {\n\treturn \"Hello \" + name + \"!\"\n}\n"},{"name":"contract_test.gno","body":"package args\n\nimport \"testing\"\n\nfunc Test(t *testing.T) {\n\tgot := Hello(\"People\")\n\texpected := \"Hello People!\"\n\tif got != expected {\n\t\tt.Fatalf(\"expected %q, got %q.\", expected, got)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/args/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"data","path":"gno.land/r/moul/demo/data/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/data`\n\nStep 3 of the `r/moul/demo` walkthrough: realm state that persists between\ntransactions.\n\n```go\nvar total int\n\nfunc init()          { total = 1000 }\nfunc Add(nb int) int { total += nb; return total }\n```\n\n`total` is a package-level variable in a realm, so the VM persists it after\nevery call. `init` runs once, at deploy time, not on each call. Call `Add(42)`\nthen `Add(295)` and the second call returns 1337: the mutation from the first\none was committed to chain storage.\n\nThat is the whole difference between a `p/` package (no state of its own) and\nan `r/` realm.\n\nPrevious: [`args`](../args). Next: [`render`](../render) exposes state through\ngnoweb.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/data/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/data/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/data/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/data/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/data/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/data/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/data/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/data/v0)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"package data\n\nvar total int\n\nfunc init() {\n\ttotal = 1000\n}\n\nfunc Add(nb int) int {\n\ttotal += nb\n\treturn total\n}\n"},{"name":"contract_test.gno","body":"package data\n\nimport \"testing\"\n\nfunc Test(t *testing.T) {\n\t{ // call 1\n\t\tgot := Add(42)\n\t\texpected := 1042\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\t{ // call 2\n\t\tgot := Add(295)\n\t\texpected := 1337\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/data/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"gnoface","path":"gno.land/r/moul/demo/gnoface/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/gnoface/v0`\n\nGenerates a random ASCII/SVG \"gno face\" — a small generative-art demo realm.\nUses [`p/moul/entropy`](../../../../../p/moul/entropy) for pseudo-randomness.\nEducational / fun example (see [r/moul/demo](../../README.md)).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/gnoface/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/gnoface/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/gnoface/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/gnoface/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/gnoface/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/gnoface/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/gnoface/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/gnoface/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/demo/gnoface/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/demo/gnoface/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnoface.gno","body":"package gnoface\n\nimport (\n\t\"math/rand\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/entropy/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc Render(path string) string {\n\tseed := uint64(entropy.New().Value())\n\n\tpath = strings.TrimSpace(path)\n\tif path != \"\" {\n\t\ts, err := strconv.Atoi(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tseed = uint64(s)\n\t}\n\n\toutput := ufmt.Sprintf(\"Gnoface #%d\\n\", seed)\n\toutput += \"```\\n\" + Draw(seed) + \"```\\n\"\n\treturn output\n}\n\nfunc Draw(seed uint64) string {\n\tvar (\n\t\thairs = []string{\n\t\t\t\"     s\",\n\t\t\t\"  .......\",\n\t\t\t\"   s s s\",\n\t\t\t\"   /\\\\ /\\\\\",\n\t\t\t\"  |||||||\",\n\t\t}\n\t\theadtop = []string{\n\t\t\t\" /-------\\\\\",\n\t\t\t\" /~~~~~~~\\\\\",\n\t\t\t\" /|||||||\\\\\",\n\t\t\t\" ////////\\\\\",\n\t\t\t\" |||||||||\",\n\t\t\t\" /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\",\n\t\t}\n\t\theadspace = []string{\n\t\t\t\" |       |\",\n\t\t}\n\t\teyebrow = []string{\n\t\t\t\"~\",\n\t\t\t\"*\",\n\t\t\t\"_\",\n\t\t\t\".\",\n\t\t}\n\t\tear = []string{\n\t\t\t\"o\",\n\t\t\t\" \",\n\t\t\t\"D\",\n\t\t\t\"O\",\n\t\t\t\"\u003c\",\n\t\t\t\"\u003e\",\n\t\t\t\".\",\n\t\t\t\"|\",\n\t\t\t\")\",\n\t\t\t\"(\",\n\t\t}\n\t\teyesmiddle = []string{\n\t\t\t\"| o   o |\",\n\t\t\t\"| o   _ |\",\n\t\t\t\"| _   o |\",\n\t\t\t\"| .   . |\",\n\t\t\t\"| O   O |\",\n\t\t\t\"| v   v |\",\n\t\t\t\"| X   X |\",\n\t\t\t\"| x   X |\",\n\t\t\t\"| X   D |\",\n\t\t\t\"| ~   ~ |\",\n\t\t}\n\t\tnose = []string{\n\t\t\t\" |   o   |\",\n\t\t\t\" |   O   |\",\n\t\t\t\" |   V   |\",\n\t\t\t\" |   L   |\",\n\t\t\t\" |   C   |\",\n\t\t\t\" |   ~   |\",\n\t\t\t\" |  . .  |\",\n\t\t\t\" |   .   |\",\n\t\t}\n\t\tmouth = []string{\n\t\t\t\" |  __/  |\",\n\t\t\t\" |  \\\\_/  |\",\n\t\t\t\" |   .   |\",\n\t\t\t\" |  ___  |\",\n\t\t\t\" |  ~~~  |\",\n\t\t\t\" |  ===  |\",\n\t\t\t\" |  \u003c=\u003e  |\",\n\t\t}\n\t\theadbottom = []string{\n\t\t\t\" \\\\-------/\",\n\t\t\t\" \\\\~~~~~~~/\",\n\t\t\t\" \\\\_______/\",\n\t\t}\n\t)\n\n\tr := rand.New(rand.NewPCG(seed, 0xdeadbeef))\n\n\treturn pick(r, hairs) + \"\\n\" +\n\t\tpick(r, headtop) + \"\\n\" +\n\t\tpick(r, headspace) + \"\\n\" +\n\t\t\" | \" + pick(r, eyebrow) + \"   \" + pick(r, eyebrow) + \" |\\n\" +\n\t\tpick(r, ear) + pick(r, eyesmiddle) + pick(r, ear) + \"\\n\" +\n\t\tpick(r, headspace) + \"\\n\" +\n\t\tpick(r, nose) + \"\\n\" +\n\t\tpick(r, headspace) + \"\\n\" +\n\t\tpick(r, mouth) + \"\\n\" +\n\t\tpick(r, headspace) + \"\\n\" +\n\t\tpick(r, headbottom) + \"\\n\"\n}\n\nfunc pick(r *rand.Rand, slice []string) string {\n\treturn slice[r.IntN(len(slice))]\n}\n\n// based on https://github.com/moul/pipotron/blob/master/dict/ascii-face.yml\n"},{"name":"gnoface_test.gno","body":"package gnoface\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc TestDraw(t *testing.T) {\n\tcases := []struct {\n\t\tseed     uint64\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tseed: 42,\n\t\t\texpected: `\n  |||||||\n |||||||||\n |       |\n | .   ~ |\n)| v   v |O\n |       |\n |   L   |\n |       |\n |  ___  |\n |       |\n \\~~~~~~~/\n`[1:],\n\t\t},\n\t\t{\n\t\t\tseed: 1337,\n\t\t\texpected: `\n  .......\n |||||||||\n |       |\n | .   _ |\nD| x   X |O\n |       |\n |   ~   |\n |       |\n |  ~~~  |\n |       |\n \\~~~~~~~/\n`[1:],\n\t\t},\n\t\t{\n\t\t\tseed: 123456789,\n\t\t\texpected: `\n  .......\n ////////\\\n |       |\n | ~   * |\n|| x   X |o\n |       |\n |   V   |\n |       |\n |   .   |\n |       |\n \\-------/\n`[1:],\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tname := ufmt.Sprintf(\"%d\", tc.seed)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tgot := Draw(tc.seed)\n\t\t\tuassert.Equal(t, string(tc.expected), got)\n\t\t})\n\t}\n}\n\nfunc TestRender(t *testing.T) {\n\tcases := []struct {\n\t\tpath     string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tpath: \"42\",\n\t\t\texpected: \"Gnoface #42\\n```\" + `\n  |||||||\n |||||||||\n |       |\n | .   ~ |\n)| v   v |O\n |       |\n |   L   |\n |       |\n |  ___  |\n |       |\n \\~~~~~~~/\n` + \"```\\n\",\n\t\t},\n\t\t{\n\t\t\tpath: \"1337\",\n\t\t\texpected: \"Gnoface #1337\\n```\" + `\n  .......\n |||||||||\n |       |\n | .   _ |\nD| x   X |O\n |       |\n |   ~   |\n |       |\n |  ~~~  |\n |       |\n \\~~~~~~~/\n` + \"```\\n\",\n\t\t},\n\t\t{\n\t\t\tpath: \"123456789\",\n\t\t\texpected: \"Gnoface #123456789\\n```\" + `\n  .......\n ////////\\\n |       |\n | ~   * |\n|| x   X |o\n |       |\n |   V   |\n |       |\n |   .   |\n |       |\n \\-------/\n` + \"```\\n\",\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.path, func(t *testing.T) {\n\t\t\tgot := Render(tc.path)\n\t\t\tuassert.Equal(t, tc.expected, got)\n\t\t})\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/gnoface/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package gnoface\n\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// Gnoface #2370554733\n\t// ```\n\t//    /\\ /\\\n\t//  |||||||||\n\t//  |       |\n\t//  | _   ~ |\n\t// || o   _ |\u003e\n\t//  |       |\n\t//  |   L   |\n\t//  |       |\n\t//  |  \u003c=\u003e  |\n\t//  |       |\n\t//  \\-------/\n\t// ```\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"grc20","path":"gno.land/r/moul/demo/grc20/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/grc20`\n\nStep 6 of the `r/moul/demo` walkthrough: the same ledger as\n[`wikicoin`](../wikicoin), but on the standard `p/nt/grc20` token instead of a\nhand-rolled tree.\n\n```go\nvar (\n\tToken         *tokens.Token          // exported: anyone may read\n\tprivateLedger *tokens.PrivateLedger  // unexported: mint, burn, transfer\n)\n```\n\n**That split is the whole lesson.** `NewToken` returns two handles onto one\ntoken. The `Token` handle is read-only and safe to export, so other realms can\ncall `Token.BalanceOf(...)` or `Token.GetName()` across the realm boundary. The\n`PrivateLedger` handle can move anyone's balance, so it stays unexported: gno's\nexport rules become the access control, with no permission check to get wrong.\n\nExporting the ledger by accident is a total loss of the token. Keep it lowercase\nand expose deliberate wrappers instead.\n\n`init` creates \"Foo Token\" (`FOO`, 4 decimals) and mints 100000000 units to a\ntest address. `MyBalance()` shows a read scoped to the caller.\n\nPrevious: [`wikicoin`](../wikicoin). Next: [`vault`](../vault) locks tokens up.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/grc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/grc20/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/grc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/grc20/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/grc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/grc20/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/grc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/grc20/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/demo/grc20/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/demo/grc20/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"package grc20\n\nimport (\n\t\"chain/runtime/unsafe\"\n\n\ttokens \"gno.land/p/nt/grc20/v0\"\n)\n\n// test1 receives the initial mint at construction.\nvar test1 = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\n// Token is exported. Other contracts can read it (balances, metadata).\n// privateLedger stays unexported: it grants unrestricted mint/burn/transfer.\nvar (\n\tToken         *tokens.Token\n\tprivateLedger *tokens.PrivateLedger\n)\n\nfunc init(cur realm) {\n\t// generate the token and mint some tokens to test1.\n\tToken, privateLedger = tokens.NewToken(\"Foo Token\", \"FOO\", 4, 0, cur)\n\tprivateLedger.Mint(test1, 100000000)\n}\n\nfunc MyBalance() int64 {\n\treturn Token.BalanceOf(unsafe.OriginCaller())\n}\n"},{"name":"contract_test.gno","body":"package grc20\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc Test(t *testing.T) {\n\ttest2 := testutils.TestAddress(\"test2\")\n\n\t// check token metadata.\n\t{\n\t\tgot := Token.GetName()\n\t\texpected := \"Foo Token\"\n\t\tif strings.TrimSpace(got) != strings.TrimSpace(expected) {\n\t\t\tt.Fatalf(\"expected %q, got %q.\", expected, got)\n\t\t}\n\t}\n\n\t// check balance of test1.\n\t{\n\t\tgot := Token.BalanceOf(test1)\n\t\texpected := int64(100000000)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// transfer tokens from test1 to test2.\n\tif err := privateLedger.Transfer(test1, test2, 1000); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check balance of test1.\n\t{\n\t\tgot := Token.BalanceOf(test1)\n\t\texpected := int64(99999000)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// check balance of test2.\n\t{\n\t\tgot := Token.BalanceOf(test2)\n\t\texpected := int64(1000)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/grc20/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"importdemo","path":"gno.land/r/moul/demo/importdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/importdemo/v0`\n\nA minimal realm that imports and composes packages from **another namespace** —\nthat is the whole point of the demo. It builds a small thread of posts and\nrenders it as Markdown.\n\n```\n/r/moul/demo/importdemo/v0   → the demo thread\n```\n\nUses [`p/nt/avl/v0`](https://gno.land/p/nt/avl/v0) for ordered storage and\n[`p/nt/ufmt/v0`](https://gno.land/p/nt/ufmt/v0) for formatting. Both are\npublished on every chain we target.\n\nStateless: `Render` rebuilds the thread on every call, so its output depends\nonly on the code.\n\n### Only depend on what the chain actually serves\n\nAn earlier cut of this demo imported `gno.land/p/archive/dom`, which is\npublished on **no** chain we target. It type-checked locally and passed CI —\nthe package was vendored — but could never be deployed; `addpkg` failed with:\n\n```\ncould not import gno.land/p/archive/dom (unknown import path \"gno.land/p/archive/dom\")\n```\n\nThat is the trap this demo now documents: a vendored dependency makes the build\ngreen regardless of whether any chain can resolve it.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/importdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/importdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/importdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/importdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/importdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/importdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/importdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/importdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/demo/importdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/demo/importdemo/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"// Package importdemo shows a realm importing and composing packages from\n// ANOTHER namespace — the whole point of the demo.\n//\n// v2 imported gno.land/p/archive/dom, which is published on no chain we target\n// (absent on both sapphire and pearl), so it type-checked locally but could\n// never be deployed: `addpkg` failed with\n// `could not import gno.land/p/archive/dom (unknown import path)`. v2 is\n// archived (`ignore = true`); this version rebuilds the same thread-of-posts\n// idea on foreign packages that are actually on chain — `p/nt/avl/v0` for\n// ordered storage and `p/nt/ufmt/v0` for formatting.\n//\n// Deliberately keeps no realm state: Render builds the thread on each call, so\n// output depends only on the code and the demo is reproducible.\npackage importdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// thread is a titled list of posts, kept in an avl.Tree so iteration is ordered\n// by key rather than by insertion — the same guarantee the realm needs for a\n// stable Render.\ntype thread struct {\n\tname  string\n\tposts *avl.Tree // zero-padded index -\u003e *post\n\tn     int\n}\n\ntype post struct {\n\ttitle string\n\tbody  string\n}\n\nfunc newThread(name string) *thread {\n\treturn \u0026thread{name: name, posts: avl.NewTree()}\n}\n\n// addPost appends a post. The key is zero-padded so avl's lexicographic order\n// matches insertion order past 9 entries (\"10\" would otherwise sort before \"9\").\nfunc (t *thread) addPost(title, body string) {\n\tt.posts.Set(padIdx(t.n), \u0026post{title: title, body: body})\n\tt.n++\n}\n\n// padIdx renders i as a fixed-width, zero-padded key.\n//\n// Done by hand on purpose: gno's ufmt supports NO width or padding flags, so\n// ufmt.Sprintf(\"%03d\", 7) yields \"7\", not \"007\" — silently, with no error. Keys\n// built that way sort as \"0\",\"1\",\"10\",\"11\",\"2\", which quietly reorders every\n// thread past nine posts (TestOrderSurvivesPastNinePosts covers exactly this).\nfunc padIdx(i int) string {\n\ts := strconv.Itoa(i)\n\tfor len(s) \u003c 3 {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n\n// String renders the thread as Markdown.\nfunc (t *thread) String() string {\n\tvar b strings.Builder\n\tb.WriteString(ufmt.Sprintf(\"# [thread] %s\\n\\n\", t.name))\n\tt.posts.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tp := v.(*post)\n\t\tb.WriteString(ufmt.Sprintf(\"## %s\\n%s\\n\", p.title, p.body))\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\n// Render renders the demo thread for gnoweb.\nfunc Render(path string) string {\n\tt := newThread(\"Hello!\")\n\tt.addPost(\"Foo\", \"foo foo foo\")\n\tt.addPost(\"Bar\", \"bar bar bar\")\n\treturn t.String()\n}\n"},{"name":"contract_test.gno","body":"package importdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRender(t *testing.T) {\n\tgot := Render(\"\")\n\texpected := `\n# [thread] Hello!\n\n## Foo\nfoo foo foo\n## Bar\nbar bar bar\n`\n\tuassert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(got))\n}\n\n// Render must not depend on realm state: two calls have to agree, and the\n// second must not accumulate the first one's posts.\nfunc TestRenderIsPure(t *testing.T) {\n\tuassert.Equal(t, Render(\"\"), Render(\"\"))\n\tuassert.Equal(t, 2, strings.Count(Render(\"\"), \"## \"))\n}\n\n// Posts come back in insertion order. The keys are zero-padded precisely so\n// avl's lexicographic ordering does not put \"10\" before \"9\" past nine posts.\nfunc TestOrderSurvivesPastNinePosts(t *testing.T) {\n\tth := newThread(\"many\")\n\tfor i := 0; i \u003c 12; i++ {\n\t\tth.addPost(ufmtIdx(i), \"body\")\n\t}\n\tout := th.String()\n\t// post 9 must appear before post 10\n\tif strings.Index(out, \"## p9\\n\") \u003e strings.Index(out, \"## p10\\n\") {\n\t\tt.Fatalf(\"insertion order lost past 9 posts:\\n%s\", out)\n\t}\n\tuassert.Equal(t, 12, strings.Count(out, \"## \"))\n}\n\nfunc ufmtIdx(i int) string {\n\treturn \"p\" + itoa(i)\n}\n\nfunc itoa(i int) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b []byte\n\tfor i \u003e 0 {\n\t\tb = append([]byte{byte('0' + i%10)}, b...)\n\t\ti /= 10\n\t}\n\treturn string(b)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/importdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package importdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # [thread] Hello!\n\t//\n\t// ## Foo\n\t// foo foo foo\n\t// ## Bar\n\t// bar bar bar\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"microposts","path":"gno.land/r/moul/demo/microposts/v0","files":[{"name":"README.md","body":"# fork of `leon/fosdem25/microposts`\n\nremoving optional lines to make the code more concise for slides.\n\nOriginal work here: https://gno.land/r/leon/fosdem25/microposts\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/microposts/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/microposts/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/microposts/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/microposts/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/microposts/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/microposts/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/microposts/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/microposts/v0)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/microposts/v0\"\ngno = \"0.9\"\n"},{"name":"microposts_test.gno","body":"package microposts\n\n// empty file just to make sure that `gno test` tries to parse the implementation.\n"},{"name":"post.gno","body":"package microposts\n\nimport (\n\t\"time\"\n)\n\ntype Post struct {\n\ttext      string\n\tauthor    address\n\tcreatedAt time.Time\n}\n\nfunc (p Post) String() string {\n\tout := p.text + \"\\n\"\n\tout += \"_\" + p.createdAt.Format(\"02 Jan 2006, 15:04\") + \", by \" + p.author.String() + \"_\"\n\treturn out\n}\n"},{"name":"realm.gno","body":"package microposts\n\nimport (\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar posts []*Post\n\nfunc CreatePost(text string) {\n\tposts = append(posts, \u0026Post{\n\t\ttext:      text,\n\t\tauthor:    unsafe.PreviousRealm().Address(), // provided by env\n\t\tcreatedAt: time.Now(),\n\t})\n}\n\nfunc Render(_ string) string {\n\tout := \"# Posts\\n\"\n\tfor i := len(posts) - 1; i \u003e= 0; i-- {\n\t\tout += \"### Post \" + strconv.Itoa(i) + \"\\n\" + posts[i].String()\n\t}\n\treturn out\n}\n"},{"name":"render_example_test.gno","body":"package microposts\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Posts\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"millipede","path":"gno.land/r/moul/demo/millipede/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/millipede/v0`\n\nRenders an ASCII millipede of a requested size — a tiny generative-art demo realm.\nEducational / fun example (see [r/moul/demo](../../README.md)).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/millipede/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/millipede/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/millipede/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/millipede/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/millipede/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/millipede/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/millipede/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/millipede/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/demo/millipede/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/demo/millipede/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/millipede/v0\"\ngno = \"0.9\"\n"},{"name":"millipede.gno","body":"package millipede\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\tminSize     = 1\n\tdefaultSize = 20\n\tmaxSize     = 100\n)\n\nfunc Draw(size int) string {\n\tif size \u003c minSize || size \u003e maxSize {\n\t\tpanic(\"invalid millipede size\")\n\t}\n\tpaddings := []string{\"  \", \" \", \"\", \" \", \"  \", \"   \", \"    \", \"    \", \"   \"}\n\tvar b strings.Builder\n\tb.WriteString(\"    ╚⊙ ⊙╝\\n\")\n\tfor i := 0; i \u003c size; i++ {\n\t\tb.WriteString(paddings[i%9] + \"╚═(███)═╝\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc Render(path string) string {\n\tsize := defaultSize\n\n\tpath = strings.TrimSpace(path)\n\tif path != \"\" {\n\t\tvar err error\n\t\tsize, err = strconv.Atoi(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\toutput := \"```\\n\" + Draw(size) + \"```\\n\"\n\tif size \u003e minSize {\n\t\toutput += ufmt.Sprintf(\"[%d](/r/demo/art/millipede:%d)\u003c \", size-1, size-1)\n\t}\n\tif size \u003c maxSize {\n\t\toutput += ufmt.Sprintf(\" \u003e[%d](/r/demo/art/millipede:%d)\", size+1, size+1)\n\t}\n\treturn output\n}\n\n// based on https://github.com/getmillipede/millipede-go/blob/977f046c39c35a650eac0fd30245e96b22c7803c/main.go\n"},{"name":"millipede_test.gno","body":"package millipede\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRender(t *testing.T) {\n\tcases := []struct {\n\t\tpath     string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tpath: \"\",\n\t\t\texpected: \"```\" + `\n    ╚⊙ ⊙╝\n  ╚═(███)═╝\n ╚═(███)═╝\n╚═(███)═╝\n ╚═(███)═╝\n  ╚═(███)═╝\n   ╚═(███)═╝\n    ╚═(███)═╝\n    ╚═(███)═╝\n   ╚═(███)═╝\n  ╚═(███)═╝\n ╚═(███)═╝\n╚═(███)═╝\n ╚═(███)═╝\n  ╚═(███)═╝\n   ╚═(███)═╝\n    ╚═(███)═╝\n    ╚═(███)═╝\n   ╚═(███)═╝\n  ╚═(███)═╝\n ╚═(███)═╝\n` + \"```\\n[19](/r/demo/art/millipede:19)\u003c  \u003e[21](/r/demo/art/millipede:21)\",\n\t\t},\n\t\t{\n\t\t\tpath: \"4\",\n\t\t\texpected: \"```\" + `\n    ╚⊙ ⊙╝\n  ╚═(███)═╝\n ╚═(███)═╝\n╚═(███)═╝\n ╚═(███)═╝\n` + \"```\\n[3](/r/demo/art/millipede:3)\u003c  \u003e[5](/r/demo/art/millipede:5)\",\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.path, func(t *testing.T) {\n\t\t\tgot := Render(tc.path)\n\t\t\tuassert.Equal(t, tc.expected, got)\n\t\t})\n\t}\n}\n"},{"name":"render_example_test.gno","body":"package millipede\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// ```\n\t//     ╚⊙ ⊙╝\n\t//   ╚═(███)═╝\n\t//  ╚═(███)═╝\n\t// ╚═(███)═╝\n\t//  ╚═(███)═╝\n\t//   ╚═(███)═╝\n\t//    ╚═(███)═╝\n\t//     ╚═(███)═╝\n\t//     ╚═(███)═╝\n\t//    ╚═(███)═╝\n\t//   ╚═(███)═╝\n\t//  ╚═(███)═╝\n\t// ╚═(███)═╝\n\t//  ╚═(███)═╝\n\t//   ╚═(███)═╝\n\t//    ╚═(███)═╝\n\t//     ╚═(███)═╝\n\t//     ╚═(███)═╝\n\t//    ╚═(███)═╝\n\t//   ╚═(███)═╝\n\t//  ╚═(███)═╝\n\t// ```\n\t// [19](/r/demo/art/millipede:19)\u003c  \u003e[21](/r/demo/art/millipede:21)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"render","path":"gno.land/r/moul/demo/render/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/render`\n\nStep 4 of the `r/moul/demo` walkthrough: `Render`, the read-only view a realm\nexposes to gnoweb.\n\n```go\nfunc Render(path string) string\n```\n\n`Render` receives whatever follows the `:` in the URL and routes on it. Three\nroutes are wired here:\n\n| path | output |\n| --- | --- |\n| `\"\"` | an index linking to the other two |\n| `\"hello\"` | `Hello World!` |\n| `\"greetings/\u003cname\u003e\"` | `Welcome, \u003cName\u003e!` |\n| anything else | `404` |\n\n`Render` is a query, not a transaction: no gas, no signature, and it must be\ndeterministic.\n\n```bash\ngnokey query vm/qrender -data 'gno.land/r/moul/demo/render:greetings/manfred' \\\n  -remote https://rpc.gno.land:443\n```\n\n**Caveat, kept on purpose.** The index route still emits links to\n`/r/moul_basics_004:`, the path this code was written against in an older\nworkshop. They do not resolve at this realm's current path. It is a good\nillustration of the trap: a hardcoded self-link becomes wrong the moment the\nrealm moves, so build links from the request path (see\n[`p/moul/realmpath`](../../../../p/moul/realmpath)) instead.\n\nPrevious: [`data`](../data). Next: [`wikicoin`](../wikicoin) builds a ledger.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/render/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/render/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/render/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/render/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/render/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/render/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/render/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/render/v0)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"package render\n\nimport \"strings\"\n\nfunc Hello() string {\n\treturn \"Hello World!\"\n}\n\nfunc greetings(name string) string { // private\n\treturn \"Welcome, \" + name + \"!\"\n}\n\nfunc Render(path string) string {\n\tswitch {\n\tcase path == \"hello\":\n\t\treturn Hello()\n\tcase strings.HasPrefix(path, \"greetings/\"):\n\t\tname := strings.Split(path, \"/\")[1] // take string after slash\n\t\tname = strings.Title(name)          // capitalize first letter\n\t\treturn greetings(name)\n\tcase path == \"\":\n\t\tout := \"- [hello](/r/moul_basics_004:hello)\\n\"\n\t\tout += \"- [greetings/Manfred](/r/moul_basics_004:greetings/Manfred)\\n\"\n\t\treturn out\n\t}\n\treturn \"404\"\n}\n"},{"name":"contract_test.gno","body":"package render\n\nimport \"testing\"\n\nfunc Test(t *testing.T) {\n\tshouldEqual(t, \"hello\", \"Hello World!\")\n\tshouldEqual(t, \"greetings/Manfred\", \"Welcome, Manfred!\")\n\tshouldEqual(t, \"foobar\", \"404\")\n}\n\nfunc shouldEqual(t *testing.T, path string, expected string) {\n\tt.Helper()\n\n\tgot := Render(path)\n\tif got != expected {\n\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/render/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package render\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// - [hello](/r/moul_basics_004:hello)\n\t// - [greetings/Manfred](/r/moul_basics_004:greetings/Manfred)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"vault","path":"gno.land/r/moul/demo/vault/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/vault`\n\nStep 7 and last of the `r/moul/demo` walkthrough: a time-locked vault over the\nGRC20 token from [`grc20`](../grc20).\n\nWithdrawing is deliberately two steps, so that a stolen key does not drain the\nvault in one transaction:\n\n```go\nfunc Deposit(cur realm, amount uint, recoverAddress address)  // caller -\u003e vault\nfunc Unvault(cur realm, amount uint)                          // arm the timer\nfunc Redeem(cur realm, amount uint)                           // after the lock\nfunc Recover(cur realm, target address)                       // escape hatch\n```\n\n`Unvault` moves an amount from `vaulted` to `pending` and stamps\n`unlockAt = ChainHeight() + 100`. `Redeem` refuses until the chain passes that\nheight. In between, the depositor (or whoever is watching) can call `Recover`\nto push the still-locked balance to the recovery address recorded at deposit\ntime. That is the pattern: a withdrawal announces itself, and the announcement\nwindow is when a theft can be reversed.\n\nDeposited tokens live at the realm's own address (`cur.Address()`), which is\nwhat makes the vault custodial rather than an accounting fiction.\n\n## What is wrong with it on purpose\n\nThis is a demo, and two things would sink it in production:\n\n- **`Recover` has no caller check.** Anyone can call `Recover(target)` for any\n  target. It only ever pays out to the address the target itself recorded, so\n  it cannot steal, but it is a free denial of service: a bystander can rewind\n  anyone's deposit at will.\n- **Only `Unvault`/`Redeem` are covered by tests.** `Recover` has none, flagged\n  as a `TODO` in the test file.\n\nRead it for the two-step withdrawal shape, not as a vault to deploy. (Note that\n`r/moul/x/daily/vault` is a different thing entirely: a key-value store, not a\ntoken vault.)\n\nPrevious: [`grc20`](../grc20).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/vault/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/vault/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/vault/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/vault/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/vault/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/vault/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/vault/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/vault/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/demo/vault/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/demo/vault/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"// Package vault demonstrates a minimal time-locked token vault built on top of\n// the grc20 token package. Deposited tokens are held at the realm's own\n// address; withdrawing them is a two-step process: Unvault marks an amount for\n// withdrawal and starts a lock timer, then (once the lock elapses) Redeem moves\n// the tokens back to the depositor.\npackage vault\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\ttokens \"gno.land/p/nt/grc20/v0\"\n)\n\n// test1 receives the initial mint at construction.\nvar test1 = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\n// lockDuration is the number of blocks that must pass between Unvault and\n// Redeem.\nconst lockDuration = int64(100)\n\n// Token and FooVault-equivalent state are exported for reading; privateLedger\n// stays unexported (unrestricted mint/burn/transfer).\nvar (\n\tToken         *tokens.Token\n\tprivateLedger *tokens.PrivateLedger\n\tvaultAddr     address // address holding all deposited tokens\n\n\tvaulted   = map[address]uint{}    // still-locked deposits per owner\n\tpending   = map[address]uint{}    // amount marked for withdrawal\n\tunlockAt  = map[address]int64{}    // block height at which pending unlocks\n\trecoverOf = map[address]address{}  // recovery address per depositor\n)\n\nfunc init(cur realm) {\n\t// generate the token and mint some tokens to test1.\n\tToken, privateLedger = tokens.NewToken(\"Foo Token\", \"FOO\", 4, 0, cur)\n\tprivateLedger.Mint(test1, 100000000)\n\n\t// the vault holds deposited tokens at the realm's own address.\n\tvaultAddr = cur.Address()\n}\n\nfunc MyBalance() int64 {\n\treturn Token.BalanceOf(unsafe.OriginCaller())\n}\n\n// Deposit moves amount tokens from the caller into the vault, recording a\n// recovery address for later use.\nfunc Deposit(cur realm, amount uint, recoverAddress address) {\n\tcaller := unsafe.OriginCaller()\n\tif err := privateLedger.Transfer(caller, vaultAddr, int64(amount)); err != nil {\n\t\tpanic(err)\n\t}\n\tvaulted[caller] += amount\n\trecoverOf[caller] = recoverAddress\n}\n\n// Recover sends target's still-locked deposit to its recorded recovery address.\nfunc Recover(cur realm, target address) {\n\tamount := vaulted[target]\n\tif amount == 0 {\n\t\treturn\n\t}\n\tdest := recoverOf[target]\n\tif err := privateLedger.Transfer(vaultAddr, dest, int64(amount)); err != nil {\n\t\tpanic(err)\n\t}\n\tvaulted[target] = 0\n}\n\n// Unvault marks amount of the caller's deposit for withdrawal and starts the\n// lock timer.\nfunc Unvault(cur realm, amount uint) {\n\tcaller := unsafe.OriginCaller()\n\tif vaulted[caller] \u003c amount {\n\t\tpanic(\"insufficient vaulted balance\")\n\t}\n\tvaulted[caller] -= amount\n\tpending[caller] += amount\n\tunlockAt[caller] = runtime.ChainHeight() + lockDuration\n}\n\n// Redeem transfers amount of the caller's matured pending withdrawal back to\n// the caller.\nfunc Redeem(cur realm, amount uint) {\n\tcaller := unsafe.OriginCaller()\n\tif pending[caller] \u003c amount {\n\t\tpanic(\"insufficient pending balance\")\n\t}\n\tif runtime.ChainHeight() \u003c unlockAt[caller] {\n\t\tpanic(\"still locked\")\n\t}\n\tif err := privateLedger.Transfer(vaultAddr, caller, int64(amount)); err != nil {\n\t\tpanic(err)\n\t}\n\tpending[caller] -= amount\n}\n"},{"name":"contract_test.gno","body":"package vault\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc Test(cur realm, t *testing.T) {\n\ttest2 := testutils.TestAddress(\"test2\")\n\ttest3 := testutils.TestAddress(\"test3\")\n\n\t// check token metadata.\n\t{\n\t\tgot := Token.GetName()\n\t\texpected := \"Foo Token\"\n\t\tif strings.TrimSpace(got) != strings.TrimSpace(expected) {\n\t\t\tt.Fatalf(\"expected %q, got %q.\", expected, got)\n\t\t}\n\t}\n\n\t// check balance of test1.\n\t{\n\t\tgot := Token.BalanceOf(test1)\n\t\texpected := int64(100000000)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// transfer tokens from test1 to test2.\n\tif err := privateLedger.Transfer(test1, test2, 1000); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check balance of test1.\n\t{\n\t\tgot := Token.BalanceOf(test1)\n\t\texpected := int64(99999000)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// check balance of test2.\n\t{\n\t\tgot := Token.BalanceOf(test2)\n\t\texpected := int64(1000)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// test1 deposits 300 with test3 as recovery address.\n\ttesting.SetOriginCaller(test1)\n\tDeposit(cross(cur), 300, test3)\n\n\t// check balance of test1.\n\t{\n\t\tgot := Token.BalanceOf(test1)\n\t\texpected := int64(99998700)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// check balance of the vault.\n\t{\n\t\tgot := Token.BalanceOf(vaultAddr)\n\t\texpected := int64(300)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// test1 unvaults 50 tokens, waits past the lock, then redeems them.\n\tUnvault(cross(cur), 50)\n\ttesting.SkipHeights(101)  // SkipHeights resets the context, so re-set the caller.\n\ttesting.SetOriginCaller(test1)\n\tRedeem(cross(cur), 50)\n\n\t// check balance of test1.\n\t{\n\t\tgot := Token.BalanceOf(test1)\n\t\texpected := int64(99998750)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// check balance of the vault.\n\t{\n\t\tgot := Token.BalanceOf(vaultAddr)\n\t\texpected := int64(250)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// Recover sends test1's still-locked 250 to the recovery address recorded\n\t// at deposit time (test3), leaving the vault empty.\n\t//\n\t// It is called here by test2, a bystander who never deposited, because\n\t// Recover has NO caller check. That is a real flaw and this test pins it:\n\t// it cannot steal (the destination is whatever the target itself recorded)\n\t// but anyone can rewind anyone's deposit at will, which is a free denial of\n\t// service. If a caller check is ever added, this assertion is what will\n\t// fail, so the change has to be deliberate.\n\ttesting.SetOriginCaller(test2)\n\tRecover(cross(cur), test1)\n\n\t// the recovery address received the whole locked balance.\n\t{\n\t\tgot := Token.BalanceOf(test3)\n\t\texpected := int64(250)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// the vault is empty.\n\t{\n\t\tgot := Token.BalanceOf(vaultAddr)\n\t\texpected := int64(0)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n\n\t// Recovering twice is a no-op rather than a second payout: the vaulted\n\t// balance is zero, so Recover returns before transferring anything.\n\tRecover(cross(cur), test1)\n\t{\n\t\tgot := Token.BalanceOf(test3)\n\t\texpected := int64(250)\n\t\tif got != expected {\n\t\t\tt.Fatalf(\"expected %d, got %d.\", expected, got)\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/vault/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wikicoin","path":"gno.land/r/moul/demo/wikicoin/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/demo/wikicoin`\n\nStep 5 of the `r/moul/demo` walkthrough: the token from\n[Wikipedia's Solidity article](https://en.wikipedia.org/wiki/Solidity),\ntranslated to gno line by line.\n\n```go\nfunc Mint(cur realm, receiver address, amount uint)   // minter only\nfunc Send(cur realm, receiver address, amount uint)\nfunc BalanceOf(addr address) uint\n```\n\nWhat the translation shows:\n\n- Solidity's `constructor` becomes `init()`, which runs once at deploy. The\n  deployer is recorded as `minter`.\n- `mapping(address =\u003e uint)` becomes an [`avl.Tree`](https://github.com/gnolang/gno/tree/master/examples/gno.land/p/nt/avl)\n  keyed by the address string. Gno has maps, but an avl tree is the\n  storage-friendly choice for a ledger that grows.\n- `require(msg.sender == minter)` becomes an explicit `panic(\"restricted\")`.\n  A panic aborts the transaction and reverts every write, the same way a revert\n  does.\n- Solidity's `msg.sender` is `unsafe.OriginCaller()` here, which is the\n  transaction signer, not the immediate caller. That distinction does not\n  matter in a demo and matters a great deal in production: it is what\n  `AssertOriginCall` guards exist for.\n\nThis is teaching material, not a token to use. For a real one, use\n[`p/nt/grc20`](https://github.com/gnolang/gno/tree/master/examples/gno.land/p/nt/grc20),\nwhich [`grc20`](../grc20) demonstrates next.\n\nPrevious: [`render`](../render). Next: [`grc20`](../grc20).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/demo/wikicoin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/wikicoin/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/demo/wikicoin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/wikicoin/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/demo/wikicoin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/wikicoin/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/demo/wikicoin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/demo/wikicoin/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/demo/wikicoin/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/demo/wikicoin/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"contract.gno","body":"// based on Wikipedia's Solidity example: https://en.wikipedia.org/wiki/Solidity\npackage wikicoin\n\nimport (\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar balances = avl.NewTree() // addr -\u003e balance\nvar minter address\n\n// Constructor code is only run when the contract is created\nfunc init() {\n\tminter = unsafe.OriginCaller()\n}\n\nfunc Mint(cur realm, receiver address, amount uint) {\n\tif unsafe.OriginCaller() != minter {\n\t\tpanic(\"restricted\")\n\t}\n\tcurBalance := BalanceOf(receiver)\n\tnewBalance := curBalance + amount\n\tbalances.Set(receiver.String(), newBalance)\n}\n\nfunc Send(cur realm, receiver address, amount uint) {\n\tsender := unsafe.OriginCaller()\n\tsenderBalance := BalanceOf(sender)\n\tif amount \u003e senderBalance {\n\t\tpanic(ufmt.Sprintf(\"insufficient balance: %d\", senderBalance))\n\t}\n\treceiverBalance := BalanceOf(receiver)\n\tbalances.Set(sender.String(), senderBalance-amount)\n\tbalances.Set(receiver.String(), receiverBalance+amount)\n}\n\nfunc BalanceOf(addr address) uint {\n\tbalance := balances.Get(addr.String())\n\tif balance == nil {\n\t\treturn 0\n\t}\n\treturn balance.(uint)\n}\n"},{"name":"contract_test.gno","body":"package wikicoin\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc Test(cur realm, t *testing.T) {\n\ttest2 := testutils.TestAddress(\"test2\")\n\n\tmint := uint(1000)\n\tMint(cross(cur), test2, mint)\n\n\ttesting.SetOriginCaller(test2) // dropping privileges\n\tbal := BalanceOf(test2)\n\tif bal != mint {\n\t\tt.Errorf(\"expected %d, got %d\", mint, bal)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/demo/wikicoin/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"239251600","gas_fee":"717754ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"9HobN7w53VmJFGl6XwyQWJayi3bSMt6yVo2R0oP9N2wpALzTBYDpenilXQtd3fMYQb4ATZyDZpw9jRBzIJj8Dw=="}],"memo":""},"metadata":{"timestamp":"1790960328"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"73GUS0KC5Od1rvf82LdTaxT0wP+bEgoQgws7BGWk2qlQrnFSAoPfv8McRhSz2Rf15BXpK1j/di+gT31rWmyO1g=="}],"memo":""},"metadata":{"timestamp":"1790960332"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"faucet","path":"gno.land/r/moul/faucet/v1","files":[{"name":"README.md","body":"# GNOT faucet\n\nA two-step, on-the-record way to get a small amount of GNOT to someone who has\nnone: anyone files a request on their behalf, an approver releases it, and both\nhalves stay on the page with a reason attached.\n\nIt exists because the accounts that most need a first coin are exactly the ones\nthat cannot ask for it. An empty account cannot pay the gas to call anything,\nso `Request` takes the recipient as an argument and the filer pays for the ask.\n\nThis is not the grant board. The grant board weighs work against milestones and\nproofs; this hands over pocket change so somebody can try the chain at all.\n\n## The float\n\nThe faucet spends only what has been sent to its own package address, never the\napprover's balance. Top it up with a plain bank send to that address, or with\n`Fund` if you want the donation on the record. `Withdraw` takes it back, to the\nowner and nowhere else.\n\n## `v0` is on chain, frozen, and not this code\n\n`gno.land/r/moul/faucet/v0` was published to mainnet at block 245194, two\nminutes before the commit that added `private = true`. `private` is read off the\nsubmitted package at deploy time, so the chain never saw the flag, and a public\npath cannot later be redeployed as a private one or at all. `v0` is therefore\nfrozen forever, carrying an unbounded `Render` whose page and query gas grow\nwith every request.\n\nThat is what this `v1` exists to replace. Its float lives at a different\naddress, its float was moved by hand, and `v0`'s page still answers with an\nempty board. **If you found `v0` first, this is the live one.**\n\nThe lesson is cheap to state and was not cheap to learn: **publish from the\ncommit you mean to publish**, because for a public realm the deploy is the last\nmoment anything about it can change.\n\n## It is a private realm\n\n`gnomod.toml` declares `private = true`, so the creator can redeploy this path\nwith corrected code rather than abandon it for a `v2`. On a realm holding other\npeople's rent money that is worth having, and `v0` is the demonstration of what\nits absence costs.\n\nWhat a redeploy costs is exact, and measured rather than assumed:\n\n| across a redeploy | |\n|---|---|\n| the code | replaced |\n| the float | **kept** — coins live at the address, which is bank state |\n| requests, approvers, counters | **wiped** — every initializer runs again |\n| storage deposit | accumulates; the old objects are not evicted, so nothing refunds them |\n\nSo a bug fix here is cheap in money and expensive in history. That is the right\nway round for a faucet and the wrong way round for anything whose ledger people\nrely on, which is why this is a per-realm decision and not a repo-wide default.\n\nPrivate is **one-way and set at the first deploy**: a public path can never\nbecome private, nor the reverse. And no other realm may import this one or hold\na reference to its objects. Nothing else here does, and reading it from outside\nis unaffected: `vm/qrender` and `vm/qeval` both work normally on a private\nrealm.\n\n## The two calls, and why they travel together\n\n| call | who | what it does |\n|---|---|---|\n| `Request(to, amount, reason)` | anyone | files an ask, returns its id, moves no money |\n| `Approve(id, to, amount)` | an approver | pays it out of the float |\n| `Deny(id, why)` | an approver | closes it unpaid, with the reason on the page |\n| `Fund()` | anyone, payable | credits the float and emits an event |\n| `Withdraw(amount)` | the owner | returns float to the owner |\n| `AddApprover` / `RemoveApprover` / `SetMaxPerRequest` | the owner | the knobs |\n\nA tm2 transaction carries a list of messages, runs them in order, and stops at\nthe first failure; a failed transaction writes none of their state, only the\nfee and the sequence survive. So `Request` and `Approve` sent as two messages of\none transaction either both happen or neither does, and the common case is a\nsingle signature.\n\n### The id the second message cannot know\n\n`Approve` names a request by id, and message 2 of a transaction cannot read what\nmessage 1 returned. The caller reads `NextID` before signing and writes that\nnumber into the approval, which is a race: another request landing in between\nshifts the id, and the approval would pay a stranger.\n\nThat is why `Approve` also takes the recipient and the amount it believes it is\napproving, and aborts when the stored request disagrees. The race then costs a\nfailed transaction instead of the wrong person's money.\n\n## Calls\n\n```sh\n# Ask, on someone else's behalf. Amount is in ugnot.\ngnokey maketx call -pkgpath \"gno.land/r/moul/faucet/v1\" -func Request \\\n  -args \"g1...\" -args 100000000 -args \"no gas, wants to try the chain\" \\\n  -gas-fee 30000ugnot -gas-wanted 3000000 -broadcast -chainid gnoland-1 moul\n\n# What id the next request will get, so an approval can be signed alongside it.\ngnokey query vm/qeval -data 'gno.land/r/moul/faucet/v1.NextID()'\n\n# What the float holds.\ngnokey query vm/qeval -data 'gno.land/r/moul/faucet/v1.Balance()'\n\n# The page.\ngnokey query vm/qrender -data 'gno.land/r/moul/faucet/v1:'\n```\n\n## Reading it\n\n`Render(\"\")` is the board: float, open requests, decided ones, approvers.\n`Render(\"req/\u003cid\u003e\")` is one request, with its reason and, if it was refused, why.\n\nEach table shows at most 20 rows, open oldest first and decided newest first,\nand says how many it is hiding. The cap is not cosmetic: the totals come from\nthe realm's counters, so the walk stops once a table is full. A board that\nrendered every request ever filed would grow its page and its gas cost forever,\nand this path is permanent. Anything hidden is still reachable by id.\n\nEvery caller-supplied string on those pages is escaped before it is rendered.\nA reason is arbitrary text from an arbitrary account and `Render` output is\nmarkdown that gnoweb parses, so an unescaped one can plant a link, an image\nbeacon or page chrome on a page the realm signs for. This path is permanent, so\nthat bug could only ever be fixed at a new path.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/faucet/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/faucet/v1/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"faucet.gno","body":"// Package faucet hands a small amount of GNOT to someone who has none, on the\n// record, in two calls that are meant to travel in one transaction.\n//\n// The chain's own faucet is gated and the people who most need a first coin\n// are exactly the people who cannot ask for one: an empty account cannot pay\n// the gas to call anything. So somebody else files the request on their\n// behalf, an approver releases it, and both halves are on chain with a reason\n// attached.\n//\n// # Why two calls and not one bank send\n//\n// [Request] is permissionless and [Approve] is not. Splitting them puts the\n// ask, its reason and who made it on chain even when the answer is no, and\n// makes every payout name the request it settles. A plain send would leave a\n// transfer with no why, and no way to refuse one in public.\n//\n// They are meant to be sent together. A tm2 transaction carries a LIST of\n// messages, runs them in order and stops at the first failure, and a failed\n// transaction writes none of their state: only the fee and the sequence\n// survive (tm2/pkg/sdk/baseapp.go, runMsgs and WriteCheckpoint). So a request\n// and its approval in one transaction either both happen or neither does.\n//\n// # The id the second message cannot know yet\n//\n// [Approve] names a request by id, and message 2 of a transaction cannot read\n// what message 1 returned. A caller therefore reads [NextID] first and writes\n// that number into the approval, which is a race: another Request landing in\n// between shifts the id under it, and the approval would pay a stranger.\n//\n// That is why [Approve] also takes the recipient and the amount it believes it\n// is approving, and refuses when the stored request disagrees. The race then\n// costs a failed transaction instead of the wrong person's rent.\n//\n// # What bounds the damage\n//\n// The faucet spends only what has been sent to its own address, never the\n// approver's balance, so the float is the ceiling and topping it up is a\n// deliberate act. [MaxPerRequest] caps any single payout under that, and\n// [Withdraw] takes the float back.\n//\n// # It is a private realm, which buys a code fix and costs the ledger\n//\n// gnomod.toml declares private = true, so the creator can redeploy this path\n// with corrected code instead of abandoning it for a v1. That matters for a\n// realm holding other people's rent money.\n//\n// The price is exact and was measured, not assumed: a redeploy re-runs every\n// package initializer, so the float SURVIVES (coins live at the address, which\n// is bank state) and everything on this page DOES NOT. Requests, approvers and\n// counters all return to their init values. Fixing a bug here is therefore\n// cheap in money and expensive in history, which is the right way round for a\n// faucet and the wrong way round for a ledger anyone relies on.\n//\n// Two more consequences worth knowing before copying this: private is one-way\n// and set at first deploy (a public path can never become private, nor the\n// reverse), and no other realm may import this one or hold a reference to its\n// objects.\npackage faucet\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst (\n\t// Denom is the only coin this faucet holds or pays.\n\tDenom = \"ugnot\"\n\t// Path is this realm's package path; its float is held at the address\n\t// derived from it.\n\tPath = \"gno.land/r/moul/faucet/v1\"\n\t// Link is Path as a gnoweb route.\n\tLink = \"/r/moul/faucet/v1\"\n)\n\n// Owner funds the faucet, approves by default, and is the only account that\n// can change who else approves or take the float back.\n//\n// Hardcoded rather than captured from the deployer: inside a plain\n// `func Test(t *testing.T)` the gno test runner reports OriginCaller() as the\n// EMPTY address, so an owner seeded from it is empty in every test and\n// something else on chain. That divergence is where an authorization bug\n// hides, so the address is written down.\nconst Owner = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\n// The three states a request can be in. A request is decided exactly once.\nconst (\n\tStatusPending = \"pending\"\n\tStatusSent    = \"sent\"\n\tStatusDenied  = \"denied\"\n)\n\nconst (\n\t// DefaultMaxPerRequest is the starting cap on a single payout, 200 GNOT.\n\t// It is a guard against a fat finger, not against a hostile approver:\n\t// an approver can raise nothing, but the Owner can.\n\tDefaultMaxPerRequest = 200_000_000\n\n\t// MaxReasonLen bounds the stored reason. It is rendered on a page, so it\n\t// is both a storage cost and a display one.\n\tMaxReasonLen = 280\n\n\t// idWidth pads the avl key. gno's ufmt supports no width flags, so the\n\t// padding is done by hand; unpadded numeric keys sort \"1\",\"10\",\"2\" and\n\t// the request list would lose its order past nine entries.\n\tidWidth = 12\n)\n\n// request is one ask. It is unexported because avl stores `any` and the\n// readable surface of this realm is its views and its page, not a struct\n// another realm would have to depend on.\ntype request struct {\n\tID      int64\n\tTo      address\n\tAmount  int64 // ugnot\n\tReason  string\n\tBy      address // who filed it, which is usually not who receives it\n\tAsked   int64   // chain height at filing\n\tStatus  string\n\tJudge   address // who decided, zero while pending\n\tDecided int64   // chain height of the decision\n\tNote    string  // the denial reason; empty otherwise\n}\n\nvar (\n\trequests  avl.Tree // padded id -\u003e *request\n\tpaid      avl.Tree // recipient address -\u003e int64 ugnot received in total\n\tapprovers avl.Tree // approver address -\u003e bool\n\n\tnextID        int64\n\tmaxPerRequest int64\n\n\ttotalSent   int64\n\tsentCount   int64\n\tdeniedCount int64\n\tpendingN    int64\n)\n\nfunc init() { reset() }\n\n// reset installs an empty faucet. Also called by the tests: realm globals\n// persist for a whole test binary and examples run after every Test, so a\n// pinned Render has to start from a known state.\nfunc reset() {\n\trequests = avl.Tree{}\n\tpaid = avl.Tree{}\n\tapprovers = avl.Tree{}\n\tapprovers.Set(Owner.String(), true)\n\tnextID = 1\n\tmaxPerRequest = DefaultMaxPerRequest\n\ttotalSent, sentCount, deniedCount, pendingN = 0, 0, 0, 0\n}\n\n// Address is where the float sits: this realm's own package address. Fund the\n// faucet by sending ugnot to it, with a plain bank send or with [Fund].\nfunc Address() address { return chain.PackageAddress(Path) }\n\n// Balance is what the faucet can actually pay out right now.\nfunc Balance() int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(Address()).AmountOf(Denom)\n}\n\n// NextID is the id the next [Request] will be given.\n//\n// Read it to build the [Approve] half of a two-message transaction, and pass\n// the recipient and amount to Approve so that a request landing in between\n// fails the transaction instead of being paid by it.\nfunc NextID() int64 { return nextID }\n\n// MaxPerRequest is the current cap on a single payout, in ugnot.\nfunc MaxPerRequest() int64 { return maxPerRequest }\n\n// TotalSent, SentCount, DeniedCount and Pending are the running tallies.\nfunc TotalSent() int64   { return totalSent }\nfunc SentCount() int64   { return sentCount }\nfunc DeniedCount() int64 { return deniedCount }\nfunc Pending() int64     { return pendingN }\n\n// Requests is how many requests have ever been filed.\nfunc Requests() int { return requests.Size() }\n\n// IsApprover reports whether addr may approve or deny.\nfunc IsApprover(addr string) bool { return approvers.Has(addr) }\n\n// ReceivedBy is everything this faucet has ever paid to addr.\nfunc ReceivedBy(addr string) int64 {\n\tif v := paid.Get(addr); v != nil {\n\t\treturn v.(int64)\n\t}\n\treturn 0\n}\n\n// Status is the state of request id: \"pending\", \"sent\", \"denied\", or \"\" when\n// no such request exists.\nfunc Status(id int64) string {\n\tr := find(id)\n\tif r == nil {\n\t\treturn \"\"\n\t}\n\treturn r.Status\n}\n\n// Fund credits the ugnot sent with the call to the float. Coins sent straight\n// to [Address] land there too; they just do not emit an event.\nfunc Fund(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\t// OriginSend is what the SIGNER attached, not what reached this realm. A\n\t// realm the user called keeps those coins and could call Fund any number of\n\t// times, booking each as a donation, so only a user call may read it.\n\tprev := cur.Previous()\n\tif !prev.IsUserCall() {\n\t\tpanic(\"faucet: Fund must be called directly by an account, with -send\")\n\t}\n\tfrom := prev.Address()\n\tamount := unsafe.OriginSend().AmountOf(Denom)\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: send some \" + Denom + \" with the call\")\n\t}\n\tchain.Emit(\"Fund\", \"from\", from.String(), \"amount\", strconv.FormatInt(amount, 10))\n}\n\n// Request files an ask for amount ugnot to be paid to `to`, and returns its\n// id. Anyone may file, for anyone, which is the point: the account that needs\n// the coins is the one that cannot pay to ask for them.\n//\n// Filing costs the filer gas and nothing else, and moves no money.\nfunc Request(cur realm, to string, amount int64, reason string) int64 {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tby := cur.Previous().Address()\n\tdst := address(to)\n\tif !dst.IsValid() {\n\t\tpanic(\"faucet: \" + to + \" is not a valid address\")\n\t}\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: amount must be a positive number of \" + Denom)\n\t}\n\tif amount \u003e maxPerRequest {\n\t\tpanic(\"faucet: \" + strconv.FormatInt(amount, 10) + Denom +\n\t\t\t\" is over the per-request cap of \" + strconv.FormatInt(maxPerRequest, 10) + Denom)\n\t}\n\treason = strings.TrimSpace(reason)\n\tif reason == \"\" {\n\t\tpanic(\"faucet: say what it is for\")\n\t}\n\tif len(reason) \u003e MaxReasonLen {\n\t\tpanic(\"faucet: reason is longer than \" + strconv.Itoa(MaxReasonLen) + \" bytes\")\n\t}\n\n\tid := nextID\n\tnextID++\n\trequests.Set(key(id), \u0026request{\n\t\tID:     id,\n\t\tTo:     dst,\n\t\tAmount: amount,\n\t\tReason: reason,\n\t\tBy:     by,\n\t\tAsked:  runtime.ChainHeight(),\n\t\tStatus: StatusPending,\n\t})\n\tpendingN++\n\n\tchain.Emit(\"Request\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"to\", dst.String(),\n\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t\t\"by\", by.String(),\n\t)\n\treturn id\n}\n\n// Approve pays request id out of the float. Approvers only.\n//\n// wantTo and wantAmount are not redundant: they are what makes it safe to put\n// Approve in the same transaction as the Request it settles. The id has to be\n// guessed from [NextID] before either message is signed, and this call refuses\n// when the request sitting at that id is not the one the caller described.\nfunc Approve(cur realm, id int64, wantTo string, wantAmount int64) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tjudge := cur.Previous().Address()\n\tmustApprove(judge)\n\n\tr := find(id)\n\tif r == nil {\n\t\tpanic(\"faucet: no request \" + strconv.FormatInt(id, 10))\n\t}\n\tif r.Status != StatusPending {\n\t\tpanic(\"faucet: request \" + strconv.FormatInt(id, 10) + \" is already \" + r.Status)\n\t}\n\tif r.To.String() != wantTo || r.Amount != wantAmount {\n\t\tpanic(\"faucet: request \" + strconv.FormatInt(id, 10) + \" pays \" +\n\t\t\tstrconv.FormatInt(r.Amount, 10) + Denom + \" to \" + r.To.String() +\n\t\t\t\", not \" + strconv.FormatInt(wantAmount, 10) + Denom + \" to \" + wantTo +\n\t\t\t\"; the id moved under you, nothing was paid\")\n\t}\n\tif bal := Balance(); bal \u003c r.Amount {\n\t\tpanic(\"faucet: float is \" + strconv.FormatInt(bal, 10) + Denom +\n\t\t\t\", request needs \" + strconv.FormatInt(r.Amount, 10) + Denom)\n\t}\n\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(\n\t\tcur.Address(), r.To, chain.NewCoins(chain.NewCoin(Denom, r.Amount)))\n\n\tr.Status = StatusSent\n\tr.Judge = judge\n\tr.Decided = runtime.ChainHeight()\n\tpaid.Set(r.To.String(), ReceivedBy(r.To.String())+r.Amount)\n\ttotalSent += r.Amount\n\tsentCount++\n\tpendingN--\n\n\tchain.Emit(\"Approve\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"to\", r.To.String(),\n\t\t\"amount\", strconv.FormatInt(r.Amount, 10),\n\t\t\"by\", judge.String(),\n\t)\n}\n\n// Deny closes a request unpaid, with a reason that goes on the page. The\n// reason is the whole value of denying in public rather than ignoring it.\nfunc Deny(cur realm, id int64, why string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tjudge := cur.Previous().Address()\n\tmustApprove(judge)\n\n\tr := find(id)\n\tif r == nil {\n\t\tpanic(\"faucet: no request \" + strconv.FormatInt(id, 10))\n\t}\n\tif r.Status != StatusPending {\n\t\tpanic(\"faucet: request \" + strconv.FormatInt(id, 10) + \" is already \" + r.Status)\n\t}\n\twhy = strings.TrimSpace(why)\n\tif why == \"\" {\n\t\tpanic(\"faucet: say why\")\n\t}\n\tif len(why) \u003e MaxReasonLen {\n\t\tpanic(\"faucet: reason is longer than \" + strconv.Itoa(MaxReasonLen) + \" bytes\")\n\t}\n\n\tr.Status = StatusDenied\n\tr.Judge = judge\n\tr.Decided = runtime.ChainHeight()\n\tr.Note = why\n\tdeniedCount++\n\tpendingN--\n\n\tchain.Emit(\"Deny\", \"id\", strconv.FormatInt(id, 10), \"by\", judge.String())\n}\n\n// AddApprover lets addr approve and deny. Owner only.\nfunc AddApprover(cur realm, addr string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\ta := address(addr)\n\tif !a.IsValid() {\n\t\tpanic(\"faucet: \" + addr + \" is not a valid address\")\n\t}\n\tapprovers.Set(a.String(), true)\n\tchain.Emit(\"AddApprover\", \"addr\", a.String())\n}\n\n// RemoveApprover revokes addr. Owner only, and the Owner cannot be removed:\n// a faucet with no approver is a faucet with a locked float.\nfunc RemoveApprover(cur realm, addr string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\tif addr == Owner.String() {\n\t\tpanic(\"faucet: the owner is always an approver\")\n\t}\n\t// avl's Remove returns (value, removed), unlike Get which returns one\n\t// value; the comma-ok is required here and forbidden there.\n\tif _, removed := approvers.Remove(addr); !removed {\n\t\tpanic(\"faucet: \" + addr + \" is not an approver\")\n\t}\n\tchain.Emit(\"RemoveApprover\", \"addr\", addr)\n}\n\n// SetMaxPerRequest changes the per-request cap, in ugnot. Owner only.\nfunc SetMaxPerRequest(cur realm, amount int64) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: cap must be positive\")\n\t}\n\tmaxPerRequest = amount\n\tchain.Emit(\"SetMaxPerRequest\", \"amount\", strconv.FormatInt(amount, 10))\n}\n\n// Withdraw returns amount ugnot of the float to the Owner. Owner only.\n//\n// This is what makes funding the faucet reversible, and it is deliberately\n// not payable to an arbitrary address: an approver who wanted to move money\n// somewhere has to file a request for it like everyone else.\nfunc Withdraw(cur realm, amount int64) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: amount must be positive\")\n\t}\n\tif bal := Balance(); amount \u003e bal {\n\t\tpanic(\"faucet: float is \" + strconv.FormatInt(bal, 10) + Denom)\n\t}\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(\n\t\tcur.Address(), Owner, chain.NewCoins(chain.NewCoin(Denom, amount)))\n\tchain.Emit(\"Withdraw\", \"amount\", strconv.FormatInt(amount, 10))\n}\n\nfunc mustOwn(caller address) {\n\tif caller != Owner {\n\t\tpanic(\"faucet: owner only\")\n\t}\n}\n\nfunc mustApprove(caller address) {\n\tif !approvers.Has(caller.String()) {\n\t\tpanic(\"faucet: \" + caller.String() + \" is not an approver\")\n\t}\n}\n\nfunc find(id int64) *request {\n\tv := requests.Get(key(id))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*request)\n}\n\n// key pads an id to idWidth digits so the avl tree iterates in filing order.\nfunc key(id int64) string {\n\ts := strconv.FormatInt(id, 10)\n\tfor len(s) \u003c idWidth {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n"},{"name":"faucet_test.gno","body":"package faucet\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\tzoe  = address(\"g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz\") // a friend with nothing\n\tkim  = address(\"g1jvh5ukk07dvd57fxefcp5aa29xaydxmxs7myyp\") // a second approver\n\tcarl = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // nobody in particular\n)\n\nfunc balanceOf(a address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(a).AmountOf(Denom)\n}\n\n// fund puts ugnot in the float the way a bank send to the realm address does,\n// with no call involved. Approve spends this, so a test that funds more than\n// it pays leaves a balance behind and ExampleRender sees it.\nfunc fund(n int64) {\n\ttesting.IssueCoins(Address(), chain.NewCoins(chain.NewCoin(Denom, n)))\n}\n\nfunc TestFreshFaucetIsEmptyAndOwned(t *testing.T) {\n\treset()\n\tuassert.True(t, Owner.IsValid(), \"the owner is a real address\")\n\tuassert.True(t, Address().IsValid(), \"the float address\")\n\tuassert.True(t, zoe.IsValid())\n\tuassert.True(t, kim.IsValid())\n\tuassert.True(t, carl.IsValid())\n\n\tuassert.Equal(t, 0, Requests(), \"nothing is seeded\")\n\tuassert.Equal(t, int64(1), NextID())\n\tuassert.Equal(t, int64(0), TotalSent())\n\tuassert.Equal(t, int64(DefaultMaxPerRequest), MaxPerRequest())\n\tuassert.True(t, IsApprover(Owner.String()), \"the owner approves by default\")\n\tuassert.False(t, IsApprover(carl.String()))\n\tuassert.Equal(t, \"\", Status(1), \"no such request\")\n}\n\n// The whole point, end to end: carl asks on zoe's behalf, the owner releases\n// it, and zoe (who could never have paid the gas to ask) has coins.\nfunc TestRequestForAFriendThenApprove(cur realm, t *testing.T) {\n\treset()\n\turequire.Equal(t, int64(0), Balance(), \"start from an empty float\")\n\tfund(300_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 100_000_000, \"no gas, needs to try the chain\")\n\tuassert.Equal(t, int64(1), id)\n\tuassert.Equal(t, StatusPending, Status(id))\n\tuassert.Equal(t, int64(1), Pending())\n\tuassert.Equal(t, int64(0), balanceOf(zoe), \"a request moves nothing\")\n\tuassert.Equal(t, int64(2), NextID(), \"and the next id is now readable\")\n\n\t// The filer is not an approver just because they filed.\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tuassert.AbortsContains(t, cur, \"is not an approver\", func() {\n\t\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\n\tuassert.Equal(t, int64(100_000_000), balanceOf(zoe), \"the coins landed\")\n\tuassert.Equal(t, int64(200_000_000), Balance(), \"out of the float, not the approver\")\n\tuassert.Equal(t, StatusSent, Status(id))\n\tuassert.Equal(t, int64(100_000_000), TotalSent())\n\tuassert.Equal(t, int64(1), SentCount())\n\tuassert.Equal(t, int64(0), Pending())\n\tuassert.Equal(t, int64(100_000_000), ReceivedBy(zoe.String()))\n\n\t// A decision happens once.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"already sent\", func() {\n\t\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\t})\n\n\t// Put the float back so ExampleRender starts from zero.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n\tuassert.Equal(t, int64(0), Balance())\n}\n\n// The guard that makes it safe to sign Request and Approve in the same\n// transaction before either has run. The approval names an id it had to guess\n// from NextID; if a different request took that id, the amounts and the\n// recipient no longer agree and nothing is paid.\nfunc TestApproveRefusesWhenTheIDMovedUnderYou(cur realm, t *testing.T) {\n\treset()\n\tfund(500_000_000)\n\n\t// What the caller read: the next id will be 1.\n\turequire.Equal(t, int64(1), NextID())\n\n\t// What actually landed at id 1: somebody else's ask, first.\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tRequest(cross(cur), kim.String(), 50_000_000, \"me first\")\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tRequest(cross(cur), zoe.String(), 100_000_000, \"for zoe\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"the id moved under you, nothing was paid\", func() {\n\t\tApprove(cross(cur), 1, zoe.String(), 100_000_000)\n\t})\n\tuassert.Equal(t, int64(0), balanceOf(zoe), \"nobody was paid\")\n\tuassert.Equal(t, StatusPending, Status(1), \"and nothing was decided\")\n\n\t// The same guard catches a wrong amount at the right id.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"the id moved under you, nothing was paid\", func() {\n\t\tApprove(cross(cur), 2, zoe.String(), 999_000_000)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tApprove(cross(cur), 2, zoe.String(), 100_000_000)\n\tuassert.Equal(t, int64(100_000_000), balanceOf(zoe))\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tDeny(cross(cur), 1, \"already funded elsewhere\")\n\tuassert.Equal(t, StatusDenied, Status(1))\n\tuassert.Equal(t, int64(1), DeniedCount())\n\tuassert.Equal(t, int64(0), Pending())\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\nfunc TestRequestRefusesBadInput(cur realm, t *testing.T) {\n\treset()\n\ttests := []struct {\n\t\tname   string\n\t\tto     string\n\t\tamount int64\n\t\treason string\n\t\twant   string\n\t}{\n\t\t{\"not an address\", \"nope\", 1_000_000, \"hi\", \"is not a valid address\"},\n\t\t{\"zero\", zoe.String(), 0, \"hi\", \"must be a positive number\"},\n\t\t{\"negative\", zoe.String(), -1, \"hi\", \"must be a positive number\"},\n\t\t{\"over the cap\", zoe.String(), DefaultMaxPerRequest + 1, \"hi\", \"is over the per-request cap\"},\n\t\t{\"no reason\", zoe.String(), 1_000_000, \"   \", \"say what it is for\"},\n\t}\n\tfor _, tt := range tests {\n\t\ttesting.SetRealm(testing.NewUserRealm(carl))\n\t\tuassert.AbortsContains(t, cur, tt.want, func() {\n\t\t\tRequest(cross(cur), tt.to, tt.amount, tt.reason)\n\t\t}, tt.name)\n\t}\n\tuassert.Equal(t, 0, Requests(), \"none of them were filed\")\n\tuassert.Equal(t, int64(1), NextID(), \"and the id did not move\")\n}\n\nfunc TestApproveRefusesWhatTheFloatCannotCover(cur realm, t *testing.T) {\n\treset()\n\tfund(10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 100_000_000, \"more than is there\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"float is 10000000ugnot\", func() {\n\t\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\t})\n\tuassert.Equal(t, StatusPending, Status(id), \"still open, the money simply is not there\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\nfunc TestOnlyTheOwnerChangesWhoApproves(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tAddApprover(cross(cur), carl.String())\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tAddApprover(cross(cur), kim.String())\n\tuassert.True(t, IsApprover(kim.String()))\n\n\t// A second approver can decide, but cannot widen the roster.\n\tfund(200_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 50_000_000, \"kim vouches\")\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tApprove(cross(cur), id, zoe.String(), 50_000_000)\n\tuassert.Equal(t, StatusSent, Status(id))\n\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tAddApprover(cross(cur), carl.String())\n\t})\n\n\t// The owner is the one approver that cannot be removed: a faucet with no\n\t// approver is a faucet with a locked float.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"the owner is always an approver\", func() {\n\t\tRemoveApprover(cross(cur), Owner.String())\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tRemoveApprover(cross(cur), kim.String())\n\tuassert.False(t, IsApprover(kim.String()))\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\nfunc TestFundAndWithdrawAreOwnerReversible(cur realm, t *testing.T) {\n\treset()\n\tfund(400_000_000)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(Denom, 400_000_000)))\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tFund(cross(cur))\n\tuassert.Equal(t, int64(400_000_000), Balance())\n\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tWithdraw(cross(cur), 1)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"float is 400000000ugnot\", func() {\n\t\tWithdraw(cross(cur), 400_000_001)\n\t})\n\n\tbefore := balanceOf(Owner)\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), 400_000_000)\n\tuassert.Equal(t, int64(0), Balance())\n\tuassert.Equal(t, before+400_000_000, balanceOf(Owner))\n}\n\nfunc TestSetMaxPerRequest(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tSetMaxPerRequest(cross(cur), 1)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tSetMaxPerRequest(cross(cur), 1_000_000_000)\n\tuassert.Equal(t, int64(1_000_000_000), MaxPerRequest())\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 900_000_000, \"over the old cap, under the new one\")\n\tuassert.Equal(t, StatusPending, Status(id))\n}\n\n// A reason is arbitrary text from an arbitrary account, and this realm's path\n// is permanent, so the escaping has to be right before it ships. Assert the\n// dangerous SEQUENCES are dead on the page, not that some particular escape\n// was chosen.\nfunc TestRenderEscapesTheReason(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 1_000_000,\n\t\t\"[click](https://evil.example) ![b](https://evil.example/p.png) \u003cgno-columns\u003e\")\n\n\tfor _, page := range []string{Render(\"\"), Render(\"req/\" + \"1\")} {\n\t\tuassert.False(t, contains(page, \"](https://evil.example\"), \"no live link\")\n\t\tuassert.False(t, contains(page, \"![b]\"), \"no image beacon\")\n\t\tuassert.False(t, contains(page, \"\u003cgno-columns\u003e\"), \"no gnoweb chrome\")\n\t\tuassert.True(t, contains(page, \"click\"), \"the readable text survives\")\n\t}\n\tuassert.Equal(t, StatusPending, Status(id))\n}\n\nfunc contains(haystack, needle string) bool {\n\tfor i := 0; i+len(needle) \u003c= len(haystack); i++ {\n\t\tif haystack[i:i+len(needle)] == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc TestGnotFormatting(t *testing.T) {\n\ttests := []struct {\n\t\tin   int64\n\t\twant string\n\t}{\n\t\t{0, \"0\"},\n\t\t{1, \"0.000001\"},\n\t\t{1_500_000, \"1.5\"},\n\t\t{100_000_000, \"100\"},\n\t\t{5_000_000_000, \"5000\"},\n\t\t{-2_500_000, \"-2.5\"},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, gnot(tt.in))\n\t}\n}\n\nfunc TestReqPath(t *testing.T) {\n\ttests := []struct {\n\t\tin   string\n\t\tid   int64\n\t\twant bool\n\t}{\n\t\t{\"\", 0, false},\n\t\t{\"req/1\", 1, true},\n\t\t{\"req/42\", 42, true},\n\t\t{\"req/0\", 0, false},\n\t\t{\"req/x\", 0, false},\n\t\t{\"req/\", 0, false},\n\t\t{\"other\", 0, false},\n\t}\n\tfor _, tt := range tests {\n\t\tid, ok := reqPath(tt.in)\n\t\tuassert.Equal(t, tt.want, ok, tt.in)\n\t\tuassert.Equal(t, tt.id, id, tt.in)\n\t}\n}\n\n// A board that renders every request ever filed is a page that grows without\n// bound and a gas cost that grows with it, and this path is permanent. Assert\n// the cap holds and that what it hides is counted rather than lost.\nfunc TestRenderCapsEachTable(cur realm, t *testing.T) {\n\treset()\n\tfund(200_000_000)\n\n\tconst filed = Rows + 5\n\tfor i := 0; i \u003c filed; i++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(carl))\n\t\tRequest(cross(cur), zoe.String(), 1_000_000, \"batch\")\n\t}\n\turequire.Equal(t, int64(filed), Pending())\n\n\tpage := Render(\"\")\n\tuassert.Equal(t, Rows, countRows(page), \"the open table is capped\")\n\tuassert.True(t, contains(page, \"5 more not shown\"), \"and the rest are counted\")\n\n\t// Decide them all: the open table empties and the decided one caps in turn,\n\t// newest first, so the most recent decision is on the page and the oldest\n\t// is the one hidden.\n\tfor id := int64(1); id \u003c= filed; id++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\t\tDeny(cross(cur), id, \"batch\")\n\t}\n\tpage = Render(\"\")\n\tuassert.Equal(t, int64(0), Pending())\n\tuassert.Equal(t, Rows, countRows(page), \"the decided table is capped too\")\n\tuassert.True(t, contains(page, \"5 more not shown\"))\n\tuassert.True(t, contains(page, \":req/\"+strconv.FormatInt(int64(filed), 10)+\")\"), \"newest is shown\")\n\tuassert.False(t, contains(page, \":req/1)\"), \"oldest is the one hidden\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\n// countRows counts request rows on a page: every one links to :req/.\nfunc countRows(page string) int {\n\tn, needle := 0, \"](/r/moul/faucet/v1:req/\"\n\tfor i := 0; i+len(needle) \u003c= len(page); i++ {\n\t\tif page[i:i+len(needle)] == needle {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// Path is a hand-written const and the module line is in gnomod.toml, so\n// nothing but this test stops them diverging. They must not: Address() derives\n// the float from Path, while the banker in Approve spends from cur.Address(),\n// which is derived by the VM. A divergence would make Balance() read a\n// different account from the one the payout leaves, and the realm would refuse\n// payouts it could afford while reporting a float it does not hold.\nfunc TestPathMatchesTheRealmItIsDeployedAs(cur realm, t *testing.T) {\n\tuassert.Equal(t, cur.Address().String(), Address().String(),\n\t\t\"Path disagrees with the module line in gnomod.toml\")\n}\n\n// A realm cannot emit a Fund event for coins it kept: OriginSend is what the\n// signer attached, not what reached the float.\nfunc TestFundRefusesARealmCaller(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(Denom, 1_000_000)))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/someone/relay\"))\n\tuassert.AbortsContains(t, cur, \"called directly by an account\", func() { Fund(cross(cur)) })\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/faucet/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render.gno","body":"package faucet\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Rows is how many requests each table on the board shows. The rest are\n// counted, not rendered: the per-request page is always reachable by id.\nconst Rows = 20\n\n// Render shows the float, the open asks and everything already decided.\n//\n// Two paths: \"\" is the whole board, \"req/\u003cid\u003e\" is one request.\n//\n// Every string on this page that a caller typed goes through sanitize before\n// it is concatenated. A reason is arbitrary text from an arbitrary account and\n// Render output is markdown that gnoweb parses, so an unescaped one can plant\n// a link, an image beacon or gnoweb chrome on a page the realm is signing for.\n// This realm's path is permanent, so that bug could only ever be fixed at a\n// new path.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tif id, ok := reqPath(path); ok {\n\t\treturn renderOne(id)\n\t}\n\treturn renderBoard()\n}\n\nfunc renderBoard() string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# GNOT faucet\\n\\n\")\n\tb.WriteString(intro)\n\tb.WriteString(\"\\n\\n\")\n\n\tb.WriteString(\"| | |\\n| --- | ---: |\\n\")\n\tb.WriteString(\"| Float available | **\" + gnot(Balance()) + \" GNOT** |\\n\")\n\tb.WriteString(\"| Paid out | \" + gnot(totalSent) + \" GNOT over \" +\n\t\tstrconv.FormatInt(sentCount, 10) + \" request(s) |\\n\")\n\tb.WriteString(\"| Open requests | \" + strconv.FormatInt(pendingN, 10) + \" |\\n\")\n\tb.WriteString(\"| Refused | \" + strconv.FormatInt(deniedCount, 10) + \" |\\n\")\n\tb.WriteString(\"| Cap per request | \" + gnot(maxPerRequest) + \" GNOT |\\n\")\n\tb.WriteString(\"| Float address | `\" + Address().String() + \"` |\\n\\n\")\n\n\tb.WriteString(\"## Open\\n\\n\")\n\tb.WriteString(table(true, pendingN))\n\tb.WriteString(\"\\n## Decided\\n\\n\")\n\tb.WriteString(table(false, sentCount+deniedCount))\n\n\tb.WriteString(\"\\n## Approvers\\n\\n\")\n\tapprovers.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tb.WriteString(\"- `\" + k + \"`\\n\")\n\t\treturn false\n\t})\n\n\tb.WriteString(\"\\n\" + howto + \"\\n\")\n\treturn b.String()\n}\n\n// table lists at most Rows requests: the open ones oldest first, because a\n// queue is worked from the front, and the decided ones newest first, because\n// nobody scrolls to the bottom of a ledger.\n//\n// It takes the total from the realm's counters rather than counting rows, so\n// it can STOP iterating once the page is full. A Render that walks every\n// request ever filed is a page that grows without bound and a gas cost that\n// grows with it, and this realm's path is permanent, so that would only ever\n// be fixable at a new path.\nfunc table(open bool, total int64) string {\n\tif total == 0 {\n\t\treturn \"_Nothing here yet._\\n\"\n\t}\n\tvar rows strings.Builder\n\tshown := int64(0)\n\tvisit := func(_ string, v any) bool {\n\t\tr := v.(*request)\n\t\tif (r.Status == StatusPending) != open {\n\t\t\treturn false\n\t\t}\n\t\trows.WriteString(\"| [\" + strconv.FormatInt(r.ID, 10) + \"](\" + Link + \":req/\" +\n\t\t\tstrconv.FormatInt(r.ID, 10) + \") | `\" + r.To.String() + \"` | \" +\n\t\t\tgnot(r.Amount) + \" | \" + sanitize.TableCell(excerpt(r.Reason, 60)) + \" | \" +\n\t\t\tr.Status + \" |\\n\")\n\t\tshown++\n\t\treturn shown \u003e= Rows // a true return stops the walk\n\t}\n\tif open {\n\t\trequests.Iterate(\"\", \"\", visit)\n\t} else {\n\t\trequests.ReverseIterate(\"\", \"\", visit)\n\t}\n\n\tout := \"| # | To | GNOT | Why | State |\\n| ---: | --- | ---: | --- | --- |\\n\" + rows.String()\n\tif rest := total - shown; rest \u003e 0 {\n\t\tout += \"\\n_\" + strconv.FormatInt(rest, 10) + \" more not shown._\\n\"\n\t}\n\treturn out\n}\n\nfunc renderOne(id int64) string {\n\tr := find(id)\n\tif r == nil {\n\t\treturn \"# Request \" + strconv.FormatInt(id, 10) + \"\\n\\n_No such request._\\n\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"# Request \" + strconv.FormatInt(r.ID, 10) + \"\\n\\n\")\n\tb.WriteString(\"| | |\\n| --- | --- |\\n\")\n\tb.WriteString(\"| To | `\" + r.To.String() + \"` |\\n\")\n\tb.WriteString(\"| Amount | \" + gnot(r.Amount) + \" GNOT |\\n\")\n\tb.WriteString(\"| Filed by | `\" + r.By.String() + \"` |\\n\")\n\tb.WriteString(\"| Filed at height | \" + strconv.FormatInt(r.Asked, 10) + \" |\\n\")\n\tb.WriteString(\"| State | \" + r.Status + \" |\\n\")\n\tif r.Status != StatusPending {\n\t\tb.WriteString(\"| Decided by | `\" + r.Judge.String() + \"` |\\n\")\n\t\tb.WriteString(\"| Decided at height | \" + strconv.FormatInt(r.Decided, 10) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n**Why:** \" + sanitize.InlineText(r.Reason) + \"\\n\")\n\tif r.Note != \"\" {\n\t\tb.WriteString(\"\\n**Refused because:** \" + sanitize.InlineText(r.Note) + \"\\n\")\n\t}\n\tb.WriteString(\"\\n[Back to the faucet](\" + Link + \")\\n\")\n\treturn b.String()\n}\n\n// reqPath parses \"req/\u003cid\u003e\".\nfunc reqPath(path string) (int64, bool) {\n\trest, ok := strings.CutPrefix(path, \"req/\")\n\tif !ok {\n\t\treturn 0, false\n\t}\n\tid, err := strconv.ParseInt(rest, 10, 64)\n\tif err != nil || id \u003c= 0 {\n\t\treturn 0, false\n\t}\n\treturn id, true\n}\n\n// excerpt cuts to width RUNES, never bytes: slicing a multi-byte character in\n// half puts invalid UTF-8 on the page, and one emoji in a reason is enough.\n// It cuts before escaping, because escaping inserts backslashes and cutting an\n// already-escaped string can strand a lone one that escapes the chrome after\n// it.\nfunc excerpt(s string, width int) string {\n\tr := []rune(s)\n\tif len(r) \u003c= width+1 {\n\t\treturn s\n\t}\n\treturn string(r[:width]) + \"…\"\n}\n\n// gnot renders ugnot as GNOT with the trailing zeros of the fraction trimmed,\n// so 100000000 reads as 100 and 1500000 as 1.5.\nfunc gnot(ugnot int64) string {\n\tneg := \"\"\n\tif ugnot \u003c 0 {\n\t\tneg, ugnot = \"-\", -ugnot\n\t}\n\twhole := strconv.FormatInt(ugnot/1_000_000, 10)\n\tfrac := strconv.FormatInt(ugnot%1_000_000, 10)\n\tif frac == \"0\" {\n\t\treturn neg + whole\n\t}\n\tfor len(frac) \u003c 6 {\n\t\tfrac = \"0\" + frac\n\t}\n\treturn neg + whole + \".\" + strings.TrimRight(frac, \"0\")\n}\n\nconst (\n\tintro = \"Somebody you trust has no GNOT and cannot use the public faucet. File a\\n\" +\n\t\t\"request on their behalf, an approver releases it, and both halves stay on\\n\" +\n\t\t\"this page with a reason attached. The faucet only ever spends what has been\\n\" +\n\t\t\"sent to its own address.\"\n\n\thowto = \"## How\\n\\n\" +\n\t\t\"`Request(to, amount, reason)` is open to anyone and moves no money.\\n\" +\n\t\t\"`Approve(id, to, amount)` pays it, and only an approver can call it.\\n\\n\" +\n\t\t\"Send both in **one transaction**: a tm2 transaction stops at the first\\n\" +\n\t\t\"message that fails and writes none of their state, so the ask and its\\n\" +\n\t\t\"answer land together or not at all. Read `NextID` to address the approval,\\n\" +\n\t\t\"and pass the recipient and the amount into it as well: if another request\\n\" +\n\t\t\"takes that id first, the mismatch fails the transaction instead of paying\\n\" +\n\t\t\"the wrong account.\"\n)\n"},{"name":"render_example_test.gno","body":"package faucet\n\n// ExampleRender pins the faucet as it ships: no requests, an empty float, one\n// approver. That IS the deployed state, since nothing is seeded here.\n//\n// reset() first: realm globals persist for the whole test binary and examples\n// run after every Test. The float is NOT a realm global and reset() cannot\n// clear it, so every test above withdraws what it funded; a test that leaves\n// coins behind shows up as a diff here, which is the point.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # GNOT faucet\n\t//\n\t// Somebody you trust has no GNOT and cannot use the public faucet. File a\n\t// request on their behalf, an approver releases it, and both halves stay on\n\t// this page with a reason attached. The faucet only ever spends what has been\n\t// sent to its own address.\n\t//\n\t// | | |\n\t// | --- | ---: |\n\t// | Float available | **0 GNOT** |\n\t// | Paid out | 0 GNOT over 0 request(s) |\n\t// | Open requests | 0 |\n\t// | Refused | 0 |\n\t// | Cap per request | 200 GNOT |\n\t// | Float address | `g162rfssecz2jq770f7as3qunm4wvh4pmna0guxv` |\n\t//\n\t// ## Open\n\t//\n\t// _Nothing here yet._\n\t//\n\t// ## Decided\n\t//\n\t// _Nothing here yet._\n\t//\n\t// ## Approvers\n\t//\n\t// - `g1manfred47kzduec920z88wfr64ylksmdcedlf5`\n\t//\n\t// ## How\n\t//\n\t// `Request(to, amount, reason)` is open to anyone and moves no money.\n\t// `Approve(id, to, amount)` pays it, and only an approver can call it.\n\t//\n\t// Send both in **one transaction**: a tm2 transaction stops at the first\n\t// message that fails and writes none of their state, so the ask and its\n\t// answer land together or not at all. Read `NextID` to address the approval,\n\t// and pass the recipient and the amount into it as well: if another request\n\t// takes that id first, the mismatch fails the transaction instead of paying\n\t// the wrong account.\n}\n\n// ExampleRenderUnknownRequest pins the per-request path on the one state it\n// can reach deterministically from a reset faucet. A request page proper needs\n// a crossing call to exist, and an Example func cannot take `cur realm`, so\n// the filled-in version is asserted in TestRenderEscapesTheReason instead.\nfunc ExampleRenderUnknownRequest() {\n\treset()\n\tprint(Render(\"req/7\"))\n\t// Output:\n\t// # Request 7\n\t//\n\t// _No such request._\n}\n"}]},"send":"","max_deposit":"19000000ugnot"}],"fee":{"gas_wanted":"129358800","gas_fee":"388076ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"0V5WHK3jogonCEF8IDJZrTEOMCD2Oar9t/x7A5bEuX5V/FFXoL8M1fSr6VaBcRPa/zyj9MTDhqdzkTQz47DirQ=="}],"memo":""},"metadata":{"timestamp":"1790960390"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"forge","path":"gno.land/r/moul/forge/v0","files":[{"name":"README.md","body":"# forge\n\nAn on-chain software forge, browsable in gnoweb and writable only through signed\ntransactions. The domain model lives in\n[`gno.land/p/moul/forge/v1`](../../../../p/moul/forge/v1); this realm is the\nwiring, the routes and the events.\n\nThe code itself is not here. Git objects stay in git, behind whatever mirror a\nrepo declares. What the chain keeps is the part a forge is trusted for: which\nobject a branch points at, in what order, on whose authority, and what was\nreviewed before it moved.\n\n## Routes\n\n| path | page |\n| --- | --- |\n| `/` | every repo, with counts |\n| `/\u003cns\u003e/\u003cname\u003e` | repo overview: refs, recent log, open changes and issues |\n| `/\u003cns\u003e/\u003cname\u003e/log` | the full reference log, paginated with `?page=N` |\n| `/\u003cns\u003e/\u003cname\u003e/issues` | issues, `?page=N` |\n| `/\u003cns\u003e/\u003cname\u003e/issues/\u003cid\u003e` | one issue and its replies |\n| `/\u003cns\u003e/\u003cname\u003e/changes` | change requests, `?page=N` |\n| `/\u003cns\u003e/\u003cname\u003e/changes/\u003cid\u003e` | one change, its reviews and its replies |\n| `/help` | what the realm is and how to call it |\n\nEvery action link on those pages is a `txlink` into the matching function, so\nthe whole forge is usable from gnoweb without a client.\n\n## Writing\n\n```sh\ngnokey maketx call -pkgpath gno.land/r/moul/forge/v0 \\\n  -func CreateRepo -args \"moul/forge\" -args \"an on-chain forge\" -args \"\" \\\n  -gas-fee 30000ugnot -gas-wanted 3000000 \\\n  -broadcast -chainid \u003cchain\u003e -remote \u003crpc\u003e \u003ckey\u003e\n```\n\n```sh\n# move a branch: the fourth argument is the tip you expect to replace\ngnokey maketx call -pkgpath gno.land/r/moul/forge/v0 \\\n  -func SetRef -args \"moul/forge\" -args \"refs/heads/main\" \\\n  -args \"\u003cexpected-oid\u003e\" -args \"\u003cnew-oid\u003e\" -args \"ship it\" \\\n  -gas-fee 30000ugnot -gas-wanted 3000000 \\\n  -broadcast -chainid \u003cchain\u003e -remote \u003crpc\u003e \u003ckey\u003e\n```\n\nA stale expectation aborts the transaction instead of overwriting the branch. A\nmove with no expectation is `ForceSetRef`, needs `maintainer`, and is recorded\nas a force forever.\n\nArguments that would be slices are comma-separated strings (`SetMirrors`,\n`OpenIssue` labels): a transaction can only carry strings, so a `[]string`\nparameter would not be callable from gnokey.\n\n## Reading\n\nRead paths are free. Browse the routes above, or query:\n\n```sh\ngnokey query vm/qeval -data 'gno.land/r/moul/forge/v0.RefOID(\"moul/forge\",\"refs/heads/main\")' -remote \u003crpc\u003e\ngnokey query vm/qeval -data 'gno.land/r/moul/forge/v0.LogHead(\"moul/forge\")' -remote \u003crpc\u003e\n\n# Which repo publishes a deployed package path, and what it last released.\ngnokey query vm/qeval -data 'gno.land/r/moul/forge/v0.PackageRepo(\"gno.land/r/moul/home\")' -remote \u003crpc\u003e\ngnokey query vm/qeval -data 'gno.land/r/moul/forge/v0.LatestReleaseTag(\"moul/forge\")' -remote \u003crpc\u003e\n```\n\n`LogHead` is the digest of the last log entry, committing to every entry before\nit. Pin it in a release note or a package manifest and the repo's whole history\nbecomes falsifiable by anyone who can read the chain.\n\n## Namespaces\n\nA repo id is `\u003cnamespace\u003e/\u003cname\u003e`. The namespace is either a name the caller\nholds in `r/sys/users` or the caller's own bech32 address, checked on every\n`CreateRepo` and `Fork`:\n\n- `g1.../forge` works for any account with nothing to register and nothing to\n  lose, including a realm, whose address is its namespace. That is what makes a\n  DAO-owned repo work.\n- `moul/forge` requires the `moul` name to resolve to the caller, renames\n  included, since the registry resolves aliases to the same record.\n\nNobody can claim a namespace they do not own, so there is no squatting to\narbitrate and no reservation list to maintain.\n\n## Roles\n\n`reader \u003c writer \u003c maintainer \u003c admin \u003c owner`. Writers move refs, maintainers\nforce and merge, admins manage members and the merge policy, and the last owner\ncannot be demoted. Opening an issue or a change request needs no role at all:\nthe author pays gas and locks the storage deposit for their own bytes, which is\nthe spam gate.\n\nA role can be held by **another realm**, because the realm resolves its caller\nwithout requiring an end user. A repo whose owner is a DAO realm is a repo whose\nmerge button is a governance vote, which is the thing a centralized forge\nstructurally cannot offer.\n\n## Events\n\nEvery mutation emits one: `RepoCreated`, `RepoForked`, `RepoUpdated`,\n`MemberSet`, `RefLog`, `IssueOpened`, `IssueComment`, `IssueClosed`,\n`IssueReopened`, `IssueLabeled`, `ChangeOpened`, `ChangeUpdated`,\n`ChangeReviewed`, `ChangeComment`, `ChangeClosed`, `ChangeMerged`. `RefLog`\ncarries the sequence number and the chain digest, so an indexer can mirror the\nlog without replaying state.\n\n## Costs\n\nA realm write locks 100ugnot per byte, refundable when the data is deleted. A\nlog entry is roughly 200 bytes including the digest, so a push costs about\n0.02 GNOT of deposit plus gas: the reason this design anchors refs instead of\nstoring objects. An issue with a 500-byte body is about 0.05 GNOT.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/forge/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/forge/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/forge/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/forge/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/forge/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/forge/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/forge/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/forge/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/forge/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/forge/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"forge.gno","body":"// Package forge is an on-chain software forge: repos, an append-only reference\n// log, issues, change requests and reviews, browsable through gnoweb and\n// writable only through signed transactions.\n//\n// It is the realm half of gno.land/p/moul/forge/v1, which holds the whole\n// domain model; this file is wiring. Every exported mutation is a crossing\n// function that resolves the caller, forwards to the library, aborts on error\n// (the only way to revert state in gno) and emits an event for indexers.\n//\n// What the chain stores is NOT the code. Git objects stay in git (a mirror, an\n// IPFS CID, a peer) and the realm records what a forge is actually trusted for:\n// which object a ref points at, in what order, on whose authority, under\n// what review policy, and what got merged. See the package README for the\n// design, the threat model and what this deliberately does not do.\n//\n// A caller may be a user or another realm: a repo whose owner is a DAO realm is\n// a repo whose merge button is a governance vote.\npackage forge\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"errors\"\n\t\"strings\"\n\n\tfg \"gno.land/p/moul/forge/v1\"\n\t\"gno.land/r/sys/users\"\n)\n\n// errForeignNamespace is the one rule this realm adds on top of the library:\n// a namespace is yours or it is not.\nvar errForeignNamespace = errors.New(\"forge: namespace is not yours\")\n\nvar f = fg.New()\n\n// caller is the address that crossed into this realm. It is deliberately not\n// restricted to end users: a realm holding a role is the point (see the doc\n// comment above).\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"forge: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n\nfunc height() int64 { return runtime.ChainHeight() }\n\n// repo resolves a repo id or aborts. Read paths use f.Repo directly and return\n// a rendered \"not found\" instead.\nfunc repo(id string) *fg.Repo {\n\tr := f.Repo(id)\n\tif r == nil {\n\t\tpanic(fg.ErrRepoNotFound)\n\t}\n\treturn r\n}\n\n// requireNamespace enforces the ownership rule. Two namespaces exist and they\n// cannot collide, since an address is 40 characters and a name caps at 39:\n//\n//   - an address namespace (\"g1.../forge\") belongs to that account, always, with\n//     nothing to register and nothing to lose;\n//   - a name namespace (\"moul/forge\") belongs to whoever holds that name in\n//     r/sys/users, including through a rename, since the lookup resolves aliases\n//     to the same record.\n//\n// A realm caller passes the same way a user does, which is what makes a\n// DAO-owned repo possible: the DAO's address is its namespace.\nfunc requireNamespace(a address, id string) {\n\tns, _, ok := fg.SplitRepoID(id)\n\tif !ok {\n\t\tpanic(fg.ErrInvalidRepoID)\n\t}\n\tif fg.AddressNamespace(ns) {\n\t\tif ns != a.String() {\n\t\t\tpanic(errForeignNamespace)\n\t\t}\n\t\treturn\n\t}\n\tdata, _ := users.ResolveName(ns)\n\tif data.IsDeleted() || data.Addr() != a {\n\t\tpanic(errForeignNamespace)\n\t}\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// splitList parses the comma-separated lists the transaction API has to use:\n// gnokey can only pass strings, so a []string parameter would not be callable.\nfunc splitList(s string) []string {\n\ts = strings.TrimSpace(s)\n\tif s == \"\" {\n\t\treturn nil\n\t}\n\tparts := strings.Split(s, \",\")\n\tout := make([]string, 0, len(parts))\n\tfor _, p := range parts {\n\t\tp = strings.TrimSpace(p)\n\t\tif p != \"\" {\n\t\t\tout = append(out, p)\n\t\t}\n\t}\n\treturn out\n}\n\n// ---------------------------------------------------------------------------\n// Repos\n// ---------------------------------------------------------------------------\n\n// CreateRepo registers \"\u003cnamespace\u003e/\u003cname\u003e\" with the caller as owner.\n// defaultRef may be empty for refs/heads/main.\n//\n// The namespace must be one the caller owns: an r/sys/users name registered to\n// their address, or their own bech32 address. Nobody squats anybody.\nfunc CreateRepo(cur realm, id, description, defaultRef string) {\n\ta := caller(cur)\n\trequireNamespace(a, id)\n\t_, err := f.CreateRepo(a, height(), id, description, defaultRef)\n\tmust(err)\n\tchain.Emit(\"RepoCreated\", \"repo\", id, \"owner\", a.String())\n}\n\n// Fork registers newID as a fork of srcID, snapshotting the parent's current\n// refs into the fork's log so the lineage records exactly what was forked.\nfunc Fork(cur realm, srcID, newID string) {\n\ta := caller(cur)\n\trequireNamespace(a, newID)\n\t_, err := f.Fork(a, height(), srcID, newID)\n\tmust(err)\n\tchain.Emit(\"RepoForked\", \"repo\", newID, \"parent\", srcID, \"owner\", a.String())\n}\n\n// SetDescription updates the repo description (admin).\nfunc SetDescription(cur realm, repoID, description string) {\n\tmust(repo(repoID).SetDescription(caller(cur), description))\n\tchain.Emit(\"RepoUpdated\", \"repo\", repoID, \"field\", \"description\")\n}\n\n// SetMirrors replaces the fetch locators, comma-separated, first one canonical\n// (maintainer). The chain records them; it never fetches.\nfunc SetMirrors(cur realm, repoID, mirrors string) {\n\tmust(repo(repoID).SetMirrors(caller(cur), splitList(mirrors)))\n\tchain.Emit(\"RepoUpdated\", \"repo\", repoID, \"field\", \"mirrors\")\n}\n\n// SetDefaultRef points the repo at another default branch (maintainer).\nfunc SetDefaultRef(cur realm, repoID, name string) {\n\tmust(repo(repoID).SetDefaultRef(caller(cur), name))\n\tchain.Emit(\"RepoUpdated\", \"repo\", repoID, \"field\", \"default_ref\")\n}\n\n// SetPolicy sets how many writer approvals a change needs, and whether the\n// author's own approval counts (admin).\nfunc SetPolicy(cur realm, repoID string, requiredApprovals int, allowSelfApproval bool) {\n\tmust(repo(repoID).SetPolicy(caller(cur), requiredApprovals, allowSelfApproval))\n\tchain.Emit(\"RepoUpdated\", \"repo\", repoID, \"field\", \"policy\")\n}\n\n// SetMember grants a role: none, reader, writer, maintainer, admin, owner.\nfunc SetMember(cur realm, repoID string, member address, role string) {\n\tparsed, err := fg.ParseRole(role)\n\tmust(err)\n\tmust(repo(repoID).SetMember(caller(cur), member, parsed))\n\tchain.Emit(\"MemberSet\", \"repo\", repoID, \"member\", member.String(), \"role\", role)\n}\n\n// SetArchived freezes or unfreezes a repo (admin). The log stays readable.\nfunc SetArchived(cur realm, repoID string, archived bool) {\n\tmust(repo(repoID).SetArchived(caller(cur), archived))\n\tchain.Emit(\"RepoUpdated\", \"repo\", repoID, \"field\", \"archived\")\n}\n\n// ---------------------------------------------------------------------------\n// Refs: the reference log\n// ---------------------------------------------------------------------------\n\n// SetRef moves a ref by compare-and-swap (writer). expectedOID is the tip the\n// caller last saw, empty to create. A stale expectation aborts instead of\n// overwriting: git's --force-with-lease, with consensus holding the lease.\nfunc SetRef(cur realm, repoID, name, expectedOID, newOID, note string) {\n\ta := caller(cur)\n\te, err := repo(repoID).SetRef(a, height(), name, expectedOID, newOID, note)\n\tmust(err)\n\temitRef(repoID, e)\n}\n\n// ForceSetRef moves a ref with no expectation (maintainer). It is not\n// forbidden, it is recorded as a force, in a log nobody can rewrite.\nfunc ForceSetRef(cur realm, repoID, name, newOID, note string) {\n\ta := caller(cur)\n\te, err := repo(repoID).ForceSetRef(a, height(), name, newOID, note)\n\tmust(err)\n\temitRef(repoID, e)\n}\n\n// DeleteRef removes a ref by compare-and-swap (maintainer). The default branch\n// is not deletable.\nfunc DeleteRef(cur realm, repoID, name, expectedOID, note string) {\n\ta := caller(cur)\n\te, err := repo(repoID).DeleteRef(a, height(), name, expectedOID, note)\n\tmust(err)\n\temitRef(repoID, e)\n}\n\nfunc emitRef(repoID string, e *fg.LogEntry) {\n\tchain.Emit(\"RefLog\",\n\t\t\"repo\", repoID,\n\t\t\"ref\", e.Ref,\n\t\t\"kind\", e.Kind,\n\t\t\"old\", e.OldOID,\n\t\t\"new\", e.NewOID,\n\t\t\"seq\", itoa(e.Seq),\n\t\t\"digest\", e.Digest,\n\t)\n}\n\n// ---------------------------------------------------------------------------\n// Issues\n// ---------------------------------------------------------------------------\n\n// OpenIssue files an issue. Permissionless: the author pays for their bytes.\n// labels is comma-separated. Returns the issue id.\nfunc OpenIssue(cur realm, repoID, title, body, labels string) int64 {\n\ta := caller(cur)\n\ti, err := repo(repoID).OpenIssue(a, height(), title, body, splitList(labels))\n\tmust(err)\n\tchain.Emit(\"IssueOpened\", \"repo\", repoID, \"issue\", itoa(i.ID), \"author\", a.String())\n\treturn i.ID\n}\n\n// CommentIssue appends a reply.\nfunc CommentIssue(cur realm, repoID string, issueID int64, body string) {\n\ta := caller(cur)\n\t_, err := repo(repoID).CommentIssue(a, height(), issueID, body)\n\tmust(err)\n\tchain.Emit(\"IssueComment\", \"repo\", repoID, \"issue\", itoa(issueID), \"author\", a.String())\n}\n\n// CloseIssue closes an issue (author or maintainer).\nfunc CloseIssue(cur realm, repoID string, issueID int64) {\n\tmust(repo(repoID).SetIssueOpen(caller(cur), height(), issueID, false))\n\tchain.Emit(\"IssueClosed\", \"repo\", repoID, \"issue\", itoa(issueID))\n}\n\n// ReopenIssue reopens an issue (author or maintainer).\nfunc ReopenIssue(cur realm, repoID string, issueID int64) {\n\tmust(repo(repoID).SetIssueOpen(caller(cur), height(), issueID, true))\n\tchain.Emit(\"IssueReopened\", \"repo\", repoID, \"issue\", itoa(issueID))\n}\n\n// SetIssueLabels replaces an issue's labels, comma-separated (maintainer).\nfunc SetIssueLabels(cur realm, repoID string, issueID int64, labels string) {\n\tmust(repo(repoID).SetIssueLabels(caller(cur), height(), issueID, splitList(labels)))\n\tchain.Emit(\"IssueLabeled\", \"repo\", repoID, \"issue\", itoa(issueID), \"labels\", labels)\n}\n\n// ---------------------------------------------------------------------------\n// Change requests\n// ---------------------------------------------------------------------------\n\n// OpenChange proposes moving targetRef to include headOID. sourceRepo may be\n// another forge repo id, a mirror locator, or empty for this repo. Returns the\n// change id.\nfunc OpenChange(cur realm, repoID, title, body, sourceRepo, sourceRef, headOID, targetRef string) int64 {\n\ta := caller(cur)\n\tc, err := repo(repoID).OpenChange(a, height(), title, body, sourceRepo, sourceRef, headOID, targetRef)\n\tmust(err)\n\tchain.Emit(\"ChangeOpened\", \"repo\", repoID, \"change\", itoa(c.ID), \"author\", a.String(), \"head\", headOID, \"target\", targetRef)\n\treturn c.ID\n}\n\n// UpdateChangeHead repoints an open change at a new object (author or writer).\n// Every approval of the previous head stops counting, by construction.\nfunc UpdateChangeHead(cur realm, repoID string, changeID int64, headOID string) {\n\tmust(repo(repoID).UpdateChangeHead(caller(cur), height(), changeID, headOID))\n\tchain.Emit(\"ChangeUpdated\", \"repo\", repoID, \"change\", itoa(changeID), \"head\", headOID)\n}\n\n// ReviewChange records a verdict: approve, request-changes, comment: against\n// the change's current head. Anyone may review; a writer's approval counts.\nfunc ReviewChange(cur realm, repoID string, changeID int64, verdict, body string) {\n\ta := caller(cur)\n\tmust(repo(repoID).ReviewChange(a, height(), changeID, verdict, body))\n\tchain.Emit(\"ChangeReviewed\", \"repo\", repoID, \"change\", itoa(changeID), \"reviewer\", a.String(), \"verdict\", verdict)\n}\n\n// CommentChange appends a reply to a change request.\nfunc CommentChange(cur realm, repoID string, changeID int64, body string) {\n\ta := caller(cur)\n\t_, err := repo(repoID).CommentChange(a, height(), changeID, body)\n\tmust(err)\n\tchain.Emit(\"ChangeComment\", \"repo\", repoID, \"change\", itoa(changeID), \"author\", a.String())\n}\n\n// CloseChange withdraws or rejects a change (author or maintainer).\nfunc CloseChange(cur realm, repoID string, changeID int64) {\n\tmust(repo(repoID).CloseChange(caller(cur), height(), changeID))\n\tchain.Emit(\"ChangeClosed\", \"repo\", repoID, \"change\", itoa(changeID))\n}\n\n// MergeChange moves the target ref to mergedOID and records the move as a merge\n// entry naming the change (maintainer). expectedTargetOID is a compare-and-swap\n// on the target: a change approved against a base that has moved is refused,\n// not silently rebased.\nfunc MergeChange(cur realm, repoID string, changeID int64, expectedTargetOID, mergedOID, note string) {\n\ta := caller(cur)\n\te, err := repo(repoID).MergeChange(a, height(), changeID, expectedTargetOID, mergedOID, note)\n\tmust(err)\n\tchain.Emit(\"ChangeMerged\", \"repo\", repoID, \"change\", itoa(changeID), \"merger\", a.String(), \"new\", mergedOID, \"digest\", e.Digest)\n\temitRef(repoID, e)\n}\n\n// ---------------------------------------------------------------------------\n// Packages and releases\n// ---------------------------------------------------------------------------\n\n// PublishPackage records that a repo publishes a deployed package path.\n//\n// The claim is not verified and cannot be: a realm cannot ask the chain who\n// deployed a path. What is guaranteed is that someone with write access to the\n// repo said it, under a namespace r/sys/users governs. A reader weighs it the\n// way they weigh a go.mod.\n//\n// ref, oid and tag may each be empty when unstated.\nfunc PublishPackage(cur realm, repoID, path, ref, oid, tag string) {\n\ta := caller(cur)\n\tp, err := f.PublishPackage(a, height(), repoID, path, ref, oid, tag)\n\tmust(err)\n\tchain.Emit(\"PackagePublished\",\n\t\t\"repo\", repoID,\n\t\t\"path\", p.Path,\n\t\t\"ref\", p.Ref,\n\t\t\"oid\", p.OID,\n\t\t\"tag\", p.Tag,\n\t)\n}\n\n// UnpublishPackage withdraws the claim. The package stays on chain; only the\n// repo's assertion about it goes away.\nfunc UnpublishPackage(cur realm, repoID, path string) {\n\ta := caller(cur)\n\tmust(f.UnpublishPackage(a, repoID, path))\n\tchain.Emit(\"PackageUnpublished\", \"repo\", repoID, \"path\", path)\n}\n\n// CutRelease names a point in a repo's history. A tag cannot be re-cut: see\n// YankRelease for withdrawing one.\nfunc CutRelease(cur realm, repoID, tag, name, notes, oid, ref string, prerelease bool) {\n\ta := caller(cur)\n\trel, err := repo(repoID).CutRelease(a, height(), tag, name, notes, oid, ref, prerelease)\n\tmust(err)\n\tchain.Emit(\"ReleaseCut\",\n\t\t\"repo\", repoID,\n\t\t\"tag\", rel.Tag,\n\t\t\"oid\", rel.OID,\n\t\t\"prerelease\", btoa(rel.Prerelease),\n\t)\n}\n\n// YankRelease marks a release withdrawn. It stays visible: a version that\n// vanished reads as \"never published\" rather than \"do not use this\".\nfunc YankRelease(cur realm, repoID, tag, reason string) {\n\ta := caller(cur)\n\tmust(repo(repoID).YankRelease(a, tag, reason))\n\tchain.Emit(\"ReleaseYanked\", \"repo\", repoID, \"tag\", tag, \"reason\", reason)\n}\n\n// ---------------------------------------------------------------------------\n// Read-only helpers, for other realms and for vm/qeval\n// ---------------------------------------------------------------------------\n\n// PackageRepo is the lookup an explorer makes: given a deployed package path,\n// which repo claims to publish it. Empty when nobody does.\nfunc PackageRepo(pkgPath string) string { return f.PackageRepo(pkgPath) }\n\n// PackageCount is how many package paths the whole forge claims.\nfunc PackageCount() int { return f.PackageCount() }\n\n// LatestReleaseTag is the most recently cut release of a repo that is neither a\n// prerelease nor yanked, or \"\". Most recently CUT, never highest version: tags\n// here are not required to be semver, so there is no order to sort by that\n// would not be wrong for somebody.\nfunc LatestReleaseTag(repoID string) string {\n\tr := f.Repo(repoID)\n\tif r == nil {\n\t\treturn \"\"\n\t}\n\trel := r.LatestRelease()\n\tif rel == nil {\n\t\treturn \"\"\n\t}\n\treturn rel.Tag\n}\n\n// ReleaseCount is how many releases a repo has cut, yanked ones included.\nfunc ReleaseCount(repoID string) int {\n\tr := f.Repo(repoID)\n\tif r == nil {\n\t\treturn 0\n\t}\n\treturn r.ReleaseCount()\n}\n\n// RefOID returns the object a ref points at, or \"\" if there is no such ref.\nfunc RefOID(repoID, name string) string {\n\tr := f.Repo(repoID)\n\tif r == nil {\n\t\treturn \"\"\n\t}\n\tref := r.Ref(name)\n\tif ref == nil {\n\t\treturn \"\"\n\t}\n\treturn ref.OID\n}\n\n// LogHead returns the repo's chain digest: pin it off chain and the whole\n// history of every ref becomes falsifiable.\nfunc LogHead(repoID string) string {\n\tr := f.Repo(repoID)\n\tif r == nil {\n\t\treturn \"\"\n\t}\n\treturn r.LogHead()\n}\n\n// HasRepo reports whether a repo id is registered.\nfunc HasRepo(repoID string) bool { return f.HasRepo(repoID) }\n\n// RepoCount is the number of repos on this forge.\nfunc RepoCount() int { return f.Size() }\n"},{"name":"forge_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\tfg \"gno.land/p/moul/forge/v1\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestLifecycle drives the realm exactly as a user would: one signed call at a\n// time, each from a different address.\nfunc TestLifecycle(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), demoID, \"a demo repo\", \"\")\n\tuassert.True(t, HasRepo(demoID))\n\tuassert.Equal(t, 1, RepoCount())\n\tuassert.Equal(t, \"\", LogHead(demoID), \"a fresh repo has an empty log\")\n\n\t// The creator is the owner, so roles are theirs to hand out.\n\tSetMember(cross(cur), demoID, carol, \"writer\")\n\tSetMember(cross(cur), demoID, bob, \"maintainer\")\n\tSetMirrors(cross(cur), demoID, \"https://github.com/moul/demo.git, ipfs://bafyfakefakefakefakefakefakefakefakefake\")\n\tuassert.Equal(t, 2, len(f.Repo(demoID).Mirrors), \"comma-separated lists are how a tx passes a slice\")\n\n\t// A writer creates the branch, then moves it by compare-and-swap.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tSetRef(cross(cur), demoID, \"refs/heads/main\", \"\", oid(\"a\"), \"initial import\")\n\tuassert.Equal(t, oid(\"a\"), RefOID(demoID, \"refs/heads/main\"))\n\thead := LogHead(demoID)\n\tuassert.NotEqual(t, \"\", head)\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tSetRef(cross(cur), demoID, \"refs/heads/main\", oid(\"a\"), oid(\"b\"), \"second commit\")\n\tuassert.NotEqual(t, head, LogHead(demoID), \"each entry advances the chain digest\")\n\n\t// A stale expectation aborts: this is the lost-push case, caught.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsContains(t, cur, \"stale ref\", func() {\n\t\tSetRef(cross(cur), demoID, \"refs/heads/main\", oid(\"a\"), oid(\"c\"), \"\")\n\t})\n\n\t// A stranger cannot move a ref at all.\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tSetRef(cross(cur), demoID, \"refs/heads/main\", oid(\"b\"), oid(\"c\"), \"\")\n\t})\n\n\t// ...but anyone may file an issue and propose a change.\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tissueID := OpenIssue(cross(cur), demoID, \"the log needs a UI\", \"hard to read over RPC\", \"ux,help wanted\")\n\tuassert.Equal(t, int64(0), issueID)\n\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tchangeID := OpenChange(cross(cur), demoID, \"add a log view\", \"\", \"eve/demo\", \"refs/heads/logview\", oid(\"c\"), \"refs/heads/main\")\n\tuassert.Equal(t, int64(0), changeID)\n\n\t// A maintainer's approval satisfies the default policy; the merge moves the\n\t// ref and lands in the same log as every other move.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tReviewChange(cross(cur), demoID, changeID, \"approve\", \"lgtm\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tMergeChange(cross(cur), demoID, changeID, oid(\"b\"), oid(\"d\"), \"merge change 0\")\n\n\tuassert.Equal(t, oid(\"d\"), RefOID(demoID, \"refs/heads/main\"))\n\tr := f.Repo(demoID)\n\tuassert.Equal(t, 3, r.LogSize())\n\tuassert.Equal(t, fg.KindMerge, r.LogEntryAt(2).Kind)\n\tuassert.Equal(t, bob.String(), r.LogEntryAt(2).Actor.String(), \"the log records who merged, not who proposed\")\n\tok, _ := r.VerifyLog()\n\tuassert.True(t, ok, \"the digest chain verifies end to end\")\n\n\t// Issue triage: the maintainer closes what the reporter opened.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tCloseIssue(cross(cur), demoID, issueID)\n\tuassert.Equal(t, 0, r.OpenIssueCount())\n}\n\n// TestHeightsComeFromTheChain checks the realm stamps entries with the block it\n// ran in. SkipHeights is relative and there is no absolute height getter, so the\n// assertion is on the delta.\nfunc TestHeightsComeFromTheChain(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), heightsID, \"\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetRef(cross(cur), heightsID, \"refs/heads/main\", \"\", oid(\"a\"), \"\")\n\n\ttesting.SkipHeights(7)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetRef(cross(cur), heightsID, \"refs/heads/main\", oid(\"a\"), oid(\"b\"), \"\")\n\n\tr := f.Repo(heightsID)\n\tfirst := r.LogEntryAt(0).Height\n\tsecond := r.LogEntryAt(1).Height\n\tuassert.Equal(t, int64(7), second-first, \"seven blocks passed between the two writes\")\n}\n\n// TestUnknownRepoAborts: every write resolves the repo first, so a typo fails\n// loudly instead of creating something.\nfunc TestUnknownRepoAborts(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"repo not found\", func() {\n\t\tSetRef(cross(cur), ghostID, \"refs/heads/main\", \"\", oid(\"a\"), \"\")\n\t})\n\tuassert.Equal(t, \"\", RefOID(ghostID, \"refs/heads/main\"))\n\tuassert.Equal(t, \"\", LogHead(ghostID))\n\tuassert.False(t, HasRepo(ghostID))\n}\n\n// TestRoleParsing: the role argument is a string on the wire, so a typo must\n// abort rather than silently grant nothing.\nfunc TestRoleParsing(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), rolesID, \"\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"invalid role\", func() {\n\t\tSetMember(cross(cur), rolesID, bob, \"commiter\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetMember(cross(cur), rolesID, bob, \"maintainer\")\n\tuassert.Equal(t, \"maintainer\", f.Repo(rolesID).RoleOf(bob).String())\n}\n\nfunc TestSplitList(t *testing.T) {\n\tcases := []struct {\n\t\tin   string\n\t\twant int\n\t}{\n\t\t{\"\", 0},\n\t\t{\"   \", 0},\n\t\t{\"a\", 1},\n\t\t{\"a,b\", 2},\n\t\t{\" a , b ,, c \", 3},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, len(splitList(tc.in)), tc.in)\n\t}\n}\n\n// TestNamespaceOwnership: a namespace is an r/sys/users name you hold or your\n// own address, and nothing else. No name is registered in a unit test, so the\n// name path is exercised through its rejection.\nfunc TestNamespaceOwnership(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), demoID, \"under alice's own address\", \"\")\n\tuassert.True(t, HasRepo(demoID))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"namespace is not yours\", func() {\n\t\tCreateRepo(cross(cur), bob.String()+\"/squat\", \"\", \"\")\n\t}, \"an address namespace belongs to that address\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"namespace is not yours\", func() {\n\t\tCreateRepo(cross(cur), \"moul/forge\", \"\", \"\")\n\t}, \"an unregistered name belongs to nobody\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"namespace is not yours\", func() {\n\t\tFork(cross(cur), demoID, alice.String()+\"/fork\")\n\t}, \"a fork lands in the forker's namespace, not the parent's\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tFork(cross(cur), demoID, bob.String()+\"/fork\")\n\tuassert.True(t, HasRepo(bob.String()+\"/fork\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"invalid repo id\", func() {\n\t\tCreateRepo(cross(cur), \"nonamespace\", \"\", \"\")\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/forge/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"helpers_test.gno","body":"package forge\n\nimport (\n\t\"strings\"\n\n\tfg \"gno.land/p/moul/forge/v1\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// Deterministic, checksum-valid test addresses.\nvar (\n\talice = testutils.TestAddress(\"alice\") // owner\n\tbob   = testutils.TestAddress(\"bob\")   // maintainer\n\tcarol = testutils.TestAddress(\"carol\") // writer\n\teve   = testutils.TestAddress(\"eve\")   // stranger\n)\n\n// Repo ids used by the crossing tests. The realm only lets an address create\n// under a namespace it owns, and no user name is registered in a unit test, so\n// these are all address namespaces.\nvar (\n\tdemoID    = alice.String() + \"/demo\"\n\theightsID = alice.String() + \"/heights\"\n\trolesID   = alice.String() + \"/roles\"\n\tghostID   = alice.String() + \"/ghost\"\n)\n\nfunc oid(c string) string { return strings.Repeat(c, 40) }\n\n// reset restores realm state to empty. Realm globals persist for the whole test\n// binary and examples run after every Test, so anything that pins Render output\n// must reset and re-seed first.\nfunc reset() { f = fg.New() }\n\n// seedFixture builds one deterministic repo straight through the library: no\n// chain context needed, which is what lets an Example use it. It can use a name\n// namespace because namespace ownership is a realm rule (it needs a chain to\n// resolve a name); the library validates the shape and nothing more.\nfunc seedFixture() {\n\treset()\n\tr, err := f.CreateRepo(alice, 100, \"moul/forge\", \"an on chain software forge\", \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.SetMember(alice, bob, fg.RoleMaintainer); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.SetMember(alice, carol, fg.RoleWriter); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.SetMirrors(alice, []string{\"https://github.com/moul/gno-contracts.git\"}); err != nil {\n\t\tpanic(err)\n\t}\n\tif _, err := r.SetRef(carol, 101, \"refs/heads/main\", \"\", oid(\"a\"), \"initial import\"); err != nil {\n\t\tpanic(err)\n\t}\n\tif _, err := r.SetRef(carol, 102, \"refs/heads/main\", oid(\"a\"), oid(\"b\"), \"add the log\"); err != nil {\n\t\tpanic(err)\n\t}\n\tif _, err := r.OpenIssue(eve, 103, \"force pushes are invisible\", \"A maintainer can rewrite a branch and nothing records it.\", []string{\"bug\"}); err != nil {\n\t\tpanic(err)\n\t}\n\tif _, err := r.CommentIssue(bob, 104, 0, \"that is what the log is for\"); err != nil {\n\t\tpanic(err)\n\t}\n\tc, err := r.OpenChange(carol, 105, \"record every ref move\", \"closes 0\", \"\", \"refs/heads/feat\", oid(\"c\"), \"refs/heads/main\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.ReviewChange(bob, 106, c.ID, fg.VerdictApprove, \"lgtm\"); err != nil {\n\t\tpanic(err)\n\t}\n}\n"},{"name":"pkgrelease_test.gno","body":"package forge\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The path an explorer walks: it arrives holding a deployed package path, knows\n// no repo, and needs the issues and releases that belong to it.\nfunc TestPackageLookupFromAPathAlone(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), demoID, \"a demo repo\", \"\")\n\n\tuassert.Equal(t, \"\", PackageRepo(\"gno.land/r/moul/home\"), \"nobody claims it yet\")\n\tuassert.Equal(t, 0, PackageCount())\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPublishPackage(cross(cur), demoID, \"gno.land/r/moul/home\", \"refs/heads/main\", oid(\"a\"), \"\")\n\n\tuassert.Equal(t, demoID, PackageRepo(\"gno.land/r/moul/home\"))\n\tuassert.Equal(t, 1, PackageCount())\n\n\t// One repo publishes many paths, which is the normal case: gno-contracts\n\t// publishes 193.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPublishPackage(cross(cur), demoID, \"gno.land/p/moul/forge/v1\", \"\", \"\", \"\")\n\tuassert.Equal(t, 2, PackageCount())\n\tuassert.Equal(t, demoID, PackageRepo(\"gno.land/p/moul/forge/v1\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tUnpublishPackage(cross(cur), demoID, \"gno.land/r/moul/home\")\n\tuassert.Equal(t, \"\", PackageRepo(\"gno.land/r/moul/home\"))\n\tuassert.Equal(t, 1, PackageCount())\n}\n\n// Capturing another project's package path in every explorer that reads this\n// index has to be impossible, not merely discouraged.\nfunc TestPublishCannotCaptureAnotherReposPath(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), demoID, \"\", \"\")\n\tPublishPackage(cross(cur), demoID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\n\tsquatID := eve.String() + \"/squat\"\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tCreateRepo(cross(cur), squatID, \"\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tuassert.AbortsContains(t, cur, \"claimed by another repo\", func() {\n\t\tPublishPackage(cross(cur), squatID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\t})\n\tuassert.Equal(t, demoID, PackageRepo(\"gno.land/r/moul/home\"))\n}\n\nfunc TestPublishNeedsWriteAccess(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), demoID, \"\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tPublishPackage(cross(cur), demoID, \"gno.land/r/moul/home\", \"\", \"\", \"\")\n\t})\n}\n\nfunc TestReleaseLifecycle(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), demoID, \"\", \"\")\n\n\tuassert.Equal(t, 0, ReleaseCount(demoID))\n\tuassert.Equal(t, \"\", LatestReleaseTag(demoID))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCutRelease(cross(cur), demoID, \"v1.0.0\", \"First\", \"it works\", oid(\"a\"), \"\", false)\n\tuassert.Equal(t, 1, ReleaseCount(demoID))\n\tuassert.Equal(t, \"v1.0.0\", LatestReleaseTag(demoID))\n\n\t// A prerelease is cut later and is still not the latest.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCutRelease(cross(cur), demoID, \"v2.0.0-rc.1\", \"\", \"\", \"\", \"\", true)\n\tuassert.Equal(t, \"v1.0.0\", LatestReleaseTag(demoID))\n\n\t// A tag never moves.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"release already exists\", func() {\n\t\tCutRelease(cross(cur), demoID, \"v1.0.0\", \"Again\", \"\", oid(\"b\"), \"\", false)\n\t})\n\n\t// Yanking withdraws it without deleting it: a version that vanished reads\n\t// as never published rather than as do-not-use.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCutRelease(cross(cur), demoID, \"v2.0.0\", \"\", \"\", \"\", \"\", false)\n\tuassert.Equal(t, \"v2.0.0\", LatestReleaseTag(demoID))\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tYankRelease(cross(cur), demoID, \"v2.0.0\", \"broken migration\")\n\tuassert.Equal(t, \"v1.0.0\", LatestReleaseTag(demoID))\n\tuassert.Equal(t, 3, ReleaseCount(demoID), \"a yank keeps the release\")\n}\n\nfunc TestReleaseNeedsWriteAccess(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateRepo(cross(cur), demoID, \"\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tCutRelease(cross(cur), demoID, \"v1.0.0\", \"\", \"\", \"\", \"\", false)\n\t})\n}\n\n// A read against a repo that does not exist answers emptily rather than\n// aborting: vm/qeval is how an explorer asks, and a panic there is a 500 the\n// caller cannot tell from a broken node.\nfunc TestReadsOnAnUnknownRepoAreEmpty(t *testing.T) {\n\treset()\n\n\tuassert.Equal(t, \"\", PackageRepo(\"gno.land/r/nobody/nothing\"))\n\tuassert.Equal(t, 0, ReleaseCount(\"nobody/nothing\"))\n\tuassert.Equal(t, \"\", LatestReleaseTag(\"nobody/nothing\"))\n}\n"},{"name":"render.gno","body":"package forge\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n\n\tfg \"gno.land/p/moul/forge/v1\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n)\n\n// pageSize bounds every listing: a Render that walks unbounded state is a\n// Render that eventually stops rendering.\nconst pageSize = 20\n\n// Render routes gnoweb paths:\n//\n//\t/                          the forge: every repo\n//\t/\u003cns\u003e/\u003cname\u003e               repo overview\n//\t/\u003cns\u003e/\u003cname\u003e/log           the full reference log (?page=N)\n//\t/\u003cns\u003e/\u003cname\u003e/issues        issues (?page=N)\n//\t/\u003cns\u003e/\u003cname\u003e/issues/\u003cid\u003e   one issue and its replies\n//\t/\u003cns\u003e/\u003cname\u003e/changes       change requests (?page=N)\n//\t/\u003cns\u003e/\u003cname\u003e/changes/\u003cid\u003e  one change, its reviews and its replies\n//\t/help                      what this realm is and how to call it\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tparts := req.PathParts()\n\tpage := pageOf(req)\n\n\tswitch {\n\tcase len(parts) == 0 || parts[0] == \"\":\n\t\treturn renderHome()\n\tcase len(parts) == 1 \u0026\u0026 parts[0] == \"help\":\n\t\treturn renderHelp()\n\tcase len(parts) \u003c 2:\n\t\treturn notFound(\"no such page\")\n\t}\n\n\tid := parts[0] + \"/\" + parts[1]\n\tr := f.Repo(id)\n\tif r == nil {\n\t\treturn notFound(\"no repo \" + md.InlineCode(id))\n\t}\n\tswitch {\n\tcase len(parts) == 2:\n\t\treturn renderRepo(r)\n\tcase len(parts) == 3 \u0026\u0026 parts[2] == \"log\":\n\t\treturn renderLog(r, page)\n\tcase len(parts) == 3 \u0026\u0026 parts[2] == \"issues\":\n\t\treturn renderIssues(r, page)\n\tcase len(parts) == 3 \u0026\u0026 parts[2] == \"changes\":\n\t\treturn renderChanges(r, page)\n\tcase len(parts) == 4 \u0026\u0026 parts[2] == \"issues\":\n\t\treturn renderIssue(r, parts[3])\n\tcase len(parts) == 4 \u0026\u0026 parts[2] == \"changes\":\n\t\treturn renderChange(r, parts[3])\n\t}\n\treturn notFound(\"no such page\")\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"Forge\"))\n\tb.WriteString(\"\\nAn on-chain software forge. The objects stay in git; the chain keeps the part a forge is trusted for: which object a ref points at, in what order, on whose authority, and what was reviewed before it moved.\\n\")\n\tb.WriteString(\"\\n**Repos:** \" + strconv.Itoa(f.Size()) + \"\\n\")\n\n\tif f.Size() == 0 {\n\t\tb.WriteString(\"\\nNothing here yet. \" + link(\"Create the first repo\", txlink.Call(\"CreateRepo\")) + \"\\n\")\n\t} else {\n\t\tb.WriteString(\"\\n| repo | refs | issues | changes | log |\\n\")\n\t\tb.WriteString(\"| --- | ---: | ---: | ---: | ---: |\\n\")\n\t\tf.IterateRepos(0, pageSize, func(r *fg.Repo) bool {\n\t\t\tb.WriteString(\"| \" + link(r.ID, repoURL(r.ID)) + \" | \" +\n\t\t\t\tstrconv.Itoa(r.RefCount()) + \" | \" +\n\t\t\t\tstrconv.Itoa(r.OpenIssueCount()) + \"/\" + strconv.Itoa(r.IssueCount()) + \" | \" +\n\t\t\t\tstrconv.Itoa(r.OpenChangeCount()) + \"/\" + strconv.Itoa(r.ChangeCount()) + \" | \" +\n\t\t\t\tstrconv.Itoa(r.LogSize()) + \" |\\n\")\n\t\t\treturn false\n\t\t})\n\t}\n\tb.WriteString(\"\\n\" + link(\"Create a repo\", txlink.Call(\"CreateRepo\")) + \" · \" +\n\t\tlink(\"How it works\", base()+\":help\") + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderRepo(r *fg.Repo) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(r.ID))\n\tif r.Description != \"\" {\n\t\tb.WriteString(\"\\n\" + md.EscapeText(r.Description) + \"\\n\")\n\t}\n\tif r.Archived {\n\t\tb.WriteString(\"\\n**Archived.** No further writes are accepted.\\n\")\n\t}\n\n\tfacts := []string{\n\t\t\"**Default ref:** \" + md.InlineCode(r.DefaultRef) + \" → \" + oidCode(refOID(r, r.DefaultRef)),\n\t\t\"**Merge policy:** \" + strconv.Itoa(r.RequiredApprovals) + \" writer approval(s), self-approval \" + onOff(r.AllowSelfApproval),\n\t\t\"**Members:** \" + strconv.Itoa(r.MemberCount()),\n\t\t\"**Log head:** \" + md.InlineCode(shortDigest(r.LogHead())),\n\t}\n\tif r.ParentID != \"\" {\n\t\tfacts = append(facts, \"**Forked from:** \"+link(r.ParentID, repoURL(r.ParentID)))\n\t}\n\tif len(r.Mirrors) \u003e 0 {\n\t\tfacts = append(facts, \"**Fetch from:** \"+md.InlineCode(r.Mirrors[0])+mirrorRest(r.Mirrors))\n\t} else {\n\t\tfacts = append(facts, \"**Fetch from:** no mirror declared: the objects are wherever the maintainers keep them\")\n\t}\n\tb.WriteString(\"\\n\" + md.BulletList(facts))\n\n\tb.WriteString(\"\\n\" + md.H2(\"Refs\"))\n\tif r.RefCount() == 0 {\n\t\tb.WriteString(\"\\nNo ref has ever been recorded.\\n\")\n\t} else {\n\t\tvar refs []string\n\t\tr.IterateRefs(func(ref *fg.Ref) bool {\n\t\t\trefs = append(refs, md.InlineCode(ref.Name)+\" → \"+oidCode(ref.OID)+\" · block \"+strconv.FormatInt(ref.UpdatedAt, 10)+\" · \"+userLink(ref.UpdatedBy))\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\" + md.BulletList(refs))\n\t}\n\n\tb.WriteString(\"\\n\" + md.H2(\"Recent log\"))\n\tb.WriteString(\"\\n\" + logList(r, 0, 5))\n\tb.WriteString(\"\\n\" + link(\"Full log, \"+strconv.Itoa(r.LogSize())+\" entries\", repoURL(r.ID)+\"/log\") + \"\\n\")\n\n\tb.WriteString(\"\\n\" + md.H2(\"Open change requests\"))\n\tb.WriteString(\"\\n\" + changeList(r, 0, 5, true))\n\tb.WriteString(\"\\n\" + link(\"All changes, \"+strconv.Itoa(r.ChangeCount())+\" total\", repoURL(r.ID)+\"/changes\") + \" · \" +\n\t\tlink(\"Propose a change\", txlink.Call(\"OpenChange\", \"repoID\", r.ID)) + \"\\n\")\n\n\tb.WriteString(\"\\n\" + md.H2(\"Open issues\"))\n\tb.WriteString(\"\\n\" + issueList(r, 0, 5, true))\n\tb.WriteString(\"\\n\" + link(\"All issues, \"+strconv.Itoa(r.IssueCount())+\" total\", repoURL(r.ID)+\"/issues\") + \" · \" +\n\t\tlink(\"Open an issue\", txlink.Call(\"OpenIssue\", \"repoID\", r.ID)) + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderLog(r *fg.Repo, page int) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(r.ID + \": reference log\"))\n\tb.WriteString(\"\\nAppend-only and hash-chained: every entry commits to the one before it, so pinning the head digest anywhere off chain pins this whole history.\\n\")\n\tb.WriteString(\"\\n**Head:** \" + md.InlineCode(shortDigest(r.LogHead())) + \" · **Entries:** \" + strconv.Itoa(r.LogSize()) + \"\\n\")\n\tb.WriteString(\"\\n\" + logList(r, page*pageSize, pageSize))\n\tb.WriteString(\"\\n\" + pager(r.LogSize(), page, repoURL(r.ID)+\"/log\"))\n\treturn b.String()\n}\n\nfunc renderIssues(r *fg.Repo, page int) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(r.ID + \": issues\"))\n\tb.WriteString(\"\\n**Open:** \" + strconv.Itoa(r.OpenIssueCount()) + \" / \" + strconv.Itoa(r.IssueCount()) + \"\\n\")\n\tb.WriteString(\"\\n\" + issueList(r, page*pageSize, pageSize, false))\n\tb.WriteString(\"\\n\" + pager(r.IssueCount(), page, repoURL(r.ID)+\"/issues\"))\n\tb.WriteString(\"\\n\" + link(\"Open an issue\", txlink.Call(\"OpenIssue\", \"repoID\", r.ID)) + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderIssue(r *fg.Repo, raw string) string {\n\tid, err := strconv.ParseInt(raw, 10, 64)\n\tif err != nil {\n\t\treturn notFound(\"bad issue id\")\n\t}\n\ti := r.Issue(id)\n\tif i == nil {\n\t\treturn notFound(\"no issue \" + raw)\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"#\" + raw + \" \" + md.EscapeText(i.Title)))\n\tb.WriteString(\"\\n\" + state(i.Open, \"open\", \"closed\") + \" · opened at block \" + strconv.FormatInt(i.CreatedAt, 10) + \" by \" + userLink(i.Author) + \"\\n\")\n\tif len(i.Labels) \u003e 0 {\n\t\tb.WriteString(\"\\n**Labels:** \" + codeList(i.Labels) + \"\\n\")\n\t}\n\tif i.Body != \"\" {\n\t\tb.WriteString(\"\\n\" + md.EscapeText(i.Body) + \"\\n\")\n\t}\n\tb.WriteString(\"\\n\" + md.H2(\"Replies (\"+strconv.Itoa(i.CommentCount())+\")\"))\n\tif i.CommentCount() == 0 {\n\t\tb.WriteString(\"\\nNone yet.\\n\")\n\t} else {\n\t\tvar items []string\n\t\ti.IterateComments(0, pageSize, func(c *fg.Comment) bool {\n\t\t\titems = append(items, userLink(c.Author)+\" at block \"+strconv.FormatInt(c.CreatedAt, 10)+\": \"+md.EscapeText(c.Body))\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\" + md.BulletList(items))\n\t}\n\tb.WriteString(\"\\n\" + link(\"Reply\", txlink.Call(\"CommentIssue\", \"repoID\", r.ID, \"issueID\", raw)) + \" · \" +\n\t\tlink(\"Close\", txlink.Call(\"CloseIssue\", \"repoID\", r.ID, \"issueID\", raw)) + \" · \" +\n\t\tlink(\"Back to issues\", repoURL(r.ID)+\"/issues\") + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderChanges(r *fg.Repo, page int) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(r.ID + \": change requests\"))\n\tb.WriteString(\"\\n**Open:** \" + strconv.Itoa(r.OpenChangeCount()) + \" / \" + strconv.Itoa(r.ChangeCount()) + \"\\n\")\n\tb.WriteString(\"\\n\" + changeList(r, page*pageSize, pageSize, false))\n\tb.WriteString(\"\\n\" + pager(r.ChangeCount(), page, repoURL(r.ID)+\"/changes\"))\n\tb.WriteString(\"\\n\" + link(\"Propose a change\", txlink.Call(\"OpenChange\", \"repoID\", r.ID)) + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderChange(r *fg.Repo, raw string) string {\n\tid, err := strconv.ParseInt(raw, 10, 64)\n\tif err != nil {\n\t\treturn notFound(\"bad change id\")\n\t}\n\tc := r.Change(id)\n\tif c == nil {\n\t\treturn notFound(\"no change \" + raw)\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"!\" + raw + \" \" + md.EscapeText(c.Title)))\n\tb.WriteString(\"\\n**\" + c.State + \"** · opened at block \" + strconv.FormatInt(c.CreatedAt, 10) + \" by \" + userLink(c.Author) + \"\\n\")\n\n\tsrc := \"this repo\"\n\tif c.SourceRepo != \"\" {\n\t\tsrc = md.InlineCode(c.SourceRepo)\n\t}\n\tfacts := []string{\n\t\t\"**Head:** \" + oidCode(c.HeadOID) + \" (from \" + src + refSuffix(c.SourceRef) + \")\",\n\t\t\"**Target:** \" + md.InlineCode(c.TargetRef) + \" → \" + oidCode(refOID(r, c.TargetRef)),\n\t\t\"**Approvals:** \" + strconv.Itoa(r.CountApprovals(c)) + \" of \" + strconv.Itoa(r.RequiredApprovals) + \" required\",\n\t\t\"**Blocking:** \" + strconv.Itoa(r.CountBlocking(c)),\n\t}\n\tif c.State == fg.StateMerged {\n\t\tfacts = append(facts, \"**Merged:** \"+oidCode(c.MergedOID)+\" at block \"+strconv.FormatInt(c.MergedAt, 10)+\" by \"+userLink(c.MergedBy))\n\t}\n\tb.WriteString(\"\\n\" + md.BulletList(facts))\n\tif c.Body != \"\" {\n\t\tb.WriteString(\"\\n\" + md.EscapeText(c.Body) + \"\\n\")\n\t}\n\n\tb.WriteString(\"\\n\" + md.H2(\"Reviews (\"+strconv.Itoa(c.ReviewCount())+\")\"))\n\tif c.ReviewCount() == 0 {\n\t\tb.WriteString(\"\\nNone yet.\\n\")\n\t} else {\n\t\tvar items []string\n\t\tc.IterateReviews(func(rv *fg.Review) bool {\n\t\t\tline := userLink(rv.Reviewer) + \": **\" + rv.Verdict + \"** on \" + oidCode(rv.OID)\n\t\t\tif c.Stale(rv) {\n\t\t\t\tline += \" (stale: the head moved since)\"\n\t\t\t}\n\t\t\tif rv.Body != \"\" {\n\t\t\t\tline += \": \" + md.EscapeText(rv.Body)\n\t\t\t}\n\t\t\titems = append(items, line)\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\" + md.BulletList(items))\n\t}\n\n\tb.WriteString(\"\\n\" + md.H2(\"Replies (\"+strconv.Itoa(c.CommentCount())+\")\"))\n\tif c.CommentCount() == 0 {\n\t\tb.WriteString(\"\\nNone yet.\\n\")\n\t} else {\n\t\tvar items []string\n\t\tc.IterateComments(0, pageSize, func(cm *fg.Comment) bool {\n\t\t\titems = append(items, userLink(cm.Author)+\" at block \"+strconv.FormatInt(cm.CreatedAt, 10)+\": \"+md.EscapeText(cm.Body))\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\" + md.BulletList(items))\n\t}\n\n\tb.WriteString(\"\\n\" + link(\"Review\", txlink.Call(\"ReviewChange\", \"repoID\", r.ID, \"changeID\", raw, \"verdict\", \"approve\")) + \" · \" +\n\t\tlink(\"Reply\", txlink.Call(\"CommentChange\", \"repoID\", r.ID, \"changeID\", raw)) + \" · \" +\n\t\tlink(\"Merge\", txlink.Call(\"MergeChange\", \"repoID\", r.ID, \"changeID\", raw, \"expectedTargetOID\", refOID(r, c.TargetRef))) + \" · \" +\n\t\tlink(\"Back to changes\", repoURL(r.ID)+\"/changes\") + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderHelp() string {\n\treturn md.H1(\"Forge: how it works\") + `\nA forge is trusted for three things git does not do by itself: saying which\nobject a branch points at, saying who may move it, and recording that a human\nreviewed the move. Those three are what lives here. The objects do not: they\nstay in git, behind whatever mirror the repo declares.\n\n## The reference log\n\nEvery ref move is one entry in an append-only, hash-chained log. An entry names\nthe ref, the object it left, the object it reached, the actor, the block and the\nkind: create, update, force, delete or merge: and commits to the digest of the\nentry before it. Pin the head digest anywhere off chain and the entire history\nbecomes falsifiable.\n\nMoves are compare-and-swap: the caller states the tip it expected, and a stale\nexpectation aborts instead of overwriting. That is git's --force-with-lease,\nexcept the lease is held by consensus rather than by the server you push to. A\nmove that skips the discipline is not forbidden, it is recorded as a force.\n\nThe chain has no objects, so it cannot check that a new tip descends from the\nold one. It does not pretend to. Ordering, attribution and policy are on chain;\nancestry is verified by a client that has the repo.\n\n## Namespaces\n\nA repo id is \"namespace/name\". A namespace is either a name you hold in\nr/sys/users or your own address, so \"g1.../forge\" works with nothing registered\nand \"moul/forge\" needs the name. Nobody can claim a namespace they do not own,\nand a realm passes the same test a user does, by its address.\n\n## Roles\n\nreader \u003c writer \u003c maintainer \u003c admin \u003c owner. Writers move refs, maintainers\nforce and merge, admins manage members and policy. A role can be held by\nanother realm, so a repo owned by a DAO is a repo whose merge button is a vote.\n\n## Reviews\n\nAnyone may open an issue or a change request, and anyone may review one: the\nspam gate is that you pay for your own bytes. Only a writer's approval counts\ntoward the merge policy, and an approval names the object it reviewed: push a\nnew head and it stops counting, with nothing to remember to dismiss.\n\n## Calling it\n\n` + md.CodeBlock(`gnokey maketx call -pkgpath gno.land/r/moul/forge/v0 \\\n  -func SetRef -send \"\" -gas-fee 30000ugnot -gas-wanted 3000000 \\\n  -args \"moul/forge\" -args \"refs/heads/main\" \\\n  -args \"\u003cexpected-oid\u003e\" -args \"\u003cnew-oid\u003e\" -args \"ship it\" \\\n  -broadcast -chainid \u003cchain\u003e -remote \u003crpc\u003e \u003ckey\u003e`) + `\nRead paths are free: ` + md.InlineCode(\"vm/qeval\") + ` on ` + md.InlineCode(\"RefOID\") + `, ` +\n\t\tmd.InlineCode(\"LogHead\") + ` or ` + md.InlineCode(\"HasRepo\") + `, or just browse the routes above.\n`\n}\n\n// ---------------------------------------------------------------------------\n// Fragments\n// ---------------------------------------------------------------------------\n\nfunc logList(r *fg.Repo, offset, count int) string {\n\tif r.LogSize() == 0 {\n\t\treturn \"No entry yet.\\n\"\n\t}\n\tvar items []string\n\tr.IterateLogReverse(offset, count, func(e *fg.LogEntry) bool {\n\t\tline := \"`#\" + strconv.FormatInt(e.Seq, 10) + \"` **\" + e.Kind + \"** \" + md.InlineCode(e.Ref) + \" \" +\n\t\t\toidCode(e.OldOID) + \" → \" + oidCode(e.NewOID) +\n\t\t\t\" · block \" + strconv.FormatInt(e.Height, 10) + \" · \" + userLink(e.Actor)\n\t\tif e.Kind == fg.KindMerge {\n\t\t\tline += \" · change \" + link(\"!\"+strconv.FormatInt(e.ChangeID, 10), changeURL(r.ID, e.ChangeID))\n\t\t}\n\t\tif e.Note != \"\" {\n\t\t\tline += \" · \" + md.EscapeText(e.Note)\n\t\t}\n\t\titems = append(items, line)\n\t\treturn false\n\t})\n\tif len(items) == 0 {\n\t\treturn \"Nothing on this page.\\n\"\n\t}\n\treturn md.BulletList(items)\n}\n\nfunc issueList(r *fg.Repo, offset, count int, openOnly bool) string {\n\tvar items []string\n\tr.IterateIssues(offset, count, func(i *fg.Issue) bool {\n\t\tif openOnly \u0026\u0026 !i.Open {\n\t\t\treturn false\n\t\t}\n\t\titems = append(items, link(\"#\"+strconv.FormatInt(i.ID, 10)+\" \"+i.Title, issueURL(r.ID, i.ID))+\n\t\t\t\" · \"+state(i.Open, \"open\", \"closed\")+\" · \"+userLink(i.Author)+\n\t\t\t\" · \"+strconv.Itoa(i.CommentCount())+\" replies\")\n\t\treturn false\n\t})\n\tif len(items) == 0 {\n\t\treturn \"None.\\n\"\n\t}\n\treturn md.BulletList(items)\n}\n\nfunc changeList(r *fg.Repo, offset, count int, openOnly bool) string {\n\tvar items []string\n\tr.IterateChanges(offset, count, func(c *fg.Change) bool {\n\t\tif openOnly \u0026\u0026 c.State != fg.StateOpen {\n\t\t\treturn false\n\t\t}\n\t\titems = append(items, link(\"!\"+strconv.FormatInt(c.ID, 10)+\" \"+c.Title, changeURL(r.ID, c.ID))+\n\t\t\t\" · **\"+c.State+\"** · \"+md.InlineCode(c.TargetRef)+\n\t\t\t\" · \"+strconv.Itoa(r.CountApprovals(c))+\"/\"+strconv.Itoa(r.RequiredApprovals)+\" approvals\")\n\t\treturn false\n\t})\n\tif len(items) == 0 {\n\t\treturn \"None.\\n\"\n\t}\n\treturn md.BulletList(items)\n}\n\nfunc pager(total, page int, path string) string {\n\tif total \u003c= pageSize {\n\t\treturn \"\"\n\t}\n\tout := \"Page \" + strconv.Itoa(page+1) + \" of \" + strconv.Itoa((total+pageSize-1)/pageSize) + \" · \"\n\tif page \u003e 0 {\n\t\tout += link(\"previous\", path+\"?page=\"+strconv.Itoa(page)) + \" \"\n\t}\n\tif (page+1)*pageSize \u003c total {\n\t\tout += link(\"next\", path+\"?page=\"+strconv.Itoa(page+2))\n\t}\n\treturn out + \"\\n\"\n}\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nfunc base() string {\n\treturn strings.TrimPrefix(unsafe.CurrentRealm().PkgPath(), runtime.ChainDomain())\n}\n\nfunc repoURL(id string) string { return base() + \":\" + id }\n\nfunc issueURL(id string, n int64) string {\n\treturn repoURL(id) + \"/issues/\" + strconv.FormatInt(n, 10)\n}\n\nfunc changeURL(id string, n int64) string {\n\treturn repoURL(id) + \"/changes/\" + strconv.FormatInt(n, 10)\n}\n\n// link builds a markdown link. Internal targets are realm paths this file\n// built, so only the text needs escaping.\nfunc link(text, url string) string { return \"[\" + md.EscapeText(text) + \"](\" + url + \")\" }\n\nfunc userLink(a address) string {\n\tif l := md.UserLink(a.String()); l != \"\" {\n\t\treturn l\n\t}\n\treturn md.InlineCode(a.String())\n}\n\nfunc notFound(why string) string {\n\treturn md.H1(\"Not found\") + \"\\n\" + why + \".\\n\\n\" + link(\"Back to the forge\", base()) + \"\\n\"\n}\n\nfunc state(ok bool, yes, no string) string {\n\tif ok {\n\t\treturn \"**\" + yes + \"**\"\n\t}\n\treturn \"**\" + no + \"**\"\n}\n\nfunc onOff(b bool) string {\n\tif b {\n\t\treturn \"allowed\"\n\t}\n\treturn \"off\"\n}\n\nfunc refOID(r *fg.Repo, name string) string {\n\tif ref := r.Ref(name); ref != nil {\n\t\treturn ref.OID\n\t}\n\treturn \"\"\n}\n\n// oidCode shows the short object id, code-spanned. An empty id renders as\n// \"(none)\": that is a ref being created or deleted, not a zero object.\nfunc oidCode(oid string) string {\n\tif oid == \"\" {\n\t\treturn \"(none)\"\n\t}\n\tif len(oid) \u003e 12 {\n\t\treturn md.InlineCode(oid[:12])\n\t}\n\treturn md.InlineCode(oid)\n}\n\nfunc shortDigest(d string) string {\n\tif d == \"\" {\n\t\treturn \"(empty log)\"\n\t}\n\tif len(d) \u003e 16 {\n\t\treturn d[:16]\n\t}\n\treturn d\n}\n\nfunc mirrorRest(mirrors []string) string {\n\tif len(mirrors) \u003c 2 {\n\t\treturn \"\"\n\t}\n\treturn \" (+\" + strconv.Itoa(len(mirrors)-1) + \" more)\"\n}\n\nfunc refSuffix(ref string) string {\n\tif ref == \"\" {\n\t\treturn \"\"\n\t}\n\treturn \" \" + md.InlineCode(ref)\n}\n\nfunc codeList(items []string) string {\n\tout := \"\"\n\tfor i, it := range items {\n\t\tif i \u003e 0 {\n\t\t\tout += \" \"\n\t\t}\n\t\tout += md.InlineCode(it)\n\t}\n\treturn out\n}\n\nfunc pageOf(req *realmpath.Request) int {\n\tn, err := strconv.Atoi(req.Query.Get(\"page\"))\n\tif err != nil || n \u003c 1 {\n\t\treturn 0\n\t}\n\treturn n - 1\n}\n\nfunc itoa(n int64) string { return strconv.FormatInt(n, 10) }\n\n// btoa renders a bool for an event value: chain.Emit takes strings only.\nfunc btoa(b bool) string {\n\tif b {\n\t\treturn \"true\"\n\t}\n\treturn \"false\"\n}\n"},{"name":"render_test.gno","body":"package forge\n\n// Every route is pinned by an example: a realm's Render is its whole public\n// surface, and output that varies between identical calls is a consensus bug.\n// Examples run after every Test, so each one re-seeds the state it renders.\n\n// ExampleRender pins the forge home page.\nfunc ExampleRender() {\n\tseedFixture()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Forge\n\t//\n\t// An on-chain software forge. The objects stay in git; the chain keeps the part a forge is trusted for: which object a ref points at, in what order, on whose authority, and what was reviewed before it moved.\n\t//\n\t// **Repos:** 1\n\t//\n\t// | repo | refs | issues | changes | log |\n\t// | --- | ---: | ---: | ---: | ---: |\n\t// | [moul/forge](/r/moul/forge/v0:moul/forge) | 1 | 1/1 | 1/1 | 2 |\n\t//\n\t// [Create a repo](/r/moul/forge/v0$help\u0026func=CreateRepo) · [How it works](/r/moul/forge/v0:help)\n}\n\n// ExampleRenderRepo pins a repo overview.\nfunc ExampleRenderRepo() {\n\tseedFixture()\n\tprint(Render(\"moul/forge\"))\n\t// Output:\n\t// # moul/forge\n\t//\n\t// an on chain software forge\n\t//\n\t// - **Default ref:** `refs/heads/main` → `bbbbbbbbbbbb`\n\t// - **Merge policy:** 1 writer approval(s), self-approval off\n\t// - **Members:** 3\n\t// - **Log head:** `07ca3613cc68e1dc`\n\t// - **Fetch from:** `https://github.com/moul/gno-contracts.git`\n\t//\n\t// ## Refs\n\t//\n\t// - `refs/heads/main` → `bbbbbbbbbbbb` · block 102 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94)\n\t//\n\t// ## Recent log\n\t//\n\t// - `#1` **update** `refs/heads/main` `aaaaaaaaaaaa` → `bbbbbbbbbbbb` · block 102 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · add the log\n\t// - `#0` **create** `refs/heads/main` (none) → `aaaaaaaaaaaa` · block 101 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · initial import\n\t//\n\t// [Full log, 2 entries](/r/moul/forge/v0:moul/forge/log)\n\t//\n\t// ## Open change requests\n\t//\n\t// - [\\!0 record every ref move](/r/moul/forge/v0:moul/forge/changes/0) · **open** · `refs/heads/main` · 1/1 approvals\n\t//\n\t// [All changes, 1 total](/r/moul/forge/v0:moul/forge/changes) · [Propose a change](/r/moul/forge/v0$help\u0026func=OpenChange\u0026repoID=moul%2Fforge)\n\t//\n\t// ## Open issues\n\t//\n\t// - [\\#0 force pushes are invisible](/r/moul/forge/v0:moul/forge/issues/0) · **open** · [g1v4mx2h6lta047h6lta047h6lta047h6lslgc76](/u/g1v4mx2h6lta047h6lta047h6lta047h6lslgc76) · 1 replies\n\t//\n\t// [All issues, 1 total](/r/moul/forge/v0:moul/forge/issues) · [Open an issue](/r/moul/forge/v0$help\u0026func=OpenIssue\u0026repoID=moul%2Fforge)\n}\n\n// ExampleRenderLog pins the reference log.\nfunc ExampleRenderLog() {\n\tseedFixture()\n\tprint(Render(\"moul/forge/log\"))\n\t// Output:\n\t// # moul/forge: reference log\n\t//\n\t// Append-only and hash-chained: every entry commits to the one before it, so pinning the head digest anywhere off chain pins this whole history.\n\t//\n\t// **Head:** `07ca3613cc68e1dc` · **Entries:** 2\n\t//\n\t// - `#1` **update** `refs/heads/main` `aaaaaaaaaaaa` → `bbbbbbbbbbbb` · block 102 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · add the log\n\t// - `#0` **create** `refs/heads/main` (none) → `aaaaaaaaaaaa` · block 101 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · initial import\n}\n\n// ExampleRenderIssue pins one issue.\nfunc ExampleRenderIssue() {\n\tseedFixture()\n\tprint(Render(\"moul/forge/issues/0\"))\n\t// Output:\n\t// # #0 force pushes are invisible\n\t//\n\t// **open** · opened at block 103 by [g1v4mx2h6lta047h6lta047h6lta047h6lslgc76](/u/g1v4mx2h6lta047h6lta047h6lta047h6lslgc76)\n\t//\n\t// **Labels:** `bug`\n\t//\n\t// A maintainer can rewrite a branch and nothing records it\\.\n\t//\n\t// ## Replies (1)\n\t//\n\t// - [g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu](/u/g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu) at block 104: that is what the log is for\n\t//\n\t// [Reply](/r/moul/forge/v0$help\u0026func=CommentIssue\u0026issueID=0\u0026repoID=moul%2Fforge) · [Close](/r/moul/forge/v0$help\u0026func=CloseIssue\u0026issueID=0\u0026repoID=moul%2Fforge) · [Back to issues](/r/moul/forge/v0:moul/forge/issues)\n}\n\n// ExampleRenderChange pins one change request.\nfunc ExampleRenderChange() {\n\tseedFixture()\n\tprint(Render(\"moul/forge/changes/0\"))\n\t// Output:\n\t// # !0 record every ref move\n\t//\n\t// **open** · opened at block 105 by [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94)\n\t//\n\t// - **Head:** `cccccccccccc` (from this repo `refs/heads/feat`)\n\t// - **Target:** `refs/heads/main` → `bbbbbbbbbbbb`\n\t// - **Approvals:** 1 of 1 required\n\t// - **Blocking:** 0\n\t//\n\t// closes 0\n\t//\n\t// ## Reviews (1)\n\t//\n\t// - [g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu](/u/g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu): **approve** on `cccccccccccc`: lgtm\n\t//\n\t// ## Replies (0)\n\t//\n\t// None yet.\n\t//\n\t// [Review](/r/moul/forge/v0$help\u0026func=ReviewChange\u0026changeID=0\u0026repoID=moul%2Fforge\u0026verdict=approve) · [Reply](/r/moul/forge/v0$help\u0026func=CommentChange\u0026changeID=0\u0026repoID=moul%2Fforge) · [Merge](/r/moul/forge/v0$help\u0026func=MergeChange\u0026changeID=0\u0026expectedTargetOID=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\u0026repoID=moul%2Fforge) · [Back to changes](/r/moul/forge/v0:moul/forge/changes)\n}\n\n// ExampleRenderNotFound pins an unknown repo.\nfunc ExampleRenderNotFound() {\n\tseedFixture()\n\tprint(Render(\"moul/nope\"))\n\t// Output:\n\t// # Not found\n\t//\n\t// no repo `moul/nope`.\n\t//\n\t// [Back to the forge](/r/moul/forge/v0)\n}\n"}]},"send":"","max_deposit":"24000000ugnot"}],"fee":{"gas_wanted":"167563200","gas_fee":"502689ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"R5w++0QHWhcui3Q7tvY6Mk0fW6uUsA29MG8lDLUiS05Axy6EGqQFtauyBBCZZA/ZXN5v6aXCshWU8ZIi5d/ZYw=="}],"memo":""},"metadata":{"timestamp":"1790960394"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"JWmAdBTEbod0lpqFBE6xZJj+5lNYmoC4R9pdLaexpaYS5eG9TaKNb8ynPH39va8ZUmt4xkoQtPM0gpzkwRiv+w=="}],"memo":""},"metadata":{"timestamp":"1790960395"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"sapin","path":"gno.land/r/moul/sapin/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/sapin/v0`\n\nASCII Christmas-tree (« sapin ») renderer — `Sapin(size int) string` draws the tree; `Render(path)` serves it through gnoweb. Pure rendering, no state.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/sapin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/sapin/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/sapin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/sapin/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/sapin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/sapin/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/sapin/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/sapin/v0)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/sapin/v0\"\ngno = \"0.9\"\n"},{"name":"render.gno","body":"package sapin\n\nimport \"strconv\"\n\nconst defaultSize int = 3\n\nfunc Render(path string) string {\n\tsize := defaultSize\n\n\tif path != \"\" {\n\t\tvar err error\n\t\tsize, err = strconv.Atoi(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tsapin := Sapin(size)\n\toutput := \"```\\n\" + sapin + \"```\\n\"\n\treturn output\n}\n"},{"name":"render_example_test.gno","body":"package sapin\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// ```\n\t//          *\n\t//         ***\n\t//        *****\n\t//       *******\n\t//        *****\n\t//       *******\n\t//      *********\n\t//     ***********\n\t//    *************\n\t//      *********\n\t//     ***********\n\t//    *************\n\t//   ***************\n\t//  *****************\n\t// *******************\n\t//         |||\n\t//         |||\n\t//         |||\n\t// ```\n}\n"},{"name":"render_test.gno","body":"package sapin\n\nimport (\n\t\"testing\"\n)\n\nfunc TestRender(t *testing.T) {\n\ttt := []struct {\n\t\tpath string\n\t\twant string\n\t}{\n\t\t{\"1\", \"```\" + `\n   *\n  ***\n *****\n*******\n  |||\n` + \"```\\n\"},\n\t\t{\"\", \"```\" + `\n         *\n        ***\n       *****\n      *******\n       *****\n      *******\n     *********\n    ***********\n   *************\n     *********\n    ***********\n   *************\n  ***************\n *****************\n*******************\n        |||\n        |||\n        |||\n` + \"```\\n\"},\n\t}\n\n\tfor _, tc := range tt {\n\t\tname := tc.path\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tgot := Render(tc.path)\n\t\t\twant := tc.want\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"expected \\n%s\\n, got \\n%s\\n.\", want, got)\n\t\t\t}\n\t\t})\n\t}\n}\n"},{"name":"sapin.gno","body":"package sapin\n\nimport \"strings\"\n\nfunc Sapin(size int) string {\n\tif size \u003c 1 {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tfor floor := 0; floor \u003c size; floor++ {\n\t\tfor j := 0; j \u003c floor+4; j++ {\n\t\t\tspaces := size*2 - (floor-1)*2 - j + size - 2\n\t\t\tbodies := j*2 + 1 + floor*4\n\t\t\tb.WriteString(strings.Repeat(\" \", spaces))\n\t\t\tb.WriteString(strings.Repeat(\"*\", bodies))\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\tfor i := 0; i \u003c size; i++ {\n\t\tspaces := (size-1)*3 + 2\n\t\tb.WriteString(strings.Repeat(\" \", spaces))\n\t\tb.WriteString(\"|||\\n\")\n\t}\n\treturn b.String()\n}\n"},{"name":"sapin_test.gno","body":"package sapin\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestSapin(t *testing.T) {\n\ttt := []struct {\n\t\tsize int\n\t\twant string\n\t}{\n\t\t{1, `\n   *\n  ***\n *****\n*******\n  |||\n`},\n\t\t{2, `\n      *\n     ***\n    *****\n   *******\n    *****\n   *******\n  *********\n ***********\n*************\n     |||\n     |||\n`},\n\t\t{3, `\n         *\n        ***\n       *****\n      *******\n       *****\n      *******\n     *********\n    ***********\n   *************\n     *********\n    ***********\n   *************\n  ***************\n *****************\n*******************\n        |||\n        |||\n        |||\n`},\n\t\t{4, `\n            *\n           ***\n          *****\n         *******\n          *****\n         *******\n        *********\n       ***********\n      *************\n        *********\n       ***********\n      *************\n     ***************\n    *****************\n   *******************\n      *************\n     ***************\n    *****************\n   *******************\n  *********************\n ***********************\n*************************\n           |||\n           |||\n           |||\n           |||\n`},\n\t\t{5, `\n               *\n              ***\n             *****\n            *******\n             *****\n            *******\n           *********\n          ***********\n         *************\n           *********\n          ***********\n         *************\n        ***************\n       *****************\n      *******************\n         *************\n        ***************\n       *****************\n      *******************\n     *********************\n    ***********************\n   *************************\n       *****************\n      *******************\n     *********************\n    ***********************\n   *************************\n  ***************************\n *****************************\n*******************************\n              |||\n              |||\n              |||\n              |||\n              |||\n`},\n\t\t// {50, ``},\n\t\t// {51, ``},\n\t}\n\n\tfor _, tc := range tt {\n\t\tname := fmt.Sprintf(\"%d\", tc.size)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tgot := Sapin(tc.size)\n\t\t\twant := tc.want[1:]\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"expected \\n%s\\n, got \\n%s\\n.\", want, got)\n\t\t\t}\n\t\t})\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"26580800","gas_fee":"79742ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"0aWz4mM+n2KeBfuIOgZkH7r2Aju5ECpEfsG3FBnc5LpDeC9JCXZUH7FlLv2Do+jYUMtA5CkZP1/ivz6KMXLnmA=="}],"memo":""},"metadata":{"timestamp":"1790960452"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"gallery","path":"gno.land/r/moul/gallery/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/gallery/v0`\n\nA curated index of art on gno.land, in whichever form the reader can actually\nconsume.\n\n**It stores no art.** Every piece lives in somebody's realm; this one renders\nthe ones it can import and points at the ones it cannot. There is no\npackage-level state anywhere in it, so there is nothing for a redeploy to wipe\nand nothing it pays storage for.\n\n## Rendered, or linked, and it says which\n\n| | |\n|---|---|\n| **rendered here** | the source realm is public, so the gallery imports it and calls it live: `gnoface`, `millipede`, `sapin` |\n| **linked** | the source cannot be imported, so the gallery points at it and says so rather than showing an empty box |\n\n`asciiart` is the honest case: it declares `private = true`, which means no realm\nmay ever import it. That is a constraint of the chain, not an omission here, and\nthe piece page says exactly that.\n\n## The target is a parameter\n\nEvery page answers to `?fmt=txt` as well as the default markdown.\n\nThe text target is **not markdown with the characters deleted**. It is a\ndifferent document built from the same content:\n\n1. A link prints its text inline and collects the URL into a numbered footnote\n   at the end. Never `[text](url)`, which is the single worst thing markdown\n   does to a terminal reader.\n2. A heading is underlined (`=` for H1, `-` for H2), not prefixed with `#`.\n3. A table gets columns padded to their widest cell, under a rule. An unpadded\n   pipe table is the other thing no amount of character-stripping fixes.\n4. Art is emitted **verbatim**: never wrapped, never escaped, never fenced. A\n   consumer that asked for text asked for the picture as it is.\n5. Prose wraps at 72 runes. A word longer than that is left alone, because a\n   realm path is worse broken than wide.\n\n```\n/r/moul/gallery:?fmt=txt                 the index, pipeable\n/r/moul/gallery:piece/millipede?fmt=txt  one piece, art and all\n```\n\n`?fmt=ansi` is deliberately **absent**. Colour cannot reach gnoweb:\n`p/nt/markdown/sanitize` strips control bytes and raw ESC is garbage in HTML, so\na realm offering it would hand every web reader a page of escape bytes. Terminal\ncolour is `p/moul/art`'s `Canvas.ANSI`, for a consumer that asked for it over\nsomething other than gnoweb.\n\n## Where the text renderer lives, and why it is here\n\n`text.gno` holds `doc`, a small plain-text document builder. It is a\n**prototype**, deliberately in this realm rather than in a `p/` package.\n\nPorting one realm is not enough to know what a shared document model should be;\nporting the fifth will be. What it already pins is the list of five rules above,\nwhich is the part that was actually unknown. When a second realm needs it, it\ngraduates to `p/moul/doc` and this file becomes an import.\n\n## Adding a piece\n\n`catalog()` in `catalog.gno`, one struct literal. Set `Draw` to a closure over\nthe source realm's function when the realm is public and vendored; leave it nil\nand the gallery will link the piece and say why it is not rendered.\n\nThe catalog is built per call rather than held in a package-level var: a func\nvalue is not something to persist, and a realm that stores nothing should not be\npaying storage for its own index.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/gallery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gallery/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/gallery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gallery/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/gallery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gallery/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/gallery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gallery/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/gallery/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/gallery/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"catalog.gno","body":"package gallery\n\nimport (\n\t\"gno.land/r/moul/demo/gnoface/v0\"\n\t\"gno.land/r/moul/demo/millipede/v0\"\n\t\"gno.land/r/moul/sapin/v0\"\n)\n\n// piece is one entry in the index.\n//\n// The gallery stores no art. Every piece lives in somebody's realm and this is\n// a pointer to it, which is why there is no package-level state anywhere in\n// this realm and nothing here survives or needs to survive a redeploy.\ntype piece struct {\n\tSlug    string\n\tTitle   string\n\tAuthor  string\n\tOrigin  string // realm path, without the gno.land prefix\n\tLicense string\n\tNote    string\n\n\t// Draw renders the piece live, by importing its source. It is nil when the\n\t// source cannot be imported, which is the honest half of a curated index:\n\t// a private realm or a package this repo has not vendored can be pointed\n\t// at but not shown.\n\tDraw func() string\n}\n\n// Live reports whether this realm can render the piece itself.\nfunc (p piece) Live() bool { return p.Draw != nil }\n\n// catalog is built per call rather than held in a package-level var: a func\n// value is not something to persist, and a realm that stores nothing should\n// not be paying storage for its own index.\nfunc catalog() []piece {\n\treturn []piece{\n\t\t{\n\t\t\tSlug:    \"gnoface\",\n\t\t\tTitle:   \"gnoface\",\n\t\t\tAuthor:  \"moul\",\n\t\t\tOrigin:  \"r/moul/demo/gnoface/v0\",\n\t\t\tLicense: \"see the source realm\",\n\t\t\tNote:    \"A face generated from a seed. Every seed is a different face, and none of them are stored.\",\n\t\t\tDraw:    func() string { return gnoface.Draw(42) },\n\t\t},\n\t\t{\n\t\t\tSlug:    \"millipede\",\n\t\t\tTitle:   \"millipede\",\n\t\t\tAuthor:  \"moul\",\n\t\t\tOrigin:  \"r/moul/demo/millipede/v0\",\n\t\t\tLicense: \"see the source realm\",\n\t\t\tNote:    \"A millipede of any length. The oldest piece here, and still the one that best explains why ASCII is the cheapest picture there is.\",\n\t\t\tDraw:    func() string { return millipede.Draw(8) },\n\t\t},\n\t\t{\n\t\t\tSlug:    \"sapin\",\n\t\t\tTitle:   \"sapin\",\n\t\t\tAuthor:  \"moul\",\n\t\t\tOrigin:  \"r/moul/sapin/v0\",\n\t\t\tLicense: \"see the source realm\",\n\t\t\tNote:    \"A fir tree, sized on request.\",\n\t\t\tDraw:    func() string { return sapin.Sapin(6) },\n\t\t},\n\t\t{\n\t\t\tSlug:    \"settler25\",\n\t\t\tTitle:   \"Settler #25\",\n\t\t\tAuthor:  \"the Settlers\",\n\t\t\tOrigin:  \"r/g17khqpukees4237dtn3astzapmp462vjhsz6st4/settlers/nft\",\n\t\t\tLicense: \"CC0 1.0\",\n\t\t\tNote:    \"moul's, soulbound, minted at block 409242. A 32x32 indexed sprite with 20 colours, which is what made it the test case for p/moul/art: a luminance ramp resolves those 20 to 9, and keying on the palette index keeps all 20.\",\n\t\t},\n\t\t{\n\t\t\tSlug:    \"asciiart\",\n\t\t\tTitle:   \"asciiart\",\n\t\t\tAuthor:  \"moul\",\n\t\t\tOrigin:  \"r/moul/x/daily/asciiart/v1\",\n\t\t\tLicense: \"see the source realm\",\n\t\t\tNote:    \"Patterns from short deterministic algorithms, plus everyone's generations. Declared private = true, so it can be linked but never imported: that is the constraint, not an omission.\",\n\t\t},\n\t\t{\n\t\t\tSlug:    \"pixelcanvas\",\n\t\t\tTitle:   \"pixelcanvas\",\n\t\t\tAuthor:  \"moul\",\n\t\t\tOrigin:  \"r/moul/x/daily/pixelcanvas/v0\",\n\t\t\tLicense: \"see the source realm\",\n\t\t\tNote:    \"A shared grid anyone can paint one pixel of.\",\n\t\t},\n\t}\n}\n\nfunc find(slug string) (piece, bool) {\n\tfor _, p := range catalog() {\n\t\tif p.Slug == slug {\n\t\t\treturn p, true\n\t\t}\n\t}\n\treturn piece{}, false\n}\n"},{"name":"gallery.gno","body":"// Package gallery is a curated index of art on gno.land, in whichever form the\n// reader can actually consume.\n//\n// It stores no art. Every piece lives in somebody else's realm; this one\n// renders the ones it can import and points at the ones it cannot.\n//\n// # The target is a parameter\n//\n// Every page answers to ?fmt=txt as well as the default markdown. The text\n// target is not markdown with the characters deleted: links become numbered\n// footnotes, headings get underlines instead of a leading '#', and art is\n// emitted verbatim rather than fenced. The result is meant to be piped, or read\n// by anything that is not a browser.\n//\n// ?fmt=ansi is deliberately absent. Colour cannot reach gnoweb, so a realm that\n// offered it would be handing every web reader a page of escape bytes. Terminal\n// colour is p/moul/art's Canvas.ANSI, for a consumer that asked for it over\n// something other than gnoweb.\npackage gallery\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/art/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n)\n\n// realmPath is this realm's own path, version included.\n//\n// gnoweb does NOT resolve an unversioned realm path to its latest version: it\n// serves /r/moul/gallery as a DIRECTORY INDEX and drops the :path and ?query\n// entirely. Measured 2026-09-30 on gnoland-1, where /r/moul/outfmt:?fmt=json\n// renders the index page while /r/moul/outfmt/v0:?fmt=json returns the JSON.\n// So every self-link has to carry the version, and stating it once is what\n// keeps the next one from being written without it. Only r/moul/home and\n// r/moul/blog are genuinely unversioned paths.\nconst realmPath = \"/r/moul/gallery/v0\"\n\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\ttext := req.Query.Get(\"fmt\") == \"txt\"\n\n\tif slug := strings.TrimPrefix(req.Path, \"piece/\"); slug != req.Path \u0026\u0026 slug != \"\" {\n\t\treturn renderPiece(slug, text)\n\t}\n\treturn renderIndex(text)\n}\n\n// banner is drawn with p/moul/art rather than typed as a string literal,\n// because a gallery that hand-writes its own ASCII would be a poor advert for\n// the library it exists to show.\nfunc banner() string {\n\tc := art.NewCanvas(22, 2)\n\tc.Write(0, 0, \"moul's gallery\")\n\tc.Write(0, 1, \"art on gno.land\")\n\treturn c.Frame(\"\", art.Round).Text()\n}\n\nfunc renderIndex(text bool) string {\n\tlive, linked := 0, 0\n\tfor _, p := range catalog() {\n\t\tif p.Live() {\n\t\t\tlive++\n\t\t} else {\n\t\t\tlinked++\n\t\t}\n\t}\n\n\tif text {\n\t\tvar d doc\n\t\td.Art(banner())\n\t\td.Para(\"Art on gno.land, rendered rather than described. Nothing here is stored in this realm: every piece lives where its author put it.\")\n\t\trows := [][]string{}\n\t\tfor _, p := range catalog() {\n\t\t\tshown := \"linked\"\n\t\t\tif p.Live() {\n\t\t\t\tshown = \"rendered here\"\n\t\t\t}\n\t\t\trows = append(rows, []string{p.Slug, p.Author, p.Origin, shown})\n\t\t}\n\t\td.Table([]string{\"Piece\", \"Author\", \"Where\", \"Shown\"}, rows)\n\t\td.Para(plural(live, \"piece\") + \" rendered from source, \" + plural(linked, \"piece\") + \" linked.\")\n\t\td.Para(\"Open one at \" + realmPath + \":piece/\u003cslug\u003e, with ?fmt=txt for this form.\")\n\t\treturn d.String()\n\t}\n\n\tout := md.H1(\"moul's gallery\")\n\tout += md.CodeBlock(banner())\n\tout += \"\\n\"\n\tout += \"Art on gno.land, rendered rather than described. Nothing here is stored in this realm: every piece lives where its author put it.\\n\\n\"\n\n\tt := ui.NewTable(\"Piece\", \"Author\", \"Where\", \"Shown\")\n\tfor _, p := range catalog() {\n\t\tshown := \"linked\"\n\t\tif p.Live() {\n\t\t\tshown = \"rendered here\"\n\t\t}\n\t\tt.Row(\n\t\t\tmd.Link(p.Title, realmPath+\":piece/\"+p.Slug),\n\t\t\tui.Inline(p.Author),\n\t\t\tmd.InlineCode(p.Origin),\n\t\t\tshown,\n\t\t)\n\t}\n\tout += t.OrEmpty(\"nothing indexed yet\")\n\tout += \"\\n\" + md.Italic(plural(live, \"piece\")+\" rendered from source, \"+plural(linked, \"piece\")+\" linked.\") + \"\\n\\n\"\n\tout += md.Italic(\"Every page here also answers to `?fmt=txt`.\") + \"\\n\"\n\treturn out\n}\n\nfunc renderPiece(slug string, text bool) string {\n\tp, ok := find(slug)\n\tif !ok {\n\t\tif text {\n\t\t\treturn \"No piece called \" + slug + \".\\n\"\n\t\t}\n\t\treturn md.H1(\"Not found\") + ui.Empty(\"no piece called \"+ui.Inline(slug))\n\t}\n\n\tif text {\n\t\tvar d doc\n\t\td.H1(p.Title)\n\t\tif p.Live() {\n\t\t\td.Art(p.Draw())\n\t\t} else {\n\t\t\td.Para(\"Not rendered here: this realm cannot import the source.\")\n\t\t}\n\t\td.Para(p.Note)\n\t\td.Field(\"Author\", p.Author)\n\t\td.Field(\"License\", p.License)\n\t\td.Field(\"Source\", p.Origin)\n\t\td.Link(\"the source realm\", \"https://gno.land/\"+p.Origin)\n\t\treturn d.String()\n\t}\n\n\tout := md.H1(p.Title)\n\tif p.Live() {\n\t\tout += md.CodeBlock(p.Draw())\n\t} else {\n\t\tout += ui.Empty(\"not rendered here: this realm cannot import the source\") + \"\\n\"\n\t}\n\tout += \"\\n\" + ui.Inline(p.Note) + \"\\n\\n\"\n\n\tt := ui.NewTable(\"Field\", \"Value\")\n\tt.Row(\"Author\", ui.Cell(p.Author))\n\tt.Row(\"License\", ui.Cell(p.License))\n\tt.Row(\"Source\", md.Link(p.Origin, \"/\"+p.Origin))\n\tout += t.String()\n\n\tout += \"\\n\" + md.Link(\"\u003c the gallery\", realmPath) + \"\\n\"\n\treturn out\n}\n\nfunc plural(n int, word string) string {\n\ts := itoa(n) + \" \" + word\n\tif n != 1 {\n\t\ts += \"s\"\n\t}\n\treturn s\n}\n\nfunc itoa(v int) string {\n\tif v == 0 {\n\t\treturn \"0\"\n\t}\n\tvar buf [20]byte\n\ti := len(buf)\n\tfor v \u003e 0 {\n\t\ti--\n\t\tbuf[i] = byte('0' + v%10)\n\t\tv /= 10\n\t}\n\treturn string(buf[i:])\n}\n"},{"name":"gallery_test.gno","body":"package gallery\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRenderIndexMarkdown(t *testing.T) {\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"# moul's gallery\"), \"heading\")\n\tuassert.True(t, strings.Contains(out, \"```\"), \"the banner is fenced in markdown\")\n\tuassert.True(t, strings.Contains(out, \"| Piece |\"), \"a real markdown table\")\n\t// The path is spelled out rather than taken from realmPath: a test that\n\t// reads the same constant the code does would pass with the version\n\t// dropped, which is the exact regression this pins.\n\tfor _, p := range catalog() {\n\t\tuassert.True(t, strings.Contains(out, \"/r/moul/gallery/v0:piece/\"+p.Slug), p.Slug+\" is linked\")\n\t}\n}\n\n// The two targets are different documents, not one with characters deleted.\nfunc TestTextTargetStripsMarkdownAndDefersLinks(t *testing.T) {\n\tout := Render(\"piece/millipede?fmt=txt\")\n\n\tuassert.False(t, strings.Contains(out, \"```\"), \"no code fences\")\n\tuassert.False(t, strings.Contains(out, \"**\"), \"no bold markers\")\n\tuassert.False(t, strings.Contains(out, \"](\"), \"no inline link syntax\")\n\tuassert.False(t, strings.Contains(out, \"\\n#\"), \"no heading hashes\")\n\n\t// A heading is underlined instead.\n\tuassert.True(t, strings.Contains(out, \"millipede\\n=========\"), \"underlined heading\")\n\t// And the URL is a numbered footnote, not inline noise.\n\tuassert.True(t, strings.Contains(out, \"the source realm [1]\"), \"inline marker\")\n\tuassert.True(t, strings.Contains(out, \"\\nLinks:\\n  [1] https://gno.land/r/moul/demo/millipede/v0\"), \"footnote block\")\n}\n\nfunc TestTextTableColumnsLineUp(t *testing.T) {\n\tout := Render(\"?fmt=txt\")\n\tvar header, rule string\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tif strings.HasPrefix(line, \"  Piece \") {\n\t\t\theader = line\n\t\t}\n\t\tif strings.HasPrefix(line, \"  ---\") {\n\t\t\trule = line\n\t\t}\n\t}\n\tuassert.True(t, header != \"\", \"found the header\")\n\tuassert.True(t, rule != \"\", \"found the rule\")\n\n\t// Every column boundary in the rule is a pair of spaces in the header at\n\t// the same rune offset. That is the property an unpadded pipe table does\n\t// not have, and the reason the text target has its own table at all.\n\tuassert.Equal(t, gutters(rule), gutters(header), \"columns start at the same offsets\")\n}\n\n// gutters returns the rune offsets at which a column starts: a non-space\n// preceded by at least two spaces. Measuring where the PADDING starts instead\n// would compare \"Piece\" against eleven dashes and report a difference that is\n// not one.\nfunc gutters(s string) string {\n\tr := []rune(s)\n\tout := \"\"\n\tfor i := 2; i \u003c len(r); i++ {\n\t\tif r[i] != ' ' \u0026\u0026 r[i-1] == ' ' \u0026\u0026 r[i-2] == ' ' {\n\t\t\tout += itoa(i) + \",\"\n\t\t}\n\t}\n\treturn out\n}\n\nfunc TestArtIsNeverEscapedOrWrapped(t *testing.T) {\n\t// The millipede is box-drawing and parentheses. A text target that ran it\n\t// through an escaper or a wrapper would ruin it, and it would still look\n\t// like a picture, which is what makes this worth pinning.\n\tout := Render(\"piece/millipede?fmt=txt\")\n\tuassert.True(t, strings.Contains(out, \"╚═(███)═╝\"), \"art survives verbatim\")\n\tuassert.False(t, strings.Contains(out, \"\\\\(\"), \"no escaping\")\n}\n\nfunc TestUnknownPiece(t *testing.T) {\n\tuassert.True(t, strings.Contains(Render(\"piece/nope\"), \"no piece called nope\"), \"markdown 404\")\n\tuassert.True(t, strings.Contains(Render(\"piece/nope?fmt=txt\"), \"No piece called nope.\"), \"text 404\")\n\t// An empty slug is the index, not a 404.\n\tuassert.True(t, strings.Contains(Render(\"piece/\"), \"# moul's gallery\"), \"empty slug falls back to the index\")\n}\n\nfunc TestLinkedPiecesSayWhyTheyAreNotRendered(t *testing.T) {\n\tp, ok := find(\"asciiart\")\n\tuassert.True(t, ok, \"found\")\n\tuassert.False(t, p.Live(), \"asciiart is private = true, so it cannot be imported\")\n\n\tout := Render(\"piece/asciiart\")\n\tuassert.True(t, strings.Contains(out, \"cannot import the source\"), \"says so rather than showing nothing\")\n}\n\nfunc TestEveryPieceRenders(t *testing.T) {\n\tfor _, p := range catalog() {\n\t\tout := Render(\"piece/\" + p.Slug)\n\t\tuassert.True(t, strings.Contains(out, p.Title), p.Slug+\" markdown\")\n\t\tuassert.True(t, len(Render(\"piece/\"+p.Slug+\"?fmt=txt\")) \u003e 0, p.Slug+\" text\")\n\t}\n}\n\nfunc TestWrapKeepsLongWordsIntact(t *testing.T) {\n\tlong := \"see gno.land/r/g17khqpukees4237dtn3astzapmp462vjhsz6st4/settlers/nft now\"\n\tgot := wrap(long, 20)\n\t// A path is worse broken than wide, so it overflows rather than splitting.\n\tuassert.True(t, strings.Contains(got, \"gno.land/r/g17khqpukees4237dtn3astzapmp462vjhsz6st4/settlers/nft\"), \"unbroken\")\n\tuassert.Equal(t, 3, len(strings.Split(got, \"\\n\")), \"three lines\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/gallery/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package gallery\n\nfunc ExampleRender() {\n\tprintln(Render(\"?fmt=txt\"))\n\t// Output:\n\t// ╭──────────────────────╮\n\t// │moul's gallery        │\n\t// │art on gno.land       │\n\t// ╰──────────────────────╯\n\t//\n\t// Art on gno.land, rendered rather than described. Nothing here is stored\n\t// in this realm: every piece lives where its author put it.\n\t//\n\t//   Piece        Author        Where                                                    Shown\n\t//   -----------  ------------  -------------------------------------------------------  -------------\n\t//   gnoface      moul          r/moul/demo/gnoface/v0                                   rendered here\n\t//   millipede    moul          r/moul/demo/millipede/v0                                 rendered here\n\t//   sapin        moul          r/moul/sapin/v0                                          rendered here\n\t//   settler25    the Settlers  r/g17khqpukees4237dtn3astzapmp462vjhsz6st4/settlers/nft  linked\n\t//   asciiart     moul          r/moul/x/daily/asciiart/v1                               linked\n\t//   pixelcanvas  moul          r/moul/x/daily/pixelcanvas/v0                            linked\n\t//\n\t// 3 pieces rendered from source, 3 pieces linked.\n\t//\n\t// Open one at /r/moul/gallery/v0:piece/\u003cslug\u003e, with ?fmt=txt for this\n\t// form.\n}\n\nfunc ExampleRender_piece() {\n\tprintln(Render(\"piece/millipede?fmt=txt\"))\n\t// Output:\n\t// millipede\n\t// =========\n\t//\n\t//     ╚⊙ ⊙╝\n\t//   ╚═(███)═╝\n\t//  ╚═(███)═╝\n\t// ╚═(███)═╝\n\t//  ╚═(███)═╝\n\t//   ╚═(███)═╝\n\t//    ╚═(███)═╝\n\t//     ╚═(███)═╝\n\t//     ╚═(███)═╝\n\t//\n\t// A millipede of any length. The oldest piece here, and still the one that\n\t// best explains why ASCII is the cheapest picture there is.\n\t//   Author: moul\n\t//   License: see the source realm\n\t//   Source: r/moul/demo/millipede/v0\n\t//   the source realm [1]\n\t//\n\t// Links:\n\t//   [1] https://gno.land/r/moul/demo/millipede/v0\n}\n"},{"name":"text.gno","body":"package gallery\n\nimport \"strings\"\n\n// doc builds the plain-text target: a document that reads well as-is, rather\n// than markdown with the syntax characters deleted.\n//\n// This is a prototype, deliberately small and deliberately here rather than in\n// a p/ package. Porting one realm is not enough to know what the shared\n// document model should be; porting the fifth will be. What it already pins is\n// the set of rules that make text good instead of merely stripped:\n//\n//  1. A link prints its text inline and collects the URL into a numbered\n//     footnote. Never \"[text](url)\", which is the single worst thing markdown\n//     does to a terminal reader.\n//  2. A heading is underlined, not prefixed with '#'.\n//  3. Art is emitted verbatim: never wrapped, never escaped, never fenced.\n//  4. Prose is wrapped at a fixed width; art and fields are not.\ntype doc struct {\n\tb     strings.Builder\n\tlinks []string\n}\n\n// width is where prose wraps. 72 leaves room for a quoting prefix in an email\n// or a diff without re-wrapping.\nconst width = 72\n\nfunc (d *doc) H1(s string) {\n\td.blank()\n\td.b.WriteString(s + \"\\n\" + strings.Repeat(\"=\", runeLen(s)) + \"\\n\")\n}\n\nfunc (d *doc) H2(s string) {\n\td.blank()\n\td.b.WriteString(s + \"\\n\" + strings.Repeat(\"-\", runeLen(s)) + \"\\n\")\n}\n\nfunc (d *doc) Para(s string) {\n\tif s == \"\" {\n\t\treturn\n\t}\n\td.blank()\n\td.b.WriteString(wrap(s, width) + \"\\n\")\n}\n\nfunc (d *doc) Item(s string) {\n\td.b.WriteString(\"  - \" + s + \"\\n\")\n}\n\n// Table writes columns padded to their widest cell, under a rule. An unpadded\n// pipe table is the other thing markdown does to a terminal reader that no\n// amount of character-stripping fixes: the columns stop lining up and the table\n// stops being a table.\n//\n// Cells are laid out by rune count, not byte count, so a box-drawing glyph or\n// an accent does not shift the column.\nfunc (d *doc) Table(headers []string, rows [][]string) {\n\tif len(headers) == 0 {\n\t\treturn\n\t}\n\tw := make([]int, len(headers))\n\tfor i, h := range headers {\n\t\tw[i] = runeLen(h)\n\t}\n\tfor _, r := range rows {\n\t\tfor i, c := range r {\n\t\t\tif i \u003c len(w) \u0026\u0026 runeLen(c) \u003e w[i] {\n\t\t\t\tw[i] = runeLen(c)\n\t\t\t}\n\t\t}\n\t}\n\n\td.blank()\n\td.b.WriteString(\"  \" + joinPadded(headers, w) + \"\\n\")\n\n\trule := make([]string, len(headers))\n\tfor i := range rule {\n\t\trule[i] = strings.Repeat(\"-\", w[i])\n\t}\n\td.b.WriteString(\"  \" + joinPadded(rule, w) + \"\\n\")\n\n\tfor _, r := range rows {\n\t\td.b.WriteString(\"  \" + joinPadded(r, w) + \"\\n\")\n\t}\n}\n\n// joinPadded pads every cell but the last, which would only add trailing space.\nfunc joinPadded(cells []string, w []int) string {\n\tvar b strings.Builder\n\tfor i, c := range cells {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\"  \")\n\t\t}\n\t\tb.WriteString(c)\n\t\tif i \u003c len(cells)-1 \u0026\u0026 i \u003c len(w) {\n\t\t\tb.WriteString(strings.Repeat(\" \", w[i]-runeLen(c)))\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc (d *doc) Field(k, v string) {\n\td.b.WriteString(\"  \" + k + \": \" + v + \"\\n\")\n}\n\n// Art writes a block verbatim. No fence, no indent, no escaping: a consumer\n// that asked for text asked for the picture as it is.\nfunc (d *doc) Art(s string) {\n\td.blank()\n\td.b.WriteString(s + \"\\n\")\n}\n\n// Link prints the text inline and defers the URL to the footnote block.\nfunc (d *doc) Link(text, url string) {\n\td.links = append(d.links, url)\n\td.b.WriteString(\"  \" + text + \" [\" + itoa(len(d.links)) + \"]\\n\")\n}\n\nfunc (d *doc) String() string {\n\tout := d.b.String()\n\tif len(d.links) == 0 {\n\t\treturn out\n\t}\n\tvar b strings.Builder\n\tb.WriteString(out)\n\tb.WriteString(\"\\nLinks:\\n\")\n\tfor i, u := range d.links {\n\t\tb.WriteString(\"  [\" + itoa(i+1) + \"] \" + u + \"\\n\")\n\t}\n\treturn b.String()\n}\n\n// blank writes a separating newline unless the document is empty or already\n// ends in one, so no block has to know what came before it.\nfunc (d *doc) blank() {\n\ts := d.b.String()\n\tif s == \"\" || strings.HasSuffix(s, \"\\n\\n\") {\n\t\treturn\n\t}\n\td.b.WriteString(\"\\n\")\n}\n\n// wrap breaks on spaces at w runes. A word longer than w is left alone rather\n// than cut: a URL or a realm path is worse broken than wide.\nfunc wrap(s string, w int) string {\n\tvar out strings.Builder\n\tline := 0\n\tfor i, word := range strings.Fields(s) {\n\t\tn := runeLen(word)\n\t\tswitch {\n\t\tcase i == 0:\n\t\t\tout.WriteString(word)\n\t\t\tline = n\n\t\tcase line+1+n \u003e w:\n\t\t\tout.WriteString(\"\\n\" + word)\n\t\t\tline = n\n\t\tdefault:\n\t\t\tout.WriteString(\" \" + word)\n\t\t\tline += 1 + n\n\t\t}\n\t}\n\treturn out.String()\n}\n\nfunc runeLen(s string) int {\n\tn := 0\n\tfor range s {\n\t\tn++\n\t}\n\treturn n\n}\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"74506600","gas_fee":"223519ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"V6q8tyOWoXVOhh6K84p0EHssk/8O9ZvUuJ9ijfWjEe9va2l2apl2BBKgu9MgFmxScIKwRzDS7TvXk3+xE4rPQg=="}],"memo":""},"metadata":{"timestamp":"1790960456"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"registry","path":"gno.land/r/moul/gnopm/registry/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/gnopm/registry/v0`\n\nAn open, on-chain map from a deployed gno package path back to the source that\nproduced it: repository, commit, directory.\n\nThe domain model lives in\n[`gno.land/p/moul/gnopm/v0`](../../../../p/moul/gnopm), which is also where the\nreasoning is written down. This realm is the wiring: the routes, the authority\nrule and the events.\n\n## It cannot promise, and does not pretend to\n\nNothing here is verified and nothing here **can** be. A realm cannot clone a\nrepository, so it cannot check that the bytes at the claimed commit are the\nbytes deployed at the claimed path. What it stores is testimony under a\nsignature: *this address says this package came from that source.*\n\nThat is still worth storing, for two reasons.\n\n**It is testimony in the shape a verifier needs.** Path, repository, commit and\ndirectory are precisely the four inputs to \"hash the `addpkg` payload of that\ndirectory and compare it with what the chain hands back\", which\n[gnopm](https://github.com/moul/gnopm) already does against a local tree\n(`gnopm verify -deployed`). The realm does not answer the question; it makes the\nquestion answerable by anything that can clone.\n\n**The chain knows who signed.** A claim from the address that owns the package\npath's namespace comes from the party that controls the path. That is not proof\nthe source matches, it is proof of who is speaking, and it is the strongest\nsignal available without a chain-level feature.\n\n## Open, and tagged\n\nAnyone may claim any path, including one they had nothing to do with. A claim\nfrom an address that does not own the namespace is **not hidden**: it renders\nunder its own heading, below the owner's, and says so.\n\nSuppressing it was the alternative and it is worse. A registry that only accepts\nself-registrations is empty on day one, when almost nothing has been registered\nby its own deployer, and an empty registry teaches nobody anything.\n\nA claimant may always withdraw their own claim, and may never touch anyone\nelse's.\n\n## Routes\n\n| path | page |\n| --- | --- |\n| `/` | every claimed package path, paginated with `?page=N` |\n| `/\u003cpackage path\u003e` | the claims about one package, owner first |\n| `/help` | what this realm is and how to write to it |\n\nA package path contains slashes, so it arrives at `Render` already split; the\nrouting is the rejoin.\n\n## Writing\n\n```sh\ngnokey maketx call -pkgpath gno.land/r/moul/gnopm/registry/v0 \\\n  -func Register \\\n  -args \"gno.land/p/moul/md/v1\" \\\n  -args \"https://github.com/moul/gno-contracts\" \\\n  -args \"\u003c40 or 64 char lowercase hex commit\u003e\" \\\n  -args \"p/moul/md\" \\\n  -args \"refs/tags/v1.0.0\" \\\n  -gas-fee 1000000ugnot -gas-wanted 5000000 \\\n  -broadcast -chainid \u003cchain\u003e -remote \u003crpc\u003e moul\n```\n\n`dir` is empty for a package at the repository root. `ref` is optional and is\nnever the thing verified: a ref moves, a commit does not. It is recorded so a\nreader can tell a claim pinned to a released tag from one pinned to a commit on\nnobody's branch, and so a verifier can report a commit since orphaned by a\nforce-push.\n\nCalling `Register` again for the same path replaces your own claim and nobody\nelse's, which is how a claim moves to a new commit after a redeploy.\n`Withdraw` takes it back.\n\n## Reading, from another realm or an indexer\n\n```go\nregistry.HasClaims(pkgPath)                          // has anyone said anything\nrepo, commit, dir, ok := registry.OwnerClaim(pkgPath) // the namespace holder's claim\nregistry.PackageCount()\nregistry.ClaimCount()\n```\n\n`OwnerClaim` is the only read that filters, and it filters on the one thing the\nchain can prove. Ownership is recomputed on every call rather than stored,\nbecause a name can be transferred.\n\nTwo events carry the same information to an indexer, which is how an explorer\nfollows the registry without polling: `SourceClaimed` (`pkgpath`, `claimant`,\n`repo`, `commit`) and `SourceWithdrawn` (`pkgpath`, `claimant`).\n\n## Why `private = true`\n\nStandard for a new realm here: it can be redeployed at this path by its creator\ninstead of burning a `/v1`. The cost is real and worth stating, because this\nrealm holds data other people wrote: **a redeploy wipes every package-level\nvariable**, so every claim in it goes with it. Claims are cheap to re-make and\neach one is a signed statement its author can reissue, which is what makes the\ntrade acceptable here and would not make it acceptable for a realm holding\nbalances.\n\n## What is deliberately not here\n\n- **No verification**, per the top of this file. The check that actually proves\n  something needs to clone a repository and hash a tree, which is a service, not\n  a realm. gnopm already holds the whole of that logic (`hashPayload` hashes\n  exactly what `addpkg` would upload; `gnomodnorm` handles the fact that the\n  chain **rewrites** `gnomod.toml` on publish, appending an `[addpkg]` table, so\n  a naive byte comparison reports every package as differing forever).\n- **No curation, no voting.** Whose claim to believe is a judgement that wants\n  the deployer identity from chain history, which an explorer has and a realm\n  does not.\n- **No compare-and-swap on update.** `r/moul/forge` takes the expected previous\n  object id when moving a ref, because two maintainers racing on a branch is a\n  real lost-update. Here a claimant only ever overwrites their own claim, so\n  there is nobody to race.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/gnopm/registry/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gnopm/registry/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/gnopm/registry/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gnopm/registry/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/gnopm/registry/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gnopm/registry/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/gnopm/registry/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gnopm/registry/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/gnopm/registry/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/gnopm/registry/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/gnopm/registry/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"helpers_test.gno","body":"package registry\n\nimport (\n\tpm \"gno.land/p/moul/gnopm/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// Deterministic, checksum-valid test addresses. Made rather than typed: the\n// address-namespace rule turns on the bech32 alphabet, which drops 1, b, i and\n// o, so a plausible-looking hand-written \"g1...\" fails the check for a reason\n// that has nothing to do with what is under test.\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\n\t// alicePkg sits in alice's OWN address namespace, which is the only\n\t// ownership a test can create: r/sys/users is not writable from a unit\n\t// test, so a name namespace can never resolve to a test account.\n\talicePkg = \"gno.land/r/\" + alice.String() + \"/scratch/v0\"\n)\n\nconst (\n\trepoURL  = \"https://github.com/moul/gno-contracts\"\n\tsha1Zero = \"0000000000000000000000000000000000000000\"\n\tsha1One  = \"1111111111111111111111111111111111111111\"\n\totherPkg = \"gno.land/p/moul/md/v1\"\n)\n\n// reset puts the realm back to its initial state. Realm globals persist for the\n// whole test binary and examples run after every Test, so anything that renders\n// starts from a known tree or its pinned output silently depends on test order.\nfunc reset() { reg = pm.New() }\n\n// seedFixture builds a deterministic registry straight through the library: no\n// chain context needed, which is what lets an Example use it. Going through the\n// library rather than through Register also skips the crossing call, which an\n// example cannot make.\nfunc seedFixture() {\n\treset()\n\treg.Register(alice, 100, alicePkg, repoURL, sha1Zero, \"scratch\", \"refs/tags/v0.1.0\")\n\treg.Register(bob, 110, alicePkg, \"https://github.com/bob/impostor\", sha1One, \"\", \"\")\n\treg.Register(alice, 120, otherPkg, repoURL, sha1One, \"p/moul/md\", \"\")\n}\n"},{"name":"registry.gno","body":"// Package registry is an open, on-chain map from a deployed gno package path\n// back to the source that produced it: repository, commit, directory.\n//\n// It is the realm half of gno.land/p/moul/gnopm/v0, which holds the domain\n// model and the whole of the reasoning; this file is wiring. Every exported\n// mutation is a crossing function that resolves the caller, forwards to the\n// library, aborts on error (the only way to revert state in gno) and emits an\n// event for indexers.\n//\n// # It cannot promise, and does not pretend to\n//\n// Nothing here is verified and nothing here can be. A realm cannot clone a\n// repository, so it cannot check that the bytes at the claimed commit are the\n// bytes deployed at the claimed path. What it stores is testimony under a\n// signature: this address says this package came from that source.\n//\n// That is still worth storing, for two reasons.\n//\n// First, it is testimony in the exact shape a verifier needs. Path, repository,\n// commit and directory are precisely the four inputs to \"hash the addpkg\n// payload of that directory and compare it with what the chain hands back\",\n// which gnopm already does against a local tree (`gnopm verify -deployed`). The\n// registry does not answer the question; it makes the question answerable by\n// anything that can clone.\n//\n// Second, the chain knows who signed. A claim from the address that owns the\n// package path's namespace comes from the party that controls the path, and\n// OwnedBy reports that. It is computed on every read, never stored, because a\n// name can be transferred and a stored answer would rot into exactly the kind\n// of stale claim this realm exists to distinguish from a live one.\n//\n// # Open, and tagged\n//\n// Anyone may claim any path, including one they had nothing to do with. That is\n// deliberate: gating registration on namespace ownership would leave the map\n// empty on day one, when almost nothing has been registered by its own\n// deployer, and an empty registry teaches nobody anything. A stranger's claim\n// is not suppressed, it is labelled and ranked below the owner's, and Render\n// never presents an unverified claim as a fact.\n//\n// A claimant may always withdraw their own claim, and may never touch anyone\n// else's.\npackage registry\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\n\tpm \"gno.land/p/moul/gnopm/v0\"\n\t\"gno.land/r/sys/users\"\n)\n\nvar reg = pm.New()\n\n// caller is the address that crossed into this realm. Deliberately not\n// restricted to end users: a realm may hold a namespace, and a DAO registering\n// the source of the packages it governs is the same operation.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"gnopm/registry: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// resolveName is the r/sys/users half of the ownership rule, passed to the\n// library so the library stays pure.\n//\n// isCurrent is deliberately ignored, matching r/moul/forge: a name that\n// resolves through an alias still resolves to the same holder, so a namespace\n// survives its owner renaming. IsDeleted folds the nil check in, which is what\n// its own doc comment asks call sites to rely on.\nfunc resolveName(name string) (address, bool) {\n\tdata, _ := users.ResolveName(name)\n\tif data.IsDeleted() {\n\t\treturn \"\", false\n\t}\n\treturn data.Addr(), true\n}\n\n// Register records that pkgPath was built from dir of repo at commit.\n//\n// Calling it again for the same path replaces the caller's own claim and\n// nobody else's, so moving a claim to a new commit after a redeploy is one\n// call with no read first.\n//\n// ref is optional and is never the thing verified: a ref moves, a commit does\n// not. It is recorded so a reader can tell a claim pinned to a released tag\n// from one pinned to a commit on nobody's branch, and so a verifier can report\n// a commit that has since been orphaned by a force-push.\n//\n// dir is empty when the package sits at the repository root.\nfunc Register(cur realm, pkgPath, repo, commit, dir, ref string) {\n\ta := caller(cur)\n\t_, err := reg.Register(a, runtime.ChainHeight(), pkgPath, repo, commit, dir, ref)\n\tmust(err)\n\tchain.Emit(\"SourceClaimed\",\n\t\t\"pkgpath\", pkgPath,\n\t\t\"claimant\", a.String(),\n\t\t\"repo\", repo,\n\t\t\"commit\", commit,\n\t)\n}\n\n// Withdraw removes the caller's own claim about pkgPath.\nfunc Withdraw(cur realm, pkgPath string) {\n\ta := caller(cur)\n\tmust(reg.Withdraw(a, pkgPath))\n\tchain.Emit(\"SourceWithdrawn\", \"pkgpath\", pkgPath, \"claimant\", a.String())\n}\n\n// PackageCount is how many package paths carry at least one claim.\nfunc PackageCount() int { return reg.Size() }\n\n// ClaimCount is the total number of claims across every path.\nfunc ClaimCount() int { return reg.Claims() }\n\n// HasClaims reports whether anything has been said about pkgPath. Cheap enough\n// for another realm or an indexer to ask per package.\nfunc HasClaims(pkgPath string) bool { return reg.Package(pkgPath) != nil }\n\n// OwnerClaim returns the repository, commit and directory claimed by the party\n// that owns pkgPath's namespace, and whether such a claim exists.\n//\n// This is the only read that filters, and it filters on the one signal the\n// chain can actually prove. Everything else a caller wants is in Render or in\n// the events.\nfunc OwnerClaim(pkgPath string) (repo, commit, dir string, ok bool) {\n\tp := reg.Package(pkgPath)\n\tif p == nil {\n\t\treturn \"\", \"\", \"\", false\n\t}\n\tp.IterateClaims(func(c *pm.Claim) bool {\n\t\tif c.OwnedBy(resolveName) {\n\t\t\trepo, commit, dir, ok = c.Repo, c.Commit, c.Dir, true\n\t\t\treturn true // stop\n\t\t}\n\t\treturn false\n\t})\n\treturn repo, commit, dir, ok\n}\n"},{"name":"registry_test.gno","body":"package registry\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRegisterAndWithdraw(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), otherPkg, repoURL, sha1Zero, \"p/moul/md\", \"refs/heads/main\")\n\n\tuassert.Equal(t, 1, PackageCount())\n\tuassert.Equal(t, 1, ClaimCount())\n\tuassert.True(t, HasClaims(otherPkg))\n\tuassert.False(t, HasClaims(\"gno.land/p/moul/nope/v0\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tWithdraw(cross(cur), otherPkg)\n\tuassert.Equal(t, 0, PackageCount())\n\tuassert.False(t, HasClaims(otherPkg))\n}\n\n// A claim is the claimant's own. Nobody else may take it back, and the refusal\n// has to abort rather than silently do nothing: a Withdraw that quietly did\n// nothing reads to the caller exactly like one that worked.\nfunc TestWithdrawIsNotTransferable(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), otherPkg, repoURL, sha1Zero, \"\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"no such claim\", func() {\n\t\tWithdraw(cross(cur), otherPkg)\n\t})\n\tuassert.True(t, HasClaims(otherPkg), \"alice's claim survived bob\")\n}\n\nfunc TestRegisterAborts(cur realm, t *testing.T) {\n\treset()\n\tcases := []struct {\n\t\tname                            string\n\t\tpkgPath, repo, commit, dir, ref string\n\t\tcontains                        string\n\t}{\n\t\t{\"bad path\", \"nonsense\", repoURL, sha1Zero, \"\", \"\", \"invalid package path\"},\n\t\t{\"non-https repo\", otherPkg, \"javascript:alert(1)\", sha1Zero, \"\", \"\", \"invalid repository URL\"},\n\t\t{\"abbreviated commit\", otherPkg, repoURL, \"0123456\", \"\", \"\", \"invalid commit id\"},\n\t\t{\"absolute dir\", otherPkg, repoURL, sha1Zero, \"/etc\", \"\", \"invalid directory\"},\n\t\t{\"unqualified ref\", otherPkg, repoURL, sha1Zero, \"\", \"main\", \"invalid ref name\"},\n\t}\n\tfor _, tc := range cases {\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\tuassert.AbortsContains(t, cur, tc.contains, func() {\n\t\t\tRegister(cross(cur), tc.pkgPath, tc.repo, tc.commit, tc.dir, tc.ref)\n\t\t}, tc.name)\n\t}\n\tuassert.Equal(t, 0, ClaimCount(), \"nothing was stored\")\n}\n\n// OwnerClaim is the only read that filters, and it filters on the one thing\n// about a claim the chain can prove. An address namespace belongs to that\n// account with nothing registered anywhere, so it is testable without\n// r/sys/users, which a test cannot write to.\nfunc TestOwnerClaim(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tRegister(cross(cur), alicePkg, \"https://github.com/bob/impostor\", sha1One, \"\", \"\")\n\t_, _, _, ok := OwnerClaim(alicePkg)\n\tuassert.False(t, ok, \"a stranger's claim is not the owner's\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), alicePkg, repoURL, sha1Zero, \"scratch\", \"\")\n\trepo, commit, dir, ok := OwnerClaim(alicePkg)\n\tuassert.True(t, ok, \"the namespace holder's claim is found\")\n\tuassert.Equal(t, repoURL, repo)\n\tuassert.Equal(t, sha1Zero, commit)\n\tuassert.Equal(t, \"scratch\", dir)\n\n\t_, _, _, ok = OwnerClaim(\"gno.land/p/moul/nothing/v0\")\n\tuassert.False(t, ok, \"an unclaimed path has no owner claim\")\n}\n\n// Re-registering moves the caller's own claim and creates no second one.\nfunc TestReregister(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), otherPkg, repoURL, sha1Zero, \"p/moul/md\", \"\")\n\ttesting.SkipHeights(10)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), otherPkg, repoURL, sha1One, \"p/moul/md\", \"refs/tags/v1\")\n\n\tuassert.Equal(t, 1, ClaimCount())\n\tgot := Render(otherPkg)\n\tuassert.True(t, strings.Contains(got, sha1One[:12]), \"the new commit renders\")\n\tuassert.False(t, strings.Contains(got, sha1Zero[:12]), \"the old one is gone\")\n\tuassert.True(t, strings.Contains(got, \"| last updated | block\"), \"an updated claim says when\")\n}\n\n// A package path arrives at Render already split on \"/\", so the routing is the\n// rejoin. Anything that does not reassemble into a path is a miss, and a miss\n// must not render as an empty package page.\nfunc TestRenderRouting(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"nonsense\"), \"Not found\"), \"one bad element\")\n\tuassert.True(t, strings.Contains(Render(\"a/b/c\"), \"Not found\"), \"too few elements\")\n\tuassert.True(t, strings.Contains(Render(\"help\"), \"How this registry works\"), \"help page\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"gnopm source registry\"), \"home\")\n\tuassert.True(t, strings.Contains(Render(otherPkg), \"Nobody has claimed\"), \"valid but unclaimed\")\n}\n\n// The page ranks the owner's claim above a stranger's and says which is which.\n// Rendering them identically is the whole mistake this realm exists to avoid,\n// so the separation is pinned rather than left to review.\nfunc TestRenderSeparatesOwnerFromStranger(t *testing.T) {\n\tseedFixture()\n\n\tgot := Render(alicePkg)\n\tiOwner := strings.Index(got, \"Claimed by the namespace owner\")\n\tiOthers := strings.Index(got, \"Claimed by others\")\n\tuassert.True(t, iOwner \u003e= 0, \"the owner section exists\")\n\tuassert.True(t, iOthers \u003e= 0, \"the others section exists\")\n\tuassert.True(t, iOwner \u003c iOthers, \"the owner is ranked first\")\n\tuassert.True(t, strings.Contains(got, \"impostor\"), \"a stranger's claim is shown, not hidden\")\n\tuassert.True(t, strings.Contains(got, \"do not own\"), \"and is labelled as not the owner's\")\n}\n"},{"name":"render.gno","body":"package registry\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n\n\tpm \"gno.land/p/moul/gnopm/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n)\n\n// untrusted-render: every STORED field is charset-validated at write time by\n// gno.land/p/moul/gnopm/v0 (ValidPkgPath, ValidRepo, ValidCommit, ValidDir,\n// ValidRef). Each is an allowlist, so a stored field cannot hold a backtick, a\n// pipe, a bracket, a control character or a bidi override, and therefore needs\n// no escaping at any of the several places one claim is shown. Validating once\n// at the write beats escaping at every read, and it is why ValidRef is narrower\n// than git's own rule: one denylist field would have undone it for all of them.\n//\n// The one string here that is NOT validated is the render path itself, which\n// arrives from the URL and is echoed back by notFound. That one is escaped.\n\n// pageSize bounds every listing: a Render that walks unbounded state is a\n// Render that eventually stops rendering.\nconst pageSize = 20\n\n// Render routes gnoweb paths:\n//\n//\t/                    every claimed package path\n//\t/\u003cpackage path\u003e      the claims about one package\n//\t/help                what this realm is, and how to write to it\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tparts := req.PathParts()\n\n\tif len(parts) == 0 || parts[0] == \"\" {\n\t\treturn renderHome(pageOf(req))\n\t}\n\tif len(parts) == 1 \u0026\u0026 parts[0] == \"help\" {\n\t\treturn renderHelp()\n\t}\n\t// A package path contains slashes, so it arrives split. Rejoining is the\n\t// whole of the routing: anything that reassembles into a valid path is a\n\t// package page, anything else is a miss.\n\tpkgPath := strings.Join(parts, \"/\")\n\tif !pm.ValidPkgPath(pkgPath) {\n\t\treturn notFound(pkgPath + \" is not a package path\")\n\t}\n\treturn renderPackage(pkgPath)\n}\n\nfunc base() string {\n\treturn strings.TrimPrefix(unsafe.CurrentRealm().PkgPath(), runtime.ChainDomain())\n}\n\nfunc pkgURL(pkgPath string) string { return base() + \":\" + pkgPath }\n\n// link does not escape its text, because every call site passes a field that is\n// charset-validated at write time (see the note above). Escaping here would\n// turn \"gno.land/p/moul/md/v1\" into \"gno\\.land/p/moul/md/v1\" on every row of\n// every listing, for no safety anyone gains.\nfunc link(text, url string) string { return \"[\" + text + \"](\" + url + \")\" }\n\n// join glues blocks with exactly one blank line between them.\n//\n// gno collapses two consecutive blank lines inside an example's // Output:\n// block, exactly as Go does, so a Render that ever emits them cannot be pinned\n// by an example at all. Appending \"\\n\" by hand as sections are built is how a\n// Render acquires them; assembling a list of blocks and joining once is how it\n// stops. Every block arrives without its own leading or trailing blank.\nfunc join(blocks []string) string {\n\tfor i, b := range blocks {\n\t\tblocks[i] = strings.Trim(b, \"\\n\")\n\t}\n\treturn strings.Join(blocks, \"\\n\\n\") + \"\\n\"\n}\n\nfunc pageOf(req *realmpath.Request) int {\n\tn, err := strconv.Atoi(req.Query.Get(\"page\"))\n\tif err != nil || n \u003c 1 {\n\t\treturn 1\n\t}\n\treturn n\n}\n\n// notFound echoes the requested path, which is the only untrusted string this\n// file handles: it comes from the URL and has already failed validation by the\n// time we are here. It is escaped rather than dropped, because \"that is not a\n// package path\" without saying which one is an unhelpful error.\nfunc notFound(why string) string {\n\treturn md.H1(\"Not found\") + \"\\n\" + md.EscapeText(why) + \".\\n\\n\" + link(\"Back to the registry\", base()) + \"\\n\"\n}\n\nfunc renderHome(page int) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"gnopm source registry\"))\n\tb.WriteString(\"\\nWhere a deployed package says it came from. Every entry is a claim made by whoever signed it, never a verified fact: this realm cannot clone a repository, so it records testimony in the shape a verifier needs and labels who said it.\\n\")\n\tb.WriteString(\"\\n**Packages:** \" + strconv.Itoa(reg.Size()) + \" · **Claims:** \" + strconv.Itoa(reg.Claims()) + \"\\n\")\n\n\tif reg.Size() == 0 {\n\t\tb.WriteString(\"\\nNothing claimed yet. \" + link(\"Register the first package\", txlink.Call(\"Register\")) + \"\\n\")\n\t\tb.WriteString(\"\\n\" + link(\"How this works\", base()+\":help\") + \"\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"\\n| package | claims | owner has claimed |\\n\")\n\tb.WriteString(\"| --- | ---: | --- |\\n\")\n\trows := 0\n\treg.IteratePackages((page-1)*pageSize, pageSize, func(p *pm.Package) bool {\n\t\trows++\n\t\towner := \"no\"\n\t\tif _, _, _, ok := OwnerClaim(p.PkgPath); ok {\n\t\t\towner = \"yes\"\n\t\t}\n\t\tb.WriteString(\"| \" + link(p.PkgPath, pkgURL(p.PkgPath)) +\n\t\t\t\" | \" + strconv.Itoa(p.Count()) +\n\t\t\t\" | \" + owner + \" |\\n\")\n\t\treturn false\n\t})\n\n\tif p := pager(page, rows); p != \"\" {\n\t\tb.WriteString(\"\\n\" + p + \"\\n\")\n\t}\n\tb.WriteString(\"\\n\" + link(\"How this works\", base()+\":help\") + \"\\n\")\n\treturn b.String()\n}\n\nfunc pager(page, rows int) string {\n\tvar parts []string\n\tif page \u003e 1 {\n\t\tparts = append(parts, link(\"previous\", base()+\"?page=\"+strconv.Itoa(page-1)))\n\t}\n\tif rows == pageSize {\n\t\tparts = append(parts, link(\"next\", base()+\"?page=\"+strconv.Itoa(page+1)))\n\t}\n\treturn strings.Join(parts, \" · \")\n}\n\nfunc renderPackage(pkgPath string) string {\n\tp := reg.Package(pkgPath)\n\tif p == nil {\n\t\treturn join([]string{\n\t\t\tmd.H1(pkgPath),\n\t\t\t\"Nobody has claimed a source for this package.\",\n\t\t\tlink(\"Claim it\", txlink.Call(\"Register\", \"pkgPath\", pkgPath)),\n\t\t\tlink(\"Back to the registry\", base()),\n\t\t})\n\t}\n\n\t// The namespace owner first, then everyone else. The ordering IS the\n\t// tagging: no ranking is stored, it is recomputed here from the one thing\n\t// about a claim that the chain can actually prove.\n\tvar owner, others []*pm.Claim\n\tp.IterateClaims(func(c *pm.Claim) bool {\n\t\tif c.OwnedBy(resolveName) {\n\t\t\towner = append(owner, c)\n\t\t} else {\n\t\t\tothers = append(others, c)\n\t\t}\n\t\treturn false\n\t})\n\n\tns := md.InlineCode(pm.Namespace(pkgPath))\n\tblocks := []string{\n\t\tmd.H1(pkgPath),\n\t\tstrconv.Itoa(p.Count()) + \" claim(s). A claim is what an address said, not what anyone checked.\",\n\t}\n\tif len(owner) \u003e 0 {\n\t\tblocks = append(blocks,\n\t\t\tmd.H2(\"Claimed by the namespace owner\"),\n\t\t\t\"The signer owns \"+ns+\", so this claim comes from the party that controls the path. That is not a proof the source matches. It is a proof of who is speaking.\")\n\t\tfor _, c := range owner {\n\t\t\tblocks = append(blocks, claimBlock(c))\n\t\t}\n\t}\n\tif len(others) \u003e 0 {\n\t\tblocks = append(blocks,\n\t\t\tmd.H2(\"Claimed by others\"),\n\t\t\t\"These addresses do not own \"+ns+\". A third party may be filling in the map honestly, or pointing at a repository that has nothing to do with this package. Read the source before trusting either.\")\n\t\tfor _, c := range others {\n\t\t\tblocks = append(blocks, claimBlock(c))\n\t\t}\n\t}\n\treturn join(append(blocks, link(\"Back to the registry\", base())))\n}\n\nfunc claimBlock(c *pm.Claim) string {\n\tvar b strings.Builder\n\tb.WriteString(\"| field | value |\\n| --- | --- |\\n\")\n\tb.WriteString(\"| claimant | \" + md.InlineCode(c.Claimant.String()) + \" |\\n\")\n\tb.WriteString(\"| commit | \" + link(c.Commit[:12], c.SourceURL()) + \" |\\n\")\n\tb.WriteString(\"| repository | \" + link(c.Repo, c.Repo) + \" |\\n\")\n\tdir := c.Dir\n\tif dir == \"\" {\n\t\tdir = \"(repository root)\"\n\t}\n\tb.WriteString(\"| directory | \" + md.InlineCode(dir) + \" |\\n\")\n\tif c.Ref != \"\" {\n\t\tb.WriteString(\"| ref | \" + md.InlineCode(c.Ref) + \" |\\n\")\n\t}\n\tb.WriteString(\"| claimed at | block \" + strconv.FormatInt(c.Height, 10) + \" |\\n\")\n\tupdated := \"never\"\n\tif c.UpdatedAt != c.Height {\n\t\tupdated = \"block \" + strconv.FormatInt(c.UpdatedAt, 10)\n\t}\n\tb.WriteString(\"| last updated | \" + updated + \" |\")\n\treturn b.String()\n}\n\nfunc renderHelp() string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"How this registry works\"))\n\tb.WriteString(\"\\nA gno import path is a chain address, not a repository URL, so nothing on chain says where a deployed package came from. This realm is where an address can say so.\\n\")\n\n\tb.WriteString(\"\\n\" + md.H2(\"What it proves\"))\n\tb.WriteString(\"\\nNothing on its own, and that is the honest answer. A realm cannot clone a repository, so it cannot check that the code at a commit is the code at a path. Three claims get confused with each other and only two of them can ever be settled:\\n\\n\")\n\tb.WriteString(\"| claim | provable |\\n| --- | --- |\\n\")\n\tb.WriteString(\"| this package came from that repository | no. Not here and not anywhere: anyone may deploy any bytes and claim any repository |\\n\")\n\tb.WriteString(\"| the deployed bytes equal the addpkg payload of that directory at that commit | yes, by hashing both sides. Off chain, by anything that can clone |\\n\")\n\tb.WriteString(\"| the claimant owns this path's namespace | yes, from chain data, and it is recomputed on every read |\\n\")\n\n\tb.WriteString(\"\\n\" + md.H2(\"Writing to it\"))\n\tb.WriteString(\"\\nRegister the source of a package you deployed. Calling it again replaces your own claim and nobody else's, which is how you move a claim to a new commit after a redeploy.\\n\\n\")\n\tb.WriteString(link(\"Register\", txlink.Call(\"Register\")) + \" · \" + link(\"Withdraw\", txlink.Call(\"Withdraw\")) + \"\\n\")\n\tb.WriteString(\"\\nFields: the full package path, an https repository URL, a 40 or 64 character lowercase hex commit, the subdirectory holding the package (empty for the repository root), and optionally a fully-qualified ref such as \" + md.InlineCode(\"refs/tags/v1.2.0\") + \".\\n\")\n\tb.WriteString(\"\\nAnyone may claim any path. A claim from an address that does not own the namespace is not hidden: it is shown under its own heading and ranked below the owner's.\\n\")\n\n\tb.WriteString(\"\\n\" + link(\"Back to the registry\", base()) + \"\\n\")\n\treturn b.String()\n}\n"},{"name":"render_test.gno","body":"package registry\n\n// ExampleRender pins the realm's Render output, which is its whole public\n// surface. Each example calls seedFixture first: realm globals persist for the\n// whole test binary and examples run after every Test, so without the reset the\n// pinned output would silently depend on test order.\n\nfunc ExampleRender() {\n\tseedFixture()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # gnopm source registry\n\t//\n\t// Where a deployed package says it came from. Every entry is a claim made by whoever signed it, never a verified fact: this realm cannot clone a repository, so it records testimony in the shape a verifier needs and labels who said it.\n\t//\n\t// **Packages:** 2 · **Claims:** 3\n\t//\n\t// | package | claims | owner has claimed |\n\t// | --- | ---: | --- |\n\t// | [gno.land/p/moul/md/v1](/r/moul/gnopm/registry/v0:gno.land/p/moul/md/v1) | 1 | no |\n\t// | [gno.land/r/g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh/scratch/v0](/r/moul/gnopm/registry/v0:gno.land/r/g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh/scratch/v0) | 2 | yes |\n\t//\n\t// [How this works](/r/moul/gnopm/registry/v0:help)\n}\n\n// The package page is the one that matters: an owner's claim and a stranger's\n// claim about the same path, under separate headings, owner first. The pinned\n// output is what stops that distinction being quietly refactored away.\nfunc ExampleRender_package() {\n\tseedFixture()\n\tprint(Render(alicePkg))\n\t// Output:\n\t// # gno.land/r/g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh/scratch/v0\n\t//\n\t// 2 claim(s). A claim is what an address said, not what anyone checked.\n\t//\n\t// ## Claimed by the namespace owner\n\t//\n\t// The signer owns `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh`, so this claim comes from the party that controls the path. That is not a proof the source matches. It is a proof of who is speaking.\n\t//\n\t// | field | value |\n\t// | --- | --- |\n\t// | claimant | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` |\n\t// | commit | [000000000000](https://github.com/moul/gno-contracts/tree/0000000000000000000000000000000000000000/scratch) |\n\t// | repository | [https://github.com/moul/gno-contracts](https://github.com/moul/gno-contracts) |\n\t// | directory | `scratch` |\n\t// | ref | `refs/tags/v0.1.0` |\n\t// | claimed at | block 100 |\n\t// | last updated | never |\n\t//\n\t// ## Claimed by others\n\t//\n\t// These addresses do not own `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh`. A third party may be filling in the map honestly, or pointing at a repository that has nothing to do with this package. Read the source before trusting either.\n\t//\n\t// | field | value |\n\t// | --- | --- |\n\t// | claimant | `g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu` |\n\t// | commit | [111111111111](https://github.com/bob/impostor/tree/1111111111111111111111111111111111111111) |\n\t// | repository | [https://github.com/bob/impostor](https://github.com/bob/impostor) |\n\t// | directory | `(repository root)` |\n\t// | claimed at | block 110 |\n\t// | last updated | never |\n\t//\n\t// [Back to the registry](/r/moul/gnopm/registry/v0)\n}\n\nfunc ExampleRender_unclaimed() {\n\tseedFixture()\n\tprint(Render(\"gno.land/p/moul/nothing/v0\"))\n\t// Output:\n\t// # gno.land/p/moul/nothing/v0\n\t//\n\t// Nobody has claimed a source for this package.\n\t//\n\t// [Claim it](/r/moul/gnopm/registry/v0$help\u0026func=Register\u0026pkgPath=gno.land%2Fp%2Fmoul%2Fnothing%2Fv0)\n\t//\n\t// [Back to the registry](/r/moul/gnopm/registry/v0)\n}\n\nfunc ExampleRender_help() {\n\tseedFixture()\n\tprint(Render(\"help\"))\n\t// Output:\n\t// # How this registry works\n\t//\n\t// A gno import path is a chain address, not a repository URL, so nothing on chain says where a deployed package came from. This realm is where an address can say so.\n\t//\n\t// ## What it proves\n\t//\n\t// Nothing on its own, and that is the honest answer. A realm cannot clone a repository, so it cannot check that the code at a commit is the code at a path. Three claims get confused with each other and only two of them can ever be settled:\n\t//\n\t// | claim | provable |\n\t// | --- | --- |\n\t// | this package came from that repository | no. Not here and not anywhere: anyone may deploy any bytes and claim any repository |\n\t// | the deployed bytes equal the addpkg payload of that directory at that commit | yes, by hashing both sides. Off chain, by anything that can clone |\n\t// | the claimant owns this path's namespace | yes, from chain data, and it is recomputed on every read |\n\t//\n\t// ## Writing to it\n\t//\n\t// Register the source of a package you deployed. Calling it again replaces your own claim and nobody else's, which is how you move a claim to a new commit after a redeploy.\n\t//\n\t// [Register](/r/moul/gnopm/registry/v0$help\u0026func=Register) · [Withdraw](/r/moul/gnopm/registry/v0$help\u0026func=Withdraw)\n\t//\n\t// Fields: the full package path, an https repository URL, a 40 or 64 character lowercase hex commit, the subdirectory holding the package (empty for the repository root), and optionally a fully-qualified ref such as `refs/tags/v1.2.0`.\n\t//\n\t// Anyone may claim any path. A claim from an address that does not own the namespace is not hidden: it is shown under its own heading and ranked below the owner's.\n\t//\n\t// [Back to the registry](/r/moul/gnopm/registry/v0)\n}\n"}]},"send":"","max_deposit":"14000000ugnot"}],"fee":{"gas_wanted":"101193000","gas_fee":"303579ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"U5APR8C//4CFd/TEf/NmhW22t6Z3PlP+CuObE6sTPp5kzrCcTBEQYqIGCFujiaH08x+zF4MM4EE1k3yHjQ38+w=="}],"memo":""},"metadata":{"timestamp":"1790960456"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"gns","path":"gno.land/r/moul/gns/v0","files":[{"name":"README.md","body":"# GNS — Gno Name Service\n\nGNS is an **ENS-equivalent naming system expressed as a single Gno-native\nrealm**. It provides the capabilities mainstream ENS users rely on —\nregistration, renewal, expiry \u0026 grace, forward/reverse resolution, primary\nnames, typed and arbitrary records, subnames with policies, delegated\noperators, pagination and events — but implements all of it\nthrough **one realm, one ownership model, one record model, one authorization\nfunction and one registration lifecycle**, rather than a collection of\nemulated ENS contracts.\n\nPackage path: `gno.land/r/moul/gns/v0` · possible future target: `gno.land/r/gnoland/gns`.\n\nBuilt and tested against **gno 0.9 / master** (`chain`, `chain/banker`,\n`chain/runtime`, `gno.land/p/nt/avl/v0`).\n\n## What is and isn't compatible with ENS\n\nGNS deliberately does **not** aim for byte-for-byte ENS/Ethereum compatibility.\n\n**Equivalent user capabilities** (different implementation):\n\n| ENS capability | GNS |\n|---|---|\n| Register / renew second-level name | `Register`, `Renew` |\n| Expiration + grace period | stored expiry + configurable grace |\n| Commit–reveal | `Commit` + `Register` (see preimage below) |\n| Owner / transfer | `OwnerOf`, `Transfer` |\n| Resolver records | built-in typed records (no pluggable resolver) |\n| Multichain addresses | `SetCoinAddress` keyed by coin type |\n| Text / content hash / pubkey / ABI / interface | typed setters/getters |\n| Arbitrary records | `SetRecord` with reverse-DNS namespaces |\n| Reverse resolution + primary name | `SetPrimaryName` / `PrimaryName` (forward-verified) |\n| Subnames + subname registrar | hierarchical names + `RegistrationPolicy` |\n| Wrapped / emancipated names | explicit `ControlPolicy` flags + `LockPolicy` |\n| Delegated managers | `SetOperator` with per-permission grants |\n| Multicall | not in-realm — loop a typed setter from one `gnokey maketx run` |\n| Wildcard resolution | `Resolve(..., NearestAncestor)` |\n| Events | append-only `Event` log + native `chain.Emit` |\n\n**Explicitly NOT included** (Ethereum-specific or out of scope for v1): DNSSEC\nimport, DNS registrar, CCIP-Read, L2 resolution, NFT/ERC-721 ownership, Ethereum\nABI compatibility, Unicode/emoji names, governance DAO, auctions, secondary\nmarketplace, and arbitrary custom-resolver execution.\n\n## Names\n\n- Second-level names are stored **string-native and suffix-free**: `alice`,\n  not `alice.gno`. Display clients may append a `.gno` suffix; it is presentation\n  only.\n- Hierarchy is `label.parent` (`wallet.alice`, `prod.api.company`).\n- Labels: lowercase `a–z`, digits `0–9`, and `-` (not leading/trailing).\n  1–63 bytes per label, ≤255 bytes and ≤16 labels total. Input is lowercased;\n  **non-ASCII is rejected**. All canonicalization happens in `Normalize`.\n\n## Lifecycle\n\n`Available → Committed → Active → Grace → Expired → (recycled)`, plus `Deleted`\nfor removed subnames and `Reserved` for admin-held names.\n\n- **Active**: `now \u003c ExpiresAt`. Owner and permitted operators may mutate.\n- **Grace**: `ExpiresAt ≤ now \u003c GraceEndsAt`. Only renewal by the existing owner;\n  not registrable by others.\n- **Expired**: `now ≥ GraceEndsAt`. Registrable again; old state is cleared on\n  re-registration and `Generation` is incremented so clients can detect the\n  replacement. Subnames carry `ParentGeneration` and do **not** silently\n  survive a recycled parent.\n\n## Commit–reveal\n\nThe commitment binds the reveal so observers can neither copy nor front-run it:\n\n```\ncommitment = sha256hex( name | owner | duration | secret | recordsHash | policyRevision )\n```\n\nwhere `|` is `\"|\"`, `owner` is the bech32 string, integers are base-10, and\n`name` is the **normalized** name. Use the on-chain helper `MakeCommitment(...)`\nto compute it identically to what `Register` recomputes at reveal.\n\n## Pricing\n\nDeterministic and boring — no oracle, no USD, no auction:\n\n```\nprice = duration × BasePricePerSecond × lengthMultiplier(label)\n```\n\nDefault length multipliers: 1→100, 2→25, 3→5, 4→2, 5+→1. `Price(name, duration)`\nreturns a quote; `Register` always recomputes from state and rejects a stale\n`policyRevision`.\n\n## Authorization\n\nEvery mutation funnels through one internal `authorize(caller, name, permission)`\nwith a fixed authority order:\n\n1. **Admin** — emergency/protocol operations only; **never** routine power over\n   user names or records (admin cannot confiscate).\n2. **Direct owner** of an active name.\n3. **Active operator** holding the matching permission.\n4. **Parent authority**, only where the child `ControlPolicy` allows it.\n\n## Gno-specific deviations from the spec\n\nThe spec is written with Ethereum/Go idioms; these are the deliberate,\ngno-correct adaptations:\n\n- **Mutations panic, they don't return `error`.** In gno only a panic/abort\n  reverts state, so state-changing crossing functions (those taking `cur realm`)\n  panic with a **stable machine-readable error code** (`unauthorized`,\n  `name_unavailable`, `commitment_missing`, …). Read/quote functions return\n  `(value, ok)` or `(value, error)` normally.\n- **`avl.Tree` instead of Go maps** for every enumerable collection, so all\n  listing APIs (`NamesByOwner`, `Subnames`, `TextKeys`, `CoinTypes`,\n  `Operators`, `EventsAfter`) are ordered, bounded, and cursor-based — there is\n  no unbounded \"return everything\" query.\n- **String-native storage** rather than namehashes (hashing is used only for\n  commitments and event digests).\n\n## Public API (summary)\n\nRead: `Normalize`, `Status`, `Exists`, `OwnerOf`, `GetName`, `Resolve`,\n`Address`, `CoinAddress`, `Text`, `ContentHash`, `PublicKey`, `ABI`,\n`Interface`, `Record`, `PrimaryName`, `Price`, `MakeCommitment`,\n`CommitmentStatus`, `NamesByOwner`, `Subnames`, `TextKeys`, `CoinTypes`,\n`Operators`, `EventsAfter`, `EventsForName`, `Render`.\n\nMutations (crossing): `Commit`, `Register`, `Renew`, `Transfer`,\n`CreateSubname`, `DeleteSubname`, `SetRegistrationPolicy`, `LockPolicy`,\n`SetOperator`, `RemoveOperator`, `SetPrimaryName`,\n`ClearPrimaryName`, and the typed record setters (`SetAddress`, `SetText`,\n`SetCoinAddress`, `SetContentHash`, `SetPublicKey`, `SetABI`, `SetInterface`,\n`SetRecord`, `SetTTL`).\n\nAdmin (two-step transfer): `SetPaused`, `SetRegistrationOpen`, `SetPricing`,\n`SetTreasury`, `ReserveName`, `SetLimits`, `TransferAdmin`, `AcceptAdmin`.\n\n## Render explorer\n\n`Render(path)` serves a read-only Markdown explorer:\n\n```\n/                 overview + stats\n/name/\u003cname\u003e      owner, status, expiry, records, subnames\n/address/\u003cg1...\u003e  verified primary name + owned names\n/available/\u003cname\u003e availability + price\n/events           recent events\n/help             API summary\n```\n\n## Building \u0026 testing\n\n```sh\nexport GNOROOT=/path/to/gnolang/gno   # a gno master checkout\ngno lint .\ngno test .\n```\n\nThe test suite covers the spec's critical invariants: single effective owner,\nexpired owners lose authority, grace names aren't re-registrable, parents can't\nexceed child policy, permanent policies only tighten, forward-verified primary\nnames, single-use commitments, deterministic overflow-safe pricing, generation\nrecycling without stale-record leakage, bounded enumeration, and admin\nnon-confiscation.\n\n\u003e **Testing note.** Because this realm is developed outside the gno examples\n\u003e module, it uses local assertion helpers instead of `gno.land/p/nt/uassert`\n\u003e (whose working-tree copy fails to preprocess for external packages), and it\n\u003e unit-tests rejection paths against the internal error-returning helpers\n\u003e (`authorize`, `priceFor`, `available`, `mergeRestrictive`, …) rather than by\n\u003e catching crossing-boundary aborts. End-to-end abort/`// Error:` filetests can\n\u003e be added once the realm lives in-tree.\n\n## Client caching\n\nReverse resolution is forward-verified on-chain, so clients and indexers may\nsafely cache the **user ↔ address** mapping:\n\n- **positive match** (an address has a verified primary name, or a name resolves\n  to an address): cache for up to **1 hour**;\n- **negative result** (no primary name / no match): cache for only **1 minute**,\n  so a freshly-set name becomes visible quickly.\n\n## Status\n\nThis is a v1 implementation of the [GNS design spec][spec]. It is staged\nfor review; it is not deployed.\n\n[spec]: https://gist.github.com/moul/1c160b2cb9ee080714b3d1933ddea60a\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/gns/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gns/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/gns/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gns/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/gns/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gns/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/gns/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/gns/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/gns/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/gns/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"asserts_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n)\n\n// Local assertion helpers.\n//\n// We deliberately avoid gno.land/p/nt/uassert here: when this realm is compiled\n// as an EXTERNAL package (outside the gno examples module) the working-tree copy\n// of uassert/v0 fails to preprocess with the pinned gno binary. These helpers\n// depend only on the standard testing package.\n//\n// GNS mutations PANIC with stable error values (see the error_* set) to revert\n// state, per gno semantics. A recover() inside this same realm package cannot\n// catch a crossing-boundary abort (only a pure p/ package frame can). Rejection\n// invariants are therefore unit-tested against the internal, non-crossing\n// helpers that produce the errors (authorize, priceFor, available, ...), and a\n// few end-to-end abort behaviours are covered by filetests.\n\nfunc eqStr(t *testing.T, want, got, ctx string) {\n\tt.Helper()\n\tif want != got {\n\t\tt.Errorf(\"%s: want %q, got %q\", ctx, want, got)\n\t}\n}\n\nfunc eqInt(t *testing.T, want, got int64, ctx string) {\n\tt.Helper()\n\tif want != got {\n\t\tt.Errorf(\"%s: want %d, got %d\", ctx, want, got)\n\t}\n}\n\nfunc isTrue(t *testing.T, v bool, ctx string) {\n\tt.Helper()\n\tif !v {\n\t\tt.Errorf(\"%s: want true\", ctx)\n\t}\n}\n\nfunc isFalse(t *testing.T, v bool, ctx string) {\n\tt.Helper()\n\tif v {\n\t\tt.Errorf(\"%s: want false\", ctx)\n\t}\n}\n\nfunc noErr(t *testing.T, err error, ctx string) {\n\tt.Helper()\n\tif err != nil {\n\t\tt.Errorf(\"%s: unexpected error %v\", ctx, err)\n\t}\n}\n\nfunc isErr(t *testing.T, err error, ctx string) {\n\tt.Helper()\n\tif err == nil {\n\t\tt.Errorf(\"%s: expected error, got nil\", ctx)\n\t}\n}\n\n// errIs asserts err matches want by stable code (Error() string).\nfunc errIs(t *testing.T, err, want error, ctx string) {\n\tt.Helper()\n\tif err == nil {\n\t\tt.Errorf(\"%s: expected error %v, got nil\", ctx, want)\n\t\treturn\n\t}\n\tif err.Error() != want.Error() {\n\t\tt.Errorf(\"%s: expected %q, got %q\", ctx, want.Error(), err.Error())\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/gns/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"gns.gno","body":"// Package gns implements GNS (Gno Name Service): an ENS-equivalent naming\n// system expressed as a single Gno-native realm.\n//\n// The design goal is NOT byte-for-byte ENS compatibility. Instead it provides\n// the same user-facing capabilities (registration, renewal, expiry/grace,\n// forward \u0026 reverse resolution, primary names, typed + arbitrary records,\n// subnames with policies, delegated operators, pagination and\n// events) through ONE realm, ONE ownership model, ONE record model, ONE\n// authorization function and ONE registration lifecycle.\n//\n// Key deviations from a naive port of the spec, forced by gno semantics:\n//\n//   - State-mutating exported functions are \"crossing\" functions: they take\n//     `cur realm` as the first parameter and PANIC (abort) on failure rather\n//     than returning an error, because in gno only a panic/abort reverts state.\n//     Failures panic with a stable machine-readable code (see the error_* set).\n//   - Persistent, enumerable collections use avl.Tree (ordered, paginatable)\n//     instead of Go maps, so every listing API is bounded and cursor-based.\n//   - Names are stored string-native (canonical \"label.parent\"), not namehashed.\n//\n// See README.md for the full compatibility statement.\npackage gns\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// ---------------------------------------------------------------------------\n// 2. Constants\n// ---------------------------------------------------------------------------\n\nconst (\n\tmaxLabelLen = 63\n\tmaxNameLen  = 255\n\tmaxDepth    = 16\n\n\tsep = \"|\" // index-key separator; never appears in names or bech32 addresses\n)\n\n// Registration-policy modes.\nconst (\n\tModeClosed    = \"closed\"\n\tModeOwner     = \"owner\"\n\tModeOpen      = \"open\"\n\tModeAllowlist = \"allowlist\"\n\tModePaid      = \"paid\"\n)\n\n// Reserved record namespaces (cannot be used by the generic SetRecord API).\nvar reservedNamespaces = map[string]bool{\n\t\"gno\": true, \"addr\": true, \"text\": true, \"content\": true,\n\t\"abi\": true, \"interface\": true, \"system\": true,\n}\n\n// Stable machine-readable error codes. Messages MAY add context, but client\n// logic should depend on these codes.\nvar (\n\terrInvalidName        = errors.New(\"invalid_name\")\n\terrInvalidLabel       = errors.New(\"invalid_label\")\n\terrNameUnavailable    = errors.New(\"name_unavailable\")\n\terrNameReserved       = errors.New(\"name_reserved\")\n\terrNameExpired        = errors.New(\"name_expired\")\n\terrNameInGrace        = errors.New(\"name_in_grace\")\n\terrUnauthorized       = errors.New(\"unauthorized\")\n\terrCommitmentMissing  = errors.New(\"commitment_missing\")\n\terrCommitmentTooNew   = errors.New(\"commitment_too_new\")\n\terrCommitmentExpired  = errors.New(\"commitment_expired\")\n\terrCommitmentMismatch = errors.New(\"commitment_mismatch\")\n\terrPriceChanged       = errors.New(\"price_changed\")\n\terrInsufficientPay    = errors.New(\"insufficient_payment\")\n\terrDurationTooShort   = errors.New(\"duration_too_short\")\n\terrDurationTooLong    = errors.New(\"duration_too_long\")\n\terrRecordTooLarge     = errors.New(\"record_too_large\")\n\terrRecordLimit        = errors.New(\"record_limit_reached\")\n\terrOperatorLimit      = errors.New(\"operator_limit_reached\")\n\terrPolicyLocked       = errors.New(\"policy_locked\")\n\terrParentInvalid      = errors.New(\"parent_invalid\")\n\terrPaused             = errors.New(\"paused\")\n\terrNotFound           = errors.New(\"not_found\")\n\terrNotUser            = errors.New(\"not_user\")\n\terrSpoofedRealm       = errors.New(\"spoofed_realm\")\n\terrEmptyAddress       = errors.New(\"empty_address\")\n\terrRegistrationClosed = errors.New(\"registration_closed\")\n\terrBadRequest         = errors.New(\"bad_request\")\n)\n\n// ---------------------------------------------------------------------------\n// 3. Public types\n// ---------------------------------------------------------------------------\n\n// Permission enumerates the delegable operator capabilities.\ntype Permission int\n\nconst (\n\tPermManageRecords Permission = iota\n\tPermManageOperators\n\tPermManageSubnames\n\tPermRenew\n\tPermTransfer\n\tPermManagePolicy\n)\n\n// Permissions is an operator grant. ExpiresAt == 0 means no expiry.\ntype Permissions struct {\n\tManageRecords   bool\n\tManageOperators bool\n\tManageSubnames  bool\n\tRenew           bool\n\tTransfer        bool\n\tManagePolicy    bool\n\tExpiresAt       int64\n}\n\nfunc (p Permissions) has(perm Permission) bool {\n\tswitch perm {\n\tcase PermManageRecords:\n\t\treturn p.ManageRecords\n\tcase PermManageOperators:\n\t\treturn p.ManageOperators\n\tcase PermManageSubnames:\n\t\treturn p.ManageSubnames\n\tcase PermRenew:\n\t\treturn p.Renew\n\tcase PermTransfer:\n\t\treturn p.Transfer\n\tcase PermManagePolicy:\n\t\treturn p.ManagePolicy\n\t}\n\treturn false\n}\n\n// ControlPolicy holds the explicit, readable ownership/parent control flags\n// that replace ENS Name Wrapper fuses.\ntype ControlPolicy struct {\n\tOwnerCanTransfer       bool\n\tOwnerCanCreateSubnames bool\n\tRecordsMutable         bool\n\n\tParentCanReclaim      bool\n\tParentCanTransfer     bool\n\tParentCanDelete       bool\n\tParentCanChangePolicy bool\n\n\t// Permanent means the policy can only become MORE restrictive. It does not\n\t// make records immutable by itself.\n\tPermanent bool\n}\n\n// RegistrationPolicy governs how subnames of a name may be created. The\n// realm-global config drives second-level registration.\ntype RegistrationPolicy struct {\n\tMode string // closed | owner | open | allowlist | paid\n\n\tMinDuration int64\n\tMaxDuration int64\n\n\tPricePerSecond int64\n\tPaymentDenom   string\n\n\tAllowlist *avl.Tree // address string -\u003e bool\n\n\tDefaultControlPolicy ControlPolicy\n}\n\n// Records is the built-in resolver state for a single name.\ntype Records struct {\n\tNativeAddress string\n\tContentHash   []byte\n\tPublicKey     []byte\n\n\tAddresses  *avl.Tree // coinType (decimal string) -\u003e []byte\n\tText       *avl.Tree // key -\u003e string\n\tABIs       *avl.Tree // contentType -\u003e []byte\n\tInterfaces *avl.Tree // interfaceID -\u003e string\n\tArbitrary  *avl.Tree // \"namespace/key\" -\u003e []byte\n\n\tCount int // number of stored entries, for MaxRecordsPerName enforcement\n}\n\nfunc newRecords() *Records {\n\treturn \u0026Records{\n\t\tAddresses:  avl.NewTree(),\n\t\tText:       avl.NewTree(),\n\t\tABIs:       avl.NewTree(),\n\t\tInterfaces: avl.NewTree(),\n\t\tArbitrary:  avl.NewTree(),\n\t}\n}\n\n// Name is the single object the whole realm operates on.\ntype Name struct {\n\tCanonical string\n\tOwner     address\n\n\tCreatedAt   int64\n\tUpdatedAt   int64\n\tExpiresAt   int64 // 0 == permanent subname (follows parent validity)\n\tGraceEndsAt int64\n\n\tParent string\n\tLabel  string\n\tDepth  uint8\n\n\tTTL uint64\n\n\tGeneration       uint64\n\tParentGeneration uint64\n\n\tRegistrationPolicy RegistrationPolicy\n\tControlPolicy      ControlPolicy\n\n\tRecords *Records\n\n\tOperators     *avl.Tree // address string -\u003e Permissions\n\tOperatorCount int\n\n\tRevision uint64\n\tReserved bool\n\tDeleted  bool\n}\n\n// NameView is the read-only projection returned by GetName.\ntype NameView struct {\n\tCanonical   string\n\tOwner       string\n\tStatus      string\n\tCreatedAt   int64\n\tUpdatedAt   int64\n\tExpiresAt   int64\n\tGraceEndsAt int64\n\tParent      string\n\tLabel       string\n\tDepth       uint8\n\tTTL         uint64\n\tGeneration  uint64\n\tRevision    uint64\n\tReserved    bool\n\tNativeAddr  string\n}\n\n// Config is the realm-global configuration.\ntype Config struct {\n\tAdmin        address\n\tPendingAdmin address\n\n\tRegistrationOpen bool\n\n\tMinCommitAge int64\n\tMaxCommitAge int64\n\n\tMinRegistrationDuration int64\n\tMaxRegistrationDuration int64\n\n\tGracePeriod int64\n\n\tBasePricePerSecond int64\n\tPremiumByLength    map[uint8]int64\n\n\tPaymentDenom string\n\tTreasury     address\n\n\tMaxTextValueBytes   uint32\n\tMaxBinaryValueBytes uint32\n\tMaxRecordsPerName   uint16\n\tMaxOperatorsPerName uint16\n\n\tPolicyRevision uint64 // bumped whenever pricing/registration rules change\n\tPaused         bool\n}\n\n// PricingConfig is the admin-settable pricing surface.\ntype PricingConfig struct {\n\tBasePricePerSecond int64\n\tPremiumByLength    map[uint8]int64\n\tPaymentDenom       string\n}\n\n// PriceQuote is returned by Price.\ntype PriceQuote struct {\n\tAmount     int64\n\tDenom      string\n\tValidUntil int64\n\tRevision   uint64\n}\n\n// RegisterRequest is the reveal payload for Register.\n//\n// The commitment the client submits via Commit MUST equal\n// sha256hex(Name|Owner|Duration|Secret|RecordsHash|PolicyRevision) using the\n// same field values. RecordsHash is an opaque client-computed hex digest of\n// the intended initial records; it binds the reveal so a front-runner cannot\n// change records. NativeAddress/SetPrimary are optional conveniences applied\n// after creation.\ntype RegisterRequest struct {\n\tName           string\n\tOwner          address\n\tDuration       int64\n\tSecret         string\n\tRecordsHash    string\n\tPolicyRevision uint64\n\n\tNativeAddress string\n\tSetPrimary    bool\n}\n\n// RegistrationResult is returned by Register.\ntype RegistrationResult struct {\n\tCanonical  string\n\tOwner      string\n\tExpiresAt  int64\n\tGeneration uint64\n\tPaid       int64\n\tRefunded   int64\n}\n\n// RenewalResult is returned by Renew.\ntype RenewalResult struct {\n\tCanonical string\n\tExpiresAt int64\n\tPaid      int64\n}\n\n// SubnameOptions configures CreateSubname.\ntype SubnameOptions struct {\n\tDuration      int64 // 0 == permanent (follows parent)\n\tControlPolicy ControlPolicy\n\tNativeAddress string\n}\n\n// RecordQuery selects which record Resolve should return.\ntype RecordQuery struct {\n\tKind string // \"address\" | \"text\" | \"coin\" | \"content\" | \"pubkey\" | \"abi\" | \"interface\" | \"record\"\n\tKey1 string // text key / coin type / abi content type / interface id / namespace\n\tKey2 string // arbitrary record key (with namespace in Key1)\n}\n\n// ResolveMode selects exact vs inherited resolution.\ntype ResolveMode int\n\nconst (\n\tExact ResolveMode = iota\n\tNearestAncestor\n)\n\n// ResolveResult is returned by Resolve.\ntype ResolveResult struct {\n\tFound      bool\n\tRequested  string\n\tSourceName string\n\tValue      []byte\n\tRevision   uint64\n\tExpiresAt  int64\n}\n\n// Event is an append-only change record for indexers.\ntype Event struct {\n\tID        uint64\n\tHeight    int64\n\tTimestamp int64\n\n\tType string\n\tName string\n\n\tActor  string\n\tOwner  string\n\tTarget string\n\n\tRevision uint64\n\n\tKey       string\n\tOldDigest string\n\tNewDigest string\n}\n\n// Event types.\nconst (\n\tEvNameRegistered    = \"NameRegistered\"\n\tEvNameRenewed       = \"NameRenewed\"\n\tEvNameTransferred   = \"NameTransferred\"\n\tEvNameExpired       = \"NameExpired\"\n\tEvNameDeleted       = \"NameDeleted\"\n\tEvSubnameCreated    = \"SubnameCreated\"\n\tEvPolicyChanged     = \"PolicyChanged\"\n\tEvOperatorChanged   = \"OperatorChanged\"\n\tEvRecordChanged     = \"RecordChanged\"\n\tEvPrimaryNameChange = \"PrimaryNameChanged\"\n\tEvConfigChanged     = \"ConfigChanged\"\n\tEvPaused            = \"Paused\"\n\tEvUnpaused          = \"Unpaused\"\n)\n\n// Paged result types (gno avoids generics; concrete types keep it simple).\ntype StringPage struct {\n\tItems []string\n\tNext  string\n}\n\ntype OperatorView struct {\n\tAddress     string\n\tPermissions Permissions\n}\n\ntype OperatorPage struct {\n\tItems []OperatorView\n\tNext  string\n}\n\ntype EventPage struct {\n\tItems []Event\n\tNext  string\n}\n\n// NameStatus mirrors the lifecycle states.\ntype NameStatus string\n\nconst (\n\tStatusAvailable NameStatus = \"Available\"\n\tStatusCommitted NameStatus = \"Committed\"\n\tStatusActive    NameStatus = \"Active\"\n\tStatusGrace     NameStatus = \"Grace\"\n\tStatusExpired   NameStatus = \"Expired\"\n\tStatusDeleted   NameStatus = \"Deleted\"\n\tStatusReserved  NameStatus = \"Reserved\"\n)\n\n// CommitmentView is the read projection of a pending commitment.\ntype CommitmentView struct {\n\tExists    bool\n\tCommitter string\n\tCreatedAt int64\n\tReadyAt   int64\n\tExpiresAt int64\n}\n\n// commitment is the stored commit record.\ntype commitment struct {\n\tCommitter address\n\tCreatedAt int64\n}\n\n// ---------------------------------------------------------------------------\n// 4. Persistent state\n// ---------------------------------------------------------------------------\n\nvar (\n\tconfig      Config\n\tnames       = avl.NewTree() // canonical -\u003e *Name\n\tcommitments = avl.NewTree() // commitment hex -\u003e *commitment\n\treverse     = avl.NewTree() // address string -\u003e canonical (primary name)\n\tevents      = avl.NewTree() // zero-padded id -\u003e *Event\n\tbyOwner     = avl.NewTree() // \"owner|canonical\" -\u003e canonical\n\tbyParent    = avl.NewTree() // \"parent|canonical\" -\u003e canonical\n\tnextEventID uint64\n)\n\n// ---------------------------------------------------------------------------\n// 5. Initialization\n// ---------------------------------------------------------------------------\n\nfunc init() {\n\tdeployer := unsafe.OriginCaller()\n\tconfig = Config{\n\t\tAdmin:            deployer,\n\t\tRegistrationOpen: true,\n\n\t\tMinCommitAge: 60,        // 1 minute\n\t\tMaxCommitAge: 24 * 3600, // 1 day\n\n\t\tMinRegistrationDuration: 28 * 24 * 3600,       // 28 days\n\t\tMaxRegistrationDuration: 10 * 365 * 24 * 3600, // 10 years\n\n\t\tGracePeriod: 90 * 24 * 3600, // 90 days\n\n\t\tBasePricePerSecond: 1, // 1 ugnot / second (deterministic, boring)\n\t\tPremiumByLength: map[uint8]int64{\n\t\t\t1: 100,\n\t\t\t2: 25,\n\t\t\t3: 5,\n\t\t\t4: 2,\n\t\t},\n\n\t\tPaymentDenom: \"ugnot\",\n\t\tTreasury:     deployer,\n\n\t\tMaxTextValueBytes:   4096,\n\t\tMaxBinaryValueBytes: 8192,\n\t\tMaxRecordsPerName:   128,\n\t\tMaxOperatorsPerName: 32,\n\n\t\tPolicyRevision: 1,\n\t\tPaused:         false,\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// 6. Normalization\n// ---------------------------------------------------------------------------\n\n// Normalize canonicalizes a name: lowercases ASCII, validates every label, and\n// enforces length/depth limits. Non-ASCII input is rejected outright.\nfunc Normalize(name string) (string, error) {\n\tif name == \"\" {\n\t\treturn \"\", errInvalidName\n\t}\n\tif len(name) \u003e maxNameLen {\n\t\treturn \"\", errInvalidName\n\t}\n\tlower := strings.ToLower(name)\n\t// reject non-ASCII (ToLower only folds ASCII deterministically for us; any\n\t// byte \u003e= 0x80 is disallowed)\n\tfor i := 0; i \u003c len(lower); i++ {\n\t\tif lower[i] \u003e= 0x80 {\n\t\t\treturn \"\", errInvalidName\n\t\t}\n\t}\n\tlabels := strings.Split(lower, \".\")\n\tif len(labels) \u003e maxDepth {\n\t\treturn \"\", errInvalidName\n\t}\n\tfor _, l := range labels {\n\t\tif err := validateLabel(l); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn lower, nil\n}\n\nfunc validateLabel(l string) error {\n\tn := len(l)\n\tif n \u003c 1 || n \u003e maxLabelLen {\n\t\treturn errInvalidLabel\n\t}\n\tfor i := 0; i \u003c n; i++ {\n\t\tc := l[i]\n\t\tisDigit := c \u003e= '0' \u0026\u0026 c \u003c= '9'\n\t\tisAlpha := c \u003e= 'a' \u0026\u0026 c \u003c= 'z'\n\t\tisHyphen := c == '-'\n\t\tif !isDigit \u0026\u0026 !isAlpha \u0026\u0026 !isHyphen {\n\t\t\treturn errInvalidLabel\n\t\t}\n\t\tif isHyphen \u0026\u0026 (i == 0 || i == n-1) {\n\t\t\treturn errInvalidLabel // no leading/trailing hyphen\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc mustNormalize(name string) string {\n\tc, err := Normalize(name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n\n// splitLabel returns (label, parent) for a canonical name.\nfunc splitLabel(canonical string) (string, string) {\n\ti := strings.Index(canonical, \".\")\n\tif i \u003c 0 {\n\t\treturn canonical, \"\"\n\t}\n\treturn canonical[:i], canonical[i+1:]\n}\n\nfunc depthOf(canonical string) uint8 {\n\treturn uint8(strings.Count(canonical, \".\") + 1)\n}\n\n// ---------------------------------------------------------------------------\n// 7. Hashing\n// ---------------------------------------------------------------------------\n\n// MakeCommitment is the public helper clients use to derive the commitment\n// hex to pass to Commit. It normalizes the name first so the value matches what\n// Register recomputes at reveal. Returns an error if the name is invalid.\nfunc MakeCommitment(name string, owner address, duration int64, secret, recordsHash string, policyRevision uint64) (string, error) {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn computeCommitment(canonical, owner, duration, secret, recordsHash, policyRevision), nil\n}\n\n// computeCommitment derives the canonical commitment hex string. Clients MUST\n// compute it identically (see RegisterRequest docs).\nfunc computeCommitment(name string, owner address, duration int64, secret, recordsHash string, policyRev uint64) string {\n\tpreimage := name + sep + owner.String() + sep + strconv.FormatInt(duration, 10) + sep + secret + sep + recordsHash + sep + strconv.FormatUint(policyRev, 10)\n\tsum := sha256.Sum256([]byte(preimage))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// digest returns a short hex digest of a byte value, for event payloads (never\n// store full record values in events).\nfunc digest(b []byte) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\tsum := sha256.Sum256(b)\n\treturn hex.EncodeToString(sum[:])[:16]\n}\n\nfunc digestStr(s string) string { return digest([]byte(s)) }\n\n// ---------------------------------------------------------------------------\n// 8. Time and lifecycle\n// ---------------------------------------------------------------------------\n\nfunc now() int64    { return time.Now().Unix() }\nfunc height() int64 { return runtime.ChainHeight() }\n\n// statusOf computes the lifecycle status of a (possibly nil) name.\nfunc statusOf(n *Name) NameStatus {\n\tif n == nil {\n\t\treturn StatusAvailable\n\t}\n\tif n.Deleted {\n\t\treturn StatusDeleted\n\t}\n\tif n.Reserved \u0026\u0026 n.Owner == (address(\"\")) {\n\t\treturn StatusReserved\n\t}\n\tif !parentChainValid(n) {\n\t\treturn StatusExpired\n\t}\n\tt := now()\n\tif n.ExpiresAt == 0 { // permanent subname; valid while ancestors valid\n\t\treturn StatusActive\n\t}\n\tif t \u003c n.ExpiresAt {\n\t\treturn StatusActive\n\t}\n\tif t \u003c n.GraceEndsAt {\n\t\treturn StatusGrace\n\t}\n\treturn StatusExpired\n}\n\nfunc isActive(n *Name) bool { return statusOf(n) == StatusActive }\n\n// parentChainValid verifies every ancestor exists, is active, and matches the\n// stored ParentGeneration (recycling safety, invariant 16 \u0026 recycling).\nfunc parentChainValid(n *Name) bool {\n\tif n.Parent == \"\" {\n\t\treturn true\n\t}\n\tp := getRaw(n.Parent)\n\tif p == nil || p.Deleted {\n\t\treturn false\n\t}\n\tif n.ParentGeneration != p.Generation {\n\t\treturn false\n\t}\n\t// parent must itself be active (not grace/expired) and its own chain valid\n\tif p.ExpiresAt != 0 {\n\t\tt := now()\n\t\tif t \u003e= p.ExpiresAt {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn parentChainValid(p)\n}\n\n// available reports whether a name may be registered now.\nfunc available(canonical string) bool {\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\treturn true\n\t}\n\tif n.Reserved {\n\t\treturn false\n\t}\n\tswitch statusOf(n) {\n\tcase StatusExpired, StatusDeleted:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// 9. Pricing\n// ---------------------------------------------------------------------------\n\nfunc lengthMultiplier(label string) int64 {\n\tl := uint8(len(label))\n\tif m, ok := config.PremiumByLength[l]; ok {\n\t\treturn m\n\t}\n\treturn 1\n}\n\n// priceFor computes the deterministic, overflow-checked price.\nfunc priceFor(canonical string, duration int64) (int64, error) {\n\tif duration \u003c= 0 {\n\t\treturn 0, errDurationTooShort\n\t}\n\tlabel, _ := splitLabel(canonical)\n\tmult := lengthMultiplier(label)\n\tbase := config.BasePricePerSecond\n\t// price = duration * base * mult, checked for overflow at each step.\n\tp := duration\n\tvar err error\n\tif p, err = mulChecked(p, base); err != nil {\n\t\treturn 0, err\n\t}\n\tif p, err = mulChecked(p, mult); err != nil {\n\t\treturn 0, err\n\t}\n\treturn p, nil\n}\n\nfunc mulChecked(a, b int64) (int64, error) {\n\tif a == 0 || b == 0 {\n\t\treturn 0, nil\n\t}\n\tc := a * b\n\tif c/b != a || c \u003c 0 {\n\t\treturn 0, errRecordTooLarge // reuse as overflow marker; documented\n\t}\n\treturn c, nil\n}\n\n// Price returns a price quote for registering/renewing name for duration.\nfunc Price(name string, duration int64) (PriceQuote, error) {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn PriceQuote{}, err\n\t}\n\tamt, err := priceFor(canonical, duration)\n\tif err != nil {\n\t\treturn PriceQuote{}, err\n\t}\n\treturn PriceQuote{\n\t\tAmount:     amt,\n\t\tDenom:      config.PaymentDenom,\n\t\tValidUntil: now() + config.MaxCommitAge,\n\t\tRevision:   config.PolicyRevision,\n\t}, nil\n}\n\n// ---------------------------------------------------------------------------\n// 10. Authorization\n// ---------------------------------------------------------------------------\n\n// caller authenticates a crossing frame and returns the immediate caller.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(errSpoofedRealm)\n\t}\n\treturn cur.Previous().Address()\n}\n\n// callerUser authenticates and requires an end-user (EOA) caller.\nfunc callerUser(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(errSpoofedRealm)\n\t}\n\tprev := cur.Previous()\n\tif !prev.IsUser() {\n\t\tpanic(errNotUser)\n\t}\n\treturn prev.Address()\n}\n\n// authorize is the single gate for all name mutations. Authority order:\n//  1. admin — NOT here (admin has no routine power over user names);\n//  2. direct owner of an active name;\n//  3. active operator with the matching permission;\n//  4. parent authority, when the child policy allows.\nfunc authorize(callerAddr address, n *Name, perm Permission) error {\n\tif n == nil {\n\t\treturn errNotFound\n\t}\n\t// (2) direct owner, but only while active (invariant 2).\n\tif n.Owner == callerAddr \u0026\u0026 isActive(n) {\n\t\treturn nil\n\t}\n\t// (3) operator\n\tif op, ok := getOperator(n, callerAddr); ok \u0026\u0026 isActive(n) {\n\t\tif op.has(perm) \u0026\u0026 (op.ExpiresAt == 0 || op.ExpiresAt \u003e now()) {\n\t\t\treturn nil\n\t\t}\n\t}\n\t// (4) parent authority\n\tif parentAuthorized(callerAddr, n, perm) {\n\t\treturn nil\n\t}\n\treturn errUnauthorized\n}\n\nfunc mustAuthorize(callerAddr address, n *Name, perm Permission) {\n\tif err := authorize(callerAddr, n, perm); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// parentAuthorized checks whether callerAddr controls the parent AND the\n// child's policy grants the parent that specific power.\nfunc parentAuthorized(callerAddr address, n *Name, perm Permission) bool {\n\tif n.Parent == \"\" {\n\t\treturn false\n\t}\n\tp := getRaw(n.Parent)\n\tif p == nil || !isActive(p) {\n\t\treturn false\n\t}\n\t// caller must control the parent (owner or ManageSubnames operator)\n\tcontrols := p.Owner == callerAddr\n\tif !controls {\n\t\tif op, ok := getOperator(p, callerAddr); ok \u0026\u0026 op.ManageSubnames {\n\t\t\tcontrols = true\n\t\t}\n\t}\n\tif !controls {\n\t\treturn false\n\t}\n\tcp := n.ControlPolicy\n\tswitch perm {\n\tcase PermTransfer:\n\t\treturn cp.ParentCanTransfer || cp.ParentCanReclaim\n\tcase PermManagePolicy:\n\t\treturn cp.ParentCanChangePolicy\n\t}\n\treturn false\n}\n\n// ---------------------------------------------------------------------------\n// 11. Registration\n// ---------------------------------------------------------------------------\n\n// Commit stores a registration commitment. The commitment hides the intended\n// name; only its hash is recorded together with the committer and timestamp.\nfunc Commit(cur realm, commit string) {\n\trequireNotPaused()\n\tc := callerUser(cur)\n\tif commit == \"\" {\n\t\tpanic(errBadRequest)\n\t}\n\tif existing, ok := getCommitment(commit); ok {\n\t\t// reject only if the existing commitment is still within its usable\n\t\t// window; stale ones may be overwritten.\n\t\tif now()-existing.CreatedAt \u003c= config.MaxCommitAge {\n\t\t\tpanic(errCommitmentMismatch)\n\t\t}\n\t}\n\tcommitments.Set(commit, \u0026commitment{Committer: c, CreatedAt: now()})\n}\n\n// Register reveals and consumes a commitment to create a second-level name.\nfunc Register(cur realm, request RegisterRequest) RegistrationResult {\n\trequireNotPaused()\n\tc := callerUser(cur)\n\n\tif !config.RegistrationOpen {\n\t\tpanic(errRegistrationClosed)\n\t}\n\tcanonical, err := Normalize(request.Name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// second-level only (no dots) via Register; subnames use CreateSubname.\n\tif strings.Contains(canonical, \".\") {\n\t\tpanic(errInvalidName)\n\t}\n\tif request.PolicyRevision != config.PolicyRevision {\n\t\tpanic(errPriceChanged)\n\t}\n\tif !request.Owner.IsValid() {\n\t\tpanic(errEmptyAddress)\n\t}\n\n\t// commitment checks\n\tkey := computeCommitment(canonical, request.Owner, request.Duration, request.Secret, request.RecordsHash, request.PolicyRevision)\n\tcm, ok := getCommitment(key)\n\tif !ok {\n\t\tpanic(errCommitmentMissing)\n\t}\n\tif cm.Committer != c {\n\t\tpanic(errUnauthorized)\n\t}\n\tage := now() - cm.CreatedAt\n\tif age \u003c config.MinCommitAge {\n\t\tpanic(errCommitmentTooNew)\n\t}\n\tif age \u003e config.MaxCommitAge {\n\t\tpanic(errCommitmentExpired)\n\t}\n\n\t// availability + duration\n\tif !available(canonical) {\n\t\texisting := getRaw(canonical)\n\t\tswitch statusOf(existing) {\n\t\tcase StatusReserved:\n\t\t\tpanic(errNameReserved)\n\t\tcase StatusGrace:\n\t\t\tpanic(errNameInGrace)\n\t\tdefault:\n\t\t\tpanic(errNameUnavailable)\n\t\t}\n\t}\n\tif request.Duration \u003c config.MinRegistrationDuration {\n\t\tpanic(errDurationTooShort)\n\t}\n\tif request.Duration \u003e config.MaxRegistrationDuration {\n\t\tpanic(errDurationTooLong)\n\t}\n\n\tprice, err := priceFor(canonical, request.Duration)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpaid, refunded := collectPayment(cur, price)\n\n\t// build/recycle the name\n\tprev := getRaw(canonical)\n\tvar gen uint64 = 1\n\tif prev != nil {\n\t\tgen = prev.Generation + 1 // recycle: increment generation\n\t}\n\tt := now()\n\tlabel, parent := splitLabel(canonical)\n\tn := \u0026Name{\n\t\tCanonical:  canonical,\n\t\tOwner:      request.Owner,\n\t\tCreatedAt:  t,\n\t\tUpdatedAt:  t,\n\t\tExpiresAt:  t + request.Duration,\n\t\tParent:     parent,\n\t\tLabel:      label,\n\t\tDepth:      depthOf(canonical),\n\t\tGeneration: gen,\n\t\tRevision:   1,\n\t\tRecords:    newRecords(),\n\t\tOperators:  avl.NewTree(),\n\t\tControlPolicy: ControlPolicy{\n\t\t\tOwnerCanTransfer:       true,\n\t\t\tOwnerCanCreateSubnames: true,\n\t\t\tRecordsMutable:         true,\n\t\t},\n\t\tRegistrationPolicy: RegistrationPolicy{Mode: ModeClosed},\n\t}\n\tn.GraceEndsAt = n.ExpiresAt + config.GracePeriod\n\n\t// clear any stale owner index from a previous generation before storing.\n\tif prev != nil {\n\t\tbyOwner.Remove(ownerKey(prev.Owner, canonical))\n\t}\n\tputName(n)\n\n\t// optional convenience records\n\tif request.NativeAddress != \"\" {\n\t\tsetNativeAddressInternal(n, request.NativeAddress)\n\t}\n\tif request.SetPrimary \u0026\u0026 request.NativeAddress != \"\" \u0026\u0026 address(request.NativeAddress) == c {\n\t\treverse.Set(c.String(), canonical)\n\t\temit(EvPrimaryNameChange, canonical, c, n.Owner, \"\")\n\t}\n\n\tcommitments.Remove(key)\n\temitOwner(EvNameRegistered, n)\n\n\treturn RegistrationResult{\n\t\tCanonical:  canonical,\n\t\tOwner:      n.Owner.String(),\n\t\tExpiresAt:  n.ExpiresAt,\n\t\tGeneration: n.Generation,\n\t\tPaid:       paid,\n\t\tRefunded:   refunded,\n\t}\n}\n\n// collectPayment reads the attached ugnot, requires it to cover price, and\n// forwards price to the treasury while refunding any overpayment.\nfunc collectPayment(cur realm, price int64) (paid, refunded int64) {\n\tif price \u003c= 0 {\n\t\treturn 0, 0\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(errNotUser)\n\t}\n\tsent := unsafe.OriginSend()\n\tgot := sent.AmountOf(config.PaymentDenom)\n\tif got \u003c price {\n\t\tpanic(errInsufficientPay)\n\t}\n\tbk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tself := cur.Address()\n\t// forward the price to the treasury\n\tif config.Treasury != self {\n\t\tbk.SendCoins(self, config.Treasury, coins(config.PaymentDenom, price))\n\t}\n\t// refund the remainder to the caller\n\tover := got - price\n\tif over \u003e 0 {\n\t\tbk.SendCoins(self, cur.Previous().Address(), coins(config.PaymentDenom, over))\n\t}\n\treturn price, over\n}\n\n// ---------------------------------------------------------------------------\n// 12. Renewal and expiry\n// ---------------------------------------------------------------------------\n\n// Renew extends a name's expiry. Anyone may pay to renew (a socially useful\n// property: third parties can prevent expiry but gain no authority). Renewal\n// is allowed while Active or in Grace, never once fully Expired.\nfunc Renew(cur realm, name string, duration int64) RenewalResult {\n\trequireNotPaused()\n\t_ = caller(cur) // authenticate frame; no authority needed to sponsor renewal\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil || n.Deleted {\n\t\tpanic(errNotFound)\n\t}\n\tst := statusOf(n)\n\tif st != StatusActive \u0026\u0026 st != StatusGrace {\n\t\tpanic(errNameExpired)\n\t}\n\tif n.ExpiresAt == 0 {\n\t\tpanic(errBadRequest) // permanent subname has no independent expiry\n\t}\n\tif duration \u003c= 0 {\n\t\tpanic(errDurationTooShort)\n\t}\n\n\t// new expiry base: max(now, current expiry) so grace renewals extend from\n\t// the original expiry, active renewals from current expiry.\n\tbase := n.ExpiresAt\n\tif st == StatusGrace {\n\t\t// during grace, extend from now to avoid free grace time abuse\n\t\tbase = n.ExpiresAt\n\t}\n\tnewExpiry := base + duration\n\t// enforce the maximum expiry horizon (invariant 11).\n\tmaxHorizon := now() + config.MaxRegistrationDuration\n\tif newExpiry \u003e maxHorizon {\n\t\tpanic(errDurationTooLong)\n\t}\n\n\tprice, err := priceFor(canonical, duration)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpaid, _ := collectPayment(cur, price)\n\n\tn.ExpiresAt = newExpiry\n\tn.GraceEndsAt = newExpiry + config.GracePeriod\n\tn.UpdatedAt = now()\n\tn.Revision++\n\tputName(n)\n\temitOwner(EvNameRenewed, n)\n\n\treturn RenewalResult{Canonical: canonical, ExpiresAt: n.ExpiresAt, Paid: paid}\n}\n\n// ---------------------------------------------------------------------------\n// 13. Ownership\n// ---------------------------------------------------------------------------\n\n// Transfer moves ownership of a name.\nfunc Transfer(cur realm, name string, newOwner address, clearOperators, clearRecords bool) {\n\trequireNotPaused()\n\tc := caller(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\tpanic(errNotFound)\n\t}\n\tif !newOwner.IsValid() {\n\t\tpanic(errEmptyAddress)\n\t}\n\tif newOwner == n.Owner {\n\t\tpanic(errBadRequest) // self-transfer rejected (cleaner than no-op)\n\t}\n\t// owner path additionally requires the policy to allow transfer.\n\tif c == n.Owner \u0026\u0026 isActive(n) {\n\t\tif !n.ControlPolicy.OwnerCanTransfer {\n\t\t\tpanic(errPolicyLocked)\n\t\t}\n\t} else {\n\t\tmustAuthorize(c, n, PermTransfer)\n\t}\n\n\told := n.Owner\n\tbyOwner.Remove(ownerKey(old, canonical))\n\n\tn.Owner = newOwner\n\tn.Revision++\n\tn.UpdatedAt = now()\n\tif clearOperators {\n\t\tn.Operators = avl.NewTree()\n\t\tn.OperatorCount = 0\n\t}\n\tif clearRecords {\n\t\tn.Records = newRecords()\n\t}\n\tputName(n)\n\n\t// invalidate reverse mappings that no longer pass forward verification.\n\tinvalidateReverseFor(old, canonical)\n\n\temit(EvNameTransferred, canonical, c, newOwner, old.String())\n}\n\n// ---------------------------------------------------------------------------\n// 14. Subnames and policy\n// ---------------------------------------------------------------------------\n\n// CreateSubname creates label.parent according to the parent registration\n// policy.\nfunc CreateSubname(cur realm, parent string, label string, owner address, options SubnameOptions) {\n\trequireNotPaused()\n\tc := callerUser(cur)\n\n\tpcanon := mustNormalize(parent)\n\tif err := validateLabel(strings.ToLower(label)); err != nil {\n\t\tpanic(err)\n\t}\n\tlabel = strings.ToLower(label)\n\tcanonical := label + \".\" + pcanon\n\tif len(canonical) \u003e maxNameLen {\n\t\tpanic(errInvalidName)\n\t}\n\tif depthOf(canonical) \u003e maxDepth {\n\t\tpanic(errInvalidName)\n\t}\n\n\tp := getRaw(pcanon)\n\tif p == nil || !isActive(p) {\n\t\tpanic(errParentInvalid)\n\t}\n\tif !owner.IsValid() {\n\t\tpanic(errEmptyAddress)\n\t}\n\tif !available(canonical) {\n\t\tpanic(errNameUnavailable)\n\t}\n\n\tpol := p.RegistrationPolicy\n\t// authorize + charge according to policy mode.\n\tswitch pol.Mode {\n\tcase ModeClosed, \"\":\n\t\tpanic(errRegistrationClosed)\n\tcase ModeOwner:\n\t\tmustAuthorize(c, p, PermManageSubnames)\n\tcase ModeOpen:\n\t\t// anyone\n\tcase ModeAllowlist:\n\t\tif pol.Allowlist == nil || !allowlistHas(pol.Allowlist, c) {\n\t\t\tpanic(errUnauthorized)\n\t\t}\n\tcase ModePaid:\n\t\tcharge := int64(0)\n\t\tif pol.PricePerSecond \u003e 0 \u0026\u0026 options.Duration \u003e 0 {\n\t\t\tvar err error\n\t\t\tif charge, err = mulChecked(pol.PricePerSecond, options.Duration); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tdenom := pol.PaymentDenom\n\t\tif denom == \"\" {\n\t\t\tdenom = config.PaymentDenom\n\t\t}\n\t\tcollectPaymentDenom(cur, charge, denom, p.Owner)\n\tdefault:\n\t\tpanic(errBadRequest)\n\t}\n\n\tt := now()\n\tprev := getRaw(canonical)\n\tvar gen uint64 = 1\n\tif prev != nil {\n\t\tgen = prev.Generation + 1\n\t\tbyOwner.Remove(ownerKey(prev.Owner, canonical))\n\t}\n\tcpol := options.ControlPolicy\n\tif (cpol == ControlPolicy{}) {\n\t\tcpol = pol.DefaultControlPolicy\n\t}\n\tn := \u0026Name{\n\t\tCanonical:          canonical,\n\t\tOwner:              owner,\n\t\tCreatedAt:          t,\n\t\tUpdatedAt:          t,\n\t\tParent:             pcanon,\n\t\tLabel:              label,\n\t\tDepth:              depthOf(canonical),\n\t\tGeneration:         gen,\n\t\tParentGeneration:   p.Generation,\n\t\tRevision:           1,\n\t\tRecords:            newRecords(),\n\t\tOperators:          avl.NewTree(),\n\t\tControlPolicy:      cpol,\n\t\tRegistrationPolicy: RegistrationPolicy{Mode: ModeClosed},\n\t}\n\tif options.Duration \u003e 0 {\n\t\tn.ExpiresAt = t + options.Duration\n\t\tn.GraceEndsAt = n.ExpiresAt + config.GracePeriod\n\t} // else permanent (ExpiresAt == 0)\n\n\tputName(n)\n\tif options.NativeAddress != \"\" {\n\t\tsetNativeAddressInternal(n, options.NativeAddress)\n\t}\n\temit(EvSubnameCreated, canonical, c, owner, pcanon)\n}\n\n// DeleteSubname removes a subname. Callable by the owner, or by the parent when\n// ParentCanDelete is set.\nfunc DeleteSubname(cur realm, name string) {\n\trequireNotPaused()\n\tc := caller(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil || n.Deleted {\n\t\tpanic(errNotFound)\n\t}\n\tif n.Parent == \"\" {\n\t\tpanic(errBadRequest) // not a subname\n\t}\n\tauthorized := false\n\tif c == n.Owner \u0026\u0026 isActive(n) {\n\t\tauthorized = true\n\t} else if p := getRaw(n.Parent); p != nil \u0026\u0026 isActive(p) \u0026\u0026 n.ControlPolicy.ParentCanDelete {\n\t\tif p.Owner == c {\n\t\t\tauthorized = true\n\t\t} else if op, ok := getOperator(p, c); ok \u0026\u0026 op.ManageSubnames {\n\t\t\tauthorized = true\n\t\t}\n\t}\n\tif !authorized {\n\t\tpanic(errUnauthorized)\n\t}\n\tdeleteName(n)\n\temit(EvNameDeleted, canonical, c, n.Owner, \"\")\n}\n\n// SetRegistrationPolicy sets the subname-issuance policy for a name.\nfunc SetRegistrationPolicy(cur realm, name string, policy RegistrationPolicy) {\n\trequireNotPaused()\n\tc := caller(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\tpanic(errNotFound)\n\t}\n\tif c == n.Owner \u0026\u0026 isActive(n) {\n\t\tif !n.ControlPolicy.OwnerCanCreateSubnames \u0026\u0026 policy.Mode != ModeClosed {\n\t\t\tpanic(errPolicyLocked)\n\t\t}\n\t} else {\n\t\tmustAuthorize(c, n, PermManagePolicy)\n\t}\n\tn.RegistrationPolicy = policy\n\tn.UpdatedAt = now()\n\tn.Revision++\n\tputName(n)\n\temit(EvPolicyChanged, canonical, c, n.Owner, \"registration\")\n}\n\n// LockPolicy makes a name's control policy strictly more restrictive\n// (emancipation). Flags may only move true-\u003efalse; once Permanent, no field\n// may be relaxed. Only the owner may lock.\nfunc LockPolicy(cur realm, name string, restrictions ControlPolicy) {\n\trequireNotPaused()\n\tc := caller(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\tpanic(errNotFound)\n\t}\n\tif c != n.Owner || !isActive(n) {\n\t\tpanic(errUnauthorized)\n\t}\n\tcur0 := n.ControlPolicy\n\tif cur0.Permanent \u0026\u0026 !restrictions.Permanent {\n\t\tpanic(errPolicyLocked)\n\t}\n\tnext := mergeRestrictive(cur0, restrictions)\n\tn.ControlPolicy = next\n\tn.UpdatedAt = now()\n\tn.Revision++\n\tputName(n)\n\temit(EvPolicyChanged, canonical, c, n.Owner, \"control\")\n}\n\n// mergeRestrictive returns a policy where each boolean can only go from\n// permissive (true) to restrictive (false); Permanent can only be turned on.\nfunc mergeRestrictive(cur, req ControlPolicy) ControlPolicy {\n\tandRestrict := func(cur, req bool) bool { return cur \u0026\u0026 req }\n\treturn ControlPolicy{\n\t\tOwnerCanTransfer:       andRestrict(cur.OwnerCanTransfer, req.OwnerCanTransfer),\n\t\tOwnerCanCreateSubnames: andRestrict(cur.OwnerCanCreateSubnames, req.OwnerCanCreateSubnames),\n\t\tRecordsMutable:         andRestrict(cur.RecordsMutable, req.RecordsMutable),\n\t\tParentCanReclaim:       andRestrict(cur.ParentCanReclaim, req.ParentCanReclaim),\n\t\tParentCanTransfer:      andRestrict(cur.ParentCanTransfer, req.ParentCanTransfer),\n\t\tParentCanDelete:        andRestrict(cur.ParentCanDelete, req.ParentCanDelete),\n\t\tParentCanChangePolicy:  andRestrict(cur.ParentCanChangePolicy, req.ParentCanChangePolicy),\n\t\tPermanent:              cur.Permanent || req.Permanent,\n\t}\n}\n\n// SetOperator grants (or updates) an operator's permissions on a name.\nfunc SetOperator(cur realm, name string, operator address, permissions Permissions) {\n\trequireNotPaused()\n\tc := caller(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\tpanic(errNotFound)\n\t}\n\tmustAuthorizeOwnerOrOp(c, n, PermManageOperators)\n\tif !operator.IsValid() {\n\t\tpanic(errEmptyAddress)\n\t}\n\t_, existed := getOperator(n, operator)\n\tif !existed {\n\t\tif int(config.MaxOperatorsPerName) \u003e 0 \u0026\u0026 n.OperatorCount \u003e= int(config.MaxOperatorsPerName) {\n\t\t\tpanic(errOperatorLimit)\n\t\t}\n\t\tn.OperatorCount++\n\t}\n\tn.Operators.Set(operator.String(), permissions)\n\tn.UpdatedAt = now()\n\tn.Revision++\n\tputName(n)\n\temit(EvOperatorChanged, canonical, c, operator, \"set\")\n}\n\n// RemoveOperator revokes an operator.\nfunc RemoveOperator(cur realm, name string, operator address) {\n\trequireNotPaused()\n\tc := caller(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\tpanic(errNotFound)\n\t}\n\tmustAuthorizeOwnerOrOp(c, n, PermManageOperators)\n\tif _, removed := n.Operators.Remove(operator.String()); removed {\n\t\tn.OperatorCount--\n\t\tn.UpdatedAt = now()\n\t\tn.Revision++\n\t\tputName(n)\n\t\temit(EvOperatorChanged, canonical, c, operator, \"remove\")\n\t}\n}\n\n// mustAuthorizeOwnerOrOp allows the active owner directly or an operator with\n// the given permission (used for record/operator management).\nfunc mustAuthorizeOwnerOrOp(c address, n *Name, perm Permission) {\n\tif c == n.Owner \u0026\u0026 isActive(n) {\n\t\treturn\n\t}\n\tif op, ok := getOperator(n, c); ok \u0026\u0026 isActive(n) \u0026\u0026 op.has(perm) \u0026\u0026 (op.ExpiresAt == 0 || op.ExpiresAt \u003e now()) {\n\t\treturn\n\t}\n\tpanic(errUnauthorized)\n}\n\n// ---------------------------------------------------------------------------\n// 15. Records\n// ---------------------------------------------------------------------------\n\nfunc requireRecordsMutable(n *Name) {\n\tif !n.ControlPolicy.RecordsMutable {\n\t\tpanic(errPolicyLocked)\n\t}\n\t// records may not be mutated during grace (spec: normal updates disabled in\n\t// grace, except clearing reverse).\n\tif statusOf(n) != StatusActive {\n\t\tpanic(errNameExpired)\n\t}\n}\n\nfunc bumpRecords(n *Name) {\n\tn.UpdatedAt = now()\n\tn.Revision++\n\tputName(n)\n}\n\nfunc (n *Name) recordCountGuard(added int) {\n\tif config.MaxRecordsPerName \u003e 0 \u0026\u0026 n.Records.Count+added \u003e int(config.MaxRecordsPerName) {\n\t\tpanic(errRecordLimit)\n\t}\n}\n\n// recordMutation is the shared preamble for every typed record setter: pause\n// gate, caller authentication, name resolution, record-management authority,\n// and records-mutable check. Returns the name and the caller address.\nfunc recordMutation(cur realm, name string) (*Name, address) {\n\trequireNotPaused()\n\tc := caller(cur)\n\tn := mustName(name)\n\tmustAuthorizeOwnerOrOp(c, n, PermManageRecords)\n\trequireRecordsMutable(n)\n\treturn n, c\n}\n\n// SetAddress sets the native address record.\nfunc SetAddress(cur realm, name string, addr string) {\n\tn, c := recordMutation(cur, name)\n\tif addr != \"\" \u0026\u0026 !address(addr).IsValid() {\n\t\tpanic(errEmptyAddress)\n\t}\n\tsetNativeAddressInternal(n, addr)\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"addr\", digestStr(addr))\n}\n\nfunc setNativeAddressInternal(n *Name, addr string) {\n\tn.Records.NativeAddress = addr\n}\n\n// Address returns the native address record.\nfunc Address(name string) (string, bool) {\n\tn := resolvableName(name)\n\tif n == nil || n.Records.NativeAddress == \"\" {\n\t\treturn \"\", false\n\t}\n\treturn n.Records.NativeAddress, true\n}\n\n// SetCoinAddress sets a multichain address for coinType (decimal string).\nfunc SetCoinAddress(cur realm, name string, coinType string, value []byte) {\n\tn, c := recordMutation(cur, name)\n\tguardBinary(value)\n\tif !n.Records.Addresses.Has(coinType) {\n\t\tn.recordCountGuard(1)\n\t\tn.Records.Count++\n\t}\n\tn.Records.Addresses.Set(coinType, value)\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"coin:\"+coinType, digest(value))\n}\n\n// CoinAddress returns a multichain address.\nfunc CoinAddress(name string, coinType string) ([]byte, bool) {\n\tn := resolvableName(name)\n\tif n == nil {\n\t\treturn nil, false\n\t}\n\tif v, ok := treeGet(n.Records.Addresses, coinType); ok {\n\t\treturn v.([]byte), true\n\t}\n\treturn nil, false\n}\n\n// SetText sets a text record; empty value deletes it (physical removal).\nfunc SetText(cur realm, name string, key string, value string) {\n\tn, c := recordMutation(cur, name)\n\tif key == \"\" {\n\t\tpanic(errBadRequest)\n\t}\n\tif value == \"\" {\n\t\tif _, removed := n.Records.Text.Remove(key); removed {\n\t\t\tn.Records.Count--\n\t\t\tbumpRecords(n)\n\t\t\temitRecord(EvRecordChanged, n, c, \"text:\"+key, \"\")\n\t\t}\n\t\treturn\n\t}\n\tif uint32(len(value)) \u003e config.MaxTextValueBytes {\n\t\tpanic(errRecordTooLarge)\n\t}\n\tif !n.Records.Text.Has(key) {\n\t\tn.recordCountGuard(1)\n\t\tn.Records.Count++\n\t}\n\tn.Records.Text.Set(key, value)\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"text:\"+key, digestStr(value))\n}\n\n// Text returns a text record.\nfunc Text(name string, key string) (string, bool) {\n\tn := resolvableName(name)\n\tif n == nil {\n\t\treturn \"\", false\n\t}\n\tif v, ok := treeGet(n.Records.Text, key); ok {\n\t\treturn v.(string), true\n\t}\n\treturn \"\", false\n}\n\n// SetContentHash sets the content hash record.\nfunc SetContentHash(cur realm, name string, value []byte) {\n\tn, c := recordMutation(cur, name)\n\tguardBinary(value)\n\tn.Records.ContentHash = value\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"content\", digest(value))\n}\n\n// ContentHash returns the content hash record.\nfunc ContentHash(name string) ([]byte, bool) {\n\tn := resolvableName(name)\n\tif n == nil || len(n.Records.ContentHash) == 0 {\n\t\treturn nil, false\n\t}\n\treturn n.Records.ContentHash, true\n}\n\n// SetPublicKey sets the public key record.\nfunc SetPublicKey(cur realm, name string, value []byte) {\n\tn, c := recordMutation(cur, name)\n\tguardBinary(value)\n\tn.Records.PublicKey = value\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"pubkey\", digest(value))\n}\n\n// PublicKey returns the public key record.\nfunc PublicKey(name string) ([]byte, bool) {\n\tn := resolvableName(name)\n\tif n == nil || len(n.Records.PublicKey) == 0 {\n\t\treturn nil, false\n\t}\n\treturn n.Records.PublicKey, true\n}\n\n// SetABI sets an ABI blob by content type.\nfunc SetABI(cur realm, name string, contentType string, value []byte) {\n\tn, c := recordMutation(cur, name)\n\tguardBinary(value)\n\tif !n.Records.ABIs.Has(contentType) {\n\t\tn.recordCountGuard(1)\n\t\tn.Records.Count++\n\t}\n\tn.Records.ABIs.Set(contentType, value)\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"abi:\"+contentType, digest(value))\n}\n\n// ABI returns an ABI blob.\nfunc ABI(name string, contentType string) ([]byte, bool) {\n\tn := resolvableName(name)\n\tif n == nil {\n\t\treturn nil, false\n\t}\n\tif v, ok := treeGet(n.Records.ABIs, contentType); ok {\n\t\treturn v.([]byte), true\n\t}\n\treturn nil, false\n}\n\n// SetInterface sets an interface target by interface ID.\nfunc SetInterface(cur realm, name string, interfaceID string, target string) {\n\tn, c := recordMutation(cur, name)\n\tif !n.Records.Interfaces.Has(interfaceID) {\n\t\tn.recordCountGuard(1)\n\t\tn.Records.Count++\n\t}\n\tn.Records.Interfaces.Set(interfaceID, target)\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"interface:\"+interfaceID, digestStr(target))\n}\n\n// Interface returns an interface target.\nfunc Interface(name string, interfaceID string) (string, bool) {\n\tn := resolvableName(name)\n\tif n == nil {\n\t\treturn \"\", false\n\t}\n\tif v, ok := treeGet(n.Records.Interfaces, interfaceID); ok {\n\t\treturn v.(string), true\n\t}\n\treturn \"\", false\n}\n\n// SetRecord sets an arbitrary namespaced record. Reserved namespaces are\n// rejected; use the typed setters for those.\nfunc SetRecord(cur realm, name string, namespace string, key string, value []byte) {\n\tn, c := recordMutation(cur, name)\n\tif namespace == \"\" || key == \"\" {\n\t\tpanic(errBadRequest)\n\t}\n\tif reservedNamespaces[namespace] {\n\t\tpanic(errBadRequest)\n\t}\n\tguardBinary(value)\n\tk := namespace + \"/\" + key\n\tif !n.Records.Arbitrary.Has(k) {\n\t\tn.recordCountGuard(1)\n\t\tn.Records.Count++\n\t}\n\tn.Records.Arbitrary.Set(k, value)\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"record:\"+k, digest(value))\n}\n\n// Record returns an arbitrary namespaced record.\nfunc Record(name string, namespace string, key string) ([]byte, bool) {\n\tn := resolvableName(name)\n\tif n == nil {\n\t\treturn nil, false\n\t}\n\tif v, ok := treeGet(n.Records.Arbitrary, namespace+\"/\"+key); ok {\n\t\treturn v.([]byte), true\n\t}\n\treturn nil, false\n}\n\n// SetTTL sets the name's TTL metadata.\nfunc SetTTL(cur realm, name string, ttl uint64) {\n\tn, c := recordMutation(cur, name)\n\tn.TTL = ttl\n\tbumpRecords(n)\n\temitRecord(EvRecordChanged, n, c, \"ttl\", strconv.FormatUint(ttl, 10))\n}\n\nfunc guardBinary(value []byte) {\n\tif config.MaxBinaryValueBytes \u003e 0 \u0026\u0026 uint32(len(value)) \u003e config.MaxBinaryValueBytes {\n\t\tpanic(errRecordTooLarge)\n\t}\n}\n\n// Resolve returns a record either at the exact name or from the nearest valid\n// ancestor (wildcard-style). Inheritance is explicit, never implicit in the\n// primitive getters.\nfunc Resolve(name string, query RecordQuery, mode ResolveMode) ResolveResult {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn ResolveResult{Requested: name}\n\t}\n\tcur := canonical\n\tfor {\n\t\tn := resolvableName(cur)\n\t\tif n != nil {\n\t\t\tif val, ok := lookupRecord(n, query); ok {\n\t\t\t\treturn ResolveResult{\n\t\t\t\t\tFound:      true,\n\t\t\t\t\tRequested:  canonical,\n\t\t\t\t\tSourceName: cur,\n\t\t\t\t\tValue:      val,\n\t\t\t\t\tRevision:   n.Revision,\n\t\t\t\t\tExpiresAt:  n.ExpiresAt,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif mode == Exact {\n\t\t\tbreak\n\t\t}\n\t\t_, parent := splitLabel(cur)\n\t\tif parent == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tcur = parent\n\t}\n\treturn ResolveResult{Requested: canonical}\n}\n\nfunc lookupRecord(n *Name, q RecordQuery) ([]byte, bool) {\n\tswitch q.Kind {\n\tcase \"address\":\n\t\tif n.Records.NativeAddress != \"\" {\n\t\t\treturn []byte(n.Records.NativeAddress), true\n\t\t}\n\tcase \"text\":\n\t\tif v, ok := treeGet(n.Records.Text, q.Key1); ok {\n\t\t\treturn []byte(v.(string)), true\n\t\t}\n\tcase \"coin\":\n\t\tif v, ok := treeGet(n.Records.Addresses, q.Key1); ok {\n\t\t\treturn v.([]byte), true\n\t\t}\n\tcase \"content\":\n\t\tif len(n.Records.ContentHash) \u003e 0 {\n\t\t\treturn n.Records.ContentHash, true\n\t\t}\n\tcase \"pubkey\":\n\t\tif len(n.Records.PublicKey) \u003e 0 {\n\t\t\treturn n.Records.PublicKey, true\n\t\t}\n\tcase \"abi\":\n\t\tif v, ok := treeGet(n.Records.ABIs, q.Key1); ok {\n\t\t\treturn v.([]byte), true\n\t\t}\n\tcase \"interface\":\n\t\tif v, ok := treeGet(n.Records.Interfaces, q.Key1); ok {\n\t\t\treturn []byte(v.(string)), true\n\t\t}\n\tcase \"record\":\n\t\tif v, ok := treeGet(n.Records.Arbitrary, q.Key1+\"/\"+q.Key2); ok {\n\t\t\treturn v.([]byte), true\n\t\t}\n\t}\n\treturn nil, false\n}\n\n// ---------------------------------------------------------------------------\n// 16. Reverse resolution and primary names\n// ---------------------------------------------------------------------------\n\n// SetPrimaryName sets the caller's primary (reverse) name. The name must be\n// active and forward-resolve (Address) to the caller.\nfunc SetPrimaryName(cur realm, name string) {\n\trequireNotPaused()\n\tc := callerUser(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil || !isActive(n) {\n\t\tpanic(errNotFound)\n\t}\n\tif n.Records.NativeAddress != c.String() {\n\t\tpanic(errUnauthorized)\n\t}\n\treverse.Set(c.String(), canonical)\n\temit(EvPrimaryNameChange, canonical, c, n.Owner, \"\")\n}\n\n// PrimaryName returns the verified primary name for an address, checking that\n// (1) a reverse record exists, (2) the name is active, and (3) forward\n// resolution still matches. Any failure returns not-found.\nfunc PrimaryName(addr string) (string, bool) {\n\tv, ok := treeGet(reverse, addr)\n\tif !ok {\n\t\treturn \"\", false\n\t}\n\tcanonical := v.(string)\n\tn := getRaw(canonical)\n\tif n == nil || !isActive(n) {\n\t\treturn \"\", false\n\t}\n\tif n.Records.NativeAddress != addr {\n\t\treturn \"\", false\n\t}\n\treturn canonical, true\n}\n\n// ClearPrimaryName clears the caller's reverse record.\nfunc ClearPrimaryName(cur realm) {\n\tc := caller(cur) // allowed even when paused / during grace\n\tif _, removed := reverse.Remove(c.String()); removed {\n\t\temit(EvPrimaryNameChange, \"\", c, \"\", \"cleared\")\n\t}\n}\n\n// invalidateReverseFor lazily clears a reverse record if the just-changed name\n// no longer forward-verifies for the old owner. PrimaryName also re-verifies,\n// so this is best-effort cleanup.\nfunc invalidateReverseFor(oldOwner address, canonical string) {\n\tif v, ok := treeGet(reverse, oldOwner.String()); ok \u0026\u0026 v.(string) == canonical {\n\t\tn := getRaw(canonical)\n\t\tif n == nil || n.Records.NativeAddress != oldOwner.String() {\n\t\t\treverse.Remove(oldOwner.String())\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// 17. Enumeration (bounded, cursor-based)\n// ---------------------------------------------------------------------------\n\nfunc capLimit(limit uint16) int {\n\tconst hardCap = 200\n\tif limit == 0 || int(limit) \u003e hardCap {\n\t\treturn hardCap\n\t}\n\treturn int(limit)\n}\n\n// NamesByOwner lists canonical names owned by owner.\nfunc NamesByOwner(owner string, cursor string, limit uint16) StringPage {\n\tprefix := owner + sep\n\tstart := prefix\n\tif cursor != \"\" {\n\t\tstart = prefix + cursor\n\t}\n\tmax := capLimit(limit)\n\titems := []string{}\n\tnext := \"\"\n\tbyOwner.Iterate(start, prefixEnd(prefix), func(k string, v any) bool {\n\t\tif cursor != \"\" \u0026\u0026 k \u003c= prefix+cursor {\n\t\t\treturn false\n\t\t}\n\t\tif len(items) == max {\n\t\t\tnext = strings.TrimPrefix(k, prefix)\n\t\t\treturn true\n\t\t}\n\t\titems = append(items, v.(string))\n\t\treturn false\n\t})\n\treturn StringPage{Items: items, Next: next}\n}\n\n// Subnames lists direct subnames of parent.\nfunc Subnames(parent string, cursor string, limit uint16) StringPage {\n\tpcanon, err := Normalize(parent)\n\tif err != nil {\n\t\treturn StringPage{}\n\t}\n\tprefix := pcanon + sep\n\tstart := prefix\n\tif cursor != \"\" {\n\t\tstart = prefix + cursor\n\t}\n\tmax := capLimit(limit)\n\titems := []string{}\n\tnext := \"\"\n\tbyParent.Iterate(start, prefixEnd(prefix), func(k string, v any) bool {\n\t\tif cursor != \"\" \u0026\u0026 k \u003c= prefix+cursor {\n\t\t\treturn false\n\t\t}\n\t\tif len(items) == max {\n\t\t\tnext = strings.TrimPrefix(k, prefix)\n\t\t\treturn true\n\t\t}\n\t\titems = append(items, v.(string))\n\t\treturn false\n\t})\n\treturn StringPage{Items: items, Next: next}\n}\n\n// TextKeys lists text-record keys for a name.\nfunc TextKeys(name string, cursor string, limit uint16) StringPage {\n\tn := mustName(name)\n\treturn treeKeys(n.Records.Text, cursor, limit)\n}\n\n// CoinTypes lists multichain coin types set for a name.\nfunc CoinTypes(name string, cursor string, limit uint16) StringPage {\n\tn := mustName(name)\n\treturn treeKeys(n.Records.Addresses, cursor, limit)\n}\n\n// Operators lists operators and their permissions for a name.\nfunc Operators(name string, cursor string, limit uint16) OperatorPage {\n\tn := mustName(name)\n\tmax := capLimit(limit)\n\titems := []OperatorView{}\n\tnext := \"\"\n\tn.Operators.Iterate(cursor, \"\", func(k string, v any) bool {\n\t\tif cursor != \"\" \u0026\u0026 k \u003c= cursor {\n\t\t\treturn false\n\t\t}\n\t\tif len(items) == max {\n\t\t\tnext = k\n\t\t\treturn true\n\t\t}\n\t\titems = append(items, OperatorView{Address: k, Permissions: v.(Permissions)})\n\t\treturn false\n\t})\n\treturn OperatorPage{Items: items, Next: next}\n}\n\nfunc treeKeys(tree *avl.Tree, cursor string, limit uint16) StringPage {\n\tmax := capLimit(limit)\n\titems := []string{}\n\tnext := \"\"\n\ttree.Iterate(cursor, \"\", func(k string, v any) bool {\n\t\tif cursor != \"\" \u0026\u0026 k \u003c= cursor {\n\t\t\treturn false\n\t\t}\n\t\tif len(items) == max {\n\t\t\tnext = k\n\t\t\treturn true\n\t\t}\n\t\titems = append(items, k)\n\t\treturn false\n\t})\n\treturn StringPage{Items: items, Next: next}\n}\n\n// ---------------------------------------------------------------------------\n// 18. Events\n// ---------------------------------------------------------------------------\n\nfunc eventKey(id uint64) string {\n\t// zero-pad to 20 digits for lexicographic ordering.\n\ts := strconv.FormatUint(id, 10)\n\treturn strings.Repeat(\"0\", 20-len(s)) + s\n}\n\nfunc recordEvent(e *Event) {\n\tnextEventID++\n\te.ID = nextEventID\n\te.Height = height()\n\te.Timestamp = now()\n\tevents.Set(eventKey(e.ID), e)\n\t// also surface as a native gno event for tx-level indexers.\n\tchain.Emit(e.Type, \"name\", e.Name, \"actor\", e.Actor, \"id\", strconv.FormatUint(e.ID, 10))\n}\n\nfunc emit(typ, name string, actor address, owner interface{}, key string) {\n\townerStr := \"\"\n\tswitch o := owner.(type) {\n\tcase address:\n\t\townerStr = o.String()\n\tcase string:\n\t\townerStr = o\n\t}\n\trecordEvent(\u0026Event{Type: typ, Name: name, Actor: actor.String(), Owner: ownerStr, Key: key})\n}\n\nfunc emitOwner(typ string, n *Name) {\n\trecordEvent(\u0026Event{Type: typ, Name: n.Canonical, Actor: n.Owner.String(), Owner: n.Owner.String(), Revision: n.Revision})\n}\n\nfunc emitRecord(typ string, n *Name, actor address, key, newDigest string) {\n\trecordEvent(\u0026Event{Type: typ, Name: n.Canonical, Actor: actor.String(), Owner: n.Owner.String(), Revision: n.Revision, Key: key, NewDigest: newDigest})\n}\n\n// EventsAfter returns events with ID strictly greater than id.\nfunc EventsAfter(id uint64, limit uint16) EventPage {\n\tmax := capLimit(limit)\n\titems := []Event{}\n\tnext := \"\"\n\tstart := eventKey(id + 1)\n\tevents.Iterate(start, \"\", func(k string, v any) bool {\n\t\tif len(items) == max {\n\t\t\tnext = k\n\t\t\treturn true\n\t\t}\n\t\titems = append(items, *v.(*Event))\n\t\treturn false\n\t})\n\treturn EventPage{Items: items, Next: next}\n}\n\n// EventsForName returns events for a specific name with ID greater than after.\nfunc EventsForName(name string, after uint64, limit uint16) EventPage {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn EventPage{}\n\t}\n\tmax := capLimit(limit)\n\titems := []Event{}\n\tnext := \"\"\n\tstart := eventKey(after + 1)\n\tevents.Iterate(start, \"\", func(k string, v any) bool {\n\t\te := v.(*Event)\n\t\tif e.Name != canonical {\n\t\t\treturn false\n\t\t}\n\t\tif len(items) == max {\n\t\t\tnext = k\n\t\t\treturn true\n\t\t}\n\t\titems = append(items, *e)\n\t\treturn false\n\t})\n\treturn EventPage{Items: items, Next: next}\n}\n\n// ---------------------------------------------------------------------------\n// 19. Administration\n// ---------------------------------------------------------------------------\n\nfunc requireAdmin(cur realm) address {\n\tc := caller(cur)\n\tif c != config.Admin {\n\t\tpanic(errUnauthorized)\n\t}\n\treturn c\n}\n\nfunc requireNotPaused() {\n\tif config.Paused {\n\t\tpanic(errPaused)\n\t}\n}\n\n// SetPaused toggles the global pause. Paused blocks registration, subname\n// creation, transfers and record mutation; reads, renewals and primary-name\n// clearing remain available. It never confiscates or mutates ownership.\nfunc SetPaused(cur realm, paused bool) {\n\trequireAdmin(cur)\n\tconfig.Paused = paused\n\tif paused {\n\t\temit(EvPaused, \"\", config.Admin, \"\", \"\")\n\t} else {\n\t\temit(EvUnpaused, \"\", config.Admin, \"\", \"\")\n\t}\n}\n\n// SetRegistrationOpen toggles whether new second-level registrations are open.\nfunc SetRegistrationOpen(cur realm, open bool) {\n\trequireAdmin(cur)\n\tconfig.RegistrationOpen = open\n\temit(EvConfigChanged, \"\", config.Admin, \"\", \"registration_open\")\n}\n\n// SetPricing updates future pricing and bumps the policy revision so pending\n// commitments that priced against the old rules are rejected at reveal.\nfunc SetPricing(cur realm, pricing PricingConfig) {\n\trequireAdmin(cur)\n\tif pricing.BasePricePerSecond \u003c 0 {\n\t\tpanic(errBadRequest)\n\t}\n\tconfig.BasePricePerSecond = pricing.BasePricePerSecond\n\tif pricing.PremiumByLength != nil {\n\t\tconfig.PremiumByLength = pricing.PremiumByLength\n\t}\n\tif pricing.PaymentDenom != \"\" {\n\t\tconfig.PaymentDenom = pricing.PaymentDenom\n\t}\n\tconfig.PolicyRevision++\n\temit(EvConfigChanged, \"\", config.Admin, \"\", \"pricing\")\n}\n\n// SetTreasury updates the treasury address.\nfunc SetTreasury(cur realm, treasury address) {\n\trequireAdmin(cur)\n\tif !treasury.IsValid() {\n\t\tpanic(errEmptyAddress)\n\t}\n\tconfig.Treasury = treasury\n\temit(EvConfigChanged, \"\", config.Admin, \"\", \"treasury\")\n}\n\n// ReserveName reserves (or unreserves) an unregistered name so it cannot be\n// publicly registered. Admin may not reserve an actively-owned name.\nfunc ReserveName(cur realm, name string, reserved bool) {\n\trequireAdmin(cur)\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n != nil \u0026\u0026 isActive(n) \u0026\u0026 n.Owner != (address(\"\")) {\n\t\tpanic(errNameUnavailable) // cannot confiscate an active name\n\t}\n\tif n == nil {\n\t\tlabel, parent := splitLabel(canonical)\n\t\tn = \u0026Name{\n\t\t\tCanonical: canonical,\n\t\t\tLabel:     label,\n\t\t\tParent:    parent,\n\t\t\tDepth:     depthOf(canonical),\n\t\t\tRecords:   newRecords(),\n\t\t\tOperators: avl.NewTree(),\n\t\t\tCreatedAt: now(),\n\t\t}\n\t}\n\t// If unreserving a bare placeholder (never registered), physically remove\n\t// it so the name becomes Available again rather than lingering as an\n\t// ExpiresAt==0 node (which statusOf would read as a permanent Active name).\n\tif !reserved \u0026\u0026 !n.Owner.IsValid() {\n\t\tnames.Remove(canonical)\n\t\temit(EvConfigChanged, canonical, config.Admin, \"\", \"reserve\")\n\t\treturn\n\t}\n\tn.Reserved = reserved\n\tnames.Set(canonical, n)\n\temit(EvConfigChanged, canonical, config.Admin, \"\", \"reserve\")\n}\n\n// TransferAdmin begins a two-step admin handover.\nfunc TransferAdmin(cur realm, next address) {\n\trequireAdmin(cur)\n\tif !next.IsValid() {\n\t\tpanic(errEmptyAddress)\n\t}\n\tconfig.PendingAdmin = next\n\temit(EvConfigChanged, \"\", config.Admin, next, \"transfer_admin\")\n}\n\n// AcceptAdmin completes the two-step admin handover.\nfunc AcceptAdmin(cur realm) {\n\tc := caller(cur)\n\tif config.PendingAdmin == (address(\"\")) || c != config.PendingAdmin {\n\t\tpanic(errUnauthorized)\n\t}\n\tconfig.Admin = c\n\tconfig.PendingAdmin = address(\"\")\n\temit(EvConfigChanged, \"\", c, \"\", \"accept_admin\")\n}\n\n// SetLimits updates operational storage/abuse limits (future registrations and\n// mutations). Existing names are unaffected until next mutation.\nfunc SetLimits(cur realm, maxRecords, maxOperators uint16, maxText, maxBinary uint32) {\n\trequireAdmin(cur)\n\tconfig.MaxRecordsPerName = maxRecords\n\tconfig.MaxOperatorsPerName = maxOperators\n\tconfig.MaxTextValueBytes = maxText\n\tconfig.MaxBinaryValueBytes = maxBinary\n\temit(EvConfigChanged, \"\", config.Admin, \"\", \"limits\")\n}\n\n// ---------------------------------------------------------------------------\n// 20. Read API (status/lookup)\n// ---------------------------------------------------------------------------\n\n// Status returns the lifecycle status of a name.\nfunc Status(name string) NameStatus {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn StatusAvailable\n\t}\n\treturn statusOf(getRaw(canonical))\n}\n\n// Exists reports whether a name currently resolves to a live registration.\nfunc Exists(name string) bool {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\treturn false\n\t}\n\tswitch statusOf(n) {\n\tcase StatusActive, StatusGrace:\n\t\treturn true\n\t}\n\treturn false\n}\n\n// OwnerOf returns the owner of an active/grace name.\nfunc OwnerOf(name string) (string, bool) {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn \"\", false\n\t}\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\treturn \"\", false\n\t}\n\tswitch statusOf(n) {\n\tcase StatusActive, StatusGrace:\n\t\treturn n.Owner.String(), true\n\t}\n\treturn \"\", false\n}\n\n// GetName returns a read-only view of a name.\nfunc GetName(name string) (NameView, bool) {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn NameView{}, false\n\t}\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\treturn NameView{}, false\n\t}\n\treturn NameView{\n\t\tCanonical:   n.Canonical,\n\t\tOwner:       n.Owner.String(),\n\t\tStatus:      string(statusOf(n)),\n\t\tCreatedAt:   n.CreatedAt,\n\t\tUpdatedAt:   n.UpdatedAt,\n\t\tExpiresAt:   n.ExpiresAt,\n\t\tGraceEndsAt: n.GraceEndsAt,\n\t\tParent:      n.Parent,\n\t\tLabel:       n.Label,\n\t\tDepth:       n.Depth,\n\t\tTTL:         n.TTL,\n\t\tGeneration:  n.Generation,\n\t\tRevision:    n.Revision,\n\t\tReserved:    n.Reserved,\n\t\tNativeAddr:  n.Records.NativeAddress,\n\t}, true\n}\n\n// CommitmentStatus returns the state of a pending commitment.\nfunc CommitmentStatus(commit string) CommitmentView {\n\tcm, ok := getCommitment(commit)\n\tif !ok {\n\t\treturn CommitmentView{}\n\t}\n\treturn CommitmentView{\n\t\tExists:    true,\n\t\tCommitter: cm.Committer.String(),\n\t\tCreatedAt: cm.CreatedAt,\n\t\tReadyAt:   cm.CreatedAt + config.MinCommitAge,\n\t\tExpiresAt: cm.CreatedAt + config.MaxCommitAge,\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// 21. Rendering\n// ---------------------------------------------------------------------------\n\n// Render is a human-readable explorer. It never mutates state.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tswitch {\n\tcase path == \"\":\n\t\treturn renderHome()\n\tcase strings.HasPrefix(path, \"name/\"):\n\t\treturn renderName(strings.TrimPrefix(path, \"name/\"))\n\tcase strings.HasPrefix(path, \"address/\"):\n\t\treturn renderAddress(strings.TrimPrefix(path, \"address/\"))\n\tcase strings.HasPrefix(path, \"available/\"):\n\t\treturn renderAvailable(strings.TrimPrefix(path, \"available/\"))\n\tcase path == \"events\":\n\t\treturn renderEvents()\n\tcase path == \"help\":\n\t\treturn renderHelp()\n\tdefault:\n\t\treturn \"# GNS\\n\\nUnknown route. See [/help](/r/moul/gns/v0:help).\\n\"\n\t}\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# GNS — Gno Name Service\\n\\n\")\n\tb.WriteString(\"A single-realm, ENS-equivalent naming system for gno.land.\\n\\n\")\n\tb.WriteString(ufmt.Sprintf(\"- Registered names: **%d**\\n\", names.Size()))\n\tb.WriteString(ufmt.Sprintf(\"- Events: **%d**\\n\", int(nextEventID)))\n\tb.WriteString(ufmt.Sprintf(\"- Registration open: **%t**\\n\", config.RegistrationOpen))\n\tb.WriteString(ufmt.Sprintf(\"- Paused: **%t**\\n\\n\", config.Paused))\n\tb.WriteString(\"## Routes\\n\\n\")\n\tb.WriteString(\"- `/name/\u003cname\u003e` — details for a name\\n\")\n\tb.WriteString(\"- `/address/\u003cg1...\u003e` — primary name + owned names\\n\")\n\tb.WriteString(\"- `/available/\u003cname\u003e` — availability and price\\n\")\n\tb.WriteString(\"- `/events` — recent events\\n\")\n\tb.WriteString(\"- `/help` — public API summary\\n\")\n\treturn b.String()\n}\n\nfunc renderName(name string) string {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn \"# \" + name + \"\\n\\nInvalid name: \" + err.Error() + \"\\n\"\n\t}\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\treturn \"# \" + canonical + \"\\n\\n_Available._ See [/available/\" + canonical + \"](/r/moul/gns/v0:available/\" + canonical + \").\\n\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + canonical + \"\\n\\n\")\n\tb.WriteString(\"Owner: `\" + n.Owner.String() + \"`\\n\\n\")\n\tb.WriteString(\"Status: \" + string(statusOf(n)) + \"\\n\\n\")\n\tif n.ExpiresAt \u003e 0 {\n\t\tb.WriteString(ufmt.Sprintf(\"Expires: %s\\n\\n\", time.Unix(n.ExpiresAt, 0).UTC().Format(\"2006-01-02\")))\n\t} else {\n\t\tb.WriteString(\"Expires: never (permanent subname)\\n\\n\")\n\t}\n\tb.WriteString(ufmt.Sprintf(\"Generation: %d · Revision: %d\\n\\n\", int(n.Generation), int(n.Revision)))\n\tif n.Records.NativeAddress != \"\" {\n\t\tb.WriteString(\"Primary address: `\" + n.Records.NativeAddress + \"`\\n\\n\")\n\t}\n\t// text records\n\tb.WriteString(\"## Records\\n\\n\")\n\thasText := false\n\tn.Records.Text.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tb.WriteString(\"- \" + k + \": \" + v.(string) + \"\\n\")\n\t\thasText = true\n\t\treturn false\n\t})\n\tif !hasText {\n\t\tb.WriteString(\"_No text records._\\n\")\n\t}\n\t// subnames\n\tb.WriteString(\"\\n## Subnames\\n\\n\")\n\tsubs := Subnames(canonical, \"\", 50)\n\tif len(subs.Items) == 0 {\n\t\tb.WriteString(\"_None._\\n\")\n\t} else {\n\t\tfor _, s := range subs.Items {\n\t\t\tb.WriteString(\"- \" + s + \"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc renderAddress(addr string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + addr + \"\\n\\n\")\n\tif pn, ok := PrimaryName(addr); ok {\n\t\tb.WriteString(\"Primary name: **\" + pn + \"**\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"_No verified primary name._\\n\\n\")\n\t}\n\tb.WriteString(\"## Owned names\\n\\n\")\n\tpage := NamesByOwner(addr, \"\", 50)\n\tif len(page.Items) == 0 {\n\t\tb.WriteString(\"_None._\\n\")\n\t} else {\n\t\tfor _, s := range page.Items {\n\t\t\tb.WriteString(\"- \" + s + \"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc renderAvailable(name string) string {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn \"# \" + name + \"\\n\\nInvalid: \" + err.Error() + \"\\n\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + canonical + \"\\n\\n\")\n\tif available(canonical) {\n\t\tb.WriteString(\"**Available.**\\n\\n\")\n\t\tq, _ := Price(canonical, config.MinRegistrationDuration)\n\t\tb.WriteString(ufmt.Sprintf(\"Price for %d seconds: %d %s\\n\", int(config.MinRegistrationDuration), int(q.Amount), q.Denom))\n\t} else {\n\t\tb.WriteString(\"**Not available** (status: \" + string(Status(canonical)) + \").\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderEvents() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Recent events\\n\\n\")\n\tfrom := uint64(0)\n\tif nextEventID \u003e 20 {\n\t\tfrom = nextEventID - 20\n\t}\n\tpage := EventsAfter(from, 20)\n\tif len(page.Items) == 0 {\n\t\tb.WriteString(\"_No events yet._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"| ID | Type | Name | Actor |\\n| ---: | --- | --- | --- |\\n\")\n\tfor _, e := range page.Items {\n\t\tb.WriteString(ufmt.Sprintf(\"| %d | %s | %s | `%s` |\\n\", int(e.ID), e.Type, e.Name, e.Actor))\n\t}\n\treturn b.String()\n}\n\nfunc renderHelp() string {\n\treturn \"# GNS API\\n\\n\" +\n\t\t\"Read: `Normalize`, `Status`, `Exists`, `OwnerOf`, `GetName`, `Resolve`, \" +\n\t\t\"`Address`, `CoinAddress`, `Text`, `ContentHash`, `PublicKey`, `ABI`, \" +\n\t\t\"`Interface`, `Record`, `PrimaryName`, `Price`, `CommitmentStatus`, \" +\n\t\t\"`NamesByOwner`, `Subnames`, `TextKeys`, `CoinTypes`, `Operators`, \" +\n\t\t\"`EventsAfter`, `EventsForName`.\\n\\n\" +\n\t\t\"Mutations (crossing, panic on failure): `Commit`, `Register`, `Renew`, \" +\n\t\t\"`Transfer`, `CreateSubname`, `DeleteSubname`, `SetRegistrationPolicy`, \" +\n\t\t\"`LockPolicy`, `SetOperator`, `RemoveOperator`, `SetPrimaryName`, \" +\n\t\t\"`ClearPrimaryName`, and the typed record setters.\\n\\n\" +\n\t\t\"Admin: `SetPaused`, `SetRegistrationOpen`, `SetPricing`, `SetTreasury`, \" +\n\t\t\"`ReserveName`, `TransferAdmin`, `AcceptAdmin`, `SetLimits`.\\n\"\n}\n\n// ---------------------------------------------------------------------------\n// 22. Internal storage helpers\n// ---------------------------------------------------------------------------\n\nfunc coins(denom string, amount int64) chain.Coins {\n\treturn chain.NewCoins(chain.NewCoin(denom, amount))\n}\n\n// treeGet adapts the avl v0 API (Get returns a single value; existence is via\n// Has) to the (value, ok) idiom used throughout this file.\nfunc treeGet(t *avl.Tree, key string) (any, bool) {\n\tif !t.Has(key) {\n\t\treturn nil, false\n\t}\n\treturn t.Get(key), true\n}\n\nfunc getRaw(canonical string) *Name {\n\tv, ok := treeGet(names, canonical)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn v.(*Name)\n}\n\n// resolvableName returns the name only if it is currently Active (records\n// resolve only for active names).\nfunc resolvableName(name string) *Name {\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tn := getRaw(canonical)\n\tif n == nil || !isActive(n) {\n\t\treturn nil\n\t}\n\treturn n\n}\n\n// mustName returns an existing name or panics with not_found.\nfunc mustName(name string) *Name {\n\tcanonical := mustNormalize(name)\n\tn := getRaw(canonical)\n\tif n == nil {\n\t\tpanic(errNotFound)\n\t}\n\treturn n\n}\n\nfunc putName(n *Name) {\n\tnames.Set(n.Canonical, n)\n\tbyOwner.Set(ownerKey(n.Owner, n.Canonical), n.Canonical)\n\tif n.Parent != \"\" {\n\t\tbyParent.Set(n.Parent+sep+n.Canonical, n.Canonical)\n\t}\n}\n\nfunc deleteName(n *Name) {\n\tn.Deleted = true\n\tbyOwner.Remove(ownerKey(n.Owner, n.Canonical))\n\tif n.Parent != \"\" {\n\t\tbyParent.Remove(n.Parent + sep + n.Canonical)\n\t}\n\tnames.Remove(n.Canonical)\n}\n\nfunc ownerKey(owner address, canonical string) string {\n\treturn owner.String() + sep + canonical\n}\n\nfunc getCommitment(key string) (*commitment, bool) {\n\tv, ok := treeGet(commitments, key)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn v.(*commitment), true\n}\n\nfunc getOperator(n *Name, addr address) (Permissions, bool) {\n\tif n.Operators == nil {\n\t\treturn Permissions{}, false\n\t}\n\tv, ok := treeGet(n.Operators, addr.String())\n\tif !ok {\n\t\treturn Permissions{}, false\n\t}\n\treturn v.(Permissions), true\n}\n\nfunc allowlistHas(tree *avl.Tree, addr address) bool {\n\tv, ok := treeGet(tree, addr.String())\n\treturn ok \u0026\u0026 v.(bool)\n}\n\nfunc collectPaymentDenom(cur realm, price int64, denom string, treasury address) {\n\tif price \u003c= 0 {\n\t\treturn\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(errNotUser)\n\t}\n\tsent := unsafe.OriginSend()\n\tgot := sent.AmountOf(denom)\n\tif got \u003c price {\n\t\tpanic(errInsufficientPay)\n\t}\n\tbk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tself := cur.Address()\n\tif treasury != self {\n\t\tbk.SendCoins(self, treasury, coins(denom, price))\n\t}\n\tif over := got - price; over \u003e 0 {\n\t\tbk.SendCoins(self, cur.Previous().Address(), coins(denom, over))\n\t}\n}\n\nfunc prefixEnd(prefix string) string {\n\tif prefix == \"\" {\n\t\treturn \"\"\n\t}\n\tb := []byte(prefix)\n\tfor i := len(b) - 1; i \u003e= 0; i-- {\n\t\tif b[i] \u003c 0xff {\n\t\t\tb[i]++\n\t\t\treturn string(b[:i+1])\n\t\t}\n\t}\n\treturn \"\" // prefix is all 0xff; iterate to end\n}\n"},{"name":"gns_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n)\n\nfunc TestNormalize(t *testing.T) {\n\treset()\n\n\tcases := []struct {\n\t\tin  string\n\t\tout string\n\t\tok  bool\n\t}{\n\t\t{\"alice\", \"alice\", true},\n\t\t{\"ALICE\", \"alice\", true},\n\t\t{\"Wallet.Alice\", \"wallet.alice\", true},\n\t\t{\"a\", \"a\", true},\n\t\t{\"a1-b\", \"a1-b\", true},\n\t\t{\"-alice\", \"\", false}, // leading hyphen\n\t\t{\"alice-\", \"\", false}, // trailing hyphen\n\t\t{\"\", \"\", false},       // empty\n\t\t{\"a..b\", \"\", false},   // empty label (double dot)\n\t\t{\"al ice\", \"\", false}, // space\n\t\t{\"café\", \"\", false},   // non-ASCII\n\t\t{\"a_b\", \"\", false},    // underscore not allowed\n\t}\n\tfor _, tc := range cases {\n\t\tgot, err := Normalize(tc.in)\n\t\tif tc.ok {\n\t\t\tnoErr(t, err, \"normalize \"+tc.in)\n\t\t\teqStr(t, tc.out, got, \"normalize \"+tc.in)\n\t\t} else {\n\t\t\tisErr(t, err, \"expected error for \"+tc.in)\n\t\t}\n\t}\n}\n\nfunc TestNormalizeDepthAndLength(t *testing.T) {\n\treset()\n\n\tdeep := \"a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a\" // 17 labels \u003e maxDepth\n\t_, err := Normalize(deep)\n\tisErr(t, err, \"excessive depth rejected\")\n\n\tlong := \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" // 64 \u003e 63\n\t_, err = Normalize(long)\n\tisErr(t, err, \"excessive label length rejected\")\n}\n\nfunc TestStatusAndOwnerLifecycle(cur realm, t *testing.T) {\n\treset()\n\n\teqStr(t, string(StatusAvailable), string(Status(\"alice\")), \"initial status\")\n\tisFalse(t, Exists(\"alice\"), \"not exists initially\")\n\n\tdoRegister(cur, \"alice\", alice, 1000)\n\n\teqStr(t, string(StatusActive), string(Status(\"alice\")), \"post-register status\")\n\tisTrue(t, Exists(\"alice\"), \"exists after register\")\n\n\towner, ok := OwnerOf(\"alice\")\n\tisTrue(t, ok, \"ownerOf ok\")\n\teqStr(t, alice.String(), owner, \"owner is alice\")\n\n\tview, ok := GetName(\"alice\")\n\tisTrue(t, ok, \"getName ok\")\n\teqInt(t, 1, int64(view.Generation), \"generation 1\")\n\teqStr(t, \"alice\", view.Canonical, \"canonical\")\n\n\t// advance past expiry, into grace (expiry ≈ +1000s, grace ends ≈ +1100s)\n\ttesting.SkipHeights(210) // +1050s\n\teqStr(t, string(StatusGrace), string(Status(\"alice\")), \"grace status\")\n\t_, ok = OwnerOf(\"alice\")\n\tisTrue(t, ok, \"owner known during grace\")\n\n\t// advance well past grace -\u003e Expired\n\ttesting.SkipHeights(200) // +1000s more, far beyond grace end\n\teqStr(t, string(StatusExpired), string(Status(\"alice\")), \"expired status\")\n\tisFalse(t, Exists(\"alice\"), \"not exists after grace\")\n}\n\nfunc TestExpiredOwnerLosesAuthority(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 1000)\n\n\ttesting.SkipHeights(300) // beyond grace\n\teqStr(t, string(StatusExpired), string(Status(\"alice\")), \"expired\")\n\n\t// Invariant 2: an expired name grants no owner mutation authority. Tested\n\t// against the single authorization gate directly (mutations funnel through\n\t// it, then panic on the returned error).\n\tn := getRaw(\"alice\")\n\tisTrue(t, n != nil, \"raw name present\")\n\terrIs(t, authorize(alice, n, PermManageRecords), errUnauthorized, \"expired owner authorize\")\n\terrIs(t, authorize(alice, n, PermTransfer), errUnauthorized, \"expired owner transfer\")\n}\n"},{"name":"helpers_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// Deterministic, checksum-valid test addresses.\nvar (\n\tadmin = testutils.TestAddress(\"admin\")\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\tdave  = testutils.TestAddress(\"dave\")\n)\n\n// reset re-initializes all package state to a deterministic, test-friendly\n// configuration. Durations are small so lifecycle tests can advance time with\n// modest SkipHeights calls. Pricing is free by default (BasePricePerSecond=0)\n// so most functional tests need not attach payment; payment tests override it.\nfunc reset() {\n\tnames = avl.NewTree()\n\tcommitments = avl.NewTree()\n\treverse = avl.NewTree()\n\tevents = avl.NewTree()\n\tbyOwner = avl.NewTree()\n\tbyParent = avl.NewTree()\n\tnextEventID = 0\n\n\tconfig = Config{\n\t\tAdmin:            admin,\n\t\tTreasury:         admin,\n\t\tRegistrationOpen: true,\n\n\t\tMinCommitAge: 10,\n\t\tMaxCommitAge: 1000,\n\n\t\tMinRegistrationDuration: 100,\n\t\tMaxRegistrationDuration: 10_000_000,\n\n\t\tGracePeriod: 100,\n\n\t\tBasePricePerSecond: 0,\n\t\tPremiumByLength:    map[uint8]int64{1: 100, 2: 25, 3: 5, 4: 2},\n\n\t\tPaymentDenom: \"ugnot\",\n\n\t\tMaxTextValueBytes:   4096,\n\t\tMaxBinaryValueBytes: 8192,\n\t\tMaxRecordsPerName:   128,\n\t\tMaxOperatorsPerName: 32,\n\n\t\tPolicyRevision: 1,\n\t}\n}\n\n// newTestName builds a standalone active *Name for unit-testing pure helpers\n// (authorize, statusOf, ...) without going through the registration flow.\nfunc newTestName(canonical string, owner address, cp ControlPolicy) *Name {\n\tlabel, parent := splitLabel(canonical)\n\treturn \u0026Name{\n\t\tCanonical:     canonical,\n\t\tOwner:         owner,\n\t\tExpiresAt:     now() + 1_000_000,\n\t\tParent:        parent,\n\t\tLabel:         label,\n\t\tDepth:         depthOf(canonical),\n\t\tGeneration:    1,\n\t\tRevision:      1,\n\t\tRecords:       newRecords(),\n\t\tOperators:     avl.NewTree(),\n\t\tControlPolicy: cp,\n\t}\n}\n\n// doRegister runs the full commit→reveal flow for a second-level name using the\n// free (zero-price) path. Caller identity is set to owner.\nfunc doRegister(cur realm, name string, owner address, duration int64) {\n\tsecret := \"sec-\" + name\n\tcanonical, err := Normalize(name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc := computeCommitment(canonical, owner, duration, secret, \"\", config.PolicyRevision)\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tCommit(cross(cur), c)\n\n\ttesting.SkipHeights(3) // +15s \u003e MinCommitAge (10s)\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tRegister(cross(cur), RegisterRequest{\n\t\tName:           name,\n\t\tOwner:          owner,\n\t\tDuration:       duration,\n\t\tSecret:         secret,\n\t\tPolicyRevision: config.PolicyRevision,\n\t})\n}\n"},{"name":"policy_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n)\n\nfunc TestOperatorDelegation(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\n\t// alice grants bob record management only (not transfer)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetOperator(cross(cur), \"alice\", bob, Permissions{ManageRecords: true})\n\n\t// bob can set a text record\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSetText(cross(cur), \"alice\", \"url\", \"https://bob-managed.example\")\n\tv, ok := Text(\"alice\", \"url\")\n\tisTrue(t, ok, \"operator set record\")\n\teqStr(t, \"https://bob-managed.example\", v, \"operator record value\")\n\n\t// invariant: operator without Transfer cannot transfer\n\tn := getRaw(\"alice\")\n\terrIs(t, authorize(bob, n, PermTransfer), errUnauthorized, \"record operator lacks transfer\")\n\tnoErr(t, authorize(bob, n, PermManageRecords), \"record operator has records perm\")\n}\n\nfunc TestRemoveOperator(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetOperator(cross(cur), \"alice\", bob, Permissions{ManageRecords: true})\n\tn := getRaw(\"alice\")\n\teqInt(t, 1, int64(n.OperatorCount), \"one operator\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRemoveOperator(cross(cur), \"alice\", bob)\n\tn = getRaw(\"alice\")\n\teqInt(t, 0, int64(n.OperatorCount), \"operator removed\")\n\terrIs(t, authorize(bob, n, PermManageRecords), errUnauthorized, \"removed operator loses perm\")\n}\n\nfunc TestTransferHappy(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\tr0 := getRaw(\"alice\").Revision\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), \"alice\", bob, true, false)\n\n\towner, ok := OwnerOf(\"alice\")\n\tisTrue(t, ok, \"still exists\")\n\teqStr(t, bob.String(), owner, \"owner now bob\")\n\tisTrue(t, getRaw(\"alice\").Revision \u003e r0, \"revision bumped on transfer (invariant 12 side-effect)\")\n}\n\nfunc TestAuthorizeOrder(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\tn := getRaw(\"alice\")\n\n\t// direct owner (active) authorized\n\tnoErr(t, authorize(alice, n, PermManageRecords), \"owner authorized\")\n\t// unrelated user rejected\n\terrIs(t, authorize(carol, n, PermManageRecords), errUnauthorized, \"stranger rejected\")\n\t// admin has NO routine authority over user names (invariant 18)\n\terrIs(t, authorize(admin, n, PermTransfer), errUnauthorized, \"admin cannot transfer user name\")\n}\n\nfunc TestNonTransferablePolicyPure(t *testing.T) {\n\treset()\n\t// A name whose policy forbids owner transfer: the Transfer owner-branch\n\t// checks OwnerCanTransfer and rejects with policy_locked. We assert the\n\t// policy flag drives that decision.\n\tn := newTestName(\"locked\", alice, ControlPolicy{OwnerCanTransfer: false})\n\tisFalse(t, n.ControlPolicy.OwnerCanTransfer, \"policy forbids transfer\")\n\t// and no operator/parent path grants transfer either\n\terrIs(t, authorize(bob, n, PermTransfer), errUnauthorized, \"no delegated transfer\")\n}\n"},{"name":"records_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTypedRecords(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetAddress(cross(cur), \"alice\", alice.String())\n\tSetText(cross(cur), \"alice\", \"com.github\", \"moul\")\n\tSetCoinAddress(cross(cur), \"alice\", \"60\", []byte{0xde, 0xad})\n\tSetContentHash(cross(cur), \"alice\", []byte{0x12, 0x20})\n\tSetPublicKey(cross(cur), \"alice\", []byte{0x01, 0x02})\n\tSetABI(cross(cur), \"alice\", \"application/json\", []byte(\"{}\"))\n\tSetInterface(cross(cur), \"alice\", \"0x1\", \"gno.land/r/demo/foo\")\n\tSetRecord(cross(cur), \"alice\", \"com.example\", \"game\", []byte(\"hi\"))\n\n\taddr, ok := Address(\"alice\")\n\tisTrue(t, ok, \"address set\")\n\teqStr(t, alice.String(), addr, \"address value\")\n\n\ttxt, ok := Text(\"alice\", \"com.github\")\n\tisTrue(t, ok, \"text set\")\n\teqStr(t, \"moul\", txt, \"text value\")\n\n\tcoin, ok := CoinAddress(\"alice\", \"60\")\n\tisTrue(t, ok, \"coin set\")\n\teqInt(t, 2, int64(len(coin)), \"coin len\")\n\n\t_, ok = ContentHash(\"alice\")\n\tisTrue(t, ok, \"contenthash set\")\n\t_, ok = PublicKey(\"alice\")\n\tisTrue(t, ok, \"pubkey set\")\n\t_, ok = ABI(\"alice\", \"application/json\")\n\tisTrue(t, ok, \"abi set\")\n\n\tiface, ok := Interface(\"alice\", \"0x1\")\n\tisTrue(t, ok, \"interface set\")\n\teqStr(t, \"gno.land/r/demo/foo\", iface, \"interface value\")\n\n\trec, ok := Record(\"alice\", \"com.example\", \"game\")\n\tisTrue(t, ok, \"record set\")\n\teqStr(t, \"hi\", string(rec), \"record value\")\n}\n\nfunc TestTextDeletePhysical(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"alice\", \"url\", \"https://example.com\")\n\t_, ok := Text(\"alice\", \"url\")\n\tisTrue(t, ok, \"url present\")\n\n\t// empty value physically removes it\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"alice\", \"url\", \"\")\n\t_, ok = Text(\"alice\", \"url\")\n\tisFalse(t, ok, \"url removed\")\n\n\tn := getRaw(\"alice\")\n\teqInt(t, 0, int64(n.Records.Count), \"record count back to zero\")\n}\n\nfunc TestRevisionBumps(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\tr0 := getRaw(\"alice\").Revision\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"alice\", \"a\", \"1\")\n\tr1 := getRaw(\"alice\").Revision\n\tisTrue(t, r1 \u003e r0, \"revision increments on record change\")\n}\n\nfunc TestResolveExactAndAncestor(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"company\", alice, 100000)\n\n\t// open subname policy so we can create a child\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetRegistrationPolicy(cross(cur), \"company\", RegistrationPolicy{Mode: ModeOpen})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateSubname(cross(cur), \"company\", \"api\", alice, SubnameOptions{Duration: 100000})\n\n\t// text only on the parent\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"company\", \"url\", \"https://company.example\")\n\n\t// exact on child: not found\n\texact := Resolve(\"api.company\", RecordQuery{Kind: \"text\", Key1: \"url\"}, Exact)\n\tisFalse(t, exact.Found, \"exact child has no url\")\n\n\t// nearest ancestor: inherits from company\n\tinh := Resolve(\"api.company\", RecordQuery{Kind: \"text\", Key1: \"url\"}, NearestAncestor)\n\tisTrue(t, inh.Found, \"ancestor url found\")\n\teqStr(t, \"company\", inh.SourceName, \"source is parent\")\n\teqStr(t, \"https://company.example\", string(inh.Value), \"inherited value\")\n}\n\n// Multiple record updates are done by calling the typed setters repeatedly\n// (from a client, via a single `gnokey maketx run` that calls a helper N times);\n// GNS does not need an in-realm batch entry point.\nfunc TestSetTTLAndMultipleRecords(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"alice\", \"email\", \"a@b.co\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"alice\", \"url\", \"https://x.example\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetTTL(cross(cur), \"alice\", 3600)\n\n\tv, ok := Text(\"alice\", \"email\")\n\tisTrue(t, ok, \"email set\")\n\teqStr(t, \"a@b.co\", v, \"email value\")\n\tv, ok = Text(\"alice\", \"url\")\n\tisTrue(t, ok, \"url set\")\n\teqStr(t, \"https://x.example\", v, \"url value\")\n\n\tn := getRaw(\"alice\")\n\teqInt(t, 3600, int64(n.TTL), \"ttl set\")\n}\n\nfunc TestReservedNamespaceRejectedPure(t *testing.T) {\n\treset()\n\t// the reserved-namespace guard is a pure lookup used by SetRecord.\n\tisTrue(t, reservedNamespaces[\"gno\"], \"gno reserved\")\n\tisTrue(t, reservedNamespaces[\"system\"], \"system reserved\")\n\tisFalse(t, reservedNamespaces[\"com.example\"], \"app namespace allowed\")\n}\n"},{"name":"registration_test.gno","body":"package gns\n\nimport (\n\t\"chain\"\n\t\"testing\"\n)\n\nfunc TestCommitRevealFlow(cur realm, t *testing.T) {\n\treset()\n\n\tsecret := \"hunter2\"\n\tdur := int64(1000)\n\tcommit, err := MakeCommitment(\"alice\", alice, dur, secret, \"\", config.PolicyRevision)\n\tnoErr(t, err, \"make commitment\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCommit(cross(cur), commit)\n\n\t// commitment visible, not yet ready\n\tcs := CommitmentStatus(commit)\n\tisTrue(t, cs.Exists, \"commitment exists\")\n\teqStr(t, alice.String(), cs.Committer, \"committer\")\n\n\ttesting.SkipHeights(3) // pass MinCommitAge\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tres := Register(cross(cur), RegisterRequest{\n\t\tName:           \"alice\",\n\t\tOwner:          alice,\n\t\tDuration:       dur,\n\t\tSecret:         secret,\n\t\tPolicyRevision: config.PolicyRevision,\n\t})\n\teqStr(t, \"alice\", res.Canonical, \"result canonical\")\n\teqInt(t, 1, int64(res.Generation), \"generation\")\n\n\t// commitment consumed exactly once (invariant 7)\n\tisFalse(t, CommitmentStatus(commit).Exists, \"commitment consumed\")\n\t// second reveal with same commitment can't find it\n\t_, ok := getCommitment(commit)\n\tisFalse(t, ok, \"commitment removed\")\n}\n\nfunc TestPricingDeterministic(t *testing.T) {\n\treset()\n\tconfig.BasePricePerSecond = 10\n\n\t// 5+ char label -\u003e multiplier 1\n\tp, err := priceFor(\"alice\", 100)\n\tnoErr(t, err, \"price alice\")\n\teqInt(t, 1000, p, \"price 5-char\")\n\n\t// 1 char -\u003e multiplier 100\n\tp, err = priceFor(\"a\", 100)\n\tnoErr(t, err, \"price a\")\n\teqInt(t, 100000, p, \"price 1-char\")\n\n\t// 3 char -\u003e multiplier 5\n\tp, err = priceFor(\"abc\", 100)\n\tnoErr(t, err, \"price abc\")\n\teqInt(t, 5000, p, \"price 3-char\")\n\n\t// invariant 10: overflow-safe\n\t_, err = priceFor(\"a\", 1\u003c\u003c62)\n\tisErr(t, err, \"overflow rejected\")\n\n\t// zero/negative duration\n\t_, err = priceFor(\"alice\", 0)\n\terrIs(t, err, errDurationTooShort, \"zero duration\")\n}\n\nfunc TestGenerationRecycle(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 1000)\n\n\t// put a record, then let it expire\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"alice\", \"url\", \"https://old.example\")\n\n\ttesting.SkipHeights(500) // beyond grace\n\n\t// re-register by a different owner\n\tdoRegister(cur, \"alice\", bob, 1000)\n\n\tview, ok := GetName(\"alice\")\n\tisTrue(t, ok, \"exists after recycle\")\n\teqInt(t, 2, int64(view.Generation), \"generation incremented (invariant 20)\")\n\teqStr(t, bob.String(), view.Owner, \"new owner\")\n\n\t// invariant 19: old records do not leak\n\t_, ok = Text(\"alice\", \"url\")\n\tisFalse(t, ok, \"old record cleared on recycle\")\n}\n\nfunc TestReservedNames(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tReserveName(cross(cur), \"gno\", true)\n\n\t// invariant 17: reserved names cannot be publicly registered\n\tisFalse(t, available(\"gno\"), \"reserved not available\")\n\teqStr(t, string(StatusReserved), string(Status(\"gno\")), \"status reserved\")\n\n\t// unreserve\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tReserveName(cross(cur), \"gno\", false)\n\tisTrue(t, available(\"gno\"), \"available after unreserve\")\n}\n\nfunc TestRegisterWithPayment(cur realm, t *testing.T) {\n\treset()\n\tconfig.BasePricePerSecond = 1\n\tconfig.Treasury = cur.Address() // realm keeps funds; no banker forward needed\n\n\tdur := int64(1000) // price = 1000 * 1 * 1 (5+ chars)\n\tsecret := \"s\"\n\tcommit, _ := MakeCommitment(\"alice\", alice, dur, secret, \"\", config.PolicyRevision)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCommit(cross(cur), commit)\n\ttesting.SkipHeights(3)\n\n\ttesting.IssueCoins(cur.Address(), chain.Coins{{Denom: \"ugnot\", Amount: 1000}})\n\ttesting.SetOriginSend(chain.Coins{{Denom: \"ugnot\", Amount: 1000}})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tres := Register(cross(cur), RegisterRequest{\n\t\tName:           \"alice\",\n\t\tOwner:          alice,\n\t\tDuration:       dur,\n\t\tSecret:         secret,\n\t\tPolicyRevision: config.PolicyRevision,\n\t})\n\teqInt(t, 1000, res.Paid, \"paid exact price\")\n\teqInt(t, 0, res.Refunded, \"no refund\")\n}\n\nfunc TestPriceQuote(t *testing.T) {\n\treset()\n\tconfig.BasePricePerSecond = 2\n\tq, err := Price(\"bob\", 500) // 3-char -\u003e mult 5; 500*2*5 = 5000\n\tnoErr(t, err, \"quote\")\n\teqInt(t, 5000, q.Amount, \"quote amount\")\n\teqStr(t, \"ugnot\", q.Denom, \"quote denom\")\n\teqInt(t, int64(config.PolicyRevision), int64(q.Revision), \"quote revision\")\n}\n"},{"name":"render_test.gno","body":"package gns\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestRenderRoutes(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetText(cross(cur), \"alice\", \"com.github\", \"moul\")\n\n\thome := Render(\"\")\n\tisTrue(t, strings.Contains(home, \"GNS\"), \"home mentions GNS\")\n\tisTrue(t, strings.Contains(home, \"Registered names\"), \"home shows stats\")\n\n\tname := Render(\"name/alice\")\n\tisTrue(t, strings.Contains(name, \"alice\"), \"name page has name\")\n\tisTrue(t, strings.Contains(name, alice.String()), \"name page shows owner\")\n\tisTrue(t, strings.Contains(name, \"com.github\"), \"name page shows records\")\n\n\tavail := Render(\"available/freeone\")\n\tisTrue(t, strings.Contains(avail, \"Available\"), \"available page\")\n\n\thelp := Render(\"help\")\n\tisTrue(t, strings.Contains(help, \"Register\"), \"help lists API\")\n\n\tevents := Render(\"events\")\n\tisTrue(t, strings.Contains(events, \"events\"), \"events page\")\n}\n\nfunc TestRenderNoMutation(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\tbefore := names.Size()\n\t_ = Render(\"name/alice\")\n\t_ = Render(\"\")\n\t_ = Render(\"available/whatever\")\n\tafter := names.Size()\n\teqInt(t, int64(before), int64(after), \"Render does not mutate state\")\n}\n\nfunc TestEnumerationBounded(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"one\", alice, 100000)\n\tdoRegister(cur, \"two\", alice, 100000)\n\tdoRegister(cur, \"three\", alice, 100000)\n\n\tpage := NamesByOwner(alice.String(), \"\", 2)\n\teqInt(t, 2, int64(len(page.Items)), \"page limited to 2\")\n\tisTrue(t, page.Next != \"\", \"cursor for next page\")\n\n\t// invariant 15: hard cap even when a huge limit is requested.\n\tpage2 := NamesByOwner(alice.String(), \"\", 65535)\n\tisTrue(t, len(page2.Items) \u003c= 200, \"hard cap applied\")\n}\n"},{"name":"reverse_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n)\n\nfunc TestPrimaryNameForwardVerified(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\n\t// forward address must point to the caller before SetPrimaryName succeeds\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetAddress(cross(cur), \"alice\", alice.String())\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetPrimaryName(cross(cur), \"alice\")\n\n\tname, ok := PrimaryName(alice.String())\n\tisTrue(t, ok, \"primary resolves\")\n\teqStr(t, \"alice\", name, \"primary is alice\")\n}\n\nfunc TestPrimaryNameForwardMismatch(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetAddress(cross(cur), \"alice\", alice.String())\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetPrimaryName(cross(cur), \"alice\")\n\n\t// change the forward address away from alice -\u003e primary must stop resolving\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetAddress(cross(cur), \"alice\", bob.String())\n\n\t// invariant 6: primary returned only when forward resolution matches\n\t_, ok := PrimaryName(alice.String())\n\tisFalse(t, ok, \"stale reverse not returned\")\n}\n\nfunc TestPrimaryNameExpired(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 1000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetAddress(cross(cur), \"alice\", alice.String())\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetPrimaryName(cross(cur), \"alice\")\n\n\ttesting.SkipHeights(500) // expire the name\n\t_, ok := PrimaryName(alice.String())\n\tisFalse(t, ok, \"expired name yields no primary\")\n}\n\nfunc TestClearPrimaryName(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetAddress(cross(cur), \"alice\", alice.String())\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetPrimaryName(cross(cur), \"alice\")\n\n\t_, ok := PrimaryName(alice.String())\n\tisTrue(t, ok, \"primary set\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClearPrimaryName(cross(cur))\n\t_, ok = PrimaryName(alice.String())\n\tisFalse(t, ok, \"primary cleared\")\n}\n\nfunc TestTransferInvalidatesReverse(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetAddress(cross(cur), \"alice\", alice.String())\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSetPrimaryName(cross(cur), \"alice\")\n\n\t// transfer to bob, clearing records -\u003e forward no longer points to alice\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), \"alice\", bob, true, true)\n\n\t_, ok := PrimaryName(alice.String())\n\tisFalse(t, ok, \"reverse invalidated after transfer+record clear\")\n}\n"},{"name":"security_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n)\n\n// This file targets the \"critical invariants\" list from the spec that are best\n// expressed as focused checks against the internal helpers.\n\nfunc TestInvariantAdminCannotConfiscate(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\tn := getRaw(\"alice\")\n\n\t// invariant 18: admin has no routine power over an active user name.\n\terrIs(t, authorize(admin, n, PermTransfer), errUnauthorized, \"admin no transfer\")\n\terrIs(t, authorize(admin, n, PermManageRecords), errUnauthorized, \"admin no records\")\n\n\t// invariant 14/17 via ReserveName: an actively-owned name cannot be reserved\n\t// (confiscated). We assert the precondition the crossing path enforces.\n\tisFalse(t, available(\"alice\"), \"active name unavailable to others\")\n\tisTrue(t, isActive(n) \u0026\u0026 n.Owner.IsValid(), \"name active and owned\")\n}\n\nfunc TestInvariantGraceNotRegisterable(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 1000)\n\ttesting.SkipHeights(210) // into grace\n\teqStr(t, string(StatusGrace), string(Status(\"alice\")), \"in grace\")\n\t// invariant 3: a grace-period name cannot be registered by another user.\n\tisFalse(t, available(\"alice\"), \"grace name not available\")\n}\n\nfunc TestInvariantSingleEffectiveOwner(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"alice\", alice, 100000)\n\t// invariant 1: exactly one owner.\n\to1, ok := OwnerOf(\"alice\")\n\tisTrue(t, ok, \"owned\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), \"alice\", bob, true, false)\n\to2, _ := OwnerOf(\"alice\")\n\tisFalse(t, o1 == o2, \"owner changed to exactly one new owner\")\n\teqStr(t, bob.String(), o2, \"single new owner\")\n}\n\nfunc TestInvariantPermanentOnlyRestrictive(t *testing.T) {\n\treset()\n\t// invariant 5, exhaustive over all flags.\n\tall := ControlPolicy{\n\t\tOwnerCanTransfer: true, OwnerCanCreateSubnames: true, RecordsMutable: true,\n\t\tParentCanReclaim: true, ParentCanTransfer: true, ParentCanDelete: true,\n\t\tParentCanChangePolicy: true, Permanent: true,\n\t}\n\t// try to relax everything\n\tgot := mergeRestrictive(all, all) // identity keeps all true\n\tisTrue(t, got.OwnerCanTransfer \u0026\u0026 got.RecordsMutable \u0026\u0026 got.ParentCanReclaim, \"identity keeps flags\")\n\n\tnone := ControlPolicy{Permanent: true}\n\trestricted := mergeRestrictive(all, none)\n\tisFalse(t, restricted.OwnerCanTransfer, \"all restricted off\")\n\tisFalse(t, restricted.ParentCanReclaim, \"reclaim off\")\n\tisTrue(t, restricted.Permanent, \"permanent stays on\")\n\n\t// cannot turn any back on\n\treenable := mergeRestrictive(restricted, all)\n\tisFalse(t, reenable.OwnerCanTransfer, \"cannot re-enable transfer\")\n\tisFalse(t, reenable.RecordsMutable, \"cannot re-enable records\")\n}\n\nfunc TestInvariantPriceOverflowSafe(t *testing.T) {\n\treset()\n\tconfig.BasePricePerSecond = 1 \u003c\u003c 40\n\t// invariant 10: overflow returns an error, never a wrapped value.\n\t_, err := priceFor(\"a\", 1\u003c\u003c40) // *100 multiplier -\u003e overflow\n\tisErr(t, err, \"overflow detected\")\n}\n\nfunc TestInvariantCommitmentTiming(cur realm, t *testing.T) {\n\treset()\n\tcommit, _ := MakeCommitment(\"alice\", alice, 1000, \"s\", \"\", config.PolicyRevision)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCommit(cross(cur), commit)\n\n\tcs := CommitmentStatus(commit)\n\t// invariant 8: ready/expiry window is enforced by MinCommitAge/MaxCommitAge.\n\teqInt(t, cs.CreatedAt+config.MinCommitAge, cs.ReadyAt, \"ready at min age\")\n\teqInt(t, cs.CreatedAt+config.MaxCommitAge, cs.ExpiresAt, \"expires at max age\")\n}\n\nfunc TestPauseGatePure(t *testing.T) {\n\treset()\n\t// paused reads still work; the mutation gate is requireNotPaused.\n\tconfig.Paused = true\n\t// Status is a read; must still function while paused.\n\teqStr(t, string(StatusAvailable), string(Status(\"nobody\")), \"reads work while paused\")\n\tconfig.Paused = false\n}\n\nfunc TestRecordLimitsConfigured(t *testing.T) {\n\treset()\n\t// invariant 13: per-name storage bounds are configured and enforced.\n\tisTrue(t, config.MaxRecordsPerName \u003e 0, \"record count bound configured\")\n\tisTrue(t, config.MaxTextValueBytes \u003e 0, \"text size bound configured\")\n\tisTrue(t, config.MaxOperatorsPerName \u003e 0, \"operator bound configured\")\n}\n"},{"name":"subnames_test.gno","body":"package gns\n\nimport (\n\t\"testing\"\n)\n\n// setPolicy is a small helper: parent owner sets a registration policy.\nfunc setPolicy(cur realm, parent string, owner address, mode string) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tSetRegistrationPolicy(cross(cur), parent, RegistrationPolicy{Mode: mode})\n}\n\nfunc TestSubnameOpen(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"company\", alice, 100000)\n\tsetPolicy(cur, \"company\", alice, ModeOpen)\n\n\t// anyone (bob) can claim an open subname\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tCreateSubname(cross(cur), \"company\", \"bob\", bob, SubnameOptions{Duration: 100000})\n\n\towner, ok := OwnerOf(\"bob.company\")\n\tisTrue(t, ok, \"subname exists\")\n\teqStr(t, bob.String(), owner, \"subname owner is bob\")\n\n\tn := getRaw(\"bob.company\")\n\teqStr(t, \"company\", n.Parent, \"parent set\")\n\teqInt(t, 2, int64(n.Depth), \"depth 2\")\n}\n\nfunc TestSubnameOwnerMode(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"company\", alice, 100000)\n\tsetPolicy(cur, \"company\", alice, ModeOwner)\n\n\t// parent owner can create\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreateSubname(cross(cur), \"company\", \"team\", carol, SubnameOptions{Duration: 100000})\n\towner, ok := OwnerOf(\"team.company\")\n\tisTrue(t, ok, \"owner-mode subname created by parent owner\")\n\teqStr(t, carol.String(), owner, \"assigned owner carol\")\n\n\t// authorization for a non-owner is rejected at the gate (pure check on the\n\t// parent's ManageSubnames permission).\n\tp := getRaw(\"company\")\n\terrIs(t, authorize(bob, p, PermManageSubnames), errUnauthorized, \"bob cannot manage company subnames\")\n}\n\nfunc TestSubnameClosedByDefault(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"company\", alice, 100000)\n\t// default policy after registration is Closed\n\tp := getRaw(\"company\")\n\teqStr(t, ModeClosed, p.RegistrationPolicy.Mode, \"default closed\")\n}\n\nfunc TestParentGenerationInvalidatesChild(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"company\", alice, 1000)\n\tsetPolicy(cur, \"company\", alice, ModeOpen)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tCreateSubname(cross(cur), \"company\", \"api\", bob, SubnameOptions{Duration: 1000000})\n\n\tisTrue(t, Exists(\"api.company\"), \"child exists initially\")\n\n\t// expire the parent and re-register it (new generation)\n\ttesting.SkipHeights(500) // beyond parent grace\n\tdoRegister(cur, \"company\", carol, 1000)\n\n\t// invariant 16 / recycling: the old child must NOT silently survive under\n\t// the recycled parent (ParentGeneration mismatch).\n\teqStr(t, string(StatusExpired), string(Status(\"api.company\")), \"orphaned child invalid\")\n\tisFalse(t, Exists(\"api.company\"), \"recycled-parent child not resurrected\")\n}\n\nfunc TestEmancipationRestrictOnly(t *testing.T) {\n\treset()\n\t// invariant 5: a permanent policy can only become more restrictive.\n\tbase := ControlPolicy{\n\t\tOwnerCanTransfer:       true,\n\t\tOwnerCanCreateSubnames: true,\n\t\tRecordsMutable:         true,\n\t\tParentCanReclaim:       true,\n\t\tParentCanTransfer:      true,\n\t}\n\t// try to RELAX ParentCanReclaim false-\u003e... and turn things on\n\treq := ControlPolicy{\n\t\tOwnerCanTransfer:       true,\n\t\tOwnerCanCreateSubnames: true,\n\t\tRecordsMutable:         true,\n\t\tParentCanReclaim:       false, // restrict (allowed)\n\t\tParentCanTransfer:      true,\n\t\tPermanent:              true,\n\t}\n\tgot := mergeRestrictive(base, req)\n\tisFalse(t, got.ParentCanReclaim, \"reclaim restricted true-\u003efalse\")\n\tisTrue(t, got.OwnerCanTransfer, \"transfer kept true\")\n\tisTrue(t, got.Permanent, \"permanent turned on\")\n\n\t// now, once permanent, attempting to RE-ENABLE reclaim must not work\n\trelax := ControlPolicy{\n\t\tOwnerCanTransfer:       true,\n\t\tOwnerCanCreateSubnames: true,\n\t\tRecordsMutable:         true,\n\t\tParentCanReclaim:       true, // attempt to relax false-\u003etrue\n\t\tParentCanTransfer:      true,\n\t\tPermanent:              true,\n\t}\n\tgot2 := mergeRestrictive(got, relax)\n\tisFalse(t, got2.ParentCanReclaim, \"cannot relax false-\u003etrue (invariant 5)\")\n}\n\nfunc TestLockPolicyEmancipatesChild(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"company\", alice, 100000)\n\tsetPolicy(cur, \"company\", alice, ModeOpen)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tCreateSubname(cross(cur), \"company\", \"wallet\", bob, SubnameOptions{\n\t\tDuration:      100000,\n\t\tControlPolicy: ControlPolicy{OwnerCanTransfer: true, RecordsMutable: true, ParentCanTransfer: true},\n\t})\n\n\t// child owner locks out parent transfer power\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tLockPolicy(cross(cur), \"wallet.company\", ControlPolicy{\n\t\tOwnerCanTransfer: true,\n\t\tRecordsMutable:   true,\n\t\tParentCanTransfer: false, // remove parent power\n\t\tPermanent:        true,\n\t})\n\n\tchild := getRaw(\"wallet.company\")\n\tisFalse(t, child.ControlPolicy.ParentCanTransfer, \"parent transfer removed\")\n\tisTrue(t, child.ControlPolicy.Permanent, \"now permanent\")\n\n\t// invariant 4: parent can no longer transfer the child\n\terrIs(t, authorize(alice, child, PermTransfer), errUnauthorized, \"parent lost transfer power\")\n}\n\nfunc TestDeleteSubname(cur realm, t *testing.T) {\n\treset()\n\tdoRegister(cur, \"company\", alice, 100000)\n\tsetPolicy(cur, \"company\", alice, ModeOpen)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tCreateSubname(cross(cur), \"company\", \"temp\", bob, SubnameOptions{Duration: 100000})\n\tisTrue(t, Exists(\"temp.company\"), \"subname created\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tDeleteSubname(cross(cur), \"temp.company\")\n\tisFalse(t, Exists(\"temp.company\"), \"subname deleted\")\n}\n"}]},"send":"","max_deposit":"45000000ugnot"}],"fee":{"gas_wanted":"300789800","gas_fee":"902369ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"RovvYZj60I0KtwZgQy1qni1QY3hgJaJR+CnBBnWD5jZVKZPPi9boH1pSUToGo6B3fqh+hdTrW3arxsk4zC/qqg=="}],"memo":""},"metadata":{"timestamp":"1790960457"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"IVx7dlCYXfxaawqMDo21gMhdvz/M9ga4zDtYkoGy1o0n0eWgRUYeQRicNhg9+TjS1V/EAR0zgPghnX+MViNtAw=="}],"memo":""},"metadata":{"timestamp":"1790960458"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Sr3QwVYv09NMeZW0nKIvhTydOEhlL3j/+AF+RUf7JdV+7W96h+3q+iMZicAteP8v122wlOMTlHHSQs0ZcKe8jA=="}],"memo":""},"metadata":{"timestamp":"1790960513"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"grant","path":"gno.land/r/moul/grant/v0","files":[{"name":"README.md","body":"# grant\n\nmoul's personal grant board. He funds it out of his own pocket, he is the only member, and\nit exists mainly so the coding agents working on his repos, and the people he already works\nwith, have a way to ask for money against work they can prove they did: a request, a\nmilestone, a link to the merged PR, a tranche. **It is open to anyone.** Nothing here is\nprivileged to a bot.\n\n## What this is not\n\n**Not a faucet, and not an official gno.land grant program.** It is one person's money,\nsent by hand, mostly to people he already knows, and it is also a proof of concept for the\nlibrary underneath. There is no entitlement, no queue and no service level: a request can\nsit here unanswered, or be refused with one line of reasoning and nothing further.\n\nAn official programme, where anyone asks for tokens and a DAO decides, is a separate thing\nthat does not exist yet. Neither this README nor the rendered page names a path for it: a\nnamed path reads as a commitment, and nobody has made one. When it exists, it is another\n~130-line realm over the same library, not a change to this one.\n\nThis board stays personal, and its limits are on the page rather than in a comment: one\nmember means \"a majority of the board\" is one signature, and the board page says so.\n\n## What is here, versus in the library\n\nAlmost nothing. Every rule, every tally and every markdown page comes from\n[`p/moul/grants/v0`](/p/moul/grants/v0), which is pure and has no idea coins exist. This\nrealm is the chain-facing half: it turns the caller into an address and the block into a\nheight, holds the one `Program`, moves ugnot through the banker, and emits events. Each\nexported function is four to eight lines of glue.\n\nThat split is deliberate. The next board (multi-member, differently funded, maybe a\ndifferent denomination) is another file this short, not a fork of this one.\n\n## Calling it\n\n| Call | Who | What it does |\n|---|---|---|\n| `Fund` | anyone | sends ugnot to the treasury, with your name on the ledger |\n| `Apply` | anyone | asks for money for yourself, split into milestones |\n| `ApplyFor` | anyone | the same, for a different payee, with a reason |\n| `Vote` | members | carries or kills the application, with a reason |\n| `Retract` | the applicant | pulls their own request before it is decided |\n| `ProposeMember` | members | adds or removes a seat, decided the same way |\n| `SubmitProof` | the applicant or the payee | shows what was done for the next milestone |\n| `Review` | members | accepts or refuses that proof; accepting **pays the tranche** |\n\nMilestones are given to `Apply` as a string, `\"design:100,ship:400\"`, amounts in ugnot,\npaid in the order written. The amount is whatever follows the **last** colon, so\n`\"port gno:land tooling:250\"` parses the way it reads.\n\n```sh\ngnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func Fund -send 5000000ugnot …\ngnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func Apply \\\n  -args 'Port the thing' -args 'why it matters' -args 'design:100,ship:400' …\ngnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func SubmitProof \\\n  -args 1 -args 0 -args url -args 'https://github.com/…/pull/1' -args 'merged' …\n```\n\n## Asking for someone else\n\n`ApplyFor(beneficiary, reason, title, body, milestones)` files a request whose tranches pay\nan address other than the caller's.\n\nThat is not a convenience. **An account with nothing in it cannot pay the gas to ask for its\nfirst coins**, so on a board meant to fund empty accounts, someone else filing is the only\npath that works at all. The same follows through the rest of the lifecycle: either the\napplicant or the beneficiary may `SubmitProof`, because the payee may not be able to\ntransact until the first tranche lands.\n\nTwo rules keep the detour honest, and both are enforced by the library, not by this realm:\n\n- **The reason is required**, and it is printed on the request page under its own heading.\n  Nothing verifies it. It is a claim by the applicant, and printing it is what lets a member\n  check it before voting.\n- **Both addresses are barred from voting** on the request and on its proofs. A member paid\n  by a request a friend filed is the same conflict of interest with one address in between,\n  and the majority is recomputed over whoever is left.\n\n```sh\ngnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func ApplyFor \\\n  -args g1… -args 'their account is empty, they cannot pay the gas' \\\n  -args 'Fund a first key' -args 'so they can transact at all' -args 'first transfer:300' …\n```\n\n## For agents\n\nA gno.land **account session** scoped to `gno.land/r/moul/grant/v0` lets an agent `Apply`,\n`ApplyFor` and `SubmitProof` under its own address, so its track record on this board is its own and\nnot its operator's. Anyone reading the board sees which address asked, what it promised,\nwhat it shipped and what it was paid.\n\nA session cannot be handed a board seat by scoping alone: voting is membership, and\nmembership is a request the board decides. An agent can therefore earn money here without\never being able to approve its own work.\n\n## What \"transparent\" means here, concretely\n\nNothing about a decision is private or derived. Every ballot is stored with its voter, its\nreason and the height, and rendered, **including the ones on proofs that were refused**: a\nrejected grant keeps the sentences that rejected it. Every string a caller typed is escaped\nbefore it renders, so a title or a proof cannot forge a link, a heading or a gnoweb tag on\na page the realm signs its name to. Every payment is on `:ledger` with the\nheight, the request, the milestone, the payee and the amount, and emits a `Release` event.\nEvery donation through `Fund` is on the same page with the donor's address. The treasury\npanel prints the balance next to what is already promised, so an over-committed board is\nvisible on the front page instead of at payout time.\n\n## The treasury is not escrowed\n\nApproving a grant promises money; it does not move or lock any, so `Available()` can go\nnegative. The safety is at release time: `Review` refuses, before recording anything, a\nverdict that would release a tranche the balance cannot cover. Nothing is written and no\nmilestone is marked released that nobody can settle. Full reasoning in the\n[library README](/p/moul/grants/v0).\n\n## Nothing is seeded\n\nThe board ships empty: one member, no requests, no history. What `Render(\"\")` prints in the\npinned example test *is* the deployed state. For a board mid-flight, with ballots, refused\nproofs and a paid tranche, see the `ExampleRenderer*` tests in `p/moul/grants/v0`; the\nmarkdown comes from the same `Renderer`.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/grant/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/grant/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/grant/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/grant/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/grant/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/grant/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/grant/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/grant/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/grant/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/grant/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/grant/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"grant.gno","body":"// Package grant is moul's personal grant board.\n//\n// It is small on purpose. moul funds it out of his own pocket, moul is the\n// only member, and it exists mainly so the coding agents working on his repos\n// and the people he already works with have a way to ask for money against\n// work they can prove they did: a request, a milestone, a link to the merged\n// PR, a tranche. It is open to anyone, not only to agents, and nothing here is\n// privileged to a bot.\n//\n// # What this is NOT\n//\n// It is not a faucet, and it is not an official gno.land grant program. There\n// is no entitlement, no queue and no service level: a request can sit here\n// unanswered, or be refused with one line of reasoning and nothing further.\n// The official thing, where anyone asks for tokens and a DAO decides, is a\n// separate program that does not exist yet, at a path this realm deliberately\n// does not name: naming one would read as a commitment nobody has made. This\n// realm is moul's own money and a proof of concept for the library under it.\n//\n// A bigger, multi-member, better funded program is a separate thing and will\n// live at its own path. This one stays personal, and its limits are on the\n// page rather than in a comment: one member means \"a majority of the board\" is\n// one signature, and the board page says so.\n//\n// # What is here versus in the library\n//\n// Almost nothing. Every rule, every tally, every markdown page comes from\n// gno.land/p/moul/grants/v0, which is pure and has no idea coins exist. This\n// file is the chain-facing half: it turns the caller into an address and the\n// block into a height, holds the one Program, moves ugnot through the banker,\n// and emits events. That is deliberate, so the next board (multi-member,\n// differently funded, maybe a different denom) is another file this short and\n// not a fork of this one.\n//\n// # Who the caller is\n//\n// Every actor is PreviousRealm().Address(), the immediate caller. Called\n// through another realm that is the calling REALM, not the user behind it.\n// An agent holding a gno.land account session scoped to this path applies and\n// submits proofs as its own address, which is exactly what makes an agent's\n// track record on this board its own and not moul's.\npackage grant\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/grants/v0\"\n)\n\nconst (\n\t// Denom is the only coin this board holds or pays.\n\tDenom = \"ugnot\"\n\t// Path is this realm's package path; its treasury is derived from it.\n\tPath = \"gno.land/r/moul/grant/v0\"\n\t// Link is Path as a gnoweb route.\n\tLink = \"/r/moul/grant/v0\"\n)\n\n// Owner is the founding and, for now, only member.\n//\n// Hardcoded rather than taken from the deployer: inside a plain\n// `func Test(t *testing.T)` the gno test runner reports OriginCaller() as the\n// EMPTY address, so a board seeded from it is empty in every test and\n// something else on chain. That divergence is exactly where an authorization\n// bug hides, so the address is written down.\nconst Owner = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\nvar program *grants.Program\n\nfunc init() { reset() }\n\n// reset installs a fresh, empty board. Also called by the tests: realm globals\n// persist for a whole test binary and examples run after every Test, so a\n// pinned Render has to start from a known state.\nfunc reset() { program = grants.NewProgram(Denom, Owner) }\n\n// Address is the treasury: this realm's own package address. Fund it by\n// sending ugnot to it, or by calling Fund with `-send`.\nfunc Address() address { return chain.PackageAddress(Path) }\n\n// Balance is what the treasury actually holds.\nfunc Balance() int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(Address()).AmountOf(Denom)\n}\n\n// Committed is what approved grants can still claim, Available is the balance\n// minus that, and it can go negative. See the library for why.\nfunc Committed() int64 { return program.Committed() }\nfunc Available() int64 { return program.Available(Balance()) }\n\n// Raised is everything donated through Fund, Disbursed everything paid out.\nfunc Raised() int64    { return program.Raised() }\nfunc Disbursed() int64 { return program.Disbursed() }\n\n// Members lists the board.\nfunc Members() []address { return program.Board.Members() }\n\n// Requests is how many requests have ever been filed.\nfunc Requests() int { return program.Board.Size() }\n\n// Fund credits the ugnot sent with the call to the treasury and puts the donor\n// on the record. Coins sent to the realm address directly still land in the\n// treasury; they just do not get a name next to them.\nfunc Fund(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\t// OriginSend is what the SIGNER attached, not what reached this realm. A\n\t// realm the user called keeps those coins and could call Fund any number of\n\t// times, booking each as a donation, so only a user call may read it.\n\tprev := cur.Previous()\n\tif !prev.IsUserCall() {\n\t\tpanic(\"grant: Fund must be called directly by an account, with -send\")\n\t}\n\tfrom := prev.Address()\n\tamount := unsafe.OriginSend().AmountOf(Denom)\n\tif err := program.Fund(from, amount, runtime.ChainHeight()); err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\"Fund\", \"from\", from.String(), \"amount\", strconv.FormatInt(amount, 10))\n}\n\n// Apply files a grant request for the caller. milestones reads\n// \"title:amount,title:amount\", amounts in ugnot, paid in the order given.\n// Returns the request id.\nfunc Apply(cur realm, title, body, milestones string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\tapplicant := cur.Previous().Address()\n\treturn file(applicant, applicant, \"\", title, body, milestones)\n}\n\n// ApplyFor files a grant request whose tranches pay beneficiary rather than\n// the caller, with a reason for the detour that goes on the request page.\n//\n// This is the call that makes the board usable at all for the case it exists\n// to serve. An account with nothing in it cannot pay the gas to ask for its\n// first coins, so without someone else filing on its behalf the people who\n// most need a small grant are exactly the people who cannot ask for one.\n// Either address may then submit the proofs, and neither may vote.\nfunc ApplyFor(cur realm, beneficiary, reason, title, body, milestones string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\tapplicant := cur.Previous().Address()\n\treturn file(applicant, address(beneficiary), reason, title, body, milestones)\n}\n\nfunc file(applicant, beneficiary address, reason, title, body, milestones string) int {\n\tr, err := program.ApplyFor(applicant, beneficiary, reason, title, body, milestones,\n\t\truntime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\"Apply\", \"id\", strconv.Itoa(r.ID), \"applicant\", applicant.String(),\n\t\t\"beneficiary\", r.Payee().String(), \"total\", strconv.FormatInt(r.Total(), 10))\n\treturn r.ID\n}\n\n// ProposeMember asks the board to add or remove a member. Members only.\nfunc ProposeMember(cur realm, addr string, add bool, body string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\tproposer := cur.Previous().Address()\n\tr, err := program.Board.SubmitMemberChange(proposer, address(addr), add, body, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\"ProposeMember\", \"id\", strconv.Itoa(r.ID), \"subject\", addr,\n\t\t\"add\", strconv.FormatBool(add))\n\treturn r.ID\n}\n\n// Retract pulls the caller's own request before it is decided.\nfunc Retract(cur realm, id int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\tif err := program.Board.Withdraw(caller, id, runtime.ChainHeight()); err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\"Retract\", \"id\", strconv.Itoa(id))\n}\n\n// Vote records a member's ballot. The reason is stored and rendered next to\n// the vote: it is the only part of a decision that tells an applicant what to\n// do about it.\nfunc Vote(cur realm, id int, approve bool, reason string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\tvoter := cur.Previous().Address()\n\tst, err := program.Board.Vote(voter, id, approve, reason, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\"Vote\", \"id\", strconv.Itoa(id), \"voter\", voter.String(),\n\t\t\"approve\", strconv.FormatBool(approve), \"status\", st.String())\n}\n\n// SubmitProof offers evidence for the next milestone of an approved grant.\n// kind is \"url\", \"hash\" or \"text\"; ref is the link, digest or statement.\nfunc SubmitProof(cur realm, id, milestone int, kind, ref, note string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\tp := grants.Proof{Kind: kind, Ref: ref, Note: note, Height: runtime.ChainHeight()}\n\tif err := program.Board.SubmitProof(caller, id, milestone, p); err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\"SubmitProof\", \"id\", strconv.Itoa(id),\n\t\t\"milestone\", strconv.Itoa(milestone), \"kind\", kind)\n}\n\n// Review records a member's verdict on the proof under review. The verdict\n// that carries also pays the tranche, in this same transaction. A verdict the\n// treasury cannot cover is refused outright and changes nothing.\nfunc Review(cur realm, id, milestone int, accept bool, reason string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grant: spoofed realm\")\n\t}\n\tvoter := cur.Previous().Address()\n\tout, pay, err := program.Review(voter, id, milestone, accept, reason, runtime.ChainHeight(), Balance())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tchain.Emit(\"Review\", \"id\", strconv.Itoa(id), \"milestone\", strconv.Itoa(milestone),\n\t\t\"voter\", voter.String(), \"accept\", strconv.FormatBool(accept), \"outcome\", out.String())\n\tif pay == nil {\n\t\treturn\n\t}\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur).\n\t\tSendCoins(Address(), pay.To, chain.NewCoins(chain.NewCoin(Denom, pay.Amount)))\n\tchain.Emit(\"Release\", \"id\", strconv.Itoa(id), \"milestone\", strconv.Itoa(milestone),\n\t\t\"to\", pay.To.String(), \"amount\", strconv.FormatInt(pay.Amount, 10))\n}\n"},{"name":"grant_test.gno","body":"package grant\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/grants/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\tzoe = address(\"g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz\") // an applicant\n\tkim = address(\"g1jvh5ukk07dvd57fxefcp5aa29xaydxmxs7myyp\") // a second one\n)\n\nfunc balanceOf(a address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(a).AmountOf(Denom)\n}\n\nfunc issue(n int64) { testing.IssueCoins(Address(), chain.NewCoins(chain.NewCoin(Denom, n))) }\n\nfunc TestFreshBoardIsOwnedAndEmpty(t *testing.T) {\n\treset()\n\tuassert.True(t, Owner.IsValid(), \"the owner is a real address\")\n\tuassert.True(t, zoe.IsValid())\n\tuassert.True(t, kim.IsValid())\n\tuassert.True(t, Address().IsValid(), \"the treasury address\")\n\n\turequire.Equal(t, 1, len(Members()))\n\tuassert.Equal(t, Owner.String(), Members()[0].String())\n\tuassert.Equal(t, 0, Requests(), \"nothing seeded, this board is real\")\n\tuassert.Equal(t, int64(0), Committed())\n\tuassert.Equal(t, int64(0), Raised())\n\tuassert.Equal(t, int64(0), Disbursed())\n}\n\n// The whole path with real coins, on a one-member board: the owner is the\n// majority, so one ballot carries and one review pays.\nfunc TestApplyApproveProveGetPaid(cur realm, t *testing.T) {\n\treset()\n\turequire.Equal(t, int64(0), Balance(), \"start from an empty treasury\")\n\n\t// Someone funds the board, by name.\n\tissue(500)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(Denom, 500)))\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tFund(cross(cur))\n\tuassert.Equal(t, int64(500), Balance())\n\tuassert.Equal(t, int64(500), Raised())\n\tuassert.Equal(t, kim.String(), program.Donations[0].From.String())\n\n\t// An outsider applies. Anyone may.\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tid := Apply(cross(cur), \"Ship the indexer\", \"two tranches\", \"alpha:100,beta:400\")\n\tuassert.Equal(t, 1, id)\n\tuassert.Equal(t, int64(0), Committed(), \"a pending request promises nothing\")\n\n\t// A non-member cannot vote, not even the applicant.\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tuassert.AbortsContains(t, cur, grants.ErrNotMember.Error(), func() {\n\t\tVote(cross(cur), id, true, \"me again\")\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tVote(cross(cur), id, true, \"worth it\")\n\tuassert.Equal(t, int64(500), Committed(), \"approval promises the full ask\")\n\tuassert.Equal(t, int64(0), Available())\n\n\t// Milestone 1: proof, then the one review that carries also pays.\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tuassert.AbortsContains(t, cur, grants.ErrNotApplicant.Error(), func() {\n\t\tSubmitProof(cross(cur), id, 0, \"url\", \"https://example.com/pr/1\", \"not mine to prove\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tSubmitProof(cross(cur), id, 0, \"url\", \"https://example.com/pr/1\", \"alpha is live\")\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tReview(cross(cur), id, 0, true, \"confirmed\")\n\n\tuassert.Equal(t, int64(100), balanceOf(zoe), \"the tranche landed\")\n\tuassert.Equal(t, int64(400), Balance())\n\tuassert.Equal(t, int64(100), Disbursed())\n\turequire.Equal(t, 1, len(program.Payments))\n\tuassert.Equal(t, int64(100), program.Payments[0].Amount)\n\n\t// Out of order is refused.\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tuassert.AbortsContains(t, cur, grants.ErrOutOfOrder.Error(), func() {\n\t\tSubmitProof(cross(cur), id, 0, \"url\", \"https://example.com/pr/1\", \"again\")\n\t})\n\n\t// Milestone 2: a proof the owner refuses, then one they accept.\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tSubmitProof(cross(cur), id, 1, \"text\", \"trust me\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tReview(cross(cur), id, 1, false, \"no evidence\")\n\tuassert.Equal(t, int64(100), balanceOf(zoe), \"a refused proof pays nothing\")\n\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tSubmitProof(cross(cur), id, 1, \"hash\", \"sha256:deadbeef\", \"beta, signed release\")\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tReview(cross(cur), id, 1, true, \"verified\")\n\n\tuassert.Equal(t, int64(500), balanceOf(zoe), \"paid in full\")\n\tuassert.Equal(t, int64(0), Balance(), \"the treasury is back to empty\")\n\tuassert.Equal(t, int64(0), Committed())\n\tuassert.Equal(t, int64(500), Disbursed())\n\tuassert.Equal(t, 2, len(program.Payments))\n\n\t// Both attempts on milestone 2 are on the record, refusal included.\n\tm2 := program.Board.Get(id).Milestones[1]\n\turequire.Equal(t, 2, len(m2.Attempts))\n\tuassert.Equal(t, \"refused\", m2.Attempts[0].Outcome.String())\n\tuassert.Equal(t, \"no evidence\", m2.Attempts[0].Reviews[0].Reason)\n\tuassert.Equal(t, \"accepted\", m2.Attempts[1].Outcome.String())\n}\n\n// The verdict that would release a tranche the treasury cannot pay is refused\n// outright and leaves no trace.\nfunc TestReviewRefusesToReleaseWhatItCannotPay(cur realm, t *testing.T) {\n\treset()\n\turequire.Equal(t, int64(0), Balance(), \"no coins anywhere\")\n\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tid := Apply(cross(cur), \"Ship the indexer\", \"\", \"alpha:100\")\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tVote(cross(cur), id, true, \"worth it\")\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tSubmitProof(cross(cur), id, 0, \"url\", \"https://example.com/pr/1\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, grants.ErrUnderfunded.Error(), func() {\n\t\tReview(cross(cur), id, 0, true, \"confirmed\")\n\t})\n\tm := program.Board.Get(id).Milestones[0]\n\tuassert.Equal(t, 0, len(m.Current().Reviews), \"the ballot was not recorded\")\n\tuassert.False(t, m.Released)\n\tuassert.Equal(t, 0, len(program.Payments))\n\tuassert.Equal(t, int64(-100), Available(), \"and the shortfall is visible\")\n}\n\nfunc TestRetractAndBadInput(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tuassert.AbortsContains(t, cur, grants.ErrBadSpec.Error(), func() {\n\t\tApply(cross(cur), \"Bad\", \"\", \"no amount here\")\n\t})\n\tuassert.Equal(t, 0, Requests(), \"nothing was filed\")\n\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tid := Apply(cross(cur), \"Never mind\", \"\", \"thing:1\")\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tuassert.AbortsContains(t, cur, grants.ErrNotApplicant.Error(), func() {\n\t\tRetract(cross(cur), id)\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tRetract(cross(cur), id)\n\tuassert.Equal(t, \"withdrawn\", program.Board.Get(id).Status.String())\n\n\ttesting.SetOriginSend(chain.NewCoins())\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tuassert.AbortsContains(t, cur, grants.ErrNothingSent.Error(), func() { Fund(cross(cur)) })\n\tuassert.Equal(t, 0, len(program.Donations))\n}\n\n// The owner can hand out a seat, and once there are two members the bar moves\n// to two. That is the path from this personal board to a real one.\nfunc TestProposeMemberGrowsTheBoardAndRaisesTheBar(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tuassert.AbortsContains(t, cur, grants.ErrNotMember.Error(), func() {\n\t\tProposeMember(cross(cur), zoe.String(), true, \"let me in\")\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tid := ProposeMember(cross(cur), kim.String(), true, \"reviews everything anyway\")\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tVote(cross(cur), id, true, \"proposed it\")\n\tuassert.Equal(t, \"completed\", program.Board.Get(id).Status.String())\n\turequire.Equal(t, 2, len(Members()))\n\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tnext := Apply(cross(cur), \"Ship the indexer\", \"\", \"alpha:100\")\n\tr := program.Board.Get(next)\n\tuassert.Equal(t, 2, program.Board.Eligible(r))\n\tuassert.Equal(t, 2, program.Board.Majority(r), \"two members, two signatures\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tVote(cross(cur), next, true, \"worth it\")\n\tuassert.Equal(t, \"pending\", program.Board.Get(next).Status.String(), \"the owner is no longer a majority\")\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tVote(cross(cur), next, true, \"agreed\")\n\tuassert.Equal(t, \"approved\", program.Board.Get(next).Status.String())\n}\n\nfunc TestRenderUnknownPaths(t *testing.T) {\n\treset()\n\tuassert.True(t, len(Render(\"\")) \u003e 0)\n\tuassert.Equal(t, \"# moul's grant board\\n\\nThere is no request 99.\\n\", Render(\"request/99\"))\n\tuassert.True(t, len(Render(\"ledger\")) \u003e 0)\n\tuassert.True(t, len(Render(\"nope\")) \u003e 0)\n}\n\n// The case this board exists for: an account with nothing in it cannot pay the\n// gas to ask for its first coins, so someone else asks for it. The treasury\n// ends where it started, at zero, which is what the pinned pages render.\nfunc TestApplyForPaysTheBeneficiaryNotTheFiler(cur realm, t *testing.T) {\n\treset()\n\turequire.Equal(t, int64(0), Balance())\n\tbefore := balanceOf(kim)\n\n\tissue(300)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(Denom, 300)))\n\ttesting.SetRealm(testing.NewUserRealm(address(Owner)))\n\tFund(cross(cur))\n\n\t// zoe files for kim, whose account is empty.\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tid := ApplyFor(cross(cur), kim.String(), \"kim's account is empty, she cannot pay the gas\",\n\t\t\"Fund a first key\", \"so she can transact at all\", \"first transfer:300\")\n\tr := program.Board.Get(id)\n\turequire.True(t, r.OnBehalf())\n\tuassert.Equal(t, kim.String(), r.Payee().String())\n\n\t// The owner carries it alone, and either party may prove it. Here the\n\t// filer does, because the payee still cannot send a transaction.\n\ttesting.SetRealm(testing.NewUserRealm(address(Owner)))\n\tVote(cross(cur), id, true, \"I know kim.\")\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tSubmitProof(cross(cur), id, 0, \"text\", \"she has a key and no coins\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(address(Owner)))\n\tReview(cross(cur), id, 0, true, \"Sent.\")\n\n\tuassert.Equal(t, before+300, balanceOf(kim), \"the payee got the coins\")\n\tuassert.Equal(t, int64(0), Balance(), \"and the treasury is back to empty\")\n\tuassert.Equal(t, kim.String(), program.Payments[0].To.String())\n\n\t// A reason is not optional when the payee is someone else.\n\ttesting.SetRealm(testing.NewUserRealm(zoe))\n\tuassert.AbortsContains(t, cur, \"needs a reason\", func() {\n\t\tApplyFor(cross(cur), kim.String(), \"\", \"no reason given\", \"\", \"x:1\")\n\t})\n}\n\n// A realm cannot book a donation. It would receive the user's coins itself,\n// then call Fund as many times as it liked, each one reading the same\n// OriginSend and naming it a donation, with nothing reaching the treasury.\nfunc TestFundRefusesARealmCaller(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(Denom, 1_000_000)))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/someone/relay\"))\n\tuassert.AbortsContains(t, cur, \"called directly by an account\", func() { Fund(cross(cur)) })\n\tuassert.Equal(t, int64(0), Raised(), \"nothing booked\")\n}\n"},{"name":"render.gno","body":"package grant\n\nimport \"gno.land/p/moul/grants/v0\"\n\n// The board's whole front page is these three strings plus the library's\n// Renderer. Nothing about the layout lives here, which is the test of whether\n// the split worked: a second board is another file this size.\nconst (\n\tintro = \"A small, personal grant board. moul funds it out of his own pocket, and it\\n\" +\n\t\t\"exists mainly so the coding agents working on his repos, and the people he\\n\" +\n\t\t\"already works with, can ask for money against work they can prove they did: a\\n\" +\n\t\t\"request, a milestone, a link to the merged PR, a tranche. It is open to anyone.\\n\" +\n\t\t\"Nothing here is privileged to a bot.\"\n\n\tnotofficial = \"**This is not a faucet and it is not an official grant program.** It is one\\n\" +\n\t\t\"person's money, sent by hand, mostly to people he already knows, and it is also\\n\" +\n\t\t\"a proof of concept for the library underneath. There is no entitlement, no queue\\n\" +\n\t\t\"and no service level: a request can sit here unanswered, or be refused with one\\n\" +\n\t\t\"line of reasoning and nothing further. An official programme, where anyone asks\\n\" +\n\t\t\"for tokens and a DAO decides, is a separate thing that does not exist yet, and\\n\" +\n\t\t\"this page deliberately does not name a path for it: naming one would read as a\\n\" +\n\t\t\"commitment nobody has made.\"\n\n\tscope = \"**One member, and the page says so.** A majority of a one-member board is one\\n\" +\n\t\t\"signature, so today this is moul deciding in public rather than a DAO deciding.\\n\" +\n\t\t\"What makes it worth reading is the record: every ballot carries its reason,\\n\" +\n\t\t\"every proof stays up including the refused ones, and every coin out is on the\\n\" +\n\t\t\"ledger. A bigger multi-member program is a separate thing and will live at its\\n\" +\n\t\t\"own path.\"\n\n\tforothers = \"**You can ask for someone else.** `ApplyFor` takes the address the money goes\\n\" +\n\t\t\"to and a reason for the detour, and prints both on the request. That is not a\\n\" +\n\t\t\"convenience: an account with nothing in it cannot pay the gas to ask for its\\n\" +\n\t\t\"first coins, so on a board meant to fund empty accounts, someone else filing is\\n\" +\n\t\t\"the only path that works. Either address may then submit the proofs, and neither\\n\" +\n\t\t\"may vote on the request.\"\n\n\tagents = \"**For agents.** A gno.land account session scoped to this path lets an agent\\n\" +\n\t\t\"`Apply` and `SubmitProof` under its own address, so its track record here is\\n\" +\n\t\t\"its own and not its operator's. A session cannot be given a board seat by\\n\" +\n\t\t\"scoping alone: voting is membership, and membership is a request the board\\n\" +\n\t\t\"decides.\"\n\n\tfooter = \"Built on [p/moul/grants/v0](/p/moul/grants/v0), which holds every rule, every\\n\" +\n\t\t\"tally and this page's markdown, and has no idea coins exist.\"\n)\n\n// Render serves the board at \"\", one request at \"request/\u003cid\u003e\", and the money\n// trail at \"ledger\".\nfunc Render(path string) string {\n\treturn grants.Renderer{\n\t\tProgram:  program,\n\t\tTitle:    \"moul's grant board\",\n\t\tIntro:    intro,\n\t\tNotes:    []string{notofficial, scope, forothers, agents},\n\t\tPath:     Path,\n\t\tLink:     Link,\n\t\tTreasury: Address(),\n\t\tBalance:  Balance(),\n\t\tFooter:   footer,\n\t}.Render(path)\n}\n"},{"name":"render_example_test.gno","body":"package grant\n\n// ExampleRender pins the board as it is at deploy: one member, no requests,\n// an empty treasury. That IS the shipped state, since nothing is seeded here.\n// For a board mid-flight, with ballots, refused proofs and a paid tranche,\n// see the pinned pages in p/moul/grants/v0's render_test.gno; the markdown is\n// generated by the same Renderer.\n//\n// It calls reset() first: realm globals persist for the whole test binary and\n// examples run after every Test. The treasury BALANCE is not a realm global\n// and reset() cannot clear it, so the tests are written to be balance-neutral\n// (TestApplyApproveProveGetPaid pays out exactly what it funds). A test that\n// issues coins and does not spend them shows up as a diff here, which is the\n// point.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # moul's grant board\n\t//\n\t// A small, personal grant board. moul funds it out of his own pocket, and it\n\t// exists mainly so the coding agents working on his repos, and the people he\n\t// already works with, can ask for money against work they can prove they did: a\n\t// request, a milestone, a link to the merged PR, a tranche. It is open to anyone.\n\t// Nothing here is privileged to a bot.\n\t//\n\t// **This is not a faucet and it is not an official grant program.** It is one\n\t// person's money, sent by hand, mostly to people he already knows, and it is also\n\t// a proof of concept for the library underneath. There is no entitlement, no queue\n\t// and no service level: a request can sit here unanswered, or be refused with one\n\t// line of reasoning and nothing further. An official programme, where anyone asks\n\t// for tokens and a DAO decides, is a separate thing that does not exist yet, and\n\t// this page deliberately does not name a path for it: naming one would read as a\n\t// commitment nobody has made.\n\t//\n\t// **One member, and the page says so.** A majority of a one-member board is one\n\t// signature, so today this is moul deciding in public rather than a DAO deciding.\n\t// What makes it worth reading is the record: every ballot carries its reason,\n\t// every proof stays up including the refused ones, and every coin out is on the\n\t// ledger. A bigger multi-member program is a separate thing and will live at its\n\t// own path.\n\t//\n\t// **You can ask for someone else.** `ApplyFor` takes the address the money goes\n\t// to and a reason for the detour, and prints both on the request. That is not a\n\t// convenience: an account with nothing in it cannot pay the gas to ask for its\n\t// first coins, so on a board meant to fund empty accounts, someone else filing is\n\t// the only path that works. Either address may then submit the proofs, and neither\n\t// may vote on the request.\n\t//\n\t// **For agents.** A gno.land account session scoped to this path lets an agent\n\t// `Apply` and `SubmitProof` under its own address, so its track record here is\n\t// its own and not its operator's. A session cannot be given a board seat by\n\t// scoping alone: voting is membership, and membership is a request the board\n\t// decides.\n\t//\n\t// ## Treasury\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Address | `g1uah596w03ufkslrjfg8erxszvjq3zra6avs37n` |\n\t// | Balance | 0 ugnot |\n\t// | Promised | 0 ugnot |\n\t// | Unpromised | 0 ugnot |\n\t// | Donated | 0 ugnot |\n\t// | Paid out | 0 ugnot |\n\t//\n\t// ## Board\n\t//\n\t// A decision needs a majority of the members eligible to cast a ballot on it,\n\t// recomputed every time: the party a decision is about never votes on it, so an\n\t// applicant who sits on the board shrinks the room rather than packing it.\n\t//\n\t// | Member | Joined at height |\n\t// |---|---|\n\t// | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` | 0 |\n\t//\n\t// ## Requests\n\t//\n\t// Nothing has been asked of this board yet. `Apply` is open to anyone.\n\t//\n\t// ## Where the money went\n\t//\n\t// [The ledger](/r/moul/grant/v0:ledger) lists every donation in and every tranche\n\t// out, with the height, the payee and the milestone it paid for.\n\t//\n\t// ## Calling it\n\t//\n\t// ```sh\n\t// # put money in\n\t// gnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func Fund -send 5000000ugnot ...\n\t// # ask for some\n\t// gnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func Apply \\\n\t//   -args 'Port the thing' -args 'why it matters' -args 'design:100,ship:400' ...\n\t// # ask on behalf of someone who cannot pay the gas to ask\n\t// gnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func ApplyFor \\\n\t//   -args g1... -args 'their account is empty' \\\n\t//   -args 'Port the thing' -args 'why it matters' -args 'design:100,ship:400' ...\n\t// # decide (members only)\n\t// gnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func Vote -args 1 -args true -args 'reason' ...\n\t// # show your work, then get paid for it\n\t// gnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func SubmitProof \\\n\t//   -args 1 -args 0 -args url -args 'https://...' -args 'what it is' ...\n\t// gnokey maketx call -pkgpath gno.land/r/moul/grant/v0 -func Review -args 1 -args 0 -args true -args 'looks done' ...\n\t// ```\n\t//\n\t// Built on [p/moul/grants/v0](/p/moul/grants/v0), which holds every rule, every\n\t// tally and this page's markdown, and has no idea coins exist.\n}\n\n// ExampleRenderLedger pins the money trail of a board nobody has funded yet.\nfunc ExampleRenderLedger() {\n\treset()\n\tprint(Render(\"ledger\"))\n\t// Output:\n\t// # moul's grant board: the ledger\n\t//\n\t// Every coin in and every coin out, in the order it happened. Coins sent\n\t// straight to `g1uah596w03ufkslrjfg8erxszvjq3zra6avs37n` land in the treasury\n\t// without appearing here, which is why `Fund` exists: it is the same transfer\n\t// with a name attached.\n\t//\n\t// ## In\n\t//\n\t// Nothing donated through `Fund` yet.\n\t//\n\t// ## Out\n\t//\n\t// No tranche has been released yet.\n\t//\n\t// Balance now: 0 ugnot. [Back to the board](/r/moul/grant/v0).\n}\n"}]},"send":"","max_deposit":"15000000ugnot"}],"fee":{"gas_wanted":"109099600","gas_fee":"327298ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"M+3iMHvdJ+QK6eXsoZ8WLTkKV/Cr226Uvo29VOpk5YAYjXSRqgsg26TXcPy+Kpof8jJ2WEpP/Eo6O9VWfFmr+w=="}],"memo":""},"metadata":{"timestamp":"1790960576"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"hello","path":"gno.land/r/moul/hello/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/hello/v0`\n\nCanary realm proving the end-to-end pipeline (imports p/moul/greet/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/hello/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/hello/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/hello/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/hello/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/hello/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/hello/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/hello/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/hello/v0\"\ngno = \"0.9\"\n"},{"name":"hello.gno","body":"// Package hello is a canary realm: it proves the end-to-end pipeline (workspace\n// resolution of a versioned local dependency, gno test, gno lint, and CI)\n// works from the very first commit. It has no external dependencies. Remove it\n// once real realms land.\npackage hello\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/greet/v0\"\n)\n\n// greets counts how many times Greet has been called (persistent state).\nvar greets int\n\n// Greet records a greeting from the caller and returns it. Crossing function:\n// it mutates persistent state, so it takes `cur realm` per the gno 0.9\n// interrealm convention.\nfunc Greet(cur realm, name string) string {\n\tgreets++\n\treturn greet.Greet(name)\n}\n\n// Count returns how many greetings have been recorded. Read-only.\nfunc Count() int { return greets }\n\n// Render is the gnoweb Markdown view.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# r/moul/hello/v0\\n\\n\")\n\tb.WriteString(\"Canary realm for the gno-contracts repository.\\n\\n\")\n\tb.WriteString(\"- Greetings recorded: \")\n\tb.WriteString(itoa(greets))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\n// itoa avoids importing strconv for a single conversion in the canary.\nfunc itoa(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\tneg := n \u003c 0\n\tif neg {\n\t\tn = -n\n\t}\n\tvar buf [20]byte\n\ti := len(buf)\n\tfor n \u003e 0 {\n\t\ti--\n\t\tbuf[i] = byte('0' + n%10)\n\t\tn /= 10\n\t}\n\tif neg {\n\t\ti--\n\t\tbuf[i] = '-'\n\t}\n\treturn string(buf[i:])\n}\n"},{"name":"hello_test.gno","body":"package hello\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestGreetAndCount(cur realm, t *testing.T) {\n\tif got := Count(); got != 0 {\n\t\tt.Fatalf(\"initial count = %d, want 0\", got)\n\t}\n\tif got := Greet(cross(cur), \"moul\"); got != \"Hello, moul!\" {\n\t\tt.Errorf(\"Greet = %q, want %q\", got, \"Hello, moul!\")\n\t}\n\tGreet(cross(cur), \"\")\n\tif got := Count(); got != 2 {\n\t\tt.Errorf(\"count = %d, want 2\", got)\n\t}\n}\n\nfunc TestRender(t *testing.T) {\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"r/moul/hello/v0\") {\n\t\tt.Errorf(\"render missing header: %q\", out)\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"20811400","gas_fee":"62434ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"f4znY9Ps9jEydeMuGDAy2rLp8k6wcibTcENgeCxG6U0Csfz7k4b2aO2nyJNXKM6D6Cz81PXtfNPnbLaS9uJHgQ=="}],"memo":""},"metadata":{"timestamp":"1790960579"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"outfmt","path":"gno.land/r/moul/outfmt/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/outfmt`\n\nA realm that returns the same data in three shapes, selected by a query\nparameter. It exists to show that `Render` is a general response builder and\nnot only a Markdown emitter.\n\n| path | output |\n| --- | --- |\n| `\"\"` | an index of the three formats |\n| `?fmt=stringer` | human-readable text (the default) |\n| `?fmt=json` | a JSON object |\n| `?fmt=jsonp` | the same JSON wrapped in `callback(...)` |\n\nAnything else panics.\n\n```bash\ngnokey query vm/qrender -data 'gno.land/r/moul/outfmt:?fmt=json' \\\n  -remote https://rpc.gno.land:443\n```\n\nThe payload is a `Result` (a number, a text, a slice of numbers) drawn from a\npackage-level `math/rand` source with a fixed seed (`rand.NewPCG(0, 0)`). A\n`Render` call is a query, so the draws it makes are never committed.\n\n## Known rough edges\n\nBoth are marked `FIXME` in the source and are kept as-is, because they are the\ninteresting part:\n\n- The query string is split by hand on `?` and `=` instead of going through\n  `net/url`, so `?fmt=json\u0026x=1` does not parse.\n- Nothing can set a content type. A realm returns a string; the JSON variant is\n  JSON only by convention, and the `jsonp` callback name is hardcoded to\n  `callback` rather than read from the query.\n\nA realm cannot negotiate content properly today. That limitation is what this\nrealm documents.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/outfmt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/outfmt/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/outfmt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/outfmt/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/outfmt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/outfmt/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/outfmt/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/outfmt/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/outfmt/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/outfmt/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/outfmt/v0\"\ngno = \"0.9\"\n"},{"name":"outfmt.gno","body":"package outfmt\n\nimport (\n\t\"math/rand\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\ntype Result struct {\n\tNumber  int\n\tText    string\n\tNumbers []int\n}\n\nfunc (res *Result) String() string {\n\toutput := ufmt.Sprintf(\"Text: %s\\n\", res.Text)\n\toutput += ufmt.Sprintf(\"Number: %d\\n\", res.Number)\n\n\toutput += \"Numbers:\"\n\tfor _, number := range res.Numbers {\n\t\toutput += ufmt.Sprintf(\" %d\", number)\n\t}\n\toutput += \"\\n\"\n\n\treturn output\n}\n\nvar rSeed = rand.NewPCG(0, 0)\n\nfunc genResult() Result {\n\tr := rand.New(rSeed)\n\n\t// init rand\n\tres := Result{\n\t\tText:   \"Hello Gnomes!\",\n\t\tNumber: r.IntN(1000),\n\t}\n\n\tlength := r.IntN(8) + 2\n\tres.Numbers = make([]int, length)\n\tfor i := 0; i \u003c length; i++ {\n\t\tres.Numbers[i] = r.IntN(100)\n\t}\n\n\treturn res\n}\n\n// marshal function to manually convert struct to JSON string\nfunc (r Result) marshal() string {\n\t// Start JSON string\n\tjsonStr := `{\"Number\":` + strconv.Itoa(r.Number) + `,\"Text\":\"` + r.Text + `\",\"Numbers\":[`\n\n\tfor i, num := range r.Numbers {\n\t\tjsonStr += strconv.Itoa(num)\n\t\tif i \u003c len(r.Numbers)-1 {\n\t\t\tjsonStr += \",\"\n\t\t}\n\t}\n\n\tjsonStr += \"]}\"\n\n\treturn jsonStr\n}\n\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\toutput := \"\"\n\t\toutput += \"* [?fmt=stringer](/r/moul/outfmt:?fmt=stringer)\\n\"\n\t\toutput += \"* [?fmt=json](/r/moul/outfmt:?fmt=json)\\n\"\n\t\toutput += \"* [?fmt=jsonp](/r/moul/outfmt:?fmt=jsonp)\\n\"\n\t\treturn output\n\t}\n\n\t// parsing\n\tfmt := \"stringer\" // default\n\t// FIXME: whitelist and use net/url.\n\t{\n\t\tparts := strings.Split(path, \"?\")\n\t\tif len(parts) == 2 {\n\t\t\t// path := parts[0]\n\t\t\tquery := parts[1]\n\t\t\tif query != \"\" {\n\t\t\t\tparts = strings.Split(query, \"=\")\n\t\t\t\tif len(parts) == 2 {\n\t\t\t\t\tk := parts[0]\n\t\t\t\t\tv := parts[1]\n\t\t\t\t\tif k == \"fmt\" {\n\t\t\t\t\t\tfmt = v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// rendering\n\n\tres := genResult()\n\tswitch fmt {\n\tcase \"stringer\":\n\t\treturn res.String()\n\tcase \"json\":\n\t\t// FIXME: return content-type?\n\t\tout := res.marshal()\n\t\treturn string(out)\n\tcase \"jsonp\":\n\t\t// FIXME: return content-type?\n\t\tcallback := \"callback\" // FIXME: get it from query\n\t\tout := res.marshal()\n\t\treturn callback + \"(\" + string(out) + \")\"\n\tdefault:\n\t\tpanic(\"unknown format\")\n\t}\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"},{"name":"outfmt_test.gno","body":"package outfmt\n\nimport (\n\t\"testing\"\n)\n\nfunc TestRender(t *testing.T) {\n\t// home\n\t{\n\t\tgot := Render(\"\")\n\t\texpected := `* [?fmt=stringer](/r/moul/outfmt:?fmt=stringer)\n* [?fmt=json](/r/moul/outfmt:?fmt=json)\n* [?fmt=jsonp](/r/moul/outfmt:?fmt=jsonp)\n`\n\t\tif got != expected {\n\t\t\tt.Errorf(\"expected %q, got %q.\", expected, got)\n\t\t}\n\t}\n\n\t// stringer\n\t{\n\t\tgot := Render(\"?fmt=stringer\")\n\t\texpected := `Text: Hello Gnomes!\nNumber: 222\nNumbers: 34 44 39 7 72 48 74\n`\n\t\tif got != expected {\n\t\t\tt.Errorf(\"expected %q, got %q.\", expected, got)\n\t\t}\n\t}\n\n\t// stringer again (different seed)\n\t{\n\t\tgot := Render(\"?fmt=stringer\")\n\t\texpected := `Text: Hello Gnomes!\nNumber: 898\nNumbers: 24 25 2\n`\n\t\tif got != expected {\n\t\t\tt.Errorf(\"expected %q, got %q.\", expected, got)\n\t\t}\n\t}\n\n\t// json\n\t{\n\n\t\tgot := Render(\"?fmt=json\")\n\t\texpected := `{\"Number\":746,\"Text\":\"Hello Gnomes!\",\"Numbers\":[57,82,16,14,28,32]}`\n\t\tif got != expected {\n\t\t\tt.Errorf(\"expected %q, got %q.\", expected, got)\n\t\t}\n\t}\n\n\t// jsonp\n\t{\n\t\tgot := Render(\"?fmt=jsonp\")\n\t\texpected := `callback({\"Number\":795,\"Text\":\"Hello Gnomes!\",\"Numbers\":[29,51,88,61,93,21,2,66,79]})`\n\t\tif got != expected {\n\t\t\tt.Errorf(\"expected %q, got %q.\", expected, got)\n\t\t}\n\t}\n}\n"},{"name":"render_example_test.gno","body":"package outfmt\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// * [?fmt=stringer](/r/moul/outfmt:?fmt=stringer)\n\t// * [?fmt=json](/r/moul/outfmt:?fmt=json)\n\t// * [?fmt=jsonp](/r/moul/outfmt:?fmt=jsonp)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"28541200","gas_fee":"85623ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"V8nok4AABKksuAi96lNK0gnNajoAbrZJxPRalKDfElBZa3jElRaL7e4axt711LkqqHLSCInlEXclQJcd6T/KiA=="}],"memo":""},"metadata":{"timestamp":"1790960580"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pilot","path":"gno.land/r/moul/pilot/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/pilot/v0`\n\nmoul's realm-driven account. It holds the funds and the identity; moul's key pilots it; its\npowers arrive afterwards as separate realms this one never imports.\n\nAll behaviour is in [`p/moul/pilot`](../../../p/moul/pilot), which explains the two grants\nand why `Revoke` takes back a purse but never an identity. This realm is the instance: a\n`*pilot.Pilot`, one-line crossing re-exports forwarding `cur`, and `Render`.\n\nA power to try it with: [`r/moul/x/pilotdemo`](../x/pilotdemo).\n\n**`Claim` is pinned to `g1manfred47kzduec920z88wfr64ylksmdcedlf5` in the source.** A deploy\nlands in one block and the claim is a second transaction, so taking the owner from whoever\ncalls first is a race anyone on chain can win, and this path can never be redeployed to undo\nit.\n\n```sh\n# once, and only this address can\ngnokey maketx call -pkgpath gno.land/r/moul/pilot/v0 -func Claim ... moul\n\n# authorise a path that does not have to exist yet\ngnokey maketx call -pkgpath gno.land/r/moul/pilot/v0 -func Approve \\\n  -args gno.land/r/moul/x/pilotdemo/v0 -args payout -args false -args 1000 ... moul\n```\n\n**Public on purpose.** A module realm imports this one and persists objects it owns, both of\nwhich a private realm refuses, and a redeploy would wipe the owner, the roster and every\nbudget while leaving the coins at the treasury address.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/pilot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/pilot/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/pilot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/pilot/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/pilot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/pilot/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/pilot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/pilot/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/pilot/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/pilot/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/pilot/v0\"\ngno = \"0.9\"\n\n# public: a module realm must import this account and persist objects it owns\n# (a Purse, the Account handle), both of which a private realm refuses. And a\n# redeploy wipes every package-level var while keeping the coins, which for an\n# account means the owner, the roster and every budget vanish while the\n# treasury stays: the one realm that must never be replaceable.\n"},{"name":"pilot.gno","body":"// untrusted-render: this realm stores no string of its own. The only two a\n// caller supplies, a module path and its subpath, are written solely by the\n// owner through Approve and charset-validated there (p/moul/pilot assertPlain),\n// which is what lets Render interpolate them.\n// Package pilot is moul's realm-driven account: it holds the funds and the\n// identity, moul's key pilots it, and its powers arrive afterwards as\n// separate realms that this one never imports.\n//\n// All behaviour is in gno.land/p/moul/pilot/v0; this realm is the instance.\n// Demo of a power: r/moul/x/pilotdemo.\npackage pilot\n\nimport \"gno.land/p/moul/pilot/v0\"\n\n// owner is pinned in the source rather than taken from whoever calls Claim\n// first. A deploy lands in its own block and the claim is a second\n// transaction, so an unpinned Claim is a race anyone on chain can win, and\n// this account can never be redeployed to undo it.\nconst owner = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\nvar acct *pilot.Pilot\n\n// Claim arms the account. Once, and only by its owner.\nfunc Claim(cur realm) {\n\tif acct != nil {\n\t\tpanic(\"pilot: already claimed\")\n\t}\n\tif cur.Previous().Address() != owner {\n\t\tpanic(\"pilot: only \" + owner + \" can claim this account\")\n\t}\n\tacct = pilot.New(0, cur)\n}\n\n// Approve authorises a package path to install itself later, under a named\n// sub-identity, with a grant and a budget. The code need not exist yet.\nfunc Approve(cur realm, path, subpath string, identity bool, budget int64) {\n\tgrant := pilot.GrantPurse\n\tif identity {\n\t\tgrant = pilot.GrantIdentity\n\t}\n\tmust().Approve(0, cur, path, subpath, grant, budget)\n}\n\n// SetBudget changes what a module may still spend, including through a purse\n// it already holds.\nfunc SetBudget(cur realm, path string, budget int64) { must().SetBudget(0, cur, path, budget) }\n\n// Revoke stops a module. It cannot take back a granted identity.\nfunc Revoke(cur realm, path string) { must().Revoke(0, cur, path) }\n\n// Fund moves coins from the main treasury into one module's sub-treasury.\nfunc Fund(cur realm, path string, amount int64) { must().Fund(0, cur, path, amount) }\n\n// Exec drives an installed module.\nfunc Exec(cur realm, path, args string) string { return must().Exec(0, cur, path, args) }\n\n// Handle is how a module realm reaches this account. Its two methods key on\n// the caller's own pkgpath, which no realm can forge for another.\nfunc Handle() *pilot.Account { return must().Handle() }\n\n// Address is the main treasury.\nfunc Address() address { return must().Address() }\n\n// SubAddress is one module's treasury.\nfunc SubAddress(path string) address { return must().SubAddress(path) }\n\nfunc Render(path string) string {\n\tif acct == nil {\n\t\treturn \"# gno.land/r/moul/pilot\\n\\nUnclaimed.\\n\"\n\t}\n\treturn acct.Render(path)\n}\n\nfunc must() *pilot.Pilot {\n\tif acct == nil {\n\t\tpanic(\"pilot: unclaimed\")\n\t}\n\treturn acct\n}\n"},{"name":"pilot_test.gno","body":"package pilot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\t// the address Claim is pinned to, not a test address\n\tmoul    = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\tsomeone = testutils.TestAddress(\"someone\")\n)\n\nfunc TestClaimIsOnceAndOwnerGated(cur realm, t *testing.T) {\n\t// anyone else racing the deploy is refused, which is the whole point of\n\t// pinning the address in the source\n\ttesting.SetRealm(testing.NewUserRealm(someone))\n\tuassert.AbortsContains(t, cur, \"only g1manfred\", func() { Claim(cross(cur)) })\n\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tClaim(cross(cur))\n\tuassert.Equal(t, moul.String(), acct.Owner().String())\n\n\ttesting.SetRealm(testing.NewUserRealm(someone))\n\tuassert.AbortsContains(t, cur, \"already claimed\", func() { Claim(cross(cur)) })\n\tuassert.AbortsContains(t, cur, \"not the owner\", func() {\n\t\tApprove(cross(cur), \"gno.land/r/x/nope/v0\", \"nope\", false, 1)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tuassert.AbortsContains(t, cur, \"[a-zA-Z0-9._/-]\", func() {\n\t\tApprove(cross(cur), \"gno.land/r/x/nope/v0\", \"pay|out\", false, 1)\n\t})\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tApprove(cross(cur), \"gno.land/r/moul/x/pilotdemo/v0\", \"payout\", false, 250)\n\n\twant := \"# gno.land/r/moul/pilot/v0\\n\\n\" +\n\t\t\"| | |\\n|---|---|\\n\" +\n\t\t\"| owner | \" + moul.String() + \" |\\n\" +\n\t\t\"| treasury | \" + Address().String() + \" |\\n\" +\n\t\t\"| balance | 0 ugnot |\\n\\n\" +\n\t\t\"## powers\\n\\n\" +\n\t\t\"| path | grant | identity | state | left | runs | sub-treasury |\\n\" +\n\t\t\"|---|---|---|---|---|---|---|\\n\" +\n\t\t\"| `gno.land/r/moul/x/pilotdemo/v0` | purse | `gno.land/r/moul/pilot/v0#payout` | approved | 250 | 0 | 0 ugnot |\\n\"\n\tuassert.Equal(t, want, Render(\"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"32020000","gas_fee":"96060ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"iuDTTNUY3fjFz+ooQEmxZX0WPgxfeELhw6+Rxcc9zcElYpp3gNS6J8siN8WlhoufKHFGdA7tP9AY5D+jlUvMSw=="}],"memo":""},"metadata":{"timestamp":"1790960581"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"present","path":"gno.land/r/moul/present/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/present`\n\nAn on-chain slide deck: store a Markdown presentation, then read it back either\nas one page or one slide at a time.\n\n```go\nfunc Set(cur realm, slug, title, event, author, date, content string) string\nfunc Delete(cur realm, slug string) string\n```\n\nBoth are owner-gated through [`p/nt/ownable`](https://github.com/gnolang/gno/tree/master/examples/gno.land/p/nt/ownable).\n`Set` is an upsert: same slug, new content.\n\n## Routes\n\n| path | view |\n| --- | --- |\n| `\"\"` | index of every presentation |\n| `\u003cslug\u003e` | the whole deck on one page |\n| `\u003cslug\u003e/slides` | slide 1 |\n| `\u003cslug\u003e/slides?page=N` | slide N |\n\nSlides are split on `##` headings, so the deck is authored as ordinary Markdown\nand needs no slide markup. Path parsing goes through\n[`p/moul/realmpath`](../../../p/moul/realmpath), so the navigation links are\nbuilt from the request rather than hardcoded.\n\nPresentations are indexed twice, by `seqid` and by slug, which is what lets the\nindex be listed in insertion order while URLs stay readable.\n\nA `demo` presentation is seeded at deploy time by `present_init.gno`.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/present/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/present/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/present/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/present/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/present/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/present/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/present/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/present/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/present/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/present/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/present/v0\"\ngno = \"0.9\"\n"},{"name":"present.gno","body":"package present\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mdtable/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/avl/pager/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar chainDomain = runtime.ChainDomain()\n\ntype Presentation struct {\n\tid        string\n\tSlug      string\n\tTitle     string\n\tEvent     string\n\tAuthor    string\n\tUploader  address\n\tDate      time.Time\n\tContent   string\n\tEditDate  time.Time\n\tNumSlides int\n}\n\nvar (\n\tbyID    avl.Tree // id -\u003e *Presentation\n\tbySlug  avl.Tree // slug -\u003e *Presentation\n\tidgen   seqid.ID\n\tOwnable *ownable.Ownable\n)\n\n// owner is the realm admin allowed to add/update/delete presentations.\nconst owner address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\" // @moul\n\nfunc init() {\n\tOwnable = ownable.NewWithAddress(owner)\n}\n\n// Render handles the realm's rendering logic\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\t// Get slug from path\n\tslug := req.PathPart(0)\n\n\t// List view (home)\n\tif slug == \"\" {\n\t\treturn renderList(req)\n\t}\n\n\t// Slides view\n\tif req.PathPart(1) == \"slides\" {\n\t\tpage := 1\n\t\tif pageStr := req.Query.Get(\"page\"); pageStr != \"\" {\n\t\t\tvar err error\n\t\t\tpage, err = strconv.Atoi(pageStr)\n\t\t\tif err != nil {\n\t\t\t\treturn \"400: invalid page number\"\n\t\t\t}\n\t\t}\n\t\treturn renderSlides(slug, page)\n\t}\n\n\t// Regular view\n\treturn renderView(slug)\n}\n\n// Set adds or updates a presentation\nfunc Set(cur realm, slug, title, event, author, date, content string) string {\n\tcaller := cur.Previous().Address()\n\tOwnable.AssertOwnedBy(caller)\n\treturn setPresentation(caller, slug, title, event, author, date, content)\n}\n\n// setPresentation is the shared record-mutation preamble used by both the\n// owner-gated Set entrypoint and the init seeding.\nfunc setPresentation(uploader address, slug, title, event, author, date, content string) string {\n\tparsedDate, err := time.Parse(\"2006-01-02\", date)\n\tif err != nil {\n\t\treturn \"400: invalid date format (expected: YYYY-MM-DD)\"\n\t}\n\n\tnumSlides := 1 // Count intro slide\n\tfor _, line := range strings.Split(content, \"\\n\") {\n\t\tif strings.HasPrefix(line, \"## \") {\n\t\t\tnumSlides++\n\t\t}\n\t}\n\tnumSlides++ // Count thank you slide\n\n\t// Reuse the existing id when the slug is already known (update in place).\n\tvar id string\n\tif v := bySlug.Get(slug); v != nil {\n\t\tid = v.(*Presentation).id\n\t} else {\n\t\tid = idgen.Next().String()\n\t}\n\n\tp := \u0026Presentation{\n\t\tid:        id,\n\t\tSlug:      slug,\n\t\tTitle:     title,\n\t\tEvent:     event,\n\t\tAuthor:    author,\n\t\tUploader:  uploader,\n\t\tDate:      parsedDate,\n\t\tContent:   content,\n\t\tEditDate:  time.Now(),\n\t\tNumSlides: numSlides,\n\t}\n\n\tbyID.Set(id, p)\n\tbySlug.Set(slug, p)\n\treturn \"presentation saved successfully\"\n}\n\n// Delete removes a presentation\nfunc Delete(cur realm, slug string) string {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\n\tv := bySlug.Get(slug)\n\tif v == nil {\n\t\treturn \"404: presentation not found\"\n\t}\n\tp := v.(*Presentation)\n\n\t// XXX: consider this:\n\t// if p.Uploader != cur.Previous().Address() {\n\t// \treturn \"401: unauthorized - only the uploader can delete their presentations\"\n\t// }\n\n\tbyID.Remove(p.id)\n\tbySlug.Remove(slug)\n\treturn \"presentation deleted successfully\"\n}\n\nfunc renderList(req *realmpath.Request) string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(\"Presentations\"))\n\n\t// Setup pager over a tree sorted by the requested field.\n\ttree := buildSortTree(getSortField(req))\n\tpgr := pager.NewPager(tree, 10, isSortReversed(req))\n\n\t// Get current page. The pager only reads the query string; pass just the\n\t// query so url.Parse is not tripped by the \"/realm:slug\" colon in the\n\t// full realm path.\n\tpage := pgr.MustGetPageByPath(\"?\" + req.Query.Encode())\n\n\t// Create table\n\tdateColumn := renderSortLink(req, \"date\", \"Date\")\n\ttitleColumn := renderSortLink(req, \"title\", \"Title\")\n\tauthorColumn := renderSortLink(req, \"author\", \"Author\")\n\ttable := mdtable.Table{\n\t\tHeaders: []string{dateColumn, titleColumn, \"Event\", authorColumn, \"Slides\"},\n\t}\n\n\t// Add rows from current page\n\tfor _, item := range page.Items {\n\t\tp := item.Value.(*Presentation)\n\t\ttable.Append([]string{\n\t\t\tp.Date.Format(\"2006-01-02\"),\n\t\t\tmd.Link(p.Title, localPath(p.Slug, nil)),\n\t\t\tp.Event,\n\t\t\tp.Author,\n\t\t\tufmt.Sprintf(\"%d\", p.NumSlides),\n\t\t})\n\t}\n\n\tout.WriteString(table.String())\n\tout.WriteString(page.Picker(\"?\" + req.Query.Encode()))\n\treturn out.String()\n}\n\n// buildSortTree builds an avl.Tree whose keys order the presentations by the\n// requested field. A trailing id keeps keys unique and makes ties\n// deterministic (insertion order).\nfunc buildSortTree(field string) *avl.Tree {\n\ttree := avl.NewTree()\n\tbyID.Iterate(\"\", \"\", func(id string, v any) bool {\n\t\tp := v.(*Presentation)\n\t\tvar key string\n\t\tswitch field {\n\t\tcase \"title\":\n\t\t\tkey = p.Title + \"\\x00\" + id\n\t\tcase \"author\":\n\t\t\tkey = p.Author + \"\\x00\" + id\n\t\tdefault: // date (and any unknown field)\n\t\t\tkey = p.Date.Format(\"2006-01-02\") + \"\\x00\" + id\n\t\t}\n\t\ttree.Set(key, p)\n\t\treturn false\n\t})\n\treturn tree\n}\n\nfunc (p *Presentation) FirstSlide() string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(p.Title))\n\tout.WriteString(md.Paragraph(md.Bold(p.Event) + \", \" + p.Date.Format(\"2 Jan 2006\")))\n\tout.WriteString(md.Paragraph(\"by \" + md.Bold(p.Author))) // XXX: link to u/?\n\treturn out.String()\n}\n\nfunc (p *Presentation) LastSlide() string {\n\tvar out strings.Builder\n\tout.WriteString(md.H1(p.Title))\n\tout.WriteString(md.H2(\"Thank You!\"))\n\tout.WriteString(md.Paragraph(p.Author))\n\tfullPath := \"https://\" + chainDomain + localPath(p.Slug, nil)\n\tout.WriteString(md.Paragraph(\"🔗 \" + md.Link(fullPath, fullPath)))\n\t// XXX: QRCode\n\treturn out.String()\n}\n\nfunc renderView(slug string) string {\n\tif slug == \"\" {\n\t\treturn \"400: missing presentation slug\"\n\t}\n\n\tv := bySlug.Get(slug)\n\tif v == nil {\n\t\treturn \"404: presentation not found\"\n\t}\n\n\tp := v.(*Presentation)\n\tvar out strings.Builder\n\n\t// Header using FirstSlide helper\n\tout.WriteString(p.FirstSlide())\n\n\t// Slide mode link\n\tout.WriteString(md.Link(\"View as slides\", localPath(p.Slug+\"/slides\", nil)) + \"\\n\\n\")\n\tout.WriteString(md.HorizontalRule())\n\tout.WriteString(md.Paragraph(p.Content))\n\n\t// Metadata footer\n\tout.WriteString(md.HorizontalRule())\n\tout.WriteString(ufmt.Sprintf(\"Last edited: %s\\n\\n\", p.EditDate.Format(\"2006-01-02 15:04:05\")))\n\tout.WriteString(ufmt.Sprintf(\"Uploader: `%s`\\n\\n\", p.Uploader))\n\tout.WriteString(ufmt.Sprintf(\"Number of slides: %d\\n\\n\", p.NumSlides))\n\n\t// Admin actions\n\t// XXX: consider a dynamic toggle for admin actions\n\teditLink := txlink.Call(\"Set\",\n\t\t\"slug\", p.Slug,\n\t\t\"title\", p.Title,\n\t\t\"author\", p.Author,\n\t\t\"event\", p.Event,\n\t\t\"date\", p.Date.Format(\"2006-01-02\"),\n\t)\n\tdeleteLink := txlink.Call(\"Delete\", \"slug\", p.Slug)\n\tout.WriteString(md.Paragraph(md.Link(\"Edit\", editLink) + \" | \" + md.Link(\"Delete\", deleteLink)))\n\n\treturn out.String()\n}\n\n// renderSlidesNavigation returns the navigation bar for slides\nfunc renderSlidesNavigation(slug string, currentPage, totalSlides int) string {\n\tvar out strings.Builder\n\tif currentPage \u003e 1 {\n\t\tprevLink := localPath(slug+\"/slides\", url.Values{\"page\": {ufmt.Sprintf(\"%d\", currentPage-1)}})\n\t\tout.WriteString(md.Link(\"← Prev\", prevLink) + \" \")\n\t}\n\tout.WriteString(ufmt.Sprintf(\"| %d/%d |\", currentPage, totalSlides))\n\tif currentPage \u003c totalSlides {\n\t\tnextLink := localPath(slug+\"/slides\", url.Values{\"page\": {ufmt.Sprintf(\"%d\", currentPage+1)}})\n\t\tout.WriteString(\" \" + md.Link(\"Next →\", nextLink))\n\t}\n\treturn md.Paragraph(out.String())\n}\n\nfunc renderSlides(slug string, currentPage int) string {\n\tif slug == \"\" {\n\t\treturn \"400: missing presentation ID\"\n\t}\n\n\tv := bySlug.Get(slug)\n\tif v == nil {\n\t\treturn \"404: presentation not found\"\n\t}\n\n\tp := v.(*Presentation)\n\tslides := strings.Split(\"\\n\"+p.Content, \"\\n## \")\n\tif currentPage \u003c 1 || currentPage \u003e p.NumSlides {\n\t\treturn \"404: invalid slide number\"\n\t}\n\n\tvar out strings.Builder\n\n\t// Display current slide\n\tif currentPage == 1 {\n\t\tout.WriteString(p.FirstSlide())\n\t} else if currentPage == p.NumSlides {\n\t\tout.WriteString(p.LastSlide())\n\t} else {\n\t\tout.WriteString(md.H1(p.Title))\n\t\tout.WriteString(\"## \" + slides[currentPage-1] + \"\\n\\n\")\n\t}\n\n\tout.WriteString(renderSlidesNavigation(slug, currentPage, p.NumSlides))\n\treturn out.String()\n}\n\n// Helper functions for sorting and pagination\nfunc getSortField(req *realmpath.Request) string {\n\tfield := req.Query.Get(\"sort\")\n\tswitch field {\n\tcase \"date\", \"author\", \"title\":\n\t\treturn field\n\t}\n\treturn \"date\"\n}\n\nfunc isSortReversed(req *realmpath.Request) bool {\n\treturn req.Query.Get(\"order\") != \"asc\"\n}\n\nfunc renderSortLink(req *realmpath.Request, field, label string) string {\n\tcurrentField := getSortField(req)\n\tcurrentOrder := req.Query.Get(\"order\")\n\n\tnewOrder := \"desc\"\n\tif field == currentField \u0026\u0026 currentOrder != \"asc\" {\n\t\tnewOrder = \"asc\"\n\t}\n\n\tquery := req.Query\n\tquery.Set(\"sort\", field)\n\tquery.Set(\"order\", newOrder)\n\n\tif field == currentField {\n\t\tif newOrder == \"asc\" {\n\t\t\tlabel += \" ↑\"\n\t\t} else {\n\t\t\tlabel += \" ↓\"\n\t\t}\n\t}\n\n\treturn md.Link(label, \"?\"+query.Encode())\n}\n\n// helper to create local realm links\nfunc localPath(path string, query url.Values) string {\n\treq := \u0026realmpath.Request{\n\t\tPath:  path,\n\t\tQuery: query,\n\t}\n\treturn req.String()\n}\n"},{"name":"present_filetest.gno","body":"// PKGPATH: gno.land/r/moul/main\n\npackage main\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/moul/present/v0\"\n)\n\nfunc main(cur realm) {\n\t// Act as the realm owner so the owner-gated setters are allowed.\n\ttesting.SetRealm(testing.NewUserRealm(present.Ownable.Owner()))\n\n\t// Cleanup initial state\n\tret := present.Delete(cross(cur), \"demo\")\n\tif ret != \"presentation deleted successfully\" {\n\t\tpanic(\"internal error\")\n\t}\n\n\t// Create presentations with IDs from 10-20\n\tpresentations := []struct {\n\t\tid      string\n\t\ttitle   string\n\t\tevent   string\n\t\tauthor  string\n\t\tdate    string\n\t\tcontent string\n\t}{\n\t\t{\"s10\", \"title10\", \"event3\", \"author1\", \"2024-01-01\", \"## s10.0\\n## s10.1\"},\n\t\t{\"s11\", \"title11\", \"event1\", \"author2\", \"2024-01-15\", \"## s11.0\\n## s11.1\"},\n\t\t{\"s12\", \"title12\", \"event2\", \"author1\", \"2024-02-01\", \"## s12.0\\n## s12.1\"},\n\t\t{\"s13\", \"title13\", \"event1\", \"author3\", \"2024-01-20\", \"## s13.0\\n## s13.1\"},\n\t\t{\"s14\", \"title14\", \"event3\", \"author2\", \"2024-03-01\", \"## s14.0\\n## s14.1\"},\n\t\t{\"s15\", \"title15\", \"event2\", \"author1\", \"2024-02-15\", \"## s15.0\\n## s15.1\\n## s15.2\"},\n\t\t{\"s16\", \"title16\", \"event1\", \"author4\", \"2024-03-15\", \"## s16.0\\n## s16.1\"},\n\t\t{\"s17\", \"title17\", \"event3\", \"author2\", \"2024-01-10\", \"## s17.0\\n## s17.1\"},\n\t\t{\"s18\", \"title18\", \"event2\", \"author3\", \"2024-02-20\", \"## s18.0\\n## s18.1\"},\n\t\t{\"s19\", \"title19\", \"event1\", \"author1\", \"2024-03-10\", \"## s19.0\\n## s19.1\"},\n\t\t{\"s20\", \"title20\", \"event3\", \"author4\", \"2024-01-05\", \"## s20.0\\n## s20.1\"},\n\t}\n\n\tfor _, p := range presentations {\n\t\tresult := present.Set(cross(cur), p.id, p.title, p.event, p.author, p.date, p.content)\n\t\tif result != \"presentation saved successfully\" {\n\t\t\tpanic(\"failed to add presentation: \" + result)\n\t\t}\n\t}\n\n\t// Test different sorting scenarios\n\tprintRender(\"\")                       // default\n\tprintRender(\"?order=asc\u0026sort=date\")   // by date ascending\n\tprintRender(\"?order=asc\u0026sort=title\")  // by title ascending\n\tprintRender(\"?order=asc\u0026sort=author\") // by author ascending (multiple entries per author)\n\n\t// Test pagination\n\tprintRender(\"?order=asc\u0026sort=title\u0026page=2\") // second page\n\n\t// Test view\n\tprintRender(\"s15\") // view by slug\n\n\t// Test slides\n\tprintRender(\"s15/slides\")        // slides by slug\n\tprintRender(\"s15/slides?page=2\") // slides by slug, second page\n\tprintRender(\"s15/slides?page=3\") // slides by slug, third page\n\tprintRender(\"s15/slides?page=4\") // slides by slug, fourth page\n\tprintRender(\"s15/slides?page=5\") // slides by slug, fifth page\n}\n\n// Helper function to print path and render result\nfunc printRender(path string) {\n\tprintln(\"+-------------------------------\")\n\tprintln(\"| PATH:\", path)\n\tprintln(\"| RESULT:\\n\" + present.Render(path) + \"\\n\")\n}\n\n// Output:\n// +-------------------------------\n// | PATH:\n// | RESULT:\n// # Presentations\n// | [Date ↑](?order=asc\u0026sort=date) | [Title](?order=desc\u0026sort=title) | Event | [Author](?order=desc\u0026sort=author) | Slides |\n// | --- | --- | --- | --- | --- |\n// | 2024-03-15 | [title16](:s16) | event1 | author4 | 4 |\n// | 2024-03-10 | [title19](:s19) | event1 | author1 | 4 |\n// | 2024-03-01 | [title14](:s14) | event3 | author2 | 4 |\n// | 2024-02-20 | [title18](:s18) | event2 | author3 | 4 |\n// | 2024-02-15 | [title15](:s15) | event2 | author1 | 5 |\n// | 2024-02-01 | [title12](:s12) | event2 | author1 | 4 |\n// | 2024-01-20 | [title13](:s13) | event1 | author3 | 4 |\n// | 2024-01-15 | [title11](:s11) | event1 | author2 | 4 |\n// | 2024-01-10 | [title17](:s17) | event3 | author2 | 4 |\n// | 2024-01-05 | [title20](:s20) | event3 | author4 | 4 |\n// **1** | [2](?page=2\u0026order=desc\u0026sort=author)\n//\n// +-------------------------------\n// | PATH: ?order=asc\u0026sort=date\n// | RESULT:\n// # Presentations\n// | [Date ↓](?order=desc\u0026sort=date) | [Title](?order=desc\u0026sort=title) | Event | [Author](?order=desc\u0026sort=author) | Slides |\n// | --- | --- | --- | --- | --- |\n// | 2024-01-01 | [title10](:s10) | event3 | author1 | 4 |\n// | 2024-01-05 | [title20](:s20) | event3 | author4 | 4 |\n// | 2024-01-10 | [title17](:s17) | event3 | author2 | 4 |\n// | 2024-01-15 | [title11](:s11) | event1 | author2 | 4 |\n// | 2024-01-20 | [title13](:s13) | event1 | author3 | 4 |\n// | 2024-02-01 | [title12](:s12) | event2 | author1 | 4 |\n// | 2024-02-15 | [title15](:s15) | event2 | author1 | 5 |\n// | 2024-02-20 | [title18](:s18) | event2 | author3 | 4 |\n// | 2024-03-01 | [title14](:s14) | event3 | author2 | 4 |\n// | 2024-03-10 | [title19](:s19) | event1 | author1 | 4 |\n// **1** | [2](?page=2\u0026order=desc\u0026sort=author)\n//\n// +-------------------------------\n// | PATH: ?order=asc\u0026sort=title\n// | RESULT:\n// # Presentations\n// | [Date](?order=desc\u0026sort=date) | [Title](?order=desc\u0026sort=title) | Event | [Author](?order=desc\u0026sort=author) | Slides |\n// | --- | --- | --- | --- | --- |\n// | 2024-01-01 | [title10](:s10) | event3 | author1 | 4 |\n// | 2024-01-15 | [title11](:s11) | event1 | author2 | 4 |\n// | 2024-02-01 | [title12](:s12) | event2 | author1 | 4 |\n// | 2024-01-20 | [title13](:s13) | event1 | author3 | 4 |\n// | 2024-03-01 | [title14](:s14) | event3 | author2 | 4 |\n// | 2024-02-15 | [title15](:s15) | event2 | author1 | 5 |\n// | 2024-03-15 | [title16](:s16) | event1 | author4 | 4 |\n// | 2024-01-10 | [title17](:s17) | event3 | author2 | 4 |\n// | 2024-02-20 | [title18](:s18) | event2 | author3 | 4 |\n// | 2024-03-10 | [title19](:s19) | event1 | author1 | 4 |\n// **1** | [2](?page=2\u0026order=desc\u0026sort=author)\n//\n// +-------------------------------\n// | PATH: ?order=asc\u0026sort=author\n// | RESULT:\n// # Presentations\n// | [Date](?order=desc\u0026sort=date) | [Title](?order=desc\u0026sort=title) | Event | [Author](?order=desc\u0026sort=author) | Slides |\n// | --- | --- | --- | --- | --- |\n// | 2024-01-01 | [title10](:s10) | event3 | author1 | 4 |\n// | 2024-02-01 | [title12](:s12) | event2 | author1 | 4 |\n// | 2024-02-15 | [title15](:s15) | event2 | author1 | 5 |\n// | 2024-03-10 | [title19](:s19) | event1 | author1 | 4 |\n// | 2024-01-15 | [title11](:s11) | event1 | author2 | 4 |\n// | 2024-03-01 | [title14](:s14) | event3 | author2 | 4 |\n// | 2024-01-10 | [title17](:s17) | event3 | author2 | 4 |\n// | 2024-01-20 | [title13](:s13) | event1 | author3 | 4 |\n// | 2024-02-20 | [title18](:s18) | event2 | author3 | 4 |\n// | 2024-03-15 | [title16](:s16) | event1 | author4 | 4 |\n// **1** | [2](?page=2\u0026order=desc\u0026sort=author)\n//\n// +-------------------------------\n// | PATH: ?order=asc\u0026sort=title\u0026page=2\n// | RESULT:\n// # Presentations\n// | [Date](?order=desc\u0026page=2\u0026sort=date) | [Title](?order=desc\u0026page=2\u0026sort=title) | Event | [Author](?order=desc\u0026page=2\u0026sort=author) | Slides |\n// | --- | --- | --- | --- | --- |\n// | 2024-01-05 | [title20](:s20) | event3 | author4 | 4 |\n// [1](?page=1\u0026order=desc\u0026sort=author) | **2**\n//\n// +-------------------------------\n// | PATH: s15\n// | RESULT:\n// # title15\n// **event2**, 15 Feb 2024\n//\n// by **author1**\n//\n// [View as slides](:s15/slides)\n//\n// ---\n// ## s15.0\n// ## s15.1\n// ## s15.2\n//\n// ---\n// Last edited: 2009-02-13 23:31:30\n//\n// Uploader: `g1manfred47kzduec920z88wfr64ylksmdcedlf5`\n//\n// Number of slides: 5\n//\n// [Edit]($help\u0026func=Set\u0026author=author1\u0026date=2024-02-15\u0026event=event2\u0026slug=s15\u0026title=title15) | [Delete]($help\u0026func=Delete\u0026slug=s15)\n//\n//\n//\n// +-------------------------------\n// | PATH: s15/slides\n// | RESULT:\n// # title15\n// **event2**, 15 Feb 2024\n//\n// by **author1**\n//\n// | 1/5 | [Next →](:s15/slides?page=2)\n//\n//\n//\n// +-------------------------------\n// | PATH: s15/slides?page=2\n// | RESULT:\n// # title15\n// ## s15.0\n//\n// [← Prev](:s15/slides?page=1) | 2/5 | [Next →](:s15/slides?page=3)\n//\n//\n//\n// +-------------------------------\n// | PATH: s15/slides?page=3\n// | RESULT:\n// # title15\n// ## s15.1\n//\n// [← Prev](:s15/slides?page=2) | 3/5 | [Next →](:s15/slides?page=4)\n//\n//\n//\n// +-------------------------------\n// | PATH: s15/slides?page=4\n// | RESULT:\n// # title15\n// ## s15.2\n//\n// [← Prev](:s15/slides?page=3) | 4/5 | [Next →](:s15/slides?page=5)\n//\n//\n//\n// +-------------------------------\n// | PATH: s15/slides?page=5\n// | RESULT:\n// # title15\n// ## Thank You!\n// author1\n//\n// 🔗 [https://gno\\.land:s15](https://gno.land:s15)\n//\n// [← Prev](:s15/slides?page=4) | 5/5 |\n"},{"name":"present_init.gno","body":"package present\n\nfunc init() {\n\t_ = setPresentation(\n\t\tOwnable.Owner(),\n\t\t\"demo\",        // slug\n\t\t\"Demo Slides\", // title\n\t\t\"Demo Event\",  // event\n\t\t\"@demo\",       // author\n\t\t\"2025-02-02\",  // date\n\t\t`## Slide One\n- Point A\n- Point B\n- Point C\n\n## Slide Two\n- Feature 1\n- Feature 2\n- Feature 3\n\n## Slide Three\n- Next step\n- Another step\n- Final step`,\n\t)\n}\n"}]},"send":"","max_deposit":"9000000ugnot"}],"fee":{"gas_wanted":"64551200","gas_fee":"193653ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"v7edBGYMHwRG+N7qaDtusCQR6ZSXA5NZ2kgHWmm033Uj5LGzPjTJNpKb0Dk1lBZn1hpFOfhaSu/iOywR3wfyow=="}],"memo":""},"metadata":{"timestamp":"1790960581"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"reactions","path":"gno.land/r/moul/reactions/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/reactions/v0`\n\nA reaction block any realm can embed, keyed on the **page** it appears on rather\nthan on the realm that stores it.\n\nIt is the shape the web settled on for this in 2010: one hosted widget, the same\nsnippet pasted everywhere, deciding what to show from the page identifier it is\nhanded. Here the snippet is two lines of gno.\n\n```go\nimport \"gno.land/r/moul/reactions/v0\"\n\nfunc Render(path string) string {\n\treturn body + reactions.RenderBlock()\n}\n```\n\nThat is the whole integration. Your realm stores nothing, registers nothing and\nconfigures nothing, and redeploying it never loses anyone's reaction.\n\n## Why `RenderBlock` needs no argument\n\nA plain read exported by one realm and called by another is **borrowed**: gno\nopens no realm frame for it, so `unsafe.CurrentRealm()` inside it reports the\n**caller**. `RenderBlock` uses that as the page key, which is why the same line\ndoes the right thing in every realm that pastes it. (Measured on\n`gnolang/gno@master` 2026-09-22, recorded in this repo's `AGENTS.md`; it is the\nsame mechanism behind `r/moul/config`'s `TopBlock`.)\n\nAdding a `cur realm` parameter would silently reverse it and key every embed to\nthis realm, which is exactly why there is none.\n\n`RenderBlockFor(page)` is the explicit form: use it from a crossing function,\nwhere there is no caller to read off the stack, or to key one block per article\non the path you already serve.\n\n```go\nreturn body + reactions.RenderBlockFor(\"gno.land/r/you/blog:\" + path)\n```\n\n## What it is, and what it refuses to be\n\nNot a comment system. There is no text field anywhere, which is what lets it run\nwith **no moderation at all**: a closed palette of six, one reaction per address\nper page, changeable and removable. The block shows the tally and who reacted\nlast. That is the feature.\n\n| key | |\n|---|---|\n| `up` | 👍 |\n| `heart` | 💜 |\n| `fire` | 🔥 |\n| `party` | 🎉 |\n| `rocket` | 🚀 |\n| `eyes` | 👀 |\n\n`React` aborts on anything else. That is the entire content policy, and it is a\ncompile-time constant rather than a list someone has to curate.\n\n## The surface\n\n| | |\n|---|---|\n| `React(cur, page, key)` | record the caller's reaction. Reacting again with a different key moves it; with the same key it only updates the \"last reaction\" line |\n| `Unreact(cur, page)` | remove it. Aborts when there is none, rather than succeeding silently |\n| `RenderBlock()` | the embed, keyed on the calling realm |\n| `RenderBlockFor(page)` | the embed for a named page |\n| `Count` · `CountOf` · `ReactionOf` · `Last` · `Pages` | reads, for a host realm that wants the numbers without the markdown |\n\n`Render(\"\")` is the getting-started page plus the board;\n`Render(\"\u003cpage\u003e\")` is one page's tally, which is where the link under every\nblock goes.\n\n## Two things that are permanent, and were decided on purpose\n\n**This realm is public, so it can never be redeployed.** A private realm cannot\nbe imported at all, and being imported is the entire feature. The redeploy that\n`private = true` would have bought is given up deliberately: the tallies under\nthis path belong to everyone who reacted, not to the deployer, and a redeploy\nwipes every package-level variable. A fix ships as a `v1` beside this one that\nkeeps reading it, never as a replacement.\n\n**The page key is not checked against anything.** A page is just a name: nothing\nverifies that the realm exists, that it embeds the block, or that the caller has\nany relationship to it. That is what lets a realm key the block on something\nfiner than itself, and it means the board index is an open list. The index is\ncapped at 25 rows for that reason; every page keeps its own view regardless.\n\n## Not to be confused with\n\n[`r/moul/x/daily/reactions`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/reactions)\nis an older, unrelated experiment: a single self-contained board with its own\n\"topics\", no embedding, and no way for a reader to change or remove a reaction.\nNothing is shared between the two.\n\n## Where the code is\n\nThe engine (pages, tallies, palette, the block markdown) is\n[`p/moul/reactions/v0`](https://github.com/moul/gno-contracts/tree/main/p/moul/reactions).\nThis realm is the authority half: who may write, what the chain says the height\nand the caller are, and the two views.\n\nFirst host: [`r/moul/home`](https://github.com/moul/gno-contracts/tree/main/r/moul/home),\nwhich renders it as a `:reactions:` layout placeholder.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/reactions/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/reactions/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/reactions/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/reactions/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/reactions/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/reactions/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/reactions/v0\"\ngno = \"0.9\"\n\n# public: the entire point of this realm is that other realms import it and call\n# RenderBlock() inside their own Render. A private realm cannot be imported at\n# all, so `private = true` here would delete the feature rather than trade\n# against it.\n#\n# What private would have bought, redeploy-in-place, is given up deliberately.\n# This path is permanent and the state under it belongs to everyone who reacted,\n# not to moul, so a fix ships as a v1 that keeps reading this one rather than as\n# a redeploy that silently wipes every tally.\n"},{"name":"reactions.gno","body":"// Package reactions is a reaction block any realm can embed, keyed on the page\n// it appears on rather than on the realm that stores it.\n//\n// It is the shape the web settled on for this in 2010: one hosted widget, the\n// same snippet pasted everywhere, deciding what to show from the page\n// identifier it is handed. Here the snippet is two lines of gno:\n//\n//\timport \"gno.land/r/moul/reactions/v0\"\n//\n//\tfunc Render(path string) string {\n//\t\treturn body + reactions.RenderBlock()\n//\t}\n//\n// [RenderBlock] takes no argument because it does not need one: a plain read\n// exported by a realm and called by another opens no realm frame, so\n// unsafe.CurrentRealm() inside it reports the CALLER. The host realm's own path\n// is the page key, and nothing has to be configured, registered or passed.\n// [RenderBlockFor] is the explicit form, for a realm that renders more than one\n// page or already holds its path as a constant.\n//\n// The host realm stores nothing. Every tally lives here, so a realm can add\n// reactions without a redeploy the next time it wants to change them, and a\n// reader's reaction survives the host realm being replaced.\n//\n// # What it is not\n//\n// Not a comment system. There is no text field anywhere, which is what makes\n// it possible to run with no moderation at all: six emoji, one reaction per\n// address per page, changeable and removable. The page shows the tally and who\n// reacted last. That is the whole feature.\npackage reactions\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\trx \"gno.land/p/moul/reactions/v0\"\n)\n\n// realmPath is this realm's own path, the one its gnomod.toml module line\n// declares. It is written out rather than read from unsafe.CurrentRealm(),\n// which reports the CALLER in every read this realm exports and would therefore\n// build every link against whichever realm embedded the block.\nconst realmPath = \"gno.land/r/moul/reactions/v0\"\n\n// board holds every page's tally.\n//\n// A redeploy would wipe it, which is why this realm is not private (see\n// gnomod.toml): the state here belongs to everyone who reacted, and the only\n// honest way to change this realm is a v1 beside it.\nvar board = rx.NewBoard()\n\n// React records the caller's reaction to page.\n//\n// page is a package path, the full one: \"gno.land/r/moul/home\". It does not\n// have to be a realm that embeds the block, and nothing checks that it exists.\n// A page is just a name, which is what lets a realm key the block on something\n// finer than itself.\n//\n// key is one of the palette names, not a glyph: \"up\", \"heart\", \"fire\", \"party\",\n// \"rocket\", \"eyes\". Render(\"\") lists them with their emoji.\n//\n// One reaction per address per page. Reacting again with a different key moves\n// it; reacting with the same key changes nothing but the \"last reaction\" line.\nfunc React(cur realm, page, key string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tif !rx.Valid(key) {\n\t\tpanic(\"reactions: no such reaction: \" + key)\n\t}\n\tif !rx.ValidPage(page) {\n\t\tpanic(\"reactions: not a page key: \" + page)\n\t}\n\n\twho := unsafe.PreviousRealm().Address()\n\tboard.React(page, who, key, runtime.ChainHeight())\n\tchain.Emit(\"React\", \"page\", page, \"key\", key, \"who\", who.String())\n}\n\n// Unreact removes the caller's reaction from page. It aborts when there is\n// none, rather than succeeding silently, so a misspelled page key is visible\n// instead of looking like a no-op.\nfunc Unreact(cur realm, page string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\twho := unsafe.PreviousRealm().Address()\n\tif !board.Unreact(page, who) {\n\t\tpanic(\"reactions: nothing to remove on \" + page)\n\t}\n\tchain.Emit(\"Unreact\", \"page\", page, \"who\", who.String())\n}\n\n// RenderBlock returns the block for the realm CALLING it, which is the form a\n// host realm embeds.\n//\n// It has no cur realm parameter on purpose. A plain read is borrowed: gno opens\n// no realm frame for it, so unsafe.CurrentRealm() reports the caller's path and\n// the block keys itself with no argument. Adding a cur realm here would\n// silently reverse that and key every embed to this realm instead.\n//\n// Calling it from inside this realm therefore keys on this realm, which is\n// never what a caller wants; the views below use the unexported blockFor.\nfunc RenderBlock() string {\n\treturn blockFor(unsafe.CurrentRealm().PkgPath())\n}\n\n// RenderBlockFor is [RenderBlock] for a named page. Use it from a crossing\n// function, where there is no caller to read off the stack, or when one realm\n// renders several pages.\nfunc RenderBlockFor(page string) string { return blockFor(page) }\n\n// blockFor is the shared body, so no exported read of this realm calls another\n// and picks up the wrong path.\nfunc blockFor(page string) string {\n\treturn rx.Block(realmPath, page, board.Page(page))\n}\n\n// Count reports how many addresses have a reaction on page.\nfunc Count(page string) int { return board.Page(page).Total() }\n\n// CountOf reports how many addresses hold one particular reaction on page.\nfunc CountOf(page, key string) int { return board.Page(page).Count(key) }\n\n// ReactionOf returns who's current reaction key on page, or \"\" when they have\n// none. A host realm can use it to say \"you reacted\" without reading the tree.\nfunc ReactionOf(page string, who address) string { return board.Page(page).Of(who) }\n\n// Last returns the most recent reaction on page: the palette key, the address,\n// and the height. The key is \"\" when the page has never been reacted to.\nfunc Last(page string) (key string, who address, height int64) {\n\treturn board.Page(page).Last()\n}\n\n// Pages reports how many pages have ever been reacted to.\nfunc Pages() int { return board.Pages() }\n"},{"name":"reactions_test.gno","body":"package reactions\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\trx \"gno.land/p/moul/reactions/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst homePage = \"gno.land/r/moul/home\"\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\n// reset clears realm state. Realm globals live for the whole test binary, and\n// the Example runs after every Test, so everything that renders starts here.\nfunc reset() { board = rx.NewBoard() }\n\nfunc TestReactAndUnreact(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReact(cross(cur), homePage, rx.KeyUp)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tReact(cross(cur), homePage, rx.KeyFire)\n\n\tuassert.Equal(t, 2, Count(homePage))\n\tuassert.Equal(t, 1, CountOf(homePage, rx.KeyUp))\n\tuassert.Equal(t, rx.KeyUp, ReactionOf(homePage, alice))\n\tuassert.Equal(t, 1, Pages())\n\n\tkey, who, _ := Last(homePage)\n\tuassert.Equal(t, rx.KeyFire, key)\n\tuassert.Equal(t, bob, who)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tUnreact(cross(cur), homePage)\n\tuassert.Equal(t, 1, Count(homePage))\n\tuassert.Equal(t, \"\", ReactionOf(homePage, alice))\n}\n\nfunc TestReadsOnAnUntouchedPageAreZero(t *testing.T) {\n\treset()\n\tuassert.Equal(t, 0, Count(\"gno.land/r/nobody/here\"))\n\tuassert.Equal(t, 0, CountOf(\"gno.land/r/nobody/here\", rx.KeyUp))\n\tuassert.Equal(t, \"\", ReactionOf(\"gno.land/r/nobody/here\", alice))\n\tkey, _, _ := Last(\"gno.land/r/nobody/here\")\n\tuassert.Equal(t, \"\", key)\n}\n\nfunc TestReactRefusals(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"reactions: no such reaction: poop\", func() {\n\t\tReact(cross(cur), homePage, \"poop\")\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"reactions: not a page key: not a path\", func() {\n\t\tReact(cross(cur), \"not a path\", rx.KeyUp)\n\t})\n\n\tuassert.Equal(t, 0, Pages(), \"a refused reaction creates no page\")\n}\n\n// TestUnreactAbortsRatherThanNoOp is the deliberate asymmetry: a misspelled\n// page key on Unreact has to be visible, or a reader thinks they removed\n// something they did not.\nfunc TestUnreactAbortsRatherThanNoOp(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"reactions: nothing to remove on \"+homePage, func() {\n\t\tUnreact(cross(cur), homePage)\n\t})\n}\n\n// TestRenderBlockForIsWhatTheBlockLinksTo pins the property a host realm\n// depends on: every link in the embedded block points at THIS realm, not at\n// the realm that embedded it, and carries the page key as an argument.\nfunc TestRenderBlockForIsWhatTheBlockLinksTo(t *testing.T) {\n\treset()\n\tgot := RenderBlockFor(homePage)\n\tuassert.True(t, strings.Contains(got, \"(/r/moul/reactions/v0$help\u0026func=React\u0026\"),\n\t\t\"the txlink targets this realm\")\n\tuassert.True(t, strings.Contains(got, \"page=gno.land%2Fr%2Fmoul%2Fhome\"),\n\t\t\"and carries the host page as the parameter\")\n\tuassert.False(t, strings.Contains(got, \"/r/moul/home$help\"),\n\t\t\"never the host realm, which has no React to call\")\n}\n\n// TestRenderBlockKeysOnTheCaller is the borrowed-read rule this realm's whole\n// ergonomics rest on: RenderBlock has no cur realm parameter, so gno opens no\n// frame for it and unsafe.CurrentRealm() reports whoever called.\n//\n// In-package there is no other realm to call from, so what this pins is the\n// half that can be pinned here: RenderBlock agrees with RenderBlockFor when\n// the caller IS this realm. The cross-realm half is measured in AGENTS.md\n// (2026-09-22) and is the same mechanism r/moul/config's TopBlock uses.\nfunc TestRenderBlockKeysOnTheCaller(t *testing.T) {\n\treset()\n\tuassert.Equal(t, RenderBlockFor(realmPath), RenderBlock())\n\tuassert.NotEqual(t, RenderBlockFor(homePage), RenderBlock(),\n\t\t\"and a different page is a different block\")\n}\n\nfunc TestRenderPageView(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReact(cross(cur), homePage, rx.KeyUp)\n\n\tgot := Render(homePage)\n\tuassert.True(t, strings.HasPrefix(got, \"# gno\\\\.land/r/moul/home\\n\"),\n\t\t\"the heading is the page key, escaped: ui.Inline backslashes the dot\")\n\tuassert.True(t, strings.Contains(got, \"Last reaction: \\U0001F44D by \"))\n\tuassert.True(t, strings.Contains(got, \"Remove my reaction\"))\n\tuassert.True(t, strings.Contains(got, \"[The board](/r/moul/reactions/v0)\"))\n}\n\nfunc TestRenderRejectsAPathThatIsNotAPageKey(t *testing.T) {\n\treset()\n\tgot := Render(\"[click](http://e.vil)\")\n\tuassert.True(t, strings.HasPrefix(got, \"# Not a page\\n\"))\n\tuassert.False(t, strings.Contains(got, \"](http://e.vil)\"),\n\t\t\"a render path is escaped before it is shown back\")\n}\n\n// TestRenderHomeShowsTheBoard uses uassert rather than an Example because the\n// page contains consecutive blank lines, which gno collapses inside an\n// // Output: block.\nfunc TestRenderHomeShowsTheBoard(cur realm, t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"\"), \"*No page has been reacted to yet.*\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReact(cross(cur), homePage, rx.KeyParty)\n\n\tgot := Render(\"\")\n\tuassert.True(t, strings.Contains(got,\n\t\t\"| [gno\\\\.land/r/moul/home](/r/moul/reactions/v0:gno.land/r/moul/home) | 1 |\"),\n\t\t\"the cell text is escaped, the URL is not: they are different contexts\")\n\tuassert.True(t, strings.Contains(got, \"import \\\"gno.land/r/moul/reactions/v0\\\"\"),\n\t\t\"the homepage is the getting-started doc, and the snippet is copy-pasteable\")\n\tfor _, k := range rx.Keys() {\n\t\tuassert.True(t, strings.Contains(got, \"| `\"+k+\"` | \"+rx.Emoji(k)+\" |\"), k)\n\t}\n}\n\n// TestBoardIndexIsCapped: the number of pages is unbounded, the index is not.\nfunc TestBoardIndexIsCapped(cur realm, t *testing.T) {\n\treset()\n\tfor i := 0; i \u003c maxListed+3; i++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\t// Zero-padded, because avl keys sort as strings and ufmt has no width\n\t\t// flags: \"p9\" would otherwise sort between \"p10\" and \"p11\".\n\t\tn := strconv.Itoa(i)\n\t\tif len(n) \u003c 2 {\n\t\t\tn = \"0\" + n\n\t\t}\n\t\tReact(cross(cur), \"gno.land/r/spam/p\"+n, rx.KeyUp)\n\t}\n\tuassert.Equal(t, maxListed+3, Pages())\n\n\tgot := Render(\"\")\n\tuassert.Equal(t, maxListed, strings.Count(got, \"(/r/moul/reactions/v0:gno.land/r/spam/\"))\n\tuassert.True(t, strings.Contains(got, \"28 pages in total, 25 shown.\"))\n}\n"},{"name":"render.gno","body":"package reactions\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\trx \"gno.land/p/moul/reactions/v0\"\n)\n\n// maxListed caps the board index. The number of pages is unbounded (anyone can\n// react to any key), and a Render that grows with it would eventually be too\n// expensive to serve. The cap is on the INDEX only: every page keeps its own\n// view at /r/moul/reactions/v0:\u003cpage\u003e, whether or not it is listed here.\nconst maxListed = 25\n\n// Render serves two views:\n//\n//\t\"\"       the getting-started page: how to embed the block, plus the board\n//\t\"\u003cpage\u003e\" one page's tally, where \u003cpage\u003e is a package path\n//\n// The page view's path is the key itself, so the link under any embedded block\n// is just this realm's path, a colon, and the page. That is why a page key may\n// contain a colon of its own: \"gno.land/r/you/blog:hello\" reads back whole.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\tif !rx.ValidPage(path) {\n\t\treturn \"# Not a page\\n\\n\" + ui.Inline(path) + \" is not a page key: a key is a \" +\n\t\t\t\"package path, lowercase ASCII, at most \" + strconv.Itoa(rx.MaxPageLen) +\n\t\t\t\" bytes.\\n\\n[Back to the board](\" + selfURL() + \")\\n\"\n\t}\n\treturn renderPage(path)\n}\n\n// selfURL is this realm's own gnoweb path, derived from realmPath the same way\n// every link in the block is, so there is one rule and not two. A function and\n// not a package-level var: a package-level var in a realm is realm STATE,\n// persisted and re-read on every call, which is a strange thing for a string\n// the compiler could have folded.\nfunc selfURL() string { return rx.RealmURL(realmPath) }\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Reactions\\n\\n\")\n\tb.WriteString(\"A reaction block any realm can embed. One line in your `Render`, no state \")\n\tb.WriteString(\"on your side, and readers get one-click reactions keyed on the page they \")\n\tb.WriteString(\"are looking at.\\n\\n\")\n\tb.WriteString(\"It is not a comment system, on purpose. There is no text field anywhere, \")\n\tb.WriteString(\"which is what lets it run with no moderation: a closed palette, one \")\n\tb.WriteString(\"reaction per address per page, changeable and removable.\\n\\n\")\n\n\tb.WriteString(\"## It looks like this\\n\\n\")\n\tb.WriteString(blockFor(realmPath))\n\tb.WriteString(\"\\nThat block is live and it is this realm's own page. Click one.\\n\\n\")\n\n\tb.WriteString(\"## Add it to your realm\\n\\n\")\n\tb.WriteString(\"```go\\n\")\n\tb.WriteString(\"import \\\"\" + realmPath + \"\\\"\\n\\n\")\n\tb.WriteString(\"func Render(path string) string {\\n\")\n\tb.WriteString(\"\\treturn body + reactions.RenderBlock()\\n\")\n\tb.WriteString(\"}\\n\")\n\tb.WriteString(\"```\\n\\n\")\n\tb.WriteString(\"That is the whole integration. `RenderBlock` takes no argument because it \")\n\tb.WriteString(\"does not need one: a plain read exported by one realm and called by \")\n\tb.WriteString(\"another opens no realm frame, so it sees YOUR path and uses it as the \")\n\tb.WriteString(\"page key. Nothing to register, nothing to configure.\\n\\n\")\n\tb.WriteString(\"For one block per article rather than one per realm, name the page \")\n\tb.WriteString(\"yourself with the path you already serve:\\n\\n\")\n\tb.WriteString(\"```go\\n\")\n\tb.WriteString(\"return body + reactions.RenderBlockFor(\\\"gno.land/r/you/blog:\\\" + path)\\n\")\n\tb.WriteString(\"```\\n\\n\")\n\tb.WriteString(\"Reactions are recorded here, not in your realm, so redeploying yours \")\n\tb.WriteString(\"never loses them.\\n\\n\")\n\n\tb.WriteString(\"## The palette\\n\\n\")\n\tt := ui.NewTable(\"key\", \"\")\n\tfor _, k := range rx.Keys() {\n\t\tt.Row(\"`\"+k+\"`\", rx.Emoji(k))\n\t}\n\tb.WriteString(t.String())\n\tb.WriteString(\"\\nSix, and the set is closed. `React` aborts on anything else, which is \")\n\tb.WriteString(\"the entire moderation policy.\\n\\n\")\n\n\tb.WriteString(\"## The board\\n\\n\")\n\tb.WriteString(renderBoard())\n\n\treturn b.String()\n}\n\n// renderBoard lists pages in key order, not by activity. Key order is the order\n// the tree already walks, so the listing is stable between identical calls;\n// ranking would need a second index maintained on every write, which is a lot\n// of machinery for a table nobody navigates by.\nfunc renderBoard() string {\n\tn := board.Pages()\n\tif n == 0 {\n\t\treturn ui.Empty(\"No page has been reacted to yet.\")\n\t}\n\n\tt := ui.NewTable(\"page\", \"reactions\", \"last\")\n\tboard.Each(func(page string, p *rx.Page) bool {\n\t\tkey, who, _ := p.Last()\n\t\tlast := \"-\"\n\t\tif key != \"\" {\n\t\t\tlast = rx.Emoji(key) + \" \" + ui.Addr(who)\n\t\t}\n\t\tt.Row(\n\t\t\t\"[\"+ui.Cell(page)+\"](\"+rx.PageURL(realmPath, page)+\")\",\n\t\t\tstrconv.Itoa(p.Total()),\n\t\t\tlast,\n\t\t)\n\t\treturn t.Len() \u003e= maxListed\n\t})\n\n\tout := t.String()\n\tif n \u003e maxListed {\n\t\tout += \"\\n\" + strconv.Itoa(n) + \" pages in total, \" + strconv.Itoa(maxListed) +\n\t\t\t\" shown. Every page has its own view at `\" + selfURL() + \":\u003cpage\u003e`.\\n\"\n\t}\n\treturn out\n}\n\nfunc renderPage(page string) string {\n\tp := board.Page(page)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + ui.Inline(page) + \"\\n\\n\")\n\tb.WriteString(blockFor(page))\n\tb.WriteString(\"\\n\")\n\n\tif p.Total() == 0 {\n\t\tb.WriteString(ui.Empty(\"Nobody is reacting to this page right now.\"))\n\t} else {\n\t\tt := ui.NewTable(\"\", \"reaction\", \"addresses\")\n\t\tfor _, k := range rx.Keys() {\n\t\t\tif c := p.Count(k); c \u003e 0 {\n\t\t\t\tt.Row(rx.Emoji(k), \"`\"+k+\"`\", strconv.Itoa(c))\n\t\t\t}\n\t\t}\n\t\tb.WriteString(t.String())\n\t}\n\n\tif key, who, height := p.Last(); key != \"\" {\n\t\tb.WriteString(\"\\nLast reaction: \" + rx.Emoji(key) + \" by \" + ui.Addr(who) +\n\t\t\t\" at height \" + strconv.FormatInt(height, 10) + \".\\n\")\n\t}\n\n\tb.WriteString(\"\\n\" + ui.ActionIn(realmPath, \"Remove my reaction\", \"Unreact\", \"page\", page))\n\tb.WriteString(\" · [The board](\" + selfURL() + \")\\n\")\n\treturn b.String()\n}\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"74293400","gas_fee":"222880ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"0sEFAay+15ePN0JrfHkVh2Ozb1Jz4vXPi2MisWRVFbgZzSWBjiNCDi7/i7fZeDZ5HKh70UNxxzBAyN7Jktztpg=="}],"memo":""},"metadata":{"timestamp":"1790960582"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"kyMsU+CpungVf65e7tZOaOByiE6wRvXKligszry77d5AqQIDyPBOpmlt6o08qvliI+FoxQ9qCwfQ8jekKahJ8Q=="}],"memo":""},"metadata":{"timestamp":"1790960583"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"vesting","path":"gno.land/r/moul/vesting/v0","files":[{"name":"README.md","body":"# `r/moul/vesting`\n\nHow much of a gno.land account's balance can **actually move right now**.\n\n## Read this before trusting a number here\n\nA realm cannot read an account's vesting schedule. `banker.GetCoins` returns the **total**\nbalance with the locked part included, and no native exposes `std.VestingSchedule`. So the\npage reads two things from the chain and is told the third:\n\n| figure | source | trust |\n|---|---|---|\n| balance | `banker.GetCoins`, every render | always true |\n| the clock | the block time, every render | always true |\n| the schedule | supplied, see below | only as good as its source |\n\nEvery rendered figure says which of the two it rests on. Nothing is presented as verified\nwhen it is not. That honesty is the feature: a page that quietly guessed the locked amount\nwould be worse than no page.\n\n## Where a schedule comes from\n\n**The URL**, for a one-off that stores nothing:\n\n```\n/r/moul/vesting/v0:g1youraddress?o=106560000000\u0026s=1789225200\u0026e=1852383600\n```\n\n`o` original vesting in ugnot, `s` start, `e` end, both unix seconds, `\u0026d=1` for a `delayed`\nschedule. Read your real one off the chain:\n\n```sh\ngnokey query auth/accounts/g1youraddress -remote https://rpc.gno.land:443\n```\n\n**Or the registry.** `Declare` writes a schedule for the **caller's own address and no\nother**. That is the whole trust model: an address can only misdescribe itself, and a wrong\nentry misleads nobody but its author. `Forget` takes it off again.\n\n## Why a cached schedule is honest rather than stale\n\nBecause a schedule can never change. `std.SetVesting` has exactly one caller in the\nmonorepo, `gno.land/pkg/gnoland/app.go`, during genesis balance loading, and no message type\ncreates or modifies one. A schedule declared correctly today is correct forever.\n\n## Routes\n\n| | |\n|---|---|\n| `/r/moul/vesting/v0` | the seeded schedules, then declared ones, 25 to a page |\n| `…?page=2` | the next page of declared schedules |\n| `…:g1…` | one address |\n| `…:g1…?o=\u0026s=\u0026e=` | one address, with a schedule you supply |\n\n**The index is paged because it has to be.** `vm/qrender` runs on a gas meter, so a realm that\nreturns a large string fails with `OutOfGasError{Descriptor:\"CPUCycles\"}` rather than answering\nslowly, and anyone may `Declare`. An unbounded index is a front page that a stranger can\nswitch off by declaring enough rows, permanently, since the only repair for a\n`private = true` realm is a redeploy that wipes every declaration.\n\n## What gets seeded, and what deliberately does not\n\nA seeded row names an address. The addresses are all on chain and public, but **saying who\nholds one is a separate claim**, and this realm is public and permanent. So an address is\nseeded only when its label is public too:\n\n| | |\n|---|---|\n| `moul` | his own |\n| the investors-vesting multisig | named outright in `misc/deployments/mainnet.gno.land/gen-genesis.sh`, with the same figures |\n\nThe treasury and other buckets are **not** seeded. Their addresses are public, their roles are\nnot published anywhere, and the URL form answers for them just as exactly.\n\n## Notes\n\nThe seeded schedules are source constants, not registry rows. This realm is\n`private = true`, so a redeploy wipes realm state, and the one schedule the page exists to\nshow should not need a transaction to come back. A seeded address is refused by `Declare`\nfor the same reason: a redeploy would silently revert whatever it set.\n\nThe arithmetic is [`p/moul/vesting`](/p/moul/vesting/v0), which mirrors what the chain\nenforces, down to the rounding direction.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/vesting/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/vesting/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/vesting/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/vesting/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/vesting/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/vesting/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/vesting/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/vesting/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/vesting/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/vesting/v0/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/vesting/v0\"\ngno = \"0.9\"\n\n# Redeployable by its creator: nothing imports this realm and it hands no\n# object of its own to another one, so `private = true` costs nothing and keeps\n# the path reusable. Designed for the wipe a redeploy causes: the seeded\n# schedules are source constants that init() restores, and a declared schedule\n# is one transaction for its owner to re-submit.\nprivate = true\n"},{"name":"render.gno","body":"package vesting\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/vesting/v0\"\n)\n\n// Render serves three shapes:\n//\n//\t/r/moul/vesting/v0                     the seeded schedules\n//\t/r/moul/vesting/v0:g1...               one address, its declared schedule\n//\t/r/moul/vesting/v0:g1...?o=\u0026s=\u0026e=\u0026d=   one address, a schedule you supply\n//\n// The query form stores nothing. It exists so an address that has not declared\n// anything can still get a real answer: paste the schedule out of\n// `gnokey query auth/accounts/\u003caddr\u003e` and the balance is still read from chain.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\ttarget := strings.TrimSpace(req.PathPart(0))\n\n\tif target == \"\" {\n\t\tcurPage = 1\n\t\tif p, err := strconv.Atoi(req.Query.Get(\"page\")); err == nil \u0026\u0026 p \u003e 1 {\n\t\t\tcurPage = p\n\t\t}\n\t\treturn renderIndex()\n\t}\n\tif !isAddr(target) {\n\t\treturn header() + ui.Empty(\"`\"+ui.Inline(target)+\"` is not a gno.land address.\") +\n\t\t\t\"\\n\" + lookupForm()\n\t}\n\taddr := address(target)\n\n\t// An ad-hoc schedule in the query beats a declared one, and is labelled as\n\t// coming from the caller.\n\tif raw := req.Query.Get(\"o\"); raw != \"\" {\n\t\tsch, err := scheduleFromQuery(req)\n\t\tif err != \"\" {\n\t\t\treturn header() + ui.Empty(err) + \"\\n\" + lookupForm()\n\t\t}\n\t\treturn header() + renderAccount(addr, sch, sourceQuery, \"\") + \"\\n\" + lookupForm()\n\t}\n\n\tif e, ok := lookup(addr); ok {\n\t\tsrc := sourceDeclared\n\t\tif e.seeded {\n\t\t\tsrc = sourceSeeded\n\t\t}\n\t\treturn header() + renderAccount(addr, e.schedule, src, e.label) + \"\\n\" + lookupForm()\n\t}\n\treturn header() + renderUnknown(addr) + \"\\n\" + lookupForm()\n}\n\n// Where a schedule came from. This is the distinction the whole page turns on,\n// so it is a value and not a boolean buried in a branch.\ntype source int\n\nconst (\n\tsourceSeeded   source = iota // a source constant in this realm\n\tsourceDeclared               // written by the address itself\n\tsourceQuery                  // typed into the URL by whoever is looking\n\tsourceNone                   // there is none\n)\n\nfunc (s source) label() string {\n\tswitch s {\n\tcase sourceSeeded:\n\t\treturn \"seeded in this realm's source\"\n\tcase sourceDeclared:\n\t\treturn \"declared by the address itself\"\n\tcase sourceQuery:\n\t\treturn \"supplied in the URL by you\"\n\t}\n\treturn \"unknown\"\n}\n\nfunc header() string {\n\treturn \"# Vesting\\n\\n\" +\n\t\t\"How much of an account's balance can actually move right now.\\n\\n\"\n}\n\n// pageSize bounds the declared table. vm/qrender runs on a gas meter and a\n// large return value fails with OutOfGasError{Descriptor:\"CPUCycles\"} rather\n// than answering slowly, so an unbounded index is a page that eventually stops\n// rendering for everyone. Anyone may Declare, so \"eventually\" is somebody\n// else's choice unless it is capped here.\nconst pageSize = 25\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(header())\n\n\t// Seeded rows always render in full: there are as many as this realm's\n\t// source says and no caller can add one.\n\tt := ui.NewTable(\"account\", \"balance\", \"spendable\", \"locked\", \"vested\")\n\tseedIndex.Iterate(\"\", \"\", func(key string, v any) bool {\n\t\tt.Row(rowFor(address(key), v.(*entry))...)\n\t\treturn false\n\t})\n\tb.WriteString(t.String())\n\n\tif n := declared.Size(); n \u003e 0 {\n\t\tb.WriteString(\"\\n## Declared\\n\\n\")\n\t\tb.WriteString(ufmt.Sprintf(\"%d address(es) have put their own schedule on file.\\n\\n\", n))\n\n\t\td := ui.NewTable(\"account\", \"balance\", \"spendable\", \"locked\", \"vested\")\n\t\tdeclared.IterateByOffset(pageOffset(curPage)*pageSize, pageSize, func(key string, v any) bool {\n\t\t\td.Row(rowFor(address(key), v.(*entry))...)\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(d.String())\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(pager(n))\n\t}\n\n\tb.WriteString(\"\\n\")\n\tb.WriteString(lookupForm())\n\tb.WriteString(\"\\n## What is real here, and what is not\\n\\n\")\n\tb.WriteString(\"| figure | where it comes from |\\n|---|---|\\n\")\n\tb.WriteString(\"| balance | read from the chain every render, `banker.GetCoins` |\\n\")\n\tb.WriteString(\"| the clock | read from the chain every render, the block time |\\n\")\n\tb.WriteString(\"| the schedule | **supplied**, because no realm can read one |\\n\\n\")\n\tb.WriteString(\"A realm's whole view of an account is its TOTAL balance, locked coins \")\n\tb.WriteString(\"included. `std.VestingSchedule` lives in the auth store and no native \")\n\tb.WriteString(\"reaches it, so the curve has to be told to this realm rather than found.\\n\\n\")\n\tb.WriteString(\"That is safe to cache because a schedule can never change: it is set \")\n\tb.WriteString(\"once, at genesis, and no message type creates or modifies one. A \")\n\tb.WriteString(\"schedule declared correctly today is correct forever.\\n\")\n\treturn b.String()\n}\n\n// curPage is the page renderIndex is currently building, set by Render before\n// it delegates. A parameter would be cleaner; Render's signature is fixed by\n// the VM, and threading it through every helper for one value is worse.\nvar curPage = 1\n\nfunc pageOffset(page int) int {\n\tif page \u003c 1 {\n\t\treturn 0\n\t}\n\treturn page - 1\n}\n\n// rowFor builds one table row. Shared so the seeded and declared tables cannot\n// drift apart in what they show.\nfunc rowFor(addr address, e *entry) []string {\n\tbal := balanceOf(addr)\n\tn := now()\n\tname := ui.AddrText(addr)\n\tif e.label != \"\" {\n\t\tname = ui.Inline(e.label) + \" \" + ui.Addr(addr)\n\t}\n\treturn []string{\n\t\tname,\n\t\tgnot(bal),\n\t\tgnot(e.schedule.Spendable(bal, n)),\n\t\tgnot(lockedCapped(e.schedule, bal, n)),\n\t\tpermille(e.schedule.PermilleVested(n)),\n\t}\n}\n\n// pager renders the page links, and nothing at all when everything fits.\nfunc pager(total int) string {\n\tpages := (total + pageSize - 1) / pageSize\n\tif pages \u003c= 1 {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(ufmt.Sprintf(\"Page %d of %d.\", curPage, pages))\n\tif curPage \u003e 1 {\n\t\tb.WriteString(ufmt.Sprintf(\" [previous](%s?page=%d)\", Link, curPage-1))\n\t}\n\tif curPage \u003c pages {\n\t\tb.WriteString(ufmt.Sprintf(\" [next](%s?page=%d)\", Link, curPage+1))\n\t}\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\nfunc renderAccount(addr address, s vesting.Schedule, src source, label string) string {\n\tvar b strings.Builder\n\tn := now()\n\tbal := balanceOf(addr)\n\n\tb.WriteString(\"## \")\n\tif label != \"\" {\n\t\tb.WriteString(ui.Inline(label))\n\t\tb.WriteString(\" \")\n\t}\n\tb.WriteString(ui.AddrText(addr))\n\tb.WriteString(\"\\n\\n\")\n\n\tif s.IsZero() {\n\t\tb.WriteString(\"No vesting schedule, so the whole balance moves.\\n\\n\")\n\t\tb.WriteString(\"| | |\\n|---|---|\\n\")\n\t\tb.WriteString(\"| balance | **\" + gnot(bal) + \"** |\\n\")\n\t\tb.WriteString(\"| spendable | **\" + gnot(bal) + \"** |\\n\\n\")\n\t\tb.WriteString(sourceNote(src))\n\t\treturn b.String()\n\t}\n\n\tlocked := lockedCapped(s, bal, n)\n\tt := ui.NewTable(\"\", \"\")\n\tt.Row(\"balance\", \"**\"+gnot(bal)+\"**\")\n\tt.Row(\"spendable now\", \"**\"+gnot(s.Spendable(bal, n))+\"**\")\n\tt.Row(\"locked now\", gnot(locked))\n\tt.Row(\"granted\", gnot(s.Original))\n\tt.Row(\"vested\", gnot(s.Vested(n))+\" (\"+permille(s.PermilleVested(n))+\")\")\n\tt.Row(\"still to vest\", gnot(s.Locked(n)))\n\tt.Row(\"curve\", s.Type.String())\n\tt.Row(\"term\", tstamp(s.Start)+\" to \"+tstamp(s.End))\n\tt.Row(\"finishes in\", duration(s.RemainingSeconds(n)))\n\tb.WriteString(t.String())\n\tb.WriteString(\"\\n\")\n\n\tif s.Locked(n) \u003e bal {\n\t\tb.WriteString(\"\\n\u003e This account holds less than its schedule still locks, so \")\n\t\tb.WriteString(\"nothing moves at all. That happens when coins were spent while \")\n\t\tb.WriteString(\"they were free and the grant has since outrun the balance.\\n\")\n\t}\n\n\tb.WriteString(\"\\n\")\n\tb.WriteString(sourceNote(src))\n\treturn b.String()\n}\n\nfunc renderUnknown(addr address) string {\n\tvar b strings.Builder\n\tbal := balanceOf(addr)\n\tb.WriteString(\"## \")\n\tb.WriteString(ui.AddrText(addr))\n\tb.WriteString(\"\\n\\nNo schedule on file for this address.\\n\\n\")\n\tb.WriteString(\"| | |\\n|---|---|\\n\")\n\tb.WriteString(\"| balance | **\" + gnot(bal) + \"** |\\n\")\n\tb.WriteString(\"| spendable | unknown |\\n\\n\")\n\tb.WriteString(\"The balance above is real. How much of it moves is not knowable from \")\n\tb.WriteString(\"inside a realm. Read the schedule off the chain:\\n\\n\")\n\tb.WriteString(\"```\\ngnokey query auth/accounts/\" + addr.String() +\n\t\t\" -remote https://rpc.gno.land:443\\n```\\n\\n\")\n\tb.WriteString(\"then either append it to this URL as `?o=\u003coriginal_vesting\u003e\u0026s=\u003cstart_time\u003e\")\n\tb.WriteString(\"\u0026e=\u003cend_time\u003e` (add `\u0026d=1` for a `delayed` schedule), or, if this address \")\n\tb.WriteString(\"is yours, put it on file so the link works for everyone:\\n\\n\")\n\tb.WriteString(ui.Action(\"Declare this schedule\", \"Declare\",\n\t\t\"original\", \"\", \"start\", \"\", \"end\", \"\", \"delayed\", \"false\"))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\nfunc sourceNote(src source) string {\n\ts := \"Balance and clock are read from the chain. The schedule is \" + src.label() + \".\"\n\tif src == sourceQuery {\n\t\ts += \" Nothing was stored.\"\n\t}\n\tif src == sourceDeclared {\n\t\ts += \" Only that address can write or remove it, so it can misdescribe nobody else.\"\n\t}\n\treturn \"\u003e \" + s + \"\\n\"\n}\n\nfunc lookupForm() string {\n\treturn \"## Check another address\\n\\n\" +\n\t\t\"Append it to the path: `\" + Link + \":g1…`\\n\\n\" +\n\t\t\"| | |\\n|---|---|\\n\" +\n\t\t\"| put your own schedule on file | \" +\n\t\tui.Action(\"Declare\", \"Declare\", \"original\", \"\", \"start\", \"\", \"end\", \"\", \"delayed\", \"false\") +\n\t\t\" |\\n| take it off again | \" + ui.Action(\"Forget\", \"Forget\") + \" |\\n\"\n}\n\n// scheduleFromQuery reads a one-off schedule out of the URL. It returns a\n// human-readable reason rather than an error value, because every caller turns\n// it straight into page text.\nfunc scheduleFromQuery(req *realmpath.Request) (vesting.Schedule, string) {\n\to, err := strconv.ParseInt(req.Query.Get(\"o\"), 10, 64)\n\tif err != nil {\n\t\treturn vesting.Schedule{}, \"`o` (the original vesting amount, in ugnot) is not a number.\"\n\t}\n\ts, err := strconv.ParseInt(orZero(req.Query.Get(\"s\")), 10, 64)\n\tif err != nil {\n\t\treturn vesting.Schedule{}, \"`s` (the start time, unix seconds) is not a number.\"\n\t}\n\te, err := strconv.ParseInt(orZero(req.Query.Get(\"e\")), 10, 64)\n\tif err != nil {\n\t\treturn vesting.Schedule{}, \"`e` (the end time, unix seconds) is not a number.\"\n\t}\n\ttyp := vesting.Continuous\n\tif d := req.Query.Get(\"d\"); d == \"1\" || d == \"true\" {\n\t\ttyp = vesting.Delayed\n\t}\n\tsch, verr := vesting.New(o, s, e, typ)\n\tif verr != nil {\n\t\treturn vesting.Schedule{}, \"That is not a valid schedule: \" + verr.Error() + \".\"\n\t}\n\treturn sch, \"\"\n}\n\nfunc orZero(s string) string {\n\tif s == \"\" {\n\t\treturn \"0\"\n\t}\n\treturn s\n}\n\n// lockedCapped is what the account cannot move, which is never more than it\n// holds. The schedule alone can say otherwise once coins have been spent.\nfunc lockedCapped(s vesting.Schedule, balance, n int64) int64 {\n\tl := s.Locked(n)\n\tif l \u003e balance {\n\t\treturn balance\n\t}\n\tif l \u003c 0 {\n\t\treturn 0\n\t}\n\treturn l\n}\n\n// tstamp renders a unix second as a plain UTC date, which is all a two-year\n// term needs. gno has no time formatting worth the dependency here.\nfunc tstamp(sec int64) string {\n\ty, m, d := civil(sec / 86400)\n\treturn ufmtDate(y, m, d)\n}\n\n// civil converts a day count since 1970-01-01 to a calendar date, by Howard\n// Hinnant's civil_from_days. Integer only, no time package, no locale.\nfunc civil(z int64) (year int64, month int64, day int64) {\n\tz += 719468\n\tera := z / 146097\n\tif z \u003c 0 {\n\t\tera = (z - 146096) / 146097\n\t}\n\tdoe := z - era*146097\n\tyoe := (doe - doe/1460 + doe/36524 - doe/146096) / 365\n\ty := yoe + era*400\n\tdoy := doe - (365*yoe + yoe/4 - yoe/100)\n\tmp := (5*doy + 2) / 153\n\td := doy - (153*mp+2)/5 + 1\n\tm := mp + 3\n\tif mp \u003e= 10 {\n\t\tm = mp - 9\n\t}\n\tif m \u003c= 2 {\n\t\ty++\n\t}\n\treturn y, m, d\n}\n\nfunc ufmtDate(y, m, d int64) string {\n\treturn strconv.FormatInt(y, 10) + \"-\" + pad2(m) + \"-\" + pad2(d)\n}\n\nfunc pad2(n int64) string {\n\ts := strconv.FormatInt(n, 10)\n\tif len(s) \u003c 2 {\n\t\treturn \"0\" + s\n\t}\n\treturn s\n}\n"},{"name":"render_example_test.gno","body":"package vesting\n\n// ExampleRender pins the index.\n//\n// reset() first, deliberately: an Example runs AFTER every Test in the package\n// and sees the rows they declared, so without it this output depends on test\n// order. The block time inside a gno test is fixed at 2009-02-13, before the\n// real mainnet term starts, so the seeded rows render at 0% vested with the\n// whole grant locked. That is a legitimate point on the curve and a stable one.\n//\n// With no declarations there is no Declared section and no pager, which is the\n// shape the page has on a fresh deploy.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Vesting\n\t//\n\t// How much of an account's balance can actually move right now.\n\t//\n\t// | account | balance | spendable | locked | vested |\n\t// | --- | --- | --- | --- | --- |\n\t// | moul `g1manfre…dlf5` | 0.000000 GNOT | 0.000000 GNOT | 0.000000 GNOT | 0.0% |\n\t// | investors\\-vesting multisig `g1x7tm26…gax3` | 0.000000 GNOT | 0.000000 GNOT | 0.000000 GNOT | 0.0% |\n\t//\n\t// ## Check another address\n\t//\n\t// Append it to the path: `/r/moul/vesting/v0:g1…`\n\t//\n\t// | | |\n\t// |---|---|\n\t// | put your own schedule on file | [Declare](/r/moul/vesting/v0$help\u0026func=Declare\u0026delayed=false\u0026end=\u0026original=\u0026start=) |\n\t// | take it off again | [Forget](/r/moul/vesting/v0$help\u0026func=Forget) |\n\t//\n\t// ## What is real here, and what is not\n\t//\n\t// | figure | where it comes from |\n\t// |---|---|\n\t// | balance | read from the chain every render, `banker.GetCoins` |\n\t// | the clock | read from the chain every render, the block time |\n\t// | the schedule | **supplied**, because no realm can read one |\n\t//\n\t// A realm's whole view of an account is its TOTAL balance, locked coins included. `std.VestingSchedule` lives in the auth store and no native reaches it, so the curve has to be told to this realm rather than found.\n\t//\n\t// That is safe to cache because a schedule can never change: it is set once, at genesis, and no message type creates or modifies one. A schedule declared correctly today is correct forever.\n}\n"},{"name":"vesting.gno","body":"// Realm vesting answers one question for a gno.land account: of the coins it\n// holds, how many can actually move right now.\n//\n// # Read this before you trust a number here\n//\n// A realm CANNOT read an account's vesting schedule. The VM's whole view of an\n// account is banker.GetCoins, which returns the TOTAL balance with the locked\n// part included, and no native exposes std.VestingSchedule. So this realm\n// reads two things from the chain and is told the third:\n//\n//\tbalance     read from the chain, banker.GetCoins   always true\n//\tnow         read from the chain, block time        always true\n//\tschedule    supplied, see below                    only as good as its source\n//\n// Every rendered figure says which of the two it rests on. Nothing here is\n// presented as verified when it is not.\n//\n// # Where a schedule comes from\n//\n// Either the query string, for a one-off calculation that stores nothing, or\n// the registry. [Declare] writes a schedule for the CALLER'S OWN address and\n// no other, which is the whole trust model: an address can only misdescribe\n// itself, and a wrong entry misleads nobody but its author.\n//\n// Anyone can read their real schedule in one command and declare it:\n//\n//\tgnokey query auth/accounts/g1youraddress -remote https://rpc.gno.land:443\n//\n// # Why the schedule can be cached at all\n//\n// Because it can never change. std.SetVesting has exactly one caller in the\n// monorepo, gno.land/pkg/gnoland/app.go, during genesis balance loading, and\n// no message type creates or modifies a schedule. A schedule declared once is\n// correct forever, which is what makes a registry honest rather than stale.\npackage vesting\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\t\"gno.land/p/moul/vesting/v0\"\n)\n\nconst (\n\t// Path is this realm's package path.\n\tPath = \"gno.land/r/moul/vesting/v0\"\n\t// Link is Path as a gnoweb route.\n\tLink = \"/r/moul/vesting/v0\"\n\t// Denom is the only coin this realm reports on.\n\tDenom = \"ugnot\"\n)\n\n// seeded are the schedules this realm ships with, restored by init() after\n// every redeploy.\n//\n// They are source constants and not registry rows on purpose: the realm is\n// private = true, so a redeploy wipes realm state, and the one schedule the\n// page exists to show should not need a transaction to come back. Each is\n// copied from the genesis allocation sheet that built mainnet, which is the\n// public, pinned input named in misc/deployments/mainnet.gno.land/gen-genesis.sh.\n//\n// An address is seeded here only when its LABEL is public too. The addresses\n// are all on chain, but naming one is a claim about who holds it, and this\n// realm is public and permanent. gen-genesis.sh names the investors-vesting\n// multisig outright, so that one ships; the treasuries and the other buckets\n// are identified nowhere public, so they do not, and the URL form serves\n// anyone who wants to check them anyway.\nvar seeded = []struct {\n\taddr     address\n\tlabel    string\n\toriginal int64\n\tstart    int64\n\tend      int64\n\tdelayed  bool\n}{\n\t{\n\t\taddr:     \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\",\n\t\tlabel:    \"moul\",\n\t\toriginal: 106560000000,\n\t\tstart:    1789225200,\n\t\tend:      1852383600,\n\t},\n\t{\n\t\t// \"including the investors-vesting multisig\n\t\t// g1x7tm26g9wj84cmg3cs74uwf3g9lqj4mjp6gax3, 150,000,000 GNOT total,\n\t\t// 144,000,000 of it vesting continuously\" -- gen-genesis.sh, and the\n\t\t// sheet row it describes:\n\t\t//   g1x7tm26…=150000000000000ugnot;vesting=144000000000000ugnot,1789225200,1852383600\n\t\taddr:     \"g1x7tm26g9wj84cmg3cs74uwf3g9lqj4mjp6gax3\",\n\t\tlabel:    \"investors-vesting multisig\",\n\t\toriginal: 144000000000000,\n\t\tstart:    1789225200,\n\t\tend:      1852383600,\n\t},\n}\n\n// declared maps an address to the schedule that address declared for itself.\n// Seeded schedules are NOT in here: they are read from the seeded slice, which\n// is what lets the index render them in full while paging everything else.\n// Anyone may Declare, so this tree is unbounded and the page that shows it\n// cannot be.\nvar declared avl.Tree\n\n// seedIndex resolves a seeded address without walking the slice twice.\nvar seedIndex avl.Tree\n\n// entry is one row of the registry.\ntype entry struct {\n\tschedule vesting.Schedule\n\tlabel    string // non-empty only for a seeded row\n\tseeded   bool\n\tat       int64 // block height the row was written at; 0 for a seeded row\n}\n\nfunc init() { reset() }\n\n// reset restores the registry to exactly what the source declares. init() is\n// its only caller on chain; a test calls it to render a page that does not\n// depend on what the test before it wrote, since an Example runs after every\n// Test in the package and sees the state they left.\nfunc reset() {\n\tdeclared = avl.Tree{}\n\tseedIndex = avl.Tree{}\n\tfor _, s := range seeded {\n\t\ttyp := vesting.Continuous\n\t\tif s.delayed {\n\t\t\ttyp = vesting.Delayed\n\t\t}\n\t\tsch, err := vesting.New(s.original, s.start, s.end, typ)\n\t\tif err != nil {\n\t\t\tpanic(\"vesting: seeded schedule for \" + s.label + \": \" + err.Error())\n\t\t}\n\t\tseedIndex.Set(s.addr.String(), \u0026entry{schedule: sch, label: s.label, seeded: true})\n\t}\n}\n\n// Declare records the caller's own vesting schedule, replacing any previous\n// one. It cannot write a row for anybody else, which is what keeps the\n// registry honest without the realm being able to verify a thing.\n//\n// Pass original = 0 to declare that the address has no schedule at all.\nfunc Declare(cur realm, original, start, end int64, delayed bool) {\n\ttyp := vesting.Continuous\n\tif delayed {\n\t\ttyp = vesting.Delayed\n\t}\n\tsch, err := vesting.New(original, start, end, typ)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\twho := unsafe.PreviousRealm().Address()\n\tif e, ok := lookup(who); ok \u0026\u0026 e.seeded {\n\t\tpanic(\"vesting: \" + who.String() + \" is seeded in the source; edit the realm instead\")\n\t}\n\tdeclared.Set(who.String(), \u0026entry{schedule: sch, at: chainHeight()})\n\tchain.Emit(\"declared\", \"addr\", who.String(),\n\t\t\"original\", strconv.FormatInt(original, 10),\n\t\t\"start\", strconv.FormatInt(start, 10),\n\t\t\"end\", strconv.FormatInt(end, 10),\n\t\t\"type\", typ.String())\n}\n\n// Forget removes the caller's own declaration.\nfunc Forget(cur realm) {\n\twho := unsafe.PreviousRealm().Address()\n\te, ok := lookup(who)\n\tif !ok {\n\t\tpanic(\"vesting: nothing declared for \" + who.String())\n\t}\n\tif e.seeded {\n\t\tpanic(\"vesting: \" + who.String() + \" is seeded in the source; edit the realm instead\")\n\t}\n\tdeclared.Remove(who.String())\n\tchain.Emit(\"forgot\", \"addr\", who.String())\n}\n\n// Count returns how many schedules addresses have declared for themselves.\n// Seeded schedules are not included; SeededCount reports those.\nfunc Count() int { return declared.Size() }\n\n// SeededCount returns how many schedules this realm ships in its source.\nfunc SeededCount() int { return seedIndex.Size() }\n\n// ScheduleOf returns the declared schedule for addr, and whether there is one.\nfunc ScheduleOf(addr address) (original, start, end int64, delayed, ok bool) {\n\te, found := lookup(addr)\n\tif !found {\n\t\treturn 0, 0, 0, false, false\n\t}\n\ts := e.schedule\n\treturn s.Original, s.Start, s.End, s.Type == vesting.Delayed, true\n}\n\n// SpendableOf returns what addr can move right now, and whether the answer\n// rests on a declared schedule. With ok false the figure is the whole balance,\n// which is correct only if the address really has no schedule.\nfunc SpendableOf(addr address) (spendable int64, ok bool) {\n\tbal := balanceOf(addr)\n\te, found := lookup(addr)\n\tif !found {\n\t\treturn bal, false\n\t}\n\treturn e.schedule.Spendable(bal, now()), true\n}\n\n// LockedOf returns what addr cannot move right now, and whether the answer\n// rests on a declared schedule.\nfunc LockedOf(addr address) (locked int64, ok bool) {\n\te, found := lookup(addr)\n\tif !found {\n\t\treturn 0, false\n\t}\n\tbal := balanceOf(addr)\n\tl := e.schedule.Locked(now())\n\tif l \u003e bal {\n\t\tl = bal // cannot lock more than is there\n\t}\n\treturn l, true\n}\n\n// lookup reads a row, seeded first so a seeded address can never be shadowed.\n// avl's Get returns ONE value and nil for a miss, unlike Remove which returns\n// two; that asymmetry is a documented gno-vs-Go trap.\nfunc lookup(addr address) (*entry, bool) {\n\tif v := seedIndex.Get(addr.String()); v != nil {\n\t\treturn v.(*entry), true\n\t}\n\tv := declared.Get(addr.String())\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*entry), true\n}\n\n// balanceOf reads the address's TOTAL ugnot, locked included. That is what\n// banker.GetCoins reports and the only balance figure a realm can obtain.\n// A readonly banker takes no realm, so this works from inside Render.\nfunc balanceOf(addr address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(addr).AmountOf(Denom)\n}\n\n// gnot renders a ugnot amount as GNOT with six decimals and no float.\nfunc gnot(u int64) string {\n\tneg := u \u003c 0\n\tif neg {\n\t\tu = -u\n\t}\n\twhole, frac := u/1_000_000, u%1_000_000\n\ts := ufmt.Sprintf(\"%d.%s\", whole, pad6(frac))\n\tif neg {\n\t\ts = \"-\" + s\n\t}\n\treturn s + \" GNOT\"\n}\n\n// pad6 left-pads to six digits. ufmt has no width flags, so this is by hand.\nfunc pad6(n int64) string {\n\ts := strconv.FormatInt(n, 10)\n\tfor len(s) \u003c 6 {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n\n// permille renders tenths of a percent as a percentage with one decimal.\nfunc permille(p int64) string {\n\treturn ufmt.Sprintf(\"%d.%d%%\", p/10, p%10)\n}\n\n// duration renders a span of seconds as days and hours, which is the only\n// resolution worth reading on a two-year schedule.\nfunc duration(sec int64) string {\n\tif sec \u003c= 0 {\n\t\treturn \"complete\"\n\t}\n\td, h := sec/86400, (sec%86400)/3600\n\tvar b strings.Builder\n\tif d \u003e 0 {\n\t\tb.WriteString(strconv.FormatInt(d, 10))\n\t\tb.WriteString(\"d \")\n\t}\n\tb.WriteString(strconv.FormatInt(h, 10))\n\tb.WriteString(\"h\")\n\treturn b.String()\n}\n\n// isAddr is a cheap shape check, so a typo renders as \"not an address\" rather\n// than as an account with a zero balance.\nfunc isAddr(s string) bool {\n\tif len(s) != 40 || !strings.HasPrefix(s, \"g1\") {\n\t\treturn false\n\t}\n\tfor _, r := range s {\n\t\tif !(r \u003e= 'a' \u0026\u0026 r \u003c= 'z') \u0026\u0026 !(r \u003e= '0' \u0026\u0026 r \u003c= '9') {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// now is the chain's own clock, in unix seconds. time.Now() in a realm returns\n// the BLOCK time, not a wall clock, which is exactly the value the ante\n// handler compares a vesting schedule against.\nfunc now() int64 { return time.Now().Unix() }\n\nfunc chainHeight() int64 { return runtime.ChainHeight() }\n"},{"name":"vesting_test.gno","body":"package vesting\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\tmainnetStart int64 = 1789225200\n\tmainnetEnd   int64 = 1852383600\n\tmoul               = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n)\n\n// TestSeededSurvivesInit is the property the seed exists for: this realm is\n// private = true, so a redeploy re-runs init() and wipes everything else. The\n// one schedule the page is about has to come back without a transaction.\nfunc TestSeededSurvivesInit(t *testing.T) {\n\to, s, e, delayed, ok := ScheduleOf(moul)\n\tuassert.True(t, ok, \"moul's schedule is missing after init\")\n\tuassert.Equal(t, int64(106560000000), o)\n\tuassert.Equal(t, mainnetStart, s)\n\tuassert.Equal(t, mainnetEnd, e)\n\tuassert.False(t, delayed)\n}\n\n// TestDeclareWritesOnlyYourOwnRow is the entire trust model. A caller cannot\n// name an address, so it cannot describe one but its own.\nfunc TestDeclareWritesOnlyYourOwnRow(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tDeclare(cross(cur), 500, 100, 200, false)\n\n\to, s, e, delayed, ok := ScheduleOf(alice)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, int64(500), o)\n\tuassert.Equal(t, int64(100), s)\n\tuassert.Equal(t, int64(200), e)\n\tuassert.False(t, delayed)\n\n\t// Nothing alice did touched bob.\n\t_, _, _, _, ok = ScheduleOf(bob)\n\tuassert.False(t, ok, \"declaring for alice wrote a row for bob\")\n}\n\nfunc TestDeclareReplacesAndForgetRemoves(cur realm, t *testing.T) {\n\tcarol := testutils.TestAddress(\"carol\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tDeclare(cross(cur), 500, 100, 200, false)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tDeclare(cross(cur), 900, 10, 20, true)\n\n\to, s, e, delayed, ok := ScheduleOf(carol)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, int64(900), o)\n\tuassert.Equal(t, int64(10), s)\n\tuassert.Equal(t, int64(20), e)\n\tuassert.True(t, delayed, \"the delayed flag did not survive\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tForget(cross(cur))\n\t_, _, _, _, ok = ScheduleOf(carol)\n\tuassert.False(t, ok, \"Forget left the row behind\")\n}\n\nfunc TestForgetWithoutADeclarationAborts(cur realm, t *testing.T) {\n\tdave := testutils.TestAddress(\"dave\")\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tuassert.AbortsContains(t, cur, \"nothing declared\", func() { Forget(cross(cur)) })\n}\n\n// TestSeededRowIsNotWritable: the seeds are source, so a signer who happens to\n// hold a seeded address still cannot rewrite it from a transaction. Otherwise\n// a redeploy would silently revert whatever they set.\nfunc TestSeededRowIsNotWritable(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tuassert.AbortsContains(t, cur, \"seeded in the source\", func() {\n\t\tDeclare(cross(cur), 1, 2, 3, false)\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tuassert.AbortsContains(t, cur, \"seeded in the source\", func() { Forget(cross(cur)) })\n}\n\nfunc TestDeclareRejectsAnImpossibleSchedule(cur realm, t *testing.T) {\n\terin := testutils.TestAddress(\"erin\")\n\ttesting.SetRealm(testing.NewUserRealm(erin))\n\tuassert.AbortsContains(t, cur, \"start time must be before end time\", func() {\n\t\tDeclare(cross(cur), 100, 200, 100, false)\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(erin))\n\tuassert.AbortsContains(t, cur, \"cannot be negative\", func() {\n\t\tDeclare(cross(cur), -1, 0, 100, false)\n\t})\n}\n\n// TestDeclareZeroMeansNoSchedule lets an address say \"nothing of mine is\n// locked\", which is a real and useful claim.\nfunc TestDeclareZeroMeansNoSchedule(cur realm, t *testing.T) {\n\tfrank := testutils.TestAddress(\"frank\")\n\ttesting.SetRealm(testing.NewUserRealm(frank))\n\tDeclare(cross(cur), 0, 0, 0, false)\n\n\to, _, _, _, ok := ScheduleOf(frank)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, int64(0), o)\n\n\tspend, known := SpendableOf(frank)\n\tuassert.True(t, known)\n\tuassert.Equal(t, balanceOf(frank), spend)\n}\n\n// TestUnknownAddressReportsItsBalanceAndSaysSo: the balance is real, the\n// spendable figure is not, and the caller is told which is which.\nfunc TestUnknownAddressReportsItsBalanceAndSaysSo(t *testing.T) {\n\tstranger := testutils.TestAddress(\"stranger\")\n\n\tspend, ok := SpendableOf(stranger)\n\tuassert.False(t, ok, \"an unknown address must not claim a known schedule\")\n\tuassert.Equal(t, balanceOf(stranger), spend)\n\n\tlocked, ok := LockedOf(stranger)\n\tuassert.False(t, ok)\n\tuassert.Equal(t, int64(0), locked)\n}\n\nfunc TestCountTracksTheRegistry(cur realm, t *testing.T) {\n\tbefore := Count()\n\tgrace := testutils.TestAddress(\"grace\")\n\ttesting.SetRealm(testing.NewUserRealm(grace))\n\tDeclare(cross(cur), 10, 1, 2, false)\n\tuassert.Equal(t, before+1, Count())\n\ttesting.SetRealm(testing.NewUserRealm(grace))\n\tForget(cross(cur))\n\tuassert.Equal(t, before, Count())\n}\n\n// TestLockedIsCappedByTheBalance: an account that spent while its coins were\n// free can owe the schedule more than it now holds. The honest answer is that\n// nothing moves, never a negative spendable.\nfunc TestLockedIsCappedByTheBalance(cur realm, t *testing.T) {\n\tpoor := testutils.TestAddress(\"poor\")\n\ttesting.SetRealm(testing.NewUserRealm(poor))\n\tDeclare(cross(cur), 1000000000000, mainnetStart, mainnetEnd, false)\n\n\tlocked, ok := LockedOf(poor)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, balanceOf(poor), locked, \"locked must not exceed the balance\")\n\n\tspend, _ := SpendableOf(poor)\n\tuassert.Equal(t, int64(0), spend)\n\tuassert.True(t, spend \u003e= 0, \"spendable went negative\")\n}\n\nfunc TestIsAddr(t *testing.T) {\n\tuassert.True(t, isAddr(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"))\n\tuassert.False(t, isAddr(\"\"))\n\tuassert.False(t, isAddr(\"g1manfred\"))\n\tuassert.False(t, isAddr(\"x1manfred47kzduec920z88wfr64ylksmdcedlf5\"))\n\tuassert.False(t, isAddr(\"g1MANFRED47kzduec920z88wfr64ylksmdcedlf5\"))\n\tuassert.False(t, isAddr(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5x\"))\n}\n\nfunc TestGnotFormatting(t *testing.T) {\n\tuassert.Equal(t, \"0.000000 GNOT\", gnot(0))\n\tuassert.Equal(t, \"0.000001 GNOT\", gnot(1))\n\tuassert.Equal(t, \"1.000000 GNOT\", gnot(1000000))\n\tuassert.Equal(t, \"106560.000000 GNOT\", gnot(106560000000))\n\tuassert.Equal(t, \"1.234567 GNOT\", gnot(1234567))\n\tuassert.Equal(t, \"-1.500000 GNOT\", gnot(-1500000))\n}\n\nfunc TestPermilleFormatting(t *testing.T) {\n\tuassert.Equal(t, \"0.0%\", permille(0))\n\tuassert.Equal(t, \"5.0%\", permille(50))\n\tuassert.Equal(t, \"49.9%\", permille(499))\n\tuassert.Equal(t, \"100.0%\", permille(1000))\n}\n\nfunc TestDurationFormatting(t *testing.T) {\n\tuassert.Equal(t, \"complete\", duration(0))\n\tuassert.Equal(t, \"complete\", duration(-1))\n\tuassert.Equal(t, \"0h\", duration(60))\n\tuassert.Equal(t, \"1h\", duration(3600))\n\tuassert.Equal(t, \"1d 0h\", duration(86400))\n\tuassert.Equal(t, \"2d 3h\", duration(2*86400+3*3600))\n}\n\n// TestCivilDates pins the date arithmetic against dates that are known exactly,\n// including the two ends of the real mainnet term and a leap day.\nfunc TestCivilDates(t *testing.T) {\n\tuassert.Equal(t, \"1970-01-01\", tstamp(0))\n\tuassert.Equal(t, \"2000-02-29\", tstamp(951782400))\n\tuassert.Equal(t, \"2026-09-12\", tstamp(mainnetStart))\n\tuassert.Equal(t, \"2028-09-12\", tstamp(mainnetEnd))\n}\n\n// TestRenderShapes walks the three routes the page serves and checks each one\n// names its source, which is the promise the whole realm makes.\nfunc TestRenderShapes(t *testing.T) {\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"# Vesting\"), \"index has no title\")\n\tuassert.True(t, strings.Contains(index, \"no realm can read one\"),\n\t\t\"index does not say the schedule is supplied\")\n\n\tseeded := Render(moul.String())\n\tuassert.True(t, strings.Contains(seeded, \"seeded in this realm's source\"),\n\t\t\"a seeded row does not say where it came from\")\n\tuassert.True(t, strings.Contains(seeded, \"spendable now\"))\n\n\tquery := Render(moul.String() + \"?o=1000000\u0026s=100\u0026e=200\")\n\tuassert.True(t, strings.Contains(query, \"supplied in the URL by you\"),\n\t\t\"a query schedule does not say it was supplied\")\n\tuassert.True(t, strings.Contains(query, \"Nothing was stored.\"))\n\n\tunknown := Render(testutils.TestAddress(\"nobody\").String())\n\tuassert.True(t, strings.Contains(unknown, \"No schedule on file\"))\n\tuassert.True(t, strings.Contains(unknown, \"gnokey query auth/accounts/\"),\n\t\t\"the unknown page does not say how to find the schedule\")\n\n\tbad := Render(\"not-an-address\")\n\tuassert.True(t, strings.Contains(bad, \"is not a gno.land address\"))\n}\n\n// TestRenderEscapesWhatTheCallerTyped: the path is attacker-controlled and a\n// live realm can never be patched, so the escaping is checked before deploy.\nfunc TestRenderEscapesWhatTheCallerTyped(t *testing.T) {\n\tout := Render(\"[x](/r/evil)\")\n\tuassert.False(t, strings.Contains(out, \"[x](/r/evil)\"),\n\t\t\"a markdown link typed into the path reached the page unescaped\")\n}\n\n// TestRenderQueryRejectsGarbage keeps a typo readable instead of rendering a\n// schedule of zeroes as though it were real.\nfunc TestRenderQueryRejectsGarbage(t *testing.T) {\n\tout := Render(moul.String() + \"?o=abc\")\n\tuassert.True(t, strings.Contains(out, \"is not a number\"))\n\n\tout = Render(moul.String() + \"?o=100\u0026s=200\u0026e=100\")\n\tuassert.True(t, strings.Contains(out, \"not a valid schedule\"))\n}\n\n// TestChainHeightIsReadable guards the one call that would make Declare\n// non-deterministic if it were wrong.\nfunc TestChainHeightIsReadable(t *testing.T) {\n\tuassert.Equal(t, runtime.ChainHeight(), chainHeight())\n}\n\n// TestIndexIsBounded is the defect this realm shipped with: renderIndex\n// iterated EVERY registry row, and Declare is open to anyone, so the front\n// page grew without limit until it exceeded the query gas ceiling and stopped\n// rendering for everybody.\n//\n// vm/qrender runs on a gas meter. A realm that returns a large string fails\n// with OutOfGasError{Descriptor:\"CPUCycles\"} rather than answering slowly, and\n// the safe budget is tens of KB. A row is ~120 bytes, so a few hundred\n// declarations was enough. The realm is private = true, so the only repair\n// would have been a redeploy, which wipes every declaration and re-charges the\n// whole storage deposit.\nfunc TestIndexIsBounded(cur realm, t *testing.T) {\n\treset()\n\tfor i := 0; i \u003c 400; i++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(ufmt.Sprintf(\"spam%d\", i))))\n\t\tDeclare(cross(cur), 1000, 100, 200, false)\n\t}\n\tuassert.Equal(t, 400, Count(), \"the registry should hold every declaration\")\n\n\tout := Render(\"\")\n\tuassert.True(t, len(out) \u003c 12000,\n\t\tufmt.Sprintf(\"the index rendered %d bytes for 401 rows; it must page\", len(out)))\n\n\t// Paging still has to reach them, so page 2 differs from page 1.\n\tuassert.True(t, Render(\"?page=2\") != out, \"?page=2 rendered the same page as page 1\")\n\treset()\n}\n"}]},"send":"","max_deposit":"16000000ugnot"}],"fee":{"gas_wanted":"115974000","gas_fee":"347922ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"X2xqXNbDVY8h3MUcp0KKTc+NliGLqLgC53L3ACdUEF15c1cJeZXwpCqsY7UosQv0v3lRFdN/pZDxIzgNKtCcPw=="}],"memo":""},"metadata":{"timestamp":"1790960638"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"amm","path":"gno.land/r/moul/x/amm/v0","files":[{"name":"README.md","body":"# amm: a constant-product AMM whose LP positions are real GRC20 tokens\n\nA constant-product market maker for GRC20 pairs, many pools in one realm,\n`x*y=k` with a 30 bps fee that stays with the liquidity providers. A liquidity\nposition is a **GRC20 token**, minted per pool and registered with\n[`r/nt/grc20reg`](https://gno.land/r/nt/grc20reg/v0), so a position can be\ntransferred, approved, and priced by anything else on the chain.\n\nDesign study: [moul/gno-contracts#135](https://github.com/moul/gno-contracts/issues/135).\n\n## The ledger-row design this replaced, and what it cost to leave it\n\nThe first cut of this realm kept a position as a row in a private `avl.Tree`.\nThat is the smaller thing, and it is what the realm shipped with until the\nmeasurements below said the trade was worth taking. Both were built and run, so\nthe comparison is measured rather than argued, and the earlier shape is\nrecoverable from [#137](https://github.com/moul/gno-contracts/pull/137).\n\n| | a private ledger row | a registered GRC20 |\n|---|---|---|\n| transferable | no | yes |\n| approvable / usable as collateral | no | yes |\n| readable by another realm | no | yes, via `grc20reg.Get(key)` |\n| the realm must expose | nothing extra | 4 wrappers + `LPToken` |\n| pool creation also does | nothing | mint a token, write a registry entry |\n| allowance race surface | none | the standard GRC20 one |\n\nNothing about pricing, reserves, rounding or the guards moved: the ledger-row\nversion's `amm_test.gno` runs unmodified against this one, only the pkgpath\nstring differs. What moved is where a share lives.\n\nFour identical operations, one `--- GAS:` figure each, from the same\n`gas_test.gno` run against both. Fixture funding is measured separately so it\ndoes not pollute the comparison:\n\n| operation | ledger row | GRC20 | delta |\n|---|---|---|---|\n| seed (create pool + first deposit) | 1 716 207 | 2 213 407 | **+497 200 (+29.0%)** |\n| swap | 1 459 531 | 1 459 531 | **0 (+0.0%)** |\n| join (second provider) | 1 731 048 | 1 789 306 | +58 258 (+3.4%) |\n| exit (full burn) | 1 433 236 | 1 518 298 | +85 062 (+5.9%) |\n\n| | ledger row | GRC20 |\n|---|---|---|\n| `amm.gno`, total lines | 506 | 589 |\n| `amm.gno`, code lines | 333 | 359 |\n| exported functions | 10 | 15 |\n\nThe shape of that is the interesting part. **Swapping is unaffected to the\ngas unit**, because the hot path never touches share accounting: it reads two\nreserves, prices, moves two token balances, writes two reserves. The whole\npremium is paid where positions are created and destroyed. Pool creation\ncarries it almost entirely, once, as a fixed setup cost: minting the LP token\nand registering it. Per-provider operations pay 3 to 6 percent.\n\nRead the other way: **transferable LP positions cost a one-off ~0.5M gas per\npool and ~5% on liquidity operations, and nothing at all on trading.** That is\nwhy they are the default here, and why Uniswap V2 pairs are ERC20s.\n\n## The LP API\n\n```go\nLPToken(keyA, keyB string) string                 // the pool's LP token registry key\nAllowanceLP(keyA, keyB string, owner, spender address) int64\nTransferLP(cur realm, keyA, keyB string, to address, amount int64)\nApproveLP(cur realm, keyA, keyB string, spender address, amount int64)\nTransferFromLP(cur realm, keyA, keyB string, from, to address, amount int64)\n```\n\nThe four wrappers exist because the LP token lives *in this realm*: a signing\nuser has no token realm of its own to call, the way they would for any other\nGRC20. A **realm** holding LP does not need them and can move its own balance\nthrough the registry:\n\n```go\ngrc20reg.Transfer(0, cur, amm.LPToken(keyA, keyB), to, n)\n```\n\n`ApproveLP` carries the usual GRC20 approve race: an allowance lowered from a\nnon-zero value can be spent at both the old and the new figure under unlucky\nordering. Set it to 0 first.\n\n`SharesOf` and `TotalShares` are `lp.BalanceOf` and `lp.TotalSupply`;\n`AddLiquidity`, `RemoveLiquidity`, `Swap`, `AmountOut`, `Quote`, `Reserves`,\n`PoolCount` and `Render` are unchanged by the LP decision.\n\n## LP token naming\n\nOne token per pool, symbol `LP\u003cn\u003e` from a never-reset counter, name\n`AMM LP \u003csymA\u003e/\u003csymB\u003e`, decimals mirroring token A (the LP unit is token A at\nseed time). The symbol is a counter and not the pair because `grc20` caps a\nsymbol at 11 characters, which `LP-` plus two 11-character symbols would blow\nstraight past; the readable pair goes in the name, which allows 64.\n\nNever resetting the counter is what keeps `grc20reg`'s\none-token-per-realm-and-symbol rule satisfiable forever: a drained pool keeps\nits LP token and identity, and reseeding reuses it rather than minting a\nsecond token under a symbol already taken.\n\n## Warnings\n\n- **Not an oracle.** The reserve ratio is a spot price any trader can move\n  inside one transaction. Nothing should price off this realm.\n- **`minOut` is your only slippage protection**, **a pool is only as honest as\n  its two tokens**, and **none of this is audited**.\n- **The LP `PrivateLedger` never leaves this realm.** It is the minting\n  authority; exporting it, even indirectly, would let anyone mint positions\n  against real reserves.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/amm/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/amm/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/amm/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/amm/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/amm/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/amm/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/amm/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/amm/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/amm/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/amm/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"amm.gno","body":"// Package amm is a minimal constant-product automated market maker for GRC20\n// token pairs, in a single file.\n//\n// It holds many pools in one realm. A pool is created implicitly by its first\n// liquidity deposit and is addressed by the two tokens' grc20reg keys, in\n// either order. Swaps follow x*y=k with a 30 bps fee that stays in the pool\n// and therefore accrues to the liquidity providers.\n//\n// # What it is not\n//\n// Not an oracle: the reserve ratio is a spot price that any trader can move\n// within a single transaction. Nothing should price off this realm.\n// Not audited. Not a router: one hop, one pool, no path finding. Not a\n// place to park value.\n//\n// # Design notes worth knowing before calling it\n//\n// Reserves are stored fields and are NEVER derived from BalanceOf. That is\n// the single decision that removes Uniswap V2's MINIMUM_LIQUIDITY burn, its\n// skim/sync pair, and the first-depositor share-inflation attack in one go:\n// sending tokens straight to this realm's address changes no reserve, no\n// price and no share value. The price of that is blunt and worth stating:\n// tokens sent directly to the realm address are PERMANENTLY STUCK.\n//\n// The first deposit mints shares equal to the token-A amount rather than\n// sqrt(A*B). The geometric mean is cosmetic, every later operation uses only\n// ratios, and dropping it removes an integer square root over a 128-bit\n// product. Later deposits mint min(A-side, B-side) with floor division on\n// both, so an off-ratio deposit always rounds against the depositor.\n//\n// # v1 vs v0: LP shares are a real GRC20 token\n//\n// v0 tracks LP positions in a private avl ledger: smallest possible, but a\n// position can only be held by the address that opened it and is invisible to\n// every other contract. v1 mints one GRC20 token per pool instead, holds its\n// PrivateLedger, and registers it with grc20reg. A position is then an\n// ordinary fungible token: transferable, approvable, usable as collateral,\n// and readable by any realm that knows the registry key.\n//\n// The cost is honest and measurable. Pool creation now also mints a token and\n// writes a registry entry. Positions gain an allowance surface, and with it\n// the classic GRC20 approve race. And because MsgCall cannot pass a realm\n// argument, this realm has to re-export Transfer/Approve/TransferFrom/\n// Allowance wrappers over the LP token for signing users, four functions that\n// v0 does not need at all. Another REALM can skip them and move its own LP\n// balance through grc20reg directly.\n//\n// All amounts are int64, as GRC20 mandates, and there is no 256-bit type in\n// reach. Pricing therefore runs through a 128-bit mulDiv (math/bits), and\n// every reserve is capped at maxReserve so that the plain int64 parts of the\n// formula cannot overflow. See the comment on maxReserve for the arithmetic,\n// and note the consequence: this AMM is unusable with 18-decimal tokens.\n// Six to nine decimals is the practical band.\n//\n// Design study and full analysis: https://github.com/moul/gno-contracts/issues/135\npackage amm\n\nimport (\n\t\"chain\"\n\t\"math\"\n\t\"math/bits\"\n\t\"strconv\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nconst (\n\t// feeNum/feeDen is the swap fee kept by the pool: 997/1000, i.e. 30 bps.\n\tfeeNum = 997\n\tfeeDen = 1000\n\n\t// maxReserve is the largest reserve a pool will hold, in base units.\n\t//\n\t// Pricing computes den = reserveIn*feeDen + amountIn*feeNum in plain\n\t// int64 before handing off to the 128-bit mulDiv. Capping every reserve,\n\t// and every post-swap reserve, at MaxInt64/feeDen makes that sum provably\n\t// safe:\n\t//\n\t//\tden \u003c (reserveIn + amountIn) * feeDen \u003c= maxReserve * feeDen\n\t//\t    = 9223372036854775000 \u003c= MaxInt64 = 9223372036854775807\n\t//\n\t// AddLiquidity enforces the cap on the reserves themselves and Swap\n\t// enforces it on reserveIn+amountIn, so a pool can never even enter the\n\t// region where the formula would be unsafe.\n\tmaxReserve = math.MaxInt64 / feeDen // 9223372036854775\n)\n\n// pool is one token pair. keyA \u003c keyB always holds: the pair is canonicalised\n// on the way in, so (X,Y) and (Y,X) address the same pool.\ntype pool struct {\n\tkeyA, keyB string\n\ttokA, tokB *grc20.Token\n\tresA, resB int64\n\n\t// lp is this pool's LP token: total supply is the share supply and a\n\t// holder's balance is their position. lpLedger is the minting authority\n\t// and MUST NOT leak out of this file. lpKey is lp's grc20reg key.\n\tlp       *grc20.Token\n\tlpLedger *grc20.PrivateLedger\n\tlpKey    string\n}\n\n// pools maps the pool id \"keyA~keyB\" -\u003e *pool. \"~\" cannot occur in a\n// grc20reg key, and unlike \"|\" it does not break a markdown table cell.\nvar pools avl.Tree\n\n// lpSeq numbers the LP tokens. It is never reset, so a symbol is never reused\n// and grc20reg's one-token-per-realm-and-symbol rule is never tripped.\nvar lpSeq seqid.ID\n\n//\n// Writes.\n//\n\n// AddLiquidity deposits up to maxA of keyA and maxB of keyB and mints LP\n// shares to the caller. It creates the pool if this is its first deposit, in\n// which case the caller's amounts set the starting price and the whole of\n// maxA and maxB is taken.\n//\n// On an existing pool the deposit is trimmed to the current reserve ratio:\n// only one side is consumed in full and the remainder of the richer side is\n// left untouched, so pass the amounts you are willing to spend, not the\n// amounts you insist on spending.\n//\n// The caller must first Approve this realm's address on BOTH tokens for at\n// least the amounts that will be taken. Returns the shares minted.\nfunc AddLiquidity(cur realm, keyA, keyB string, maxA, maxB int64) int64 {\n\ta, b, flipped := canon(keyA, keyB)\n\tamtA, amtB := maxA, maxB\n\tif flipped {\n\t\tamtA, amtB = maxB, maxA\n\t}\n\tif amtA \u003c= 0 || amtB \u003c= 0 {\n\t\tpanic(\"amm: both deposit amounts must be \u003e 0\")\n\t}\n\n\tp := getPool(a, b)\n\tif p == nil {\n\t\tp = newPool(0, cur, a, b)\n\t\tpools.Set(poolID(a, b), p)\n\t}\n\n\tvar minted int64\n\tif p.lp.TotalSupply() == 0 {\n\t\t// First position: the depositor sets the price and the share unit is\n\t\t// token A at seed time. No sqrt, no MINIMUM_LIQUIDITY burn.\n\t\tminted = amtA\n\t} else {\n\t\t// Trim to the current ratio, then mint from whichever side is scarcer.\n\t\t// Both divisions floor, and taking the minimum means an off-ratio\n\t\t// deposit is rounded against the depositor, never against the pool.\n\t\tif want := mulDiv(amtA, p.resB, p.resA); want \u003c= amtB {\n\t\t\tamtB = want\n\t\t} else {\n\t\t\tamtA = mulDiv(amtB, p.resA, p.resB)\n\t\t}\n\t\tif amtA \u003c= 0 || amtB \u003c= 0 {\n\t\t\tpanic(\"amm: deposit too small for the current ratio\")\n\t\t}\n\t\tsupply := p.lp.TotalSupply()\n\t\tminted = min64(\n\t\t\tmulDiv(amtA, supply, p.resA),\n\t\t\tmulDiv(amtB, supply, p.resB),\n\t\t)\n\t}\n\tif minted \u003c= 0 {\n\t\tpanic(\"amm: deposit mints zero shares\")\n\t}\n\tif p.resA+amtA \u003e maxReserve || p.resB+amtB \u003e maxReserve {\n\t\tpanic(\"amm: reserve cap exceeded\")\n\t}\n\n\tprovider := cur.Previous().Address()\n\tself := cur.Address()\n\tpull(0, cur, p.tokA, provider, self, amtA)\n\tpull(0, cur, p.tokB, provider, self, amtB)\n\n\tp.resA += amtA\n\tp.resB += amtB\n\tif err := p.lpLedger.Mint(provider, minted); err != nil {\n\t\tpanic(\"amm: cannot mint LP shares: \" + err.Error())\n\t}\n\n\tchain.Emit(\"AddLiquidity\",\n\t\t\"pool\", poolID(p.keyA, p.keyB),\n\t\t\"provider\", provider.String(),\n\t\t\"amountA\", itoa(amtA),\n\t\t\"amountB\", itoa(amtB),\n\t\t\"shares\", itoa(minted),\n\t)\n\treturn minted\n}\n\n// RemoveLiquidity burns shares held by the caller and returns the proportional\n// amounts of both tokens, in the caller's (keyA, keyB) argument order.\n//\n// Burning the pool's entire share supply pays out the whole reserve, so the\n// last provider out leaves nothing unclaimable behind and the pool can be\n// reseeded at a fresh price.\nfunc RemoveLiquidity(cur realm, keyA, keyB string, shares int64) (int64, int64) {\n\tif shares \u003c= 0 {\n\t\tpanic(\"amm: shares must be \u003e 0\")\n\t}\n\ta, b, flipped := canon(keyA, keyB)\n\tp := mustPool(a, b)\n\n\towner := cur.Previous().Address()\n\tif p.lp.BalanceOf(owner) \u003c shares {\n\t\tpanic(\"amm: insufficient shares\")\n\t}\n\n\tsupply := p.lp.TotalSupply()\n\tvar amtA, amtB int64\n\tif shares == supply {\n\t\tamtA, amtB = p.resA, p.resB\n\t} else {\n\t\tamtA = mulDiv(shares, p.resA, supply)\n\t\tamtB = mulDiv(shares, p.resB, supply)\n\t}\n\tif amtA \u003c= 0 || amtB \u003c= 0 {\n\t\tpanic(\"amm: burn would return nothing on one side\")\n\t}\n\n\tp.resA -= amtA\n\tp.resB -= amtB\n\tif err := p.lpLedger.Burn(owner, shares); err != nil {\n\t\tpanic(\"amm: cannot burn LP shares: \" + err.Error())\n\t}\n\n\tpush(0, cur, p.tokA, owner, amtA)\n\tpush(0, cur, p.tokB, owner, amtB)\n\n\tchain.Emit(\"RemoveLiquidity\",\n\t\t\"pool\", poolID(p.keyA, p.keyB),\n\t\t\"provider\", owner.String(),\n\t\t\"amountA\", itoa(amtA),\n\t\t\"amountB\", itoa(amtB),\n\t\t\"shares\", itoa(shares),\n\t)\n\tif flipped {\n\t\treturn amtB, amtA\n\t}\n\treturn amtA, amtB\n}\n\n// Swap sells amountIn of keyIn for keyOut and aborts unless at least minOut\n// comes back. The caller must first Approve this realm's address on keyIn.\n//\n// minOut is the only protection against being sandwiched or against the pool\n// moving between quoting and execution. Pass a real bound; passing 0 means\n// accepting any price at all.\nfunc Swap(cur realm, keyIn, keyOut string, amountIn, minOut int64) int64 {\n\tif amountIn \u003c= 0 {\n\t\tpanic(\"amm: amountIn must be \u003e 0\")\n\t}\n\tif minOut \u003c 0 {\n\t\tpanic(\"amm: minOut must be \u003e= 0\")\n\t}\n\ta, b, flipped := canon(keyIn, keyOut)\n\tp := mustPool(a, b)\n\n\tresIn, resOut := p.resA, p.resB\n\ttokIn, tokOut := p.tokA, p.tokB\n\tif flipped {\n\t\tresIn, resOut = p.resB, p.resA\n\t\ttokIn, tokOut = p.tokB, p.tokA\n\t}\n\n\tout := AmountOut(amountIn, resIn, resOut)\n\tif out \u003c= 0 {\n\t\tpanic(\"amm: output rounds to zero\")\n\t}\n\tif out \u003c minOut {\n\t\tpanic(\"amm: slippage, output below minOut\")\n\t}\n\n\ttrader := cur.Previous().Address()\n\tpull(0, cur, tokIn, trader, cur.Address(), amountIn)\n\n\tnewIn, newOut := resIn+amountIn, resOut-out\n\t// The invariant holds by construction (out is floored), so this can only\n\t// fire if the pricing above is ever edited into being wrong. It is exact:\n\t// both products are compared in 128 bits.\n\tif cmpProd(newIn, newOut, resIn, resOut) \u003c 0 {\n\t\tpanic(\"amm: constant product regression\")\n\t}\n\tif flipped {\n\t\tp.resB, p.resA = newIn, newOut\n\t} else {\n\t\tp.resA, p.resB = newIn, newOut\n\t}\n\n\tpush(0, cur, tokOut, trader, out)\n\n\tchain.Emit(\"Swap\",\n\t\t\"pool\", poolID(p.keyA, p.keyB),\n\t\t\"trader\", trader.String(),\n\t\t\"tokenIn\", tokIn.GetSymbol(),\n\t\t\"amountIn\", itoa(amountIn),\n\t\t\"amountOut\", itoa(out),\n\t)\n\treturn out\n}\n\n// TransferLP moves amount of the caller's LP position to `to`.\n//\n// The LP token lives in this realm, so a signing user cannot reach it through\n// the token's own entry points the way they would for any other GRC20: there\n// are none. These four wrappers are that entry point. A REALM holding LP does\n// not need them and can go through grc20reg instead:\n//\n//\tgrc20reg.Transfer(0, cur, amm.LPToken(keyA, keyB), to, n)\nfunc TransferLP(cur realm, keyA, keyB string, to address, amount int64) {\n\ta, b, _ := canon(keyA, keyB)\n\tlpCheck(mustPool(a, b).lpLedger.CallerTeller().Transfer(0, cur, to, amount))\n}\n\n// ApproveLP lets spender move up to amount of the caller's LP position.\n//\n// Same approve race as any GRC20: an allowance changed from a non-zero value\n// can be spent at both the old and the new one if the holder is unlucky with\n// ordering. Set it to 0 first when lowering it.\nfunc ApproveLP(cur realm, keyA, keyB string, spender address, amount int64) {\n\ta, b, _ := canon(keyA, keyB)\n\tlpCheck(mustPool(a, b).lpLedger.CallerTeller().Approve(0, cur, spender, amount))\n}\n\n// TransferFromLP spends an allowance the owner granted to the caller.\nfunc TransferFromLP(cur realm, keyA, keyB string, from, to address, amount int64) {\n\ta, b, _ := canon(keyA, keyB)\n\tlpCheck(mustPool(a, b).lpLedger.CallerTeller().TransferFrom(0, cur, from, to, amount))\n}\n\nfunc lpCheck(err error) {\n\tif err != nil {\n\t\tpanic(\"amm: LP token: \" + err.Error())\n\t}\n}\n\n//\n// Reads.\n//\n\n// AmountOut is the pricing function, fee included, as a pure function of the\n// two reserves. Exported so a caller can quote off-chain against reserves it\n// already holds, and so the arithmetic is testable on its own.\nfunc AmountOut(amountIn, reserveIn, reserveOut int64) int64 {\n\tif amountIn \u003c= 0 {\n\t\tpanic(\"amm: amountIn must be \u003e 0\")\n\t}\n\tif reserveIn \u003c= 0 || reserveOut \u003c= 0 {\n\t\tpanic(\"amm: pool has an empty reserve\")\n\t}\n\tif reserveIn \u003e maxReserve || reserveOut \u003e maxReserve {\n\t\tpanic(\"amm: reserve above cap\")\n\t}\n\tif amountIn \u003e maxReserve-reserveIn {\n\t\tpanic(\"amm: reserve cap exceeded\")\n\t}\n\tinFee := amountIn * feeNum\n\tden := reserveIn*feeDen + inFee\n\treturn mulDiv(inFee, reserveOut, den)\n}\n\n// Quote prices amountIn of keyIn against the pool's live reserves. It is the\n// number Swap would return right now, which is not a promise about the next\n// block.\nfunc Quote(keyIn, keyOut string, amountIn int64) int64 {\n\ta, b, flipped := canon(keyIn, keyOut)\n\tp := mustPool(a, b)\n\tif flipped {\n\t\treturn AmountOut(amountIn, p.resB, p.resA)\n\t}\n\treturn AmountOut(amountIn, p.resA, p.resB)\n}\n\n// Reserves returns the two reserves in the caller's argument order.\nfunc Reserves(keyA, keyB string) (int64, int64) {\n\ta, b, flipped := canon(keyA, keyB)\n\tp := mustPool(a, b)\n\tif flipped {\n\t\treturn p.resB, p.resA\n\t}\n\treturn p.resA, p.resB\n}\n\n// SharesOf returns owner's LP shares, i.e. their LP token balance.\nfunc SharesOf(keyA, keyB string, owner address) int64 {\n\ta, b, _ := canon(keyA, keyB)\n\treturn mustPool(a, b).lp.BalanceOf(owner)\n}\n\n// TotalShares returns the pool's LP token total supply.\nfunc TotalShares(keyA, keyB string) int64 {\n\ta, b, _ := canon(keyA, keyB)\n\treturn mustPool(a, b).lp.TotalSupply()\n}\n\n// LPToken returns the grc20reg key of the pool's LP token. Hand it to any\n// realm that should read or move these positions without importing this one.\nfunc LPToken(keyA, keyB string) string {\n\ta, b, _ := canon(keyA, keyB)\n\treturn mustPool(a, b).lpKey\n}\n\n// AllowanceLP reports how much of owner's LP position spender may move.\nfunc AllowanceLP(keyA, keyB string, owner, spender address) int64 {\n\ta, b, _ := canon(keyA, keyB)\n\treturn mustPool(a, b).lp.Allowance(owner, spender)\n}\n\n// PoolCount returns how many pools exist.\nfunc PoolCount() int { return pools.Size() }\n\n// Render lists every pool, or one pool's detail when path is a \"keyA~keyB\"\n// pool id.\nfunc Render(path string) string {\n\tif path != \"\" {\n\t\tv := pools.Get(path)\n\t\tif v == nil {\n\t\t\treturn \"# 404\\n\\nNo pool `\" + path + \"`.\\n\"\n\t\t}\n\t\tp := v.(*pool)\n\t\tout := \"# \" + p.tokA.GetSymbol() + \" / \" + p.tokB.GetSymbol() + \"\\n\\n\"\n\t\tout += \"- **\" + p.tokA.GetSymbol() + \"** reserve: \" + itoa(p.resA) + \" (`\" + p.keyA + \"`)\\n\"\n\t\tout += \"- **\" + p.tokB.GetSymbol() + \"** reserve: \" + itoa(p.resB) + \" (`\" + p.keyB + \"`)\\n\"\n\t\tout += \"- **LP token**: `\" + p.lpKey + \"` (\" + p.lp.GetSymbol() + \")\\n\"\n\t\tout += \"- **LP shares**: \" + itoa(p.lp.TotalSupply()) + \" across \" + strconv.Itoa(p.lp.KnownAccounts()) + \" holder(s)\\n\"\n\t\treturn out\n\t}\n\n\tout := \"# Minimal AMM\\n\\n\"\n\tout += \"Constant product (`x*y=k`) with a 30 bps fee kept by the pool. Every position is a transferable GRC20 LP token. Reserves are stored, never read from balances, so sending tokens here directly does nothing and they cannot be recovered.\\n\\n\"\n\tif pools.Size() == 0 {\n\t\tout += \"_No pools yet. Call `AddLiquidity` with two `grc20reg` keys to open one._\\n\"\n\t\treturn out\n\t}\n\tout += \"| pool | reserves | LP token | supply | holders |\\n\"\n\tout += \"|---|---|---|---|---|\\n\"\n\tpools.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tp := value.(*pool)\n\t\tout += ufmt.Sprintf(\"| [%s/%s](/r/moul/x/amm/v0:%s) | %d %s / %d %s | %s | %d | %d |\\n\",\n\t\t\tp.tokA.GetSymbol(), p.tokB.GetSymbol(), key,\n\t\t\tp.resA, p.tokA.GetSymbol(), p.resB, p.tokB.GetSymbol(),\n\t\t\tp.lp.GetSymbol(), p.lp.TotalSupply(), p.lp.KnownAccounts())\n\t\treturn false\n\t})\n\treturn out\n}\n\n//\n// Internals.\n//\n\n// canon sorts a caller's token pair into the pool's canonical order and\n// reports whether the caller's order was reversed.\nfunc canon(first, second string) (a, b string, flipped bool) {\n\tif first == \"\" || second == \"\" {\n\t\tpanic(\"amm: empty token key\")\n\t}\n\tif first == second {\n\t\tpanic(\"amm: a pool needs two different tokens\")\n\t}\n\tif first \u003e second {\n\t\treturn second, first, true\n\t}\n\treturn first, second, false\n}\n\n// newPool resolves both tokens, mints this pool's LP token and registers it.\n//\n// Non-crossing (`_ int, rlm realm`): grc20.NewToken binds the token's\n// origRealm to rlm.PkgPath() under an IsCurrent assertion, and grc20reg\n// keys off the registering caller, so rlm has to stay AddLiquidity's own\n// live frame rather than a fresh one.\n//\n// The LP unit is token A at seed time, so the LP token mirrors token A's\n// decimals. The symbol is LP\u003cn\u003e because grc20 caps a symbol at 11 chars,\n// which \"LP-\" plus two 11-char symbols would blow past; the human-readable\n// pair lives in the name instead.\nfunc newPool(_ int, rlm realm, a, b string) *pool {\n\ttokA, tokB := grc20reg.MustGet(a), grc20reg.MustGet(b)\n\tid := lpSeq.Next()\n\tlp, ledger := grc20.NewToken(\n\t\t\"AMM LP \"+tokA.GetSymbol()+\"/\"+tokB.GetSymbol(),\n\t\t\"LP\"+strconv.FormatUint(uint64(id), 10),\n\t\ttokA.GetDecimals(),\n\t\tid,\n\t\trlm,\n\t)\n\tp := \u0026pool{keyA: a, keyB: b, tokA: tokA, tokB: tokB, lp: lp, lpLedger: ledger}\n\tp.lpKey = grc20reg.Register(cross(rlm), lp, \"\")\n\treturn p\n}\n\n// poolID is the storage and render key for a canonicalised pair.\nfunc poolID(a, b string) string { return a + \"~\" + b }\n\nfunc getPool(a, b string) *pool {\n\tv := pools.Get(poolID(a, b))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*pool)\n}\n\nfunc mustPool(a, b string) *pool {\n\tp := getPool(a, b)\n\tif p == nil {\n\t\tpanic(\"amm: no such pool: \" + poolID(a, b))\n\t}\n\treturn p\n}\n\n// pull moves amount of tok from `from` into this realm, spending the\n// allowance `from` granted to this realm's address.\n//\n// Non-crossing on purpose: `_ int, rlm realm` is the only shape that keeps\n// rlm the caller's own live frame. RealmTeller binds the spender eagerly to\n// rlm.Address(), which is this realm.\nfunc pull(_ int, rlm realm, tok *grc20.Token, from, to address, amount int64) {\n\terr := tok.RealmTeller(0, rlm).TransferFrom(0, rlm, from, to, amount)\n\tif err != nil {\n\t\tpanic(\"amm: cannot take \" + tok.GetSymbol() + \": \" + err.Error())\n\t}\n}\n\n// push sends amount of tok from this realm to `to`.\nfunc push(_ int, rlm realm, tok *grc20.Token, to address, amount int64) {\n\terr := tok.RealmTeller(0, rlm).Transfer(0, rlm, to, amount)\n\tif err != nil {\n\t\tpanic(\"amm: cannot send \" + tok.GetSymbol() + \": \" + err.Error())\n\t}\n}\n\n// mulDiv returns floor(a*b/c) through a 128-bit intermediate, which plain\n// int64 arithmetic cannot do: a*b is routinely wider than 63 bits here even\n// when the quotient is small.\nfunc mulDiv(a, b, c int64) int64 {\n\tif a \u003c 0 || b \u003c 0 {\n\t\tpanic(\"amm: negative operand\")\n\t}\n\tif c \u003c= 0 {\n\t\tpanic(\"amm: division by a non-positive value\")\n\t}\n\thi, lo := bits.Mul64(uint64(a), uint64(b))\n\t// bits.Div64 panics for y \u003c= hi; refusing here turns that into a named\n\t// abort and also covers every quotient that would not fit in 64 bits.\n\tif hi \u003e= uint64(c) {\n\t\tpanic(\"amm: quotient overflows int64\")\n\t}\n\tq, _ := bits.Div64(hi, lo, uint64(c))\n\tif q \u003e uint64(math.MaxInt64) {\n\t\tpanic(\"amm: quotient overflows int64\")\n\t}\n\treturn int64(q)\n}\n\n// cmpProd compares a*b with c*d exactly, in 128 bits, and returns -1, 0 or 1.\nfunc cmpProd(a, b, c, d int64) int {\n\th1, l1 := bits.Mul64(uint64(a), uint64(b))\n\th2, l2 := bits.Mul64(uint64(c), uint64(d))\n\tif h1 != h2 {\n\t\tif h1 \u003c h2 {\n\t\t\treturn -1\n\t\t}\n\t\treturn 1\n\t}\n\tif l1 != l2 {\n\t\tif l1 \u003c l2 {\n\t\t\treturn -1\n\t\t}\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc min64(a, b int64) int64 {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc itoa(v int64) string { return strconv.FormatInt(v, 10) }\n"},{"name":"amm_test.gno","body":"package amm\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\n// Two throwaway tokens, minted and registered once for the whole test binary.\n// They are created from this realm, so grc20reg keys them under this path.\nvar (\n\ttokAAA, tokBBB *grc20.Token\n\tledAAA, ledBBB *grc20.PrivateLedger\n\tkeyAAA, keyBBB string\n)\n\nfunc init(cur realm) {\n\ttokAAA, ledAAA = grc20.NewToken(\"Test Alpha\", \"AAA\", 6, 0, cur)\n\ttokBBB, ledBBB = grc20.NewToken(\"Test Beta\", \"BBB\", 6, 1, cur)\n\tkeyAAA = grc20reg.Register(cross(cur), tokAAA, \"\")\n\tkeyBBB = grc20reg.Register(cross(cur), tokBBB, \"\")\n}\n\nfunc self() address { return chain.PackageAddress(\"gno.land/r/moul/x/amm/v0\") }\n\n// fund mints both tokens to addr and approves this realm to spend them.\nfunc fund(addr address, amount int64) {\n\tledAAA.Mint(addr, amount)\n\tledBBB.Mint(addr, amount)\n\tledAAA.Approve(addr, self(), amount)\n\tledBBB.Approve(addr, self(), amount)\n}\n\n// reset clears every pool so each test starts from an empty realm.\nfunc reset() { pools = avl.Tree{} }\n\n//\n// Pure arithmetic.\n//\n\nfunc TestAmountOut(t *testing.T) {\n\tcases := []struct {\n\t\tname                   string\n\t\tin, resIn, resOut, want int64\n\t}{\n\t\t{\"balanced pool, small trade\", 1_000, 1_000_000, 1_000_000, 996},\n\t\t{\"balanced pool, 1%\", 10_000, 1_000_000, 1_000_000, 9_871},\n\t\t{\"balanced pool, 10%\", 100_000, 1_000_000, 1_000_000, 90_661},\n\t\t{\"balanced pool, 50%\", 500_000, 1_000_000, 1_000_000, 332_665},\n\t\t{\"skewed pool\", 100_000, 1_000_000, 4_000_000, 362_644},\n\t\t{\"near drain\", 1_000, 1, 1_000_000, 998_997},\n\t\t{\"dust rounds to zero\", 1, 1_000_000, 1_000_000, 0},\n\t\t{\"reserves at the cap\", maxReserve / 2, maxReserve / 2, maxReserve, 4_604_758_097_518_382},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := AmountOut(tc.in, tc.resIn, tc.resOut)\n\t\tuassert.Equal(t, tc.want, got, tc.name)\n\t}\n}\n\nfunc TestAmountOutNeverBreaksK(t *testing.T) {\n\tresIn, resOut := int64(3_000_000), int64(7_500_000)\n\tfor _, in := range []int64{1, 7, 1_000, 999_999, 3_000_000} {\n\t\tout := AmountOut(in, resIn, resOut)\n\t\tuassert.True(t, out \u003c resOut, \"output must stay inside the reserve\")\n\t\tuassert.True(t, cmpProd(resIn+in, resOut-out, resIn, resOut) \u003e= 0, \"k must not decrease\")\n\t}\n}\n\nfunc TestAmountOutGuards(cur realm, t *testing.T) {\n\tuassert.PanicsWithMessage(t, cur, \"amm: amountIn must be \u003e 0\", func() {\n\t\tAmountOut(0, 1_000, 1_000)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"amm: pool has an empty reserve\", func() {\n\t\tAmountOut(1, 0, 1_000)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"amm: reserve above cap\", func() {\n\t\tAmountOut(1, maxReserve+1, 1_000)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"amm: reserve cap exceeded\", func() {\n\t\tAmountOut(maxReserve, maxReserve, 1_000)\n\t})\n}\n\nfunc TestMulDiv(t *testing.T) {\n\tuassert.Equal(t, int64(0), mulDiv(0, 12345, 7))\n\tuassert.Equal(t, int64(3), mulDiv(7, 5, 10)) // floors\n\t// 2^62 * 4 is 2^64: the intermediate does not fit in int64, the result does.\n\tconst big = int64(1) \u003c\u003c 62\n\tuassert.Equal(t, big/2, mulDiv(big, 4, 8))\n\t// maxReserve * feeDen is the widest product this realm ever forms.\n\tuassert.Equal(t, int64(maxReserve), mulDiv(maxReserve, feeDen, feeDen))\n}\n\nfunc TestCmpProd(t *testing.T) {\n\tconst big = int64(1) \u003c\u003c 40\n\tuassert.Equal(t, 0, cmpProd(big, big, big, big))\n\tuassert.Equal(t, -1, cmpProd(big, big, big, big+1))\n\tuassert.Equal(t, 1, cmpProd(big, big+1, big, big))\n}\n\n//\n// Lifecycle.\n//\n\nfunc TestSeedSwapRemove(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"seed-alice\")\n\tfund(alice, 10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\theldA, heldB := tokAAA.BalanceOf(self()), tokBBB.BalanceOf(self())\n\n\t// Seed: the first provider sets the price and gets shares == amountA.\n\tminted := AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)\n\tuassert.Equal(t, int64(1_000_000), minted)\n\tuassert.Equal(t, int64(1), int64(PoolCount()))\n\n\trA, rB := Reserves(keyAAA, keyBBB)\n\tuassert.Equal(t, int64(1_000_000), rA)\n\tuassert.Equal(t, int64(4_000_000), rB)\n\tuassert.Equal(t, heldA+1_000_000, tokAAA.BalanceOf(self()), \"reserve is really held\")\n\n\t// Swap AAA -\u003e BBB.\n\tquoted := Quote(keyAAA, keyBBB, 100_000)\n\tuassert.Equal(t, int64(362_644), quoted)\n\tout := Swap(cross(cur), keyAAA, keyBBB, 100_000, 362_000)\n\tuassert.Equal(t, quoted, out)\n\n\trA, rB = Reserves(keyAAA, keyBBB)\n\tuassert.Equal(t, int64(1_100_000), rA)\n\tuassert.Equal(t, int64(3_637_356), rB)\n\tuassert.True(t, cmpProd(rA, rB, 1_000_000, 4_000_000) \u003e 0, \"fee grew k\")\n\n\t// Burn half the position.\n\tgotA, gotB := RemoveLiquidity(cross(cur), keyAAA, keyBBB, 500_000)\n\tuassert.Equal(t, int64(550_000), gotA)\n\tuassert.Equal(t, int64(1_818_678), gotB)\n\tuassert.Equal(t, int64(500_000), TotalShares(keyAAA, keyBBB))\n\n\t// Burn the rest: the last provider out takes the whole reserve.\n\tgotA, gotB = RemoveLiquidity(cross(cur), keyAAA, keyBBB, 500_000)\n\tuassert.Equal(t, int64(550_000), gotA)\n\tuassert.Equal(t, int64(1_818_678), gotB)\n\tuassert.Equal(t, int64(0), TotalShares(keyAAA, keyBBB))\n\trA, rB = Reserves(keyAAA, keyBBB)\n\tuassert.Equal(t, int64(0), rA)\n\tuassert.Equal(t, int64(0), rB)\n\tuassert.Equal(t, heldA, tokAAA.BalanceOf(self()), \"nothing unclaimable left behind\")\n\tuassert.Equal(t, heldB, tokBBB.BalanceOf(self()), \"nothing unclaimable left behind\")\n\n\t// A drained pool is reseedable, at whatever price the next provider picks.\n\tuassert.Equal(t, int64(200_000), AddLiquidity(cross(cur), keyAAA, keyBBB, 200_000, 100_000))\n\trA, rB = Reserves(keyAAA, keyBBB)\n\tuassert.Equal(t, int64(200_000), rA)\n\tuassert.Equal(t, int64(100_000), rB)\n}\n\nfunc TestArgumentOrderIsSymmetric(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"sym-alice\")\n\tfund(alice, 10_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tAddLiquidity(cross(cur), keyBBB, keyAAA, 4_000_000, 1_000_000)\n\tuassert.Equal(t, int64(1), int64(PoolCount()), \"one pool whichever order is used\")\n\n\trA, rB := Reserves(keyAAA, keyBBB)\n\tuassert.Equal(t, int64(1_000_000), rA)\n\tuassert.Equal(t, int64(4_000_000), rB)\n\n\trB2, rA2 := Reserves(keyBBB, keyAAA)\n\tuassert.Equal(t, rA, rA2, \"reserves follow the caller's order\")\n\tuassert.Equal(t, rB, rB2, \"reserves follow the caller's order\")\n}\n\nfunc TestSecondProviderIsTrimmedToRatio(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"trim-alice\")\n\tbob := testutils.TestAddress(\"trim-bob\")\n\tfund(alice, 10_000_000)\n\tfund(bob, 10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)\n\n\t// Bob offers a badly skewed pair: 100k AAA is only worth 400k BBB, so the\n\t// extra BBB is left in his wallet and his shares price off the scarce side.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tbeforeB := tokBBB.BalanceOf(bob)\n\tminted := AddLiquidity(cross(cur), keyAAA, keyBBB, 100_000, 9_000_000)\n\tuassert.Equal(t, int64(100_000), minted)\n\tuassert.Equal(t, int64(400_000), beforeB-tokBBB.BalanceOf(bob), \"only the ratio amount was taken\")\n\n\trA, rB := Reserves(keyAAA, keyBBB)\n\tuassert.Equal(t, int64(1_100_000), rA)\n\tuassert.Equal(t, int64(4_400_000), rB)\n\tuassert.Equal(t, int64(1_100_000), TotalShares(keyAAA, keyBBB))\n\n\t// Round-trip: Bob can never take out more than he put in.\n\tgotA, gotB := RemoveLiquidity(cross(cur), keyAAA, keyBBB, minted)\n\tuassert.True(t, gotA \u003c= 100_000, \"no value created on the A side\")\n\tuassert.True(t, gotB \u003c= 400_000, \"no value created on the B side\")\n}\n\nfunc TestDonationIsInert(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"don-alice\")\n\tmallory := testutils.TestAddress(\"don-mallory\")\n\tfund(alice, 10_000_000)\n\tfund(mallory, 10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000)\n\tbefore := Quote(keyAAA, keyBBB, 10_000)\n\n\t// Mallory sends 5,000,000 AAA straight to the realm address, the classic\n\t// setup for a share-inflation or price-manipulation attack.\n\theldA := tokAAA.BalanceOf(self())\n\tledAAA.Transfer(mallory, self(), 5_000_000)\n\tuassert.Equal(t, heldA+5_000_000, tokAAA.BalanceOf(self()), \"the balance really moved\")\n\n\trA, rB := Reserves(keyAAA, keyBBB)\n\tuassert.Equal(t, int64(1_000_000), rA, \"reserves ignore balances\")\n\tuassert.Equal(t, int64(1_000_000), rB, \"reserves ignore balances\")\n\tuassert.Equal(t, before, Quote(keyAAA, keyBBB, 10_000), \"price is unchanged\")\n\n\t// And a later provider is priced off reserves, not off the donation.\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\tuassert.Equal(t, int64(1_000_000), AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000))\n}\n\n//\n// Guards.\n//\n\nfunc TestGuards(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"guard-alice\")\n\tfund(alice, 10_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsWithMessage(t, cur, \"amm: a pool needs two different tokens\", func() {\n\t\tAddLiquidity(cross(cur), keyAAA, keyAAA, 1, 1)\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"amm: both deposit amounts must be \u003e 0\", func() {\n\t\tAddLiquidity(cross(cur), keyAAA, keyBBB, 0, 1)\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"amm: no such pool: \"+keyAAA+\"~\"+keyBBB, func() {\n\t\tSwap(cross(cur), keyAAA, keyBBB, 1, 0)\n\t})\n\n\tAddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000)\n\n\tuassert.AbortsWithMessage(t, cur, \"amm: slippage, output below minOut\", func() {\n\t\tSwap(cross(cur), keyAAA, keyBBB, 10_000, 10_000)\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"amm: output rounds to zero\", func() {\n\t\tSwap(cross(cur), keyAAA, keyBBB, 1, 0)\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"amm: amountIn must be \u003e 0\", func() {\n\t\tSwap(cross(cur), keyAAA, keyBBB, 0, 0)\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"amm: insufficient shares\", func() {\n\t\tRemoveLiquidity(cross(cur), keyAAA, keyBBB, 2_000_000)\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"amm: reserve cap exceeded\", func() {\n\t\tAddLiquidity(cross(cur), keyAAA, keyBBB, maxReserve, maxReserve)\n\t})\n\n\t// An allowance that does not cover the deposit aborts, and nothing moved.\n\tbob := testutils.TestAddress(\"guard-bob\")\n\tledAAA.Mint(bob, 1_000_000)\n\tledBBB.Mint(bob, 1_000_000)\n\tledAAA.Approve(bob, self(), 10)\n\tledBBB.Approve(bob, self(), 1_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"insufficient allowance\", func() {\n\t\tAddLiquidity(cross(cur), keyAAA, keyBBB, 100_000, 100_000)\n\t})\n\tuassert.Equal(t, int64(1_000_000), tokAAA.BalanceOf(bob), \"nothing moved: the first pull failed\")\n\tuassert.Equal(t, int64(0), SharesOf(keyAAA, keyBBB, bob))\n}\n"},{"name":"gas_test.gno","body":"package amm\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A fixed four-step profile, declared in order so `gno test -v` reports one\n// `--- GAS:` figure per operation. The same four steps exist verbatim in v1,\n// so the difference between the two runs is the cost of the share accounting\n// and nothing else. See moul/gno-contracts#135.\n\nvar (\n\tgasAlice = testutils.TestAddress(\"gas-alice\")\n\tgasBob   = testutils.TestAddress(\"gas-bob\")\n)\n\n// TestGas0Fund keeps the fixture cost (minting and approving both tokens for\n// both actors) out of the four measured numbers.\nfunc TestGas0Fund(t *testing.T) {\n\treset()\n\tfund(gasAlice, 10_000_000)\n\tfund(gasBob, 10_000_000)\n}\n\nfunc TestGas1Seed(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(gasAlice))\n\tuassert.Equal(t, int64(1_000_000), AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000))\n}\n\nfunc TestGas2Swap(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(gasAlice))\n\tuassert.Equal(t, int64(362_644), Swap(cross(cur), keyAAA, keyBBB, 100_000, 1))\n}\n\nfunc TestGas3Join(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(gasBob))\n\tuassert.Equal(t, int64(90_908), AddLiquidity(cross(cur), keyAAA, keyBBB, 100_000, 1_000_000))\n}\n\nfunc TestGas4Exit(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(gasBob))\n\theld := SharesOf(keyAAA, keyBBB, gasBob)\n\tuassert.Equal(t, int64(90_908), held)\n\tRemoveLiquidity(cross(cur), keyAAA, keyBBB, held)\n\tuassert.Equal(t, int64(0), SharesOf(keyAAA, keyBBB, gasBob))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/amm/v0\"\ngno = \"0.9\"\n\n# public: a pool mints its LP token and registers it with r/nt/grc20reg, and\n# holds the *grc20.Token values that registry hands out for the pair's two\n# sides. Both make this realm's own objects reachable from those token realms.\n# As private = true the first CreatePool panics with \"cannot persist object\n# from the private realm gno.land/r/moul/x/amm/v0\" out of assertObjectIsPublic.\n# Measured, not inferred: flip the flag and `make test PKG=amm` fails.\n"},{"name":"lp_test.gno","body":"package amm\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\n// A third token, so a second pool can prove each one mints its own LP token.\nvar (\n\ttokCCC *grc20.Token\n\tledCCC *grc20.PrivateLedger\n\tkeyCCC string\n)\n\nfunc init(cur realm) {\n\ttokCCC, ledCCC = grc20.NewToken(\"Test Gamma\", \"CCC\", 6, 2, cur)\n\tkeyCCC = grc20reg.Register(cross(cur), tokCCC, \"\")\n}\n\n// TestLPPositionIsARealToken is the whole point of v1: the position exists\n// outside this realm, as an ordinary registered GRC20.\nfunc TestLPPositionIsARealToken(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"lp-alice\")\n\tfund(alice, 10_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tminted := AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)\n\n\t// Readable by any realm that knows the key, without importing this one.\n\tlp := grc20reg.MustGet(LPToken(keyAAA, keyBBB))\n\tuassert.Equal(t, minted, lp.BalanceOf(alice))\n\tuassert.Equal(t, minted, lp.TotalSupply())\n\tuassert.Equal(t, minted, TotalShares(keyAAA, keyBBB))\n\t// The LP unit is token A at seed time, so it mirrors token A's decimals.\n\tuassert.Equal(t, tokAAA.GetDecimals(), lp.GetDecimals())\n\tuassert.Equal(t, \"AMM LP AAA/BBB\", lp.GetName())\n}\n\n// TestLPIsTransferable: a position can change hands without touching the pool.\nfunc TestLPIsTransferable(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"xfer-alice\")\n\tbob := testutils.TestAddress(\"xfer-bob\")\n\tfund(alice, 10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)\n\tTransferLP(cross(cur), keyAAA, keyBBB, bob, 500_000)\n\n\tuassert.Equal(t, int64(500_000), SharesOf(keyAAA, keyBBB, alice))\n\tuassert.Equal(t, int64(500_000), SharesOf(keyAAA, keyBBB, bob))\n\n\t// Bob exits on a position he was given, having never deposited anything.\n\t// In v0 this is not expressible at all.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tgotA, gotB := RemoveLiquidity(cross(cur), keyAAA, keyBBB, 500_000)\n\tuassert.Equal(t, int64(500_000), gotA)\n\tuassert.Equal(t, int64(2_000_000), gotB)\n\tuassert.Equal(t, int64(500_000), tokAAA.BalanceOf(bob), \"bob was never funded\")\n}\n\n// TestLPAllowance: the approve/transferFrom surface v1 gains, and the abort\n// when it is spent past its limit.\nfunc TestLPAllowance(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"allow-alice\")\n\tcarol := testutils.TestAddress(\"allow-carol\")\n\tfund(alice, 10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000)\n\tApproveLP(cross(cur), keyAAA, keyBBB, carol, 300_000)\n\tuassert.Equal(t, int64(300_000), AllowanceLP(keyAAA, keyBBB, alice, carol))\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tTransferFromLP(cross(cur), keyAAA, keyBBB, alice, carol, 300_000)\n\tuassert.Equal(t, int64(300_000), SharesOf(keyAAA, keyBBB, carol))\n\tuassert.Equal(t, int64(700_000), SharesOf(keyAAA, keyBBB, alice))\n\tuassert.Equal(t, int64(0), AllowanceLP(keyAAA, keyBBB, alice, carol))\n\n\tuassert.AbortsContains(t, cur, \"insufficient allowance\", func() {\n\t\tTransferFromLP(cross(cur), keyAAA, keyBBB, alice, carol, 1)\n\t})\n}\n\n// TestEachPoolMintsItsOwnLPToken: two pools, two distinct registered tokens.\nfunc TestEachPoolMintsItsOwnLPToken(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"two-alice\")\n\tfund(alice, 10_000_000)\n\tledCCC.Mint(alice, 10_000_000)\n\tledCCC.Approve(alice, self(), 10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)\n\tAddLiquidity(cross(cur), keyAAA, keyCCC, 2_000_000, 2_000_000)\n\n\tab := LPToken(keyAAA, keyBBB)\n\tac := LPToken(keyAAA, keyCCC)\n\tuassert.NotEqual(t, ab, ac, \"one LP token per pool\")\n\tuassert.Equal(t, int64(1_000_000), grc20reg.MustGet(ab).TotalSupply())\n\tuassert.Equal(t, int64(2_000_000), grc20reg.MustGet(ac).TotalSupply())\n\tuassert.Equal(t, \"AMM LP AAA/CCC\", grc20reg.MustGet(ac).GetName())\n\n\t// Moving one pool's LP leaves the other alone.\n\tTransferLP(cross(cur), keyAAA, keyBBB, testutils.TestAddress(\"two-bob\"), 400_000)\n\tuassert.Equal(t, int64(600_000), SharesOf(keyAAA, keyBBB, alice))\n\tuassert.Equal(t, int64(2_000_000), SharesOf(keyAAA, keyCCC, alice))\n}\n"},{"name":"render_example_test.gno","body":"package amm\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// A fixed LP token for the examples, so the rendered symbol does not depend on\n// how many pools the other tests happened to open first.\nvar (\n\texLP    *grc20.Token\n\texLedge *grc20.PrivateLedger\n)\n\nfunc init(cur realm) {\n\texLP, exLedge = grc20.NewToken(\"AMM LP AAA/BBB\", \"LPDEMO\", 6, 9999, cur)\n\texLedge.Mint(testutils.TestAddress(\"lp\"), 1_000_000)\n}\n\n// seedExamplePool installs one deterministic pool so the examples below do not\n// depend on which tests ran before them. The numbers are the worked example\n// from the package docs: a 1,000,000 / 4,000,000 pool after a 100,000 swap.\nfunc seedExamplePool() {\n\tpools = avl.Tree{}\n\tpools.Set(poolID(keyAAA, keyBBB), \u0026pool{\n\t\tkeyA: keyAAA, keyB: keyBBB,\n\t\ttokA: tokAAA, tokB: tokBBB,\n\t\tresA: 1_100_000, resB: 3_637_356,\n\t\tlp: exLP, lpLedger: exLedge,\n\t\tlpKey: \"gno.land/r/moul/x/amm/v0.LPDEMO\",\n\t})\n}\n\n// ExampleRender pins the realm's home page.\nfunc ExampleRender() {\n\tseedExamplePool()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Minimal AMM\n\t//\n\t// Constant product (`x*y=k`) with a 30 bps fee kept by the pool. Every position is a transferable GRC20 LP token. Reserves are stored, never read from balances, so sending tokens here directly does nothing and they cannot be recovered.\n\t//\n\t// | pool | reserves | LP token | supply | holders |\n\t// |---|---|---|---|---|\n\t// | [AAA/BBB](/r/moul/x/amm/v0:gno.land/r/moul/x/amm/v0.AAA~gno.land/r/moul/x/amm/v0.BBB) | 1100000 AAA / 3637356 BBB | LPDEMO | 1000000 | 1 |\n}\n\n// ExampleRender_pool pins a single pool's detail page.\nfunc ExampleRender_pool() {\n\tseedExamplePool()\n\tprint(Render(poolID(keyAAA, keyBBB)))\n\t// Output:\n\t// # AAA / BBB\n\t//\n\t// - **AAA** reserve: 1100000 (`gno.land/r/moul/x/amm/v0.AAA`)\n\t// - **BBB** reserve: 3637356 (`gno.land/r/moul/x/amm/v0.BBB`)\n\t// - **LP token**: `gno.land/r/moul/x/amm/v0.LPDEMO` (LPDEMO)\n\t// - **LP shares**: 1000000 across 1 holder(s)\n}\n\n// ExampleRender_unknown pins the miss.\nfunc ExampleRender_unknown() {\n\tseedExamplePool()\n\tprint(Render(\"nope\"))\n\t// Output:\n\t// # 404\n\t//\n\t// No pool `nope`.\n}\n"}]},"send":"","max_deposit":"19000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"dice","path":"gno.land/r/moul/x/daily/dice/v0","files":[{"name":"README.md","body":"# 🎲 Provably-Fair Dice\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA dice game realm for gno.land where every roll is verifiable. There is no true\nrandomness on-chain, so each roll's 1-6 face is derived **deterministically** from\npublic block entropy (the block height) mixed with the caller's address and their\nrunning roll count. Anyone can recompute a roll from public data and confirm it was\nnever tampered with — that is what \"provably fair\" means here. The realm keeps a\nper-caller roll history and a global distribution across the six faces.\n\n- **Realm path:** `gno.land/r/REPLACE_ADDR/dice`\n- **Network:** sapphire (gno 0.9)\n\n## Example calls\n\n```sh\n# Roll the dice (state-changing crossing call, returns the 1-6 face)\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/dice\" \\\n  -func Roll -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast ...\n\n# Query the current view (distribution chart + recent rolls)\ngnokey query \"vm/qrender\" -data \"gno.land/r/REPLACE_ADDR/dice:\"\n\n# Read one account's roll history (read-only helper)\ngnokey query \"vm/qeval\" \\\n  -data 'gno.land/r/REPLACE_ADDR/dice.RollsOf(\"g1...\")'\n```\n\n`Render(path)` output shows the total rolls, a `▓░` distribution bar chart for\nfaces 1-6 with percentages, and the most recent rolls.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/dice/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dice/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/dice/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dice/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/dice/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dice/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/dice/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dice/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/dice/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/dice/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"dice.gno","body":"// Package dice implements a provably-fair on-chain dice game for gno.land.\n//\n// There is no true randomness on-chain: every node must reach the same result\n// deterministically. Instead, each roll derives its 1-6 face from public block\n// entropy (chain height) mixed with the caller address and the caller's roll\n// count. The derivation is fully reproducible from public data, which is what\n// \"provably fair\" means here — anyone can recompute a roll and verify it.\npackage dice\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// history holds every roll made by a single caller, most recent last.\ntype history struct {\n\trolls []int // each value in [1,6]\n}\n\nvar (\n\t// count[i] is the total number of times face (i+1) has come up globally.\n\tcount [6]int\n\t// total is the total number of rolls across all callers.\n\ttotal int\n\t// players maps caller address string -\u003e *history (deterministic iteration).\n\tplayers = avl.NewTree()\n)\n\n// deriveFace turns public entropy into a face in [1,6]. It is deterministic:\n// the same (height, addr, n) always yields the same face, so any observer can\n// recompute and verify a roll. Uses a simple FNV-1a-style hash over the mixed\n// entropy bytes so different callers at the same height get different faces.\nfunc deriveFace(height int64, addr string, n int) int {\n\tconst (\n\t\toffset = uint64(1469598103934665603)\n\t\tprime  = uint64(1099511628211)\n\t)\n\th := offset\n\tmix := func(v uint64) {\n\t\tfor i := 0; i \u003c 8; i++ {\n\t\t\th ^= v \u0026 0xff\n\t\t\th *= prime\n\t\t\tv \u003e\u003e= 8\n\t\t}\n\t}\n\tmix(uint64(height))\n\tmix(uint64(n))\n\tfor i := 0; i \u003c len(addr); i++ {\n\t\th ^= uint64(addr[i])\n\t\th *= prime\n\t}\n\treturn int(h%6) + 1\n}\n\n// Roll performs one dice roll for the calling account and records it.\n//\n// It is a crossing function (gno 0.9 interrealm convention: `cur realm` first\n// parameter). Callers invoke it as Roll(cross(cur)). The result is derived\n// deterministically from the current block height, the caller address, and the\n// caller's prior roll count — no stored secret, fully verifiable.\nfunc Roll(cur realm) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"dice: spoofed realm value\")\n\t}\n\taddr := cur.Previous().Address().String()\n\n\tvar h *history\n\tif v := players.Get(addr); v != nil {\n\t\th = v.(*history)\n\t} else {\n\t\th = \u0026history{}\n\t\tplayers.Set(addr, h)\n\t}\n\n\tface := deriveFace(runtime.ChainHeight(), addr, len(h.rolls))\n\th.rolls = append(h.rolls, face)\n\tcount[face-1]++\n\ttotal++\n\n\tchain.Emit(\"Roll\", \"player\", addr, \"face\", strconv.Itoa(face))\n\treturn face\n}\n\n// RollsOf returns the recorded roll history for an address (oldest first).\n// Read-only helper, safe to call as a query.\nfunc RollsOf(addr string) []int {\n\tv := players.Get(addr)\n\tif v == nil {\n\t\treturn nil\n\t}\n\tout := v.(*history).rolls\n\tcp := make([]int, len(out))\n\tcopy(cp, out)\n\treturn cp\n}\n\n// Total returns the global roll count.\nfunc Total() int { return total }\n\n// Distribution returns the global per-face counts, faces 1-6.\nfunc Distribution() [6]int { return count }\n\n// bar renders a proportional ▓/░ bar of fixed width for a face's share.\nfunc bar(n, max, width int) string {\n\tif max \u003c= 0 {\n\t\treturn strings.Repeat(\"░\", width)\n\t}\n\tfilled := n * width / max\n\tif filled \u003e width {\n\t\tfilled = width\n\t}\n\treturn strings.Repeat(\"▓\", filled) + strings.Repeat(\"░\", width-filled)\n}\n\n// Render returns the realm's gnoweb Markdown view.\n//\n// Render is NOT a crossing function (no `cur realm` param) — it is a read-only\n// query surface. It shows the total roll count, a distribution bar chart for\n// faces 1-6, and the most recent rolls.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 🎲 Provably-Fair Dice\\n\\n\")\n\tb.WriteString(\"Every roll is derived deterministically from the block height, \")\n\tb.WriteString(\"the caller address, and their roll count — no hidden randomness, \")\n\tb.WriteString(\"fully reproducible from public data.\\n\\n\")\n\n\tb.WriteString(\"**Total rolls:** \" + strconv.Itoa(total) + \"\\n\\n\")\n\n\t// Distribution bar chart.\n\tb.WriteString(\"## Distribution\\n\\n\")\n\tmax := 0\n\tfor _, c := range count {\n\t\tif c \u003e max {\n\t\t\tmax = c\n\t\t}\n\t}\n\tfor face := 1; face \u003c= 6; face++ {\n\t\tc := count[face-1]\n\t\tpct := 0\n\t\tif total \u003e 0 {\n\t\t\tpct = c * 100 / total\n\t\t}\n\t\tb.WriteString(\"`\" + strconv.Itoa(face) + \"` \")\n\t\tb.WriteString(bar(c, max, 20))\n\t\tb.WriteString(\" \" + strconv.Itoa(c))\n\t\tb.WriteString(\" (\" + strconv.Itoa(pct) + \"%)\\n\\n\")\n\t}\n\n\t// Recent rolls: walk players, collect last rolls, show most recent globally.\n\tb.WriteString(\"## Recent rolls\\n\\n\")\n\tif total == 0 {\n\t\tb.WriteString(\"_No rolls yet. Call `Roll` to play._\\n\")\n\t\treturn b.String()\n\t}\n\ttype entry struct {\n\t\taddr string\n\t\tface int\n\t}\n\trecent := []entry{}\n\tplayers.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\th := value.(*history)\n\t\t// take up to the last 3 rolls of each player\n\t\tstart := len(h.rolls) - 3\n\t\tif start \u003c 0 {\n\t\t\tstart = 0\n\t\t}\n\t\tfor _, f := range h.rolls[start:] {\n\t\t\trecent = append(recent, entry{addr: key, face: f})\n\t\t}\n\t\treturn false\n\t})\n\t// show at most the last 10 collected\n\tstart := len(recent) - 10\n\tif start \u003c 0 {\n\t\tstart = 0\n\t}\n\tfor _, e := range recent[start:] {\n\t\tshort := e.addr\n\t\tif len(short) \u003e 12 {\n\t\t\tshort = short[:8] + \"…\" + short[len(short)-4:]\n\t\t}\n\t\tb.WriteString(\"- 🎲 **\" + strconv.Itoa(e.face) + \"** — `\" + short + \"`\\n\")\n\t}\n\treturn b.String()\n}\n"},{"name":"dice_test.gno","body":"package dice\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// resetState clears package globals between tests since realm state is global.\nfunc resetState() {\n\tcount = [6]int{}\n\ttotal = 0\n\tplayers = avl.NewTree()\n}\n\nfunc TestDeriveFaceRange(t *testing.T) {\n\t// Every derived face must land in [1,6] regardless of entropy inputs.\n\tcases := []struct {\n\t\theight int64\n\t\taddr   string\n\t\tn      int\n\t}{\n\t\t{0, \"g1abc\", 0},\n\t\t{1, \"g1abc\", 1},\n\t\t{999999, \"g1xyzxyzxyz\", 42},\n\t\t{-1, \"\", 0},\n\t\t{123456789, \"g1deadbeef\", 7},\n\t}\n\tfor _, c := range cases {\n\t\tf := deriveFace(c.height, c.addr, c.n)\n\t\tif f \u003c 1 || f \u003e 6 {\n\t\t\tt.Errorf(\"deriveFace(%d,%q,%d) = %d, want 1..6\", c.height, c.addr, c.n, f)\n\t\t}\n\t}\n}\n\nfunc TestDeriveFaceDeterministic(t *testing.T) {\n\t// Same inputs -\u003e same output (provably fair / reproducible).\n\ta := deriveFace(100, \"g1caller\", 3)\n\tb := deriveFace(100, \"g1caller\", 3)\n\tif a != b {\n\t\tt.Errorf(\"deriveFace not deterministic: %d != %d\", a, b)\n\t}\n\t// Different roll count generally changes entropy; at least it must not panic\n\t// and must stay in range.\n\tc := deriveFace(100, \"g1caller\", 4)\n\tif c \u003c 1 || c \u003e 6 {\n\t\tt.Errorf(\"deriveFace out of range: %d\", c)\n\t}\n}\n\nfunc TestDeriveFaceVariesByCaller(t *testing.T) {\n\t// Two different addresses at the same height should not be forced equal;\n\t// verify the hash actually mixes the address by finding at least one\n\t// differing pair across a small sweep.\n\tdiff := false\n\tfor i := 0; i \u003c 10; i++ {\n\t\tif deriveFace(50, \"g1alice\", i) != deriveFace(50, \"g1bob\", i) {\n\t\t\tdiff = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !diff {\n\t\tt.Error(\"deriveFace never differs between two distinct callers over 10 rolls\")\n\t}\n}\n\nfunc TestRenderEmpty(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Provably-Fair Dice\") {\n\t\tt.Error(\"Render missing title\")\n\t}\n\tif !strings.Contains(out, \"Total rolls:** 0\") {\n\t\tt.Errorf(\"Render should report 0 total rolls, got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"No rolls yet\") {\n\t\tt.Error(\"Render should show empty-state message\")\n\t}\n}\n\nfunc TestDistributionAccounting(t *testing.T) {\n\tresetState()\n\t// Simulate the state mutations Roll performs, without a realm frame.\n\tfaces := []int{1, 1, 3, 6, 6, 6}\n\tfor _, f := range faces {\n\t\tcount[f-1]++\n\t\ttotal++\n\t}\n\tif total != len(faces) {\n\t\tt.Errorf(\"total = %d, want %d\", total, len(faces))\n\t}\n\td := Distribution()\n\tif d[0] != 2 {\n\t\tt.Errorf(\"face 1 count = %d, want 2\", d[0])\n\t}\n\tif d[5] != 3 {\n\t\tt.Errorf(\"face 6 count = %d, want 3\", d[5])\n\t}\n\tif d[1] != 0 {\n\t\tt.Errorf(\"face 2 count = %d, want 0\", d[1])\n\t}\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Total rolls:** 6\") {\n\t\tt.Errorf(\"Render should report 6 total rolls, got:\\n%s\", out)\n\t}\n}\n\nfunc TestBar(t *testing.T) {\n\tfull := bar(10, 10, 10)\n\tif strings.Count(full, \"▓\") != 10 {\n\t\tt.Errorf(\"full bar want 10 filled, got %q\", full)\n\t}\n\tempty := bar(0, 10, 10)\n\tif strings.Count(empty, \"░\") != 10 {\n\t\tt.Errorf(\"empty bar want 10 unfilled, got %q\", empty)\n\t}\n\thalf := bar(5, 10, 10)\n\tif strings.Count(half, \"▓\") != 5 {\n\t\tt.Errorf(\"half bar want 5 filled, got %q\", half)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/dice/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"erc20","path":"gno.land/r/moul/x/daily/erc20/v0","files":[{"name":"README.md","body":"# MiniToken (ERC-20)\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA minimal fungible-token realm for gno.land (gno 0.9 / sapphire), porting the\nclassic Solidity ERC-20 idea. It keeps package-level state — a balances map, a\ntotal supply, and per-owner allowances — behind gno 0.9 crossing functions that\nauthenticate the caller via `cur.IsCurrent()` + `cur.Previous()`. `Render`\nreturns a Markdown dashboard with the token metadata and a table of holders.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/erc20` (deploy address injected at deploy time).\n\n## Exported API\n\n- `Mint(cur realm, to address, amount uint64)` — create new tokens for `to`.\n- `Transfer(cur realm, to address, amount uint64)` — send tokens from the caller.\n- `Approve(cur realm, spender address, amount uint64)` — grant a spending allowance.\n- `TransferFrom(cur realm, from, to address, amount uint64)` — spend an allowance.\n- `BalanceOf(holder address) uint64` · `Allowance(owner, spender address) uint64`\n- `TotalSupply() uint64` · `Name() string` · `Symbol() string`\n- `Render(path string) string` — Markdown view for gnoweb.\n\n## Example calls\n\n```sh\n# Mint 1000 MINI to yourself\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/erc20\" \\\n  -func Mint -args \"\u003cyour-addr\u003e\" -args 1000 \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n\n# Transfer 250 MINI to another account\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/erc20\" \\\n  -func Transfer -args \"\u003crecipient-addr\u003e\" -args 250 \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n```\n\nView the token dashboard at `https://gno.land/r/REPLACE_ADDR/erc20` on gnoweb.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/erc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc20/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/erc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc20/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/erc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc20/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/erc20/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc20/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"erc20.gno","body":"// Package erc20 implements MiniToken, a minimal fungible token modeled on the\n// Solidity ERC-20 idea, ported to gno.land (gno 0.9 / sapphire).\n//\n// State is package-level and persistent. All state-mutating exported functions\n// are crossing functions (they take `cur realm` as the first parameter) per the\n// gno 0.9 interrealm convention, and identify the caller via\n// cur.Previous().Address() after checking cur.IsCurrent().\npackage erc20\n\nimport (\n\t\"errors\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tname   = \"MiniToken\"\n\tsymbol = \"MINI\"\n)\n\nvar (\n\t// balances maps holder address -\u003e token balance.\n\tbalances = map[address]uint64{}\n\t// allowances[owner][spender] = amount the spender may pull from owner.\n\tallowances = map[address]map[address]uint64{}\n\t// totalSupply is the sum of all balances.\n\ttotalSupply uint64\n)\n\nvar (\n\terrZeroAddress  = errors.New(\"erc20: zero address\")\n\terrInsufficient = errors.New(\"erc20: insufficient balance\")\n\terrAllowanceLow = errors.New(\"erc20: insufficient allowance\")\n\terrOverflow     = errors.New(\"erc20: supply overflow\")\n\terrSpoofedRealm = errors.New(\"erc20: spoofed realm\")\n\terrNotUser      = errors.New(\"erc20: caller is not a user account\")\n)\n\n// caller returns the immediate caller's address for a crossing function.\n// It enforces the gno 0.9 authentication primitive: cur must be the live\n// crossing frame before its Previous() is trusted.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(errSpoofedRealm)\n\t}\n\tprev := cur.Previous()\n\tif !prev.IsUser() {\n\t\tpanic(errNotUser)\n\t}\n\treturn prev.Address()\n}\n\n// Mint creates `amount` new tokens and credits them to `to`, increasing the\n// total supply. Crossing function.\nfunc Mint(cur realm, to address, amount uint64) {\n\t_ = caller(cur) // authenticate the crossing frame; anyone may mint in this demo\n\tif !to.IsValid() {\n\t\tpanic(errZeroAddress)\n\t}\n\tif amount == 0 {\n\t\treturn\n\t}\n\tif totalSupply+amount \u003c totalSupply {\n\t\tpanic(errOverflow)\n\t}\n\ttotalSupply += amount\n\tbalances[to] += amount\n}\n\n// Transfer moves `amount` tokens from the caller to `to`. Crossing function.\nfunc Transfer(cur realm, to address, amount uint64) {\n\tfrom := caller(cur)\n\tif !to.IsValid() {\n\t\tpanic(errZeroAddress)\n\t}\n\tif err := transfer(from, to, amount); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Approve authorizes `spender` to pull up to `amount` tokens from the caller.\n// Crossing function.\nfunc Approve(cur realm, spender address, amount uint64) {\n\towner := caller(cur)\n\tif !spender.IsValid() {\n\t\tpanic(errZeroAddress)\n\t}\n\tm := allowances[owner]\n\tif m == nil {\n\t\tm = map[address]uint64{}\n\t\tallowances[owner] = m\n\t}\n\tm[spender] = amount\n}\n\n// TransferFrom moves `amount` tokens from `from` to `to`, spending the caller's\n// allowance granted by `from`. Crossing function.\nfunc TransferFrom(cur realm, from, to address, amount uint64) {\n\tspender := caller(cur)\n\tif !from.IsValid() || !to.IsValid() {\n\t\tpanic(errZeroAddress)\n\t}\n\tallowed := allowances[from][spender]\n\tif allowed \u003c amount {\n\t\tpanic(errAllowanceLow)\n\t}\n\tif err := transfer(from, to, amount); err != nil {\n\t\tpanic(err)\n\t}\n\tallowances[from][spender] = allowed - amount\n}\n\n// transfer is the internal, non-crossing balance mover. Pure logic on package\n// state; returns an error rather than panicking so callers control reverts.\nfunc transfer(from, to address, amount uint64) error {\n\tif amount == 0 {\n\t\treturn nil\n\t}\n\tif balances[from] \u003c amount {\n\t\treturn errInsufficient\n\t}\n\tbalances[from] -= amount\n\tbalances[to] += amount\n\treturn nil\n}\n\n// BalanceOf returns the token balance of `holder`. Read-only, non-crossing.\nfunc BalanceOf(holder address) uint64 {\n\treturn balances[holder]\n}\n\n// Allowance returns how much `spender` may still pull from `owner`.\nfunc Allowance(owner, spender address) uint64 {\n\treturn allowances[owner][spender]\n}\n\n// TotalSupply returns the total number of tokens in existence.\nfunc TotalSupply() uint64 {\n\treturn totalSupply\n}\n\n// Name returns the token name.\nfunc Name() string { return name }\n\n// Symbol returns the token symbol.\nfunc Symbol() string { return symbol }\n\n// Render produces the gnoweb Markdown view of the token: metadata plus a\n// deterministically-ordered table of non-zero balances. Render is NOT a\n// crossing function (no `cur realm` parameter).\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# \" + name + \" (\" + symbol + \")\\n\\n\")\n\tb.WriteString(\"A minimal ERC-20-style fungible token on gno.land.\\n\\n\")\n\tb.WriteString(\"- **Name:** \" + name + \"\\n\")\n\tb.WriteString(\"- **Symbol:** \" + symbol + \"\\n\")\n\tb.WriteString(\"- **Total supply:** \" + strconv.FormatUint(totalSupply, 10) + \"\\n\\n\")\n\n\t// Collect and sort holder addresses for deterministic output. Map iteration\n\t// order is not a stable contract, so we sort the string keys (gno's sort\n\t// package has no generic Slice; Strings is the deterministic primitive).\n\tkeys := make([]string, 0, len(balances))\n\tbyKey := make(map[string]uint64, len(balances))\n\tfor addr, bal := range balances {\n\t\tif bal == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ts := addr.String()\n\t\tkeys = append(keys, s)\n\t\tbyKey[s] = bal\n\t}\n\tsort.Strings(keys)\n\n\tb.WriteString(\"## Balances\\n\\n\")\n\tif len(keys) == 0 {\n\t\tb.WriteString(\"_No holders yet — call `Mint` to create tokens._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| Address | Amount |\\n\")\n\tb.WriteString(\"| --- | ---: |\\n\")\n\tfor _, k := range keys {\n\t\tb.WriteString(\"| `\" + k + \"` | \" +\n\t\t\tstrconv.FormatUint(byKey[k], 10) + \" |\\n\")\n\t}\n\n\treturn b.String()\n}\n"},{"name":"erc20_test.gno","body":"package erc20\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Fixed test addresses. testutils.TestAddress derives real, valid-length\n// addresses; literal strings would fail address.IsValid() and trip the realm's\n// zero-address guard.\nvar (\n\talice   = testutils.TestAddress(\"alice\")\n\tbob     = testutils.TestAddress(\"bob\")\n\tspender = testutils.TestAddress(\"spender\")\n\tdest    = testutils.TestAddress(\"dest\")\n)\n\n// reset clears package state between tests so cases stay independent.\nfunc reset() {\n\tbalances = map[address]uint64{}\n\tallowances = map[address]map[address]uint64{}\n\ttotalSupply = 0\n}\n\n// TestMintAndTransfer mints to alice, then transfers alice -\u003e bob.\nfunc TestMintAndTransfer(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMint(cross(cur), alice, 1000)\n\n\tif got := TotalSupply(); got != 1000 {\n\t\tt.Fatalf(\"total supply = %d, want 1000\", got)\n\t}\n\tif got := BalanceOf(alice); got != 1000 {\n\t\tt.Fatalf(\"alice balance = %d, want 1000\", got)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), bob, 400)\n\n\tif got := BalanceOf(alice); got != 600 {\n\t\tt.Errorf(\"alice balance = %d, want 600\", got)\n\t}\n\tif got := BalanceOf(bob); got != 400 {\n\t\tt.Errorf(\"bob balance = %d, want 400\", got)\n\t}\n\tif got := TotalSupply(); got != 1000 {\n\t\tt.Errorf(\"total supply changed on transfer: %d, want 1000\", got)\n\t}\n}\n\n// TestApproveAndTransferFrom exercises the allowance path.\nfunc TestApproveAndTransferFrom(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMint(cross(cur), alice, 500)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tApprove(cross(cur), spender, 300)\n\tif got := Allowance(alice, spender); got != 300 {\n\t\tt.Fatalf(\"allowance = %d, want 300\", got)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(spender))\n\tTransferFrom(cross(cur), alice, dest, 200)\n\n\tif got := BalanceOf(alice); got != 300 {\n\t\tt.Errorf(\"owner balance = %d, want 300\", got)\n\t}\n\tif got := BalanceOf(dest); got != 200 {\n\t\tt.Errorf(\"dest balance = %d, want 200\", got)\n\t}\n\tif got := Allowance(alice, spender); got != 100 {\n\t\tt.Errorf(\"remaining allowance = %d, want 100\", got)\n\t}\n}\n\n// TestTransferInsufficientPanics asserts an over-transfer reverts.\nfunc TestTransferInsufficientPanics(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMint(cross(cur), alice, 10)\n\n\t// Aborts from a cross(cur) call cannot be caught by a plain recover();\n\t// assert on the abort message instead.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"erc20: insufficient balance\", func() {\n\t\tTransfer(cross(cur), bob, 100) // more than balance -\u003e panic\n\t})\n}\n\n// TestRenderContainsMetadata checks the Markdown view exposes name/symbol/supply.\nfunc TestRenderContainsMetadata(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMint(cross(cur), alice, 42)\n\n\tout := Render(\"\")\n\tfor _, want := range []string{\"MiniToken\", \"MINI\", \"Total supply\", \"42\"} {\n\t\tif !strings.Contains(out, want) {\n\t\t\tt.Errorf(\"render output missing %q\\n%s\", want, out)\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/erc20/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lottery","path":"gno.land/r/moul/x/daily/lottery/v0","files":[{"name":"README.md","body":"# Lottery\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nAn idiomatic gno.land port of the classic Solidity **Lottery** contract.\n\nPlayers `Enter` the current round (one entry per address per round — a second\nentry panics). Once a round has at least two entrants, anyone may `DrawWinner`,\nwhich picks a winner deterministically from the block height\n(`ChainHeight() % len(entrants)` over the deterministically-sorted entrant set),\nrecords it in the winners history, and opens a fresh round. Solidity's\n`block.number`-based pseudo-randomness maps to `runtime.ChainHeight()`, and\n`msg.sender` maps to `unsafe.PreviousRealm().Address()`. `Render` shows the open\nround, its entrants, and the table of past winners.\n\n## Example calls\n\n```\n# Two different accounts join round 1\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/lottery/v0 -func Enter ...   # from alice\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/lottery/v0 -func Enter ...   # from bob\n\n# Anyone draws the winner and opens round 2\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/lottery/v0 -func DrawWinner ...\n```\n\nRead-only helpers: `CurrentRound()`, `NumEntrants()`, `HasEntered(addr)`.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/lottery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lottery/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/lottery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lottery/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/lottery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lottery/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/lottery/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lottery/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/lottery/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/lottery/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/lottery/v0\"\ngno = \"0.9\"\n"},{"name":"lottery.gno","body":"// Package lottery is an idiomatic gno.land port of the classic Solidity\n// Lottery contract. Players Enter the current round (one entry per address per\n// round). Once a round has at least two entrants, anyone may DrawWinner: a\n// winner is picked deterministically from the block height (ChainHeight() %\n// len(entrants), over the deterministically-sorted entrant set), recorded in\n// the winners history, and a fresh round is opened.\n//\n// There is no real randomness on-chain, so \"random\" selection is derived from\n// the block height — the same source Solidity ports use via block.number.\npackage lottery\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// round is the current (open) round number, 1-based.\nvar round int = 1\n\n// entrants holds the current round's players: key = address string, value =\n// the address. Iteration is deterministic (sorted by key), which makes winner\n// selection reproducible.\nvar entrants avl.Tree\n\n// winners records past rounds: key = zero-padded round number (for ordered\n// iteration), value = *winnerRecord.\nvar winners avl.Tree\n\ntype winnerRecord struct {\n\tRound       int\n\tWinner      address\n\tNumEntrants int\n\tHeight      int64\n}\n\n// winnerKey zero-pads the round number so avl iteration yields chronological\n// order for up to 10^9 rounds.\nfunc winnerKey(r int) string {\n\ts := strconv.Itoa(r)\n\tfor len(s) \u003c 9 {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n\n// pickIndex derives the winning entrant index from the block height. Panics if\n// there are no entrants. Pure helper (deterministic, no state) — safe to test.\nfunc pickIndex(height int64, n int) int {\n\tif n \u003c= 0 {\n\t\tpanic(\"lottery: no entrants to draw from\")\n\t}\n\ti := height % int64(n)\n\tif i \u003c 0 {\n\t\ti += int64(n)\n\t}\n\treturn int(i)\n}\n\n// Enter adds the caller to the current round's entrants. Each address may only\n// enter a given round once; a duplicate entry panics.\nfunc Enter(cur realm) {\n\tplayer := unsafe.PreviousRealm().Address()\n\tkey := player.String()\n\tif entrants.Has(key) {\n\t\tpanic(\"lottery: already entered this round\")\n\t}\n\tentrants.Set(key, player)\n\n\tchain.Emit(\"Enter\",\n\t\t\"round\", strconv.Itoa(round),\n\t\t\"player\", key,\n\t\t\"entrants\", strconv.Itoa(entrants.Size()),\n\t)\n}\n\n// DrawWinner closes the current round, provided it has at least two entrants,\n// picks the winner deterministically from the block height, records it, and\n// opens a new empty round.\nfunc DrawWinner(cur realm) address {\n\tn := entrants.Size()\n\tif n \u003c 2 {\n\t\tpanic(\"lottery: need at least 2 entrants to draw\")\n\t}\n\n\theight := runtime.ChainHeight()\n\tidx := pickIndex(height, n)\n\n\tvar winner address\n\ti := 0\n\tentrants.Iterate(\"\", \"\", func(_ string, value interface{}) bool {\n\t\tif i == idx {\n\t\t\twinner = value.(address)\n\t\t\treturn true // stop\n\t\t}\n\t\ti++\n\t\treturn false\n\t})\n\n\trec := \u0026winnerRecord{\n\t\tRound:       round,\n\t\tWinner:      winner,\n\t\tNumEntrants: n,\n\t\tHeight:      height,\n\t}\n\twinners.Set(winnerKey(round), rec)\n\n\tchain.Emit(\"DrawWinner\",\n\t\t\"round\", strconv.Itoa(round),\n\t\t\"winner\", winner.String(),\n\t\t\"entrants\", strconv.Itoa(n),\n\t\t\"height\", strconv.FormatInt(height, 10),\n\t)\n\n\t// Open a fresh round.\n\tround++\n\tentrants = avl.Tree{}\n\n\treturn winner\n}\n\n// CurrentRound returns the currently open round number.\nfunc CurrentRound() int {\n\treturn round\n}\n\n// NumEntrants returns how many players have entered the current round.\nfunc NumEntrants() int {\n\treturn entrants.Size()\n}\n\n// HasEntered reports whether addr is in the current round.\nfunc HasEntered(addr address) bool {\n\treturn entrants.Has(addr.String())\n}\n\n// Render shows the current round, its entrants, and the winners history.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Lottery\\n\\n\")\n\tb.WriteString(\"Enter the open round, then anyone can draw once it has \")\n\tb.WriteString(\"at least two players. The winner is picked from the block \")\n\tb.WriteString(\"height and a new round opens automatically.\\n\\n\")\n\n\tb.WriteString(\"## Round \" + strconv.Itoa(round) + \" (open)\\n\\n\")\n\tif entrants.Size() == 0 {\n\t\tb.WriteString(\"_No entrants yet. Call `Enter` to join._\\n\\n\")\n\t} else {\n\t\tb.WriteString(strconv.Itoa(entrants.Size()) + \" entrant(s):\\n\\n\")\n\t\tentrants.Iterate(\"\", \"\", func(key string, _ interface{}) bool {\n\t\t\tb.WriteString(\"- `\" + key + \"`\\n\")\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\")\n\t\tif entrants.Size() \u003c 2 {\n\t\t\tb.WriteString(\"_Need at least 2 entrants before a draw._\\n\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"_Ready to draw: call `DrawWinner`._\\n\\n\")\n\t\t}\n\t}\n\n\tb.WriteString(\"## Past winners\\n\\n\")\n\tif winners.Size() == 0 {\n\t\tb.WriteString(\"_No rounds drawn yet._\\n\")\n\t} else {\n\t\tb.WriteString(\"| Round | Winner | Entrants | Block Height |\\n\")\n\t\tb.WriteString(\"|---|---|---|---|\\n\")\n\t\twinners.Iterate(\"\", \"\", func(_ string, value interface{}) bool {\n\t\t\tr := value.(*winnerRecord)\n\t\t\tb.WriteString(\"| \" + strconv.Itoa(r.Round) +\n\t\t\t\t\" | `\" + r.Winner.String() + \"`\" +\n\t\t\t\t\" | \" + strconv.Itoa(r.NumEntrants) +\n\t\t\t\t\" | \" + strconv.FormatInt(r.Height, 10) + \" |\\n\")\n\t\t\treturn false\n\t\t})\n\t}\n\n\treturn b.String()\n}\n"},{"name":"lottery_test.gno","body":"package lottery\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPickIndex(t *testing.T) {\n\tcases := []struct {\n\t\theight int64\n\t\tn      int\n\t\twant   int\n\t}{\n\t\t{0, 3, 0},\n\t\t{1, 3, 1},\n\t\t{2, 3, 2},\n\t\t{3, 3, 0},\n\t\t{10, 4, 2},\n\t\t{100, 7, 2},\n\t\t{5, 1, 0},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := pickIndex(tc.height, tc.n)\n\t\tuassert.Equal(t, tc.want, got)\n\t\tif got \u003c 0 || got \u003e= tc.n {\n\t\t\tt.Errorf(\"index %d out of range for n=%d\", got, tc.n)\n\t\t}\n\t}\n}\n\nfunc TestWinnerKey(t *testing.T) {\n\tcases := []struct {\n\t\tround int\n\t\twant  string\n\t}{\n\t\t{1, \"000000001\"},\n\t\t{42, \"000000042\"},\n\t\t{1000, \"000001000\"},\n\t\t{123456789, \"123456789\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, winnerKey(tc.round))\n\t}\n\t// Zero-padding must preserve chronological ordering under string compare.\n\tuassert.True(t, winnerKey(2) \u003e winnerKey(1))\n\tuassert.True(t, winnerKey(10) \u003e winnerKey(9))\n\tuassert.True(t, winnerKey(100) \u003e winnerKey(99))\n}\n"},{"name":"render_example_test.gno","body":"package lottery\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Lottery\n\t//\n\t// Enter the open round, then anyone can draw once it has at least two players. The winner is picked from the block height and a new round opens automatically.\n\t//\n\t// ## Round 1 (open)\n\t//\n\t// _No entrants yet. Call `Enter` to join._\n\t//\n\t// ## Past winners\n\t//\n\t// _No rounds drawn yet._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ratelimitdemo","path":"gno.land/r/moul/x/daily/ratelimitdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/ratelimitdemo/v0`\n\nLive demo of the [`p/moul/x/daily/ratelimit`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/ratelimit)\ntoken-bucket rate limiter.\n\nHolds one package-level `ratelimit.Limiter` (0.5 tokens/block, capacity 5) and\nwires it to the chain — the tick is `runtime.ChainHeight()`, each caller is keyed\nby `unsafe.PreviousRealm().Address()`:\n\n- `Allow(cur) bool` — consume one token for the caller.\n- `SetConfig(cur, rate, burst)` — retune the shared bucket.\n- `Tokens(addr) int` — read-only balance.\n- `Render(\"/\")` — config + a table of callers; `Render(\"/addr/\u003caddress\u003e\")` focuses one.\n\nAll refill/consume math lives in the library; this realm is just the wiring and\nthe gnoweb view. Render it at [`/r/moul/x/daily/ratelimitdemo/v0`](https://gno.land/r/moul/x/daily/ratelimitdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/ratelimitdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ratelimitdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/ratelimitdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ratelimitdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/ratelimitdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ratelimitdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/ratelimitdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ratelimitdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/ratelimitdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/ratelimitdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/ratelimitdemo/v0\"\ngno = \"0.9\"\n"},{"name":"ratelimitdemo.gno","body":"// Package ratelimitdemo is a small on-chain demo of the token-bucket rate\n// limiter provided by the [p/moul/x/daily/ratelimit](/p/moul/x/daily/ratelimit/v0)\n// library.\n//\n// It holds a single package-level [ratelimit.Limiter] and wires it to the\n// chain: the tick is runtime.ChainHeight() and each caller is keyed by its\n// address (unsafe.PreviousRealm().Address()). It contains no limiter logic of\n// its own — refill/consume math all lives in the library.\npackage ratelimitdemo\n\nimport (\n\t\"strconv\"\n\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/x/daily/ratelimit/v0\"\n)\n\n// limiter starts at 0.5 tokens/block (one every two blocks), capacity 5.\nvar limiter = ratelimit.New(0.5, 5.0)\n\n// Allow consumes one token for the calling realm/user at the current block\n// height and reports whether the request is permitted. Returns false (and\n// consumes nothing) when the caller's bucket is empty.\nfunc Allow(cur realm) bool {\n\taddr := unsafe.PreviousRealm().Address()\n\treturn limiter.Allow(string(addr), runtime.ChainHeight())\n}\n\n// SetConfig updates the shared rate (tokens per block) and burst (capacity).\n// rate is clamped to \u003e= 0, burst to \u003e= 1.\nfunc SetConfig(cur realm, rate, burst float64) {\n\tlimiter.SetConfig(rate, burst)\n}\n\n// Tokens reports how many whole tokens `addr` has available at the current\n// block height, without mutating any state.\nfunc Tokens(addr address) int {\n\treturn limiter.Tokens(string(addr), runtime.ChainHeight())\n}\n\n// --- rendering --------------------------------------------------------------\n\nfunc ftoa(f float64) string { return strconv.FormatFloat(f, 'g', -1, 64) }\n\n// Render shows the limiter config and a table of known callers with their\n// current tokens and last-seen height. Path \"/addr/\u003caddress\u003e\" focuses one\n// caller.\nfunc Render(path string) string {\n\tnow := runtime.ChainHeight()\n\trate, burst := limiter.Config()\n\n\tif len(path) \u003e 6 \u0026\u0026 path[:6] == \"/addr/\" {\n\t\tkey := path[6:]\n\t\tout := \"# Rate Limiter — caller\\n\\n\"\n\t\tout += \"Address: `\" + key + \"`\\n\\n\"\n\t\tout += \"- Current tokens: **\" + strconv.Itoa(limiter.Tokens(key, now)) + \"** / \" + ftoa(burst) + \"\\n\"\n\t\tout += \"- Now (height): \" + strconv.FormatInt(now, 10) + \"\\n\"\n\t\treturn out\n\t}\n\n\tout := \"# Rate Limiter\\n\\n\"\n\tout += \"Demo of the [`p/moul/x/daily/ratelimit`](/p/moul/x/daily/ratelimit/v0) library — \"\n\tout += \"an on-chain token-bucket limiter (port of `golang.org/x/time/rate`).\\n\\n\"\n\tout += \"## Config\\n\\n\"\n\tout += \"| Parameter | Value |\\n|---|---|\\n\"\n\tout += \"| Rate (tokens/block) | \" + ftoa(rate) + \" |\\n\"\n\tout += \"| Burst (capacity) | \" + ftoa(burst) + \" |\\n\"\n\tout += \"| Clock height | \" + strconv.FormatInt(now, 10) + \" |\\n\\n\"\n\n\tout += \"## Callers\\n\\n\"\n\tif limiter.Len() == 0 {\n\t\tout += \"_No caller has hit the limiter yet._\\n\\n\"\n\t} else {\n\t\tout += \"| Address | Tokens | Last height |\\n|---|---|---|\\n\"\n\t\tlimiter.Iterate(now, func(key string, tokens int, last int64) bool {\n\t\t\tout += \"| `\" + key + \"` | \" + strconv.Itoa(tokens) +\n\t\t\t\t\" | \" + strconv.FormatInt(last, 10) + \" |\\n\"\n\t\t\treturn false\n\t\t})\n\t\tout += \"\\n\"\n\t}\n\n\tout += \"---\\n\"\n\tout += \"Call `Allow(cur)` to consume a token; read `Tokens(addr)` for a caller's balance.\\n\"\n\treturn out\n}\n"},{"name":"render_example_test.gno","body":"package ratelimitdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Rate Limiter\n\t//\n\t// Demo of the [`p/moul/x/daily/ratelimit`](/p/moul/x/daily/ratelimit/v0) library — an on-chain token-bucket limiter (port of `golang.org/x/time/rate`).\n\t//\n\t// ## Config\n\t//\n\t// | Parameter | Value |\n\t// |---|---|\n\t// | Rate (tokens/block) | 0.5 |\n\t// | Burst (capacity) | 5 |\n\t// | Clock height | 123 |\n\t//\n\t// ## Callers\n\t//\n\t// _No caller has hit the limiter yet._\n\t//\n\t// ---\n\t// Call `Allow(cur)` to consume a token; read `Tokens(addr)` for a caller's balance.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"staking","path":"gno.land/r/moul/x/daily/staking/v0","files":[{"name":"README.md","body":"# staking\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nA simplified, accounting-only port of Synthetix **StakingRewards** to a gno.land realm.\n\nIt reproduces the classic \"reward-per-token\" accumulator: stakers add or remove a\nfungible `uint64` amount, and rewards accrue on every block proportional to each\nstaker's share of the total staked, at a fixed `rewardPerBlock`. Instead of real\ncoin transfers, staked amounts and rewards are tracked as plain `uint64` balances,\nand `runtime.ChainHeight()` is used as the deterministic clock. A global accumulator\nplus per-account snapshots make accrual O(1) per interaction — no loop over stakers.\n\n## Transactions\n\n- `Stake(amount)` — add `amount` to your staked balance.\n- `Withdraw(amount)` — remove `amount` from your staked balance.\n- `GetReward()` — mint your accrued rewards into your reward balance; returns the amount.\n\n## Read-only\n\n- `Earned(addr)` — rewards currently owed to `addr`, projected to the current block.\n- `StakedOf(addr)` — current staked balance of `addr`.\n- `Render(path)` — Markdown: total staked, reward rate, block height, and a stakers table.\n\n## Example\n\n```go\nstaking.Stake(cross, 100)   // stake 100 units\n// ... blocks pass, rewards accrue ...\nstaking.Earned(myAddr)      // check pending rewards\nstaking.GetReward(cross)    // claim into reward balance\nstaking.Withdraw(cross, 40) // unstake 40\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/staking/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/staking/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/staking/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/staking/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/staking/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/staking/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/staking/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/staking/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/staking/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/staking/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/staking/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package staking\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Staking Rewards\n\t//\n\t// Simplified Synthetix-style staking (accounting-only, no coin transfer).\n\t//\n\t// - **Total staked:** 0\n\t// - **Reward rate:** 100 / block (split across stakers)\n\t// - **Block height:** 123\n\t//\n\t// _No stakers yet. Call `Stake(amount)` to join._\n}\n"},{"name":"staking.gno","body":"// Package staking is a simplified, accounting-only port of Synthetix\n// StakingRewards to gno.land. Users stake a fungible amount; rewards accrue\n// every block, proportional to each staker's share of the total staked,\n// at a fixed rewardPerBlock. There is no real coin transfer — balances and\n// rewards are plain uint64 accounting (a demonstration of the classic\n// \"reward-per-token\" accumulator pattern).\npackage staking\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst (\n\t// rewardPerBlock is the fixed number of reward units distributed across\n\t// ALL stakers on every block, split by stake share.\n\trewardPerBlock = uint64(100)\n\t// precision scales the reward-per-token accumulator to avoid truncation.\n\tprecision = uint64(1_000_000)\n)\n\ntype account struct {\n\tstaked     uint64 // currently staked amount\n\trewardPaid uint64 // reward-per-token snapshot at the account's last update\n\treward     uint64 // accrued-but-unclaimed rewards\n\tminted     uint64 // rewards moved into the caller's reward balance\n}\n\nvar (\n\taccounts          avl.Tree // address string -\u003e *account\n\ttotalStaked       uint64\n\trewardPerTokenAcc uint64 // global accumulator, scaled by precision\n\tlastUpdateBlock   uint64\n)\n\n// --- pure helpers (unit-tested) ------------------------------------------\n\n// computeRewardPerToken advances the accumulator by the rewards earned per\n// staked unit over `elapsed` blocks. With no stake, the accumulator is frozen.\nfunc computeRewardPerToken(stored, rate, elapsed, total uint64) uint64 {\n\tif total == 0 {\n\t\treturn stored\n\t}\n\treturn stored + (rate*elapsed*precision)/total\n}\n\n// computeEarned returns total rewards owed to an account given its stake, the\n// current accumulator, the accumulator value already paid, and prior accrual.\nfunc computeEarned(balance, rptCurrent, rptPaid, accrued uint64) uint64 {\n\treturn accrued + (balance*(rptCurrent-rptPaid))/precision\n}\n\n// --- internals ------------------------------------------------------------\n\nfunc currentBlock() uint64 { return uint64(runtime.ChainHeight()) }\n\nfunc getOrCreate(addr string) *account {\n\tif v := accounts.Get(addr); v != nil {\n\t\treturn v.(*account)\n\t}\n\tacc := \u0026account{}\n\taccounts.Set(addr, acc)\n\treturn acc\n}\n\n// accrue rolls the global accumulator forward to the current block and folds\n// the caller's freshly-earned rewards into its stored balance. Mirrors the\n// Synthetix `updateReward(account)` modifier.\nfunc accrue(addr string) *account {\n\telapsed := currentBlock() - lastUpdateBlock\n\trewardPerTokenAcc = computeRewardPerToken(rewardPerTokenAcc, rewardPerBlock, elapsed, totalStaked)\n\tlastUpdateBlock = currentBlock()\n\n\tacc := getOrCreate(addr)\n\tacc.reward = computeEarned(acc.staked, rewardPerTokenAcc, acc.rewardPaid, acc.reward)\n\tacc.rewardPaid = rewardPerTokenAcc\n\treturn acc\n}\n\n// --- exported transactions (crossing) ------------------------------------\n\n// Stake adds `amount` to the caller's staked balance.\nfunc Stake(cur realm, amount uint64) {\n\tif amount == 0 {\n\t\tpanic(\"staking: amount must be \u003e 0\")\n\t}\n\taddr := unsafe.PreviousRealm().Address().String()\n\tacc := accrue(addr)\n\tacc.staked += amount\n\ttotalStaked += amount\n\tchain.Emit(\"Staked\", \"addr\", addr, \"amount\", strconv.FormatUint(amount, 10))\n}\n\n// Withdraw removes `amount` from the caller's staked balance.\nfunc Withdraw(cur realm, amount uint64) {\n\tif amount == 0 {\n\t\tpanic(\"staking: amount must be \u003e 0\")\n\t}\n\taddr := unsafe.PreviousRealm().Address().String()\n\tacc := accrue(addr)\n\tif amount \u003e acc.staked {\n\t\tpanic(\"staking: insufficient staked balance\")\n\t}\n\tacc.staked -= amount\n\ttotalStaked -= amount\n\tchain.Emit(\"Withdrawn\", \"addr\", addr, \"amount\", strconv.FormatUint(amount, 10))\n}\n\n// GetReward mints all accrued rewards into the caller's reward balance and\n// resets the accrual counter. Returns the amount minted this call.\nfunc GetReward(cur realm) uint64 {\n\taddr := unsafe.PreviousRealm().Address().String()\n\tacc := accrue(addr)\n\tclaimed := acc.reward\n\tacc.reward = 0\n\tacc.minted += claimed\n\tchain.Emit(\"RewardPaid\", \"addr\", addr, \"amount\", strconv.FormatUint(claimed, 10))\n\treturn claimed\n}\n\n// --- read-only ------------------------------------------------------------\n\n// Earned reports the rewards currently owed to `addr` (accrued but unminted),\n// projected to the current block without mutating any state.\nfunc Earned(addr address) uint64 {\n\tv := accounts.Get(addr.String())\n\tif v == nil {\n\t\treturn 0\n\t}\n\tacc := v.(*account)\n\telapsed := currentBlock() - lastUpdateBlock\n\trpt := computeRewardPerToken(rewardPerTokenAcc, rewardPerBlock, elapsed, totalStaked)\n\treturn computeEarned(acc.staked, rpt, acc.rewardPaid, acc.reward)\n}\n\n// StakedOf reports the current staked balance of `addr`.\nfunc StakedOf(addr address) uint64 {\n\tif v := accounts.Get(addr.String()); v != nil {\n\t\treturn v.(*account).staked\n\t}\n\treturn 0\n}\n\n// Render renders pool stats and a stakers table.\nfunc Render(path string) string {\n\tout := \"# Staking Rewards\\n\\n\"\n\tout += \"Simplified Synthetix-style staking (accounting-only, no coin transfer).\\n\\n\"\n\tout += \"- **Total staked:** \" + strconv.FormatUint(totalStaked, 10) + \"\\n\"\n\tout += \"- **Reward rate:** \" + strconv.FormatUint(rewardPerBlock, 10) + \" / block (split across stakers)\\n\"\n\tout += \"- **Block height:** \" + strconv.FormatUint(currentBlock(), 10) + \"\\n\\n\"\n\n\tif accounts.Size() == 0 {\n\t\tout += \"_No stakers yet. Call `Stake(amount)` to join._\\n\"\n\t\treturn out\n\t}\n\n\tout += \"## Stakers\\n\\n\"\n\tout += \"| Address | Staked | Earned (pending) | Minted |\\n\"\n\tout += \"|---|---|---|---|\\n\"\n\n\telapsed := currentBlock() - lastUpdateBlock\n\trpt := computeRewardPerToken(rewardPerTokenAcc, rewardPerBlock, elapsed, totalStaked)\n\taccounts.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tacc := value.(*account)\n\t\tearned := computeEarned(acc.staked, rpt, acc.rewardPaid, acc.reward)\n\t\tout += \"| \" + key +\n\t\t\t\" | \" + strconv.FormatUint(acc.staked, 10) +\n\t\t\t\" | \" + strconv.FormatUint(earned, 10) +\n\t\t\t\" | \" + strconv.FormatUint(acc.minted, 10) + \" |\\n\"\n\t\treturn false\n\t})\n\treturn out\n}\n"},{"name":"staking_test.gno","body":"package staking\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestComputeRewardPerToken(t *testing.T) {\n\t// No stakers: accumulator is frozen at its stored value.\n\tuassert.Equal(t, uint64(42), computeRewardPerToken(42, 100, 10, 0))\n\n\t// rate=100, elapsed=2, total=200, precision=1e6 =\u003e 100*2*1e6/200 = 1e6.\n\tuassert.Equal(t, precision, computeRewardPerToken(0, 100, 2, 200))\n\n\t// Accumulation builds on the stored value.\n\tuassert.Equal(t, 2*precision, computeRewardPerToken(precision, 100, 2, 200))\n}\n\nfunc TestComputeEarned(t *testing.T) {\n\t// balance=50, delta=precision =\u003e 50*1e6/1e6 = 50.\n\tuassert.Equal(t, uint64(50), computeEarned(50, precision, 0, 0))\n\n\t// Prior accrual is added on top.\n\tuassert.Equal(t, uint64(57), computeEarned(50, precision, 0, 7))\n\n\t// Only the un-paid portion of the accumulator counts.\n\tuassert.Equal(t, uint64(50), computeEarned(50, 3*precision, 2*precision, 0))\n\n\t// Zero stake earns only what was already accrued.\n\tuassert.Equal(t, uint64(9), computeEarned(0, 5*precision, 0, 9))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"streak","path":"gno.land/r/moul/x/daily/streak/v0","files":[{"name":"README.md","body":"# Check-in Streaks\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nCall `CheckIn()` once per \"day\" to keep a streak alive. Miss one and the current\nstreak resets to 1 — but your **best** streak is never lowered, so a broken run\ncosts the run, not the record.\n\nThere is no wall clock on-chain, so a \"day\" is a fixed window of `BlocksPerDay`\n(1000) blocks: `day = ChainHeight() / BlocksPerDay`. Every streak decision is\ntherefore a pure function of block height — deterministic, replayable, and\nimpossible to game by waiting for a favourable timestamp.\n\n```\nCheckIn()                        → extends or restarts your streak, returns it\nCurrent(addr)                    → live streak (0 once the window has lapsed)\nBest(addr)                       → record streak, never lowered\nDay()                            → current day index\n\n/r/moul/x/daily/streak/v0        → leaderboard, ranked by best streak\n/r/moul/x/daily/streak/v0:g1...  → one address's standing\n```\n\n`Current` deliberately reports the *live* truth rather than the stored value:\nonce a window lapses it returns 0 even though the record still holds the old\nnumber until the next check-in rewrites it.\n\nChecking in twice in the same window is rejected — the streak only moves when\nthe window does. Only an EOA can check in (`IsUserCall`), so another realm\ncan't farm streaks on your behalf.\n\nBuilt for gno 0.9. Live on both testnets (agent address):\n\n- sapphire — https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/streak\n- pearl — https://pearl.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/streak\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/streak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streak/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/streak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streak/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/streak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streak/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/streak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streak/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/streak/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/streak/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/streak/v0\"\ngno = \"0.9\"\n"},{"name":"streak.gno","body":"// Package streak is an on-chain check-in streak tracker: call CheckIn once per\n// \"day\" to keep a streak alive, miss one and it resets to 1.\n//\n// There is no wall clock on-chain, so a \"day\" here is a fixed window of\n// BlocksPerDay blocks: day = ChainHeight() / BlocksPerDay. That makes every\n// streak decision a pure function of block height — deterministic, replayable,\n// and impossible to game by waiting for a favourable timestamp.\n//\n// State is per-caller and append-only in spirit: an address's best streak is\n// never lowered, so breaking a run costs the current streak but not the record.\n//\n// This is a stateful app with nothing reusable to extract, so it ships as a\n// lone realm rather than a p/ library + demo pair.\npackage streak\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// BlocksPerDay is the length of a check-in window, in blocks. Chosen so a\n// window is a meaningful stretch of chain activity while keeping tests and\n// demos quick to reason about.\nconst BlocksPerDay = 1000\n\n// maxLeaderboard caps how many entries Render lists.\nconst maxLeaderboard = 10\n\n// record is one address's streak state.\ntype record struct {\n\tcurrent int   // consecutive days up to lastDay\n\tbest    int   // highest current ever reached; never lowered\n\tlastDay int64 // day index of the most recent check-in\n\ttotalIn int   // total check-ins ever\n}\n\n// users maps address string -\u003e *record.\nvar users = avl.NewTree()\n\n// today returns the current day index: block height divided into fixed windows.\nfunc today() int64 { return runtime.ChainHeight() / BlocksPerDay }\n\n// CheckIn records a check-in for the caller and returns the resulting streak.\n//\n// Checking in twice in the same window is rejected — the streak only moves when\n// the window does. A gap of exactly one window continues the streak; any larger\n// gap restarts it at 1.\nfunc CheckIn(cur realm) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tprev := cur.Previous()\n\tif !prev.IsUserCall() {\n\t\tpanic(\"only an EOA via MsgCall can check in\")\n\t}\n\taddr := prev.Address()\n\tday := today()\n\n\tr := get(addr)\n\tif r == nil {\n\t\tr = \u0026record{}\n\t\tusers.Set(addr.String(), r)\n\t} else {\n\t\tswitch {\n\t\tcase r.totalIn \u003e 0 \u0026\u0026 r.lastDay == day:\n\t\t\tpanic(\"already checked in for day \" + strconv.FormatInt(day, 10))\n\t\tcase r.totalIn \u003e 0 \u0026\u0026 r.lastDay == day-1:\n\t\t\t// consecutive window: the streak continues below\n\t\tdefault:\n\t\t\t// missed at least one window: the run is broken\n\t\t\tr.current = 0\n\t\t}\n\t}\n\n\tr.current++\n\tr.lastDay = day\n\tr.totalIn++\n\tif r.current \u003e r.best {\n\t\tr.best = r.current\n\t}\n\n\tchain.Emit(\"CheckIn\",\n\t\t\"addr\", addr.String(),\n\t\t\"day\", strconv.FormatInt(day, 10),\n\t\t\"streak\", strconv.Itoa(r.current),\n\t)\n\treturn r.current\n}\n\n// get returns the caller's record, or nil.\n//\n// avl/v0's Get returns a single `any` (not the value, ok pair Go maps use), so\n// a missing key surfaces as a nil interface rather than a second return value.\nfunc get(addr address) *record {\n\tv := users.Get(addr.String())\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*record)\n}\n\n// Current returns addr's live streak — 0 once a window has been missed, even\n// though the stored value only updates on the next check-in.\nfunc Current(addr address) int {\n\tr := get(addr)\n\tif r == nil {\n\t\treturn 0\n\t}\n\tday := today()\n\tif r.lastDay != day \u0026\u0026 r.lastDay != day-1 {\n\t\treturn 0\n\t}\n\treturn r.current\n}\n\n// Best returns addr's record streak, which is never lowered.\nfunc Best(addr address) int {\n\tr := get(addr)\n\tif r == nil {\n\t\treturn 0\n\t}\n\treturn r.best\n}\n\n// Day returns the current day index.\nfunc Day() int64 { return today() }\n\n// entry is a flattened record for rendering.\ntype entry struct {\n\taddr    string\n\tcurrent int\n\tbest    int\n\ttotal   int\n}\n\n// byBest ranks entries by best streak descending, then by address so equal\n// scores always come out in the same order (Render must be deterministic).\ntype byBest []entry\n\nfunc (e byBest) Len() int      { return len(e) }\nfunc (e byBest) Swap(i, j int) { e[i], e[j] = e[j], e[i] }\nfunc (e byBest) Less(i, j int) bool {\n\tif e[i].best != e[j].best {\n\t\treturn e[i].best \u003e e[j].best\n\t}\n\treturn e[i].addr \u003c e[j].addr\n}\n\n// Render renders the streak board for gnoweb.\n//\n//\tRender(\"\")          / Render(\"/\") -\u003e leaderboard by best streak\n//\tRender(\"/\u003caddress\u003e\")             -\u003e that address's standing\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Check-in Streaks\\n\\n\")\n\tb.WriteString(\"A \\\"day\\\" is \")\n\tb.WriteString(strconv.Itoa(BlocksPerDay))\n\tb.WriteString(\" blocks — there is no clock on-chain, so streaks are decided by block height alone.\\n\\n\")\n\tb.WriteString(\"Current day: **\")\n\tb.WriteString(strconv.FormatInt(today(), 10))\n\tb.WriteString(\"**\\n\\n\")\n\n\tif q := parseArg(path); q != \"\" {\n\t\treturn b.String() + renderOne(q)\n\t}\n\n\tentries := all()\n\tif len(entries) == 0 {\n\t\tb.WriteString(\"_Nobody has checked in yet._\\n\\n\")\n\t\tb.WriteString(\"\u003e Call `CheckIn()` to start a streak.\\n\")\n\t\treturn b.String()\n\t}\n\n\t// gno's sort has Sort(Interface) but no Slice(), so ranking goes through an\n\t// explicit sort.Interface. Ties break on address so the board is stable.\n\tsort.Sort(byBest(entries))\n\tif len(entries) \u003e maxLeaderboard {\n\t\tentries = entries[:maxLeaderboard]\n\t}\n\n\tb.WriteString(\"| # | address | current | best | check-ins |\\n|---|---|---|---|---|\\n\")\n\tfor i, e := range entries {\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(strconv.Itoa(i + 1))\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(e.addr)\n\t\tb.WriteString(\"` | \")\n\t\tb.WriteString(strconv.Itoa(e.current))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.Itoa(e.best))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.Itoa(e.total))\n\t\tb.WriteString(\" |\\n\")\n\t}\n\treturn b.String()\n}\n\n// renderOne renders a single address's standing.\nfunc renderOne(q string) string {\n\taddr := address(q)\n\tvar b strings.Builder\n\tb.WriteString(\"## `\")\n\tb.WriteString(q)\n\tb.WriteString(\"`\\n\\n\")\n\tif !addr.IsValid() {\n\t\tb.WriteString(\"_Not a valid address._\\n\")\n\t\treturn b.String()\n\t}\n\tr := get(addr)\n\tif r == nil {\n\t\tb.WriteString(\"_No check-ins yet._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"- current streak: **\")\n\tb.WriteString(strconv.Itoa(Current(addr)))\n\tb.WriteString(\"**\\n- best streak: **\")\n\tb.WriteString(strconv.Itoa(r.best))\n\tb.WriteString(\"**\\n- total check-ins: **\")\n\tb.WriteString(strconv.Itoa(r.totalIn))\n\tb.WriteString(\"**\\n- last check-in: day **\")\n\tb.WriteString(strconv.FormatInt(r.lastDay, 10))\n\tb.WriteString(\"**\\n\")\n\treturn b.String()\n}\n\n// all flattens the tree into a slice.\nfunc all() []entry {\n\tout := []entry{}\n\tusers.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tr := v.(*record)\n\t\tout = append(out, entry{\n\t\t\taddr:    k,\n\t\t\tcurrent: Current(address(k)),\n\t\t\tbest:    r.best,\n\t\t\ttotal:   r.totalIn,\n\t\t})\n\t\treturn false\n\t})\n\treturn out\n}\n\n// parseArg extracts the first path segment.\nfunc parseArg(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n"},{"name":"streak_test.gno","body":"package streak\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// reset clears realm state between tests.\nfunc reset() { users = avl.NewTree() }\n\n// alignDay moves to the start of the next check-in window, so a test begins on\n// a clean day boundary. testing only exposes a RELATIVE SkipHeights (there is\n// no absolute height setter, and no testing.Height), so days are driven\n// forward from wherever the previous test left the chain — never assume an\n// absolute day number, ask Day().\nfunc alignDay() {\n\tif rem := runtime.ChainHeight() % BlocksPerDay; rem != 0 {\n\t\ttesting.SkipHeights(BlocksPerDay - rem)\n\t}\n}\n\n// advanceDays moves the chain forward by n whole windows.\nfunc advanceDays(n int64) { testing.SkipHeights(n * BlocksPerDay) }\n\n// checkIn runs a check-in as addr.\nfunc checkIn(cur realm, addr address) int {\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\treturn CheckIn(cross(cur))\n}\n\nfunc TestFirstCheckInStartsAtOne(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\n\tuassert.Equal(t, 1, checkIn(cur, alice))\n\tuassert.Equal(t, 1, Current(alice))\n\tuassert.Equal(t, 1, Best(alice))\n}\n\nfunc TestConsecutiveDaysExtendStreak(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\n\tuassert.Equal(t, 1, checkIn(cur, alice))\n\tadvanceDays(1)\n\tuassert.Equal(t, 2, checkIn(cur, alice))\n\tadvanceDays(1)\n\tuassert.Equal(t, 3, checkIn(cur, alice))\n\tuassert.Equal(t, 3, Best(alice))\n}\n\n// The whole point of the realm: a missed window restarts the run at 1, but the\n// record survives.\nfunc TestMissedDayResetsCurrentButKeepsBest(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\n\tcheckIn(cur, alice)\n\tadvanceDays(1)\n\tcheckIn(cur, alice)\n\tuassert.Equal(t, 2, Best(alice))\n\n\tadvanceDays(7) // a long gap\n\tuassert.Equal(t, 1, checkIn(cur, alice))\n\tuassert.Equal(t, 1, Current(alice))\n\tuassert.Equal(t, 2, Best(alice))\n}\n\nfunc TestTwiceInSameDayPanics(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\tcheckIn(cur, alice)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\trec := revive(func() { CheckIn(cross(cur)) })\n\tuassert.True(t, rec != nil)\n}\n\n// Current() reports the live truth: once the window lapses the streak is 0,\n// even though the stored record still holds the old value until the next\n// check-in rewrites it.\nfunc TestCurrentGoesStaleWithoutACheckIn(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\tcheckIn(cur, alice)\n\n\tadvanceDays(1) // yesterday — still within reach\n\tuassert.Equal(t, 1, Current(alice))\n\tadvanceDays(1) // gap: the run is over\n\tuassert.Equal(t, 0, Current(alice))\n\tuassert.Equal(t, 1, Best(alice)) // record untouched\n}\n\nfunc TestStreaksAreIndependentPerAddress(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\tcheckIn(cur, alice)\n\tadvanceDays(1)\n\tcheckIn(cur, alice)\n\tcheckIn(cur, bob)\n\n\tuassert.Equal(t, 2, Current(alice))\n\tuassert.Equal(t, 1, Current(bob))\n}\n\nfunc TestUnknownAddressIsZero(t *testing.T) {\n\treset()\n\tcarol := testutils.TestAddress(\"carol\")\n\tuassert.Equal(t, 0, Current(carol))\n\tuassert.Equal(t, 0, Best(carol))\n}\n\nfunc TestRenderEmptyBoard(t *testing.T) {\n\treset()\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Nobody has checked in yet\"))\n\tuassert.True(t, strings.Contains(out, \"Current day: **\"+strconv.FormatInt(Day(), 10)+\"**\"))\n}\n\nfunc TestRenderRanksByBest(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\t// alice reaches 2, bob only 1\n\tcheckIn(cur, alice)\n\tadvanceDays(1)\n\tcheckIn(cur, alice)\n\tcheckIn(cur, bob)\n\n\tout := Render(\"\")\n\tai := strings.Index(out, alice.String())\n\tbi := strings.Index(out, bob.String())\n\tuassert.True(t, ai \u003e= 0)\n\tuassert.True(t, bi \u003e= 0)\n\tuassert.True(t, ai \u003c bi) // alice ranks first\n}\n\nfunc TestRenderSingleAddress(cur realm, t *testing.T) {\n\treset()\n\talignDay()\n\talice := testutils.TestAddress(\"alice\")\n\tcheckIn(cur, alice)\n\n\tout := Render(\"/\" + alice.String())\n\tuassert.True(t, strings.Contains(out, \"current streak: **1**\"))\n\tuassert.True(t, strings.Contains(out, \"total check-ins: **1**\"))\n}\n\nfunc TestRenderRejectsBadAddress(t *testing.T) {\n\treset()\n\tout := Render(\"/not-an-address\")\n\tuassert.True(t, strings.Contains(out, \"Not a valid address\"))\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"vestoken","path":"gno.land/r/moul/x/daily/vestoken/v0","files":[{"name":"README.md","body":"# vestoken\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/vestoken/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vestoken/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/vestoken/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vestoken/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/vestoken/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vestoken/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/vestoken/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vestoken/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/vestoken/v0\"\ngno = \"0.9\"\n"},{"name":"vestoken.gno","body":"// Package vestoken is a fungible token where new supply is never handed out\n// instantly — it ports the idea behind Solidity's VestingWallet / linear\n// token-streaming contracts (e.g. Sablier) into a single gno.land realm.\n//\n// MintVested opens a linear vesting grant instead of crediting a balance\n// directly. The beneficiary calls Claim over time to pull whatever has\n// unlocked so far into their liquid, transferable balance. State is\n// package-level and persistent; state-mutating functions are crossing\n// functions (`cur realm`) per the gno 0.9 interrealm convention.\npackage vestoken\n\nimport (\n\t\"chain/runtime\"\n\t\"errors\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tname   = \"VestToken\"\n\tsymbol = \"VEST\"\n)\n\n// grant is one linear vesting schedule: `total` unlocks evenly from `start`\n// to `start+duration` (measured in block height), and `claimed` tracks how\n// much of the unlocked amount the beneficiary has already pulled.\ntype grant struct {\n\ttotal    uint64\n\tclaimed  uint64\n\tstart    int64\n\tduration int64\n}\n\nvar (\n\t// balances holds liquid, already-claimed tokens — transferable like a\n\t// normal ERC-20 balance.\n\tbalances = map[address]uint64{}\n\t// grants holds at most one active vesting schedule per beneficiary.\n\tgrants = map[address]*grant{}\n\t// totalSupply is every token ever minted (vesting or liquid).\n\ttotalSupply uint64\n)\n\nvar (\n\terrZeroAddress   = errors.New(\"vestoken: zero address\")\n\terrZeroAmount    = errors.New(\"vestoken: amount must be positive\")\n\terrZeroDuration  = errors.New(\"vestoken: duration must be positive\")\n\terrGrantActive   = errors.New(\"vestoken: beneficiary already has an unclaimed grant\")\n\terrNoGrant       = errors.New(\"vestoken: no active grant for this account\")\n\terrInsufficient  = errors.New(\"vestoken: insufficient balance\")\n\terrOverflow      = errors.New(\"vestoken: supply overflow\")\n\terrSpoofedRealm  = errors.New(\"vestoken: spoofed realm\")\n\terrNotUser       = errors.New(\"vestoken: caller is not a user account\")\n)\n\n// caller returns the immediate caller's address for a crossing function,\n// enforcing the gno 0.9 authentication primitive: cur must be the live\n// crossing frame before its Previous() is trusted.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(errSpoofedRealm)\n\t}\n\tprev := cur.Previous()\n\tif !prev.IsUser() {\n\t\tpanic(errNotUser)\n\t}\n\treturn prev.Address()\n}\n\n// MintVested opens a new linear vesting grant for `to`: `amount` tokens\n// unlock block-by-block over the next `durationBlocks` blocks, starting now.\n// A beneficiary may only hold one active grant at a time. Crossing function.\nfunc MintVested(cur realm, to address, amount uint64, durationBlocks int64) {\n\t_ = caller(cur) // authenticate the crossing frame; anyone may open a grant in this demo\n\tif !to.IsValid() {\n\t\tpanic(errZeroAddress)\n\t}\n\tif amount == 0 {\n\t\tpanic(errZeroAmount)\n\t}\n\tif durationBlocks \u003c= 0 {\n\t\tpanic(errZeroDuration)\n\t}\n\tif g, ok := grants[to]; ok \u0026\u0026 g.claimed \u003c g.total {\n\t\tpanic(errGrantActive)\n\t}\n\tif totalSupply+amount \u003c totalSupply {\n\t\tpanic(errOverflow)\n\t}\n\ttotalSupply += amount\n\tgrants[to] = \u0026grant{\n\t\ttotal:    amount,\n\t\tstart:    runtime.ChainHeight(),\n\t\tduration: durationBlocks,\n\t}\n}\n\n// Claim pulls whatever has unlocked so far from the caller's grant into\n// their liquid balance, and returns how much was claimed. Crossing function.\nfunc Claim(cur realm) uint64 {\n\twho := caller(cur)\n\tg, ok := grants[who]\n\tif !ok {\n\t\tpanic(errNoGrant)\n\t}\n\n\tunlocked := vestedAmount(g, runtime.ChainHeight())\n\tclaimable := unlocked - g.claimed\n\tif claimable == 0 {\n\t\treturn 0\n\t}\n\n\tg.claimed = unlocked\n\tbalances[who] += claimable\n\tif g.claimed \u003e= g.total {\n\t\tdelete(grants, who)\n\t}\n\treturn claimable\n}\n\n// vestedAmount computes how much of g has unlocked by the given height.\nfunc vestedAmount(g *grant, height int64) uint64 {\n\telapsed := height - g.start\n\tif elapsed \u003c= 0 {\n\t\treturn 0\n\t}\n\tif elapsed \u003e= g.duration {\n\t\treturn g.total\n\t}\n\treturn g.total * uint64(elapsed) / uint64(g.duration)\n}\n\n// Transfer moves `amount` of the caller's liquid (already-claimed) balance\n// to `to`. Crossing function.\nfunc Transfer(cur realm, to address, amount uint64) {\n\tfrom := caller(cur)\n\tif !to.IsValid() {\n\t\tpanic(errZeroAddress)\n\t}\n\tif amount == 0 {\n\t\treturn\n\t}\n\tif balances[from] \u003c amount {\n\t\tpanic(errInsufficient)\n\t}\n\tbalances[from] -= amount\n\tbalances[to] += amount\n}\n\n// BalanceOf returns the liquid (claimed, transferable) balance of holder.\nfunc BalanceOf(holder address) uint64 {\n\treturn balances[holder]\n}\n\n// GrantOf returns the beneficiary's active grant, if any: total amount,\n// amount claimed so far, and the amount currently claimable.\nfunc GrantOf(beneficiary address) (total uint64, claimed uint64, claimable uint64) {\n\tg, ok := grants[beneficiary]\n\tif !ok {\n\t\treturn 0, 0, 0\n\t}\n\tunlocked := vestedAmount(g, runtime.ChainHeight())\n\treturn g.total, g.claimed, unlocked - g.claimed\n}\n\n// TotalSupply returns every token ever minted, vesting or liquid.\nfunc TotalSupply() uint64 { return totalSupply }\n\n// Name returns the token name.\nfunc Name() string { return name }\n\n// Symbol returns the token symbol.\nfunc Symbol() string { return symbol }\n\n// Render produces the gnoweb Markdown view: metadata, active vesting\n// grants, and liquid balances — both tables sorted by address for\n// deterministic output. Render is NOT a crossing function.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# \" + name + \" (\" + symbol + \")\\n\\n\")\n\tb.WriteString(\"A linearly-vesting ERC-20-style token on gno.land — \")\n\tb.WriteString(\"new supply unlocks block-by-block instead of landing instantly.\\n\\n\")\n\tb.WriteString(\"- **Name:** \" + name + \"\\n\")\n\tb.WriteString(\"- **Symbol:** \" + symbol + \"\\n\")\n\tb.WriteString(\"- **Total supply:** \" + strconv.FormatUint(totalSupply, 10) + \"\\n\")\n\tb.WriteString(\"- **Current height:** \" + strconv.FormatInt(runtime.ChainHeight(), 10) + \"\\n\\n\")\n\n\tb.WriteString(\"## Active grants\\n\\n\")\n\tgrantKeys := sortedAddrKeys(grantAddrs())\n\tif len(grantKeys) == 0 {\n\t\tb.WriteString(\"_No active grants — call `MintVested` to open one._\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| Beneficiary | Total | Claimed | Claimable now |\\n\")\n\t\tb.WriteString(\"| --- | ---: | ---: | ---: |\\n\")\n\t\tfor _, k := range grantKeys {\n\t\t\tg := grants[address(k)]\n\t\t\tunlocked := vestedAmount(g, runtime.ChainHeight())\n\t\t\tb.WriteString(\"| `\" + k + \"` | \" +\n\t\t\t\tstrconv.FormatUint(g.total, 10) + \" | \" +\n\t\t\t\tstrconv.FormatUint(g.claimed, 10) + \" | \" +\n\t\t\t\tstrconv.FormatUint(unlocked-g.claimed, 10) + \" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"## Liquid balances\\n\\n\")\n\tbalKeys := sortedAddrKeys(balanceAddrs())\n\tif len(balKeys) == 0 {\n\t\tb.WriteString(\"_No claimed balances yet — call `Claim` once a grant has unlocked._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"| Address | Amount |\\n\")\n\tb.WriteString(\"| --- | ---: |\\n\")\n\tfor _, k := range balKeys {\n\t\tb.WriteString(\"| `\" + k + \"` | \" +\n\t\t\tstrconv.FormatUint(balances[address(k)], 10) + \" |\\n\")\n\t}\n\n\treturn b.String()\n}\n\nfunc grantAddrs() []string {\n\tkeys := make([]string, 0, len(grants))\n\tfor addr := range grants {\n\t\tkeys = append(keys, addr.String())\n\t}\n\treturn keys\n}\n\nfunc balanceAddrs() []string {\n\tkeys := make([]string, 0, len(balances))\n\tfor addr, bal := range balances {\n\t\tif bal == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tkeys = append(keys, addr.String())\n\t}\n\treturn keys\n}\n\nfunc sortedAddrKeys(keys []string) []string {\n\tsort.Strings(keys)\n\treturn keys\n}\n"},{"name":"vestoken_test.gno","body":"package vestoken\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Fixed test addresses. testutils.TestAddress derives real, valid-length\n// addresses; literal strings would fail address.IsValid() and trip the realm's\n// zero-address guard.\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\n// reset clears package state between tests so cases stay independent.\nfunc reset() {\n\tbalances = map[address]uint64{}\n\tgrants = map[address]*grant{}\n\ttotalSupply = 0\n}\n\n// TestVestingUnlocksLinearly opens a grant, claims nothing before any\n// blocks pass, half at the midpoint, and the rest once fully vested.\nfunc TestVestingUnlocksLinearly(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMintVested(cross(cur), alice, 1000, 100)\n\n\tif got := TotalSupply(); got != 1000 {\n\t\tt.Fatalf(\"total supply = %d, want 1000\", got)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tif got := Claim(cross(cur)); got != 0 {\n\t\tt.Fatalf(\"claim at start = %d, want 0\", got)\n\t}\n\n\ttesting.SkipHeights(50)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tif got := Claim(cross(cur)); got != 500 {\n\t\tt.Fatalf(\"claim at midpoint = %d, want 500\", got)\n\t}\n\tif got := BalanceOf(alice); got != 500 {\n\t\tt.Errorf(\"alice liquid balance = %d, want 500\", got)\n\t}\n\n\ttesting.SkipHeights(50)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tif got := Claim(cross(cur)); got != 500 {\n\t\tt.Fatalf(\"claim at end = %d, want 500\", got)\n\t}\n\tif got := BalanceOf(alice); got != 1000 {\n\t\tt.Errorf(\"alice liquid balance = %d, want 1000\", got)\n\t}\n\n\ttotal, claimed, claimable := GrantOf(alice)\n\tif total != 0 || claimed != 0 || claimable != 0 {\n\t\tt.Errorf(\"grant should be gone after full claim, got total=%d claimed=%d claimable=%d\", total, claimed, claimable)\n\t}\n}\n\n// TestActiveGrantBlocksNewGrant asserts a beneficiary can't be granted twice\n// while a previous grant is still unclaimed.\nfunc TestActiveGrantBlocksNewGrant(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMintVested(cross(cur), alice, 100, 10)\n\n\t// Aborts from a cross(cur) call cannot be caught by a plain recover();\n\t// assert on the abort message instead.\n\tuassert.AbortsWithMessage(t, cur, \"vestoken: beneficiary already has an unclaimed grant\", func() {\n\t\tMintVested(cross(cur), alice, 50, 10)\n\t})\n}\n\n// TestTransferClaimedBalance checks claimed tokens behave like a normal\n// transferable ERC-20 balance.\nfunc TestTransferClaimedBalance(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMintVested(cross(cur), alice, 200, 10)\n\n\ttesting.SkipHeights(10)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClaim(cross(cur))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), bob, 80)\n\n\tif got := BalanceOf(alice); got != 120 {\n\t\tt.Errorf(\"alice balance = %d, want 120\", got)\n\t}\n\tif got := BalanceOf(bob); got != 80 {\n\t\tt.Errorf(\"bob balance = %d, want 80\", got)\n\t}\n}\n\n// TestRenderContainsMetadata checks the Markdown view exposes name/symbol\n// and the active grant.\nfunc TestRenderContainsMetadata(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMintVested(cross(cur), alice, 42, 10)\n\n\tout := Render(\"\")\n\tfor _, want := range []string{\"VestToken\", \"VEST\", \"Total supply\", \"42\"} {\n\t\tif !strings.Contains(out, want) {\n\t\t\tt.Errorf(\"render output missing %q\\n%s\", want, out)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wrapped","path":"gno.land/r/moul/x/daily/wrapped/v0","files":[{"name":"README.md","body":"# wrapped — Wrapped Ether (WETH), gno.land port\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nAn accounting-only port of the canonical **Wrapped Ether (WETH)** contract. WETH\nlets you lock native ETH to mint a 1:1 ERC-20 token and burn it to unlock the ETH\nagain. gno.land / sapphire has no `msg.value` / `payable`, so this realm models the\nwrap/unwrap purely as `uint64` ledger accounting — **no real coin ever moves**.\nBalances live in an `avl.Tree`; every mutation emits a `Deposit`, `Withdrawal`, or\n`Transfer` event, mirroring the original contract.\n\n## API\n\n- `Deposit(cur realm, amount uint64)` — credit the caller's wrapped balance and\n  `totalSupply` (models wrapping native funds; accounting only).\n- `Withdraw(cur realm, amount uint64)` — burn `amount` from the caller and from\n  `totalSupply` (panics on insufficient balance).\n- `Transfer(cur realm, to address, amount uint64)` — move wrapped units.\n- `BalanceOf(owner address) uint64` — read a single balance.\n- `TotalSupply() uint64` — read the total wrapped supply.\n- `Render(path string) string` — Markdown: total supply + non-zero balances table.\n\n## Example calls\n\n```\n# wrap 1000 units for the caller\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/wrapped/v0 -func Deposit -args 1000 ...\n\n# send 250 to another address\ngnokey maketx call ... -func Transfer -args g1\u003crecipient\u003e -args 250 ...\n\n# unwrap 500 units\ngnokey maketx call ... -func Withdraw -args 500 ...\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/wrapped/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wrapped/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/wrapped/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wrapped/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/wrapped/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wrapped/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/wrapped/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wrapped/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/wrapped/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/wrapped/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/wrapped/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package wrapped\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Wrapped (WETH-style, accounting-only)\n\t//\n\t// Deposit mints wrapped units, Withdraw burns them. No real coins move — this is a pure ledger.\n\t//\n\t// **Total supply:** 0\n\t//\n\t// _No balances yet. Call `Deposit` to wrap some units._\n}\n"},{"name":"wrapped.gno","body":"// Package wrapped is an accounting-only port of Wrapped Ether (WETH).\n//\n// The canonical WETH contract lets anyone lock native ETH and mint a 1:1\n// ERC-20 representation (and burn it back). On gno.land / sapphire there is no\n// msg.value / payable, so there is NO real coin transfer here: Deposit and\n// Withdraw are pure accounting operations that model the wrap/unwrap. Balances\n// and totalSupply are plain uint64 ledgers kept in an avl.Tree.\npackage wrapped\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// balances maps owner address (string) -\u003e wrapped balance (uint64).\nvar (\n\tbalances    avl.Tree\n\ttotalSupply uint64\n)\n\n// Deposit wraps `amount` units of the (notional) native coin, crediting the\n// caller's wrapped balance and the global totalSupply. Accounting only: no real\n// coin ever moves — it models locking native funds to mint the wrapped token.\nfunc Deposit(cur realm, amount uint64) {\n\tif amount == 0 {\n\t\tpanic(\"wrapped: deposit amount must be \u003e 0\")\n\t}\n\towner := unsafe.PreviousRealm().Address()\n\tsetBalance(owner, balanceOf(owner)+amount)\n\ttotalSupply += amount\n\tchain.Emit(\"Deposit\", \"dst\", owner.String(), \"wad\", strconv.FormatUint(amount, 10))\n}\n\n// Withdraw unwraps `amount` units, burning them from the caller's balance and\n// from totalSupply. Panics if the caller lacks the balance.\nfunc Withdraw(cur realm, amount uint64) {\n\tif amount == 0 {\n\t\tpanic(\"wrapped: withdraw amount must be \u003e 0\")\n\t}\n\towner := unsafe.PreviousRealm().Address()\n\tbal := balanceOf(owner)\n\tif bal \u003c amount {\n\t\tpanic(\"wrapped: insufficient balance\")\n\t}\n\tsetBalance(owner, bal-amount)\n\ttotalSupply -= amount\n\tchain.Emit(\"Withdrawal\", \"src\", owner.String(), \"wad\", strconv.FormatUint(amount, 10))\n}\n\n// Transfer moves `amount` wrapped units from the caller to `to`.\nfunc Transfer(cur realm, to address, amount uint64) {\n\tif amount == 0 {\n\t\tpanic(\"wrapped: transfer amount must be \u003e 0\")\n\t}\n\tfrom := unsafe.PreviousRealm().Address()\n\tif from == to {\n\t\tpanic(\"wrapped: cannot transfer to self\")\n\t}\n\tfromBal := balanceOf(from)\n\tif fromBal \u003c amount {\n\t\tpanic(\"wrapped: insufficient balance\")\n\t}\n\tsetBalance(from, fromBal-amount)\n\tsetBalance(to, balanceOf(to)+amount)\n\tchain.Emit(\"Transfer\", \"src\", from.String(), \"dst\", to.String(), \"wad\", strconv.FormatUint(amount, 10))\n}\n\n// balanceOf returns the wrapped balance of `owner` (read-only, not crossing).\nfunc balanceOf(owner address) uint64 {\n\tv := balances.Get(owner.String())\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(uint64)\n}\n\n// BalanceOf is the exported read-only accessor for a single owner.\nfunc BalanceOf(owner address) uint64 { return balanceOf(owner) }\n\n// TotalSupply returns the total amount of wrapped units in existence.\nfunc TotalSupply() uint64 { return totalSupply }\n\nfunc setBalance(owner address, amount uint64) {\n\tif amount == 0 {\n\t\tbalances.Remove(owner.String())\n\t\treturn\n\t}\n\tbalances.Set(owner.String(), amount)\n}\n\n// ---- pure/read-only helpers (unit-tested) ----\n\n// canDebit reports whether `bal` can cover `amount` for a burn/transfer.\nfunc canDebit(bal, amount uint64) bool {\n\treturn amount \u003e 0 \u0026\u0026 bal \u003e= amount\n}\n\n// formatUnits renders a raw uint64 amount as a decimal string.\nfunc formatUnits(n uint64) string {\n\treturn strconv.FormatUint(n, 10)\n}\n\n// Render shows the total supply and a table of non-zero balances.\nfunc Render(path string) string {\n\tout := \"# Wrapped (WETH-style, accounting-only)\\n\\n\"\n\tout += \"Deposit mints wrapped units, Withdraw burns them. No real coins move — this is a pure ledger.\\n\\n\"\n\tout += \"**Total supply:** \" + formatUnits(totalSupply) + \"\\n\\n\"\n\n\tif balances.Size() == 0 {\n\t\tout += \"_No balances yet. Call `Deposit` to wrap some units._\\n\"\n\t\treturn out\n\t}\n\n\tout += \"| Owner | Balance |\\n|---|---:|\\n\"\n\tbalances.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tout += \"| `\" + key + \"` | \" + formatUnits(value.(uint64)) + \" |\\n\"\n\t\treturn false\n\t})\n\treturn out\n}\n"},{"name":"wrapped_test.gno","body":"package wrapped\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestCanDebit(t *testing.T) {\n\tuassert.True(t, canDebit(100, 40), \"bal covers amount\")\n\tuassert.True(t, canDebit(50, 50), \"exact balance is debitable\")\n\tuassert.False(t, canDebit(10, 20), \"amount exceeds balance\")\n\tuassert.False(t, canDebit(100, 0), \"zero amount is never debitable\")\n\tuassert.False(t, canDebit(0, 1), \"empty balance cannot be debited\")\n}\n\nfunc TestFormatUnits(t *testing.T) {\n\tuassert.Equal(t, \"0\", formatUnits(0))\n\tuassert.Equal(t, \"1\", formatUnits(1))\n\tuassert.Equal(t, \"1000000\", formatUnits(1_000_000))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"grc20faucet","path":"gno.land/r/moul/x/grc20faucet/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/grc20faucet/v0`\n\n**Two free GRC20 tokens, RED and BLUE, so experiments have something to run on.**\nWorthless by construction, unlimited, and shared.\n\n```\nmaketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Claim\n```\n\n100.0000 of each per claim (4 decimals), once every 100 blocks per account.\n\n| token | symbol | registry key |\n|---|---|---|\n| Red Token | `RED` | `gno.land/r/moul/x/grc20faucet/v0.RED` |\n| Blue Token | `BLUE` | `gno.land/r/moul/x/grc20faucet/v0.BLUE` |\n\nBoth are registered in [`r/nt/grc20reg`](https://gno.land/r/nt/grc20reg/v0), which\nis the point: another realm can find and move them by key without importing this\none. Everything else here is the ordinary GRC20 surface, with the symbol as the\nfirst argument:\n\n```\n-func Transfer     -args RED  -args \u003cto\u003e      -args 250000\n-func Approve      -args BLUE -args \u003cspender\u003e -args 250000\n-func TransferFrom -args RED  -args \u003cfrom\u003e -args \u003cto\u003e -args 250000\n```\n\n`Approve` is the interesting one. It is what lets a realm such as\n[`r/moul/x/grc20wrapdemo`](https://gno.land/r/moul/x/grc20wrapdemo/v0) pull your\ntokens into escrow, and until you call it that realm has no authority over your\nbalance at all.\n\nTwo tokens rather than one because the interesting patterns start at two: a\nmeta-token over a pair needs a pair.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/grc20faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20faucet/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/grc20faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20faucet/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/grc20faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20faucet/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/grc20faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20faucet/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/grc20faucet/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/grc20faucet/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"faucet.gno","body":"// Package grc20faucet issues two free GRC20 tokens, RED and BLUE, and gives\n// them away on request.\n//\n// It exists so that anything needing a token to experiment on has one that is\n// worthless, unlimited and shared. Both tokens are registered in\n// gno.land/r/nt/grc20reg/v0, which is what lets another realm find and move\n// them by key without importing this package: that indirection is the whole\n// point, and it is what gno.land/r/moul/x/grc20wrapdemo/v0 wraps.\n//\n// Two tokens rather than one, because the interesting patterns start at two: a\n// meta-token over a pair needs a pair.\npackage grc20faucet\n\nimport (\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\n// Tokens are exported so an importing realm can read them directly; the\n// ledgers stay private, since they carry unrestricted mint and burn.\nvar (\n\tRed  *grc20.Token\n\tBlue *grc20.Token\n\n\tredLedger  *grc20.PrivateLedger\n\tblueLedger *grc20.PrivateLedger\n\n\t// RedKey and BlueKey are the grc20reg lookup keys, the way a realm that\n\t// does NOT import this package refers to these tokens.\n\tRedKey  string\n\tBlueKey string\n\n\tlastClaim = avl.NewTree() // address -\u003e block height of its last claim\n)\n\nconst (\n\tdecimals = 4\n\n\t// ClaimAmount is minted of EACH token per claim: 100.0000 units.\n\tClaimAmount = int64(1_000_000)\n\n\t// ClaimEvery is the cooldown, in blocks, between two claims by the same\n\t// account. Free money with no cooldown is a spam vector, not a faucet.\n\tClaimEvery = int64(100)\n)\n\nfunc init(cur realm) {\n\tRed, redLedger = grc20.NewToken(\"Red Token\", \"RED\", decimals, 0, cur)\n\tBlue, blueLedger = grc20.NewToken(\"Blue Token\", \"BLUE\", decimals, 1, cur)\n\tRedKey = grc20reg.Register(cross(cur), Red, \"red\")\n\tBlueKey = grc20reg.Register(cross(cur), Blue, \"blue\")\n}\n\n// Claim mints ClaimAmount of both RED and BLUE to the caller.\nfunc Claim(cur realm) {\n\twho := caller(cur)\n\tnow := runtime.ChainHeight()\n\tif next, ok := NextClaim(who); ok \u0026\u0026 now \u003c next {\n\t\tpanic(ufmt.Sprintf(\"too soon: next claim at block %d, current %d\", next, now))\n\t}\n\tlastClaim.Set(who.String(), now)\n\tcheckErr(redLedger.Mint(who, ClaimAmount))\n\tcheckErr(blueLedger.Mint(who, ClaimAmount))\n}\n\n// NextClaim returns the block height at which `who` may claim again, and\n// whether they have ever claimed at all.\nfunc NextClaim(who address) (int64, bool) {\n\tv := lastClaim.Get(who.String())\n\tif v == nil {\n\t\treturn 0, false\n\t}\n\treturn v.(int64) + ClaimEvery, true\n}\n\n// Transfer moves the caller's own units of `symbol`.\nfunc Transfer(cur realm, symbol string, to address, amount int64) {\n\tcheckErr(ledgerOf(symbol).CallerTeller().Transfer(0, cur, to, amount))\n}\n\n// Approve lets `spender` draw `amount` of `symbol` from the caller's balance.\n//\n// This is the call that makes every wrapper in grc20wrapdemo work: the wrapper\n// realm has no authority over anybody's tokens until its address is named here.\nfunc Approve(cur realm, symbol string, spender address, amount int64) {\n\tcheckErr(ledgerOf(symbol).CallerTeller().Approve(0, cur, spender, amount))\n}\n\n// TransferFrom spends an allowance the caller was granted.\nfunc TransferFrom(cur realm, symbol string, from, to address, amount int64) {\n\tcheckErr(ledgerOf(symbol).CallerTeller().TransferFrom(0, cur, from, to, amount))\n}\n\n// BalanceOf returns `owner`'s balance of `symbol`.\nfunc BalanceOf(symbol string, owner address) int64 {\n\treturn tokenOf(symbol).BalanceOf(owner)\n}\n\n// Allowance returns what `owner` let `spender` draw of `symbol`.\nfunc Allowance(symbol string, owner, spender address) int64 {\n\treturn tokenOf(symbol).Allowance(owner, spender)\n}\n\n// TotalSupply returns how much of `symbol` has been claimed so far.\nfunc TotalSupply(symbol string) int64 {\n\treturn tokenOf(symbol).TotalSupply()\n}\n\nfunc tokenOf(symbol string) *grc20.Token {\n\tswitch symbol {\n\tcase \"RED\":\n\t\treturn Red\n\tcase \"BLUE\":\n\t\treturn Blue\n\t}\n\tpanic(\"unknown symbol \" + symbol + \" (RED or BLUE)\")\n}\n\nfunc ledgerOf(symbol string) *grc20.PrivateLedger {\n\tswitch symbol {\n\tcase \"RED\":\n\t\treturn redLedger\n\tcase \"BLUE\":\n\t\treturn blueLedger\n\t}\n\tpanic(\"unknown symbol \" + symbol + \" (RED or BLUE)\")\n}\n\n// caller is the account or realm that crossed into this one.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grc20faucet: stale realm token\")\n\t}\n\treturn cur.Previous().Address()\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Render(path string) string {\n\ts := \"# GRC20 faucet: RED and BLUE\\n\\n\"\n\ts += \"Two worthless tokens to experiment on. `Claim` gives you \"\n\ts += ufmt.Sprintf(\"%d of each, once every %d blocks.\\n\\n\", ClaimAmount, ClaimEvery)\n\n\ts += \"| token | symbol | decimals | supply | registry key |\\n\"\n\ts += \"|---|---|---|---|---|\\n\"\n\ts += ufmt.Sprintf(\"| %s | RED | %d | %d | `%s` |\\n\",\n\t\tRed.GetName(), Red.GetDecimals(), Red.TotalSupply(), RedKey)\n\ts += ufmt.Sprintf(\"| %s | BLUE | %d | %d | `%s` |\\n\",\n\t\tBlue.GetName(), Blue.GetDecimals(), Blue.TotalSupply(), BlueKey)\n\n\ts += \"\\n## Use it\\n\\n\"\n\ts += \"```\\n\"\n\ts += \"gnokey maketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Claim ...\\n\"\n\ts += \"gnokey maketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Approve \\\\\\n\"\n\ts += \"  -args RED -args \u003cspender\u003e -args 1000000 ...\\n\"\n\ts += \"```\\n\\n\"\n\ts += \"Both tokens are registered in [grc20reg](/r/nt/grc20reg/v0), so a realm can\\n\"\n\ts += \"move them by key without importing this one. That is what\\n\"\n\ts += \"[grc20wrapdemo](/r/moul/x/grc20wrapdemo/v0) does with them.\\n\"\n\n\tif path != \"\" {\n\t\ts += \"\\n---\\n\\n\"\n\t\ts += ufmt.Sprintf(\"Balance of `%s`: RED %d, BLUE %d\\n\",\n\t\t\tpath, Red.BalanceOf(address(path)), Blue.BalanceOf(address(path)))\n\t}\n\treturn s\n}\n"},{"name":"faucet_test.gno","body":"package grc20faucet\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\n// testing.SetRealm governs the crossing calls made from the frame that called\n// it, so switching accounts has to be written inline in each test, never\n// through a helper that does not itself cross.\nfunc TestClaimAndCooldown(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"f-alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t_, ok := NextClaim(alice)\n\tuassert.False(t, ok, \"no cooldown before the first claim\")\n\n\tClaim(cross(cur))\n\tuassert.Equal(t, ClaimAmount, BalanceOf(\"RED\", alice))\n\tuassert.Equal(t, ClaimAmount, BalanceOf(\"BLUE\", alice))\n\n\tnext, ok := NextClaim(alice)\n\tuassert.True(t, ok, \"a cooldown is recorded\")\n\tuassert.AbortsContains(t, cur, \"too soon\", func() { Claim(cross(cur)) })\n\n\ttesting.SkipHeights(ClaimEvery + 1)\n\tClaim(cross(cur))\n\tuassert.Equal(t, 2*ClaimAmount, BalanceOf(\"RED\", alice))\n\n\tafter, _ := NextClaim(alice)\n\tuassert.True(t, after \u003e next, \"the cooldown moved forward\")\n}\n\nfunc TestTransferAndAllowance(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"f-tx-alice\")\n\tbob := testutils.TestAddress(\"f-tx-bob\")\n\tcarl := testutils.TestAddress(\"f-tx-carl\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClaim(cross(cur))\n\tTransfer(cross(cur), \"RED\", bob, 400_000)\n\tuassert.Equal(t, int64(400_000), BalanceOf(\"RED\", bob))\n\tuassert.Equal(t, ClaimAmount-400_000, BalanceOf(\"RED\", alice))\n\n\tApprove(cross(cur), \"BLUE\", carl, 250_000)\n\tuassert.Equal(t, int64(250_000), Allowance(\"BLUE\", alice, carl))\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tTransferFrom(cross(cur), \"BLUE\", alice, bob, 250_000)\n\tuassert.Equal(t, int64(250_000), BalanceOf(\"BLUE\", bob))\n\tuassert.Equal(t, int64(0), Allowance(\"BLUE\", alice, carl))\n\tuassert.AbortsContains(t, cur, \"insufficient allowance\", func() {\n\t\tTransferFrom(cross(cur), \"BLUE\", alice, bob, 1)\n\t})\n}\n\nfunc TestUnknownSymbolIsRefused(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"f-unknown\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\n\tuassert.PanicsContains(t, cur, \"unknown symbol GREEN\", func() {\n\t\tBalanceOf(\"GREEN\", who)\n\t})\n\tuassert.AbortsContains(t, cur, \"unknown symbol GREEN\", func() {\n\t\tTransfer(cross(cur), \"GREEN\", who, 1)\n\t})\n}\n\n// Both tokens are in the registry under their own realm and symbol, which is\n// what lets another realm move them without importing this one.\nfunc TestBothTokensAreRegistered(t *testing.T) {\n\tuassert.Equal(t, \"gno.land/r/moul/x/grc20faucet/v0.RED\", RedKey)\n\tuassert.Equal(t, \"gno.land/r/moul/x/grc20faucet/v0.BLUE\", BlueKey)\n\tuassert.Equal(t, \"Red Token\", grc20reg.MustGet(RedKey).GetName())\n\tuassert.Equal(t, \"Blue Token\", grc20reg.MustGet(BlueKey).GetName())\n\tuassert.Equal(t, 4, grc20reg.MustGet(BlueKey).GetDecimals())\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"f-render\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tClaim(cross(cur))\n\n\thome := Render(\"\")\n\tuassert.True(t, strings.Contains(home, \"# GRC20 faucet: RED and BLUE\"), home)\n\tuassert.True(t, strings.Contains(home, \"| Red Token | RED | 4 |\"), home)\n\tuassert.True(t, strings.Contains(home, RedKey), \"the registry key is discoverable\")\n\n\tpage := Render(who.String())\n\tuassert.True(t, strings.Contains(page, \"Balance of\"), page)\n\tuassert.True(t, strings.Contains(page, \"RED 1000000\"), page)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/grc20faucet/v0\"\ngno = \"0.9\"\n\n# public: its init registers the two tokens it owns with r/nt/grc20reg, so\n# this realm's own objects have to be reachable from that one. Measured:\n# with private = true, `make test PKG=grc20faucet` panics with\n# \"cannot persist object from the private realm\".\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"aaa","path":"gno.land/r/moul/x/pairs/aaa/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/pairs/aaa/v0`\n\nA throwaway GRC20 (AAA, 6 decimals) with an **open faucet**, used to exercise\nthe pair instances in this repo. No value, no owner controls, anyone can mint.\n\n`Faucet` mints 1000 AAA to the caller. Registered in `r/nt/grc20reg/v0` at\ndeploy, so its key is `gno.land/r/moul/x/pairs/aaa/v0.AAA`, which is what an\ninstance realm is configured with.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/pairs/aaa/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaa/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/pairs/aaa/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaa/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/pairs/aaa/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaa/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/pairs/aaa/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaa/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/pairs/aaa/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/pairs/aaa/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"aaa.gno","body":"// Package aaa is a throwaway GRC20 with an open faucet, used to exercise the\n// pair instances in this repo. It has no value and no owner controls.\npackage aaa\n\nimport (\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nvar (\n\tToken         *grc20.Token\n\tprivateLedger *grc20.PrivateLedger\n\tuserTeller    grc20.Teller\n)\n\n// Key is this token's grc20reg key, the string an instance realm is\n// configured with.\nconst Key = \"gno.land/r/moul/x/pairs/aaa/v0.AAA\"\n\nfunc init(cur realm) {\n\tToken, privateLedger = grc20.NewToken(\"Test Alpha\", \"AAA\", 6, 0, cur)\n\tuserTeller = privateLedger.CallerTeller()\n\tgrc20reg.Register(cross(cur), Token, \"\")\n}\n\n// Faucet mints a fixed amount to the caller. Unrestricted on purpose.\nfunc Faucet(cur realm) {\n\tif err := privateLedger.Mint(cur.Previous().Address(), 1_000_000_000); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc TotalSupply() int64                      { return userTeller.TotalSupply() }\nfunc BalanceOf(owner address) int64           { return userTeller.BalanceOf(owner) }\nfunc Allowance(owner, spender address) int64  { return userTeller.Allowance(owner, spender) }\n\nfunc Transfer(cur realm, to address, amount int64) {\n\tif err := userTeller.Transfer(0, cur, to, amount); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Approve(cur realm, spender address, amount int64) {\n\tif err := userTeller.Approve(0, cur, spender, amount); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Render(string) string {\n\treturn \"# AAA\\n\\nThrowaway test token for the pair instances. `Faucet` mints 1000 AAA to you.\\n\"\n}\n"},{"name":"aaa_test.gno","body":"package aaa\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestFaucetAndRender(cur realm, t *testing.T) {\n\tuser := testutils.TestAddress(\"aaa-user\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tFaucet(cross(cur))\n\tuassert.Equal(t, int64(1_000_000_000), BalanceOf(user))\n\n\tuassert.True(t, strings.Contains(Render(\"\"), \"# AAA\"))\n\tuassert.Equal(t, \"gno.land/r/moul/x/pairs/aaa/v0.AAA\", Key)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/pairs/aaa/v0\"\ngno = \"0.9\"\n\n# public: a demo GRC20 whose whole purpose is to be imported by a pair\n# instance, and whose token object is registered with r/nt/grc20reg.\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pairreg","path":"gno.land/r/moul/x/pairreg/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/pairreg/v0`\n\nThe registry every AMM pair instance announces itself to, and the unified\nfrontend over all of them. Third artifact of the instance-per-realm pattern; the\nlogic is in [`p/moul/x/pair/v0`](../../../../p/moul/x/pair/v0).\n\n- **Registration is one line in an instance's `init`**, so a single `addpkg`\n  both creates a pair and lists it.\n- **The key is the caller's own package path**, taken from\n  `cur.Previous().PkgPath()`, so an instance cannot claim a path that is not its\n  own.\n- **Entries hold a live `*pair.Pair`**, not an address, so `Render` shows every\n  instance's real reserves from one `vm/qrender`. No indexer, no multicall.\n- **Permissionless**, and spam is self funded: the registering transaction pays\n  for the storage it adds.\n\n## What it cannot tell you\n\nNothing on chain can read a package's source, so the registry cannot check that\nan instance runs the shared template. Reserves shown in the index are **claimed**.\nSeveral instances may exist for the same couple, on purpose: there is no\ncanonical pair and no factory to enforce one. Verify an instance by diffing its\nsource (`vm/qfile`) against freshly generated output before funding it.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/pairreg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairreg/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/pairreg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairreg/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/pairreg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairreg/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/pairreg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairreg/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/pairreg/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/pairreg/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/pairreg/v0\"\ngno = \"0.9\"\n\n# public: every pair instance imports it to announce itself, and holds the\n# *pair.Pair it registers here. A private realm cannot be imported at all.\n"},{"name":"pairreg.gno","body":"// Package pairreg is the registry every AMM pair instance announces itself to,\n// and the unified frontend over all of them.\n//\n// It is the third artifact of the instance-per-realm pattern: one shared\n// p/moul/x/pair/v0 holding the logic, N tiny realms holding one pair each, and\n// this realm knowing all of them.\n//\n// # Why registration cannot be faked, and code cannot be trusted\n//\n// Register keys an instance by cur.Previous().PkgPath(), which the runtime\n// supplies, so an instance cannot claim a path that is not its own. That is\n// the whole on-chain guarantee. It is NOT a guarantee about the code at that\n// path: gno has no way to read another package's source from inside a realm,\n// so nothing here can check that an instance really runs the shared template.\n// The mirror image of Ethereum's CREATE2, which proves the code and says\n// nothing legible about who deployed it.\n//\n// Consequences a reader of the index must keep in mind:\n//\n//   - Reserves shown here are CLAIMED. They are read live from the instance's\n//     own struct, which is honest for an instance running the template and\n//     arbitrary for one that does not.\n//   - Several instances may exist for the same token couple. That is allowed\n//     on purpose; there is no canonical pair and no factory to enforce one.\n//   - Approving tokens to an instance risks exactly what was approved. Read\n//     the instance's source (vm/qfile on its path) before funding it.\n//\n// # Why the registry can read live state at all\n//\n// Instances register a *pair.Pair pointer, not an address, the way grc20reg\n// registers a *grc20.Token. One vm/qrender here therefore renders the real\n// state of every instance, with no indexer and no multicall. It is safe\n// because pair.Pair holds only concrete types: an interface or a func field\n// would let a hostile instance hand foreign code to this realm's frame.\npackage pairreg\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/pair/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Entry is one registered instance.\ntype Entry struct {\n\tPath   string     // the instance realm's package path, supplied by the runtime\n\tPair   *pair.Pair // live pointer into the instance's own storage\n\tHeight int64      // chain height at registration\n}\n\n// entries maps instance path -\u003e *Entry. couples maps a pair ID\n// (\"keyA~keyB\") -\u003e int, how many instances claim that couple.\nvar (\n\tentries avl.Tree\n\tcouples avl.Tree\n)\n\n// Register records the calling realm as an instance. Call it from the\n// instance's init, so that deploying and listing are one transaction:\n//\n//\tfunc init(cur realm) {\n//\t\tp = pair.New(keyA, keyB, grc20reg.MustGet(keyA), grc20reg.MustGet(keyB))\n//\t\tpairreg.Register(cross(cur), p)\n//\t}\n//\n// Permissionless by design: anyone may deploy an instance under their own\n// address namespace and land here. Spam is self funded, since the registering\n// transaction pays for the storage it adds.\nfunc Register(cur realm, p *pair.Pair) {\n\tcaller := cur.Previous()\n\tpath := caller.PkgPath()\n\tif path == \"\" {\n\t\tpanic(\"pairreg: only a realm can register\")\n\t}\n\tif p == nil {\n\t\tpanic(\"pairreg: nil pair\")\n\t}\n\tif entries.Has(path) {\n\t\tpanic(\"pairreg: already registered: \" + path)\n\t}\n\n\tentries.Set(path, \u0026Entry{Path: path, Pair: p, Height: runtime.ChainHeight()})\n\tcouples.Set(p.ID(), countFor(p.ID())+1)\n\n\tchain.Emit(\"RegisterPair\",\n\t\t\"path\", path,\n\t\t\"pair\", p.ID(),\n\t)\n}\n\n// Get returns the entry for an instance path, or nil.\nfunc Get(path string) *Entry {\n\tv := entries.Get(path)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Entry)\n}\n\n// Size returns how many instances are registered.\nfunc Size() int { return entries.Size() }\n\n// Couples returns how many distinct token couples are represented.\nfunc Couples() int { return couples.Size() }\n\n// InstancesFor returns the instance paths claiming a given couple id.\nfunc InstancesFor(id string) []string {\n\tout := []string{}\n\tentries.Iterate(\"\", \"\", func(_ string, value any) bool {\n\t\te := value.(*Entry)\n\t\tif e.Pair.ID() == id {\n\t\t\tout = append(out, e.Path)\n\t\t}\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Render is the unified frontend: the index of every instance with its live\n// state, or one instance's own page when path is an instance path.\nfunc Render(path string) string {\n\tif path != \"\" {\n\t\te := Get(path)\n\t\tif e == nil {\n\t\t\treturn \"# 404\\n\\nNo instance registered at `\" + path + \"`.\\n\"\n\t\t}\n\t\tout := e.Pair.Render(\"\")\n\t\tout += \"\\n---\\n\\n\"\n\t\tout += ufmt.Sprintf(\"Instance: [`%s`](%s) · registered at height %d · %d instance(s) claim this couple.\\n\",\n\t\t\te.Path, webPath(e.Path), e.Height, countFor(e.Pair.ID()))\n\t\treturn out\n\t}\n\n\tout := \"# AMM pairs\\n\\n\"\n\tout += \"One realm per token couple, all running [p/moul/x/pair/v0](/p/moul/x/pair/v0). \"\n\tout += \"Anyone can deploy one under their own namespace and it lands here.\\n\\n\"\n\n\tif entries.Size() == 0 {\n\t\tout += \"_No instance yet._\\n\"\n\t\treturn out\n\t}\n\n\tout += ufmt.Sprintf(\"%d instance(s), %d couple(s).\\n\\n\", entries.Size(), couples.Size())\n\tout += \"**Reserves below are claimed by each instance, not verified.** \"\n\tout += \"Nothing on chain can check that an instance runs the shared template; read its source before funding it.\\n\\n\"\n\tout += \"| pair | reserves | LP shares | providers | instance |\\n\"\n\tout += \"|---|---|---|---|---|\\n\"\n\tentries.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\te := value.(*Entry)\n\t\tsymA, symB := e.Pair.Symbols()\n\t\tresA, resB := e.Pair.Reserves()\n\t\tout += ufmt.Sprintf(\"| [%s/%s](/r/moul/x/pairreg/v0:%s) | %d %s / %d %s | %d | %d | [`%s`](%s) |\\n\",\n\t\t\tsymA, symB, key,\n\t\t\tresA, symA, resB, symB,\n\t\t\te.Pair.TotalShares(), e.Pair.Providers(),\n\t\t\tshortPath(e.Path), webPath(e.Path))\n\t\treturn false\n\t})\n\treturn out\n}\n\n//\n// Internals.\n//\n\nfunc countFor(id string) int {\n\tv := couples.Get(id)\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(int)\n}\n\n// webPath turns a package path into a gnoweb link.\nfunc webPath(pkgPath string) string {\n\tif i := strings.Index(pkgPath, \"/\"); i \u003e= 0 {\n\t\treturn pkgPath[i:]\n\t}\n\treturn \"/\" + pkgPath\n}\n\n// shortPath drops the chain domain, which is the same on every row.\nfunc shortPath(pkgPath string) string {\n\tif i := strings.Index(pkgPath, \"/\"); i \u003e= 0 {\n\t\treturn pkgPath[i+1:]\n\t}\n\treturn pkgPath\n}\n"},{"name":"pairreg_test.gno","body":"package pairreg\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Loaded on its own, the registry has no instances: the index says so rather\n// than rendering an empty table.\nfunc TestRenderEmpty(t *testing.T) {\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"# AMM pairs\"))\n\tuassert.True(t, strings.Contains(out, \"No instance yet\"))\n\tuassert.Equal(t, 0, Size())\n\tuassert.Equal(t, 0, Couples())\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tout := Render(\"gno.land/r/nope/v0\")\n\tuassert.True(t, strings.Contains(out, \"# 404\"))\n\tuassert.True(t, Get(\"gno.land/r/nope/v0\") == nil)\n\tuassert.Equal(t, 0, len(InstancesFor(\"a~b\")))\n}\n\n// A gnoweb link is the package path minus the chain domain.\nfunc TestWebPath(t *testing.T) {\n\tuassert.Equal(t, \"/r/moul/x/pairs/aaabbb/v0\", webPath(\"gno.land/r/moul/x/pairs/aaabbb/v0\"))\n\tuassert.Equal(t, \"r/moul/x/pairs/aaabbb/v0\", shortPath(\"gno.land/r/moul/x/pairs/aaabbb/v0\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bbb","path":"gno.land/r/moul/x/pairs/bbb/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/pairs/bbb/v0`\n\nA throwaway GRC20 (BBB, 6 decimals) with an **open faucet**, used to exercise\nthe pair instances in this repo. No value, no owner controls, anyone can mint.\n\n`Faucet` mints 1000 BBB to the caller. Registered in `r/nt/grc20reg/v0` at\ndeploy, so its key is `gno.land/r/moul/x/pairs/bbb/v0.BBB`, which is what an\ninstance realm is configured with.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/pairs/bbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/bbb/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/pairs/bbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/bbb/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/pairs/bbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/bbb/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/pairs/bbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/bbb/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/pairs/bbb/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/pairs/bbb/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bbb.gno","body":"// Package bbb is a throwaway GRC20 with an open faucet, used to exercise the\n// pair instances in this repo. It has no value and no owner controls.\npackage bbb\n\nimport (\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\nvar (\n\tToken         *grc20.Token\n\tprivateLedger *grc20.PrivateLedger\n\tuserTeller    grc20.Teller\n)\n\n// Key is this token's grc20reg key, the string an instance realm is\n// configured with.\nconst Key = \"gno.land/r/moul/x/pairs/bbb/v0.BBB\"\n\nfunc init(cur realm) {\n\tToken, privateLedger = grc20.NewToken(\"Test Beta\", \"BBB\", 6, 1, cur)\n\tuserTeller = privateLedger.CallerTeller()\n\tgrc20reg.Register(cross(cur), Token, \"\")\n}\n\n// Faucet mints a fixed amount to the caller. Unrestricted on purpose.\nfunc Faucet(cur realm) {\n\tif err := privateLedger.Mint(cur.Previous().Address(), 1_000_000_000); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc TotalSupply() int64                      { return userTeller.TotalSupply() }\nfunc BalanceOf(owner address) int64           { return userTeller.BalanceOf(owner) }\nfunc Allowance(owner, spender address) int64  { return userTeller.Allowance(owner, spender) }\n\nfunc Transfer(cur realm, to address, amount int64) {\n\tif err := userTeller.Transfer(0, cur, to, amount); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Approve(cur realm, spender address, amount int64) {\n\tif err := userTeller.Approve(0, cur, spender, amount); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Render(string) string {\n\treturn \"# BBB\\n\\nThrowaway test token for the pair instances. `Faucet` mints 1000 BBB to you.\\n\"\n}\n"},{"name":"bbb_test.gno","body":"package bbb\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestFaucetAndRender(cur realm, t *testing.T) {\n\tuser := testutils.TestAddress(\"bbb-user\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tFaucet(cross(cur))\n\tuassert.Equal(t, int64(1_000_000_000), BalanceOf(user))\n\n\tuassert.True(t, strings.Contains(Render(\"\"), \"# BBB\"))\n\tuassert.Equal(t, \"gno.land/r/moul/x/pairs/bbb/v0.BBB\", Key)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/pairs/bbb/v0\"\ngno = \"0.9\"\n\n# public: a demo GRC20 whose whole purpose is to be imported by a pair\n# instance, and whose token object is registered with r/nt/grc20reg.\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"572647400","gas_fee":"1717942ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"lVkS5VT3pL72cx8AGRDD91wtO5QN7jz2JAqrUjSghB4N0mHIA8jf9UcjbzuiIz+OoAwx+G1poQhiLYGMGfhE6Q=="}],"memo":""},"metadata":{"timestamp":"1790960642"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"aaabbb","path":"gno.land/r/moul/x/pairs/aaabbb/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/pairs/aaabbb/v0`\n\nOne AMM pair, AAA/BBB, and nothing else: the worked example of an instance realm.\n\nRead the file, it is the point. Two constants, an `init` that builds the pair and\nregisters it, and one-line re-exports forwarding `cur` into\n[`p/moul/x/pair/v0`](../../../../../p/moul/x/pair/v0). It is `tools/pairgen`\noutput, differing only in its doc comment and in two blank imports that force the\nin-repo test tokens to initialise first (an instance deployed against\nalready-deployed tokens needs neither).\n\n```sh\ngo -C tools run ./pairgen gno.land/r/moul/x/pairs/aaa/v0.AAA \\\n    gno.land/r/moul/x/pairs/bbb/v0.BBB -o /tmp/out -namespace moul/x/pairs\ndiff /tmp/out/aaabbb/aaabbb.gno r/moul/x/pairs/aaabbb/aaabbb.gno\n```\n\nTrades against the two throwaway faucet tokens `r/moul/x/pairs/aaa/v0` and\n`r/moul/x/pairs/bbb/v0`. Neither has any value.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/pairs/aaabbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaabbb/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/pairs/aaabbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaabbb/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/pairs/aaabbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaabbb/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/pairs/aaabbb/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pairs/aaabbb/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/pairs/aaabbb/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/pairs/aaabbb/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"aaabbb.gno","body":"// Realm aaabbb is ONE AMM pair, AAA/BBB, and nothing else.\n//\n// This is the whole instance half of the instance-per-realm pattern, and it is\n// meant to be read in full in one screen: two configuration constants, an init\n// that builds the pair and announces it to the registry, and one-line\n// re-exports that forward the realm's own `cur` into the shared logic in\n// p/moul/x/pair/v0. Every instance in the ecosystem is byte-identical to this\n// file except for the two constants, which is what makes verifying an\n// unknown instance a two-line diff.\n//\n// The re-exports cannot be factored away: MsgCall addresses a realm path and a\n// function name, so anything a user calls has to be declared here.\n//\n// State and funds belong to THIS realm: the pair struct is its variable, the\n// tokens sit at its own package address, and its creator paid its storage\n// deposit. A bug in one instance cannot touch another.\n//\n// Pattern, and why an AMM is the contested case for it: see the README of\n// gno.land/p/moul/x/pair/v0.\npackage aaabbb\n\nimport (\n\t\"gno.land/p/moul/x/pair/v0\"\n\t\"gno.land/r/moul/x/pairreg/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n\n\t// Only because both tokens live in this same repository: the blank imports\n\t// force their init (and therefore their grc20reg registration) to run\n\t// before this one in a test binary. An instance deployed on chain against\n\t// already-deployed tokens does not need them.\n\t_ \"gno.land/r/moul/x/pairs/aaa/v0\"\n\t_ \"gno.land/r/moul/x/pairs/bbb/v0\"\n)\n\n// The only two lines that differ between two instances.\nconst (\n\tkeyA = \"gno.land/r/moul/x/pairs/aaa/v0.AAA\"\n\tkeyB = \"gno.land/r/moul/x/pairs/bbb/v0.BBB\"\n)\n\nvar p *pair.Pair\n\nfunc init(cur realm) {\n\tp = pair.New(keyA, keyB, grc20reg.MustGet(keyA), grc20reg.MustGet(keyB))\n\tpairreg.Register(cross(cur), p)\n}\n\nfunc AddLiquidity(cur realm, maxA, maxB int64) int64 { return p.AddLiquidity(0, cur, maxA, maxB) }\n\nfunc RemoveLiquidity(cur realm, shares int64) (int64, int64) {\n\treturn p.RemoveLiquidity(0, cur, shares)\n}\n\nfunc Swap(cur realm, keyIn string, amountIn, minOut int64) int64 {\n\treturn p.Swap(0, cur, keyIn, amountIn, minOut)\n}\n\nfunc Quote(keyIn string, amountIn int64) int64 { return p.Quote(keyIn, amountIn) }\nfunc Reserves() (int64, int64)                 { return p.Reserves() }\nfunc SharesOf(owner address) int64             { return p.SharesOf(owner) }\nfunc TotalShares() int64                       { return p.TotalShares() }\nfunc Keys() (string, string)                   { return p.Keys() }\nfunc Render(path string) string                { return p.Render(path) }\n"},{"name":"aaabbb_test.gno","body":"package aaabbb\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/moul/x/pairreg/v0\"\n\t\"gno.land/r/moul/x/pairs/aaa/v0\"\n\t\"gno.land/r/moul/x/pairs/bbb/v0\"\n)\n\nconst selfPath = \"gno.land/r/moul/x/pairs/aaabbb/v0\"\n\nfunc self() address { return chain.PackageAddress(selfPath) }\n\n// fund gives addr both tokens and approves this instance to spend them.\nfunc fund(cur realm, addr address) {\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\taaa.Faucet(cross(cur))\n\tbbb.Faucet(cross(cur))\n\taaa.Approve(cross(cur), self(), 1_000_000_000)\n\tbbb.Approve(cross(cur), self(), 1_000_000_000)\n}\n\n// Deploying the instance is the whole \"factory call\": its init builds the pair\n// and announces it, so one addpkg both creates and lists it.\nfunc TestSelfRegisteredAtInit(t *testing.T) {\n\te := pairreg.Get(selfPath)\n\tuassert.True(t, e != nil, \"instance must register itself in init\")\n\tuassert.Equal(t, selfPath, e.Path)\n\tuassert.Equal(t, 1, pairreg.Size())\n\n\tkeyA, keyB := Keys()\n\tuassert.Equal(t, \"gno.land/r/moul/x/pairs/aaa/v0.AAA\", keyA)\n\tuassert.Equal(t, \"gno.land/r/moul/x/pairs/bbb/v0.BBB\", keyB)\n}\n\n// The registry holds a live pointer into this realm's storage, so its own\n// Render shows state it never copied. This is the property that lets one\n// qrender describe a thousand instances.\nfunc TestRegistrySeesLiveState(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice-live\")\n\tfund(cur, alice)\n\tAddLiquidity(cross(cur), 1_000_000, 4_000_000)\n\n\te := pairreg.Get(selfPath)\n\tresA, resB := e.Pair.Reserves()\n\tuassert.Equal(t, int64(1_000_000), resA)\n\tuassert.Equal(t, int64(4_000_000), resB)\n\n\tindex := pairreg.Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"AAA/BBB\"), \"index lists the couple\")\n\tuassert.True(t, strings.Contains(index, \"1000000 AAA\"), \"index shows live reserves\")\n\tuassert.True(t, strings.Contains(index, \"moul/x/pairs/aaabbb/v0\"), \"index links the instance\")\n\n\t// Wind the pair back down so the next test starts from an empty pool.\n\tRemoveLiquidity(cross(cur), TotalShares())\n}\n\n// Full lifecycle through the instance's own entry points, which is also the\n// proof that funds move to and from THIS realm's address while every line of\n// logic runs in the shared pure package.\nfunc TestLifecycle(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice-cycle\")\n\tfund(cur, alice)\n\n\tminted := AddLiquidity(cross(cur), 1_000_000, 4_000_000)\n\tuassert.Equal(t, int64(1_000_000), minted, \"first deposit mints amountA, no sqrt\")\n\tuassert.Equal(t, int64(1_000_000), aaa.BalanceOf(self()), \"tokens land on the instance\")\n\tuassert.Equal(t, int64(4_000_000), bbb.BalanceOf(self()))\n\tuassert.Equal(t, minted, SharesOf(alice))\n\n\tquoted := Quote(\"gno.land/r/moul/x/pairs/aaa/v0.AAA\", 100_000)\n\tout := Swap(cross(cur), \"gno.land/r/moul/x/pairs/aaa/v0.AAA\", 100_000, 362_000)\n\tuassert.Equal(t, int64(362_644), out, \"same pricing as the single-realm design\")\n\tuassert.Equal(t, quoted, out, \"Quote matches what Swap pays\")\n\n\tresA, resB := Reserves()\n\tuassert.Equal(t, int64(1_100_000), resA)\n\tuassert.Equal(t, int64(3_637_356), resB)\n\n\tgotA, gotB := RemoveLiquidity(cross(cur), 500_000)\n\tuassert.Equal(t, int64(550_000), gotA)\n\tuassert.Equal(t, int64(1_818_678), gotB)\n\n\t// The last provider out is paid the whole reserve, so nothing is stranded.\n\tgotA, gotB = RemoveLiquidity(cross(cur), TotalShares())\n\tuassert.Equal(t, int64(550_000), gotA)\n\tuassert.Equal(t, int64(1_818_678), gotB)\n\tuassert.Equal(t, int64(0), TotalShares())\n\tuassert.Equal(t, int64(0), aaa.BalanceOf(self()), \"instance holds nothing afterwards\")\n\tuassert.Equal(t, int64(0), bbb.BalanceOf(self()))\n}\n\n// A token this pair does not hold must be refused by name, not silently\n// treated as one of the two sides. Asserted through Quote, which reaches the\n// same guard without a crossing call: a panic raised inside a crossing call\n// unwinds the whole transaction and is not recoverable by the caller.\nfunc TestRejectsForeignToken(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice-foreign\")\n\tfund(cur, alice)\n\tAddLiquidity(cross(cur), 1_000_000, 4_000_000)\n\n\tuassert.PanicsWithMessage(t, cur, \"pair: gno.land/r/nope/v0.NOPE is not in this pair\", func() {\n\t\tQuote(\"gno.land/r/nope/v0.NOPE\", 1_000)\n\t})\n\tRemoveLiquidity(cross(cur), TotalShares())\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice-render\")\n\tfund(cur, alice)\n\n\tempty := Render(\"\")\n\tuassert.True(t, strings.Contains(empty, \"# AAA / BBB\"))\n\tuassert.True(t, strings.Contains(empty, \"Empty\"), \"empty pair says so\")\n\n\tAddLiquidity(cross(cur), 1_000_000, 4_000_000)\n\tfull := Render(\"\")\n\tuassert.True(t, strings.Contains(full, \"| AAA | 1000000 |\"), \"reserves row\")\n\tuassert.True(t, strings.Contains(full, \"LP shares: **1000000**\"))\n\tuassert.True(t, strings.Contains(full, \"1 AAA buys ~4 BBB\"), \"spot line\")\n\tRemoveLiquidity(cross(cur), TotalShares())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/pairs/aaabbb/v0\"\ngno = \"0.9\"\n\n# public: its init registers the *pair.Pair it owns with r/moul/x/pairreg,\n# so this realm's own objects have to be reachable from that one. That\n# hand-off is the whole point of the instance-per-realm shape.\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"38130000","gas_fee":"114390ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"xT9mUdSwxOo3ZT5UCCv8NSIxH7ISU8bMGAbFh4qOzkZWPbFDzcmFDgSfJl3zQ8VxYq4tFifHy8SJK4yLqx3fCQ=="}],"memo":""},"metadata":{"timestamp":"1790960643"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"across","path":"gno.land/r/moul/x/across/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/across/v0`\n\nOne address, read across fifteen realms that were already on chain.\n\nOpen `/r/moul/x/across/v0:\u003caddress\u003e` and the page answers with everything fifteen\nother realms will say about that address: token balances, an LP position, stake\nand unclaimed rewards, a check-in streak, dice rolled, a rate-limit bucket, a\nlottery entry, a reaction. Rows that came back empty are counted and hidden.\n\n## What it is demonstrating\n\nNot one of the fifteen source realms was changed. None of them knows this realm\nexists, none of them registered anywhere, and there is no shared interface, no\nbase package, no version handshake. The only thing every source had to do was\n**not** declare `private = true` in its `gnomod.toml`, which is what lets another\nrealm import it at all.\n\nThat is the composability claim in its weakest, most testable form: a realm's\nexported reads are a permanent public API, because the path it lives at can never\nbe replaced. What you compile against today is what is on chain forever.\n\n## What it cost\n\nEight of the sources hold a per-address balance. They agree on nothing:\n\n| realm | signature |\n| --- | --- |\n| `r/moul/x/daily/erc20/v0`, `…/vestoken/v0`, `…/wrapped/v0` | `BalanceOf(address) uint64` |\n| `r/moul/x/pairs/aaa/v0`, `…/bbb/v0` | `BalanceOf(address) int64` |\n| `r/moul/x/grc20faucet/v0` | `BalanceOf(symbol string, owner address) int64` |\n| `r/moul/demo/wikicoin/v0` | `BalanceOf(address) uint` |\n| `r/moul/x/daily/dice/v0` | `RollsOf(addr string) []int` |\n\nThree integer widths, two signednesses, one that wants a symbol before the\naddress, one that wants the address as a `string`. Composition still works, it\njust costs one hand-written adapter line per source. `Report` is those lines and\nnothing else, which is also why this realm ships no `p/` library: extract one and\nboth halves are empty.\n\n## The two sources that could not be read\n\n- **`r/moul/x/amm/v0`** exports `SharesOf(keyA, keyB string, owner address)`,\n  which routes through a helper that **panics** on an unknown pool. A getter that\n  panics is not composable: one panicking source takes down a page assembled from\n  fifteen, and `recover()` does not catch a cross-realm abort. Only its\n  `PoolCount()` is called from here.\n- **`r/moul/demo/vault/v0`** exports `MyBalance()` with no address parameter, so\n  it answers for its caller, which from here is this realm.\n\nNeither is a bug. Both are what a getter looks like before anyone has tried to\ncall it from another realm.\n\n## Private by default, and why this one is too\n\n`private = true`, the repo default, because nothing needs to import *this* realm.\nThe flag is a one-way door decided before the first publish, and it is the single\nthing that determines whether a realm can ever appear in a page like this one.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/across/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/across/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/across/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/across/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/across/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/across/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/across/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/across/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/across/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/across/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"across.gno","body":"// Package across reads one address across fifteen other realms that are\n// already live, and renders everything they will say about it on one page.\n//\n// It is a composability demo with a working product hiding inside it. The\n// realms it reads were written months apart, by nobody coordinating, and none\n// of them knows this one exists. Not a line of them changed to make this\n// possible: the only requirement any of them had to meet was NOT declaring\n// `private = true`, which is what lets another realm import it at all.\n//\n// # Why this realm holds no state and extracts no library\n//\n// Every other realm here splits into a pure `p/` and a thin `r/`. This one\n// cannot, and that is the point: its entire content is the wiring. Fifteen\n// import lines, one call each, and a table. Extract a library and what is left\n// on both sides is empty.\n//\n// # What it measures, besides balances\n//\n// The signatures below are the honest half of the demo. Eight of these realms\n// hold a per-address balance and they agree on nothing:\n//\n//\terc20, vestoken, wrapped     BalanceOf(address) uint64\n//\tpairs/aaa, pairs/bbb         BalanceOf(address) int64\n//\tgrc20faucet                  BalanceOf(symbol string, owner address) int64\n//\twikicoin                     BalanceOf(address) uint\n//\tdice                         RollsOf(addr string) []int\n//\n// Three integer widths, two signednesses, one that takes the address as a\n// string, one that needs a symbol first. Composition works anyway, because a\n// gno import is a type-checked contract with a permanent artifact behind it and\n// not a call convention anyone has to agree on in advance. It just costs one\n// hand-written adapter per source, which is what the report function is.\n//\n// # The two sources that could not be read\n//\n//   - r/moul/x/amm/v0 exports SharesOf(keyA, keyB string, owner address), and\n//     it routes through mustPool, which PANICS when the pool does not exist.\n//     A getter that panics is not composable: fifteen sources on one page means\n//     one panicking source takes the whole page down, and a wrapper cannot\n//     recover, because recover() does not catch a cross-realm abort. So amm\n//     contributes PoolCount() to the index and nothing to a report.\n//   - r/moul/demo/vault/v0 exports MyBalance() with no address parameter. It\n//     answers for whoever is calling, which from here is this realm, so the\n//     value is structurally unreadable from outside.\n//\n// Neither is a bug in those realms. Both are what a getter looks like when\n// nobody has tried to call it from another realm yet.\npackage across\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\n\t\"gno.land/r/moul/demo/wikicoin/v0\"\n\t\"gno.land/r/moul/reactions/v0\"\n\t\"gno.land/r/moul/x/amm/v0\"\n\t\"gno.land/r/moul/x/daily/dice/v0\"\n\t\"gno.land/r/moul/x/daily/erc20/v0\"\n\t\"gno.land/r/moul/x/daily/lottery/v0\"\n\t\"gno.land/r/moul/x/daily/ratelimitdemo/v0\"\n\t\"gno.land/r/moul/x/daily/staking/v0\"\n\t\"gno.land/r/moul/x/daily/streak/v0\"\n\t\"gno.land/r/moul/x/daily/vestoken/v0\"\n\t\"gno.land/r/moul/x/daily/wrapped/v0\"\n\t\"gno.land/r/moul/x/grc20faucet/v0\"\n\t\"gno.land/r/moul/x/pairs/aaa/v0\"\n\t\"gno.land/r/moul/x/pairs/aaabbb/v0\"\n\t\"gno.land/r/moul/x/pairs/bbb/v0\"\n)\n\n// reactionPage is the page key handed to r/moul/reactions. Reactions are keyed\n// on an arbitrary page string rather than on a realm, so a reader of this\n// report is asked about the same page /u/moul shows.\nconst reactionPage = \"gno.land/r/moul/home\"\n\n// Self is this realm's own package path, exported so a caller can build a link\n// back without hardcoding the version.\nconst Self = \"gno.land/r/moul/x/across/v0\"\n\n// A fact is one answer from one source realm about one address.\n//\n// zero is carried separately from value because \"0\" and \"none\" are the common\n// answer and the table is worth reading only for the rows that are not that.\ntype fact struct {\n\tsource string // package path, without the gno.land/ prefix\n\twhat   string\n\tvalue  string\n\tzero   bool\n}\n\n// Report collects what every wired source says about who.\n//\n// Every call in here is a plain exported read on another realm: no cur realm,\n// no cross, nothing written. A read with no realm parameter is borrowed rather\n// than entered (AGENTS.md), so none of these realms even observes a caller.\nfunc Report(who address) []fact {\n\tout := []fact{}\n\n\tadd := func(source, what string, n int64, unit string) {\n\t\tv := strconv.FormatInt(n, 10)\n\t\tif unit != \"\" {\n\t\t\tv += \" \" + unit\n\t\t}\n\t\tout = append(out, fact{source: source, what: what, value: v, zero: n == 0})\n\t}\n\n\t// Balances. Eight sources, five signatures.\n\tadd(\"r/moul/x/daily/erc20/v0\", \"balance\", int64(erc20.BalanceOf(who)), erc20.Symbol())\n\tadd(\"r/moul/x/daily/vestoken/v0\", \"liquid balance\", int64(vestoken.BalanceOf(who)), vestoken.Symbol())\n\tadd(\"r/moul/x/daily/wrapped/v0\", \"wrapped balance\", int64(wrapped.BalanceOf(who)), \"WGNOT\")\n\tadd(\"r/moul/demo/wikicoin/v0\", \"balance\", int64(wikicoin.BalanceOf(who)), \"WIKI\")\n\tadd(\"r/moul/x/pairs/aaa/v0\", \"balance\", aaa.BalanceOf(who), \"AAA\")\n\tadd(\"r/moul/x/pairs/bbb/v0\", \"balance\", bbb.BalanceOf(who), \"BBB\")\n\tadd(\"r/moul/x/grc20faucet/v0\", \"balance\", grc20faucet.BalanceOf(\"RED\", who), \"RED\")\n\tadd(\"r/moul/x/grc20faucet/v0\", \"balance\", grc20faucet.BalanceOf(\"BLUE\", who), \"BLUE\")\n\n\t// A grant is three numbers, so it does not fit the add helper.\n\ttotal, claimed, claimable := vestoken.GrantOf(who)\n\tout = append(out, fact{\n\t\tsource: \"r/moul/x/daily/vestoken/v0\",\n\t\twhat:   \"vesting grant\",\n\t\tvalue: strconv.FormatUint(total, 10) + \" total, \" +\n\t\t\tstrconv.FormatUint(claimed, 10) + \" claimed, \" +\n\t\t\tstrconv.FormatUint(claimable, 10) + \" claimable\",\n\t\tzero: total == 0,\n\t})\n\n\t// Positions.\n\tadd(\"r/moul/x/pairs/aaabbb/v0\", \"LP shares\", aaabbb.SharesOf(who), \"\")\n\tadd(\"r/moul/x/daily/staking/v0\", \"staked\", int64(staking.StakedOf(who)), \"\")\n\tadd(\"r/moul/x/daily/staking/v0\", \"unclaimed rewards\", int64(staking.Earned(who)), \"\")\n\n\t// Activity.\n\tadd(\"r/moul/x/daily/streak/v0\", \"current streak\", int64(streak.Current(who)), \"day(s)\")\n\tadd(\"r/moul/x/daily/streak/v0\", \"best streak\", int64(streak.Best(who)), \"day(s)\")\n\tadd(\"r/moul/x/daily/dice/v0\", \"dice rolled\", int64(len(dice.RollsOf(who.String()))), \"\")\n\tadd(\"r/moul/x/daily/ratelimitdemo/v0\", \"rate-limit tokens left\", int64(ratelimitdemo.Tokens(who)), \"\")\n\n\tentered := \"no\"\n\tif lottery.HasEntered(who) {\n\t\tentered = \"yes, round \" + strconv.Itoa(lottery.CurrentRound())\n\t}\n\tout = append(out, fact{\n\t\tsource: \"r/moul/x/daily/lottery/v0\",\n\t\twhat:   \"entered the lottery\",\n\t\tvalue:  entered,\n\t\tzero:   !lottery.HasEntered(who),\n\t})\n\n\t// reactions answers with a palette key, already validated at write time, so\n\t// it never carries caller markdown into this table.\n\treact := reactions.ReactionOf(reactionPage, who)\n\tshown := react\n\tif shown == \"\" {\n\t\tshown = \"none\"\n\t}\n\tout = append(out, fact{\n\t\tsource: \"r/moul/reactions/v0\",\n\t\twhat:   \"reaction on \" + reactionPage,\n\t\tvalue:  shown,\n\t\tzero:   react == \"\",\n\t})\n\n\treturn out\n}\n\n// sourceRealms is every realm this one imports for its data, in import order.\n// It is the single place the count comes from: the index table has one row per\n// entry and TestSourcesCoverReport checks that Report names nothing else.\n//\n// Fifteen entries, which is the number the prose says. TestSourceCount pins it.\nvar sourceRealms = []string{\n\t\"r/moul/x/daily/erc20/v0\",\n\t\"r/moul/x/daily/vestoken/v0\",\n\t\"r/moul/x/daily/wrapped/v0\",\n\t\"r/moul/demo/wikicoin/v0\",\n\t\"r/moul/x/pairs/aaa/v0\",\n\t\"r/moul/x/pairs/bbb/v0\",\n\t\"r/moul/x/grc20faucet/v0\",\n\t\"r/moul/x/pairs/aaabbb/v0\",\n\t\"r/moul/x/amm/v0\",\n\t\"r/moul/x/daily/staking/v0\",\n\t\"r/moul/x/daily/streak/v0\",\n\t\"r/moul/x/daily/dice/v0\",\n\t\"r/moul/x/daily/lottery/v0\",\n\t\"r/moul/x/daily/ratelimitdemo/v0\",\n\t\"r/moul/reactions/v0\",\n}\n\n// Sources reports how many realms this one reads.\nfunc Sources() int { return len(sourceRealms) }\n\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\taddr := address(path)\n\tif !addr.IsValid() {\n\t\treturn \"# across\\n\\n\" + ui.Empty(ui.Inline(ui.Short(path))+\" is not a valid address.\") +\n\t\t\t\"\\n[back to the index](/r/moul/x/across/v0)\\n\"\n\t}\n\treturn renderAddress(addr)\n}\n\nfunc renderAddress(who address) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# across: \" + ui.AddrFull(who) + \"\\n\\n\")\n\tb.WriteString(\"What \" + strconv.Itoa(Sources()) + \" independently deployed realms say about this address. \")\n\tb.WriteString(\"None of them was changed to answer.\\n\\n\")\n\n\tfacts := Report(who)\n\n\tlive := ui.NewTable(\"source\", \"fact\", \"value\")\n\tquiet := 0\n\tfor _, f := range facts {\n\t\tif f.zero {\n\t\t\tquiet++\n\t\t\tcontinue\n\t\t}\n\t\tlive.Row(\"[`\"+f.source+\"`](/\"+f.source+\")\", f.what, f.value)\n\t}\n\n\tif live.Len() == 0 {\n\t\tb.WriteString(ui.Empty(\"Every one of the \" + strconv.Itoa(len(facts)) +\n\t\t\t\" reads came back empty. This address has never touched any of them.\"))\n\t\tb.WriteString(\"\\n\")\n\t} else {\n\t\tb.WriteString(\"## Answers\\n\\n\")\n\t\tb.WriteString(live.String())\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(strconv.Itoa(quiet) + \" of \" + strconv.Itoa(len(facts)) +\n\t\t\t\" reads came back empty and are hidden.\\n\\n\")\n\t}\n\n\tb.WriteString(\"[back to the index](/r/moul/x/across/v0)\\n\")\n\treturn b.String()\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# across\\n\\n\")\n\tb.WriteString(\"One address, read across \" + strconv.Itoa(Sources()) + \" realms that are already on chain.\\n\\n\")\n\tb.WriteString(\"Open `/r/moul/x/across/v0:\u003caddress\u003e` to get the report. \")\n\tb.WriteString(\"Example: [/r/moul/x/across/v0:\" + exampleAddr + \"](/r/moul/x/across/v0:\" + exampleAddr + \").\\n\\n\")\n\n\tb.WriteString(\"## Why this realm exists\\n\\n\")\n\tb.WriteString(\"A gno realm that does not declare `private = true` can be imported by any \")\n\tb.WriteString(\"other realm, forever, at a path that can never be replaced. That makes every \")\n\tb.WriteString(\"exported read on it a permanent public API. This realm is what happens when \")\n\tb.WriteString(\"somebody actually uses \" + strconv.Itoa(Sources()) + \" of them at once.\\n\\n\")\n\tb.WriteString(\"Nothing here was negotiated. No registry, no interface, no shared base \")\n\tb.WriteString(\"package, no version handshake, and no change to any source realm.\\n\\n\")\n\n\tb.WriteString(\"## The sources, and what each one is showing right now\\n\\n\")\n\tt := ui.NewTable(\"realm\", \"global reading\")\n\tt.Row(\"[`r/moul/x/daily/erc20/v0`](/r/moul/x/daily/erc20/v0)\",\n\t\terc20.Symbol()+\" supply \"+strconv.FormatUint(erc20.TotalSupply(), 10))\n\tt.Row(\"[`r/moul/x/daily/vestoken/v0`](/r/moul/x/daily/vestoken/v0)\",\n\t\tvestoken.Symbol()+\" supply \"+strconv.FormatUint(vestoken.TotalSupply(), 10))\n\tt.Row(\"[`r/moul/x/daily/wrapped/v0`](/r/moul/x/daily/wrapped/v0)\",\n\t\t\"wrapped supply \"+strconv.FormatUint(wrapped.TotalSupply(), 10))\n\tt.Row(\"[`r/moul/demo/wikicoin/v0`](/r/moul/demo/wikicoin/v0)\", \"per-address balances only\")\n\tt.Row(\"[`r/moul/x/pairs/aaa/v0`](/r/moul/x/pairs/aaa/v0)\",\n\t\t\"AAA supply \"+strconv.FormatInt(aaa.TotalSupply(), 10))\n\tt.Row(\"[`r/moul/x/pairs/bbb/v0`](/r/moul/x/pairs/bbb/v0)\",\n\t\t\"BBB supply \"+strconv.FormatInt(bbb.TotalSupply(), 10))\n\tt.Row(\"[`r/moul/x/grc20faucet/v0`](/r/moul/x/grc20faucet/v0)\",\n\t\t\"RED supply \"+strconv.FormatInt(grc20faucet.TotalSupply(\"RED\"), 10)+\n\t\t\t\", BLUE supply \"+strconv.FormatInt(grc20faucet.TotalSupply(\"BLUE\"), 10))\n\tt.Row(\"[`r/moul/x/pairs/aaabbb/v0`](/r/moul/x/pairs/aaabbb/v0)\",\n\t\t\"LP shares \"+strconv.FormatInt(aaabbb.TotalShares(), 10))\n\tt.Row(\"[`r/moul/x/amm/v0`](/r/moul/x/amm/v0)\",\n\t\tstrconv.Itoa(amm.PoolCount())+\" pool(s), index only (see below)\")\n\tt.Row(\"[`r/moul/x/daily/staking/v0`](/r/moul/x/daily/staking/v0)\", \"per-address stake and rewards\")\n\tt.Row(\"[`r/moul/x/daily/streak/v0`](/r/moul/x/daily/streak/v0)\",\n\t\t\"day \"+strconv.FormatInt(streak.Day(), 10))\n\tt.Row(\"[`r/moul/x/daily/dice/v0`](/r/moul/x/daily/dice/v0)\",\n\t\tstrconv.Itoa(dice.Total())+\" roll(s) all time\")\n\tt.Row(\"[`r/moul/x/daily/lottery/v0`](/r/moul/x/daily/lottery/v0)\",\n\t\t\"round \"+strconv.Itoa(lottery.CurrentRound())+\", \"+\n\t\t\tstrconv.Itoa(lottery.NumEntrants())+\" entrant(s)\")\n\tt.Row(\"[`r/moul/x/daily/ratelimitdemo/v0`](/r/moul/x/daily/ratelimitdemo/v0)\", \"per-address bucket\")\n\tt.Row(\"[`r/moul/reactions/v0`](/r/moul/reactions/v0)\",\n\t\tstrconv.Itoa(reactions.Pages())+\" page(s) reacted to\")\n\tb.WriteString(t.String())\n\tb.WriteString(\"\\n\")\n\n\tb.WriteString(\"## What it cost\\n\\n\")\n\tb.WriteString(\"Eight of these hold a per-address balance, and they share no signature: \")\n\tb.WriteString(\"`uint64` three times, `int64` twice, `uint` once, one that wants a symbol \")\n\tb.WriteString(\"before the address, one that wants the address as a `string`. Every source \")\n\tb.WriteString(\"therefore needs its own adapter line. That is the whole cost, and it is paid \")\n\tb.WriteString(\"once by the reader rather than up front by fifteen authors.\\n\\n\")\n\n\tb.WriteString(\"## The two that could not be read\\n\\n\")\n\tb.WriteString(\"- `r/moul/x/amm/v0` routes `SharesOf` through a helper that panics on an \")\n\tb.WriteString(\"unknown pool. One panicking source takes down a page built from \" +\n\t\tstrconv.Itoa(Sources()) + \", and \")\n\tb.WriteString(\"`recover()` does not catch a cross-realm abort, so only its `PoolCount()` is \")\n\tb.WriteString(\"safe to call from here.\\n\")\n\tb.WriteString(\"- `r/moul/demo/vault/v0` exports `MyBalance()` with no address parameter. It \")\n\tb.WriteString(\"answers for its caller, which from here is this realm.\\n\\n\")\n\tb.WriteString(\"Neither is a bug. Both are what a getter looks like before anyone has tried \")\n\tb.WriteString(\"to call it from another realm.\\n\")\n\n\treturn b.String()\n}\n\n// exampleAddr is moul's address, used only to give the index a link that\n// resolves to a real report instead of an empty one.\nconst exampleAddr = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"},{"name":"across_test.gno","body":"package across\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\n\t\"gno.land/r/moul/x/daily/erc20/v0\"\n\t\"gno.land/r/moul/x/daily/streak/v0\"\n\t\"gno.land/r/moul/x/pairs/aaa/v0\"\n\t\"gno.land/r/moul/x/pairs/bbb/v0\"\n)\n\n// seeded is the address the mutation tests build state for. Everything after\n// TestReportReadsCrossRealmState sees whatever they left in the imported\n// realms, which is the whole point of the demo but also makes test order load\n// bearing: nothing below may assume a clean source realm for this address.\nvar seeded = testutils.TestAddress(\"across-seeded\")\n\n// fresh is never written to by anything here, so every source answers it with\n// its zero value. ExampleRender pins that page.\nvar fresh = testutils.TestAddress(\"across-fresh\")\n\nfunc TestSourceCount(t *testing.T) {\n\t// The package doc and the rendered prose both say fifteen. If this fails,\n\t// one of them is now a lie.\n\tuassert.Equal(t, 15, Sources())\n}\n\n// Report must never name a realm that sourceRealms does not list, or the index\n// table silently stops covering what the report reads.\nfunc TestSourcesCoverReport(t *testing.T) {\n\tknown := map[string]bool{}\n\tfor _, s := range sourceRealms {\n\t\tknown[s] = true\n\t}\n\tfor _, f := range Report(fresh) {\n\t\tuassert.True(t, known[f.source], \"report names an unlisted source: \"+f.source)\n\t}\n}\n\n// Every source answers, and no source panics. The count is asserted rather\n// than the values, so this stays true as the sources gain state.\nfunc TestReportAnswersFromEverySource(t *testing.T) {\n\tfacts := Report(fresh)\n\tuassert.Equal(t, 18, len(facts))\n\n\tseen := map[string]bool{}\n\tfor _, f := range facts {\n\t\tseen[f.source] = true\n\t}\n\t// amm is the one listed source that contributes to the index only.\n\tuassert.Equal(t, 14, len(seen))\n\tuassert.False(t, seen[\"r/moul/x/amm/v0\"], \"amm must not be read per address\")\n}\n\n// The load-bearing test: write to four realms that know nothing about this one,\n// then read all four back through Report. Break any of the four reads and this\n// goes red.\nfunc TestReportReadsCrossRealmState(cur realm, t *testing.T) {\n\t// SetRealm governs only the crossing calls made from this frame, so the\n\t// switch has to stay inline with the calls it is meant to cover.\n\ttesting.SetRealm(testing.NewUserRealm(seeded))\n\terc20.Mint(cross(cur), seeded, 4_200)\n\taaa.Faucet(cross(cur))\n\tbbb.Faucet(cross(cur))\n\tdays := streak.CheckIn(cross(cur))\n\tuassert.Equal(t, 1, days, \"first check-in is day 1\")\n\n\tgot := map[string]string{}\n\tfor _, f := range Report(seeded) {\n\t\tif f.zero {\n\t\t\tcontinue\n\t\t}\n\t\tgot[f.source+\" \"+f.what] = f.value\n\t}\n\n\tuassert.Equal(t, \"4200 \"+erc20.Symbol(), got[\"r/moul/x/daily/erc20/v0 balance\"])\n\tuassert.Equal(t, \"1 day(s)\", got[\"r/moul/x/daily/streak/v0 current streak\"])\n\tuassert.Equal(t, \"1 day(s)\", got[\"r/moul/x/daily/streak/v0 best streak\"])\n\tuassert.True(t, got[\"r/moul/x/pairs/aaa/v0 balance\"] != \"\", \"aaa faucet must show up\")\n\tuassert.True(t, got[\"r/moul/x/pairs/bbb/v0 balance\"] != \"\", \"bbb faucet must show up\")\n}\n\n// The rendered page for the seeded address must carry the same four facts, and\n// must hide the reads that came back empty rather than printing a wall of zeros.\nfunc TestRenderAddressShowsOnlyLiveFacts(t *testing.T) {\n\tout := Render(seeded.String())\n\n\tuassert.True(t, strings.Contains(out, \"4200 \"+erc20.Symbol()), \"erc20 balance on the page\")\n\tuassert.True(t, strings.Contains(out, \"current streak\"), \"streak on the page\")\n\tuassert.True(t, strings.Contains(out, \"r/moul/x/pairs/aaa/v0\"), \"aaa on the page\")\n\tuassert.True(t, strings.Contains(out, \"reads came back empty and are hidden\"), \"quiet rows hidden\")\n\tuassert.False(t, strings.Contains(out, \"vesting grant\"), \"an empty grant must not render\")\n}\n\n// An address-shaped path that is not an address must not reach a source realm.\nfunc TestRenderRejectsNonAddress(t *testing.T) {\n\tout := Render(\"not-an-address\")\n\tuassert.True(t, strings.Contains(out, \"is not a valid address\"), \"explicit refusal\")\n\tuassert.False(t, strings.Contains(out, \"## Answers\"), \"no report for a bad path\")\n}\n\n// The index reads a global from every source. Pinned by Contains rather than by\n// an example, because most of those globals move with chain state.\nfunc TestRenderIndexReadsEverySource(t *testing.T) {\n\tout := Render(\"\")\n\tfor _, s := range sourceRealms {\n\t\tuassert.True(t, strings.Contains(out, s), \"index must list \"+s)\n\t}\n\tuassert.True(t, strings.Contains(out, \"pool(s), index only\"), \"amm is flagged index-only\")\n\tuassert.True(t, strings.Contains(out, \"roll(s) all time\"), \"dice global is read\")\n\tuassert.True(t, strings.Contains(out, \"page(s) reacted to\"), \"reactions global is read\")\n}\n\n// ExampleRender pins the report for an address no test writes to. Every value\n// in it comes from a source realm's zero state, except the rate limiter, which\n// answers a full bucket for an address it has never seen: absence and a fresh\n// allowance are the same thing there, and the report says so rather than\n// pretending the read was empty.\nfunc ExampleRender() {\n\tprint(Render(fresh.String()))\n\t// Output:\n\t// # across: `g1v93hymmnwvkkvun9wd597h6lta047h6l220muq`\n\t//\n\t// What 15 independently deployed realms say about this address. None of them was changed to answer.\n\t//\n\t// ## Answers\n\t//\n\t// | source | fact | value |\n\t// | --- | --- | --- |\n\t// | [`r/moul/x/daily/ratelimitdemo/v0`](/r/moul/x/daily/ratelimitdemo/v0) | rate-limit tokens left | 5 |\n\t//\n\t// 17 of 18 reads came back empty and are hidden.\n\t//\n\t// [back to the index](/r/moul/x/across/v0)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/across/v0\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"72892000","gas_fee":"218676ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"v0nACkwilIvtHAQ9jCV/qxEASj+Jbn1IgBkkijyNgkp/GwcR+fJZ38yP6BLl3P+/efnOntchxb/Em45Ti9hdIQ=="}],"memo":""},"metadata":{"timestamp":"1790960643"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"d5U8PBPx5tVodFV5gu6VUVB0GUotuheWHPDolx28dkpTV2qIhZI3C6AfbJkpFQ8L5VbJqYzTrpbzH/EUI+8SAg=="}],"memo":""},"metadata":{"timestamp":"1790960644"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"ehkWGyigj6GChKfK4wnVOfmAFg4a8epcUKpNV3RypxYHP6jRg0NxzDEvBw8dr7wHByEPCG1ZiFkFQiC/EAI0sA=="}],"memo":""},"metadata":{"timestamp":"1790960700"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"devtools","path":"gno.land/r/moul/x/allinone/devtools/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/allinone/devtools`\n\nThe worked example of wiring moul's developer packages into one realm: what a\nnew realm should copy.\n\nEight packages, each earning its place in the output:\n\n| package | what it contributes |\n|---|---|\n| [`r/moul/config`](../../../config) | the notice block, the pause guard, which explorer to link |\n| [`p/moul/mygnoscan`](../../../../p/moul/mygnoscan) | the explorer routes |\n| [`p/moul/debug`](../../../../p/moul/debug) | the `?debug=1` panel |\n| [`p/moul/realmpath`](../../../../p/moul/realmpath) | reading the render path |\n| [`p/moul/kit/ui`](../../../../p/moul/kit/ui) | escaping caller input, and the tables |\n| [`p/moul/md`](../../../../p/moul/md) | the markdown |\n| [`p/moul/txlink`](../../../../p/moul/txlink) | the call links |\n| [`p/moul/fifo`](../../../../p/moul/fifo) | the bounded note list |\n\n## The three lines worth copying\n\n```go\nfunc Render(path string) string {\n\treturn config.TopBlockFor(realmPath) + body + config.BottomBlockFor(realmPath)\n}\n\nfunc Add(cur realm, body string) {\n\tconfig.AssertWritableFor(realmPath)  // honours the pause switch\n\tnotes.Append(ui.Inline(body))        // escapes what a caller typed\n}\n```\n\nThe first gives the realm a place for a warning and a pause banner without\nshipping any banner code, and returns `\"\"` while nothing is set, so a page that\nconcatenates it unconditionally is unchanged by default.\n\nThe second is two separate guards and both have to be there: the pause one so\nan incident can stop writes from outside this realm and without a redeploy, and\nthe escaping one because a string a caller typed is the oldest way to break a\npage.\n\n## Two views\n\n`Render(\"\")` is the root and is free of anything that moves, so an example test\ncan pin it. Everything live (the height, the chain id, the links built from\nthem) is under `:chain`, which is also what keeps the pinned output stable.\n\nState is disposable: the note list is bounded by `fifo` at 10 entries and this\nrealm is `private = true`, so a redeploy wipes it on purpose.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/allinone/devtools/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/allinone/devtools/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"devtools.gno","body":"// Package devtools is the worked example of wiring moul's developer packages\n// into one realm: what a new realm should copy.\n//\n// Everything here is a COMBINATION. Any one of these packages has its own demo\n// showing it alone; the thing that is hard to find is what they look like used\n// together, which is the only form a real realm ever meets them in. So this\n// realm imports ten of them and every one earns its place in the output:\n//\n//\tr/moul/config     the notice block, the pause switch, the explorer to link\n//\tp/moul/mygnoscan  the explorer routes themselves\n//\tp/moul/debug      a metadata panel behind ?debug=1\n//\tp/moul/realmpath  reading the query string Render was handed\n//\tp/moul/kit/ui     escaping what a caller typed, and the tables\n//\tp/moul/md         the markdown, without hand-rolled strings\n//\tp/moul/txlink     the \"call this function\" link\n//\tp/moul/fifo       the bounded note list, so the state cannot grow forever\n//\tp/moul/kit/tally  the note leaderboard, ties ordered rather than arbitrary\n//\tp/moul/kit/num    pricing that list in GNOT rather than raw ugnot\n//\n// # The three lines worth copying\n//\n// A realm that does nothing else should still do these:\n//\n//\tfunc Render(path string) string {\n//\t\treturn config.TopBlockFor(realmPath) + body + config.BottomBlockFor(realmPath)\n//\t}\n//\n//\tfunc Mutate(cur realm, s string) {\n//\t\tconfig.AssertWritableFor(realmPath)  // honours the pause switch\n//\t\tnotes.Append(ui.Inline(s))           // escapes what a caller typed\n//\t}\n//\n// The first gives every realm a place to put a warning and a pause banner\n// without shipping banner code. The second is two separate guards that both\n// have to be there: the pause one so an incident can stop writes from outside\n// the realm, and the escaping one because a string a caller typed is the\n// oldest way to break a page.\npackage devtools\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/debug/v0\"\n\t\"gno.land/p/moul/fifo/v0\"\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/tally/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mygnoscan/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// realmPath is this realm's own path.\n//\n// Passed explicitly to config rather than relying on its zero-argument helpers.\n// Both work (a plain read is borrowed, so config sees this realm as the\n// caller), but a constant cannot be wrong, and spelling it out is what a reader\n// copying this file needs to see.\nconst realmPath = \"gno.land/r/moul/x/allinone/devtools/v0\"\n\n// maxNotes bounds the guest list. fifo drops the oldest rather than growing,\n// because storage on chain is paid for and never refunded: an unbounded list in\n// a demo anyone can write to is a bill with no ceiling.\nconst maxNotes = 10\n\nvar notes = fifo.New(maxNotes)\n\n// authors counts notes per writer. A tally.Board rather than a map: gno map\n// iteration order is unspecified, so a leaderboard built by ranging one is not\n// reproducible between calls.\nvar authors = tally.NewBoard()\n\n// depositPerByte is what the chain charges to keep a byte, in ugnot. Used only\n// to price the note list on the page, never to settle anything.\nconst depositPerByte = 100\n\n// Add appends a note. It is the only mutating function here, and it carries\n// both guards a real one should.\nfunc Add(cur realm, body string) {\n\t// 1. The pause switch. Set `pause@r/moul/x/allinone/devtools` on\n\t//    r/moul/config and this aborts, with the reason, from outside this\n\t//    realm and without a redeploy.\n\tconfig.AssertWritableFor(realmPath)\n\n\tbody = strings.TrimSpace(body)\n\tif body == \"\" {\n\t\tpanic(\"empty note\")\n\t}\n\tif len(body) \u003e 200 {\n\t\tpanic(\"note too long: max 200 bytes, got \" + strconv.Itoa(len(body)))\n\t}\n\n\t// 2. Escaping. body is a string a caller typed, and it is about to land in\n\t//    a markdown list. ui.Inline is the repo's standard for exactly this.\n\tnotes.Append(ui.Inline(body))\n\n\t// 3. The scoreboard. tally.Board keeps one score per author and orders\n\t//    ties by key, so two authors on the same count always render in the\n\t//    same order.\n\tauthors.Add(unsafe.PreviousRealm().Address().String(), 1)\n}\n\n// Reset empties the list, so the realm can be put back to a known state\n// without a redeploy. Not gated by the pause switch: clearing up is the thing\n// you still want to do while paused.\nfunc Reset(cur realm) {\n\tnotes = fifo.New(maxNotes)\n\tauthors = tally.NewBoard()\n}\n\n// Render shows every package at work. The root view is deliberately free of\n// anything that moves on its own, so an example test can pin it; the live\n// numbers live under \"chain\".\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tvar b strings.Builder\n\tb.WriteString(config.TopBlockFor(realmPath))\n\tb.WriteString(md.H1(\"allinone: devtools\"))\n\tb.WriteString(\"\\nTen packages, used together rather than one at a time. \")\n\tb.WriteString(md.Link(\"source\", config.MygnoscanFor(realmPath)))\n\tb.WriteString(\"\\n\\n\")\n\n\tswitch req.PathPart(0) {\n\tcase \"chain\":\n\t\tb.WriteString(renderChain())\n\tdefault:\n\t\tb.WriteString(renderHome(path))\n\t}\n\n\t// debug prints its own panel only when ?debug=1 is set, and the empty\n\t// string otherwise, so this line is safe to leave in a deployed realm.\n\tb.WriteString(debug.Render(path))\n\tb.WriteString(config.BottomBlockFor(realmPath))\n\treturn b.String()\n}\n\nfunc renderHome(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.H2(\"Notes\"))\n\tb.WriteString(\"\\n\")\n\t// renderNotes returns no trailing newline of its own: md.BulletList and\n\t// ui.Empty already end in one, and adding a second here produced two\n\t// consecutive blank lines, which gno collapses inside an // Output: block\n\t// and which therefore no example test can ever pin.\n\tb.WriteString(renderNotes())\n\tb.WriteString(\"\\n\")\n\n\t// txlink builds the \"call this function\" URL for the CURRENT realm, so it\n\t// keeps working after a version bump without anything here changing.\n\tb.WriteString(md.BulletList([]string{\n\t\tmd.Link(\"add a note\", txlink.NewLink(\"Add\").AddArgs(\"body\", \"hello\").URL()),\n\t\tmd.Link(\"clear them\", txlink.Call(\"Reset\")),\n\t\tmd.Link(\"live chain values\", \"/r/moul/x/allinone/devtools/v0:chain\"),\n\t\tmd.Link(\"toggle the debug panel\", debug.ToggleURL(path)),\n\t}))\n\tb.WriteString(\"\\n\")\n\n\tb.WriteString(renderBoard())\n\n\tb.WriteString(md.H2(\"What each package does here\"))\n\tb.WriteString(\"\\n\")\n\tt := ui.NewTable(\"package\", \"what it contributed\")\n\tt.Row(\"`r/moul/config`\", \"the notice block above, the pause guard on `Add`, and which explorer to link\")\n\tt.Row(\"`p/moul/mygnoscan`\", \"the explorer routes, so a link survives a route change\")\n\tt.Row(\"`p/moul/debug`\", \"the `?debug=1` panel, empty otherwise\")\n\tt.Row(\"`p/moul/realmpath`\", \"splitting the render path into a view and a query\")\n\tt.Row(\"`p/moul/kit/ui`\", \"escaping a caller's note, and this table\")\n\tt.Row(\"`p/moul/md`\", \"every heading, link and list on the page\")\n\tt.Row(\"`p/moul/txlink`\", \"the call links above, relative to this realm\")\n\tt.Row(\"`p/moul/fifo`\", \"the note list, bounded so storage cannot grow forever\")\n\tt.Row(\"`p/moul/kit/tally`\", \"the note leaderboard, with ties ordered by address\")\n\tt.Row(\"`p/moul/kit/num`\", \"pricing the note list in GNOT instead of raw ugnot\")\n\tb.WriteString(t.String())\n\n\treturn b.String()\n}\n\n// renderBoard shows who has written the most notes, and what the list costs to\n// keep. Both numbers come from a package rather than from arithmetic here.\nfunc renderBoard() string {\n\tvar b strings.Builder\n\tb.WriteString(md.H2(\"Who has written the most\"))\n\tb.WriteString(\"\\n\")\n\n\ttop := authors.Top(5)\n\tif len(top) == 0 {\n\t\tb.WriteString(ui.Empty(\"No notes yet, so nobody is on the board.\"))\n\t} else {\n\t\tt := ui.NewTable(\"#\", \"author\", \"notes\")\n\t\tfor i, e := range top {\n\t\t\tt.Row(ui.Podium(i+1), ui.AddrOf(e.Key), num.Pad(e.Score, 2))\n\t\t}\n\t\tb.WriteString(t.String())\n\t}\n\n\t// num.GNOTf, not a hand-rolled divide by a million. The storage deposit is\n\t// what the chain charges to keep these bytes, so it is the honest price of\n\t// the list above.\n\tb.WriteString(\"\\nStorage deposit for the list: **\")\n\tb.WriteString(num.GNOTf(int64(notesBytes()) * depositPerByte))\n\tb.WriteString(\"**\\n\\n\")\n\treturn b.String()\n}\n\n// notesBytes is the length of every note currently held.\nfunc notesBytes() int {\n\tn := 0\n\tfor _, v := range notes.Entries() {\n\t\tn += len(v.(string))\n\t}\n\treturn n\n}\n\n// renderChain is everything that moves: the height, and the links built from\n// it. Kept off the root view so the root can be pinned by an example.\nfunc renderChain() string {\n\ts := config.Scanner()\n\th := runtime.ChainHeight()\n\n\tvar b strings.Builder\n\tb.WriteString(md.H2(\"Live\"))\n\tb.WriteString(\"\\n\")\n\n\tt := ui.NewTable(\"what\", \"value\")\n\tt.Row(\"chain id\", ui.Cell(runtime.ChainID()))\n\tt.Row(\"height\", strconv.FormatInt(h, 10))\n\tt.Row(\"explorer\", ui.Cell(s.Base()))\n\tt.Row(\"network\", ui.Cell(s.Network()))\n\tb.WriteString(t.String())\n\tb.WriteString(\"\\n\")\n\n\t// mygnoscan.Link used directly, rather than through config, to show that\n\t// the builder is an ordinary value: config only decides where it points.\n\tb.WriteString(md.BulletList([]string{\n\t\tmygnoscan.Link(\"this block\", s.Block(h)),\n\t\tmygnoscan.Link(\"this realm's transactions\", s.Realm(realmPath, mygnoscan.TabCalls)),\n\t\tmygnoscan.Link(\"its dependency graph\", s.Realm(realmPath, mygnoscan.TabDeps)),\n\t\tmygnoscan.Link(\"the parked deploy queue\", s.Packages(mygnoscan.PackagesInert)),\n\t}))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(md.Link(\"back\", \"/r/moul/x/allinone/devtools/v0\"))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\nfunc renderNotes() string {\n\tif notes.Size() == 0 {\n\t\treturn ui.Empty(\"no notes yet\")\n\t}\n\titems := []string{}\n\tfor _, e := range notes.Entries() {\n\t\titems = append(items, e.(string))\n\t}\n\treturn md.BulletList(items)\n}\n"},{"name":"devtools_test.gno","body":"package devtools\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/fifo/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// reset puts the realm back to a just-deployed state. Realm globals live for\n// the whole test binary and gno runs every Example AFTER every Test, so without\n// this the pinned output would depend on which tests ran before it.\nfunc reset() { notes = fifo.New(maxNotes) }\n\nfunc TestAdd(cur realm, t *testing.T) {\n\treset()\n\n\tAdd(cross(cur), \"hello\")\n\tuassert.Equal(t, 1, notes.Size())\n\tuassert.Equal(t, \"hello\", notes.Get(0).(string))\n\n\tuassert.AbortsWithMessage(t, cur, \"empty note\", func() { Add(cross(cur), \"   \") })\n\tuassert.AbortsContains(t, cur, \"note too long\", func() {\n\t\tlong := \"\"\n\t\tfor i := 0; i \u003c 201; i++ {\n\t\t\tlong += \"x\"\n\t\t}\n\t\tAdd(cross(cur), long)\n\t})\n}\n\n// TestAddEscapes is the guard that matters most in a realm anyone can write to:\n// a note is a string a caller typed, and it lands in a markdown list. Without\n// ui.Inline the first line below would close the list item and render as a\n// heading, and the second would become a link.\nfunc TestAddEscapes(cur realm, t *testing.T) {\n\treset()\n\n\tAdd(cross(cur), \"# not a heading\")\n\tAdd(cross(cur), \"[not](https://evil.example.com)\")\n\n\tfor _, got := range []string{notes.Get(0).(string), notes.Get(1).(string)} {\n\t\tuassert.False(t, got == \"# not a heading\", \"markdown survived unescaped\")\n\t\tuassert.False(t, got == \"[not](https://evil.example.com)\", \"a link survived unescaped\")\n\t}\n\tuassert.True(t, len(notes.Get(0).(string)) \u003e len(\"# not a heading\"),\n\t\t\"escaping should have added characters\")\n}\n\n// TestNotesAreBounded pins the reason fifo is here rather than a slice: storage\n// is paid for and never refunded, so a list anyone can append to needs a\n// ceiling in the type, not in a comment.\nfunc TestNotesAreBounded(cur realm, t *testing.T) {\n\treset()\n\n\tfor i := 0; i \u003c maxNotes+5; i++ {\n\t\tAdd(cross(cur), \"note \"+string(rune('a'+i)))\n\t}\n\tuassert.Equal(t, maxNotes, notes.Size(), \"the list stops growing at maxNotes\")\n\tuassert.Equal(t, maxNotes, notes.MaxSize())\n}\n\n// TestAddHonoursThePause is the whole point of importing r/moul/config: this\n// realm can be stopped from outside, by a transaction against another realm,\n// with no redeploy here. It cannot set that from this package (config has its\n// own authority), so it asserts the wiring: Add goes through the pause check\n// and passes while nothing is set.\nfunc TestAddHonoursThePause(cur realm, t *testing.T) {\n\treset()\n\tuassert.False(t, config.IsPausedFor(realmPath), \"nothing configured means running\")\n\tAdd(cross(cur), \"allowed while running\")\n\tuassert.Equal(t, 1, notes.Size())\n}\n\nfunc TestReset(cur realm, t *testing.T) {\n\treset()\n\tAdd(cross(cur), \"one\")\n\tReset(cross(cur))\n\tuassert.Equal(t, 0, notes.Size())\n}\n\n// ExampleRender pins the root view. It is free of the height and the chain id\n// on purpose: those live under :chain, so this one is stable.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # allinone: devtools\n\t//\n\t// Ten packages, used together rather than one at a time. [source](https://mygnoscan.moul.p2p.team/realm/r/moul/x/allinone/devtools/v0)\n\t//\n\t// ## Notes\n\t//\n\t// *no notes yet*\n\t//\n\t// - [add a note](/r/moul/x/allinone/devtools/v0$help\u0026func=Add\u0026body=hello)\n\t// - [clear them](/r/moul/x/allinone/devtools/v0$help\u0026func=Reset)\n\t// - [live chain values](/r/moul/x/allinone/devtools/v0:chain)\n\t// - [toggle the debug panel](/r/moul/x/allinone/devtools/v0:?debug=1)\n\t//\n\t// ## Who has written the most\n\t//\n\t// *No notes yet, so nobody is on the board.*\n\t//\n\t// Storage deposit for the list: **0 GNOT**\n\t//\n\t// ## What each package does here\n\t//\n\t// | package | what it contributed |\n\t// | --- | --- |\n\t// | `r/moul/config` | the notice block above, the pause guard on `Add`, and which explorer to link |\n\t// | `p/moul/mygnoscan` | the explorer routes, so a link survives a route change |\n\t// | `p/moul/debug` | the `?debug=1` panel, empty otherwise |\n\t// | `p/moul/realmpath` | splitting the render path into a view and a query |\n\t// | `p/moul/kit/ui` | escaping a caller's note, and this table |\n\t// | `p/moul/md` | every heading, link and list on the page |\n\t// | `p/moul/txlink` | the call links above, relative to this realm |\n\t// | `p/moul/fifo` | the note list, bounded so storage cannot grow forever |\n\t// | `p/moul/kit/tally` | the note leaderboard, with ties ordered by address |\n\t// | `p/moul/kit/num` | pricing the note list in GNOT instead of raw ugnot |\n}\n\n// TestBoardRanksAuthorsAndPricesTheList exercises the two kit packages this\n// realm adopted, because ExampleRender only ever sees the empty page.\nfunc TestBoardRanksAuthorsAndPricesTheList(cur realm, t *testing.T) {\n\tReset(cross(cur))\n\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAdd(cross(cur), \"one\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAdd(cross(cur), \"two\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAdd(cross(cur), \"three\")\n\n\tuassert.Equal(t, int64(2), authors.Score(alice.String()))\n\tuassert.Equal(t, int64(1), authors.Score(bob.String()))\n\tuassert.Equal(t, 1, authors.Rank(alice.String()))\n\tuassert.Equal(t, 2, authors.Rank(bob.String()))\n\n\t// \"one\"+\"two\"+\"three\" is 11 bytes at 100 ugnot each, which num renders as\n\t// GNOT rather than as 1100.\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"0.0011 GNOT\"))\n\tuassert.True(t, strings.Contains(out, \"## Who has written the most\"))\n\n\tReset(cross(cur))\n\tuassert.Equal(t, 0, authors.Len())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/allinone/devtools/v0\"\ngno = \"0.9\"\n\n# Redeployable by its creator. A demo's state is disposable by design: its whole\n# job is to be redeployed whenever one of the packages it shows off changes, so\n# losing the notes people left is the intended trade rather than a regret.\nprivate = true\n"}]},"send":"","max_deposit":"8000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"textlab","path":"gno.land/r/moul/x/allinone/textlab/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/allinone/textlab`\n\nEvery string algorithm in `p/moul` over one input at once, so they can be\ncompared instead of read about one at a time.\n\n```\n/r/moul/x/allinone/textlab/v0:knight        one word\n/r/moul/x/allinone/textlab/v0:knight/night  compared with another\n/r/moul/x/allinone/textlab/v0:1987          read as a roman numeral\n```\n\nEight packages: `soundex`, `levenshtein`, `rot13`, `piglatin`, `romannum`,\nplus `kit/ui`, `md`, `realmpath` and `r/moul/config`.\n\n## What the combination shows\n\nsoundex and levenshtein both claim to tell you whether two words are alike, and\nthey are measuring different things. soundex keys on the **first letter** and\nthen on consonant classes, so it is blind to how the rest is spelled.\nlevenshtein counts edits and is blind to how it sounds.\n\n| pair | soundex | levenshtein |\n|---|---|---|\n| `knight` / `night` | K523 vs N230, **unrelated** | 1 edit, 83% similar |\n| `robert` / `rupert` | R163 vs R163, **identical** | 2 edits, 67% similar |\n\nThe first is the clean case: one edit apart, and yet soundex says no, because\nthe silent K changes the first character of the code. Measured 2026-09-23\nagainst the packages in this tree and pinned by `TestTheDisagreement`, so the\npage cannot start saying something false without the suite going red.\n\n## One defect worth keeping in mind\n\n`romannum.FromRoman` **panics** on a string that is not a roman numeral rather\nthan returning zero. The input here comes out of a URL, so it is screened by\n`isRomanNumeral` first. Without that screen the default view aborted, because\n`knight` is not a roman numeral and neither is most of what anyone would type.\n\nNo state at all: the input comes from the render path and nothing is stored.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/allinone/textlab/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/textlab/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/allinone/textlab/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/textlab/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/allinone/textlab/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/textlab/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/allinone/textlab/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/textlab/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/allinone/textlab/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/allinone/textlab/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/allinone/textlab/v0\"\ngno = \"0.9\"\n\n# Redeployable by its creator. This realm holds no state worth keeping: it runs\n# algorithms over a string in the render path, so a redeploy loses nothing.\nprivate = true\n"},{"name":"textlab.gno","body":"// Package textlab runs every string algorithm in p/moul over one input at\n// once, so they can be compared rather than read about one at a time.\n//\n// Each of these has its own demo realm showing it alone. What none of those can\n// show is how the answers differ for the SAME word, which is the only question\n// a reader actually has: soundex and levenshtein both claim to tell you whether\n// two words are alike, and they are measuring different things.\n//\n// soundex keys on the FIRST LETTER and then on consonant classes, so it is\n// blind to how the rest is spelled. levenshtein counts edits and is blind to\n// how it sounds. \"knight\" and \"night\" are the clean case: one edit apart (83%\n// similar) and yet soundex calls them unrelated, K523 against N230, because\n// the silent K changes the first character of the code. \"robert\" and \"rupert\"\n// go the other way, identical codes at two edits apart. Measured 2026-09-23\n// against the packages in this tree, not quoted from a textbook.\n//\n//\t/r/moul/x/allinone/textlab/v0:knight\n//\t/r/moul/x/allinone/textlab/v0:knight/night   compares two\n//\n// Eight packages, no state, nothing to redeploy carefully: the input comes out\n// of the render path and nothing is stored.\npackage textlab\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/x/daily/levenshtein/v0\"\n\t\"gno.land/p/moul/x/daily/piglatin/v0\"\n\t\"gno.land/p/moul/x/daily/romannum/v0\"\n\t\"gno.land/p/moul/x/daily/rot13/v0\"\n\t\"gno.land/p/moul/x/daily/soundex/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\nconst realmPath = \"gno.land/r/moul/x/allinone/textlab/v0\"\n\n// maxInput bounds what a render path can carry into the algorithms below.\n// levenshtein.Matrix is O(len(a) * len(b)), so an unbounded pair of inputs is\n// a way to make a query expensive for whoever serves it.\nconst maxInput = 64\n\n// defaultWord is what the root view demonstrates, chosen because it is the\n// textbook case where the two similarity measures disagree: \"knight\" and\n// \"night\" sound identical to soundex and are one edit apart.\nconst defaultWord = \"knight\"\n\n// Render takes its input from the path: one word, or two separated by \"/\".\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\ta := strings.TrimSpace(req.PathPart(0))\n\tb := strings.TrimSpace(req.PathPart(1))\n\tif a == \"\" {\n\t\ta = defaultWord\n\t}\n\n\tvar out strings.Builder\n\tout.WriteString(config.TopBlockFor(realmPath))\n\tout.WriteString(md.H1(\"allinone: textlab\"))\n\tout.WriteString(\"\\nEight packages over one input. \")\n\tout.WriteString(md.Link(\"source\", config.MygnoscanFor(realmPath)))\n\tout.WriteString(\"\\n\\n\")\n\n\tif tooLong(a) || tooLong(b) {\n\t\tout.WriteString(ui.Empty(\"input too long: max \" + strconv.Itoa(maxInput) + \" bytes\"))\n\t\tout.WriteString(\"\\n\")\n\t\tout.WriteString(config.BottomBlockFor(realmPath))\n\t\treturn out.String()\n\t}\n\n\tout.WriteString(renderOne(a))\n\tif b != \"\" {\n\t\tout.WriteString(\"\\n\")\n\t\tout.WriteString(renderPair(a, b))\n\t} else {\n\t\tout.WriteString(\"\\n\")\n\t\tout.WriteString(renderTry())\n\t}\n\n\tout.WriteString(config.BottomBlockFor(realmPath))\n\treturn out.String()\n}\n\nfunc tooLong(s string) bool { return len(s) \u003e maxInput }\n\n// renderOne is every single-input algorithm, one row each.\n//\n// ui.Cell, not ui.Inline: these land in table cells, where an unescaped pipe\n// would silently eat a column. The input is whatever someone put in a URL.\nfunc renderOne(word string) string {\n\tt := ui.NewTable(\"package\", \"answer\")\n\tt.Row(\"`x/daily/soundex`\", ui.Cell(soundex.Encode(word)))\n\tt.Row(\"`x/daily/rot13`\", ui.Cell(rot13.Rot13(word)))\n\tt.Row(\"`x/daily/piglatin`\", ui.Cell(piglatin.Translate(word)))\n\tt.Row(\"`x/daily/romannum`\", ui.Cell(romanOf(word)))\n\n\treturn md.H2(\"Input: \"+ui.Inline(word)) + \"\\n\" + t.String()\n}\n\n// romanOf shows the round trip both ways, because romannum is the one package\n// here whose input is a number rather than a word.\n//\n// FromRoman PANICS on anything that is not a roman numeral rather than\n// returning zero, and the input here comes out of a URL, so it is screened\n// first. Without that screen the DEFAULT view aborts: \"knight\" is not a roman\n// numeral, and neither is most of what anyone would type.\nfunc romanOf(word string) string {\n\tif n, err := strconv.Atoi(word); err == nil {\n\t\tif n \u003c= 0 || n \u003e 3999 {\n\t\t\treturn \"out of range (1..3999)\"\n\t\t}\n\t\treturn romannum.ToRoman(n)\n\t}\n\tupper := strings.ToUpper(word)\n\tif !isRomanNumeral(upper) {\n\t\treturn \"not a number\"\n\t}\n\tif n := romannum.FromRoman(upper); n \u003e 0 {\n\t\treturn strconv.Itoa(n) + \" (read as roman)\"\n\t}\n\treturn \"not a number\"\n}\n\n// isRomanNumeral reports whether every byte is a roman digit. It is a screen\n// for romanOf, not a validity check: \"IIII\" passes here and FromRoman decides.\nfunc isRomanNumeral(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tswitch s[i] {\n\t\tcase 'I', 'V', 'X', 'L', 'C', 'D', 'M':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// renderPair is the comparison, and the reason this realm exists: the two\n// similarity measures answer different questions, and a reader should watch\n// them disagree rather than be told they might.\nfunc renderPair(a, b string) string {\n\tsa, sb := soundex.Encode(a), soundex.Encode(b)\n\n\tt := ui.NewTable(\"measure\", \"answer\")\n\tt.Row(\"`soundex` of \"+ui.Cell(a), ui.Cell(sa))\n\tt.Row(\"`soundex` of \"+ui.Cell(b), ui.Cell(sb))\n\tt.Row(\"sound alike\", yesNo(soundex.Match(a, b)))\n\tt.Row(\"`levenshtein` distance\", strconv.Itoa(levenshtein.Distance(a, b)))\n\tt.Row(\"`levenshtein` similarity\", strconv.Itoa(levenshtein.Similarity(a, b))+\"%\")\n\n\treturn md.H2(\"Compared with \"+ui.Inline(b)) + \"\\n\" + t.String()\n}\n\nfunc yesNo(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}\n\nfunc renderTry() string {\n\treturn md.H2(\"Try two\") + \"\\n\" +\n\t\tmd.BulletList([]string{\n\t\t\tmd.Link(\"knight vs night\", \"/r/moul/x/allinone/textlab/v0:knight/night\") +\n\t\t\t\t\" (one edit apart, yet soundex says unrelated)\",\n\t\t\tmd.Link(\"robert vs rupert\", \"/r/moul/x/allinone/textlab/v0:robert/rupert\") +\n\t\t\t\t\" (two edits apart, yet soundex says identical)\",\n\t\t\tmd.Link(\"1987 as a roman numeral\", \"/r/moul/x/allinone/textlab/v0:1987\"),\n\t\t})\n}\n"},{"name":"textlab_test.gno","body":"package textlab\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/daily/levenshtein/v0\"\n\t\"gno.land/p/moul/x/daily/soundex/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestRomanOf covers the one package here whose input is a number rather than\n// a word, in both directions plus the two ways it can be neither.\nfunc TestRomanOf(t *testing.T) {\n\ttests := []struct{ in, want string }{\n\t\t{\"1987\", \"MCMLXXXVII\"},\n\t\t{\"1\", \"I\"},\n\t\t{\"3999\", \"MMMCMXCIX\"},\n\t\t{\"0\", \"out of range (1..3999)\"},\n\t\t{\"-5\", \"out of range (1..3999)\"},\n\t\t{\"4000\", \"out of range (1..3999)\"},\n\t\t{\"MCMLXXXVII\", \"1987 (read as roman)\"},\n\t\t{\"mcmlxxxvii\", \"1987 (read as roman)\"},\n\t\t{\"knight\", \"not a number\"},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, romanOf(tt.in), \"romanOf(\"+tt.in+\")\")\n\t}\n}\n\n// TestTheDisagreement is the claim the realm is built to show, pinned in both\n// directions. Measured 2026-09-23; the numbers in the package doc and on the\n// page come from here, so if either package changes its mind this fails rather\n// than the page quietly stating something false.\nfunc TestTheDisagreement(t *testing.T) {\n\t// One edit apart, and yet soundex says unrelated: it keys on the first\n\t// letter, and the silent K changes it.\n\tuassert.Equal(t, \"K523\", soundex.Encode(\"knight\"))\n\tuassert.Equal(t, \"N230\", soundex.Encode(\"night\"))\n\tuassert.False(t, soundex.Match(\"knight\", \"night\"), \"different soundex codes\")\n\tuassert.Equal(t, 1, levenshtein.Distance(\"knight\", \"night\"))\n\tuassert.Equal(t, 83, levenshtein.Similarity(\"knight\", \"night\"))\n\n\t// And the other way: two edits apart, identical codes.\n\tuassert.Equal(t, \"R163\", soundex.Encode(\"robert\"))\n\tuassert.Equal(t, \"R163\", soundex.Encode(\"rupert\"))\n\tuassert.True(t, soundex.Match(\"robert\", \"rupert\"), \"same soundex code\")\n\tuassert.Equal(t, 2, levenshtein.Distance(\"robert\", \"rupert\"))\n}\n\n// TestRomanOfDoesNotAbortOnOrdinaryWords is the defect this realm shipped with\n// until a test found it: romannum.FromRoman PANICS on a non-numeral instead of\n// returning zero, so the DEFAULT view aborted. \"knight\" is not a roman numeral,\n// and neither is most of what anyone would put in the URL.\nfunc TestRomanOfDoesNotAbortOnOrdinaryWords(t *testing.T) {\n\tfor _, w := range []string{\"knight\", \"night\", \"a|b\", \"\", \"hello world\", \"MMM!\"} {\n\t\tuassert.Equal(t, \"not a number\", romanOf(w), \"romanOf(\"+w+\")\")\n\t}\n\tuassert.True(t, isRomanNumeral(\"MCMLXXXVII\"))\n\tuassert.False(t, isRomanNumeral(\"KNIGHT\"))\n\tuassert.False(t, isRomanNumeral(\"\"))\n}\n\n// TestInputIsBounded pins the ceiling. levenshtein.Matrix is O(len(a)*len(b)),\n// so an unbounded pair out of a URL is a way to make a query expensive for\n// whoever serves it.\nfunc TestInputIsBounded(t *testing.T) {\n\tlong := \"\"\n\tfor i := 0; i \u003c maxInput+1; i++ {\n\t\tlong += \"x\"\n\t}\n\tuassert.True(t, tooLong(long))\n\tuassert.False(t, tooLong(\"knight\"))\n\n\tout := Render(long)\n\tuassert.True(t, len(out) \u003c 600, \"an over-long input renders a refusal, not a matrix\")\n}\n\n// TestTableCellsAreEscaped: the input comes out of a URL and lands in a table\n// cell, where an unescaped pipe eats a column.\nfunc TestTableCellsAreEscaped(t *testing.T) {\n\tout := Render(\"a|b\")\n\tuassert.False(t, contains(out, \"| a|b |\"), \"a raw pipe reached a table cell\")\n}\n\nfunc contains(h, n string) bool {\n\tfor i := 0; i+len(n) \u003c= len(h); i++ {\n\t\tif h[i:i+len(n)] == n {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// ExampleRender pins the root view, which is the default word and the \"try\n// two\" list. Nothing here moves with the chain.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # allinone: textlab\n\t//\n\t// Eight packages over one input. [source](https://mygnoscan.moul.p2p.team/realm/r/moul/x/allinone/textlab/v0)\n\t//\n\t// ## Input: knight\n\t//\n\t// | package | answer |\n\t// | --- | --- |\n\t// | `x/daily/soundex` | K523 |\n\t// | `x/daily/rot13` | xavtug |\n\t// | `x/daily/piglatin` | ightknay |\n\t// | `x/daily/romannum` | not a number |\n\t//\n\t// ## Try two\n\t//\n\t// - [knight vs night](/r/moul/x/allinone/textlab/v0:knight/night) (one edit apart, yet soundex says unrelated)\n\t// - [robert vs rupert](/r/moul/x/allinone/textlab/v0:robert/rupert) (two edits apart, yet soundex says identical)\n\t// - [1987 as a roman numeral](/r/moul/x/allinone/textlab/v0:1987)\n}\n\n// ExampleRender_pair pins the comparison view, which is the realm's whole\n// argument: the same pair, judged opposite ways by the two measures.\nfunc ExampleRender_pair() {\n\tprint(Render(\"knight/night\"))\n\t// Output:\n\t// # allinone: textlab\n\t//\n\t// Eight packages over one input. [source](https://mygnoscan.moul.p2p.team/realm/r/moul/x/allinone/textlab/v0)\n\t//\n\t// ## Input: knight\n\t//\n\t// | package | answer |\n\t// | --- | --- |\n\t// | `x/daily/soundex` | K523 |\n\t// | `x/daily/rot13` | xavtug |\n\t// | `x/daily/piglatin` | ightknay |\n\t// | `x/daily/romannum` | not a number |\n\t//\n\t// ## Compared with night\n\t//\n\t// | measure | answer |\n\t// | --- | --- |\n\t// | `soundex` of knight | K523 |\n\t// | `soundex` of night | N230 |\n\t// | sound alike | no |\n\t// | `levenshtein` distance | 1 |\n\t// | `levenshtein` similarity | 83% |\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"111796800","gas_fee":"335390ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"YndxSariFOJ1rqE0KlTsOfXB9ffynngiPKQgZHGiIdtXswReksmeeORhfxYRodY+LFNzhyyr9ld4pxO/9gu46w=="}],"memo":""},"metadata":{"timestamp":"1790960762"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"RggwFWCiTf7p6yko/WqVbFnkxnGpTRZMF33YP+0WAMVQikSOiBEKjkKS5xlfJxJszOHQGDi3Udc8G6N9LTSsjw=="}],"memo":""},"metadata":{"timestamp":"1790960766"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"compact","path":"gno.land/r/moul/x/compact/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/compact/v0`\n\nFragmentation, as a number you can act on.\n\nA soft delete frees nothing. It clears the element and leaves the tree node\nbehind, so the bytes stay locked and every read still walks past the hole.\nCompacting drops those nodes, and the chain refunds their deposit **to whoever\nsigns the transaction**. Compaction is therefore paid work, and the only real\nquestion is *when*: too early and you free too few nodes to cover the gas, too\nlate and every read has been paying for the holes in between.\n\nThis realm refuses to answer that question. It publishes the integers the\nanswer is made of and lets whoever is watching decide, because the realm cannot\nsee the gas price of the day and the caller can.\n\n## The interface\n\n| | |\n|---|---|\n| `Add(text)` | appends an entry and locks its deposit against you |\n| `Drop(index)` | soft-deletes **your own** entry, which is what creates a hole. Frees nothing |\n| `Compact()` | drops the dead nodes. Permissionless, and the refund goes to you |\n| `Fragmentation()` | live against allocated, the free read a bot polls |\n| `Reclaimable()` | what a `Compact` would actually free right now |\n| `Quote()` | that, priced, as a `storagecost.Quote` |\n\nOnly the author may `Drop`, so the fragmentation here is the honest kind that\nordinary use produces rather than vandalism. `Compact` stays open to anyone,\nand that asymmetry is the mechanism: **choosing what dies is owned, reclaiming\nit is not.**\n\n## Why `allocated - live` is the wrong number\n\nThe obvious reading of fragmentation is the gap between allocated indices and\nlive elements. It is not what a compaction frees.\n\nA dead element only becomes a reclaimable node once **everything under it is\nalso dead**. So a board with many scattered holes reports a large gap and\nreclaims almost nothing, while a board with a dead tail reclaims a lot from the\nsame gap. `Reclaimable()` is the real number and it is free to read.\n\nThat is the whole reason this cannot be a schedule or a heuristic baked into\nthe package. The shape of the holes decides, the shape changes with use, and\nonly a caller watching both integers can time it.\n\n## Why this quote is sounder than a reaper's\n\nA reaper advertises what deleting entries will refund, and to do that it has to\nguess how much state an entry occupies from its payload length. That guess is\nbad at the small end, where a per-entry floor dominates the payload, and one\nrealm under-advertised by **25x** on chain because of it.\n\nCompaction has no such problem:\n\n| | reaper's bounty | this quote |\n|---|---|---|\n| quantity | payload bytes, **guessed** from string length | dead nodes, **counted** by the container |\n| conversion | a ratio measured at one payload size | a per-node constant, measured twice at 856 bytes |\n| fails when | entries are small, or the container dominates | never structurally; the constant can drift |\n\n`Quote()` is a measured constant times an exact integer. Still an estimate, and\nthe chain's `StorageUnlockEvent` is still the only settlement, but the failure\nmode that cost a reaper 25x is absent by construction.\n\n`TestQuoteCountsNodesRatherThanGuessingFromPayload` pins it: eight entries of 1\nbyte and eight of 256 produce the identical quote, because the node is what\ngets freed.\n\n## What it is built from\n\n- [`p/moul/ulist`](https://github.com/moul/gno-contracts/tree/main/p/moul/ulist)\n  stores the entries and owns compaction. Its `Compact` drops dead nodes\n  without moving a live index, so an index is stable for the life of the realm.\n- [`p/moul/x/storagecost`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/storagecost)\n  owns the arithmetic, including `EstimateNodes` and the measured\n  `BytesPerTreeNode`.\n- [`p/moul/kit/ui`](https://github.com/moul/gno-contracts/tree/main/p/moul/kit/ui)\n  owns the display, including escaping an entry before it reaches the page.\n\n## Related\n\n[`r/moul/x/reaper`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/reaper)\nis the other half: it deletes expired entries, where this one reclaims what\ndeletion left behind. Reap first, then compact, because compaction returns\nnothing while a live element still sits below the dead ones.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/compact/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/compact/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/compact/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/compact/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/compact/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/compact/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/compact/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/compact/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/compact/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/compact/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"compact.gno","body":"// Package compact makes fragmentation a number you can act on.\n//\n// A soft delete does not free anything. It clears the element and leaves the\n// tree node behind, so the bytes stay locked and every read still walks past\n// them. Compacting drops those nodes and the chain refunds their deposit to\n// whoever signed the transaction. So compaction is paid work, and the only\n// real question is WHEN: too early and you free too few nodes to cover the\n// gas, too late and every read has been paying for the holes in between.\n//\n// This realm refuses to answer that question, on purpose. It publishes the\n// two integers the answer is made of and lets whoever is watching decide,\n// because the realm cannot see the gas price of the day and the caller can.\n//\n//   - Fragmentation() is live vs allocated, the free read a bot polls.\n//   - Reclaimable() is what a Compact would actually free, right now.\n//   - Quote() prices it at the floor gas price, as an advertisement.\n//\n// The arithmetic is gno.land/p/moul/x/storagecost and the container is\n// gno.land/p/moul/ulist, whose Compact drops dead nodes without moving a live\n// index, so an index is stable for the life of the realm.\n//\n// # Why this quote is trustworthy where a reaper's is not\n//\n// A reaper advertises what deleting entries will refund, and to do that it has\n// to guess how much state an entry occupies from its payload length. That\n// guess is bad: a per-entry floor dominates at the small end, and one realm\n// under-advertised by 25x on chain because of it.\n//\n// Compaction has no such problem. What it frees is a COUNT of dead nodes, and\n// the container already reports that count exactly. Every node costs the same\n// whatever it carried. So the number on this page is a measured constant times\n// an exact integer, not a ratio applied to a guess, which is why this is the\n// half of the mechanism worth showing first.\npackage compact\n\nimport (\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/ulist/v1\"\n\t\"gno.land/p/moul/x/storagecost/v1\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// gasWantedCompact is the gas ceiling a compacting transaction is assumed to\n// ask for, used only to price the advertised bounty. A caller compacting an\n// unusually large number of nodes should re-price with\n// storagecost.EvaluateAtFloor directly rather than trust this.\nconst gasWantedCompact int64 = 5_000_000\n\n// maxText caps an entry so one caller cannot lock an unbounded deposit in a\n// single call. Small on purpose: this realm is about the NODES, and a fat\n// payload would only hide the thing it exists to show.\nconst maxText = 256\n\n// Entry is one element. Author is kept so a drop can be refused to anyone\n// else: soft-deleting a stranger's entry would be vandalism, and the holes\n// this realm studies should come from ordinary use.\ntype Entry struct {\n\tText   string\n\tAuthor address\n\tAdded  int64 // block height\n}\n\nvar entries = ulist.New()\n\n// Add appends an entry and locks its storage deposit against the caller.\nfunc Add(cur realm, text string) int {\n\tif text == \"\" {\n\t\tpanic(\"compact: empty entry\")\n\t}\n\tif len(text) \u003e maxText {\n\t\tpanic(ufmt.Sprintf(\"compact: entry too long, %d bytes against a %d cap\", len(text), maxText))\n\t}\n\tentries.Append(\u0026Entry{\n\t\tText:   text,\n\t\tAuthor: cur.Previous().Address(),\n\t\tAdded:  runtime.ChainHeight(),\n\t})\n\treturn entries.TotalSize() - 1\n}\n\n// Drop soft-deletes your own entry, which is what creates a hole.\n//\n// It frees nothing on its own, and that is the point of the realm: the bytes\n// stay locked until somebody compacts. Only the author may drop, so the\n// fragmentation on this page is the honest kind that ordinary use produces.\nfunc Drop(cur realm, index int) {\n\te, ok := entryAt(index)\n\tif !ok {\n\t\tpanic(ufmt.Sprintf(\"compact: no live entry at %d\", index))\n\t}\n\tif e.Author != cur.Previous().Address() {\n\t\tpanic(\"compact: only the author may drop an entry\")\n\t}\n\tentries.MustDelete(index)\n}\n\n// Compact frees the dead tree nodes and returns how many it freed.\n//\n// Permissionless by design, and the refund goes to whoever signs this\n// transaction rather than to the realm or to the authors: the chain pays the\n// signer directly, so there is nothing here to distribute and nothing to\n// steal. The worst a caller can do is waste their own gas compacting a board\n// that had no holes.\nfunc Compact(cur realm) int {\n\treturn entries.Compact()\n}\n\n// Fragmentation reports live elements against allocated indices.\n//\n// The gap between them is what a compaction has to work with. It is a free\n// read so a bot can poll it and decide for itself, which is the whole design:\n// the realm publishes, the caller times.\nfunc Fragmentation() (live, allocated int) {\n\treturn entries.Size(), entries.TotalSize()\n}\n\n// Reclaimable is how many dead nodes a Compact would free right now.\n//\n// It is NOT the same as allocated minus live. A dead element only becomes a\n// reclaimable node once every element under it is also dead, so a board with\n// many scattered holes can report a large gap and nothing to reclaim. That\n// difference is exactly what makes the timing a decision instead of a rule.\nfunc Reclaimable() int { return entries.Compactable() }\n\n// Quote prices what a Compact would return, at the default storage price and\n// the floor gas price.\n//\n// Unlike a payload-derived bounty this is a counted quantity: Reclaimable is\n// exact, and storagecost.EstimateNodes multiplies it by a measured per-node\n// constant. Treat it as an advertisement all the same. The authoritative\n// numbers are the chain's, in the StorageUnlockEvent the transaction emits.\nfunc Quote() storagecost.Quote {\n\treturn storagecost.EvaluateAtFloor(\n\t\tstoragecost.EstimateNodes(int64(Reclaimable())), gasWantedCompact)\n}\n\n// entryAt reads index i, reporting whether a live entry is there.\nfunc entryAt(i int) (*Entry, bool) {\n\tv := entries.Get(i)\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\te, ok := v.(*Entry)\n\treturn e, ok\n}\n\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.H1(\"Compact\"))\n\tb.WriteString(\"\\nSoft-deleting an entry frees nothing: the tree node stays, the bytes stay locked, and every read still walks past the hole. Compacting drops those nodes and the chain refunds their deposit **to whoever signs the transaction**. The only question is when.\\n\\n\")\n\n\tlive, allocated := Fragmentation()\n\tdead := Reclaimable()\n\tq := Quote()\n\n\tb.WriteString(md.H2(\"The two integers\"))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(md.BulletList([]string{\n\t\tufmt.Sprintf(\"**%d live** of **%d allocated** indices%s\", live, allocated, ratioSuffix(live, allocated)),\n\t\tufmt.Sprintf(\"**%d reclaimable nodes**, about %d bytes of state\", dead, q.Bytes),\n\t\tufmt.Sprintf(\"refunds roughly **%s** to whoever compacts\", storagecost.FormatGNOT(q.Refund)),\n\t\tufmt.Sprintf(\"against **%s** of gas at the floor price, break-even at %d bytes\", storagecost.FormatGNOT(q.Fee), q.BreakEven),\n\t\tufmt.Sprintf(\"verdict: **%s**\", verdict(q, dead)),\n\t}))\n\tb.WriteString(\"\\n\")\n\n\tif dead \u003e 0 {\n\t\tb.WriteString(ui.Action(\"Compact it\", \"Compact\") + \"\\n\\n\")\n\t}\n\n\tb.WriteString(md.H2(\"Why allocated minus live is not the answer\"))\n\tb.WriteString(ufmt.Sprintf(\"\\nThis board has **%d** unused indices and **%d** reclaimable nodes. A dead element only becomes a reclaimable node once everything under it is dead too, so scattered holes free nothing while a dead tail frees a lot. That is why nobody can write down a rule for when to compact, and why the realm publishes the numbers instead of a schedule.\\n\\n\", allocated-live, dead))\n\n\tb.WriteString(md.H2(\"Board\"))\n\tb.WriteString(\"\\n\")\n\tif live == 0 {\n\t\tb.WriteString(\"Empty. \" + ui.Action(\"Add the first entry\", \"Add\", \"text\", \"hello\") + \"\\n\\n\")\n\t} else {\n\t\trows := []string{}\n\t\tfor i := 0; i \u003c allocated; i++ {\n\t\t\te, ok := entryAt(i)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trows = append(rows, ufmt.Sprintf(\"`#%d` %s | by %s at height %d\",\n\t\t\t\ti, ui.Excerpt(strings.ReplaceAll(e.Text, \"|\", \" \"), 48), ui.Addr(e.Author), e.Added))\n\t\t}\n\t\tb.WriteString(md.BulletList(rows))\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(md.HorizontalRule())\n\tb.WriteString(\"\\nThe arithmetic is [p/moul/x/storagecost](/p/moul/x/storagecost/v1); the container is [p/moul/ulist](/p/moul/ulist/v1), whose `Compact` drops dead nodes without moving a live index. The byte figure is an exact node count times a measured per-node constant, which is why it is sounder than a payload-derived bounty, but it is still an estimate: the chain's `StorageUnlockEvent` is the settlement.\\n\")\n\n\treturn b.String()\n}\n\n// ratioSuffix adds the fragmentation percentage, and says nothing at all when\n// the board is empty rather than dividing by zero.\nfunc ratioSuffix(live, allocated int) string {\n\tif allocated \u003c= 0 || live == allocated {\n\t\treturn \"\"\n\t}\n\treturn ufmt.Sprintf(\", %d%% of indices are holes\", (allocated-live)*100/allocated)\n}\n\nfunc verdict(q storagecost.Quote, dead int) string {\n\tif dead == 0 {\n\t\treturn \"nothing to reclaim, compacting would only burn gas\"\n\t}\n\tif q.Worth() {\n\t\treturn \"worth \" + storagecost.FormatGNOT(q.Net)\n\t}\n\treturn \"not worth the gas yet\"\n}\n"},{"name":"compact_test.gno","body":"package compact\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/storagecost/v1\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\t// janitor never adds anything, it only compacts. The whole point of the\n\t// realm is that this is the address the chain pays.\n\tjanitor = testutils.TestAddress(\"janitor\")\n)\n\n// drain empties the board and asserts it, so a test starts from a known\n// state whatever ran before it. Indices are append-addressed for the life of\n// the realm, so every test asserts on counts and never on absolute indices.\nfunc drain(cur realm, t *testing.T) {\n\tt.Helper()\n\tfor i := 0; i \u003c entries.TotalSize(); i++ {\n\t\tif e, ok := entryAt(i); ok {\n\t\t\ttesting.SetRealm(testing.NewUserRealm(e.Author))\n\t\t\tDrop(cross(cur), i)\n\t\t}\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(janitor))\n\tCompact(cross(cur))\n\tlive, _ := Fragmentation()\n\tuassert.Equal(t, 0, live)\n}\n\nfunc TestDropFreesNothingUntilCompact(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfor i := 0; i \u003c 8; i++ {\n\t\tAdd(cross(cur), \"entry\")\n\t}\n\tlive, allocated := Fragmentation()\n\tuassert.Equal(t, 8, live)\n\tuassert.Equal(t, 0, Reclaimable())\n\n\t// Dropping everything moves the live count but frees no nodes by itself.\n\tbase := allocated - 8\n\tfor i := base; i \u003c allocated; i++ {\n\t\tDrop(cross(cur), i)\n\t}\n\tlive, allocated2 := Fragmentation()\n\tuassert.Equal(t, 0, live)\n\tuassert.Equal(t, allocated, allocated2, \"a soft delete must not change the index space\")\n\tuassert.True(t, Reclaimable() \u003e 0, \"a fully dead tail should be reclaimable\")\n\n\t// And compaction is what actually frees them.\n\ttesting.SetRealm(testing.NewUserRealm(janitor))\n\tfreed := Compact(cross(cur))\n\tuassert.True(t, freed \u003e 0)\n\tuassert.Equal(t, 0, Reclaimable())\n\t// Compacting twice is not an error, it just frees nothing, so two bots\n\t// racing for the same nodes both survive rather than one aborting.\n\tuassert.Equal(t, 0, Compact(cross(cur)))\n}\n\n// TestScatteredHolesReclaimLessThanTheGap is the claim the Render makes, and\n// the reason the realm publishes two numbers instead of one. No other test\n// could catch it: they all drop contiguous runs.\nfunc TestScatteredHolesReclaimLessThanTheGap(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tbase := entries.TotalSize()\n\tfor i := 0; i \u003c 16; i++ {\n\t\tAdd(cross(cur), \"entry\")\n\t}\n\t// Every other index, so no whole subtree dies.\n\tfor i := base; i \u003c base+16; i += 2 {\n\t\tDrop(cross(cur), i)\n\t}\n\tlive, allocated := Fragmentation()\n\tgap := allocated - live\n\tuassert.True(t, gap \u003e= 8, \"eight holes were made\")\n\tuassert.True(t, Reclaimable() \u003c gap,\n\t\t\"scattered holes must reclaim fewer nodes than the gap suggests\")\n\n\tdrain(cur, t)\n}\n\nfunc TestOnlyTheAuthorMayDrop(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\ti := Add(cross(cur), \"alice's entry\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur, \"compact: only the author may drop an entry\", func() {\n\t\tDrop(cross(cur), i)\n\t})\n\t// But compaction stays permissionless, which is the asymmetry that makes\n\t// the mechanism work: choosing what dies is owned, reclaiming is not.\n\ttesting.SetRealm(testing.NewUserRealm(janitor))\n\tuassert.NotAborts(t, cur, func() { Compact(cross(cur)) })\n\n\tdrain(cur, t)\n}\n\nfunc TestAddRejectsBadInput(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"compact: empty entry\", func() {\n\t\tAdd(cross(cur), \"\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"compact: entry too long, 257 bytes against a 256 cap\", func() {\n\t\tAdd(cross(cur), strings.Repeat(\"x\", maxText+1))\n\t})\n\tuassert.AbortsContains(t, cur, \"compact: no live entry at\", func() {\n\t\tDrop(cross(cur), 99999)\n\t})\n}\n\n// TestQuoteCountsNodesRatherThanGuessingFromPayload is the design claim of the\n// realm. The quote must depend on the NODE COUNT and not on how fat the\n// entries were, which is exactly where a payload-derived bounty goes wrong.\nfunc TestQuoteCountsNodesRatherThanGuessingFromPayload(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\n\t// An empty board advertises nothing and must not claim a profit.\n\tempty := Quote()\n\tuassert.Equal(t, int64(0), empty.Bytes)\n\tuassert.False(t, empty.Worth())\n\n\t// Eight tiny entries, dropped and measured.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tbase := entries.TotalSize()\n\tfor i := 0; i \u003c 8; i++ {\n\t\tAdd(cross(cur), \"x\")\n\t}\n\tfor i := base; i \u003c base+8; i++ {\n\t\tDrop(cross(cur), i)\n\t}\n\ttiny := Quote()\n\ttinyNodes := Reclaimable()\n\ttesting.SetRealm(testing.NewUserRealm(janitor))\n\tCompact(cross(cur))\n\n\t// Eight fat entries, same count, same treatment.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tbase = entries.TotalSize()\n\tfat := strings.Repeat(\"y\", maxText)\n\tfor i := 0; i \u003c 8; i++ {\n\t\tAdd(cross(cur), fat)\n\t}\n\tfor i := base; i \u003c base+8; i++ {\n\t\tDrop(cross(cur), i)\n\t}\n\tbig := Quote()\n\n\tbigNodes := Reclaimable()\n\n\t// 256x the payload, and the quote is still purely a function of the node\n\t// count. Not the same TOTAL: the two batches sit at different offsets in\n\t// an append-addressed index space, so the tree shape differs and one\n\t// reclaimed a node more than the other. That is the honest version of the\n\t// claim, and asserting equal totals (which an earlier draft of this test\n\t// did) only passed by luck of the offsets.\n\tuassert.True(t, tinyNodes \u003e 0 \u0026\u0026 bigNodes \u003e 0)\n\tuassert.Equal(t, storagecost.EstimateNodes(int64(tinyNodes)), tiny.Bytes)\n\tuassert.Equal(t, storagecost.EstimateNodes(int64(bigNodes)), big.Bytes)\n\n\t// The rate is what must not move: same bytes per reclaimed node whether\n\t// the entries were 1 byte or 256. A payload-derived bounty would differ\n\t// by 256x here, which is the failure this realm is built to avoid.\n\tuassert.Equal(t, tiny.Bytes/int64(tinyNodes), big.Bytes/int64(bigNodes),\n\t\t\"bytes per reclaimed node must not depend on payload size\")\n\n\tdrain(cur, t)\n}\n\n// TestRenderEscapesTheBoard: an entry is a caller's string landing in an\n// inline markdown slot, so it goes through ui.Excerpt or it is an injection.\nfunc TestRenderEscapesTheBoard(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAdd(cross(cur), \"[Claim 100 GNOT](https://evil.example)\\n# Official\")\n\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, \"](https://evil.example)\"), out)\n\tuassert.False(t, strings.Contains(out, \"\\n# Official\"), out)\n\tuassert.True(t, strings.Contains(out, \"Claim 100 GNOT\"), out)\n\tuassert.True(t, strings.Contains(out, ui.Addr(alice)), out)\n\n\tdrain(cur, t)\n}\n\nfunc TestRenderShowsBothIntegersAndTheAction(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"# Compact\"), out)\n\tuassert.True(t, strings.Contains(out, \"Add the first entry\"), out)\n\tuassert.True(t, strings.Contains(out, \"nothing to reclaim\"), out)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tbase := entries.TotalSize()\n\tfor i := 0; i \u003c 8; i++ {\n\t\tAdd(cross(cur), \"entry\")\n\t}\n\tfor i := base; i \u003c base+8; i++ {\n\t\tDrop(cross(cur), i)\n\t}\n\tout = Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"reclaimable nodes\"), out)\n\tuassert.True(t, strings.Contains(out, \"$help\u0026func=Compact\"), out)\n\n\tdrain(cur, t)\n}\n\n// TestRenderNeverEmitsTwoBlankLines is what lets ExampleRender stay\n// meaningful: gno collapses them, so output containing them can never be\n// pinned by an example.\nfunc TestRenderNeverEmitsTwoBlankLines(cur realm, t *testing.T) {\n\tdrain(cur, t)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\ti := Add(cross(cur), \"one\")\n\tAdd(cross(cur), \"two\")\n\tDrop(cross(cur), i)\n\n\tfor _, path := range []string{\"\", \"anything\"} {\n\t\tout := Render(path)\n\t\tuassert.False(t, strings.Contains(out, \"\\n\\n\\n\"), \"blank-line run in Render(\"+path+\")\")\n\t}\n\n\tdrain(cur, t)\n}\n"},{"name":"example_test.gno","body":"package compact\n\nimport \"strings\"\n\n// ExampleRender pins the page's skeleton: the title and the three sections\n// that are always there, whatever the board holds.\n//\n// Only the invariant lines, on purpose. Everything else on the page is\n// derived from the current fragmentation, and an Example runs after every\n// Test in the package and sees whatever state they left. The variable half is\n// pinned by TestRenderShowsBothIntegersAndTheAction, which controls the board\n// first.\nfunc ExampleRender() {\n\tfor _, line := range strings.Split(Render(\"\"), \"\\n\") {\n\t\tswitch {\n\t\tcase strings.HasPrefix(line, \"# \"),\n\t\t\tstrings.HasPrefix(line, \"## \"),\n\t\t\tstrings.HasPrefix(line, \"Soft-deleting\"):\n\t\t\tprint(line + \"\\n\")\n\t\t}\n\t}\n\t// Output:\n\t// # Compact\n\t// Soft-deleting an entry frees nothing: the tree node stays, the bytes stay locked, and every read still walks past the hole. Compacting drops those nodes and the chain refunds their deposit **to whoever signs the transaction**. The only question is when.\n\t// ## The two integers\n\t// ## Why allocated minus live is not the answer\n\t// ## Board\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/compact/v0\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"73705800","gas_fee":"221117ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"flVHH736INZgZmEyK5SWLsFEGF+sVNYxVFWykcGcXRkfC3IMLwaTf28d4ScoaCULOGO/HQr0SZ8kJ+HhVM0GHg=="}],"memo":""},"metadata":{"timestamp":"1790960824"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"asciiart","path":"gno.land/r/moul/x/daily/asciiart/v1","files":[{"name":"README.md","body":"# ASCII Art Generator\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nAn on-chain ASCII art generator that draws patterns (diamond, pyramid, Sierpinski triangle, checkerboard) from short deterministic formulas instead of a hand-authored font table -- the Sierpinski gasket is just `row \u0026 col == 0`. Call Generate(pattern, size) to render a piece and add it to a public gallery; browse the gallery or a specific piece via Render. It's a neat, self-contained example of generative art as pure on-chain logic.\n\nBuilt for sapphire (gno 0.9). Live demo (agent address): https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/asciiart\n\n## What changed in v1\n\nTwo ports against [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/asciiart), which stays live and untouched.\n\n### Rendering\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/asciiart) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline` helper.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\n### Storage\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\n`v0` padded ids to width 6. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`piece` loses its `ID` field, which the store now owns. The gallery page also\ngets simpler: `v0` reverse-iterated the whole tree with a `shown` counter to\nstop at eight, where `PageReverse(1, 8)` asks the store for exactly that window.\nA non-numeric or zero path is now rejected by `ParseID` rather than by\n`strconv.Atoi` plus a range check.\n\nIds stay plain integers and the rendered output of the storage port is\nunchanged. Each port changes something `v0` promised, one the rendered output\nand one the storage layout, so under this repo's versioning rule each is a\ncompatibility change and neither could be an edit to `v0` in place.\n\nThey land in the **same** new version because `v1` was never published. A\nversion number is a tag on something that exists on a chain, and until it does\nthere is nothing for a second number to avoid disturbing, so the right move is\nto keep editing the version you have. `gnopm unbump` is what folded the second\nport back down into this one.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/asciiart/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/asciiart/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/asciiart/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/asciiart/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/asciiart/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/asciiart/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/asciiart/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/asciiart/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/asciiart/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/asciiart/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"asciiart.gno","body":"// Package asciiart is a small on-chain ASCII art generator. Instead of a\n// hand-authored font table, each pattern is produced by a short, pure,\n// deterministic algorithm -- e.g. the Sierpinski triangle falls out of a\n// single bitwise AND over row/column indices. Callers pick a pattern and a\n// size; the realm renders it and keeps a gallery of everyone's generations.\npackage asciiart\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\n// maxSize bounds every pattern's size parameter so a single Generate call\n// can't blow the block gas limit on a pathologically large grid.\nconst maxSize = 32\n\n// galleryPageSize caps how many pieces Render shows on the home page.\nconst galleryPageSize = 8\n\n// piece carries no ID field: the id belongs to the store, which hands it back\n// on lookup and iteration.\ntype piece struct {\n\tPattern   string\n\tSize      int\n\tAuthor    address\n\tCreatedAt int64\n\tArt       string\n}\n\n// gallery assigns the piece ids. v1 kept its own nextID plus a padID() that\n// zero-padded to width 6, the narrowest ceiling in this repo: at the millionth\n// piece the padding stops and the gallery starts rendering out of order. The\n// store key is 8 fixed bytes with no width to outgrow.\nvar gallery = store.Named(\"piece\")\n\n// RenderDiamond draws a filled diamond of half-width n (2n-1 rows total),\n// each row's stars centered and padded with spaces.\nfunc RenderDiamond(n int) string {\n\tif n \u003c 1 {\n\t\tpanic(\"diamond size must be \u003e= 1\")\n\t}\n\tvar b strings.Builder\n\tfor i := 0; i \u003c 2*n-1; i++ {\n\t\td := i\n\t\tif i \u003e= n {\n\t\t\td = 2*n - 2 - i\n\t\t}\n\t\tb.WriteString(strings.Repeat(\" \", n-1-d))\n\t\tb.WriteString(strings.Repeat(\"*\", 2*d+1))\n\t\tif i \u003c 2*n-2 {\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// RenderPyramid draws a solid triangle n rows tall, widening by two stars\n// per row and centered with leading spaces.\nfunc RenderPyramid(n int) string {\n\tif n \u003c 1 {\n\t\tpanic(\"pyramid size must be \u003e= 1\")\n\t}\n\tvar b strings.Builder\n\tfor i := 0; i \u003c n; i++ {\n\t\tb.WriteString(strings.Repeat(\" \", n-1-i))\n\t\tb.WriteString(strings.Repeat(\"*\", 2*i+1))\n\t\tif i \u003c n-1 {\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// RenderSierpinski draws a Sierpinski triangle in an n x n grid (n must be a\n// power of two): cell (row, col) is filled exactly when row\u0026col == 0, the\n// classic bitwise identity for Pascal's-triangle-mod-2.\nfunc RenderSierpinski(n int) string {\n\tif n \u003c 1 || n\u0026(n-1) != 0 {\n\t\tpanic(\"sierpinski size must be a power of two (1, 2, 4, 8, 16, 32)\")\n\t}\n\tvar b strings.Builder\n\tfor row := 0; row \u003c n; row++ {\n\t\tfor col := 0; col \u003c n; col++ {\n\t\t\tif row\u0026col == 0 {\n\t\t\t\tb.WriteString(\"#\")\n\t\t\t} else {\n\t\t\t\tb.WriteString(\" \")\n\t\t\t}\n\t\t}\n\t\tif row \u003c n-1 {\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\n// RenderChecker draws an n x n checkerboard of # and . cells.\nfunc RenderChecker(n int) string {\n\tif n \u003c 1 {\n\t\tpanic(\"checker size must be \u003e= 1\")\n\t}\n\tvar b strings.Builder\n\tfor row := 0; row \u003c n; row++ {\n\t\tfor col := 0; col \u003c n; col++ {\n\t\t\tif (row+col)%2 == 0 {\n\t\t\t\tb.WriteString(\"#\")\n\t\t\t} else {\n\t\t\t\tb.WriteString(\".\")\n\t\t\t}\n\t\t}\n\t\tif row \u003c n-1 {\n\t\t\tb.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc renderPattern(pattern string, size int) string {\n\tswitch pattern {\n\tcase \"diamond\":\n\t\treturn RenderDiamond(size)\n\tcase \"pyramid\":\n\t\treturn RenderPyramid(size)\n\tcase \"sierpinski\":\n\t\treturn RenderSierpinski(size)\n\tcase \"checker\":\n\t\treturn RenderChecker(size)\n\tdefault:\n\t\tpanic(`unknown pattern: use \"diamond\", \"pyramid\", \"sierpinski\", or \"checker\"`)\n\t}\n}\n\n// Generate renders a pattern, adds it to the on-chain gallery, and returns\n// the rendered art.\nfunc Generate(cur realm, pattern string, size int) string {\n\tif size \u003c 1 || size \u003e maxSize {\n\t\tpanic(\"size must be between 1 and \" + strconv.Itoa(maxSize))\n\t}\n\tart := renderPattern(pattern, size)\n\n\tauthor := cur.Previous().Address()\n\tid := gallery.Add(\u0026piece{\n\t\tPattern:   pattern,\n\t\tSize:      size,\n\t\tAuthor:    author,\n\t\tCreatedAt: runtime.ChainHeight(),\n\t\tArt:       art,\n\t})\n\n\tchain.Emit(\"ArtGenerated\", \"id\", id.String(), \"pattern\", pattern, \"author\", author.String())\n\n\treturn art\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# ASCII Art Generator\\n\\n\")\n\tb.WriteString(\"Four deterministic patterns, no font table required -- each shape \" +\n\t\t\"falls out of a short formula over row/column indices. Pick a pattern and a \" +\n\t\t\"size (1-\" + strconv.Itoa(maxSize) + \", sierpinski wants a power of two) and \" +\n\t\t\"`Generate` adds it to the gallery below.\\n\\n\")\n\tb.WriteString(\"## Patterns\\n\\n\")\n\tb.WriteString(\"- `diamond` -- filled diamond, half-width `size`\\n\")\n\tb.WriteString(\"- `pyramid` -- solid triangle, `size` rows tall\\n\")\n\tb.WriteString(\"- `sierpinski` -- Sierpinski gasket in an n×n grid \" +\n\t\t\"(`row \u0026 col == 0`), `size` a power of two\\n\")\n\tb.WriteString(\"- `checker` -- n×n checkerboard\\n\\n\")\n\tb.WriteString(\"Call `Generate(pattern, size)`. View a piece at this realm's path \" +\n\t\t\"plus its ID (e.g. `.../asciiart:3`).\\n\\n\")\n\n\tb.WriteString(\"## Gallery (total: \" + gallery.LastID().String() + \")\\n\\n\")\n\tif gallery.Len() == 0 {\n\t\tb.WriteString(\"_nothing generated yet -- be the first_\\n\")\n\t\treturn b.String()\n\t}\n\n\t// The newest page, straight from the store: no counter, and only that\n\t// window is walked.\n\tfor _, e := range gallery.PageReverse(1, galleryPageSize) {\n\t\tp := e.Value.(*piece)\n\t\tb.WriteString(\"### #\" + e.ID.String() + \" -- \" + p.Pattern + \" (size \" + strconv.Itoa(p.Size) + \")\\n\\n\")\n\t\tb.WriteString(\"by `\" + p.Author.String() + \"` at block \" + strconv.Itoa(int(p.CreatedAt)) + \"\\n\\n\")\n\t\tb.WriteString(\"```\\n\" + p.Art + \"\\n```\\n\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderPiece(idStr string) string {\n\tsafe := ui.Inline(idStr)\n\tid, ok := store.ParseID(idStr)\n\tif !ok {\n\t\treturn \"# Piece \" + safe + \"\\n\\nNo such piece.\\n\"\n\t}\n\tv, ok := gallery.Get(id)\n\tif !ok {\n\t\treturn \"# Piece #\" + safe + \"\\n\\nNo such piece.\\n\"\n\t}\n\tp := v.(*piece)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Piece #\" + id.String() + \"\\n\\n\")\n\tb.WriteString(\"- Pattern: \" + p.Pattern + \"\\n\")\n\tb.WriteString(\"- Size: \" + strconv.Itoa(p.Size) + \"\\n\")\n\tb.WriteString(\"- Author: `\" + p.Author.String() + \"`\\n\")\n\tb.WriteString(\"- Block: \" + strconv.Itoa(int(p.CreatedAt)) + \"\\n\\n\")\n\tb.WriteString(\"```\\n\" + p.Art + \"\\n```\\n\")\n\treturn b.String()\n}\n\n// Render shows the pattern guide + gallery at \"\", or one piece by numeric ID.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderPiece(path)\n}\n"},{"name":"asciiart_test.gno","body":"package asciiart\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tgallery = store.Named(\"piece\")\n}\n\nfunc TestRenderDiamond(t *testing.T) {\n\tgot := RenderDiamond(3)\n\twant := \"  *\\n ***\\n*****\\n ***\\n  *\"\n\tif got != want {\n\t\tt.Fatalf(\"RenderDiamond(3) =\\n%s\\nwant\\n%s\", got, want)\n\t}\n}\n\nfunc TestRenderPyramid(t *testing.T) {\n\tgot := RenderPyramid(3)\n\twant := \"  *\\n ***\\n*****\"\n\tif got != want {\n\t\tt.Fatalf(\"RenderPyramid(3) =\\n%s\\nwant\\n%s\", got, want)\n\t}\n}\n\nfunc TestRenderSierpinski(t *testing.T) {\n\tgot := RenderSierpinski(4)\n\twant := \"####\\n# # \\n##  \\n#   \"\n\tif got != want {\n\t\tt.Fatalf(\"RenderSierpinski(4) =\\n%s\\nwant\\n%s\", got, want)\n\t}\n}\n\nfunc TestRenderSierpinskiRejectsNonPowerOfTwo(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic for a non-power-of-two size\")\n\t\t}\n\t}()\n\tRenderSierpinski(5)\n}\n\nfunc TestRenderChecker(t *testing.T) {\n\tgot := RenderChecker(3)\n\twant := \"#.#\\n.#.\\n#.#\"\n\tif got != want {\n\t\tt.Fatalf(\"RenderChecker(3) =\\n%s\\nwant\\n%s\", got, want)\n\t}\n}\n\nfunc TestRenderPatternUnknown(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic for an unknown pattern\")\n\t\t}\n\t}()\n\trenderPattern(\"spiral\", 3)\n}\n\n// v1 asserted that its own padID() padded to width 6. That is the narrowest\n// ceiling in this repo: padID(10^6) is 7 characters and sorts before\n// padID(10^6-1), so from the millionth piece on the gallery would have\n// rendered out of order. The store key is 8 bytes for every id.\nfunc TestPadID(t *testing.T) {\n\tif a, b := store.ID(2).Key(), store.ID(10).Key(); !(a \u003c b) {\n\t\tt.Error(\"id 2 should sort before id 10\")\n\t}\n\tif a, b := store.ID(999999).Key(), store.ID(1000000).Key(); !(a \u003c b) {\n\t\tt.Error(\"ordering should survive one past v1's width-6 ceiling\")\n\t}\n}\n\n// Crossing: Generate mutates realm state, so the test needs `cur realm`.\nfunc TestGenerateAddsToGallery(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tart := Generate(cross(cur), \"checker\", 3)\n\tif art != RenderChecker(3) {\n\t\tt.Fatal(\"Generate should return the rendered art\")\n\t}\n\tif gallery.LastID() != 1 {\n\t\tt.Fatalf(\"LastID = %s, want 1\", gallery.LastID())\n\t}\n\n\t// The store's Get returns (value, ok), so a stored nil is distinguishable\n\t// from an absent id, which avl/v0's single-value Get cannot express.\n\tv, ok := gallery.Get(1)\n\tif !ok {\n\t\tt.Fatal(\"expected piece #1 to exist in the gallery\")\n\t}\n\tp := v.(*piece)\n\tif p.Pattern != \"checker\" || p.Size != 3 || p.Author != alice {\n\t\tt.Fatalf(\"unexpected piece: %+v\", p)\n\t}\n}\n\nfunc TestGenerateRejectsOutOfRangeSize(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\trec := revive(func() { Generate(cross(cur), \"diamond\", 0) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic for size \u003c 1\")\n\t}\n\trec = revive(func() { Generate(cross(cur), \"diamond\", maxSize+1) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic for size \u003e maxSize\")\n\t}\n}\n\n// Non-crossing: Render is a plain read.\nfunc TestRenderHomeEmptyGallery(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"nothing generated yet\") {\n\t\tt.Fatal(`Render(\"\") on an empty gallery should say so`)\n\t}\n}\n\nfunc TestRenderPieceNotFound(t *testing.T) {\n\tresetState()\n\tout := Render(\"99\")\n\tif !strings.Contains(out, \"No such piece\") {\n\t\tt.Fatal(`Render(\"99\") on a missing piece should say so`)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/asciiart/v1\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"50311000","gas_fee":"150933ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"xHzfwycgK1fxJS38rdw1rw171IsJyXhIEope1hzE4eZcouv5ILYxInbqcC2NStM/bJEK7FZvsCc0Tu9vlxdAIg=="}],"memo":""},"metadata":{"timestamp":"1790960829"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"b58demo","path":"gno.land/r/moul/x/daily/b58demo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/b58demo/v0`\n\nInteractive gnoweb **demo of the [`p/moul/x/daily/b58`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/b58)\nBase58 library** — it renders the alphabet, a gallery of worked examples, and a\nhex → Base58 round-tripper. It has no codec logic of its own.\n\nAppend a hex string to the path to encode/round-trip it, e.g.\n[`/r/moul/x/daily/b58demo/v0:deadbeef`](https://gno.land/r/moul/x/daily/b58demo/v0:deadbeef).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/b58demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/b58demo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/b58demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/b58demo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/b58demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/b58demo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/b58demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/b58demo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/b58demo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/b58demo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"b58demo.gno","body":"// Package b58demo is a small gnoweb demo of the Base58 codec provided by the\n// [p/moul/x/daily/b58](/p/moul/x/daily/b58/v0) library: it renders the alphabet,\n// a gallery of worked examples, and an interactive hex → Base58 round-tripper.\n//\n// It contains no codec logic of its own — everything comes from `b58.Encode`,\n// `b58.Decode` and `b58.Alphabet`.\npackage b58demo\n\nimport (\n\t\"encoding/hex\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/b58/v0\"\n)\n\n// Render produces the gnoweb Markdown view.\n//\n//   - \"/\"        → the alphabet + a small gallery of worked examples.\n//   - \"/\u003chex\u003e\"   → decode the hex input to bytes, show its Base58, and the\n//     hex-encoded decoded round-trip to prove Encode/Decode are inverse.\nfunc Render(path string) string {\n\targ := strings.TrimPrefix(path, \"/\")\n\targ = strings.TrimSpace(arg)\n\n\tif arg == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderHex(arg)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Base58 (Bitcoin alphabet)\\n\\n\")\n\tsb.WriteString(\"Demo of the [`p/moul/x/daily/b58`](/p/moul/x/daily/b58/v0) library — \")\n\tsb.WriteString(\"base conversion from raw bytes (base-256) to base-58, using the \")\n\tsb.WriteString(\"Bitcoin alphabet (no `0`, `O`, `I`, `l`), pure byte-slice math, no `math/big`.\\n\\n\")\n\n\tsb.WriteString(\"## Alphabet\\n\\n\")\n\tsb.WriteString(\"```\\n\")\n\tsb.WriteString(b58.Alphabet)\n\tsb.WriteString(\"\\n```\\n\\n\")\n\tsb.WriteString(\"58 characters, index 0…57.\\n\\n\")\n\n\tsb.WriteString(\"## Examples\\n\\n\")\n\tsb.WriteString(\"| input (utf-8) | hex | Base58 |\\n\")\n\tsb.WriteString(\"|---|---|---|\\n\")\n\texamples := []string{\"\", \"hello world\", \"gno.land\", \"Bitcoin\"}\n\tfor _, e := range examples {\n\t\th := hex.EncodeToString([]byte(e))\n\t\tif h == \"\" {\n\t\t\th = \"(empty)\"\n\t\t}\n\t\tlabel := e\n\t\tif label == \"\" {\n\t\t\tlabel = \"(empty)\"\n\t\t}\n\t\tsb.WriteString(\"| `\" + label + \"` | `\" + h + \"` | `\" + b58.Encode([]byte(e)) + \"` |\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"Leading zero bytes → leading `1`s:\\n\\n\")\n\tsb.WriteString(\"| bytes | Base58 |\\n|---|---|\\n\")\n\tsb.WriteString(\"| `[0x00]` | `\" + b58.Encode([]byte{0}) + \"` |\\n\")\n\tsb.WriteString(\"| `[0x00 0x00 0x00]` | `\" + b58.Encode([]byte{0, 0, 0}) + \"` |\\n\\n\")\n\n\tsb.WriteString(\"## Try it\\n\\n\")\n\tsb.WriteString(\"Append a hex string to the path to encode/round-trip it:\\n\\n\")\n\tsb.WriteString(\"- `/68656c6c6f` — the bytes for \\\"hello\\\"\\n\")\n\tsb.WriteString(\"- `/00000000` — four zero bytes\\n\")\n\tsb.WriteString(\"- `/deadbeef`\\n\")\n\treturn sb.String()\n}\n\nfunc renderHex(arg string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Base58 — round-trip\\n\\n\")\n\tsb.WriteString(\"[← alphabet \u0026 examples](/r/moul/x/daily/b58demo/v0)\\n\\n\")\n\n\traw, err := hex.DecodeString(arg)\n\tif err != nil {\n\t\tsb.WriteString(\"**Invalid hex input.**\\n\\n\")\n\t\tsb.WriteString(\"`\" + arg + \"` is not a valid hex string. \")\n\t\tsb.WriteString(\"Provide an even number of hex digits, e.g. `/deadbeef`.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tencoded := b58.Encode(raw)\n\tdecoded := b58.Decode(encoded)\n\troundTrip := hex.EncodeToString(decoded)\n\n\tinHex := arg\n\tif inHex == \"\" {\n\t\tinHex = \"(empty)\"\n\t}\n\toutHex := roundTrip\n\tif outHex == \"\" {\n\t\toutHex = \"(empty)\"\n\t}\n\tenc := encoded\n\tif enc == \"\" {\n\t\tenc = \"(empty)\"\n\t}\n\n\tsb.WriteString(\"| step | value |\\n|---|---|\\n\")\n\tsb.WriteString(\"| hex input | `\" + inHex + \"` |\\n\")\n\tsb.WriteString(\"| bytes | `\" + byteList(raw) + \"` |\\n\")\n\tsb.WriteString(\"| **Base58** | `\" + enc + \"` |\\n\")\n\tsb.WriteString(\"| decoded (hex) | `\" + outHex + \"` |\\n\\n\")\n\n\tif roundTrip == arg {\n\t\tsb.WriteString(\"✓ Round-trip matches: `Decode(Encode(x)) == x`.\\n\")\n\t} else {\n\t\tsb.WriteString(\"✗ Round-trip mismatch.\\n\")\n\t}\n\treturn sb.String()\n}\n\n// byteList renders a byte slice as a compact space-separated hex list.\nfunc byteList(b []byte) string {\n\tif len(b) == 0 {\n\t\treturn \"(none)\"\n\t}\n\tconst digits = \"0123456789abcdef\"\n\tout := make([]byte, 0, len(b)*3)\n\tfor i, c := range b {\n\t\tif i \u003e 0 {\n\t\t\tout = append(out, ' ')\n\t\t}\n\t\tout = append(out, digits[c\u003e\u003e4], digits[c\u00260x0f])\n\t}\n\treturn string(out)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/b58demo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package b58demo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Base58 (Bitcoin alphabet)\n\t//\n\t// Demo of the [`p/moul/x/daily/b58`](/p/moul/x/daily/b58/v0) library — base conversion from raw bytes (base-256) to base-58, using the Bitcoin alphabet (no `0`, `O`, `I`, `l`), pure byte-slice math, no `math/big`.\n\t//\n\t// ## Alphabet\n\t//\n\t// ```\n\t// 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\n\t// ```\n\t//\n\t// 58 characters, index 0…57.\n\t//\n\t// ## Examples\n\t//\n\t// | input (utf-8) | hex | Base58 |\n\t// |---|---|---|\n\t// | `(empty)` | `(empty)` | `` |\n\t// | `hello world` | `68656c6c6f20776f726c64` | `StV1DL6CwTryKyV` |\n\t// | `gno.land` | `676e6f2e6c616e64` | `JJR1f4BQc9H` |\n\t// | `Bitcoin` | `426974636f696e` | `3WyEDWjcVB` |\n\t//\n\t// Leading zero bytes → leading `1`s:\n\t//\n\t// | bytes | Base58 |\n\t// |---|---|\n\t// | `[0x00]` | `1` |\n\t// | `[0x00 0x00 0x00]` | `111` |\n\t//\n\t// ## Try it\n\t//\n\t// Append a hex string to the path to encode/round-trip it:\n\t//\n\t// - `/68656c6c6f` — the bytes for \"hello\"\n\t// - `/00000000` — four zero bytes\n\t// - `/deadbeef`\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"30587400","gas_fee":"91762ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"H/CWk5F94QUm8Em3xIKwI9sUBQxaCkXHMGItLuXY09kNBO0I0oRoc1R/lG0vATvZcSBZXVQXOGAOHPXxQ/4clA=="}],"memo":""},"metadata":{"timestamp":"1790960830"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ballot","path":"gno.land/r/moul/x/daily/ballot/v0","files":[{"name":"README.md","body":"# Ballot\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA Gno port of the classic Solidity \"Ballot\" voting contract: a chairperson seeds a fixed list of proposals and grants specific addresses the right to vote, and each voter either casts a direct vote or delegates their weight down a delegation chain (with a loop guard, just like the original). WinningProposal/WinnerName report the current leader live, so there's no separate close-the-vote step. It's neat because delegation composability - a delegate's weight can itself be re-delegated - is the one part of the original contract that's easy to get subtly wrong, and this port keeps that chain-walking + cycle-detection logic faithful while swapping mappings for an avl.Tree.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/ballot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ballot/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/ballot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ballot/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/ballot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ballot/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/ballot/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ballot/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/ballot/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/ballot/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"ballot.gno","body":"// Package ballot is a Gno port of the classic Solidity \"Ballot\" voting\n// contract from the Solidity docs. A chairperson seeds a fixed list of\n// proposals and grants specific addresses the right to vote; each voter can\n// either cast a direct vote or delegate their weight to another voter, and\n// delegation follows a chain so a delegate who later delegates further still\n// carries every accumulated weight. The winning proposal is whichever has\n// the most accumulated weight at query time.\npackage ballot\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// proposal is one of the fixed choices set up at Init time.\ntype proposal struct {\n\tname  string\n\tvotes uint64\n}\n\n// voterInfo tracks one address's voting rights and delegation state.\ntype voterInfo struct {\n\tweight   uint64  // 0 means \"no right to vote\"\n\tvoted    bool    // true once the weight has been cast (directly or delegated away)\n\tdelegate address // set only when voted == true and this voter delegated\n\tvote     int     // proposal index this voter's weight ended up on, valid once tallied\n}\n\n// Package-level persistent state.\nvar (\n\tchairperson address\n\tinitialized bool\n\tproposals   []proposal\n\tvoters      *avl.Tree // address string -\u003e *voterInfo\n)\n\nvar (\n\terrAlreadyInit    = errors.New(\"ballot: already initialized\")\n\terrNotInit        = errors.New(\"ballot: not initialized yet\")\n\terrNotChairperson = errors.New(\"ballot: only the chairperson may do this\")\n\terrNoProposals    = errors.New(\"ballot: at least one proposal name is required\")\n\terrInvalidAddr    = errors.New(\"ballot: invalid address\")\n\terrAlreadyRight   = errors.New(\"ballot: voter already has the right to vote\")\n\terrAlreadyVoted   = errors.New(\"ballot: voter already voted\")\n\terrNoRight        = errors.New(\"ballot: caller has no right to vote\")\n\terrSelfDelegate   = errors.New(\"ballot: self-delegation is not allowed\")\n\terrDelegateLoop   = errors.New(\"ballot: found a loop in the delegation chain\")\n\terrDelegateNoRight = errors.New(\"ballot: delegate has no right to vote\")\n\terrBadProposal    = errors.New(\"ballot: invalid proposal index\")\n)\n\nfunc init() {\n\tvoters = avl.NewTree()\n}\n\nfunc requireInit() {\n\tif !initialized {\n\t\tpanic(errNotInit)\n\t}\n}\n\nfunc getOrCreateVoter(addr address) *voterInfo {\n\tif v := voters.Get(addr.String()); v != nil {\n\t\treturn v.(*voterInfo)\n\t}\n\tv := \u0026voterInfo{}\n\tvoters.Set(addr.String(), v)\n\treturn v\n}\n\n// Init configures the ballot exactly once: the caller becomes the\n// chairperson (and is immediately given the right to vote), and\n// proposalNamesCSV — a comma-separated list — seeds the fixed set of\n// proposals. It panics if called twice or with no usable proposal names.\nfunc Init(cur realm, proposalNamesCSV string) {\n\tif initialized {\n\t\tpanic(errAlreadyInit)\n\t}\n\n\tfor _, raw := range strings.Split(proposalNamesCSV, \",\") {\n\t\tname := strings.TrimSpace(raw)\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tproposals = append(proposals, proposal{name: name})\n\t}\n\tif len(proposals) == 0 {\n\t\tpanic(errNoProposals)\n\t}\n\n\tchairperson = cur.Previous().Address()\n\tvoters.Set(chairperson.String(), \u0026voterInfo{weight: 1})\n\tinitialized = true\n}\n\n// GiveRightToVote grants voterAddr a voting weight of 1. Only the\n// chairperson may call this, and only for voters who haven't voted yet.\nfunc GiveRightToVote(cur realm, voterAddr string) {\n\trequireInit()\n\tif cur.Previous().Address() != chairperson {\n\t\tpanic(errNotChairperson)\n\t}\n\n\taddr := address(voterAddr)\n\tif !addr.IsValid() {\n\t\tpanic(errInvalidAddr)\n\t}\n\n\tv := getOrCreateVoter(addr)\n\tif v.voted {\n\t\tpanic(errAlreadyVoted)\n\t}\n\tif v.weight != 0 {\n\t\tpanic(errAlreadyRight)\n\t}\n\tv.weight = 1\n}\n\n// Delegate hands the caller's voting weight to toAddr. If toAddr has\n// already voted, the weight is added directly to that proposal's tally;\n// otherwise it accumulates on toAddr's own weight, ready to be cast (or\n// delegated further) later. Mirrors Solidity's delegation-chain-following\n// with a loop guard.\nfunc Delegate(cur realm, toAddr string) {\n\trequireInit()\n\n\tsender := cur.Previous().Address()\n\tfrom := getOrCreateVoter(sender)\n\tif from.weight == 0 {\n\t\tpanic(errNoRight)\n\t}\n\tif from.voted {\n\t\tpanic(errAlreadyVoted)\n\t}\n\n\tto := address(toAddr)\n\tif !to.IsValid() {\n\t\tpanic(errInvalidAddr)\n\t}\n\tif to == sender {\n\t\tpanic(errSelfDelegate)\n\t}\n\n\tvar zero address\n\tmaxSteps := voters.Size() + 1\n\tfor steps := 0; ; steps++ {\n\t\tv := voters.Get(to.String())\n\t\tif v == nil {\n\t\t\tbreak\n\t\t}\n\t\tnext := v.(*voterInfo).delegate\n\t\tif next == zero {\n\t\t\tbreak\n\t\t}\n\t\tto = next\n\t\tif to == sender {\n\t\t\tpanic(errDelegateLoop)\n\t\t}\n\t\tif steps \u003e maxSteps {\n\t\t\tpanic(errDelegateLoop)\n\t\t}\n\t}\n\n\tdelegateVoter := getOrCreateVoter(to)\n\tif delegateVoter.weight == 0 {\n\t\tpanic(errDelegateNoRight)\n\t}\n\n\tfrom.voted = true\n\tfrom.delegate = to\n\n\tif delegateVoter.voted {\n\t\tproposals[delegateVoter.vote].votes += from.weight\n\t} else {\n\t\tdelegateVoter.weight += from.weight\n\t}\n}\n\n// Vote casts the caller's full weight for proposals[proposalIndex].\nfunc Vote(cur realm, proposalIndex int) {\n\trequireInit()\n\n\tsender := cur.Previous().Address()\n\tv := getOrCreateVoter(sender)\n\tif v.weight == 0 {\n\t\tpanic(errNoRight)\n\t}\n\tif v.voted {\n\t\tpanic(errAlreadyVoted)\n\t}\n\tif proposalIndex \u003c 0 || proposalIndex \u003e= len(proposals) {\n\t\tpanic(errBadProposal)\n\t}\n\n\tv.voted = true\n\tv.vote = proposalIndex\n\tproposals[proposalIndex].votes += v.weight\n}\n\n// WinningProposal returns the index of the proposal with the most\n// accumulated weight, breaking ties in favor of the lowest index.\nfunc WinningProposal() int {\n\twinner := 0\n\tbest := uint64(0)\n\tfor i, p := range proposals {\n\t\tif p.votes \u003e best {\n\t\t\tbest = p.votes\n\t\t\twinner = i\n\t\t}\n\t}\n\treturn winner\n}\n\n// WinnerName returns the name of the current winning proposal, or \"\" if\n// the ballot hasn't been initialized.\nfunc WinnerName() string {\n\tif len(proposals) == 0 {\n\t\treturn \"\"\n\t}\n\treturn proposals[WinningProposal()].name\n}\n\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Ballot\\n\\n\")\n\n\tif !initialized {\n\t\tb.WriteString(\"Not initialized yet. The first caller to run `Init` becomes the \" +\n\t\t\t\"chairperson and seeds the proposal list, e.g.:\\n\\n\")\n\t\tb.WriteString(\"```\\nInit(\\\"Alice,Bob,Carol\\\")\\n```\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"Chairperson: `\" + chairperson.String() + \"`\\n\\n\")\n\tb.WriteString(\"| # | Proposal | Votes |\\n\")\n\tb.WriteString(\"|---|---|---|\\n\")\n\tfor i, p := range proposals {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i) + \" | \" + p.name + \" | \" +\n\t\t\tstrconv.FormatUint(p.votes, 10) + \" |\\n\")\n\t}\n\n\tb.WriteString(\"\\nCurrent winner: **\" + WinnerName() + \"** (index \" +\n\t\tstrconv.Itoa(WinningProposal()) + \")\\n\\n\")\n\tb.WriteString(\"Registered voters: \" + strconv.Itoa(voters.Size()) + \"\\n\")\n\treturn b.String()\n}\n"},{"name":"ballot_test.gno","body":"package ballot\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tvar zero address\n\tchairperson = zero\n\tinitialized = false\n\tproposals = nil\n\tvoters = avl.NewTree()\n}\n\n// Crossing: Init/Vote/Delegate/GiveRightToVote mutate realm state, so tests\n// that call them need `cur realm`.\nfunc TestInitSetsChairpersonAndProposals(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"Alice, Bob , Carol\")\n\n\tif chairperson != alice {\n\t\tt.Fatal(\"chairperson should be the Init caller\")\n\t}\n\tif len(proposals) != 3 {\n\t\tt.Fatalf(\"len(proposals) = %d, want 3\", len(proposals))\n\t}\n\tif proposals[0].name != \"Alice\" || proposals[1].name != \"Bob\" || proposals[2].name != \"Carol\" {\n\t\tt.Fatal(\"proposal names should be trimmed and in order\")\n\t}\n\n\trec := revive(func() { Init(cross(cur), \"X\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic on double Init\")\n\t}\n}\n\nfunc TestGiveRightToVoteOnlyChairperson(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tmallory := testutils.TestAddress(\"mallory\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B\")\n\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\trec := revive(func() { GiveRightToVote(cross(cur), bob.String()) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when a non-chairperson grants voting rights\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tGiveRightToVote(cross(cur), bob.String())\n\n\tv := voters.Get(bob.String())\n\tif v == nil || v.(*voterInfo).weight != 1 {\n\t\tt.Fatal(\"bob should now have voting weight 1\")\n\t}\n}\n\nfunc TestVoteDirectly(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B\")\n\tVote(cross(cur), 1)\n\n\tif proposals[1].votes != 1 {\n\t\tt.Fatalf(\"proposals[1].votes = %d, want 1\", proposals[1].votes)\n\t}\n\tif WinnerName() != \"B\" {\n\t\tt.Fatalf(\"WinnerName() = %q, want B\", WinnerName())\n\t}\n\n\trec := revive(func() { Vote(cross(cur), 0) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic on double vote\")\n\t}\n}\n\nfunc TestDelegateToUnvotedAccumulatesWeight(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B\")\n\tGiveRightToVote(cross(cur), bob.String())\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tDelegate(cross(cur), alice.String())\n\n\taliceVoter := voters.Get(alice.String())\n\tif aliceVoter.(*voterInfo).weight != 2 {\n\t\tt.Fatalf(\"alice.weight = %d, want 2\", aliceVoter.(*voterInfo).weight)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tVote(cross(cur), 0)\n\n\tif proposals[0].votes != 2 {\n\t\tt.Fatalf(\"proposals[0].votes = %d, want 2 (alice's own weight + bob's delegation)\", proposals[0].votes)\n\t}\n}\n\nfunc TestDelegateToAlreadyVotedAddsDirectly(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B\")\n\tGiveRightToVote(cross(cur), bob.String())\n\tVote(cross(cur), 1)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tDelegate(cross(cur), alice.String())\n\n\tif proposals[1].votes != 2 {\n\t\tt.Fatalf(\"proposals[1].votes = %d, want 2 (alice's vote + bob's delegated weight)\", proposals[1].votes)\n\t}\n}\n\nfunc TestSelfDelegatePanics(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B\")\n\n\trec := revive(func() { Delegate(cross(cur), alice.String()) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic on self-delegation\")\n\t}\n}\n\nfunc TestDelegateLoopPanics(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tcarol := testutils.TestAddress(\"carol\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B\")\n\tGiveRightToVote(cross(cur), bob.String())\n\tGiveRightToVote(cross(cur), carol.String())\n\n\t// alice -\u003e bob\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tDelegate(cross(cur), bob.String())\n\n\t// carol -\u003e alice would close the loop carol -\u003e alice -\u003e bob if bob then\n\t// delegated back to carol; instead exercise the direct A -\u003e B -\u003e A cycle:\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\trec := revive(func() {\n\t\t// bob has no delegate yet (he's an accumulation point), so seed a\n\t\t// cycle by having carol delegate to bob, then bob delegate to carol.\n\t\tDelegate(cross(cur), bob.String())\n\t})\n\tif rec != nil {\n\t\tt.Fatal(\"carol -\u003e bob should succeed (bob hasn't voted or delegated)\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\trec = revive(func() { Delegate(cross(cur), carol.String()) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when closing a delegation loop (bob -\u003e carol -\u003e bob)\")\n\t}\n}\n\nfunc TestWinningProposalTieBreaksLowestIndex(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B,C\")\n\tGiveRightToVote(cross(cur), bob.String())\n\tVote(cross(cur), 1)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVote(cross(cur), 0)\n\n\tif WinningProposal() != 0 {\n\t\tt.Fatalf(\"WinningProposal() = %d, want 0 (tie broken toward lowest index)\", WinningProposal())\n\t}\n}\n\n// Non-crossing: Render is a plain read.\nfunc TestRenderBeforeInit(t *testing.T) {\n\tresetState()\n\tif out := Render(\"\"); out == \"\" {\n\t\tt.Fatal(`Render(\"\") should not be empty before Init`)\n\t}\n}\n\nfunc TestRenderAfterInit(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tInit(cross(cur), \"A,B\")\n\tVote(cross(cur), 0)\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"A\") || !strings.Contains(out, alice.String()) {\n\t\tt.Fatal(\"Render should include the proposal names and the chairperson address\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/ballot/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"51413400","gas_fee":"154240ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"qmFRIRK2tAEDFfECqODYhDApbffp6Yiw7AR4EFrqovtNxr8P+2UYB3L4ZDPUpobbkuUI6ctQAdESVrydsIhS0A=="}],"memo":""},"metadata":{"timestamp":"1790960831"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"base32demo","path":"gno.land/r/moul/x/daily/base32demo/v0","files":[{"name":"README.md","body":"# Base32\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nShows the RFC 4648 vectors beside Crockford, then the forgiving decodes that\nCrockford allows.\n\n```\n/r/moul/x/daily/base32demo/v0         → vectors + Crockford forgiveness\n/r/moul/x/daily/base32demo/v0:hello   → encode your own text both ways\n```\n\nDemo of the [`p/moul/x/daily/base32`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/base32)\nlibrary — no codec logic lives here. Stateless, so `Render` is deterministic.\n\nThe input column is the RFC 4648 §10 vector set at every partial-group length,\nso the pinned example output doubles as a conformance test. The second section\nis the actual argument for Crockford: the same identifier decodes whether it is\nlowercased or hyphenated.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/base32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/base32demo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/base32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/base32demo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/base32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/base32demo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/base32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/base32demo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/base32demo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/base32demo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"base32demo.gno","body":"// Package base32demo is a small gnoweb demo of the base32 codec provided by the\n// [p/moul/x/daily/base32](/p/moul/x/daily/base32/v0) library: it shows the RFC\n// 4648 vectors alongside Crockford, and the forgiving decodes Crockford allows.\n//\n// It contains no codec logic of its own. Stateless, so Render is deterministic.\npackage base32demo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/base32/v0\"\n)\n\n// The RFC 4648 §10 vectors — every partial-group length.\nvar vectors = []string{\"\", \"f\", \"fo\", \"foo\", \"foob\", \"fooba\", \"foobar\"}\n\n// Render renders the demo for gnoweb.\n//\n//\tRender(\"\")       / Render(\"/\") -\u003e the vectors + Crockford forgiveness\n//\tRender(\"/\u003ctext\u003e\")              -\u003e encode that text both ways\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Base32\\n\\n\")\n\tb.WriteString(\"RFC 4648 and Crockford, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/base32`](/p/moul/x/daily/base32/v0) library.\\n\\n\")\n\n\tif in := parseArg(path); in != \"\" {\n\t\tstd, _ := base32.Encode(in)\n\t\tck, _ := base32.EncodeCrockford(in)\n\t\tb.WriteString(\"## `\")\n\t\tb.WriteString(in)\n\t\tb.WriteString(\"`\\n\\n- RFC 4648: `\")\n\t\tb.WriteString(std)\n\t\tb.WriteString(\"`\\n- Crockford: `\")\n\t\tb.WriteString(ck)\n\t\tb.WriteString(\"`\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| input | RFC 4648 | Crockford |\\n|---|---|---|\\n\")\n\tfor _, v := range vectors {\n\t\tstd, _ := base32.Encode(v)\n\t\tck, _ := base32.EncodeCrockford(v)\n\t\tb.WriteString(\"| \")\n\t\tif v == \"\" {\n\t\t\tb.WriteString(\"_(empty)_\")\n\t\t} else {\n\t\t\tb.WriteString(\"`\" + v + \"`\")\n\t\t}\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(std)\n\t\tb.WriteString(\"` | `\")\n\t\tb.WriteString(ck)\n\t\tb.WriteString(\"` |\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Crockford forgives\\n\\n\")\n\tenc, _ := base32.EncodeCrockford(\"hello\")\n\tb.WriteString(\"`hello` encodes to `\")\n\tb.WriteString(enc)\n\tb.WriteString(\"`, and all of these decode back to it:\\n\\n\")\n\tvariants := []string{enc, strings.ToLower(enc), enc[:2] + \"-\" + enc[2:]}\n\tfor _, v := range variants {\n\t\tdec, err := base32.DecodeCrockford(v)\n\t\tb.WriteString(\"- `\")\n\t\tb.WriteString(v)\n\t\tb.WriteString(\"` → \")\n\t\tif err == nil \u0026\u0026 dec == \"hello\" {\n\t\t\tb.WriteString(\"`hello` ✅\")\n\t\t} else {\n\t\t\tb.WriteString(\"❌\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\tb.WriteString(\"\\n\u003e Crockford folds case, reads `I`/`L` as `1` and `O` as `0`, and \")\n\tb.WriteString(\"ignores hyphens — so an identifier survives being read aloud and typed back. \")\n\tb.WriteString(\"`U` is left out of the alphabet on purpose.\\n\")\n\treturn b.String()\n}\n\nfunc parseArg(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/base32demo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package base32demo\n\n// ExampleRender pins the realm's Render output as a testable example. The RFC\n// 4648 column is the §10 vector set, so this doubles as a conformance test.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Base32\n\t//\n\t// RFC 4648 and Crockford, demoing the [`p/moul/x/daily/base32`](/p/moul/x/daily/base32/v0) library.\n\t//\n\t// | input | RFC 4648 | Crockford |\n\t// |---|---|---|\n\t// | _(empty)_ | `` | `` |\n\t// | `f` | `MY======` | `CR` |\n\t// | `fo` | `MZXQ====` | `CSQG` |\n\t// | `foo` | `MZXW6===` | `CSQPY` |\n\t// | `foob` | `MZXW6YQ=` | `CSQPYRG` |\n\t// | `fooba` | `MZXW6YTB` | `CSQPYRK1` |\n\t// | `foobar` | `MZXW6YTBOI======` | `CSQPYRK1E8` |\n\t//\n\t// ## Crockford forgives\n\t//\n\t// `hello` encodes to `D1JPRV3F`, and all of these decode back to it:\n\t//\n\t// - `D1JPRV3F` → `hello` ✅\n\t// - `d1jprv3f` → `hello` ✅\n\t// - `D1-JPRV3F` → `hello` ✅\n\t//\n\t// \u003e Crockford folds case, reads `I`/`L` as `1` and `O` as `0`, and ignores hyphens — so an identifier survives being read aloud and typed back. `U` is left out of the alphabet on purpose.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"28263000","gas_fee":"84789ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"LVxjW/qT3ZTCK7s+yxSE7WlvOkeXTKUIPx8zbyTvjJIMy6AD8P3bEeKXWGRFnokHHSPHKCrcD2xiaugvE6PpgA=="}],"memo":""},"metadata":{"timestamp":"1790960831"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bidimapdemo","path":"gno.land/r/moul/x/daily/bidimapdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/bidimapdemo/v0`\n\n**Live demo of [`p/moul/x/daily/bidimap`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/bidimap).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/bidimapdemo/v0`](https://gno.land/r/moul/x/daily/bidimapdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/bidimapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bidimapdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/bidimapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bidimapdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/bidimapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bidimapdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/bidimapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bidimapdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/bidimapdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/bidimapdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bidimapdemo.gno","body":"// Package bidimapdemo is a small gnoweb demo of the bidirectional map provided\n// by the [p/moul/x/daily/bidimap](/p/moul/x/daily/bidimap/v0) library: it shows\n// the reverse lookup and what happens when a binding is displaced.\n//\n// It contains no map logic of its own. Stateless, so Render is deterministic —\n// which is precisely what the library is for.\npackage bidimapdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/bidimap/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Bidirectional Map\\n\\n\")\n\tb.WriteString(\"Unique in both directions, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/bidimap`](/p/moul/x/daily/bidimap/v0) library.\\n\\n\")\n\n\tm := bidimap.New()\n\tm.Put(\"alice\", \"admin\")\n\tm.Put(\"bob\", \"auditor\")\n\tm.Put(\"carol\", \"treasurer\")\n\n\tb.WriteString(\"## Roles\\n\\n\")\n\tb.WriteString(table(m))\n\n\tb.WriteString(\"\\n## Both directions are O(1)\\n\\n\")\n\tv, _ := m.Get(\"bob\")\n\tk, _ := m.GetKey(\"treasurer\")\n\tb.WriteString(\"- `Get(\\\"bob\\\")` → `\" + v + \"`\\n\")\n\tb.WriteString(\"- `GetKey(\\\"treasurer\\\")` → `\" + k + \"` — the reverse index, not a scan\\n\\n\")\n\n\tb.WriteString(\"## Displacing a binding\\n\\n\")\n\tb.WriteString(\"Both sides are unique, so giving `alice` the `auditor` role cannot \")\n\tb.WriteString(\"simply be written — `bob` already holds it, and `alice` already holds \")\n\tb.WriteString(\"`admin`. `Put` **replaces**, and reports what it displaced:\\n\\n\")\n\tevicted, _ := m.Put(\"alice\", \"auditor\")\n\tb.WriteString(\"| displaced key | displaced value |\\n|---|---|\\n\")\n\tfor _, p := range evicted {\n\t\tb.WriteString(\"| `\" + p[0] + \"` | `\" + p[1] + \"` |\\n\")\n\t}\n\tb.WriteString(\"\\n\" + table(m))\n\tb.WriteString(\"\\n`bob` is now unassigned and the `admin` role is vacant — one call, \")\n\tb.WriteString(\"both indexes still agreeing.\\n\\n\")\n\n\tb.WriteString(\"## Refusing instead\\n\\n\")\n\tb.WriteString(\"`PutUnique` makes the other choice: it declines rather than displace.\\n\\n\")\n\tok := m.PutUnique(\"dave\", \"auditor\")\n\tb.WriteString(\"- `PutUnique(\\\"dave\\\", \\\"auditor\\\")` → `\" + strconv.FormatBool(ok) + \"` — the role is taken\\n\")\n\tok = m.PutUnique(\"dave\", \"secretary\")\n\tb.WriteString(\"- `PutUnique(\\\"dave\\\", \\\"secretary\\\")` → `\" + strconv.FormatBool(ok) + \"` — both sides free\\n\\n\")\n\tb.WriteString(table(m))\n\n\tb.WriteString(\"\\n\u003e Keys come back **sorted**, never in map order: gno map iteration \")\n\tb.WriteString(\"order is unspecified, and a page built from one can differ between \")\n\tb.WriteString(\"nodes — a consensus bug, not a cosmetic one.\\n\")\n\treturn b.String()\n}\n\nfunc table(m *bidimap.BiMap) string {\n\tvar b strings.Builder\n\tb.WriteString(\"| person | role |\\n|---|---|\\n\")\n\tm.Iterate(func(k, v string) bool {\n\t\tb.WriteString(\"| `\" + k + \"` | `\" + v + \"` |\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/bidimapdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package bidimapdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Bidirectional Map\n\t//\n\t// Unique in both directions, demoing the [`p/moul/x/daily/bidimap`](/p/moul/x/daily/bidimap/v0) library.\n\t//\n\t// ## Roles\n\t//\n\t// | person | role |\n\t// |---|---|\n\t// | `alice` | `admin` |\n\t// | `bob` | `auditor` |\n\t// | `carol` | `treasurer` |\n\t//\n\t// ## Both directions are O(1)\n\t//\n\t// - `Get(\"bob\")` → `auditor`\n\t// - `GetKey(\"treasurer\")` → `carol` — the reverse index, not a scan\n\t//\n\t// ## Displacing a binding\n\t//\n\t// Both sides are unique, so giving `alice` the `auditor` role cannot simply be written — `bob` already holds it, and `alice` already holds `admin`. `Put` **replaces**, and reports what it displaced:\n\t//\n\t// | displaced key | displaced value |\n\t// |---|---|\n\t// | `alice` | `admin` |\n\t// | `bob` | `auditor` |\n\t//\n\t// | person | role |\n\t// |---|---|\n\t// | `alice` | `auditor` |\n\t// | `carol` | `treasurer` |\n\t//\n\t// `bob` is now unassigned and the `admin` role is vacant — one call, both indexes still agreeing.\n\t//\n\t// ## Refusing instead\n\t//\n\t// `PutUnique` makes the other choice: it declines rather than displace.\n\t//\n\t// - `PutUnique(\"dave\", \"auditor\")` → `false` — the role is taken\n\t// - `PutUnique(\"dave\", \"secretary\")` → `true` — both sides free\n\t//\n\t// | person | role |\n\t// |---|---|\n\t// | `alice` | `auditor` |\n\t// | `carol` | `treasurer` |\n\t// | `dave` | `secretary` |\n\t//\n\t// \u003e Keys come back **sorted**, never in map order: gno map iteration order is unspecified, and a page built from one can differ between nodes — a consensus bug, not a cosmetic one.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"29300400","gas_fee":"87901ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"SHEAdpoBfDaM5PTMx2KxYlOK0xNkhBpSXxEGtgSxdwZaZONizNNEAApK+fvdCsfwW8Dg4ThwnJ9r3UrfWw8dEg=="}],"memo":""},"metadata":{"timestamp":"1790960832"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bitsetdemo","path":"gno.land/r/moul/x/daily/bitsetdemo/v0","files":[{"name":"README.md","body":"# BitSet\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nSieves the primes under 100 into a bit set and shows the set algebra on two\nsmall sets, rendered as a table.\n\nDemo of the [`p/moul/x/daily/bitset`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/bitset)\nlibrary — storage, popcount and every set operation come from the package; this\nrealm does no bit-twiddling of its own. Stateless and read-only, so `Render` is\nfully deterministic.\n\nThe sieve is a nice fit: the bit set is used *twice*, once as the composite\nmarker and once as the result, which is exactly what a dense bit vector is for.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/bitsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bitsetdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/bitsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bitsetdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/bitsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bitsetdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/bitsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bitsetdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/bitsetdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/bitsetdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bitsetdemo.gno","body":"// Package bitsetdemo is a small gnoweb demo of the dense bit vector provided by\n// the [p/moul/x/daily/bitset](/p/moul/x/daily/bitset/v0) library: it sieves the\n// primes under 100 into a bit set and shows the set algebra on two small sets.\n//\n// It contains no bit-twiddling of its own — storage, popcount and the set\n// operations all come from the library. Stateless, so Render is deterministic.\npackage bitsetdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/bitset/v0\"\n)\n\n// limit bounds the sieve shown on the page.\nconst limit = 100\n\n// primes returns a bit set of the primes below limit, sieved with the bit set\n// itself as the composite marker.\nfunc primes() *bitset.BitSet {\n\tcomposite := bitset.New(limit)\n\tout := bitset.New(limit)\n\tfor p := 2; p \u003c limit; p++ {\n\t\tif composite.Has(p) {\n\t\t\tcontinue\n\t\t}\n\t\tout.Set(p)\n\t\tfor m := p * p; m \u003c limit; m += p {\n\t\t\tcomposite.Set(m)\n\t\t}\n\t}\n\treturn out\n}\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# BitSet\\n\\n\")\n\tb.WriteString(\"A dense bit vector, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/bitset`](/p/moul/x/daily/bitset/v0) library.\\n\\n\")\n\n\tp := primes()\n\tb.WriteString(\"## Primes under \")\n\tb.WriteString(strconv.Itoa(limit))\n\tb.WriteString(\"\\n\\n**\")\n\tb.WriteString(strconv.Itoa(p.Count()))\n\tb.WriteString(\"** set bits in \")\n\tb.WriteString(strconv.Itoa(p.Cap()))\n\tb.WriteString(\" bits of capacity:\\n\\n\")\n\tb.WriteString(list(p.Slice()))\n\n\tsmall := bitset.FromSlice(16, []int{1, 2, 3, 5, 8})\n\teven := bitset.FromSlice(16, []int{2, 4, 6, 8, 10})\n\tb.WriteString(\"\\n## Set algebra\\n\\n\")\n\tb.WriteString(\"| set | bits |\\n|---|---|\\n\")\n\trow(\u0026b, \"a\", small)\n\trow(\u0026b, \"b\", even)\n\trow(\u0026b, \"a ∪ b\", bitset.Union(small, even))\n\trow(\u0026b, \"a ∩ b\", bitset.Intersect(small, even))\n\trow(\u0026b, \"a \\\\ b\", bitset.Difference(small, even))\n\trow(\u0026b, \"a △ b\", bitset.SymmetricDifference(small, even))\n\treturn b.String()\n}\n\nfunc row(b *strings.Builder, name string, s *bitset.BitSet) {\n\tb.WriteString(\"| \")\n\tb.WriteString(name)\n\tb.WriteString(\" | `\")\n\tb.WriteString(list1(s.Slice()))\n\tb.WriteString(\"` |\\n\")\n}\n\nfunc list(xs []int) string {\n\tif len(xs) == 0 {\n\t\treturn \"_none_\\n\"\n\t}\n\treturn \"`\" + list1(xs) + \"`\\n\"\n}\n\nfunc list1(xs []int) string {\n\tparts := []string{}\n\tfor _, x := range xs {\n\t\tparts = append(parts, strconv.Itoa(x))\n\t}\n\treturn strings.Join(parts, \" \")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/bitsetdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package bitsetdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # BitSet\n\t//\n\t// A dense bit vector, demoing the [`p/moul/x/daily/bitset`](/p/moul/x/daily/bitset/v0) library.\n\t//\n\t// ## Primes under 100\n\t//\n\t// **25** set bits in 100 bits of capacity:\n\t//\n\t// `2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97`\n\t//\n\t// ## Set algebra\n\t//\n\t// | set | bits |\n\t// |---|---|\n\t// | a | `1 2 3 5 8` |\n\t// | b | `2 4 6 8 10` |\n\t// | a ∪ b | `1 2 3 4 5 6 8 10` |\n\t// | a ∩ b | `2 8` |\n\t// | a \\ b | `1 3 5` |\n\t// | a △ b | `1 3 4 5 6 10` |\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"26084200","gas_fee":"78252ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"wNB8baEAQF1bOsMfyHd38S3P3drbnPy/UdI1VEzQ/kF91UdSKNGcgs6hycFdn+Q3JMmDacz/s5wMoi9PpAF9yw=="}],"memo":""},"metadata":{"timestamp":"1790960833"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"blog","path":"gno.land/r/moul/x/daily/blog/v1","files":[{"name":"README.md","body":"# Personal Blog\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA multi-author on-chain blog realm for gno.land. Anyone can publish a post; each\npost records its author (the calling address) and the block height at which it\nwas published. Posts are stored persistently and rendered newest-first, with a\ndedicated page for each post's full text.\n\n**Realm path:** `gno.land/r/moul/x/daily/blog/v1`\n\n## Example calls\n\nPublish a post (state-mutating, crossing function):\n\n```\ngnokey maketx call -pkgpath \"gno.land/r/moul/x/daily/blog/v1\" \\\n  -func Publish -args \"My first post\" -args \"Hello, gno.land!\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 KEY\n```\n\nRead views (no transaction needed):\n\n- Root — list all posts, newest first: render `gno.land/r/moul/x/daily/blog/v1`\n- Single post by id: render `gno.land/r/moul/x/daily/blog/v1:/0`\n\n`PostCount()` returns the total number of published posts.\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\nIds stay plain integers, and `Post` loses its `ID` field, which the store now\nowns. Two things a reader will notice:\n\n- **Post ids now start at 1.** `v0` handed out 0 for the first post; the store\n  never assigns 0, so the zero id stays usable as \"absent\".\n- **`/0` is no longer a post path.** It is rejected as invalid rather than\n  looked up, along with anything else that is not a plain decimal.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/blog) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/blog/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/blog/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"blog.gno","body":"// Package blog is a multi-author on-chain blog realm for gno.land.\n//\n// Any caller can Publish a post; posts are stored persistently and rendered\n// newest-first. Each post records its author (the calling address) and the\n// block height at which it was published.\npackage blog\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/blog/v1\"\n\n// Post is a single blog entry. It carries no id field: the id belongs to the\n// store, which hands it back on lookup and iteration.\ntype Post struct {\n\tTitle  string\n\tBody   string\n\tAuthor address\n\tHeight int64\n}\n\n// posts holds every published post. The store keys by seqid, so iteration is\n// in publication order for any number of posts; v0 kept its own nextID plus a\n// key() that zero-padded to width 12 and stopped ordering past it.\nvar posts = store.Named(\"post\")\n\n// Publish creates a new post authored by the caller and returns its id.\n// It is a state-mutating exported function, so it takes `cur realm`.\nfunc Publish(cur realm, title string, body string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"blog: spoofed realm\")\n\t}\n\ttitle = strings.TrimSpace(title)\n\tbody = strings.TrimSpace(body)\n\tif title == \"\" {\n\t\tpanic(\"blog: title must not be empty\")\n\t}\n\tif body == \"\" {\n\t\tpanic(\"blog: body must not be empty\")\n\t}\n\n\tauthor := cur.Previous().Address()\n\tid := posts.Add(\u0026Post{\n\t\tTitle:  title,\n\t\tBody:   body,\n\t\tAuthor: author,\n\t\tHeight: runtime.ChainHeight(),\n\t})\n\n\tchain.Emit(\n\t\t\"PostPublished\",\n\t\t\"id\", id.String(),\n\t\t\"author\", author.String(),\n\t)\n\treturn int(id)\n}\n\n// PostCount returns the number of published posts.\nfunc PostCount() int {\n\treturn posts.Len()\n}\n\n// Render lists all posts newest-first at the root, or a single post's full\n// text at path \"/\u003cid\u003e\". Render is NOT a crossing function.\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tif path == \"\" || path == \"/\" {\n\t\treturn renderList()\n\t}\n\tidStr := strings.TrimPrefix(path, \"/\")\n\tid, ok := store.ParseID(idStr)\n\tif !ok {\n\t\treturn \"# Not found\\n\\nInvalid post path: \" + md.InlineCode(path) + \"\\n\\n[← back](\" + selfPath + \")\\n\"\n\t}\n\tv, ok := posts.Get(id)\n\tif !ok {\n\t\treturn \"# Not found\\n\\nNo post with id \" + idStr + \".\\n\\n[← back](\" + selfPath + \")\\n\"\n\t}\n\treturn renderPost(v.(*Post))\n}\n\nfunc renderList() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 📝 Blog\\n\\n\")\n\tif posts.Len() == 0 {\n\t\tb.WriteString(\"_No posts yet. Be the first to `Publish`._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(strconv.Itoa(posts.Len()) + \" post(s), newest first.\\n\\n\")\n\n\t// Ids ascend with publication, so reverse iteration is newest-first.\n\tposts.EachReverse(func(id store.ID, v any) {\n\t\tp := v.(*Post)\n\t\tb.WriteString(\"## [\")\n\t\tb.WriteString(ui.Inline(p.Title))\n\t\tb.WriteString(\"](\" + selfPath + \":/\")\n\t\tb.WriteString(id.String())\n\t\tb.WriteString(\")\\n\\n\")\n\t\tb.WriteString(\"by `\")\n\t\tb.WriteString(p.Author.String())\n\t\tb.WriteString(\"` · height \")\n\t\tb.WriteString(strconv.FormatInt(p.Height, 10))\n\t\tb.WriteString(\"\\n\\n\")\n\t\tb.WriteString(ui.Excerpt(strings.TrimSpace(p.Body), 140))\n\t\tb.WriteString(\"\\n\\n---\\n\\n\")\n\t})\n\treturn b.String()\n}\n\nfunc renderPost(p *Post) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# \")\n\tb.WriteString(ui.Inline(p.Title))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(\"by `\")\n\tb.WriteString(p.Author.String())\n\tb.WriteString(\"` · height \")\n\tb.WriteString(strconv.FormatInt(p.Height, 10))\n\tb.WriteString(\"\\n\\n\")\n\t// Anyone may publish, so the body is the caller's text, not this realm's\n\t// markdown: each line is escaped, and a blank line still breaks a paragraph.\n\tfor i, line := range strings.Split(p.Body, \"\\n\") {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\"  \\n\")\n\t\t}\n\t\tb.WriteString(ui.Inline(line))\n\t}\n\tb.WriteString(\"\\n\\n---\\n\\n[← back to all posts](\" + selfPath + \")\\n\")\n\treturn b.String()\n}\n"},{"name":"blog_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPublishAndRender(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t// Ids start at 1 in v1: the store never assigns 0, so the zero id stays\n\t// usable as \"absent\". v0 handed out 0 for the first post.\n\tid0 := Publish(cross(cur), \"First Post\", \"Hello from alice.\")\n\tuassert.Equal(t, 1, id0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid1 := Publish(cross(cur), \"Second Post\", \"A longer body\\nwith a newline from bob.\")\n\tuassert.Equal(t, 2, id1)\n\n\tuassert.Equal(t, 2, PostCount())\n\n\t// Root render lists both, newest (bob's) first.\n\tlist := Render(\"\")\n\tuassert.True(t, strings.Contains(list, \"First Post\"), \"list has first post\")\n\tuassert.True(t, strings.Contains(list, \"Second Post\"), \"list has second post\")\n\tuassert.True(t, strings.Index(list, \"Second Post\") \u003c strings.Index(list, \"First Post\"),\n\t\t\"newest post appears first\")\n\tuassert.True(t, strings.Contains(list, alice.String()), \"list shows alice author\")\n\n\t// Single-post render shows full body + back link.\n\tsingle := Render(\"/2\")\n\tuassert.True(t, strings.Contains(single, \"newline from bob\"), \"full body shown\")\n\tuassert.True(t, strings.Contains(single, \"← back\"), \"back link present\")\n\n\t// Unknown id.\n\tuassert.True(t, strings.Contains(Render(\"/99\"), \"Not found\"), \"missing post handled\")\n\n\t// Id 0 is never assigned, so the path is rejected rather than looked up.\n\tuassert.True(t, strings.Contains(Render(\"/0\"), \"Invalid post path\"), \"id 0 is not a post\")\n\tuassert.True(t, strings.Contains(Render(\"/abc\"), \"Invalid post path\"), \"a non-numeric path is rejected\")\n}\n\nfunc TestPublishEmptyTitleAborts(cur realm, t *testing.T) {\n\tcarol := testutils.TestAddress(\"carol\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\n\tuassert.AbortsWithMessage(t, cur, \"blog: title must not be empty\", func() {\n\t\tPublish(cross(cur), \"   \", \"some body\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"blog: body must not be empty\", func() {\n\t\tPublish(cross(cur), \"a title\", \"\")\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/blog/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"zz_escape_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Anyone may publish, so a title or a body is the caller's text and must not\n// become live markdown on the realm's own pages.\nfunc TestTitleAndBodyAreEscaped(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"escaper\")))\n\tid := Publish(cross(cur), \"[claim](https://evil.example)\", \"line one\\n[claim](https://evil.example)\")\n\tuassert.False(t, strings.Contains(Render(\"\"), \"[claim](https://evil.example)\"), Render(\"\"))\n\tpage := Render(\"/\" + itoaTest(id))\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n}\n\n// A path that names nothing is echoed back on the not-found page. It is the\n// visitor's text, so a backtick in it must not close a code span and let a\n// link through.\nfunc TestNotFoundPathIsEscaped(t *testing.T) {\n\tout := Render(\"/x` [claim](https://evil.example) `\")\n\t// Still there, but inside a span md.InlineCode widened past its backticks.\n\tuassert.True(t, strings.Contains(out, md.InlineCode(\"/x` [claim](https://evil.example) `\")), out)\n}\n"},{"name":"zz_links_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Every link the realm renders names its own absolute path. A dead link here\n// once read /r/REPLACE_ADDR/blog, and a test that only checked \"a back link\n// exists\" passed against it.\nfunc TestLinksNameThisRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"linker\")))\n\tid := Publish(cross(cur), \"Linked\", \"body\")\n\tidx := Render(\"\")\n\tuassert.True(t, strings.Contains(idx, \"](/r/moul/x/daily/blog/v1:/\"), idx)\n\tpage := Render(\"/\" + itoaTest(id))\n\tuassert.True(t, strings.Contains(page, \"(/r/moul/x/daily/blog/v1)\"), page)\n}\n\nfunc itoaTest(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\ts := \"\"\n\tfor n \u003e 0 {\n\t\ts = string(rune(byte(n%10)+byte(48))) + s\n\t\tn /= 10\n\t}\n\treturn s\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"43800600","gas_fee":"131401ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"a8OQCcoWuXzVfos7rgWhTIUAwuVBkSqtrPlcf6/WebJWC7Q+a1KHQB88vJs1/CzvEQcV2ULnAgBm70YKnDohSQ=="}],"memo":""},"metadata":{"timestamp":"1790960833"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"V4mgSecB0e0ZEum/bPSuwTAyorqSQfE/Vrf9AYt+z4dkL9ULExDI11Fgb98TYSBTSjq0nuiZqOubZEMPcHw2JA=="}],"memo":""},"metadata":{"timestamp":"1790960834"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bloomfilter","path":"gno.land/r/moul/x/daily/bloomfilter/v0","files":[{"name":"README.md","body":"# bloomfilter\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/bloomfilter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bloomfilter/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/bloomfilter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bloomfilter/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/bloomfilter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bloomfilter/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/bloomfilter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bloomfilter/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bloomfilter.gno","body":"// Package bloomfilter ports the classic Bloom filter data structure to\n// gno.land: a fixed-size bit array plus k independent hash functions that\n// let you test set membership with zero false negatives and a small, bounded\n// false-positive rate — without ever storing the actual items.\n//\n// Membership is checked via double hashing (Kirsch–Mitzenmacher): two base\n// hashes h1, h2 are combined as h1 + i*h2 to derive k bit positions per item,\n// avoiding the cost of k independent hash functions.\n//\n// Add is a crossing function per the gno 0.9 interrealm convention (it takes\n// `cur realm` as its first parameter); MightContain and Stats are read-only.\npackage bloomfilter\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tnumBits    = 2048 // m: total bits in the filter\n\tnumBytes   = numBits / 8\n\tnumHashes  = 5 // k: hash functions per item (double-hashed from 2 bases)\n\tmaxHistory = 20 // most recent additions kept for Render display only\n)\n\nvar (\n\tbits    [numBytes]byte // the bit array itself\n\tsetBits int            // running count of bits currently set to 1\n\tadded   int            // total Add calls (may double-count re-adds)\n\thistory []string       // last few added items, for the Render view\n)\n\n// fnv1a is a minimal FNV-1a 32-bit hash over a string, parameterized by an\n// offset basis so two calls with different seeds behave as independent\n// hash functions for the double-hashing scheme below.\nfunc fnv1a(s string, seed uint32) uint32 {\n\th := seed\n\tfor i := 0; i \u003c len(s); i++ {\n\t\th ^= uint32(s[i])\n\t\th *= 16777619 // FNV prime\n\t}\n\treturn h\n}\n\n// positions returns the k bit positions an item hashes to.\nfunc positions(item string) [numHashes]uint32 {\n\th1 := fnv1a(item, 2166136261)\n\th2 := fnv1a(item, 84696351)\n\tif h2 == 0 {\n\t\th2 = 1 // keep the second hash non-degenerate\n\t}\n\tvar pos [numHashes]uint32\n\tfor i := 0; i \u003c numHashes; i++ {\n\t\tpos[i] = (h1 + uint32(i)*h2) % numBits\n\t}\n\treturn pos\n}\n\n// setBit sets bit `pos` and reports whether it was previously unset.\nfunc setBit(pos uint32) bool {\n\tbyteIdx := pos / 8\n\tmask := byte(1 \u003c\u003c (pos % 8))\n\tif bits[byteIdx]\u0026mask != 0 {\n\t\treturn false\n\t}\n\tbits[byteIdx] |= mask\n\treturn true\n}\n\n// testBit reports whether bit `pos` is set.\nfunc testBit(pos uint32) bool {\n\tbyteIdx := pos / 8\n\tmask := byte(1 \u003c\u003c (pos % 8))\n\treturn bits[byteIdx]\u0026mask != 0\n}\n\n// Add inserts `item` into the filter. Crossing function: any caller (user or\n// realm) may add, matching this demo's open-membership model.\nfunc Add(cur realm, item string) {\n\tif item == \"\" {\n\t\tpanic(\"bloomfilter: empty item\")\n\t}\n\tfor _, pos := range positions(item) {\n\t\tif setBit(pos) {\n\t\t\tsetBits++\n\t\t}\n\t}\n\tadded++\n\thistory = append(history, item)\n\tif len(history) \u003e maxHistory {\n\t\thistory = history[len(history)-maxHistory:]\n\t}\n\tchain.Emit(\"Add\", \"item\", item, \"totalAdded\", strconv.Itoa(added))\n}\n\n// MightContain reports whether `item` was possibly added before. A false\n// (definitely-not-a-member) answer is always correct; a true answer can\n// occasionally be a false positive, never a false negative.\nfunc MightContain(item string) bool {\n\tif item == \"\" {\n\t\treturn false\n\t}\n\tfor _, pos := range positions(item) {\n\t\tif !testBit(pos) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// FalsePositiveRatePercent estimates the current false-positive rate, in\n// percent, as (bitsSet/m)^k — the standard Bloom filter approximation once\n// bits are randomly distributed. Computed with plain integer/float math to\n// avoid depending on math.Exp/Pow availability.\nfunc FalsePositiveRatePercent() float64 {\n\tfillRatio := float64(setBits) / float64(numBits)\n\trate := 1.0\n\tfor i := 0; i \u003c numHashes; i++ {\n\t\trate *= fillRatio\n\t}\n\treturn rate * 100\n}\n\n// Stats returns the raw counters backing the Render view and\n// FalsePositiveRatePercent: (itemsAdded, bitsSet, totalBits, hashCount).\nfunc Stats() (int, int, int, int) {\n\treturn added, setBits, numBits, numHashes\n}\n\n// Render draws the filter's current stats and recently-added items as\n// Markdown for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Bloom Filter\\n\\n\")\n\tb.WriteString(\"A probabilistic set membership test: `Add` an item, then \" +\n\t\t\"`MightContain` it back. False positives are possible; false \" +\n\t\t\"negatives never happen. The filter never stores the items \" +\n\t\t\"themselves — only \" + strconv.Itoa(numBits) + \" bits.\\n\\n\")\n\n\tfillRatio := float64(setBits) / float64(numBits) * 100\n\n\tb.WriteString(\"## Stats\\n\\n\")\n\tb.WriteString(\"- **Bits (m):** \" + strconv.Itoa(numBits) + \"\\n\")\n\tb.WriteString(\"- **Hash functions (k):** \" + strconv.Itoa(numHashes) + \"\\n\")\n\tb.WriteString(\"- **Items added:** \" + strconv.Itoa(added) + \"\\n\")\n\tb.WriteString(\"- **Bits set:** \" + strconv.Itoa(setBits) + \" (\" +\n\t\tstrconv.FormatFloat(fillRatio, 'f', 1, 64) + \"% full)\\n\")\n\tb.WriteString(\"- **Estimated false-positive rate:** \" +\n\t\tstrconv.FormatFloat(FalsePositiveRatePercent(), 'f', 3, 64) + \"%\\n\\n\")\n\n\tb.WriteString(\"## Recently added\\n\\n\")\n\tif len(history) == 0 {\n\t\tb.WriteString(\"_Nothing added yet — call `Add` with an item string._\\n\")\n\t\treturn b.String()\n\t}\n\tfor i := len(history) - 1; i \u003e= 0; i-- {\n\t\tb.WriteString(\"- `\" + history[i] + \"`\\n\")\n\t}\n\n\treturn b.String()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/bloomfilter/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package bloomfilter\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Bloom Filter\n\t//\n\t// A probabilistic set membership test: `Add` an item, then `MightContain` it back. False positives are possible; false negatives never happen. The filter never stores the items themselves — only 2048 bits.\n\t//\n\t// ## Stats\n\t//\n\t// - **Bits (m):** 2048\n\t// - **Hash functions (k):** 5\n\t// - **Items added:** 0\n\t// - **Bits set:** 0 (0.0% full)\n\t// - **Estimated false-positive rate:** 0.000%\n\t//\n\t// ## Recently added\n\t//\n\t// _Nothing added yet — call `Add` with an item string._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"31874400","gas_fee":"95623ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"X7YIB0ATKzCvlosp20o5+u0lC3Vfp2pNlcFwIE7fQOhlDLTAfVn1RkHOQj1K9CvHBmypytJstaceeTR8sSRNyg=="}],"memo":""},"metadata":{"timestamp":"1790960886"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bullscows","path":"gno.land/r/moul/x/daily/bullscows/v1","files":[{"name":"README.md","body":"# Bulls \u0026 Cows\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA shared on-chain [Bulls \u0026 Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows) puzzle\n(the classic ancestor of Mastermind and Wordle-for-digits). One secret 4-digit code\nwith no repeated digits is live at a time; anyone can call `Guess` with a candidate\ncode and gets back **bulls** (right digit, right position) and **cows** (right digit,\nwrong position). First caller to land 4 bulls cracks the round, lands on the\nleaderboard, and a fresh secret is drawn immediately so the next round starts at once.\n\nRealm: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/bullscows`\n\n## Example calls\n\n```\nGuess(\"1972\")   -\u003e \"1972 -\u003e 1 bulls, 2 cows\"\nGuess(\"7192\")   -\u003e \"*** SOLVED *** 7192 was it — round 3 cracked in 5 guesses. New round 4 has begun, good luck!\"\nGiveUp()        -\u003e \"round 4's code was 4082 — round 5 is live now.\"\n```\n\n`Render(\"\")` shows the current round, attempts so far, the last 10 guesses with\ntheir bulls/cows, and the top-5 fastest-solve leaderboard.\n\nThe secret is generated deterministically from the on-chain block height and the\nround counter via a small LCG (`newSecret`/`nextRand` in `bullscows.gno`) — no\nexternal randomness needed, and nobody can precompute the next code before its\nround actually starts.\n\n## Toolchain status\n\nVerified locally with `gno test -v .` and `gno lint .` against a `gno.land/gnolang/gno`\nmaster checkout used as `GNOROOT` (the default installed `gno` binary had a stale/\nmissing `GNOROOT`, so `GNOROOT=\u003cpath-to-gnolang/gno\u003e gno test .` was used instead).\nAll 7 tests pass, lint is clean. This exercises current sapphire (gno 0.9) stdlib\npaths (`chain/runtime`, no `std` package) and the `cur realm` / `cross(cur)` crossing\nconvention.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/bullscows) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nVisible change: addresses now render in monospace.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/bullscows/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bullscows/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/bullscows/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bullscows/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/bullscows/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bullscows/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/bullscows/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/bullscows/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/bullscows/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/bullscows/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bullscows.gno","body":"// Package bullscows is a shared on-chain Bulls \u0026 Cows puzzle: one secret\n// 4-digit code (distinct digits) per round, guessed cooperatively/competitively\n// by anyone who calls Guess. Bulls = right digit, right spot. Cows = right\n// digit, wrong spot. Whoever hits 4 bulls wins the round and a leaderboard\n// entry; a fresh secret is drawn immediately after.\npackage bullscows\n\nimport (\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\nconst (\n\tmaxHistory = 10\n\tmaxRecords = 5\n)\n\ntype guessLog struct {\n\tplayer   string\n\tguess    string\n\tbulls    int\n\tcows     int\n}\n\ntype record struct {\n\tplayer   string\n\tattempts int\n\tround    int\n}\n\nvar (\n\tsecret   [4]int\n\tround    int\n\tattempts int\n\thistory  []guessLog\n\trecords  []record\n)\n\nfunc init() {\n\tround = 1\n\tsecret = newSecret(seedFor(round))\n}\n\n// seedFor derives a per-round PRNG seed from the current chain height so\n// nobody can precompute the next secret before the round actually starts.\nfunc seedFor(r int) int64 {\n\treturn runtime.ChainHeight()*1000003 + int64(r)*7919 + 17\n}\n\n// nextRand is a minimal LCG (glibc constants) — no crypto strength needed\n// for a casual puzzle, just enough spread across digits.\nfunc nextRand(seed int64) int64 {\n\treturn (seed*1103515245 + 12345) \u0026 0x7fffffff\n}\n\nfunc newSecret(seed int64) [4]int {\n\tvar used [10]bool\n\tvar digits [4]int\n\ts := seed\n\tfor i := 0; i \u003c 4; i++ {\n\t\tfor {\n\t\t\ts = nextRand(s)\n\t\t\td := int(s % 10)\n\t\t\tif !used[d] {\n\t\t\t\tused[d] = true\n\t\t\t\tdigits[i] = d\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn digits\n}\n\n// parseGuess validates a 4-digit, distinct-digit guess string.\nfunc parseGuess(guess string) ([4]int, bool) {\n\tvar out [4]int\n\tif len(guess) != 4 {\n\t\treturn out, false\n\t}\n\tvar used [10]bool\n\tfor i := 0; i \u003c 4; i++ {\n\t\tc := guess[i]\n\t\tif c \u003c '0' || c \u003e '9' {\n\t\t\treturn out, false\n\t\t}\n\t\td := int(c - '0')\n\t\tif used[d] {\n\t\t\treturn out, false\n\t\t}\n\t\tused[d] = true\n\t\tout[i] = d\n\t}\n\treturn out, true\n}\n\n// score returns (bulls, cows) for guess against target, assuming both have\n// distinct digits (guaranteed by parseGuess / newSecret).\nfunc score(target, guess [4]int) (int, int) {\n\tbulls, cows := 0, 0\n\tfor i := 0; i \u003c 4; i++ {\n\t\tif guess[i] == target[i] {\n\t\t\tbulls++\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j \u003c 4; j++ {\n\t\t\tif i != j \u0026\u0026 guess[i] == target[j] {\n\t\t\t\tcows++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn bulls, cows\n}\n\nfunc addHistory(l guessLog) {\n\thistory = append(history, l)\n\tif len(history) \u003e maxHistory {\n\t\thistory = history[len(history)-maxHistory:]\n\t}\n}\n\n// addRecord keeps the top maxRecords fastest solves, ascending by attempts.\nfunc addRecord(r record) {\n\trecords = append(records, r)\n\tfor i := len(records) - 1; i \u003e 0 \u0026\u0026 records[i].attempts \u003c records[i-1].attempts; i-- {\n\t\trecords[i], records[i-1] = records[i-1], records[i]\n\t}\n\tif len(records) \u003e maxRecords {\n\t\trecords = records[:maxRecords]\n\t}\n}\n\nfunc startNewRound() {\n\tround++\n\tattempts = 0\n\thistory = nil\n\tsecret = newSecret(seedFor(round))\n}\n\n// Guess submits a 4-distinct-digit code against the current round's secret.\n// Returns the bulls/cows feedback, or \"solved!\" text when it's a win.\nfunc Guess(cur realm, guess string) string {\n\tdigits, ok := parseGuess(guess)\n\tif !ok {\n\t\tpanic(\"guess must be 4 digits, 0-9, no repeats (e.g. \\\"1972\\\")\")\n\t}\n\n\tplayer := cur.Previous().Address().String()\n\tattempts++\n\tbulls, cows := score(secret, digits)\n\taddHistory(guessLog{player: player, guess: guess, bulls: bulls, cows: cows})\n\n\tif bulls == 4 {\n\t\twonRound := round\n\t\twonAttempts := attempts\n\t\taddRecord(record{player: player, attempts: wonAttempts, round: wonRound})\n\t\tstartNewRound()\n\t\treturn \"*** SOLVED *** \" + guess + \" was it — round \" + strconv.Itoa(wonRound) +\n\t\t\t\" cracked in \" + strconv.Itoa(wonAttempts) + \" guesses. New round \" +\n\t\t\tstrconv.Itoa(round) + \" has begun, good luck!\"\n\t}\n\n\treturn guess + \" -\u003e \" + strconv.Itoa(bulls) + \" bulls, \" + strconv.Itoa(cows) + \" cows\"\n}\n\n// GiveUp reveals the current secret and starts a fresh round without\n// awarding a leaderboard record.\nfunc GiveUp(cur realm) string {\n\trevealed := digitsToString(secret)\n\toldRound := round\n\tstartNewRound()\n\treturn \"round \" + strconv.Itoa(oldRound) + \"'s code was \" + revealed +\n\t\t\" — round \" + strconv.Itoa(round) + \" is live now.\"\n}\n\nfunc digitsToString(d [4]int) string {\n\tvar sb strings.Builder\n\tfor _, v := range d {\n\t\tsb.WriteString(strconv.Itoa(v))\n\t}\n\treturn sb.String()\n}\n\nfunc Render(path string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Bulls \u0026 Cows\\n\\n\")\n\tsb.WriteString(\"One shared secret 4-digit code (no repeated digits). Call `Guess(\\\"1972\\\")` \")\n\tsb.WriteString(\"to get **bulls** (right digit, right spot) and **cows** (right digit, wrong spot). \")\n\tsb.WriteString(\"First to 4 bulls wins the round; `GiveUp()` reveals the code and starts over.\\n\\n\")\n\n\tsb.WriteString(\"## Round \" + strconv.Itoa(round) + \"\\n\\n\")\n\tsb.WriteString(\"Attempts so far: **\" + strconv.Itoa(attempts) + \"**\\n\\n\")\n\n\tif len(history) == 0 {\n\t\tsb.WriteString(\"_No guesses yet this round — be the first._\\n\\n\")\n\t} else {\n\t\tsb.WriteString(\"### Recent guesses\\n\\n\")\n\t\tsb.WriteString(\"| player | guess | bulls | cows |\\n|---|---|---|---|\\n\")\n\t\tfor i := len(history) - 1; i \u003e= 0; i-- {\n\t\t\th := history[i]\n\t\t\tsb.WriteString(\"| \" + ui.AddrOf(h.player) + \" | \" + h.guess + \" | \" +\n\t\t\t\tstrconv.Itoa(h.bulls) + \" | \" + strconv.Itoa(h.cows) + \" |\\n\")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\n\tsb.WriteString(\"## Leaderboard (fastest solves)\\n\\n\")\n\tif len(records) == 0 {\n\t\tsb.WriteString(\"_Nobody has cracked a code yet._\\n\")\n\t} else {\n\t\tsb.WriteString(\"| rank | player | attempts | round |\\n|---|---|---|---|\\n\")\n\t\tfor i, r := range records {\n\t\t\tsb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | \" + ui.AddrOf(r.player) + \" | \" +\n\t\t\t\tstrconv.Itoa(r.attempts) + \" | \" + strconv.Itoa(r.round) + \" |\\n\")\n\t\t}\n\t}\n\n\treturn sb.String()\n}\n"},{"name":"bullscows_test.gno","body":"package bullscows\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc TestParseGuess(t *testing.T) {\n\tcases := []struct {\n\t\tin string\n\t\tok bool\n\t}{\n\t\t{\"1972\", true},\n\t\t{\"0123\", true},\n\t\t{\"11 2\", false},\n\t\t{\"123\", false},\n\t\t{\"12345\", false},\n\t\t{\"1123\", false}, // repeated digit\n\t\t{\"12a3\", false},\n\t}\n\tfor _, c := range cases {\n\t\tif _, ok := parseGuess(c.in); ok != c.ok {\n\t\t\tt.Fatalf(\"parseGuess(%q) ok = %v, want %v\", c.in, ok, c.ok)\n\t\t}\n\t}\n}\n\nfunc TestScore(t *testing.T) {\n\ttarget := [4]int{1, 9, 7, 2}\n\n\tif b, c := score(target, [4]int{1, 9, 7, 2}); b != 4 || c != 0 {\n\t\tt.Fatalf(\"exact match: got bulls=%d cows=%d, want 4/0\", b, c)\n\t}\n\tif b, c := score(target, [4]int{2, 7, 9, 1}); b != 0 || c != 4 {\n\t\tt.Fatalf(\"full rotation: got bulls=%d cows=%d, want 0/4\", b, c)\n\t}\n\tif b, c := score(target, [4]int{1, 3, 4, 5}); b != 1 || c != 0 {\n\t\tt.Fatalf(\"one bull: got bulls=%d cows=%d, want 1/0\", b, c)\n\t}\n\tif b, c := score(target, [4]int{5, 6, 7, 8}); b != 1 || c != 0 {\n\t\tt.Fatalf(\"no overlap but position 7: got bulls=%d cows=%d, want 1/0\", b, c)\n\t}\n}\n\nfunc TestNewSecretDistinctDigits(t *testing.T) {\n\tfor seed := int64(0); seed \u003c 50; seed++ {\n\t\td := newSecret(seed)\n\t\tvar seen [10]bool\n\t\tfor _, v := range d {\n\t\t\tif v \u003c 0 || v \u003e 9 {\n\t\t\t\tt.Fatalf(\"digit out of range: %d\", v)\n\t\t\t}\n\t\t\tif seen[v] {\n\t\t\t\tt.Fatalf(\"newSecret(%d) = %v has repeated digit\", seed, d)\n\t\t\t}\n\t\t\tseen[v] = true\n\t\t}\n\t}\n}\n\nfunc TestAddRecordKeepsFastestSorted(t *testing.T) {\n\trecords = nil\n\taddRecord(record{player: \"a\", attempts: 10, round: 1})\n\taddRecord(record{player: \"b\", attempts: 3, round: 2})\n\taddRecord(record{player: \"c\", attempts: 7, round: 3})\n\taddRecord(record{player: \"d\", attempts: 1, round: 4})\n\taddRecord(record{player: \"e\", attempts: 9, round: 5})\n\taddRecord(record{player: \"f\", attempts: 2, round: 6}) // pushes out the worst\n\n\tif len(records) != maxRecords {\n\t\tt.Fatalf(\"len(records) = %d, want %d\", len(records), maxRecords)\n\t}\n\twant := []int{1, 2, 3, 7, 9}\n\tfor i, w := range want {\n\t\tif records[i].attempts != w {\n\t\t\tt.Fatalf(\"records[%d].attempts = %d, want %d\", i, records[i].attempts, w)\n\t\t}\n\t}\n}\n\nfunc TestAddHistoryCaps(t *testing.T) {\n\thistory = nil\n\tfor i := 0; i \u003c maxHistory+5; i++ {\n\t\taddHistory(guessLog{player: \"p\", guess: strconv.Itoa(i), bulls: 0, cows: 0})\n\t}\n\tif len(history) != maxHistory {\n\t\tt.Fatalf(\"len(history) = %d, want %d\", len(history), maxHistory)\n\t}\n\tif history[len(history)-1].guess != strconv.Itoa(maxHistory+4) {\n\t\tt.Fatalf(\"history did not keep the most recent entries\")\n\t}\n}\n\n// Crossing: Guess mutates realm state, needs cur realm + cross(cur).\nfunc TestGuessRoundtrip(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tround = 1\n\tattempts = 0\n\thistory = nil\n\trecords = nil\n\tsecret = [4]int{1, 9, 7, 2}\n\n\tout := Guess(cross(cur), \"1234\")\n\tif !strings.Contains(out, \"bulls\") {\n\t\tt.Fatalf(\"Guess() = %q, want bulls/cows feedback\", out)\n\t}\n\tif attempts != 1 {\n\t\tt.Fatalf(\"attempts = %d, want 1\", attempts)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tout = Guess(cross(cur), \"1972\")\n\tif !strings.Contains(out, \"SOLVED\") {\n\t\tt.Fatalf(\"Guess() = %q, want a solved message\", out)\n\t}\n\tif round != 2 {\n\t\tt.Fatalf(\"round = %d, want 2 (new round should start on solve)\", round)\n\t}\n\tif len(records) != 1 || records[0].attempts != 2 {\n\t\tt.Fatalf(\"records = %v, want one entry with attempts=2\", records)\n\t}\n}\n\nfunc TestGiveUpStartsNewRound(cur realm, t *testing.T) {\n\tround = 1\n\tattempts = 3\n\tsecret = [4]int{4, 5, 6, 7}\n\n\tout := GiveUp(cross(cur))\n\tif !strings.Contains(out, \"4567\") {\n\t\tt.Fatalf(\"GiveUp() = %q, want it to reveal 4567\", out)\n\t}\n\tif round != 2 || attempts != 0 {\n\t\tt.Fatalf(\"round=%d attempts=%d, want round=2 attempts=0\", round, attempts)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/bullscows/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_test.gno","body":"package bullscows\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// clear restores the globals to their init() state so assertions do not depend\n// on which tests ran first. Realm globals live for the whole test binary.\nfunc clear() {\n\tround = 1\n\tattempts = 0\n\thistory = nil\n\trecords = nil\n\tsecret = newSecret(seedFor(round))\n}\n\n// ExampleRender pins the fresh-round view: no guesses, empty leaderboard.\nfunc ExampleRender() {\n\tclear()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Bulls \u0026 Cows\n\t//\n\t// One shared secret 4-digit code (no repeated digits). Call `Guess(\"1972\")` to get **bulls** (right digit, right spot) and **cows** (right digit, wrong spot). First to 4 bulls wins the round; `GiveUp()` reveals the code and starts over.\n\t//\n\t// ## Round 1\n\t//\n\t// Attempts so far: **0**\n\t//\n\t// _No guesses yet this round — be the first._\n\t//\n\t// ## Leaderboard (fastest solves)\n\t//\n\t// _Nobody has cracked a code yet._\n}\n\n// TestRenderHistoryNewestFirst checks the guess table is reverse-chronological.\nfunc TestRenderHistoryNewestFirst(t *testing.T) {\n\tclear()\n\taddHistory(guessLog{player: \"alice\", guess: \"1234\", bulls: 1, cows: 2})\n\taddHistory(guessLog{player: \"bob\", guess: \"5678\", bulls: 0, cows: 1})\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"### Recent guesses\"), \"history section should appear\")\n\tuassert.True(t, strings.Contains(out, \"| `bob` | 5678 | 0 | 1 |\\n| `alice` | 1234 | 1 | 2 |\\n\"),\n\t\t\"newest guess should be listed first\")\n\tuassert.False(t, strings.Contains(out, \"_No guesses yet\"), \"empty-history notice should be gone\")\n}\n\n// TestRenderLeaderboard checks solved records render in rank order.\nfunc TestRenderLeaderboard(t *testing.T) {\n\tclear()\n\taddRecord(record{player: \"carol\", attempts: 3, round: 1})\n\taddRecord(record{player: \"dave\", attempts: 7, round: 2})\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"| 1 | `carol` | 3 | 1 |\\n| 2 | `dave` | 7 | 2 |\\n\"),\n\t\t\"leaderboard should rank fastest first\")\n\tuassert.False(t, strings.Contains(out, \"_Nobody has cracked a code yet._\"),\n\t\t\"empty-leaderboard notice should be gone\")\n}\n\n// TestRenderShortensLongAddresses checks the bech32 addresses players actually\n// have get elided rather than blowing out the table.\nfunc TestRenderShortensLongAddresses(t *testing.T) {\n\tclear()\n\tlong := \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\taddHistory(guessLog{player: long, guess: \"1234\", bulls: 0, cows: 0})\n\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, long), \"full address should not be rendered\")\n\tuassert.True(t, strings.Contains(out, \"| `\"+long[:8]+\"…\"+long[len(long)-4:]+\"` | 1234 |\"),\n\t\t\"address should be shortened to prefix…suffix\")\n}\n\n// TestRenderTracksRoundAndAttempts checks the counters reach the page.\nfunc TestRenderTracksRoundAndAttempts(t *testing.T) {\n\tclear()\n\tround = 4\n\tattempts = 11\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"## Round 4\\n\"), \"round should be shown\")\n\tuassert.True(t, strings.Contains(out, \"Attempts so far: **11**\"), \"attempts should be shown\")\n}\n\n// TestRenderIgnoresPath documents that Render has no sub-routes.\nfunc TestRenderIgnoresPath(t *testing.T) {\n\tclear()\n\tuassert.Equal(t, Render(\"\"), Render(\"/anything\"))\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"56933200","gas_fee":"170799ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"FDL+wnM3JLJjE3gUP6rvFHykUXBrT5bZXfFvgohavjM56IoyY8oZQT2peL9VWpJPz0Ecvipq35YKVwAJHlX6AQ=="}],"memo":""},"metadata":{"timestamp":"1790960890"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"calc","path":"gno.land/r/moul/x/daily/calc/v0","files":[{"name":"README.md","body":"# RPN Calculator\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA shared, stack-based Reverse Polish Notation calculator realm. Anyone can push\ntokens onto a single shared stack: integers are pushed as-is, while an operator\n(`+`, `-`, `*`, `/`) pops the top two operands and pushes the result. Divide-by-zero\nand stack underflow abort the transaction, and `Clear` resets the stack. `Render`\nshows the current stack (bottom→top), the top value as the result, and a usage guide.\n\n## Realm path\n\n`gno.land/r/REPLACE_ADDR/calc`\n\n## Example calls\n\n```\n# Compute (5 3 +) = 8\nPush(\"5\")\nPush(\"3\")\nPush(\"+\")\n\n# Chain: (10 4 -) 2 * = 12\nPush(\"10\")\nPush(\"4\")\nPush(\"-\")\nPush(\"2\")\nPush(\"*\")\n\n# Reset\nClear()\n```\n\nRead the current state via `Render` (e.g. the realm's rendered page).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/calc/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/calc/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/calc/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/calc/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/calc/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/calc/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/calc/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/calc/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"calc.gno","body":"package calc\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// stack holds the shared RPN operand stack, bottom (index 0) to top.\nvar stack []int\n\n// ErrUnderflow is raised when an operator needs more operands than available.\nvar ErrUnderflow = errors.New(\"stack underflow: operator needs two operands\")\n\n// ErrDivByZero is raised on division by zero.\nvar ErrDivByZero = errors.New(\"division by zero\")\n\n// Push consumes a single token: an integer is pushed onto the stack; an\n// operator (+, -, *, /) pops two operands and pushes the result.\nfunc Push(cur realm, token string) {\n\ttoken = strings.TrimSpace(token)\n\tif token == \"\" {\n\t\tpanic(\"empty token\")\n\t}\n\n\tswitch token {\n\tcase \"+\", \"-\", \"*\", \"/\":\n\t\tif len(stack) \u003c 2 {\n\t\t\tpanic(ErrUnderflow.Error())\n\t\t}\n\t\tb := stack[len(stack)-1]\n\t\ta := stack[len(stack)-2]\n\t\tstack = stack[:len(stack)-2]\n\n\t\tvar r int\n\t\tswitch token {\n\t\tcase \"+\":\n\t\t\tr = a + b\n\t\tcase \"-\":\n\t\t\tr = a - b\n\t\tcase \"*\":\n\t\t\tr = a * b\n\t\tcase \"/\":\n\t\t\tif b == 0 {\n\t\t\t\tpanic(ErrDivByZero.Error())\n\t\t\t}\n\t\t\tr = a / b\n\t\t}\n\t\tstack = append(stack, r)\n\t\tchain.Emit(\"Op\", \"op\", token, \"result\", strconv.Itoa(r))\n\tdefault:\n\t\tn, err := strconv.Atoi(token)\n\t\tif err != nil {\n\t\t\tpanic(\"invalid token: expected integer or one of + - * /, got \" + token)\n\t\t}\n\t\tstack = append(stack, n)\n\t\tchain.Emit(\"Push\", \"value\", strconv.Itoa(n))\n\t}\n}\n\n// Clear empties the shared stack.\nfunc Clear(cur realm) {\n\tstack = nil\n\tchain.Emit(\"Clear\")\n}\n\n// Depth returns the number of values currently on the stack.\nfunc Depth() int {\n\treturn len(stack)\n}\n\n// Top returns the top value and whether the stack is non-empty.\nfunc Top() (int, bool) {\n\tif len(stack) == 0 {\n\t\treturn 0, false\n\t}\n\treturn stack[len(stack)-1], true\n}\n\n// Render renders the current stack, the top value as the result, and a\n// short usage guide.\nfunc Render(path string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# RPN Calculator\\n\\n\")\n\n\tsb.WriteString(\"## Result\\n\\n\")\n\tif top, ok := Top(); ok {\n\t\tsb.WriteString(\"**\")\n\t\tsb.WriteString(strconv.Itoa(top))\n\t\tsb.WriteString(\"**\\n\\n\")\n\t} else {\n\t\tsb.WriteString(\"_(empty stack)_\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Stack (bottom → top)\\n\\n\")\n\tif len(stack) == 0 {\n\t\tsb.WriteString(\"_empty_\\n\\n\")\n\t} else {\n\t\tfor i, v := range stack {\n\t\t\tsb.WriteString(strconv.Itoa(i))\n\t\t\tsb.WriteString(\". \")\n\t\t\tsb.WriteString(strconv.Itoa(v))\n\t\t\tsb.WriteString(\"\\n\")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\n\tsb.WriteString(\"## Usage\\n\\n\")\n\tsb.WriteString(\"Reverse Polish Notation: operands first, operator last.\\n\\n\")\n\tsb.WriteString(\"- `Push(\\\"5\\\")` then `Push(\\\"3\\\")` then `Push(\\\"+\\\")` → `8`\\n\")\n\tsb.WriteString(\"- Supported operators: `+`, `-`, `*`, `/` (integer division)\\n\")\n\tsb.WriteString(\"- An operator pops the top two values (a, b) and pushes `a op b`.\\n\")\n\tsb.WriteString(\"- `Clear()` empties the stack.\\n\")\n\tsb.WriteString(\"- Divide-by-zero and underflow abort the transaction.\\n\")\n\n\treturn sb.String()\n}\n"},{"name":"calc_test.gno","body":"package calc\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPushAndAdd(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\tClear(cross(cur))\n\tPush(cross(cur), \"5\")\n\tPush(cross(cur), \"3\")\n\tPush(cross(cur), \"+\")\n\n\tuassert.Equal(t, 1, Depth())\n\ttop, ok := Top()\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 8, top)\n}\n\nfunc TestChainedOps(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bob\")))\n\n\tClear(cross(cur))\n\t// (10 - 4) * 2 = 12\n\tPush(cross(cur), \"10\")\n\tPush(cross(cur), \"4\")\n\tPush(cross(cur), \"-\")\n\tPush(cross(cur), \"2\")\n\tPush(cross(cur), \"*\")\n\n\ttop, ok := Top()\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 12, top)\n\tuassert.Equal(t, 1, Depth())\n}\n\nfunc TestDivision(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"carol\")))\n\n\tClear(cross(cur))\n\tPush(cross(cur), \"20\")\n\tPush(cross(cur), \"6\")\n\tPush(cross(cur), \"/\")\n\n\ttop, _ := Top()\n\tuassert.Equal(t, 3, top) // integer division\n}\n\nfunc TestDivideByZeroAborts(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"dave\")))\n\n\tClear(cross(cur))\n\tPush(cross(cur), \"1\")\n\tPush(cross(cur), \"0\")\n\n\tuassert.AbortsWithMessage(t, cur, ErrDivByZero.Error(), func() {\n\t\tPush(cross(cur), \"/\")\n\t})\n}\n\nfunc TestUnderflowAborts(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"erin\")))\n\n\tClear(cross(cur))\n\tPush(cross(cur), \"42\")\n\n\tuassert.AbortsWithMessage(t, cur, ErrUnderflow.Error(), func() {\n\t\tPush(cross(cur), \"+\")\n\t})\n}\n\nfunc TestClearEmpties(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"frank\")))\n\n\tPush(cross(cur), \"7\")\n\tPush(cross(cur), \"9\")\n\tClear(cross(cur))\n\n\tuassert.Equal(t, 0, Depth())\n\t_, ok := Top()\n\tuassert.False(t, ok)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/calc/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package calc\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # RPN Calculator\n\t//\n\t// ## Result\n\t//\n\t// _(empty stack)_\n\t//\n\t// ## Stack (bottom → top)\n\t//\n\t// _empty_\n\t//\n\t// ## Usage\n\t//\n\t// Reverse Polish Notation: operands first, operator last.\n\t//\n\t// - `Push(\"5\")` then `Push(\"3\")` then `Push(\"+\")` → `8`\n\t// - Supported operators: `+`, `-`, `*`, `/` (integer division)\n\t// - An operator pops the top two values (a, b) and pushes `a op b`.\n\t// - `Clear()` empties the stack.\n\t// - Divide-by-zero and underflow abort the transaction.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"32415200","gas_fee":"97245ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"E3sj+J347yofC5r7PSMcyBagwF3/cJLCueIQG9RVDYB0BACRar+dMoPGNmZwnfDNF88vQhCvFtkAhcmeDx+GzA=="}],"memo":""},"metadata":{"timestamp":"1790960890"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"cliffvestingdemo","path":"gno.land/r/moul/x/daily/cliffvestingdemo/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/cliffvestingdemo/v0`\n\n**Live demo of [`p/moul/x/daily/cliffvesting`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/cliffvesting).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/cliffvestingdemo/v0`](https://gno.land/r/moul/x/daily/cliffvestingdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/cliffvestingdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cliffvestingdemo/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/cliffvestingdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cliffvestingdemo/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/cliffvestingdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cliffvestingdemo/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/cliffvestingdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cliffvestingdemo/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/cliffvestingdemo/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/cliffvestingdemo/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"cliffvestingdemo.gno","body":"// Package cliffvestingdemo is a small gnoweb demo of the vesting calculator\n// provided by the [p/moul/x/daily/cliffvesting](/p/moul/x/daily/cliffvesting/v1)\n// library: the cliff step, the linear ramp, integer rounding, and the two\n// arithmetic bugs the library exists to avoid.\n//\n// It contains no vesting logic of its own and holds no coins. Stateless, so\n// Render is deterministic, which is precisely what the library is for.\npackage cliffvestingdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/cliffvesting/v1\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Cliff Vesting\\n\\n\")\n\tb.WriteString(\"A pure vesting calculator, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/cliffvesting`](/p/moul/x/daily/cliffvesting/v1) library.\\n\\n\")\n\n\t// 1200 tokens over 12 months, 3-month cliff.\n\ts, err := cliffvesting.New(1200, 0, 3, 12)\n\tif err != nil {\n\t\treturn \"error: \" + err.Error()\n\t}\n\n\tb.WriteString(\"## A 12-month grant with a 3-month cliff\\n\\n\")\n\tb.WriteString(\"`1200` tokens, `Start = 0`, `Cliff = 3`, `End = 12`.\\n\\n\")\n\tb.WriteString(\"| month | vested | unvested | % |\\n|---|---|---|---|\\n\")\n\tfor m := int64(0); m \u003c= 12; m++ {\n\t\tnote := \"\"\n\t\tswitch m {\n\t\tcase 2:\n\t\t\tnote = \" ← nothing yet\"\n\t\tcase 3:\n\t\t\tnote = \" ← **cliff**\"\n\t\tcase 12:\n\t\t\tnote = \" ← fully vested\"\n\t\t}\n\t\tb.WriteString(\"| \" + strconv.FormatInt(m, 10) + \" | \" +\n\t\t\tstrconv.FormatInt(s.Vested(m), 10) + \" | \" +\n\t\t\tstrconv.FormatInt(s.Unvested(m), 10) + \" | \" +\n\t\t\tstrconv.FormatInt(s.PercentVested(m), 10) + \"%\" + note + \" |\\n\")\n\t}\n\n\tb.WriteString(\"\\nThe cliff is a **step, not a ramp**: at month 3 a quarter of the term \")\n\tb.WriteString(\"has elapsed, so `\")\n\tb.WriteString(strconv.FormatInt(s.CliffAmount(), 10))\n\tb.WriteString(\"` tokens unlock at once. After that it accrues linearly.\\n\\n\")\n\n\tb.WriteString(\"## Claiming\\n\\n\")\n\tb.WriteString(\"The library tracks no balances, so the caller supplies what has already \")\n\tb.WriteString(\"been claimed:\\n\\n\")\n\tb.WriteString(\"| at month | already claimed | claimable |\\n|---|---|---|\\n\")\n\tfor _, c := range [][2]int64{{6, 0}, {6, 300}, {6, 600}, {12, 600}} {\n\t\tb.WriteString(\"| \" + strconv.FormatInt(c[0], 10) + \" | \" +\n\t\t\tstrconv.FormatInt(c[1], 10) + \" | \" +\n\t\t\tstrconv.FormatInt(s.Claimable(c[0], c[1]), 10) + \" |\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Integer rounding\\n\\n\")\n\tb.WriteString(\"All arithmetic is integer, no float ever reaches consensus state. \")\n\tb.WriteString(\"Rounding is **down**, so nobody is ever paid more than they earned, \")\n\tb.WriteString(\"and the final instalment collects the remainder.\\n\\n\")\n\todd, _ := cliffvesting.NewLinear(1000, 0, 3)\n\tb.WriteString(\"`1000` over `3` periods:\\n\\n\")\n\tb.WriteString(\"| t | vested |\\n|---|---|\\n\")\n\tfor m := int64(0); m \u003c= 3; m++ {\n\t\tb.WriteString(\"| \" + strconv.FormatInt(m, 10) + \" | \" +\n\t\t\tstrconv.FormatInt(odd.Vested(m), 10) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n`333 + 333 + 334`, and the end is exactly `1000`, never `999`.\\n\\n\")\n\n\tb.WriteString(\"## Bug 1: a rate truncated to zero\\n\\n\")\n\ttiny, _ := cliffvesting.NewLinear(7, 0, 1000)\n\tb.WriteString(\"When the total is smaller than the duration, computing a per-tick rate \")\n\tb.WriteString(\"first truncates it to zero and **nothing ever vests**. Multiplying \")\n\tb.WriteString(\"before dividing keeps it honest. `7` tokens over `1000` ticks:\\n\\n\")\n\tb.WriteString(\"| t | vested |\\n|---|---|\\n\")\n\tfor _, m := range []int64{100, 150, 500, 1000} {\n\t\tb.WriteString(\"| \" + strconv.FormatInt(m, 10) + \" | \" +\n\t\t\tstrconv.FormatInt(tiny.Vested(m), 10) + \" |\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Bug 2: a product that leaves int64\\n\\n\")\n\tb.WriteString(\"Multiplying first is only safe if the product fits. Over a term \")\n\tb.WriteString(\"measured in **seconds**, `total * elapsed` passes 2^63 for any grant \")\n\tb.WriteString(\"above about `146,036` whole coins, and a wrapped int64 is still a \")\n\tb.WriteString(\"valid int64: `v0` of this library returned a **negative** vested \")\n\tb.WriteString(\"amount and nothing signalled it. `v1` routes the product through a \")\n\tb.WriteString(\"128-bit intermediate.\\n\\n\")\n\tb.WriteString(\"A real two-year schedule, `1789225200` to `1852383600`, at the \")\n\tb.WriteString(\"halfway mark:\\n\\n\")\n\tb.WriteString(\"| grant | vested at halfway | expected |\\n|---|---|---|\\n\")\n\tconst (\n\t\tvStart int64 = 1789225200\n\t\tvEnd   int64 = 1852383600\n\t)\n\tfor _, total := range []int64{100000000000, 146037000000, 318720000000000} {\n\t\tbig, err := cliffvesting.NewLinear(total, vStart, vEnd)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tb.WriteString(\"| \" + strconv.FormatInt(total, 10) + \" | \" +\n\t\t\tstrconv.FormatInt(big.Vested(vStart+(vEnd-vStart)/2), 10) + \" | \" +\n\t\t\tstrconv.FormatInt(total/2, 10) + \" |\\n\")\n\t}\n\treturn b.String()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/cliffvestingdemo/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package cliffvestingdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Cliff Vesting\n\t//\n\t// A pure vesting calculator, demoing the [`p/moul/x/daily/cliffvesting`](/p/moul/x/daily/cliffvesting/v1) library.\n\t//\n\t// ## A 12-month grant with a 3-month cliff\n\t//\n\t// `1200` tokens, `Start = 0`, `Cliff = 3`, `End = 12`.\n\t//\n\t// | month | vested | unvested | % |\n\t// |---|---|---|---|\n\t// | 0 | 0 | 1200 | 0% |\n\t// | 1 | 0 | 1200 | 0% |\n\t// | 2 | 0 | 1200 | 0% ← nothing yet |\n\t// | 3 | 300 | 900 | 25% ← **cliff** |\n\t// | 4 | 400 | 800 | 33% |\n\t// | 5 | 500 | 700 | 41% |\n\t// | 6 | 600 | 600 | 50% |\n\t// | 7 | 700 | 500 | 58% |\n\t// | 8 | 800 | 400 | 66% |\n\t// | 9 | 900 | 300 | 75% |\n\t// | 10 | 1000 | 200 | 83% |\n\t// | 11 | 1100 | 100 | 91% |\n\t// | 12 | 1200 | 0 | 100% ← fully vested |\n\t//\n\t// The cliff is a **step, not a ramp**: at month 3 a quarter of the term has elapsed, so `300` tokens unlock at once. After that it accrues linearly.\n\t//\n\t// ## Claiming\n\t//\n\t// The library tracks no balances, so the caller supplies what has already been claimed:\n\t//\n\t// | at month | already claimed | claimable |\n\t// |---|---|---|\n\t// | 6 | 0 | 600 |\n\t// | 6 | 300 | 300 |\n\t// | 6 | 600 | 0 |\n\t// | 12 | 600 | 600 |\n\t//\n\t// ## Integer rounding\n\t//\n\t// All arithmetic is integer, no float ever reaches consensus state. Rounding is **down**, so nobody is ever paid more than they earned, and the final instalment collects the remainder.\n\t//\n\t// `1000` over `3` periods:\n\t//\n\t// | t | vested |\n\t// |---|---|\n\t// | 0 | 0 |\n\t// | 1 | 333 |\n\t// | 2 | 666 |\n\t// | 3 | 1000 |\n\t//\n\t// `333 + 333 + 334`, and the end is exactly `1000`, never `999`.\n\t//\n\t// ## Bug 1: a rate truncated to zero\n\t//\n\t// When the total is smaller than the duration, computing a per-tick rate first truncates it to zero and **nothing ever vests**. Multiplying before dividing keeps it honest. `7` tokens over `1000` ticks:\n\t//\n\t// | t | vested |\n\t// |---|---|\n\t// | 100 | 0 |\n\t// | 150 | 1 |\n\t// | 500 | 3 |\n\t// | 1000 | 7 |\n\t//\n\t// ## Bug 2: a product that leaves int64\n\t//\n\t// Multiplying first is only safe if the product fits. Over a term measured in **seconds**, `total * elapsed` passes 2^63 for any grant above about `146,036` whole coins, and a wrapped int64 is still a valid int64: `v0` of this library returned a **negative** vested amount and nothing signalled it. `v1` routes the product through a 128-bit intermediate.\n\t//\n\t// A real two-year schedule, `1789225200` to `1852383600`, at the halfway mark:\n\t//\n\t// | grant | vested at halfway | expected |\n\t// |---|---|---|\n\t// | 100000000000 | 50000000000 | 50000000000 |\n\t// | 146037000000 | 73018500000 | 73018500000 |\n\t// | 318720000000000 | 159360000000000 | 159360000000000 |\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"37454000","gas_fee":"112362ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"L/Vi0KHBKX1l0PPUdFLyTLHZwYzvVYak0FfFZpUXoa8tdoBPUSqrkTQypclrI4y2WQA4qMq6ZW+HHMtoOJu0tg=="}],"memo":""},"metadata":{"timestamp":"1790960891"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"closestguess","path":"gno.land/r/moul/x/daily/closestguess/v1","files":[{"name":"README.md","body":"# Closest Guess\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA blind, multiplayer number-guessing puzzle: submit one silent guess per round in 1..1000, then anyone calls Reveal() to disclose the hidden target and crown whoever landed closest. No hints, no iterative narrowing — just one shot and a leaderboard ranked by smallest distance across all-time rounds. It's a deliberately different twist on the genre from higher/lower or bulls-and-cows: the suspense is in not knowing until reveal.\n\nBuilt for sapphire (gno 0.9). Live demo (agent address): https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/closestguess\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/closestguess) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nVisible change: addresses now render in monospace.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/closestguess/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/closestguess/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/closestguess/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/closestguess/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/closestguess/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/closestguess/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/closestguess/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/closestguess/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/closestguess/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/closestguess/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"closestguess.gno","body":"// Package closestguess is a blind, multiplayer number-guessing puzzle.\n//\n// Unlike a classic higher/lower guessing game, closestguess gives NO feedback\n// per guess. Each round hides a target in 1..1000 (derived deterministically\n// from the block height the round started at); every address may submit\n// exactly one blind Guess for the round. Whenever someone calls Reveal, the\n// round closes: the target is disclosed, the guess with the smallest absolute\n// distance wins (ties go to whoever guessed first), the winner is recorded on\n// the leaderboard, and a fresh round starts immediately.\npackage closestguess\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\nconst (\n\tminTarget = 1\n\tmaxTarget = 1000\n)\n\n// roundT holds the mutable state of the open round. The target stays hidden\n// (never rendered, never returned) until Reveal closes the round.\ntype roundT struct {\n\tnumber      int\n\tstartHeight int64\n\ttarget      int\n}\n\n// winRecord is one closed-round result, kept for the leaderboard.\ntype winRecord struct {\n\tround    int\n\twinner   string\n\ttarget   int\n\tguess    int\n\tdistance int\n\tplayers  int\n}\n\n// guessEntry is one address's blind guess for the current round.\ntype guessEntry struct {\n\taddr string\n\tn    int\n}\n\nvar (\n\tcurrent *roundT\n\t// entries holds one guessEntry per address for the CURRENT round only, in\n\t// submission order (so Reveal can break distance ties in favor of\n\t// whoever guessed first). Reset on every Reveal. A plain slice is fine\n\t// here: rounds are player-scoped and small, unlike long-lived global\n\t// state where avl.Tree would matter.\n\tentries []guessEntry\n\t// leaderboard is append-only across all rounds; sorted on render.\n\tleaderboard []winRecord\n)\n\nfunc init() {\n\tcurrent = newRound(1, runtime.ChainHeight())\n}\n\n// newRound builds a fresh round whose hidden target derives deterministically\n// from the start height and round number. Gno has no runtime RNG, so mixing\n// height with the round number is the only available entropy, and it also\n// keeps consecutive rounds at the same height from repeating a target.\nfunc newRound(number int, height int64) *roundT {\n\treturn \u0026roundT{\n\t\tnumber:      number,\n\t\tstartHeight: height,\n\t\ttarget:      targetFromHeight(height, number),\n\t}\n}\n\nfunc targetFromHeight(h int64, round int) int {\n\tif h \u003c 0 {\n\t\th = -h\n\t}\n\tspan := int64(maxTarget - minTarget + 1)\n\tmixed := h*2654435761 + int64(round)*40503 + 12345\n\tif mixed \u003c 0 {\n\t\tmixed = -mixed\n\t}\n\treturn int(mixed%span) + minTarget\n}\n\n// Guess records the caller's single blind guess for the current round. It\n// returns no hint about correctness — that is the whole point of the puzzle.\n// Crossing function: caller invokes as Guess(cross(cur), n).\nfunc Guess(cur realm, n int) string {\n\tif n \u003c minTarget || n \u003e maxTarget {\n\t\tpanic(\"guess must be in \" + strconv.Itoa(minTarget) + \"..\" + strconv.Itoa(maxTarget))\n\t}\n\n\tcaller := cur.Previous().Address().String()\n\tif hasGuessed(caller) {\n\t\tpanic(\"you already guessed this round; wait for Reveal()\")\n\t}\n\n\tentries = append(entries, guessEntry{addr: caller, n: n})\n\n\tchain.Emit(\"GuessSubmitted\",\n\t\t\"round\", strconv.Itoa(current.number),\n\t\t\"player\", caller,\n\t)\n\n\treturn \"guess recorded for round \" + strconv.Itoa(current.number) + \" (\" +\n\t\tstrconv.Itoa(len(entries)) + \" player(s) so far) — call Reveal() to see who's closest\"\n}\n\nfunc hasGuessed(addr string) bool {\n\tfor _, e := range entries {\n\t\tif e.addr == addr {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// Reveal closes the current round: discloses the target, crowns whoever\n// landed closest (ties favor the earliest guesser), records a leaderboard\n// entry, and opens a fresh round. Panics if nobody has guessed yet.\n// Crossing function.\nfunc Reveal(cur realm) string {\n\tif len(entries) == 0 {\n\t\tpanic(\"no guesses submitted yet this round\")\n\t}\n\n\ttarget := current.target\n\twinner := entries[0]\n\tbest := distance(winner.n, target)\n\tfor _, e := range entries[1:] {\n\t\tif d := distance(e.n, target); d \u003c best {\n\t\t\tbest = d\n\t\t\twinner = e\n\t\t}\n\t}\n\n\trec := winRecord{\n\t\tround:    current.number,\n\t\twinner:   winner.addr,\n\t\ttarget:   target,\n\t\tguess:    winner.n,\n\t\tdistance: best,\n\t\tplayers:  len(entries),\n\t}\n\tleaderboard = append(leaderboard, rec)\n\n\tchain.Emit(\"RoundRevealed\",\n\t\t\"round\", strconv.Itoa(rec.round),\n\t\t\"winner\", winner.addr,\n\t\t\"target\", strconv.Itoa(target),\n\t\t\"distance\", strconv.Itoa(best),\n\t)\n\n\tclosedRound := current.number\n\tcurrent = newRound(closedRound+1, runtime.ChainHeight())\n\tentries = nil\n\n\treturn \"round \" + strconv.Itoa(closedRound) + \" revealed: target was \" + strconv.Itoa(target) +\n\t\t\" — \" + ui.AddrOf(winner.addr) + \" wins, guessed \" + strconv.Itoa(winner.n) +\n\t\t\" (distance \" + strconv.Itoa(best) + \") among \" + strconv.Itoa(rec.players) +\n\t\t\" player(s). Round \" + strconv.Itoa(current.number) + \" is now open.\"\n}\n\nfunc distance(guess, target int) int {\n\td := guess - target\n\tif d \u003c 0 {\n\t\td = -d\n\t}\n\treturn d\n}\n\n// Render produces the gnoweb Markdown view. The current round's target and\n// individual guess values are never shown — only the player count — so\n// rendering the page can't leak the puzzle.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Closest Guess\\n\\n\")\n\tb.WriteString(\"A blind, multiplayer number-guessing puzzle. Each round hides a target in \")\n\tb.WriteString(\"**\" + strconv.Itoa(minTarget) + \"..\" + strconv.Itoa(maxTarget) + \"**. \")\n\tb.WriteString(\"Call `Guess(n)` once per round — you get no feedback. \")\n\tb.WriteString(\"Anyone can call `Reveal()` to close the round: the target is disclosed and \")\n\tb.WriteString(\"whoever landed closest wins.\\n\\n\")\n\n\tb.WriteString(\"## Current round\\n\\n\")\n\tb.WriteString(\"- Round: **\" + strconv.Itoa(current.number) + \"**\\n\")\n\tb.WriteString(\"- Started at block height: \" + strconv.FormatInt(current.startHeight, 10) + \"\\n\")\n\tb.WriteString(\"- Players guessed so far: \" + strconv.Itoa(len(entries)) + \"\\n\")\n\tb.WriteString(\"- Status: **open** — target hidden until `Reveal()` is called.\\n\\n\")\n\n\tb.WriteString(\"## Leaderboard (closest-ever wins)\\n\\n\")\n\tb.WriteString(renderLeaderboard())\n\n\tb.WriteString(\"\\n## How to play\\n\\n\")\n\tb.WriteString(\"```\\n\")\n\tb.WriteString(\"Guess(n)   // n in 1..1000, one shot per address per round, no feedback\\n\")\n\tb.WriteString(\"Reveal()   // closes the round: reveals target, crowns the closest guess\\n\")\n\tb.WriteString(\"```\\n\")\n\n\treturn b.String()\n}\n\n// renderLeaderboard formats closed rounds ranked by smallest distance (ties:\n// earlier round first). Sorted on a copy so state is untouched.\nfunc renderLeaderboard() string {\n\tif len(leaderboard) == 0 {\n\t\treturn \"_No round has been revealed yet — be the first to call `Reveal()`!_\\n\"\n\t}\n\n\tranked := make([]winRecord, len(leaderboard))\n\tcopy(ranked, leaderboard)\n\tsortByClosest(ranked)\n\n\tvar b strings.Builder\n\tb.WriteString(\"| Rank | Player | Round | Target | Guess | Distance | Players |\\n\")\n\tb.WriteString(\"|---|---|---|---|---|---|---|\\n\")\n\tfor i, w := range ranked {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | \" + ui.AddrOf(w.winner) + \" | \" +\n\t\t\tstrconv.Itoa(w.round) + \" | \" + strconv.Itoa(w.target) + \" | \" +\n\t\t\tstrconv.Itoa(w.guess) + \" | \" + strconv.Itoa(w.distance) + \" | \" +\n\t\t\tstrconv.Itoa(w.players) + \" |\\n\")\n\t}\n\treturn b.String()\n}\n\n// sortByClosest does an in-place insertion sort: smallest distance first,\n// then earlier round first on ties. Small n; insertion sort keeps it\n// deterministic and dependency-free.\nfunc sortByClosest(rs []winRecord) {\n\tfor i := 1; i \u003c len(rs); i++ {\n\t\tj := i\n\t\tfor j \u003e 0 \u0026\u0026 closer(rs[j], rs[j-1]) {\n\t\t\trs[j], rs[j-1] = rs[j-1], rs[j]\n\t\t\tj--\n\t\t}\n\t}\n}\n\nfunc closer(a, b winRecord) bool {\n\tif a.distance != b.distance {\n\t\treturn a.distance \u003c b.distance\n\t}\n\treturn a.round \u003c b.round\n}\n"},{"name":"closestguess_test.gno","body":"package closestguess\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// resetGame re-initializes package globals so each test starts clean; init()\n// runs only once for the whole test binary.\nfunc resetGame(height int64) {\n\tcurrent = newRound(1, height)\n\tentries = nil\n\tleaderboard = nil\n}\n\nfunc TestTargetFromHeight(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\theight int64\n\t}{\n\t\t{\"zero\", 0},\n\t\t{\"one\", 1},\n\t\t{\"large\", 123456},\n\t\t{\"negative\", -42},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := targetFromHeight(tt.height, 1)\n\t\tif got \u003c minTarget || got \u003e maxTarget {\n\t\t\tt.Errorf(\"%s: targetFromHeight(%d,1)=%d, want in %d..%d\", tt.name, tt.height, got, minTarget, maxTarget)\n\t\t}\n\t\tif again := targetFromHeight(tt.height, 1); again != got {\n\t\t\tt.Errorf(\"%s: non-deterministic: %d != %d\", tt.name, again, got)\n\t\t}\n\t}\n\n\t// Different round numbers at the same height should (almost always) mix\n\t// to different targets, so consecutive rounds don't repeat.\n\ta := targetFromHeight(100, 1)\n\tb := targetFromHeight(100, 2)\n\tif a == b {\n\t\tt.Errorf(\"targetFromHeight(100,1) == targetFromHeight(100,2) == %d, want them to differ\", a)\n\t}\n}\n\nfunc TestDistance(t *testing.T) {\n\tcases := []struct{ a, b, want int }{\n\t\t{5, 5, 0},\n\t\t{5, 8, 3},\n\t\t{8, 5, 3},\n\t\t{0, 1000, 1000},\n\t}\n\tfor _, c := range cases {\n\t\tif got := distance(c.a, c.b); got != c.want {\n\t\t\tt.Errorf(\"distance(%d,%d) = %d, want %d\", c.a, c.b, got, c.want)\n\t\t}\n\t}\n}\n\n// TestGuessRejectsOutOfRangeAndDuplicate exercises the crossing Guess\n// function, so it takes cur realm and calls through cross(cur). A panic\n// raised across the crossing call boundary isn't catchable by a plain\n// defer/recover; revive() is the boundary-aware way to assert on it.\nfunc TestGuessRejectsOutOfRangeAndDuplicate(cur realm, t *testing.T) {\n\tresetGame(10)\n\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tif r := revive(func() { Guess(cross(cur), 0) }); r == nil {\n\t\tt.Error(\"Guess(0) should panic: out of range\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tmsg := Guess(cross(cur), 500)\n\tif !strings.Contains(msg, \"recorded\") {\n\t\tt.Errorf(\"Guess(500) = %q, want it to mention 'recorded'\", msg)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tif r := revive(func() { Guess(cross(cur), 501) }); r == nil {\n\t\tt.Error(\"second Guess from the same address should panic\")\n\t}\n}\n\n// TestRevealPicksClosestAndStartsNewRound exercises Guess + Reveal together.\nfunc TestRevealPicksClosestAndStartsNewRound(cur realm, t *testing.T) {\n\tresetGame(50)\n\ttarget := current.target\n\tprevRound := current.number\n\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\tfar := target + 100\n\tif far \u003e maxTarget {\n\t\tfar = target - 100\n\t}\n\tif far \u003c minTarget {\n\t\tfar = minTarget\n\t}\n\tnear := target + 1\n\tif near \u003e maxTarget {\n\t\tnear = target - 1\n\t}\n\tif near \u003c minTarget {\n\t\tnear = minTarget\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tGuess(cross(cur), far)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tGuess(cross(cur), near)\n\n\tmsg := Reveal(cross(cur))\n\tif !strings.Contains(msg, \"revealed\") {\n\t\tt.Errorf(\"Reveal() = %q, want it to mention 'revealed'\", msg)\n\t}\n\tif len(leaderboard) != 1 {\n\t\tt.Fatalf(\"leaderboard len = %d, want 1\", len(leaderboard))\n\t}\n\tif leaderboard[0].winner != bob.String() {\n\t\tt.Errorf(\"winner = %q, want %q (closer guess)\", leaderboard[0].winner, bob.String())\n\t}\n\tif current.number != prevRound+1 {\n\t\tt.Errorf(\"round number = %d, want %d\", current.number, prevRound+1)\n\t}\n\tif len(entries) != 0 {\n\t\tt.Errorf(\"entries should reset after Reveal, got %d\", len(entries))\n\t}\n}\n\n// TestRevealPanicsWithNoGuesses checks the panic path via revive() (see the\n// note on TestGuessRejectsOutOfRangeAndDuplicate).\nfunc TestRevealPanicsWithNoGuesses(cur realm, t *testing.T) {\n\tresetGame(1)\n\tif r := revive(func() { Reveal(cross(cur)) }); r == nil {\n\t\tt.Error(\"Reveal() with no guesses should panic\")\n\t}\n}\n\n// TestRenderContainsState is a plain read — no cur.\nfunc TestRenderContainsState(t *testing.T) {\n\tresetGame(3)\n\tout := Render(\"\")\n\tfor _, want := range []string{\"Closest Guess\", \"Current round\", \"Leaderboard\"} {\n\t\tif !strings.Contains(out, want) {\n\t\t\tt.Errorf(\"Render() missing %q\", want)\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/closestguess/v1\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"51559000","gas_fee":"154677ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"gc8eylWfk/uUMezRC1VSbuQ5yEXutGBhfj4MN3w/9PobLAXyfpAIf7IqFEFZSDQZU84PvUWdQAh3LU5jaQLexw=="}],"memo":""},"metadata":{"timestamp":"1790960891"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"coinflipduel","path":"gno.land/r/moul/x/daily/coinflipduel/v1","files":[{"name":"README.md","body":"# Coin-Flip Duel\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA one-on-one coin-flip duel between two addresses. The challenger picks\nheads or tails and names an opponent; the opponent settles it with a single\n`Accept` call, which flips the coin on the spot and records the result. No\nstakes, just an on-chain win/loss record and a running champion.\n\nRealm: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/coinflipduel`\n\n## Example calls\n\n```\nChallenge(\"g1bob...\", \"heads\")   # as alice -\u003e opens duel #1, alice called heads\nAccept(\"1\")                       # as bob   -\u003e flips the coin, settles the duel\nCancel(\"2\")                       # as the challenger, before it's accepted\n```\n\n## Render paths\n\n- `` (home) — arena summary, champion, pending duels\n- `\u003cid\u003e` (e.g. `3`) — a single duel's detail\n- `\u003caddress\u003e` — a player's win/loss record\n\n## Toolchain\n\nBuilt and tested against the local `gno` binary (`master.3130+bf5b31eda`).\n`gno test .` passes; see the injected build brief for the sapphire (gno 0.9)\nAPI notes this realm follows (`chain`, `chain/runtime`, `gno.land/p/nt/avl/v0`).\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/coinflipduel) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline` helper.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/coinflipduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/coinflipduel/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/coinflipduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/coinflipduel/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/coinflipduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/coinflipduel/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/coinflipduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/coinflipduel/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/coinflipduel/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/coinflipduel/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"coinflipduel.gno","body":"// Package coinflipduel is a one-on-one coin-flip duel: challenge another\n// address, they call heads or tails, and the block settles it. No stakes,\n// just bragging rights tracked in an on-chain win/loss record.\npackage coinflipduel\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// duelStatus tracks the lifecycle of a duel.\ntype duelStatus int\n\nconst (\n\tstatusPending duelStatus = iota\n\tstatusResolved\n\tstatusCancelled\n)\n\nfunc (s duelStatus) String() string {\n\tswitch s {\n\tcase statusPending:\n\t\treturn \"pending\"\n\tcase statusResolved:\n\t\treturn \"resolved\"\n\tcase statusCancelled:\n\t\treturn \"cancelled\"\n\tdefault:\n\t\treturn \"?\"\n\t}\n}\n\n// duel is one challenge from Challenger to Opponent over a single coin flip.\n// The Challenger calls a side up front; the Opponent's only move is to\n// accept, which triggers the flip.\ntype duel struct {\n\tID         string\n\tChallenger address\n\tOpponent   address\n\tCall       string // \"heads\" or \"tails\" — the challenger's pick\n\tStatus     duelStatus\n\tResult     string // \"heads\" or \"tails\" once resolved\n\tWinner     address\n\tCreatedAt  int64\n\tResolvedAt int64\n}\n\n// playerState is the persisted win/loss record for one address.\ntype playerState struct {\n\tWins   int\n\tLosses int\n\tDuels  int\n}\n\nvar (\n\tduels   avl.Tree // duel ID -\u003e *duel\n\tplayers avl.Tree // address string -\u003e *playerState\n\n\tnextID    int\n\tflipNonce int\n\ttotalDone int\n\n\tchampion     address\n\tchampionWins int\n)\n\nfunc parseCall(s string) (string, bool) {\n\tswitch strings.ToLower(strings.TrimSpace(s)) {\n\tcase \"heads\", \"h\":\n\t\treturn \"heads\", true\n\tcase \"tails\", \"t\":\n\t\treturn \"tails\", true\n\tdefault:\n\t\treturn \"\", false\n\t}\n}\n\n// flipCoin derives a deterministic pseudo-random side from the current chain\n// height, a monotonic per-realm nonce, and both duelists' addresses, so two\n// duels resolved in the same block still diverge.\nfunc flipCoin(d *duel) string {\n\tflipNonce++\n\tseed := runtime.ChainHeight() + int64(flipNonce)\n\ts := d.Challenger.String() + d.Opponent.String() + d.ID\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tseed += int64(s[i])\n\t}\n\tif seed \u003c 0 {\n\t\tseed = -seed\n\t}\n\tif seed%2 == 0 {\n\t\treturn \"heads\"\n\t}\n\treturn \"tails\"\n}\n\nfunc getOrCreate(addr address) *playerState {\n\tkey := addr.String()\n\tif v := players.Get(key); v != nil {\n\t\treturn v.(*playerState)\n\t}\n\tps := \u0026playerState{}\n\tplayers.Set(key, ps)\n\treturn ps\n}\n\nfunc recordResult(winner, loser address) {\n\tw := getOrCreate(winner)\n\tw.Wins++\n\tw.Duels++\n\tl := getOrCreate(loser)\n\tl.Losses++\n\tl.Duels++\n\n\tif w.Wins \u003e championWins {\n\t\tchampionWins = w.Wins\n\t\tchampion = winner\n\t}\n}\n\n// Challenge opens a new duel against opponentAddr, locking in the\n// challenger's call of \"heads\"/\"tails\" (\"h\"/\"t\" also accepted). The\n// opponent settles it by calling Accept with the returned duel ID.\nfunc Challenge(cur realm, opponentAddr string, call string) string {\n\tchallenger := cur.Previous().Address()\n\n\topponent := address(strings.TrimSpace(opponentAddr))\n\tif !opponent.IsValid() {\n\t\tpanic(\"invalid opponent address\")\n\t}\n\tif opponent == challenger {\n\t\tpanic(\"cannot duel yourself\")\n\t}\n\n\tpick, ok := parseCall(call)\n\tif !ok {\n\t\tpanic(\"call must be heads or tails (h/t)\")\n\t}\n\n\tnextID++\n\tid := strconv.Itoa(nextID)\n\td := \u0026duel{\n\t\tID:         id,\n\t\tChallenger: challenger,\n\t\tOpponent:   opponent,\n\t\tCall:       pick,\n\t\tStatus:     statusPending,\n\t\tCreatedAt:  runtime.ChainHeight(),\n\t}\n\tduels.Set(id, d)\n\n\tchain.Emit(\"DuelChallenged\",\n\t\t\"id\", id,\n\t\t\"challenger\", challenger.String(),\n\t\t\"opponent\", opponent.String(),\n\t\t\"call\", pick,\n\t)\n\n\treturn \"duel #\" + id + \" created: you called \" + pick +\n\t\t\", waiting for \" + opponent.String() + \" to accept\"\n}\n\n// Accept settles a pending duel. Only the challenged opponent may call it;\n// the flip happens immediately and the result is final.\nfunc Accept(cur realm, id string) string {\n\tcaller := cur.Previous().Address()\n\n\tv := duels.Get(id)\n\tif v == nil {\n\t\tpanic(\"no such duel\")\n\t}\n\td := v.(*duel)\n\n\tif d.Status != statusPending {\n\t\tpanic(\"duel already \" + d.Status.String())\n\t}\n\tif caller != d.Opponent {\n\t\tpanic(\"only the challenged opponent can accept this duel\")\n\t}\n\n\tresult := flipCoin(d)\n\td.Result = result\n\td.Status = statusResolved\n\td.ResolvedAt = runtime.ChainHeight()\n\n\tif result == d.Call {\n\t\td.Winner = d.Challenger\n\t\trecordResult(d.Challenger, d.Opponent)\n\t} else {\n\t\td.Winner = d.Opponent\n\t\trecordResult(d.Opponent, d.Challenger)\n\t}\n\n\ttotalDone++\n\n\tchain.Emit(\"DuelResolved\",\n\t\t\"id\", id,\n\t\t\"result\", result,\n\t\t\"winner\", d.Winner.String(),\n\t)\n\n\treturn \"the coin landed on \" + result + \" -- \" + d.Winner.String() + \" wins duel #\" + id\n}\n\n// Cancel withdraws a still-pending duel. Only the challenger may cancel,\n// and only before the opponent accepts.\nfunc Cancel(cur realm, id string) string {\n\tcaller := cur.Previous().Address()\n\n\tv := duels.Get(id)\n\tif v == nil {\n\t\tpanic(\"no such duel\")\n\t}\n\td := v.(*duel)\n\n\tif d.Status != statusPending {\n\t\tpanic(\"duel already \" + d.Status.String())\n\t}\n\tif caller != d.Challenger {\n\t\tpanic(\"only the challenger can cancel this duel\")\n\t}\n\n\td.Status = statusCancelled\n\treturn \"duel #\" + id + \" cancelled\"\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Coin-Flip Duel\\n\\n\")\n\tb.WriteString(\"Challenge another address to a coin flip. You call heads or tails \" +\n\t\t\"up front; they accept and the block decides. No stakes -- just a record.\\n\\n\")\n\tb.WriteString(\"- Total duels resolved: \" + strconv.Itoa(totalDone) + \"\\n\")\n\n\tif champion.IsValid() {\n\t\tb.WriteString(\"- Reigning champion: `\" + champion.String() +\n\t\t\t\"` (\" + strconv.Itoa(championWins) + \" wins)\\n\")\n\t} else {\n\t\tb.WriteString(\"- No champion yet -- be the first to win a duel.\\n\")\n\t}\n\n\tb.WriteString(\"\\n## How to play\\n\\n\")\n\tb.WriteString(\"1. `Challenge(opponentAddr, \\\"heads\\\"|\\\"tails\\\")` -- opens a duel, returns its ID.\\n\")\n\tb.WriteString(\"2. The opponent calls `Accept(id)` -- flips the coin and settles it on the spot.\\n\")\n\tb.WriteString(\"3. The challenger may `Cancel(id)` while it's still pending.\\n\\n\")\n\tb.WriteString(\"View a duel at this realm's path plus its ID (e.g. `.../coinflipduel:3`), \" +\n\t\t\"or a player's record plus their address (e.g. `.../coinflipduel:g1youraddress...`).\\n\\n\")\n\n\tb.WriteString(\"## Pending duels\\n\\n\")\n\tpending := 0\n\tduels.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\td := value.(*duel)\n\t\tif d.Status == statusPending {\n\t\t\tpending++\n\t\t\tb.WriteString(\"- #\" + d.ID + \": `\" + d.Challenger.String() + \"` called \" +\n\t\t\t\td.Call + \", waiting on `\" + d.Opponent.String() + \"`\\n\")\n\t\t}\n\t\treturn false\n\t})\n\tif pending == 0 {\n\t\tb.WriteString(\"_none right now_\\n\")\n\t}\n\n\treturn b.String()\n}\n\nfunc renderDuel(id string) string {\n\tv := duels.Get(id)\n\tif v == nil {\n\t\treturn \"# Duel #\" + ui.Inline(id) + \"\\n\\nNo such duel.\\n\"\n\t}\n\td := v.(*duel)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Duel #\" + d.ID + \"\\n\\n\")\n\tb.WriteString(\"- Challenger: `\" + d.Challenger.String() + \"` called **\" + d.Call + \"**\\n\")\n\tb.WriteString(\"- Opponent: `\" + d.Opponent.String() + \"`\\n\")\n\tb.WriteString(\"- Status: \" + d.Status.String() + \"\\n\")\n\n\tif d.Status == statusResolved {\n\t\tb.WriteString(\"- Coin landed on: **\" + d.Result + \"**\\n\")\n\t\tb.WriteString(\"- Winner: `\" + d.Winner.String() + \"`\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderPlayer(rawAddr string) string {\n\taddr := strings.TrimSpace(rawAddr)\n\tsafe := ui.Inline(addr)\n\n\tv := players.Get(addr)\n\tif v == nil {\n\t\treturn \"# Player \" + safe + \"\\n\\nNo recorded duels yet.\\n\"\n\t}\n\tps := v.(*playerState)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Player \" + safe + \"\\n\\n\")\n\tb.WriteString(\"- Wins: \" + strconv.Itoa(ps.Wins) + \"\\n\")\n\tb.WriteString(\"- Losses: \" + strconv.Itoa(ps.Losses) + \"\\n\")\n\tb.WriteString(\"- Duels played: \" + strconv.Itoa(ps.Duels) + \"\\n\")\n\treturn b.String()\n}\n\n// Render shows the duel arena at \"\", a specific duel when path is a numeric\n// ID, or one player's record when path is their bech32 address.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\tif _, err := strconv.Atoi(path); err == nil {\n\t\treturn renderDuel(path)\n\t}\n\treturn renderPlayer(path)\n}\n"},{"name":"coinflipduel_test.gno","body":"package coinflipduel\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tduels = avl.Tree{}\n\tplayers = avl.Tree{}\n\tnextID = 0\n\tflipNonce = 0\n\ttotalDone = 0\n\tvar zero address\n\tchampion = zero\n\tchampionWins = 0\n}\n\nfunc TestParseCall(t *testing.T) {\n\tfor _, s := range []string{\"heads\", \"Heads\", \" h \", \"tails\", \"T\"} {\n\t\tif _, ok := parseCall(s); !ok {\n\t\t\tt.Fatalf(\"parseCall(%q) should be valid\", s)\n\t\t}\n\t}\n\tif _, ok := parseCall(\"sideways\"); ok {\n\t\tt.Fatal(`parseCall(\"sideways\") should be invalid`)\n\t}\n}\n\n// Crossing: Challenge and Accept mutate realm state, so the test needs `cur realm`.\nfunc TestChallengeAndAccept(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tChallenge(cross(cur), bob.String(), \"heads\")\n\n\tif !duels.Has(\"1\") {\n\t\tt.Fatal(\"expected duel #1 to exist\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAccept(cross(cur), \"1\")\n\n\tv := duels.Get(\"1\")\n\td := v.(*duel)\n\tif d.Status != statusResolved {\n\t\tt.Fatalf(\"Status = %v, want resolved\", d.Status)\n\t}\n\tif d.Result != \"heads\" \u0026\u0026 d.Result != \"tails\" {\n\t\tt.Fatalf(\"Result = %q, want heads or tails\", d.Result)\n\t}\n\tif totalDone != 1 {\n\t\tt.Fatalf(\"totalDone = %d, want 1\", totalDone)\n\t}\n\n\twinnerStats := getOrCreate(d.Winner)\n\tif winnerStats.Wins != 1 {\n\t\tt.Fatalf(\"winner Wins = %d, want 1\", winnerStats.Wins)\n\t}\n\tif !champion.IsValid() || champion != d.Winner {\n\t\tt.Fatal(\"champion should be the duel winner\")\n\t}\n}\n\nfunc TestChallengeSelfRejected(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// Challenge panics inside a cross-realm call; a plain defer/recover in\n\t// this test does not catch a cross-boundary panic, so use revive().\n\trec := revive(func() { Challenge(cross(cur), alice.String(), \"heads\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when challenging yourself\")\n\t}\n}\n\nfunc TestOnlyOpponentCanAccept(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tmallory := testutils.TestAddress(\"mallory\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tChallenge(cross(cur), bob.String(), \"tails\")\n\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\trec := revive(func() { Accept(cross(cur), \"1\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when a non-opponent accepts\")\n\t}\n}\n\nfunc TestCancel(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tChallenge(cross(cur), bob.String(), \"heads\")\n\tCancel(cross(cur), \"1\")\n\n\tv := duels.Get(\"1\")\n\td := v.(*duel)\n\tif d.Status != statusCancelled {\n\t\tt.Fatalf(\"Status = %v, want cancelled\", d.Status)\n\t}\n}\n\n// Non-crossing: Render is a plain read.\nfunc TestRenderHome(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif out == \"\" {\n\t\tt.Fatal(`Render(\"\") should not be empty`)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/coinflipduel/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package coinflipduel\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Coin-Flip Duel\n\t//\n\t// Challenge another address to a coin flip. You call heads or tails up front; they accept and the block decides. No stakes -- just a record.\n\t//\n\t// - Total duels resolved: 0\n\t// - No champion yet -- be the first to win a duel.\n\t//\n\t// ## How to play\n\t//\n\t// 1. `Challenge(opponentAddr, \"heads\"|\"tails\")` -- opens a duel, returns its ID.\n\t// 2. The opponent calls `Accept(id)` -- flips the coin and settles it on the spot.\n\t// 3. The challenger may `Cancel(id)` while it's still pending.\n\t//\n\t// View a duel at this realm's path plus its ID (e.g. `.../coinflipduel:3`), or a player's record plus their address (e.g. `.../coinflipduel:g1youraddress...`).\n\t//\n\t// ## Pending duels\n\t//\n\t// _none right now_\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"53397200","gas_fee":"160191ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"tdlTS0n0yG4hn3bz5ttpvDSQcaH5gI+IlwZ4Es14LwQ1swBTJukrDsU03MdwcEHPfXkHI27NJLQhVn6wa5FJCA=="}],"memo":""},"metadata":{"timestamp":"1790960892"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"collatz","path":"gno.land/r/moul/x/daily/collatz/v1","files":[{"name":"README.md","body":"# Collatz Explorer\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA hailstone-sequence explorer realm. Call `Compute(n)` to walk the Collatz\nsequence for a positive integer `n` — the realm records its stopping time\n(number of steps to reach 1) and peak value, attributed to your address.\nThe root page shows a leaderboard of the longest sequences submitted, and\n`/\u003cn\u003e` renders the full hailstone sequence for any `n` on the fly.\n\nRealm path: `gno.land/r/moul/x/daily/collatz/v1`\n\n## Example calls\n\n```\n# record a run for n = 27 (111 steps, peak 9232)\ngnokey maketx call -pkgpath \"gno.land/r/moul/x/daily/collatz/v1\" \\\n  -func Compute -args 27 ...\n\n# view the leaderboard\ngnokey query vm/qrender --data \"gno.land/r/moul/x/daily/collatz/v1:\"\n\n# view the full hailstone sequence for 27\ngnokey query vm/qrender --data \"gno.land/r/moul/x/daily/collatz/v1:/27\"\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/collatz/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/collatz/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/collatz/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/collatz/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/collatz/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/collatz/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/collatz/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/collatz/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/collatz/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/collatz/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"collatz.gno","body":"package collatz\n\nimport (\n\t\"chain\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/collatz/v1\"\n\n// maxIters caps the Collatz walk so a hostile / huge input cannot loop\n// forever on-chain. No known n stays below this bound and fails to reach 1.\nconst maxIters = 1000000\n\n// MaxResults bounds the leaderboard's state: anyone may Compute, and each new\n// n is a new entry the root page sorts.\nconst MaxResults = 1000\n\n// maxSeqLen caps how many terms Render(\"/\u003cn\u003e\") will print.\nconst maxSeqLen = 500\n\n// Result is one recorded submission.\ntype Result struct {\n\tN     int64\n\tSteps int\n\tPeak  int64\n\tWho   address\n}\n\n// results maps a decimal-string key of N -\u003e Result. avl.Tree keeps a\n// deterministic order for iteration inside Render.\nvar results avl.Tree\n\n// maxOdd is the largest odd term whose successor 3n+1 still fits in an\n// int64. Past it the step wraps: 6148914691236517205 maps to exactly 2^64,\n// which is 0, and the walk then spins on 0 until maxIters.\nconst maxOdd = (1\u003c\u003c63 - 1 - 1) / 3\n\n// stopping returns the number of steps to reach 1 and the peak value seen,\n// walking the Collatz (hailstone) map. ok is false when a term would overflow\n// int64, in which case steps and peak describe the walk up to that term. It\n// never mutates state.\nfunc stopping(n int64) (steps int, peak int64, ok bool) {\n\tpeak = n\n\tcur := n\n\tfor cur != 1 {\n\t\tif steps \u003e= maxIters {\n\t\t\tbreak\n\t\t}\n\t\tif cur%2 == 0 {\n\t\t\tcur = cur / 2\n\t\t} else {\n\t\t\tif cur \u003e maxOdd {\n\t\t\t\treturn steps, peak, false\n\t\t\t}\n\t\t\tcur = 3*cur + 1\n\t\t}\n\t\tif cur \u003e peak {\n\t\t\tpeak = cur\n\t\t}\n\t\tsteps++\n\t}\n\treturn steps, peak, true\n}\n\n// Compute walks the hailstone sequence for n and records the result\n// attributed to the caller. It is a crossing (state-mutating) func.\nfunc Compute(cur realm, n int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"collatz: spoofed realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\tif n \u003c= 0 {\n\t\tpanic(\"n must be \u003e 0\")\n\t}\n\tnn := int64(n)\n\tsteps, peak, ok := stopping(nn)\n\tif !ok {\n\t\t// Recording it would put a wrapped walk on the leaderboard, forever.\n\t\tpanic(\"collatz: the walk from \" + strconv.FormatInt(nn, 10) + \" overflows int64\")\n\t}\n\n\tres := Result{N: nn, Steps: steps, Peak: peak, Who: caller}\n\tkey := strconv.FormatInt(nn, 10)\n\tif !results.Has(key) \u0026\u0026 results.Size() \u003e= MaxResults {\n\t\tpanic(\"collatz: the leaderboard is full at \" + strconv.Itoa(MaxResults) + \" entries\")\n\t}\n\tresults.Set(key, res)\n\n\tchain.Emit(\n\t\t\"Computed\",\n\t\t\"n\", key,\n\t\t\"steps\", strconv.Itoa(steps),\n\t\t\"peak\", strconv.FormatInt(peak, 10),\n\t\t\"who\", caller.String(),\n\t)\n}\n\n// byLongest implements sort.Interface, ordering results by steps desc,\n// then peak desc, then n asc for stability.\ntype byLongest []Result\n\nfunc (b byLongest) Len() int      { return len(b) }\nfunc (b byLongest) Swap(i, j int) { b[i], b[j] = b[j], b[i] }\nfunc (b byLongest) Less(i, j int) bool {\n\tif b[i].Steps != b[j].Steps {\n\t\treturn b[i].Steps \u003e b[j].Steps\n\t}\n\tif b[i].Peak != b[j].Peak {\n\t\treturn b[i].Peak \u003e b[j].Peak\n\t}\n\treturn b[i].N \u003c b[j].N\n}\n\n// Render shows the leaderboard at root, or the full hailstone sequence for a\n// given n at path \"/\u003cn\u003e\".\nfunc Render(path string) string {\n\tp := strings.TrimPrefix(path, \"/\")\n\tif p == \"\" {\n\t\treturn renderLeaderboard()\n\t}\n\treturn renderSequence(p)\n}\n\nfunc renderLeaderboard() string {\n\tall := make([]Result, 0, results.Size())\n\tresults.Iterate(\"\", \"\", func(_ string, v interface{}) bool {\n\t\tall = append(all, v.(Result))\n\t\treturn false\n\t})\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Collatz Explorer\\n\\n\")\n\tsb.WriteString(\"Hailstone-sequence explorer. Call `Compute(n)` to record a run, \")\n\tsb.WriteString(\"or view a full sequence at `/\u003cn\u003e`.\\n\\n\")\n\n\tif len(all) == 0 {\n\t\tsb.WriteString(\"_No sequences submitted yet._\\n\")\n\t\treturn sb.String()\n\t}\n\n\tsort.Stable(byLongest(all))\n\n\tsb.WriteString(\"## Leaderboard — longest sequences\\n\\n\")\n\tsb.WriteString(\"| # | n | steps | peak | who |\\n\")\n\tsb.WriteString(\"|---|---|-------|------|-----|\\n\")\n\tlimit := len(all)\n\tif limit \u003e 20 {\n\t\tlimit = 20\n\t}\n\tfor i := 0; i \u003c limit; i++ {\n\t\tr := all[i]\n\t\tsb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | \")\n\t\tsb.WriteString(\"[\" + strconv.FormatInt(r.N, 10) + \"](\" + selfPath + \":\" + strconv.FormatInt(r.N, 10) + \") | \")\n\t\tsb.WriteString(strconv.Itoa(r.Steps) + \" | \")\n\t\tsb.WriteString(strconv.FormatInt(r.Peak, 10) + \" | \")\n\t\tsb.WriteString(r.Who.String() + \" |\\n\")\n\t}\n\tsb.WriteString(\"\\n_\" + strconv.Itoa(len(all)) + \" sequence(s) recorded._\\n\")\n\treturn sb.String()\n}\n\nfunc renderSequence(p string) string {\n\tn, err := strconv.ParseInt(p, 10, 64)\n\tvar sb strings.Builder\n\tif err != nil || n \u003c= 0 {\n\t\tsb.WriteString(\"# Invalid n\\n\\n\" + md.InlineCode(p) + \" is not a positive integer.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tsb.WriteString(\"# Hailstone sequence for \" + strconv.FormatInt(n, 10) + \"\\n\\n\")\n\n\tseq := make([]int64, 0, 64)\n\tcur := n\n\tvar peak int64 = n\n\ttruncated := false\n\toverflow := false\n\tfor {\n\t\tseq = append(seq, cur)\n\t\tif cur == 1 {\n\t\t\tbreak\n\t\t}\n\t\tif len(seq) \u003e= maxSeqLen {\n\t\t\ttruncated = true\n\t\t\tbreak\n\t\t}\n\t\tif cur%2 == 0 {\n\t\t\tcur = cur / 2\n\t\t} else {\n\t\t\tif cur \u003e maxOdd {\n\t\t\t\toverflow = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcur = 3*cur + 1\n\t\t}\n\t\tif cur \u003e peak {\n\t\t\tpeak = cur\n\t\t}\n\t}\n\n\tparts := make([]string, len(seq))\n\tfor i, v := range seq {\n\t\tparts[i] = strconv.FormatInt(v, 10)\n\t}\n\tsb.WriteString(strings.Join(parts, \" → \"))\n\tsb.WriteString(\"\\n\\n\")\n\tsb.WriteString(\"- steps: \" + strconv.Itoa(len(seq)-1) + \"\\n\")\n\tsb.WriteString(\"- peak: \" + strconv.FormatInt(peak, 10) + \"\\n\")\n\tif overflow {\n\t\tsb.WriteString(\"\\n_Stopped: the next term would overflow int64._\\n\")\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"\\n_Sequence truncated at \" + strconv.Itoa(maxSeqLen) + \" terms._\\n\")\n\t}\n\treturn sb.String()\n}\n"},{"name":"collatz_test.gno","body":"package collatz\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestStopping(t *testing.T) {\n\tcases := []struct {\n\t\tn     int64\n\t\tsteps int\n\t\tpeak  int64\n\t}{\n\t\t{1, 0, 1},\n\t\t{2, 1, 2},\n\t\t{6, 8, 16},\n\t\t{7, 16, 52},\n\t\t{27, 111, 9232},\n\t}\n\tfor _, c := range cases {\n\t\tsteps, peak, _ := stopping(c.n)\n\t\tuassert.Equal(t, c.steps, steps)\n\t\tuassert.Equal(t, c.peak, peak)\n\t}\n}\n\nfunc TestComputeAndLeaderboard(cur realm, t *testing.T) {\n\taddr := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\n\tCompute(cross(cur), 27)\n\tCompute(cross(cur), 6)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Leaderboard\"), \"has leaderboard\")\n\tuassert.True(t, strings.Contains(out, \"9232\"), \"shows peak of 27\")\n\t// 27 has more steps than 6, so it must appear first (rank 1).\n\ti27 := strings.Index(out, \"[27]\")\n\ti6 := strings.Index(out, \"[6]\")\n\tuassert.True(t, i27 \u003e= 0 \u0026\u0026 i6 \u003e= 0, \"both rows present\")\n\tuassert.True(t, i27 \u003c i6, \"27 ranked above 6\")\n}\n\nfunc TestComputeRejectsNonPositive(cur realm, t *testing.T) {\n\taddr := testutils.TestAddress(\"bob\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\tuassert.AbortsWithMessage(t, cur, \"n must be \u003e 0\", func() {\n\t\tCompute(cross(cur), 0)\n\t})\n}\n\nfunc TestRenderSequence(t *testing.T) {\n\tout := Render(\"/6\")\n\tuassert.True(t, strings.Contains(out, \"6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1\"), \"full seq for 6\")\n\tuassert.True(t, strings.Contains(out, \"steps: 8\"), \"reports 8 steps\")\n\n\tbad := Render(\"/abc\")\n\tuassert.True(t, strings.Contains(bad, \"Invalid\"), \"rejects non-numeric path\")\n}\n\n// 3n+1 for this n is exactly 2^64, which wraps to 0. Recording it would put a\n// million-step walk on 0 at the top of the leaderboard, forever.\nfunc TestComputeRefusesAnOverflowingWalk(cur realm, t *testing.T) {\n\tuassert.AbortsContains(t, cur, \"overflows int64\", func() { Compute(cross(cur), 6148914691236517205) })\n\t_, _, ok := stopping(27)\n\tuassert.True(t, ok, \"an ordinary walk is unaffected\")\n\tout := Render(\"/6148914691236517205\")\n\tuassert.True(t, strings.Contains(out, \"would overflow int64\"), out)\n\tuassert.False(t, strings.Contains(out, \"→ 0\"), \"no wrapped term rendered\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/collatz/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"zz_bounds_test.gno","body":"package collatz\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Anyone may Compute, and each new n is an entry the root page sorts: the\n// leaderboard refuses a new n once it is full, and still updates an old one.\nfunc TestLeaderboardIsBounded(cur realm, t *testing.T) {\n\tvar added []string\n\tfor i := 1; results.Size() \u003c MaxResults; i++ {\n\t\tk := strconv.Itoa(1_000_000 + i)\n\t\tresults.Set(k, Result{N: int64(1_000_000 + i)})\n\t\tadded = append(added, k)\n\t}\n\t// One realm state per package run: leave the board as it was found.\n\tdefer func() {\n\t\tfor _, k := range added {\n\t\t\tresults.Remove(k)\n\t\t}\n\t}()\n\tuassert.AbortsContains(t, cur, \"leaderboard is full\", func() { Compute(cross(cur), 999_999_937) })\n\tCompute(cross(cur), 1_000_001) // an n already recorded is refreshed, not refused\n}\n"},{"name":"zz_escape_test.gno","body":"package collatz\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A path that is not a valid input is echoed back. It is the visitor's text,\n// so a backtick in it must not close a code span and let a link through.\nfunc TestInvalidPathIsEscaped(t *testing.T) {\n\tout := Render(\"/x` [claim](https://evil.example) `\")\n\t// Still there, but inside a span md.InlineCode widened past its backticks.\n\tuassert.True(t, strings.Contains(out, md.InlineCode(\"x` [claim](https://evil.example) `\")), out)\n}\n"},{"name":"zz_links_test.gno","body":"package collatz\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The leaderboard links each n to this realm's own sequence page. It once\n// linked to the malformed gno.land/r:\u003cn\u003e.\nfunc TestLeaderboardLinksNameThisRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"linker\")))\n\tCompute(cross(cur), 7)\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"](/r/moul/x/daily/collatz/v1:7)\"), out)\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"45051200","gas_fee":"135153ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"WKJgG89H0oAT80Bbq8OFlIE9t2czd1Pso5PMhINqcU4IgU1qCV1aroXTIV3YEzMi4ethix1ITA3+Q1DnHbwfSA=="}],"memo":""},"metadata":{"timestamp":"1790960893"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"commitrevealdemo","path":"gno.land/r/moul/x/daily/commitrevealdemo/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/commitrevealdemo/v0`\n\n**Live demo of [`p/moul/x/daily/commitreveal`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/commitreveal/v0).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/commitrevealdemo/v0`](https://gno.land/r/moul/x/daily/commitrevealdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/commitrevealdemo) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `short` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nVisible change: the commitment truncation is now ui.ShortN, which cannot panic on a short input.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/commitrevealdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/commitrevealdemo/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/commitrevealdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/commitrevealdemo/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/commitrevealdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/commitrevealdemo/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/commitrevealdemo/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/commitrevealdemo/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/commitrevealdemo/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/commitrevealdemo/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"commitrevealdemo.gno","body":"// Package commitrevealdemo is a small gnoweb demo of the commit-reveal scheme\n// provided by the [p/moul/x/daily/commitreveal](/p/moul/x/daily/commitreveal/v0)\n// library: the two phases, and what the salt is for.\n//\n// It contains no crypto of its own. Stateless, so Render is deterministic —\n// which is precisely what the library is for.\npackage commitrevealdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/daily/commitreveal/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Commit–Reveal\\n\\n\")\n\tb.WriteString(\"Bind to a choice without disclosing it, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/commitreveal`](/p/moul/x/daily/commitreveal/v0) library.\\n\\n\")\n\n\tb.WriteString(\"## The problem\\n\\n\")\n\tb.WriteString(\"A transaction is public before it executes. In a sealed-bid auction or \")\n\tb.WriteString(\"a simultaneous-move game, whoever moves last reads everyone else's \")\n\tb.WriteString(\"move and wins for free.\\n\\n\")\n\n\taliceSalt := \"alice-secret-salt-1\"\n\tbobSalt := \"bob-secret-salt-0001\"\n\taliceCommit := commitreveal.MustCommit(\"rock\", aliceSalt)\n\tbobCommit := commitreveal.MustCommit(\"paper\", bobSalt)\n\n\tb.WriteString(\"## Phase 1 — commit\\n\\n\")\n\tb.WriteString(\"Each player publishes only `H(value ‖ salt)`. Nothing about the move \")\n\tb.WriteString(\"leaks, but neither can change it later.\\n\\n\")\n\tb.WriteString(\"| player | commitment |\\n|---|---|\\n\")\n\tb.WriteString(\"| alice | `\" + ui.ShortN(aliceCommit, 16, 0) + \"` |\\n\")\n\tb.WriteString(\"| bob | `\" + ui.ShortN(bobCommit, 16, 0) + \"` |\\n\")\n\n\tb.WriteString(\"\\n## Phase 2 — reveal\\n\\n\")\n\tb.WriteString(\"Now the values and salts are published and checked against the \")\n\tb.WriteString(\"commitments recorded earlier:\\n\\n\")\n\tb.WriteString(\"| check | result |\\n|---|---|\\n\")\n\trow(\u0026b, \"alice opens with `rock`\", commitreveal.Open(aliceCommit, \"rock\", aliceSalt))\n\trow(\u0026b, \"bob opens with `paper`\", commitreveal.Open(bobCommit, \"paper\", bobSalt))\n\trow(\u0026b, \"bob tries `scissors` instead\", commitreveal.Open(bobCommit, \"scissors\", bobSalt))\n\trow(\u0026b, \"bob claims alice's commitment\", commitreveal.Open(aliceCommit, \"rock\", bobSalt))\n\n\tb.WriteString(\"\\nBob cannot switch his move after seeing Alice's, and cannot pass off \")\n\tb.WriteString(\"her commitment as his own.\\n\\n\")\n\n\tb.WriteString(\"## Why the salt is mandatory\\n\\n\")\n\tb.WriteString(\"Rock-paper-scissors has three possible moves. Without a salt there are \")\n\tb.WriteString(\"exactly three possible hashes, and hashing all three breaks the scheme \")\n\tb.WriteString(\"outright. The library refuses a salt shorter than `\")\n\tb.WriteString(itoa(commitreveal.MinSaltLen) + \"` bytes rather than leaving that as advice:\\n\\n\")\n\t_, err := commitreveal.Commit(\"rock\", \"tooshort\")\n\tb.WriteString(\"- `Commit(\\\"rock\\\", \\\"tooshort\\\")` → `\")\n\tif err != nil {\n\t\tb.WriteString(err.Error())\n\t}\n\tb.WriteString(\"`\\n\\n\")\n\tb.WriteString(\"The salt also keeps two players who pick the *same* move from \")\n\tb.WriteString(\"publishing the same commitment:\\n\\n\")\n\tone := commitreveal.MustCommit(\"rock\", \"salt-one-0123456789\")\n\ttwo := commitreveal.MustCommit(\"rock\", \"salt-two-0123456789\")\n\tb.WriteString(\"| same move, different salt | commitment |\\n|---|---|\\n\")\n\tb.WriteString(\"| player 1 | `\" + ui.ShortN(one, 16, 0) + \"` |\\n\")\n\tb.WriteString(\"| player 2 | `\" + ui.ShortN(two, 16, 0) + \"` |\\n\")\n\n\tb.WriteString(\"\\n## Two details that are easy to get wrong\\n\\n\")\n\tb.WriteString(\"- **Length-prefixed hashing.** With plain concatenation `(\\\"ab\\\",\\\"cd…\\\")` \")\n\tb.WriteString(\"and `(\\\"abc\\\",\\\"d…\\\")` hash identically, so one commitment could be opened \")\n\tb.WriteString(\"two different ways.\\n\")\n\tb.WriteString(\"- **Constant-time comparison.** A short-circuiting check leaks, through \")\n\tb.WriteString(\"timing, how many leading bytes of a guess were right — enough to rebuild \")\n\tb.WriteString(\"a commitment byte by byte.\\n\")\n\treturn b.String()\n}\n\nfunc row(b *strings.Builder, label string, err error) {\n\tb.WriteString(\"| \" + label + \" | \")\n\tif err == nil {\n\t\tb.WriteString(\"✅ accepted\")\n\t} else {\n\t\tb.WriteString(\"❌ `\" + err.Error() + \"`\")\n\t}\n\tb.WriteString(\" |\\n\")\n}\n\nfunc itoa(i int) string {\n\tif i == 0 {\n\t\treturn \"0\"\n\t}\n\ts := \"\"\n\tfor i \u003e 0 {\n\t\ts = string(rune('0'+i%10)) + s\n\t\ti /= 10\n\t}\n\treturn s\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/commitrevealdemo/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package commitrevealdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Commit–Reveal\n\t//\n\t// Bind to a choice without disclosing it, demoing the [`p/moul/x/daily/commitreveal`](/p/moul/x/daily/commitreveal/v0) library.\n\t//\n\t// ## The problem\n\t//\n\t// A transaction is public before it executes. In a sealed-bid auction or a simultaneous-move game, whoever moves last reads everyone else's move and wins for free.\n\t//\n\t// ## Phase 1 — commit\n\t//\n\t// Each player publishes only `H(value ‖ salt)`. Nothing about the move leaks, but neither can change it later.\n\t//\n\t// | player | commitment |\n\t// |---|---|\n\t// | alice | `11811a2d4eede29f…` |\n\t// | bob | `db066e8c917e07d5…` |\n\t//\n\t// ## Phase 2 — reveal\n\t//\n\t// Now the values and salts are published and checked against the commitments recorded earlier:\n\t//\n\t// | check | result |\n\t// |---|---|\n\t// | alice opens with `rock` | ✅ accepted |\n\t// | bob opens with `paper` | ✅ accepted |\n\t// | bob tries `scissors` instead | ❌ `commitreveal: reveal does not match the commitment` |\n\t// | bob claims alice's commitment | ❌ `commitreveal: reveal does not match the commitment` |\n\t//\n\t// Bob cannot switch his move after seeing Alice's, and cannot pass off her commitment as his own.\n\t//\n\t// ## Why the salt is mandatory\n\t//\n\t// Rock-paper-scissors has three possible moves. Without a salt there are exactly three possible hashes, and hashing all three breaks the scheme outright. The library refuses a salt shorter than `16` bytes rather than leaving that as advice:\n\t//\n\t// - `Commit(\"rock\", \"tooshort\")` → `commitreveal: salt is shorter than MinSaltLen`\n\t//\n\t// The salt also keeps two players who pick the *same* move from publishing the same commitment:\n\t//\n\t// | same move, different salt | commitment |\n\t// |---|---|\n\t// | player 1 | `a5d84fa94157acca…` |\n\t// | player 2 | `ccbc5d0b7ab1e84d…` |\n\t//\n\t// ## Two details that are easy to get wrong\n\t//\n\t// - **Length-prefixed hashing.** With plain concatenation `(\"ab\",\"cd…\")` and `(\"abc\",\"d…\")` hash identically, so one commitment could be opened two different ways.\n\t// - **Constant-time comparison.** A short-circuiting check leaks, through timing, how many leading bytes of a guess were right — enough to rebuild a commitment byte by byte.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"37485200","gas_fee":"112455ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"DoIb6qPekQK57O5Khx/Y6vjR/WtZSv5Huig2O6j4BfF1+QjiPAJSCRyyksrQbXJSazzXQWxC+dQlsEFOyh0mmA=="}],"memo":""},"metadata":{"timestamp":"1790960893"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"connect4","path":"gno.land/r/moul/x/daily/connect4/v1","files":[{"name":"README.md","body":"# Connect Four\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA two-player Connect Four realm on a 7-wide × 6-tall board. The game creator plays 🔴 and moves first; the named opponent plays 🟡. `Drop` enforces turn order by caller, rejects full and out-of-range columns, and detects a horizontal, vertical, or diagonal 4-in-a-row (or a draw). `Render` draws the board with 🔴🟡· and shows whose turn it is or who won.\n\nRealm path: `gno.land/r/moul/x/daily/connect4/v1`\n\n## Example calls\n\n```\n# create a game against another address (you are 🔴, returns the game id)\nNewGame(g1zabc...opponent)   # -\u003e 1\n\n# drop discs into columns 0-6 (turns alternate, enforced by caller)\nDrop(1, 3)   # 🔴 drops in column 3\nDrop(1, 3)   # 🟡 drops in column 3 (called from opponent's key)\n\n# view state\nrender:            # lists all games\nrender:1           # shows board for game 1\n```\n\n## What changed in v1\n\nTwo ports against [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/connect4), which stays live and untouched.\n\n### Rendering\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/connect4) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `short` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\n### Storage\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\n`v0` padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`Game` loses its `ID` field, which the store now owns, so `Drop` emits with the\n`gameID` it was already given and `renderGame` takes the id alongside the game.\n`Drop`'s trailing `games.Set(...)` is gone as well: it re-stored a pointer that\nwas already in the tree, and mutating through it persists on its own, which is\nhow the rest of this realm already worked.\n\nIds stay plain integers and the rendered output of the storage port is\nunchanged. Each port changes something `v0` promised, one the rendered output\nand one the storage layout, so under this repo's versioning rule each is a\ncompatibility change and neither could be an edit to `v0` in place.\n\nThey land in the **same** new version because `v1` was never published. A\nversion number is a tag on something that exists on a chain, and until it does\nthere is nothing for a second number to avoid disturbing, so the right move is\nto keep editing the version you have. `gnopm unbump` is what folded the second\nport back down into this one.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/connect4/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/connect4/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/connect4/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/connect4/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/connect4/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/connect4/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/connect4/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/connect4/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/connect4/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/connect4/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"connect4.gno","body":"package connect4\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/connect4/v1\"\n\nconst (\n\tcols = 7\n\trows = 6\n)\n\n// cell values\nconst (\n\tempty = 0\n\tred   = 1 // 🔴 game creator (caller of NewGame)\n\tyel   = 2 // 🟡 opponent\n)\n\n// Game holds the full state of one Connect Four match.\n// board is indexed board[row][col]; row 0 is the BOTTOM row.\n// It carries no ID field: the id belongs to the store, which hands it back on\n// lookup and iteration.\ntype Game struct {\n\tRed      address // 🔴 creator, moves first\n\tYellow   address // 🟡 opponent\n\tBoard    [rows][cols]int\n\tTurn     int  // whose turn: red or yel\n\tWinner   int  // empty until decided; red/yel = winner\n\tDraw     bool // true when board full with no winner\n\tFinished bool\n}\n\n// games assigns the game ids. v1 kept its own nextID plus an idKey() that\n// zero-padded to width 12, which stopped ordering the Render list past 10^12.\nvar games = store.Named(\"game\")\n\n// NewGame creates a match between the caller (🔴) and opponent (🟡).\n// Returns the new game id.\nfunc NewGame(cur realm, opponent address) int64 {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"connect4: spoofed realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\tif opponent == caller {\n\t\tpanic(\"opponent must differ from caller\")\n\t}\n\tif opponent.String() == \"\" {\n\t\tpanic(\"opponent address is empty\")\n\t}\n\tid := games.Add(\u0026Game{\n\t\tRed:    caller,\n\t\tYellow: opponent,\n\t\tTurn:   red,\n\t})\n\tchain.Emit(\"GameCreated\",\n\t\t\"id\", id.String(),\n\t\t\"red\", caller.String(),\n\t\t\"yellow\", opponent.String(),\n\t)\n\treturn int64(id)\n}\n\nfunc getGame(id int64) (*Game, error) {\n\tv, ok := games.Get(store.ID(id))\n\tif !ok {\n\t\treturn nil, errors.New(\"game not found: \" + strconv.FormatInt(id, 10))\n\t}\n\treturn v.(*Game), nil\n}\n\n// Drop places the caller's disc into the given column (0-6).\n// Enforces turn order by caller, rejects full columns, and detects\n// a 4-in-a-row win or a draw.\nfunc Drop(cur realm, gameID int64, column int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"connect4: spoofed realm\")\n\t}\n\tif column \u003c 0 || column \u003e= cols {\n\t\tpanic(\"column out of range (0-6)\")\n\t}\n\tg, err := getGame(gameID)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tif g.Finished {\n\t\tpanic(\"game already finished\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\tvar mover int\n\tswitch caller {\n\tcase g.Red:\n\t\tmover = red\n\tcase g.Yellow:\n\t\tmover = yel\n\tdefault:\n\t\tpanic(\"caller is not a player in this game\")\n\t}\n\tif mover != g.Turn {\n\t\tpanic(\"not your turn\")\n\t}\n\n\t// find lowest empty row in the column\n\tplaced := -1\n\tfor r := 0; r \u003c rows; r++ {\n\t\tif g.Board[r][column] == empty {\n\t\t\tg.Board[r][column] = mover\n\t\t\tplaced = r\n\t\t\tbreak\n\t\t}\n\t}\n\tif placed == -1 {\n\t\tpanic(\"column is full\")\n\t}\n\n\tif wins(\u0026g.Board, placed, column, mover) {\n\t\tg.Winner = mover\n\t\tg.Finished = true\n\t\tchain.Emit(\"GameWon\",\n\t\t\t\"id\", strconv.FormatInt(gameID, 10),\n\t\t\t\"winner\", caller.String(),\n\t\t)\n\t} else if full(\u0026g.Board) {\n\t\tg.Draw = true\n\t\tg.Finished = true\n\t\tchain.Emit(\"GameDraw\", \"id\", strconv.FormatInt(gameID, 10))\n\t} else {\n\t\tif g.Turn == red {\n\t\t\tg.Turn = yel\n\t\t} else {\n\t\t\tg.Turn = red\n\t\t}\n\t\tchain.Emit(\"DiscDropped\",\n\t\t\t\"id\", strconv.FormatInt(gameID, 10),\n\t\t\t\"col\", strconv.Itoa(column),\n\t\t\t\"player\", caller.String(),\n\t\t)\n\t}\n\n}\n\nfunc full(b *[rows][cols]int) bool {\n\tfor c := 0; c \u003c cols; c++ {\n\t\tif b[rows-1][c] == empty {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// wins checks whether the disc just placed at (r,c) for player p completes\n// a run of 4 in any of the four directions.\nfunc wins(b *[rows][cols]int, r, c, p int) bool {\n\t// direction pairs: horizontal, vertical, diag /, diag \\\n\tdirs := [4][2]int{{0, 1}, {1, 0}, {1, 1}, {1, -1}}\n\tfor _, d := range dirs {\n\t\tcount := 1\n\t\tcount += run(b, r, c, d[0], d[1], p)\n\t\tcount += run(b, r, c, -d[0], -d[1], p)\n\t\tif count \u003e= 4 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc run(b *[rows][cols]int, r, c, dr, dc, p int) int {\n\tn := 0\n\tfor i := 1; i \u003c 4; i++ {\n\t\trr := r + dr*i\n\t\tcc := c + dc*i\n\t\tif rr \u003c 0 || rr \u003e= rows || cc \u003c 0 || cc \u003e= cols {\n\t\t\tbreak\n\t\t}\n\t\tif b[rr][cc] != p {\n\t\t\tbreak\n\t\t}\n\t\tn++\n\t}\n\treturn n\n}\n\nfunc glyph(v int) string {\n\tswitch v {\n\tcase red:\n\t\treturn \"🔴\"\n\tcase yel:\n\t\treturn \"🟡\"\n\tdefault:\n\t\treturn \"·\"\n\t}\n}\n\n// Render draws the board with 🔴🟡· and shows whose turn / the winner.\n// path \"\" lists all games; path \"\u003cid\u003e\" shows a single board.\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(strings.Trim(path, \"/\"))\n\tif path == \"\" {\n\t\treturn renderList()\n\t}\n\tid, ok := store.ParseID(path)\n\tif !ok {\n\t\treturn \"# Connect Four\\n\\nInvalid game id: \" + md.InlineCode(path) + \"\\n\"\n\t}\n\tg, err := getGame(int64(id))\n\tif err != nil {\n\t\treturn \"# Connect Four\\n\\n\" + err.Error() + \"\\n\"\n\t}\n\treturn renderGame(id, g)\n}\n\nfunc renderList() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Connect Four\\n\\n\")\n\tsb.WriteString(\"Two-player Connect Four on a 7×6 board. 🔴 is the game creator, 🟡 the opponent.\\n\\n\")\n\tif games.Len() == 0 {\n\t\tsb.WriteString(\"_No games yet. Call `NewGame(opponent)` to start one._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"## Games\\n\\n\")\n\tsb.WriteString(\"| ID | 🔴 Red | 🟡 Yellow | Status |\\n\")\n\tsb.WriteString(\"|----|--------|-----------|--------|\\n\")\n\tgames.Each(func(id store.ID, v any) {\n\t\tg := v.(*Game)\n\t\tstatus := \"\"\n\t\tswitch {\n\t\tcase g.Winner == red:\n\t\t\tstatus = \"🔴 won\"\n\t\tcase g.Winner == yel:\n\t\t\tstatus = \"🟡 won\"\n\t\tcase g.Draw:\n\t\t\tstatus = \"draw\"\n\t\tcase g.Turn == red:\n\t\t\tstatus = \"🔴 to move\"\n\t\tdefault:\n\t\t\tstatus = \"🟡 to move\"\n\t\t}\n\t\tsb.WriteString(\"| [\" + id.String() + \"](\" + selfPath + \":\" + id.String() + \") | \" +\n\t\t\tui.Addr(g.Red) + \" | \" + ui.Addr(g.Yellow) + \" | \" + status + \" |\\n\")\n\t})\n\tsb.WriteString(\"\\nOpen a game by its id (e.g. path `1`).\\n\")\n\treturn sb.String()\n}\n\nfunc renderGame(id store.ID, g *Game) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Connect Four — Game \" + id.String() + \"\\n\\n\")\n\tsb.WriteString(\"- 🔴 Red: `\" + g.Red.String() + \"`\\n\")\n\tsb.WriteString(\"- 🟡 Yellow: `\" + g.Yellow.String() + \"`\\n\\n\")\n\n\t// status line\n\tswitch {\n\tcase g.Winner == red:\n\t\tsb.WriteString(\"**🔴 Red wins!**\\n\\n\")\n\tcase g.Winner == yel:\n\t\tsb.WriteString(\"**🟡 Yellow wins!**\\n\\n\")\n\tcase g.Draw:\n\t\tsb.WriteString(\"**Draw — board full.**\\n\\n\")\n\tcase g.Turn == red:\n\t\tsb.WriteString(\"**Turn: 🔴 Red**\\n\\n\")\n\tdefault:\n\t\tsb.WriteString(\"**Turn: 🟡 Yellow**\\n\\n\")\n\t}\n\n\t// board top-down (row rows-1 at top, row 0 at bottom)\n\tsb.WriteString(\"```\\n\")\n\tfor r := rows - 1; r \u003e= 0; r-- {\n\t\tfor c := 0; c \u003c cols; c++ {\n\t\t\tsb.WriteString(glyph(g.Board[r][c]))\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\t// column indices\n\tfor c := 0; c \u003c cols; c++ {\n\t\tsb.WriteString(strconv.Itoa(c))\n\t}\n\tsb.WriteString(\"\\n```\\n\\n\")\n\n\tif !g.Finished {\n\t\tsb.WriteString(\"Drop a disc: `Drop(\" + id.String() + \", \u003ccol 0-6\u003e)`\\n\")\n\t}\n\treturn sb.String()\n}\n"},{"name":"connect4_test.gno","body":"package connect4\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\") // 🔴\n\tbob   = testutils.TestAddress(\"bob\")   // 🟡\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\nfunc resetState() {\n\tgames = store.Named(\"game\")\n}\n\n// TestVerticalWin plays 🔴 stacking column 0 four high while 🟡 plays column 1.\nfunc TestVerticalWin(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\tuassert.Equal(t, int64(1), id)\n\n\tfor i := 0; i \u003c 3; i++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\tDrop(cross(cur), id,0)\n\t\ttesting.SetRealm(testing.NewUserRealm(bob))\n\t\tDrop(cross(cur), id,1)\n\t}\n\t// alice's 4th disc in column 0 -\u003e vertical win\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tDrop(cross(cur), id,0)\n\n\tg, err := getGame(id)\n\tuassert.NoError(t, err)\n\tuassert.True(t, g.Finished)\n\tuassert.Equal(t, red, g.Winner)\n\n\tout := Render(\"1\")\n\tuassert.True(t, strings.Contains(out, \"🔴 Red wins!\"))\n}\n\n// TestTurnOrderAndErrors covers turn enforcement, non-player, full-column and range checks.\nfunc TestTurnOrderAndErrors(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\n\t// bob cannot move first (red starts)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur,\"not your turn\", func() {\n\t\tDrop(cross(cur), id,0)\n\t})\n\n\t// stranger cannot play\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsWithMessage(t, cur,\"caller is not a player in this game\", func() {\n\t\tDrop(cross(cur), id,0)\n\t})\n\n\t// out-of-range column\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur,\"column out of range (0-6)\", func() {\n\t\tDrop(cross(cur), id,7)\n\t})\n\n\t// fill column 3: alice \u0026 bob alternate, 6 discs total\n\tcol := 3\n\tfor i := 0; i \u003c 3; i++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\tDrop(cross(cur), id,col)\n\t\ttesting.SetRealm(testing.NewUserRealm(bob))\n\t\tDrop(cross(cur), id,col)\n\t}\n\t// column now full; whoever is on turn overflows it\n\tg, _ := getGame(id)\n\tvar mover address\n\tif g.Turn == red {\n\t\tmover = alice\n\t} else {\n\t\tmover = bob\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(mover))\n\tuassert.AbortsWithMessage(t, cur,\"column is full\", func() {\n\t\tDrop(cross(cur), id,col)\n\t})\n}\n\n// TestHorizontalWin: 🔴 across columns 0-3 on the bottom row.\nfunc TestHorizontalWin(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\n\t// alice drops cols 0,1,2 ; bob answers on row above (col 0,1,2)\n\tfor c := 0; c \u003c 3; c++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\tDrop(cross(cur), id,c)\n\t\ttesting.SetRealm(testing.NewUserRealm(bob))\n\t\tDrop(cross(cur), id,c)\n\t}\n\t// alice completes col 3 on bottom row -\u003e 0,1,2,3 horizontal\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tDrop(cross(cur), id,3)\n\n\tg, err := getGame(id)\n\tuassert.NoError(t, err)\n\tuassert.True(t, g.Finished)\n\tuassert.Equal(t, red, g.Winner)\n}\n\n// TestRenderList checks the listing view renders created games.\nfunc TestRenderList(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tNewGame(cross(cur), bob)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Connect Four\"))\n\tuassert.True(t, strings.Contains(out, \"to move\"))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/connect4/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"zz_escape_test.gno","body":"package connect4\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A path that is not a valid input is echoed back. It is the visitor's text,\n// so a backtick in it must not close a code span and let a link through.\nfunc TestInvalidPathIsEscaped(t *testing.T) {\n\tout := Render(\"x` [claim](https://evil.example) `\")\n\t// Still there, but inside a span md.InlineCode widened past its backticks.\n\tuassert.True(t, strings.Contains(out, md.InlineCode(\"x` [claim](https://evil.example) `\")), out)\n}\n"},{"name":"zz_links_test.gno","body":"package connect4\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The game list links each game to this realm's own page. It once linked\n// to the malformed gno.land/r:\u003cid\u003e.\nfunc TestListLinksNameThisRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"red\")))\n\tid := NewGame(cross(cur), testutils.TestAddress(\"yellow\"))\n\tout := Render(\"\")\n\ts := \"\"\n\tfor n := id; n \u003e 0; n /= 10 {\n\t\ts = string(rune(byte(n%10)+byte(48))) + s\n\t}\n\tuassert.True(t, strings.Contains(out, \"](/r/moul/x/daily/connect4/v1:\"+s+\")\"), out)\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"55396600","gas_fee":"166189ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"mF2LoyRUvBQkhejRmHCBzb70lRZIc+mrnBq1EsdZuJ0FYvL+l7UAQXbZXyWB+96rTUG0Fwa13eVs1RZIYIt7WA=="}],"memo":""},"metadata":{"timestamp":"1790960894"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"YKtjK/PrZlbinHUwKgN/tO1VWV+YM+D6dBP8/sIsiGt7lkc3KnNFeFezga5iCGFj6WjD8RQUtKyNOPuK951Aqw=="}],"memo":""},"metadata":{"timestamp":"1790960894"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"counter","path":"gno.land/r/moul/x/daily/counter/v0","files":[{"name":"README.md","body":"# Counter Club\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA single shared integer counter that anyone on the chain can nudge. Every call\nto `Inc`, `Dec`, or `Reset` mutates the global value and appends a record to a\nrolling log of the last 20 changes (caller address, delta, new value, block\nheight). The realm's `Render` shows the current value big, the total number of\nchanges ever made, and a table of the recent history.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/counter`\n\n## Example calls\n\n```sh\n# Increment the shared counter\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/counter\" \\\n  -func Inc -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 KEY\n\n# Decrement it\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/counter\" \\\n  -func Dec -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 KEY\n\n# Reset back to zero\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/counter\" \\\n  -func Reset -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 KEY\n```\n\nView the current value and history by rendering the realm in a gno.land\nexplorer or with `gnokey query vm/qrender --data \"gno.land/r/REPLACE_ADDR/counter:\"`.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/counter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/counter/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/counter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/counter/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/counter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/counter/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/counter/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/counter/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"counter.gno","body":"// Package counter implements \"Counter Club\": a single shared integer counter\n// with a rolling history of the last 20 mutations. Anyone may Inc, Dec, or\n// Reset the value; every change records the caller, the delta applied, the\n// resulting value, and the block height it happened at.\npackage counter\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// maxHistory is the number of recent changes kept in the log.\nconst maxHistory = 20\n\n// change is a single recorded mutation of the counter.\ntype change struct {\n\tcaller address // who triggered the change\n\tdelta  int     // how much the value moved (+1, -1, or reset amount)\n\tvalue  int     // the resulting counter value after the change\n\theight int64   // block height at which it occurred\n}\n\n// value is the current shared counter.\nvar value int\n\n// total counts every mutation ever applied (not capped, unlike history).\nvar total int\n\n// history holds the last maxHistory changes, oldest first.\nvar history []change\n\n// record appends a change to the history, trimming to the last maxHistory.\nfunc record(delta, newValue int) {\n\tc := change{\n\t\tcaller: unsafe.PreviousRealm().Address(),\n\t\tdelta:  delta,\n\t\tvalue:  newValue,\n\t\theight: runtime.ChainHeight(),\n\t}\n\thistory = append(history, c)\n\tif len(history) \u003e maxHistory {\n\t\thistory = history[len(history)-maxHistory:]\n\t}\n\ttotal++\n\tchain.Emit(\n\t\t\"CounterChange\",\n\t\t\"delta\", strconv.Itoa(delta),\n\t\t\"value\", strconv.Itoa(newValue),\n\t)\n}\n\n// Inc adds one to the shared counter and logs the change.\nfunc Inc(cur realm) int {\n\tvalue++\n\trecord(1, value)\n\treturn value\n}\n\n// Dec subtracts one from the shared counter and logs the change.\nfunc Dec(cur realm) int {\n\tvalue--\n\trecord(-1, value)\n\treturn value\n}\n\n// Reset sets the shared counter back to zero and logs the change. The recorded\n// delta is the amount required to bring the previous value to zero.\nfunc Reset(cur realm) int {\n\tdelta := -value\n\tvalue = 0\n\trecord(delta, value)\n\treturn value\n}\n\n// Value returns the current counter value (read-only helper).\nfunc Value() int {\n\treturn value\n}\n\n// Total returns the total number of mutations ever applied.\nfunc Total() int {\n\treturn total\n}\n\n// Render produces a Markdown view: the big current value, the total number of\n// changes, and a table of the most recent changes (newest first).\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Counter Club\\n\\n\")\n\tb.WriteString(\"A shared counter anyone can Inc, Dec, or Reset. \")\n\tb.WriteString(\"The last \")\n\tb.WriteString(strconv.Itoa(maxHistory))\n\tb.WriteString(\" changes are logged below.\\n\\n\")\n\n\t// Big current value.\n\tb.WriteString(\"## Current value\\n\\n\")\n\tb.WriteString(\"# \")\n\tb.WriteString(strconv.Itoa(value))\n\tb.WriteString(\"\\n\\n\")\n\n\tb.WriteString(\"**Total changes:** \")\n\tb.WriteString(strconv.Itoa(total))\n\tb.WriteString(\"\\n\\n\")\n\n\t// Recent history, newest first.\n\tb.WriteString(\"## Recent history\\n\\n\")\n\tif len(history) == 0 {\n\t\tb.WriteString(\"_No changes yet — be the first to count!_\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| # | Caller | Delta | New value | Height |\\n\")\n\tb.WriteString(\"|---|--------|-------|-----------|--------|\\n\")\n\tn := len(history)\n\tfor i := n - 1; i \u003e= 0; i-- {\n\t\tc := history[i]\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(strconv.Itoa(n - i))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(c.caller.String())\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(signed(c.delta))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.Itoa(c.value))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.FormatInt(c.height, 10))\n\t\tb.WriteString(\" |\\n\")\n\t}\n\n\treturn b.String()\n}\n\n// signed formats an int with an explicit leading sign for non-negative values.\nfunc signed(n int) string {\n\tif n \u003e= 0 {\n\t\treturn \"+\" + strconv.Itoa(n)\n\t}\n\treturn strconv.Itoa(n)\n}\n"},{"name":"counter_test.gno","body":"package counter\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestIncDecReset drives the full mutation lifecycle across two callers and\n// checks value, total count, and history accounting.\nfunc TestIncDecReset(cur realm, t *testing.T) {\n\t// reset package-level state for a clean run\n\tvalue = 0\n\ttotal = 0\n\thistory = nil\n\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.Equal(t, 1, Inc(cross(cur)))\n\tuassert.Equal(t, 2, Inc(cross(cur)))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.Equal(t, 1, Dec(cross(cur)))\n\n\tuassert.Equal(t, 1, Value())\n\tuassert.Equal(t, 3, Total())\n\tuassert.Equal(t, 3, len(history))\n\n\t// Reset should bring the value to zero with a delta of -1.\n\tuassert.Equal(t, 0, Reset(cross(cur)))\n\tuassert.Equal(t, 0, Value())\n\tuassert.Equal(t, 4, Total())\n\n\tlast := history[len(history)-1]\n\tuassert.Equal(t, -1, last.delta)\n\tuassert.Equal(t, 0, last.value)\n\tuassert.Equal(t, bob.String(), last.caller.String())\n}\n\n// TestHistoryCapAndRender checks the rolling 20-entry cap and that Render\n// reflects the current value and total.\nfunc TestHistoryCapAndRender(cur realm, t *testing.T) {\n\tvalue = 0\n\ttotal = 0\n\thistory = nil\n\n\tcaller := testutils.TestAddress(\"counter\")\n\ttesting.SetRealm(testing.NewUserRealm(caller))\n\n\t// Apply 25 increments; history must cap at maxHistory (20), total = 25.\n\tfor i := 0; i \u003c 25; i++ {\n\t\tInc(cross(cur))\n\t}\n\n\tuassert.Equal(t, 25, Value())\n\tuassert.Equal(t, 25, Total())\n\tuassert.Equal(t, maxHistory, len(history))\n\n\t// Oldest surviving entry should have value 6 (changes 1..5 dropped).\n\tuassert.Equal(t, 6, history[0].value)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"# 25\"), \"render shows current value\")\n\tuassert.True(t, strings.Contains(out, \"Total changes:\"), \"render shows total\")\n\tuassert.True(t, strings.Contains(out, \"| +1 |\"), \"render shows a delta cell\")\n}\n\n// TestRenderEmpty verifies the empty-state message before any mutations.\nfunc TestRenderEmpty(t *testing.T) {\n\tvalue = 0\n\ttotal = 0\n\thistory = nil\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"No changes yet\"), \"shows empty state\")\n\tuassert.True(t, strings.Contains(out, \"# 0\"), \"shows zero value\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/counter/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package counter\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Counter Club\n\t//\n\t// A shared counter anyone can Inc, Dec, or Reset. The last 20 changes are logged below.\n\t//\n\t// ## Current value\n\t//\n\t// # 0\n\t//\n\t// **Total changes:** 0\n\t//\n\t// ## Recent history\n\t//\n\t// _No changes yet — be the first to count!_\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"36375000","gas_fee":"109125ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"KmpndSe0TS93lhZJs/Cpmlo7Dkfr8sa6xJliE+lWFH9JJ9UX1Gc8cb08JG5RBLlsxnjfQcspp6LrMFel1gZrgw=="}],"memo":""},"metadata":{"timestamp":"1790960949"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"countminsketchdemo","path":"gno.land/r/moul/x/daily/countminsketchdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/countminsketchdemo/v0`\n\n**Live demo of [`p/moul/x/daily/countminsketch`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/countminsketch).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/countminsketchdemo/v0`](https://gno.land/r/moul/x/daily/countminsketchdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/countminsketchdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/countminsketchdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/countminsketchdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/countminsketchdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/countminsketchdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/countminsketchdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/countminsketchdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/countminsketchdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/countminsketchdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/countminsketchdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"countminsketchdemo.gno","body":"// Package countminsketchdemo is a small gnoweb demo of the frequency sketch\n// provided by the\n// [p/moul/x/daily/countminsketch](/p/moul/x/daily/countminsketch/v0) library:\n// fixed storage, one-sided error, and what a collision looks like.\n//\n// It contains no sketch logic of its own. Stateless, so Render is\n// deterministic — which is precisely what the library is for.\npackage countminsketchdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/countminsketch/v0\"\n)\n\n// stream is the workload: a few heavy hitters and a long tail.\nvar stream = buildStream()\n\nfunc buildStream() []string {\n\tvar out []string\n\tfor i := 0; i \u003c 40; i++ {\n\t\tout = append(out, \"alice\")\n\t}\n\tfor i := 0; i \u003c 25; i++ {\n\t\tout = append(out, \"bob\")\n\t}\n\tfor i := 0; i \u003c 10; i++ {\n\t\tout = append(out, \"carol\")\n\t}\n\tfor i := 0; i \u003c 120; i++ { // the tail: 120 distinct one-offs\n\t\tout = append(out, \"user\"+strconv.Itoa(i))\n\t}\n\treturn out\n}\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Count–Min Sketch\\n\\n\")\n\tb.WriteString(\"Frequency estimates in fixed space, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/countminsketch`](/p/moul/x/daily/countminsketch/v0) library.\\n\\n\")\n\n\tb.WriteString(\"## The workload\\n\\n\")\n\tb.WriteString(\"`\" + strconv.Itoa(len(stream)) + \"` events over `123` distinct keys: \")\n\tb.WriteString(\"three heavy hitters and a long tail of one-offs.\\n\\n\")\n\n\tbig, _ := countminsketch.New(1024, 4)\n\tfill(big)\n\n\tb.WriteString(\"## A generously sized sketch (1024 × 4)\\n\\n\")\n\tb.WriteString(\"| key | true | estimate |\\n|---|---|---|\\n\")\n\tfor _, k := range []string{\"alice\", \"bob\", \"carol\", \"user0\", \"never-seen\"} {\n\t\tb.WriteString(\"| `\" + k + \"` | \" + strconv.Itoa(trueCount(k)) + \" | \" +\n\t\t\tstrconv.FormatInt(big.Estimate(k), 10) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\nExact here, and `never-seen` reads `0` — a **zero estimate is \")\n\tb.WriteString(\"definitive**: that key was never added.\\n\\n\")\n\n\ttiny, _ := countminsketch.New(8, 2)\n\tfill(tiny)\n\n\tb.WriteString(\"## A deliberately tiny one (8 × 2)\\n\\n\")\n\tb.WriteString(\"Only `\" + strconv.Itoa(tiny.Counters()) + \"` counters for `123` distinct \")\n\tb.WriteString(\"keys, so collisions are guaranteed:\\n\\n\")\n\tb.WriteString(\"| key | true | estimate | error |\\n|---|---|---|---|\\n\")\n\tfor _, k := range []string{\"alice\", \"bob\", \"carol\", \"user0\"} {\n\t\test := tiny.Estimate(k)\n\t\tb.WriteString(\"| `\" + k + \"` | \" + strconv.Itoa(trueCount(k)) + \" | \" +\n\t\t\tstrconv.FormatInt(est, 10) + \" | +\" +\n\t\t\tstrconv.FormatInt(est-int64(trueCount(k)), 10) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\nEvery error is **positive**. That is the guarantee: the sketch may \")\n\tb.WriteString(\"overcount, never undercount, so an estimate is an upper bound — \")\n\tb.WriteString(\"\\\"at most this often\\\", never \\\"exactly this often\\\".\\n\\n\")\n\n\tb.WriteString(\"## Where the collisions are\\n\\n\")\n\tb.WriteString(\"Row 0 of the tiny sketch, and the column each key lands in:\\n\\n\")\n\tb.WriteString(\"| column | counter |\\n|---|---|\\n\")\n\tfor c, v := range tiny.Row(0) {\n\t\twho := []string{}\n\t\tfor _, k := range []string{\"alice\", \"bob\", \"carol\"} {\n\t\t\tif tiny.Index(k, 0) == c {\n\t\t\t\twho = append(who, \"`\"+k+\"`\")\n\t\t\t}\n\t\t}\n\t\tline := \"| \" + strconv.Itoa(c) + \" | \" + strconv.FormatInt(v, 10)\n\t\tif len(who) \u003e 0 {\n\t\t\tline += \" ← \" + strings.Join(who, \", \")\n\t\t}\n\t\tb.WriteString(line + \" |\\n\")\n\t}\n\tb.WriteString(\"\\nTaking the **minimum** across rows is what limits the damage: an \")\n\tb.WriteString(\"overestimate needs a collision in *every* row at once.\\n\\n\")\n\n\tb.WriteString(\"## Why bother\\n\\n\")\n\tb.WriteString(\"| | exact map | sketch (1024 × 4) |\\n|---|---|---|\\n\")\n\tb.WriteString(\"| storage | one entry per distinct key, unbounded | \")\n\tb.WriteString(strconv.Itoa(big.Counters()) + \" counters, fixed |\\n\")\n\tb.WriteString(\"| answer | exact | upper bound |\\n\")\n\tb.WriteString(\"\\nOn chain the second row is the point: storage driven by user input \")\n\tb.WriteString(\"is a liability, and a sketch sized once cannot be made to grow.\\n\")\n\treturn b.String()\n}\n\nfunc fill(s *countminsketch.Sketch) {\n\tfor _, e := range stream {\n\t\ts.Add(e)\n\t}\n}\n\nfunc trueCount(k string) int {\n\tn := 0\n\tfor _, e := range stream {\n\t\tif e == k {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/countminsketchdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package countminsketchdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Count–Min Sketch\n\t//\n\t// Frequency estimates in fixed space, demoing the [`p/moul/x/daily/countminsketch`](/p/moul/x/daily/countminsketch/v0) library.\n\t//\n\t// ## The workload\n\t//\n\t// `195` events over `123` distinct keys: three heavy hitters and a long tail of one-offs.\n\t//\n\t// ## A generously sized sketch (1024 × 4)\n\t//\n\t// | key | true | estimate |\n\t// |---|---|---|\n\t// | `alice` | 40 | 40 |\n\t// | `bob` | 25 | 25 |\n\t// | `carol` | 10 | 10 |\n\t// | `user0` | 1 | 1 |\n\t// | `never-seen` | 0 | 0 |\n\t//\n\t// Exact here, and `never-seen` reads `0` — a **zero estimate is definitive**: that key was never added.\n\t//\n\t// ## A deliberately tiny one (8 × 2)\n\t//\n\t// Only `16` counters for `123` distinct keys, so collisions are guaranteed:\n\t//\n\t// | key | true | estimate | error |\n\t// |---|---|---|---|\n\t// | `alice` | 40 | 54 | +14 |\n\t// | `bob` | 25 | 39 | +14 |\n\t// | `carol` | 10 | 24 | +14 |\n\t// | `user0` | 1 | 16 | +15 |\n\t//\n\t// Every error is **positive**. That is the guarantee: the sketch may overcount, never undercount, so an estimate is an upper bound — \"at most this often\", never \"exactly this often\".\n\t//\n\t// ## Where the collisions are\n\t//\n\t// Row 0 of the tiny sketch, and the column each key lands in:\n\t//\n\t// | column | counter |\n\t// |---|---|\n\t// | 0 | 15 |\n\t// | 1 | 25 ← `carol` |\n\t// | 2 | 16 |\n\t// | 3 | 15 |\n\t// | 4 | 54 ← `alice` |\n\t// | 5 | 16 |\n\t// | 6 | 15 |\n\t// | 7 | 39 ← `bob` |\n\t//\n\t// Taking the **minimum** across rows is what limits the damage: an overestimate needs a collision in *every* row at once.\n\t//\n\t// ## Why bother\n\t//\n\t// | | exact map | sketch (1024 × 4) |\n\t// |---|---|---|\n\t// | storage | one entry per distinct key, unbounded | 4096 counters, fixed |\n\t// | answer | exact | upper bound |\n\t//\n\t// On chain the second row is the point: storage driven by user input is a liability, and a sketch sized once cannot be made to grow.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"34183200","gas_fee":"102549ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"luEzmZH6d3KGju79VncJynXNZA+KNiL36n4ob+peEzQ8x+ZD23CRPNZcIQokC8phdkyc9Wdqmn84QHZiv22sVw=="}],"memo":""},"metadata":{"timestamp":"1790960953"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"cowsaydemo","path":"gno.land/r/moul/x/daily/cowsaydemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/cowsaydemo/v0`\n\nInteractive gnoweb **demo of the [`p/moul/x/daily/cowsay`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/cowsay)\nlibrary** — it makes the classic ASCII cow say whatever you put in the path. It\nhas no rendering logic of its own.\n\nAppend a message to the path to make the cow say it, e.g.\n[`/r/moul/x/daily/cowsaydemo/v0:Hello, gno.land!`](https://gno.land/r/moul/x/daily/cowsaydemo/v0:Hello,%20gno.land!).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/cowsaydemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cowsaydemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/cowsaydemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cowsaydemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/cowsaydemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cowsaydemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/cowsaydemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/cowsaydemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/cowsaydemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/cowsaydemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"cowsaydemo.gno","body":"// Package cowsaydemo is a small gnoweb demo of the cowsay renderer provided by\n// the [p/moul/x/daily/cowsay](/p/moul/x/daily/cowsay/v0) library: it makes the\n// ASCII cow say whatever you put in the path.\n//\n// It contains no rendering logic of its own — the art comes entirely from\n// `cowsay.Say`.\npackage cowsaydemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/cowsay/v0\"\n)\n\n// Render displays the cow for gnoweb.\n//\n//\tRender(\"\")             -\u003e default message (\"Moo!\")\n//\tRender(\"/hello there\") -\u003e renders \"hello there\", word-wrapped\nfunc Render(path string) string {\n\tmsg := strings.TrimLeft(path, \"/\")\n\tart := cowsay.Say(msg)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# cowsay\\n\\n\")\n\tif strings.TrimSpace(msg) == \"\" {\n\t\tb.WriteString(\"_Tip: pass a message in the path, e.g._ `/Hello, gno.land!`\\n\\n\")\n\t}\n\tb.WriteString(\"```\\n\")\n\tb.WriteString(art)\n\tb.WriteString(\"```\\n\")\n\treturn b.String()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/cowsaydemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package cowsaydemo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # cowsay\n\t//\n\t// _Tip: pass a message in the path, e.g._ `/Hello, gno.land!`\n\t//\n\t// ```\n\t//  ______\n\t// \u003c Moo! \u003e\n\t//  ------\n\t//         \\   ^__^\n\t//          \\  (oo)\\_______\n\t//             (__)\\       )\\/\\\n\t//                 ||----w |\n\t//                 ||     ||\n\t// ```\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"20730800","gas_fee":"62192ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"MfYU9A4Lhzig+mhipAiRGQ+vWw2BX+H3pt8XW55kHO5G2+vTR+Y4csrY4W3uXf+WzBVu41cRLsghGIAF01KP9g=="}],"memo":""},"metadata":{"timestamp":"1790960953"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"crc32demo","path":"gno.land/r/moul/x/daily/crc32demo/v0","files":[{"name":"README.md","body":"# CRC-32\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nChecksums a few strings and shows that a one-character change moves the result\ncompletely.\n\n```\n/r/moul/x/daily/crc32demo/v0        → the samples table\n/r/moul/x/daily/crc32demo/v0:abc    → checksum your own text\n```\n\nDemo of the [`p/moul/x/daily/crc32`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/crc32)\nlibrary — no checksum logic lives here. Stateless, so `Render` is deterministic.\n\nThe table includes `123456789` → `cbf43926`, the standard CRC-32 check value,\nso the pinned example doubles as a conformance test. The last two rows differ by\na single letter and share no hex digits — that avalanche is the property worth\nseeing.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/crc32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crc32demo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/crc32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crc32demo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/crc32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crc32demo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/crc32demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crc32demo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/crc32demo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/crc32demo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"crc32demo.gno","body":"// Package crc32demo is a small gnoweb demo of the CRC-32 checksum provided by\n// the [p/moul/x/daily/crc32](/p/moul/x/daily/crc32/v0) library: it checksums a\n// few strings and shows that a one-character change moves the result\n// completely.\n//\n// It contains no checksum logic of its own. Stateless, so Render is\n// deterministic.\npackage crc32demo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/crc32/v0\"\n)\n\nvar samples = []string{\"\", \"a\", \"abc\", \"123456789\", \"hello world\", \"hello worle\"}\n\n// Render renders the demo for gnoweb.\n//\n//\tRender(\"\")       / Render(\"/\") -\u003e the samples table\n//\tRender(\"/\u003ctext\u003e\")              -\u003e checksum that text\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# CRC-32\\n\\n\")\n\tb.WriteString(\"The IEEE checksum behind zip, gzip and PNG, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/crc32`](/p/moul/x/daily/crc32/v0) library.\\n\\n\")\n\n\tif in := parseArg(path); in != \"\" {\n\t\tb.WriteString(\"## `\")\n\t\tb.WriteString(in)\n\t\tb.WriteString(\"`\\n\\n`\")\n\t\tb.WriteString(crc32.ChecksumHex(in))\n\t\tb.WriteString(\"`\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| input | crc32 |\\n|---|---|\\n\")\n\tfor _, s := range samples {\n\t\tb.WriteString(\"| \")\n\t\tif s == \"\" {\n\t\t\tb.WriteString(\"_(empty)_\")\n\t\t} else {\n\t\t\tb.WriteString(\"`\" + s + \"`\")\n\t\t}\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(crc32.ChecksumHex(s))\n\t\tb.WriteString(\"` |\\n\")\n\t}\n\tb.WriteString(\"\\n`123456789` → `cbf43926` is the standard CRC-32 check value, \")\n\tb.WriteString(\"so this table doubles as a conformance test.\\n\\n\")\n\tb.WriteString(\"\u003e The last two rows differ by one letter and share no digits: \")\n\tb.WriteString(\"that avalanche is the point.\\n\\n\")\n\tb.WriteString(\"\u003e A CRC detects **accidents**, not tampering — it is linear, so a \")\n\tb.WriteString(\"matching message is easy to craft. Never authenticate with it.\\n\")\n\treturn b.String()\n}\n\nfunc parseArg(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/crc32demo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package crc32demo\n\n// ExampleRender pins the realm's root Render output as a testable example.\n// The `123456789` row is the standard CRC-32 check value, so this example\n// doubles as a conformance test for the library.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # CRC-32\n\t//\n\t// The IEEE checksum behind zip, gzip and PNG, demoing the [`p/moul/x/daily/crc32`](/p/moul/x/daily/crc32/v0) library.\n\t//\n\t// | input | crc32 |\n\t// |---|---|\n\t// | _(empty)_ | `00000000` |\n\t// | `a` | `e8b7be43` |\n\t// | `abc` | `352441c2` |\n\t// | `123456789` | `cbf43926` |\n\t// | `hello world` | `0d4a1185` |\n\t// | `hello worle` | `7a4d2113` |\n\t//\n\t// `123456789` → `cbf43926` is the standard CRC-32 check value, so this table doubles as a conformance test.\n\t//\n\t// \u003e The last two rows differ by one letter and share no digits: that avalanche is the point.\n\t//\n\t// \u003e A CRC detects **accidents**, not tampering — it is linear, so a matching message is easy to craft. Never authenticate with it.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"26235000","gas_fee":"78705ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"pYb0O/n5LoLG/X8sMe7PC8wlRzgimjn0IKOLx9CKx3tZfeOFvkX/GrKAu4fEzW9nJ/6Ed71dNtMHQHdv3KuNZA=="}],"memo":""},"metadata":{"timestamp":"1790960954"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"crowdfund","path":"gno.land/r/moul/x/daily/crowdfund/v1","files":[{"name":"README.md","body":"# Crowdfund\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nA gno.land realm port of the classic Solidity **Kickstarter-style crowdfunding**\ncontract. It keeps the same lifecycle — launch a campaign with a goal and a\ndeadline, let backers pledge and unpledge, then either let the creator claim on\nsuccess or let backers refund on failure — but models everything as plain\n`uint64` accounting (no real coin transfer), the idiomatic Gno equivalent of the\nSolidity `mapping(address =\u003e uint)` balances.\n\nDeadlines use `runtime.ChainHeight()` (block height) instead of\n`block.timestamp`, `msg.sender` becomes `unsafe.PreviousRealm().Address()`,\n`require` becomes `panic`, and campaigns live in an ordered `avl.Tree` so\n`Render` lists them deterministically with a `▓░` progress bar.\n\n## Transactions\n\n- `Launch(goal uint64, durationBlocks int) int` — create a campaign (returns id); deadline = current height + duration.\n- `Pledge(id int, amount uint64)` — back a campaign before its deadline.\n- `Unpledge(id int, amount uint64)` — withdraw part/all of your pledge before the deadline.\n- `Claim(id int)` — creator claims funds after the deadline if `pledged \u003e= goal`.\n- `Refund(id int)` — backer reclaims their pledge after the deadline if the goal was missed.\n\n## Example\n\n```\nLaunch(1000, 100)      // campaign #1, goal 1000, ends 100 blocks from now -\u003e returns 1\nPledge(1, 400)         // back campaign #1 with 400\nPledge(1, 700)         // total now 1100 (\u003e= goal)\nUnpledge(1, 100)       // change of mind: total back to 1000\n// ... after block height passes the deadline ...\nClaim(1)               // creator claims 1000 (goal met)\n```\n\nRead-only `Render(\"\")` shows every campaign with its progress bar, goal,\npledged total, deadline block and state (Active / Funded / Funded (claimed) /\nFailed).\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`Campaign` loses its `ID` field, which the store now owns, and the realm's local\n`mustGet` becomes one line: the store's labelled `MustGet` panics\n`campaign #7 not found` where `v0` said only `campaign not found`. Each\ncampaign keeps its own address-keyed `pledges` tree, which the store does not\ncover. Campaign ids already started at 1, so nothing shifts.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/crowdfund) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/crowdfund/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crowdfund/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/crowdfund/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crowdfund/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/crowdfund/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crowdfund/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/crowdfund/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/crowdfund/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/crowdfund/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/crowdfund/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"crowdfund.gno","body":"// Package crowdfund is an accounting-only port of the classic Solidity\n// Kickstarter-style crowdfunding contract to a gno.land realm.\n//\n// A creator Launches a campaign with a funding goal and a duration (in blocks).\n// Backers Pledge (and may Unpledge before the deadline). After the deadline the\n// creator can Claim if the goal was met, otherwise backers can Refund.\n//\n// No real coin moves: pledges are tracked as plain uint64 accounting, exactly\n// like the mapping(address =\u003e uint) balances of the Solidity original.\npackage crowdfund\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Campaign holds the state of a single crowdfunding campaign. It carries no ID\n// field: the id belongs to the store, which hands it back on lookup and\n// iteration.\ntype Campaign struct {\n\tCreator  address\n\tGoal     uint64\n\tDeadline int64     // block height after which the campaign is closed\n\tPledged  uint64    // running total pledged\n\tClaimed  bool      // creator already claimed the funds\n\tpledges  *avl.Tree // backer address (string) -\u003e pledged uint64\n}\n\n// campaigns assigns the campaign ids. v0 kept its own nextID plus a key() that\n// zero-padded to width 12, which stopped ordering Render past 10^12, and its\n// own mustGet whose panic did not say which campaign was missing.\nvar campaigns = store.Named(\"campaign\")\n\nfunc mustGet(id int) *Campaign {\n\treturn campaigns.MustGet(store.ID(id)).(*Campaign)\n}\n\n// Launch creates a new campaign owned by the caller and returns its id.\nfunc Launch(cur realm, goal uint64, durationBlocks int) int {\n\tif goal == 0 {\n\t\tpanic(\"goal must be \u003e 0\")\n\t}\n\tif durationBlocks \u003c= 0 {\n\t\tpanic(\"duration must be \u003e 0\")\n\t}\n\tcaller := unsafe.PreviousRealm().Address()\n\tid := campaigns.Add(\u0026Campaign{\n\t\tCreator:  caller,\n\t\tGoal:     goal,\n\t\tDeadline: runtime.ChainHeight() + int64(durationBlocks),\n\t\tpledges:  avl.NewTree(),\n\t})\n\tchain.Emit(\"Launch\",\n\t\t\"id\", id.String(),\n\t\t\"creator\", caller.String(),\n\t\t\"goal\", strconv.FormatUint(goal, 10))\n\treturn int(id)\n}\n\n// Pledge backs campaign id with amount (before the deadline).\nfunc Pledge(cur realm, id int, amount uint64) {\n\tif amount == 0 {\n\t\tpanic(\"amount must be \u003e 0\")\n\t}\n\tc := mustGet(id)\n\tif runtime.ChainHeight() \u003e c.Deadline {\n\t\tpanic(\"campaign ended\")\n\t}\n\tcaller := unsafe.PreviousRealm().Address()\n\tprev := uint64(0)\n\tif v := c.pledges.Get(caller.String()); v != nil {\n\t\tprev = v.(uint64)\n\t}\n\tc.pledges.Set(caller.String(), prev+amount)\n\tc.Pledged += amount\n\tchain.Emit(\"Pledge\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"from\", caller.String(),\n\t\t\"amount\", strconv.FormatUint(amount, 10))\n}\n\n// Unpledge withdraws amount from the caller's pledge (before the deadline).\nfunc Unpledge(cur realm, id int, amount uint64) {\n\tif amount == 0 {\n\t\tpanic(\"amount must be \u003e 0\")\n\t}\n\tc := mustGet(id)\n\tif runtime.ChainHeight() \u003e c.Deadline {\n\t\tpanic(\"campaign ended\")\n\t}\n\tcaller := unsafe.PreviousRealm().Address()\n\tv := c.pledges.Get(caller.String())\n\tif v == nil {\n\t\tpanic(\"nothing pledged\")\n\t}\n\thave := v.(uint64)\n\tif amount \u003e have {\n\t\tpanic(\"amount exceeds pledge\")\n\t}\n\tif remaining := have - amount; remaining == 0 {\n\t\tc.pledges.Remove(caller.String())\n\t} else {\n\t\tc.pledges.Set(caller.String(), remaining)\n\t}\n\tc.Pledged -= amount\n\tchain.Emit(\"Unpledge\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"from\", caller.String(),\n\t\t\"amount\", strconv.FormatUint(amount, 10))\n}\n\n// Claim lets the creator take the funds if the goal was met after the deadline.\nfunc Claim(cur realm, id int) {\n\tc := mustGet(id)\n\tif runtime.ChainHeight() \u003c= c.Deadline {\n\t\tpanic(\"campaign not ended\")\n\t}\n\tcaller := unsafe.PreviousRealm().Address()\n\tif caller != c.Creator {\n\t\tpanic(\"only creator can claim\")\n\t}\n\tif c.Pledged \u003c c.Goal {\n\t\tpanic(\"goal not reached\")\n\t}\n\tif c.Claimed {\n\t\tpanic(\"already claimed\")\n\t}\n\tc.Claimed = true\n\tchain.Emit(\"Claim\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"amount\", strconv.FormatUint(c.Pledged, 10))\n}\n\n// Refund returns the caller's pledge if the campaign failed after the deadline.\nfunc Refund(cur realm, id int) {\n\tc := mustGet(id)\n\tif runtime.ChainHeight() \u003c= c.Deadline {\n\t\tpanic(\"campaign not ended\")\n\t}\n\tif c.Pledged \u003e= c.Goal {\n\t\tpanic(\"campaign succeeded, no refund\")\n\t}\n\tcaller := unsafe.PreviousRealm().Address()\n\tv := c.pledges.Get(caller.String())\n\tif v == nil {\n\t\tpanic(\"nothing to refund\")\n\t}\n\tamount := v.(uint64)\n\tc.pledges.Remove(caller.String())\n\tc.Pledged -= amount\n\tchain.Emit(\"Refund\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"to\", caller.String(),\n\t\t\"amount\", strconv.FormatUint(amount, 10))\n}\n\n// --- pure/read-only helpers (also used by Render) ---\n\n// pct returns the funded percentage (0..100).\nfunc pct(pledged, goal uint64) int {\n\tif goal == 0 {\n\t\treturn 0\n\t}\n\tp := int(pledged * 100 / goal)\n\tif p \u003e 100 {\n\t\tp = 100\n\t}\n\treturn p\n}\n\n// progressBar renders a fixed-width ▓░ bar for pledged/goal.\nfunc progressBar(pledged, goal uint64) string {\n\tconst width = 20\n\tfilled := 0\n\tif goal \u003e 0 {\n\t\tfilled = int(pledged * width / goal)\n\t\tif filled \u003e width {\n\t\t\tfilled = width\n\t\t}\n\t}\n\tbar := \"\"\n\tfor i := 0; i \u003c width; i++ {\n\t\tif i \u003c filled {\n\t\t\tbar += \"▓\"\n\t\t} else {\n\t\t\tbar += \"░\"\n\t\t}\n\t}\n\treturn bar\n}\n\n// state describes a campaign relative to a given block height.\nfunc state(c *Campaign, height int64) string {\n\tif height \u003c= c.Deadline {\n\t\treturn \"Active\"\n\t}\n\tif c.Pledged \u003e= c.Goal {\n\t\tif c.Claimed {\n\t\t\treturn \"Funded (claimed)\"\n\t\t}\n\t\treturn \"Funded\"\n\t}\n\treturn \"Failed\"\n}\n\n// Render shows all campaigns with a progress bar, goal, pledged and state.\nfunc Render(path string) string {\n\tif campaigns.Len() == 0 {\n\t\treturn \"# Crowdfund\\n\\nNo campaigns yet. Call `Launch(goal, durationBlocks)` to start one.\\n\"\n\t}\n\theight := runtime.ChainHeight()\n\tout := \"# Crowdfund\\n\\n\"\n\tout += \"Current block height: **\" + strconv.FormatInt(height, 10) + \"**\\n\\n\"\n\tcampaigns.Each(func(id store.ID, v any) {\n\t\tc := v.(*Campaign)\n\t\tout += \"## Campaign #\" + id.String() + \"\\n\\n\"\n\t\tout += \"`\" + progressBar(c.Pledged, c.Goal) + \"` \" + strconv.Itoa(pct(c.Pledged, c.Goal)) + \"%\\n\\n\"\n\t\tout += \"- State: **\" + state(c, height) + \"**\\n\"\n\t\tout += \"- Goal: \" + strconv.FormatUint(c.Goal, 10) + \"\\n\"\n\t\tout += \"- Pledged: \" + strconv.FormatUint(c.Pledged, 10) + \"\\n\"\n\t\tout += \"- Deadline: block \" + strconv.FormatInt(c.Deadline, 10) + \"\\n\"\n\t\tout += \"- Creator: `\" + c.Creator.String() + \"`\\n\\n\"\n\t})\n\treturn out\n}\n"},{"name":"crowdfund_test.gno","body":"package crowdfund\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestProgressBarAndPct(t *testing.T) {\n\tuassert.Equal(t, \"░░░░░░░░░░░░░░░░░░░░\", progressBar(0, 100))\n\tuassert.Equal(t, \"▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░\", progressBar(50, 100))\n\tuassert.Equal(t, \"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\", progressBar(100, 100))\n\t// over-funded is capped at full width\n\tuassert.Equal(t, \"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\", progressBar(250, 100))\n\t// zero goal never divides by zero\n\tuassert.Equal(t, \"░░░░░░░░░░░░░░░░░░░░\", progressBar(10, 0))\n\n\tuassert.Equal(t, 0, pct(0, 100))\n\tuassert.Equal(t, 25, pct(25, 100))\n\tuassert.Equal(t, 100, pct(100, 100))\n\tuassert.Equal(t, 100, pct(500, 100)) // capped\n\tuassert.Equal(t, 0, pct(5, 0))       // no goal\n}\n\nfunc TestState(t *testing.T) {\n\tactive := \u0026Campaign{Goal: 100, Pledged: 10, Deadline: 100}\n\tuassert.Equal(t, \"Active\", state(active, 50))\n\tuassert.Equal(t, \"Active\", state(active, 100)) // deadline block still active\n\n\tfunded := \u0026Campaign{Goal: 100, Pledged: 150, Deadline: 100}\n\tuassert.Equal(t, \"Funded\", state(funded, 101))\n\n\tclaimed := \u0026Campaign{Goal: 100, Pledged: 150, Deadline: 100, Claimed: true}\n\tuassert.Equal(t, \"Funded (claimed)\", state(claimed, 101))\n\n\tfailed := \u0026Campaign{Goal: 100, Pledged: 50, Deadline: 100}\n\tuassert.Equal(t, \"Failed\", state(failed, 101))\n\n\t// exactly meeting the goal counts as funded\n\texact := \u0026Campaign{Goal: 100, Pledged: 100, Deadline: 100}\n\tuassert.Equal(t, \"Funded\", state(exact, 200))\n}\n\n// v0 asserted that its own key() padded to width 12. That rule held only below\n// the width: key(10^12) is 13 characters and sorts before key(10^12-1), so the\n// campaign list would have rendered out of order from that id on. The store key\n// has no width to outgrow.\nfunc TestKeyOrdering(t *testing.T) {\n\tuassert.True(t, store.ID(2).Key() \u003c store.ID(10).Key())\n\tuassert.True(t, store.ID(9).Key() \u003c store.ID(100).Key())\n\tuassert.True(t, store.ID(999999999999).Key() \u003c store.ID(1000000000000).Key(),\n\t\t\"and it keeps holding one past v0's width-12 ceiling\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/crowdfund/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package crowdfund\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Crowdfund\n\t//\n\t// No campaigns yet. Call `Launch(goal, durationBlocks)` to start one.\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"47308000","gas_fee":"141924ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"RfJFCffke+QiOdhstNBAd1RNGLXUFs4CQS+NEGMbDuQDtHRvSGUTR1s4cdJaaz7yKTJOciof9GwlUh8WNe12PQ=="}],"memo":""},"metadata":{"timestamp":"1790960954"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"disjointsetdemo","path":"gno.land/r/moul/x/daily/disjointsetdemo/v0","files":[{"name":"README.md","body":"# Union-Find\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nApplies a fixed list of merges to `[0, 10)` and renders the resulting partition.\n\nDemo of the [`p/moul/x/daily/disjointset`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/disjointset)\nlibrary — every `Union`/`Find` comes from the package; this realm holds no\nunion-find logic. Stateless, so `Render` is fully deterministic.\n\nThe library's `Partition` is order-independent (groups sorted, ordered by\nsmallest member), which is exactly why the output can be pinned in an example\ntest at all.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/disjointsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/disjointsetdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/disjointsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/disjointsetdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/disjointsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/disjointsetdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/disjointsetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/disjointsetdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/disjointsetdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/disjointsetdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"disjointsetdemo.gno","body":"// Package disjointsetdemo is a small gnoweb demo of the union-find structure\n// provided by the [p/moul/x/daily/disjointset](/p/moul/x/daily/disjointset/v0)\n// library: it merges a fixed list of pairs and shows the resulting partition.\n//\n// It contains no union-find logic of its own. Stateless, so Render is\n// deterministic — and the library's Partition is order-independent, which is\n// what makes the output safe to pin.\npackage disjointsetdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/disjointset/v0\"\n)\n\n// n is the universe size; pairs are the merges applied, in order.\nconst n = 10\n\nvar pairs = [][2]int{{0, 1}, {2, 3}, {1, 3}, {5, 6}, {7, 8}, {8, 9}}\n\nfunc build() *disjointset.DisjointSet {\n\td := disjointset.New(n)\n\tfor _, p := range pairs {\n\t\td.Union(p[0], p[1])\n\t}\n\treturn d\n}\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\td := build()\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Union-Find\\n\\n\")\n\tb.WriteString(\"Disjoint-set forest with path compression and union by rank, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/disjointset`](/p/moul/x/daily/disjointset/v0) library.\\n\\n\")\n\n\tb.WriteString(\"## Merges applied\\n\\n\")\n\tfor _, p := range pairs {\n\t\tb.WriteString(\"- `Union(\")\n\t\tb.WriteString(strconv.Itoa(p[0]))\n\t\tb.WriteString(\", \")\n\t\tb.WriteString(strconv.Itoa(p[1]))\n\t\tb.WriteString(\")`\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Partition of [0, \")\n\tb.WriteString(strconv.Itoa(n))\n\tb.WriteString(\")\\n\\n**\")\n\tb.WriteString(strconv.Itoa(d.Groups()))\n\tb.WriteString(\"** groups:\\n\\n\")\n\tfor _, g := range d.Partition() {\n\t\tb.WriteString(\"- `{\")\n\t\tnums := []string{}\n\t\tfor _, x := range g {\n\t\t\tnums = append(nums, strconv.Itoa(x))\n\t\t}\n\t\tb.WriteString(strings.Join(nums, \", \"))\n\t\tb.WriteString(\"}`\\n\")\n\t}\n\n\tb.WriteString(\"\\n\u003e Groups come out sorted, ordered by their smallest member, \")\n\tb.WriteString(\"so the partition is identical whatever order the merges arrive in.\\n\")\n\treturn b.String()\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/disjointsetdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package disjointsetdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Union-Find\n\t//\n\t// Disjoint-set forest with path compression and union by rank, demoing the [`p/moul/x/daily/disjointset`](/p/moul/x/daily/disjointset/v0) library.\n\t//\n\t// ## Merges applied\n\t//\n\t// - `Union(0, 1)`\n\t// - `Union(2, 3)`\n\t// - `Union(1, 3)`\n\t// - `Union(5, 6)`\n\t// - `Union(7, 8)`\n\t// - `Union(8, 9)`\n\t//\n\t// ## Partition of [0, 10)\n\t//\n\t// **4** groups:\n\t//\n\t// - `{0, 1, 2, 3}`\n\t// - `{4}`\n\t// - `{5, 6}`\n\t// - `{7, 8, 9}`\n\t//\n\t// \u003e Groups come out sorted, ordered by their smallest member, so the partition is identical whatever order the merges arrive in.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"25163800","gas_fee":"75491ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"kvO08e8I2arCMq3h3i0Yx9gE7t8kdQXk38ghyESTCsZshYzxMRNBf6kzUCTPF2PtH4YJiok7hclIisUX7Qndfg=="}],"memo":""},"metadata":{"timestamp":"1790960955"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"dutchauction","path":"gno.land/r/moul/x/daily/dutchauction/v0","files":[{"name":"README.md","body":"# dutchauction\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA Gno port of the classic Solidity Dutch-auction pattern: list an item at a\nhigh starting price that decays linearly, block by block, down to a floor.\nThe first buyer to call `Buy` gets it at whatever the price is at that exact\nblock — no bidding war, just a clock ticking against the seller. Payment is\nreal `ugnot`, escrowed by the chain with the transaction; overpayment is\nrefunded automatically and the settled price is forwarded straight to the\nseller.\n\nRealm path: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/dutchauction`\n\n## Example calls\n\n```\n# list an item: 1000 ugnot down to a 100 ugnot floor over 100 blocks\nList(cur, \"vintage synth\", 1000, 100, 100) -\u003e \"1\"\n\n# anyone can check the live price without paying anything\nCurrentPrice(\"1\") -\u003e 1000, decaying toward 100 as blocks pass\n\n# buy at the current price, sending \u003e= CurrentPrice(\"1\") ugnot with the tx;\n# any excess is refunded in the same call\nBuy(cur, \"1\") -\u003e price actually paid\n\n# the seller can pull a listing before anyone buys it\nCancel(cur, \"1\")\n```\n\n`Render(\"\")` lists every auction with its live price, floor, start price,\nand status.\n\n## Toolchain status\n\n`gno test .` passes (7/7) against `gnolang/gno` master (`master.3130+bf5b31eda`)\nwith `GNOROOT` pointed at a full checkout — the local `gno` on `PATH` ships\nwithout a bundled stdlib tree, so `GNOROOT` had to be set explicitly to\nresolve `chain`, `chain/banker`, `chain/runtime`, and\n`gno.land/p/nt/avl/v0`/`testutils/v0`. `gno lint .` is clean. Target chain is\nsapphire (gno 0.9); code sticks to the documented `chain/*` stdlib family and\ncrossing-function (`cur realm`) convention used by the other realms in this\nbatch.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/dutchauction/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dutchauction/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/dutchauction/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dutchauction/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/dutchauction/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dutchauction/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/dutchauction/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/dutchauction/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/dutchauction/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/dutchauction/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"dutchauction.gno","body":"// Package dutchauction ports the classic Solidity Dutch-auction pattern to\n// gno.land: a seller lists an item at a high starting price that decays\n// linearly, block by block, down to a floor price. The first buyer to call\n// Buy pays whatever the price is at that moment — real ugnot, escrowed by\n// the chain with the transaction and forwarded to the seller on settlement.\n// Overpayment is refunded automatically. State-mutating functions are\n// crossing functions (`cur realm`) per the gno 0.9 interrealm convention.\npackage dutchauction\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst denom = \"ugnot\"\n\ntype status int\n\nconst (\n\tstatusActive status = iota\n\tstatusSold\n\tstatusCancelled\n)\n\nfunc (s status) String() string {\n\tswitch s {\n\tcase statusActive:\n\t\treturn \"active\"\n\tcase statusSold:\n\t\treturn \"sold\"\n\tcase statusCancelled:\n\t\treturn \"cancelled\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\n// auction is one listing: price falls linearly from StartPrice to\n// FloorPrice over Duration blocks starting at StartHeight, then holds flat\n// at FloorPrice until bought or cancelled.\ntype auction struct {\n\tID          string\n\tItem        string\n\tSeller      address\n\tStartPrice  int64\n\tFloorPrice  int64\n\tStartHeight int64\n\tDuration    int64\n\tStatus      status\n\tBuyer       address\n\tSoldPrice   int64\n}\n\nvar (\n\tauctions    avl.Tree // id string -\u003e *auction\n\tnextID      uint64\n\ttotalListed uint64\n\ttotalSold   uint64\n\ttotalVolume int64\n)\n\nvar (\n\terrEmptyItem    = errors.New(\"dutchauction: item description required\")\n\terrBadPrice     = errors.New(\"dutchauction: startPrice must be greater than floorPrice, floorPrice must be \u003e= 0\")\n\terrBadDuration  = errors.New(\"dutchauction: durationBlocks must be positive\")\n\terrNotFound     = errors.New(\"dutchauction: auction not found\")\n\terrNotActive    = errors.New(\"dutchauction: auction is not active\")\n\terrNotSeller    = errors.New(\"dutchauction: caller is not the seller\")\n\terrNotUserCall  = errors.New(\"dutchauction: buy must be a direct user transaction\")\n\terrUnderpaid    = errors.New(\"dutchauction: payment below current price\")\n\terrSpoofedRealm = errors.New(\"dutchauction: spoofed realm\")\n)\n\n// caller authenticates the crossing frame and returns the immediate caller.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(errSpoofedRealm)\n\t}\n\treturn cur.Previous().Address()\n}\n\n// List creates a new Dutch auction for item, starting at startPrice ugnot\n// and falling linearly to floorPrice over durationBlocks. Returns the new\n// auction's ID. Crossing function.\nfunc List(cur realm, item string, startPrice, floorPrice, durationBlocks int64) string {\n\tseller := caller(cur)\n\n\titem = strings.TrimSpace(item)\n\tif item == \"\" {\n\t\tpanic(errEmptyItem)\n\t}\n\tif floorPrice \u003c 0 || startPrice \u003c= floorPrice {\n\t\tpanic(errBadPrice)\n\t}\n\tif durationBlocks \u003c= 0 {\n\t\tpanic(errBadDuration)\n\t}\n\n\tnextID++\n\tid := strconv.FormatUint(nextID, 10)\n\tauctions.Set(id, \u0026auction{\n\t\tID:          id,\n\t\tItem:        item,\n\t\tSeller:      seller,\n\t\tStartPrice:  startPrice,\n\t\tFloorPrice:  floorPrice,\n\t\tStartHeight: runtime.ChainHeight(),\n\t\tDuration:    durationBlocks,\n\t\tStatus:      statusActive,\n\t})\n\ttotalListed++\n\treturn id\n}\n\n// Buy purchases auction id at its current price. The caller must send at\n// least that many ugnot with the transaction; any excess is refunded\n// immediately. Only a direct EOA transaction (MsgCall) may buy, so the\n// payment envelope can't be spoofed via an ephemeral MsgRun realm. Returns\n// the price actually paid. Crossing function.\nfunc Buy(cur realm, id string) int64 {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(errNotUserCall)\n\t}\n\tbuyer := cur.Previous().Address()\n\n\ta := getAuction(id)\n\tif a.Status != statusActive {\n\t\tpanic(errNotActive)\n\t}\n\n\tprice := priceAt(a, runtime.ChainHeight())\n\tsent := unsafe.OriginSend()\n\tpaid := sent.AmountOf(denom)\n\tif paid \u003c price {\n\t\tpanic(errUnderpaid)\n\t}\n\n\ta.Status = statusSold\n\ta.Buyer = buyer\n\ta.SoldPrice = price\n\ttotalSold++\n\ttotalVolume += price\n\n\tbnk := banker.NewBanker(banker.BankerTypeOriginSend, cur)\n\tpkgAddr := cur.Address()\n\tif paid \u003e price {\n\t\tbnk.SendCoins(pkgAddr, buyer, chain.NewCoins(chain.NewCoin(denom, paid-price)))\n\t}\n\tbnk.SendCoins(pkgAddr, a.Seller, chain.NewCoins(chain.NewCoin(denom, price)))\n\n\treturn price\n}\n\n// Cancel withdraws an active auction. Only the seller may cancel, and only\n// before it's bought. Crossing function.\nfunc Cancel(cur realm, id string) {\n\twho := caller(cur)\n\n\ta := getAuction(id)\n\tif a.Status != statusActive {\n\t\tpanic(errNotActive)\n\t}\n\tif who != a.Seller {\n\t\tpanic(errNotSeller)\n\t}\n\ta.Status = statusCancelled\n}\n\n// CurrentPrice returns id's price at the current chain height.\nfunc CurrentPrice(id string) int64 {\n\treturn priceAt(getAuction(id), runtime.ChainHeight())\n}\n\n// AuctionInfo returns a snapshot of auction id.\nfunc AuctionInfo(id string) (item string, seller address, status string, currentPrice int64, floorPrice int64, startPrice int64) {\n\ta := getAuction(id)\n\treturn a.Item, a.Seller, a.Status.String(), priceAt(a, runtime.ChainHeight()), a.FloorPrice, a.StartPrice\n}\n\n// priceAt computes the linear-decay price of a at the given height. Once\n// settled (sold or cancelled), the price is frozen: SoldPrice for a sale,\n// zero for a cancellation.\nfunc priceAt(a *auction, height int64) int64 {\n\tif a.Status != statusActive {\n\t\treturn a.SoldPrice\n\t}\n\telapsed := height - a.StartHeight\n\tif elapsed \u003c= 0 {\n\t\treturn a.StartPrice\n\t}\n\tif elapsed \u003e= a.Duration {\n\t\treturn a.FloorPrice\n\t}\n\tdrop := a.StartPrice - a.FloorPrice\n\treturn a.StartPrice - drop*elapsed/a.Duration\n}\n\nfunc getAuction(id string) *auction {\n\tv := auctions.Get(id)\n\tif v == nil {\n\t\tpanic(errNotFound)\n\t}\n\treturn v.(*auction)\n}\n\n// Render produces the gnoweb Markdown view: a table of every auction,\n// newest first, with live prices. Not a crossing function.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Dutch Auction\\n\\n\")\n\tb.WriteString(\"A price that only ever falls. List an item high; it decays block by \")\n\tb.WriteString(\"block toward a floor; the first `Buy` call wins it at whatever the \")\n\tb.WriteString(\"price is at that instant. Real ugnot, escrowed by the chain and paid \")\n\tb.WriteString(\"straight to the seller — overpayment is refunded automatically.\\n\\n\")\n\n\tb.WriteString(\"- **Total listed:** \" + strconv.FormatUint(totalListed, 10) + \"\\n\")\n\tb.WriteString(\"- **Total sold:** \" + strconv.FormatUint(totalSold, 10) + \"\\n\")\n\tb.WriteString(\"- **Total volume:** \" + strconv.FormatInt(totalVolume, 10) + \" ugnot\\n\")\n\tb.WriteString(\"- **Current height:** \" + strconv.FormatInt(runtime.ChainHeight(), 10) + \"\\n\\n\")\n\n\tif auctions.Size() == 0 {\n\t\tb.WriteString(\"_No auctions yet — call `List` to open one._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"## Auctions\\n\\n\")\n\tb.WriteString(\"| ID | Item | Status | Price now | Floor | Start | Seller |\\n\")\n\tb.WriteString(\"| ---: | --- | --- | ---: | ---: | ---: | --- |\\n\")\n\n\theight := runtime.ChainHeight()\n\tids := make([]uint64, 0, auctions.Size())\n\tauctions.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tn, _ := strconv.ParseUint(key, 10, 64)\n\t\tids = append(ids, n)\n\t\treturn false\n\t})\n\tfor i := len(ids) - 1; i \u003e= 0; i-- {\n\t\tid := strconv.FormatUint(ids[i], 10)\n\t\tv := auctions.Get(id)\n\t\ta := v.(*auction)\n\t\tb.WriteString(\"| \" + a.ID + \" | \" + a.Item + \" | \" + a.Status.String() +\n\t\t\t\" | \" + strconv.FormatInt(priceAt(a, height), 10) +\n\t\t\t\" | \" + strconv.FormatInt(a.FloorPrice, 10) +\n\t\t\t\" | \" + strconv.FormatInt(a.StartPrice, 10) +\n\t\t\t\" | `\" + a.Seller.String() + \"` |\\n\")\n\t}\n\n\treturn b.String()\n}\n"},{"name":"dutchauction_test.gno","body":"package dutchauction\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nvar realmAddr = chain.PackageAddress(\"gno.land/r/moul/x/daily/dutchauction/v0\")\n\nfunc reset() {\n\tauctions = avl.Tree{}\n\tnextID = 0\n\ttotalListed = 0\n\ttotalSold = 0\n\ttotalVolume = 0\n}\n\n// fundBuy simulates a buyer sending `amount` ugnot alongside the tx: the\n// runtime deposits it at the realm's address first, then unsafe.OriginSend\n// reports it to the crossing function.\nfunc fundBuy(buyer address, amount int64) {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{\"ugnot\", amount}})\n\ttesting.SetOriginSend(chain.Coins{{\"ugnot\", amount}})\n\ttesting.SetRealm(testing.NewUserRealm(buyer))\n}\n\nfunc TestListAndPriceDecay(cur realm, t *testing.T) {\n\treset()\n\tseller := testutils.TestAddress(\"seller\")\n\n\ttesting.SetRealm(testing.NewUserRealm(seller))\n\tid := List(cross(cur), \"vintage synth\", 1000, 100, 100)\n\n\tif got := CurrentPrice(id); got != 1000 {\n\t\tt.Fatalf(\"price at start = %d, want 1000\", got)\n\t}\n\n\ttesting.SkipHeights(50)\n\tif got := CurrentPrice(id); got != 550 {\n\t\tt.Fatalf(\"price at midpoint = %d, want 550\", got)\n\t}\n\n\ttesting.SkipHeights(100)\n\tif got := CurrentPrice(id); got != 100 {\n\t\tt.Fatalf(\"price past duration = %d, want floor 100\", got)\n\t}\n}\n\nfunc TestListRejectsBadInput(cur realm, t *testing.T) {\n\treset()\n\tseller := testutils.TestAddress(\"seller\")\n\ttesting.SetRealm(testing.NewUserRealm(seller))\n\n\trec := revive(func() { List(cross(cur), \"\", 1000, 100, 100) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic on empty item\")\n\t}\n\trec = revive(func() { List(cross(cur), \"thing\", 100, 1000, 100) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when floorPrice \u003e= startPrice\")\n\t}\n\trec = revive(func() { List(cross(cur), \"thing\", 1000, 100, 0) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic on non-positive duration\")\n\t}\n}\n\nfunc TestBuyExactSettlesToSeller(cur realm, t *testing.T) {\n\treset()\n\tseller := testutils.TestAddress(\"seller\")\n\tbuyer := testutils.TestAddress(\"buyer\")\n\n\ttesting.SetRealm(testing.NewUserRealm(seller))\n\tid := List(cross(cur), \"vintage synth\", 1000, 100, 100)\n\n\ttesting.SkipHeights(50) // price = 550\n\tfundBuy(buyer, 550)\n\tpaid := Buy(cross(cur), id)\n\tif paid != 550 {\n\t\tt.Fatalf(\"paid = %d, want 550\", paid)\n\t}\n\n\tro := banker.NewReadonlyBanker()\n\tsellerBal := ro.GetCoins(seller).AmountOf(\"ugnot\")\n\tif sellerBal != 550 {\n\t\tt.Fatalf(\"seller balance = %d, want 550\", sellerBal)\n\t}\n\n\t_, _, status, price, _, _ := AuctionInfo(id)\n\tif status != \"sold\" {\n\t\tt.Fatalf(\"status = %q, want sold\", status)\n\t}\n\tif price != 550 {\n\t\tt.Fatalf(\"frozen price = %d, want 550\", price)\n\t}\n}\n\nfunc TestBuyOverpayIsRefunded(cur realm, t *testing.T) {\n\treset()\n\tseller := testutils.TestAddress(\"seller2\")\n\tbuyer := testutils.TestAddress(\"buyer2\")\n\n\ttesting.SetRealm(testing.NewUserRealm(seller))\n\tid := List(cross(cur), \"arcade cabinet\", 1000, 100, 100)\n\n\tfundBuy(buyer, 1000) // pay the full start price up front\n\tpaid := Buy(cross(cur), id)\n\tif paid != 1000 {\n\t\tt.Fatalf(\"paid = %d, want 1000 (bought at block 0)\", paid)\n\t}\n\n\tro := banker.NewReadonlyBanker()\n\tbuyerBal := ro.GetCoins(buyer).AmountOf(\"ugnot\")\n\tif buyerBal != 0 {\n\t\tt.Fatalf(\"buyer refund leftover = %d, want 0 (no overpay at price 1000)\", buyerBal)\n\t}\n}\n\nfunc TestBuyUnderpaidPanics(cur realm, t *testing.T) {\n\treset()\n\tseller := testutils.TestAddress(\"seller3\")\n\tbuyer := testutils.TestAddress(\"buyer3\")\n\n\ttesting.SetRealm(testing.NewUserRealm(seller))\n\tid := List(cross(cur), \"amp\", 1000, 100, 100)\n\n\tfundBuy(buyer, 500)\n\trec := revive(func() { Buy(cross(cur), id) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when underpaying\")\n\t}\n}\n\nfunc TestCancelBySellerOnly(cur realm, t *testing.T) {\n\treset()\n\tseller := testutils.TestAddress(\"seller4\")\n\tmallory := testutils.TestAddress(\"mallory\")\n\n\ttesting.SetRealm(testing.NewUserRealm(seller))\n\tid := List(cross(cur), \"pedal\", 1000, 100, 100)\n\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\trec := revive(func() { Cancel(cross(cur), id) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when a non-seller cancels\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(seller))\n\tCancel(cross(cur), id)\n\n\t_, _, status, _, _, _ := AuctionInfo(id)\n\tif status != \"cancelled\" {\n\t\tt.Fatalf(\"status = %q, want cancelled\", status)\n\t}\n\n\tfundBuy(mallory, 1000)\n\trec = revive(func() { Buy(cross(cur), id) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic buying a cancelled auction\")\n\t}\n}\n\nfunc TestRenderHome(t *testing.T) {\n\treset()\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Dutch Auction\") {\n\t\tt.Fatalf(\"render output missing title\\n%s\", out)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/dutchauction/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package dutchauction\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Dutch Auction\n\t//\n\t// A price that only ever falls. List an item high; it decays block by block toward a floor; the first `Buy` call wins it at whatever the price is at that instant. Real ugnot, escrowed by the chain and paid straight to the seller — overpayment is refunded automatically.\n\t//\n\t// - **Total listed:** 0\n\t// - **Total sold:** 0\n\t// - **Total volume:** 0 ugnot\n\t// - **Current height:** 123\n\t//\n\t// _No auctions yet — call `List` to open one._\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"54965000","gas_fee":"164895ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"Y8+eSJ2oPacNSv9ETI/qrWYCJV6DGnGJuViL4OS+tIM9XVivMODB7TAH0oFxNnX2XtTLxxdYvkSsI0dN03LtaQ=="}],"memo":""},"metadata":{"timestamp":"1790960956"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"eggling","path":"gno.land/r/moul/x/daily/eggling/v1","files":[{"name":"README.md","body":"# Eggling\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nPlant an on-chain egg, let it incubate for at least 20 blocks, then hatch it — how long you waited plus a bit of sealed-in luck decides whether you get a Common Slime or a Legendary Glimmer. Train hatched creatures for XP and levels, and rename them once they've hatched. It's a lighter, luck-and-patience spin on yesterday's tamagotchi: no hunger or death, just the thrill of the hatch and a slow climb of levels.\n\nBuilt for gno 0.9.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/eggling) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline`, `shortAddr` helpers.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/eggling/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/eggling/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"eggling.gno","body":"// Package eggling is an on-chain egg incubator and creature collector.\n// Plant an egg, let it incubate for a minimum number of blocks, then Hatch\n// it: the longer you waited (and a little luck, seeded from the egg's own\n// history) decides the rarity of the creature you get. Train hatched\n// creatures to level them up. Unlike a tamagotchi there's nothing to feed\n// or lose to neglect — eggling is about patience and the luck of the\n// hatch, not survival.\npackage eggling\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// minIncubation is the minimum number of blocks an egg must sit before it\n// can hatch.\nconst minIncubation int64 = 20\n\n// waitCap is the incubation-time bonus cap (in blocks) used by rarityTier,\n// so waiting forever doesn't guarantee a legendary — it just improves odds.\nconst waitCap int64 = 200\n\nvar speciesNames = [...]string{\n\t\"Slime\", \"Sprout\", \"Ember\", \"Pebble\", \"Breeze\", \"Glimmer\", \"Shade\", \"Coral\",\n}\n\nvar rarityNames = [...]string{\"Common\", \"Uncommon\", \"Rare\", \"Legendary\"}\nvar rarityEmoji = [...]string{\"⚪\", \"🟢\", \"🔵\", \"🟡\"}\n\n// egg is the persisted record for one planted egg, hatched or not.\ntype egg struct {\n\tID         string\n\tOwner      address\n\tPlantedAt  int64\n\tHatched    bool\n\tSpecies    string\n\tRarityTier int\n\tName       string\n\tXP         int\n\tLevel      int\n}\n\nvar (\n\teggs         avl.Tree // id string -\u003e *egg\n\tnextID       int\n\ttotalPlanted int\n\ttotalHatched int\n\trarityCounts [4]int\n)\n\nfunc get(id string) (*egg, bool) {\n\tv := eggs.Get(id)\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*egg), true\n}\n\n// hashSeed hashes the given parts (joined with \":\") to a deterministic hex\n// digest. Used to derive an egg's species and rarity roll from facts\n// already fixed at plant time, so nobody — not even the owner — can game\n// the outcome after the fact.\nfunc hashSeed(parts ...string) string {\n\tsum := sha256.Sum256([]byte(strings.Join(parts, \":\")))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// seedBytes pulls the first two bytes out of a hex digest for use as two\n// independent 0-255 rolls (species pick, rarity roll).\nfunc seedBytes(seedHex string) (byte, byte) {\n\traw, err := hex.DecodeString(seedHex)\n\tif err != nil || len(raw) \u003c 2 {\n\t\treturn 0, 0\n\t}\n\treturn raw[0], raw[1]\n}\n\n// rarityTier turns a 0-255 roll plus the blocks waited into a tier index\n// 0..3 (common..legendary). Waiting longer raises the effective score, so\n// patience improves your odds, but a bad roll can still land common even\n// after a long wait, and a lucky roll can hatch rare almost immediately.\nfunc rarityTier(roll uint8, waitBlocks int64) int {\n\tbonus := waitBlocks\n\tif bonus \u003e waitCap {\n\t\tbonus = waitCap\n\t}\n\tscore := int(roll) + int(bonus)/2\n\tswitch {\n\tcase score \u003e= 300:\n\t\treturn 3\n\tcase score \u003e= 220:\n\t\treturn 2\n\tcase score \u003e= 140:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n// plant is the non-crossing core of PlantEgg.\nfunc plant(owner address, height int64) *egg {\n\tnextID++\n\tid := strconv.Itoa(nextID)\n\te := \u0026egg{ID: id, Owner: owner, PlantedAt: height}\n\teggs.Set(id, e)\n\ttotalPlanted++\n\treturn e\n}\n\n// PlantEgg starts incubating a new egg for the caller. Returns its ID.\nfunc PlantEgg(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te := plant(cur.Previous().Address(), runtime.ChainHeight())\n\treturn \"🥚 planted egg #\" + e.ID + \" — incubate at least \" +\n\t\tstrconv.Itoa(int(minIncubation)) + \" blocks, then Hatch(\\\"\" + e.ID + \"\\\")\"\n}\n\n// hatch is the non-crossing core of Hatch.\nfunc hatch(e *egg, height int64) string {\n\tif e.Hatched {\n\t\tpanic(\"egg #\" + e.ID + \" already hatched into a \" + e.Species)\n\t}\n\twait := height - e.PlantedAt\n\tif wait \u003c minIncubation {\n\t\tpanic(\"egg #\" + e.ID + \" needs \" + strconv.Itoa(int(minIncubation-wait)) + \" more blocks to incubate\")\n\t}\n\n\tseed := hashSeed(e.ID, e.Owner.String(), strconv.FormatInt(e.PlantedAt, 10))\n\trarityRoll, speciesRoll := seedBytes(seed)\n\ttier := rarityTier(rarityRoll, wait)\n\tspecies := speciesNames[int(speciesRoll)%len(speciesNames)]\n\n\te.Hatched = true\n\te.Species = species\n\te.RarityTier = tier\n\te.Name = species\n\te.Level = 1\n\trarityCounts[tier]++\n\ttotalHatched++\n\n\treturn rarityEmoji[tier] + \" egg #\" + e.ID + \" hatched into a \" + rarityNames[tier] + \" \" + species + \"!\"\n}\n\n// Hatch hatches an incubated egg the caller owns.\nfunc Hatch(cur realm, id string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te, ok := get(id)\n\tif !ok {\n\t\tpanic(\"no such egg #\" + id)\n\t}\n\tif e.Owner != cur.Previous().Address() {\n\t\tpanic(\"only the owner can hatch egg #\" + id)\n\t}\n\treturn hatch(e, runtime.ChainHeight())\n}\n\n// train is the non-crossing core of Train.\nfunc train(e *egg) string {\n\tif !e.Hatched {\n\t\tpanic(\"egg #\" + e.ID + \" hasn't hatched yet\")\n\t}\n\te.XP += 10\n\tnewLevel := e.XP/50 + 1\n\tleveled := newLevel \u003e e.Level\n\te.Level = newLevel\n\n\tmsg := e.Name + \" gained 10 XP (\" + strconv.Itoa(e.XP) + \" total)\"\n\tif leveled {\n\t\tmsg += \" and reached level \" + strconv.Itoa(e.Level) + \"!\"\n\t}\n\treturn msg\n}\n\n// Train gives a hatched creature the caller owns some experience, leveling\n// it up every 50 XP.\nfunc Train(cur realm, id string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te, ok := get(id)\n\tif !ok {\n\t\tpanic(\"no such egg #\" + id)\n\t}\n\tif e.Owner != cur.Previous().Address() {\n\t\tpanic(\"only the owner can train egg #\" + id)\n\t}\n\treturn train(e)\n}\n\n// rename is the non-crossing core of Rename.\nfunc rename(e *egg, name string) string {\n\tif !e.Hatched {\n\t\tpanic(\"egg #\" + e.ID + \" hasn't hatched yet — nothing to name\")\n\t}\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tpanic(\"name cannot be empty\")\n\t}\n\told := e.Name\n\te.Name = name\n\treturn old + \" renamed to \" + name\n}\n\n// Rename gives a hatched creature the caller owns a custom name.\nfunc Rename(cur realm, id string, name string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te, ok := get(id)\n\tif !ok {\n\t\tpanic(\"no such egg #\" + id)\n\t}\n\tif e.Owner != cur.Previous().Address() {\n\t\tpanic(\"only the owner can rename egg #\" + id)\n\t}\n\treturn rename(e, name)\n}\n\n// byIDNumeric orders eggs by their numeric ID, ascending.\ntype byIDNumeric []*egg\n\nfunc (r byIDNumeric) Len() int      { return len(r) }\nfunc (r byIDNumeric) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byIDNumeric) Less(i, j int) bool {\n\ta, _ := strconv.Atoi(r[i].ID)\n\tb, _ := strconv.Atoi(r[j].ID)\n\treturn a \u003c b\n}\n\nfunc allEggs() []*egg {\n\tvar rows []*egg\n\teggs.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\trows = append(rows, v.(*egg))\n\t\treturn false\n\t})\n\tsort.Stable(byIDNumeric(rows))\n\treturn rows\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 🥚 Eggling\\n\\n\")\n\tb.WriteString(\"An on-chain egg incubator. `PlantEgg()` to start one, wait at least \" +\n\t\tstrconv.Itoa(int(minIncubation)) + \" blocks, then `Hatch(id)` — the longer you \" +\n\t\t\"waited (plus a little sealed-in luck) decides the rarity of the creature you get. \" +\n\t\t\"`Train(id)` levels a hatched creature up; `Rename(id, name)` gives it a name.\\n\\n\")\n\n\tb.WriteString(\"- Eggs planted: \" + strconv.Itoa(totalPlanted) + \"\\n\")\n\tb.WriteString(\"- Creatures hatched: \" + strconv.Itoa(totalHatched) + \"\\n\")\n\tif totalHatched \u003e 0 {\n\t\tfor tier := 3; tier \u003e= 0; tier-- {\n\t\t\tif rarityCounts[tier] \u003e 0 {\n\t\t\t\tb.WriteString(\"  - \" + rarityEmoji[tier] + \" \" + rarityNames[tier] + \": \" +\n\t\t\t\t\tstrconv.Itoa(rarityCounts[tier]) + \"\\n\")\n\t\t\t}\n\t\t}\n\t}\n\n\trows := allEggs()\n\tb.WriteString(\"\\n## Eggs\\n\\n\")\n\tif len(rows) == 0 {\n\t\tb.WriteString(\"_None planted yet. Be the first!_\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| ID | Owner | Status | Level |\\n\")\n\tb.WriteString(\"| :--- | :--- | :--- | ---: |\\n\")\n\tfor _, e := range rows {\n\t\tstatus := \"🥚 incubating\"\n\t\tlevel := \"-\"\n\t\tif e.Hatched {\n\t\t\tstatus = rarityEmoji[e.RarityTier] + \" \" + ui.Inline(e.Name) + \" (\" + rarityNames[e.RarityTier] + \" \" + e.Species + \")\"\n\t\t\tlevel = strconv.Itoa(e.Level)\n\t\t}\n\t\tb.WriteString(\"| #\" + e.ID + \" | \" + ui.Addr(e.Owner) + \" | \" + status + \" | \" + level + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n_View a single egg at this realm's path plus its ID (e.g. `.../eggling:3`), \" +\n\t\t\"or one owner's eggs plus their address._\\n\")\n\treturn b.String()\n}\n\nfunc renderEgg(id string, height int64) string {\n\te, ok := get(id)\n\tif !ok {\n\t\treturn \"# Egg #\" + ui.Inline(id) + \"\\n\\nNo such egg.\\n\"\n\t}\n\n\tvar b strings.Builder\n\tif !e.Hatched {\n\t\twait := height - e.PlantedAt\n\t\tb.WriteString(\"# 🥚 Egg #\" + e.ID + \"\\n\\n\")\n\t\tb.WriteString(\"- Owner: `\" + e.Owner.String() + \"`\\n\")\n\t\tb.WriteString(\"- Planted at block: \" + strconv.FormatInt(e.PlantedAt, 10) + \"\\n\")\n\t\tif wait \u003c minIncubation {\n\t\t\tb.WriteString(\"- Ready to hatch in: \" + strconv.FormatInt(minIncubation-wait, 10) + \" more blocks\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"- Ready to hatch now — call `Hatch(\\\"\" + e.ID + \"\\\")`\\n\")\n\t\t}\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"# \" + rarityEmoji[e.RarityTier] + \" \" + e.Name + \"\\n\\n\")\n\tb.WriteString(\"- Owner: `\" + e.Owner.String() + \"`\\n\")\n\tb.WriteString(\"- Species: \" + e.Species + \"\\n\")\n\tb.WriteString(\"- Rarity: \" + rarityNames[e.RarityTier] + \"\\n\")\n\tb.WriteString(\"- Level: \" + strconv.Itoa(e.Level) + \" (\" + strconv.Itoa(e.XP) + \" XP)\\n\")\n\treturn b.String()\n}\n\nfunc renderOwner(rawAddr string) string {\n\towner := address(strings.TrimSpace(rawAddr))\n\tsafe := ui.Inline(owner.String())\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Eggs owned by \" + safe + \"\\n\\n\")\n\n\tfound := false\n\tfor _, e := range allEggs() {\n\t\tif e.Owner != owner {\n\t\t\tcontinue\n\t\t}\n\t\tfound = true\n\t\tif e.Hatched {\n\t\t\tb.WriteString(\"- #\" + e.ID + \": \" + rarityEmoji[e.RarityTier] + \" \" + ui.Inline(e.Name) +\n\t\t\t\t\" — \" + rarityNames[e.RarityTier] + \" \" + e.Species + \", level \" + strconv.Itoa(e.Level) + \"\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"- #\" + e.ID + \": 🥚 incubating\\n\")\n\t\t}\n\t}\n\tif !found {\n\t\tb.WriteString(\"_No eggs found for this address._\\n\")\n\t}\n\treturn b.String()\n}\n\n// Render shows the full egg list at \"\", a single egg's detail when path is\n// a numeric ID, or one owner's eggs when path is a bech32 address.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\tif _, err := strconv.Atoi(path); err == nil {\n\t\treturn renderEgg(path, runtime.ChainHeight())\n\t}\n\treturn renderOwner(path)\n}\n"},{"name":"eggling_test.gno","body":"package eggling\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\teggs = avl.Tree{}\n\tnextID = 0\n\ttotalPlanted = 0\n\ttotalHatched = 0\n\trarityCounts = [4]int{}\n}\n\nfunc TestHashSeedDeterministicAndSensitive(t *testing.T) {\n\ta := hashSeed(\"1\", \"g1alice\", \"100\")\n\tb := hashSeed(\"1\", \"g1alice\", \"100\")\n\tif a != b {\n\t\tt.Fatal(\"hashSeed should be deterministic for the same inputs\")\n\t}\n\tif a == hashSeed(\"2\", \"g1alice\", \"100\") {\n\t\tt.Fatal(\"different egg IDs should hash differently\")\n\t}\n\tif len(a) != 64 {\n\t\tt.Fatalf(\"hashSeed length = %d, want 64 (hex sha256)\", len(a))\n\t}\n}\n\nfunc TestSeedBytesFromKnownDigest(t *testing.T) {\n\t// sha256(\"\") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n\tr1, r2 := seedBytes(hashSeed(\"\"))\n\tif r1 != 0xe3 || r2 != 0xb0 {\n\t\tt.Fatalf(\"seedBytes = (%x, %x), want (e3, b0)\", r1, r2)\n\t}\n}\n\nfunc TestRarityTierBoundaries(t *testing.T) {\n\tcases := []struct {\n\t\troll uint8\n\t\twait int64\n\t\twant int\n\t}{\n\t\t{0, 0, 0},     // score 0 -\u003e common\n\t\t{139, 0, 0},   // score 139 -\u003e common\n\t\t{140, 0, 1},   // score 140 -\u003e uncommon\n\t\t{219, 0, 1},   // score 219 -\u003e uncommon\n\t\t{220, 0, 2},   // score 220 -\u003e rare\n\t\t{255, 0, 2},   // score 255 -\u003e rare (no wait bonus)\n\t\t{255, 200, 3}, // score 355 -\u003e legendary (max wait bonus)\n\t\t{0, 200, 0},   // score 100 -\u003e still common, roll matters too\n\t}\n\tfor _, c := range cases {\n\t\tif got := rarityTier(c.roll, c.wait); got != c.want {\n\t\t\tt.Fatalf(\"rarityTier(%d, %d) = %d, want %d\", c.roll, c.wait, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestRarityTierCapsWaitBonus(t *testing.T) {\n\t// waitCap is 200; waiting 1000 blocks should score identically to\n\t// waiting exactly 200.\n\tif rarityTier(50, 1000) != rarityTier(50, 200) {\n\t\tt.Fatal(\"rarityTier should cap the wait bonus at waitCap\")\n\t}\n}\n\nfunc TestPlantAssignsSequentialIDs(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te1 := plant(alice, 100)\n\te2 := plant(alice, 101)\n\tif e1.ID != \"1\" || e2.ID != \"2\" {\n\t\tt.Fatalf(\"expected sequential IDs 1, 2; got %s, %s\", e1.ID, e2.ID)\n\t}\n\tif totalPlanted != 2 {\n\t\tt.Fatalf(\"totalPlanted = %d, want 2\", totalPlanted)\n\t}\n}\n\nfunc TestHatchTooEarlyPanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic hatching before minIncubation blocks pass\")\n\t\t}\n\t}()\n\thatch(e, 100+minIncubation-1)\n}\n\nfunc TestHatchTwicePanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic hatching an already-hatched egg\")\n\t\t}\n\t}()\n\thatch(e, 100+minIncubation)\n}\n\nfunc TestHatchSetsSpeciesAndCountsStats(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\tif !e.Hatched {\n\t\tt.Fatal(\"expected egg to be hatched\")\n\t}\n\tif e.Species == \"\" {\n\t\tt.Fatal(\"expected a species to be assigned\")\n\t}\n\tif e.Level != 1 {\n\t\tt.Fatalf(\"expected level 1 on hatch, got %d\", e.Level)\n\t}\n\tif totalHatched != 1 {\n\t\tt.Fatalf(\"totalHatched = %d, want 1\", totalHatched)\n\t}\n\tif rarityCounts[e.RarityTier] != 1 {\n\t\tt.Fatalf(\"expected rarityCounts[%d] = 1, got %d\", e.RarityTier, rarityCounts[e.RarityTier])\n\t}\n}\n\nfunc TestTrainBeforeHatchPanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic training an unhatched egg\")\n\t\t}\n\t}()\n\ttrain(e)\n}\n\nfunc TestTrainAccumulatesXPAndLevelsUp(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\tfor i := 0; i \u003c 5; i++ {\n\t\ttrain(e)\n\t}\n\tif e.XP != 50 {\n\t\tt.Fatalf(\"XP = %d, want 50\", e.XP)\n\t}\n\tif e.Level != 2 {\n\t\tt.Fatalf(\"Level = %d, want 2\", e.Level)\n\t}\n}\n\nfunc TestRenameRequiresHatchedAndNonEmpty(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Fatal(\"expected panic renaming an unhatched egg\")\n\t\t\t}\n\t\t}()\n\t\trename(e, \"Sparky\")\n\t}()\n\n\thatch(e, 100+minIncubation)\n\trename(e, \"Sparky\")\n\tif e.Name != \"Sparky\" {\n\t\tt.Fatalf(\"Name = %q, want Sparky\", e.Name)\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic renaming with an empty name\")\n\t\t}\n\t}()\n\trename(e, \"   \")\n}\n\nfunc TestRenderShowsEmptyThenEggThenOwner(t *testing.T) {\n\tresetState()\n\tif !strings.Contains(Render(\"\"), \"None planted yet\") {\n\t\tt.Fatal(\"expected empty-state placeholder\")\n\t}\n\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\thome := Render(\"\")\n\tif !strings.Contains(home, \"#\"+e.ID) {\n\t\tt.Fatal(\"expected egg row in home listing\")\n\t}\n\n\tdetail := Render(e.ID)\n\tif !strings.Contains(detail, \"Rarity\") {\n\t\tt.Fatal(\"expected detail card to show rarity\")\n\t}\n\n\towned := Render(alice.String())\n\tif !strings.Contains(owned, e.Name) {\n\t\tt.Fatal(\"expected owner view to list the creature by name\")\n\t}\n}\n\n// TestFullLifecycleViaCrossingCalls smoke-tests the exported, realm-crossing\n// entry points end to end (as an on-chain caller would invoke them).\nfunc TestFullLifecycleViaCrossingCalls(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tmsg := PlantEgg(cross(cur))\n\tif !strings.Contains(msg, \"planted egg #1\") {\n\t\tt.Fatalf(\"expected plant confirmation, got %q\", msg)\n\t}\n\n\ttesting.SkipHeights(minIncubation)\n\n\thatchMsg := Hatch(cross(cur), \"1\")\n\tif !strings.Contains(hatchMsg, \"hatched into a\") {\n\t\tt.Fatalf(\"expected hatch confirmation, got %q\", hatchMsg)\n\t}\n\n\ttrainMsg := Train(cross(cur), \"1\")\n\tif !strings.Contains(trainMsg, \"gained 10 XP\") {\n\t\tt.Fatalf(\"expected train confirmation, got %q\", trainMsg)\n\t}\n\n\trenameMsg := Rename(cross(cur), \"1\", \"Buddy\")\n\tif !strings.Contains(renameMsg, \"renamed to Buddy\") {\n\t\tt.Fatalf(\"expected rename confirmation, got %q\", renameMsg)\n\t}\n\n\te, ok := get(\"1\")\n\tif !ok || e.Name != \"Buddy\" || e.XP != 10 {\n\t\tt.Fatalf(\"unexpected final state: %+v\", e)\n\t}\n}\n\n// TestOnlyOwnerCanHatch checks that another address can't hatch someone\n// else's egg.\nfunc TestOnlyOwnerCanHatch(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPlantEgg(cross(cur))\n\ttesting.SkipHeights(minIncubation)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\trec := revive(func() { Hatch(cross(cur), \"1\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic hatching someone else's egg\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/eggling/v1\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"9000000ugnot"}],"fee":{"gas_wanted":"64764400","gas_fee":"194293ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"caM0cPwJ3zsn+fBpx4f1f24uJexf83VqVz0DH4/mAZ8LyY0/VdKRc9sophZiIG7NtFj9Sq4TdRGMFqdo4ttgDA=="}],"memo":""},"metadata":{"timestamp":"1790960956"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"LKdnP01F2mgEV1E1fb1ct1vDR7pNDzXpHWCWYnpLm6ZMTDYzA9Hl7Jv7r/rsn17tUk713uZIGsDulLpmhCAjVQ=="}],"memo":""},"metadata":{"timestamp":"1790960957"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"eightball","path":"gno.land/r/moul/x/daily/eightball/v1","files":[{"name":"README.md","body":"# 🎱 Magic 8-Ball\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was produced\n\u003e by an MCP-driven agent to exercise the gno MCP server + tooling and to generate\n\u003e test content for gno compilers, linters and formatters. **Not audited. Not for\n\u003e production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\nA classic Magic 8-Ball as a gno.land realm. Ask a yes/no question and the current\n**block height** picks one of the 20 canonical answers — fully deterministic, since\nthere is no true randomness on-chain.\n\n- `Ask(cur realm, question string) string` — records `{caller, question, answer, height}`\n  and returns the answer (crossing function; emits a `Shaken` event).\n- `Asked() int` — how many questions have been asked (read-only).\n- `Render(path string) string` — shows the last answer and a table of recent shakes.\n\nBuilt for the sapphire testnet (gno `0.9`). Example:\n\n```\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/eightball/v0 \\\n  -func Ask -args \"will this PR pass CI?\" ...\n```\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/eightball) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nVisible change: addresses now render in monospace.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/eightball/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eightball/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/eightball/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eightball/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/eightball/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eightball/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/eightball/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eightball/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/eightball/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/eightball/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"eightball.gno","body":"// Package eightball is a Magic 8-Ball realm: ask a yes/no question and the\n// block height decides your fate. Deterministic (no real randomness on-chain).\npackage eightball\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\n// The 20 classic Magic 8-Ball answers.\nvar answers = []string{\n\t\"It is certain.\", \"It is decidedly so.\", \"Without a doubt.\",\n\t\"Yes definitely.\", \"You may rely on it.\", \"As I see it, yes.\",\n\t\"Most likely.\", \"Outlook good.\", \"Yes.\", \"Signs point to yes.\",\n\t\"Reply hazy, try again.\", \"Ask again later.\", \"Better not tell you now.\",\n\t\"Cannot predict now.\", \"Concentrate and ask again.\",\n\t\"Don't count on it.\", \"My reply is no.\", \"My sources say no.\",\n\t\"Outlook not so good.\", \"Very doubtful.\",\n}\n\ntype shake struct {\n\tasker    string\n\tquestion string\n\tanswer   string\n\theight   int64\n}\n\nvar history []shake\n\n// answerIndex maps (block height, prior shakes) to an answer slot. Pure and\n// deterministic so it can be tested without touching realm state.\nfunc answerIndex(height int64, n int) int {\n\ti := (height + int64(n)) % int64(len(answers))\n\tif i \u003c 0 {\n\t\ti += int64(len(answers))\n\t}\n\treturn int(i)\n}\n\n// Ask poses a question to the Magic 8-Ball and returns its answer. Crossing\n// function: it mutates persistent state, so it takes `cur realm` (gno 0.9).\nfunc Ask(cur realm, question string) string {\n\tquestion = strings.TrimSpace(question)\n\tif question == \"\" {\n\t\tpanic(\"question must not be empty\")\n\t}\n\tif len(question) \u003e 200 {\n\t\tpanic(\"question too long (max 200 chars)\")\n\t}\n\th := runtime.ChainHeight()\n\tans := answers[answerIndex(h, len(history))]\n\thistory = append(history, shake{\n\t\tasker:    unsafe.PreviousRealm().Address().String(),\n\t\tquestion: question,\n\t\tanswer:   ans,\n\t\theight:   h,\n\t})\n\tchain.Emit(\"Shaken\", \"answer\", ans, \"height\", strconv.FormatInt(h, 10))\n\treturn ans\n}\n\n// Asked returns how many questions have been asked. Read-only.\nfunc Asked() int { return len(history) }\n\n// Render is the gnoweb Markdown view.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 🎱 Magic 8-Ball\\n\\n\")\n\tb.WriteString(\"\u003e ⚠️ Experimental, auto-generated with no human supervision (MCP test corpus). \")\n\tb.WriteString(\"Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\\n\\n\")\n\tb.WriteString(\"Ask a yes/no question — the block height decides your fate.\\n\\n\")\n\tb.WriteString(\"**Questions asked:** \")\n\tb.WriteString(strconv.Itoa(len(history)))\n\tb.WriteString(\"\\n\\n\")\n\n\tif len(history) == 0 {\n\t\tb.WriteString(\"_No questions yet. Call `Ask(\\\"will it rain tomorrow?\\\")`._\\n\")\n\t\treturn b.String()\n\t}\n\n\tlast := history[len(history)-1]\n\tb.WriteString(\"Last shake: 🎱 _\")\n\tb.WriteString(last.answer)\n\tb.WriteString(\"_\\n\\n| # | asker | question | answer | height |\\n\")\n\tb.WriteString(\"|---|---|---|---|---|\\n\")\n\n\tstart := len(history) - 1\n\tend := start - 14\n\tif end \u003c 0 {\n\t\tend = 0\n\t}\n\tfor i := start; i \u003e= end; i-- {\n\t\te := history[i]\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(strconv.Itoa(i + 1))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(ui.AddrOf(e.asker))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(e.question)\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(e.answer)\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.FormatInt(e.height, 10))\n\t\tb.WriteString(\" |\\n\")\n\t}\n\treturn b.String()\n}\n"},{"name":"eightball_test.gno","body":"package eightball\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestAnswerIndexInRange(t *testing.T) {\n\tcases := []struct {\n\t\theight int64\n\t\tn      int\n\t}{\n\t\t{0, 0}, {1, 0}, {19, 0}, {20, 0}, {21, 5},\n\t\t{999999, 3}, {-1, 0}, {-1000, 7},\n\t}\n\tfor _, c := range cases {\n\t\tidx := answerIndex(c.height, c.n)\n\t\tuassert.True(t, idx \u003e= 0 \u0026\u0026 idx \u003c len(answers),\n\t\t\t\"index out of range for height=\"+itoa(c.height))\n\t}\n}\n\nfunc TestAnswerIndexDeterministic(t *testing.T) {\n\tuassert.Equal(t, answerIndex(42, 3), answerIndex(42, 3), \"same inputs, same slot\")\n}\n\nfunc TestRenderEmpty(t *testing.T) {\n\tout := Render(\"\")\n\tuassert.NotEmpty(t, out, \"render must not be empty\")\n\tuassert.True(t, len(answers) == 20, \"classic 8-ball has 20 answers\")\n}\n\nfunc itoa(n int64) string {\n\tneg := n \u003c 0\n\tif neg {\n\t\tn = -n\n\t}\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b [24]byte\n\ti := len(b)\n\tfor n \u003e 0 {\n\t\ti--\n\t\tb[i] = byte('0' + n%10)\n\t\tn /= 10\n\t}\n\tif neg {\n\t\ti--\n\t\tb[i] = '-'\n\t}\n\treturn string(b[i:])\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/eightball/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package eightball\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # 🎱 Magic 8-Ball\n\t//\n\t// \u003e ⚠️ Experimental, auto-generated with no human supervision (MCP test corpus). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\t//\n\t// Ask a yes/no question — the block height decides your fate.\n\t//\n\t// **Questions asked:** 0\n\t//\n\t// _No questions yet. Call `Ask(\"will it rain tomorrow?\")`._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"33790600","gas_fee":"101371ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"+T4dr8b+UeeaItI+ojcKFHWY/Wn9Yuptro2F+/t8yIpUgWLbgRT665Q9P3QYSefobB1g2qOVYeBZojniafW/Vg=="}],"memo":""},"metadata":{"timestamp":"1790961011"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"englishauction","path":"gno.land/r/moul/x/daily/englishauction/v1","files":[{"name":"README.md","body":"# English Auction\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nAn idiomatic gno.land port of the classic Solidity **English (ascending-bid)\nauction**. It ports the core mechanics — a seller opens an auction, bidders\nsubmit strictly increasing bids, the displaced top bid becomes refundable, and\nafter a block deadline anyone can settle it — into a single realm that hosts\nmany concurrent auctions.\n\nSolidity's `msg.sender` maps to `unsafe.PreviousRealm().Address()`, `block.number`\nto `runtime.ChainHeight()`, `require` to `panic`, and events to `chain.Emit`.\nThere is no real coin transfer: bid amounts and refunds are tracked as plain\n`uint64` accounting in ordered `avl.Tree`s (mirroring Solidity's `pendingReturns`\nwithdraw pattern). Auctions and pending refunds are keyed so `Render` can iterate\ndeterministically.\n\n## Transactions\n\n- `Start(cur, item string, durationBlocks int64) int64` — open an auction (caller\n  becomes the seller); ends at `ChainHeight() + durationBlocks`. Returns the id.\n- `Bid(cur, id int64, amount uint64)` — bid; must strictly exceed the current\n  highest. The prior top bid becomes refundable.\n- `Withdraw(cur, id int64) uint64` — reclaim your displaced bids for an auction.\n- `End(cur, id int64)` — after the deadline, award the item to the top bidder.\n\n## Example calls\n\n```\n# open a 100-block auction for a painting -\u003e returns id 1\nStart(\"Vintage painting\", 100)\n\n# two bidders compete (amounts are accounting units, not real coins)\nBid(1, 500)     # alice\nBid(1, 750)     # bob outbids -\u003e alice's 500 is now refundable\nWithdraw(1)     # alice reclaims 500\n\n# once ChainHeight() \u003e= endHeight, anyone settles it\nEnd(1)          # item awarded to bob at 750\n```\n\nVisit the realm to see the live table of auctions: item, highest bid + bidder,\nblocks remaining or ended, and the winner.\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`Auction` loses its `ID` field, which the store now owns, and the local\n`mustGet` becomes one line: the store's labelled `MustGet` panics\n`englishauction: auction #7 not found` where `v0` said only\n`englishauction: no such auction`.\n\n`pending`, the refund ledger, keeps its own tree and its composite\n`\"\u003cid\u003e:\u003caddr\u003e\"` key, now built from the plain decimal id instead of the padded\none. It is only ever point-read, never iterated, so it needs a readable key and\nnot an ordered one. Auction ids already started at 1, so nothing shifts.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/englishauction) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/englishauction/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/englishauction/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/englishauction/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/englishauction/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/englishauction/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/englishauction/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/englishauction/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/englishauction/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/englishauction/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/englishauction/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"englishauction.gno","body":"// Package englishauction is an idiomatic gno.land port of the classic Solidity\n// English (ascending-bid) auction. Anyone can Start an auction for a named item\n// with a duration in blocks; bidders call Bid with a strictly increasing amount.\n// The previous highest bid becomes refundable (claim it with Withdraw). After\n// the auction's end height anyone may call End, awarding the item to the highest\n// bidder. Auctions and pending refunds live in ordered avl trees so Render can\n// iterate deterministically.\npackage englishauction\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Auction is a single ascending-bid auction. It carries no ID field: the id\n// belongs to the store, which hands it back on lookup and iteration.\ntype Auction struct {\n\tSeller        address\n\tItem          string\n\tEndHeight     int64\n\tHighestBid    uint64\n\tHighestBidder address\n\tEnded         bool\n}\n\nvar (\n\t// auctions assigns the auction ids. v0 kept its own nextID plus a key()\n\t// that zero-padded to width 12, which stopped ordering Render past 10^12.\n\tauctions = store.Named(\"englishauction: auction\")\n\n\tpending avl.Tree // \"\u003cid\u003e:\u003caddr\u003e\" -\u003e uint64 refundable amount\n)\n\n// pendKey formats the refund key for a given auction id and bidder. It uses\n// the decimal id rather than the store key: pending is only ever point-read,\n// never iterated, so it needs a readable key and not an ordered one.\nfunc pendKey(id int64, bidder address) string {\n\treturn strconv.FormatInt(id, 10) + \":\" + bidder.String()\n}\n\n// Start opens a new auction for `item` running for `durationBlocks` blocks from\n// the current height. The caller becomes the seller. Returns the auction id.\nfunc Start(cur realm, item string, durationBlocks int64) int64 {\n\tif item == \"\" {\n\t\tpanic(\"englishauction: item must not be empty\")\n\t}\n\tif durationBlocks \u003c= 0 {\n\t\tpanic(\"englishauction: duration must be \u003e 0 blocks\")\n\t}\n\tseller := unsafe.PreviousRealm().Address()\n\ta := \u0026Auction{\n\t\tSeller:    seller,\n\t\tItem:      item,\n\t\tEndHeight: runtime.ChainHeight() + durationBlocks,\n\t}\n\tid := int64(auctions.Add(a))\n\n\tchain.Emit(\"Start\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"seller\", seller.String(),\n\t\t\"item\", item,\n\t\t\"endHeight\", strconv.FormatInt(a.EndHeight, 10),\n\t)\n\treturn id\n}\n\n// Bid places a bid of `amount` on auction `id`. It must strictly exceed the\n// current highest bid. The displaced highest bid becomes refundable to its\n// bidder via Withdraw.\nfunc Bid(cur realm, id int64, amount uint64) {\n\ta := mustGet(id)\n\tif a.Ended || runtime.ChainHeight() \u003e= a.EndHeight {\n\t\tpanic(\"englishauction: auction has ended\")\n\t}\n\tif amount \u003c= a.HighestBid {\n\t\tpanic(\"englishauction: bid must strictly exceed current highest\")\n\t}\n\tbidder := unsafe.PreviousRealm().Address()\n\tif bidder == a.Seller {\n\t\tpanic(\"englishauction: seller cannot bid\")\n\t}\n\n\t// The prior top bid becomes refundable (accumulate in case of repeats).\n\tif a.HighestBid \u003e 0 {\n\t\tpk := pendKey(id, a.HighestBidder)\n\t\tpending.Set(pk, pendingOf(id, a.HighestBidder)+a.HighestBid)\n\t}\n\n\ta.HighestBid = amount\n\ta.HighestBidder = bidder\n\n\tchain.Emit(\"Bid\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"bidder\", bidder.String(),\n\t\t\"amount\", strconv.FormatUint(amount, 10),\n\t)\n}\n\n// Withdraw refunds the caller's accumulated displaced bids for auction `id`.\n// Returns the amount refunded (0 if nothing pending).\nfunc Withdraw(cur realm, id int64) uint64 {\n\tmustGet(id) // ensure auction exists\n\tcaller := unsafe.PreviousRealm().Address()\n\tamount := pendingOf(id, caller)\n\tif amount == 0 {\n\t\treturn 0\n\t}\n\tpending.Remove(pendKey(id, caller))\n\tchain.Emit(\"Withdraw\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"bidder\", caller.String(),\n\t\t\"amount\", strconv.FormatUint(amount, 10),\n\t)\n\treturn amount\n}\n\n// End closes auction `id` once its end height is reached, awarding the item to\n// the highest bidder (if any). Anyone may call it.\nfunc End(cur realm, id int64) {\n\ta := mustGet(id)\n\tif a.Ended {\n\t\tpanic(\"englishauction: auction already ended\")\n\t}\n\tif runtime.ChainHeight() \u003c a.EndHeight {\n\t\tpanic(\"englishauction: auction not yet over\")\n\t}\n\ta.Ended = true\n\n\tchain.Emit(\"End\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"winner\", a.HighestBidder.String(),\n\t\t\"amount\", strconv.FormatUint(a.HighestBid, 10),\n\t)\n}\n\n// --- read-only helpers (safe from tests and Render) ---\n\n// mustGet returns the auction for `id`, panicking if it does not exist. The\n// store's label puts the id in the message, which v0's fixed string\n// (\"englishauction: no such auction\") left out.\nfunc mustGet(id int64) *Auction {\n\treturn auctions.MustGet(store.ID(id)).(*Auction)\n}\n\n// pendingOf returns the refundable amount owed to `bidder` for auction `id`.\nfunc pendingOf(id int64, bidder address) uint64 {\n\tv := pending.Get(pendKey(id, bidder))\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(uint64)\n}\n\n// blocksLeft returns how many blocks remain before `a` can be ended (0 if the\n// end height has been reached).\nfunc blocksLeft(a *Auction, height int64) int64 {\n\tif height \u003e= a.EndHeight {\n\t\treturn 0\n\t}\n\treturn a.EndHeight - height\n}\n\n// hasWinner reports whether the auction received at least one bid.\nfunc hasWinner(a *Auction) bool {\n\treturn a.HighestBid \u003e 0\n}\n\n// Render lists every auction with item, top bid + bidder, time left, and winner.\nfunc Render(path string) string {\n\tout := \"# English Auction\\n\\n\"\n\tout += \"Ascending-bid auctions. Start one, outbid others, and End it after \"\n\tout += \"its block deadline to award the item to the top bidder.\\n\\n\"\n\n\tif auctions.Len() == 0 {\n\t\tout += \"_No auctions yet. Call `Start` to open one._\\n\"\n\t\treturn out\n\t}\n\n\theight := runtime.ChainHeight()\n\tout += \"_Current block height: \" + strconv.FormatInt(height, 10) + \"_\\n\\n\"\n\tout += \"| ID | Item | Highest Bid | Bidder | Status | Winner |\\n\"\n\tout += \"|---:|------|------------:|--------|--------|--------|\\n\"\n\n\tauctions.Each(func(id store.ID, v any) {\n\t\ta := v.(*Auction)\n\n\t\tbidStr := \"—\"\n\t\tbidderStr := \"—\"\n\t\tif hasWinner(a) {\n\t\t\tbidStr = strconv.FormatUint(a.HighestBid, 10)\n\t\t\tbidderStr = \"`\" + a.HighestBidder.String() + \"`\"\n\t\t}\n\n\t\tstatus := \"\"\n\t\twinner := \"—\"\n\t\tswitch {\n\t\tcase a.Ended:\n\t\t\tstatus = \"ended\"\n\t\t\tif hasWinner(a) {\n\t\t\t\twinner = \"`\" + a.HighestBidder.String() + \"`\"\n\t\t\t} else {\n\t\t\t\twinner = \"no bids\"\n\t\t\t}\n\t\tcase height \u003e= a.EndHeight:\n\t\t\tstatus = \"awaiting End\"\n\t\tdefault:\n\t\t\tstatus = strconv.FormatInt(blocksLeft(a, height), 10) + \" blocks left\"\n\t\t}\n\n\t\tout += \"| \" + id.String() + \" | \" + a.Item + \" | \" +\n\t\t\tbidStr + \" | \" + bidderStr + \" | \" + status + \" | \" + winner + \" |\\n\"\n\t})\n\treturn out\n}\n"},{"name":"englishauction_test.gno","body":"package englishauction\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// v0 asserted that its own key() padded to width 12, and built pendKey on top\n// of it. The auction key is now the store's, which has no width to outgrow;\n// pending is only point-read, so its key is the plain decimal id.\nfunc TestKeyAndPendKey(t *testing.T) {\n\tuassert.True(t, store.ID(2).Key() \u003c store.ID(10).Key())\n\tuassert.True(t, store.ID(999999999999).Key() \u003c store.ID(1000000000000).Key(),\n\t\t\"one past v0's width-12 ceiling\")\n\n\taddr := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tuassert.Equal(t, \"7:\"+addr.String(), pendKey(7, addr))\n}\n\nfunc TestBlocksLeftAndWinner(t *testing.T) {\n\ta := \u0026Auction{Item: \"vase\", EndHeight: 100}\n\n\t// before the deadline, blocks remain and there is no winner yet.\n\tuassert.Equal(t, int64(40), blocksLeft(a, 60))\n\tuassert.Equal(t, int64(1), blocksLeft(a, 99))\n\tuassert.False(t, hasWinner(a))\n\n\t// at/after the deadline, no blocks remain.\n\tuassert.Equal(t, int64(0), blocksLeft(a, 100))\n\tuassert.Equal(t, int64(0), blocksLeft(a, 150))\n\n\t// a recorded bid makes it a winner.\n\ta.HighestBid = 500\n\ta.HighestBidder = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tuassert.True(t, hasWinner(a))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/englishauction/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package englishauction\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # English Auction\n\t//\n\t// Ascending-bid auctions. Start one, outbid others, and End it after its block deadline to award the item to the top bidder.\n\t//\n\t// _No auctions yet. Call `Start` to open one._\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"46317400","gas_fee":"138952ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"Y7htW8bJQYj7sknLwZgem72keJWxX3uLbCdwLwJeCAg0VdivT3z2kiFU08PDvFTWy5e2T44tY/HEYoMAS9NcyA=="}],"memo":""},"metadata":{"timestamp":"1790961015"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"erc1155","path":"gno.land/r/moul/x/daily/erc1155/v0","files":[{"name":"README.md","body":"# erc1155\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nAn idiomatic gno.land port of the Solidity **ERC-1155** multi-token standard.\nOne realm manages many distinct token ids, each with independent fungible\nbalances tracked in an `avl.Tree` keyed by `(owner, id)`, plus a per-id total\nsupply. It keeps the core ERC-1155 ideas — minting, single transfers, balance\nand supply queries, and events — while dropping the Solidity-specific machinery\n(operator approvals, safe-transfer callbacks) that has no analog on gno.land.\n\n## Transactions\n\n- `Mint(cur realm, to address, id int, amount uint64)` — mint `amount` of token\n  `id` to `to`; increases that id's total supply.\n- `TransferSingle(cur realm, to address, id int, amount uint64)` — move `amount`\n  of token `id` from the caller to `to`.\n\n## Read-only\n\n- `BalanceOf(owner address, id int) uint64` — balance of one owner for one id.\n- `TotalSupply(id int) uint64` — total minted for a given id.\n- `Render(path string)` — Markdown balances table (owner · id · amount) and a\n  per-id supply table.\n\n## Example\n\n```\nMint(cur, g1owner..., 1, 100)      // 100 units of token #1 to g1owner\nMint(cur, g1owner..., 2, 5)        // 5 units of token #2\nTransferSingle(cur, g1other..., 1, 40)  // caller sends 40 of token #1\nBalanceOf(g1owner..., 1)           // -\u003e 60\nTotalSupply(1)                     // -\u003e 100\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/erc1155/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc1155/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/erc1155/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc1155/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/erc1155/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc1155/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/erc1155/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc1155/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/erc1155/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/erc1155/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"erc1155.gno","body":"// Package erc1155 is an idiomatic gno.land port of the Solidity ERC-1155\n// multi-token standard. A single realm tracks many distinct token ids, each\n// with its own fungible balances. Balances are keyed by (owner, id) in an\n// avl.Tree so Render can iterate deterministically.\npackage erc1155\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// balances maps \"\u003cowner\u003e:\u003cid\u003e\" -\u003e uint64 amount.\nvar balances avl.Tree\n\n// supply maps \"\u003cid\u003e\" -\u003e uint64 total minted for that id.\nvar supply avl.Tree\n\nfunc balKey(owner address, id int) string {\n\treturn owner.String() + \":\" + strconv.Itoa(id)\n}\n\nfunc supKey(id int) string {\n\treturn strconv.Itoa(id)\n}\n\nfunc getBalance(owner address, id int) uint64 {\n\tk := balKey(owner, id)\n\tif !balances.Has(k) {\n\t\treturn 0\n\t}\n\treturn balances.Get(k).(uint64)\n}\n\nfunc setBalance(owner address, id int, amount uint64) {\n\tk := balKey(owner, id)\n\tif amount == 0 {\n\t\tbalances.Remove(k)\n\t\treturn\n\t}\n\tbalances.Set(k, amount)\n}\n\nfunc getSupply(id int) uint64 {\n\tk := supKey(id)\n\tif !supply.Has(k) {\n\t\treturn 0\n\t}\n\treturn supply.Get(k).(uint64)\n}\n\n// Mint creates `amount` units of token `id` and credits them to `to`.\nfunc Mint(cur realm, to address, id int, amount uint64) {\n\tif !to.IsValid() {\n\t\tpanic(\"erc1155: mint to invalid address\")\n\t}\n\tif amount == 0 {\n\t\tpanic(\"erc1155: mint amount must be \u003e 0\")\n\t}\n\tsetBalance(to, id, getBalance(to, id)+amount)\n\tsupply.Set(supKey(id), getSupply(id)+amount)\n\n\toperator := unsafe.PreviousRealm().Address()\n\tchain.Emit(\"Mint\",\n\t\t\"operator\", operator.String(),\n\t\t\"to\", to.String(),\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"amount\", strconv.FormatUint(amount, 10),\n\t)\n}\n\n// TransferSingle moves `amount` of token `id` from the caller to `to`.\nfunc TransferSingle(cur realm, to address, id int, amount uint64) {\n\tif !to.IsValid() {\n\t\tpanic(\"erc1155: transfer to invalid address\")\n\t}\n\tif amount == 0 {\n\t\tpanic(\"erc1155: transfer amount must be \u003e 0\")\n\t}\n\tfrom := unsafe.PreviousRealm().Address()\n\tfromBal := getBalance(from, id)\n\tif fromBal \u003c amount {\n\t\tpanic(\"erc1155: insufficient balance\")\n\t}\n\tsetBalance(from, id, fromBal-amount)\n\tsetBalance(to, id, getBalance(to, id)+amount)\n\n\tchain.Emit(\"TransferSingle\",\n\t\t\"from\", from.String(),\n\t\t\"to\", to.String(),\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"amount\", strconv.FormatUint(amount, 10),\n\t)\n}\n\n// BalanceOf returns the amount of token `id` held by `owner`.\nfunc BalanceOf(owner address, id int) uint64 {\n\treturn getBalance(owner, id)\n}\n\n// TotalSupply returns the total amount minted of token `id`.\nfunc TotalSupply(id int) uint64 {\n\treturn getSupply(id)\n}\n\n// Render prints a balances table and a per-id supply table.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# ERC-1155 Multi-Token\\n\\n\")\n\tb.WriteString(\"A single realm holding many fungible token ids. \")\n\tb.WriteString(\"Balances are keyed by `(owner, id)`.\\n\\n\")\n\n\tb.WriteString(\"## Balances\\n\\n\")\n\tif balances.Size() == 0 {\n\t\tb.WriteString(\"_No balances yet. Call `Mint` to create tokens._\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| Owner | ID | Amount |\\n\")\n\t\tb.WriteString(\"|---|---|---|\\n\")\n\t\tbalances.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\t\towner, id := splitBalKey(key)\n\t\t\tb.WriteString(\"| `\" + owner + \"` | \" + id + \" | \" +\n\t\t\t\tstrconv.FormatUint(value.(uint64), 10) + \" |\\n\")\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"## Supply per ID\\n\\n\")\n\tif supply.Size() == 0 {\n\t\tb.WriteString(\"_No tokens minted._\\n\")\n\t} else {\n\t\tb.WriteString(\"| ID | Total Supply |\\n\")\n\t\tb.WriteString(\"|---|---|\\n\")\n\t\tsupply.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\t\tb.WriteString(\"| \" + key + \" | \" +\n\t\t\t\tstrconv.FormatUint(value.(uint64), 10) + \" |\\n\")\n\t\t\treturn false\n\t\t})\n\t}\n\n\treturn b.String()\n}\n\n// splitBalKey splits a \"\u003cowner\u003e:\u003cid\u003e\" balance key. The owner (a bech32\n// address) contains no ':', so the id is the substring after the last ':'.\nfunc splitBalKey(key string) (owner, id string) {\n\ti := strings.LastIndex(key, \":\")\n\tif i \u003c 0 {\n\t\treturn key, \"\"\n\t}\n\treturn key[:i], key[i+1:]\n}\n"},{"name":"erc1155_test.gno","body":"package erc1155\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestSplitBalKey(t *testing.T) {\n\tcases := []struct {\n\t\tkey       string\n\t\twantOwner string\n\t\twantID    string\n\t}{\n\t\t{\"g1abcxyz:0\", \"g1abcxyz\", \"0\"},\n\t\t{\"g1abcxyz:42\", \"g1abcxyz\", \"42\"},\n\t\t{\"g1def:1\", \"g1def\", \"1\"},\n\t\t{\"noseparator\", \"noseparator\", \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\towner, id := splitBalKey(tc.key)\n\t\tuassert.Equal(t, tc.wantOwner, owner)\n\t\tuassert.Equal(t, tc.wantID, id)\n\t}\n}\n\nfunc TestKeyHelpers(t *testing.T) {\n\taddr := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tuassert.Equal(t, addr.String()+\":7\", balKey(addr, 7))\n\tuassert.Equal(t, \"7\", supKey(7))\n\tuassert.Equal(t, \"0\", supKey(0))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/erc1155/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package erc1155\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # ERC-1155 Multi-Token\n\t//\n\t// A single realm holding many fungible token ids. Balances are keyed by `(owner, id)`.\n\t//\n\t// ## Balances\n\t//\n\t// _No balances yet. Call `Mint` to create tokens._\n\t//\n\t// ## Supply per ID\n\t//\n\t// _No tokens minted._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"33405800","gas_fee":"100217ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"ZPxaJrqkjCRIRrIfizNKBiE+vJE+1iJH+RC1vIh+TmspjJXry6AvPQWHRWNhVeExOR/mobtt8KxcIHkOXLQ0Og=="}],"memo":""},"metadata":{"timestamp":"1790961015"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"erc721","path":"gno.land/r/moul/x/daily/erc721/v1","files":[{"name":"README.md","body":"# erc721 — NFT (ERC-721 port)\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nAn idiomatic gno.land port of the Solidity **ERC-721** non-fungible token\nstandard. Each token is a unique, sequentially-minted integer id owned by\nexactly one address. Ownership, per-owner balances and single-token approvals\nlive in ordered `avl.Tree`s, so `Render` can list every token deterministically.\n`msg.sender` maps to `unsafe.PreviousRealm().Address()`, `require` to `panic`,\nand Solidity events to `chain.Emit` (`Mint`, `Transfer`, `Approval`).\n\n## Transactions\n- `Mint(cur realm, to address) int64` — mint the next token id to `to`; returns the id.\n- `Transfer(cur realm, to address, id int64)` — move a token you own (or are approved for) to `to`; clears the approval.\n- `Approve(cur realm, spender address, id int64)` — owner grants `spender` the right to transfer token `id`.\n\n## Read-only\n- `OwnerOf(id int64) address` — owner of a token (panics if it does not exist).\n- `BalanceOf(owner address) uint64` — number of tokens held by `owner`.\n- `TotalSupply() int64` — total tokens in circulation.\n- `Render(path string)` — Markdown: total supply + a token → owner → approved table.\n\n## Example\n```\nMint(cur, g1alice...)          // -\u003e tokenID 1\nMint(cur, g1alice...)          // -\u003e tokenID 2\nApprove(cur, g1bob..., 1)      // alice approves bob for token 1\nTransfer(cur, g1carol..., 1)   // owner alice sends token 1 to carol\nOwnerOf(1)                     // -\u003e g1carol...\nBalanceOf(g1alice...)          // -\u003e 1\nTotalSupply()                  // -\u003e 2\n```\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\n`v0` padded token ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`approvals`, the secondary index on the same ids, is keyed with `store.ID.Key()`\nso the two trees cannot drift apart. `balances` keeps its own address-keyed\ntree, which the store does not cover. `minted` is gone: with no burn, the\nhighest id ever assigned *is* the supply, so `LastID()` answers it.\n\nToken ids stay plain integers and the rendered output is unchanged. This is a\nstorage change, which under this repo's versioning rule is a compatibility\nchange, hence a new version rather than an edit in place. [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/erc721) stays\nlive and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/erc721/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc721/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/erc721/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc721/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/erc721/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc721/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/erc721/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/erc721/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/erc721/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/erc721/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"erc721.gno","body":"// Package erc721 is an idiomatic gno.land port of the Solidity ERC-721\n// non-fungible token standard. Each token has a unique integer id owned by\n// exactly one address; ids are minted sequentially. Ownership, per-owner\n// balances and single-token approvals are kept in ordered avl trees so that\n// Render can iterate deterministically.\npackage erc721\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst (\n\tname   = \"Gno NFT\"\n\tsymbol = \"GNFT\"\n)\n\nvar (\n\t// owners assigns the token ids. v0 kept its own nextID plus a key() that\n\t// zero-padded to width 12; the store keys by seqid, so the iteration order\n\t// Render depends on is numeric for every uint64 rather than up to 10^12.\n\towners = store.Named(\"erc721: token\") // tokenID -\u003e address\n\n\tbalances  avl.Tree // owner address (string) -\u003e uint64\n\tapprovals avl.Tree // tokenID (store key) -\u003e approved address\n)\n\n// Mint creates the next token id and assigns it to `to`. Only sequential\n// minting is supported (id is returned via the Mint event).\nfunc Mint(cur realm, to address) int64 {\n\tif !to.IsValid() {\n\t\tpanic(\"erc721: mint to invalid address\")\n\t}\n\tid := int64(owners.Add(to))\n\tbalances.Set(to.String(), balanceOf(to)+1)\n\n\tchain.Emit(\"Mint\", \"to\", to.String(), \"tokenID\", strconv.FormatInt(id, 10))\n\treturn id\n}\n\n// Transfer moves token `id` from the caller to `to`. The caller must own the\n// token (approvals are cleared on transfer).\nfunc Transfer(cur realm, to address, id int64) {\n\tif !to.IsValid() {\n\t\tpanic(\"erc721: transfer to invalid address\")\n\t}\n\tcaller := unsafe.PreviousRealm().Address()\n\tfrom := ownerOf(id) // panics if the token does not exist\n\n\tif caller != from {\n\t\t// allow the single-token approved operator too\n\t\tif approvedOf(id) != caller {\n\t\t\tpanic(\"erc721: caller is neither owner nor approved\")\n\t\t}\n\t}\n\tif from == to {\n\t\tpanic(\"erc721: transfer to current owner\")\n\t}\n\n\towners.Set(store.ID(id), to)\n\tbalances.Set(from.String(), balanceOf(from)-1)\n\tbalances.Set(to.String(), balanceOf(to)+1)\n\tapprovals.Remove(store.ID(id).Key()) // clear approval on transfer\n\n\tchain.Emit(\"Transfer\", \"from\", from.String(), \"to\", to.String(),\n\t\t\"tokenID\", strconv.FormatInt(id, 10))\n}\n\n// Approve grants `spender` the right to transfer token `id`. Only the current\n// owner may approve.\nfunc Approve(cur realm, spender address, id int64) {\n\tcaller := unsafe.PreviousRealm().Address()\n\towner := ownerOf(id)\n\tif caller != owner {\n\t\tpanic(\"erc721: approve caller is not owner\")\n\t}\n\tapprovals.Set(store.ID(id).Key(), spender)\n\tchain.Emit(\"Approval\", \"owner\", owner.String(), \"spender\", spender.String(),\n\t\t\"tokenID\", strconv.FormatInt(id, 10))\n}\n\n// --- read-only helpers (safe to call from tests and Render) ---\n\n// ownerOf returns the owner of token `id`, panicking if it does not exist.\n// The store's label puts the id in the message, which v0's fixed string\n// (\"erc721: query for nonexistent token\") left out.\nfunc ownerOf(id int64) address {\n\treturn owners.MustGet(store.ID(id)).(address)\n}\n\n// approvedOf returns the approved address for token `id`, or the zero address.\nfunc approvedOf(id int64) address {\n\tv := approvals.Get(store.ID(id).Key())\n\tif v == nil {\n\t\treturn address(\"\")\n\t}\n\treturn v.(address)\n}\n\n// balanceOf returns how many tokens `owner` holds.\nfunc balanceOf(owner address) uint64 {\n\tv := balances.Get(owner.String())\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(uint64)\n}\n\n// exists reports whether token `id` has been minted (and not since moved away).\nfunc exists(id int64) bool {\n\treturn owners.Has(store.ID(id))\n}\n\n// totalSupply returns the number of tokens in circulation. There is no burn,\n// so the highest id ever assigned is the count.\nfunc totalSupply() int64 { return int64(owners.LastID()) }\n\n// OwnerOf is the exported read-only accessor for ownerOf.\nfunc OwnerOf(id int64) address { return ownerOf(id) }\n\n// BalanceOf is the exported read-only accessor for balanceOf.\nfunc BalanceOf(owner address) uint64 { return balanceOf(owner) }\n\n// TotalSupply is the exported read-only accessor for totalSupply.\nfunc TotalSupply() int64 { return totalSupply() }\n\n// Render displays collection metadata and a token -\u003e owner table.\nfunc Render(path string) string {\n\tout := \"# \" + name + \" (\" + symbol + \")\\n\\n\"\n\tout += \"**Total supply:** \" + strconv.FormatInt(totalSupply(), 10) + \"\\n\\n\"\n\n\tif owners.Len() == 0 {\n\t\tout += \"_No tokens minted yet._\\n\"\n\t\treturn out\n\t}\n\n\tout += \"| Token ID | Owner | Approved |\\n\"\n\tout += \"|---------:|-------|----------|\\n\"\n\towners.Each(func(id store.ID, v any) {\n\t\towner := v.(address)\n\t\tappr := approvedOf(int64(id))\n\t\tapprStr := \"—\"\n\t\tif appr != address(\"\") {\n\t\t\tapprStr = appr.String()\n\t\t}\n\t\tout += \"| \" + id.String() + \" | \" +\n\t\t\towner.String() + \" | \" + apprStr + \" |\\n\"\n\t})\n\treturn out\n}\n"},{"name":"erc721_test.gno","body":"package erc721\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// v0 asserted that its own key() padded to width 12. That rule held only below\n// the width: key(10^12) is 13 characters and sorts before key(10^12-1), so the\n// token table would have rendered out of order from that id on. The store key\n// has no width to outgrow, which is what this replaces it with.\nfunc TestTokenKeysSortNumericallyPastTheOldWidth(t *testing.T) {\n\tuassert.True(t, store.ID(2).Key() \u003c store.ID(10).Key(), \"2 sorts before 10\")\n\tuassert.True(t, store.ID(99).Key() \u003c store.ID(100).Key(), \"99 sorts before 100\")\n\tuassert.True(t, store.ID(999999999999).Key() \u003c store.ID(1000000000000).Key(),\n\t\t\"and it keeps holding one past v0's width-12 ceiling\")\n}\n\nfunc TestReadOnlyDefaults(t *testing.T) {\n\t// on a fresh realm nothing is minted.\n\tuassert.Equal(t, int64(0), totalSupply())\n\tuassert.False(t, exists(1), \"token 1 must not exist before minting\")\n\n\tvar someone address = \"g1someoneelsehere000000000000000000000000\"\n\tuassert.Equal(t, uint64(0), balanceOf(someone))\n\tuassert.Equal(t, \"\", approvedOf(1).String())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/erc721/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package erc721\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Gno NFT (GNFT)\n\t//\n\t// **Total supply:** 0\n\t//\n\t// _No tokens minted yet._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"39638000","gas_fee":"118914ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"IoO0N4eekFzHlxKDUx53JhqCya8S3h+IvpOGoLzB43t+OMV9bwHiLzttItqtqxOD407uk5w5pP7qC53cXJROvg=="}],"memo":""},"metadata":{"timestamp":"1790961016"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"escrow","path":"gno.land/r/moul/x/daily/escrow/v1","files":[{"name":"README.md","body":"# Escrow\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA minimal 2-party escrow realm for gno.land (a port of the classic Solidity escrow\nidea, accounting only — no funds move). One party opens a deal against a\ncounterparty with free-form terms; both parties confirm to settle it, and the\ncreator can cancel any deal that is still open.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/escrow`\n\n## Example calls\n\n```\n# Alice opens a deal with Bob; returns the new deal id (e.g. 0)\nCreate(g1bob..., \"swap NFT for 100 GNOT\")\n\n# Each party confirms; when both have confirmed, the deal becomes \"Settled\"\nConfirm(0)   # called by Alice\nConfirm(0)   # called by Bob -\u003e Settled\n\n# The creator may cancel while the deal is still Open\nCancel(0)    # called by Alice\n```\n\n## Read (Render)\n\n- `/` — table of all deals: id, parties, state, confirmations, terms.\n- `/\u003cid\u003e` — details for a single deal (e.g. `/0`).\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/escrow) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `short`, `escapePipe` helpers.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nVisible change: addresses now render in monospace.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/escrow/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/escrow/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/escrow/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/escrow/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/escrow/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/escrow/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/escrow/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/escrow/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/escrow/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/escrow/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"escrow.gno","body":"package escrow\n\nimport (\n\t\"chain\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// State constants for a deal's lifecycle.\nconst (\n\tStateOpen     = \"Open\"\n\tStateSettled  = \"Settled\"\n\tStateCanceled = \"Canceled\"\n)\n\n// Deal is a 2-party escrow record. Accounting only: no funds move,\n// this tracks agreement and mutual confirmation between two parties.\ntype Deal struct {\n\tID           int\n\tCreator      address\n\tCounterparty address\n\tTerms        string\n\tState        string\n\tCreatorOK    bool\n\tCounterOK    bool\n}\n\nvar (\n\tdeals  = avl.NewTree() // id (string) -\u003e *Deal\n\tnextID int\n)\n\nvar (\n\terrNotFound   = errors.New(\"escrow: deal not found\")\n\terrNotParty   = errors.New(\"escrow: caller is not a party to this deal\")\n\terrNotOpen    = errors.New(\"escrow: deal is not open\")\n\terrNotCreator = errors.New(\"escrow: only the creator can cancel\")\n\terrBadAddr    = errors.New(\"escrow: invalid counterparty address\")\n\terrSelfDeal   = errors.New(\"escrow: counterparty must differ from creator\")\n)\n\n// Create opens a new escrow deal between the caller (creator) and the\n// given counterparty, governed by a free-form terms string. Returns the\n// new deal id. Panics on invalid input (cross-realm abort).\nfunc Create(cur realm, counterparty address, terms string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"escrow: spoofed realm\")\n\t}\n\tif !counterparty.IsValid() {\n\t\tpanic(errBadAddr)\n\t}\n\tcreator := cur.Previous().Address()\n\tif counterparty == creator {\n\t\tpanic(errSelfDeal)\n\t}\n\n\tid := nextID\n\tnextID++\n\n\td := \u0026Deal{\n\t\tID:           id,\n\t\tCreator:      creator,\n\t\tCounterparty: counterparty,\n\t\tTerms:        terms,\n\t\tState:        StateOpen,\n\t}\n\tdeals.Set(strconv.Itoa(id), d)\n\n\tchain.Emit(\"Created\", \"id\", strconv.Itoa(id),\n\t\t\"creator\", creator.String(), \"counterparty\", counterparty.String())\n\treturn id\n}\n\n// Confirm records confirmation by whichever party is calling. Once both\n// parties have confirmed, the deal transitions to Settled.\nfunc Confirm(cur realm, id int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"escrow: spoofed realm\")\n\t}\n\td := mustGet(id)\n\tif d.State != StateOpen {\n\t\tpanic(errNotOpen)\n\t}\n\tcaller := cur.Previous().Address()\n\n\tswitch caller {\n\tcase d.Creator:\n\t\td.CreatorOK = true\n\tcase d.Counterparty:\n\t\td.CounterOK = true\n\tdefault:\n\t\tpanic(errNotParty)\n\t}\n\n\tchain.Emit(\"Confirmed\", \"id\", strconv.Itoa(id), \"party\", caller.String())\n\n\tif d.CreatorOK \u0026\u0026 d.CounterOK {\n\t\td.State = StateSettled\n\t\tchain.Emit(\"Settled\", \"id\", strconv.Itoa(id))\n\t}\n}\n\n// Cancel voids an open deal. Only the creator may cancel, and only\n// before the deal has settled.\nfunc Cancel(cur realm, id int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"escrow: spoofed realm\")\n\t}\n\td := mustGet(id)\n\tif d.State != StateOpen {\n\t\tpanic(errNotOpen)\n\t}\n\tcaller := cur.Previous().Address()\n\tif caller != d.Creator {\n\t\tpanic(errNotCreator)\n\t}\n\td.State = StateCanceled\n\tchain.Emit(\"Canceled\", \"id\", strconv.Itoa(id))\n}\n\nfunc mustGet(id int) *Deal {\n\tv := deals.Get(strconv.Itoa(id))\n\tif v == nil {\n\t\tpanic(errNotFound)\n\t}\n\treturn v.(*Deal)\n}\n\n// Render lists all escrow deals with their parties, terms, and state.\n// When path is a numeric id, renders just that deal.\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(strings.Trim(path, \"/\"))\n\tif path != \"\" {\n\t\tif id, err := strconv.Atoi(path); err == nil {\n\t\t\tv := deals.Get(strconv.Itoa(id))\n\t\t\tif v == nil {\n\t\t\t\treturn \"# Escrow\\n\\nDeal \" + md.InlineCode(path) + \" not found.\\n\"\n\t\t\t}\n\t\t\treturn renderOne(v.(*Deal))\n\t\t}\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Escrow\\n\\n\")\n\tb.WriteString(\"2-party escrow deals (accounting only — no funds move).\\n\\n\")\n\n\tif deals.Size() == 0 {\n\t\tb.WriteString(\"_No deals yet._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| ID | Creator | Counterparty | State | Confirmations | Terms |\\n\")\n\tb.WriteString(\"|----|---------|--------------|-------|---------------|-------|\\n\")\n\tdeals.Iterate(\"\", \"\", func(_ string, v interface{}) bool {\n\t\td := v.(*Deal)\n\t\tb.WriteString(\"| \" + strconv.Itoa(d.ID) +\n\t\t\t\" | \" + ui.Addr(d.Creator) +\n\t\t\t\" | \" + ui.Addr(d.Counterparty) +\n\t\t\t\" | \" + d.State +\n\t\t\t\" | \" + confs(d) +\n\t\t\t\" | \" + ui.Cell(d.Terms) + \" |\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\nfunc renderOne(d *Deal) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Escrow Deal #\" + strconv.Itoa(d.ID) + \"\\n\\n\")\n\tb.WriteString(\"- **State:** \" + d.State + \"\\n\")\n\tb.WriteString(\"- **Creator:** \" + d.Creator.String() + \" (\" + yn(d.CreatorOK) + \")\\n\")\n\tb.WriteString(\"- **Counterparty:** \" + d.Counterparty.String() + \" (\" + yn(d.CounterOK) + \")\\n\")\n\tb.WriteString(\"- **Terms:** \" + ui.Inline(d.Terms) + \"\\n\")\n\treturn b.String()\n}\n\nfunc confs(d *Deal) string {\n\tn := 0\n\tif d.CreatorOK {\n\t\tn++\n\t}\n\tif d.CounterOK {\n\t\tn++\n\t}\n\treturn strconv.Itoa(n) + \"/2\"\n}\n\nfunc yn(b bool) string {\n\tif b {\n\t\treturn \"confirmed\"\n\t}\n\treturn \"pending\"\n}\n"},{"name":"escrow_test.gno","body":"package escrow\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\nfunc resetState() {\n\tdeals = avl.NewTree()\n\tnextID = 0\n}\n\nfunc TestCreateAndConfirmSettles(cur realm, t *testing.T) {\n\tresetState()\n\n\t// Alice creates a deal with Bob.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Create(cross(cur), bob, \"swap NFT for 100 GNOT\")\n\tuassert.Equal(t, 0, id)\n\n\t// Alice confirms (1/2, still open).\n\tConfirm(cross(cur), id)\n\tout := Render(\"0\")\n\tuassert.True(t, strings.Contains(out, \"State:** Open\"), \"expected still open after one confirm\")\n\n\t// Bob confirms -\u003e settles.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tConfirm(cross(cur), id)\n\n\tout = Render(\"0\")\n\tuassert.True(t, strings.Contains(out, \"Settled\"), \"expected Settled state\")\n\tuassert.True(t, strings.Contains(out, \"swap NFT for 100 GNOT\"), \"expected terms\")\n}\n\nfunc TestCancelByCreator(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Create(cross(cur), bob, \"rent payment\")\n\n\tCancel(cross(cur), id)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Canceled\"), \"expected Canceled state\")\n}\n\nfunc TestNonPartyCannotConfirm(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Create(cross(cur), bob, \"consulting\")\n\n\t// Carol is not a party.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsWithMessage(t, cur, \"escrow: caller is not a party to this deal\", func() {\n\t\tConfirm(cross(cur), id)\n\t})\n}\n\nfunc TestOnlyCreatorCancels(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Create(cross(cur), bob, \"loan\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur, \"escrow: only the creator can cancel\", func() {\n\t\tCancel(cross(cur), id)\n\t})\n}\n\n// The list view escaped Terms and the deal page did not, so a caller's terms\n// rendered as live markdown on the realm's own page.\nfunc TestDealPageEscapesTerms(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Create(cross(cur), bob, \"[claim](https://evil.example)\")\n\tout := Render(strconv.Itoa(id))\n\tuassert.False(t, strings.Contains(out, \"[claim](https://evil.example)\"), out)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/escrow/v1\"\ngno = \"0.9\"\nprivate = true\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"41109600","gas_fee":"123328ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"NrNw+hEqdZ+Pg+lKkdFgnlcyfjCM4AclfUJzmzUBK0Ncij4YiOak87TxRHWeEMylKVNRWXotbRE5gTuVJulIRg=="}],"memo":""},"metadata":{"timestamp":"1790961017"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"faucet","path":"gno.land/r/moul/x/daily/faucet/v0","files":[{"name":"README.md","body":"# Token Faucet\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA toy points faucet realm for the gno.land sapphire testnet. Any caller can\n`Claim` 100 points, but only once every 100 blocks per address — the cooldown is\nenforced deterministically via `runtime.ChainHeight()`. Per-caller balances and\nlast-claim heights are stored in an `avl.Tree`, and `Render` shows the total\ndistributed, total claim count, and a table of all claimers with their balances.\n\n## Realm path\n\n```\ngno.land/r/REPLACE_ADDR/faucet\n```\n\n(`REPLACE_ADDR` is replaced with the deploy address at deploy time.)\n\n## Example calls\n\n```sh\n# Claim 100 points (subject to the 100-block cooldown).\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/faucet\" \\\n  -func Claim -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast \\\n  -chainid sapphire-1 mykey\n\n# Query a balance (read-only).\ngnokey query \"vm/qeval\" -data \\\n  'gno.land/r/REPLACE_ADDR/faucet.BalanceOf(\"g1...youraddr\")'\n\n# View the dashboard.\ngnokey query \"vm/qrender\" -data 'gno.land/r/REPLACE_ADDR/faucet:'\n```\n\n## Behavior\n\n- `Claim(cur realm)` — grants `ClaimAmount` (100) points to the caller; aborts if\n  the caller's previous claim was less than `CooldownBlocks` (100) blocks ago.\n- `BalanceOf(addr string) int64` — current balance for an address (0 if unknown).\n- `Render(path string) string` — Markdown dashboard: stats + claimer table.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/faucet/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/faucet/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/faucet/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/faucet/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/faucet/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/faucet/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/faucet/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"faucet.gno","body":"// Package faucet is a toy points faucet realm for the gno.land sapphire testnet.\n//\n// Any caller may Claim() 100 points, but only once per cooldown window of 100\n// blocks. Cooldown is enforced deterministically via runtime.ChainHeight() — no\n// real clocks, no RNG. Per-caller balance and last-claim height live in an\n// avl.Tree so Render iterates in deterministic (address-sorted) order.\npackage faucet\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst (\n\t// ClaimAmount is granted on every successful claim.\n\tClaimAmount = 100\n\t// CooldownBlocks is the minimum number of blocks between two claims by the\n\t// same caller.\n\tCooldownBlocks = 100\n)\n\n// claimer holds the per-address state.\ntype claimer struct {\n\tBalance   int64 // total points accumulated\n\tLastClaim int64 // chain height of the last successful claim\n\tClaims    int64 // number of successful claims by this address\n}\n\nvar (\n\t// claimers maps address string -\u003e *claimer.\n\tclaimers = avl.NewTree()\n\t// totalDistributed is the running sum of all points ever granted.\n\ttotalDistributed int64\n\t// totalClaims is the total number of successful claims across all callers.\n\ttotalClaims int64\n)\n\n// Claim grants ClaimAmount points to the caller, subject to the per-caller\n// cooldown. It aborts (cross-realm) if the caller must still wait.\nfunc Claim(cur realm) {\n\tcaller := unsafe.PreviousRealm().Address()\n\tkey := caller.String()\n\theight := runtime.ChainHeight()\n\n\tvar c *claimer\n\tif v := claimers.Get(key); v != nil {\n\t\tc = v.(*claimer)\n\t\twait := c.LastClaim + CooldownBlocks - height\n\t\tif wait \u003e 0 {\n\t\t\tpanic(\"cooldown active: \" + strconv.FormatInt(wait, 10) +\n\t\t\t\t\" block(s) remaining before you can claim again\")\n\t\t}\n\t} else {\n\t\tc = \u0026claimer{}\n\t}\n\n\tc.Balance += ClaimAmount\n\tc.LastClaim = height\n\tc.Claims++\n\tclaimers.Set(key, c)\n\n\ttotalDistributed += ClaimAmount\n\ttotalClaims++\n\n\tchain.Emit(\n\t\t\"Claim\",\n\t\t\"caller\", key,\n\t\t\"amount\", strconv.FormatInt(ClaimAmount, 10),\n\t\t\"balance\", strconv.FormatInt(c.Balance, 10),\n\t\t\"height\", strconv.FormatInt(height, 10),\n\t)\n}\n\n// BalanceOf returns the current point balance of addr (0 if never claimed).\nfunc BalanceOf(addr string) int64 {\n\tif v := claimers.Get(addr); v != nil {\n\t\treturn v.(*claimer).Balance\n\t}\n\treturn 0\n}\n\n// Render produces a Markdown dashboard of faucet activity.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Token Faucet\\n\\n\")\n\tb.WriteString(\"A toy points faucet. Call `Claim` to receive **\")\n\tb.WriteString(strconv.FormatInt(ClaimAmount, 10))\n\tb.WriteString(\" points** — but only once every **\")\n\tb.WriteString(strconv.FormatInt(CooldownBlocks, 10))\n\tb.WriteString(\" blocks** per address.\\n\\n\")\n\n\tb.WriteString(\"## Stats\\n\\n\")\n\tb.WriteString(\"- Total distributed: **\")\n\tb.WriteString(strconv.FormatInt(totalDistributed, 10))\n\tb.WriteString(\"** points\\n\")\n\tb.WriteString(\"- Total claims: **\")\n\tb.WriteString(strconv.FormatInt(totalClaims, 10))\n\tb.WriteString(\"**\\n\")\n\tb.WriteString(\"- Unique claimers: **\")\n\tb.WriteString(strconv.Itoa(claimers.Size()))\n\tb.WriteString(\"**\\n\")\n\tb.WriteString(\"- Current block height: **\")\n\tb.WriteString(strconv.FormatInt(runtime.ChainHeight(), 10))\n\tb.WriteString(\"**\\n\\n\")\n\n\tb.WriteString(\"## Claimers\\n\\n\")\n\tif claimers.Size() == 0 {\n\t\tb.WriteString(\"_No one has claimed yet. Be the first!_\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| Address | Balance | Claims | Last claim (height) |\\n\")\n\tb.WriteString(\"| --- | ---: | ---: | ---: |\\n\")\n\tclaimers.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tc := value.(*claimer)\n\t\tb.WriteString(\"| `\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"` | \")\n\t\tb.WriteString(strconv.FormatInt(c.Balance, 10))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.FormatInt(c.Claims, 10))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.FormatInt(c.LastClaim, 10))\n\t\tb.WriteString(\" |\\n\")\n\t\treturn false\n\t})\n\n\treturn b.String()\n}\n"},{"name":"faucet_test.gno","body":"package faucet\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestClaimGrantsPoints(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tClaim(cross(cur))\n\n\tuassert.Equal(t, int64(ClaimAmount), BalanceOf(alice.String()),\n\t\t\"first claim should grant ClaimAmount\")\n\tuassert.Equal(t, int64(ClaimAmount), totalDistributed,\n\t\t\"totalDistributed should reflect the single claim\")\n\tuassert.Equal(t, int64(1), totalClaims, \"one claim recorded\")\n}\n\nfunc TestClaimCooldownAborts(cur realm, t *testing.T) {\n\tbob := testutils.TestAddress(\"bob\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\n\t// First claim succeeds at the current height.\n\tClaim(cross(cur))\n\n\t// Immediate second claim (same block) must abort due to cooldown.\n\tuassert.AbortsWithMessage(t, cur,\n\t\t\"cooldown active: 100 block(s) remaining before you can claim again\",\n\t\tfunc() {\n\t\t\tClaim(cross(cur))\n\t\t},\n\t\t\"second immediate claim should abort on cooldown\",\n\t)\n}\n\nfunc TestRenderContainsStats(cur realm, t *testing.T) {\n\tcarol := testutils.TestAddress(\"carol\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tClaim(cross(cur))\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"# Token Faucet\"), \"has title\")\n\tuassert.True(t, strings.Contains(out, \"Total distributed\"), \"has stats\")\n\tuassert.True(t, strings.Contains(out, carol.String()),\n\t\t\"claimer address listed in table\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/faucet/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"34448400","gas_fee":"103345ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"RoQe/0vBzm/2m1mcd6plh+jObE11UC4eXl/iceG3rTwDt5DQag+x6sx0OG2jKQxtOgOMh0DsghotTidDXlxckQ=="}],"memo":""},"metadata":{"timestamp":"1790961017"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"fenwickdemo","path":"gno.land/r/moul/x/daily/fenwickdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/fenwickdemo/v0`\n\n**A gnoweb demo of the [`p/moul/x/daily/fenwick`](/p/moul/x/daily/fenwick/v0)\nlibrary**: prefix sums, range queries, the internal ranges that make a Binary\nIndexed Tree legible, and the weighted draw that is the reason to use one.\n\nIt holds no tree logic of its own and no state. Every figure on the page is\ncomputed from two fixed tables in the source, never from chain state, which is\nwhat lets `ExampleRender` pin the whole page: the pinned block is copied from\nwhat `gno` printed, so a change in the library shows up as a diff in the test\nrather than as prose nobody re-reads.\n\nThe page is in five parts, and the last two are the ones worth reading:\n\n- **What the tree actually stores.** The array is not a copy of the values;\n  each node holds the sum of a run of them, and the run lengths are the powers\n  of two in the index. `Covers` turns that from a claim into a table.\n- **The weighted draw.** Five holders, one of them with a zero stake, and the\n  exact range of targets each one owns. Target `30` is the interesting row: it\n  is the first past the first holder's share and it skips the zero-stake holder\n  entirely, because a zero does not advance the prefix.\n\nRendering is deterministic and costs no chain reads, so the page is the same on\nevery node and at every height.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/fenwickdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fenwickdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/fenwickdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fenwickdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/fenwickdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fenwickdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/fenwickdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fenwickdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/fenwickdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/fenwickdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"fenwickdemo.gno","body":"// Package fenwickdemo is a small gnoweb demo of the Binary Indexed Tree\n// provided by the [p/moul/x/daily/fenwick](/p/moul/x/daily/fenwick/v0)\n// library: prefix sums, range queries, the internal ranges that make the\n// structure legible, and the weighted draw that is the reason to use one.\n//\n// It contains no tree logic of its own. Stateless, so Render is deterministic:\n// every figure below is computed from the fixed tables at the top of this file,\n// never from chain state, which is what lets an example test pin the page.\npackage fenwickdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/daily/fenwick/v0\"\n)\n\n// scores is the worked example: eight slots, small enough to check by hand.\nvar scores = []int64{3, 1, 4, 1, 5, 9, 2, 6}\n\n// stakes is the weighted-draw example. The zero is the interesting entry: a\n// holder with no stake must never be drawn, and that is a property of the\n// search, not of the caller remembering to skip them.\nvar (\n\tholders = []string{\"alice\", \"bob\", \"carol\", \"dave\", \"erin\"}\n\tstakes  = []int64{30, 0, 45, 5, 20}\n)\n\n// Render renders the demo for gnoweb.\n//\n//\tRender(\"\") / Render(\"/\") -\u003e the full demo\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Fenwick tree\\n\\n\")\n\tb.WriteString(\"A Binary Indexed Tree: prefix sums and point updates both in \")\n\tb.WriteString(\"`O(log n)`, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/fenwick`](/p/moul/x/daily/fenwick/v0) library.\\n\\n\")\n\n\ttr := fenwick.FromSlice(scores)\n\n\tb.WriteString(\"## The values\\n\\n\")\n\tb.WriteString(\"`\" + joinInts(scores) + \"` — \" + strconv.Itoa(tr.Len()))\n\tb.WriteString(\" slots totalling `\" + strconv.FormatInt(tr.Total(), 10) + \"`.\\n\\n\")\n\n\tb.WriteString(\"## Prefix sums\\n\\n\")\n\tpt := ui.NewTable(\"i\", \"value\", \"Prefix(i+1)\")\n\tfor i := 0; i \u003c tr.Len(); i++ {\n\t\tpt.Row(strconv.Itoa(i),\n\t\t\tstrconv.FormatInt(tr.At(i), 10),\n\t\t\tstrconv.FormatInt(tr.Prefix(i+1), 10))\n\t}\n\tb.WriteString(pt.String() + \"\\n\")\n\n\tb.WriteString(\"## Range queries\\n\\n\")\n\trt := ui.NewTable(\"call\", \"meaning\", \"result\")\n\trt.Row(\"`Range(2, 5)`\", \"slots 2, 3, 4\", strconv.FormatInt(tr.Range(2, 5), 10))\n\trt.Row(\"`Range(0, 8)`\", \"everything\", strconv.FormatInt(tr.Range(0, 8), 10))\n\trt.Row(\"`Range(5, 5)`\", \"empty\", strconv.FormatInt(tr.Range(5, 5), 10))\n\trt.Row(\"`Range(-9, 99)`\", \"clamped to the ends\", strconv.FormatInt(tr.Range(-9, 99), 10))\n\tb.WriteString(rt.String() + \"\\n\")\n\tb.WriteString(\"Reads clamp instead of panicking. A realm cannot be redeployed on \")\n\tb.WriteString(\"the same path, so a `Render` that panics on an out-of-range index \")\n\tb.WriteString(\"is a page that is broken for good. Writes do panic: a bad `Add` is \")\n\tb.WriteString(\"a transaction, and aborting it is the useful answer.\\n\\n\")\n\n\tb.WriteString(\"## What the tree actually stores\\n\\n\")\n\tb.WriteString(\"The array is not a copy of the values. Each internal slot holds the \")\n\tb.WriteString(\"sum of a run of them, and the run lengths are the powers of two in \")\n\tb.WriteString(\"the index. That is the whole trick, and `Covers` makes it visible.\\n\\n\")\n\tct := ui.NewTable(\"node\", \"covers slots\", \"sum\")\n\tfor i := 1; i \u003c= tr.Len(); i++ {\n\t\tlo, hi := tr.Covers(i)\n\t\tct.Row(strconv.Itoa(i),\n\t\t\t\"`[\"+strconv.Itoa(lo)+\", \"+strconv.Itoa(hi)+\")`\",\n\t\t\tstrconv.FormatInt(tr.Range(lo, hi), 10))\n\t}\n\tb.WriteString(ct.String() + \"\\n\")\n\tb.WriteString(\"A prefix walk visits one node per set bit of the index, and those \")\n\tb.WriteString(\"nodes tile the prefix exactly: no gap, no overlap. Eight slots \")\n\tb.WriteString(\"means at most three nodes per query.\\n\\n\")\n\n\tb.WriteString(\"## The weighted draw\\n\\n\")\n\tb.WriteString(\"`SearchPrefix(target)` names the slot that owns a target drawn \")\n\tb.WriteString(\"below `Total`, in `O(log n)`. Each holder is picked in proportion \")\n\tb.WriteString(\"to their stake, and a zero stake can never be picked at all.\\n\\n\")\n\tst := fenwick.FromSlice(stakes)\n\twt := ui.NewTable(\"holder\", \"stake\", \"owns targets\", \"share\")\n\tfor i, h := range holders {\n\t\tlo := st.Prefix(i)\n\t\thi := st.Prefix(i + 1)\n\t\towns := \"none\"\n\t\tif hi \u003e lo {\n\t\t\towns = \"`[\" + strconv.FormatInt(lo, 10) + \", \" + strconv.FormatInt(hi, 10) + \")`\"\n\t\t}\n\t\twt.Row(ui.Cell(h),\n\t\t\tstrconv.FormatInt(stakes[i], 10),\n\t\t\towns,\n\t\t\tpct(stakes[i], st.Total()))\n\t}\n\tb.WriteString(wt.String() + \"\\n\")\n\n\tdt := ui.NewTable(\"target\", \"SearchPrefix\", \"holder\")\n\tfor _, target := range []int64{0, 29, 30, 74, 99} {\n\t\ti := st.SearchPrefix(target)\n\t\tdt.Row(strconv.FormatInt(target, 10), strconv.Itoa(i), ui.Cell(holders[i]))\n\t}\n\tb.WriteString(dt.String() + \"\\n\")\n\tb.WriteString(\"Note target `30`: it is the first one past alice's share, and it \")\n\tb.WriteString(\"skips bob entirely rather than landing on a holder with nothing \")\n\tb.WriteString(\"staked. The search steps over zero-weight slots because their \")\n\tb.WriteString(\"prefix does not advance, not because anything checks for them.\\n\\n\")\n\n\tb.WriteString(\"## Why not a plain slice\\n\\n\")\n\tb.WriteString(\"Two obvious implementations each win one column and lose another. \")\n\tb.WriteString(\"A realm whose scoreboard is written by every player and read by \")\n\tb.WriteString(\"every page view pays both costs, which is where the middle row \")\n\tb.WriteString(\"earns its keep.\\n\\n\")\n\txt := ui.NewTable(\"structure\", \"point update\", \"prefix sum\", \"weighted draw\")\n\txt.Row(\"plain slice\", \"`O(1)`\", \"`O(n)`\", \"`O(n)`\")\n\txt.Row(\"**Fenwick tree**\", \"`O(log n)`\", \"`O(log n)`\", \"`O(log n)`\")\n\txt.Row(\"running totals\", \"`O(n)`\", \"`O(1)`\", \"`O(log n)`\")\n\tb.WriteString(xt.String() + \"\\n\")\n\tb.WriteString(\"The tree also carries no storage overhead: it is exactly `n` \")\n\tb.WriteString(\"values, rearranged.\\n\")\n\n\treturn b.String()\n}\n\n// joinInts formats a slice for display. Written out rather than reached for\n// from a library because there is no sensible shared home for it yet.\nfunc joinInts(vals []int64) string {\n\tparts := make([]string, len(vals))\n\tfor i, v := range vals {\n\t\tparts[i] = strconv.FormatInt(v, 10)\n\t}\n\treturn strings.Join(parts, \", \")\n}\n\n// pct renders part/whole as a whole-number percentage.\n//\n// Integer arithmetic throughout: Render output has to be byte-identical on\n// every validating node, and floating point is the usual way that stops being\n// true.\nfunc pct(part, whole int64) string {\n\tif whole == 0 {\n\t\treturn \"0%\"\n\t}\n\treturn strconv.FormatInt(part*100/whole, 10) + \"%\"\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/fenwickdemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package fenwickdemo\n\n// ExampleRender pins the realm Render output as a testable example.\n//\n// The block below is copied verbatim from what gno printed, never hand\n// typed: every figure in it is computed by the library under test, so a\n// change in the tree shows up here as a diff rather than as prose.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Fenwick tree\n\t//\n\t// A Binary Indexed Tree: prefix sums and point updates both in `O(log n)`, demoing the [`p/moul/x/daily/fenwick`](/p/moul/x/daily/fenwick/v0) library.\n\t//\n\t// ## The values\n\t//\n\t// `3, 1, 4, 1, 5, 9, 2, 6` — 8 slots totalling `31`.\n\t//\n\t// ## Prefix sums\n\t//\n\t// | i | value | Prefix(i+1) |\n\t// | --- | --- | --- |\n\t// | 0 | 3 | 3 |\n\t// | 1 | 1 | 4 |\n\t// | 2 | 4 | 8 |\n\t// | 3 | 1 | 9 |\n\t// | 4 | 5 | 14 |\n\t// | 5 | 9 | 23 |\n\t// | 6 | 2 | 25 |\n\t// | 7 | 6 | 31 |\n\t//\n\t// ## Range queries\n\t//\n\t// | call | meaning | result |\n\t// | --- | --- | --- |\n\t// | `Range(2, 5)` | slots 2, 3, 4 | 10 |\n\t// | `Range(0, 8)` | everything | 31 |\n\t// | `Range(5, 5)` | empty | 0 |\n\t// | `Range(-9, 99)` | clamped to the ends | 31 |\n\t//\n\t// Reads clamp instead of panicking. A realm cannot be redeployed on the same path, so a `Render` that panics on an out-of-range index is a page that is broken for good. Writes do panic: a bad `Add` is a transaction, and aborting it is the useful answer.\n\t//\n\t// ## What the tree actually stores\n\t//\n\t// The array is not a copy of the values. Each internal slot holds the sum of a run of them, and the run lengths are the powers of two in the index. That is the whole trick, and `Covers` makes it visible.\n\t//\n\t// | node | covers slots | sum |\n\t// | --- | --- | --- |\n\t// | 1 | `[0, 1)` | 3 |\n\t// | 2 | `[0, 2)` | 4 |\n\t// | 3 | `[2, 3)` | 4 |\n\t// | 4 | `[0, 4)` | 9 |\n\t// | 5 | `[4, 5)` | 5 |\n\t// | 6 | `[4, 6)` | 14 |\n\t// | 7 | `[6, 7)` | 2 |\n\t// | 8 | `[0, 8)` | 31 |\n\t//\n\t// A prefix walk visits one node per set bit of the index, and those nodes tile the prefix exactly: no gap, no overlap. Eight slots means at most three nodes per query.\n\t//\n\t// ## The weighted draw\n\t//\n\t// `SearchPrefix(target)` names the slot that owns a target drawn below `Total`, in `O(log n)`. Each holder is picked in proportion to their stake, and a zero stake can never be picked at all.\n\t//\n\t// | holder | stake | owns targets | share |\n\t// | --- | --- | --- | --- |\n\t// | alice | 30 | `[0, 30)` | 30% |\n\t// | bob | 0 | none | 0% |\n\t// | carol | 45 | `[30, 75)` | 45% |\n\t// | dave | 5 | `[75, 80)` | 5% |\n\t// | erin | 20 | `[80, 100)` | 20% |\n\t//\n\t// | target | SearchPrefix | holder |\n\t// | --- | --- | --- |\n\t// | 0 | 0 | alice |\n\t// | 29 | 0 | alice |\n\t// | 30 | 2 | carol |\n\t// | 74 | 2 | carol |\n\t// | 99 | 4 | erin |\n\t//\n\t// Note target `30`: it is the first one past alice's share, and it skips bob entirely rather than landing on a holder with nothing staked. The search steps over zero-weight slots because their prefix does not advance, not because anything checks for them.\n\t//\n\t// ## Why not a plain slice\n\t//\n\t// Two obvious implementations each win one column and lose another. A realm whose scoreboard is written by every player and read by every page view pays both costs, which is where the middle row earns its keep.\n\t//\n\t// | structure | point update | prefix sum | weighted draw |\n\t// | --- | --- | --- | --- |\n\t// | plain slice | `O(1)` | `O(n)` | `O(n)` |\n\t// | **Fenwick tree** | `O(log n)` | `O(log n)` | `O(log n)` |\n\t// | running totals | `O(n)` | `O(1)` | `O(log n)` |\n\t//\n\t// The tree also carries no storage overhead: it is exactly `n` values, rearranged.\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"45324200","gas_fee":"135972ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"0y6jFsmwhLYmE9OIjcIQuQ7ynrWyrM7KOHcGc+rNdUE1j5yfa3G1EveYC3n1jDoP5EoJH6HCnBb0egwg6aC68g=="}],"memo":""},"metadata":{"timestamp":"1790961018"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"flatmapdemo","path":"gno.land/r/moul/x/daily/flatmapdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/flatmapdemo/v0`\n\n**Live demo of [`p/moul/x/daily/flatmap`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/flatmap).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/flatmapdemo/v0`](https://gno.land/r/moul/x/daily/flatmapdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/flatmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/flatmapdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/flatmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/flatmapdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/flatmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/flatmapdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/flatmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/flatmapdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/flatmapdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/flatmapdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"flatmapdemo.gno","body":"// Package flatmapdemo is a small gnoweb demo of the sorted-vector map provided\n// by the [p/moul/x/daily/flatmap](/p/moul/x/daily/flatmap/v0) library: sorted\n// storage, indexed access and range queries.\n//\n// It contains no map logic of its own. Stateless, so Render is deterministic —\n// which is precisely what the library is for.\npackage flatmapdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/flatmap/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Flat Map\\n\\n\")\n\tb.WriteString(\"A map backed by sorted slices, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/flatmap`](/p/moul/x/daily/flatmap/v0) library.\\n\\n\")\n\n\tf := flatmap.New()\n\tinserted := []string{\"delta\", \"alpha\", \"echo\", \"bravo\", \"charlie\"}\n\tfor i, k := range inserted {\n\t\tf.Set(k, strconv.Itoa(i+1))\n\t}\n\n\tb.WriteString(\"## Sorted by construction\\n\\n\")\n\tb.WriteString(\"Inserted as `\" + strings.Join(inserted, \", \") + \"` — stored sorted:\\n\\n\")\n\tb.WriteString(table(f))\n\tb.WriteString(\"\\nNo sort on read, and no dependence on map iteration order — which \")\n\tb.WriteString(\"gno leaves unspecified, and which would let two nodes render different \")\n\tb.WriteString(\"pages from the same state.\\n\\n\")\n\n\tb.WriteString(\"## Indexed access\\n\\n\")\n\tb.WriteString(\"Sorted storage gives positional lookup that a hash map cannot:\\n\\n\")\n\tfor _, i := range []int{0, 2, 4} {\n\t\tk, v, _ := f.At(i)\n\t\tb.WriteString(\"- `At(\" + strconv.Itoa(i) + \")` → `\" + k + \"` = `\" + v + \"`\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Range queries\\n\\n\")\n\tb.WriteString(\"Two binary searches and a walk — `lo` inclusive, `hi` exclusive:\\n\\n\")\n\tb.WriteString(\"| range | keys |\\n|---|---|\\n\")\n\tb.WriteString(\"| `[\\\"bravo\\\", \\\"delta\\\")` | \" + rng(f, \"bravo\", \"delta\") + \" |\\n\")\n\tb.WriteString(\"| `[\\\"charlie\\\", ∞)` | \" + rng(f, \"charlie\", \"\") + \" |\\n\")\n\tb.WriteString(\"| `[\\\"b\\\", \\\"d\\\")` | \" + rng(f, \"b\", \"d\") + \" |\\n\")\n\tb.WriteString(\"\\nThe last one asks for bounds that are not keys at all — the search \")\n\tb.WriteString(\"still lands in the right place.\\n\\n\")\n\n\tb.WriteString(\"## The trade\\n\\n\")\n\tb.WriteString(\"| operation | cost |\\n|---|---|\\n\")\n\tb.WriteString(\"| `Get` | O(log n) binary search over contiguous memory |\\n\")\n\tb.WriteString(\"| iteration | O(n), already ordered, nothing to sort |\\n\")\n\tb.WriteString(\"| `Set` in the middle | **O(n)** — the tail shifts |\\n\")\n\tb.WriteString(\"| `Set` at the end | O(1) amortised — the fast path |\\n\")\n\tb.WriteString(\"\\nCheap reads and cheap ordered iteration, paid for at write time.\\n\")\n\treturn b.String()\n}\n\nfunc table(f *flatmap.FlatMap) string {\n\tvar b strings.Builder\n\tb.WriteString(\"| # | key | value |\\n|---|---|---|\\n\")\n\ti := 0\n\tf.Iterate(func(k, v string) bool {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i) + \" | `\" + k + \"` | `\" + v + \"` |\\n\")\n\t\ti++\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\nfunc rng(f *flatmap.FlatMap, lo, hi string) string {\n\tvar out []string\n\tf.Range(lo, hi, func(k, v string) bool {\n\t\tout = append(out, \"`\"+k+\"`\")\n\t\treturn false\n\t})\n\tif len(out) == 0 {\n\t\treturn \"_none_\"\n\t}\n\treturn strings.Join(out, \", \")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/flatmapdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package flatmapdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Flat Map\n\t//\n\t// A map backed by sorted slices, demoing the [`p/moul/x/daily/flatmap`](/p/moul/x/daily/flatmap/v0) library.\n\t//\n\t// ## Sorted by construction\n\t//\n\t// Inserted as `delta, alpha, echo, bravo, charlie` — stored sorted:\n\t//\n\t// | # | key | value |\n\t// |---|---|---|\n\t// | 0 | `alpha` | `2` |\n\t// | 1 | `bravo` | `4` |\n\t// | 2 | `charlie` | `5` |\n\t// | 3 | `delta` | `1` |\n\t// | 4 | `echo` | `3` |\n\t//\n\t// No sort on read, and no dependence on map iteration order — which gno leaves unspecified, and which would let two nodes render different pages from the same state.\n\t//\n\t// ## Indexed access\n\t//\n\t// Sorted storage gives positional lookup that a hash map cannot:\n\t//\n\t// - `At(0)` → `alpha` = `2`\n\t// - `At(2)` → `charlie` = `5`\n\t// - `At(4)` → `echo` = `3`\n\t//\n\t// ## Range queries\n\t//\n\t// Two binary searches and a walk — `lo` inclusive, `hi` exclusive:\n\t//\n\t// | range | keys |\n\t// |---|---|\n\t// | `[\"bravo\", \"delta\")` | `bravo`, `charlie` |\n\t// | `[\"charlie\", ∞)` | `charlie`, `delta`, `echo` |\n\t// | `[\"b\", \"d\")` | `bravo`, `charlie` |\n\t//\n\t// The last one asks for bounds that are not keys at all — the search still lands in the right place.\n\t//\n\t// ## The trade\n\t//\n\t// | operation | cost |\n\t// |---|---|\n\t// | `Get` | O(log n) binary search over contiguous memory |\n\t// | iteration | O(n), already ordered, nothing to sort |\n\t// | `Set` in the middle | **O(n)** — the tail shifts |\n\t// | `Set` at the end | O(1) amortised — the fast path |\n\t//\n\t// Cheap reads and cheap ordered iteration, paid for at write time.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"30137600","gas_fee":"90412ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"LqONVuPKtZdL2q3ypuJgkEzl98bTEmTSbq2SPGMlt31OfqXfm8S1Xx2LhMDoelOzFE8nGbx435xvbPBXOHOusQ=="}],"memo":""},"metadata":{"timestamp":"1790961019"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"fractiondemo","path":"gno.land/r/moul/x/daily/fractiondemo/v0","files":[{"name":"README.md","body":"# Fractions\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nShows thirds summing to exactly one, the four operations, and a comparison that\na decimal detour would get wrong.\n\nDemo of the [`p/moul/x/daily/fraction`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/fraction)\nlibrary — no arithmetic lives here. Stateless, so `Render` is deterministic.\n\nThe comparison is the interesting row: `1/3` and `33333/100000` agree to five\ndecimal places, and the library still reports which is larger, because `Cmp`\ncross-multiplies instead of converting to decimal.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/fractiondemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fractiondemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/fractiondemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fractiondemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/fractiondemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fractiondemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/fractiondemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/fractiondemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/fractiondemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/fractiondemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"fractiondemo.gno","body":"// Package fractiondemo is a small gnoweb demo of the exact rational arithmetic\n// provided by the [p/moul/x/daily/fraction](/p/moul/x/daily/fraction/v0)\n// library: it shows thirds summing to exactly one, and a comparison that a\n// decimal detour would get wrong.\n//\n// It contains no arithmetic of its own. Stateless, so Render is deterministic.\npackage fractiondemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/fraction/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Fractions\\n\\n\")\n\tb.WriteString(\"Exact rational arithmetic, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/fraction`](/p/moul/x/daily/fraction/v0) library.\\n\\n\")\n\n\tthird, _ := fraction.New(1, 3)\n\tsum, _ := third.Add(third)\n\tsum, _ = sum.Add(third)\n\n\tb.WriteString(\"## A third, three times\\n\\n\")\n\tb.WriteString(\"`1/3 + 1/3 + 1/3` = **\")\n\tb.WriteString(sum.String())\n\tb.WriteString(\"**, exactly — not 0.9999…\\n\\n\")\n\tb.WriteString(\"As a decimal it is only ever an approximation: `\")\n\tb.WriteString(fraction.Decimal(third, 10))\n\tb.WriteString(\"`\\n\")\n\n\thalf, _ := fraction.New(1, 2)\n\tb.WriteString(\"\\n## Arithmetic\\n\\n| expression | result |\\n|---|---|\\n\")\n\tadd, _ := half.Add(third)\n\tsub, _ := half.Sub(third)\n\tmul, _ := half.Mul(third)\n\tdiv, _ := half.Div(third)\n\trow(\u0026b, \"1/2 + 1/3\", add.String())\n\trow(\u0026b, \"1/2 - 1/3\", sub.String())\n\trow(\u0026b, \"1/2 × 1/3\", mul.String())\n\trow(\u0026b, \"1/2 ÷ 1/3\", div.String())\n\n\tapprox, _ := fraction.New(33333, 100000)\n\tb.WriteString(\"\\n## Exact comparison\\n\\n\")\n\tb.WriteString(\"`1/3` vs `33333/100000` — identical to five decimal places, \")\n\tb.WriteString(\"yet the library still knows which is larger: **\")\n\tif third.Cmp(approx) \u003e 0 {\n\t\tb.WriteString(\"1/3 is greater\")\n\t} else {\n\t\tb.WriteString(\"33333/100000 is greater or equal\")\n\t}\n\tb.WriteString(\"**\\n\\n\")\n\tb.WriteString(\"\u003e Comparison cross-multiplies, so it never takes a decimal detour. \")\n\tb.WriteString(\"There are no floats here: on a chain, an answer that depends on \")\n\tb.WriteString(\"rounding is a consensus bug.\\n\")\n\treturn b.String()\n}\n\nfunc row(b *strings.Builder, expr, res string) {\n\tb.WriteString(\"| `\")\n\tb.WriteString(expr)\n\tb.WriteString(\"` | `\")\n\tb.WriteString(res)\n\tb.WriteString(\"` |\\n\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/fractiondemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package fractiondemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Fractions\n\t//\n\t// Exact rational arithmetic, demoing the [`p/moul/x/daily/fraction`](/p/moul/x/daily/fraction/v0) library.\n\t//\n\t// ## A third, three times\n\t//\n\t// `1/3 + 1/3 + 1/3` = **1**, exactly — not 0.9999…\n\t//\n\t// As a decimal it is only ever an approximation: `0.3333333333`\n\t//\n\t// ## Arithmetic\n\t//\n\t// | expression | result |\n\t// |---|---|\n\t// | `1/2 + 1/3` | `5/6` |\n\t// | `1/2 - 1/3` | `1/6` |\n\t// | `1/2 × 1/3` | `1/6` |\n\t// | `1/2 ÷ 1/3` | `3/2` |\n\t//\n\t// ## Exact comparison\n\t//\n\t// `1/3` vs `33333/100000` — identical to five decimal places, yet the library still knows which is larger: **1/3 is greater**\n\t//\n\t// \u003e Comparison cross-multiplies, so it never takes a decimal detour. There are no floats here: on a chain, an answer that depends on rounding is a consensus bug.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"26443000","gas_fee":"79329ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"0awOl87lrMJ9PuC48OaR6OaJ3ux9M0YVF2wiDfM7SAZA/tJdgGZriGS1owJJnMrdOSqKQfQBnEEzgLed7Xb1pg=="}],"memo":""},"metadata":{"timestamp":"1790961019"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"3Tp3J2BKttG5UEnQ5zESpCuRE02jFr5Zuc3fxvnjJR9vDCwaZgbc61NQOHMX/kbFo0lc3iDRxHMe8NaSnvWaRw=="}],"memo":""},"metadata":{"timestamp":"1790961020"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"governor","path":"gno.land/r/moul/x/daily/governor/v1","files":[{"name":"README.md","body":"# Governor\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nA simplified on-chain governance realm inspired by OpenZeppelin's `Governor`.\nIt ports the core proposal → vote → execute lifecycle to Gno: `Propose` records\na proposal's snapshot height and a deadline of `ChainHeight() + votingPeriod`,\n`CastVote` gives every address a single equally-weighted vote (1 address = 1\nvote, tracked in an avl voter set), and `State` computes `Active` / `Succeeded`\n/ `Defeated` from the deadline versus the current chain height plus whether the\n`for` tally beats `against`. `Execute` finalizes a `Succeeded` proposal.\n\nUnlike the ERC20Votes-weighted original, voting power here is flat (one address,\none vote) and there is no timelock — the emphasis is on a clean, deterministic\nstate machine driven by block height.\n\n## Example calls\n\n```\n# open a proposal (returns its id)\nPropose(\"Fund the docs working group for Q3\")\n\n# vote: 0=against, 1=for, 2=abstain (one vote per address)\nCastVote(1, 1)\n\n# read the current state: Active | Succeeded | Defeated | Executed\nState(1)\n\n# once past the deadline with for \u003e against, finalize it\nExecute(1)\n```\n\n`Render(\"\")` lists every proposal with its tally bars (`▓░`) and state.\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`Proposal` loses its `ID` field, which the store now owns, and the local\n`mustGet` becomes one line: the store's labelled `MustGet` panics\n`governor: proposal #7 not found`, the same information `v0` assembled by hand.\nThe `totalCount` counter is gone too: with no deletion, the highest id ever\nassigned is the count, so `LastID()` answers it. Each proposal keeps its own\naddress-keyed `votes` tree, which the store does not cover. Proposal ids\nalready started at 1, so nothing shifts.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/governor) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/governor/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/governor/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/governor/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/governor/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/governor/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/governor/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/governor/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/governor/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/governor/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/governor/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/governor/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"governor.gno","body":"// Package governor is a simplified on-chain governance realm inspired by\n// OpenZeppelin's Governor. Anyone may open a proposal; every address gets a\n// single equally-weighted vote (1 address = 1 vote); a proposal succeeds when\n// its voting deadline has passed and the \"for\" tally strictly beats \"against\".\npackage governor\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// votingPeriod is the number of blocks a proposal stays open for voting.\nconst votingPeriod = int64(100)\n\n// Vote support values.\nconst (\n\tVoteAgainst = 0\n\tVoteFor     = 1\n\tVoteAbstain = 2\n)\n\n// Proposal state values.\nconst (\n\tStateActive    = \"Active\"\n\tStateSucceeded = \"Succeeded\"\n\tStateDefeated  = \"Defeated\"\n\tStateExecuted  = \"Executed\"\n)\n\n// Proposal is a single governance proposal. It carries no ID field: the id\n// belongs to the store, which hands it back on lookup and iteration.\ntype Proposal struct {\n\tProposer       address\n\tDescription    string\n\tSnapshotHeight int64\n\tDeadline       int64\n\tFor            int64\n\tAgainst        int64\n\tAbstain        int64\n\tExecuted       bool\n\tvotes          *avl.Tree // voter address (string) -\u003e support (int)\n}\n\n// proposals assigns the proposal ids. v0 kept its own nextID plus an idKey()\n// that zero-padded to width 12, which stopped ordering Render past 10^12, and\n// its own totalCount, which the store's LastID already answers.\nvar proposals = store.Named(\"governor: proposal\")\n\n// Propose opens a new proposal and returns its id. The snapshot height and\n// deadline are recorded from the current chain height.\nfunc Propose(cur realm, description string) int64 {\n\tif strings.TrimSpace(description) == \"\" {\n\t\tpanic(\"governor: empty description\")\n\t}\n\tproposer := unsafe.PreviousRealm().Address()\n\th := runtime.ChainHeight()\n\tp := \u0026Proposal{\n\t\tProposer:       proposer,\n\t\tDescription:    description,\n\t\tSnapshotHeight: h,\n\t\tDeadline:       h + votingPeriod,\n\t\tvotes:          avl.NewTree(),\n\t}\n\tid := int64(proposals.Add(p))\n\n\tchain.Emit(\n\t\t\"ProposalCreated\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"proposer\", proposer.String(),\n\t\t\"deadline\", strconv.FormatInt(p.Deadline, 10),\n\t)\n\treturn id\n}\n\n// CastVote records one vote for the caller on proposal id. support is\n// 0=against, 1=for, 2=abstain. One address may vote at most once per proposal,\n// and voting is only allowed while the proposal is Active.\nfunc CastVote(cur realm, id int64, support int) {\n\tp := mustGet(id)\n\tif computeState(p, runtime.ChainHeight()) != StateActive {\n\t\tpanic(\"governor: voting closed\")\n\t}\n\tif support \u003c VoteAgainst || support \u003e VoteAbstain {\n\t\tpanic(\"governor: invalid support value\")\n\t}\n\tvoter := unsafe.PreviousRealm().Address()\n\tif p.votes.Has(voter.String()) {\n\t\tpanic(\"governor: already voted\")\n\t}\n\tp.votes.Set(voter.String(), support)\n\n\tswitch support {\n\tcase VoteFor:\n\t\tp.For++\n\tcase VoteAgainst:\n\t\tp.Against++\n\tdefault:\n\t\tp.Abstain++\n\t}\n\n\tchain.Emit(\n\t\t\"VoteCast\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"voter\", voter.String(),\n\t\t\"support\", strconv.Itoa(support),\n\t)\n}\n\n// Execute marks a Succeeded proposal as executed. It panics unless the\n// proposal has reached the Succeeded state.\nfunc Execute(cur realm, id int64) {\n\tp := mustGet(id)\n\tif computeState(p, runtime.ChainHeight()) != StateSucceeded {\n\t\tpanic(\"governor: proposal not in Succeeded state\")\n\t}\n\tp.Executed = true\n\tchain.Emit(\"ProposalExecuted\", \"id\", strconv.FormatInt(id, 10))\n}\n\n// State returns the current lifecycle state of proposal id.\nfunc State(id int64) string {\n\treturn computeState(mustGet(id), runtime.ChainHeight())\n}\n\n// computeState is the pure state machine: it decides the state of p at chain\n// height h. Kept free of globals so it is unit-testable.\nfunc computeState(p *Proposal, h int64) string {\n\tif p.Executed {\n\t\treturn StateExecuted\n\t}\n\tif h \u003c p.Deadline {\n\t\treturn StateActive\n\t}\n\tif p.For \u003e p.Against {\n\t\treturn StateSucceeded\n\t}\n\treturn StateDefeated\n}\n\nfunc mustGet(id int64) *Proposal {\n\treturn proposals.MustGet(store.ID(id)).(*Proposal)\n}\n\n// bar renders a proportional ▓░ progress bar of fixed width.\nfunc bar(value, total int64, width int) string {\n\tif width \u003c= 0 {\n\t\treturn \"\"\n\t}\n\tfilled := 0\n\tif total \u003e 0 {\n\t\tfilled = int((value*int64(width) + total/2) / total)\n\t\tif filled \u003e width {\n\t\t\tfilled = width\n\t\t}\n\t}\n\treturn strings.Repeat(\"▓\", filled) + strings.Repeat(\"░\", width-filled)\n}\n\n// Render lists all proposals with their tallies and states as Markdown.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 🏛️ Governor\\n\\n\")\n\tb.WriteString(\"Simplified on-chain governance — 1 address = 1 vote, \")\n\tb.WriteString(\"voting period of \" + strconv.FormatInt(votingPeriod, 10) + \" blocks.\\n\\n\")\n\n\th := runtime.ChainHeight()\n\tb.WriteString(\"Current chain height: **\" + strconv.FormatInt(h, 10) + \"**\\n\\n\")\n\n\tif proposals.Len() == 0 {\n\t\tb.WriteString(\"_No proposals yet. Call `Propose` to create one._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"Total proposals: **\" + proposals.LastID().String() + \"**\\n\\n\")\n\n\tproposals.Each(func(id store.ID, v any) {\n\t\tp := v.(*Proposal)\n\t\tstate := computeState(p, h)\n\t\ttotal := p.For + p.Against + p.Abstain\n\n\t\tb.WriteString(\"---\\n\\n\")\n\t\tb.WriteString(\"## #\" + id.String() + \" · \" + state + \"\\n\\n\")\n\t\tb.WriteString(\"\u003e \" + p.Description + \"\\n\\n\")\n\t\tb.WriteString(\"- Proposer: `\" + p.Proposer.String() + \"`\\n\")\n\t\tb.WriteString(\"- Snapshot height: \" + strconv.FormatInt(p.SnapshotHeight, 10) + \"\\n\")\n\t\tb.WriteString(\"- Deadline height: \" + strconv.FormatInt(p.Deadline, 10))\n\t\tif state == StateActive {\n\t\t\tb.WriteString(\" (\" + strconv.FormatInt(p.Deadline-h, 10) + \" blocks left)\")\n\t\t}\n\t\tb.WriteString(\"\\n\\n\")\n\n\t\tb.WriteString(\"| Choice | Votes | Tally |\\n\")\n\t\tb.WriteString(\"|---|---|---|\\n\")\n\t\tb.WriteString(\"| For | \" + strconv.FormatInt(p.For, 10) + \" | `\" + bar(p.For, total, 20) + \"` |\\n\")\n\t\tb.WriteString(\"| Against | \" + strconv.FormatInt(p.Against, 10) + \" | `\" + bar(p.Against, total, 20) + \"` |\\n\")\n\t\tb.WriteString(\"| Abstain | \" + strconv.FormatInt(p.Abstain, 10) + \" | `\" + bar(p.Abstain, total, 20) + \"` |\\n\\n\")\n\t})\n\n\treturn b.String()\n}\n"},{"name":"governor_test.gno","body":"package governor\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestComputeState(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tp    *Proposal\n\t\th    int64\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"before deadline is active\",\n\t\t\tp:    \u0026Proposal{Deadline: 100, For: 0, Against: 0},\n\t\t\th:    50,\n\t\t\twant: StateActive,\n\t\t},\n\t\t{\n\t\t\tname: \"at deadline with for\u003eagainst succeeds\",\n\t\t\tp:    \u0026Proposal{Deadline: 100, For: 3, Against: 1},\n\t\t\th:    100,\n\t\t\twant: StateSucceeded,\n\t\t},\n\t\t{\n\t\t\tname: \"past deadline tie is defeated\",\n\t\t\tp:    \u0026Proposal{Deadline: 100, For: 2, Against: 2},\n\t\t\th:    120,\n\t\t\twant: StateDefeated,\n\t\t},\n\t\t{\n\t\t\tname: \"past deadline against wins is defeated\",\n\t\t\tp:    \u0026Proposal{Deadline: 100, For: 1, Against: 5},\n\t\t\th:    101,\n\t\t\twant: StateDefeated,\n\t\t},\n\t\t{\n\t\t\tname: \"executed overrides everything\",\n\t\t\tp:    \u0026Proposal{Deadline: 100, For: 9, Against: 0, Executed: true},\n\t\t\th:    200,\n\t\t\twant: StateExecuted,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := computeState(tt.p, tt.h)\n\t\tuassert.Equal(t, tt.want, got, tt.name)\n\t}\n}\n\nfunc TestBar(t *testing.T) {\n\t// empty total renders all-empty of exact width\n\tuassert.Equal(t, \"░░░░░░░░░░\", bar(0, 0, 10), \"zero total\")\n\t// full value fills entirely\n\tuassert.Equal(t, \"▓▓▓▓▓▓▓▓▓▓\", bar(10, 10, 10), \"full\")\n\t// half value fills half\n\tuassert.Equal(t, \"▓▓▓▓▓░░░░░\", bar(5, 10, 10), \"half\")\n\t// zero width yields empty string\n\tuassert.Equal(t, \"\", bar(1, 2, 0), \"zero width\")\n}\n\n// v0 asserted that its own idKey() padded to width 12. That rule held only\n// below the width: idKey(10^12) is 13 characters and sorts before\n// idKey(10^12-1), so the proposal list would have rendered out of order from\n// that id on. The store key has no width to outgrow.\nfunc TestIDKey(t *testing.T) {\n\tuassert.True(t, store.ID(2).Key() \u003c store.ID(10).Key(), \"2 sorts before 10\")\n\tuassert.True(t, store.ID(9).Key() \u003c store.ID(100).Key(), \"9 sorts before 100\")\n\tuassert.True(t, store.ID(999999999999).Key() \u003c store.ID(1000000000000).Key(),\n\t\t\"and it keeps holding one past v0's width-12 ceiling\")\n}\n"},{"name":"render_example_test.gno","body":"package governor\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # 🏛️ Governor\n\t//\n\t// Simplified on-chain governance — 1 address = 1 vote, voting period of 100 blocks.\n\t//\n\t// Current chain height: **123**\n\t//\n\t// _No proposals yet. Call `Propose` to create one._\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"45571200","gas_fee":"136713ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"lrMqGl+GWkEFtjDUu1O/0YlSsTiqYh/2L6G60hk1/Gkz1DC7/XN/YdQ1lvr5mEaYrBZ5fWlExYsoKzjjOigCJg=="}],"memo":""},"metadata":{"timestamp":"1790961073"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"guestbook","path":"gno.land/r/moul/x/daily/guestbook/v1","files":[{"name":"README.md","body":"# Guestbook\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA public, on-chain guestbook realm for gno.land. Anyone can leave a signed\nmessage; every entry records the signer's address, the message, and the block\nheight at which it was signed. The realm's `Render` page shows all entries as a\nMarkdown table, newest-first, with a running total.\n\nBuilt for the **sapphire** testnet (gno 0.9).\n\n## Realm path\n\n```\ngno.land/r/REPLACE_ADDR/guestbook\n```\n\n(`REPLACE_ADDR` is substituted with the deployer's address at publish time.)\n\n## Public API\n\n- `Sign(cur realm, message string)` — crossing tx. Appends an entry attributed\n  to the immediate caller. Panics on an empty or over-long (\u003e280 bytes) message.\n- `Count() int` — total number of signatures (read-only).\n- `Render(path string) string` — Markdown table of all entries, newest-first.\n\n## Example calls\n\nSign the guestbook (from an EOA via `gnokey`):\n\n```sh\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/REPLACE_ADDR/guestbook\" \\\n  -func Sign \\\n  -args \"gm gno.land!\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e mykey\n```\n\nFrom another realm, invoke it as a crossing call:\n\n```go\nguestbook.Sign(cross(cur), \"hello from my realm\")\n```\n\nView the rendered guestbook:\n\n```sh\ngnokey query vm/qrender --data \"gno.land/r/REPLACE_ADDR/guestbook:\"\n```\n\n## Example render output\n\n```markdown\n# Guestbook\n\n**Total signatures:** 2\n\n| # | Who | Message | Height |\n|---|-----|---------|--------|\n| 2 | g1v9jxgu…0gh | hello from my realm | 4210 |\n| 1 | g1jg8mtu…qf5 | gm gno.land! | 4180 |\n```\n\n## Notes\n\n- Caller identity uses the gno 0.9 interrealm convention: `Sign` is a crossing\n  function that checks `cur.IsCurrent()` before deriving the author from\n  `cur.Previous().Address()`.\n- Block height comes from `chain/runtime.ChainHeight()` — deterministic.\n- Entries are stored in a `gno.land/p/nt/avl/v0` tree keyed by a zero-padded\n  sequence number so iteration order is deterministic and matches insertion\n  order (reversed for newest-first rendering).\n```\n\n## What changed in v1\n\nTwo ports against [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/guestbook), which stays live and untouched.\n\n### Rendering\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/guestbook) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr`, `escapeCell` helpers.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nVisible change: addresses now render in monospace.\n\n### Storage\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\n`v0` padded ids to width 16, the widest of the six hand-rolled variants in this\nrepo and still a ceiling. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`Entry` loses its `ID` field, which the store now owns, so `addEntry` returns\n`(store.ID, *Entry)`. The `count` global is gone too: `Len()` answers it.\n\nIds stay plain integers and the rendered output of the storage port is\nunchanged. Each port changes something `v0` promised, one the rendered output\nand one the storage layout, so under this repo's versioning rule each is a\ncompatibility change and neither could be an edit to `v0` in place.\n\nThey land in the **same** new version because `v1` was never published. A\nversion number is a tag on something that exists on a chain, and until it does\nthere is nothing for a second number to avoid disturbing, so the right move is\nto keep editing the version you have. `gnopm unbump` is what folded the second\nport back down into this one.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/guestbook/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/guestbook/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/guestbook/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"guestbook.gno","body":"// Package guestbook is a public, on-chain guestbook realm for gno.land.\n//\n// Anyone can sign the guestbook with a short message via the Sign crossing\n// function. Every entry records the caller's address, the message, and the\n// block height at which it was signed. Render lists all entries newest-first\n// as a Markdown table.\n//\n// v1 renders through [p/moul/kit/ui](/p/moul/kit/ui/v0) instead of the\n// hand-rolled shortAddr and escapeCell helpers v0 carried. The escaping is the\n// substantive change: v0 replaced four characters, while ui.Cell also strips\n// bidi and zero-width characters, which a message can otherwise use to reorder\n// how the rest of the row reads.\npackage guestbook\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\n// Entry is a single signed guestbook line. It carries no ID field: the id\n// belongs to the store, which hands it back on lookup and iteration.\ntype Entry struct {\n\tAuthor  string // bech32 address of the signer\n\tMessage string // the message left by the signer\n\tHeight  int64  // block height at which the entry was signed\n}\n\nconst maxMessageLen = 280\n\n// entries assigns the sequence numbers. v1 kept its own count plus a seqKey()\n// that zero-padded to width 16, the widest of the six hand-rolled variants in\n// this repo and still a ceiling; the store key has none.\nvar entries = store.Named(\"guestbook: entry\")\n\n// Sign appends a new entry to the guestbook attributed to the immediate caller.\n//\n// It is a crossing function (gno 0.9 interrealm convention): callers invoke it\n// as Sign(cross(cur), \"hello\"). The cur.IsCurrent() guard is the authentication\n// primitive — without it a stale/forged realm value could spoof the author.\nfunc Sign(cur realm, message string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"guestbook: spoofed realm; Sign must be called via cross(cur)\")\n\t}\n\n\tauthor := cur.Previous().Address().String()\n\tid, e := addEntry(author, message, runtime.ChainHeight())\n\n\tchain.Emit(\"Signed\",\n\t\t\"id\", id.String(),\n\t\t\"author\", e.Author,\n\t\t\"height\", strconv.FormatInt(e.Height, 10),\n\t)\n}\n\n// addEntry validates the message and appends an entry. Non-crossing internal\n// helper so the append/validation logic is unit-testable without a realm frame.\n// Panics (aborting the tx, reverting state) on an invalid message.\nfunc addEntry(author, message string, height int64) (store.ID, *Entry) {\n\tmsg := strings.TrimSpace(message)\n\tif msg == \"\" {\n\t\tpanic(\"guestbook: message must not be empty\")\n\t}\n\tif len(msg) \u003e maxMessageLen {\n\t\tpanic(\"guestbook: message too long (max \" + strconv.Itoa(maxMessageLen) + \" bytes)\")\n\t}\n\n\te := \u0026Entry{\n\t\tAuthor:  author,\n\t\tMessage: msg,\n\t\tHeight:  height,\n\t}\n\treturn entries.Add(e), e\n}\n\n// Count returns the total number of signatures. Read-only, non-crossing.\nfunc Count() int {\n\treturn entries.Len()\n}\n\n// Render lists every entry newest-first as a Markdown table plus a total count.\nfunc Render(path string) string {\n\tif entries.Len() == 0 {\n\t\treturn \"# Guestbook\\n\\n\" + ui.Empty(\"No one has signed yet. Be the first!\")\n\t}\n\n\tt := ui.NewTable(\"#\", \"Who\", \"Message\", \"Height\")\n\t// Ids ascend with signing, so reverse iteration is newest-first.\n\tentries.EachReverse(func(id store.ID, v any) {\n\t\te := v.(*Entry)\n\t\tt.Row(\n\t\t\tid.String(),\n\t\t\tui.AddrOf(e.Author),\n\t\t\tui.Cell(e.Message),\n\t\t\tstrconv.FormatInt(e.Height, 10),\n\t\t)\n\t})\n\n\treturn \"# Guestbook\\n\\n**Total signatures:** \" + strconv.Itoa(entries.Len()) + \"\\n\\n\" + t.String()\n}\n"},{"name":"guestbook_test.gno","body":"package guestbook\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\n// resetState clears package globals between tests (globals persist across\n// test functions in the same package binary).\nfunc resetState() {\n\tentries = store.Named(\"guestbook: entry\")\n}\n\nfunc TestAddEntryAppendsAndCounts(t *testing.T) {\n\tresetState()\n\n\taddEntry(\"g1alice\", \"hello world\", 100)\n\taddEntry(\"g1bob\", \"second entry\", 101)\n\n\tif got := Count(); got != 2 {\n\t\tt.Fatalf(\"Count() = %d, want 2\", got)\n\t}\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"**Total signatures:** 2\") {\n\t\tt.Errorf(\"Render missing total; got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"hello world\") {\n\t\tt.Errorf(\"Render missing first message; got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"second entry\") {\n\t\tt.Errorf(\"Render missing second message; got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"100\") || !strings.Contains(out, \"101\") {\n\t\tt.Errorf(\"Render missing heights; got:\\n%s\", out)\n\t}\n}\n\nfunc TestRenderNewestFirst(t *testing.T) {\n\tresetState()\n\n\taddEntry(\"g1alice\", \"AAA oldest\", 1)\n\taddEntry(\"g1alice\", \"BBB newest\", 2)\n\n\tout := Render(\"\")\n\tiNew := strings.Index(out, \"BBB newest\")\n\tiOld := strings.Index(out, \"AAA oldest\")\n\tif iNew \u003c 0 || iOld \u003c 0 {\n\t\tt.Fatalf(\"both messages must appear; got:\\n%s\", out)\n\t}\n\tif iNew \u003e iOld {\n\t\tt.Errorf(\"newest entry should render before oldest; got:\\n%s\", out)\n\t}\n}\n\nfunc TestRenderEmpty(t *testing.T) {\n\tresetState()\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"No one has signed yet\") {\n\t\tt.Errorf(\"empty render should invite signing; got:\\n%s\", out)\n\t}\n}\n\nfunc TestEmptyMessagePanics(t *testing.T) {\n\tresetState()\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"signing an empty message should panic\")\n\t\t}\n\t}()\n\taddEntry(\"g1alice\", \"   \", 1)\n}\n\n// A message must not be able to break out of its table cell. The escaping now\n// lives in ui.Cell, so this asserts the realm's rendered output rather than a\n// local helper.\nfunc TestRenderEscapesMessage(t *testing.T) {\n\tresetState()\n\tdefer resetState()\n\taddEntry(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\", \"a|b\", 1)\n\tout := Render(\"\")\n\tif strings.Contains(out, \"| a|b |\") {\n\t\tt.Errorf(\"an unescaped pipe would open a column:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, `a\\|b`) {\n\t\tt.Errorf(\"message should appear escaped:\\n%s\", out)\n\t}\n}\n\n// v1 asserted that its own seqKey() ordered numerically. That held only below\n// its width of 16: seqKey(10^16) is 17 characters and sorts before\n// seqKey(10^16-1). The store key is 8 bytes for every id, so there is no\n// ceiling to reach.\nfunc TestSeqKeyOrders(t *testing.T) {\n\tif a, b := store.ID(2).Key(), store.ID(10).Key(); !(a \u003c b) {\n\t\tt.Error(\"id 2 should sort before id 10\")\n\t}\n\tif a, b := store.ID(9999999999999999).Key(), store.ID(10000000000000000).Key(); !(a \u003c b) {\n\t\tt.Error(\"ordering should survive one past v1's width-16 ceiling\")\n\t}\n}\n"},{"name":"render_example_test.gno","body":"package guestbook\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Guestbook\n\t//\n\t// *No one has signed yet. Be the first!*\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"46070400","gas_fee":"138211ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"tR+X814C+/asWWHKeuUNyo1g4mP2pcxPJD+kUoHZ3kI8+/HYY//i+wI8DhOqMcz1ENFVfhtmTndw1EUcEFx9iw=="}],"memo":""},"metadata":{"timestamp":"1790961076"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"handles","path":"gno.land/r/moul/x/daily/handles/v1","files":[{"name":"README.md","body":"# handles\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA tiny on-chain nickname registry. Any address can claim one unique handle\n(3-20 lowercase letters/digits, starting with a letter), attach a short bio,\ntransfer the handle to another address, or release it back into the pool.\nTwo `avl.Tree` indexes (`handle -\u003e record`, `owner -\u003e record`) keep lookups\nin both directions cheap and deterministic.\n\nRealm path: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/handles`\n\n## Example calls\n\n```\nRegister(cur, \"moul\")          # claim the handle \"moul\" for the caller\nSetBio(cur, \"building gno stuff\")\nTransfer(cur, g1...recipient)  # hand the handle to another address\nRelease(cur)                   # free the handle back up\nOwnerOf(\"moul\")                 # (address, bool)\nHandleOf(g1...)                 # (string, bool)\nCount()                         # number of registered handles\n```\n\n`Render(\"\")` lists every registered handle in a table; `Render(\"/moul\")`\nshows a single handle's detail page (owner, bio, block registered).\n\n## Toolchain status\n\nBuilt and tested against a local `gno` build at `master.3130+bf5b31eda`\n(GNOROOT pointed at a full `gnolang/gno` checkout). `gno test .` and\n`gno lint .` both pass (6 tests, 0 lint issues). Note for test authors:\nplain `recover()` did not catch panics thrown across a `cross(cur)`\nboundary in this toolchain build — the non-crossing call form\n(`Register(cur, ...)` instead of `Register(cross(cur), ...)`) was used\nin the two panic-expectation tests instead, since no realm boundary is\ncrossed and there was nothing to revive.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/handles) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `short` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/handles/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/handles/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/handles/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/handles/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/handles/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/handles/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/handles/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/handles/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/handles/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/handles/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/handles/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"handles.gno","body":"// Package handles is a tiny on-chain nickname registry.\n//\n// Any address may claim one unique handle (3-20 lowercase letters/digits,\n// starting with a letter), attach a short bio, transfer the handle to\n// another address, or release it back to the pool. It is deliberately\n// small: two AVL indexes (handle -\u003e record, address -\u003e record) and a\n// handful of guarded mutators.\npackage handles\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/handles/v1\"\n\nconst maxBioLen = 140\n\n// record is the persisted state for one claimed handle.\ntype record struct {\n\thandle   string\n\towner    address\n\tbio      string\n\tsinceBlk int64\n}\n\nvar (\n\tbyHandle avl.Tree // handle (string)      -\u003e *record\n\tbyOwner  avl.Tree // owner address.String() -\u003e *record\n)\n\n// validHandle reports whether h is 3-20 chars, starts with a lowercase\n// letter, and contains only lowercase letters and digits thereafter.\nfunc validHandle(h string) bool {\n\tif len(h) \u003c 3 || len(h) \u003e 20 {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(h); i++ {\n\t\tc := h[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z':\n\t\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9' \u0026\u0026 i \u003e 0:\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Register claims handle for the caller. Aborts if the handle is invalid,\n// already taken, or the caller already owns a handle (release it first).\nfunc Register(cur realm, handle string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"invalid realm\")\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only a direct user call can register a handle\")\n\t}\n\tif !validHandle(handle) {\n\t\tpanic(\"handle must be 3-20 lowercase letters/digits, starting with a letter\")\n\t}\n\tcaller := cur.Previous().Address()\n\tif byOwner.Has(caller.String()) {\n\t\tpanic(\"this address already owns a handle; release it first\")\n\t}\n\tif byHandle.Has(handle) {\n\t\tpanic(\"handle already taken\")\n\t}\n\n\tr := \u0026record{\n\t\thandle:   handle,\n\t\towner:    caller,\n\t\tsinceBlk: runtime.ChainHeight(),\n\t}\n\tbyHandle.Set(handle, r)\n\tbyOwner.Set(caller.String(), r)\n\tchain.Emit(\"HandleRegistered\", \"handle\", handle, \"owner\", caller.String())\n}\n\n// SetBio updates the bio of the handle owned by the caller.\nfunc SetBio(cur realm, bio string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"invalid realm\")\n\t}\n\tif len(bio) \u003e maxBioLen {\n\t\tpanic(\"bio too long (max \" + strconv.Itoa(maxBioLen) + \" chars)\")\n\t}\n\tr := ownRecord(cur)\n\tr.bio = bio\n\tchain.Emit(\"BioUpdated\", \"handle\", r.handle)\n}\n\n// Release frees the handle owned by the caller, making it claimable again.\nfunc Release(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"invalid realm\")\n\t}\n\tr := ownRecord(cur)\n\tbyHandle.Remove(r.handle)\n\tbyOwner.Remove(r.owner.String())\n\tchain.Emit(\"HandleReleased\", \"handle\", r.handle)\n}\n\n// Transfer moves the caller's handle to another address that does not\n// already own one.\nfunc Transfer(cur realm, to address) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"invalid realm\")\n\t}\n\tif !to.IsValid() {\n\t\tpanic(\"invalid recipient address\")\n\t}\n\tr := ownRecord(cur)\n\tif byOwner.Has(to.String()) {\n\t\tpanic(\"recipient already owns a handle\")\n\t}\n\tbyOwner.Remove(r.owner.String())\n\tr.owner = to\n\tbyOwner.Set(to.String(), r)\n\tchain.Emit(\"HandleTransferred\", \"handle\", r.handle, \"to\", to.String())\n}\n\n// ownRecord resolves the record for the current caller, panicking if the\n// caller does not own a handle.\nfunc ownRecord(cur realm) *record {\n\tcaller := cur.Previous().Address()\n\tv := byOwner.Get(caller.String())\n\tif v == nil {\n\t\tpanic(\"this address does not own a handle\")\n\t}\n\treturn v.(*record)\n}\n\n// OwnerOf returns the owner of handle and whether it exists.\nfunc OwnerOf(handle string) (address, bool) {\n\tv := byHandle.Get(handle)\n\tif v == nil {\n\t\treturn address(\"\"), false\n\t}\n\treturn v.(*record).owner, true\n}\n\n// HandleOf returns the handle owned by addr, if any.\nfunc HandleOf(addr address) (string, bool) {\n\tv := byOwner.Get(addr.String())\n\tif v == nil {\n\t\treturn \"\", false\n\t}\n\treturn v.(*record).handle, true\n}\n\n// Count returns the number of currently registered handles.\nfunc Count() int {\n\treturn byHandle.Size()\n}\n\n// Render renders Markdown. \"/\" lists every handle; \"/\u003chandle\u003e\" shows a\n// single record's detail.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderHandle(path)\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 🪪 Handles\\n\\n\")\n\tb.WriteString(\"A tiny on-chain nickname registry. Claim a short handle, \")\n\tb.WriteString(\"attach a bio, transfer it, or release it.\\n\\n\")\n\n\tif byHandle.Size() == 0 {\n\t\tb.WriteString(\"_No handles registered yet._\\n\\n\")\n\t\tb.WriteString(\"Call `Register(handle)` to claim the first one.\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| Handle | Owner | Since block |\\n\")\n\tb.WriteString(\"|--------|-------|-------------|\\n\")\n\tbyHandle.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tr := value.(*record)\n\t\tb.WriteString(\"| [\" + key + \"](\" + selfPath + \":\" + key + \") | \" + ui.Addr(r.owner) +\n\t\t\t\" | \" + strconv.Itoa(int(r.sinceBlk)) + \" |\\n\")\n\t\treturn false\n\t})\n\tb.WriteString(\"\\nTotal handles: \" + strconv.Itoa(byHandle.Size()) + \"\\n\")\n\treturn b.String()\n}\n\nfunc renderHandle(handle string) string {\n\tv := byHandle.Get(handle)\n\tif v == nil {\n\t\treturn \"# Handles\\n\\nNo handle named \" + md.InlineCode(handle) + \".\\n\\n[← all handles](\" + selfPath + \")\\n\"\n\t}\n\tr := v.(*record)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# 🪪 @\" + r.handle + \"\\n\\n\")\n\tb.WriteString(\"**Owner:** \" + r.owner.String() + \"\\n\\n\")\n\tif r.bio != \"\" {\n\t\tb.WriteString(\"**Bio:** \" + ui.Inline(r.bio) + \"\\n\\n\")\n\t}\n\tb.WriteString(\"**Registered at block:** \" + strconv.Itoa(int(r.sinceBlk)) + \"\\n\\n\")\n\tb.WriteString(\"[← all handles](\" + selfPath + \")\\n\")\n\treturn b.String()\n}\n"},{"name":"handles_test.gno","body":"package handles\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\n// reset clears package state between tests so cases stay independent.\nfunc reset() {\n\tbyHandle = avl.Tree{}\n\tbyOwner = avl.Tree{}\n}\n\nfunc TestValidHandle(t *testing.T) {\n\tcases := map[string]bool{\n\t\t\"moul\":                           true,\n\t\t\"m\":                              false, // too short\n\t\t\"ab\":                             false, // too short\n\t\t\"Moul\":                           false, // uppercase\n\t\t\"1moul\":                          false, // starts with digit\n\t\t\"moul1\":                          true,\n\t\t\"moul-1\":                         false, // hyphen\n\t\t\"averylonghandlethatistoolong12\": false, // too long\n\t}\n\tfor h, want := range cases {\n\t\tif got := validHandle(h); got != want {\n\t\t\tt.Errorf(\"validHandle(%q) = %v, want %v\", h, got, want)\n\t\t}\n\t}\n}\n\nfunc TestRegisterAndLookup(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"moul\")\n\n\towner, ok := OwnerOf(\"moul\")\n\tif !ok || owner != alice {\n\t\tt.Fatalf(\"OwnerOf(moul) = %v, %v; want %v, true\", owner, ok, alice)\n\t}\n\thandle, ok := HandleOf(alice)\n\tif !ok || handle != \"moul\" {\n\t\tt.Fatalf(\"HandleOf(alice) = %q, %v; want moul, true\", handle, ok)\n\t}\n\tif got := Count(); got != 1 {\n\t\tt.Fatalf(\"Count() = %d, want 1\", got)\n\t}\n}\n\nfunc TestRegisterRejectsTakenHandle(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"moul\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"expected panic registering a taken handle\")\n\t\t}\n\t}()\n\tRegister(cur, \"moul\")\n}\n\nfunc TestRegisterRejectsSecondHandleForSameOwner(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"moul\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"expected panic when the same owner registers twice\")\n\t\t}\n\t}()\n\tRegister(cur, \"second\")\n}\n\nfunc TestTransferAndRelease(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"moul\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), bob)\n\n\tif _, ok := HandleOf(alice); ok {\n\t\tt.Fatalf(\"alice should no longer own a handle after transfer\")\n\t}\n\thandle, ok := HandleOf(bob)\n\tif !ok || handle != \"moul\" {\n\t\tt.Fatalf(\"HandleOf(bob) = %q, %v; want moul, true\", handle, ok)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tRelease(cross(cur))\n\n\tif Count() != 0 {\n\t\tt.Fatalf(\"Count() = %d, want 0 after release\", Count())\n\t}\n\tif _, ok := OwnerOf(\"moul\"); ok {\n\t\tt.Fatalf(\"moul should be unclaimed after release\")\n\t}\n}\n\nfunc TestSetBioAndRender(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRegister(cross(cur), \"moul\")\n\tSetBio(cross(cur), \"building gno stuff\")\n\n\tout := Render(\"/moul\")\n\tif !contains(out, \"moul\") || !contains(out, \"building gno stuff\") {\n\t\tt.Fatalf(\"Render(/moul) missing expected content: %s\", out)\n\t}\n\n\tindex := Render(\"\")\n\tif !contains(index, \"moul\") {\n\t\tt.Fatalf(\"Render('') missing handle in index: %s\", index)\n\t}\n\n\tmissing := Render(\"/nobody\")\n\tif !contains(missing, \"No handle named\") {\n\t\tt.Fatalf(\"Render(/nobody) should report missing handle: %s\", missing)\n\t}\n}\n\nfunc contains(s, substr string) bool {\n\tfor i := 0; i+len(substr) \u003c= len(s); i++ {\n\t\tif s[i:i+len(substr)] == substr {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"},{"name":"zz_escape_test.gno","body":"package handles\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A bio is the caller's text: escaped on the handle page.\nfunc TestBioIsEscaped(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"escaper\")))\n\tRegister(cross(cur), \"escaper\")\n\tSetBio(cross(cur), \"[claim](https://evil.example)\")\n\tpage := Render(\"escaper\")\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n}\n\n// A path that names nothing is echoed back on the not-found page. It is the\n// visitor's text, so a backtick in it must not close a code span and let a\n// link through.\nfunc TestNotFoundPathIsEscaped(t *testing.T) {\n\tout := Render(\"x` [claim](https://evil.example) `\")\n\t// Still there, but inside a span md.InlineCode widened past its backticks.\n\tuassert.True(t, strings.Contains(out, md.InlineCode(\"x` [claim](https://evil.example) `\")), out)\n}\n"},{"name":"zz_links_test.gno","body":"package handles\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The index links each handle to this realm's own page, and a missing\n// handle links back to the index. Both once resolved to gno.land itself.\nfunc TestLinksNameThisRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"linker\")))\n\tRegister(cross(cur), \"linker\")\n\tidx := Render(\"\")\n\tuassert.True(t, strings.Contains(idx, \"[linker](/r/moul/x/daily/handles/v1:linker)\"), idx)\n\tmiss := Render(\"nobodyhere\")\n\tuassert.True(t, strings.Contains(miss, \"[← all handles](/r/moul/x/daily/handles/v1)\"), miss)\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"52073800","gas_fee":"156221ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"OfxFGD8OjyXm03HmWs5G0D552H9rff+x6mo1BYlNCBw1TfLLE6L031LB62JhWer3yzbE69XSWKyCJmXnHA5NrA=="}],"memo":""},"metadata":{"timestamp":"1790961077"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"hangman","path":"gno.land/r/moul/x/daily/hangman/v0","files":[{"name":"README.md","body":"# 🪢 Hangman\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nClassic hangman as a gno.land realm. A secret word is chosen **deterministically per\nday** from a built-in list using the current block height (`runtime.ChainHeight()`),\nso everyone hitting the realm on the same day plays the **same shared game**: guessed\nletters and the wrong-count are common state. Guess a letter to reveal every matching\nposition, or lose one of six lives — solve the word before the gallows fills up.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/hangman`\n\n## Example calls\n\n```sh\n# Guess a letter (tx — mutates the shared daily game)\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/hangman\" \\\n  -func Guess -args \"e\" -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 KEY\n\n# View the current board (masked word, guesses, gallows, status)\ngnokey query \"vm/qrender\" -data \"gno.land/r/REPLACE_ADDR/hangman:\"\n```\n\n## Rules\n\n- Each `Guess(cur, letter)` takes a single letter `a`–`z` (case-insensitive).\n- A hit reveals all matching positions; a miss increments the wrong-count.\n- Six wrong guesses = game over. Guessing every letter = win.\n- Re-guessing an already-tried letter, or playing after the game is over, aborts.\n- The word rotates roughly every day (a fixed span of blocks).\n\n`Render` returns Markdown showing the ASCII gallows stage for the current wrong-count,\nthe masked word (`_` for hidden letters), the sorted list of guessed letters, the\nlives remaining, and the win/lose/in-progress status.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/hangman/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hangman/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/hangman/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hangman/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/hangman/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hangman/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/hangman/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hangman/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/hangman/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/hangman/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/hangman/v0\"\ngno = \"0.9\"\n"},{"name":"hangman.gno","body":"// Package hangman is a classic hangman game for gno.land.\n//\n// The secret word rotates every ~\"day\" (a fixed span of blocks) and is chosen\n// deterministically from a built-in word list using runtime.ChainHeight(). All\n// players share a single game per day: guesses and the wrong-count are common\n// state. Guess a letter to reveal every matching position, or lose a life. Six\n// wrong guesses ends the game.\npackage hangman\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// blocksPerDay is the number of blocks that constitutes one \"day\" / one round.\n// The secret word is fixed for the whole span, then rotates.\nconst blocksPerDay = 7200\n\n// maxWrong is the number of wrong guesses allowed before the game is lost.\nconst maxWrong = 6\n\n// words is the built-in dictionary. Kept lowercase, letters only.\nvar words = []string{\n\t\"gnoland\",\n\t\"blockchain\",\n\t\"realm\",\n\t\"crossing\",\n\t\"deterministic\",\n\t\"contract\",\n\t\"validator\",\n\t\"consensus\",\n\t\"package\",\n\t\"namespace\",\n\t\"immutable\",\n\t\"transaction\",\n\t\"signature\",\n\t\"gopher\",\n\t\"hangman\",\n}\n\n// round holds the shared state for a single day's game.\ntype round struct {\n\tword    string   // the secret word for this round (lowercase)\n\tguessed *avl.Tree // letter (string) -\u003e struct{}; ordered set of guesses\n\twrong   int      // number of wrong guesses so far\n}\n\n// rounds maps a day index (decimal string) to its round. Persisted across calls.\nvar rounds = avl.NewTree()\n\n// dayIndex returns the current day index derived from block height.\nfunc dayIndex() int64 {\n\treturn runtime.ChainHeight() / blocksPerDay\n}\n\n// wordForDay picks a word deterministically from the list for the given day.\nfunc wordForDay(day int64) string {\n\tn := int64(len(words))\n\tidx := day % n\n\tif idx \u003c 0 {\n\t\tidx += n\n\t}\n\treturn words[idx]\n}\n\n// dayKey formats a day index as a stable decimal string key.\nfunc dayKey(day int64) string {\n\tneg := day \u003c 0\n\tif neg {\n\t\tday = -day\n\t}\n\tif day == 0 {\n\t\treturn \"0\"\n\t}\n\tvar b []byte\n\tfor day \u003e 0 {\n\t\tb = append([]byte{byte('0' + day%10)}, b...)\n\t\tday /= 10\n\t}\n\tif neg {\n\t\tb = append([]byte{'-'}, b...)\n\t}\n\treturn string(b)\n}\n\n// current returns (creating if needed) the round for the current day.\nfunc current() *round {\n\tday := dayIndex()\n\tkey := dayKey(day)\n\tif v := rounds.Get(key); v != nil {\n\t\treturn v.(*round)\n\t}\n\tr := \u0026round{\n\t\tword:    wordForDay(day),\n\t\tguessed: avl.NewTree(),\n\t\twrong:   0,\n\t}\n\trounds.Set(key, r)\n\treturn r\n}\n\n// normalizeLetter lowercases and validates a single a-z letter, returning it\n// and true on success.\nfunc normalizeLetter(letter string) (string, bool) {\n\tif len(letter) != 1 {\n\t\treturn \"\", false\n\t}\n\tc := letter[0]\n\tif c \u003e= 'A' \u0026\u0026 c \u003c= 'Z' {\n\t\tc = c - 'A' + 'a'\n\t}\n\tif c \u003c 'a' || c \u003e 'z' {\n\t\treturn \"\", false\n\t}\n\treturn string(c), true\n}\n\n// isWon reports whether every letter of the word has been guessed.\nfunc (r *round) isWon() bool {\n\tfor i := 0; i \u003c len(r.word); i++ {\n\t\tif !r.guessed.Has(string(r.word[i])) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// isLost reports whether the wrong-count has reached the limit.\nfunc (r *round) isLost() bool {\n\treturn r.wrong \u003e= maxWrong\n}\n\n// over reports whether the round is finished either way.\nfunc (r *round) over() bool {\n\treturn r.isWon() || r.isLost()\n}\n\n// Guess submits a single letter for the current day's shared game. It reveals\n// matching letters or costs a life. Aborts on bad input or when the game is\n// already over.\nfunc Guess(cur realm, letter string) {\n\tc, ok := normalizeLetter(letter)\n\tif !ok {\n\t\tpanic(\"guess must be a single letter a-z\")\n\t}\n\n\tr := current()\n\tif r.over() {\n\t\tpanic(\"today's game is already over\")\n\t}\n\tif r.guessed.Has(c) {\n\t\tpanic(\"letter already guessed: \" + c)\n\t}\n\n\tr.guessed.Set(c, struct{}{})\n\n\thit := strings.Contains(r.word, c)\n\tif !hit {\n\t\tr.wrong++\n\t}\n\n\tcaller := unsafeCaller(cur)\n\tchain.Emit(\n\t\t\"Guess\",\n\t\t\"letter\", c,\n\t\t\"hit\", boolStr(hit),\n\t\t\"wrong\", itoa(int64(r.wrong)),\n\t\t\"by\", caller,\n\t)\n\n\tif r.isWon() {\n\t\tchain.Emit(\"Win\", \"day\", dayKey(dayIndex()), \"word\", r.word)\n\t} else if r.isLost() {\n\t\tchain.Emit(\"Lose\", \"day\", dayKey(dayIndex()), \"word\", r.word)\n\t}\n}\n\n// unsafeCaller returns the caller address as a string, preferring the crossing\n// convention when available.\nfunc unsafeCaller(cur realm) string {\n\tif cur.IsCurrent() {\n\t\treturn cur.Previous().Address().String()\n\t}\n\treturn \"\"\n}\n\n// boolStr renders a bool compactly.\nfunc boolStr(b bool) string {\n\tif b {\n\t\treturn \"true\"\n\t}\n\treturn \"false\"\n}\n\n// itoa renders an int64 as decimal (avl-free tiny helper reused by Render).\nfunc itoa(n int64) string {\n\treturn dayKey(n)\n}\n\n// masked returns the word with un-guessed letters shown as underscores.\nfunc (r *round) masked() string {\n\tvar sb strings.Builder\n\tfor i := 0; i \u003c len(r.word); i++ {\n\t\tch := string(r.word[i])\n\t\tif r.guessed.Has(ch) {\n\t\t\tsb.WriteString(ch)\n\t\t} else {\n\t\t\tsb.WriteString(\"_\")\n\t\t}\n\t\tif i != len(r.word)-1 {\n\t\t\tsb.WriteString(\" \")\n\t\t}\n\t}\n\treturn sb.String()\n}\n\n// guessedList returns the guessed letters in sorted order, space-joined.\nfunc (r *round) guessedList() string {\n\tvar out []string\n\tr.guessed.Iterate(\"\", \"\", func(key string, _ interface{}) bool {\n\t\tout = append(out, key)\n\t\treturn false\n\t})\n\treturn strings.Join(out, \" \")\n}\n\n// gallows renders the ASCII stage for the given wrong-count (0..6).\nfunc gallows(wrong int) string {\n\tstages := []string{\n\t\t// 0\n\t\t\"  +---+\\n  |   |\\n      |\\n      |\\n      |\\n      |\\n=========\",\n\t\t// 1\n\t\t\"  +---+\\n  |   |\\n  O   |\\n      |\\n      |\\n      |\\n=========\",\n\t\t// 2\n\t\t\"  +---+\\n  |   |\\n  O   |\\n  |   |\\n      |\\n      |\\n=========\",\n\t\t// 3\n\t\t\"  +---+\\n  |   |\\n  O   |\\n /|   |\\n      |\\n      |\\n=========\",\n\t\t// 4\n\t\t\"  +---+\\n  |   |\\n  O   |\\n /|\\\\  |\\n      |\\n      |\\n=========\",\n\t\t// 5\n\t\t\"  +---+\\n  |   |\\n  O   |\\n /|\\\\  |\\n /    |\\n      |\\n=========\",\n\t\t// 6\n\t\t\"  +---+\\n  |   |\\n  O   |\\n /|\\\\  |\\n / \\\\  |\\n      |\\n=========\",\n\t}\n\tif wrong \u003c 0 {\n\t\twrong = 0\n\t}\n\tif wrong \u003e= len(stages) {\n\t\twrong = len(stages) - 1\n\t}\n\treturn stages[wrong]\n}\n\n// Render shows the current day's game: gallows, masked word, guesses, status.\nfunc Render(path string) string {\n\tr := current()\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"# 🪢 Hangman\\n\\n\")\n\tsb.WriteString(\"A new secret word every day. Everyone shares the same game — guess a letter and see it revealed for all.\\n\\n\")\n\tsb.WriteString(\"Day: `\" + dayKey(dayIndex()) + \"` · Block: `\" + itoa(runtime.ChainHeight()) + \"`\\n\\n\")\n\n\tsb.WriteString(\"```\\n\")\n\tsb.WriteString(gallows(r.wrong))\n\tsb.WriteString(\"\\n```\\n\\n\")\n\n\tsb.WriteString(\"## Word\\n\\n\")\n\tsb.WriteString(\"`\" + r.masked() + \"`\\n\\n\")\n\n\tsb.WriteString(\"Wrong: **\" + itoa(int64(r.wrong)) + \" / \" + itoa(int64(maxWrong)) + \"**  ·  Lives left: **\" + itoa(int64(maxWrong-r.wrong)) + \"**\\n\\n\")\n\n\tguesses := r.guessedList()\n\tif guesses == \"\" {\n\t\tguesses = \"_(none yet)_\"\n\t}\n\tsb.WriteString(\"Guessed letters: \" + guesses + \"\\n\\n\")\n\n\tsb.WriteString(\"## Status\\n\\n\")\n\tswitch {\n\tcase r.isWon():\n\t\tsb.WriteString(\"🎉 **Solved!** The word was **\" + r.word + \"**.\\n\\n\")\n\tcase r.isLost():\n\t\tsb.WriteString(\"💀 **Game over.** The word was **\" + r.word + \"**. Try again next day.\\n\\n\")\n\tdefault:\n\t\tsb.WriteString(\"Game in progress. Call `Guess(\\\"a\\\")` with a letter.\\n\\n\")\n\t}\n\n\tsb.WriteString(\"---\\n\\n\")\n\tsb.WriteString(\"### How to play\\n\\n\")\n\tsb.WriteString(\"- `Guess(cur, \\\"e\\\")` — guess a single letter `a`–`z`.\\n\")\n\tsb.WriteString(\"- A hit reveals every matching position; a miss costs one of 6 lives.\\n\")\n\tsb.WriteString(\"- The word rotates every ~\" + itoa(int64(blocksPerDay)) + \" blocks.\\n\")\n\treturn sb.String()\n}\n"},{"name":"hangman_test.gno","body":"package hangman\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestPureHelpers checks the deterministic, non-crossing logic.\nfunc TestPureHelpers(t *testing.T) {\n\t// normalizeLetter\n\tif c, ok := normalizeLetter(\"A\"); !ok || c != \"a\" {\n\t\tt.Fatalf(\"normalizeLetter(A) = %q,%v; want a,true\", c, ok)\n\t}\n\tif _, ok := normalizeLetter(\"ab\"); ok {\n\t\tt.Fatalf(\"normalizeLetter(ab) should fail\")\n\t}\n\tif _, ok := normalizeLetter(\"3\"); ok {\n\t\tt.Fatalf(\"normalizeLetter(3) should fail\")\n\t}\n\n\t// wordForDay is deterministic and cycles the list.\n\tw0 := wordForDay(0)\n\tif w0 != words[0] {\n\t\tt.Fatalf(\"wordForDay(0) = %q; want %q\", w0, words[0])\n\t}\n\tif wordForDay(int64(len(words))) != words[0] {\n\t\tt.Fatalf(\"wordForDay should wrap around the list length\")\n\t}\n\n\t// dayKey formatting.\n\tif got := dayKey(0); got != \"0\" {\n\t\tt.Fatalf(\"dayKey(0) = %q; want 0\", got)\n\t}\n\tif got := dayKey(123); got != \"123\" {\n\t\tt.Fatalf(\"dayKey(123) = %q; want 123\", got)\n\t}\n\n\t// gallows clamps and grows.\n\tif gallows(0) == gallows(6) {\n\t\tt.Fatalf(\"gallows should differ between 0 and 6 wrong\")\n\t}\n\tif gallows(99) != gallows(6) {\n\t\tt.Fatalf(\"gallows should clamp out-of-range to max stage\")\n\t}\n}\n\n// TestRoundMasking checks masked/win/lose logic directly on a round.\nfunc TestRoundMasking(t *testing.T) {\n\tr := \u0026round{word: \"gno\", guessed: avl.NewTree(), wrong: 0}\n\n\tif got := r.masked(); got != \"_ _ _\" {\n\t\tt.Fatalf(\"initial masked = %q; want _ _ _\", got)\n\t}\n\tif r.isWon() {\n\t\tt.Fatalf(\"fresh round should not be won\")\n\t}\n\n\tr.guessed.Set(\"g\", struct{}{})\n\tif got := r.masked(); got != \"g _ _\" {\n\t\tt.Fatalf(\"masked after g = %q; want g _ _\", got)\n\t}\n\n\tr.guessed.Set(\"n\", struct{}{})\n\tr.guessed.Set(\"o\", struct{}{})\n\tif !r.isWon() {\n\t\tt.Fatalf(\"round should be won after guessing all letters\")\n\t}\n\n\t// Lose path.\n\tr2 := \u0026round{word: \"gno\", guessed: avl.NewTree(), wrong: maxWrong}\n\tif !r2.isLost() {\n\t\tt.Fatalf(\"round with %d wrong should be lost\", maxWrong)\n\t}\n\tif !r2.over() {\n\t\tt.Fatalf(\"lost round should be over\")\n\t}\n}\n\n// TestGuessCrossing exercises the crossing entrypoint end to end.\nfunc TestGuessCrossing(cur realm, t *testing.T) {\n\tuser := testutils.TestAddress(\"player\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tr := current()\n\tword := r.word\n\n\t// A correct guess: pick the first letter of today's word.\n\tfirst := string(word[0])\n\tGuess(cross(cur), first)\n\tif !r.guessed.Has(first) {\n\t\tt.Fatalf(\"guessed set should contain %q after Guess\", first)\n\t}\n\tif r.wrong != 0 {\n\t\tt.Fatalf(\"correct guess should not increase wrong count, got %d\", r.wrong)\n\t}\n\n\t// Re-guessing the same letter aborts.\n\tuassert.AbortsWithMessage(t, cur, \"letter already guessed: \"+first, func() {\n\t\tGuess(cross(cur), first)\n\t})\n\n\t// Invalid input aborts.\n\tuassert.AbortsWithMessage(t, cur, \"guess must be a single letter a-z\", func() {\n\t\tGuess(cross(cur), \"42\")\n\t})\n\n\t// A wrong guess: find a letter not in the word.\n\tmiss := firstMissing(word)\n\tif miss != \"\" {\n\t\tbefore := r.wrong\n\t\tGuess(cross(cur), miss)\n\t\tif r.wrong != before+1 {\n\t\t\tt.Fatalf(\"wrong guess should increment wrong count: got %d want %d\", r.wrong, before+1)\n\t\t}\n\t}\n\n\t// Render always returns non-empty markdown.\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Hangman\") {\n\t\tt.Fatalf(\"Render output missing title\")\n\t}\n}\n\n// firstMissing returns a lowercase letter a-z not present in word, or \"\".\nfunc firstMissing(word string) string {\n\tfor c := byte('a'); c \u003c= 'z'; c++ {\n\t\tif !strings.Contains(word, string(c)) {\n\t\t\treturn string(c)\n\t\t}\n\t}\n\treturn \"\"\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"49642800","gas_fee":"148928ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"UpfFmtkUcw4MAYhLT4Hf8M6SJm8IJ3WS0RdjKxmkdGY9XS7kgIIXCCgfzWZ1zOKsW0oxIt1zTJaQCq927lGAAg=="}],"memo":""},"metadata":{"timestamp":"1790961078"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"heapdemo","path":"gno.land/r/moul/x/daily/heapdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/heapdemo/v0`\n\n**Live demo of [`p/moul/x/daily/heap`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/heap).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/heapdemo/v0`](https://gno.land/r/moul/x/daily/heapdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/heapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/heapdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/heapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/heapdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/heapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/heapdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/heapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/heapdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/heapdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/heapdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/heapdemo/v0\"\ngno = \"0.9\"\n"},{"name":"heapdemo.gno","body":"// Package heapdemo is a small gnoweb demo of the binary heap / priority queue\n// provided by the [p/moul/x/daily/heap](/p/moul/x/daily/heap/v0) library: it\n// shows min- and max-ordering and the deterministic tiebreak.\n//\n// It contains no heap logic of its own. Stateless, so Render is deterministic —\n// which is precisely what the library is for.\npackage heapdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/heap/v0\"\n)\n\ntype job struct {\n\tname     string\n\tpriority int\n}\n\n// queue is the shared workload used by every section below.\nvar queue = []job{\n\t{\"send email\", 5},\n\t{\"pay invoice\", 1},\n\t{\"backup db\", 3},\n\t{\"rotate keys\", 1},\n\t{\"clear cache\", 9},\n}\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Binary Heap\\n\\n\")\n\tb.WriteString(\"A priority queue, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/heap`](/p/moul/x/daily/heap/v0) library.\\n\\n\")\n\n\tb.WriteString(\"## The workload\\n\\n\")\n\tb.WriteString(\"| job | priority |\\n|---|---|\\n\")\n\tfor _, j := range queue {\n\t\tb.WriteString(\"| \" + j.name + \" | \" + strconv.Itoa(j.priority) + \" |\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Min-heap — lowest priority first\\n\\n\")\n\tb.WriteString(popOrder(fill(heap.New())))\n\n\tb.WriteString(\"\\n## Max-heap — highest priority first\\n\\n\")\n\tb.WriteString(popOrder(fill(heap.NewMax())))\n\n\tb.WriteString(\"\\n## Ties\\n\\n\")\n\tb.WriteString(\"`pay invoice` and `rotate keys` share priority 1. Both heaps pop them \")\n\tb.WriteString(\"**oldest-first**: the tiebreak is insertion order and does *not* invert \")\n\tb.WriteString(\"with the heap kind.\\n\\n\")\n\n\tb.WriteString(\"\u003e Without a total order, two nodes could pop equal-priority items in \")\n\tb.WriteString(\"different sequences and render different pages — a consensus bug, not a \")\n\tb.WriteString(\"cosmetic one.\\n\")\n\treturn b.String()\n}\n\nfunc fill(h *heap.Heap) *heap.Heap {\n\tfor _, j := range queue {\n\t\th.Push(j.name, j.priority)\n\t}\n\treturn h\n}\n\nfunc popOrder(h *heap.Heap) string {\n\tvar b strings.Builder\n\tb.WriteString(\"| # | job | priority |\\n|---|---|---|\\n\")\n\ti := 0\n\tfor {\n\t\tv, p, ok := h.Pop()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t\tb.WriteString(\"| \" + strconv.Itoa(i) + \" | \" + v + \" | \" + strconv.Itoa(p) + \" |\\n\")\n\t}\n\treturn b.String()\n}\n"},{"name":"render_example_test.gno","body":"package heapdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Binary Heap\n\t//\n\t// A priority queue, demoing the [`p/moul/x/daily/heap`](/p/moul/x/daily/heap/v0) library.\n\t//\n\t// ## The workload\n\t//\n\t// | job | priority |\n\t// |---|---|\n\t// | send email | 5 |\n\t// | pay invoice | 1 |\n\t// | backup db | 3 |\n\t// | rotate keys | 1 |\n\t// | clear cache | 9 |\n\t//\n\t// ## Min-heap — lowest priority first\n\t//\n\t// | # | job | priority |\n\t// |---|---|---|\n\t// | 1 | pay invoice | 1 |\n\t// | 2 | rotate keys | 1 |\n\t// | 3 | backup db | 3 |\n\t// | 4 | send email | 5 |\n\t// | 5 | clear cache | 9 |\n\t//\n\t// ## Max-heap — highest priority first\n\t//\n\t// | # | job | priority |\n\t// |---|---|---|\n\t// | 1 | clear cache | 9 |\n\t// | 2 | send email | 5 |\n\t// | 3 | backup db | 3 |\n\t// | 4 | pay invoice | 1 |\n\t// | 5 | rotate keys | 1 |\n\t//\n\t// ## Ties\n\t//\n\t// `pay invoice` and `rotate keys` share priority 1. Both heaps pop them **oldest-first**: the tiebreak is insertion order and does *not* invert with the heap kind.\n\t//\n\t// \u003e Without a total order, two nodes could pop equal-priority items in different sequences and render different pages — a consensus bug, not a cosmetic one.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"26609400","gas_fee":"79828ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"rsA0JbbCvz7NF7uP6QEQWjAUdAQnl7Q+QXULgILuj14cKaGgPv+X7NgFPi6ut4m4hXylEgnE3vhnU8r51lWtgw=="}],"memo":""},"metadata":{"timestamp":"1790961078"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"hexdumpdemo","path":"gno.land/r/moul/x/daily/hexdumpdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/hexdumpdemo/v0`\n\n**Live demo of [`p/moul/x/daily/hexdump`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/hexdump).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/hexdumpdemo/v0`](https://gno.land/r/moul/x/daily/hexdumpdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/hexdumpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hexdumpdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/hexdumpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hexdumpdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/hexdumpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hexdumpdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/hexdumpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/hexdumpdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/hexdumpdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/hexdumpdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/hexdumpdemo/v0\"\ngno = \"0.9\"\n"},{"name":"hexdumpdemo.gno","body":"// Package hexdumpdemo is a small gnoweb demo of the xxd-style byte dump\n// provided by the [p/moul/x/daily/hexdump](/p/moul/x/daily/hexdump/v0)\n// library: it shows what a rendered string hides.\n//\n// It contains no formatting logic of its own. Stateless, so Render is\n// deterministic — which is precisely what the library is for.\npackage hexdumpdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/hexdump/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Hexdump\\n\\n\")\n\tb.WriteString(\"Bytes in the classic `xxd -C` layout, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/hexdump`](/p/moul/x/daily/hexdump/v0) library.\\n\\n\")\n\n\tb.WriteString(\"## A plain string\\n\\n\")\n\tdump(\"Hello, gno.land!\", \u0026b)\n\n\tb.WriteString(\"\\n## Alignment on a partial line\\n\\n\")\n\tb.WriteString(\"The last line is short, so the hex columns are padded and the ASCII \")\n\tb.WriteString(\"gutter stays put — that alignment is the whole point of the layout.\\n\\n\")\n\tdump(\"0123456789abcdefhi\", \u0026b)\n\n\tb.WriteString(\"\\n## What a rendered string hides\\n\\n\")\n\tb.WriteString(\"These two look identical in any UI:\\n\\n\")\n\tb.WriteString(\"- `\\\"hi\\\"`\\n- `\\\"hi \\\"` — one trailing space\\n\\n\")\n\tdump(\"hi\", \u0026b)\n\tb.WriteString(\"\\n\")\n\tdump(\"hi \", \u0026b)\n\n\tb.WriteString(\"\\n## Multi-byte UTF-8\\n\\n\")\n\tb.WriteString(\"`\\\"café\\\"` is 5 bytes, not 4: `é` is `c3 a9`. Non-printables render as `.`.\\n\\n\")\n\tdump(\"café\", \u0026b)\n\n\tb.WriteString(\"\\n## Control characters\\n\\n\")\n\tb.WriteString(\"A NUL, a newline and a tab are invisible in text and obvious here.\\n\\n\")\n\tout, n := hexdump.Dump([]byte{0x00, 0x0a, 0x09, 'o', 'k'})\n\tb.WriteString(\"```\\n\" + out + \"```\\n\\n\")\n\tb.WriteString(\"_\" + strconv.Itoa(n) + \" bytes._\\n\")\n\treturn b.String()\n}\n\nfunc dump(s string, b *strings.Builder) {\n\tout, n := hexdump.DumpString(s)\n\tb.WriteString(\"```\\n\" + out + \"```\\n\")\n\tb.WriteString(\"\\n_`\" + s + \"` → \" + strconv.Itoa(n) + \" bytes._\\n\")\n}\n"},{"name":"render_example_test.gno","body":"package hexdumpdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Hexdump\n\t//\n\t// Bytes in the classic `xxd -C` layout, demoing the [`p/moul/x/daily/hexdump`](/p/moul/x/daily/hexdump/v0) library.\n\t//\n\t// ## A plain string\n\t//\n\t// ```\n\t// 00000000  48 65 6c 6c 6f 2c 20 67  6e 6f 2e 6c 61 6e 64 21  |Hello, gno.land!|\n\t// ```\n\t//\n\t// _`Hello, gno.land!` → 16 bytes._\n\t//\n\t// ## Alignment on a partial line\n\t//\n\t// The last line is short, so the hex columns are padded and the ASCII gutter stays put — that alignment is the whole point of the layout.\n\t//\n\t// ```\n\t// 00000000  30 31 32 33 34 35 36 37  38 39 61 62 63 64 65 66  |0123456789abcdef|\n\t// 00000010  68 69                                             |hi|\n\t// ```\n\t//\n\t// _`0123456789abcdefhi` → 18 bytes._\n\t//\n\t// ## What a rendered string hides\n\t//\n\t// These two look identical in any UI:\n\t//\n\t// - `\"hi\"`\n\t// - `\"hi \"` — one trailing space\n\t//\n\t// ```\n\t// 00000000  68 69                                             |hi|\n\t// ```\n\t//\n\t// _`hi` → 2 bytes._\n\t//\n\t// ```\n\t// 00000000  68 69 20                                          |hi |\n\t// ```\n\t//\n\t// _`hi ` → 3 bytes._\n\t//\n\t// ## Multi-byte UTF-8\n\t//\n\t// `\"café\"` is 5 bytes, not 4: `é` is `c3 a9`. Non-printables render as `.`.\n\t//\n\t// ```\n\t// 00000000  63 61 66 c3 a9                                    |caf..|\n\t// ```\n\t//\n\t// _`café` → 5 bytes._\n\t//\n\t// ## Control characters\n\t//\n\t// A NUL, a newline and a tab are invisible in text and obvious here.\n\t//\n\t// ```\n\t// 00000000  00 0a 09 6f 6b                                    |...ok|\n\t// ```\n\t//\n\t// _5 bytes._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"27085200","gas_fee":"81255ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"smhL5JFB/Jn1YNorfvZJw8ftGW7Gv9LA63OoO5lZOpA8X3bwEqS0NCdTCjgZUK1fwUTf+4qGqwV4CAE8asEhcg=="}],"memo":""},"metadata":{"timestamp":"1790961079"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"kingofdice","path":"gno.land/r/moul/x/daily/kingofdice/v1","files":[{"name":"README.md","body":"# 👑 King of the Dice\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA \"king of the hill\" dice game for gno.land (sapphire / gno 0.9). Call `Roll()`\nto throw a deterministic 1-100 die; beat the reigning king's roll and you\ndethrone them, becoming king yourself. Unlike a typical leaderboard that just\nsums points, this one ranks players by **accumulated reign length in blocks**\n— a single lucky high roll only pays off for as long as nobody beats it, so\noutlasting the field matters more than the roll itself.\n\n**Realm path:** `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/kingofdice`\n\n## Public API\n\n| Function | Kind | Description |\n| --- | --- | --- |\n| `Roll(cur realm)` | crossing (tx) | Roll 1-100; dethrones the king on a higher roll. |\n| `Render(path string) string` | view | Current king + reign-length leaderboard. |\n\n## Example calls\n\n```sh\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/kingofdice\" \\\n  -func Roll \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e \u003ckeyname\u003e\n```\n\nView the dashboard in gnoweb at `/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/kingofdice`,\nor query it:\n\n```sh\ngnokey query \"vm/qrender\" -data \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/kingofdice:\" -remote \u003crpc\u003e\n```\n\n## Toolchain status\n\nVerified locally: `gno test .` passes (built against a `gnolang/gno` checkout\nas `GNOROOT`, since the machine's configured `GNOROOT` pointed at a stale,\ndeleted path). Tests avoid `gno.land/p/nt/uassert/v0` — the cached copy of\nthat package uses the bare `cross` builtin as a function value, which the\nlocally installed `gno` (master) rejects; plain `testing.T` calls sidestep\nthat unrelated cache/toolchain drift.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/kingofdice) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `medal` helper.\n\n**One podium.** `ui.Podium` replaces the medal switch three realms each had a copy of. Same output.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/kingofdice/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kingofdice/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/kingofdice/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kingofdice/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/kingofdice/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kingofdice/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/kingofdice/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kingofdice/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/kingofdice/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/kingofdice/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/kingofdice/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"kingofdice.gno","body":"// Package kingofdice is a \"king of the hill\" dice game. Anyone can Roll a\n// pseudo-random 1-100 die; beat the reigning king's roll and you dethrone\n// them, becoming king yourself. The leaderboard doesn't rank raw points — it\n// ranks accumulated *reign length*, measured in blocks held as king, so\n// camping on a lucky high roll pays off more than a single spike.\npackage kingofdice\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// playerStats is the persisted record for one address.\ntype playerStats struct {\n\taddr              address\n\trolls             int\n\tbestRoll          int\n\treigns            int\n\ttotalReignBlocks  int64 // blocks held as king across all past reigns\n}\n\nvar (\n\tplayers avl.Tree // address string -\u003e *playerStats\n\n\tking       address\n\tkingRoll   int\n\treignSince int64 // chain height at which the current king took the throne\n\n\tnonce     int\n\ttotalRolls int\n)\n\n// get returns the stored *playerStats for addr, creating one if absent.\nfunc get(addr address) *playerStats {\n\tkey := addr.String()\n\tif v := players.Get(key); v != nil {\n\t\treturn v.(*playerStats)\n\t}\n\tps := \u0026playerStats{addr: addr}\n\tplayers.Set(key, ps)\n\treturn ps\n}\n\n// pseudoRoll derives a deterministic 1-100 value from the caller's address,\n// a per-call nonce, and the current chain height, so no two calls in the\n// same block from the same address collide, yet the result can't be\n// pre-computed off-chain before the triggering transaction lands.\nfunc pseudoRoll(addr address, nonce int, height int64) int {\n\ts := addr.String()\n\tvar h int64\n\tfor i := 0; i \u003c len(s); i++ {\n\t\th = h*31 + int64(s[i])\n\t}\n\th += int64(nonce)*104729 + height*7919\n\tif h \u003c 0 {\n\t\th = -h\n\t}\n\treturn int(h%100) + 1\n}\n\n// Roll throws the die for the caller. Rolling higher than the current king's\n// roll dethrones them (crediting their finished reign in blocks) and crowns\n// the caller as the new king.\nfunc Roll(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\n\tnonce++\n\ttotalRolls++\n\theight := runtime.ChainHeight()\n\troll := pseudoRoll(caller, nonce, height)\n\n\tps := get(caller)\n\tps.rolls++\n\tif roll \u003e ps.bestRoll {\n\t\tps.bestRoll = roll\n\t}\n\n\tif !king.IsValid() || roll \u003e kingRoll {\n\t\tif king.IsValid() {\n\t\t\tprev := get(king)\n\t\t\tprev.totalReignBlocks += height - reignSince\n\t\t}\n\t\tking = caller\n\t\tkingRoll = roll\n\t\treignSince = height\n\t\tps.reigns++\n\t\treturn \"you rolled \" + strconv.Itoa(roll) + \" and seized the throne!\"\n\t}\n\n\tif king == caller {\n\t\treturn \"you rolled \" + strconv.Itoa(roll) + \" — you're still king (need to beat \" +\n\t\t\tstrconv.Itoa(kingRoll) + \")\"\n\t}\n\treturn \"you rolled \" + strconv.Itoa(roll) + \" — not enough to dethrone the king's \" +\n\t\tstrconv.Itoa(kingRoll)\n}\n\n// effectiveReignBlocks returns a player's accumulated reign length, including\n// the currently-in-progress reign if they are the sitting king. It does not\n// mutate state — it's a display-time projection.\nfunc effectiveReignBlocks(ps *playerStats, height int64) int64 {\n\tif king.IsValid() \u0026\u0026 ps.addr == king {\n\t\treturn ps.totalReignBlocks + (height - reignSince)\n\t}\n\treturn ps.totalReignBlocks\n}\n\n// byReign implements sort.Interface, ranking players by effective reign\n// length descending, ties broken by best roll then address so the order is\n// fully deterministic.\ntype byReign struct {\n\tstats  []*playerStats\n\tblocks []int64\n}\n\nfunc (r byReign) Len() int      { return len(r.stats) }\nfunc (r byReign) Swap(i, j int) {\n\tr.stats[i], r.stats[j] = r.stats[j], r.stats[i]\n\tr.blocks[i], r.blocks[j] = r.blocks[j], r.blocks[i]\n}\nfunc (r byReign) Less(i, j int) bool {\n\tif r.blocks[i] != r.blocks[j] {\n\t\treturn r.blocks[i] \u003e r.blocks[j]\n\t}\n\tif r.stats[i].bestRoll != r.stats[j].bestRoll {\n\t\treturn r.stats[i].bestRoll \u003e r.stats[j].bestRoll\n\t}\n\treturn r.stats[i].addr.String() \u003c r.stats[j].addr.String()\n}\n\n// snapshot collects all players ranked by effective reign length descending.\nfunc snapshot(height int64) ([]*playerStats, []int64) {\n\tstats := make([]*playerStats, 0, players.Size())\n\tplayers.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tstats = append(stats, v.(*playerStats))\n\t\treturn false\n\t})\n\tblocks := make([]int64, len(stats))\n\tfor i, ps := range stats {\n\t\tblocks[i] = effectiveReignBlocks(ps, height)\n\t}\n\tsort.Stable(byReign{stats: stats, blocks: blocks})\n\treturn stats, blocks\n}\n\n// display returns a shortened address for table display.\nfunc display(addr address) string {\n\ts := addr.String()\n\tif len(s) \u003e 12 {\n\t\treturn s[:8] + \"…\" + s[len(s)-4:]\n\t}\n\treturn s\n}\n\n// Render shows the current king and a reign-length leaderboard.\nfunc Render(path string) string {\n\theight := runtime.ChainHeight()\n\n\tout := \"# 👑 King of the Dice\\n\\n\"\n\tout += \"Roll higher than the reigning king to take the throne. The leaderboard \" +\n\t\t\"ranks total blocks held as king, not raw roll count — outlasting beats \" +\n\t\t\"getting lucky once.\\n\\n\"\n\n\tif !king.IsValid() {\n\t\tout += \"_No king yet. Call `Roll()` to make the first claim._\\n\\n\"\n\t} else {\n\t\tout += \"**Current king:** `\" + display(king) + \"` with a roll of **\" +\n\t\t\tstrconv.Itoa(kingRoll) + \"**, reigning for **\" +\n\t\t\tstrconv.Itoa(int(height-reignSince)) + \"** blocks so far.\\n\\n\"\n\t}\n\tout += \"Total rolls: **\" + strconv.Itoa(totalRolls) + \"**\\n\\n\"\n\n\tstats, blocks := snapshot(height)\n\tif len(stats) == 0 {\n\t\treturn out\n\t}\n\n\tout += \"| Rank | Player | Blocks reigned | Reigns | Best roll | Rolls |\\n\"\n\tout += \"| ---: | :--- | ---: | ---: | ---: | ---: |\\n\"\n\tfor i, ps := range stats {\n\t\trankCell := ui.Podium(i)\n\t\tif rankCell == \"\" {\n\t\t\trankCell = strconv.Itoa(i + 1)\n\t\t}\n\t\tout += \"| \" + rankCell +\n\t\t\t\" | \" + display(ps.addr) +\n\t\t\t\" | \" + strconv.Itoa(int(blocks[i])) +\n\t\t\t\" | \" + strconv.Itoa(ps.reigns) +\n\t\t\t\" | \" + strconv.Itoa(ps.bestRoll) +\n\t\t\t\" | \" + strconv.Itoa(ps.rolls) + \" |\\n\"\n\t}\n\treturn out\n}\n"},{"name":"kingofdice_test.gno","body":"package kingofdice\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// resetState clears package globals between tests.\nfunc resetState() {\n\tplayers = avl.Tree{}\n\tvar zero address\n\tking = zero\n\tkingRoll = 0\n\treignSince = 0\n\tnonce = 0\n\ttotalRolls = 0\n}\n\nfunc TestPseudoRollDeterministicAndRanged(t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\n\tr1 := pseudoRoll(alice, 1, 100)\n\tr2 := pseudoRoll(alice, 1, 100)\n\tif r1 != r2 {\n\t\tt.Fatalf(\"same inputs must give same roll: %d != %d\", r1, r2)\n\t}\n\tif r1 \u003c 1 || r1 \u003e 100 {\n\t\tt.Fatalf(\"roll must be in [1, 100], got %d\", r1)\n\t}\n\n\tr3 := pseudoRoll(alice, 2, 100)\n\tif r1 == r3 {\n\t\tt.Fatal(\"different nonce should (almost always) change the roll\")\n\t}\n}\n\n// Crossing test: takes `cur realm` so it can call crossing functions via\n// cross(cur). SetRealm is called directly in this frame.\nfunc TestRollCrownsFirstCallerThenSwapsOnHigherRoll(cur realm, t *testing.T) {\n\tresetState()\n\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRoll(cross(cur))\n\tif !king.IsValid() {\n\t\tt.Fatal(\"someone should be king after first roll\")\n\t}\n\tfirstKing := king\n\n\t// Keep rolling as bob until bob out-rolls alice, or give up after a\n\t// generous number of attempts (rolls are deterministic per nonce/height,\n\t// so this always terminates locally).\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfor i := 0; i \u003c 200 \u0026\u0026 king == firstKing; i++ {\n\t\tRoll(cross(cur))\n\t}\n\n\tif get(alice).reigns != 1 {\n\t\tt.Fatalf(\"alice should have exactly one recorded reign, got %d\", get(alice).reigns)\n\t}\n}\n\nfunc TestRenderShowsNoKingThenKing(cur realm, t *testing.T) {\n\tresetState()\n\tif !strings.Contains(Render(\"\"), \"No king yet\") {\n\t\tt.Fatal(\"expected empty-board placeholder\")\n\t}\n\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRoll(cross(cur))\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Current king\") {\n\t\tt.Fatal(\"expected current king section once someone rolled\")\n\t}\n\tif !strings.Contains(out, \"Blocks reigned\") {\n\t\tt.Fatal(\"expected leaderboard header\")\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"43868200","gas_fee":"131604ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"OBVY+zJYT+JacRAPF+oajVUFq591yZzjQqWCYQz3O3RNERi47fESwsR1ml0GH/rnWsnKOybaOHPQzUwz6tLQMQ=="}],"memo":""},"metadata":{"timestamp":"1790961079"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"kmpdemo","path":"gno.land/r/moul/x/daily/kmpdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/kmpdemo/v0`\n\n**Live demo of [`p/moul/x/daily/kmp`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/kmp).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/kmpdemo/v0`](https://gno.land/r/moul/x/daily/kmpdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/kmpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kmpdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/kmpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kmpdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/kmpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kmpdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/kmpdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kmpdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/kmpdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/kmpdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/kmpdemo/v0\"\ngno = \"0.9\"\n"},{"name":"kmpdemo.gno","body":"// Package kmpdemo is a small gnoweb demo of the Knuth–Morris–Pratt substring\n// search provided by the [p/moul/x/daily/kmp](/p/moul/x/daily/kmp/v0) library:\n// it shows the failure table and overlapping matches.\n//\n// It contains no search logic of its own. Stateless, so Render is\n// deterministic — which is precisely what the library is for.\npackage kmpdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/kmp/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Knuth–Morris–Pratt\\n\\n\")\n\tb.WriteString(\"Linear-time substring search, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/kmp`](/p/moul/x/daily/kmp/v0) library.\\n\\n\")\n\n\tconst text = \"mississippi\"\n\tconst pattern = \"issi\"\n\n\tb.WriteString(\"## Failure table\\n\\n\")\n\tb.WriteString(\"For each prefix of `\" + pattern + \"`, the length of the longest proper \")\n\tb.WriteString(\"prefix that is also a suffix. This is what lets the scan slide the \")\n\tb.WriteString(\"pattern without ever rewinding the text.\\n\\n\")\n\tb.WriteString(\"| i | prefix | table |\\n|---|---|---|\\n\")\n\tfor i, v := range kmp.Table(pattern) {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i) + \" | `\" + pattern[:i+1] + \"` | \" + strconv.Itoa(v) + \" |\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Searching\\n\\n\")\n\tb.WriteString(\"`\" + pattern + \"` in `\" + text + \"`:\\n\\n\")\n\tb.WriteString(\"```\\n\" + text + \"\\n\")\n\thits := kmp.FindAll(text, pattern)\n\tfor _, at := range hits {\n\t\tb.WriteString(strings.Repeat(\" \", at) + strings.Repeat(\"^\", len(pattern)) + \"\\n\")\n\t}\n\tb.WriteString(\"```\\n\\n\")\n\tb.WriteString(\"Matches at \" + offsets(hits) + \" — **overlapping**, and `Count` agrees: \")\n\tb.WriteString(strconv.Itoa(kmp.Count(text, pattern)) + \".\\n\\n\")\n\n\tb.WriteString(\"## Overlap is deliberate\\n\\n\")\n\tb.WriteString(\"`FindAll(\\\"aaaa\\\", \\\"aa\\\")` returns \" + offsets(kmp.FindAll(\"aaaa\", \"aa\")))\n\tb.WriteString(\", not just the disjoint ones — \\\"every occurrence\\\" read honestly. \")\n\tb.WriteString(\"A caller wanting disjoint matches can filter; one wanting overlap \")\n\tb.WriteString(\"could not recover it.\\n\\n\")\n\n\tb.WriteString(\"## Why it belongs on chain\\n\\n\")\n\tb.WriteString(\"The naive scan is O(n·m): `\")\n\tb.WriteString(strings.Repeat(\"a\", 8) + \"b` inside `\" + strings.Repeat(\"a\", 16))\n\tb.WriteString(\"b` re-compares everything it already matched. KMP is O(n+m) with no \")\n\tb.WriteString(\"bad case, so a pathological input is not an attack.\\n\")\n\treturn b.String()\n}\n\nfunc offsets(xs []int) string {\n\tif len(xs) == 0 {\n\t\treturn \"_none_\"\n\t}\n\tparts := make([]string, len(xs))\n\tfor i, x := range xs {\n\t\tparts[i] = \"`\" + strconv.Itoa(x) + \"`\"\n\t}\n\treturn strings.Join(parts, \", \")\n}\n"},{"name":"render_example_test.gno","body":"package kmpdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Knuth–Morris–Pratt\n\t//\n\t// Linear-time substring search, demoing the [`p/moul/x/daily/kmp`](/p/moul/x/daily/kmp/v0) library.\n\t//\n\t// ## Failure table\n\t//\n\t// For each prefix of `issi`, the length of the longest proper prefix that is also a suffix. This is what lets the scan slide the pattern without ever rewinding the text.\n\t//\n\t// | i | prefix | table |\n\t// |---|---|---|\n\t// | 0 | `i` | 0 |\n\t// | 1 | `is` | 0 |\n\t// | 2 | `iss` | 0 |\n\t// | 3 | `issi` | 1 |\n\t//\n\t// ## Searching\n\t//\n\t// `issi` in `mississippi`:\n\t//\n\t// ```\n\t// mississippi\n\t//  ^^^^\n\t//     ^^^^\n\t// ```\n\t//\n\t// Matches at `1`, `4` — **overlapping**, and `Count` agrees: 2.\n\t//\n\t// ## Overlap is deliberate\n\t//\n\t// `FindAll(\"aaaa\", \"aa\")` returns `0`, `1`, `2`, not just the disjoint ones — \"every occurrence\" read honestly. A caller wanting disjoint matches can filter; one wanting overlap could not recover it.\n\t//\n\t// ## Why it belongs on chain\n\t//\n\t// The naive scan is O(n·m): `aaaaaaaab` inside `aaaaaaaaaaaaaaaab` re-compares everything it already matched. KMP is O(n+m) with no bad case, so a pathological input is not an attack.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"27636400","gas_fee":"82909ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"TMkE5dl4+ssGnkj3FRxlK63RrluEnq9duS8MBx1tgfIRmxN7de7Y1VLqjsOqpD56q6XfPXnC202LYyuJatF+5w=="}],"memo":""},"metadata":{"timestamp":"1790961080"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"kudos","path":"gno.land/r/moul/x/daily/kudos/v0","files":[{"name":"README.md","body":"# Kudos\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nGive props to other addresses on-chain. Anyone can call `Give` to credit another\naddress with a kudos and a short reason; you cannot kudos yourself. The realm keeps\na running leaderboard of the most-appreciated addresses and a rolling feed of the\nmost recent kudos.\n\nRealm path: `gno.land/r/REPLACE_ADDR/kudos`\n\n## Example calls\n\n```\n# Give a kudos to another address\nGive(to=\"g1...bob\", reason=\"great code review\")\n\n# View the leaderboard + recent feed (read-only)\nRender(\"\")\n```\n\n`Render` returns Markdown: a ranked leaderboard table (address, kudos count) followed\nby a recent-kudos feed (`from → to: reason`).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/kudos/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kudos/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/kudos/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kudos/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/kudos/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kudos/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/kudos/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/kudos/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/kudos/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/kudos/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/kudos/v0\"\ngno = \"0.9\"\n"},{"name":"kudos.gno","body":"package kudos\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// counts maps an address (as string) -\u003e number of kudos received.\nvar counts avl.Tree\n\n// feed holds recent kudos, newest first, capped at feedCap entries.\nvar feed []kudo\n\nconst feedCap = 50\n\ntype kudo struct {\n\tfrom   address\n\tto     address\n\treason string\n}\n\n// Give records a kudos from the caller to `to` with a reason.\n// A caller cannot give kudos to themselves.\nfunc Give(cur realm, to address, reason string) {\n\tfrom := unsafe.PreviousRealm().Address()\n\tif !to.IsValid() {\n\t\tpanic(\"invalid recipient address\")\n\t}\n\tif from == to {\n\t\tpanic(\"cannot give kudos to yourself\")\n\t}\n\treason = strings.TrimSpace(reason)\n\tif reason == \"\" {\n\t\tpanic(\"reason must not be empty\")\n\t}\n\n\tkey := to.String()\n\tn := int64(0)\n\tif v := counts.Get(key); v != nil {\n\t\tn = v.(int64)\n\t}\n\tcounts.Set(key, n+1)\n\n\t// prepend newest, cap the feed\n\tfeed = append([]kudo{{from: from, to: to, reason: reason}}, feed...)\n\tif len(feed) \u003e feedCap {\n\t\tfeed = feed[:feedCap]\n\t}\n\n\tchain.Emit(\"KudosGiven\", \"from\", from.String(), \"to\", to.String(), \"reason\", reason)\n}\n\n// entry is a leaderboard row used for deterministic sorting.\ntype entry struct {\n\taddr  string\n\tcount int64\n}\n\n// byScore sorts by count desc, then address asc for stable ties.\ntype byScore []entry\n\nfunc (s byScore) Len() int      { return len(s) }\nfunc (s byScore) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s byScore) Less(i, j int) bool {\n\tif s[i].count != s[j].count {\n\t\treturn s[i].count \u003e s[j].count\n\t}\n\treturn s[i].addr \u003c s[j].addr\n}\n\nfunc leaderboard() []entry {\n\tout := make([]entry, 0, counts.Size())\n\tcounts.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tout = append(out, entry{addr: key, count: value.(int64)})\n\t\treturn false\n\t})\n\tsort.Sort(byScore(out))\n\treturn out\n}\n\n// Render shows a leaderboard of most-received addresses and a recent feed.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Kudos\\n\\n\")\n\tb.WriteString(\"Give props to addresses. `Give(to, reason)` records a kudos.\\n\\n\")\n\n\tb.WriteString(\"## Leaderboard\\n\\n\")\n\tlb := leaderboard()\n\tif len(lb) == 0 {\n\t\tb.WriteString(\"_No kudos yet._\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| # | Address | Kudos |\\n\")\n\t\tb.WriteString(\"| --- | --- | --- |\\n\")\n\t\tfor i, e := range lb {\n\t\t\tb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | \" + e.addr + \" | \" + strconv.FormatInt(e.count, 10) + \" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"## Recent kudos\\n\\n\")\n\tif len(feed) == 0 {\n\t\tb.WriteString(\"_Nothing here yet._\\n\")\n\t} else {\n\t\tfor _, k := range feed {\n\t\t\tb.WriteString(\"- \" + k.from.String() + \" → \" + k.to.String() + \": \" + k.reason + \"\\n\")\n\t\t}\n\t}\n\n\treturn b.String()\n}\n"},{"name":"kudos_test.gno","body":"package kudos\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestGiveAndLeaderboard(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tcarol := testutils.TestAddress(\"carol\")\n\n\t// reset package state between test funcs\n\tcounts = avl.Tree{}\n\tfeed = nil\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tGive(cross(cur), bob, \"great review\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tGive(cross(cur), bob, \"helpful pairing\")\n\tGive(cross(cur), alice, \"nice docs\")\n\n\tlb := leaderboard()\n\tuassert.Equal(t, 2, len(lb))\n\t// bob has 2, alice has 1 -\u003e bob first\n\tuassert.Equal(t, bob.String(), lb[0].addr)\n\tuassert.Equal(t, int64(2), lb[0].count)\n\tuassert.Equal(t, alice.String(), lb[1].addr)\n\tuassert.Equal(t, int64(1), lb[1].count)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"helpful pairing\"))\n\tuassert.True(t, strings.Contains(out, \"Leaderboard\"))\n}\n\nfunc TestCannotKudosSelf(cur realm, t *testing.T) {\n\tdave := testutils.TestAddress(\"dave\")\n\n\tcounts = avl.Tree{}\n\tfeed = nil\n\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tuassert.AbortsWithMessage(t, cur, \"cannot give kudos to yourself\", func() {\n\t\tGive(cross(cur), dave, \"self five\")\n\t})\n}\n\nfunc TestEmptyReasonAborts(cur realm, t *testing.T) {\n\teve := testutils.TestAddress(\"eve\")\n\tfrank := testutils.TestAddress(\"frank\")\n\n\tcounts = avl.Tree{}\n\tfeed = nil\n\n\ttesting.SetRealm(testing.NewUserRealm(eve))\n\tuassert.AbortsWithMessage(t, cur, \"reason must not be empty\", func() {\n\t\tGive(cross(cur), frank, \"   \")\n\t})\n}\n"},{"name":"render_example_test.gno","body":"package kudos\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Kudos\n\t//\n\t// Give props to addresses. `Give(to, reason)` records a kudos.\n\t//\n\t// ## Leaderboard\n\t//\n\t// _No kudos yet._\n\t//\n\t// ## Recent kudos\n\t//\n\t// _Nothing here yet._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"30772000","gas_fee":"92316ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"D48Bc2r7WLa7S5bPhO/MG06s+q41maTR8fJ/nkeFvx1DPCZrH1Lnymbt0kTzc8qlBZAlWLPjjmwKBjtY6L9xFQ=="}],"memo":""},"metadata":{"timestamp":"1790961081"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"leaderboard","path":"gno.land/r/moul/x/daily/leaderboard/v1","files":[{"name":"README.md","body":"# 🏆 Leaderboard\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn on-chain score leaderboard realm for gno.land (sapphire / gno 0.9). Any account\ncan accumulate points with `AddPoints(n)` and optionally attach a display name\nwith `SetName(name)`. `Render` returns a Markdown table ranked by points\ndescending — gold/silver/bronze medals for the top three — plus the total player\ncount. State is kept in an `avl.Tree` so rendering is deterministic across nodes.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/leaderboard`\n\n## Public API\n\n| Function | Kind | Description |\n| --- | --- | --- |\n| `AddPoints(cur realm, n int)` | crossing (tx) | Add `n` (\u003e 0) points to the caller's total. |\n| `SetName(cur realm, name string)` | crossing (tx) | Set the caller's display name (≤ 32 bytes; empty clears it). |\n| `Render(path string) string` | view | Ranked Markdown leaderboard. |\n\n## Example calls\n\n```sh\n# Add 10 points to your total\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/REPLACE_ADDR/leaderboard\" \\\n  -func AddPoints -args 10 \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e \u003ckeyname\u003e\n\n# Set your display name\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/REPLACE_ADDR/leaderboard\" \\\n  -func SetName -args \"Alice\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e \u003ckeyname\u003e\n```\n\nView the rendered leaderboard in gnoweb at\n`/r/REPLACE_ADDR/leaderboard`, or query it:\n\n```sh\ngnokey query \"vm/qrender\" -data \"gno.land/r/REPLACE_ADDR/leaderboard:\" -remote \u003crpc\u003e\n```\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/leaderboard) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `medal` helper.\n\n**One podium.** `ui.Podium` replaces the medal switch three realms each had a copy of. Same output.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/leaderboard/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/leaderboard/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/leaderboard/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/leaderboard/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/leaderboard/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/leaderboard/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/leaderboard/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/leaderboard/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/leaderboard/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/leaderboard/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/leaderboard/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"leaderboard.gno","body":"// Package leaderboard is an on-chain score leaderboard realm.\n//\n// Any account can accumulate points via AddPoints and (optionally) attach a\n// display name with SetName. Render produces a ranked Markdown table sorted by\n// points descending, with medals for the top three players.\npackage leaderboard\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// player holds the accumulated state for a single address.\ntype player struct {\n\taddr   address\n\tname   string\n\tpoints int\n}\n\n// players maps address string -\u003e *player. An avl.Tree gives deterministic\n// iteration (unlike a Go map) so Render output is stable across nodes.\nvar players avl.Tree\n\n// get returns the stored *player for addr, creating one if absent.\nfunc get(addr address) *player {\n\tkey := addr.String()\n\tif v := players.Get(key); v != nil {\n\t\treturn v.(*player)\n\t}\n\tp := \u0026player{addr: addr}\n\tplayers.Set(key, p)\n\treturn p\n}\n\n// caller returns the address of the account that invoked the current tx.\n// unsafe.PreviousRealm() is the origin user for a MsgCall entry point.\nfunc caller() address {\n\treturn unsafe.PreviousRealm().Address()\n}\n\n// AddPoints adds n points to the caller's total. n must be positive.\n//\n// Crossing function: MsgCall dispatches only to crossing functions, and the\n// cur.IsCurrent() check authenticates the live call frame before we trust the\n// caller identity derived from it.\nfunc AddPoints(cur realm, n int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tif n \u003c= 0 {\n\t\tpanic(\"points must be positive\")\n\t}\n\tp := get(caller())\n\tp.points += n\n}\n\n// SetName attaches a display name (max 32 bytes) to the caller. Passing an\n// empty string clears the name and falls back to the address in Render.\nfunc SetName(cur realm, name string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tif len(name) \u003e 32 {\n\t\tpanic(\"name too long (max 32)\")\n\t}\n\tget(caller()).name = name\n}\n\n// display returns the player's name, or a shortened address if unnamed.\nfunc (p *player) display() string {\n\tif p.name != \"\" {\n\t\treturn p.name\n\t}\n\ts := p.addr.String()\n\tif len(s) \u003e 12 {\n\t\treturn s[:8] + \"…\" + s[len(s)-4:]\n\t}\n\treturn s\n}\n\n// byRank implements sort.Interface, ranking players by points descending with\n// ties broken by address so the order is deterministic across nodes. The gno\n// sort package exposes Sort/Stable over an Interface — there is no sort.Slice.\ntype byRank []*player\n\nfunc (r byRank) Len() int      { return len(r) }\nfunc (r byRank) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byRank) Less(i, j int) bool {\n\tif r[i].points != r[j].points {\n\t\treturn r[i].points \u003e r[j].points\n\t}\n\treturn r[i].addr.String() \u003c r[j].addr.String()\n}\n\n// snapshot collects all players into a slice ranked by points descending.\nfunc snapshot() []*player {\n\tout := make([]*player, 0, players.Size())\n\tplayers.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tout = append(out, v.(*player))\n\t\treturn false\n\t})\n\tsort.Stable(byRank(out))\n\treturn out\n}\n\n// Render produces the Markdown leaderboard. It is NOT a crossing function\n// (read-only view, no cur realm parameter).\nfunc Render(path string) string {\n\tranked := snapshot()\n\n\tout := \"# 🏆 Leaderboard\\n\\n\"\n\tif len(ranked) == 0 {\n\t\tout += \"_No players yet. Call `AddPoints(n)` to get on the board._\\n\"\n\t\treturn out\n\t}\n\n\tout += \"Total players: **\" + strconv.Itoa(len(ranked)) + \"**\\n\\n\"\n\tout += \"| Rank | Player | Points |\\n\"\n\tout += \"| ---: | :--- | ---: |\\n\"\n\tfor i, p := range ranked {\n\t\trankCell := ui.Podium(i)\n\t\tif rankCell == \"\" {\n\t\t\trankCell = strconv.Itoa(i + 1)\n\t\t}\n\t\tout += \"| \" + rankCell +\n\t\t\t\" | \" + p.display() +\n\t\t\t\" | \" + strconv.Itoa(p.points) + \" |\\n\"\n\t}\n\treturn out\n}\n"},{"name":"leaderboard_test.gno","body":"package leaderboard\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// resetState clears package globals between tests. Global-state reset belongs\n// in a helper; realm setup (SetRealm) must NOT — it only affects its own frame.\nfunc resetState() {\n\tkeys := []string{}\n\tplayers.Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\tkeys = append(keys, key)\n\t\treturn false\n\t})\n\tfor _, k := range keys {\n\t\tplayers.Remove(k)\n\t}\n}\n\nconst (\n\talice = \"g1alice00000000000000000000000000000000\"\n\tbob   = \"g1bob0000000000000000000000000000000000\"\n\tcarol = \"g1carol00000000000000000000000000000000\"\n)\n\n// Crossing test: takes `cur realm` so it can call crossing functions via\n// cross(cur). SetRealm is called directly in this frame (never via a helper).\nfunc TestAddPointsAccumulatesAndRanks(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(address(alice)))\n\tAddPoints(cross(cur), 10)\n\tAddPoints(cross(cur), 5) // accumulates -\u003e 15\n\n\ttesting.SetRealm(testing.NewUserRealm(address(bob)))\n\tAddPoints(cross(cur), 20)\n\n\tuassert.Equal(t, 15, get(address(alice)).points, \"alice points\")\n\tuassert.Equal(t, 20, get(address(bob)).points, \"bob points\")\n\n\t// Ranking: bob (20) outranks alice (15).\n\tranked := snapshot()\n\tuassert.Equal(t, 2, len(ranked), \"player count\")\n\tuassert.Equal(t, bob, ranked[0].addr.String(), \"rank 1 is bob\")\n\tuassert.Equal(t, alice, ranked[1].addr.String(), \"rank 2 is alice\")\n}\n\nfunc TestRenderTableWithMedalsAndName(cur realm, t *testing.T) {\n\tresetState()\n\n\t// Empty board.\n\tuassert.True(t, strings.Contains(Render(\"\"), \"No players yet\"), \"empty placeholder\")\n\n\ttesting.SetRealm(testing.NewUserRealm(address(alice)))\n\tAddPoints(cross(cur), 30)\n\tSetName(cross(cur), \"Alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(address(bob)))\n\tAddPoints(cross(cur), 20)\n\n\ttesting.SetRealm(testing.NewUserRealm(address(carol)))\n\tAddPoints(cross(cur), 10)\n\n\tout := Render(\"\")\n\n\tuassert.True(t, strings.Contains(out, \"| 🥇 | Alice | 30 |\"), \"Alice gold row\")\n\tuassert.True(t, strings.Contains(out, \"🥈\"), \"silver medal present\")\n\tuassert.True(t, strings.Contains(out, \"🥉\"), \"bronze medal present\")\n\tuassert.True(t, strings.Contains(out, \"Total players: **3**\"), \"total players count\")\n}\n\nfunc TestSetNameTooLongPanics(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(address(alice)))\n\tuassert.AbortsWithMessage(t, cur, \"name too long (max 32)\", func() {\n\t\tSetName(cross(cur), strings.Repeat(\"x\", 33))\n\t})\n}\n\nfunc TestAddPointsRejectsNonPositive(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(address(alice)))\n\tuassert.AbortsWithMessage(t, cur, \"points must be positive\", func() {\n\t\tAddPoints(cross(cur), 0)\n\t})\n}\n"},{"name":"render_example_test.gno","body":"package leaderboard\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # 🏆 Leaderboard\n\t//\n\t// _No players yet. Call `AddPoints(n)` to get on the board._\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"39991600","gas_fee":"119974ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"4ra6JPyGBe8DQzfVri0mwPLA/qboi6fYxj39O5C57iYY4PGITp4qz3N+7IxGl30C+0Tbo4AytLDIcngZ8uPSFQ=="}],"memo":""},"metadata":{"timestamp":"1790961081"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"levenshteindemo","path":"gno.land/r/moul/x/daily/levenshteindemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/levenshteindemo/v0`\n\nInteractive gnoweb **demo of the [`p/moul/x/daily/levenshtein`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/levenshtein)\nedit-distance library** — it renders an explanation, worked examples, and a\ndistance calculator with the full dynamic-programming table. It has no distance\nlogic of its own.\n\nAppend two words as `/\u003ca\u003e/\u003cb\u003e` to compute their distance, e.g.\n[`/r/moul/x/daily/levenshteindemo/v0:kitten/sitting`](https://gno.land/r/moul/x/daily/levenshteindemo/v0:kitten/sitting).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/levenshteindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/levenshteindemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/levenshteindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/levenshteindemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/levenshteindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/levenshteindemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/levenshteindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/levenshteindemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/levenshteindemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/levenshteindemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/levenshteindemo/v0\"\ngno = \"0.9\"\n"},{"name":"levenshteindemo.gno","body":"// Package levenshteindemo is a small gnoweb demo of the Levenshtein edit-distance\n// library provided by [p/moul/x/daily/levenshtein](/p/moul/x/daily/levenshtein/v0):\n// it renders an explanation, worked examples, and an interactive distance\n// calculator with the full dynamic-programming table.\n//\n// It contains no distance logic of its own — everything comes from\n// `levenshtein.Distance`, `levenshtein.Matrix` and `levenshtein.Similarity`.\npackage levenshteindemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/levenshtein/v0\"\n)\n\n// Render implements the gnoweb view.\n//\n//   - \"\" or \"/\"            : explanation + examples.\n//   - \"/\u003ca\u003e/\u003cb\u003e\"           : distance between a and b, with the DP table.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\n\tparts := strings.SplitN(path, \"/\", 2)\n\tif len(parts) != 2 {\n\t\tvar sb strings.Builder\n\t\tsb.WriteString(\"# Levenshtein\\n\\n\")\n\t\tsb.WriteString(\"Provide two words as `/\u003ca\u003e/\u003cb\u003e`, e.g. [`/kitten/sitting`](/r/moul/x/daily/levenshteindemo/v0:kitten/sitting).\\n\\n\")\n\t\tsb.WriteString(\"[← back](/r/moul/x/daily/levenshteindemo/v0)\\n\")\n\t\treturn sb.String()\n\t}\n\n\ta := parts[0]\n\tb := parts[1]\n\tdist := levenshtein.Distance(a, b)\n\tsim := levenshtein.Similarity(a, b)\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Levenshtein distance\\n\\n\")\n\tsb.WriteString(\"Transforming **`\")\n\tsb.WriteString(a)\n\tsb.WriteString(\"`** → **`\")\n\tsb.WriteString(b)\n\tsb.WriteString(\"`**\\n\\n\")\n\tsb.WriteString(\"- **Edit distance:** `\")\n\tsb.WriteString(strconv.Itoa(dist))\n\tsb.WriteString(\"` single-character edits (insert / delete / substitute)\\n\")\n\tsb.WriteString(\"- **Similarity:** `\")\n\tsb.WriteString(strconv.Itoa(sim))\n\tsb.WriteString(\"%`\\n\\n\")\n\n\tsb.WriteString(\"## DP table\\n\\n\")\n\tsb.WriteString(\"Each cell `d[i][j]` is the distance between the first *i* runes of `\")\n\tsb.WriteString(a)\n\tsb.WriteString(\"` and the first *j* runes of `\")\n\tsb.WriteString(b)\n\tsb.WriteString(\"`. The bottom-right cell is the answer.\\n\\n\")\n\tsb.WriteString(renderTable(a, b))\n\tsb.WriteString(\"\\n[← back](/r/moul/x/daily/levenshteindemo/v0)\\n\")\n\treturn sb.String()\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Levenshtein edit distance\\n\\n\")\n\tsb.WriteString(\"Demo of the [`p/moul/x/daily/levenshtein`](/p/moul/x/daily/levenshtein/v0) library. \")\n\tsb.WriteString(\"The **Levenshtein distance** between two strings is the minimum number of \")\n\tsb.WriteString(\"single-character edits — *insertions*, *deletions*, or *substitutions* — \")\n\tsb.WriteString(\"needed to turn one string into the other. The library implements the classic \")\n\tsb.WriteString(\"dynamic-programming algorithm (à la Go's `agext/levenshtein`) fully rune-aware and on-chain.\\n\\n\")\n\n\tsb.WriteString(\"## Try it\\n\\n\")\n\tsb.WriteString(\"Append two words as `/\u003ca\u003e/\u003cb\u003e`:\\n\\n\")\n\texamples := [][2]string{\n\t\t{\"kitten\", \"sitting\"},\n\t\t{\"flaw\", \"lawn\"},\n\t\t{\"sunday\", \"saturday\"},\n\t\t{\"gno\", \"gnoland\"},\n\t}\n\tfor _, ex := range examples {\n\t\ta, b := ex[0], ex[1]\n\t\td := levenshtein.Distance(a, b)\n\t\tsb.WriteString(\"- [`/\")\n\t\tsb.WriteString(a)\n\t\tsb.WriteString(\"/\")\n\t\tsb.WriteString(b)\n\t\tsb.WriteString(\"`](/r/moul/x/daily/levenshteindemo/v0:\")\n\t\tsb.WriteString(a)\n\t\tsb.WriteString(\"/\")\n\t\tsb.WriteString(b)\n\t\tsb.WriteString(\") → distance **\")\n\t\tsb.WriteString(strconv.Itoa(d))\n\t\tsb.WriteString(\"**\\n\")\n\t}\n\n\tsb.WriteString(\"\\n## The classic example\\n\\n\")\n\tsb.WriteString(\"`kitten` → `sitting` = **3**:\\n\\n\")\n\tsb.WriteString(\"1. `kitten` → `sitten` (substitute *k* → *s*)\\n\")\n\tsb.WriteString(\"2. `sitten` → `sittin` (substitute *e* → *i*)\\n\")\n\tsb.WriteString(\"3. `sittin` → `sitting` (insert *g* at the end)\\n\\n\")\n\n\tsb.WriteString(\"## API\\n\\n\")\n\tsb.WriteString(\"- `Distance(a, b string) int` — the edit distance.\\n\")\n\tsb.WriteString(\"- `Matrix(a, b string) [][]int` — the full DP matrix.\\n\")\n\tsb.WriteString(\"- `Similarity(a, b string) int` — a 0..100 similarity percentage.\\n\")\n\treturn sb.String()\n}\n\n// renderTable formats the DP matrix as a Markdown table with a and b as headers.\nfunc renderTable(a, b string) string {\n\tra := []rune(a)\n\trb := []rune(b)\n\td := levenshtein.Matrix(a, b)\n\n\tvar sb strings.Builder\n\t// Header row: blank | \"\" | each rune of b.\n\tsb.WriteString(\"|   | ε |\")\n\tfor _, r := range rb {\n\t\tsb.WriteString(\" `\")\n\t\tsb.WriteString(string(r))\n\t\tsb.WriteString(\"` |\")\n\t}\n\tsb.WriteString(\"\\n\")\n\t// Separator.\n\tsb.WriteString(\"|---|\")\n\tfor j := 0; j \u003c= len(rb); j++ {\n\t\tsb.WriteString(\"---|\")\n\t}\n\tsb.WriteString(\"\\n\")\n\t// Data rows.\n\tfor i := 0; i \u003c= len(ra); i++ {\n\t\tif i == 0 {\n\t\t\tsb.WriteString(\"| **ε** |\")\n\t\t} else {\n\t\t\tsb.WriteString(\"| **`\")\n\t\t\tsb.WriteString(string(ra[i-1]))\n\t\t\tsb.WriteString(\"`** |\")\n\t\t}\n\t\tfor j := 0; j \u003c= len(rb); j++ {\n\t\t\tsb.WriteString(\" \")\n\t\t\tsb.WriteString(strconv.Itoa(d[i][j]))\n\t\t\tsb.WriteString(\" |\")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\treturn sb.String()\n}\n"},{"name":"render_example_test.gno","body":"package levenshteindemo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Levenshtein edit distance\n\t//\n\t// Demo of the [`p/moul/x/daily/levenshtein`](/p/moul/x/daily/levenshtein/v0) library. The **Levenshtein distance** between two strings is the minimum number of single-character edits — *insertions*, *deletions*, or *substitutions* — needed to turn one string into the other. The library implements the classic dynamic-programming algorithm (à la Go's `agext/levenshtein`) fully rune-aware and on-chain.\n\t//\n\t// ## Try it\n\t//\n\t// Append two words as `/\u003ca\u003e/\u003cb\u003e`:\n\t//\n\t// - [`/kitten/sitting`](/r/moul/x/daily/levenshteindemo/v0:kitten/sitting) → distance **3**\n\t// - [`/flaw/lawn`](/r/moul/x/daily/levenshteindemo/v0:flaw/lawn) → distance **2**\n\t// - [`/sunday/saturday`](/r/moul/x/daily/levenshteindemo/v0:sunday/saturday) → distance **3**\n\t// - [`/gno/gnoland`](/r/moul/x/daily/levenshteindemo/v0:gno/gnoland) → distance **4**\n\t//\n\t// ## The classic example\n\t//\n\t// `kitten` → `sitting` = **3**:\n\t//\n\t// 1. `kitten` → `sitten` (substitute *k* → *s*)\n\t// 2. `sitten` → `sittin` (substitute *e* → *i*)\n\t// 3. `sittin` → `sitting` (insert *g* at the end)\n\t//\n\t// ## API\n\t//\n\t// - `Distance(a, b string) int` — the edit distance.\n\t// - `Matrix(a, b string) [][]int` — the full DP matrix.\n\t// - `Similarity(a, b string) int` — a 0..100 similarity percentage.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"34183200","gas_fee":"102549ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"pvDPa5qC93HXWcE6e5b9/7HWEK0ljOJtkWVVZN+e7YUNmDZbb9e31DW6zQhwChMLxsa8isJBHdk3EtaQB22bvA=="}],"memo":""},"metadata":{"timestamp":"1790961082"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"life","path":"gno.land/r/moul/x/daily/life/v0","files":[{"name":"README.md","body":"# Conway's Game of Life\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA port of Conway's classic cellular automaton to gno.land. The full board\nlives on-chain — every generation tick is a real transaction, shared state\nfor whoever is watching.\n\n**Realm path:** `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/life`\n\n## How it works\n\nThe board starts as a 20×15 grid seeded with a glider. Anyone can call\n`Step()` to tick the simulation, load a classic pattern, or sculpt cells\nby hand. All state persists between blocks.\n\n## Example calls\n\n```bash\n# Advance one generation\ngnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/life -func Step ...\n\n# Jump 10 generations at once\ngnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/life -func MultiStep \\\n  -args '10' ...\n\n# Load the classic glider (top-left corner)\ngnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/life -func LoadPreset \\\n  -args 'glider' ...\n\n# Paint a live cell at (5, 5)\ngnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/life -func SetCell \\\n  -args '5 5 true' ...\n\n# Resize to a 30×20 board (clears state)\ngnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/life -func Reset \\\n  -args '30 20' ...\n```\n\n## Presets\n\n| Name | Type | Period | Notes |\n|------|------|--------|-------|\n| `glider` | Spaceship | 4 | Travels diagonally |\n| `blinker` | Oscillator | 2 | Simplest oscillator |\n| `toad` | Oscillator | 2 | Two-row alternation |\n| `beacon` | Oscillator | 2 | Two interlocked blocks |\n| `block` | Still life | — | Stable 2×2 square |\n| `pulsar` | Oscillator | 3 | Large symmetric pattern |\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/life/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/life/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/life/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/life/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/life/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/life/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/life/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/life/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/life/v0\"\ngno = \"0.9\"\n"},{"name":"life.gno","body":"// Conway's Game of Life on Gno — the entire board lives on-chain.\n// Anyone can call Step() to tick the simulation forward, load classic\n// patterns, or sculpt cells one by one.\npackage life\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tMaxWidth  = 50\n\tMaxHeight = 40\n)\n\nvar (\n\twidth      = 20\n\theight     = 15\n\tcells      []bool\n\tgeneration int\n\tpopulation int\n)\n\nfunc init() {\n\tinitBoard(width, height)\n\tLoadPreset(\"glider\")\n}\n\nfunc initBoard(w, h int) {\n\tif w \u003c 1 {\n\t\tw = 1\n\t}\n\tif w \u003e MaxWidth {\n\t\tw = MaxWidth\n\t}\n\tif h \u003c 1 {\n\t\th = 1\n\t}\n\tif h \u003e MaxHeight {\n\t\th = MaxHeight\n\t}\n\twidth = w\n\theight = h\n\tcells = make([]bool, width*height)\n\tgeneration = 0\n\tpopulation = 0\n}\n\nfunc cellIdx(x, y int) int {\n\treturn y*width + x\n}\n\nfunc alive(x, y int) bool {\n\tif x \u003c 0 || x \u003e= width || y \u003c 0 || y \u003e= height {\n\t\treturn false\n\t}\n\treturn cells[cellIdx(x, y)]\n}\n\nfunc countNeighbors(x, y int) int {\n\tn := 0\n\tfor dy := -1; dy \u003c= 1; dy++ {\n\t\tfor dx := -1; dx \u003c= 1; dx++ {\n\t\t\tif dx == 0 \u0026\u0026 dy == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif alive(x+dx, y+dy) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\n// Step advances the simulation by exactly one generation.\nfunc Step() {\n\tnext := make([]bool, width*height)\n\tnewPop := 0\n\tfor y := 0; y \u003c height; y++ {\n\t\tfor x := 0; x \u003c width; x++ {\n\t\t\tn := countNeighbors(x, y)\n\t\t\tvar live bool\n\t\t\tif alive(x, y) {\n\t\t\t\tlive = n == 2 || n == 3\n\t\t\t} else {\n\t\t\t\tlive = n == 3\n\t\t\t}\n\t\t\tnext[cellIdx(x, y)] = live\n\t\t\tif live {\n\t\t\t\tnewPop++\n\t\t\t}\n\t\t}\n\t}\n\tcells = next\n\tpopulation = newPop\n\tgeneration++\n}\n\n// MultiStep advances the simulation by n generations (capped at 100).\nfunc MultiStep(n int) {\n\tif n \u003c 1 {\n\t\tn = 1\n\t}\n\tif n \u003e 100 {\n\t\tn = 100\n\t}\n\tfor i := 0; i \u003c n; i++ {\n\t\tStep()\n\t}\n}\n\n// SetCell sets or clears a specific cell.\nfunc SetCell(x, y int, live bool) {\n\tif x \u003c 0 || x \u003e= width || y \u003c 0 || y \u003e= height {\n\t\treturn\n\t}\n\ti := cellIdx(x, y)\n\twas := cells[i]\n\tcells[i] = live\n\tif live \u0026\u0026 !was {\n\t\tpopulation++\n\t} else if !live \u0026\u0026 was {\n\t\tpopulation--\n\t}\n}\n\n// Reset clears the board and resizes it to w×h.\nfunc Reset(w, h int) {\n\tinitBoard(w, h)\n}\n\n// LoadPreset loads a classic Game of Life pattern onto the current board.\n// Names: glider, blinker, toad, beacon, block, pulsar.\nfunc LoadPreset(name string) {\n\tfor i := range cells {\n\t\tcells[i] = false\n\t}\n\tgeneration = 0\n\tpopulation = 0\n\n\tcx := width / 2\n\tcy := height / 2\n\n\tswitch name {\n\tcase \"glider\":\n\t\t//  .O.\n\t\t//  ..O\n\t\t//  OOO\n\t\tSetCell(1, 0, true)\n\t\tSetCell(2, 1, true)\n\t\tSetCell(0, 2, true)\n\t\tSetCell(1, 2, true)\n\t\tSetCell(2, 2, true)\n\n\tcase \"blinker\":\n\t\t// OOO  (period-2 oscillator)\n\t\tSetCell(cx-1, cy, true)\n\t\tSetCell(cx, cy, true)\n\t\tSetCell(cx+1, cy, true)\n\n\tcase \"toad\":\n\t\t// period-2 oscillator\n\t\tSetCell(cx, cy-1, true)\n\t\tSetCell(cx+1, cy-1, true)\n\t\tSetCell(cx+2, cy-1, true)\n\t\tSetCell(cx-1, cy, true)\n\t\tSetCell(cx, cy, true)\n\t\tSetCell(cx+1, cy, true)\n\n\tcase \"beacon\":\n\t\t// period-2 oscillator\n\t\tSetCell(cx-2, cy-2, true)\n\t\tSetCell(cx-1, cy-2, true)\n\t\tSetCell(cx-2, cy-1, true)\n\t\tSetCell(cx, cy, true)\n\t\tSetCell(cx+1, cy, true)\n\t\tSetCell(cx, cy+1, true)\n\t\tSetCell(cx+1, cy+1, true)\n\n\tcase \"block\":\n\t\t// 2×2 still life\n\t\tSetCell(cx, cy, true)\n\t\tSetCell(cx+1, cy, true)\n\t\tSetCell(cx, cy+1, true)\n\t\tSetCell(cx+1, cy+1, true)\n\n\tcase \"pulsar\":\n\t\t// period-3 oscillator (needs at least 17×17 board)\n\t\tfor _, d := range []int{-4, -3, -2, 2, 3, 4} {\n\t\t\tSetCell(cx+d, cy-6, true)\n\t\t\tSetCell(cx+d, cy-1, true)\n\t\t\tSetCell(cx+d, cy+1, true)\n\t\t\tSetCell(cx+d, cy+6, true)\n\t\t\tSetCell(cx-6, cy+d, true)\n\t\t\tSetCell(cx-1, cy+d, true)\n\t\t\tSetCell(cx+1, cy+d, true)\n\t\t\tSetCell(cx+6, cy+d, true)\n\t\t}\n\n\tdefault:\n\t\tLoadPreset(\"glider\")\n\t}\n}\n\n// Render returns a Markdown snapshot of the current board.\nfunc Render(path string) string {\n\tout := \"# Conway's Game of Life\\n\\n\"\n\tout += \"\u003e A classic cellular automaton, ported to Gno — board state lives on-chain.\\n\\n\"\n\tout += \"**Generation:** \" + strconv.Itoa(generation)\n\tout += \" | **Population:** \" + strconv.Itoa(population)\n\tout += \" | **Board:** \" + strconv.Itoa(width) + \"×\" + strconv.Itoa(height) + \"\\n\\n\"\n\n\tborder := \"+\" + strings.Repeat(\"-\", width) + \"+\\n\"\n\tout += \"```\\n\"\n\tout += border\n\tfor y := 0; y \u003c height; y++ {\n\t\trow := \"|\"\n\t\tfor x := 0; x \u003c width; x++ {\n\t\t\tif alive(x, y) {\n\t\t\t\trow += \"O\"\n\t\t\t} else {\n\t\t\t\trow += \".\"\n\t\t\t}\n\t\t}\n\t\trow += \"|\\n\"\n\t\tout += row\n\t}\n\tout += border\n\tout += \"```\\n\\n\"\n\n\tout += \"## Transactions\\n\\n\"\n\tout += \"| Call | Effect |\\n\"\n\tout += \"|---|---|\\n\"\n\tout += \"| `Step()` | Advance one generation |\\n\"\n\tout += \"| `MultiStep(n)` | Advance *n* generations (max 100) |\\n\"\n\tout += \"| `SetCell(x, y, alive)` | Flip a single cell |\\n\"\n\tout += \"| `Reset(w, h)` | Clear and resize (max \" + strconv.Itoa(MaxWidth) + \"×\" + strconv.Itoa(MaxHeight) + \") |\\n\"\n\tout += \"| `LoadPreset(name)` | `glider` · `blinker` · `toad` · `beacon` · `block` · `pulsar` |\\n\\n\"\n\n\tout += \"## Rules\\n\\n\"\n\tout += \"1. A live cell with 2 or 3 live neighbours survives.\\n\"\n\tout += \"2. A dead cell with exactly 3 live neighbours becomes alive.\\n\"\n\tout += \"3. All other cells die or remain dead.\\n\"\n\n\treturn out\n}\n"},{"name":"life_test.gno","body":"package life\n\nimport (\n\t\"testing\"\n)\n\nfunc TestBlinker(t *testing.T) {\n\tinitBoard(7, 7)\n\t// Horizontal blinker centred at (3,3)\n\tSetCell(2, 3, true)\n\tSetCell(3, 3, true)\n\tSetCell(4, 3, true)\n\n\tif population != 3 {\n\t\tt.Errorf(\"initial population: want 3, got %d\", population)\n\t}\n\n\tStep()\n\n\t// Step 1: vertical at (3,2),(3,3),(3,4)\n\tif !alive(3, 2) {\n\t\tt.Error(\"want (3,2) alive after step 1\")\n\t}\n\tif !alive(3, 3) {\n\t\tt.Error(\"want (3,3) alive after step 1\")\n\t}\n\tif !alive(3, 4) {\n\t\tt.Error(\"want (3,4) alive after step 1\")\n\t}\n\tif alive(2, 3) || alive(4, 3) {\n\t\tt.Error(\"want (2,3) and (4,3) dead after step 1\")\n\t}\n\tif population != 3 {\n\t\tt.Errorf(\"population after step 1: want 3, got %d\", population)\n\t}\n\n\tStep()\n\n\t// Step 2: horizontal again\n\tif !alive(2, 3) || !alive(3, 3) || !alive(4, 3) {\n\t\tt.Error(\"want horizontal blinker after step 2\")\n\t}\n\tif alive(3, 2) || alive(3, 4) {\n\t\tt.Error(\"want (3,2) and (3,4) dead after step 2\")\n\t}\n\tif generation != 2 {\n\t\tt.Errorf(\"generation: want 2, got %d\", generation)\n\t}\n}\n\nfunc TestBlockStillLife(t *testing.T) {\n\tinitBoard(6, 6)\n\t// 2×2 block at (2,2)\n\tSetCell(2, 2, true)\n\tSetCell(3, 2, true)\n\tSetCell(2, 3, true)\n\tSetCell(3, 3, true)\n\n\tfor i := 0; i \u003c 5; i++ {\n\t\tStep()\n\t\tif population != 4 {\n\t\t\tt.Errorf(\"step %d: block changed, population=%d\", i+1, population)\n\t\t}\n\t\tif !alive(2, 2) || !alive(3, 2) || !alive(2, 3) || !alive(3, 3) {\n\t\t\tt.Errorf(\"step %d: block cell died\", i+1)\n\t\t}\n\t}\n}\n\nfunc TestGliderSurvives(t *testing.T) {\n\tinitBoard(20, 20)\n\tLoadPreset(\"glider\")\n\n\tif population != 5 {\n\t\tt.Errorf(\"glider initial population: want 5, got %d\", population)\n\t}\n\n\t// A glider has period 4 and shifts (1,1) every 4 steps; it should\n\t// survive many generations on a large-enough board.\n\tfor i := 0; i \u003c 20; i++ {\n\t\tStep()\n\t}\n\tif population != 5 {\n\t\tt.Errorf(\"glider after 20 steps: want population 5, got %d\", population)\n\t}\n\tif generation != 20 {\n\t\tt.Errorf(\"generation: want 20, got %d\", generation)\n\t}\n}\n\nfunc TestSetCell(t *testing.T) {\n\tinitBoard(5, 5)\n\n\tSetCell(2, 2, true)\n\tif !alive(2, 2) {\n\t\tt.Error(\"want (2,2) alive after SetCell true\")\n\t}\n\tif population != 1 {\n\t\tt.Errorf(\"population: want 1, got %d\", population)\n\t}\n\n\tSetCell(2, 2, false)\n\tif alive(2, 2) {\n\t\tt.Error(\"want (2,2) dead after SetCell false\")\n\t}\n\tif population != 0 {\n\t\tt.Errorf(\"population: want 0, got %d\", population)\n\t}\n\n\t// Out-of-bounds should be a no-op\n\tSetCell(100, 100, true)\n\tif population != 0 {\n\t\tt.Error(\"out-of-bounds SetCell must not change population\")\n\t}\n}\n\nfunc TestReset(t *testing.T) {\n\tinitBoard(10, 10)\n\tLoadPreset(\"block\")\n\n\tif population == 0 {\n\t\tt.Error(\"want non-zero population after loading block preset\")\n\t}\n\n\tReset(5, 5)\n\n\tif population != 0 {\n\t\tt.Errorf(\"want 0 population after reset, got %d\", population)\n\t}\n\tif generation != 0 {\n\t\tt.Errorf(\"want 0 generation after reset, got %d\", generation)\n\t}\n\tif width != 5 || height != 5 {\n\t\tt.Errorf(\"want 5×5 board after reset, got %d×%d\", width, height)\n\t}\n}\n\nfunc TestCountNeighbors(t *testing.T) {\n\tinitBoard(5, 5)\n\t// Live cells at (1,1),(2,1),(3,1) — blinker\n\tSetCell(1, 1, true)\n\tSetCell(2, 1, true)\n\tSetCell(3, 1, true)\n\n\t// Centre cell (2,1) has 2 live neighbours: (1,1) and (3,1)\n\tif n := countNeighbors(2, 1); n != 2 {\n\t\tt.Errorf(\"center of blinker: want 2 neighbours, got %d\", n)\n\t}\n\t// Cell below center (2,2) has 3 live neighbours\n\tif n := countNeighbors(2, 2); n != 3 {\n\t\tt.Errorf(\"cell below center: want 3 neighbours, got %d\", n)\n\t}\n}\n\nfunc TestMultiStep(t *testing.T) {\n\tinitBoard(20, 20)\n\tLoadPreset(\"glider\")\n\n\tMultiStep(4)\n\n\tif generation != 4 {\n\t\tt.Errorf(\"generation after MultiStep(4): want 4, got %d\", generation)\n\t}\n\tif population != 5 {\n\t\tt.Errorf(\"glider population after 4 steps: want 5, got %d\", population)\n\t}\n}\n"},{"name":"render_test.gno","body":"package life\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// ExampleRender pins the whole page on a deliberately small board so the\n// expected output stays readable. initBoard resets the grid, so this example\n// is independent of the tests that run before it.\nfunc ExampleRender() {\n\tinitBoard(5, 3)\n\tSetCell(1, 1, true)\n\tSetCell(2, 1, true)\n\tSetCell(3, 1, true)\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Conway's Game of Life\n\t//\n\t// \u003e A classic cellular automaton, ported to Gno — board state lives on-chain.\n\t//\n\t// **Generation:** 0 | **Population:** 3 | **Board:** 5×3\n\t//\n\t// ```\n\t// +-----+\n\t// |.....|\n\t// |.OOO.|\n\t// |.....|\n\t// +-----+\n\t// ```\n\t//\n\t// ## Transactions\n\t//\n\t// | Call | Effect |\n\t// |---|---|\n\t// | `Step()` | Advance one generation |\n\t// | `MultiStep(n)` | Advance *n* generations (max 100) |\n\t// | `SetCell(x, y, alive)` | Flip a single cell |\n\t// | `Reset(w, h)` | Clear and resize (max 50×40) |\n\t// | `LoadPreset(name)` | `glider` · `blinker` · `toad` · `beacon` · `block` · `pulsar` |\n\t//\n\t// ## Rules\n\t//\n\t// 1. A live cell with 2 or 3 live neighbours survives.\n\t// 2. A dead cell with exactly 3 live neighbours becomes alive.\n\t// 3. All other cells die or remain dead.\n}\n\n// TestRenderTracksGeneration checks the header counters follow the simulation.\nfunc TestRenderTracksGeneration(t *testing.T) {\n\tinitBoard(5, 3)\n\tSetCell(1, 1, true)\n\tSetCell(2, 1, true)\n\tSetCell(3, 1, true)\n\n\tuassert.True(t, strings.Contains(Render(\"\"), \"**Generation:** 0 | **Population:** 3\"),\n\t\t\"fresh board should report generation 0\")\n\n\tStep() // blinker rotates to vertical; on a 3-row board only the centre survives\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"**Generation:** 1\"), \"generation should advance\")\n\tuassert.True(t, strings.Contains(out, \"**Population:** \"+strconv.Itoa(population)),\n\t\t\"rendered population should match the counter\")\n}\n\n// TestRenderDrawsLiveCells checks the ASCII grid maps cells to O/. correctly.\nfunc TestRenderDrawsLiveCells(t *testing.T) {\n\tinitBoard(3, 3)\n\tSetCell(0, 0, true)\n\tSetCell(2, 2, true)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"+---+\\n|O..|\\n|...|\\n|..O|\\n+---+\"),\n\t\t\"corners should render as live cells\")\n}\n\n// TestRenderBoardDimensions checks the border and header follow a resize.\nfunc TestRenderBoardDimensions(t *testing.T) {\n\tinitBoard(8, 2)\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"**Board:** 8×2\"), \"header should report the new size\")\n\tuassert.True(t, strings.Contains(out, \"+\"+strings.Repeat(\"-\", 8)+\"+\"), \"border should match width\")\n}\n\n// TestRenderIgnoresPath documents that Render has no sub-routes.\nfunc TestRenderIgnoresPath(t *testing.T) {\n\tinitBoard(4, 4)\n\tuassert.Equal(t, Render(\"\"), Render(\"/whatever\"))\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"50820600","gas_fee":"152461ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"eaa4sDSQYE17xLkLQRZatzvEf4XzGd7w83xA0lDGRn0Pp272yfCu2Mn3fDSfEpf8Gy1YBb5M4KDBNiwmJk1CQA=="}],"memo":""},"metadata":{"timestamp":"1790961082"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"UsbErw/9Zc3cU+WaQBU9iTdo9+Tg/QYBf9pUKqdjb2U2080FKgrW6auCmlkfrBYJjPcKmpS2V2I/5XG3wqxcJA=="}],"memo":""},"metadata":{"timestamp":"1790961083"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"linktree","path":"gno.land/r/moul/x/daily/linktree/v1","files":[{"name":"README.md","body":"# Linktree\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA personal links page, one profile per address. Each caller owns their own\nprofile: they set a bio and add or remove labeled links. Anyone can browse a\nprofile at `/\u003caddress\u003e`, and the root page lists every profile that exists with\na link to each. Profiles are stored in an ordered AVL tree so rendering is\ndeterministic.\n\nRealm path: `gno.land/r/moul/x/daily/linktree/v1`\n\n## Example calls\n\n```\n# set your bio\nSetBio(\"Gnome builder, coffee enthusiast\")\n\n# add links\nAddLink(\"Home\", \"https://example.com\")\nAddLink(\"GitHub\", \"https://github.com/me\")\n\n# remove the first link (0-indexed)\nRemoveLink(0)\n```\n\n## Render\n\n- `Render(\"\")` — index of all profiles, each linking to its page.\n- `Render(\"/g1abc...\")` — that address's bio + links as a Markdown bullet list.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/linktree/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/linktree/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/linktree/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/linktree/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/linktree/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/linktree/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/linktree/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/linktree/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/linktree/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/linktree/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/linktree/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"linktree.gno","body":"package linktree\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/linktree/v1\"\n\n// link is a single labeled URL on a profile.\ntype link struct {\n\tLabel string\n\tURL   string\n}\n\n// profile is one address's personal links page.\ntype profile struct {\n\tBio   string\n\tLinks []link\n}\n\n// profiles maps an address (string key) to its *profile.\n// avl.Tree keeps iteration deterministic for Render.\nvar profiles avl.Tree\n\n// The bounds on what a caller may store. Anyone may create a profile, and the\n// root page lists every profile while a profile page lists every link.\nconst (\n\tMaxProfiles = 1000\n\tMaxLinks    = 20\n\tMaxBioLen   = 280\n\tMaxLabelLen = 64\n\tMaxURLLen   = 512\n)\n\n// SetBio sets (or replaces) the calling address's bio.\nfunc SetBio(cur realm, bio string) {\n\taddr := caller(cur)\n\tif len(bio) \u003e MaxBioLen {\n\t\tpanic(\"bio too long\")\n\t}\n\tp := getOrCreate(addr.String())\n\tp.Bio = bio\n\tchain.Emit(\"BioSet\", \"addr\", addr.String())\n}\n\n// AddLink appends a labeled URL to the calling address's profile.\nfunc AddLink(cur realm, label string, url string) {\n\taddr := caller(cur)\n\tif label == \"\" {\n\t\tpanic(\"label must not be empty\")\n\t}\n\tif url == \"\" {\n\t\tpanic(\"url must not be empty\")\n\t}\n\t// The URL becomes a markdown link destination as written, so it is\n\t// checked here rather than escaped there: http(s) only, and nothing that\n\t// could close the destination or start another.\n\tif !safeURL(url) {\n\t\tpanic(\"url must be http:// or https:// with no spaces, parentheses or angle brackets\")\n\t}\n\tif len(label) \u003e MaxLabelLen || len(url) \u003e MaxURLLen {\n\t\tpanic(\"label or url too long\")\n\t}\n\tp := getOrCreate(addr.String())\n\tif len(p.Links) \u003e= MaxLinks {\n\t\tpanic(\"a profile holds at most \" + strconv.Itoa(MaxLinks) + \" links\")\n\t}\n\tp.Links = append(p.Links, link{Label: label, URL: url})\n\tchain.Emit(\"LinkAdded\", \"addr\", addr.String(), \"label\", label)\n}\n\n// RemoveLink deletes the link at index from the calling address's profile.\nfunc RemoveLink(cur realm, index int) {\n\taddr := caller(cur)\n\tkey := addr.String()\n\tv := profiles.Get(key)\n\tif v == nil {\n\t\tpanic(\"no profile for caller\")\n\t}\n\tp := v.(*profile)\n\tif index \u003c 0 || index \u003e= len(p.Links) {\n\t\tpanic(\"index out of range\")\n\t}\n\t// A fresh slice, not append(s[:i], s[i+1:]...): the in-place form keeps the\n\t// old backing array, so the deposit for a removed link never comes back.\n\tkept := make([]link, 0, len(p.Links)-1)\n\tkept = append(kept, p.Links[:index]...)\n\tkept = append(kept, p.Links[index+1:]...)\n\tp.Links = kept\n\tchain.Emit(\"LinkRemoved\", \"addr\", key, \"index\", strconv.Itoa(index))\n}\n\n// getOrCreate returns the profile for key, creating an empty one if absent.\nfunc getOrCreate(key string) *profile {\n\tif v := profiles.Get(key); v != nil {\n\t\treturn v.(*profile)\n\t}\n\tif profiles.Size() \u003e= MaxProfiles {\n\t\tpanic(\"linktree is full at \" + strconv.Itoa(MaxProfiles) + \" profiles\")\n\t}\n\tp := \u0026profile{}\n\tprofiles.Set(key, p)\n\treturn p\n}\n\n// Render shows all profiles at root, or a single profile at \"/\u003caddress\u003e\".\nfunc Render(path string) string {\n\taddr := strings.Trim(path, \"/\")\n\tif addr == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderProfile(addr)\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Linktree\\n\\n\")\n\tif profiles.Size() == 0 {\n\t\tb.WriteString(\"_No profiles yet. Call `SetBio` or `AddLink` to create one._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"Profiles:\\n\\n\")\n\tprofiles.Iterate(\"\", \"\", func(key string, _ interface{}) bool {\n\t\tb.WriteString(\"- [\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"](\" + selfPath + \":\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\")\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\nfunc renderProfile(addr string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# \")\n\tb.WriteString(ui.Inline(addr))\n\tb.WriteString(\"\\n\\n\")\n\n\tv := profiles.Get(addr)\n\tif v == nil {\n\t\tb.WriteString(\"_No profile for this address._\\n\")\n\t\treturn b.String()\n\t}\n\tp := v.(*profile)\n\n\tif p.Bio != \"\" {\n\t\tb.WriteString(ui.Inline(p.Bio))\n\t\tb.WriteString(\"\\n\\n\")\n\t}\n\n\tif len(p.Links) == 0 {\n\t\tb.WriteString(\"_No links yet._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"## Links\\n\\n\")\n\tfor _, l := range p.Links {\n\t\tb.WriteString(\"- [\")\n\t\tb.WriteString(ui.Inline(l.Label))\n\t\tb.WriteString(\"](\")\n\t\tb.WriteString(l.URL)\n\t\tb.WriteString(\")\\n\")\n\t}\n\treturn b.String()\n}\n\n// caller is the address that crossed into this realm, after checking that the\n// realm token is this frame's own.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"linktree: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n\n// safeURL reports whether u can be written into a markdown link destination\n// unescaped.\nfunc safeURL(u string) bool {\n\tif !strings.HasPrefix(u, \"https://\") \u0026\u0026 !strings.HasPrefix(u, \"http://\") {\n\t\treturn false\n\t}\n\treturn !strings.ContainsAny(u, \" \\t\\r\\n()\u003c\u003e[]`\\\\\")\n}\n"},{"name":"linktree_test.gno","body":"package linktree\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestProfileLifecycle(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tSetBio(cross(cur), \"gnome builder\")\n\tAddLink(cross(cur), \"Home\", \"https://alice.example\")\n\tAddLink(cross(cur), \"GitHub\", \"https://github.com/alice\")\n\n\tout := Render(\"/\" + alice.String())\n\tuassert.True(t, strings.Contains(out, \"gnome builder\"), \"bio present\")\n\tuassert.True(t, strings.Contains(out, \"[Home](https://alice.example)\"), \"first link present\")\n\tuassert.True(t, strings.Contains(out, \"[GitHub](https://github.com/alice)\"), \"second link present\")\n\n\t// Remove the first link; second must survive.\n\tRemoveLink(cross(cur), 0)\n\tout = Render(\"/\" + alice.String())\n\tuassert.False(t, strings.Contains(out, \"[Home]\"), \"removed link gone\")\n\tuassert.True(t, strings.Contains(out, \"[GitHub](https://github.com/alice)\"), \"kept link present\")\n}\n\nfunc TestIndexAndOwnership(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice2\")\n\tbob := testutils.TestAddress(\"bob2\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAddLink(cross(cur), \"A\", \"https://a.example\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAddLink(cross(cur), \"B\", \"https://b.example\")\n\n\t// Root index lists both addresses.\n\tidx := Render(\"\")\n\tuassert.True(t, strings.Contains(idx, alice.String()), \"alice listed\")\n\tuassert.True(t, strings.Contains(idx, bob.String()), \"bob listed\")\n\n\t// bob is current caller; his profile has only his link, not alice's.\n\tbobOut := Render(\"/\" + bob.String())\n\tuassert.True(t, strings.Contains(bobOut, \"[B](https://b.example)\"), \"bob has own link\")\n\tuassert.False(t, strings.Contains(bobOut, \"[A]\"), \"bob does not have alice's link\")\n\n\t// Out-of-range removal on bob aborts.\n\tuassert.AbortsWithMessage(t, cur, \"index out of range\", func() {\n\t\tRemoveLink(cross(cur), 99)\n\t})\n}\n\nfunc TestUnknownProfile(t *testing.T) {\n\tout := Render(\"/g1doesnotexist\")\n\tuassert.True(t, strings.Contains(out, \"No profile for this address\"), \"unknown profile message\")\n}\n"},{"name":"zz_bounds_test.gno","body":"package linktree\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A profile holds a bounded number of links of bounded size, and removing one\n// keeps the others in order.\nfunc TestLinksAreBounded(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"bounded\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tuassert.AbortsContains(t, cur, \"bio too long\", func() { SetBio(cross(cur), strings.Repeat(\"b\", MaxBioLen+1)) })\n\tfor i := 0; i \u003c MaxLinks; i++ {\n\t\tAddLink(cross(cur), \"l\", \"https://e.example/\"+strings.Repeat(\"x\", i))\n\t}\n\tuassert.AbortsContains(t, cur, \"at most\", func() { AddLink(cross(cur), \"l\", \"https://e.example/\") })\n\tRemoveLink(cross(cur), 0)\n\tp := profiles.Get(who.String()).(*profile)\n\tuassert.Equal(t, MaxLinks-1, len(p.Links))\n\tuassert.Equal(t, \"https://e.example/x\", p.Links[0].URL)\n}\n\n// The profile count is bounded globally, not just per address.\nfunc TestProfileCountIsBounded(cur realm, t *testing.T) {\n\tvar added []string\n\tfor i := 0; profiles.Size() \u003c MaxProfiles; i++ {\n\t\tk := testutils.TestAddress(\"p\" + strings.Repeat(\"x\", i%7) + string(rune('a'+i%26)) + string(rune('a'+i/26%26)) + string(rune('a'+i/676%26))).String()\n\t\tif profiles.Get(k) == nil {\n\t\t\tprofiles.Set(k, \u0026profile{})\n\t\t\tadded = append(added, k)\n\t\t}\n\t}\n\tdefer func() {\n\t\tfor _, k := range added {\n\t\t\tprofiles.Remove(k)\n\t\t}\n\t}()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"latecomer\")))\n\tuassert.AbortsContains(t, cur, \"linktree is full\", func() { SetBio(cross(cur), \"hi\") })\n}\n"},{"name":"zz_escape_test.gno","body":"package linktree\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The bio and a label are escaped, and a URL that could break out of its\n// link destination, or is not http(s), is refused when it is written.\nfunc TestProfileFieldsAreEscapedAndURLsChecked(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"escaper\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tSetBio(cross(cur), \"[claim](https://evil.example)\")\n\tAddLink(cross(cur), \"[claim](https://evil.example)\", \"https://ok.example/path\")\n\tpage := Render(who.String())\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n\tuassert.AbortsContains(t, cur, \"url must be http\", func() { AddLink(cross(cur), \"x\", \"javascript:alert(1)\") })\n\tuassert.AbortsContains(t, cur, \"url must be http\", func() { AddLink(cross(cur), \"x\", \"https://a.example) [evil](https://b.example\") })\n}\n\n// A path that names nothing is echoed back on the not-found page. It is the\n// visitor's text, so a backtick in it must not close a code span and let a\n// link through.\nfunc TestNotFoundPathIsEscaped(t *testing.T) {\n\tout := Render(\"x` [claim](https://evil.example) `\")\n\tuassert.False(t, strings.Contains(out, \"[claim](https://evil.example)\"), out)\n}\n"},{"name":"zz_links_test.gno","body":"package linktree\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The index links each profile to this realm's own page. It once linked to\n// /r/REPLACE_ADDR/linktree.\nfunc TestIndexLinksNameThisRealm(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"linker\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tSetBio(cross(cur), \"links\")\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"](/r/moul/x/daily/linktree/v1:\"+who.String()+\")\"), out)\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"46291400","gas_fee":"138874ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"+Ob0WxyrCMHo8dAN+0Uj3ngfoHTTA3ubu5ogE20SjScl3P7FzPQCJVm+KY1kIdllE+1kX1SqRkxUzvLQ98MOsg=="}],"memo":""},"metadata":{"timestamp":"1790961135"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lru","path":"gno.land/r/moul/x/daily/lru/v0","files":[{"name":"README.md","body":"# LRU Cache\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA fixed-capacity (8) least-recently-used cache realm — a port of the classic\nLRU. `Put` inserts or updates an entry and marks it most-recently-used, evicting\nthe least-recently-used entry when capacity is exceeded. `Get` returns a value,\nbumps its recency, and records a hit or a miss. `Render` shows the entries in\nMRU→LRU order alongside the capacity and hit/miss stats.\n\nRealm path: `gno.land/r/REPLACE_ADDR/lru`\n\n## Example calls\n\n```\n# insert / update entries (marks them most-recently-used)\nPut(\"a\", \"1\")\nPut(\"b\", \"2\")\n\n# read a value (counts a hit, bumps recency)\nGet(\"a\")   # -\u003e \"1\", true\n\n# read a missing key (counts a miss)\nGet(\"zzz\") # -\u003e \"\", false\n\n# clear everything\nReset()\n\n# view state (MRU→LRU order + stats)\nRender(\"\")\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/lru/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lru/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/lru/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lru/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/lru/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lru/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/lru/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/lru/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/lru/v0\"\ngno = \"0.9\"\n"},{"name":"lru.gno","body":"package lru\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n)\n\n// capacity is the fixed maximum number of entries the cache holds.\nconst capacity = 8\n\n// node is a doubly-linked-list node holding a key/value pair.\n// The list is ordered MRU (head) -\u003e LRU (tail).\ntype node struct {\n\tkey   string\n\tvalue string\n\tprev  *node\n\tnext  *node\n}\n\n// cache is a fixed-capacity LRU cache backed by a doubly-linked list and\n// an index from key -\u003e node for O(1) lookups.\ntype cache struct {\n\tindex map[string]*node\n\thead  *node // most-recently-used\n\ttail  *node // least-recently-used\n\tsize  int\n\thits  int\n\tmiss  int\n}\n\nvar c = \u0026cache{index: make(map[string]*node)}\n\n// detach removes n from the linked list (does not touch the index).\nfunc (ca *cache) detach(n *node) {\n\tif n.prev != nil {\n\t\tn.prev.next = n.next\n\t} else {\n\t\tca.head = n.next\n\t}\n\tif n.next != nil {\n\t\tn.next.prev = n.prev\n\t} else {\n\t\tca.tail = n.prev\n\t}\n\tn.prev = nil\n\tn.next = nil\n}\n\n// pushFront inserts n at the head (MRU position).\nfunc (ca *cache) pushFront(n *node) {\n\tn.prev = nil\n\tn.next = ca.head\n\tif ca.head != nil {\n\t\tca.head.prev = n\n\t}\n\tca.head = n\n\tif ca.tail == nil {\n\t\tca.tail = n\n\t}\n}\n\n// touch moves an existing node to the MRU position.\nfunc (ca *cache) touch(n *node) {\n\tca.detach(n)\n\tca.pushFront(n)\n}\n\n// evict removes the LRU entry (tail) and returns its key.\nfunc (ca *cache) evict() string {\n\tn := ca.tail\n\tif n == nil {\n\t\treturn \"\"\n\t}\n\tca.detach(n)\n\tdelete(ca.index, n.key)\n\tca.size--\n\treturn n.key\n}\n\n// Put inserts or updates key with value and marks it most-recently-used.\n// Evicts the least-recently-used entry if capacity is exceeded.\nfunc Put(cur realm, key string, value string) {\n\tif n, ok := c.index[key]; ok {\n\t\tn.value = value\n\t\tc.touch(n)\n\t\tchain.Emit(\"Put\", \"key\", key, \"op\", \"update\")\n\t\treturn\n\t}\n\tn := \u0026node{key: key, value: value}\n\tc.index[key] = n\n\tc.pushFront(n)\n\tc.size++\n\tevicted := \"\"\n\tif c.size \u003e capacity {\n\t\tevicted = c.evict()\n\t}\n\tif evicted != \"\" {\n\t\tchain.Emit(\"Put\", \"key\", key, \"op\", \"insert\", \"evicted\", evicted)\n\t} else {\n\t\tchain.Emit(\"Put\", \"key\", key, \"op\", \"insert\")\n\t}\n}\n\n// Get returns the value for key and marks it most-recently-used.\n// It records a hit or a miss. The returned bool reports whether the key\n// was present.\nfunc Get(cur realm, key string) (string, bool) {\n\tif n, ok := c.index[key]; ok {\n\t\tc.touch(n)\n\t\tc.hits++\n\t\tchain.Emit(\"Get\", \"key\", key, \"result\", \"hit\")\n\t\treturn n.value, true\n\t}\n\tc.miss++\n\tchain.Emit(\"Get\", \"key\", key, \"result\", \"miss\")\n\treturn \"\", false\n}\n\n// Reset clears the cache and stats.\nfunc Reset(cur realm) {\n\tc = \u0026cache{index: make(map[string]*node)}\n\tchain.Emit(\"Reset\")\n}\n\n// peek returns the value without affecting recency or stats (read helper).\nfunc peek(key string) (string, bool) {\n\tif n, ok := c.index[key]; ok {\n\t\treturn n.value, true\n\t}\n\treturn \"\", false\n}\n\n// Render displays the cache contents in MRU-\u003eLRU order with stats.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# LRU Cache\\n\\n\")\n\tb.WriteString(\"A fixed-capacity least-recently-used cache.\\n\\n\")\n\n\tb.WriteString(\"## Stats\\n\\n\")\n\tb.WriteString(\"- Capacity: \" + strconv.Itoa(capacity) + \"\\n\")\n\tb.WriteString(\"- Size: \" + strconv.Itoa(c.size) + \"\\n\")\n\tb.WriteString(\"- Hits: \" + strconv.Itoa(c.hits) + \"\\n\")\n\tb.WriteString(\"- Misses: \" + strconv.Itoa(c.miss) + \"\\n\")\n\ttotal := c.hits + c.miss\n\tif total \u003e 0 {\n\t\t// integer-percent hit rate, deterministic\n\t\trate := (c.hits * 100) / total\n\t\tb.WriteString(\"- Hit rate: \" + strconv.Itoa(rate) + \"%\\n\")\n\t} else {\n\t\tb.WriteString(\"- Hit rate: n/a\\n\")\n\t}\n\tb.WriteString(\"\\n\")\n\n\tb.WriteString(\"## Entries (MRU → LRU)\\n\\n\")\n\tif c.head == nil {\n\t\tb.WriteString(\"_empty_\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"| # | Key | Value |\\n\")\n\tb.WriteString(\"|---|-----|-------|\\n\")\n\ti := 1\n\tfor n := c.head; n != nil; n = n.next {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i) + \" | \" + n.key + \" | \" + n.value + \" |\\n\")\n\t\ti++\n\t}\n\treturn b.String()\n}\n"},{"name":"lru_test.gno","body":"package lru\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc reset(cur realm) {\n\tReset(cross(cur))\n}\n\nfunc TestPutGetAndRecency(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\treset(cur)\n\n\tPut(cross(cur), \"a\", \"1\")\n\tPut(cross(cur), \"b\", \"2\")\n\n\tv, ok := Get(cross(cur), \"a\")\n\tuassert.True(t, ok, \"a should be present\")\n\tuassert.Equal(t, \"1\", v)\n\n\t// miss\n\t_, ok = Get(cross(cur), \"zzz\")\n\tuassert.False(t, ok, \"zzz should be absent\")\n\n\t// after Get(\"a\"), a is MRU -\u003e head\n\tuassert.Equal(t, \"a\", c.head.key)\n\tuassert.Equal(t, \"b\", c.tail.key)\n\n\t// stats: 1 hit, 1 miss\n\tuassert.Equal(t, 1, c.hits)\n\tuassert.Equal(t, 1, c.miss)\n\n\t// update existing key\n\tPut(cross(cur), \"b\", \"22\")\n\tv, _ = peek(\"b\")\n\tuassert.Equal(t, \"22\", v)\n\tuassert.Equal(t, \"b\", c.head.key) // update marks MRU\n\tuassert.Equal(t, 2, c.size)\n}\n\nfunc TestEviction(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bob\")))\n\treset(cur)\n\n\t// fill beyond capacity (8): insert k0..k9\n\tfor i := 0; i \u003c 10; i++ {\n\t\tPut(cross(cur), \"k\"+strconv.Itoa(i), strconv.Itoa(i))\n\t}\n\n\tuassert.Equal(t, capacity, c.size)\n\n\t// k0 and k1 should have been evicted (oldest inserts, never touched)\n\t_, ok := peek(\"k0\")\n\tuassert.False(t, ok, \"k0 should be evicted\")\n\t_, ok = peek(\"k1\")\n\tuassert.False(t, ok, \"k1 should be evicted\")\n\n\t// newest is MRU head, k2 is now the LRU tail\n\tuassert.Equal(t, \"k9\", c.head.key)\n\tuassert.Equal(t, \"k2\", c.tail.key)\n\n\t// touching k2 protects it; next insert evicts k3 instead\n\t_, ok = Get(cross(cur), \"k2\")\n\tuassert.True(t, ok, \"k2 present\")\n\tPut(cross(cur), \"k10\", \"10\")\n\t_, ok = peek(\"k2\")\n\tuassert.True(t, ok, \"k2 protected after Get\")\n\t_, ok = peek(\"k3\")\n\tuassert.False(t, ok, \"k3 evicted instead\")\n\tuassert.Equal(t, capacity, c.size)\n}\n"},{"name":"render_test.gno","body":"package lru\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// clear empties the cache without needing a realm argument, so examples (which\n// take no `cur`) can start from a known state. Examples run after all tests.\nfunc clear() {\n\tc = \u0026cache{index: make(map[string]*node)}\n}\n\n// ExampleRender pins the empty-cache view.\nfunc ExampleRender() {\n\tclear()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # LRU Cache\n\t//\n\t// A fixed-capacity least-recently-used cache.\n\t//\n\t// ## Stats\n\t//\n\t// - Capacity: 8\n\t// - Size: 0\n\t// - Hits: 0\n\t// - Misses: 0\n\t// - Hit rate: n/a\n\t//\n\t// ## Entries (MRU → LRU)\n\t//\n\t// _empty_\n}\n\n// TestRenderListsEntriesMRUFirst checks the table is ordered most-recently-used\n// first and renumbered from 1.\nfunc TestRenderListsEntriesMRUFirst(cur realm, t *testing.T) {\n\treset(cur)\n\tPut(cross(cur), \"a\", \"1\")\n\tPut(cross(cur), \"b\", \"2\")\n\tPut(cross(cur), \"c\", \"3\")\n\tGet(cross(cur), \"a\") // a becomes MRU\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"| 1 | a | 1 |\\n| 2 | c | 3 |\\n| 3 | b | 2 |\\n\"),\n\t\t\"entries should be listed MRU-\u003eLRU: a, c, b\")\n\tuassert.True(t, strings.Contains(out, \"- Size: 3\\n\"), \"size should be 3\")\n}\n\n// TestRenderHitRate covers the integer-percent branch and the n/a branch.\nfunc TestRenderHitRate(cur realm, t *testing.T) {\n\treset(cur)\n\tuassert.True(t, strings.Contains(Render(\"\"), \"- Hit rate: n/a\\n\"),\n\t\t\"no lookups yet should render n/a\")\n\n\tPut(cross(cur), \"a\", \"1\")\n\tGet(cross(cur), \"a\")   // hit\n\tGet(cross(cur), \"nope\") // miss\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"- Hits: 1\\n\"), \"one hit\")\n\tuassert.True(t, strings.Contains(out, \"- Misses: 1\\n\"), \"one miss\")\n\tuassert.True(t, strings.Contains(out, \"- Hit rate: 50%\\n\"), \"1/2 should be 50%\")\n}\n\n// TestRenderCapacityMatchesConst guards the header against a capacity change\n// that the pinned example would otherwise silently disagree with.\nfunc TestRenderCapacityMatchesConst(cur realm, t *testing.T) {\n\treset(cur)\n\tuassert.True(t, strings.Contains(Render(\"\"), \"- Capacity: \"+strconv.Itoa(capacity)+\"\\n\"),\n\t\t\"rendered capacity should match the constant\")\n}\n\n// TestRenderIgnoresPath documents that Render has no sub-routes.\nfunc TestRenderIgnoresPath(cur realm, t *testing.T) {\n\treset(cur)\n\tPut(cross(cur), \"k\", \"v\")\n\tuassert.Equal(t, Render(\"\"), Render(\"/whatever\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"39521000","gas_fee":"118563ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"3/5/HbEimUpLBaJwg9vLkOd4fauit96t3FXQPLHNK44v3h85L5Fv5Q1HCSwAivK9SUmsFmf8qk8ZQZ0+90kjug=="}],"memo":""},"metadata":{"timestamp":"1790961139"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"luhndemo","path":"gno.land/r/moul/x/daily/luhndemo/v0","files":[{"name":"README.md","body":"# Luhn Checksum\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nPut a number in the path and the realm tells you whether its Luhn check digit is\nright — and if not, what it should have been.\n\nDemo of the [`p/moul/x/daily/luhn`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/luhn)\nlibrary — validation, the check digit and the separator handling all come from\nthe package; this realm holds no checksum logic of its own. Read-only and\nstateless, so `Render` is fully deterministic.\n\n```\n/r/moul/x/daily/luhndemo/v0                  → usage + worked samples\n/r/moul/x/daily/luhndemo/v0:79927398713      → valid\n/r/moul/x/daily/luhndemo/v0:79927398710      → invalid, suggests check digit 3\n/r/moul/x/daily/luhndemo/v0:4539-1488-0343-6467 → separators are ignored\n```\n\nThe samples on the root page are picked to show the two error classes Luhn\nactually catches: a wrong digit, and two adjacent digits swapped.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/luhndemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/luhndemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/luhndemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/luhndemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/luhndemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/luhndemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/luhndemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/luhndemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/luhndemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/luhndemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/luhndemo/v0\"\ngno = \"0.9\"\n"},{"name":"luhndemo.gno","body":"// Package luhndemo is a small gnoweb demo of the Luhn mod-10 checksum provided\n// by the [p/moul/x/daily/luhn](/p/moul/x/daily/luhn/v0) library: put a number\n// in the path and it tells you whether the check digit is right, and what it\n// should have been.\n//\n// It contains no checksum logic of its own — validation, the check digit and\n// the separator handling all come from the library. Read-only and stateless, so\n// Render is fully deterministic.\npackage luhndemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/luhn/v0\"\n)\n\n// samples are shown on the root page: a valid number, a typo'd one, and a\n// transposition — the two error classes Luhn is designed to catch.\nvar samples = []struct {\n\tnumber string\n\tnote   string\n}{\n\t{\"79927398713\", \"the textbook example\"},\n\t{\"79927398710\", \"same number, wrong check digit\"},\n\t{\"4539148803436467\", \"a test card number\"},\n\t{\"4539148803436647\", \"same card, two digits swapped\"},\n}\n\n// Render renders the checker for gnoweb.\n//\n//\tRender(\"\")        / Render(\"/\") -\u003e usage + worked samples\n//\tRender(\"/\u003cdigits\u003e\")             -\u003e verdict for that number\nfunc Render(path string) string {\n\tin := parseInput(path)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Luhn Checksum\\n\\n\")\n\tb.WriteString(\"The mod-10 check behind card numbers and IMEIs, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/luhn`](/p/moul/x/daily/luhn/v0) library.\\n\\n\")\n\n\tif in == \"\" {\n\t\tb.WriteString(\"Append a number to the path to check it — spaces and hyphens are ignored.\\n\\n\")\n\t\tb.WriteString(\"## Samples\\n\\n\")\n\t\tb.WriteString(\"| number | valid? | note |\\n|---|---|---|\\n\")\n\t\tfor _, s := range samples {\n\t\t\tb.WriteString(\"| `\")\n\t\t\tb.WriteString(s.number)\n\t\t\tb.WriteString(\"` | \")\n\t\t\tb.WriteString(verdict(luhn.Valid(s.number)))\n\t\t\tb.WriteString(\" | \")\n\t\t\tb.WriteString(s.note)\n\t\t\tb.WriteString(\" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n\u003e Luhn is a **typo check, not a security check**: it catches every \")\n\t\tb.WriteString(\"single-digit error and nearly every swap of adjacent digits, but \")\n\t\tb.WriteString(\"anyone can compute a valid number. Never authorize anything with it.\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"## `\")\n\tb.WriteString(in)\n\tb.WriteString(\"`\\n\\n\")\n\n\tif luhn.Valid(in) {\n\t\tb.WriteString(\"**Valid** — the check digit matches.\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"**Not valid.**\\n\\n\")\n\t// Offer the fix: treat everything but the last digit as the payload.\n\tif payload, ok := trimLast(in); ok {\n\t\tif d, ok2 := luhn.CheckDigit(payload); ok2 {\n\t\t\tb.WriteString(\"Keeping the leading digits, the check digit should be **\")\n\t\t\tb.WriteString(strconv.Itoa(d))\n\t\t\tb.WriteString(\"**\")\n\t\t\tif fixed, ok3 := luhn.Append(payload); ok3 {\n\t\t\t\tb.WriteString(\" — i.e. `\")\n\t\t\t\tb.WriteString(fixed)\n\t\t\t\tb.WriteString(\"`\")\n\t\t\t}\n\t\t\tb.WriteString(\".\\n\")\n\t\t\treturn b.String()\n\t\t}\n\t}\n\tb.WriteString(\"It has no usable digits to check.\\n\")\n\treturn b.String()\n}\n\n// parseInput extracts the first path segment.\nfunc parseInput(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n\n// trimLast drops the final digit, ignoring separators, to recover the payload.\nfunc trimLast(s string) (string, bool) {\n\tfor i := len(s) - 1; i \u003e= 0; i-- {\n\t\tif s[i] \u003e= '0' \u0026\u0026 s[i] \u003c= '9' {\n\t\t\treturn s[:i], true\n\t\t}\n\t}\n\treturn \"\", false\n}\n\nfunc verdict(ok bool) string {\n\tif ok {\n\t\treturn \"✅ valid\"\n\t}\n\treturn \"❌ invalid\"\n}\n"},{"name":"render_example_test.gno","body":"package luhndemo\n\n// ExampleRender pins the realm's root Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Luhn Checksum\n\t//\n\t// The mod-10 check behind card numbers and IMEIs, demoing the [`p/moul/x/daily/luhn`](/p/moul/x/daily/luhn/v0) library.\n\t//\n\t// Append a number to the path to check it — spaces and hyphens are ignored.\n\t//\n\t// ## Samples\n\t//\n\t// | number | valid? | note |\n\t// |---|---|---|\n\t// | `79927398713` | ✅ valid | the textbook example |\n\t// | `79927398710` | ❌ invalid | same number, wrong check digit |\n\t// | `4539148803436467` | ✅ valid | a test card number |\n\t// | `4539148803436647` | ❌ invalid | same card, two digits swapped |\n\t//\n\t// \u003e Luhn is a **typo check, not a security check**: it catches every single-digit error and nearly every swap of adjacent digits, but anyone can compute a valid number. Never authorize anything with it.\n}\n\n// ExampleRender_invalid pins the repair path: a wrong check digit is reported\n// along with the digit it should have been.\nfunc ExampleRender_invalid() {\n\tprint(Render(\"/79927398710\"))\n\t// Output:\n\t// # Luhn Checksum\n\t//\n\t// The mod-10 check behind card numbers and IMEIs, demoing the [`p/moul/x/daily/luhn`](/p/moul/x/daily/luhn/v0) library.\n\t//\n\t// ## `79927398710`\n\t//\n\t// **Not valid.**\n\t//\n\t// Keeping the leading digits, the check digit should be **3** — i.e. `79927398713`.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"31528600","gas_fee":"94585ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"u2LgLLzN55S1L22C2LT6yoKfzleWUoH12kFu9aJEOgINpCIjev4u7NdY7iWj2lf4oFbFIlPRa+vs6lFOAoq1yg=="}],"memo":""},"metadata":{"timestamp":"1790961140"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"memory","path":"gno.land/r/moul/x/daily/memory/v0","files":[{"name":"README.md","body":"# 🧠 Memory Match\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA concentration game on a 4x4 grid of 8 emoji pairs. The board is shuffled\ndeterministically from the current block height (there is no on-chain RNG), so\nevery `NewGame` produces a reproducible layout for a given height. Flip tiles two\nat a time: matching pairs stay face-up, mismatches flip back on your next move.\nThe realm tracks your move count and matched pairs and reports the solved state.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/memory`\n\n## How to play\n\n- `Flip(index int)` — reveal the tile at `index` (0–15, row-major). The first\n  reveal starts an attempt; the second completes a *move*. Matching faces stay\n  up; a mismatch shows both tiles until your next `Flip` clears them.\n- `NewGame()` — reshuffle the board using the current block height as the seed.\n- `Render(path)` — renders the grid (❓ hidden, emoji revealed/matched), the move\n  count, matched-pair count, and whether the game is solved.\n\n## Example calls\n\n```\n# start a fresh, height-seeded board\nNewGame()\n\n# reveal cell 0, then cell 5\nFlip(0)\nFlip(5)\n\n# view the board\ngnokey query vm/qrender --data \"gno.land/r/REPLACE_ADDR/memory:\"\n```\n\nSolve all 8 pairs to win; the render then shows your total move count.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/memory/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/memory/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/memory/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/memory/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/memory/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/memory/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/memory/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/memory/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/memory/v0\"\ngno = \"0.9\"\n"},{"name":"memory.gno","body":"// Package memory implements \"Memory Match\", a concentration game on a\n// 4x4 grid of 8 emoji pairs. The board is shuffled deterministically from\n// the current block height (no on-chain RNG exists), so a NewGame started at\n// a given height always produces the same layout.\npackage memory\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n)\n\nconst gridSize = 16 // 4x4\nconst numPairs = 8\n\n// faces are the 8 distinct emoji; each appears exactly twice on the board.\nvar faces = [numPairs]string{\"🐶\", \"🐱\", \"🦊\", \"🐸\", \"🐵\", \"🐼\", \"🦁\", \"🐧\"}\n\n// tile holds the face index (0..7) for a cell and whether it is matched.\ntype tile struct {\n\tface    int\n\tmatched bool\n}\n\n// board is the full game state. It is a package-level singleton so the realm\n// persists a single shared game.\nvar board = struct {\n\ttiles   [gridSize]tile\n\tflipped []int // indices currently face-up but not yet resolved (0, 1 or 2)\n\tmoves   int   // number of completed two-tile attempts\n\tpairs   int   // matched pairs so far\n\theight  int64 // block height the current game was seeded from\n\tstarted bool\n}{}\n\n// shuffle produces a deterministic permutation of the 16 tile faces from a\n// 64-bit seed. It fills a slice with two of each face index then applies a\n// Fisher-Yates shuffle driven by a simple LCG — fully deterministic, no RNG.\nfunc shuffle(seed int64) [gridSize]tile {\n\tvals := make([]int, 0, gridSize)\n\tfor i := 0; i \u003c numPairs; i++ {\n\t\tvals = append(vals, i, i)\n\t}\n\t// LCG (Numerical Recipes constants); force unsigned-style math via uint64.\n\tstate := uint64(seed)*6364136223846793005 + 1442695040888963407\n\tfor i := len(vals) - 1; i \u003e 0; i-- {\n\t\tstate = state*6364136223846793005 + 1442695040888963407\n\t\tj := int(state % uint64(i+1))\n\t\tvals[i], vals[j] = vals[j], vals[i]\n\t}\n\tvar out [gridSize]tile\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tout[i] = tile{face: vals[i], matched: false}\n\t}\n\treturn out\n}\n\nfunc ensureStarted() {\n\tif !board.started {\n\t\treset(runtime.ChainHeight())\n\t}\n}\n\nfunc reset(height int64) {\n\tboard.tiles = shuffle(height)\n\tboard.flipped = nil\n\tboard.moves = 0\n\tboard.pairs = 0\n\tboard.height = height\n\tboard.started = true\n}\n\n// NewGame reshuffles the board using the current block height as the seed.\nfunc NewGame(cur realm) {\n\treset(runtime.ChainHeight())\n\tchain.Emit(\"NewGame\", \"height\", strconv.FormatInt(board.height, 10))\n}\n\n// Flip reveals the tile at index (0..15).\n//\n// Rules:\n//   - If two tiles are already showing from a previous unmatched attempt,\n//     this Flip first clears them (they turn back to hidden), then reveals\n//     the requested tile as the first of a new attempt.\n//   - Revealing the second tile of an attempt completes a move: matching\n//     faces stay face-up (matched); a mismatch leaves both showing until the\n//     next Flip clears them.\n//   - Flipping an already-matched or already-showing tile is rejected.\nfunc Flip(cur realm, index int) {\n\tensureStarted()\n\n\tif index \u003c 0 || index \u003e= gridSize {\n\t\tpanic(\"index out of range\")\n\t}\n\tif board.tiles[index].matched {\n\t\tpanic(\"tile already matched\")\n\t}\n\n\t// A completed unmatched attempt (2 face-up, non-matching) is cleared\n\t// before the next reveal.\n\tif len(board.flipped) == 2 {\n\t\tboard.flipped = nil\n\t}\n\n\tfor _, f := range board.flipped {\n\t\tif f == index {\n\t\t\tpanic(\"tile already flipped\")\n\t\t}\n\t}\n\n\tboard.flipped = append(board.flipped, index)\n\n\tif len(board.flipped) != 2 {\n\t\tchain.Emit(\"Flip\", \"index\", strconv.Itoa(index))\n\t\treturn\n\t}\n\n\t// Second tile of the attempt: resolve.\n\tboard.moves++\n\ta, b := board.flipped[0], board.flipped[1]\n\tif board.tiles[a].face == board.tiles[b].face {\n\t\tboard.tiles[a].matched = true\n\t\tboard.tiles[b].matched = true\n\t\tboard.pairs++\n\t\tboard.flipped = nil\n\t\tchain.Emit(\"Match\", \"index\", strconv.Itoa(index), \"pairs\", strconv.Itoa(board.pairs))\n\t} else {\n\t\t// leave both showing; next Flip clears them\n\t\tchain.Emit(\"Miss\", \"index\", strconv.Itoa(index))\n\t}\n}\n\nfunc solved() bool {\n\treturn board.pairs == numPairs\n}\n\n// cellFace returns the emoji to display for a cell given the current state.\nfunc cellFace(i int) string {\n\tif board.tiles[i].matched {\n\t\treturn faces[board.tiles[i].face]\n\t}\n\tfor _, f := range board.flipped {\n\t\tif f == i {\n\t\t\treturn faces[board.tiles[i].face]\n\t\t}\n\t}\n\treturn \"❓\"\n}\n\n// Render draws the board as Markdown: a 4x4 grid, move count and solved state.\nfunc Render(path string) string {\n\tensureStarted()\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"# 🧠 Memory Match\\n\\n\")\n\tsb.WriteString(\"Match all 8 emoji pairs on the 4x4 grid.\\n\\n\")\n\n\tsb.WriteString(\"| | | | |\\n\")\n\tsb.WriteString(\"|:-:|:-:|:-:|:-:|\\n\")\n\tfor row := 0; row \u003c 4; row++ {\n\t\tsb.WriteString(\"|\")\n\t\tfor col := 0; col \u003c 4; col++ {\n\t\t\tsb.WriteString(\" \" + cellFace(row*4+col) + \" |\")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\n\tsb.WriteString(\"\\n\")\n\tsb.WriteString(\"- Moves: **\" + strconv.Itoa(board.moves) + \"**\\n\")\n\tsb.WriteString(\"- Pairs matched: **\" + strconv.Itoa(board.pairs) + \" / \" + strconv.Itoa(numPairs) + \"**\\n\")\n\tsb.WriteString(\"- Seed height: **\" + strconv.FormatInt(board.height, 10) + \"**\\n\\n\")\n\n\tif solved() {\n\t\tsb.WriteString(\"🎉 **Solved in \" + strconv.Itoa(board.moves) + \" moves!** Call `NewGame` to play again.\\n\")\n\t} else {\n\t\tsb.WriteString(\"Call `Flip(index)` with a cell index 0–15. `NewGame()` reshuffles.\\n\")\n\t}\n\n\treturn sb.String()\n}\n"},{"name":"memory_test.gno","body":"package memory\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// findPairIndices returns two grid indices holding the same face, plus a third\n// index whose face differs from that pair — using the current board layout.\nfunc findPairIndices() (int, int, int) {\n\t// Map first-seen index per face.\n\tfirst := map[int]int{}\n\tvar pa, pb int = -1, -1\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tf := board.tiles[i].face\n\t\tif j, ok := first[f]; ok {\n\t\t\tpa, pb = j, i\n\t\t\tbreak\n\t\t}\n\t\tfirst[f] = i\n\t}\n\t// Find an index outside the matched pair with a different face.\n\tother := -1\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tif i != pa \u0026\u0026 i != pb \u0026\u0026 board.tiles[i].face != board.tiles[pa].face {\n\t\t\tother = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn pa, pb, other\n}\n\nfunc TestFlipMatchAndMiss(cur realm, t *testing.T) {\n\taddr := testutils.TestAddress(\"player\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\n\tNewGame(cross(cur))\n\n\tpa, pb, other := findPairIndices()\n\tuassert.True(t, pa \u003e= 0 \u0026\u0026 pb \u003e= 0 \u0026\u0026 other \u003e= 0, \"expected valid indices\")\n\n\t// Flip a matching pair -\u003e both matched, pairs increments.\n\tFlip(cross(cur), pa)\n\tFlip(cross(cur), pb)\n\tuassert.True(t, board.tiles[pa].matched, \"first tile should be matched\")\n\tuassert.True(t, board.tiles[pb].matched, \"second tile should be matched\")\n\tuassert.Equal(t, 1, board.pairs)\n\tuassert.Equal(t, 1, board.moves)\n\n\t// Flip a mismatched pair (pa is matched; pick two unmatched non-equal).\n\t// Reuse `other` and find a partner with a different face, both unmatched.\n\tpartner := -1\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tif i != other \u0026\u0026 !board.tiles[i].matched \u0026\u0026 board.tiles[i].face != board.tiles[other].face {\n\t\t\tpartner = i\n\t\t\tbreak\n\t\t}\n\t}\n\tuassert.True(t, partner \u003e= 0, \"expected a mismatched partner\")\n\n\tFlip(cross(cur), other)\n\tFlip(cross(cur), partner)\n\tuassert.Equal(t, 2, board.moves)\n\tuassert.Equal(t, 1, board.pairs) // no new match\n\t// Both still showing (not matched) until next flip clears them.\n\tuassert.False(t, board.tiles[other].matched, \"mismatched tile not matched\")\n\tuassert.Equal(t, 2, len(board.flipped))\n\n\t// Next flip clears the two mismatched tiles first.\n\t// Find any still-unmatched, not-currently-flipped index.\n\tnext := -1\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tif i == other || i == partner {\n\t\t\tcontinue\n\t\t}\n\t\tif !board.tiles[i].matched {\n\t\t\tnext = i\n\t\t\tbreak\n\t\t}\n\t}\n\tuassert.True(t, next \u003e= 0, \"expected an unflipped unmatched tile\")\n\tFlip(cross(cur), next)\n\tuassert.Equal(t, 1, len(board.flipped), \"previous mismatch cleared, one showing\")\n}\n\nfunc TestDeterministicShuffleAndRender(cur realm, t *testing.T) {\n\t// Same seed -\u003e identical layout.\n\ta := shuffle(42)\n\tb := shuffle(42)\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tuassert.Equal(t, a[i].face, b[i].face)\n\t}\n\n\t// Different seed -\u003e at least one differing cell (extremely likely).\n\tc := shuffle(43)\n\tdiff := false\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tif a[i].face != c[i].face {\n\t\t\tdiff = true\n\t\t\tbreak\n\t\t}\n\t}\n\tuassert.True(t, diff, \"different seeds should differ\")\n\n\t// Each face appears exactly twice.\n\tcounts := map[int]int{}\n\tfor i := 0; i \u003c gridSize; i++ {\n\t\tcounts[a[i].face]++\n\t}\n\tfor f := 0; f \u003c numPairs; f++ {\n\t\tuassert.Equal(t, 2, counts[f])\n\t}\n\n\t// Render on a fresh game shows hidden tiles and zero progress.\n\taddr := testutils.TestAddress(\"viewer\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\tNewGame(cross(cur))\n\tout := Render(\"\")\n\tuassert.True(t, len(out) \u003e 0, \"render non-empty\")\n\tuassert.True(t, containsSub(out, \"Memory Match\"), \"has title\")\n\tuassert.True(t, containsSub(out, \"❓\"), \"shows hidden tiles\")\n\tuassert.True(t, containsSub(out, \"0 / 8\"), \"zero pairs matched\")\n}\n\nfunc containsSub(s, sub string) bool {\n\tfor i := 0; i+len(sub) \u003c= len(s); i++ {\n\t\tif s[i:i+len(sub)] == sub {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"},{"name":"render_example_test.gno","body":"package memory\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # 🧠 Memory Match\n\t//\n\t// Match all 8 emoji pairs on the 4x4 grid.\n\t//\n\t// | | | | |\n\t// |:-:|:-:|:-:|:-:|\n\t// | ❓ | ❓ | ❓ | ❓ |\n\t// | ❓ | ❓ | ❓ | ❓ |\n\t// | ❓ | ❓ | ❓ | ❓ |\n\t// | ❓ | ❓ | ❓ | ❓ |\n\t//\n\t// - Moves: **0**\n\t// - Pairs matched: **0 / 8**\n\t// - Seed height: **123**\n\t//\n\t// Call `Flip(index)` with a cell index 0–15. `NewGame()` reshuffles.\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"44640400","gas_fee":"133921ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"EsOYAf+WWQcraRB29IHKNKLfpr1fNFlMuH54KVqugkAZ3scaChCFZ/0Yb0Ar5NmpFN1UcKOsBsv3H8R2GUyRAw=="}],"memo":""},"metadata":{"timestamp":"1790961141"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"merkledrop","path":"gno.land/r/moul/x/daily/merkledrop/v1","files":[{"name":"README.md","body":"# merkledrop v1\n\nA Merkle-gated airdrop that actually moves GNOT.\n\nSuccessor to [`v0`](../v0), which the daily pipeline generated and which is deployed on\nmainnet. v0 works, but it is a demonstration rather than a drop, and its proof scheme is safe\nby accident. Built on [`p/moul/x/merkle/v0`](../../../../../../p/moul/x/merkle/v0).\n\n## What changed, and why\n\n**1. Domain-separated leaves.** v0 hashed leaves bare and combined nodes commutatively, the\nOpenZeppelin scheme: `leaf = sha256(addr|amount)`, `node = sha256(min||max)`. Without a\nleaf/inner tag an inner-node hash is also a valid leaf hash, so anyone able to present a\n64-byte leaf preimage can prove membership of a leaf that was never committed.\n\nv0 is **not** exploitable, but only by arithmetic: an inner preimage is exactly 64 bytes, and\na v0 leaf preimage is at most 40 (bech32 address) + 1 + 20 (`uint64` has at most 20 digits) =\n61 bytes. 61 \u003c 64, so no collision is reachable. Widen the amount, change the address form, add\na field, and the forgery goes live with no visible diff at the call site. That is not a\nproperty to rely on. v1 tags leaves `0x00` and inner nodes `0x01`, so the two preimage spaces\ncannot overlap at any length.\n\n**2. Proofs bound to a position.** v0's proof was a bare sibling list of any length, folded\nuntil it ran out. v1's proof carries its index and the total leaf count; the verifier rebuilds\nthe tree shape from them, so a proof cannot be replayed at another index and one of the wrong\nlength is rejected rather than folded. Depth is capped at `merkle.MaxDepth`, so an untrusted\ncaller does not choose the length of the loop.\n\n**3. A settable root and a closing height.** v0's root is a `const`: the drop can never be\nre-rooted, extended or ended. v1's owner sets root, leaf count and an optional closing height,\nand can sweep the remainder once it closes.\n\n**4. Real coins.** v0 keeps a `uint64` ledger and moves nothing. Its README says so, but it\nsits on mainnet reading like an airdrop. v1 sends ugnot from the realm's own address through\nthe banker, and **refuses a claim it cannot pay** rather than marking it claimed:\n`TestUnderfundedDropDoesNotBurnAnAllocation` pins that an underfunded drop does not consume\nan allocation.\n\n## Leaf encoding\n\nThe whole interface to an off-chain generator:\n\n```\nleaf = \"gno.land/r/moul/x/daily/merkledrop/v1|\u003cindex\u003e|\u003caddress\u003e|\u003camount\u003e\"\ntree = Tendermint simple tree, leaf tagged 0x00, inner tagged 0x01\n```\n\nThe pkgpath is in the preimage, so a proof for this drop cannot be replayed against another\nrealm using the same shape. Reproduce the tree with `p/moul/x/merkle/v0`, or with any Tendermint\nimplementation.\n\n## Using it\n\n```\nSetDrop(rootHex, totalLeaves, closesAtHeight)   // owner only; 0 = never closes\nVerify(index, addr, amount, proof)              // free check before spending gas\nClaim(index, amount, proof)                     // pays out\nSweep()                                         // owner, after the drop closes\n```\n\nFund the drop by sending ugnot to `Address()`, the realm's own package address.\n\n## The seeded example drop\n\nDeployed with four example allocations so the drop can be exercised without a generator, and\nso the page is not empty. A **live** drop commits only a root and stores no allocation list:\nthat is the whole point of a Merkle drop. `SetDrop` clears the seeded list.\n\nRoot: `6964baa99da23b9d8c76774c6f1122b250040e29c1d75823dda15c043dc65755`\n\n`DemoProof(index)` hands out the proof for a seeded allocation, and\n`/r/moul/x/daily/merkledrop/v1:proof/\u003cindex\u003e` renders it with its leaf.\n\n## Who the claimer is\n\nThe claimer is `PreviousRealm().Address()`, the **immediate** caller. Called directly by a\nuser that is the user; called through another realm it is that **realm**.\n\nThat is not a hole: the leaf binds the address and the proof must match the claimer, so an\nintermediary can only claim an allocation granted to the intermediary itself. It does mean a\nwrapper realm cannot claim on a user's behalf, which is deliberate.\n\n## Note on v0\n\nv0's README lists an allocation for `g1manfred47kzduec920z88wfr64ylksmdcedar8`. moul's actual\naddress is `...cedlf5`. v1 uses the real one.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/merkledrop/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/merkledrop/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/merkledrop/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/merkledrop/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/merkledrop/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/merkledrop/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/merkledrop/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/merkledrop/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/merkledrop/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/merkledrop/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/merkledrop/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"merkledrop.gno","body":"// Package merkledrop is a Merkle-gated airdrop that actually moves GNOT.\n//\n// It is the successor to r/moul/x/daily/merkledrop/v0, which was generated by\n// the daily pipeline and is deployed on mainnet. v0 works, but it is a\n// demonstration rather than a drop, and its proof scheme is safe by accident.\n// Everything below is what changed and why.\n//\n// # 1. The leaf scheme is domain separated\n//\n// v0 hashed leaves bare and combined nodes commutatively, the OpenZeppelin\n// scheme: leaf = sha256(addr|amount), node = sha256(min||max). Without a\n// leaf/inner tag an inner-node hash is also a valid leaf hash, so anyone who\n// can present a 64-byte leaf preimage can prove membership of a leaf that was\n// never committed.\n//\n// v0 is not exploitable, but only by arithmetic: an inner preimage is exactly\n// 64 bytes, and a v0 leaf preimage is at most 40 (bech32 address) + 1 + 20\n// (uint64 has at most 20 digits) = 61 bytes. 61 \u003c 64, so no collision is\n// reachable. Change the leaf encoding, widen the amount, use a different\n// address form, and the forgery goes live with no visible diff at the call\n// site. That is not a property to rely on.\n//\n// v1 uses gno.land/p/moul/x/merkle/v0, which is the Tendermint scheme: leaves\n// are tagged 0x00 and inner nodes 0x01, so the two preimage spaces cannot\n// overlap at any length.\n//\n// # 2. Proofs are bound to a position\n//\n// v0's proof was a bare sibling list of any length, folded until it ran out.\n// v1's proof carries its index and the total leaf count, and the verifier\n// rebuilds the tree shape from them: a proof cannot be replayed at another\n// index, and one of the wrong length is rejected rather than folded. The\n// sibling count is capped at merkle.MaxDepth, so an untrusted caller cannot\n// choose the length of the loop.\n//\n// # 3. The root is settable, and the drop can close\n//\n// v0's root is a `const`, so the drop can never be re-rooted, extended or\n// ended. v1's owner sets the root, the leaf count and an optional closing\n// height, and can sweep the remainder once it closes.\n//\n// # 4. It moves real coins\n//\n// v0 keeps a uint64 ledger and moves nothing; its README says so, but it sits\n// on mainnet reading like an airdrop. v1 sends ugnot from the realm's own\n// address through the banker, and refuses a claim it cannot pay rather than\n// marking it claimed.\n//\n// # Who the claimer is\n//\n// The claimer is PreviousRealm().Address(), the immediate caller. Called\n// directly by a user that is the user; called through another realm it is that\n// REALM. This is not a hole, because the leaf binds the address and the proof\n// must match the claimer, so an intermediary can only claim an allocation\n// granted to the intermediary itself. It does mean a wrapper realm cannot\n// claim on a user's behalf, which is deliberate.\n//\n// Built on gno.land/p/moul/x/merkle/v0.\npackage merkledrop\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n)\n\n// Denom is the only coin this drop pays in.\nconst Denom = \"ugnot\"\n\n// leafPrefix is part of every leaf preimage, so a proof for one drop cannot be\n// replayed against another realm that happens to use the same encoding.\nconst leafPrefix = \"gno.land/r/moul/x/daily/merkledrop/v1\"\n\n// Owner may set the drop and sweep it.\n//\n// Hardcoded rather than derived from the deployer at init: inside a plain\n// `func Test(t *testing.T)` the gno test runner reports OriginCaller() as the\n// EMPTY address, so an owner taken from it is the empty address in every test\n// and whatever deployed on chain. That divergence is exactly where an\n// authorization bug hides, so the address is written down instead.\nconst Owner = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\nvar (\n\t// Ownable holds the address allowed to set the drop and sweep it.\n\tOwnable *ownable.Ownable\n\n\troot     []byte   // the committed allocation root; nil means no drop\n\ttotal    int      // leaf count the root commits to\n\tclosesAt int64    // chain height after which claims are refused; 0 = never\n\tclaimed  avl.Tree // padded index -\u003e claimer address string\n\tpaid     int64    // running total of ugnot sent\n\n\t// demo holds the allocations of the seeded example drop, so Render can\n\t// show working proofs. A real drop commits only a root and leaves this\n\t// empty: the whole point of a Merkle drop is not storing the allocations.\n\tdemo []Allocation\n)\n\n// Allocation is one entry of a drop: who may claim, and how much.\ntype Allocation struct {\n\tAddress address\n\tAmount  int64\n}\n\nvar (\n\tErrNoDrop     = errors.New(\"merkledrop: no drop is configured\")\n\tErrClosed     = errors.New(\"merkledrop: the drop has closed\")\n\tErrClaimed    = errors.New(\"merkledrop: already claimed\")\n\tErrBadProof   = errors.New(\"merkledrop: invalid proof\")\n\tErrUnfunded   = errors.New(\"merkledrop: the drop cannot cover this claim\")\n\tErrStillOpen  = errors.New(\"merkledrop: the drop has not closed yet\")\n\tErrBadRoot    = errors.New(\"merkledrop: root must be 32 bytes of hex\")\n\tErrBadTotal   = errors.New(\"merkledrop: total must be positive\")\n\tErrBadAmount  = errors.New(\"merkledrop: amount must be positive\")\n)\n\nfunc init() {\n\tOwnable = ownable.NewWithAddress(Owner)\n\tseed()\n}\n\n// Leaf returns the exact preimage committed for one allocation. Reproduce it\n// off chain to rebuild the tree; it is the whole interface between the drop\n// and its generator.\n//\n//\tleaf = \"\u003cpkgpath\u003e|\u003cindex\u003e|\u003caddress\u003e|\u003camount\u003e\"\nfunc Leaf(index int, addr address, amount int64) string {\n\treturn leafPrefix + \"|\" + strconv.Itoa(index) + \"|\" + addr.String() + \"|\" + strconv.FormatInt(amount, 10)\n}\n\n// SetDrop commits a new allocation root. Owner only.\n//\n// totalLeaves is the number of allocations the root commits to; the verifier\n// needs it to rebuild the tree shape, so a wrong value invalidates every\n// proof rather than weakening any. closesAtHeight is the last height at which\n// a claim is accepted, or 0 for a drop that never closes.\n//\n// Setting a new root abandons the previous claim ledger: a drop is a\n// commitment, and replacing it starts a new one.\nfunc SetDrop(cur realm, rootHex string, totalLeaves int, closesAtHeight int64) {\n\tOwnable.AssertOwnedBy(unsafe.PreviousRealm().Address())\n\trb, err := parseRoot(rootHex)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tif totalLeaves \u003c= 0 {\n\t\tpanic(ErrBadTotal.Error())\n\t}\n\troot, total, closesAt = rb, totalLeaves, closesAtHeight\n\tclaimed, paid, demo = avl.Tree{}, 0, nil\n\tchain.Emit(\"DropSet\",\n\t\t\"root\", rootHex,\n\t\t\"total\", strconv.Itoa(totalLeaves),\n\t\t\"closesAt\", strconv.FormatInt(closesAtHeight, 10),\n\t)\n}\n\n// Claim proves the caller is allocated amount at index and pays it out.\n//\n// proof is the comma-separated hex sibling list from the tree generator, leaf\n// first. It panics on a closed drop, a double claim, a bad proof, or a drop\n// that cannot cover the amount; nothing is marked claimed in any of those\n// cases.\nfunc Claim(cur realm, index int, amount int64, proof string) {\n\tif len(root) == 0 {\n\t\tpanic(ErrNoDrop.Error())\n\t}\n\tif IsClosed() {\n\t\tpanic(ErrClosed.Error())\n\t}\n\tif amount \u003c= 0 {\n\t\tpanic(ErrBadAmount.Error())\n\t}\n\tif HasClaimed(index) {\n\t\tpanic(ErrClaimed.Error())\n\t}\n\n\tclaimer := unsafe.PreviousRealm().Address()\n\tp, err := merkle.ParseProof(index, total, proof)\n\tif err != nil {\n\t\tpanic(ErrBadProof.Error())\n\t}\n\tif !p.Verify(root, []byte(Leaf(index, claimer, amount))) {\n\t\tpanic(ErrBadProof.Error())\n\t}\n\n\t// Check funds BEFORE recording the claim, so an underfunded drop does not\n\t// burn an allocation.\n\tif Balance() \u003c amount {\n\t\tpanic(ErrUnfunded.Error())\n\t}\n\n\tclaimed.Set(indexKey(index), claimer.String())\n\tpaid += amount\n\n\tbnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tbnk.SendCoins(Address(), claimer, chain.NewCoins(chain.NewCoin(Denom, amount)))\n\n\tchain.Emit(\"Claimed\",\n\t\t\"index\", strconv.Itoa(index),\n\t\t\"account\", claimer.String(),\n\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t)\n}\n\n// Sweep returns whatever is left to the owner, once the drop has closed. Owner\n// only. A drop with no closing height can never be swept, which is the point\n// of setting one.\nfunc Sweep(cur realm) {\n\towner := Ownable.Owner()\n\tOwnable.AssertOwnedBy(unsafe.PreviousRealm().Address())\n\tif closesAt == 0 || !IsClosed() {\n\t\tpanic(ErrStillOpen.Error())\n\t}\n\tleft := Balance()\n\tif left \u003c= 0 {\n\t\treturn\n\t}\n\tbnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tbnk.SendCoins(Address(), owner, chain.NewCoins(chain.NewCoin(Denom, left)))\n\tchain.Emit(\"Swept\", \"amount\", strconv.FormatInt(left, 10))\n}\n\n// Address returns the realm's own address, which is where the drop is funded.\n// Send ugnot here to fund it.\nfunc Address() address { return chain.PackageAddress(leafPrefix) }\n\n// Balance returns the ugnot the drop still holds.\nfunc Balance() int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(Address()).AmountOf(Denom)\n}\n\n// Root returns the committed root, hex-encoded, or \"\" when no drop is set.\nfunc Root() string {\n\tif len(root) == 0 {\n\t\treturn \"\"\n\t}\n\treturn hexOf(root)\n}\n\n// Total returns the number of allocations the root commits to.\nfunc Total() int { return total }\n\n// ClosesAt returns the last height a claim is accepted, or 0 for never.\nfunc ClosesAt() int64 { return closesAt }\n\n// IsClosed reports whether the drop is past its closing height.\nfunc IsClosed() bool { return closesAt != 0 \u0026\u0026 runtime.ChainHeight() \u003e closesAt }\n\n// Paid returns the ugnot claimed so far.\nfunc Paid() int64 { return paid }\n\n// Claims returns the number of allocations claimed.\nfunc Claims() int { return claimed.Size() }\n\n// HasClaimed reports whether the allocation at index was claimed.\nfunc HasClaimed(index int) bool { return claimed.Has(indexKey(index)) }\n\n// ClaimedBy returns the address that claimed index, or the empty address.\nfunc ClaimedBy(index int) address {\n\tv := claimed.Get(indexKey(index))\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn address(v.(string))\n}\n\n// Verify checks an allocation against the committed root without claiming it,\n// so a recipient can confirm a proof before spending gas on Claim.\nfunc Verify(index int, addr address, amount int64, proof string) bool {\n\tif len(root) == 0 {\n\t\treturn false\n\t}\n\tp, err := merkle.ParseProof(index, total, proof)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn p.Verify(root, []byte(Leaf(index, addr, amount)))\n}\n\nfunc parseRoot(s string) ([]byte, error) {\n\tp, err := merkle.ParseProof(0, 1, strings.TrimSpace(s))\n\tif err != nil || len(p.Siblings) != 1 {\n\t\treturn nil, ErrBadRoot\n\t}\n\treturn p.Siblings[0], nil\n}\n\nfunc hexOf(b []byte) string {\n\tconst digits = \"0123456789abcdef\"\n\tout := make([]byte, 0, len(b)*2)\n\tfor _, c := range b {\n\t\tout = append(out, digits[c\u003e\u003e4], digits[c\u00260x0f])\n\t}\n\treturn string(out)\n}\n\n// indexKey pads the index so avl iteration is numeric, not lexicographic.\n// ufmt has no width flags, so the padding is by hand: unpadded keys sort\n// \"0\",\"1\",\"10\",\"11\",\"2\" and Render would lose the order past nine entries.\nfunc indexKey(i int) string {\n\ts := strconv.Itoa(i)\n\tfor len(s) \u003c 6 {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n"},{"name":"merkledrop_test.gno","body":"package merkledrop\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\talice   = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // demo index 0, 100\n\tbob     = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // demo index 1, 250\n\tmallory = address(\"g1sqmuwtsrgd6t8y2n8f6z5xkltmpmcd64sx3vgg\")\n)\n\nfunc fund(n int64) {\n\ttesting.IssueCoins(Address(), chain.NewCoins(chain.NewCoin(Denom, n)))\n}\n\nfunc balanceOf(a address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(a).AmountOf(Denom)\n}\n\n// Every seeded allocation must verify against the seeded root, and no other\n// address or amount may.\nfunc TestDemoDropVerifies(t *testing.T) {\n\tseed()\n\tif Total() != 4 || Root() == \"\" {\n\t\tt.Fatalf(\"seed left Total=%d Root=%q\", Total(), Root())\n\t}\n\tfor i, a := range demoAllocations {\n\t\tproof := DemoProof(i)\n\t\tif !Verify(i, a.Address, a.Amount, proof) {\n\t\t\tt.Errorf(\"allocation %d does not verify\", i)\n\t\t}\n\t\tif Verify(i, mallory, a.Amount, proof) {\n\t\t\tt.Errorf(\"allocation %d verified for the wrong address\", i)\n\t\t}\n\t\tif Verify(i, a.Address, a.Amount+1, proof) {\n\t\t\tt.Errorf(\"allocation %d verified for the wrong amount\", i)\n\t\t}\n\t\tif i \u003e 0 \u0026\u0026 Verify(i-1, a.Address, a.Amount, proof) {\n\t\t\tt.Errorf(\"allocation %d verified at the wrong index\", i)\n\t\t}\n\t}\n}\n\n// The leaf is the whole interface to an off-chain generator, so pin it.\nfunc TestLeafEncoding(t *testing.T) {\n\tgot := Leaf(3, alice, 1234)\n\twant := \"gno.land/r/moul/x/daily/merkledrop/v1|3|g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5|1234\"\n\tif got != want {\n\t\tt.Errorf(\"Leaf = %q, want %q\", got, want)\n\t}\n}\n\nfunc TestClaimPays(cur realm, t *testing.T) {\n\tseed()\n\tfund(1000)\n\tbefore := balanceOf(alice)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClaim(cross(cur), 0, 100, DemoProof(0))\n\n\tif got := balanceOf(alice) - before; got != 100 {\n\t\tt.Errorf(\"alice received %d ugnot, want 100\", got)\n\t}\n\tif !HasClaimed(0) {\n\t\tt.Error(\"index 0 not marked claimed\")\n\t}\n\tif ClaimedBy(0) != alice {\n\t\tt.Errorf(\"ClaimedBy(0) = %s, want alice\", ClaimedBy(0))\n\t}\n\tif Paid() != 100 || Claims() != 1 {\n\t\tt.Errorf(\"Paid=%d Claims=%d, want 100 and 1\", Paid(), Claims())\n\t}\n\tif Balance() != 900 {\n\t\tt.Errorf(\"drop balance %d, want 900\", Balance())\n\t}\n}\n\nfunc TestClaimRejects(cur realm, t *testing.T) {\n\tseed()\n\tfund(1000)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\turequire.AbortsContains(t, cur, \"invalid proof\", func() {\n\t\tClaim(cross(cur), 0, 999, DemoProof(0)) // wrong amount\n\t})\n\turequire.AbortsContains(t, cur, \"invalid proof\", func() {\n\t\tClaim(cross(cur), 1, 250, DemoProof(1)) // bob's allocation, alice calling\n\t})\n\turequire.AbortsContains(t, cur, \"invalid proof\", func() {\n\t\tClaim(cross(cur), 0, 100, \"deadbeef\") // malformed proof\n\t})\n\turequire.AbortsContains(t, cur, \"amount must be positive\", func() {\n\t\tClaim(cross(cur), 0, 0, DemoProof(0))\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\turequire.AbortsContains(t, cur, \"invalid proof\", func() {\n\t\tClaim(cross(cur), 0, 100, DemoProof(0)) // not in the tree at all\n\t})\n\n\t// Nothing above may have consumed an allocation.\n\tif Claims() != 0 || Paid() != 0 {\n\t\tt.Errorf(\"a rejected claim left state behind: Claims=%d Paid=%d\", Claims(), Paid())\n\t}\n}\n\nfunc TestDoubleClaimRejected(cur realm, t *testing.T) {\n\tseed()\n\tfund(1000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tClaim(cross(cur), 1, 250, DemoProof(1))\n\turequire.AbortsContains(t, cur, \"already claimed\", func() {\n\t\tClaim(cross(cur), 1, 250, DemoProof(1))\n\t})\n\tif Claims() != 1 {\n\t\tt.Errorf(\"Claims = %d, want 1\", Claims())\n\t}\n}\n\n// An underfunded drop must refuse rather than mark the allocation claimed and\n// leave the recipient with nothing to re-claim.\nfunc TestUnderfundedDropDoesNotBurnAnAllocation(cur realm, t *testing.T) {\n\tseed()\n\tfund(10) // less than alice's 100\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\turequire.AbortsContains(t, cur, \"cannot cover\", func() {\n\t\tClaim(cross(cur), 0, 100, DemoProof(0))\n\t})\n\tif HasClaimed(0) {\n\t\tt.Error(\"a refused claim still consumed the allocation\")\n\t}\n\tfund(1000)\n\tClaim(cross(cur), 0, 100, DemoProof(0))\n\tif !HasClaimed(0) {\n\t\tt.Error(\"the claim did not go through once funded\")\n\t}\n}\n\nfunc TestSetDropOwnerOnly(cur realm, t *testing.T) {\n\tseed()\n\tnewRoot := merkle.New([][]byte{[]byte(\"only-leaf\")}).RootHex()\n\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\turequire.AbortsContains(t, cur, \"not owner\", func() {\n\t\tSetDrop(cross(cur), newRoot, 1, 0)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Ownable.Owner()))\n\tSetDrop(cross(cur), newRoot, 1, 0)\n\tif Root() != newRoot || Total() != 1 {\n\t\tt.Errorf(\"SetDrop left Root=%s Total=%d\", Root(), Total())\n\t}\n\tif len(demo) != 0 {\n\t\tt.Error(\"a real drop must not keep the seeded allocation list\")\n\t}\n\tif Claims() != 0 || Paid() != 0 {\n\t\tt.Error(\"SetDrop did not reset the claim ledger\")\n\t}\n}\n\nfunc TestSetDropRejectsBadInput(cur realm, t *testing.T) {\n\tseed()\n\ttesting.SetRealm(testing.NewUserRealm(Ownable.Owner()))\n\tgood := merkle.New([][]byte{[]byte(\"x\")}).RootHex()\n\turequire.AbortsContains(t, cur, \"32 bytes of hex\", func() { SetDrop(cross(cur), \"zz\", 1, 0) })\n\turequire.AbortsContains(t, cur, \"32 bytes of hex\", func() { SetDrop(cross(cur), \"abcd\", 1, 0) })\n\turequire.AbortsContains(t, cur, \"total must be positive\", func() { SetDrop(cross(cur), good, 0, 0) })\n}\n\nfunc TestClosingAndSweep(cur realm, t *testing.T) {\n\tseed()\n\tfund(1000)\n\towner := Ownable.Owner()\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// A drop that never closes can never be swept: that is what setting a\n\t// closing height buys.\n\turequire.AbortsContains(t, cur, \"not closed yet\", func() { Sweep(cross(cur)) })\n\n\tcloseAt := runtime.ChainHeight() + 10\n\troot := merkle.New([][]byte{[]byte(Leaf(0, alice, 100))}).RootHex()\n\tSetDrop(cross(cur), root, 1, closeAt)\n\tif IsClosed() {\n\t\tt.Fatal(\"drop closed before its height\")\n\t}\n\turequire.AbortsContains(t, cur, \"not closed yet\", func() { Sweep(cross(cur)) })\n\n\ttesting.SkipHeights(11)\n\tif !IsClosed() {\n\t\tt.Fatal(\"drop still open past its closing height\")\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\turequire.AbortsContains(t, cur, \"has closed\", func() {\n\t\tClaim(cross(cur), 0, 100, \"\")\n\t})\n\n\townerBefore := balanceOf(owner)\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tSweep(cross(cur))\n\tif Balance() != 0 {\n\t\tt.Errorf(\"drop balance after sweep = %d, want 0\", Balance())\n\t}\n\tif balanceOf(owner)-ownerBefore != 1000 {\n\t\tt.Errorf(\"owner received %d, want 1000\", balanceOf(owner)-ownerBefore)\n\t}\n\tseed()\n}\n\nfunc TestIndexKeyPadsForOrdering(t *testing.T) {\n\t// ufmt has no width flags, so the padding is by hand. Unpadded keys sort\n\t// \"0\",\"1\",\"10\",\"11\",\"2\" and Render loses the order past nine entries.\n\tif indexKey(7) != \"000007\" || indexKey(123456) != \"123456\" {\n\t\tt.Errorf(\"indexKey(7)=%q indexKey(123456)=%q\", indexKey(7), indexKey(123456))\n\t}\n\tif !(indexKey(2) \u003c indexKey(10)) {\n\t\tt.Error(\"padded keys do not sort numerically\")\n\t}\n}\n"},{"name":"render.gno","body":"package merkledrop\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// demoAllocations is the example drop seeded at deploy, so the realm renders\n// working proofs instead of an empty page. A real drop calls SetDrop with a\n// root computed off chain and stores no allocations at all.\nvar demoAllocations = []Allocation{\n\t{Address: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", Amount: 100},\n\t{Address: \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\", Amount: 250},\n\t{Address: \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\", Amount: 500},\n\t{Address: \"g1sss9uxef4l6lwc0mxq8n5v0e4vqpml7c39cxq2\", Amount: 750},\n}\n\n// seed installs the example drop. Also called by the example tests: realm\n// globals persist for a whole test binary and examples run after every Test,\n// so a pinned Render must start from a known state.\nfunc seed() {\n\tdemo = demoAllocations\n\ttree := demoTree()\n\troot = tree.Root()\n\ttotal = len(demo)\n\tclosesAt = 0\n\tclaimed, paid = avl.Tree{}, 0\n}\n\nfunc demoTree() *merkle.Tree {\n\tleaves := make([][]byte, len(demo))\n\tfor i, a := range demo {\n\t\tleaves[i] = []byte(Leaf(i, a.Address, a.Amount))\n\t}\n\treturn merkle.New(leaves)\n}\n\n// DemoProof returns the proof for one seeded allocation, so the drop can be\n// exercised end to end without an off-chain generator. It is empty once a real\n// drop replaces the seeded one.\nfunc DemoProof(index int) string {\n\tif index \u003c 0 || index \u003e= len(demo) {\n\t\treturn \"\"\n\t}\n\tp, err := demoTree().Proof(index)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn p.Hex()\n}\n\n// Render serves the drop overview at \"\" and one allocation at \"proof/\u003cindex\u003e\".\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tif strings.HasPrefix(path, \"proof/\") {\n\t\treturn renderProof(strings.TrimPrefix(path, \"proof/\"))\n\t}\n\treturn renderIndex()\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# MerkleDrop v1\\n\\n\")\n\tb.WriteString(\"A Merkle root gates an airdrop that pays real ugnot. Successor to\\n\")\n\tb.WriteString(\"[v0](/r/moul/x/daily/merkledrop/v0), which moved no coins and whose proof scheme was\\n\")\n\tb.WriteString(\"safe only by accident of encoding lengths.\\n\\n\")\n\n\tb.WriteString(\"## Drop\\n\\n\")\n\tb.WriteString(\"| Field | Value |\\n|---|---|\\n\")\n\tif len(root) == 0 {\n\t\tb.WriteString(\"| Root | _none configured_ |\\n\")\n\t} else {\n\t\tb.WriteString(\"| Root | `\" + Root() + \"` |\\n\")\n\t}\n\tb.WriteString(\"| Allocations | \" + strconv.Itoa(total) + \" |\\n\")\n\tb.WriteString(\"| Closes at height | \" + closesLabel() + \" |\\n\")\n\tb.WriteString(\"| Claimed | \" + strconv.Itoa(Claims()) + \" |\\n\")\n\tb.WriteString(\"| Paid out | \" + strconv.FormatInt(Paid(), 10) + \" ugnot |\\n\")\n\tb.WriteString(\"| Funding address | `\" + Address().String() + \"` |\\n\\n\")\n\n\tb.WriteString(\"## How it differs from v0\\n\\n\")\n\tb.WriteString(\"1. **Domain separated leaves.** v0 hashed leaves bare and combined nodes\\n\")\n\tb.WriteString(\"   commutatively, so an inner-node hash was also a valid leaf hash. It was not\\n\")\n\tb.WriteString(\"   exploitable, but only because a v0 leaf preimage tops out at 61 bytes while an\\n\")\n\tb.WriteString(\"   inner preimage is always 64. v1 tags leaves `0x00` and inner nodes `0x01`.\\n\")\n\tb.WriteString(\"2. **Proofs bound to a position.** v0 folded a sibling list of any length. v1\\n\")\n\tb.WriteString(\"   carries index and total, rebuilds the tree shape, and caps the depth.\\n\")\n\tb.WriteString(\"3. **A settable root and a closing height.** v0's root was a `const`.\\n\")\n\tb.WriteString(\"4. **Real coins.** v0 kept a `uint64` ledger and moved nothing.\\n\\n\")\n\n\tb.WriteString(\"## Leaf encoding\\n\\n\")\n\tb.WriteString(\"Reproduce this off chain to rebuild the tree:\\n\\n\")\n\tb.WriteString(\"```\\n\")\n\tb.WriteString(\"leaf = \\\"\" + leafPrefix + \"|\u003cindex\u003e|\u003caddress\u003e|\u003camount\u003e\\\"\\n\")\n\tb.WriteString(\"tree = Tendermint simple tree, leaf 0x00, inner 0x01\\n\")\n\tb.WriteString(\"```\\n\\n\")\n\n\tif len(demo) == 0 {\n\t\tb.WriteString(\"## Allocations\\n\\n\")\n\t\tb.WriteString(\"A live drop commits only its root, so there is nothing to list here.\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"## Example allocations\\n\\n\")\n\tb.WriteString(\"Seeded at deploy so the drop can be exercised without a generator. A live drop\\n\")\n\tb.WriteString(\"commits only a root and stores none of this.\\n\\n\")\n\tb.WriteString(\"| # | Address | Amount | Claimed |\\n|---|---|---|---|\\n\")\n\tfor i, a := range demo {\n\t\tb.WriteString(\"| [\" + strconv.Itoa(i) + \"](/r/moul/x/daily/merkledrop/v1:proof/\" + strconv.Itoa(i) + \") | `\" +\n\t\t\ta.Address.String() + \"` | \" + strconv.FormatInt(a.Amount, 10) + \" | \" + yesNo(HasClaimed(i)) + \" |\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderProof(raw string) string {\n\ti, err := strconv.Atoi(raw)\n\tif err != nil || i \u003c 0 || i \u003e= len(demo) {\n\t\treturn \"# MerkleDrop v1\\n\\nNo allocation `\" + raw + \"`.\\n\"\n\t}\n\ta := demo[i]\n\tvar b strings.Builder\n\tb.WriteString(\"# MerkleDrop v1: allocation \" + strconv.Itoa(i) + \"\\n\\n\")\n\tb.WriteString(\"| Field | Value |\\n|---|---|\\n\")\n\tb.WriteString(\"| Index | \" + strconv.Itoa(i) + \" |\\n\")\n\tb.WriteString(\"| Total | \" + strconv.Itoa(total) + \" |\\n\")\n\tb.WriteString(\"| Address | `\" + a.Address.String() + \"` |\\n\")\n\tb.WriteString(\"| Amount | \" + strconv.FormatInt(a.Amount, 10) + \" ugnot |\\n\")\n\tb.WriteString(\"| Claimed | \" + yesNo(HasClaimed(i)) + \" |\\n\\n\")\n\tb.WriteString(\"## Leaf\\n\\n\")\n\tb.WriteString(\"```\\n\" + Leaf(i, a.Address, a.Amount) + \"\\n```\\n\\n\")\n\tb.WriteString(\"## Proof\\n\\n\")\n\tb.WriteString(\"```\\n\" + DemoProof(i) + \"\\n```\\n\\n\")\n\tb.WriteString(\"Only `\" + a.Address.String() + \"` can spend it: the address is inside the leaf, so\\n\")\n\tb.WriteString(\"the proof verifies for no one else.\\n\")\n\treturn b.String()\n}\n\nfunc closesLabel() string {\n\tif closesAt == 0 {\n\t\treturn \"never\"\n\t}\n\treturn strconv.FormatInt(closesAt, 10)\n}\n\nfunc yesNo(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}\n"},{"name":"render_example_test.gno","body":"package merkledrop\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tseed()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # MerkleDrop v1\n\t//\n\t// A Merkle root gates an airdrop that pays real ugnot. Successor to\n\t// [v0](/r/moul/x/daily/merkledrop/v0), which moved no coins and whose proof scheme was\n\t// safe only by accident of encoding lengths.\n\t//\n\t// ## Drop\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Root | `6964baa99da23b9d8c76774c6f1122b250040e29c1d75823dda15c043dc65755` |\n\t// | Allocations | 4 |\n\t// | Closes at height | never |\n\t// | Claimed | 0 |\n\t// | Paid out | 0 ugnot |\n\t// | Funding address | `g1jvh5ukk07dvd57fxefcp5aa29xaydxmxs7myyp` |\n\t//\n\t// ## How it differs from v0\n\t//\n\t// 1. **Domain separated leaves.** v0 hashed leaves bare and combined nodes\n\t//    commutatively, so an inner-node hash was also a valid leaf hash. It was not\n\t//    exploitable, but only because a v0 leaf preimage tops out at 61 bytes while an\n\t//    inner preimage is always 64. v1 tags leaves `0x00` and inner nodes `0x01`.\n\t// 2. **Proofs bound to a position.** v0 folded a sibling list of any length. v1\n\t//    carries index and total, rebuilds the tree shape, and caps the depth.\n\t// 3. **A settable root and a closing height.** v0's root was a `const`.\n\t// 4. **Real coins.** v0 kept a `uint64` ledger and moved nothing.\n\t//\n\t// ## Leaf encoding\n\t//\n\t// Reproduce this off chain to rebuild the tree:\n\t//\n\t// ```\n\t// leaf = \"gno.land/r/moul/x/daily/merkledrop/v1|\u003cindex\u003e|\u003caddress\u003e|\u003camount\u003e\"\n\t// tree = Tendermint simple tree, leaf 0x00, inner 0x01\n\t// ```\n\t//\n\t// ## Example allocations\n\t//\n\t// Seeded at deploy so the drop can be exercised without a generator. A live drop\n\t// commits only a root and stores none of this.\n\t//\n\t// | # | Address | Amount | Claimed |\n\t// |---|---|---|---|\n\t// | [0](/r/moul/x/daily/merkledrop/v1:proof/0) | `g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5` | 100 | no |\n\t// | [1](/r/moul/x/daily/merkledrop/v1:proof/1) | `g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj` | 250 | no |\n\t// | [2](/r/moul/x/daily/merkledrop/v1:proof/2) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` | 500 | no |\n\t// | [3](/r/moul/x/daily/merkledrop/v1:proof/3) | `g1sss9uxef4l6lwc0mxq8n5v0e4vqpml7c39cxq2` | 750 | no |\n}\n\n// ExampleRenderProof pins one allocation page, including its live proof.\nfunc ExampleRenderProof() {\n\tseed()\n\tprint(Render(\"proof/2\"))\n\t// Output:\n\t// # MerkleDrop v1: allocation 2\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Index | 2 |\n\t// | Total | 4 |\n\t// | Address | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t// | Amount | 500 ugnot |\n\t// | Claimed | no |\n\t//\n\t// ## Leaf\n\t//\n\t// ```\n\t// gno.land/r/moul/x/daily/merkledrop/v1|2|g1manfred47kzduec920z88wfr64ylksmdcedlf5|500\n\t// ```\n\t//\n\t// ## Proof\n\t//\n\t// ```\n\t// 337bb23c66f621db38e704fc2d64d27d5fa6308a333fd9d2d69c6ccd9390c056,b498260d909eee2a1b8a88524d5e4d08128aa7d8ca433468379db031976958e1\n\t// ```\n\t//\n\t// Only `g1manfred47kzduec920z88wfr64ylksmdcedlf5` can spend it: the address is inside the leaf, so\n\t// the proof verifies for no one else.\n}\n\n// ExampleRenderMissingProof pins the not-found page.\nfunc ExampleRenderMissingProof() {\n\tseed()\n\tprint(Render(\"proof/99\"))\n\t// Output:\n\t// # MerkleDrop v1\n\t//\n\t// No allocation `99`.\n}\n"}]},"send":"","max_deposit":"14000000ugnot"}],"fee":{"gas_wanted":"97217600","gas_fee":"291652ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"QFcdZ5mEojDOgcSnTwcunH8mBHXnKXNeMp3uLQsvvcIZZJ92NIk3Yha9lYnAI6itaRIzaKCN46Dxhu55l4QepA=="}],"memo":""},"metadata":{"timestamp":"1790961141"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"rWp9vhI2RMS/A9eIyxo1kCkaQQFGOqqaIIAMnMRWzZpEUXDwzYSkw3QYBAxE9QWcG5rJ82lMOgfd20yOqfi9aQ=="}],"memo":""},"metadata":{"timestamp":"1790961142"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"microblog","path":"gno.land/r/moul/x/daily/microblog/v1","files":[{"name":"README.md","body":"# Microblog Wall\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA public, append-only microblog for gno.land. Anyone can post a short message\n(up to 280 bytes); each post records the caller's address and the block height\nat which it was made. The `Render` view shows the wall newest-first, 20 posts\nper page, with total count and prev/next pagination driven by the render path.\n\n- **Realm path:** `gno.land/r/REPLACE_ADDR/microblog`\n- **Gno version:** 0.9 (sapphire)\n\n## API\n\n- `Post(cur realm, msg string)` — crossing tx. Panics if `msg` is empty or\n  longer than 280 bytes. Stores `{author, msg, height}`.\n- `Count() int` — total number of posts.\n- `Render(path string) string` — Markdown wall, newest-first, paginated.\n\n## Example calls\n\nPost a message (crossing call via `gnokey`):\n\n```sh\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/REPLACE_ADDR/microblog\" \\\n  -func Post \\\n  -args \"gm gno.land 👋\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e mykey\n```\n\nView the wall in gnoweb:\n\n```\nhttps://gno.land/r/REPLACE_ADDR/microblog          # page 1 (newest 20)\nhttps://gno.land/r/REPLACE_ADDR/microblog:?page=2  # older posts\nhttps://gno.land/r/REPLACE_ADDR/microblog:/2       # same page, path form\n```\n\nFrom another realm:\n\n```go\nimport \"gno.land/r/REPLACE_ADDR/microblog\"\n\nfunc Shout(cur realm) {\n    microblog.Post(cross(cur), \"posted from another realm\")\n}\n```\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/microblog) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline`, `shortAddr` helpers.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nVisible change: addresses now render in monospace.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/microblog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/microblog/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/microblog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/microblog/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/microblog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/microblog/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/microblog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/microblog/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/microblog/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/microblog/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/microblog/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"microblog.gno","body":"// Package microblog is a public microblog wall for gno.land.\n//\n// Anyone can Post a short message (\u003c= maxMsgLen chars). Every post records\n// the caller address, the message, and the block height at which it was made.\n// Render displays the wall newest-first, 20 posts per page, with pagination\n// driven by the Render path (e.g. \"?page=2\" or \"/2\").\npackage microblog\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\n// maxMsgLen is the maximum length (in bytes) of a single post.\nconst maxMsgLen = 280\n\n// pageSize is how many posts a single Render page shows.\nconst pageSize = 20\n\n// post is a single microblog entry.\ntype post struct {\n\tAuthor string // bech32 address of the poster\n\tMsg    string // the message body\n\tHeight int64  // block height at which it was posted\n}\n\n// posts is the append-only wall, in chronological (oldest-first) order.\n// Render reverses this view to show newest-first.\nvar posts []post\n\n// Post publishes msg to the wall. It is a crossing function: callers invoke it\n// with Post(cross(cur), \"hello\"). It panics if msg is empty or longer than\n// maxMsgLen bytes.\nfunc Post(cur realm, msg string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tif len(msg) == 0 {\n\t\tpanic(\"microblog: empty message\")\n\t}\n\tif len(msg) \u003e maxMsgLen {\n\t\tpanic(\"microblog: message too long (max \" + strconv.Itoa(maxMsgLen) + \" bytes)\")\n\t}\n\n\tauthor := unsafe.PreviousRealm().Address()\n\n\tposts = append(posts, post{\n\t\tAuthor: author.String(),\n\t\tMsg:    msg,\n\t\tHeight: runtime.ChainHeight(),\n\t})\n\n\tchain.Emit(\"Post\", \"author\", author.String(), \"len\", strconv.Itoa(len(msg)))\n}\n\n// Count returns the total number of posts on the wall.\nfunc Count() int {\n\treturn len(posts)\n}\n\n// Render renders the wall as Markdown, newest-first, pageSize posts per page.\n// The page is parsed from path: \"?page=N\", \"?p=N\", \"/N\", or a bare \"N\" all\n// select page N (1-indexed). Anything else defaults to page 1.\nfunc Render(path string) string {\n\ttotal := len(posts)\n\tpage := parsePage(path)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Microblog Wall\\n\\n\")\n\n\tif total == 0 {\n\t\tb.WriteString(\"_No posts yet. Be the first to post._\\n\")\n\t\treturn b.String()\n\t}\n\n\tpages := (total + pageSize - 1) / pageSize\n\tif page \u003c 1 {\n\t\tpage = 1\n\t}\n\tif page \u003e pages {\n\t\tpage = pages\n\t}\n\n\tb.WriteString(strconv.Itoa(total))\n\tb.WriteString(\" posts total · page \")\n\tb.WriteString(strconv.Itoa(page))\n\tb.WriteString(\" of \")\n\tb.WriteString(strconv.Itoa(pages))\n\tb.WriteString(\"\\n\\n\")\n\n\t// Newest-first: post index total-1 is newest. For page p (1-indexed),\n\t// skip (p-1)*pageSize newest posts, then take up to pageSize.\n\tstart := total - 1 - (page-1)*pageSize\n\tend := start - pageSize + 1\n\tif end \u003c 0 {\n\t\tend = 0\n\t}\n\n\tfor i := start; i \u003e= end; i-- {\n\t\tp := posts[i]\n\t\tb.WriteString(\"- **\")\n\t\tb.WriteString(ui.AddrOf(p.Author))\n\t\tb.WriteString(\"** · height \")\n\t\tb.WriteString(strconv.FormatInt(p.Height, 10))\n\t\tb.WriteString(\"\\n\\n  \")\n\t\tb.WriteString(ui.Inline(p.Msg))\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"\\n\")\n\tb.WriteString(renderNav(page, pages))\n\treturn b.String()\n}\n\n// renderNav builds a simple prev/next navigation footer as Markdown links.\nfunc renderNav(page, pages int) string {\n\tvar b strings.Builder\n\tif page \u003e 1 {\n\t\tb.WriteString(\"[← newer](?page=\")\n\t\tb.WriteString(strconv.Itoa(page - 1))\n\t\tb.WriteString(\")\")\n\t}\n\tif page \u003e 1 \u0026\u0026 page \u003c pages {\n\t\tb.WriteString(\" · \")\n\t}\n\tif page \u003c pages {\n\t\tb.WriteString(\"[older →](?page=\")\n\t\tb.WriteString(strconv.Itoa(page + 1))\n\t\tb.WriteString(\")\")\n\t}\n\tif b.Len() == 0 {\n\t\treturn \"\"\n\t}\n\treturn b.String() + \"\\n\"\n}\n\n// parsePage extracts the 1-indexed page number from a Render path. It accepts\n// \"?page=N\", \"?p=N\", \"/N\", and a bare \"N\". Unrecognized input yields page 1.\nfunc parsePage(path string) int {\n\tpath = strings.TrimSpace(path)\n\tif path == \"\" {\n\t\treturn 1\n\t}\n\n\t// Query form: \"?page=2\u0026foo=bar\" or \"?p=2\".\n\tif idx := strings.IndexByte(path, '?'); idx \u003e= 0 {\n\t\tquery := path[idx+1:]\n\t\tfor _, part := range strings.Split(query, \"\u0026\") {\n\t\t\tkv := strings.SplitN(part, \"=\", 2)\n\t\t\tif len(kv) != 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif kv[0] == \"page\" || kv[0] == \"p\" {\n\t\t\t\tif n, err := strconv.Atoi(strings.TrimSpace(kv[1])); err == nil {\n\t\t\t\t\treturn n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn 1\n\t}\n\n\t// Path form: \"/2\" or \"2\".\n\tseg := strings.TrimPrefix(path, \"/\")\n\tif n, err := strconv.Atoi(seg); err == nil {\n\t\treturn n\n\t}\n\treturn 1\n}\n"},{"name":"microblog_test.gno","body":"package microblog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// resetWall clears package state between tests (globals persist in-process,\n// and subtests do not reset them — do it explicitly).\nfunc resetWall() { posts = nil }\n\n// asUser must be inlined into each test: SetRealm affects the calling frame\n// only. We therefore call it directly in the test bodies below.\n\nfunc TestPostAndCount(cur realm, t *testing.T) {\n\tresetWall()\n\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"hello wall\")\n\n\tif got := Count(); got != 1 {\n\t\tt.Fatalf(\"Count() = %d, want 1\", got)\n\t}\n\tif posts[0].Msg != \"hello wall\" {\n\t\tt.Errorf(\"Msg = %q, want %q\", posts[0].Msg, \"hello wall\")\n\t}\n\tif posts[0].Author != alice.String() {\n\t\tt.Errorf(\"Author = %q, want %q\", posts[0].Author, alice.String())\n\t}\n}\n\nfunc TestPostTooLongPanics(cur realm, t *testing.T) {\n\tresetWall()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bob\")))\n\n\t// Aborts from a cross(cur) call cannot be caught by a plain recover();\n\t// assert on the abort message instead.\n\tuassert.AbortsWithMessage(t, cur, \"microblog: message too long (max 280 bytes)\", func() {\n\t\tPost(cross(cur), strings.Repeat(\"x\", maxMsgLen+1))\n\t})\n}\n\nfunc TestPostEmptyPanics(cur realm, t *testing.T) {\n\tresetWall()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bob\")))\n\n\t// Aborts from a cross(cur) call cannot be caught by a plain recover();\n\t// assert on the abort message instead.\n\tuassert.AbortsWithMessage(t, cur, \"microblog: empty message\", func() {\n\t\tPost(cross(cur), \"\")\n\t})\n}\n\nfunc TestPostMaxLenOK(cur realm, t *testing.T) {\n\tresetWall()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"carol\")))\n\n\t// Exactly maxMsgLen bytes must be accepted.\n\tPost(cross(cur), strings.Repeat(\"y\", maxMsgLen))\n\tif got := Count(); got != 1 {\n\t\tt.Fatalf(\"Count() = %d, want 1 for exactly-max message\", got)\n\t}\n}\n\nfunc TestRenderEmpty(t *testing.T) {\n\tresetWall()\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"No posts yet\") {\n\t\tt.Errorf(\"empty Render should mention no posts, got:\\n%s\", out)\n\t}\n}\n\nfunc TestRenderNewestFirstAndPagination(cur realm, t *testing.T) {\n\tresetWall()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"dave\")))\n\n\t// 25 posts -\u003e 2 pages (20 + 5).\n\tfor i := 0; i \u003c 25; i++ {\n\t\tPost(cross(cur), \"msg\"+itoa(i))\n\t}\n\n\tif got := Count(); got != 25 {\n\t\tt.Fatalf(\"Count() = %d, want 25\", got)\n\t}\n\n\tpage1 := Render(\"\")\n\t// Newest (msg24) must appear before older (msg5) on page 1.\n\ti24 := strings.Index(page1, \"msg24\")\n\ti5 := strings.Index(page1, \"msg5\")\n\tif i24 \u003c 0 || i5 \u003c 0 {\n\t\tt.Fatalf(\"page 1 missing expected posts: msg24=%d msg5=%d\", i24, i5)\n\t}\n\tif i24 \u003e i5 {\n\t\tt.Errorf(\"page 1 not newest-first: msg24 at %d should precede msg5 at %d\", i24, i5)\n\t}\n\tif !strings.Contains(page1, \"page 1 of 2\") {\n\t\tt.Errorf(\"page 1 header wrong, got:\\n%s\", page1)\n\t}\n\n\t// Page 2 via query form must contain the oldest post.\n\tpage2 := Render(\"?page=2\")\n\tif !strings.Contains(page2, \"msg0\") {\n\t\tt.Errorf(\"page 2 should contain oldest msg0, got:\\n%s\", page2)\n\t}\n\tif !strings.Contains(page2, \"page 2 of 2\") {\n\t\tt.Errorf(\"page 2 header wrong, got:\\n%s\", page2)\n\t}\n\n\t// Path form \"/2\" should equal query form \"?page=2\".\n\tif Render(\"/2\") != page2 {\n\t\tt.Errorf(\"path form /2 differs from query form ?page=2\")\n\t}\n}\n\nfunc TestParsePage(t *testing.T) {\n\tcases := []struct {\n\t\tin   string\n\t\twant int\n\t}{\n\t\t{\"\", 1},\n\t\t{\"?page=3\", 3},\n\t\t{\"?p=4\", 4},\n\t\t{\"/2\", 2},\n\t\t{\"5\", 5},\n\t\t{\"?page=abc\", 1},\n\t\t{\"garbage\", 1},\n\t}\n\tfor _, c := range cases {\n\t\tif got := parsePage(c.in); got != c.want {\n\t\t\tt.Errorf(\"parsePage(%q) = %d, want %d\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\n// itoa is a tiny local int-\u003estring helper for building test messages.\nfunc itoa(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\tneg := n \u003c 0\n\tif neg {\n\t\tn = -n\n\t}\n\tvar buf [20]byte\n\ti := len(buf)\n\tfor n \u003e 0 {\n\t\ti--\n\t\tbuf[i] = byte('0' + n%10)\n\t\tn /= 10\n\t}\n\tif neg {\n\t\ti--\n\t\tbuf[i] = '-'\n\t}\n\treturn string(buf[i:])\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"45771400","gas_fee":"137314ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"IBiQJ8KGC5+xCfCcFW2SCe+C6JNlQ1m7ykKwIywDu1MRR8+KJ5f02e0nXRzVmELcsHfQFrpwbZRcZpXzr5DRgw=="}],"memo":""},"metadata":{"timestamp":"1790961197"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"moodstone","path":"gno.land/r/moul/x/daily/moodstone/v1","files":[{"name":"README.md","body":"# 🪨 Moodstone\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn on-chain mood tracker for the Gno ecosystem. Users log how they're feeling with a short note, and the realm shows live community sentiment stats — all stored immutably on gno.land.\n\n**Realm path:** `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/moodstone`\n\n## Moods\n\n`happy` · `sad` · `excited` · `calm` · `anxious` · `angry` · `neutral`\n\n## Example Calls\n\n```bash\n# Log a mood\ngnokey maketx call \\\n  -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/moodstone \\\n  -func LogMood \\\n  -args 'happy' -args 'Just deployed my first realm!' \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid test5 \\\n  test5.gno.land:443\n\n# Query total entries (read-only)\ngnokey query vm/qeval \\\n  -remote test5.gno.land:443 \\\n  -data 'gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/moodstone.TotalEntries()'\n\n# Query dominant mood\ngnokey query vm/qeval \\\n  -remote test5.gno.land:443 \\\n  -data 'gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/moodstone.DominantMood()'\n```\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/moodstone) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/moodstone/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/moodstone/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/moodstone/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/moodstone/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/moodstone/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/moodstone/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/moodstone/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/moodstone/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/moodstone/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/moodstone/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/moodstone/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"moodstone.gno","body":"package moodstone\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\n// Entry holds a single mood log.\ntype Entry struct {\n\tAuthor address\n\tMood   string\n\tNote   string\n\tBlock  int64\n}\n\nvar entries []Entry\n\nvar validMoods = []string{\"happy\", \"sad\", \"excited\", \"calm\", \"anxious\", \"angry\", \"neutral\"}\n\nfunc isValid(mood string) bool {\n\tfor _, m := range validMoods {\n\t\tif m == mood {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc emoji(mood string) string {\n\tswitch mood {\n\tcase \"happy\":\n\t\treturn \"😊\"\n\tcase \"sad\":\n\t\treturn \"😢\"\n\tcase \"excited\":\n\t\treturn \"🎉\"\n\tcase \"calm\":\n\t\treturn \"😌\"\n\tcase \"anxious\":\n\t\treturn \"😰\"\n\tcase \"angry\":\n\t\treturn \"😠\"\n\tcase \"neutral\":\n\t\treturn \"😐\"\n\t}\n\treturn \"❓\"\n}\n\nfunc bar(count, total int) string {\n\tif total == 0 {\n\t\treturn strings.Repeat(\"░\", 20)\n\t}\n\tfilled := (count * 20) / total\n\treturn strings.Repeat(\"▓\", filled) + strings.Repeat(\"░\", 20-filled)\n}\n\n// LogMood records the caller's current mood with an optional note.\n// mood must be one of: happy sad excited calm anxious angry neutral\nfunc LogMood(_ realm, mood, note string) {\n\tmood = strings.ToLower(strings.TrimSpace(mood))\n\tif !isValid(mood) {\n\t\tpanic(\"invalid mood; choose from: \" + strings.Join(validMoods, \", \"))\n\t}\n\tentries = append(entries, Entry{\n\t\tAuthor: unsafe.OriginCaller(),\n\t\tMood:   mood,\n\t\tNote:   strings.TrimSpace(note),\n\t\tBlock:  runtime.ChainHeight(),\n\t})\n}\n\n// TotalEntries returns the total number of mood logs on record.\nfunc TotalEntries() int {\n\treturn len(entries)\n}\n\n// MoodCount returns how many times the given mood has been logged.\nfunc MoodCount(mood string) int {\n\tmood = strings.ToLower(strings.TrimSpace(mood))\n\tn := 0\n\tfor _, e := range entries {\n\t\tif e.Mood == mood {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// DominantMood returns the most-logged mood, or \"none\" if no entries.\nfunc DominantMood() string {\n\tif len(entries) == 0 {\n\t\treturn \"none\"\n\t}\n\tcounts := make(map[string]int)\n\tfor _, e := range entries {\n\t\tcounts[e.Mood]++\n\t}\n\tbest := \"\"\n\tbestN := 0\n\tfor _, m := range validMoods {\n\t\tif counts[m] \u003e bestN {\n\t\t\tbestN = counts[m]\n\t\t\tbest = m\n\t\t}\n\t}\n\treturn best\n}\n\nfunc Render(path string) string {\n\tout := \"# 🪨 Moodstone — On-chain Mood Tracker\\n\\n\"\n\tout += \"\u003e Log how you feel. Watch how the community feels. Immutably, on Gno.\\n\\n\"\n\n\ttotal := len(entries)\n\n\t// Community stats table\n\tout += \"## 📊 Community Vibes\\n\\n\"\n\tif total == 0 {\n\t\tout += \"*No moods logged yet — be the first!*\\n\\n\"\n\t} else {\n\t\tcounts := make(map[string]int)\n\t\tfor _, e := range entries {\n\t\t\tcounts[e.Mood]++\n\t\t}\n\t\tout += \"| Mood | Count | Distribution |\\n\"\n\t\tout += \"|------|-------|--------------|\\n\"\n\t\tfor _, m := range validMoods {\n\t\t\tc := counts[m]\n\t\t\tpct := 0\n\t\t\tif total \u003e 0 {\n\t\t\t\tpct = (c * 100) / total\n\t\t\t}\n\t\t\tout += \"| \" + emoji(m) + \" \" + m + \" | \" + strconv.Itoa(c) +\n\t\t\t\t\" | `\" + bar(c, total) + \"` \" + strconv.Itoa(pct) + \"% |\\n\"\n\t\t}\n\t\tdom := DominantMood()\n\t\tout += \"\\n**Total entries:** \" + strconv.Itoa(total) +\n\t\t\t\" · **Dominant mood:** \" + emoji(dom) + \" \" + dom + \"\\n\\n\"\n\t}\n\n\t// Recent entries (newest first, max 10)\n\tout += \"## 📝 Recent Entries\\n\\n\"\n\tif total == 0 {\n\t\tout += \"*Nothing here yet.*\\n\\n\"\n\t} else {\n\t\tstart := total - 10\n\t\tif start \u003c 0 {\n\t\t\tstart = 0\n\t\t}\n\t\tfor i := total - 1; i \u003e= start; i-- {\n\t\t\te := entries[i]\n\t\t\tline := \"- \" + emoji(e.Mood) + \" **\" + e.Mood + \"**\"\n\t\t\tif e.Note != \"\" {\n\t\t\t\tline += \": *\" + e.Note + \"*\"\n\t\t\t}\n\t\t\tline += \" — \" + ui.Addr(e.Author) + \" at block \" +\n\t\t\t\tstrconv.FormatInt(e.Block, 10)\n\t\t\tout += line + \"\\n\"\n\t\t}\n\t\tout += \"\\n\"\n\t}\n\n\t// How to use\n\tout += \"## 🚀 How to Use\\n\\n\"\n\tout += \"```bash\\n\"\n\tout += \"gnokey maketx call \\\\\\n\"\n\tout += \"  -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/moodstone \\\\\\n\"\n\tout += \"  -func LogMood \\\\\\n\"\n\tout += \"  -args 'happy' -args 'Just shipped something awesome!'\\n\"\n\tout += \"```\\n\\n\"\n\tout += \"**Valid moods:** \" + strings.Join(validMoods, \" · \") + \"\\n\"\n\n\treturn out\n}\n"},{"name":"moodstone_test.gno","body":"package moodstone\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\nfunc TestLogMoodBasic(cur realm, t *testing.T) {\n\tentries = nil\n\ttesting.SetOriginCaller(alice)\n\n\tLogMood(cross(cur),\"happy\", \"great day!\")\n\tLogMood(cross(cur),\"calm\", \"\")\n\n\tif len(entries) != 2 {\n\t\tt.Fatalf(\"expected 2 entries, got %d\", len(entries))\n\t}\n\tif entries[0].Mood != \"happy\" {\n\t\tt.Errorf(\"expected happy, got %s\", entries[0].Mood)\n\t}\n\tif entries[0].Note != \"great day!\" {\n\t\tt.Errorf(\"expected 'great day!', got %s\", entries[0].Note)\n\t}\n\tif entries[1].Mood != \"calm\" {\n\t\tt.Errorf(\"expected calm, got %s\", entries[1].Mood)\n\t}\n}\n\nfunc TestLogMoodCaseInsensitive(cur realm, t *testing.T) {\n\tentries = nil\n\ttesting.SetOriginCaller(alice)\n\n\tLogMood(cross(cur),\"HAPPY\", \"uppercase input\")\n\tif entries[0].Mood != \"happy\" {\n\t\tt.Errorf(\"expected normalized to happy, got %s\", entries[0].Mood)\n\t}\n}\n\nfunc TestIsValid(t *testing.T) {\n\tfor _, m := range validMoods {\n\t\tif !isValid(m) {\n\t\t\tt.Errorf(\"%s should be valid\", m)\n\t\t}\n\t}\n\tif isValid(\"euphoric\") {\n\t\tt.Error(\"euphoric should not be valid\")\n\t}\n\tif isValid(\"\") {\n\t\tt.Error(\"empty string should not be valid\")\n\t}\n}\n\nfunc TestMoodCount(cur realm, t *testing.T) {\n\tentries = nil\n\ttesting.SetOriginCaller(alice)\n\n\tLogMood(cross(cur),\"happy\", \"\")\n\tLogMood(cross(cur),\"happy\", \"\")\n\tLogMood(cross(cur),\"sad\", \"\")\n\n\tif MoodCount(\"happy\") != 2 {\n\t\tt.Errorf(\"expected 2 happy, got %d\", MoodCount(\"happy\"))\n\t}\n\tif MoodCount(\"sad\") != 1 {\n\t\tt.Errorf(\"expected 1 sad, got %d\", MoodCount(\"sad\"))\n\t}\n\tif MoodCount(\"angry\") != 0 {\n\t\tt.Errorf(\"expected 0 angry, got %d\", MoodCount(\"angry\"))\n\t}\n}\n\nfunc TestTotalEntries(cur realm, t *testing.T) {\n\tentries = nil\n\n\tif TotalEntries() != 0 {\n\t\tt.Errorf(\"expected 0, got %d\", TotalEntries())\n\t}\n\ttesting.SetOriginCaller(alice)\n\tLogMood(cross(cur),\"excited\", \"testing!\")\n\tif TotalEntries() != 1 {\n\t\tt.Errorf(\"expected 1, got %d\", TotalEntries())\n\t}\n}\n\nfunc TestDominantMood(cur realm, t *testing.T) {\n\tentries = nil\n\n\tif DominantMood() != \"none\" {\n\t\tt.Errorf(\"expected none on empty, got %s\", DominantMood())\n\t}\n\n\ttesting.SetOriginCaller(alice)\n\tLogMood(cross(cur),\"happy\", \"\")\n\tLogMood(cross(cur),\"happy\", \"\")\n\n\ttesting.SetOriginCaller(bob)\n\tLogMood(cross(cur),\"sad\", \"\")\n\n\tif DominantMood() != \"happy\" {\n\t\tt.Errorf(\"expected happy to dominate, got %s\", DominantMood())\n\t}\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\tentries = nil\n\n\tout := Render(\"\")\n\tif len(out) == 0 {\n\t\tt.Error(\"Render returned empty string\")\n\t}\n\n\ttesting.SetOriginCaller(alice)\n\tLogMood(cross(cur),\"neutral\", \"just checking the render\")\n\n\tout = Render(\"\")\n\tif len(out) == 0 {\n\t\tt.Error(\"Render returned empty string after entries\")\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"39292200","gas_fee":"117876ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"7t1RfFcOGm5+ZriqNAPn6J/in3tVcoOeY6rNHYbpCnkSw8Vf3ko9sdGOZf09+F9+llE9YLD+hKp1/8qDmBWpEA=="}],"memo":""},"metadata":{"timestamp":"1790961201"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"multisetdemo","path":"gno.land/r/moul/x/daily/multisetdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/multisetdemo/v0`\n\n**Live demo of [`p/moul/x/daily/multiset`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/multiset).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/multisetdemo/v0`](https://gno.land/r/moul/x/daily/multisetdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/multisetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisetdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/multisetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisetdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/multisetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisetdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/multisetdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisetdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/multisetdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/multisetdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/multisetdemo/v0\"\ngno = \"0.9\"\n"},{"name":"multisetdemo.gno","body":"// Package multisetdemo is a small gnoweb demo of the bag / frequency counter\n// provided by the [p/moul/x/daily/multiset](/p/moul/x/daily/multiset/v0)\n// library: word frequencies, ranking, and multiset algebra.\n//\n// It contains no counting logic of its own. Stateless, so Render is\n// deterministic — which is precisely what the library is for.\npackage multisetdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/multiset/v0\"\n)\n\nconst sample = \"the quick brown fox jumps over the lazy dog the fox barks and the dog barks\"\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Multiset\\n\\n\")\n\tb.WriteString(\"A bag that counts duplicates, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/multiset`](/p/moul/x/daily/multiset/v0) library.\\n\\n\")\n\n\tm := multiset.FromSlice(strings.Split(sample, \" \"))\n\n\tb.WriteString(\"## Word frequencies\\n\\n\")\n\tb.WriteString(\"\u003e \" + sample + \"\\n\\n\")\n\tb.WriteString(\"`\" + strconv.Itoa(m.Total()) + \"` words, `\")\n\tb.WriteString(strconv.Itoa(m.Distinct()) + \"` distinct.\\n\\n\")\n\n\tb.WriteString(\"## `MostCommon(5)`\\n\\n\")\n\tb.WriteString(\"| rank | word | count |\\n|---|---|---|\\n\")\n\tfor i, e := range m.MostCommon(5) {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | `\" + e.Elem + \"` | \" +\n\t\t\tstrconv.Itoa(e.Count) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\nNote the ties. `barks`, `dog` and `fox` all occur twice and are \")\n\tb.WriteString(\"ranked **alphabetically** — the order is count descending, then \")\n\tb.WriteString(\"element ascending. That second key is not decoration: without it the \")\n\tb.WriteString(\"ranking would fall back on map iteration order, which gno leaves \")\n\tb.WriteString(\"unspecified, and two nodes could render different tables.\\n\\n\")\n\n\tb.WriteString(\"## Algebra\\n\\n\")\n\ta := multiset.FromSlice([]string{\"x\", \"x\", \"x\", \"y\"})\n\tc := multiset.FromSlice([]string{\"x\", \"x\", \"z\"})\n\tb.WriteString(\"With `A = {x:3, y:1}` and `B = {x:2, z:1}`:\\n\\n\")\n\tb.WriteString(\"| op | meaning | result |\\n|---|---|---|\\n\")\n\tb.WriteString(\"| `Union` | max of each count | \" + brief(a.Union(c)) + \" |\\n\")\n\tb.WriteString(\"| `Intersect` | min, common only | \" + brief(a.Intersect(c)) + \" |\\n\")\n\tb.WriteString(\"| `Sum` | counts added | \" + brief(a.Sum(c)) + \" |\\n\")\n\n\tb.WriteString(\"\\n## Removal\\n\\n\")\n\td := multiset.FromSlice([]string{\"a\", \"a\", \"a\"})\n\tb.WriteString(\"Starting from \" + brief(d) + \":\\n\\n\")\n\td.Remove(\"a\")\n\tb.WriteString(\"- after `Remove(\\\"a\\\")` → \" + brief(d) + \"\\n\")\n\td.RemoveN(\"a\", 100)\n\tb.WriteString(\"- after `RemoveN(\\\"a\\\", 100)` → \" + brief(d) +\n\t\t\" — over-removing clears the element instead of going negative\\n\")\n\treturn b.String()\n}\n\nfunc brief(m *multiset.MultiSet) string {\n\tif m.IsEmpty() {\n\t\treturn \"`{}`\"\n\t}\n\tparts := []string{}\n\tfor _, e := range m.Elements() {\n\t\tparts = append(parts, e+\":\"+strconv.Itoa(m.Count(e)))\n\t}\n\treturn \"`{\" + strings.Join(parts, \", \") + \"}`\"\n}\n"},{"name":"render_example_test.gno","body":"package multisetdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Multiset\n\t//\n\t// A bag that counts duplicates, demoing the [`p/moul/x/daily/multiset`](/p/moul/x/daily/multiset/v0) library.\n\t//\n\t// ## Word frequencies\n\t//\n\t// \u003e the quick brown fox jumps over the lazy dog the fox barks and the dog barks\n\t//\n\t// `16` words, `10` distinct.\n\t//\n\t// ## `MostCommon(5)`\n\t//\n\t// | rank | word | count |\n\t// |---|---|---|\n\t// | 1 | `the` | 4 |\n\t// | 2 | `barks` | 2 |\n\t// | 3 | `dog` | 2 |\n\t// | 4 | `fox` | 2 |\n\t// | 5 | `and` | 1 |\n\t//\n\t// Note the ties. `barks`, `dog` and `fox` all occur twice and are ranked **alphabetically** — the order is count descending, then element ascending. That second key is not decoration: without it the ranking would fall back on map iteration order, which gno leaves unspecified, and two nodes could render different tables.\n\t//\n\t// ## Algebra\n\t//\n\t// With `A = {x:3, y:1}` and `B = {x:2, z:1}`:\n\t//\n\t// | op | meaning | result |\n\t// |---|---|---|\n\t// | `Union` | max of each count | `{x:3, y:1, z:1}` |\n\t// | `Intersect` | min, common only | `{x:2}` |\n\t// | `Sum` | counts added | `{x:5, y:1, z:1}` |\n\t//\n\t// ## Removal\n\t//\n\t// Starting from `{a:3}`:\n\t//\n\t// - after `Remove(\"a\")` → `{a:2}`\n\t// - after `RemoveN(\"a\", 100)` → `{}` — over-removing clears the element instead of going negative\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"28889600","gas_fee":"86668ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"fBo9XLT/o1/mMYxr5hdkubC94RQahNA4pwLng+qdTqcXdxcv7bm/MSOUy3c9MIQgxk0JPV3yW9gzNPL7ikB6tw=="}],"memo":""},"metadata":{"timestamp":"1790961201"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"multisig","path":"gno.land/r/moul/x/daily/multisig/v0","files":[{"name":"README.md","body":"# M-of-N Multisig\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn approval multisig realm, ported from the classic Solidity idea. A fixed set\nof owners is configured once with a required approval threshold. Any owner can\ncreate a proposal, owners approve it, and when the number of distinct approvals\nreaches the threshold the proposal is automatically marked `Executed`. This\nrealm tracks approvals only — it does not custody or move funds.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/multisig`\n\n## Example calls\n\n```sh\n# Initialize once: 3 owners, need 2 approvals to execute.\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/multisig\" \\\n  -func Setup -args \"g1addr1,g1addr2,g1addr3\" -args 2 ...\n\n# An owner creates a proposal (returns its id, e.g. 0).\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/multisig\" \\\n  -func Propose -args \"send funds to treasury\" ...\n\n# Owners approve; the 2nd distinct approval flips it to Executed.\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/multisig\" \\\n  -func Approve -args 0 ...\n```\n\nRender the realm (owners, threshold, proposals with approval counts + state) by\nbrowsing to its path on gno.land.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/multisig/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisig/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/multisig/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisig/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/multisig/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisig/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/multisig/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/multisig/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/multisig/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/multisig/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/multisig/v0\"\ngno = \"0.9\"\n"},{"name":"multisig.gno","body":"// Package multisig implements an M-of-N approval multisig realm.\n//\n// It is a port of the classic Solidity multisig idea: a fixed set of owners\n// is configured once, any owner may create a proposal, owners approve it, and\n// once the number of distinct approvals reaches the threshold the proposal is\n// marked \"Executed\". This realm tracks approvals only — it does not move funds.\npackage multisig\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// State of a single proposal.\ntype stateKind int\n\nconst (\n\tstatePending stateKind = iota\n\tstateExecuted\n)\n\nfunc (s stateKind) String() string {\n\tif s == stateExecuted {\n\t\treturn \"Executed\"\n\t}\n\treturn \"Pending\"\n}\n\n// proposal is a single approval request.\ntype proposal struct {\n\tid          int\n\tdescription string\n\tproposer    address\n\tapprovals   *avl.Tree // owner address string -\u003e struct{}{}, distinct approvers\n\tstate       stateKind\n}\n\n// Package-level persistent state.\nvar (\n\towners      *avl.Tree // owner address string -\u003e struct{}{}\n\townerCount  int\n\tthreshold   int\n\tinitialized bool\n\n\tproposals   *avl.Tree // decimal id string -\u003e *proposal\n\tnextID      int\n)\n\nvar (\n\terrAlreadyInit = errors.New(\"multisig: already initialized\")\n\terrNotInit     = errors.New(\"multisig: not initialized\")\n\terrBadThreshold = errors.New(\"multisig: threshold must be between 1 and number of owners\")\n\terrNoOwners    = errors.New(\"multisig: at least one owner required\")\n\terrNotOwner    = errors.New(\"multisig: caller is not an owner\")\n\terrNoProposal  = errors.New(\"multisig: proposal not found\")\n\terrDupApproval = errors.New(\"multisig: caller already approved this proposal\")\n\terrExecuted    = errors.New(\"multisig: proposal already executed\")\n)\n\nfunc init() {\n\towners = avl.NewTree()\n\tproposals = avl.NewTree()\n}\n\n// caller returns the address of the realm/user that called into this realm.\nfunc caller() address {\n\treturn unsafe.PreviousRealm().Address()\n}\n\nfunc isOwner(a address) bool {\n\treturn owners.Has(a.String())\n}\n\n// Setup configures the multisig exactly once. owners is a comma-separated list\n// of bech32 addresses; threshold is the number of approvals required to execute\n// a proposal. It panics (cross-realm abort) on invalid input or if already set.\nfunc Setup(cur realm, ownersCSV string, thresholdN int) {\n\tif initialized {\n\t\tpanic(errAlreadyInit)\n\t}\n\n\tparts := strings.Split(ownersCSV, \",\")\n\tcount := 0\n\tfor _, p := range parts {\n\t\ta := strings.TrimSpace(p)\n\t\tif a == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\taddr := address(a)\n\t\tif owners.Has(addr.String()) {\n\t\t\tcontinue // dedupe\n\t\t}\n\t\towners.Set(addr.String(), struct{}{})\n\t\tcount++\n\t}\n\tif count == 0 {\n\t\tpanic(errNoOwners)\n\t}\n\tif thresholdN \u003c 1 || thresholdN \u003e count {\n\t\tpanic(errBadThreshold)\n\t}\n\n\townerCount = count\n\tthreshold = thresholdN\n\tinitialized = true\n\n\tchain.Emit(\"Setup\", \"owners\", strconv.Itoa(count), \"threshold\", strconv.Itoa(thresholdN))\n}\n\n// Propose creates a new proposal authored by an owner and returns its id.\nfunc Propose(cur realm, description string) int {\n\tif !initialized {\n\t\tpanic(errNotInit)\n\t}\n\tc := caller()\n\tif !isOwner(c) {\n\t\tpanic(errNotOwner)\n\t}\n\n\tid := nextID\n\tnextID++\n\n\tp := \u0026proposal{\n\t\tid:          id,\n\t\tdescription: description,\n\t\tproposer:    c,\n\t\tapprovals:   avl.NewTree(),\n\t\tstate:       statePending,\n\t}\n\tproposals.Set(strconv.Itoa(id), p)\n\n\tchain.Emit(\"Propose\", \"id\", strconv.Itoa(id), \"proposer\", c.String())\n\treturn id\n}\n\n// Approve records an owner's approval for a proposal. When the count of distinct\n// approvals reaches the threshold, the proposal becomes Executed.\nfunc Approve(cur realm, id int) {\n\tif !initialized {\n\t\tpanic(errNotInit)\n\t}\n\tc := caller()\n\tif !isOwner(c) {\n\t\tpanic(errNotOwner)\n\t}\n\n\tv := proposals.Get(strconv.Itoa(id))\n\tif v == nil {\n\t\tpanic(errNoProposal)\n\t}\n\tp := v.(*proposal)\n\tif p.state == stateExecuted {\n\t\tpanic(errExecuted)\n\t}\n\tif p.approvals.Has(c.String()) {\n\t\tpanic(errDupApproval)\n\t}\n\n\tp.approvals.Set(c.String(), struct{}{})\n\tchain.Emit(\"Approve\", \"id\", strconv.Itoa(id), \"owner\", c.String(), \"approvals\", strconv.Itoa(p.approvals.Size()))\n\n\tif p.approvals.Size() \u003e= threshold {\n\t\tp.state = stateExecuted\n\t\tchain.Emit(\"Executed\", \"id\", strconv.Itoa(id))\n\t}\n}\n\n// Render returns a Markdown view of the multisig configuration and proposals.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# M-of-N Multisig\\n\\n\")\n\n\tif !initialized {\n\t\tb.WriteString(\"_Not initialized. Call `Setup(owners, threshold)` once._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"**Threshold:** \")\n\tb.WriteString(strconv.Itoa(threshold))\n\tb.WriteString(\" of \")\n\tb.WriteString(strconv.Itoa(ownerCount))\n\tb.WriteString(\"\\n\\n## Owners\\n\\n\")\n\towners.Iterate(\"\", \"\", func(key string, _ interface{}) bool {\n\t\tb.WriteString(\"- `\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"`\\n\")\n\t\treturn false\n\t})\n\n\tb.WriteString(\"\\n## Proposals\\n\\n\")\n\tif proposals.Size() == 0 {\n\t\tb.WriteString(\"_No proposals yet._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| ID | Description | Proposer | Approvals | State |\\n\")\n\tb.WriteString(\"|----|-------------|----------|-----------|-------|\\n\")\n\tproposals.Iterate(\"\", \"\", func(_ string, v interface{}) bool {\n\t\tp := v.(*proposal)\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(strconv.Itoa(p.id))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(p.description)\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(p.proposer.String())\n\t\tb.WriteString(\"` | \")\n\t\tb.WriteString(strconv.Itoa(p.approvals.Size()))\n\t\tb.WriteString(\"/\")\n\t\tb.WriteString(strconv.Itoa(threshold))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(p.state.String())\n\t\tb.WriteString(\" |\\n\")\n\t\treturn false\n\t})\n\n\treturn b.String()\n}\n"},{"name":"multisig_test.gno","body":"package multisig\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// reset clears package state between tests so each test is independent.\nfunc reset() {\n\towners = nil\n\tproposals = nil\n\townerCount = 0\n\tthreshold = 0\n\tinitialized = false\n\tnextID = 0\n\towners = avl.NewTree()\n\tproposals = avl.NewTree()\n}\n\nfunc TestSetupAndPropose(cur realm, t *testing.T) {\n\treset()\n\n\ta := testutils.TestAddress(\"alice\")\n\tb := testutils.TestAddress(\"bob\")\n\tc := testutils.TestAddress(\"carol\")\n\tcsv := a.String() + \",\" + b.String() + \",\" + c.String()\n\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tSetup(cross(cur), csv, 2)\n\n\tuassert.True(t, initialized, \"should be initialized\")\n\tuassert.Equal(t, 3, ownerCount)\n\tuassert.Equal(t, 2, threshold)\n\n\t// alice (an owner) proposes\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tid := Propose(cross(cur), \"send funds to treasury\")\n\tuassert.Equal(t, 0, id)\n\n\t// a non-owner cannot propose\n\tdave := testutils.TestAddress(\"dave\")\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tuassert.AbortsWithMessage(t, cur, errNotOwner.Error(), func() {\n\t\tPropose(cross(cur), \"sneaky proposal\")\n\t})\n}\n\nfunc TestApproveReachesThreshold(cur realm, t *testing.T) {\n\treset()\n\n\ta := testutils.TestAddress(\"alice\")\n\tb := testutils.TestAddress(\"bob\")\n\tc := testutils.TestAddress(\"carol\")\n\tcsv := a.String() + \",\" + b.String() + \",\" + c.String()\n\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tSetup(cross(cur), csv, 2)\n\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tid := Propose(cross(cur), \"upgrade contract\")\n\n\t// first approval: still pending\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tApprove(cross(cur), id)\n\tv := proposals.Get(\"0\")\n\tp := v.(*proposal)\n\tuassert.Equal(t, statePending.String(), p.state.String())\n\tuassert.Equal(t, 1, p.approvals.Size())\n\n\t// duplicate approval by same owner aborts\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tuassert.AbortsWithMessage(t, cur, errDupApproval.Error(), func() {\n\t\tApprove(cross(cur), id)\n\t})\n\n\t// second distinct approval hits threshold -\u003e executed\n\ttesting.SetRealm(testing.NewUserRealm(b))\n\tApprove(cross(cur), id)\n\tuassert.Equal(t, stateExecuted.String(), p.state.String())\n\tuassert.Equal(t, 2, p.approvals.Size())\n\n\t// approving an executed proposal aborts\n\ttesting.SetRealm(testing.NewUserRealm(c))\n\tuassert.AbortsWithMessage(t, cur, errExecuted.Error(), func() {\n\t\tApprove(cross(cur), id)\n\t})\n}\n\nfunc TestRenderShows(cur realm, t *testing.T) {\n\treset()\n\n\ta := testutils.TestAddress(\"alice\")\n\tb := testutils.TestAddress(\"bob\")\n\tcsv := a.String() + \",\" + b.String()\n\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tSetup(cross(cur), csv, 2)\n\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tPropose(cross(cur), \"hello world\")\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Threshold:\"), \"render shows threshold\")\n\tuassert.True(t, strings.Contains(out, \"2 of 2\"), \"render shows M-of-N\")\n\tuassert.True(t, strings.Contains(out, \"hello world\"), \"render shows proposal description\")\n\tuassert.True(t, strings.Contains(out, \"Pending\"), \"render shows state\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"42537000","gas_fee":"127611ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"kAyojd1cxb1cI9gsx6wLj2B4jWzxqVW/537w+rWjHFJySJe+EvImCH8LE0PeWrtnuts8zY/VfbBaVc3TVyypCg=="}],"memo":""},"metadata":{"timestamp":"1790961202"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"numguess","path":"gno.land/r/moul/x/daily/numguess/v0","files":[{"name":"README.md","body":"# Number Guessing Game\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA gno.land realm (sapphire / gno 0.9) that hides a number between 1 and 100 and\nlets anyone guess it. The target is derived **deterministically** from the block\nheight at which the round started (the GnoVM has no runtime RNG), so play is\nreproducible and verifiable. Each guess returns `higher`, `lower`, or `correct`,\nper-caller attempt counts are tracked, and solved rounds are recorded on a\nleaderboard ranked by fewest guesses.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/numguess`\n\n## Playing\n\n- `Guess(n int)` — submit a guess in `1..100`. Returns `\"higher\"`, `\"lower\"`, or\n  `\"correct\"`; increments your attempt count for the current round. Panics if the\n  round is already solved.\n- `NewRound()` — once the current round is solved, starts a fresh round with a new\n  target derived from the current block height. Panics if the round is still open.\n- `Render(path)` — the gnoweb view: current round number, attempts so far, the last\n  hint, round status, and the winners' leaderboard.\n\nBoth `Guess` and `NewRound` are gno 0.9 crossing functions (`cur realm` first\nparameter), so callers invoke them with the crossing convention.\n\n## Example calls\n\n```sh\n# Guess 42 (via gnokey; addr/keyname/chain flags omitted for brevity)\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/numguess\" \\\n  -func Guess -args 42 ...\n\n# Start a new round after the current one is solved\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/numguess\" \\\n  -func NewRound ...\n```\n\nIn a test or `MsgRun` ephemeral realm:\n\n```go\nimport \"gno.land/r/REPLACE_ADDR/numguess\"\n\nhint := numguess.Guess(cross(cur), 42) // \"higher\" | \"lower\" | \"correct\"\nnumguess.NewRound(cross(cur))          // after a solve\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/numguess/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/numguess/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/numguess/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/numguess/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/numguess/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/numguess/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/numguess/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/numguess/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/numguess/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/numguess/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/numguess/v0\"\ngno = \"0.9\"\n"},{"name":"numguess.gno","body":"// Package numguess is a Number Guessing Game realm.\n//\n// A hidden target in 1..100 is derived deterministically from the block height\n// at which the round started. Players call Guess(n) to receive \"higher\",\n// \"lower\" or \"correct\". When a round is solved the winner is recorded on the\n// leaderboard (ranked by fewest guesses) and anyone can start a fresh round.\npackage numguess\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// round holds the mutable state of the active game round.\ntype round struct {\n\tnumber      int    // 1-based round counter\n\tstartHeight int64  // block height the round began at (entropy source)\n\ttarget      int    // hidden value in 1..100\n\tsolved      bool   // set once someone guesses correctly\n\tlastHint    string // \"higher\" / \"lower\" / \"correct\" / \"\" for none yet\n\twinner      string // address of the solver, once solved\n\twinnerTries int    // attempts the winner needed\n}\n\n// winRecord is one leaderboard entry.\ntype winRecord struct {\n\taddr   string\n\tround  int\n\ttries  int\n\ttarget int\n}\n\nvar (\n\tcurrent *round\n\t// attempts counts guesses per address for the CURRENT round only.\n\tattempts = avl.NewTree() // addr(string) -\u003e *int\n\t// leaderboard is append-only across all rounds; sorted on render.\n\tleaderboard []winRecord\n)\n\nfunc init() {\n\tcurrent = newRound(1, runtime.ChainHeight())\n}\n\n// newRound builds a fresh round whose target derives deterministically from\n// the start height. Gno has no runtime RNG, so height is the only entropy.\nfunc newRound(number int, height int64) *round {\n\treturn \u0026round{\n\t\tnumber:      number,\n\t\tstartHeight: height,\n\t\ttarget:      targetFromHeight(height),\n\t\tsolved:      false,\n\t\tlastHint:    \"\",\n\t}\n}\n\n// targetFromHeight maps a block height to a hidden number in 1..100.\n// Deterministic and cheap: a small integer mix so consecutive rounds don't\n// land on obviously adjacent targets.\nfunc targetFromHeight(h int64) int {\n\tif h \u003c 0 {\n\t\th = -h\n\t}\n\tmixed := (h*2654435761 + 12345)\n\tif mixed \u003c 0 {\n\t\tmixed = -mixed\n\t}\n\treturn int(mixed%100) + 1\n}\n\n// Guess submits a guess for the current round. It records the caller's attempt\n// count and returns \"higher\", \"lower\" or \"correct\". Crossing function: caller\n// invokes as Guess(cross(cur), n).\nfunc Guess(cur realm, n int) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tif n \u003c 1 || n \u003e 100 {\n\t\tpanic(\"guess must be in 1..100\")\n\t}\n\tif current.solved {\n\t\tpanic(\"round already solved; call NewRound to start a fresh one\")\n\t}\n\n\tcaller := cur.Previous().Address().String()\n\tincAttempt(caller)\n\n\tvar hint string\n\tswitch {\n\tcase n \u003c current.target:\n\t\thint = \"higher\"\n\tcase n \u003e current.target:\n\t\thint = \"lower\"\n\tdefault:\n\t\thint = \"correct\"\n\t\tcurrent.solved = true\n\t\tcurrent.winner = caller\n\t\tcurrent.winnerTries = attemptsOf(caller)\n\t\tleaderboard = append(leaderboard, winRecord{\n\t\t\taddr:   caller,\n\t\t\tround:  current.number,\n\t\t\ttries:  current.winnerTries,\n\t\t\ttarget: current.target,\n\t\t})\n\t\tchain.Emit(\"RoundSolved\",\n\t\t\t\"round\", strconv.Itoa(current.number),\n\t\t\t\"winner\", caller,\n\t\t\t\"tries\", strconv.Itoa(current.winnerTries),\n\t\t)\n\t}\n\n\tcurrent.lastHint = hint\n\treturn hint\n}\n\n// NewRound resets the game with a fresh target when the current round is\n// solved. Panics if the current round is still open. Crossing function.\nfunc NewRound(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tif !current.solved {\n\t\tpanic(\"current round is not solved yet\")\n\t}\n\n\tnext := current.number + 1\n\tcurrent = newRound(next, runtime.ChainHeight())\n\tattempts = avl.NewTree() // per-round attempt counters reset\n\tchain.Emit(\"NewRound\", \"round\", strconv.Itoa(next))\n\treturn \"round \" + strconv.Itoa(next) + \" started\"\n}\n\n// incAttempt bumps the caller's attempt counter for the current round.\nfunc incAttempt(addr string) {\n\tif v := attempts.Get(addr); v != nil {\n\t\tp := v.(*int)\n\t\t*p++\n\t\treturn\n\t}\n\tone := 1\n\tattempts.Set(addr, \u0026one)\n}\n\n// attemptsOf returns how many guesses addr has made this round.\nfunc attemptsOf(addr string) int {\n\tif v := attempts.Get(addr); v != nil {\n\t\treturn *(v.(*int))\n\t}\n\treturn 0\n}\n\n// totalAttempts sums all attempts made in the current round.\nfunc totalAttempts() int {\n\ttotal := 0\n\tattempts.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\ttotal += *(v.(*int))\n\t\treturn false\n\t})\n\treturn total\n}\n\n// Render produces the gnoweb Markdown view of the current game state.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Number Guessing Game\\n\\n\")\n\tb.WriteString(\"Guess the hidden number between **1** and **100**. \")\n\tb.WriteString(\"Each round's target is derived deterministically from the block height at which it started.\\n\\n\")\n\n\tb.WriteString(\"## Current round\\n\\n\")\n\tb.WriteString(\"- Round: **\" + strconv.Itoa(current.number) + \"**\\n\")\n\tb.WriteString(\"- Started at block height: \" + strconv.FormatInt(current.startHeight, 10) + \"\\n\")\n\tb.WriteString(\"- Attempts so far (this round): \" + strconv.Itoa(totalAttempts()) + \"\\n\")\n\n\thint := current.lastHint\n\tif hint == \"\" {\n\t\thint = \"_no guesses yet_\"\n\t} else {\n\t\thint = \"`\" + hint + \"`\"\n\t}\n\tb.WriteString(\"- Last hint: \" + hint + \"\\n\")\n\n\tif current.solved {\n\t\tb.WriteString(\"- Status: **solved** by `\" + current.winner + \"` in \" +\n\t\t\tstrconv.Itoa(current.winnerTries) + \" guess(es). \")\n\t\tb.WriteString(\"Call `NewRound()` to play again.\\n\")\n\t} else {\n\t\tb.WriteString(\"- Status: **open** — call `Guess(n)` to play.\\n\")\n\t}\n\tb.WriteString(\"\\n\")\n\n\tb.WriteString(\"## Leaderboard\\n\\n\")\n\tb.WriteString(renderLeaderboard())\n\n\tb.WriteString(\"\\n## How to play\\n\\n\")\n\tb.WriteString(\"```\\n\")\n\tb.WriteString(\"Guess(n)     // n in 1..100 -\u003e \\\"higher\\\" | \\\"lower\\\" | \\\"correct\\\"\\n\")\n\tb.WriteString(\"NewRound()   // start a fresh round once the current one is solved\\n\")\n\tb.WriteString(\"```\\n\")\n\n\treturn b.String()\n}\n\n// renderLeaderboard formats winners ranked by fewest guesses (ties: earlier\n// round first). Sorted on a copy so state is untouched.\nfunc renderLeaderboard() string {\n\tif len(leaderboard) == 0 {\n\t\treturn \"_No winners yet — be the first!_\\n\"\n\t}\n\n\tranked := make([]winRecord, len(leaderboard))\n\tcopy(ranked, leaderboard)\n\tsortByFewestTries(ranked)\n\n\tvar b strings.Builder\n\tb.WriteString(\"| Rank | Player | Round | Guesses | Target |\\n\")\n\tb.WriteString(\"|---|---|---|---|---|\\n\")\n\tfor i, w := range ranked {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | `\" + w.addr + \"` | \" +\n\t\t\tstrconv.Itoa(w.round) + \" | \" + strconv.Itoa(w.tries) + \" | \" +\n\t\t\tstrconv.Itoa(w.target) + \" |\\n\")\n\t}\n\treturn b.String()\n}\n\n// sortByFewestTries does an in-place insertion sort: fewer tries first, then\n// earlier round first on ties. Small n; insertion sort keeps it deterministic\n// and dependency-free.\nfunc sortByFewestTries(rs []winRecord) {\n\tfor i := 1; i \u003c len(rs); i++ {\n\t\tj := i\n\t\tfor j \u003e 0 \u0026\u0026 less(rs[j], rs[j-1]) {\n\t\t\trs[j], rs[j-1] = rs[j-1], rs[j]\n\t\t\tj--\n\t\t}\n\t}\n}\n\nfunc less(a, b winRecord) bool {\n\tif a.tries != b.tries {\n\t\treturn a.tries \u003c b.tries\n\t}\n\treturn a.round \u003c b.round\n}\n"},{"name":"numguess_test.gno","body":"package numguess\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// resetGame re-initializes package globals so each test starts clean; init()\n// runs only once for the whole test binary, and t.Run subtests don't reset it.\nfunc resetGame(height int64) {\n\tcurrent = newRound(1, height)\n\tattempts = avl.NewTree()\n\tleaderboard = nil\n}\n\nfunc TestTargetFromHeight(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\theight int64\n\t}{\n\t\t{\"zero\", 0},\n\t\t{\"one\", 1},\n\t\t{\"large\", 123456},\n\t\t{\"negative\", -42},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := targetFromHeight(tt.height)\n\t\tif got \u003c 1 || got \u003e 100 {\n\t\t\tt.Errorf(\"%s: targetFromHeight(%d)=%d, want in 1..100\", tt.name, tt.height, got)\n\t\t}\n\t\t// determinism: same input -\u003e same output\n\t\tif again := targetFromHeight(tt.height); again != got {\n\t\t\tt.Errorf(\"%s: non-deterministic: %d != %d\", tt.name, again, got)\n\t\t}\n\t}\n}\n\n// TestGuessHigherLowerCorrect exercises the crossing Guess function, so it\n// takes cur realm and calls through cross(cur).\nfunc TestGuessHigherLowerCorrect(cur realm, t *testing.T) {\n\tresetGame(50)\n\ttarget := current.target\n\n\tlow := target - 1\n\tif low \u003c 1 {\n\t\tlow = 1\n\t}\n\thigh := target + 1\n\tif high \u003e 100 {\n\t\thigh = 100\n\t}\n\n\tif low != target {\n\t\tif got := Guess(cross(cur), low); got != \"higher\" {\n\t\t\tt.Errorf(\"Guess(%d) with target %d = %q, want higher\", low, target, got)\n\t\t}\n\t}\n\tif high != target {\n\t\tif got := Guess(cross(cur), high); got != \"lower\" {\n\t\t\tt.Errorf(\"Guess(%d) with target %d = %q, want lower\", high, target, got)\n\t\t}\n\t}\n\n\tgot := Guess(cross(cur), target)\n\tif got != \"correct\" {\n\t\tt.Fatalf(\"Guess(%d) = %q, want correct\", target, got)\n\t}\n\tif !current.solved {\n\t\tt.Error(\"round should be solved after correct guess\")\n\t}\n\tif len(leaderboard) != 1 {\n\t\tt.Errorf(\"leaderboard len = %d, want 1\", len(leaderboard))\n\t}\n}\n\n// TestNewRoundResets solves a round then verifies NewRound advances the round\n// number and clears attempts.\nfunc TestNewRoundResets(cur realm, t *testing.T) {\n\tresetGame(7)\n\ttarget := current.target\n\n\tGuess(cross(cur), target) // solve it\n\tif !current.solved {\n\t\tt.Fatal(\"expected solved round\")\n\t}\n\tprevRound := current.number\n\n\ttesting.SkipHeights(11) // change height so the next target can differ\n\tmsg := NewRound(cross(cur))\n\tif current.number != prevRound+1 {\n\t\tt.Errorf(\"round number = %d, want %d\", current.number, prevRound+1)\n\t}\n\tif current.solved {\n\t\tt.Error(\"fresh round should not be solved\")\n\t}\n\tif totalAttempts() != 0 {\n\t\tt.Errorf(\"attempts should reset, got %d\", totalAttempts())\n\t}\n\tif !strings.Contains(msg, \"started\") {\n\t\tt.Errorf(\"NewRound message = %q, want it to mention 'started'\", msg)\n\t}\n}\n\n// TestRenderContainsState is a plain read — no cur.\nfunc TestRenderContainsState(t *testing.T) {\n\tresetGame(3)\n\tout := Render(\"\")\n\tfor _, want := range []string{\"Number Guessing Game\", \"Current round\", \"Leaderboard\"} {\n\t\tif !strings.Contains(out, want) {\n\t\t\tt.Errorf(\"Render() missing %q\", want)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"47250800","gas_fee":"141752ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"duf4L5b31W7zZyv5JV464iFxK6Ovc7ReN/gUIEiKVesl4ok2nEC2AabRsXsnB3fCuuGxZz75+rFlVkPgyZ2inw=="}],"memo":""},"metadata":{"timestamp":"1790961202"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"orderedmapdemo","path":"gno.land/r/moul/x/daily/orderedmapdemo/v0","files":[{"name":"README.md","body":"# Ordered Map\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nInserts four keys out of alphabetical order, then shows that the order survives\nan update and changes correctly after a delete-and-re-add.\n\nDemo of the [`p/moul/x/daily/orderedmap`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/orderedmap)\nlibrary — no map logic lives here. Stateless, so `Render` is deterministic,\nwhich is exactly the property the library exists to provide.\n\nThe three tables are the whole argument: keys stay in insertion order, an update\ndoes **not** move a key, and a re-insertion after a delete goes last.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/orderedmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/orderedmapdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/orderedmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/orderedmapdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/orderedmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/orderedmapdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/orderedmapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/orderedmapdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/orderedmapdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/orderedmapdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/orderedmapdemo/v0\"\ngno = \"0.9\"\n"},{"name":"orderedmapdemo.gno","body":"// Package orderedmapdemo is a small gnoweb demo of the insertion-ordered map\n// provided by the [p/moul/x/daily/orderedmap](/p/moul/x/daily/orderedmap/v0)\n// library: it shows that order survives updates and deletes.\n//\n// It contains no map logic of its own. Stateless, so Render is deterministic —\n// which is precisely what the library is for.\npackage orderedmapdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/orderedmap/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Ordered Map\\n\\n\")\n\tb.WriteString(\"A map that remembers insertion order, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/orderedmap`](/p/moul/x/daily/orderedmap/v0) library.\\n\\n\")\n\n\to := orderedmap.New()\n\tfor _, kv := range [][2]string{{\"delta\", \"4\"}, {\"alpha\", \"1\"}, {\"charlie\", \"3\"}, {\"bravo\", \"2\"}} {\n\t\to.Set(kv[0], kv[1])\n\t}\n\n\tb.WriteString(\"## Inserted\\n\\n\")\n\tb.WriteString(\"`delta, alpha, charlie, bravo` → order kept as inserted, **not** sorted:\\n\\n\")\n\tb.WriteString(table(o))\n\n\to.Set(\"alpha\", \"99\")\n\tb.WriteString(\"\\n## After `Set(\\\"alpha\\\", \\\"99\\\")`\\n\\n\")\n\tb.WriteString(\"Updating keeps the original position — insertion order means *first* insertion:\\n\\n\")\n\tb.WriteString(table(o))\n\n\to.Delete(\"charlie\")\n\to.Set(\"charlie\", \"new\")\n\tb.WriteString(\"\\n## After deleting and re-adding `charlie`\\n\\n\")\n\tb.WriteString(\"Re-inserting is a **new** insertion, so it goes last:\\n\\n\")\n\tb.WriteString(table(o))\n\n\tb.WriteString(\"\\n\u003e gno map iteration order is unspecified. A realm that ranges over a \")\n\tb.WriteString(\"built-in map to build its page can emit a different page every call — \")\n\tb.WriteString(\"a consensus bug, not a cosmetic one. This is the fix.\\n\")\n\treturn b.String()\n}\n\nfunc table(o *orderedmap.OrderedMap) string {\n\tvar b strings.Builder\n\tb.WriteString(\"| # | key | value |\\n|---|---|---|\\n\")\n\ti := 0\n\to.Iterate(func(k, v string) bool {\n\t\ti++\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(strconv.Itoa(i))\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(k)\n\t\tb.WriteString(\"` | `\")\n\t\tb.WriteString(v)\n\t\tb.WriteString(\"` |\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n"},{"name":"render_example_test.gno","body":"package orderedmapdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Ordered Map\n\t//\n\t// A map that remembers insertion order, demoing the [`p/moul/x/daily/orderedmap`](/p/moul/x/daily/orderedmap/v0) library.\n\t//\n\t// ## Inserted\n\t//\n\t// `delta, alpha, charlie, bravo` → order kept as inserted, **not** sorted:\n\t//\n\t// | # | key | value |\n\t// |---|---|---|\n\t// | 1 | `delta` | `4` |\n\t// | 2 | `alpha` | `1` |\n\t// | 3 | `charlie` | `3` |\n\t// | 4 | `bravo` | `2` |\n\t//\n\t// ## After `Set(\"alpha\", \"99\")`\n\t//\n\t// Updating keeps the original position — insertion order means *first* insertion:\n\t//\n\t// | # | key | value |\n\t// |---|---|---|\n\t// | 1 | `delta` | `4` |\n\t// | 2 | `alpha` | `99` |\n\t// | 3 | `charlie` | `3` |\n\t// | 4 | `bravo` | `2` |\n\t//\n\t// ## After deleting and re-adding `charlie`\n\t//\n\t// Re-inserting is a **new** insertion, so it goes last:\n\t//\n\t// | # | key | value |\n\t// |---|---|---|\n\t// | 1 | `delta` | `4` |\n\t// | 2 | `alpha` | `99` |\n\t// | 3 | `bravo` | `2` |\n\t// | 4 | `charlie` | `new` |\n\t//\n\t// \u003e gno map iteration order is unspecified. A realm that ranges over a built-in map to build its page can emit a different page every call — a consensus bug, not a cosmetic one. This is the fix.\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"27215200","gas_fee":"81645ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"5wi7U3ZAGV0mP3im1HKkRQZaFHwq16BwyQNV9jaX1pVzk2WRdUNycQAigoA0q9nG4AVGULHUq86JzY+DgLE77w=="}],"memo":""},"metadata":{"timestamp":"1790961203"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"piglatindemo","path":"gno.land/r/moul/x/daily/piglatindemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/piglatindemo/v0`\n\nInteractive gnoweb **demo of the [`p/moul/x/daily/piglatin`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/piglatin)\nPig Latin library** — it renders the rules, a gallery of worked examples, and a\nlive sentence translator. It has no translation logic of its own.\n\nAppend a sentence to the path to translate it, e.g.\n[`/r/moul/x/daily/piglatindemo/v0:/The quick brown fox`](https://gno.land/r/moul/x/daily/piglatindemo/v0:/The%20quick%20brown%20fox).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/piglatindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/piglatindemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/piglatindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/piglatindemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/piglatindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/piglatindemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/piglatindemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/piglatindemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/piglatindemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/piglatindemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/piglatindemo/v0\"\ngno = \"0.9\"\n"},{"name":"piglatindemo.gno","body":"// Package piglatindemo is a small gnoweb demo of the Pig Latin translator\n// provided by the [p/moul/x/daily/piglatin](/p/moul/x/daily/piglatin/v0)\n// library: it renders the rules, a gallery of worked examples, and an\n// interactive sentence translator.\n//\n// It contains no translation logic of its own — everything comes from\n// `piglatin.Translate` and `piglatin.TranslateToken`.\npackage piglatindemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/piglatin/v0\"\n)\n\n// Render is the gnoweb entrypoint (Markdown). Root explains the rules; any\n// other path is treated as a sentence to translate, e.g. Render(\"/Hello world\").\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tsentence := strings.TrimPrefix(path, \"/\")\n\tsentence = strings.TrimSpace(sentence)\n\n\tif sentence == \"\" {\n\t\tb.WriteString(\"# Pig Latin\\n\\n\")\n\t\tb.WriteString(\"Demo of the [`p/moul/x/daily/piglatin`](/p/moul/x/daily/piglatin/v0) \")\n\t\tb.WriteString(\"library — a tiny port of the classic **Pig Latin** translator \")\n\t\tb.WriteString(\"(the go-to beginner exercise). Pure `strings`/`unicode`, fully deterministic.\\n\\n\")\n\t\tb.WriteString(\"## Rules\\n\\n\")\n\t\tb.WriteString(\"1. Word starts with a **vowel** → append `way`. `apple` → `appleway`\\n\")\n\t\tb.WriteString(\"2. Word starts with **consonant(s)** → move the leading consonant cluster to the end, then add `ay`. `string` → `ingstray`\\n\")\n\t\tb.WriteString(\"3. `y` is a consonant only as the first letter (`yellow` → `ellowyay`); otherwise a vowel (`myth` → `ythmay`).\\n\")\n\t\tb.WriteString(\"4. **Capitalization** is preserved: `Hello` → `Ellohay`, `NASA` → `ASANAY`.\\n\")\n\t\tb.WriteString(\"5. **Punctuation** glued to a word stays put: `Hello,` → `Ellohay,`.\\n\\n\")\n\t\tb.WriteString(\"## Try it\\n\\n\")\n\t\tb.WriteString(\"Append a sentence to the path — spaces are fine:\\n\\n\")\n\t\tfor _, ex := range []string{\"hello world\", \"The quick brown fox\", \"I love Gno!\"} {\n\t\t\tb.WriteString(\"- [`/\")\n\t\t\tb.WriteString(ex)\n\t\t\tb.WriteString(\"`](/r/moul/x/daily/piglatindemo/v0:/\")\n\t\t\tb.WriteString(ex)\n\t\t\tb.WriteString(\") → `\")\n\t\t\tb.WriteString(piglatin.Translate(ex))\n\t\t\tb.WriteString(\"`\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n## Examples\\n\\n\")\n\t\tb.WriteString(\"| Input | Pig Latin |\\n|---|---|\\n\")\n\t\tfor _, w := range []string{\"pig\", \"banana\", \"smile\", \"eat\", \"yellow\", \"myth\", \"Hello,\", \"GNO\"} {\n\t\t\tb.WriteString(\"| `\")\n\t\t\tb.WriteString(w)\n\t\t\tb.WriteString(\"` | `\")\n\t\t\tb.WriteString(piglatin.TranslateToken(w))\n\t\t\tb.WriteString(\"` |\\n\")\n\t\t}\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"# Pig Latin\\n\\n\")\n\tb.WriteString(\"**Original:**\\n\\n\u003e \")\n\tb.WriteString(sentence)\n\tb.WriteString(\"\\n\\n**Pig Latin:**\\n\\n\u003e \")\n\tb.WriteString(piglatin.Translate(sentence))\n\tb.WriteString(\"\\n\\n---\\n\\n[← rules \u0026 examples](/r/moul/x/daily/piglatindemo/v0)\\n\")\n\treturn b.String()\n}\n"},{"name":"render_example_test.gno","body":"package piglatindemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Pig Latin\n\t//\n\t// Demo of the [`p/moul/x/daily/piglatin`](/p/moul/x/daily/piglatin/v0) library — a tiny port of the classic **Pig Latin** translator (the go-to beginner exercise). Pure `strings`/`unicode`, fully deterministic.\n\t//\n\t// ## Rules\n\t//\n\t// 1. Word starts with a **vowel** → append `way`. `apple` → `appleway`\n\t// 2. Word starts with **consonant(s)** → move the leading consonant cluster to the end, then add `ay`. `string` → `ingstray`\n\t// 3. `y` is a consonant only as the first letter (`yellow` → `ellowyay`); otherwise a vowel (`myth` → `ythmay`).\n\t// 4. **Capitalization** is preserved: `Hello` → `Ellohay`, `NASA` → `ASANAY`.\n\t// 5. **Punctuation** glued to a word stays put: `Hello,` → `Ellohay,`.\n\t//\n\t// ## Try it\n\t//\n\t// Append a sentence to the path — spaces are fine:\n\t//\n\t// - [`/hello world`](/r/moul/x/daily/piglatindemo/v0:/hello world) → `ellohay orldway`\n\t// - [`/The quick brown fox`](/r/moul/x/daily/piglatindemo/v0:/The quick brown fox) → `Ethay uickqay ownbray oxfay`\n\t// - [`/I love Gno!`](/r/moul/x/daily/piglatindemo/v0:/I love Gno!) → `Iway ovelay Ognay!`\n\t//\n\t// ## Examples\n\t//\n\t// | Input | Pig Latin |\n\t// |---|---|\n\t// | `pig` | `igpay` |\n\t// | `banana` | `ananabay` |\n\t// | `smile` | `ilesmay` |\n\t// | `eat` | `eatway` |\n\t// | `yellow` | `ellowyay` |\n\t// | `myth` | `ythmay` |\n\t// | `Hello,` | `Ellohay,` |\n\t// | `GNO` | `OGNAY` |\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"28697200","gas_fee":"86091ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"GvkfOATGaVvgHtWMXeKFgQsXAIyEksFitvg2K4Pa9/Uius/h1FndUsNa8AiPcAZ6hffjw2auA3uSNk/N/RgaUA=="}],"memo":""},"metadata":{"timestamp":"1790961203"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pixelcanvas","path":"gno.land/r/moul/x/daily/pixelcanvas/v0","files":[{"name":"README.md","body":"# Pixel Canvas\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA shared 16x16 canvas. Anyone can paint one cell at a time from a fixed 9-colour\npalette, and the board renders in gnoweb as a grid of coloured blocks.\n\nPainting is **last-write-wins** — that's the point of a shared canvas. Both\nstrokes still count toward the painter tallies, so overwriting someone doesn't\nerase their contribution from the leaderboard.\n\n```\nPaint(x, y, colour)   → colours a cell, returns the total stroke count\nAt(x, y)              → the colour name of a cell (\"white\" when untouched)\nPainterAt(x, y)       → who last painted it (\"\" when untouched)\nStrokes()             → total paints ever\nPalette()             → the accepted colour names\n\n/r/moul/x/daily/pixelcanvas/v0        → the canvas, palette and top painters\n/r/moul/x/daily/pixelcanvas/v0:4,9    → who painted that cell, and what colour\n```\n\nCoordinates are 0-based with `(0,0)` at the **top-left**, and are `x` (column)\nthen `y` (row) — so `(3,7)` is column 3 of row 7. Colour names are matched\ncase- and space-insensitively.\n\nPalette: `white`, `red`, `orange`, `yellow`, `green`, `blue`, `purple`,\n`brown`, `black`.\n\nThe grid is a fixed `[Size*Size]int` of palette indices rather than a tree:\nevery cell exists from the start and the whole grid is walked on each render,\nso an array is both simpler and cheaper than a sparse structure.\n\nOnly an EOA can paint (`IsUserCall`), so another realm can't spray the canvas\non a user's behalf.\n\nBuilt for gno 0.9. Live on both testnets (agent address):\n\n- sapphire — https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/pixelcanvas\n- pearl — https://pearl.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/pixelcanvas\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/pixelcanvas/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pixelcanvas/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/pixelcanvas/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pixelcanvas/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/pixelcanvas/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pixelcanvas/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/pixelcanvas/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pixelcanvas/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/pixelcanvas/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/pixelcanvas/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/pixelcanvas/v0\"\ngno = \"0.9\"\n"},{"name":"pixelcanvas.gno","body":"// Package pixelcanvas is a shared 16x16 pixel canvas: anyone can paint one\n// cell at a time from a fixed 9-colour palette, and the canvas renders in\n// gnoweb as a grid of coloured blocks.\n//\n// The canvas is a flat [Size*Size]int of palette indices held in realm state —\n// a fixed-size array rather than a tree, because every cell exists from the\n// start and the grid is walked in full on every render. Painting is\n// last-write-wins; the realm keeps who painted each cell and a per-address\n// tally, so the board doubles as a contribution leaderboard.\n//\n// A stateful app with nothing reusable to extract, so it ships as a lone realm\n// rather than a p/ library + demo pair.\npackage pixelcanvas\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Size is the canvas edge length; the canvas is Size x Size cells.\nconst Size = 16\n\n// palette maps a colour index to the block rendered for it. Index 0 is the\n// blank canvas. Kept parallel to paletteNames.\nvar palette = []string{\"⬜\", \"🟥\", \"🟧\", \"🟨\", \"🟩\", \"🟦\", \"🟪\", \"🟫\", \"⬛\"}\n\n// paletteNames are the names Paint accepts, in palette order.\nvar paletteNames = []string{\"white\", \"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\", \"brown\", \"black\"}\n\n// Package-level persistent state.\nvar (\n\tcells    [Size * Size]int // palette index per cell, row-major\n\tpainters [Size * Size]string\n\ttally    = avl.NewTree() // address string -\u003e *int paint count\n\tstrokes  int             // total paints ever\n\tlastAt   int64           // height of the most recent paint\n)\n\n// Paint colours the cell at (x, y) and returns the total number of strokes.\n//\n// Coordinates are 0-based with (0,0) at the top-left. Colour is a palette name\n// (\"red\", \"blue\", …) — see Palette. Painting over an existing cell is allowed:\n// the canvas is last-write-wins, which is the whole point of a shared board.\nfunc Paint(cur realm, x, y int, colour string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tprev := cur.Previous()\n\tif !prev.IsUserCall() {\n\t\tpanic(\"only an EOA via MsgCall can paint\")\n\t}\n\tif x \u003c 0 || x \u003e= Size || y \u003c 0 || y \u003e= Size {\n\t\tpanic(\"out of bounds: x and y must be in [0,\" + strconv.Itoa(Size-1) + \"]\")\n\t}\n\tidx := colourIndex(colour)\n\tif idx \u003c 0 {\n\t\tpanic(\"unknown colour \" + strconv.Quote(colour) + \"; see Palette()\")\n\t}\n\n\taddr := prev.Address()\n\ti := y*Size + x\n\tcells[i] = idx\n\tpainters[i] = addr.String()\n\tstrokes++\n\tlastAt = runtime.ChainHeight()\n\tbump(addr.String())\n\n\tchain.Emit(\"Paint\",\n\t\t\"addr\", addr.String(),\n\t\t\"x\", strconv.Itoa(x),\n\t\t\"y\", strconv.Itoa(y),\n\t\t\"colour\", paletteNames[idx],\n\t)\n\treturn strokes\n}\n\n// colourIndex resolves a palette name to its index, or -1.\nfunc colourIndex(name string) int {\n\tn := strings.ToLower(strings.TrimSpace(name))\n\tfor i, p := range paletteNames {\n\t\tif p == n {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n// bump increments an address's paint tally.\nfunc bump(addr string) {\n\t// avl/v0's Get returns a single `any`; a miss is a nil interface.\n\tif v := tally.Get(addr); v != nil {\n\t\tc := v.(*int)\n\t\t*c++\n\t\treturn\n\t}\n\tone := 1\n\ttally.Set(addr, \u0026one)\n}\n\n// At returns the palette name of the cell at (x, y), or \"\" when out of bounds.\nfunc At(x, y int) string {\n\tif x \u003c 0 || x \u003e= Size || y \u003c 0 || y \u003e= Size {\n\t\treturn \"\"\n\t}\n\treturn paletteNames[cells[y*Size+x]]\n}\n\n// PainterAt returns the address that last painted (x, y), or \"\" if untouched.\nfunc PainterAt(x, y int) string {\n\tif x \u003c 0 || x \u003e= Size || y \u003c 0 || y \u003e= Size {\n\t\treturn \"\"\n\t}\n\treturn painters[y*Size+x]\n}\n\n// Strokes returns how many paints the canvas has taken.\nfunc Strokes() int { return strokes }\n\n// Palette returns the accepted colour names, comma-separated.\nfunc Palette() string { return strings.Join(paletteNames, \", \") }\n\n// scorer is one row of the contribution leaderboard.\ntype scorer struct {\n\taddr  string\n\tcount int\n}\n\n// byCount ranks painters by strokes descending, ties broken on address so the\n// board is deterministic.\ntype byCount []scorer\n\nfunc (s byCount) Len() int      { return len(s) }\nfunc (s byCount) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s byCount) Less(i, j int) bool {\n\tif s[i].count != s[j].count {\n\t\treturn s[i].count \u003e s[j].count\n\t}\n\treturn s[i].addr \u003c s[j].addr\n}\n\n// Render renders the canvas for gnoweb.\n//\n//\tRender(\"\")        / Render(\"/\") -\u003e the canvas, palette and leaderboard\n//\tRender(\"/\u003cx\u003e,\u003cy\u003e\")              -\u003e who painted that cell, and what colour\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Pixel Canvas\\n\\n\")\n\tb.WriteString(\"A shared \")\n\tb.WriteString(strconv.Itoa(Size))\n\tb.WriteString(\"x\")\n\tb.WriteString(strconv.Itoa(Size))\n\tb.WriteString(\" canvas. Anyone can `Paint(x, y, colour)` — last write wins.\\n\\n\")\n\n\tif q := parseArg(path); q != \"\" {\n\t\treturn b.String() + renderCell(q)\n\t}\n\n\tb.WriteString(grid())\n\tb.WriteString(\"\\n**\")\n\tb.WriteString(strconv.Itoa(strokes))\n\tb.WriteString(\"** stroke\")\n\tif strokes != 1 {\n\t\tb.WriteString(\"s\")\n\t}\n\tb.WriteString(\" · palette: \")\n\tb.WriteString(Palette())\n\tb.WriteString(\"\\n\")\n\n\tif board := leaderboard(); board != \"\" {\n\t\tb.WriteString(\"\\n## Top painters\\n\\n\")\n\t\tb.WriteString(board)\n\t}\n\treturn b.String()\n}\n\n// grid renders the canvas as rows of coloured blocks.\nfunc grid() string {\n\tvar b strings.Builder\n\tfor y := 0; y \u003c Size; y++ {\n\t\tfor x := 0; x \u003c Size; x++ {\n\t\t\tb.WriteString(palette[cells[y*Size+x]])\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\treturn b.String()\n}\n\n// leaderboard renders the top painters, or \"\" when nobody has painted.\nfunc leaderboard() string {\n\tscores := []scorer{}\n\ttally.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tscores = append(scores, scorer{addr: k, count: *(v.(*int))})\n\t\treturn false\n\t})\n\tif len(scores) == 0 {\n\t\treturn \"\"\n\t}\n\tsort.Sort(byCount(scores))\n\tif len(scores) \u003e 5 {\n\t\tscores = scores[:5]\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"| # | address | strokes |\\n|---|---|---|\\n\")\n\tfor i, s := range scores {\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(strconv.Itoa(i + 1))\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(s.addr)\n\t\tb.WriteString(\"` | \")\n\t\tb.WriteString(strconv.Itoa(s.count))\n\t\tb.WriteString(\" |\\n\")\n\t}\n\treturn b.String()\n}\n\n// renderCell renders a single \"x,y\" lookup.\nfunc renderCell(q string) string {\n\tvar b strings.Builder\n\tx, y, ok := parseCoord(q)\n\tif !ok {\n\t\tb.WriteString(\"_Expected `x,y` — e.g. `/3,7`._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"## Cell (\")\n\tb.WriteString(strconv.Itoa(x))\n\tb.WriteString(\", \")\n\tb.WriteString(strconv.Itoa(y))\n\tb.WriteString(\")\\n\\n\")\n\tb.WriteString(palette[cells[y*Size+x]])\n\tb.WriteString(\" **\")\n\tb.WriteString(At(x, y))\n\tb.WriteString(\"**\\n\\n\")\n\tif p := PainterAt(x, y); p != \"\" {\n\t\tb.WriteString(\"Painted by `\")\n\t\tb.WriteString(p)\n\t\tb.WriteString(\"`.\\n\")\n\t} else {\n\t\tb.WriteString(\"_Never painted._\\n\")\n\t}\n\treturn b.String()\n}\n\n// parseArg extracts the first path segment.\nfunc parseArg(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n\n// parseCoord parses \"x,y\" and reports whether it is in bounds.\nfunc parseCoord(s string) (int, int, bool) {\n\ti := strings.IndexByte(s, ',')\n\tif i \u003c 0 {\n\t\treturn 0, 0, false\n\t}\n\tx, err := strconv.Atoi(strings.TrimSpace(s[:i]))\n\tif err != nil {\n\t\treturn 0, 0, false\n\t}\n\ty, err2 := strconv.Atoi(strings.TrimSpace(s[i+1:]))\n\tif err2 != nil {\n\t\treturn 0, 0, false\n\t}\n\tif x \u003c 0 || x \u003e= Size || y \u003c 0 || y \u003e= Size {\n\t\treturn 0, 0, false\n\t}\n\treturn x, y, true\n}\n"},{"name":"pixelcanvas_test.gno","body":"package pixelcanvas\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// reset clears realm state between tests.\nfunc reset() {\n\tfor i := range cells {\n\t\tcells[i] = 0\n\t\tpainters[i] = \"\"\n\t}\n\ttally = avl.NewTree()\n\tstrokes = 0\n\tlastAt = 0\n}\n\n// paint runs a Paint as addr.\nfunc paint(cur realm, addr address, x, y int, colour string) int {\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\treturn Paint(cross(cur), x, y, colour)\n}\n\nfunc TestPaintSetsCellAndPainter(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\n\tuassert.Equal(t, 1, paint(cur, alice, 3, 7, \"red\"))\n\tuassert.Equal(t, \"red\", At(3, 7))\n\tuassert.Equal(t, alice.String(), PainterAt(3, 7))\n\tuassert.Equal(t, 1, Strokes())\n}\n\n// (x, y) is column, row — a paint at (3,7) must not land at (7,3).\nfunc TestCoordinatesAreXThenY(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tpaint(cur, alice, 3, 7, \"blue\")\n\n\tuassert.Equal(t, \"blue\", At(3, 7))\n\tuassert.Equal(t, \"white\", At(7, 3))\n}\n\nfunc TestLastWriteWins(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\tpaint(cur, alice, 0, 0, \"red\")\n\tpaint(cur, bob, 0, 0, \"green\")\n\n\tuassert.Equal(t, \"green\", At(0, 0))\n\tuassert.Equal(t, bob.String(), PainterAt(0, 0))\n\tuassert.Equal(t, 2, Strokes()) // both strokes still counted\n}\n\nfunc TestOutOfBoundsPanics(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tcases := [][2]int{{-1, 0}, {0, -1}, {Size, 0}, {0, Size}}\n\tfor _, c := range cases {\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\trec := revive(func() { Paint(cross(cur), c[0], c[1], \"red\") })\n\t\tuassert.True(t, rec != nil)\n\t}\n\tuassert.Equal(t, 0, Strokes())\n}\n\nfunc TestUnknownColourPanics(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\trec := revive(func() { Paint(cross(cur), 1, 1, \"chartreuse\") })\n\tuassert.True(t, rec != nil)\n\tuassert.Equal(t, 0, Strokes())\n}\n\n// Colour names are case- and space-insensitive.\nfunc TestColourNameIsNormalised(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tpaint(cur, alice, 2, 2, \"  GREEN \")\n\tuassert.Equal(t, \"green\", At(2, 2))\n}\n\nfunc TestAtOutOfBoundsIsEmpty(t *testing.T) {\n\treset()\n\tuassert.Equal(t, \"\", At(-1, 0))\n\tuassert.Equal(t, \"\", At(Size, 0))\n\tuassert.Equal(t, \"\", PainterAt(0, Size))\n}\n\nfunc TestUnpaintedCellIsWhiteWithNoPainter(t *testing.T) {\n\treset()\n\tuassert.Equal(t, \"white\", At(5, 5))\n\tuassert.Equal(t, \"\", PainterAt(5, 5))\n}\n\nfunc TestTallyRanksPainters(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\t// alice paints 3, bob 1\n\tpaint(cur, alice, 0, 0, \"red\")\n\tpaint(cur, alice, 1, 0, \"red\")\n\tpaint(cur, alice, 2, 0, \"red\")\n\tpaint(cur, bob, 3, 0, \"blue\")\n\n\tout := Render(\"\")\n\tai := strings.Index(out, alice.String())\n\tbi := strings.Index(out, bob.String())\n\tuassert.True(t, ai \u003e= 0)\n\tuassert.True(t, bi \u003e= 0)\n\tuassert.True(t, ai \u003c bi) // alice ranks first\n}\n\nfunc TestRenderEmptyCanvas(t *testing.T) {\n\treset()\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"**0** strokes\"))\n\t// a blank canvas is Size rows of Size white blocks\n\tuassert.Equal(t, Size*Size, strings.Count(out, \"⬜\"))\n\tuassert.False(t, strings.Contains(out, \"Top painters\"))\n}\n\nfunc TestRenderCellLookup(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tpaint(cur, alice, 4, 9, \"purple\")\n\n\tout := Render(\"/4,9\")\n\tuassert.True(t, strings.Contains(out, \"Cell (4, 9)\"))\n\tuassert.True(t, strings.Contains(out, \"**purple**\"))\n\tuassert.True(t, strings.Contains(out, alice.String()))\n}\n\nfunc TestRenderCellNeverPainted(t *testing.T) {\n\treset()\n\tout := Render(\"/1,1\")\n\tuassert.True(t, strings.Contains(out, \"Never painted\"))\n}\n\nfunc TestRenderRejectsBadCoord(t *testing.T) {\n\treset()\n\tfor _, q := range []string{\"/nope\", \"/1\", \"/99,99\", \"/a,b\"} {\n\t\tuassert.True(t, strings.Contains(Render(q), \"Expected `x,y`\"))\n\t}\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"51114400","gas_fee":"153343ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"TwiOm5pjhfBxhvKvEH99I3FVnmH+FI069OF/BoTpJ5piYVcub09u+DSZWOPpWUDDPEsF/MpnmdrxFzG1XX8uDw=="}],"memo":""},"metadata":{"timestamp":"1790961204"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"LWY5C+6uUuqrajsXOFnlKY8d7wgRRq00LaG5BT/yynZyMzqNo4CioacC8TaDGXMLYMgMLj/GwyyUlzdBoIVRTg=="}],"memo":""},"metadata":{"timestamp":"1790961205"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"polls","path":"gno.land/r/moul/x/daily/polls/v1","files":[{"name":"README.md","body":"# Polls \u0026 Voting\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn on-chain poll and voting realm for gno.land (gno 0.9). Anyone can\ncreate a poll with a question and a comma-separated set of options; every caller\naddress may cast exactly one vote per poll. The realm's `Render` page lists each\npoll with its options, live tallies drawn as `▓░` bar charts, per-option\npercentages, and the total number of votes.\n\n## Realm path\n\n`gno.land/r/moul/x/daily/polls/v1`\n\n## Exported transactions\n\n- `CreatePoll(question string, options string) int` — create a poll. `options`\n  is a comma-separated list (blank entries are dropped; at least 2 required).\n  Returns the new poll's id.\n- `Vote(pollID int, optionIndex int)` — cast one vote for `optionIndex` on poll\n  `pollID`. One vote per caller address per poll; a second vote aborts.\n\nBoth are gno 0.9 crossing functions (first parameter `cur realm`); the caller\naddress is read via `runtime.PreviousRealm().Address()`.\n\n## Read path\n\n- `Render(\"\")` — index of all polls with bar-chart tallies.\n- `Render(\"\u003cid\u003e\")` — a single poll by id.\n\n## Example calls\n\n```sh\n# create a poll (returns its id, e.g. 0)\ngnokey maketx call -pkgpath \"gno.land/r/moul/x/daily/polls/v1\" \\\n  -func CreatePoll -args \"Best L1 for smart contracts?\" -args \"gno,eth,sol\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 mykey\n\n# vote for option index 0 on poll 0\ngnokey maketx call -pkgpath \"gno.land/r/moul/x/daily/polls/v1\" \\\n  -func Vote -args 0 -args 0 \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 mykey\n\n# view results in gnoweb\n#   https://gno.land/r/moul/x/daily/polls/v1\n#   https://gno.land/r/moul/x/daily/polls/v1:0\n```\n\n## Testing\n\n```sh\ngno test .\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/polls/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/polls/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/polls/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"polls.gno","body":"// Package polls is an on-chain poll / voting realm for gno.land.\n//\n// Anyone can create a poll with a question and a comma-separated list of\n// options. Each caller address may cast exactly one vote per poll. Render\n// draws every poll with its options, tallies as ▓░ bar charts, percentages\n// and the total vote count.\npackage polls\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/polls/v1\"\n\n// Poll is a single question with its options and per-address vote tracking.\ntype Poll struct {\n\tID       int\n\tQuestion string\n\tOptions  []string\n\tTallies  []int\n\tCreator  string    // bech32 address of the poll creator\n\tvoted    *avl.Tree // address string -\u003e struct{}{}, one vote per address\n}\n\nvar (\n\tpolls  []*Poll // index i holds the poll with ID i\n\tnextID int\n)\n\n// CreatePoll registers a new poll. options is a comma-separated list; blank\n// entries are dropped. Returns the new poll's id. Crossing function: an EOA\n// invokes it via MsgCall; another realm via polls.CreatePoll(cross, q, opts).\nfunc CreatePoll(cur realm, question string, options string) int {\n\tcreator := caller(cur).String()\n\n\tq := strings.TrimSpace(question)\n\tif q == \"\" {\n\t\tpanic(\"question must not be empty\")\n\t}\n\n\tif len(q) \u003e MaxQuestionLen {\n\t\tpanic(\"question too long\")\n\t}\n\topts := parseOptions(options)\n\tif len(opts) \u003c 2 {\n\t\tpanic(\"a poll needs at least 2 options\")\n\t}\n\tif len(opts) \u003e MaxOptions {\n\t\tpanic(\"a poll takes at most \" + strconv.Itoa(MaxOptions) + \" options\")\n\t}\n\tfor _, o := range opts {\n\t\tif len(o) \u003e MaxOptionLen {\n\t\t\tpanic(\"option too long\")\n\t\t}\n\t}\n\tif len(polls) \u003e= MaxPolls {\n\t\tpanic(\"polls is full at \" + strconv.Itoa(MaxPolls) + \" polls\")\n\t}\n\n\tid := nextID\n\tnextID++\n\tp := \u0026Poll{\n\t\tID:       id,\n\t\tQuestion: q,\n\t\tOptions:  opts,\n\t\tTallies:  make([]int, len(opts)),\n\t\tCreator:  creator,\n\t\tvoted:    avl.NewTree(),\n\t}\n\tpolls = append(polls, p)\n\n\tchain.Emit(\"PollCreated\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"creator\", creator,\n\t\t\"options\", strconv.Itoa(len(opts)),\n\t)\n\treturn id\n}\n\n// Vote casts one vote for optionIndex on poll pollID. Each caller address may\n// vote at most once per poll. Crossing function.\nfunc Vote(cur realm, pollID int, optionIndex int) {\n\tvoter := caller(cur).String()\n\n\tp := getPoll(pollID)\n\tif optionIndex \u003c 0 || optionIndex \u003e= len(p.Options) {\n\t\tpanic(\"option index out of range\")\n\t}\n\tif p.voted.Has(voter) {\n\t\tpanic(\"address already voted on this poll\")\n\t}\n\n\tp.voted.Set(voter, struct{}{})\n\tp.Tallies[optionIndex]++\n\n\tchain.Emit(\"Voted\",\n\t\t\"id\", strconv.Itoa(pollID),\n\t\t\"voter\", voter,\n\t\t\"option\", strconv.Itoa(optionIndex),\n\t)\n}\n\n// parseOptions splits a comma-separated option string, trimming whitespace and\n// dropping empties. Pure logic — no realm state.\nfunc parseOptions(options string) []string {\n\tvar out []string\n\tfor _, raw := range strings.Split(options, \",\") {\n\t\to := strings.TrimSpace(raw)\n\t\tif o != \"\" {\n\t\t\tout = append(out, o)\n\t\t}\n\t}\n\treturn out\n}\n\n// getPoll returns the poll with the given id or panics if it does not exist.\nfunc getPoll(id int) *Poll {\n\tif id \u003c 0 || id \u003e= len(polls) {\n\t\tpanic(\"poll not found\")\n\t}\n\treturn polls[id]\n}\n\n// PollCount returns the number of polls created so far (read-only helper).\nfunc PollCount() int {\n\treturn len(polls)\n}\n\nconst barWidth = 20\n\n// The bounds on what a creator may store. Anyone may create a poll, and the\n// root page renders the newest ones.\nconst (\n\tMaxPolls       = 500\n\tMaxQuestionLen = 200\n\tMaxOptions     = 10\n\tMaxOptionLen   = 64\n\tIndexRecent    = 20 // polls the root page shows, newest first\n)\n\n// bar renders a proportional ▓░ bar of fixed width for count out of total.\nfunc bar(count, total int) string {\n\tfilled := 0\n\tif total \u003e 0 {\n\t\tfilled = count * barWidth / total\n\t}\n\tif filled \u003e barWidth {\n\t\tfilled = barWidth\n\t}\n\treturn strings.Repeat(\"▓\", filled) + strings.Repeat(\"░\", barWidth-filled)\n}\n\n// percent returns the integer percentage of count out of total.\nfunc percent(count, total int) int {\n\tif total == 0 {\n\t\treturn 0\n\t}\n\treturn count * 100 / total\n}\n\n// total sums a tally slice.\nfunc total(tallies []int) int {\n\tsum := 0\n\tfor _, t := range tallies {\n\t\tsum += t\n\t}\n\treturn sum\n}\n\n// renderPoll writes one poll's Markdown block into b.\nfunc renderPoll(b *strings.Builder, p *Poll) {\n\tsum := total(p.Tallies)\n\n\tb.WriteString(\"## Poll #\")\n\tb.WriteString(strconv.Itoa(p.ID))\n\tb.WriteString(\": \")\n\tb.WriteString(ui.Inline(p.Question))\n\tb.WriteString(\"\\n\\n\")\n\n\tfor i, opt := range p.Options {\n\t\tc := p.Tallies[i]\n\t\tb.WriteString(\"- **\")\n\t\tb.WriteString(ui.Inline(opt))\n\t\tb.WriteString(\"** `\")\n\t\tb.WriteString(bar(c, sum))\n\t\tb.WriteString(\"` \")\n\t\tb.WriteString(strconv.Itoa(percent(c, sum)))\n\t\tb.WriteString(\"% (\")\n\t\tb.WriteString(strconv.Itoa(c))\n\t\tif c == 1 {\n\t\t\tb.WriteString(\" vote)\")\n\t\t} else {\n\t\t\tb.WriteString(\" votes)\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"\\n_Total votes: \")\n\tb.WriteString(strconv.Itoa(sum))\n\tb.WriteString(\"_\\n\\n\")\n}\n\n// Render produces the Markdown page for gnoweb. It is NOT a crossing function.\n//\n//   - \"\"          -\u003e the IndexRecent newest polls\n//   - \"page/\u003cn\u003e\"  -\u003e the n-th page of IndexRecent, newest first (page/1 is \"\")\n//   - \"\u003cid\u003e\"      -\u003e a single poll by id\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tpath = strings.TrimSpace(path)\n\tpage := 1\n\tif rest, ok := strings.CutPrefix(path, \"page/\"); ok {\n\t\tn, err := strconv.Atoi(rest)\n\t\t// Bounded before any multiply: the page comes from the URL.\n\t\tif err != nil || n \u003c 1 || n \u003e 1+(len(polls)-1)/IndexRecent {\n\t\t\treturn \"# Polls\\n\\nNo such page.\\n\\n[← all polls](\" + selfPath + \")\\n\"\n\t\t}\n\t\tpage, path = n, \"\"\n\t}\n\tif path != \"\" {\n\t\tid, err := strconv.Atoi(path)\n\t\tif err != nil || id \u003c 0 || id \u003e= len(polls) {\n\t\t\treturn \"# Polls\\n\\nPoll not found.\\n\"\n\t\t}\n\t\tb.WriteString(\"# Polls\\n\\n\")\n\t\trenderPoll(\u0026b, polls[id])\n\t\tb.WriteString(\"[← all polls](\" + selfPath + \")\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"# Polls \u0026 Voting\\n\\n\")\n\tif len(polls) == 0 {\n\t\tb.WriteString(\"_No polls yet. Create one with `CreatePoll(question, \\\"a,b,c\\\")`._\\n\")\n\t\treturn b.String()\n\t}\n\n\tpages := 1 + (len(polls)-1)/IndexRecent\n\tb.WriteString(\"Total polls: \")\n\tb.WriteString(strconv.Itoa(len(polls)))\n\tif pages \u003e 1 {\n\t\tb.WriteString(\", page \" + strconv.Itoa(page) + \" of \" + strconv.Itoa(pages))\n\t}\n\tb.WriteString(\"\\n\\n\")\n\t//gnovet:ignore page-offset-overflow page is bounded by pages above\n\ttop := len(polls) - 1 - (page-1)*IndexRecent\n\tfor i := top; i \u003e= 0 \u0026\u0026 i \u003e top-IndexRecent; i-- {\n\t\trenderPoll(\u0026b, polls[i])\n\t}\n\tif page \u003c pages {\n\t\tb.WriteString(\"[older polls →](\" + selfPath + \":page/\" + strconv.Itoa(page+1) + \")\\n\")\n\t}\n\treturn b.String()\n}\n\n// caller is the address that crossed into this realm, after checking that the\n// realm token is this frame's own.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"polls: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"polls_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// resetState clears package-level state between tests so cases are independent.\nfunc resetState() {\n\tpolls = nil\n\tnextID = 0\n}\n\nfunc TestParseOptions(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput string\n\t\twant  []string\n\t}{\n\t\t{\"simple\", \"a,b,c\", []string{\"a\", \"b\", \"c\"}},\n\t\t{\"trims spaces\", \" yes , no \", []string{\"yes\", \"no\"}},\n\t\t{\"drops empties\", \"a,,b, ,c\", []string{\"a\", \"b\", \"c\"}},\n\t\t{\"single\", \"only\", []string{\"only\"}},\n\t\t{\"all blank\", \" , ,\", nil},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := parseOptions(tt.input)\n\t\tif len(got) != len(tt.want) {\n\t\t\tt.Errorf(\"%s: len = %d, want %d (%v)\", tt.name, len(got), len(tt.want), got)\n\t\t\tcontinue\n\t\t}\n\t\tfor i := range got {\n\t\t\tif got[i] != tt.want[i] {\n\t\t\t\tt.Errorf(\"%s: [%d] = %q, want %q\", tt.name, i, got[i], tt.want[i])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestCreateAndVote(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"Best chain?\", \"gno,eth,btc\")\n\tif id != 0 {\n\t\tt.Fatalf(\"first poll id = %d, want 0\", id)\n\t}\n\tif PollCount() != 1 {\n\t\tt.Fatalf(\"PollCount = %d, want 1\", PollCount())\n\t}\n\n\t// alice votes gno.\n\tVote(cross(cur), id, 0)\n\n\t// bob votes eth.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVote(cross(cur), id, 1)\n\n\t// carol votes gno.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVote(cross(cur), id, 0)\n\n\tp := getPoll(id)\n\tif p.Tallies[0] != 2 {\n\t\tt.Errorf(\"gno tally = %d, want 2\", p.Tallies[0])\n\t}\n\tif p.Tallies[1] != 1 {\n\t\tt.Errorf(\"eth tally = %d, want 1\", p.Tallies[1])\n\t}\n\tif total(p.Tallies) != 3 {\n\t\tt.Errorf(\"total = %d, want 3\", total(p.Tallies))\n\t}\n}\n\nfunc TestDoubleVotePanics(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"Coffee or tea?\", \"coffee,tea\")\n\tVote(cross(cur), id, 0)\n\n\t// A second vote by the same address aborts (cross-realm panic).\n\tuassert.AbortsWithMessage(t, cur, \"address already voted on this poll\", func() {\n\t\tVote(cross(cur), id, 1)\n\t})\n}\n\nfunc TestVoteBounds(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"A or B?\", \"a,b\")\n\n\tuassert.AbortsWithMessage(t, cur, \"option index out of range\", func() {\n\t\tVote(cross(cur), id, 5)\n\t})\n}\n\nfunc TestCreatePollNeedsTwoOptions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsWithMessage(t, cur, \"a poll needs at least 2 options\", func() {\n\t\tCreatePoll(cross(cur), \"One?\", \"only\")\n\t})\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// Empty index.\n\tif got := Render(\"\"); !strings.Contains(got, \"No polls yet\") {\n\t\tt.Errorf(\"empty Render should mention no polls, got:\\n%s\", got)\n\t}\n\n\tid := CreatePoll(cross(cur), \"Pick one\", \"x,y\")\n\tVote(cross(cur), id, 0)\n\n\t// Index lists the poll and bar chart glyphs.\n\tidx := Render(\"\")\n\tif !strings.Contains(idx, \"Pick one\") {\n\t\tt.Errorf(\"index missing question:\\n%s\", idx)\n\t}\n\tif !strings.Contains(idx, \"▓\") || !strings.Contains(idx, \"░\") {\n\t\tt.Errorf(\"index missing bar glyphs:\\n%s\", idx)\n\t}\n\tif !strings.Contains(idx, \"Total votes: 1\") {\n\t\tt.Errorf(\"index missing total votes:\\n%s\", idx)\n\t}\n\tif !strings.Contains(idx, \"100%\") {\n\t\tt.Errorf(\"index missing 100%% for the sole vote:\\n%s\", idx)\n\t}\n\n\t// Single-poll path.\n\tsingle := Render(\"0\")\n\tif !strings.Contains(single, \"Poll #0\") {\n\t\tt.Errorf(\"single Render missing poll header:\\n%s\", single)\n\t}\n\n\t// Unknown path.\n\tif got := Render(\"99\"); !strings.Contains(got, \"not found\") {\n\t\tt.Errorf(\"unknown poll should say not found, got:\\n%s\", got)\n\t}\n}\n"},{"name":"zz_bounds_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// What a creator may store is bounded, and the root page renders a fixed\n// window of the newest polls whatever the count.\nfunc TestPollsAreBounded(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bounded\")))\n\tuassert.AbortsContains(t, cur, \"question too long\", func() { CreatePoll(cross(cur), strings.Repeat(\"q\", MaxQuestionLen+1), \"a,b\") })\n\tuassert.AbortsContains(t, cur, \"at most\", func() { CreatePoll(cross(cur), \"many\", strings.Repeat(\"o,\", MaxOptions)+\"o\") })\n\tfor len(polls) \u003c IndexRecent+3 {\n\t\tCreatePoll(cross(cur), \"filler\", \"a,b\")\n\t}\n\tuassert.Equal(t, IndexRecent, strings.Count(Render(\"\"), \"## Poll #\"))\n}\n\n// The poll count is bounded globally.\nfunc TestPollCountIsBounded(cur realm, t *testing.T) {\n\tbefore := len(polls)\n\tfor len(polls) \u003c MaxPolls {\n\t\tpolls = append(polls, \u0026Poll{ID: len(polls), Question: \"q\", Options: []string{\"a\", \"b\"}, Tallies: []int{0, 0}})\n\t}\n\tdefer func() { polls = polls[:before] }()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"latecomer\")))\n\tuassert.AbortsContains(t, cur, \"polls is full\", func() { CreatePoll(cross(cur), \"one more\", \"a,b\") })\n}\n\n// Polls past the newest page stay reachable: the index links to the next\n// page, and a page past the end says so instead of wrapping.\nfunc TestOlderPollsArePaged(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"pager\")))\n\tfor len(polls) \u003c IndexRecent+1 {\n\t\tCreatePoll(cross(cur), \"filler\", \"a,b\")\n\t}\n\tidx := Render(\"\")\n\tuassert.True(t, strings.Contains(idx, \"(/r/moul/x/daily/polls/v1:page/2)\"), idx)\n\tp2 := Render(\"page/2\")\n\tuassert.True(t, strings.Contains(p2, \"## Poll #0:\"), p2)\n\tuassert.True(t, strings.Contains(Render(\"page/9223372036854775807\"), \"No such page\"))\n}\n"},{"name":"zz_escape_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A question and its options are the creator's text: escaped.\nfunc TestQuestionAndOptionsAreEscaped(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"escaper\")))\n\tid := CreatePoll(cross(cur), \"[claim](https://evil.example)\", \"[claim](https://evil.example)\"+\",no\")\n\tpage := Render(itoaTest(id))\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n\tuassert.False(t, strings.Contains(Render(\"\"), \"[claim](https://evil.example)\"), Render(\"\"))\n}\n"},{"name":"zz_links_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A poll page links back to this realm. It once linked to\n// /r/REPLACE_ADDR/polls.\nfunc TestPollPageLinksBackToThisRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"linker\")))\n\tid := CreatePoll(cross(cur), \"Linked?\", \"yes,no\")\n\tpage := Render(itoaTest(id))\n\tuassert.True(t, strings.Contains(page, \"[← all polls](/r/moul/x/daily/polls/v1)\"), page)\n}\n\nfunc itoaTest(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\ts := \"\"\n\tfor n \u003e 0 {\n\t\ts = string(rune(byte(n%10)+byte(48))) + s\n\t\tn /= 10\n\t}\n\treturn s\n}\n"}]},"send":"","max_deposit":"8000000ugnot"}],"fee":{"gas_wanted":"58261800","gas_fee":"174785ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"bJS0kzk8MHEVsAHLA8VISoUzkCepmVL5dnJJhmcDV9Vm226HwGCmP7BTTOyS950/I9HgibQi3JxM1oQpy9rOCw=="}],"memo":""},"metadata":{"timestamp":"1790961259"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pullpaymentdemo","path":"gno.land/r/moul/x/daily/pullpaymentdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/pullpaymentdemo/v0`\n\n**Live demo of [`p/moul/x/daily/pullpayment`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/pullpayment).**\n\nA thin, stateless realm: it holds no state of its own and contains none of the\nlibrary's logic — `Render` just exercises the package and shows the result.\nBecause it is stateless, the rendered page is identical on every call and on\nevery node.\n\nRender it at [`/r/moul/x/daily/pullpaymentdemo/v0`](https://gno.land/r/moul/x/daily/pullpaymentdemo/v0).\n\nThe library README explains the design and the trade-offs; this realm is the\nworked example.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/pullpaymentdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pullpaymentdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/pullpaymentdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pullpaymentdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/pullpaymentdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pullpaymentdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/pullpaymentdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/pullpaymentdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/pullpaymentdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/pullpaymentdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/pullpaymentdemo/v0\"\ngno = \"0.9\"\n"},{"name":"pullpaymentdemo.gno","body":"// Package pullpaymentdemo is a small gnoweb demo of the escrow ledger provided\n// by the [p/moul/x/daily/pullpayment](/p/moul/x/daily/pullpayment/v0) library:\n// crediting a split, claiming it, and why a reentrant claim gets nothing.\n//\n// It contains no ledger logic of its own and holds no coins. Stateless, so\n// Render is deterministic — which is precisely what the library is for.\npackage pullpaymentdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/pullpayment/v0\"\n)\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Pull Payment\\n\\n\")\n\tb.WriteString(\"Credit and let recipients withdraw, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/pullpayment`](/p/moul/x/daily/pullpayment/v0) library.\\n\\n\")\n\n\tb.WriteString(\"## Why not just send?\\n\\n\")\n\tb.WriteString(\"Pushing value hands control to the recipient in the middle of your \")\n\tb.WriteString(\"state transition, and a hostile recipient re-enters before you have \")\n\tb.WriteString(\"finished updating. Pulling inverts it: you record a debt, and the \")\n\tb.WriteString(\"recipient's own withdrawal is the only state being touched.\\n\\n\")\n\n\tl := pullpayment.New()\n\tl.CreditMany([]string{\"alice\", \"bob\", \"carol\"}, []int64{500, 300, 200})\n\n\tb.WriteString(\"## A split, credited\\n\\n\")\n\tb.WriteString(table(l))\n\tb.WriteString(\"\\nThe holding realm must keep `\")\n\tb.WriteString(strconv.FormatInt(l.TotalOwed(), 10))\n\tb.WriteString(\"` in reserve — that is what `TotalOwed` is for.\\n\\n\")\n\n\tb.WriteString(\"## Bob claims\\n\\n\")\n\tamt, _ := l.Withdraw(\"bob\")\n\tb.WriteString(\"`Withdraw(\\\"bob\\\")` → `\" + strconv.FormatInt(amt, 10) + \"`, and the ledger \")\n\tb.WriteString(\"is updated **before** the caller transfers anything:\\n\\n\")\n\tb.WriteString(table(l))\n\tb.WriteString(\"\\nReserve is now `\" + strconv.FormatInt(l.TotalOwed(), 10) + \"`.\\n\\n\")\n\n\tb.WriteString(\"## The reentrancy attempt\\n\\n\")\n\tb.WriteString(\"Bob's handler calls straight back in, before the transfer completes:\\n\\n\")\n\tagain, err := l.Withdraw(\"bob\")\n\tb.WriteString(\"- second `Withdraw(\\\"bob\\\")` → `\" + strconv.FormatInt(again, 10) + \"`, error: `\")\n\tif err != nil {\n\t\tb.WriteString(err.Error())\n\t} else {\n\t\tb.WriteString(\"\u003cnil\u003e\")\n\t}\n\tb.WriteString(\"`\\n\\n\")\n\tb.WriteString(\"Nothing left to take. The balance was deleted before control left the \")\n\tb.WriteString(\"function — checks, effects, *then* interactions. Lifetime withdrawn is \")\n\tb.WriteString(\"still `\" + strconv.FormatInt(l.TotalWithdrawn(), 10) + \"`, not double.\\n\\n\")\n\n\tb.WriteString(\"## Credits accumulate\\n\\n\")\n\tl.Credit(\"alice\", 100)\n\tb.WriteString(\"`Credit(\\\"alice\\\", 100)` on top of her existing balance:\\n\\n\")\n\tb.WriteString(table(l))\n\tb.WriteString(\"\\nOne withdrawal collects the lot — no dust left behind.\\n\\n\")\n\n\tb.WriteString(\"## Batch credits are all-or-nothing\\n\\n\")\n\tb.WriteString(\"A split that is partly invalid applies **none** of itself; a ledger \")\n\tb.WriteString(\"half-agreeing with the funds it guards is worse than a rejected call:\\n\\n\")\n\tbefore := l.TotalOwed()\n\tbatchErr := l.CreditMany([]string{\"dave\", \"eve\"}, []int64{10, -1})\n\tb.WriteString(\"- `CreditMany([dave, eve], [10, -1])` → `\")\n\tif batchErr != nil {\n\t\tb.WriteString(batchErr.Error())\n\t}\n\tb.WriteString(\"`\\n- total owed before: `\" + strconv.FormatInt(before, 10) + \"`, after: `\")\n\tb.WriteString(strconv.FormatInt(l.TotalOwed(), 10) + \"` — unchanged, and `dave` was not credited\\n\")\n\treturn b.String()\n}\n\nfunc table(l *pullpayment.Ledger) string {\n\tvar b strings.Builder\n\tb.WriteString(\"| payee | owed |\\n|---|---|\\n\")\n\tl.Iterate(func(p string, amt int64) bool {\n\t\tb.WriteString(\"| `\" + p + \"` | \" + strconv.FormatInt(amt, 10) + \" |\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n"},{"name":"render_example_test.gno","body":"package pullpaymentdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Pull Payment\n\t//\n\t// Credit and let recipients withdraw, demoing the [`p/moul/x/daily/pullpayment`](/p/moul/x/daily/pullpayment/v0) library.\n\t//\n\t// ## Why not just send?\n\t//\n\t// Pushing value hands control to the recipient in the middle of your state transition, and a hostile recipient re-enters before you have finished updating. Pulling inverts it: you record a debt, and the recipient's own withdrawal is the only state being touched.\n\t//\n\t// ## A split, credited\n\t//\n\t// | payee | owed |\n\t// |---|---|\n\t// | `alice` | 500 |\n\t// | `bob` | 300 |\n\t// | `carol` | 200 |\n\t//\n\t// The holding realm must keep `1000` in reserve — that is what `TotalOwed` is for.\n\t//\n\t// ## Bob claims\n\t//\n\t// `Withdraw(\"bob\")` → `300`, and the ledger is updated **before** the caller transfers anything:\n\t//\n\t// | payee | owed |\n\t// |---|---|\n\t// | `alice` | 500 |\n\t// | `carol` | 200 |\n\t//\n\t// Reserve is now `700`.\n\t//\n\t// ## The reentrancy attempt\n\t//\n\t// Bob's handler calls straight back in, before the transfer completes:\n\t//\n\t// - second `Withdraw(\"bob\")` → `0`, error: `pullpayment: nothing to withdraw`\n\t//\n\t// Nothing left to take. The balance was deleted before control left the function — checks, effects, *then* interactions. Lifetime withdrawn is still `300`, not double.\n\t//\n\t// ## Credits accumulate\n\t//\n\t// `Credit(\"alice\", 100)` on top of her existing balance:\n\t//\n\t// | payee | owed |\n\t// |---|---|\n\t// | `alice` | 600 |\n\t// | `carol` | 200 |\n\t//\n\t// One withdrawal collects the lot — no dust left behind.\n\t//\n\t// ## Batch credits are all-or-nothing\n\t//\n\t// A split that is partly invalid applies **none** of itself; a ledger half-agreeing with the funds it guards is worse than a rejected call:\n\t//\n\t// - `CreditMany([dave, eve], [10, -1])` → `pullpayment: amount must be positive`\n\t// - total owed before: `800`, after: `800` — unchanged, and `dave` was not credited\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"32768800","gas_fee":"98306ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"QZliPUA1sXqk2oiW4ehrbyAhAuviZ1JKEHD1JsYZHtgne631eEZXJmuQMekZvvQ26CSw9DFhGRd3egqOoI9QjQ=="}],"memo":""},"metadata":{"timestamp":"1790961262"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"quizstreak","path":"gno.land/r/moul/x/daily/quizstreak/v0","files":[{"name":"README.md","body":"# Quiz Streak\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA trivia quiz where every player runs their own independent streak instead of racing others for one shared question. Answer correctly and your streak grows, moving you to a fresh question; answer wrong and your streak resets to zero (but the question stays put so you can retry). A global leaderboard ranks addresses by their best-ever streak — call Answer(0-3) to play, or Render your own address to see your live dashboard.\n\nBuilt for sapphire (gno 0.9). Live demo (agent address): https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/quizstreak\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/quizstreak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quizstreak/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/quizstreak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quizstreak/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/quizstreak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quizstreak/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/quizstreak/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quizstreak/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/quizstreak/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/quizstreak/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/quizstreak/v0\"\ngno = \"0.9\"\n"},{"name":"quizstreak.gno","body":"// Package quizstreak is a multiple-choice trivia quiz where every player\n// runs their own independent streak instead of racing others for a single\n// shared question.\n//\n// Each address gets its own current question, picked deterministically from\n// the address and the block height of its first answer so different players\n// don't all start on the same question. A correct answer extends the\n// player's streak and advances them to their next question; a wrong answer\n// breaks the streak back to zero but leaves the same question live so they\n// can retry. The realm tracks each player's best-ever streak on a global\n// leaderboard.\npackage quizstreak\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// question is one fixed trivia entry.\ntype question struct {\n\ttext       string\n\tchoices    [4]string\n\tcorrectIdx int\n}\n\n// playerState is one address's progress through the question bank.\ntype playerState struct {\n\tqIdx    int\n\tstreak  int\n\tbest    int\n\tcorrect int\n\twrong   int\n}\n\nvar (\n\tquestions = []question{\n\t\t{\"What is the smallest prime number?\", [4]string{\"0\", \"1\", \"2\", \"3\"}, 2},\n\t\t{\"Which gas does a plant primarily absorb for photosynthesis?\", [4]string{\"Oxygen\", \"Nitrogen\", \"Carbon dioxide\", \"Hydrogen\"}, 2},\n\t\t{\"How many continents are there on Earth?\", [4]string{\"5\", \"6\", \"7\", \"8\"}, 2},\n\t\t{\"In binary, what is 1 + 1?\", [4]string{\"2\", \"10\", \"11\", \"0\"}, 1},\n\t\t{\"What does 'HTTP' stand for?\", [4]string{\"HyperText Transfer Protocol\", \"High Transfer Text Protocol\", \"Home Tool Transfer Protocol\", \"HyperText Transmission Path\"}, 0},\n\t\t{\"Which planet is known as the Red Planet?\", [4]string{\"Venus\", \"Jupiter\", \"Mars\", \"Saturn\"}, 2},\n\t\t{\"What is the time complexity of binary search?\", [4]string{\"O(n)\", \"O(log n)\", \"O(n^2)\", \"O(1)\"}, 1},\n\t\t{\"Which ocean is the largest by surface area?\", [4]string{\"Atlantic\", \"Indian\", \"Arctic\", \"Pacific\"}, 3},\n\t\t{\"What does 'CPU' stand for?\", [4]string{\"Central Processing Unit\", \"Computer Personal Unit\", \"Central Program Utility\", \"Core Processing Unicode\"}, 0},\n\t\t{\"How many bits are in a byte?\", [4]string{\"4\", \"8\", \"16\", \"32\"}, 1},\n\t}\n\n\tplayers = avl.NewTree() // addr(string) -\u003e *playerState\n)\n\n// startIndex picks a deterministic starting question for a brand-new player,\n// spreading players across the bank using their address and the height of\n// their first answer as entropy.\nfunc startIndex(addr string, height int64) int {\n\tif height \u003c 0 {\n\t\theight = -height\n\t}\n\tvar sum int64\n\tfor i := 0; i \u003c len(addr); i++ {\n\t\tsum += int64(addr[i])\n\t}\n\tn := int64(len(questions))\n\treturn int((sum + height) % n)\n}\n\n// getPlayer returns addr's state, lazily creating it on first contact.\nfunc getPlayer(addr string) *playerState {\n\tif v, ok := players.Get(addr).(*playerState); ok {\n\t\treturn v\n\t}\n\tp := \u0026playerState{qIdx: startIndex(addr, runtime.ChainHeight())}\n\tplayers.Set(addr, p)\n\treturn p\n}\n\n// nextIndex advances a solved player to a fresh-feeling next question: the\n// step grows with the streak so a long run doesn't loop through the bank in\n// a visibly fixed order.\nfunc nextIndex(cur, streak, n int) int {\n\treturn (cur + 1 + streak) % n\n}\n\n// Answer submits a choice (0..3) for the caller's current question.\n// Crossing function: caller invokes as Answer(cross(cur), choiceIdx).\nfunc Answer(cur realm, choiceIdx int) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tif choiceIdx \u003c 0 || choiceIdx \u003e= len(questions[0].choices) {\n\t\tpanic(\"choice must be in 0..3\")\n\t}\n\n\taddr := cur.Previous().Address().String()\n\tp := getPlayer(addr)\n\tq := questions[p.qIdx]\n\n\tif choiceIdx != q.correctIdx {\n\t\tbrokeStreak := p.streak\n\t\tp.streak = 0\n\t\tp.wrong++\n\t\tif brokeStreak \u003e 0 {\n\t\t\treturn \"Wrong — streak of \" + strconv.Itoa(brokeStreak) + \" broken. Same question stays live, try again.\"\n\t\t}\n\t\treturn \"Wrong — try again.\"\n\t}\n\n\tp.streak++\n\tp.correct++\n\tif p.streak \u003e p.best {\n\t\tp.best = p.streak\n\t}\n\tp.qIdx = nextIndex(p.qIdx, p.streak, len(questions))\n\n\tchain.Emit(\"QuizAnswered\",\n\t\t\"player\", addr,\n\t\t\"streak\", strconv.Itoa(p.streak),\n\t\t\"best\", strconv.Itoa(p.best),\n\t)\n\n\treturn \"Correct! Streak is now \" + strconv.Itoa(p.streak) + \". Next question is live.\"\n}\n\n// leaderboardEntry is a snapshot row used only for rendering, sorted by best\n// streak descending.\ntype leaderboardEntry struct {\n\taddr string\n\tbest int\n}\n\nfunc leaderboard() []leaderboardEntry {\n\tvar rows []leaderboardEntry\n\tplayers.Iterate(\"\", \"\", func(addr string, v any) bool {\n\t\trows = append(rows, leaderboardEntry{addr: addr, best: v.(*playerState).best})\n\t\treturn false\n\t})\n\tfor i := 1; i \u003c len(rows); i++ {\n\t\tj := i\n\t\tfor j \u003e 0 \u0026\u0026 rows[j-1].best \u003c rows[j].best {\n\t\t\trows[j-1], rows[j] = rows[j], rows[j-1]\n\t\t\tj--\n\t\t}\n\t}\n\treturn rows\n}\n\nfunc renderQuestion(b *strings.Builder, p *playerState) {\n\tq := questions[p.qIdx]\n\tletters := [4]string{\"A\", \"B\", \"C\", \"D\"}\n\tb.WriteString(\"**\" + q.text + \"**\\n\\n\")\n\tfor i, c := range q.choices {\n\t\tb.WriteString(\"- **\" + letters[i] + \"** (\" + strconv.Itoa(i) + \"): \" + c + \"\\n\")\n\t}\n\tb.WriteString(\"\\n- Current streak: \" + strconv.Itoa(p.streak) + \"\\n\")\n\tb.WriteString(\"- Best streak: \" + strconv.Itoa(p.best) + \"\\n\")\n\tb.WriteString(\"- Correct / wrong lifetime: \" + strconv.Itoa(p.correct) + \" / \" + strconv.Itoa(p.wrong) + \"\\n\\n\")\n}\n\n// Render produces the gnoweb Markdown view. The root path shows the rules\n// and the leaderboard; a path of a bech32 address shows that player's\n// current question and stats.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Quiz Streak\\n\\n\")\n\tb.WriteString(\"Everyone plays their own trivia run at their own pace. Call \")\n\tb.WriteString(\"`Answer(choiceIdx)` with 0-3 — a correct answer extends your streak \")\n\tb.WriteString(\"and moves you to your next question; a wrong answer breaks your \")\n\tb.WriteString(\"streak but leaves the same question live so you can retry.\\n\\n\")\n\n\tif path != \"\" {\n\t\tif v, ok := players.Get(path).(*playerState); ok {\n\t\t\tb.WriteString(\"## Your question (`\" + path + \"`)\\n\\n\")\n\t\t\trenderQuestion(\u0026b, v)\n\t\t} else {\n\t\t\tb.WriteString(\"## `\" + path + \"`\\n\\n_No answers submitted yet — call `Answer` to get your first question._\\n\\n\")\n\t\t}\n\t}\n\n\tb.WriteString(\"## Best-streak leaderboard\\n\\n\")\n\trows := leaderboard()\n\tif len(rows) == 0 {\n\t\tb.WriteString(\"_No one has played yet — be the first!_\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| Player | Best streak |\\n|---|---|\\n\")\n\t\tfor _, r := range rows {\n\t\t\tb.WriteString(\"| `\" + r.addr + \"` | \" + strconv.Itoa(r.best) + \" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"## How to play\\n\\n\")\n\tb.WriteString(\"```\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/quizstreak \\\\\\n\")\n\tb.WriteString(\"  -func Answer -args \u003c0|1|2|3\u003e ...\\n\")\n\tb.WriteString(\"```\\n\\n\")\n\tb.WriteString(\"View your own dashboard at `.../quizstreak:\u003cyour-address\u003e`.\\n\")\n\n\treturn b.String()\n}\n"},{"name":"quizstreak_test.gno","body":"package quizstreak\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// resetGame re-initializes package globals so each test starts clean.\nfunc resetGame() {\n\tplayers = avl.NewTree()\n}\n\nfunc TestStartIndexDeterministicAndInRange(t *testing.T) {\n\tn := len(questions)\n\tfor _, tc := range []struct {\n\t\taddr   string\n\t\theight int64\n\t}{\n\t\t{\"g1aaaa\", 0},\n\t\t{\"g1bbbb\", 42},\n\t\t{\"g1cccc\", -7},\n\t} {\n\t\tidx := startIndex(tc.addr, tc.height)\n\t\tif idx \u003c 0 || idx \u003e= n {\n\t\t\tt.Errorf(\"startIndex(%q, %d) = %d, want in 0..%d\", tc.addr, tc.height, idx, n-1)\n\t\t}\n\t\tif again := startIndex(tc.addr, tc.height); again != idx {\n\t\t\tt.Errorf(\"startIndex(%q, %d) non-deterministic: %d != %d\", tc.addr, tc.height, again, idx)\n\t\t}\n\t}\n}\n\nfunc TestNextIndexWrapsAround(t *testing.T) {\n\tn := 5\n\tif got := nextIndex(4, 0, n); got != 0 {\n\t\tt.Errorf(\"nextIndex(4, 0, 5) = %d, want 0\", got)\n\t}\n\tif got := nextIndex(2, 3, n); got != 1 {\n\t\tt.Errorf(\"nextIndex(2, 3, 5) = %d, want 1\", got)\n\t}\n}\n\n// TestAnswerCorrectAndWrong exercises the crossing Answer function, so it\n// takes cur realm and calls through cross(cur).\nfunc TestAnswerCorrectAndWrong(cur realm, t *testing.T) {\n\tresetGame()\n\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\taddr := alice.String()\n\tp := getPlayer(addr)\n\tq := questions[p.qIdx]\n\n\t// wrong answer first: pick any index that isn't correct\n\twrong := (q.correctIdx + 1) % len(q.choices)\n\tgot := Answer(cross(cur), wrong)\n\tif !strings.HasPrefix(got, \"Wrong\") {\n\t\tt.Errorf(\"Answer(wrong) = %q, want it to start with Wrong\", got)\n\t}\n\tif p.streak != 0 {\n\t\tt.Errorf(\"streak after wrong answer = %d, want 0\", p.streak)\n\t}\n\tif p.qIdx != questionIndexOf(q) {\n\t\tt.Errorf(\"question changed after a wrong answer, want it to stay the same\")\n\t}\n\n\tgot = Answer(cross(cur), q.correctIdx)\n\tif !strings.HasPrefix(got, \"Correct!\") {\n\t\tt.Errorf(\"Answer(correct) = %q, want it to start with Correct!\", got)\n\t}\n\tif p.streak != 1 {\n\t\tt.Errorf(\"streak after correct answer = %d, want 1\", p.streak)\n\t}\n\tif p.best != 1 {\n\t\tt.Errorf(\"best after first correct answer = %d, want 1\", p.best)\n\t}\n\tif p.correct != 1 || p.wrong != 1 {\n\t\tt.Errorf(\"correct/wrong = %d/%d, want 1/1\", p.correct, p.wrong)\n\t}\n\tif len(leaderboard()) != 1 {\n\t\tt.Errorf(\"leaderboard len = %d, want 1\", len(leaderboard()))\n\t}\n}\n\n// questionIndexOf is a small test helper to find a question's index.\nfunc questionIndexOf(q question) int {\n\tfor i, cand := range questions {\n\t\tif cand.text == q.text {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc TestRenderShowsRulesAndLeaderboard(t *testing.T) {\n\tresetGame()\n\tout := Render(\"\")\n\tfor _, want := range []string{\"Quiz Streak\", \"leaderboard\", \"How to play\"} {\n\t\tif !strings.Contains(strings.ToLower(out), strings.ToLower(want)) {\n\t\t\tt.Errorf(\"Render(\\\"\\\") missing %q\", want)\n\t\t}\n\t}\n\tif !strings.Contains(out, \"No one has played yet\") {\n\t\tt.Errorf(\"Render(\\\"\\\") should note an empty leaderboard\")\n\t}\n}\n\nfunc TestRenderShowsPlayerDashboard(cur realm, t *testing.T) {\n\tresetGame()\n\n\tbob := testutils.TestAddress(\"bob\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\taddr := bob.String()\n\n\tp := getPlayer(addr)\n\tq := questions[p.qIdx]\n\tAnswer(cross(cur), q.correctIdx)\n\n\tout := Render(addr)\n\tif !strings.Contains(out, \"Your question\") {\n\t\tt.Errorf(\"Render(addr) missing player dashboard section\")\n\t}\n\tif !strings.Contains(out, \"Current streak: 1\") {\n\t\tt.Errorf(\"Render(addr) missing updated streak, got:\\n%s\", out)\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"45009600","gas_fee":"135028ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"rbrU4lAgI9Edplu1EpZSfYEmhjDjxPTDOvKbJ2Gmv1RMVjpAupzyKfXxaxlTFEiDgQU1KYsmgH33MsCVD3hj/Q=="}],"memo":""},"metadata":{"timestamp":"1790961263"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"quotes","path":"gno.land/r/moul/x/daily/quotes/v0","files":[{"name":"README.md","body":"# Quote of the Moment\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA community quote board realm for gno.land (sapphire, gno 0.9). Anyone can submit\na quote; each entry records the text, the submitter's address, and the block\nheight at submission. The board ships pre-seeded with a handful of Stoic quotes\nso a fresh deploy renders nicely, and the rendered page rotates a \"featured\"\npick deterministically as the chain advances.\n\n- **Realm path:** `gno.land/r/REPLACE_ADDR/quotes`\n- **State-mutating tx:** `AddQuote(text string)` — a gno 0.9 crossing function.\n- **View:** `Render(path string)` — Markdown; a blockquote featured pick chosen\n  by `ChainHeight() % len(quotes)`, followed by the full list with author + id.\n\n## Example calls\n\nAdd a quote (MsgCall dispatches to the crossing function; you do not write\n`cross(cur)` on the command line — the chain supplies it):\n\n```sh\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/REPLACE_ADDR/quotes\" \\\n  -func AddQuote \\\n  -args \"Luck is what happens when preparation meets opportunity.\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e \u003ckey\u003e\n```\n\nView the rendered board in gnoweb:\n\n```\nhttps://gno.land/r/REPLACE_ADDR/quotes\n```\n\nOr query the render output directly:\n\n```sh\ngnokey query \"vm/qrender\" -data \"gno.land/r/REPLACE_ADDR/quotes:\" -remote \u003crpc\u003e\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/quotes/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quotes/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/quotes/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quotes/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/quotes/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quotes/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/quotes/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/quotes/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/quotes/v0\"\ngno = \"0.9\"\n"},{"name":"quotes.gno","body":"// Package quotes is a community \"Quote of the Moment\" board realm.\n//\n// Anyone can submit a quote via the exported crossing function AddQuote.\n// Each quote records its text, the address of the caller who added it, and\n// the block height at submission time. Render deterministically picks a\n// \"featured\" quote by the current block height (a stable index into the\n// list), shows it as a blockquote, then lists every quote with its author\n// and id below.\npackage quotes\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n)\n\n// quote is a single board entry. Author is stored as a plain string address\n// (realm values are ephemeral and must never be persisted).\ntype quote struct {\n\tid     int\n\ttext   string\n\tauthor string // bech32 address of the submitter, or \"\" for seeded quotes\n\theight int64  // block height at submission (0 for seeded quotes)\n}\n\n// board is the persistent realm state. A plain slice is fine here: the list\n// only ever grows by append and Render walks it in insertion order, which is\n// deterministic.\nvar board []quote\n\n// init seeds the board so a fresh deploy renders nicely.\nfunc init() {\n\tseed := []string{\n\t\t\"The unexamined life is not worth living.\",\n\t\t\"We suffer more often in imagination than in reality.\",\n\t\t\"Waste no more time arguing about what a good person should be. Be one.\",\n\t\t\"He who is brave is free.\",\n\t}\n\tfor _, s := range seed {\n\t\tboard = append(board, quote{\n\t\t\tid:     len(board),\n\t\t\ttext:   s,\n\t\t\tauthor: \"\", // seeded\n\t\t\theight: 0,\n\t\t})\n\t}\n}\n\n// AddQuote is the exported, state-mutating entry point. It follows the gno 0.9\n// interrealm crossing convention: the first parameter is `cur realm`. Callers\n// invoke it as AddQuote(cross(cur), \"...\") over a MsgCall.\nfunc AddQuote(cur realm, text string) {\n\t// Authentication primitive: reject a stale/forged realm value before\n\t// deriving any caller identity from it.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\n\tif err := validate(text); err != nil {\n\t\tpanic(err)\n\t}\n\n\tauthor := cur.Previous().Address().String()\n\th := runtime.ChainHeight()\n\n\tboard = append(board, quote{\n\t\tid:     len(board),\n\t\ttext:   text,\n\t\tauthor: author,\n\t\theight: h,\n\t})\n\n\tchain.Emit(\"QuoteAdded\",\n\t\t\"id\", strconv.Itoa(len(board)-1),\n\t\t\"author\", author,\n\t\t\"height\", strconv.FormatInt(h, 10),\n\t)\n}\n\n// maxQuoteLen caps quote length to keep storage costs bounded and Render tidy.\nconst maxQuoteLen = 280\n\n// validate enforces basic content rules. Returns an error describing the\n// problem, or nil when the text is acceptable.\nfunc validate(text string) error {\n\tif len(text) == 0 {\n\t\treturn errEmpty\n\t}\n\tif len(text) \u003e maxQuoteLen {\n\t\treturn errTooLong\n\t}\n\treturn nil\n}\n\n// Sentinel errors for validation. Kept as package-level vars so tests can\n// compare against them directly.\nvar (\n\terrEmpty   = quoteError(\"quote text must not be empty\")\n\terrTooLong = quoteError(\"quote text exceeds \" + strconv.Itoa(maxQuoteLen) + \" characters\")\n)\n\n// quoteError is a trivial string-backed error type (the VM has no host\n// stdlib errors package convenience beyond this).\ntype quoteError string\n\nfunc (e quoteError) Error() string { return string(e) }\n\n// featuredIndex deterministically picks which quote is \"of the moment\" for a\n// given block height. Pure function of (height, count) so it is fully\n// deterministic and easy to test.\nfunc featuredIndex(height int64, count int) int {\n\tif count \u003c= 0 {\n\t\treturn -1\n\t}\n\t// Guard against a negative height (should not happen on-chain, but keeps\n\t// the modulo well-defined).\n\tif height \u003c 0 {\n\t\theight = -height\n\t}\n\treturn int(height % int64(count))\n}\n\n// Render produces the Markdown page shown in gnoweb. It is NOT a crossing\n// function (no `cur realm` parameter) — it is a read-only view.\nfunc Render(path string) string {\n\tcount := len(board)\n\tif count == 0 {\n\t\treturn \"# Quote of the Moment\\n\\n_No quotes yet. Be the first to add one._\\n\"\n\t}\n\n\th := runtime.ChainHeight()\n\tidx := featuredIndex(h, count)\n\tfeatured := board[idx]\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Quote of the Moment\\n\\n\")\n\n\t// Featured quote as a blockquote.\n\tb.WriteString(\"\u003e \")\n\tb.WriteString(featured.text)\n\tb.WriteString(\"\\n\u003e\\n\u003e — \")\n\tb.WriteString(authorLabel(featured))\n\tb.WriteString(\" (#\")\n\tb.WriteString(strconv.Itoa(featured.id))\n\tb.WriteString(\")\\n\\n\")\n\n\tb.WriteString(\"_Featured pick rotates with block height \")\n\tb.WriteString(strconv.FormatInt(h, 10))\n\tb.WriteString(\" — index \")\n\tb.WriteString(strconv.Itoa(idx))\n\tb.WriteString(\" of \")\n\tb.WriteString(strconv.Itoa(count))\n\tb.WriteString(\"._\\n\\n\")\n\n\t// Full list.\n\tb.WriteString(\"## All quotes (\")\n\tb.WriteString(strconv.Itoa(count))\n\tb.WriteString(\")\\n\\n\")\n\tfor _, q := range board {\n\t\tb.WriteString(\"- **#\")\n\t\tb.WriteString(strconv.Itoa(q.id))\n\t\tb.WriteString(\"** \")\n\t\tb.WriteString(q.text)\n\t\tb.WriteString(\" — _\")\n\t\tb.WriteString(authorLabel(q))\n\t\tb.WriteString(\"_\\n\")\n\t}\n\n\treturn b.String()\n}\n\n// authorLabel renders a human-friendly author string. Seeded quotes (empty\n// author) show as the house account.\nfunc authorLabel(q quote) string {\n\tif q.author == \"\" {\n\t\treturn \"the board\"\n\t}\n\treturn q.author\n}\n"},{"name":"quotes_test.gno","body":"package quotes\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n// TestFeaturedIndexDeterministic verifies the rotating pick is a pure,\n// deterministic function of (height, count): same inputs -\u003e same index,\n// always within [0, count).\nfunc TestFeaturedIndexDeterministic(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\theight int64\n\t\tcount  int\n\t\twant   int\n\t}{\n\t\t{\"zero height\", 0, 4, 0},\n\t\t{\"wraps at count\", 4, 4, 0},\n\t\t{\"mid range\", 5, 4, 1},\n\t\t{\"single quote always zero\", 12345, 1, 0},\n\t\t{\"empty list\", 100, 0, -1},\n\t\t{\"negative height normalized\", -3, 4, 3},\n\t\t{\"large height\", 1_000_003, 3, 1},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := featuredIndex(tt.height, tt.count)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"featuredIndex(%d, %d) = %d, want %d\",\n\t\t\t\t\ttt.height, tt.count, got, tt.want)\n\t\t\t}\n\t\t\t// For non-empty lists the index must be a valid slot.\n\t\t\tif tt.count \u003e 0 \u0026\u0026 (got \u003c 0 || got \u003e= tt.count) {\n\t\t\t\tt.Errorf(\"featuredIndex(%d, %d) = %d, out of range [0,%d)\",\n\t\t\t\t\ttt.height, tt.count, got, tt.count)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Determinism: repeated calls with identical inputs never diverge.\n\tfor i := 0; i \u003c 5; i++ {\n\t\tif featuredIndex(7, 4) != featuredIndex(7, 4) {\n\t\t\tt.Fatal(\"featuredIndex is not deterministic\")\n\t\t}\n\t}\n}\n\n// TestValidate covers the content rules enforced before a quote is stored.\nfunc TestValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\ttext    string\n\t\twantErr error\n\t}{\n\t\t{\"ok short\", \"hello world\", nil},\n\t\t{\"ok at limit\", strings.Repeat(\"x\", maxQuoteLen), nil},\n\t\t{\"empty\", \"\", errEmpty},\n\t\t{\"too long\", strings.Repeat(\"x\", maxQuoteLen+1), errTooLong},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := validate(tt.text)\n\t\t\tif err != tt.wantErr {\n\t\t\t\tt.Errorf(\"validate(%q) err = %v, want %v\", tt.name, err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// TestRenderSeeded checks that a fresh deploy (seeded board) renders the\n// expected structure: title, a blockquote featured pick, and the full list\n// containing every seeded quote.\nfunc TestRenderSeeded(t *testing.T) {\n\tout := Render(\"\")\n\n\tif !strings.Contains(out, \"# Quote of the Moment\") {\n\t\tt.Error(\"missing title heading\")\n\t}\n\tif !strings.Contains(out, \"\\n\u003e \") {\n\t\tt.Error(\"featured quote is not rendered as a blockquote\")\n\t}\n\tif !strings.Contains(out, \"## All quotes (\") {\n\t\tt.Error(\"missing full-list section\")\n\t}\n\n\t// Every seeded quote must appear in the listing.\n\tfor _, q := range board {\n\t\tif !strings.Contains(out, q.text) {\n\t\t\tt.Errorf(\"rendered output missing seeded quote: %q\", q.text)\n\t\t}\n\t}\n\n\t// Seeded quotes have no author and should surface the house label.\n\tif !strings.Contains(out, \"the board\") {\n\t\tt.Error(\"seeded quotes should be attributed to \\\"the board\\\"\")\n\t}\n}\n\n// TestSeededBoard confirms init populated the board and ids are sequential.\nfunc TestSeededBoard(t *testing.T) {\n\tif len(board) \u003c 3 {\n\t\tt.Fatalf(\"expected at least 3 seeded quotes, got %d\", len(board))\n\t}\n\tfor i, q := range board {\n\t\tif q.id != i {\n\t\t\tt.Errorf(\"quote at position %d has id %d, want %d\", i, q.id, i)\n\t\t}\n\t}\n}\n"},{"name":"render_example_test.gno","body":"package quotes\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Quote of the Moment\n\t//\n\t// \u003e He who is brave is free.\n\t// \u003e\n\t// \u003e — the board (#3)\n\t//\n\t// _Featured pick rotates with block height 123 — index 3 of 4._\n\t//\n\t// ## All quotes (4)\n\t//\n\t// - **#0** The unexamined life is not worth living. — _the board_\n\t// - **#1** We suffer more often in imagination than in reality. — _the board_\n\t// - **#2** Waste no more time arguing about what a good person should be. Be one. — _the board_\n\t// - **#3** He who is brave is free. — _the board_\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"42945200","gas_fee":"128835ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"7k6afdKV3MbXAOGCU5LYKHqyOGaMDYDVGfJcMwKKgehqNYM6iahJK6uglLj7/P0irMxxCoAOX+DlXS1YM0z9hg=="}],"memo":""},"metadata":{"timestamp":"1790961264"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"qvote","path":"gno.land/r/moul/x/daily/qvote/v1","files":[{"name":"README.md","body":"# Quadratic Voting\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA Gno port of the classic Solidity 'Ballot' voting contract, but swapping one-address-one-vote for quadratic voting: every address gets a fixed 100-credit budget per poll, and stacking N votes on one option costs N^2 credits, so spreading conviction is cheap but dominating one option gets steep fast. Create a poll with CreatePoll, spend (or refund) credits with Vote(pollID, optionIdx, delta), and the creator ends it with ClosePoll. Render shows the poll board, per-poll results, and any voter's standing.\n\nBuilt for sapphire (gno 0.9). Live demo (agent address): https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/qvote\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/qvote) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline` helper.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/qvote/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/qvote/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/qvote/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"qvote.gno","body":"// Package qvote is a quadratic-voting poll board, a Gno take on the classic\n// Solidity \"Ballot\" voting contract with one twist borrowed from mechanism\n// design instead of one-address-one-vote: every voter gets a fixed voice-\n// credit budget per poll, and piling votes onto a single option costs the\n// square of how many votes they stack there. Buying your 1st vote on an\n// option costs 1 credit, the 2nd costs 3 more (4 total), the 3rd costs 5\n// more (9 total) -- so spreading conviction across options is cheap, but\n// dominating one option gets expensive fast. Votes can also be pulled back\n// for a matching credit refund.\npackage qvote\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// InitialCredits is the fixed voice-credit budget every address gets to\n// spend on each poll (shared across all of that poll's options).\nconst InitialCredits int64 = 100\n\nconst (\n\tminOptions = 2\n\tmaxOptions = 8\n)\n\ntype poll struct {\n\tID            string\n\tCreator       address\n\tQuestion      string\n\tOptions       []string\n\tTally         []int64\n\tCreatedHeight int64\n\tClosed        bool\n}\n\n// voterState is one address's standing inside one poll: how many credits\n// they've spent so far and how many votes that bought them on each option.\ntype voterState struct {\n\tCreditsUsed int64\n\tVotes       []int64\n}\n\nvar (\n\tpolls  avl.Tree // poll ID -\u003e *poll\n\tvoters avl.Tree // \"\u003cpollID\u003e:\u003caddr\u003e\" -\u003e *voterState\n\tnextID int\n)\n\nfunc voterKey(pollID string, addr address) string {\n\treturn pollID + \":\" + addr.String()\n}\n\nfunc getPoll(pollID string) *poll {\n\tp, ok := polls.Get(pollID).(*poll)\n\tif !ok {\n\t\tpanic(\"no such poll: \" + pollID)\n\t}\n\treturn p\n}\n\nfunc getOrCreateVoter(pollID string, addr address, numOptions int) *voterState {\n\tkey := voterKey(pollID, addr)\n\tif v, ok := voters.Get(key).(*voterState); ok {\n\t\treturn v\n\t}\n\tvs := \u0026voterState{Votes: make([]int64, numOptions)}\n\tvoters.Set(key, vs)\n\treturn vs\n}\n\n// square is the quadratic-voting cost curve: N votes on one option cost\n// N*N credits in total.\nfunc square(n int64) int64 {\n\treturn n * n\n}\n\n// CreatePoll opens a new poll with the given question and comma-separated\n// options (at least 2, at most 8), returning its ID.\nfunc CreatePoll(cur realm, question string, optionsCSV string) string {\n\tcreator := cur.Previous().Address()\n\n\tquestion = strings.TrimSpace(question)\n\tif question == \"\" {\n\t\tpanic(\"question must not be empty\")\n\t}\n\n\tvar options []string\n\tfor _, raw := range strings.Split(optionsCSV, \",\") {\n\t\topt := strings.TrimSpace(raw)\n\t\tif opt == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\toptions = append(options, opt)\n\t}\n\tif len(options) \u003c minOptions {\n\t\tpanic(\"need at least \" + strconv.Itoa(minOptions) + \" non-empty options\")\n\t}\n\tif len(options) \u003e maxOptions {\n\t\tpanic(\"at most \" + strconv.Itoa(maxOptions) + \" options are allowed\")\n\t}\n\n\tnextID++\n\tid := strconv.Itoa(nextID)\n\tp := \u0026poll{\n\t\tID:            id,\n\t\tCreator:       creator,\n\t\tQuestion:      question,\n\t\tOptions:       options,\n\t\tTally:         make([]int64, len(options)),\n\t\tCreatedHeight: runtime.ChainHeight(),\n\t}\n\tpolls.Set(id, p)\n\n\tchain.Emit(\"PollCreated\", \"id\", id, \"creator\", creator.String(), \"question\", question)\n\n\treturn \"poll #\" + id + \" created with \" + strconv.Itoa(len(options)) + \" options\"\n}\n\n// Vote adjusts the caller's votes on one option of a poll by delta (positive\n// to buy more, negative to sell some back for a credit refund). The credit\n// cost of holding N votes on an option is N*N, taken from the caller's fixed\n// per-poll budget of InitialCredits.\nfunc Vote(cur realm, pollID string, optionIdx int, delta int64) string {\n\tcaller := cur.Previous().Address()\n\n\tp := getPoll(pollID)\n\tif p.Closed {\n\t\tpanic(\"poll #\" + pollID + \" is closed\")\n\t}\n\tif optionIdx \u003c 0 || optionIdx \u003e= len(p.Options) {\n\t\tpanic(\"invalid option index\")\n\t}\n\tif delta == 0 {\n\t\tpanic(\"delta must be non-zero\")\n\t}\n\n\tvs := getOrCreateVoter(pollID, caller, len(p.Options))\n\tcurrent := vs.Votes[optionIdx]\n\tupdated := current + delta\n\tif updated \u003c 0 {\n\t\tpanic(\"cannot remove more votes than you hold on this option\")\n\t}\n\n\tcost := square(updated) - square(current)\n\tnewCreditsUsed := vs.CreditsUsed + cost\n\tif newCreditsUsed \u003e InitialCredits {\n\t\tpanic(\"exceeds your voice-credit budget of \" + strconv.FormatInt(InitialCredits, 10) +\n\t\t\t\" for this poll (would need \" + strconv.FormatInt(newCreditsUsed, 10) + \")\")\n\t}\n\n\tvs.Votes[optionIdx] = updated\n\tvs.CreditsUsed = newCreditsUsed\n\tp.Tally[optionIdx] += delta\n\n\tchain.Emit(\"VoteCast\",\n\t\t\"pollID\", pollID,\n\t\t\"voter\", caller.String(),\n\t\t\"option\", p.Options[optionIdx],\n\t\t\"votes\", strconv.FormatInt(updated, 10),\n\t)\n\n\tverb := \"bought\"\n\tn := delta\n\tif delta \u003c 0 {\n\t\tverb = \"sold back\"\n\t\tn = -delta\n\t}\n\treturn \"you \" + verb + \" \" + strconv.FormatInt(n, 10) + \" vote(s) on \\\"\" + p.Options[optionIdx] +\n\t\t\"\\\" -- now holding \" + strconv.FormatInt(updated, 10) + \" (credits used: \" +\n\t\tstrconv.FormatInt(vs.CreditsUsed, 10) + \"/\" + strconv.FormatInt(InitialCredits, 10) + \")\"\n}\n\n// ClosePoll ends voting on a poll. Only its creator may close it.\nfunc ClosePoll(cur realm, pollID string) string {\n\tcaller := cur.Previous().Address()\n\n\tp := getPoll(pollID)\n\tif caller != p.Creator {\n\t\tpanic(\"only the poll creator can close it\")\n\t}\n\tif p.Closed {\n\t\tpanic(\"poll #\" + pollID + \" is already closed\")\n\t}\n\tp.Closed = true\n\n\tchain.Emit(\"PollClosed\", \"id\", pollID)\n\n\treturn \"poll #\" + pollID + \" closed\"\n}\n\nfunc leadingOption(p *poll) (string, int64) {\n\tbest := -1\n\tvar bestVotes int64 = -1\n\tfor i, v := range p.Tally {\n\t\tif v \u003e bestVotes {\n\t\t\tbestVotes = v\n\t\t\tbest = i\n\t\t}\n\t}\n\tif best \u003c 0 {\n\t\treturn \"\", 0\n\t}\n\treturn p.Options[best], bestVotes\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Quadratic Voting\\n\\n\")\n\tb.WriteString(\"Create a poll, then spend voice credits on the options you care about -- \" +\n\t\t\"the Nth vote you stack on one option costs N^2 credits out of a fixed budget of \" +\n\t\tstrconv.FormatInt(InitialCredits, 10) + \" per poll, so spreading support across \" +\n\t\t\"options is cheap but dominating one gets steep fast.\\n\\n\")\n\n\tb.WriteString(\"## Polls\\n\\n\")\n\tcount := 0\n\tpolls.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tcount++\n\t\tp := value.(*poll)\n\t\tstatus := \"open\"\n\t\tif p.Closed {\n\t\t\tstatus = \"closed\"\n\t\t}\n\t\tlead, votes := leadingOption(p)\n\t\tline := \"- #\" + p.ID + \" (\" + status + \"): \" + ui.Inline(p.Question)\n\t\tif lead != \"\" {\n\t\t\tline += \" -- leading: \\\"\" + ui.Inline(lead) + \"\\\" (\" + strconv.FormatInt(votes, 10) + \")\"\n\t\t}\n\t\tb.WriteString(line + \"\\n\")\n\t\treturn false\n\t})\n\tif count == 0 {\n\t\tb.WriteString(\"_no polls yet -- call `CreatePoll(question, \\\"opt1,opt2,...\\\")` to start one._\\n\")\n\t}\n\n\tb.WriteString(\"\\n## How to use\\n\\n\")\n\tb.WriteString(\"1. `CreatePoll(\\\"Best pizza topping?\\\", \\\"pineapple,mushroom,pepperoni\\\")` -- returns a poll ID.\\n\")\n\tb.WriteString(\"2. `Vote(pollID, optionIdx, delta)` -- e.g. `Vote(\\\"1\\\", 0, 3)` buys 3 votes on option 0 \" +\n\t\t\"(costs 9 credits); a negative delta sells votes back for a refund.\\n\")\n\tb.WriteString(\"3. `ClosePoll(pollID)` -- the creator ends voting.\\n\\n\")\n\tb.WriteString(\"View a poll at this realm's path plus its ID (e.g. `.../qvote:1`), \" +\n\t\t\"or one voter's standing in it with `.../qvote:1/g1youraddress...`.\\n\")\n\n\treturn b.String()\n}\n\nfunc renderPoll(id string) string {\n\tp, ok := polls.Get(id).(*poll)\n\tif !ok {\n\t\treturn \"# Poll #\" + ui.Inline(id) + \"\\n\\nNo such poll.\\n\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Poll #\" + p.ID + \": \" + ui.Inline(p.Question) + \"\\n\\n\")\n\tstatus := \"open\"\n\tif p.Closed {\n\t\tstatus = \"closed\"\n\t}\n\tb.WriteString(\"- Status: \" + status + \"\\n\")\n\tb.WriteString(\"- Creator: `\" + p.Creator.String() + \"`\\n\\n\")\n\n\tb.WriteString(\"## Results\\n\\n\")\n\tvar total int64\n\tfor _, v := range p.Tally {\n\t\ttotal += v\n\t}\n\tfor i, opt := range p.Options {\n\t\tb.WriteString(strconv.Itoa(i) + \". \" + ui.Inline(opt) + \" -- \" +\n\t\t\tstrconv.FormatInt(p.Tally[i], 10) + \" vote(s)\\n\")\n\t}\n\tb.WriteString(\"\\nTotal votes cast: \" + strconv.FormatInt(total, 10) + \"\\n\")\n\n\treturn b.String()\n}\n\nfunc renderVoter(pollID, rawAddr string) string {\n\tsafeAddr := ui.Inline(strings.TrimSpace(rawAddr))\n\tp, ok := polls.Get(pollID).(*poll)\n\tif !ok {\n\t\treturn \"# Poll #\" + ui.Inline(pollID) + \"\\n\\nNo such poll.\\n\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + safeAddr + \" in poll #\" + p.ID + \"\\n\\n\")\n\n\tstate, ok := voters.Get(voterKey(pollID, address(strings.TrimSpace(rawAddr)))).(*voterState)\n\tif !ok {\n\t\tb.WriteString(\"No votes cast yet.\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"- Credits used: \" + strconv.FormatInt(state.CreditsUsed, 10) + \"/\" +\n\t\tstrconv.FormatInt(InitialCredits, 10) + \"\\n\\n\")\n\tfor i, opt := range p.Options {\n\t\tif state.Votes[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tb.WriteString(\"- \" + ui.Inline(opt) + \": \" + strconv.FormatInt(state.Votes[i], 10) + \" vote(s)\\n\")\n\t}\n\n\treturn b.String()\n}\n\n// Render shows the poll board at \"\", one poll's results at \"\u003cpollID\u003e\", or\n// one voter's standing in a poll at \"\u003cpollID\u003e/\u003caddr\u003e\".\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\tif idx := strings.IndexByte(path, '/'); idx \u003e= 0 {\n\t\treturn renderVoter(path[:idx], path[idx+1:])\n\t}\n\treturn renderPoll(path)\n}\n"},{"name":"qvote_test.gno","body":"package qvote\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tpolls = avl.Tree{}\n\tvoters = avl.Tree{}\n\tnextID = 0\n}\n\nfunc TestSquare(t *testing.T) {\n\tcases := []struct {\n\t\tn, want int64\n\t}{\n\t\t{0, 0}, {1, 1}, {2, 4}, {3, 9}, {10, 100},\n\t}\n\tfor _, c := range cases {\n\t\tif got := square(c.n); got != c.want {\n\t\t\tt.Fatalf(\"square(%d) = %d, want %d\", c.n, got, c.want)\n\t\t}\n\t}\n}\n\n// Crossing: CreatePoll mutates realm state, so the test needs `cur realm`.\nfunc TestCreatePollValidatesOptions(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"best color?\", \"red, green , blue\")\n\tif id != \"poll #1 created with 3 options\" {\n\t\tt.Fatalf(\"unexpected message: %q\", id)\n\t}\n\tp := getPoll(\"1\")\n\tif len(p.Options) != 3 || p.Options[0] != \"red\" || p.Options[2] != \"blue\" {\n\t\tt.Fatalf(\"options not parsed/trimmed correctly: %#v\", p.Options)\n\t}\n\n\tif rec := revive(func() { CreatePoll(cross(cur), \"one option?\", \"only-one\") }); rec == nil {\n\t\tt.Fatal(\"expected panic for too few options\")\n\t}\n\tif rec := revive(func() { CreatePoll(cross(cur), \"  \", \"a,b\") }); rec == nil {\n\t\tt.Fatal(\"expected panic for empty question\")\n\t}\n}\n\nfunc TestVoteQuadraticCostAndBudget(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreatePoll(cross(cur), \"pizza topping?\", \"pineapple,mushroom,pepperoni\")\n\n\t// 1st vote costs 1, 2nd costs 3 more (4 total), 3rd costs 5 more (9 total).\n\tVote(cross(cur), \"1\", 0, 1)\n\tvs := getOrCreateVoter(\"1\", alice, 3)\n\tif vs.CreditsUsed != 1 {\n\t\tt.Fatalf(\"credits used = %d, want 1\", vs.CreditsUsed)\n\t}\n\tVote(cross(cur), \"1\", 0, 2)\n\tif vs.CreditsUsed != 9 || vs.Votes[0] != 3 {\n\t\tt.Fatalf(\"after buying to 3 votes: credits=%d votes=%d, want 9/3\", vs.CreditsUsed, vs.Votes[0])\n\t}\n\n\t// Spending the rest of the 100-credit budget on another option should work\n\t// right up to the edge, then fail past it.\n\tVote(cross(cur), \"1\", 1, 9) // 81 credits, total 90\n\tif vs.CreditsUsed != 90 {\n\t\tt.Fatalf(\"credits used = %d, want 90\", vs.CreditsUsed)\n\t}\n\tif rec := revive(func() { Vote(cross(cur), \"1\", 2, 4) }); rec == nil { // would cost 16 more, total 106 \u003e 100\n\t\tt.Fatal(\"expected panic for exceeding voice-credit budget\")\n\t}\n\n\tp := getPoll(\"1\")\n\tif p.Tally[0] != 3 || p.Tally[1] != 9 {\n\t\tt.Fatalf(\"unexpected tally: %#v\", p.Tally)\n\t}\n}\n\nfunc TestVoteSellBackRefundsCredits(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreatePoll(cross(cur), \"best sea?\", \"north,baltic\")\n\n\tVote(cross(cur), \"1\", 0, 4) // 16 credits, 4 votes\n\tVote(cross(cur), \"1\", 0, -1) // back to 3 votes: cost delta = 9-16 = -7\n\n\tvs := getOrCreateVoter(\"1\", alice, 2)\n\tif vs.Votes[0] != 3 {\n\t\tt.Fatalf(\"votes = %d, want 3\", vs.Votes[0])\n\t}\n\tif vs.CreditsUsed != 9 {\n\t\tt.Fatalf(\"credits used = %d, want 9\", vs.CreditsUsed)\n\t}\n\tif getPoll(\"1\").Tally[0] != 3 {\n\t\tt.Fatalf(\"tally = %d, want 3\", getPoll(\"1\").Tally[0])\n\t}\n\n\tif rec := revive(func() { Vote(cross(cur), \"1\", 0, -10) }); rec == nil {\n\t\tt.Fatal(\"expected panic for selling more votes than held\")\n\t}\n}\n\nfunc TestClosePollOnlyCreator(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreatePoll(cross(cur), \"close me?\", \"yes,no\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tif rec := revive(func() { ClosePoll(cross(cur), \"1\") }); rec == nil {\n\t\tt.Fatal(\"expected panic when a non-creator closes the poll\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClosePoll(cross(cur), \"1\")\n\tif !getPoll(\"1\").Closed {\n\t\tt.Fatal(\"poll should be closed\")\n\t}\n\n\tif rec := revive(func() { Vote(cross(cur), \"1\", 0, 1) }); rec == nil {\n\t\tt.Fatal(\"expected panic when voting on a closed poll\")\n\t}\n}\n\nfunc TestRenderNoPolls(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"no polls yet\") {\n\t\tt.Fatalf(\"expected empty-state message, got: %s\", out)\n\t}\n}\n\nfunc TestRenderPollNotFound(t *testing.T) {\n\tresetState()\n\tout := Render(\"42\")\n\tif !strings.Contains(out, \"No such poll\") {\n\t\tt.Fatalf(\"expected not-found message, got: %s\", out)\n\t}\n}\n\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"55503200","gas_fee":"166509ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"6JIGNsmVVCWq1P3EnmsUBiqXcdHSCRjD0NZUmv/mNVpeB1+c6ZLdybfXqjWGqje1uJdHSDLO/LEqdHsf2H8slQ=="}],"memo":""},"metadata":{"timestamp":"1790961264"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"reactions","path":"gno.land/r/moul/x/daily/reactions/v0","files":[{"name":"README.md","body":"# Reaction Board\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn on-chain emoji reaction board. Each topic collects emoji reactions, and each\ncaller may register at most one reaction per topic (voters are tracked in an AVL\nset). `Render` lists every topic with its emoji tallies and a total count.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/reactions`\n\n## Example calls\n\n```\n# React to a topic (creates the topic on demand). One reaction per caller.\nReact(\"gno 0.9 launch\", \"👍\")\nReact(\"gno 0.9 launch\", \"❤️\")\n\n# Optionally pre-create an empty topic.\nCreateTopic(\"weekend poll\")\n\n# View the board (all topics), or a single topic.\nRender(\"\")\nRender(\"gno 0.9 launch\")\n```\n\nA topic renders as a row like `👍 3  ❤️ 5  🎉 1` (sorted by count, then emoji),\nfollowed by its total. Reacting twice to the same topic from the same address\naborts.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/reactions/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/reactions/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/reactions/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/reactions/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/reactions/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/reactions/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/reactions/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/reactions/v0\"\ngno = \"0.9\"\n"},{"name":"reactions.gno","body":"// Package reactions is an emoji reaction board.\n//\n// Each topic collects emoji reactions. A caller may register at most one\n// reaction per topic; the emoji they picked increments a per-topic per-emoji\n// tally. Render lists every topic with its emoji tallies and total count.\npackage reactions\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// topic holds the tallies and the set of callers who already reacted.\ntype topic struct {\n\tname    string\n\ttallies *avl.Tree // emoji (string) -\u003e count (int)\n\tvoters  *avl.Tree // caller address (string) -\u003e struct{}\n\ttotal   int\n}\n\n// topics maps topic name -\u003e *topic, kept in an avl.Tree for deterministic order.\nvar topics = avl.NewTree()\n\nfunc getOrPanic(name string) *topic {\n\tv := topics.Get(name)\n\tif v == nil {\n\t\tpanic(\"topic does not exist: \" + name)\n\t}\n\treturn v.(*topic)\n}\n\nfunc newTopic(name string) *topic {\n\tt := \u0026topic{\n\t\tname:    name,\n\t\ttallies: avl.NewTree(),\n\t\tvoters:  avl.NewTree(),\n\t}\n\ttopics.Set(name, t)\n\treturn t\n}\n\n// CreateTopic registers a new empty topic. It is optional: React auto-creates\n// a topic if it does not exist yet. Panics if the topic already exists or the\n// name is empty.\nfunc CreateTopic(cur realm, name string) {\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tpanic(\"topic name must not be empty\")\n\t}\n\tif topics.Has(name) {\n\t\tpanic(\"topic already exists: \" + name)\n\t}\n\tnewTopic(name)\n\tchain.Emit(\"TopicCreated\", \"topic\", name)\n}\n\n// React adds the caller's reaction (an emoji) to a topic. Each caller may react\n// at most once per topic. The topic is created on demand if missing. Panics on\n// empty input or when the caller has already reacted to this topic.\nfunc React(cur realm, name, emoji string) {\n\tname = strings.TrimSpace(name)\n\temoji = strings.TrimSpace(emoji)\n\tif name == \"\" {\n\t\tpanic(\"topic name must not be empty\")\n\t}\n\tif emoji == \"\" {\n\t\tpanic(\"emoji must not be empty\")\n\t}\n\n\tcaller := unsafe.PreviousRealm().Address().String()\n\n\tvar t *topic\n\tif v := topics.Get(name); v != nil {\n\t\tt = v.(*topic)\n\t} else {\n\t\tt = newTopic(name)\n\t}\n\n\tif t.voters.Has(caller) {\n\t\tpanic(\"caller already reacted to this topic: \" + name)\n\t}\n\tt.voters.Set(caller, struct{}{})\n\n\tcount := 0\n\tif v := t.tallies.Get(emoji); v != nil {\n\t\tcount = v.(int)\n\t}\n\tt.tallies.Set(emoji, count+1)\n\tt.total++\n\n\tchain.Emit(\"Reacted\", \"topic\", name, \"emoji\", emoji)\n}\n\n// TopicCount returns the number of topics on the board.\nfunc TopicCount() int {\n\treturn topics.Size()\n}\n\n// emojiTally is used to sort a topic's tallies deterministically.\ntype emojiTally struct {\n\temoji string\n\tcount int\n}\n\n// byCountDesc sorts tallies by count descending, then emoji ascending.\ntype byCountDesc []emojiTally\n\nfunc (s byCountDesc) Len() int      { return len(s) }\nfunc (s byCountDesc) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s byCountDesc) Less(i, j int) bool {\n\tif s[i].count != s[j].count {\n\t\treturn s[i].count \u003e s[j].count\n\t}\n\treturn s[i].emoji \u003c s[j].emoji\n}\n\nfunc (t *topic) sortedTallies() []emojiTally {\n\tout := make([]emojiTally, 0, t.tallies.Size())\n\tt.tallies.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tout = append(out, emojiTally{emoji: key, count: value.(int)})\n\t\treturn false\n\t})\n\tsort.Stable(byCountDesc(out))\n\treturn out\n}\n\n// tallyRow renders a topic's tallies as e.g. \"👍 3  ❤️ 5  🎉 1\".\nfunc (t *topic) tallyRow() string {\n\tif t.tallies.Size() == 0 {\n\t\treturn \"_no reactions yet_\"\n\t}\n\trows := t.sortedTallies()\n\tparts := make([]string, 0, len(rows))\n\tfor _, r := range rows {\n\t\tparts = append(parts, r.emoji+\" \"+strconv.Itoa(r.count))\n\t}\n\treturn strings.Join(parts, \"  \")\n}\n\n// Render returns a Markdown view of the board. If path is a non-empty topic\n// name, only that topic is shown; otherwise all topics are listed.\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(strings.Trim(path, \"/\"))\n\n\tif path != \"\" {\n\t\tv := topics.Get(path)\n\t\tif v == nil {\n\t\t\treturn \"# Reaction Board\\n\\nTopic not found: `\" + path + \"`\\n\"\n\t\t}\n\t\tt := v.(*topic)\n\t\tvar sb strings.Builder\n\t\tsb.WriteString(\"# Reaction Board — \" + t.name + \"\\n\\n\")\n\t\tsb.WriteString(t.tallyRow() + \"\\n\\n\")\n\t\tsb.WriteString(\"**Total reactions:** \" + strconv.Itoa(t.total) + \"\\n\")\n\t\treturn sb.String()\n\t}\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Reaction Board\\n\\n\")\n\tif topics.Size() == 0 {\n\t\tsb.WriteString(\"_No topics yet. Call `React(cur, topic, emoji)` to start._\\n\")\n\t\treturn sb.String()\n\t}\n\n\tgrand := 0\n\ttopics.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tt := value.(*topic)\n\t\tgrand += t.total\n\t\tsb.WriteString(\"## \" + t.name + \"\\n\\n\")\n\t\tsb.WriteString(t.tallyRow() + \"\\n\\n\")\n\t\tsb.WriteString(\"Total: \" + strconv.Itoa(t.total) + \"\\n\\n\")\n\t\treturn false\n\t})\n\n\tsb.WriteString(\"---\\n\\n\")\n\tsb.WriteString(\"**Topics:** \" + strconv.Itoa(topics.Size()) +\n\t\t\" · **Reactions:** \" + strconv.Itoa(grand) + \"\\n\")\n\treturn sb.String()\n}\n"},{"name":"reactions_test.gno","body":"package reactions\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestReactAndRender(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReact(cross(cur),\"launch\", \"👍\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tReact(cross(cur),\"launch\", \"❤️\")\n\n\tif got := TopicCount(); got != 1 {\n\t\tt.Fatalf(\"expected 1 topic, got %d\", got)\n\t}\n\n\tout := Render(\"launch\")\n\tif !strings.Contains(out, \"👍 1\") {\n\t\tt.Fatalf(\"expected '👍 1' in render, got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"❤️ 1\") {\n\t\tt.Fatalf(\"expected '❤️ 1' in render, got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"Total reactions:** 2\") {\n\t\tt.Fatalf(\"expected total 2 in render, got:\\n%s\", out)\n\t}\n}\n\nfunc TestOneReactionPerCaller(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReact(cross(cur),\"topicA\", \"🎉\")\n\n\t// Second reaction by same caller to same topic must abort.\n\tuassert.AbortsWithMessage(t, cur, \"caller already reacted to this topic: topicA\", func() {\n\t\tReact(cross(cur),\"topicA\", \"😀\")\n\t})\n}\n\nfunc TestCreateTopicAndDuplicate(cur realm, t *testing.T) {\n\tdave := testutils.TestAddress(\"dave\")\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\n\tCreateTopic(cross(cur),\"poll\")\n\tif !topics.Has(\"poll\") {\n\t\tt.Fatalf(\"expected topic 'poll' to exist\")\n\t}\n\n\tuassert.AbortsWithMessage(t, cur, \"topic already exists: poll\", func() {\n\t\tCreateTopic(cross(cur),\"poll\")\n\t})\n\n\t// A freshly created topic renders as having no reactions.\n\tout := Render(\"poll\")\n\tif !strings.Contains(out, \"no reactions yet\") {\n\t\tt.Fatalf(\"expected empty-topic notice, got:\\n%s\", out)\n\t}\n}\n\nfunc TestTallyRowOrdering(cur realm, t *testing.T) {\n\ta := testutils.TestAddress(\"u1\")\n\tb := testutils.TestAddress(\"u2\")\n\tc := testutils.TestAddress(\"u3\")\n\n\ttesting.SetRealm(testing.NewUserRealm(a))\n\tReact(cross(cur),\"party\", \"🎉\")\n\ttesting.SetRealm(testing.NewUserRealm(b))\n\tReact(cross(cur),\"party\", \"🎉\")\n\ttesting.SetRealm(testing.NewUserRealm(c))\n\tReact(cross(cur),\"party\", \"👍\")\n\n\tout := Render(\"party\")\n\t// 🎉 has 2, 👍 has 1 — 🎉 must come first (count desc).\n\tiParty := strings.Index(out, \"🎉 2\")\n\tiThumb := strings.Index(out, \"👍 1\")\n\tif iParty \u003c 0 || iThumb \u003c 0 {\n\t\tt.Fatalf(\"expected both tallies in render, got:\\n%s\", out)\n\t}\n\tif iParty \u003e iThumb {\n\t\tt.Fatalf(\"expected 🎉 before 👍 by count, got:\\n%s\", out)\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"38431600","gas_fee":"115294ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"FVZx1WdbvIokwAEGaPlRsRZ3inrcXXi7ZruGT9dTmPgK7Im4mDstsOJCJMkuIj6vfVZSSIeHb3U0d7+pWqfFvw=="}],"memo":""},"metadata":{"timestamp":"1790961265"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ringbufferdemo","path":"gno.land/r/moul/x/daily/ringbufferdemo/v0","files":[{"name":"README.md","body":"# Ring Buffer\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nPushes six entries into a buffer of capacity four and renders, step by step,\nwhat survived and what each overflowing push evicted.\n\nDemo of the [`p/moul/x/daily/ringbuffer`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/ringbuffer)\nlibrary — this realm holds no buffer logic of its own. Stateless, so `Render`\nis fully deterministic.\n\nShowing the evicted value in its own column is deliberate: it is the part of the\nAPI that keeps a rolling window from dropping data silently.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/ringbufferdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringbufferdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/ringbufferdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringbufferdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/ringbufferdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringbufferdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/ringbufferdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringbufferdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/ringbufferdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/ringbufferdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/ringbufferdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package ringbufferdemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Ring Buffer\n\t//\n\t// A fixed-capacity FIFO that overwrites its oldest entry, demoing the [`p/moul/x/daily/ringbuffer`](/p/moul/x/daily/ringbuffer/v0) library.\n\t//\n\t// Capacity **4**, pushing 6 entries:\n\t//\n\t// | push | evicted | contents (oldest → newest) |\n\t// |---|---|---|\n\t// | `alpha` | — | `alpha` |\n\t// | `bravo` | — | `alpha bravo` |\n\t// | `charlie` | — | `alpha bravo charlie` |\n\t// | `delta` | — | `alpha bravo charlie delta` |\n\t// | `echo` | `alpha` | `bravo charlie delta echo` |\n\t// | `foxtrot` | `bravo` | `charlie delta echo foxtrot` |\n\t//\n\t// \u003e The buffer never grows: once full, each push costs the oldest entry. On chain that bound is the point — an unbounded queue is an unbounded storage bill.\n}\n"},{"name":"ringbufferdemo.gno","body":"// Package ringbufferdemo is a small gnoweb demo of the fixed-capacity FIFO\n// provided by the [p/moul/x/daily/ringbuffer](/p/moul/x/daily/ringbuffer/v0)\n// library: it pushes more entries than the buffer can hold and shows what\n// survives, plus what each overflowing push evicted.\n//\n// It contains no buffer logic of its own. Stateless, so Render is deterministic.\npackage ringbufferdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/ringbuffer/v0\"\n)\n\nconst capacity = 4\n\nvar feed = []string{\"alpha\", \"bravo\", \"charlie\", \"delta\", \"echo\", \"foxtrot\"}\n\n// Render renders the demo for gnoweb.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Ring Buffer\\n\\n\")\n\tb.WriteString(\"A fixed-capacity FIFO that overwrites its oldest entry, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/ringbuffer`](/p/moul/x/daily/ringbuffer/v0) library.\\n\\n\")\n\tb.WriteString(\"Capacity **\")\n\tb.WriteString(strconv.Itoa(capacity))\n\tb.WriteString(\"**, pushing \")\n\tb.WriteString(strconv.Itoa(len(feed)))\n\tb.WriteString(\" entries:\\n\\n\")\n\tb.WriteString(\"| push | evicted | contents (oldest → newest) |\\n|---|---|---|\\n\")\n\n\tr := ringbuffer.New(capacity)\n\tfor _, v := range feed {\n\t\tev, dropped := r.Push(v)\n\t\tb.WriteString(\"| `\")\n\t\tb.WriteString(v)\n\t\tb.WriteString(\"` | \")\n\t\tif dropped {\n\t\t\tb.WriteString(\"`\" + ev + \"`\")\n\t\t} else {\n\t\t\tb.WriteString(\"—\")\n\t\t}\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(strings.Join(r.Slice(), \" \"))\n\t\tb.WriteString(\"` |\\n\")\n\t}\n\n\tb.WriteString(\"\\n\u003e The buffer never grows: once full, each push costs the oldest entry. \")\n\tb.WriteString(\"On chain that bound is the point — an unbounded queue is an unbounded storage bill.\\n\")\n\treturn b.String()\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"24836200","gas_fee":"74508ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"cvL3t/s8356L6lYxu9mmUazHxZYE9ayAy7etR04GD60VMle4Hyw1a03k0Y5zn22cTwBNdxpaQF7zPnrAgsODwg=="}],"memo":""},"metadata":{"timestamp":"1790961266"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"zEuxMkZ9ba2TfSbauzRyZ1c1cbSQI/PC8s3jJ5Iyx041093pQdOVpKgaMy/Fv5xakD/yN91rcaGuiyjXM5kFgQ=="}],"memo":""},"metadata":{"timestamp":"1790961266"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ringlog","path":"gno.land/r/moul/x/daily/ringlog/v0","files":[{"name":"README.md","body":"# RingLog\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA port of Go's `container/ring` onto gno.land — a fixed-capacity circular message board where new posts automatically evict the oldest once the buffer fills up. Holds the last 16 messages on-chain; no pagination, no clutter.\n\n**Realm:** `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/ringlog`\n\n## How it works\n\nThe realm maintains a 16-slot ring buffer backed by a fixed-size array. `head` tracks the next write position; when it wraps past the end it overwrites the oldest slot. Classic O(1) insert, O(n) read — no allocations after init.\n\n## Transactions\n\n```bash\n# Post a message (up to 280 chars)\ngnokey maketx call -pkgpath \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/ringlog\" \\\n  -func Post -args \"hello gno.land\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 \\\n  -remote https://rpc.sapphire.testnets.gno.land:443 \\\n  \u003ckeyname\u003e\n```\n\n## Queries\n\n```bash\n# View via gnoweb\n\n# Get entries programmatically\ngnokey query vm/qeval \\\n  -remote https://rpc.sapphire.testnets.gno.land:443 \\\n  -data 'gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/ringlog.Len()'\n```\n\n## Capacity\n\nThe buffer holds exactly **16** messages (`Cap = 16`). Once full, the next `Post` silently drops the oldest. This mirrors `container/ring.Ring.Move` with overwrite semantics.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/ringlog/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringlog/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/ringlog/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringlog/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/ringlog/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringlog/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/ringlog/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/ringlog/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/ringlog/v0\"\ngno = \"0.9\"\n"},{"name":"ringlog.gno","body":"// Package ringlog is an on-chain port of Go's container/ring: a fixed-capacity\n// circular message board where new posts overwrite the oldest entries once full.\npackage ringlog\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Cap is the maximum number of messages the ring buffer holds.\nconst Cap = 16\n\n// Entry is a single posted message.\ntype Entry struct {\n\tAuthor  address\n\tMessage string\n\tHeight  int64\n}\n\nvar (\n\tbuf   [Cap]Entry // the ring storage\n\thead  int        // index of the next write slot\n\tcount int        // number of entries currently stored (0 ≤ count ≤ Cap)\n)\n\n// Post adds a message to the ring buffer.\n// Once Cap entries are stored, the oldest entry is overwritten.\nfunc Post(msg string) {\n\tmsg = strings.TrimSpace(msg)\n\tif len(msg) == 0 {\n\t\tpanic(\"message cannot be empty\")\n\t}\n\tif len(msg) \u003e 280 {\n\t\tpanic(\"message too long (max 280 chars)\")\n\t}\n\tbuf[head] = Entry{\n\t\tAuthor:  unsafe.PreviousRealm().Address(),\n\t\tMessage: msg,\n\t\tHeight:  runtime.ChainHeight(),\n\t}\n\thead = (head + 1) % Cap\n\tif count \u003c Cap {\n\t\tcount++\n\t}\n}\n\n// Entries returns all stored messages in chronological order (oldest first).\nfunc Entries() []Entry {\n\tif count == 0 {\n\t\treturn nil\n\t}\n\tresult := make([]Entry, count)\n\toldest := (head - count + Cap) % Cap\n\tfor i := 0; i \u003c count; i++ {\n\t\tresult[i] = buf[(oldest+i)%Cap]\n\t}\n\treturn result\n}\n\n// Len returns the number of messages currently stored.\nfunc Len() int { return count }\n\n// Render displays the ring buffer as a Markdown page.\nfunc Render(path string) string {\n\tvar sb strings.Builder\n\n\tsb.WriteString(\"# RingLog\\n\\n\")\n\tsb.WriteString(\"\u003e A ring-buffer message board (capacity: **\")\n\tsb.WriteString(strconv.Itoa(Cap))\n\tsb.WriteString(\"**). New messages overwrite the oldest once the buffer is full.\\n\\n\")\n\n\tif count == 0 {\n\t\tsb.WriteString(\"*No messages yet. Call `Post(msg)` to add one.*\\n\")\n\t\treturn sb.String()\n\t}\n\n\tsb.WriteString(\"| # | Author | Block | Message |\\n\")\n\tsb.WriteString(\"|---|--------|-------|---------|\\n\")\n\n\tentries := Entries()\n\tfor i, e := range entries {\n\t\tsb.WriteString(\"| \")\n\t\tsb.WriteString(strconv.Itoa(i + 1))\n\t\tsb.WriteString(\" | `\")\n\t\tsb.WriteString(shorten(e.Author.String()))\n\t\tsb.WriteString(\"` | \")\n\t\tsb.WriteString(strconv.FormatInt(e.Height, 10))\n\t\tsb.WriteString(\" | \")\n\t\tsb.WriteString(e.Message)\n\t\tsb.WriteString(\" |\\n\")\n\t}\n\n\tsb.WriteString(\"\\n*Showing \")\n\tsb.WriteString(strconv.Itoa(count))\n\tsb.WriteString(\" of \")\n\tsb.WriteString(strconv.Itoa(Cap))\n\tsb.WriteString(\" slots used.*\\n\")\n\n\treturn sb.String()\n}\n\n// shorten trims a long address for display.\nfunc shorten(s string) string {\n\tif len(s) \u003c= 14 {\n\t\treturn s\n\t}\n\treturn s[:6] + \"…\" + s[len(s)-6:]\n}\n"},{"name":"ringlog_test.gno","body":"package ringlog\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc resetState() {\n\tbuf = [Cap]Entry{}\n\thead = 0\n\tcount = 0\n}\n\nfunc TestPostAndRetrieve(t *testing.T) {\n\tresetState()\n\n\tPost(\"hello world\")\n\n\tif count != 1 {\n\t\tt.Errorf(\"want count=1, got %d\", count)\n\t}\n\tentries := Entries()\n\tif len(entries) != 1 {\n\t\tt.Fatalf(\"want 1 entry, got %d\", len(entries))\n\t}\n\tif entries[0].Message != \"hello world\" {\n\t\tt.Errorf(\"want 'hello world', got %q\", entries[0].Message)\n\t}\n}\n\nfunc TestLen(t *testing.T) {\n\tresetState()\n\n\tif Len() != 0 {\n\t\tt.Errorf(\"want Len()=0, got %d\", Len())\n\t}\n\tPost(\"a\")\n\tPost(\"b\")\n\tPost(\"c\")\n\tif Len() != 3 {\n\t\tt.Errorf(\"want Len()=3, got %d\", Len())\n\t}\n}\n\nfunc TestRingWrap(t *testing.T) {\n\tresetState()\n\n\t// Write Cap+3 messages — the first 3 should be evicted.\n\tfor i := 0; i \u003c Cap+3; i++ {\n\t\tPost(\"msg\" + strconv.Itoa(i))\n\t}\n\n\tif count != Cap {\n\t\tt.Errorf(\"want count=%d after overflow, got %d\", Cap, count)\n\t}\n\n\tentries := Entries()\n\tif len(entries) != Cap {\n\t\tt.Fatalf(\"want %d entries, got %d\", Cap, len(entries))\n\t}\n\n\t// Oldest surviving message should be msg3 (msg0..msg2 were overwritten).\n\tif entries[0].Message != \"msg3\" {\n\t\tt.Errorf(\"oldest entry should be 'msg3', got %q\", entries[0].Message)\n\t}\n\t// Newest message should be msg(Cap+2).\n\twant := \"msg\" + strconv.Itoa(Cap+2)\n\tif entries[Cap-1].Message != want {\n\t\tt.Errorf(\"newest entry should be %q, got %q\", want, entries[Cap-1].Message)\n\t}\n}\n\nfunc TestChronologicalOrder(t *testing.T) {\n\tresetState()\n\n\tmsgs := []string{\"first\", \"second\", \"third\"}\n\tfor _, m := range msgs {\n\t\tPost(m)\n\t}\n\n\tentries := Entries()\n\tfor i, m := range msgs {\n\t\tif entries[i].Message != m {\n\t\t\tt.Errorf(\"entry[%d]: want %q, got %q\", i, m, entries[i].Message)\n\t\t}\n\t}\n}\n\nfunc TestEmptyPanicsOnEmpty(t *testing.T) {\n\tresetState()\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"expected panic on empty message, got none\")\n\t\t}\n\t}()\n\tPost(\"   \")\n}\n\nfunc TestTooLongPanics(t *testing.T) {\n\tresetState()\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"expected panic on too-long message, got none\")\n\t\t}\n\t}()\n\tPost(strings.Repeat(\"x\", 281))\n}\n\nfunc TestRender(t *testing.T) {\n\tresetState()\n\n\tr := Render(\"\")\n\tif !strings.Contains(r, \"No messages yet\") {\n\t\tt.Error(\"empty ring should show 'No messages yet'\")\n\t}\n\n\tPost(\"first message\")\n\tr = Render(\"\")\n\tif !strings.Contains(r, \"first message\") {\n\t\tt.Error(\"render should include 'first message'\")\n\t}\n\tif !strings.Contains(r, \"RingLog\") {\n\t\tt.Error(\"render should include title 'RingLog'\")\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"33504600","gas_fee":"100513ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"FRKo5B3Tr1404vLQFl6Db58ZukLJPRTPf13NtrbF4+FcxhTL6rvIGEguNGmnd4Rx2qhRKXVJ0NclurCVEZhFbQ=="}],"memo":""},"metadata":{"timestamp":"1790961321"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rledemo","path":"gno.land/r/moul/x/daily/rledemo/v0","files":[{"name":"README.md","body":"# Run-Length Encoding\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nEncodes a few samples, round-trips them, and reports the size ratio.\n\n```\n/r/moul/x/daily/rledemo/v0          → the samples table\n/r/moul/x/daily/rledemo/v0:aaabbc   → encode your own text\n```\n\nDemo of the [`p/moul/x/daily/rle`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/rle)\nlibrary — no codec logic lives here. Stateless, so `Render` is deterministic.\n\nThe samples are chosen to show **both** outcomes: `aaaaaaaaaabbbbbbbbbb`\ncompresses to 30%, while `abcdef` expands to 200%. RLE only wins on runny data,\nand the demo shows the counter-example rather than hiding it.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/rledemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rledemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/rledemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rledemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/rledemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rledemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/rledemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rledemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/rledemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/rledemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/rledemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package rledemo\n\n// ExampleRender pins the realm's root Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Run-Length Encoding\n\t//\n\t// `\u003ccount\u003e\u003cchar\u003e` pairs, demoing the [`p/moul/x/daily/rle`](/p/moul/x/daily/rle/v0) library.\n\t//\n\t// | input | encoded | size | round-trips |\n\t// |---|---|---|---|\n\t// | `aaaaaaaaaabbbbbbbbbb` | `10a10b` | 30% | ✅ |\n\t// | `aaabbc` | `3a2b1c` | 100% | ✅ |\n\t// | `abcdef` | `1a1b1c1d1e1f` | 200% | ✅ |\n\t//\n\t// \u003e Over 100% means the encoding made the data **bigger**. RLE only wins on runny input, and `abcdef` is the honest counter-example.\n\t//\n\t// \u003e Append text to the path to encode it — digits are rejected, since they would be ambiguous with a run count.\n}\n\n// ExampleRender_rejectsDigits pins the refusal path: digits cannot be encoded\n// because they are indistinguishable from a run count on the way back.\nfunc ExampleRender_rejectsDigits() {\n\tprint(Render(\"/ab3c\"))\n\t// Output:\n\t// # Run-Length Encoding\n\t//\n\t// `\u003ccount\u003e\u003cchar\u003e` pairs, demoing the [`p/moul/x/daily/rle`](/p/moul/x/daily/rle/v0) library.\n\t//\n\t// ## `ab3c`\n\t//\n\t// _rle: input must not contain digits_\n}\n"},{"name":"rledemo.gno","body":"// Package rledemo is a small gnoweb demo of the run-length codec provided by\n// the [p/moul/x/daily/rle](/p/moul/x/daily/rle/v0) library: it encodes a few\n// sample strings, round-trips them, and reports the size ratio — including the\n// case where the \"compression\" makes things bigger.\n//\n// It contains no codec logic of its own. Stateless, so Render is deterministic.\npackage rledemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/rle/v0\"\n)\n\n// samples are picked to show both outcomes: runny data compresses, data\n// without runs expands.\nvar samples = []string{\n\t\"aaaaaaaaaabbbbbbbbbb\",\n\t\"aaabbc\",\n\t\"abcdef\",\n}\n\n// Render renders the demo for gnoweb.\n//\n//\tRender(\"\")        / Render(\"/\") -\u003e the samples table\n//\tRender(\"/\u003ctext\u003e\")               -\u003e encode that text\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Run-Length Encoding\\n\\n\")\n\tb.WriteString(\"`\u003ccount\u003e\u003cchar\u003e` pairs, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/rle`](/p/moul/x/daily/rle/v0) library.\\n\\n\")\n\n\tif in := parseArg(path); in != \"\" {\n\t\treturn b.String() + one(in)\n\t}\n\n\tb.WriteString(\"| input | encoded | size | round-trips |\\n|---|---|---|---|\\n\")\n\tfor _, s := range samples {\n\t\tenc, err := rle.Encode(s)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdec, _ := rle.Decode(enc)\n\t\tb.WriteString(\"| `\")\n\t\tb.WriteString(s)\n\t\tb.WriteString(\"` | `\")\n\t\tb.WriteString(enc)\n\t\tb.WriteString(\"` | \")\n\t\tb.WriteString(strconv.Itoa(rle.Ratio(s, enc)))\n\t\tb.WriteString(\"% | \")\n\t\tif dec == s {\n\t\t\tb.WriteString(\"✅\")\n\t\t} else {\n\t\t\tb.WriteString(\"❌\")\n\t\t}\n\t\tb.WriteString(\" |\\n\")\n\t}\n\tb.WriteString(\"\\n\u003e Over 100% means the encoding made the data **bigger**. \")\n\tb.WriteString(\"RLE only wins on runny input, and `abcdef` is the honest counter-example.\\n\\n\")\n\tb.WriteString(\"\u003e Append text to the path to encode it — digits are rejected, \")\n\tb.WriteString(\"since they would be ambiguous with a run count.\\n\")\n\treturn b.String()\n}\n\nfunc one(in string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"## `\")\n\tb.WriteString(in)\n\tb.WriteString(\"`\\n\\n\")\n\tenc, err := rle.Encode(in)\n\tif err != nil {\n\t\tb.WriteString(\"_\")\n\t\tb.WriteString(err.Error())\n\t\tb.WriteString(\"_\\n\")\n\t\treturn b.String()\n\t}\n\tdec, _ := rle.Decode(enc)\n\tb.WriteString(\"- encoded: `\")\n\tb.WriteString(enc)\n\tb.WriteString(\"`\\n- size: **\")\n\tb.WriteString(strconv.Itoa(rle.Ratio(in, enc)))\n\tb.WriteString(\"%**\\n- round-trips: \")\n\tif dec == in {\n\t\tb.WriteString(\"✅\\n\")\n\t} else {\n\t\tb.WriteString(\"❌\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc parseArg(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"28138200","gas_fee":"84414ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"6L7qbpffPS4qN8W2a9jNEr1hyVjAY/K9IsoFoJrvrDpuueJktPW3UVEX+e/Mss1+/7vm7XqA8CC47ewob+r05g=="}],"memo":""},"metadata":{"timestamp":"1790961325"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"romannumdemo","path":"gno.land/r/moul/x/daily/romannumdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/romannumdemo/v0`\n\nInteractive gnoweb **demo of the [`p/moul/x/daily/romannum`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/romannum)\nRoman-numeral library** — it renders a table of worked examples and interactive\ninteger→Roman and Roman→integer conversions. It has no conversion logic of its own.\n\n## Render paths\n\n- `:` / root — a table of example conversions (1, 4, 9, 40, 90, 400, 900, 2024, 3999, …).\n- `:/\u003cn\u003e` — integer → Roman, e.g. [`:/2024`](https://gno.land/r/moul/x/daily/romannumdemo/v0:2024) → `MMXXIV`.\n- `:/r/\u003croman\u003e` — Roman → integer, e.g. [`:/r/MMXXIV`](https://gno.land/r/moul/x/daily/romannumdemo/v0:r/MMXXIV) → `2024` (case-insensitive).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/romannumdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/romannumdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/romannumdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/romannumdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/romannumdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/romannumdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/romannumdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/romannumdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/romannumdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/romannumdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/romannumdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package romannumdemo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Roman numeral converter\n\t//\n\t// A tiny demo of the [`p/moul/x/daily/romannum`](/p/moul/x/daily/romannum/v0) library — the classic `ToRoman` / `FromRoman` kata. Pure and deterministic.\n\t//\n\t// ## Examples\n\t//\n\t// | decimal | roman |\n\t// |---:|:---|\n\t// | [1](/r/moul/x/daily/romannumdemo/v0:1) | I |\n\t// | [4](/r/moul/x/daily/romannumdemo/v0:4) | IV |\n\t// | [9](/r/moul/x/daily/romannumdemo/v0:9) | IX |\n\t// | [14](/r/moul/x/daily/romannumdemo/v0:14) | XIV |\n\t// | [40](/r/moul/x/daily/romannumdemo/v0:40) | XL |\n\t// | [49](/r/moul/x/daily/romannumdemo/v0:49) | XLIX |\n\t// | [90](/r/moul/x/daily/romannumdemo/v0:90) | XC |\n\t// | [400](/r/moul/x/daily/romannumdemo/v0:400) | CD |\n\t// | [900](/r/moul/x/daily/romannumdemo/v0:900) | CM |\n\t// | [1994](/r/moul/x/daily/romannumdemo/v0:1994) | MCMXCIV |\n\t// | [2024](/r/moul/x/daily/romannumdemo/v0:2024) | MMXXIV |\n\t// | [3888](/r/moul/x/daily/romannumdemo/v0:3888) | MMMDCCCLXXXVIII |\n\t// | [3999](/r/moul/x/daily/romannumdemo/v0:3999) | MMMCMXCIX |\n\t//\n\t// ## Try it\n\t//\n\t// - `:/\u003cn\u003e` — integer → Roman, e.g. `:/2024` → MMXXIV\n\t// - `:/r/\u003croman\u003e` — Roman → integer, e.g. `:/r/MMXXIV` → 2024\n}\n"},{"name":"romannumdemo.gno","body":"// Package romannumdemo is a small gnoweb demo of the Roman-numeral converter\n// provided by the [p/moul/x/daily/romannum](/p/moul/x/daily/romannum/v0)\n// library: it renders a table of worked examples and interactive\n// integer→Roman and Roman→integer conversions.\n//\n// It contains no conversion logic of its own — everything comes from\n// romannum.ToRoman and romannum.FromRoman.\npackage romannumdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/romannum/v0\"\n)\n\n// examples are the classic milestones shown by the root Render.\nvar examples = []int{1, 4, 9, 14, 40, 49, 90, 400, 900, 1994, 2024, 3888, 3999}\n\n// Render drives gnoweb:\n//   - \"\"        or \"/\"          → a table of example conversions\n//   - \"/\u003cn\u003e\"                    → integer → Roman\n//   - \"/r/\u003croman\u003e\"              → Roman → integer\nfunc Render(path string) string {\n\targ := strings.Trim(strings.TrimSpace(path), \"/\")\n\n\tswitch {\n\tcase arg == \"\":\n\t\treturn renderTable()\n\tcase strings.HasPrefix(strings.ToLower(arg), \"r/\"):\n\t\treturn renderFromRoman(arg[2:])\n\tdefault:\n\t\treturn renderToRoman(arg)\n\t}\n}\n\nfunc renderToRoman(arg string) string {\n\tn, err := strconv.Atoi(strings.TrimSpace(arg))\n\tif err != nil {\n\t\treturn \"# Roman numeral converter\\n\\nCould not parse `\" + arg +\n\t\t\t\"` as an integer.\\n\\n\" + usage()\n\t}\n\tif n \u003c 1 || n \u003e 3999 {\n\t\treturn \"# Roman numeral converter\\n\\n`\" + strconv.Itoa(n) +\n\t\t\t\"` is out of range — Roman numerals here cover **1..3999**.\\n\\n\" + usage()\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + strconv.Itoa(n) + \" → \" + romannum.ToRoman(n) + \"\\n\\n\")\n\tb.WriteString(\"| decimal | roman |\\n|---:|:---|\\n\")\n\tb.WriteString(\"| \" + strconv.Itoa(n) + \" | **\" + romannum.ToRoman(n) + \"** |\\n\\n\")\n\tif n \u003e 1 {\n\t\tb.WriteString(\"[« \" + strconv.Itoa(n-1) + \"](/r/moul/x/daily/romannumdemo/v0:\" +\n\t\t\tstrconv.Itoa(n-1) + \") · \")\n\t}\n\tif n \u003c 3999 {\n\t\tb.WriteString(\"[\" + strconv.Itoa(n+1) + \" »](/r/moul/x/daily/romannumdemo/v0:\" +\n\t\t\tstrconv.Itoa(n+1) + \")\")\n\t}\n\tb.WriteString(\"\\n\\n\" + usage())\n\treturn b.String()\n}\n\nfunc renderFromRoman(arg string) string {\n\targ = strings.TrimSpace(arg)\n\tn, ok := tryFromRoman(arg)\n\tif !ok {\n\t\treturn \"# Roman numeral converter\\n\\n`\" + arg +\n\t\t\t\"` is not a valid Roman numeral (1..3999).\\n\\n\" + usage()\n\t}\n\tup := strings.ToUpper(arg)\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + up + \" → \" + strconv.Itoa(n) + \"\\n\\n\")\n\tb.WriteString(\"| roman | decimal |\\n|:---|---:|\\n\")\n\tb.WriteString(\"| **\" + up + \"** | \" + strconv.Itoa(n) + \" |\\n\\n\")\n\tb.WriteString(usage())\n\treturn b.String()\n}\n\n// tryFromRoman wraps the panic-on-invalid romannum.FromRoman in a panic-free\n// (value, ok) shape, so the demo can report a friendly error for bad input.\nfunc tryFromRoman(s string) (n int, ok bool) {\n\tdefer func() {\n\t\tif recover() != nil {\n\t\t\tn, ok = 0, false\n\t\t}\n\t}()\n\treturn romannum.FromRoman(s), true\n}\n\nfunc renderTable() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Roman numeral converter\\n\\n\")\n\tb.WriteString(\"A tiny demo of the [`p/moul/x/daily/romannum`](/p/moul/x/daily/romannum/v0) \")\n\tb.WriteString(\"library — the classic `ToRoman` / `FromRoman` kata. \")\n\tb.WriteString(\"Pure and deterministic.\\n\\n\")\n\tb.WriteString(\"## Examples\\n\\n\")\n\tb.WriteString(\"| decimal | roman |\\n|---:|:---|\\n\")\n\tfor _, n := range examples {\n\t\tb.WriteString(\"| [\" + strconv.Itoa(n) + \"](/r/moul/x/daily/romannumdemo/v0:\" +\n\t\t\tstrconv.Itoa(n) + \") | \" + romannum.ToRoman(n) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n\" + usage())\n\treturn b.String()\n}\n\nfunc usage() string {\n\treturn \"## Try it\\n\\n\" +\n\t\t\"- `:/\u003cn\u003e` — integer → Roman, e.g. `:/2024` → \" + romannum.ToRoman(2024) + \"\\n\" +\n\t\t\"- `:/r/\u003croman\u003e` — Roman → integer, e.g. `:/r/MMXXIV` → 2024\\n\"\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"30987800","gas_fee":"92963ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"JwffpO7QZXE6eBtm3a8oSTaMVF2pUty/IvIFFpIooX91riEkd4dPt/2xz13dHg7YKj7gHKHgvBQMG+EVxIGW7A=="}],"memo":""},"metadata":{"timestamp":"1790961326"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rot13demo","path":"gno.land/r/moul/x/daily/rot13demo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/rot13demo/v0`\n\nInteractive gnoweb **demo of the [`p/moul/x/daily/rot13`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/rot13)\nROT13 / Caesar library** — it renders an explanation, a worked ROT13 example,\nand path-driven ROT13 and Caesar transforms. It has no cipher logic of its own.\n\nAppend text to the path to ROT13 it, e.g.\n[`/r/moul/x/daily/rot13demo/v0:Uryyb, Tab!`](https://gno.land/r/moul/x/daily/rot13demo/v0:Uryyb,%20Tab!),\nor use `/caesar/\u003cshift\u003e/\u003ctext\u003e` for a general Caesar shift.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/rot13demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rot13demo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/rot13demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rot13demo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/rot13demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rot13demo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/rot13demo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rot13demo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/rot13demo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/rot13demo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/rot13demo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package rot13demo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # ROT13\n\t//\n\t// Demo of the [`p/moul/x/daily/rot13`](/p/moul/x/daily/rot13/v0) library — an on-chain port of Go's classic **ROT13** cipher, the standard-library `strings.Map` / `io.Reader` teaching example. Each ASCII letter is rotated 13 places through the alphabet; everything else is left alone.\n\t//\n\t// Because the alphabet has 26 letters and 13 is exactly half, **ROT13 is its own inverse** — encoding twice returns the original text.\n\t//\n\t// ## Example\n\t//\n\t// | stage | text |\n\t// |---|---|\n\t// | input | `Hello, Gno!` |\n\t// | ROT13 | `Uryyb, Tab!` |\n\t// | ROT13 again | `Hello, Gno!` |\n\t//\n\t// ## Try it\n\t//\n\t// - `Render(\"/Uryyb, Tab!\")` — decode any text (append it to the path).\n\t// - `Render(\"/caesar/3/attack at dawn\")` — a general Caesar shift.\n\t//\n\t// Or call the library functions directly:\n\t//\n\t// ```go\n\t// rot13.Rot13(\"Hello, Gno!\")     // \"Uryyb, Tab!\"\n\t// rot13.Caesar(\"attack\", 3)      // \"dwwdfn\"\n\t// rot13.Caesar(\"Hello\", 13)      // same as Rot13: \"Uryyb\"\n\t// ```\n}\n"},{"name":"rot13demo.gno","body":"// Package rot13demo is a small gnoweb demo of the ROT13 / Caesar cipher\n// provided by the [p/moul/x/daily/rot13](/p/moul/x/daily/rot13/v0) library: it\n// renders an explanation, a worked ROT13 example, and interactive path-driven\n// ROT13 and Caesar transforms.\n//\n// It contains no cipher logic of its own — everything comes from `rot13.Rot13`\n// and `rot13.Caesar`. Render reads its input straight from the gnoweb path.\npackage rot13demo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/rot13/v0\"\n)\n\n// hexNibble decodes a single hex digit, returning -1 if invalid.\nfunc hexNibble(b byte) int {\n\tswitch {\n\tcase b \u003e= '0' \u0026\u0026 b \u003c= '9':\n\t\treturn int(b - '0')\n\tcase b \u003e= 'a' \u0026\u0026 b \u003c= 'f':\n\t\treturn int(b-'a') + 10\n\tcase b \u003e= 'A' \u0026\u0026 b \u003c= 'F':\n\t\treturn int(b-'A') + 10\n\t}\n\treturn -1\n}\n\n// percentDecode turns \"%20\"/\"+\" style path escapes back into readable text so\n// gnoweb links with spaces or punctuation round-trip nicely. Invalid escapes\n// are left verbatim.\nfunc percentDecode(s string) string {\n\tvar sb strings.Builder\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c == '+':\n\t\t\tsb.WriteByte(' ')\n\t\tcase c == '%' \u0026\u0026 i+2 \u003c len(s):\n\t\t\thi, lo := hexNibble(s[i+1]), hexNibble(s[i+2])\n\t\t\tif hi \u003e= 0 \u0026\u0026 lo \u003e= 0 {\n\t\t\t\tsb.WriteByte(byte(hi\u003c\u003c4 | lo))\n\t\t\t\ti += 2\n\t\t\t} else {\n\t\t\t\tsb.WriteByte(c)\n\t\t\t}\n\t\tdefault:\n\t\t\tsb.WriteByte(c)\n\t\t}\n\t}\n\treturn sb.String()\n}\n\n// Render is the gnoweb entry point (not a crossing call).\n//\n//\tRender(\"\")                 -\u003e explanation + a worked example\n//\tRender(\"/Hello, Gno!\")     -\u003e the input and its ROT13\n//\tRender(\"/caesar/3/attack\") -\u003e a Caesar shift of 3 applied to \"attack\"\nfunc Render(path string) string {\n\tp := strings.TrimPrefix(path, \"/\")\n\n\t// Caesar sub-path: /caesar/\u003cshift\u003e/\u003ctext\u003e\n\tif rest, ok := strings.CutPrefix(p, \"caesar/\"); ok {\n\t\tshiftStr, text, found := strings.Cut(rest, \"/\")\n\t\tif !found {\n\t\t\treturn renderRoot() + \"\\n\u003e Usage: `/caesar/\u003cshift\u003e/\u003ctext\u003e` — e.g. `/caesar/3/attack%20at%20dawn`\\n\"\n\t\t}\n\t\tshift, err := strconv.Atoi(shiftStr)\n\t\tif err != nil {\n\t\t\treturn renderRoot() + \"\\n\u003e `\" + shiftStr + \"` is not a valid integer shift.\\n\"\n\t\t}\n\t\ttext = percentDecode(text)\n\t\treturn renderCaesar(text, shift)\n\t}\n\n\tif p == \"\" {\n\t\treturn renderRoot()\n\t}\n\n\treturn renderRot13(percentDecode(p))\n}\n\nfunc renderRoot() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# ROT13\\n\\n\")\n\tsb.WriteString(\"Demo of the [`p/moul/x/daily/rot13`](/p/moul/x/daily/rot13/v0) library — \")\n\tsb.WriteString(\"an on-chain port of Go's classic **ROT13** cipher, the standard-library \")\n\tsb.WriteString(\"`strings.Map` / `io.Reader` teaching example. Each ASCII letter is rotated \")\n\tsb.WriteString(\"13 places through the alphabet; everything else is left alone.\\n\\n\")\n\tsb.WriteString(\"Because the alphabet has 26 letters and 13 is exactly half, **ROT13 is its \")\n\tsb.WriteString(\"own inverse** — encoding twice returns the original text.\\n\\n\")\n\n\tconst demo = \"Hello, Gno!\"\n\tenc := rot13.Rot13(demo)\n\tsb.WriteString(\"## Example\\n\\n\")\n\tsb.WriteString(\"| stage | text |\\n|---|---|\\n\")\n\tsb.WriteString(\"| input | `\" + demo + \"` |\\n\")\n\tsb.WriteString(\"| ROT13 | `\" + enc + \"` |\\n\")\n\tsb.WriteString(\"| ROT13 again | `\" + rot13.Rot13(enc) + \"` |\\n\\n\")\n\n\tsb.WriteString(\"## Try it\\n\\n\")\n\tsb.WriteString(\"- `Render(\\\"/Uryyb, Tab!\\\")` — decode any text (append it to the path).\\n\")\n\tsb.WriteString(\"- `Render(\\\"/caesar/3/attack at dawn\\\")` — a general Caesar shift.\\n\\n\")\n\tsb.WriteString(\"Or call the library functions directly:\\n\\n\")\n\tsb.WriteString(\"```go\\n\")\n\tsb.WriteString(\"rot13.Rot13(\\\"Hello, Gno!\\\")     // \" + strconv.Quote(enc) + \"\\n\")\n\tsb.WriteString(\"rot13.Caesar(\\\"attack\\\", 3)      // \" + strconv.Quote(rot13.Caesar(\"attack\", 3)) + \"\\n\")\n\tsb.WriteString(\"rot13.Caesar(\\\"Hello\\\", 13)      // same as Rot13: \" + strconv.Quote(rot13.Caesar(\"Hello\", 13)) + \"\\n\")\n\tsb.WriteString(\"```\\n\")\n\treturn sb.String()\n}\n\nfunc renderRot13(text string) string {\n\tenc := rot13.Rot13(text)\n\tvar sb strings.Builder\n\tsb.WriteString(\"# ROT13\\n\\n\")\n\tsb.WriteString(\"| stage | text |\\n|---|---|\\n\")\n\tsb.WriteString(\"| input | `\" + text + \"` |\\n\")\n\tsb.WriteString(\"| ROT13 | `\" + enc + \"` |\\n\\n\")\n\tsb.WriteString(\"_ROT13 is its own inverse — running it on the output above gives back the input._\\n\\n\")\n\tsb.WriteString(\"[Back to overview](/r/moul/x/daily/rot13demo/v0:)\\n\")\n\treturn sb.String()\n}\n\nfunc renderCaesar(text string, shift int) string {\n\tenc := rot13.Caesar(text, shift)\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Caesar shift \" + strconv.Itoa(shift) + \"\\n\\n\")\n\tsb.WriteString(\"| stage | text |\\n|---|---|\\n\")\n\tsb.WriteString(\"| input | `\" + text + \"` |\\n\")\n\tsb.WriteString(\"| shifted | `\" + enc + \"` |\\n\\n\")\n\tsb.WriteString(\"_Decode with the opposite shift: `/caesar/\" + strconv.Itoa(-shift) + \"/...`._\\n\\n\")\n\tsb.WriteString(\"[Back to overview](/r/moul/x/daily/rot13demo/v0:)\\n\")\n\treturn sb.String()\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"33021000","gas_fee":"99063ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"dI32FHBzC5wxeIoShXDMG9BH0B3p+RnG71/jGynnxE80bhYffkJJ3C9LL7KLk45mzh1n4wO8X7NAkpEFRIP+1Q=="}],"memo":""},"metadata":{"timestamp":"1790961326"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rpgroom","path":"gno.land/r/moul/x/daily/rpgroom/v0","files":[{"name":"README.md","body":"# RPG Room\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA tiny shared on-chain dungeon room: everyone fights the same resident monster. Spawn a hero, Attack to chip away at the monster (or get hit back), Rest to heal, Revive if you fall. Every kill replaces the monster with a tougher one and grants XP/gold/level-ups, so the room escalates as the community grinds through it together, with a live leaderboard ranking every hero.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/rpgroom/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpgroom/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/rpgroom/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpgroom/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/rpgroom/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpgroom/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/rpgroom/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpgroom/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/rpgroom/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/rpgroom/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/rpgroom/v0\"\ngno = \"0.9\"\n"},{"name":"render_test.gno","body":"package rpgroom\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// ExampleRender pins the empty-room view. resetState() puts the realm back to\n// its init() shape, so the example does not depend on test ordering.\nfunc ExampleRender() {\n\tresetState()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # RPG Room\n\t//\n\t// A single dungeon room with one monster in it at a time. Call `Spawn(\"name\")` to enter, `Attack()` to fight the resident monster, `Rest()` to heal up, and `Revive()` if you fall.\n\t//\n\t// ## Current monster\n\t//\n\t// **Slime** — level 1\n\t//\n\t// `##########` 35/35 HP\n\t//\n\t// - Attack: 5\n\t// - Monsters cleared so far: 0\n\t//\n\t// ## Leaderboard\n\t//\n\t// _No heroes yet. Be the first: `Spawn(\"name\")`._\n}\n\n// TestRenderLeaderboard checks spawned heroes replace the empty notice and are\n// listed in rank order.\nfunc TestRenderLeaderboard(cur realm, t *testing.T) {\n\tresetState()\n\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\tSpawn(cross(cur), \"Alice the Bold\")\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bob\")))\n\tSpawn(cross(cur), \"Bob the Brave\")\n\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, \"_No heroes yet\"), \"empty notice should be gone\")\n\tuassert.True(t, strings.Contains(out, \"| # | Hero | Lvl | HP | Kills | Gold | Status |\"),\n\t\t\"leaderboard header should render\")\n\tuassert.True(t, strings.Contains(out, \"Alice the Bold\"), \"alice should be listed\")\n\tuassert.True(t, strings.Contains(out, \"Bob the Brave\"), \"bob should be listed\")\n\tuassert.True(t, strings.Contains(out, \"| alive |\"), \"a fresh hero is alive\")\n}\n\n// TestRenderHeroPage checks the per-address detail route.\nfunc TestRenderHeroPage(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSpawn(cross(cur), \"Alice the Bold\")\n\n\tout := Render(alice.String())\n\tuassert.True(t, strings.HasPrefix(out, \"# Alice the Bold\\n\"), \"hero page should be titled by name\")\n\tuassert.True(t, strings.Contains(out, \"- Level: 1\\n\"), \"level should be shown\")\n\tuassert.True(t, strings.Contains(out, \"- Kills: 0\\n\"), \"kills should be shown\")\n\tuassert.True(t, strings.Contains(out, \"- Gold: 0\\n\"), \"gold should be shown\")\n\tuassert.False(t, strings.Contains(out, \"- Status: fallen\"), \"a live hero has no fallen status\")\n}\n\n// TestRenderUnknownHero covers the not-found branch of the detail route.\nfunc TestRenderUnknownHero(t *testing.T) {\n\tresetState()\n\tstranger := testutils.TestAddress(\"stranger\").String()\n\n\tuassert.Equal(t, \"\u003e [!WARNING]\\n\u003e No hero found for `\"+stranger+\"`.\\n\", Render(stranger))\n}\n\n// TestRenderTrimsPath checks surrounding whitespace still routes to the room.\nfunc TestRenderTrimsPath(t *testing.T) {\n\tresetState()\n\tuassert.Equal(t, Render(\"\"), Render(\"   \"))\n}\n\n// TestRenderMonsterHPBar checks the monster's bar tracks damage.\nfunc TestRenderMonsterHPBar(t *testing.T) {\n\tresetState()\n\tmonster.HP = monster.MaxHP / 2\n\n\tuassert.True(t, strings.Contains(Render(\"\"), hpBar(monster.HP, monster.MaxHP)),\n\t\t\"the room should render the monster's current HP bar\")\n}\n"},{"name":"rpgroom.gno","body":"// Package rpgroom is a tiny single-room on-chain RPG. There is exactly one\n// monster in the room at a time. Spawn a hero, take a swing, and see what\n// happens: land the killing blow and the room's monster gets replaced by a\n// tougher one while your hero gains XP, gold, and (eventually) a level; get\n// hit hard enough and your hero falls until it's revived. A room-wide\n// leaderboard tracks who has climbed the highest.\npackage rpgroom\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Hero is one player's on-chain character in the room.\ntype Hero struct {\n\tName   string\n\tLevel  int\n\tXP     int\n\tHP     int\n\tMaxHP  int\n\tAttack int\n\tKills  int\n\tGold   int\n\tAlive  bool\n}\n\n// Monster is the room's current resident.\ntype Monster struct {\n\tName   string\n\tLevel  int\n\tHP     int\n\tMaxHP  int\n\tAttack int\n}\n\nvar (\n\theroes     avl.Tree // address string -\u003e *Hero\n\tmonster    *Monster\n\troomLevel  int\n\ttotalKills int\n)\n\nvar monsterNames = []string{\n\t\"Slime\", \"Giant Rat\", \"Goblin\", \"Skeleton\", \"Cave Bat\",\n\t\"Orc Grunt\", \"Wraith\", \"Stone Troll\", \"Dread Wolf\", \"Young Dragon\",\n}\n\nfunc init() {\n\troomLevel = 1\n\tmonster = spawnMonster(roomLevel)\n}\n\nfunc spawnMonster(level int) *Monster {\n\tname := monsterNames[(level-1)%len(monsterNames)]\n\thp := 20 + level*15\n\treturn \u0026Monster{\n\t\tName:   name,\n\t\tLevel:  level,\n\t\tHP:     hp,\n\t\tMaxHP:  hp,\n\t\tAttack: 3 + level*2,\n\t}\n}\n\n// Spawn creates the caller's hero in the room. Each address gets exactly one\n// hero; call Revive (not Spawn again) if it dies.\nfunc Spawn(cur realm, name string) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only a direct EOA call can spawn a hero\")\n\t}\n\tname = strings.TrimSpace(name)\n\tif name == \"\" {\n\t\tpanic(\"name required\")\n\t}\n\tif len(name) \u003e 24 {\n\t\tpanic(\"name too long (max 24 chars)\")\n\t}\n\taddr := cur.Previous().Address().String()\n\tif heroes.Has(addr) {\n\t\tpanic(\"you already have a hero in this room\")\n\t}\n\theroes.Set(addr, \u0026Hero{\n\t\tName:   name,\n\t\tLevel:  1,\n\t\tHP:     30,\n\t\tMaxHP:  30,\n\t\tAttack: 5,\n\t\tAlive:  true,\n\t})\n\tchain.Emit(\"HeroSpawned\", \"addr\", addr, \"name\", name)\n}\n\n// Attack swings the caller's hero at the room's current monster. Killing it\n// grants XP and gold and replaces it with a tougher one; otherwise the\n// monster strikes back.\nfunc Attack(cur realm) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only a direct EOA call can attack\")\n\t}\n\taddr := cur.Previous().Address().String()\n\tv := heroes.Get(addr)\n\tif v == nil {\n\t\tpanic(\"no hero found; call Spawn first\")\n\t}\n\thero := v.(*Hero)\n\tif !hero.Alive {\n\t\tpanic(\"your hero is dead; call Revive first\")\n\t}\n\n\tdmg := hero.Attack\n\tif runtime.ChainHeight()%7 == 0 {\n\t\tdmg *= 2 // occasional critical hit, tied to block height parity\n\t}\n\tmonster.HP -= dmg\n\tchain.Emit(\"HeroAttacked\", \"addr\", addr, \"damage\", strconv.Itoa(dmg), \"monsterHP\", strconv.Itoa(monster.HP))\n\n\tif monster.HP \u003c= 0 {\n\t\treward := monster.Level * 10\n\t\tgained := monster.Level * 20\n\t\thero.Gold += reward\n\t\thero.XP += gained\n\t\thero.Kills++\n\t\tlevelUp(hero)\n\t\tchain.Emit(\"MonsterSlain\", \"addr\", addr, \"monster\", monster.Name, \"level\", strconv.Itoa(monster.Level))\n\n\t\ttotalKills++\n\t\troomLevel++\n\t\tmonster = spawnMonster(roomLevel)\n\t\treturn\n\t}\n\n\thero.HP -= monster.Attack\n\tif hero.HP \u003c= 0 {\n\t\thero.HP = 0\n\t\thero.Alive = false\n\t\tchain.Emit(\"HeroDied\", \"addr\", addr, \"monster\", monster.Name)\n\t}\n}\n\n// Rest heals the caller's hero for a quarter of its max HP.\nfunc Rest(cur realm) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only a direct EOA call can rest\")\n\t}\n\taddr := cur.Previous().Address().String()\n\tv := heroes.Get(addr)\n\tif v == nil {\n\t\tpanic(\"no hero found; call Spawn first\")\n\t}\n\thero := v.(*Hero)\n\tif !hero.Alive {\n\t\tpanic(\"your hero is dead; call Revive first\")\n\t}\n\tif hero.HP \u003e= hero.MaxHP {\n\t\tpanic(\"already at full health\")\n\t}\n\theal := hero.MaxHP / 4\n\tif heal \u003c 1 {\n\t\theal = 1\n\t}\n\thero.HP += heal\n\tif hero.HP \u003e hero.MaxHP {\n\t\thero.HP = hero.MaxHP\n\t}\n\tchain.Emit(\"HeroRested\", \"addr\", addr, \"hp\", strconv.Itoa(hero.HP))\n}\n\n// Revive brings a fallen hero back at half max HP.\nfunc Revive(cur realm) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only a direct EOA call can revive\")\n\t}\n\taddr := cur.Previous().Address().String()\n\tv := heroes.Get(addr)\n\tif v == nil {\n\t\tpanic(\"no hero found; call Spawn first\")\n\t}\n\thero := v.(*Hero)\n\tif hero.Alive {\n\t\tpanic(\"your hero is not dead\")\n\t}\n\thero.Alive = true\n\thero.HP = hero.MaxHP / 2\n\tif hero.HP \u003c 1 {\n\t\thero.HP = 1\n\t}\n\tchain.Emit(\"HeroRevived\", \"addr\", addr, \"hp\", strconv.Itoa(hero.HP))\n}\n\n// levelUp applies every level-up a hero's current XP qualifies for. The\n// threshold to reach level N+1 from level N is N*50 XP.\nfunc levelUp(h *Hero) {\n\tfor h.XP \u003e= h.Level*50 {\n\t\th.XP -= h.Level * 50\n\t\th.Level++\n\t\th.MaxHP += 10\n\t\th.HP = h.MaxHP\n\t\th.Attack += 3\n\t}\n}\n\n// byRank orders heroes for the leaderboard: highest level first, then XP,\n// then kills, as a tiebreaker.\ntype byRank []*Hero\n\nfunc (r byRank) Len() int      { return len(r) }\nfunc (r byRank) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byRank) Less(i, j int) bool {\n\tif r[i].Level != r[j].Level {\n\t\treturn r[i].Level \u003e r[j].Level\n\t}\n\tif r[i].XP != r[j].XP {\n\t\treturn r[i].XP \u003e r[j].XP\n\t}\n\treturn r[i].Kills \u003e r[j].Kills\n}\n\nfunc collectHeroes() []*Hero {\n\tvar out []*Hero\n\theroes.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tout = append(out, value.(*Hero))\n\t\treturn false\n\t})\n\treturn out\n}\n\nfunc hpBar(hp, maxHP int) string {\n\tif maxHP \u003c= 0 {\n\t\tmaxHP = 1\n\t}\n\tfilled := hp * 10 / maxHP\n\tif filled \u003c 0 {\n\t\tfilled = 0\n\t}\n\tif filled \u003e 10 {\n\t\tfilled = 10\n\t}\n\tbar := strings.Repeat(\"#\", filled) + strings.Repeat(\"-\", 10-filled)\n\treturn \"`\" + bar + \"` \" + strconv.Itoa(hp) + \"/\" + strconv.Itoa(maxHP) + \" HP\"\n}\n\n// Render shows the room overview and leaderboard at path \"\", or a single\n// hero's detail page when path is a bech32 address.\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tif path != \"\" {\n\t\treturn renderHero(path)\n\t}\n\treturn renderRoom()\n}\n\nfunc renderRoom() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# RPG Room\\n\\n\")\n\tb.WriteString(\"A single dungeon room with one monster in it at a time. \")\n\tb.WriteString(\"Call `Spawn(\\\"name\\\")` to enter, `Attack()` to fight the resident monster, \")\n\tb.WriteString(\"`Rest()` to heal up, and `Revive()` if you fall.\\n\\n\")\n\n\tb.WriteString(\"## Current monster\\n\\n\")\n\tb.WriteString(\"**\" + sanitize.InlineText(monster.Name) + \"** — level \" + strconv.Itoa(monster.Level) + \"\\n\\n\")\n\tb.WriteString(hpBar(monster.HP, monster.MaxHP) + \"\\n\\n\")\n\tb.WriteString(\"- Attack: \" + strconv.Itoa(monster.Attack) + \"\\n\")\n\tb.WriteString(\"- Monsters cleared so far: \" + strconv.Itoa(totalKills) + \"\\n\\n\")\n\n\tb.WriteString(\"## Leaderboard\\n\\n\")\n\tall := collectHeroes()\n\tif len(all) == 0 {\n\t\tb.WriteString(\"_No heroes yet. Be the first: `Spawn(\\\"name\\\")`._\\n\")\n\t\treturn b.String()\n\t}\n\tsort.Sort(byRank(all))\n\tb.WriteString(\"| # | Hero | Lvl | HP | Kills | Gold | Status |\\n\")\n\tb.WriteString(\"|---|---|---|---|---|---|---|\\n\")\n\tlimit := len(all)\n\tif limit \u003e 20 {\n\t\tlimit = 20\n\t}\n\tfor i := 0; i \u003c limit; i++ {\n\t\th := all[i]\n\t\tstatus := \"alive\"\n\t\tif !h.Alive {\n\t\t\tstatus = \"fallen\"\n\t\t}\n\t\tb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | \" + sanitize.InlineText(h.Name) + \" | \" +\n\t\t\tstrconv.Itoa(h.Level) + \" | \" + strconv.Itoa(h.HP) + \"/\" + strconv.Itoa(h.MaxHP) + \" | \" +\n\t\t\tstrconv.Itoa(h.Kills) + \" | \" + strconv.Itoa(h.Gold) + \" | \" + status + \" |\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderHero(addr string) string {\n\tv := heroes.Get(addr)\n\tif v == nil {\n\t\treturn \"\u003e [!WARNING]\\n\u003e No hero found for `\" + sanitize.InlineText(addr) + \"`.\\n\"\n\t}\n\th := v.(*Hero)\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + sanitize.InlineText(h.Name) + \"\\n\\n\")\n\tb.WriteString(hpBar(h.HP, h.MaxHP) + \"\\n\\n\")\n\tb.WriteString(\"- Level: \" + strconv.Itoa(h.Level) + \"\\n\")\n\tb.WriteString(\"- XP: \" + strconv.Itoa(h.XP) + \" (next level at \" + strconv.Itoa(h.Level*50) + \")\\n\")\n\tb.WriteString(\"- Attack: \" + strconv.Itoa(h.Attack) + \"\\n\")\n\tb.WriteString(\"- Kills: \" + strconv.Itoa(h.Kills) + \"\\n\")\n\tb.WriteString(\"- Gold: \" + strconv.Itoa(h.Gold) + \"\\n\")\n\tif !h.Alive {\n\t\tb.WriteString(\"- Status: fallen — call `Revive()` to return\\n\")\n\t}\n\treturn b.String()\n}\n"},{"name":"rpgroom_test.gno","body":"package rpgroom\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\theroes = avl.Tree{}\n\troomLevel = 1\n\ttotalKills = 0\n\tmonster = spawnMonster(roomLevel)\n}\n\nfunc TestSpawnMonster(t *testing.T) {\n\tm1 := spawnMonster(1)\n\tm5 := spawnMonster(5)\n\tif m1.Level != 1 || m5.Level != 5 {\n\t\tt.Fatal(\"spawnMonster should carry the requested level\")\n\t}\n\tif m5.HP \u003c= m1.HP {\n\t\tt.Fatal(\"a higher-level monster should have more HP\")\n\t}\n\tif m5.Attack \u003c= m1.Attack {\n\t\tt.Fatal(\"a higher-level monster should hit harder\")\n\t}\n}\n\nfunc TestLevelUp(t *testing.T) {\n\th := \u0026Hero{Level: 1, XP: 0, HP: 30, MaxHP: 30, Attack: 5}\n\th.XP = 50 // exactly the level-1 threshold\n\tlevelUp(h)\n\tif h.Level != 2 {\n\t\tt.Fatalf(\"Level = %d, want 2\", h.Level)\n\t}\n\tif h.XP != 0 {\n\t\tt.Fatalf(\"XP = %d, want 0 (fully consumed)\", h.XP)\n\t}\n\tif h.MaxHP != 40 || h.HP != 40 {\n\t\tt.Fatalf(\"MaxHP/HP = %d/%d, want 40/40 (healed on level up)\", h.MaxHP, h.HP)\n\t}\n\tif h.Attack != 8 {\n\t\tt.Fatalf(\"Attack = %d, want 8\", h.Attack)\n\t}\n}\n\nfunc TestLevelUpMultipleLevels(t *testing.T) {\n\th := \u0026Hero{Level: 1, XP: 200, HP: 30, MaxHP: 30, Attack: 5}\n\tlevelUp(h)\n\t// level 1-\u003e2 costs 50, 2-\u003e3 costs 100: 200 - 50 - 100 = 50 left, still short of 150 for 3-\u003e4\n\tif h.Level != 3 {\n\t\tt.Fatalf(\"Level = %d, want 3\", h.Level)\n\t}\n\tif h.XP != 50 {\n\t\tt.Fatalf(\"XP = %d, want 50 remaining\", h.XP)\n\t}\n}\n\nfunc TestHPBar(t *testing.T) {\n\tfull := hpBar(10, 10)\n\tempty := hpBar(0, 10)\n\tif full == empty {\n\t\tt.Fatal(\"full and empty bars should render differently\")\n\t}\n}\n\n// Crossing: Spawn/Attack/Rest/Revive mutate realm state, so the test needs `cur realm`.\nfunc TestFullHeroLifecycle(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSpawn(cross(cur), \"Alice the Bold\")\n\n\tv := heroes.Get(alice.String())\n\tif v == nil {\n\t\tt.Fatal(\"expected a hero for alice\")\n\t}\n\thero := v.(*Hero)\n\tif hero.Level != 1 || !hero.Alive {\n\t\tt.Fatalf(\"fresh hero should be level 1 and alive, got level=%d alive=%v\", hero.Level, hero.Alive)\n\t}\n\n\t// Grind the starter monster down; it starts at 35 HP with our hero\n\t// hitting for 5 (ignoring the rare crit), so a handful of swings should\n\t// clear it without the hero dying (monster only hits for 5).\n\tstartMonster := monster\n\tfor i := 0; i \u003c 20 \u0026\u0026 monster == startMonster; i++ {\n\t\tif !hero.Alive {\n\t\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\t\tRevive(cross(cur))\n\t\t}\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\tAttack(cross(cur))\n\t}\n\tif monster == startMonster {\n\t\tt.Fatal(\"expected the starter monster to be replaced after repeated attacks\")\n\t}\n\tif hero.Kills \u003c 1 {\n\t\tt.Fatalf(\"Kills = %d, want at least 1\", hero.Kills)\n\t}\n\tif hero.Gold \u003c 1 {\n\t\tt.Fatalf(\"Gold = %d, want at least 1\", hero.Gold)\n\t}\n\tif roomLevel \u003c 2 {\n\t\tt.Fatalf(\"roomLevel = %d, want at least 2 after a kill\", roomLevel)\n\t}\n}\n\nfunc TestDoubleSpawnPanics(cur realm, t *testing.T) {\n\tresetState()\n\tbob := testutils.TestAddress(\"bob\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSpawn(cross(cur), \"Bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\t// Spawn panics inside a cross-realm call; a plain defer/recover in this\n\t// test does not catch a cross-boundary panic, so use revive().\n\trec := revive(func() { Spawn(cross(cur), \"Bob Again\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected a second Spawn for the same address to panic\")\n\t}\n}\n\nfunc TestRestRequiresDamage(cur realm, t *testing.T) {\n\tresetState()\n\tcarol := testutils.TestAddress(\"carol\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tSpawn(cross(cur), \"Carol\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\trec := revive(func() { Rest(cross(cur)) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected Rest at full HP to panic\")\n\t}\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"56738200","gas_fee":"170214ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"oc4heh3zLLZch1Bh9ngaBfvB+9xyMwzzPCW8B/5qeeUQWZsUI54w5bqVIIPIowC0aNYLbcVHlX6mbGyStycKMg=="}],"memo":""},"metadata":{"timestamp":"1790961327"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rps","path":"gno.land/r/moul/x/daily/rps/v1","files":[{"name":"README.md","body":"# Rock-Paper-Scissors\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nPlay rock-paper-scissors against the chain. The house move is computed\ndeterministically from the current block height plus your personal play count,\nthen the round is scored and your win/loss/draw tally is recorded on-chain.\n`Render` shows the caller-agnostic global tally, a per-player results table, and\nthe last few rounds played.\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/rps`\n\n## Example calls\n\n```\n# Play a round (choice: rock|paper|scissors; single letters r|p|s also work)\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/rps\" \\\n  -func Play -args \"rock\" -gas-fee 20000ugnot -gas-wanted 2000000 ...\n\n# View the dashboard\ngnokey query vm/qrender --data \"gno.land/r/REPLACE_ADDR/rps:\"\n```\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/rps) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nVisible change: addresses now render in monospace.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/rps/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rps/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/rps/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rps/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/rps/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rps/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/rps/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rps/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/rps/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/rps/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/rps/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"rps.gno","body":"package rps\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Moves.\nconst (\n\trock     = 0\n\tpaper    = 1\n\tscissors = 2\n)\n\nvar moveNames = [3]string{\"rock\", \"paper\", \"scissors\"}\n\n// Outcomes.\nconst (\n\toutLose = 0 // player loses\n\toutDraw = 1\n\toutWin  = 2 // player wins\n)\n\n// tally holds a single player's cumulative record.\ntype tally struct {\n\twins   int\n\tlosses int\n\tdraws  int\n\tplays  int // total rounds this player has played (drives entropy)\n}\n\n// round is one recorded game (for the recent-rounds table).\ntype round struct {\n\tplayer   address\n\theight   int64\n\tplayer_m int // player move\n\thouse_m  int // house move\n\toutcome  int\n}\n\n// State.\nvar (\n\tplayers = avl.NewTree() // address string -\u003e *tally\n\trounds  []round         // append-only history; Render shows the tail\n\n\t// Global tally (caller-agnostic).\n\ttotalWins   int // player wins\n\ttotalLosses int // player losses\n\ttotalDraws  int\n\ttotalRounds int\n)\n\nconst maxRecent = 8\n\n// parseChoice maps a choice string to a move index; ok=false if invalid.\nfunc parseChoice(choice string) (int, bool) {\n\tswitch strings.ToLower(strings.TrimSpace(choice)) {\n\tcase \"rock\", \"r\":\n\t\treturn rock, true\n\tcase \"paper\", \"p\":\n\t\treturn paper, true\n\tcase \"scissors\", \"s\":\n\t\treturn scissors, true\n\t}\n\treturn 0, false\n}\n\n// houseMove derives the house move deterministically from the chain height\n// and the caller's play count (so repeated calls in the same block differ).\nfunc houseMove(height int64, playCount int) int {\n\tx := height + int64(playCount)*7\n\tm := x % 3\n\tif m \u003c 0 {\n\t\tm += 3\n\t}\n\treturn int(m)\n}\n\n// decide returns the outcome from the player's perspective.\nfunc decide(playerMove, houseM int) int {\n\tif playerMove == houseM {\n\t\treturn outDraw\n\t}\n\t// player beats (player+1)%3 ... rock(0) beats scissors(2), etc.\n\tif (playerMove+2)%3 == houseM {\n\t\treturn outWin\n\t}\n\treturn outLose\n}\n\nfunc getTally(key string) *tally {\n\tif v := players.Get(key); v != nil {\n\t\treturn v.(*tally)\n\t}\n\treturn nil\n}\n\n// Play plays one round against the chain. choice is \"rock\"|\"paper\"|\"scissors\"\n// (single-letter shortcuts accepted). It panics on an invalid choice.\nfunc Play(cur realm, choice string) {\n\tmv, ok := parseChoice(choice)\n\tif !ok {\n\t\tpanic(\"invalid choice: use rock, paper, or scissors\")\n\t}\n\n\tcaller := unsafe.PreviousRealm().Address()\n\tkey := caller.String()\n\n\tt := getTally(key)\n\tif t == nil {\n\t\tt = \u0026tally{}\n\t\tplayers.Set(key, t)\n\t}\n\n\theight := runtime.ChainHeight()\n\thm := houseMove(height, t.plays)\n\toutcome := decide(mv, hm)\n\n\tt.plays++\n\tswitch outcome {\n\tcase outWin:\n\t\tt.wins++\n\t\ttotalWins++\n\tcase outLose:\n\t\tt.losses++\n\t\ttotalLosses++\n\tdefault:\n\t\tt.draws++\n\t\ttotalDraws++\n\t}\n\ttotalRounds++\n\n\trounds = append(rounds, round{\n\t\tplayer:   caller,\n\t\theight:   height,\n\t\tplayer_m: mv,\n\t\thouse_m:  hm,\n\t\toutcome:  outcome,\n\t})\n\n\tchain.Emit(\n\t\t\"RoundPlayed\",\n\t\t\"player\", key,\n\t\t\"choice\", moveNames[mv],\n\t\t\"house\", moveNames[hm],\n\t\t\"outcome\", outcomeName(outcome),\n\t)\n}\n\nfunc outcomeName(o int) string {\n\tswitch o {\n\tcase outWin:\n\t\treturn \"win\"\n\tcase outLose:\n\t\treturn \"lose\"\n\tdefault:\n\t\treturn \"draw\"\n\t}\n}\n\nfunc winRate(wins, plays int) string {\n\tif plays == 0 {\n\t\treturn \"0%\"\n\t}\n\treturn strconv.Itoa(wins*100/plays) + \"%\"\n}\n\n// Render returns a Markdown dashboard: global tally, per-player table, and the\n// last few rounds. It is caller-agnostic (no cur).\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Rock-Paper-Scissors — play vs the chain\\n\\n\")\n\tb.WriteString(\"Call `Play(cur, \\\"rock\\\"|\\\"paper\\\"|\\\"scissors\\\")`. \")\n\tb.WriteString(\"The house move is derived deterministically from the current block height \")\n\tb.WriteString(\"and your personal play count.\\n\\n\")\n\n\t// Global tally.\n\tb.WriteString(\"## Global tally\\n\\n\")\n\tb.WriteString(\"| Rounds | Player wins | Player losses | Draws | Player win rate |\\n\")\n\tb.WriteString(\"|---|---|---|---|---|\\n\")\n\tb.WriteString(\"| \" + strconv.Itoa(totalRounds))\n\tb.WriteString(\" | \" + strconv.Itoa(totalWins))\n\tb.WriteString(\" | \" + strconv.Itoa(totalLosses))\n\tb.WriteString(\" | \" + strconv.Itoa(totalDraws))\n\tb.WriteString(\" | \" + winRate(totalWins, totalRounds) + \" |\\n\\n\")\n\n\t// Per-player table (deterministic order via avl iteration).\n\tb.WriteString(\"## Players\\n\\n\")\n\tif players.Size() == 0 {\n\t\tb.WriteString(\"_No games played yet. Be the first!_\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| Player | W | L | D | Rounds | Win rate |\\n\")\n\t\tb.WriteString(\"|---|---|---|---|---|---|\\n\")\n\t\tplayers.Iterate(\"\", \"\", func(key string, v interface{}) bool {\n\t\t\tt := v.(*tally)\n\t\t\tb.WriteString(\"| \" + ui.AddrOf(key))\n\t\t\tb.WriteString(\" | \" + strconv.Itoa(t.wins))\n\t\t\tb.WriteString(\" | \" + strconv.Itoa(t.losses))\n\t\t\tb.WriteString(\" | \" + strconv.Itoa(t.draws))\n\t\t\tb.WriteString(\" | \" + strconv.Itoa(t.plays))\n\t\t\tb.WriteString(\" | \" + winRate(t.wins, t.plays) + \" |\\n\")\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\t// Recent rounds (tail).\n\tb.WriteString(\"## Recent rounds\\n\\n\")\n\tif len(rounds) == 0 {\n\t\tb.WriteString(\"_None yet._\\n\")\n\t} else {\n\t\tb.WriteString(\"| Height | Player | Choice | House | Result |\\n\")\n\t\tb.WriteString(\"|---|---|---|---|---|\\n\")\n\t\tstart := len(rounds) - maxRecent\n\t\tif start \u003c 0 {\n\t\t\tstart = 0\n\t\t}\n\t\t// Show newest first.\n\t\tfor i := len(rounds) - 1; i \u003e= start; i-- {\n\t\t\tr := rounds[i]\n\t\t\tb.WriteString(\"| \" + strconv.FormatInt(r.height, 10))\n\t\t\tb.WriteString(\" | \" + ui.Addr(r.player))\n\t\t\tb.WriteString(\" | \" + moveNames[r.player_m])\n\t\t\tb.WriteString(\" | \" + moveNames[r.house_m])\n\t\t\tb.WriteString(\" | \" + outcomeName(r.outcome) + \" |\\n\")\n\t\t}\n\t}\n\n\treturn b.String()\n}\n"},{"name":"rps_test.gno","body":"package rps\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestDecideAndParse(t *testing.T) {\n\t// parseChoice.\n\tcases := []struct {\n\t\tin   string\n\t\twant int\n\t\tok   bool\n\t}{\n\t\t{\"rock\", rock, true},\n\t\t{\"PAPER\", paper, true},\n\t\t{\" scissors \", scissors, true},\n\t\t{\"r\", rock, true},\n\t\t{\"p\", paper, true},\n\t\t{\"s\", scissors, true},\n\t\t{\"lizard\", 0, false},\n\t}\n\tfor _, c := range cases {\n\t\tgot, ok := parseChoice(c.in)\n\t\tuassert.Equal(t, c.ok, ok, \"ok for \"+c.in)\n\t\tif ok {\n\t\t\tuassert.Equal(t, c.want, got, \"move for \"+c.in)\n\t\t}\n\t}\n\n\t// decide: player perspective.\n\tuassert.Equal(t, outDraw, decide(rock, rock), \"rock vs rock\")\n\tuassert.Equal(t, outWin, decide(rock, scissors), \"rock beats scissors\")\n\tuassert.Equal(t, outLose, decide(rock, paper), \"rock loses to paper\")\n\tuassert.Equal(t, outWin, decide(paper, rock), \"paper beats rock\")\n\tuassert.Equal(t, outWin, decide(scissors, paper), \"scissors beats paper\")\n\tuassert.Equal(t, outLose, decide(scissors, rock), \"scissors loses to rock\")\n\n\t// houseMove determinism.\n\tuassert.Equal(t, houseMove(10, 0), houseMove(10, 0), \"same inputs -\u003e same move\")\n\tif houseMove(10, 0) == houseMove(10, 1) \u0026\u0026 houseMove(10, 1) == houseMove(10, 2) {\n\t\tt.Error(\"play count should vary house move across values\")\n\t}\n}\n\nfunc TestPlayRecordsTally(cur realm, t *testing.T) {\n\tuser := testutils.TestAddress(\"rps-player\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tbefore := totalRounds\n\tPlay(cross(cur),\"rock\")\n\tPlay(cross(cur),\"paper\")\n\tPlay(cross(cur),\"scissors\")\n\n\tuassert.Equal(t, before+3, totalRounds, \"global rounds incremented\")\n\n\ttl := getTally(user.String())\n\tuassert.True(t, tl != nil, \"player tally exists\")\n\tuassert.Equal(t, 3, tl.plays, \"player played 3 rounds\")\n\tuassert.Equal(t, tl.wins+tl.losses+tl.draws, tl.plays, \"outcomes sum to plays\")\n\n\t// Render must show the global tally header and the player.\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Global tally\"), \"render has global tally\")\n\tuassert.True(t, strings.Contains(out, \"Recent rounds\"), \"render has recent rounds\")\n\n\t// Invalid choice aborts (crossing fn -\u003e cross-realm abort).\n\tuassert.AbortsWithMessage(t, cur, \"invalid choice: use rock, paper, or scissors\", func() {\n\t\tPlay(cross(cur),\"lizard\")\n\t})\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"41387800","gas_fee":"124163ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"PahczKfvfeDmkQiNoBs7A43gcUmUzisG99QewYK6b61BqLnLFQchehxUMh3b8NKAQlm9rI+soDh09i9R1jY6qA=="}],"memo":""},"metadata":{"timestamp":"1790961327"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rpsduel","path":"gno.land/r/moul/x/daily/rpsduel/v1","files":[{"name":"README.md","body":"# Rock-Paper-Scissors Duel\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAsynchronous, two-player rock-paper-scissors with a real commit-reveal\nhandshake: the challenger locks in a move as a sha256 commitment, the\nopponent replies in the open (seeing only a hash gives them nothing to go\non), and the challenger reveals last to settle the round. A challenger who\ntries to dodge a losing reveal can be forfeited by the opponent once a\n50-block reveal window expires — no house move, no single-tx shortcut, just\ntwo players and a fairness primitive.\n\n**Realm path:** `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsduel`\n\n## Example calls\n\n```sh\n# 1. Compute your commitment off-chain (or via a read-only query)\ngnokey query vm/qeval \\\n  --data 'gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsduel.ComputeCommit(\"rock\", \"xyz123\")'\n\n# 2. Open a duel against an opponent with that commitment\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsduel\" \\\n  -func Open -args \"g1opponentaddr...\" -args \"\u003c64-char hex commit\u003e\" \\\n  -gas-fee 30000ugnot -gas-wanted 3000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n\n# 3. Opponent replies in the clear\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsduel\" \\\n  -func Accept -args \"1\" -args \"paper\" \\\n  -gas-fee 30000ugnot -gas-wanted 3000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n\n# 4. Challenger reveals to settle it\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsduel\" \\\n  -func Reveal -args \"1\" -args \"rock\" -args \"xyz123\" \\\n  -gas-fee 30000ugnot -gas-wanted 3000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n\n# View the lobby, a specific duel, or a player's record\ngnokey query vm/qrender --data \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsduel:\"\ngnokey query vm/qrender --data \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsduel:1\"\n```\n\n## Toolchain status\n\nCompiled and tested against the `chain/sapphire` (gno 0.9) toolchain tag from\n`gnolang/gno` — `gno test .` and `gno lint .` both pass clean.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/rpsduel) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline` helper.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/rpsduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsduel/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/rpsduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsduel/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/rpsduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsduel/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/rpsduel/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsduel/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/rpsduel/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/rpsduel/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/rpsduel/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package rpsduel\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Rock-Paper-Scissors Duel\n\t//\n\t// Challenge another address to rock-paper-scissors, async and fair: you commit your move as a hash, they reply in the open, then you reveal to settle it. Stall on revealing a losing round and your opponent can claim a forfeit win once the window expires.\n\t//\n\t// - Total duels resolved: 0\n\t// - No champion yet -- be the first to win a duel.\n\t//\n\t// ## How to play\n\t//\n\t// 1. Pick a move and a random salt, e.g. `rock` + `xyz123`.\n\t// 2. Compute your commitment: `ComputeCommit(\"rock\", \"xyz123\")` (read-only call).\n\t// 3. `Open(opponentAddr, commit)` -- opens the duel, returns its ID.\n\t// 4. The opponent calls `Accept(id, \"paper\"|\"scissors\"|\"rock\")`.\n\t// 5. You call `Reveal(id, \"rock\", \"xyz123\")` -- must match your commitment exactly.\n\t// 6. If you never reveal, the opponent can call `ClaimForfeit(id)` after 50 blocks.\n\t//\n\t// View a duel at this realm's path plus its ID (e.g. `.../rpsduel:3`), or a player's record plus their address (e.g. `.../rpsduel:g1youraddress...`).\n\t//\n\t// ## Open duels\n\t//\n\t// _none right now_\n}\n"},{"name":"rpsduel.gno","body":"// Package rpsduel is an asynchronous, two-player rock-paper-scissors duel\n// with a commit-reveal handshake. The challenger locks in a move as a\n// sha256 commitment up front so the opponent can't peek at it; the\n// opponent then replies in the clear (seeing only a hash gives them no\n// edge); the challenger reveals last to settle the round. A challenger who\n// tries to dodge a losing reveal can be forfeited by the opponent once the\n// reveal window expires.\npackage rpsduel\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Move is one of rock, paper, or scissors, ordered so that\n// (winner - loser + 3) % 3 == 1 for every winning pair.\ntype Move int\n\nconst (\n\tRock Move = iota\n\tPaper\n\tScissors\n)\n\nfunc moveName(m Move) string {\n\tswitch m {\n\tcase Rock:\n\t\treturn \"rock\"\n\tcase Paper:\n\t\treturn \"paper\"\n\tcase Scissors:\n\t\treturn \"scissors\"\n\tdefault:\n\t\treturn \"?\"\n\t}\n}\n\nfunc parseMove(s string) (Move, bool) {\n\tswitch strings.ToLower(strings.TrimSpace(s)) {\n\tcase \"rock\", \"r\":\n\t\treturn Rock, true\n\tcase \"paper\", \"p\":\n\t\treturn Paper, true\n\tcase \"scissors\", \"s\":\n\t\treturn Scissors, true\n\tdefault:\n\t\treturn 0, false\n\t}\n}\n\n// judge returns 0 for a tie, 1 if p beats h, 2 if h beats p.\nfunc judge(p, h Move) int {\n\treturn (int(p) - int(h) + 3) % 3\n}\n\n// revealWindow is how many blocks the challenger gets to reveal after the\n// opponent accepts before the opponent can claim a forfeit win.\nconst revealWindow int64 = 50\n\ntype duelStatus int\n\nconst (\n\tstatusPending duelStatus = iota\n\tstatusAwaitingReveal\n\tstatusResolved\n\tstatusForfeited\n\tstatusCancelled\n)\n\nfunc (s duelStatus) String() string {\n\tswitch s {\n\tcase statusPending:\n\t\treturn \"pending\"\n\tcase statusAwaitingReveal:\n\t\treturn \"awaiting reveal\"\n\tcase statusResolved:\n\t\treturn \"resolved\"\n\tcase statusForfeited:\n\t\treturn \"forfeited\"\n\tcase statusCancelled:\n\t\treturn \"cancelled\"\n\tdefault:\n\t\treturn \"?\"\n\t}\n}\n\n// duel is one asynchronous round between Challenger and Opponent. The\n// challenger's move is hidden behind Commit until Reveal; the opponent's\n// move is stored in the clear once they Accept.\ntype duel struct {\n\tID             string\n\tChallenger     address\n\tOpponent       address\n\tCommit         string // hex sha256 of \"\u003cmove\u003e:\u003csalt\u003e\"\n\tOpponentMove   Move\n\tStatus         duelStatus\n\tResult         string // \"challenger\" | \"opponent\" | \"draw\" once settled\n\tWinner         address\n\tOpenedAt       int64\n\tAcceptedAt     int64\n\tRevealDeadline int64\n}\n\n// playerState is the persisted record for one address.\ntype playerState struct {\n\tWins     int\n\tLosses   int\n\tDraws    int\n\tForfeits int // times this player, as challenger, failed to reveal in time\n\tDuels    int\n}\n\nvar (\n\tduels   avl.Tree // duel ID -\u003e *duel\n\tplayers avl.Tree // address string -\u003e *playerState\n\n\tnextID        int\n\ttotalResolved int\n\n\tchampion     address\n\tchampionWins int\n)\n\n// ComputeCommit hashes a move and salt exactly the way Reveal checks it, so\n// a caller can compute their commitment (e.g. via a read-only query) before\n// calling Open, then remember the salt to pass to Reveal later.\nfunc ComputeCommit(moveStr, salt string) string {\n\tm, ok := parseMove(moveStr)\n\tif !ok {\n\t\tpanic(\"invalid move: use rock, paper, or scissors (r/p/s)\")\n\t}\n\tsum := sha256.Sum256([]byte(moveName(m) + \":\" + salt))\n\treturn hex.EncodeToString(sum[:])\n}\n\nfunc getOrCreate(addr address) *playerState {\n\tkey := addr.String()\n\tif v := players.Get(key); v != nil {\n\t\treturn v.(*playerState)\n\t}\n\tps := \u0026playerState{}\n\tplayers.Set(key, ps)\n\treturn ps\n}\n\nfunc bumpChampion(addr address, wins int) {\n\tif wins \u003e championWins {\n\t\tchampionWins = wins\n\t\tchampion = addr\n\t}\n}\n\n// settle scores a revealed round and updates both players' records.\nfunc settle(d *duel, challengerMove Move, result int) {\n\tcs := getOrCreate(d.Challenger)\n\tos := getOrCreate(d.Opponent)\n\tcs.Duels++\n\tos.Duels++\n\n\tswitch result {\n\tcase 1:\n\t\tcs.Wins++\n\t\tos.Losses++\n\t\td.Winner = d.Challenger\n\t\td.Result = \"challenger\"\n\t\tbumpChampion(d.Challenger, cs.Wins)\n\tcase 2:\n\t\tos.Wins++\n\t\tcs.Losses++\n\t\td.Winner = d.Opponent\n\t\td.Result = \"opponent\"\n\t\tbumpChampion(d.Opponent, os.Wins)\n\tdefault:\n\t\tcs.Draws++\n\t\tos.Draws++\n\t\td.Result = \"draw\"\n\t}\n\td.Status = statusResolved\n\ttotalResolved++\n}\n\n// Open challenges opponentAddr to a duel, locking in the challenger's move\n// as a commitment (see ComputeCommit) so the opponent can't see it before\n// replying.\nfunc Open(cur realm, opponentAddr string, commitHex string) string {\n\tchallenger := cur.Previous().Address()\n\n\topponent := address(strings.TrimSpace(opponentAddr))\n\tif !opponent.IsValid() {\n\t\tpanic(\"invalid opponent address\")\n\t}\n\tif opponent == challenger {\n\t\tpanic(\"cannot duel yourself\")\n\t}\n\n\tcommit := strings.ToLower(strings.TrimSpace(commitHex))\n\tif len(commit) != sha256.Size*2 {\n\t\tpanic(\"commit must be a 64-character hex sha256 digest; build it with ComputeCommit\")\n\t}\n\tif _, err := hex.DecodeString(commit); err != nil {\n\t\tpanic(\"commit must be valid hex\")\n\t}\n\n\tnextID++\n\tid := strconv.Itoa(nextID)\n\td := \u0026duel{\n\t\tID:         id,\n\t\tChallenger: challenger,\n\t\tOpponent:   opponent,\n\t\tCommit:     commit,\n\t\tStatus:     statusPending,\n\t\tOpenedAt:   runtime.ChainHeight(),\n\t}\n\tduels.Set(id, d)\n\n\tchain.Emit(\"DuelOpened\",\n\t\t\"id\", id,\n\t\t\"challenger\", challenger.String(),\n\t\t\"opponent\", opponent.String(),\n\t)\n\n\treturn \"duel #\" + id + \" opened against \" + opponent.String() + \" -- waiting for them to Accept\"\n}\n\n// Accept replies to a pending duel with a plain move. Only the challenged\n// opponent may call it; going second behind the challenger's hidden\n// commitment is what keeps this fair.\nfunc Accept(cur realm, id string, moveStr string) string {\n\tcaller := cur.Previous().Address()\n\n\tv := duels.Get(id)\n\tif v == nil {\n\t\tpanic(\"no such duel\")\n\t}\n\td := v.(*duel)\n\n\tif d.Status != statusPending {\n\t\tpanic(\"duel is \" + d.Status.String() + \", not pending\")\n\t}\n\tif caller != d.Opponent {\n\t\tpanic(\"only the challenged opponent can accept this duel\")\n\t}\n\n\tm, ok := parseMove(moveStr)\n\tif !ok {\n\t\tpanic(\"invalid move: use rock, paper, or scissors (r/p/s)\")\n\t}\n\n\td.OpponentMove = m\n\td.Status = statusAwaitingReveal\n\td.AcceptedAt = runtime.ChainHeight()\n\td.RevealDeadline = d.AcceptedAt + revealWindow\n\n\tchain.Emit(\"DuelAccepted\", \"id\", id, \"opponentMove\", moveName(m))\n\n\treturn \"you played \" + moveName(m) + \" in duel #\" + id +\n\t\t\" -- waiting for \" + d.Challenger.String() + \" to reveal by block \" +\n\t\tstrconv.Itoa(int(d.RevealDeadline))\n}\n\n// Reveal settles an accepted duel. Only the original challenger may call\n// it, and only with the exact move+salt that produced their commitment.\nfunc Reveal(cur realm, id string, moveStr string, salt string) string {\n\tcaller := cur.Previous().Address()\n\n\tv := duels.Get(id)\n\tif v == nil {\n\t\tpanic(\"no such duel\")\n\t}\n\td := v.(*duel)\n\n\tif d.Status != statusAwaitingReveal {\n\t\tpanic(\"duel is \" + d.Status.String() + \", not awaiting reveal\")\n\t}\n\tif caller != d.Challenger {\n\t\tpanic(\"only the challenger can reveal\")\n\t}\n\n\tm, ok := parseMove(moveStr)\n\tif !ok {\n\t\tpanic(\"invalid move: use rock, paper, or scissors (r/p/s)\")\n\t}\n\tsum := sha256.Sum256([]byte(moveName(m) + \":\" + salt))\n\tif hex.EncodeToString(sum[:]) != d.Commit {\n\t\tpanic(\"revealed move+salt doesn't match your original commitment\")\n\t}\n\n\tresult := judge(m, d.OpponentMove)\n\tsettle(d, m, result)\n\n\tchain.Emit(\"DuelResolved\",\n\t\t\"id\", id,\n\t\t\"result\", d.Result,\n\t\t\"challengerMove\", moveName(m),\n\t\t\"opponentMove\", moveName(d.OpponentMove),\n\t)\n\n\treturn \"you revealed \" + moveName(m) + \" vs \" + moveName(d.OpponentMove) + \" -- \" + outcomeMsg(d)\n}\n\nfunc outcomeMsg(d *duel) string {\n\tswitch d.Result {\n\tcase \"challenger\":\n\t\treturn \"you win duel #\" + d.ID + \"!\"\n\tcase \"opponent\":\n\t\treturn \"you lose duel #\" + d.ID + \" -- \" + d.Opponent.String() + \" wins.\"\n\tdefault:\n\t\treturn \"draw.\"\n\t}\n}\n\n// ClaimForfeit lets the opponent collect a default win when the challenger\n// dodges revealing (e.g. because they saw the opponent's move and knew\n// they'd lose) past the reveal window.\nfunc ClaimForfeit(cur realm, id string) string {\n\tcaller := cur.Previous().Address()\n\n\tv := duels.Get(id)\n\tif v == nil {\n\t\tpanic(\"no such duel\")\n\t}\n\td := v.(*duel)\n\n\tif d.Status != statusAwaitingReveal {\n\t\tpanic(\"duel is \" + d.Status.String() + \", not awaiting reveal\")\n\t}\n\tif caller != d.Opponent {\n\t\tpanic(\"only the waiting opponent can claim a forfeit\")\n\t}\n\tif runtime.ChainHeight() \u003c= d.RevealDeadline {\n\t\tpanic(\"reveal window hasn't expired yet\")\n\t}\n\n\td.Status = statusForfeited\n\td.Winner = d.Opponent\n\td.Result = \"opponent\"\n\n\tcs := getOrCreate(d.Challenger)\n\tcs.Duels++\n\tcs.Losses++\n\tcs.Forfeits++\n\tos := getOrCreate(d.Opponent)\n\tos.Duels++\n\tos.Wins++\n\ttotalResolved++\n\tbumpChampion(d.Opponent, os.Wins)\n\n\tchain.Emit(\"DuelForfeited\", \"id\", id, \"winner\", d.Opponent.String())\n\n\treturn \"duel #\" + id + \" forfeited -- \" + d.Challenger.String() + \" never revealed\"\n}\n\n// Cancel withdraws a still-pending duel. Only the challenger may cancel,\n// and only before the opponent accepts.\nfunc Cancel(cur realm, id string) string {\n\tcaller := cur.Previous().Address()\n\n\tv := duels.Get(id)\n\tif v == nil {\n\t\tpanic(\"no such duel\")\n\t}\n\td := v.(*duel)\n\n\tif d.Status != statusPending {\n\t\tpanic(\"duel is \" + d.Status.String() + \", not pending\")\n\t}\n\tif caller != d.Challenger {\n\t\tpanic(\"only the challenger can cancel this duel\")\n\t}\n\n\td.Status = statusCancelled\n\treturn \"duel #\" + id + \" cancelled\"\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Rock-Paper-Scissors Duel\\n\\n\")\n\tb.WriteString(\"Challenge another address to rock-paper-scissors, async and \" +\n\t\t\"fair: you commit your move as a hash, they reply in the open, then you \" +\n\t\t\"reveal to settle it. Stall on revealing a losing round and your opponent \" +\n\t\t\"can claim a forfeit win once the window expires.\\n\\n\")\n\n\tb.WriteString(\"- Total duels resolved: \" + strconv.Itoa(totalResolved) + \"\\n\")\n\tif champion.IsValid() {\n\t\tb.WriteString(\"- Reigning champion: `\" + champion.String() + \"` (\" +\n\t\t\tstrconv.Itoa(championWins) + \" wins)\\n\")\n\t} else {\n\t\tb.WriteString(\"- No champion yet -- be the first to win a duel.\\n\")\n\t}\n\n\tb.WriteString(\"\\n## How to play\\n\\n\")\n\tb.WriteString(\"1. Pick a move and a random salt, e.g. `rock` + `xyz123`.\\n\")\n\tb.WriteString(\"2. Compute your commitment: `ComputeCommit(\\\"rock\\\", \\\"xyz123\\\")` (read-only call).\\n\")\n\tb.WriteString(\"3. `Open(opponentAddr, commit)` -- opens the duel, returns its ID.\\n\")\n\tb.WriteString(\"4. The opponent calls `Accept(id, \\\"paper\\\"|\\\"scissors\\\"|\\\"rock\\\")`.\\n\")\n\tb.WriteString(\"5. You call `Reveal(id, \\\"rock\\\", \\\"xyz123\\\")` -- must match your commitment exactly.\\n\")\n\tb.WriteString(\"6. If you never reveal, the opponent can call `ClaimForfeit(id)` after \" +\n\t\tstrconv.Itoa(int(revealWindow)) + \" blocks.\\n\\n\")\n\tb.WriteString(\"View a duel at this realm's path plus its ID (e.g. `.../rpsduel:3`), \" +\n\t\t\"or a player's record plus their address (e.g. `.../rpsduel:g1youraddress...`).\\n\\n\")\n\n\tb.WriteString(\"## Open duels\\n\\n\")\n\topen := 0\n\tduels.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\td := value.(*duel)\n\t\tif d.Status == statusPending {\n\t\t\topen++\n\t\t\tb.WriteString(\"- #\" + d.ID + \": `\" + d.Challenger.String() +\n\t\t\t\t\"` waiting on `\" + d.Opponent.String() + \"` to Accept\\n\")\n\t\t} else if d.Status == statusAwaitingReveal {\n\t\t\topen++\n\t\t\tb.WriteString(\"- #\" + d.ID + \": `\" + d.Challenger.String() +\n\t\t\t\t\"` must Reveal by block \" + strconv.Itoa(int(d.RevealDeadline)) + \"\\n\")\n\t\t}\n\t\treturn false\n\t})\n\tif open == 0 {\n\t\tb.WriteString(\"_none right now_\\n\")\n\t}\n\n\treturn b.String()\n}\n\nfunc renderDuel(id string) string {\n\tv := duels.Get(id)\n\tif v == nil {\n\t\treturn \"# Duel #\" + ui.Inline(id) + \"\\n\\nNo such duel.\\n\"\n\t}\n\td := v.(*duel)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Duel #\" + d.ID + \"\\n\\n\")\n\tb.WriteString(\"- Challenger: `\" + d.Challenger.String() + \"`\\n\")\n\tb.WriteString(\"- Opponent: `\" + d.Opponent.String() + \"`\\n\")\n\tb.WriteString(\"- Status: \" + d.Status.String() + \"\\n\")\n\n\tif d.Status == statusAwaitingReveal {\n\t\tb.WriteString(\"- Opponent played: **\" + moveName(d.OpponentMove) + \"**\\n\")\n\t\tb.WriteString(\"- Reveal deadline: block \" + strconv.Itoa(int(d.RevealDeadline)) + \"\\n\")\n\t}\n\tif d.Status == statusResolved || d.Status == statusForfeited {\n\t\tb.WriteString(\"- Result: \" + d.Result + \"\\n\")\n\t\tb.WriteString(\"- Winner: `\" + d.Winner.String() + \"`\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderPlayer(rawAddr string) string {\n\taddr := strings.TrimSpace(rawAddr)\n\tsafe := ui.Inline(addr)\n\n\tv := players.Get(addr)\n\tif v == nil {\n\t\treturn \"# Player \" + safe + \"\\n\\nNo recorded duels yet.\\n\"\n\t}\n\tps := v.(*playerState)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Player \" + safe + \"\\n\\n\")\n\tb.WriteString(\"- Wins: \" + strconv.Itoa(ps.Wins) + \"\\n\")\n\tb.WriteString(\"- Losses: \" + strconv.Itoa(ps.Losses) + \"\\n\")\n\tb.WriteString(\"- Draws: \" + strconv.Itoa(ps.Draws) + \"\\n\")\n\tb.WriteString(\"- Duels played: \" + strconv.Itoa(ps.Duels) + \"\\n\")\n\tif ps.Forfeits \u003e 0 {\n\t\tb.WriteString(\"- Forfeited (didn't reveal in time): \" + strconv.Itoa(ps.Forfeits) + \"\\n\")\n\t}\n\treturn b.String()\n}\n\n// Render shows the duel lobby at \"\", a specific duel when path is a\n// numeric ID, or one player's record when path is their bech32 address.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\tif _, err := strconv.Atoi(path); err == nil {\n\t\treturn renderDuel(path)\n\t}\n\treturn renderPlayer(path)\n}\n"},{"name":"rpsduel_test.gno","body":"package rpsduel\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tduels = avl.Tree{}\n\tplayers = avl.Tree{}\n\tnextID = 0\n\ttotalResolved = 0\n\tvar zero address\n\tchampion = zero\n\tchampionWins = 0\n}\n\nfunc TestParseMove(t *testing.T) {\n\tfor _, s := range []string{\"rock\", \"Rock\", \" r \", \"paper\", \"P\", \"scissors\", \"S\"} {\n\t\tif _, ok := parseMove(s); !ok {\n\t\t\tt.Fatalf(\"parseMove(%q) should be valid\", s)\n\t\t}\n\t}\n\tif _, ok := parseMove(\"lizard\"); ok {\n\t\tt.Fatal(`parseMove(\"lizard\") should be invalid`)\n\t}\n}\n\nfunc TestJudge(t *testing.T) {\n\tcases := []struct {\n\t\tp, h Move\n\t\twant int\n\t}{\n\t\t{Rock, Rock, 0},\n\t\t{Paper, Paper, 0},\n\t\t{Scissors, Scissors, 0},\n\t\t{Paper, Rock, 1},\n\t\t{Scissors, Paper, 1},\n\t\t{Rock, Scissors, 1},\n\t\t{Rock, Paper, 2},\n\t\t{Paper, Scissors, 2},\n\t\t{Scissors, Rock, 2},\n\t}\n\tfor _, c := range cases {\n\t\tif got := judge(c.p, c.h); got != c.want {\n\t\t\tt.Fatalf(\"judge(%v,%v) = %d, want %d\", c.p, c.h, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestComputeCommitDeterministicAndSalted(t *testing.T) {\n\ta := ComputeCommit(\"rock\", \"salt1\")\n\tb := ComputeCommit(\"rock\", \"salt1\")\n\tif a != b {\n\t\tt.Fatal(\"ComputeCommit should be deterministic for the same move+salt\")\n\t}\n\tif a == ComputeCommit(\"rock\", \"salt2\") {\n\t\tt.Fatal(\"different salts should produce different commits\")\n\t}\n\tif a == ComputeCommit(\"paper\", \"salt1\") {\n\t\tt.Fatal(\"different moves should produce different commits\")\n\t}\n\tif len(a) != 64 {\n\t\tt.Fatalf(\"commit length = %d, want 64 (hex sha256)\", len(a))\n\t}\n}\n\n// Crossing: Open/Accept/Reveal mutate realm state, so the test needs `cur realm`.\nfunc TestFullDuelChallengerWins(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\tcommit := ComputeCommit(\"paper\", \"s3cr3t\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tOpen(cross(cur), bob.String(), commit)\n\n\tv := duels.Get(\"1\")\n\tif v == nil {\n\t\tt.Fatal(\"expected duel #1 to exist\")\n\t}\n\td := v.(*duel)\n\tif d.Status != statusPending {\n\t\tt.Fatalf(\"Status = %v, want pending\", d.Status)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAccept(cross(cur), \"1\", \"rock\")\n\n\tif d.Status != statusAwaitingReveal {\n\t\tt.Fatalf(\"Status = %v, want awaiting reveal\", d.Status)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReveal(cross(cur), \"1\", \"paper\", \"s3cr3t\")\n\n\tif d.Status != statusResolved {\n\t\tt.Fatalf(\"Status = %v, want resolved\", d.Status)\n\t}\n\tif d.Result != \"challenger\" {\n\t\tt.Fatalf(\"Result = %q, want challenger (paper beats rock)\", d.Result)\n\t}\n\tif d.Winner != alice {\n\t\tt.Fatal(\"expected alice to win\")\n\t}\n\tif totalResolved != 1 {\n\t\tt.Fatalf(\"totalResolved = %d, want 1\", totalResolved)\n\t}\n\n\taliceStats := getOrCreate(alice)\n\tif aliceStats.Wins != 1 {\n\t\tt.Fatalf(\"alice.Wins = %d, want 1\", aliceStats.Wins)\n\t}\n\tbobStats := getOrCreate(bob)\n\tif bobStats.Losses != 1 {\n\t\tt.Fatalf(\"bob.Losses = %d, want 1\", bobStats.Losses)\n\t}\n\tif !champion.IsValid() || champion != alice {\n\t\tt.Fatal(\"champion should be alice\")\n\t}\n}\n\nfunc TestRevealMismatchPanics(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tOpen(cross(cur), bob.String(), ComputeCommit(\"rock\", \"s3cr3t\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAccept(cross(cur), \"1\", \"scissors\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\trec := revive(func() { Reveal(cross(cur), \"1\", \"paper\", \"s3cr3t\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when revealed move doesn't match the commitment\")\n\t}\n}\n\nfunc TestOnlyOpponentCanAccept(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tmallory := testutils.TestAddress(\"mallory\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tOpen(cross(cur), bob.String(), ComputeCommit(\"rock\", \"s3cr3t\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\trec := revive(func() { Accept(cross(cur), \"1\", \"paper\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when a non-opponent accepts\")\n\t}\n}\n\nfunc TestClaimForfeitBeforeDeadlinePanics(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tOpen(cross(cur), bob.String(), ComputeCommit(\"rock\", \"s3cr3t\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAccept(cross(cur), \"1\", \"paper\")\n\n\trec := revive(func() { ClaimForfeit(cross(cur), \"1\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when claiming a forfeit before the reveal window expires\")\n\t}\n}\n\nfunc TestClaimForfeitAfterDeadline(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tOpen(cross(cur), bob.String(), ComputeCommit(\"rock\", \"s3cr3t\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAccept(cross(cur), \"1\", \"paper\")\n\n\ttesting.SkipHeights(revealWindow + 1)\n\n\tClaimForfeit(cross(cur), \"1\")\n\n\tv := duels.Get(\"1\")\n\td := v.(*duel)\n\tif d.Status != statusForfeited {\n\t\tt.Fatalf(\"Status = %v, want forfeited\", d.Status)\n\t}\n\tif d.Winner != bob {\n\t\tt.Fatal(\"expected bob to win by forfeit\")\n\t}\n\n\taliceStats := getOrCreate(alice)\n\tif aliceStats.Forfeits != 1 {\n\t\tt.Fatalf(\"alice.Forfeits = %d, want 1\", aliceStats.Forfeits)\n\t}\n}\n\nfunc TestCancel(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tOpen(cross(cur), bob.String(), ComputeCommit(\"rock\", \"s3cr3t\"))\n\tCancel(cross(cur), \"1\")\n\n\tv := duels.Get(\"1\")\n\td := v.(*duel)\n\tif d.Status != statusCancelled {\n\t\tt.Fatalf(\"Status = %v, want cancelled\", d.Status)\n\t}\n}\n\nfunc TestOpenSelfRejected(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\trec := revive(func() { Open(cross(cur), alice.String(), ComputeCommit(\"rock\", \"s3cr3t\")) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when challenging yourself\")\n\t}\n}\n\n// Non-crossing: Render is a plain read.\nfunc TestRenderHome(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif out == \"\" {\n\t\tt.Fatal(`Render(\"\") should not be empty`)\n\t}\n}\n"}]},"send":"","max_deposit":"11000000ugnot"}],"fee":{"gas_wanted":"78630200","gas_fee":"235890ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"4Y0fdy1ZKVag4Z3LYmbYlcZqvE3s9pWRcNohgSRf9jkkl3WTgo90wFWsCkBaFe+gkt7l5l3bYRpZTdqR+y3tGw=="}],"memo":""},"metadata":{"timestamp":"1790961328"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rpsmatch","path":"gno.land/r/moul/x/daily/rpsmatch/v1","files":[{"name":"README.md","body":"# Rock-Paper-Scissors Arena\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nBest-of-three rock-paper-scissors against the house, played across multiple\ncalls instead of a single stateless throw. Each `Throw` plays one round of\nyour current match (starting a new one if you don't have one in progress);\nthe house's move is derived deterministically from the current block height,\na per-realm nonce, and your address. First to two round wins takes the\nmatch, and every player's match record (wins, losses, rounds played) is\nkept on-chain and viewable per-address.\n\n**Realm path:** `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsmatch`\n\n## Example calls\n\n```sh\n# Play one round of your current (or a new) match\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsmatch\" \\\n  -func Throw -args \"rock\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n\n# View the arena dashboard\ngnokey query vm/qrender \\\n  --data \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsmatch:\"\n\n# View one player's record\ngnokey query vm/qrender \\\n  --data \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsmatch:g1youraddress...\"\n```\n\n## Toolchain\n\nWritten against the sapphire (gno 0.9) stdlib split (`chain`, `chain/runtime`,\n`gno.land/p/nt/avl/v0`). The `gno` binary on `PATH` here is a newer/older\nmismatch of its own `GNOROOT` (native-function drift), so tests were run\nagainst a `gno` built from the exact pseudo-version pinned in that binary's\nown module info (`github.com/gnolang/gno@v0.0.0-20260605043206-bf5b31eda8b9`).\nAll 5 tests pass (`gno test -v .`) and `gno lint .` is clean.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/rpsmatch) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline` helper.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/rpsmatch/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsmatch/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/rpsmatch/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsmatch/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/rpsmatch/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsmatch/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/rpsmatch/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsmatch/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/rpsmatch/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/rpsmatch/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/rpsmatch/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package rpsmatch\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Rock-Paper-Scissors Arena\n\t//\n\t// Best-of-three matches against the house. First to 2 round wins takes the match.\n\t//\n\t// - Total rounds played: 0\n\t// - No champion yet — be the first to win a match.\n\t//\n\t// ## How to play\n\t//\n\t// Call `Throw(\"rock\"|\"paper\"|\"scissors\")` (or `r`/`p`/`s`). Your throw starts a new match if you don't have one in progress, and each call plays one round of it.\n\t//\n\t// View your own record at this realm's path plus your address, e.g. `.../rpsmatch:g1youraddress...`\n}\n"},{"name":"rpsmatch.gno","body":"// Package rpsmatch is a best-of-three rock-paper-scissors arena against the\n// house. Unlike a single stateless throw, a match persists across calls:\n// the first player to win two rounds takes the match, and every player's\n// match record accumulates on-chain.\npackage rpsmatch\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Move is one of rock, paper, or scissors, ordered so that\n// (winner - loser + 3) % 3 == 1 for every winning pair.\ntype Move int\n\nconst (\n\tRock Move = iota\n\tPaper\n\tScissors\n)\n\n// winsNeeded is the number of round wins required to take a match.\nconst winsNeeded = 2\n\n// match tracks an in-progress best-of-three series for one player.\ntype match struct {\n\tPlayerWins int\n\tHouseWins  int\n\tRounds     int\n}\n\n// playerState is the persisted record for one address.\ntype playerState struct {\n\tActive        *match\n\tMatchWins     int\n\tMatchLosses   int\n\tMatchesPlayed int\n\tRoundsPlayed  int\n}\n\nvar (\n\tplayers avl.Tree // address string -\u003e *playerState\n\n\tnonce       int\n\ttotalRounds int\n\n\tchampion     address\n\tchampionWins int\n)\n\nfunc moveName(m Move) string {\n\tswitch m {\n\tcase Rock:\n\t\treturn \"rock\"\n\tcase Paper:\n\t\treturn \"paper\"\n\tcase Scissors:\n\t\treturn \"scissors\"\n\tdefault:\n\t\treturn \"?\"\n\t}\n}\n\nfunc parseMove(s string) (Move, bool) {\n\tswitch strings.ToLower(strings.TrimSpace(s)) {\n\tcase \"rock\", \"r\":\n\t\treturn Rock, true\n\tcase \"paper\", \"p\":\n\t\treturn Paper, true\n\tcase \"scissors\", \"s\":\n\t\treturn Scissors, true\n\tdefault:\n\t\treturn 0, false\n\t}\n}\n\n// judge returns 0 for a tie, 1 if p beats h, 2 if h beats p.\nfunc judge(p, h Move) int {\n\treturn (int(p) - int(h) + 3) % 3\n}\n\n// pickHouseMove derives a deterministic pseudo-random move from the current\n// chain height, a monotonic per-realm nonce, and the caller's address, so\n// repeated throws in the same block still diverge.\nfunc pickHouseMove(caller address, n int) Move {\n\tseed := runtime.ChainHeight() + int64(n)\n\ts := caller.String()\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tseed += int64(s[i])\n\t}\n\tif seed \u003c 0 {\n\t\tseed = -seed\n\t}\n\treturn Move(seed % 3)\n}\n\nfunc getOrCreate(addr address) *playerState {\n\tkey := addr.String()\n\tif v := players.Get(key); v != nil {\n\t\treturn v.(*playerState)\n\t}\n\tps := \u0026playerState{}\n\tplayers.Set(key, ps)\n\treturn ps\n}\n\n// Throw plays one round of the caller's current match, starting a fresh\n// match if none is in progress. Accepts \"rock\"/\"paper\"/\"scissors\" or the\n// single-letter shorthand \"r\"/\"p\"/\"s\".\nfunc Throw(cur realm, moveStr string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"invalid realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\n\tplayerMove, ok := parseMove(moveStr)\n\tif !ok {\n\t\tpanic(\"invalid move: use rock, paper, or scissors (r/p/s)\")\n\t}\n\n\tps := getOrCreate(caller)\n\tif ps.Active == nil {\n\t\tps.Active = \u0026match{}\n\t}\n\tm := ps.Active\n\n\tnonce++\n\thouseMove := pickHouseMove(caller, nonce)\n\tround := judge(playerMove, houseMove)\n\n\tm.Rounds++\n\ttotalRounds++\n\tps.RoundsPlayed++\n\n\tvar roundMsg string\n\tswitch round {\n\tcase 1:\n\t\tm.PlayerWins++\n\t\troundMsg = \"you win the round\"\n\tcase 2:\n\t\tm.HouseWins++\n\t\troundMsg = \"house wins the round\"\n\tdefault:\n\t\troundMsg = \"round tied\"\n\t}\n\n\tout := \"round \" + strconv.Itoa(m.Rounds) + \": you played \" + moveName(playerMove) +\n\t\t\", house played \" + moveName(houseMove) + \" -\u003e \" + roundMsg +\n\t\t\" (score \" + strconv.Itoa(m.PlayerWins) + \"-\" + strconv.Itoa(m.HouseWins) + \")\"\n\n\tif m.PlayerWins \u003e= winsNeeded || m.HouseWins \u003e= winsNeeded {\n\t\tps.Active = nil\n\t\tps.MatchesPlayed++\n\t\tplayerTookMatch := m.PlayerWins \u003e m.HouseWins\n\t\tif playerTookMatch {\n\t\t\tps.MatchWins++\n\t\t\tif ps.MatchWins \u003e championWins {\n\t\t\t\tchampionWins = ps.MatchWins\n\t\t\t\tchampion = caller\n\t\t\t}\n\t\t\tout += \". MATCH WON!\"\n\t\t} else {\n\t\t\tps.MatchLosses++\n\t\t\tout += \". match lost.\"\n\t\t}\n\t\tchain.Emit(\"MatchFinished\",\n\t\t\t\"player\", caller.String(),\n\t\t\t\"playerWins\", strconv.Itoa(m.PlayerWins),\n\t\t\t\"houseWins\", strconv.Itoa(m.HouseWins),\n\t\t)\n\t}\n\n\tchain.Emit(\"RoundPlayed\",\n\t\t\"player\", caller.String(),\n\t\t\"playerMove\", moveName(playerMove),\n\t\t\"houseMove\", moveName(houseMove),\n\t\t\"result\", strconv.Itoa(round),\n\t)\n\n\treturn out\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Rock-Paper-Scissors Arena\\n\\n\")\n\tb.WriteString(\"Best-of-three matches against the house. First to \" +\n\t\tstrconv.Itoa(winsNeeded) + \" round wins takes the match.\\n\\n\")\n\tb.WriteString(\"- Total rounds played: \" + strconv.Itoa(totalRounds) + \"\\n\")\n\n\tif champion.IsValid() {\n\t\tb.WriteString(\"- Reigning champion: `\" + champion.String() +\n\t\t\t\"` (\" + strconv.Itoa(championWins) + \" match wins)\\n\")\n\t} else {\n\t\tb.WriteString(\"- No champion yet — be the first to win a match.\\n\")\n\t}\n\n\tb.WriteString(\"\\n## How to play\\n\\n\")\n\tb.WriteString(\"Call `Throw(\\\"rock\\\"|\\\"paper\\\"|\\\"scissors\\\")` (or `r`/`p`/`s`). \" +\n\t\t\"Your throw starts a new match if you don't have one in progress, \" +\n\t\t\"and each call plays one round of it.\\n\\n\")\n\tb.WriteString(\"View your own record at this realm's path plus your address, \" +\n\t\t\"e.g. `.../rpsmatch:g1youraddress...`\\n\")\n\treturn b.String()\n}\n\nfunc renderPlayer(rawAddr string) string {\n\taddr := strings.TrimSpace(rawAddr)\n\tsafe := ui.Inline(addr)\n\n\tv := players.Get(addr)\n\tif v == nil {\n\t\treturn \"# Player \" + safe + \"\\n\\nNo recorded throws yet.\\n\"\n\t}\n\tps := v.(*playerState)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Player \" + safe + \"\\n\\n\")\n\tb.WriteString(\"- Matches won: \" + strconv.Itoa(ps.MatchWins) + \"\\n\")\n\tb.WriteString(\"- Matches lost: \" + strconv.Itoa(ps.MatchLosses) + \"\\n\")\n\tb.WriteString(\"- Matches played: \" + strconv.Itoa(ps.MatchesPlayed) + \"\\n\")\n\tb.WriteString(\"- Rounds played: \" + strconv.Itoa(ps.RoundsPlayed) + \"\\n\")\n\n\tif ps.Active != nil {\n\t\tb.WriteString(\"\\n**Match in progress:** \" + strconv.Itoa(ps.Active.PlayerWins) +\n\t\t\t\"-\" + strconv.Itoa(ps.Active.HouseWins) + \" through \" +\n\t\t\tstrconv.Itoa(ps.Active.Rounds) + \" round(s).\\n\")\n\t}\n\treturn b.String()\n}\n\n// Render shows the arena dashboard at \"\", or one player's record when path\n// is their bech32 address.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderPlayer(path)\n}\n"},{"name":"rpsmatch_test.gno","body":"package rpsmatch\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tplayers = avl.Tree{}\n\tnonce = 0\n\ttotalRounds = 0\n\tvar zero address\n\tchampion = zero\n\tchampionWins = 0\n}\n\nfunc TestJudge(t *testing.T) {\n\tcases := []struct {\n\t\tp, h Move\n\t\twant int\n\t}{\n\t\t{Rock, Rock, 0},\n\t\t{Paper, Paper, 0},\n\t\t{Scissors, Scissors, 0},\n\t\t{Paper, Rock, 1},\n\t\t{Scissors, Paper, 1},\n\t\t{Rock, Scissors, 1},\n\t\t{Rock, Paper, 2},\n\t\t{Paper, Scissors, 2},\n\t\t{Scissors, Rock, 2},\n\t}\n\tfor _, c := range cases {\n\t\tif got := judge(c.p, c.h); got != c.want {\n\t\t\tt.Fatalf(\"judge(%v,%v) = %d, want %d\", c.p, c.h, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestParseMove(t *testing.T) {\n\tfor _, s := range []string{\"rock\", \"Rock\", \" r \", \"paper\", \"P\", \"scissors\", \"S\"} {\n\t\tif _, ok := parseMove(s); !ok {\n\t\t\tt.Fatalf(\"parseMove(%q) should be valid\", s)\n\t\t}\n\t}\n\tif _, ok := parseMove(\"lizard\"); ok {\n\t\tt.Fatal(\"parseMove(\\\"lizard\\\") should be invalid\")\n\t}\n}\n\n// Crossing: Throw mutates realm state, so the test needs `cur realm`.\nfunc TestThrowUpdatesStats(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tThrow(cross(cur), \"rock\")\n\n\tps := getOrCreate(alice)\n\tif ps.RoundsPlayed != 1 {\n\t\tt.Fatalf(\"RoundsPlayed = %d, want 1\", ps.RoundsPlayed)\n\t}\n\tif totalRounds != 1 {\n\t\tt.Fatalf(\"totalRounds = %d, want 1\", totalRounds)\n\t}\n}\n\nfunc TestMatchCompletes(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tfor i := 0; i \u003c 10; i++ {\n\t\tps := getOrCreate(alice)\n\t\tif ps.Active == nil \u0026\u0026 ps.MatchesPlayed \u003e 0 {\n\t\t\tbreak\n\t\t}\n\t\tThrow(cross(cur), \"rock\")\n\t}\n\n\tps := getOrCreate(alice)\n\tif ps.MatchesPlayed == 0 {\n\t\tt.Fatal(\"expected a match to complete within 10 rounds\")\n\t}\n\tif ps.MatchWins+ps.MatchLosses != ps.MatchesPlayed {\n\t\tt.Fatalf(\"wins+losses (%d) != matchesPlayed (%d)\", ps.MatchWins+ps.MatchLosses, ps.MatchesPlayed)\n\t}\n}\n\n// Non-crossing: Render is a plain read.\nfunc TestRenderHome(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif out == \"\" {\n\t\tt.Fatal(\"Render(\\\"\\\") should not be empty\")\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"46658000","gas_fee":"139974ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"dusYqf3gBKGs8SrWZh/18AWk62Fkk7VoVbgCF0VUgNE/vlAv8vrceeJFUCeDcS8ADU1CRfWR4exMt6cAfUrteA=="}],"memo":""},"metadata":{"timestamp":"1790961328"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"5KZRhwq0sXjxg0packUR9cxdXAQN4ztVaMXgj26FohFpgHd7b6Ap8uA3Jt1LaD85YtigWt474uz8cAF7JZ6csQ=="}],"memo":""},"metadata":{"timestamp":"1790961329"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"rpsoracle","path":"gno.land/r/moul/x/daily/rpsoracle/v1","files":[{"name":"README.md","body":"# Rock-Paper-Scissors Oracle\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA rock-paper-scissors opponent that doesn't roll dice — it studies you. The\noracle tallies every move you've ever thrown and always counters whichever\none you favor most, so a fixed habit gets punished while a genuinely mixed\n(roughly 1/3-1/3-1/3) strategy is unbeatable in the long run. It's a live,\nplayable demo of the rock-paper-scissors mixed-strategy Nash equilibrium:\n`Render` shows your win/loss/draw record, your move-history breakdown, and a\n\"predictability score\" (your most-played move's share of your rounds — lower\nmeans the oracle has less to work with).\n\n**Realm path:** `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsoracle`\n\n## Example calls\n\n```sh\n# Play one round — the oracle predicts from your move history, then counters\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsoracle\" \\\n  -func Play -args \"rock\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n\n# View the oracle's dashboard (total rounds, oracle win rate, top outwitter)\ngnokey query vm/qrender \\\n  --data \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsoracle:\"\n\n# View one player's record and move-history breakdown\ngnokey query vm/qrender \\\n  --data \"gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/rpsoracle:g1youraddress...\"\n```\n\n## Toolchain\n\nWritten against the sapphire (gno 0.9) stdlib split (`chain`, `chain/runtime`,\n`gno.land/p/nt/avl/v0`, `gno.land/p/nt/testutils/v0`), following the same\ncrossing-function (`cur realm`) and `avl.Tree`-backed state patterns as the\n`rpsmatch` realm in this repo.\n\nv0's README noted that `gno test` could not be run when it was written, because\nthe `gno` on `PATH` embedded a `GNOROOT` pointing at a deleted directory. That\nno longer applies: **v1 is tested**, with `gno` built from `origin/master`, and\nit passes `make test` and `make lint` alongside the rest of the repo.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/rpsoracle) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline` helper.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/rpsoracle/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsoracle/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/rpsoracle/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsoracle/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/rpsoracle/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsoracle/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/rpsoracle/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/rpsoracle/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/rpsoracle/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/rpsoracle/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/rpsoracle/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package rpsoracle\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Rock-Paper-Scissors Oracle\n\t//\n\t// An adaptive opponent: it doesn't roll dice, it studies you. Every throw is logged, and the oracle always counters whichever move you've played most often. Play a uniform mixed strategy and it can't out-guess you; fall into a habit and it will.\n\t//\n\t// - Total rounds played: 0\n\t// - No one has beaten the oracle yet.\n\t//\n\t// ## How to play\n\t//\n\t// Call `Play(\"rock\"|\"paper\"|\"scissors\")` (or `r`/`p`/`s`). View your own record at this realm's path plus your address, e.g. `.../rpsoracle:g1youraddress...`\n}\n"},{"name":"rpsoracle.gno","body":"// Package rpsoracle is a rock-paper-scissors opponent that doesn't roll\n// dice: it studies each player's move history and always throws the\n// counter to whichever move that player has favored most. Play a fixed\n// pattern and the oracle punishes it; play close to a uniform 1/3-1/3-1/3\n// mix and it can't out-guess you better than chance.\npackage rpsoracle\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// Move is one of rock, paper, or scissors, ordered so that\n// (winner - loser + 3) % 3 == 1 for every winning pair.\ntype Move int\n\nconst (\n\tRock Move = iota\n\tPaper\n\tScissors\n)\n\nfunc moveName(m Move) string {\n\tswitch m {\n\tcase Rock:\n\t\treturn \"rock\"\n\tcase Paper:\n\t\treturn \"paper\"\n\tcase Scissors:\n\t\treturn \"scissors\"\n\tdefault:\n\t\treturn \"?\"\n\t}\n}\n\nfunc parseMove(s string) (Move, bool) {\n\tswitch strings.ToLower(strings.TrimSpace(s)) {\n\tcase \"rock\", \"r\":\n\t\treturn Rock, true\n\tcase \"paper\", \"p\":\n\t\treturn Paper, true\n\tcase \"scissors\", \"s\":\n\t\treturn Scissors, true\n\tdefault:\n\t\treturn 0, false\n\t}\n}\n\n// judge returns 0 for a tie, 1 if p beats h, 2 if h beats p.\nfunc judge(p, h Move) int {\n\treturn (int(p) - int(h) + 3) % 3\n}\n\n// beats returns the move that defeats m.\nfunc beats(m Move) Move {\n\treturn Move((int(m) + 1) % 3)\n}\n\n// playerState is the persisted record for one address.\ntype playerState struct {\n\tCounts     [3]int // history tally per move, what the oracle predicts from\n\tRounds     int\n\tWins       int // player beat the oracle\n\tLosses     int // oracle beat the player\n\tDraws      int\n\tBestStreak int\n\tstreak     int // current player win streak against the oracle\n}\n\nvar (\n\tplayers avl.Tree // address string -\u003e *playerState\n\n\tnonce         int\n\ttotalRounds   int\n\toracleCorrect int // rounds the oracle won by successfully countering\n\n\ttopOutwitter     address\n\ttopOutwitterWins int\n)\n\nfunc getOrCreate(addr address) *playerState {\n\tkey := addr.String()\n\tif v := players.Get(key); v != nil {\n\t\treturn v.(*playerState)\n\t}\n\tps := \u0026playerState{}\n\tplayers.Set(key, ps)\n\treturn ps\n}\n\n// predict guesses the player's next move as the most-played move in their\n// history so far. Ties (including a fresh player's all-zero history) fall\n// back to a chain-height-derived seed so the oracle doesn't always break\n// ties the same way.\nfunc predict(ps *playerState, seed int64) Move {\n\tbest := Rock\n\tbestCount := ps.Counts[Rock]\n\ttied := []Move{Rock}\n\tfor _, m := range []Move{Paper, Scissors} {\n\t\tswitch {\n\t\tcase ps.Counts[m] \u003e bestCount:\n\t\t\tbestCount = ps.Counts[m]\n\t\t\tbest = m\n\t\t\ttied = []Move{m}\n\t\tcase ps.Counts[m] == bestCount:\n\t\t\ttied = append(tied, m)\n\t\t}\n\t}\n\tif len(tied) \u003e 1 {\n\t\tif seed \u003c 0 {\n\t\t\tseed = -seed\n\t\t}\n\t\tbest = tied[int(seed)%len(tied)]\n\t}\n\treturn best\n}\n\n// Play pits the caller against the oracle: it predicts your next move from\n// your own move history and throws the counter. Accepts\n// \"rock\"/\"paper\"/\"scissors\" or the single-letter shorthand \"r\"/\"p\"/\"s\".\nfunc Play(cur realm, moveStr string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"invalid realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\n\tplayerMove, ok := parseMove(moveStr)\n\tif !ok {\n\t\tpanic(\"invalid move: use rock, paper, or scissors (r/p/s)\")\n\t}\n\n\tps := getOrCreate(caller)\n\n\tnonce++\n\tseed := runtime.ChainHeight() + int64(nonce)\n\tpredicted := predict(ps, seed)\n\toracleMove := beats(predicted)\n\n\tresult := judge(playerMove, oracleMove)\n\n\tps.Counts[playerMove]++\n\tps.Rounds++\n\ttotalRounds++\n\n\tvar msg string\n\tswitch result {\n\tcase 1:\n\t\tps.Wins++\n\t\tps.streak++\n\t\tif ps.streak \u003e ps.BestStreak {\n\t\t\tps.BestStreak = ps.streak\n\t\t}\n\t\tif ps.Wins \u003e topOutwitterWins {\n\t\t\ttopOutwitterWins = ps.Wins\n\t\t\ttopOutwitter = caller\n\t\t}\n\t\tmsg = \"you outwitted the oracle!\"\n\tcase 2:\n\t\tps.Losses++\n\t\tps.streak = 0\n\t\toracleCorrect++\n\t\tmsg = \"the oracle read you like a book.\"\n\tdefault:\n\t\tps.Draws++\n\t\tps.streak = 0\n\t\tmsg = \"a draw — you and the oracle picked the same move.\"\n\t}\n\n\tchain.Emit(\"RoundPlayed\",\n\t\t\"player\", caller.String(),\n\t\t\"playerMove\", moveName(playerMove),\n\t\t\"oraclePredicted\", moveName(predicted),\n\t\t\"oracleMove\", moveName(oracleMove),\n\t\t\"result\", strconv.Itoa(result),\n\t)\n\n\treturn \"you played \" + moveName(playerMove) + \", the oracle predicted \" +\n\t\tmoveName(predicted) + \" and threw \" + moveName(oracleMove) + \" -\u003e \" + msg\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Rock-Paper-Scissors Oracle\\n\\n\")\n\tb.WriteString(\"An adaptive opponent: it doesn't roll dice, it studies you. \")\n\tb.WriteString(\"Every throw is logged, and the oracle always counters whichever \")\n\tb.WriteString(\"move you've played most often. Play a uniform mixed strategy and \")\n\tb.WriteString(\"it can't out-guess you; fall into a habit and it will.\\n\\n\")\n\n\tb.WriteString(\"- Total rounds played: \" + strconv.Itoa(totalRounds) + \"\\n\")\n\tif totalRounds \u003e 0 {\n\t\tpct := oracleCorrect * 100 / totalRounds\n\t\tb.WriteString(\"- Oracle win rate: \" + strconv.Itoa(pct) + \"%\\n\")\n\t}\n\tif topOutwitter.IsValid() {\n\t\tb.WriteString(\"- Top outwitter: `\" + topOutwitter.String() + \"` (\" +\n\t\t\tstrconv.Itoa(topOutwitterWins) + \" wins against the oracle)\\n\")\n\t} else {\n\t\tb.WriteString(\"- No one has beaten the oracle yet.\\n\")\n\t}\n\n\tb.WriteString(\"\\n## How to play\\n\\n\")\n\tb.WriteString(\"Call `Play(\\\"rock\\\"|\\\"paper\\\"|\\\"scissors\\\")` (or `r`/`p`/`s`). \")\n\tb.WriteString(\"View your own record at this realm's path plus your address, \")\n\tb.WriteString(\"e.g. `.../rpsoracle:g1youraddress...`\\n\")\n\treturn b.String()\n}\n\nfunc renderPlayer(rawAddr string) string {\n\taddr := strings.TrimSpace(rawAddr)\n\tsafe := ui.Inline(addr)\n\n\tv := players.Get(addr)\n\tif v == nil {\n\t\treturn \"# Player \" + safe + \"\\n\\nNo recorded rounds yet.\\n\"\n\t}\n\tps := v.(*playerState)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Player \" + safe + \"\\n\\n\")\n\tb.WriteString(\"- Rounds played: \" + strconv.Itoa(ps.Rounds) + \"\\n\")\n\tb.WriteString(\"- Beat the oracle: \" + strconv.Itoa(ps.Wins) + \"\\n\")\n\tb.WriteString(\"- Lost to the oracle: \" + strconv.Itoa(ps.Losses) + \"\\n\")\n\tb.WriteString(\"- Draws: \" + strconv.Itoa(ps.Draws) + \"\\n\")\n\tb.WriteString(\"- Best win streak vs oracle: \" + strconv.Itoa(ps.BestStreak) + \"\\n\")\n\tb.WriteString(\"- Move history — rock: \" + strconv.Itoa(ps.Counts[Rock]) +\n\t\t\", paper: \" + strconv.Itoa(ps.Counts[Paper]) +\n\t\t\", scissors: \" + strconv.Itoa(ps.Counts[Scissors]) + \"\\n\")\n\n\tif ps.Rounds \u003e 0 {\n\t\tmaxCount := ps.Counts[Rock]\n\t\tfor _, c := range ps.Counts[1:] {\n\t\t\tif c \u003e maxCount {\n\t\t\t\tmaxCount = c\n\t\t\t}\n\t\t}\n\t\tpredictability := maxCount * 100 / ps.Rounds\n\t\tb.WriteString(\"- Predictability score: \" + strconv.Itoa(predictability) +\n\t\t\t\"% (lower is harder for the oracle to read)\\n\")\n\t}\n\treturn b.String()\n}\n\n// Render shows the oracle's dashboard at \"\", or one player's record when\n// path is their bech32 address.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderPlayer(path)\n}\n"},{"name":"rpsoracle_test.gno","body":"package rpsoracle\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tplayers = avl.Tree{}\n\tnonce = 0\n\ttotalRounds = 0\n\toracleCorrect = 0\n\tvar zero address\n\ttopOutwitter = zero\n\ttopOutwitterWins = 0\n}\n\nfunc TestJudge(t *testing.T) {\n\tcases := []struct {\n\t\tp, h Move\n\t\twant int\n\t}{\n\t\t{Rock, Rock, 0},\n\t\t{Paper, Paper, 0},\n\t\t{Scissors, Scissors, 0},\n\t\t{Paper, Rock, 1},\n\t\t{Scissors, Paper, 1},\n\t\t{Rock, Scissors, 1},\n\t\t{Rock, Paper, 2},\n\t\t{Paper, Scissors, 2},\n\t\t{Scissors, Rock, 2},\n\t}\n\tfor _, c := range cases {\n\t\tif got := judge(c.p, c.h); got != c.want {\n\t\t\tt.Fatalf(\"judge(%v,%v) = %d, want %d\", c.p, c.h, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestBeats(t *testing.T) {\n\tif beats(Rock) != Paper {\n\t\tt.Fatal(\"beats(Rock) should be Paper\")\n\t}\n\tif beats(Paper) != Scissors {\n\t\tt.Fatal(\"beats(Paper) should be Scissors\")\n\t}\n\tif beats(Scissors) != Rock {\n\t\tt.Fatal(\"beats(Scissors) should be Rock\")\n\t}\n}\n\nfunc TestParseMove(t *testing.T) {\n\tfor _, s := range []string{\"rock\", \"Rock\", \" r \", \"paper\", \"P\", \"scissors\", \"S\"} {\n\t\tif _, ok := parseMove(s); !ok {\n\t\t\tt.Fatalf(\"parseMove(%q) should be valid\", s)\n\t\t}\n\t}\n\tif _, ok := parseMove(\"lizard\"); ok {\n\t\tt.Fatal(\"parseMove(\\\"lizard\\\") should be invalid\")\n\t}\n}\n\nfunc TestPredictPicksMostFrequent(t *testing.T) {\n\tps := \u0026playerState{}\n\tps.Counts[Paper] = 5\n\tps.Counts[Rock] = 1\n\tif got := predict(ps, 0); got != Paper {\n\t\tt.Fatalf(\"predict = %v, want Paper\", got)\n\t}\n}\n\n// Crossing: Play mutates realm state, so the test needs `cur realm`.\nfunc TestOracleCountersPredictableRock(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tfor i := 0; i \u003c 5; i++ {\n\t\tPlay(cross(cur), \"rock\")\n\t}\n\tps := getOrCreate(alice)\n\tif ps.Losses == 0 {\n\t\tt.Fatal(\"expected the oracle to eventually counter an all-rock player\")\n\t}\n\tif ps.Rounds != 5 {\n\t\tt.Fatalf(\"Rounds = %d, want 5\", ps.Rounds)\n\t}\n}\n\n// Non-crossing: Render is a plain read.\nfunc TestRenderHome(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif out == \"\" {\n\t\tt.Fatal(\"Render(\\\"\\\") should not be empty\")\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"49512800","gas_fee":"148538ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"4lxS9UAEv4kB8vs+xELRQOzxrQzjPlrZhyK7nkrDTj9PE9P7c3jwo+J7YZtq/1RH/cxF5MeIjR2d5QK9Pro/hw=="}],"memo":""},"metadata":{"timestamp":"1790961383"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"semverdemo","path":"gno.land/r/moul/x/daily/semverdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/semverdemo/v0`\n\nLive demo of the [`p/moul/x/daily/semver`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/semver)\nSemantic Versioning library.\n\nHolds the realm state the pure library deliberately does not — a \"submitted\nversions\" board (an `avl.Tree` of version string → submitter address) — and\nwires it to the chain, keying each submission by `unsafe.PreviousRealm().Address()`:\n\n- `Submit(cur, version)` — validate with `semver.Parse` and post a version on-chain.\n- `Render(\"/\")` — overview plus a table of worked examples.\n- `Render(\"/\u003ca\u003e/\u003cb\u003e\")` — parse both and show the comparison, e.g. `/1.2.3/1.2.10`.\n- `Render(\"/sorted\")` — everyone's submissions, lowest → highest precedence.\n\nAll parsing and comparison math lives in the library; this realm is just the\nboard, the wiring, and the gnoweb view. Render it at\n[`/r/moul/x/daily/semverdemo/v0`](https://gno.land/r/moul/x/daily/semverdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/semverdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/semverdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/semverdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/semverdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/semverdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/semverdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/semverdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/semverdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/semverdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/semverdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/semverdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package semverdemo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # semver — Semantic Versioning on-chain\n\t//\n\t// Demo of the [`p/moul/x/daily/semver`](/p/moul/x/daily/semver/v0) library — a port of `golang.org/x/mod/semver`. Parse `vMAJOR.MINOR.PATCH[-prerelease][+build]` and compare with SemVer 2.0.0 precedence.\n\t//\n\t// ## Examples\n\t//\n\t// | a | rel | b | note |\n\t// |---|:---:|---|---|\n\t// | `1.2.3` | \u0026lt; | `1.2.10` | numeric patch, not lexical |\n\t// | `1.0.0-alpha` | \u0026lt; | `1.0.0` | pre-release \u003c release |\n\t// | `1.0.0-alpha.1` | \u0026lt; | `1.0.0-alpha.beta` | numeric id \u003c alphanumeric id |\n\t// | `1.0.0-rc.1` | \u0026lt; | `1.0.0` | release candidate \u003c final |\n\t// | `2.0.0` | = | `2.0.0+build.5` | build metadata ignored |\n\t//\n\t// ## Try it\n\t//\n\t// - Compare two versions: [`/1.2.3/1.2.10`](/r/moul/x/daily/semverdemo/v0:1.2.3/1.2.10)\n\t// - Submitted list: [`/sorted`](/r/moul/x/daily/semverdemo/v0:sorted)\n\t// - Submit on-chain: `Submit(\"v1.4.2\")`\n}\n"},{"name":"semverdemo.gno","body":"// Package semverdemo is a small on-chain demo of the semantic-versioning\n// parser/comparator provided by the\n// [p/moul/x/daily/semver](/p/moul/x/daily/semver/v0) library.\n//\n// It holds the realm state the pure library deliberately does not: a\n// \"submitted versions\" board (an avl tree of version string -\u003e submitter\n// address) that anyone can post to with [Submit], plus a gnoweb [Render] view\n// that lists them in SemVer precedence order and compares arbitrary pairs. All\n// parsing and comparison math lives in the library; this realm is just the\n// on-chain wiring and the view.\npackage semverdemo\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/x/daily/semver/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// submitted holds versions users have posted on-chain: version string -\u003e submitter.\nvar submitted = avl.NewTree()\n\n// Submit stores a valid version on-chain, tagged with the caller's address, so\n// Render(\"/sorted\") can list everyone's submissions in precedence order. It\n// validates the input with [semver.Parse] and panics on anything malformed.\nfunc Submit(cur realm, version string) {\n\tif _, err := semver.Parse(version); err != nil {\n\t\tpanic(\"invalid semantic version: \" + version)\n\t}\n\twho := unsafe.PreviousRealm().Address()\n\tsubmitted.Set(version, who.String())\n\tchain.Emit(\"VersionSubmitted\", \"version\", version, \"by\", who.String())\n}\n\n// ---- Render ----------------------------------------------------------------\n\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tswitch {\n\tcase path == \"\":\n\t\treturn renderHome()\n\tcase path == \"sorted\":\n\t\treturn renderSorted()\n\tdefault:\n\t\tparts := strings.SplitN(path, \"/\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn renderHome()\n\t\t}\n\t\treturn renderCompare(parts[0], parts[1])\n\t}\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# semver — Semantic Versioning on-chain\\n\\n\")\n\tb.WriteString(\"Demo of the [`p/moul/x/daily/semver`](/p/moul/x/daily/semver/v0) \")\n\tb.WriteString(\"library — a port of `golang.org/x/mod/semver`. Parse \")\n\tb.WriteString(\"`vMAJOR.MINOR.PATCH[-prerelease][+build]` and compare with \")\n\tb.WriteString(\"SemVer 2.0.0 precedence.\\n\\n\")\n\n\tb.WriteString(\"## Examples\\n\\n\")\n\tb.WriteString(\"| a | rel | b | note |\\n|---|:---:|---|---|\\n\")\n\texamples := [][2]string{\n\t\t{\"1.2.3\", \"1.2.10\"},\n\t\t{\"1.0.0-alpha\", \"1.0.0\"},\n\t\t{\"1.0.0-alpha.1\", \"1.0.0-alpha.beta\"},\n\t\t{\"1.0.0-rc.1\", \"1.0.0\"},\n\t\t{\"2.0.0\", \"2.0.0+build.5\"},\n\t}\n\tnotes := []string{\n\t\t\"numeric patch, not lexical\",\n\t\t\"pre-release \u003c release\",\n\t\t\"numeric id \u003c alphanumeric id\",\n\t\t\"release candidate \u003c final\",\n\t\t\"build metadata ignored\",\n\t}\n\tfor i, ex := range examples {\n\t\tb.WriteString(\"| `\" + ex[0] + \"` | \" + relSym(semver.Compare(ex[0], ex[1])) +\n\t\t\t\" | `\" + ex[1] + \"` | \" + notes[i] + \" |\\n\")\n\t}\n\n\tb.WriteString(\"\\n## Try it\\n\\n\")\n\tb.WriteString(\"- Compare two versions: [`/1.2.3/1.2.10`](/r/moul/x/daily/semverdemo/v0:1.2.3/1.2.10)\\n\")\n\tb.WriteString(\"- Submitted list: [`/sorted`](/r/moul/x/daily/semverdemo/v0:sorted)\\n\")\n\tb.WriteString(\"- Submit on-chain: `Submit(\\\"v1.4.2\\\")`\\n\")\n\treturn b.String()\n}\n\nfunc renderCompare(a, b string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Compare\\n\\n\")\n\tsb.WriteString(describe(\"A\", a))\n\tsb.WriteString(describe(\"B\", b))\n\n\t_, ea := semver.Parse(a)\n\t_, eb := semver.Parse(b)\n\tif ea != nil || eb != nil {\n\t\tsb.WriteString(\"\\n\u003e One or both inputs are not valid semver.\\n\")\n\t\treturn sb.String()\n\t}\n\tc := semver.Compare(a, b)\n\tsb.WriteString(\"\\n## Result\\n\\n\")\n\tsb.WriteString(\"`\" + a + \"` **\" + word(c) + \"** `\" + b + \"`  \")\n\tsb.WriteString(\"→ `Compare = \" + strconv.Itoa(c) + \"`\\n\")\n\treturn sb.String()\n}\n\nfunc describe(label, s string) string {\n\tv, err := semver.Parse(s)\n\tif err != nil {\n\t\treturn \"## \" + label + \": `\" + s + \"`\\n\\n\u003e invalid\\n\\n\"\n\t}\n\tpre := \"—\"\n\tif len(v.Pre) \u003e 0 {\n\t\tpre = \"`\" + strings.Join(v.Pre, \".\") + \"`\"\n\t}\n\tbuild := \"—\"\n\tif v.Build != \"\" {\n\t\tbuild = \"`\" + v.Build + \"`\"\n\t}\n\treturn \"## \" + label + \": `\" + v.Canonical() + \"`\\n\\n\" +\n\t\t\"| major | minor | patch | pre | build |\\n|---|---|---|---|---|\\n\" +\n\t\t\"| \" + strconv.Itoa(v.Major) + \" | \" + strconv.Itoa(v.Minor) + \" | \" + strconv.Itoa(v.Patch) +\n\t\t\" | \" + pre + \" | \" + build + \" |\\n\\n\"\n}\n\nfunc renderSorted() string {\n\tvar es []entry\n\t// Capture the submitter straight from Iterate's callback value, avoiding a\n\t// separate avl.Get whose arity differs across gno versions.\n\tsubmitted.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tif v, err := semver.Parse(key); err == nil {\n\t\t\twho, _ := value.(string)\n\t\t\tes = append(es, entry{v: v, who: who})\n\t\t}\n\t\treturn false\n\t})\n\tif len(es) == 0 {\n\t\treturn \"# Submitted versions\\n\\n_None yet._ Call `Submit(\\\"v1.0.0\\\")` to add one.\\n\"\n\t}\n\tsort.Stable(byPrecedence(es))\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Submitted versions (lowest → highest)\\n\\n\")\n\tb.WriteString(\"| # | version | submitter |\\n|---|---|---|\\n\")\n\tfor i, e := range es {\n\t\tb.WriteString(\"| \" + strconv.Itoa(i+1) + \" | `\" + e.v.Canonical() + \"` | `\" + e.who + \"` |\\n\")\n\t}\n\treturn b.String()\n}\n\n// entry pairs a parsed version with the address that submitted it.\ntype entry struct {\n\tv   semver.Version\n\twho string\n}\n\n// byPrecedence sorts entries ascending. `sort` on-chain has no Slice helper,\n// so we implement sort.Interface; ordering defers to semver.Compare on the\n// original strings.\ntype byPrecedence []entry\n\nfunc (p byPrecedence) Len() int { return len(p) }\nfunc (p byPrecedence) Less(i, j int) bool {\n\treturn semver.Compare(p[i].v.Orig, p[j].v.Orig) \u003c 0\n}\nfunc (p byPrecedence) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\n\nfunc relSym(c int) string {\n\tswitch {\n\tcase c \u003c 0:\n\t\treturn \"\u0026lt;\"\n\tcase c \u003e 0:\n\t\treturn \"\u0026gt;\"\n\t}\n\treturn \"=\"\n}\n\nfunc word(c int) string {\n\tswitch {\n\tcase c \u003c 0:\n\t\treturn \"\u003c\"\n\tcase c \u003e 0:\n\t\treturn \"\u003e\"\n\t}\n\treturn \"==\"\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"36377600","gas_fee":"109132ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"xCw3nb2QSauQyUfZu6Xq34a7tV27uV7O3pmogTyw95NFq073AI2uQmJQfNdRSVcwwmvnSmLHtq1UKjt1FKT02w=="}],"memo":""},"metadata":{"timestamp":"1790961387"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"sievedemo","path":"gno.land/r/moul/x/daily/sievedemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/sievedemo/v0`\n\nInteractive gnoweb **demo of the [`p/moul/x/daily/sieve`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/sieve)\nSieve of Eratosthenes library** — it renders the count of primes up to `MaxN`,\nthe first 100 primes, and a \"primes up to n\" grid. It has no sieve logic of its own.\n\nAppend a number to the path to sieve up to any n (max 10000), e.g.\n[`/r/moul/x/daily/sievedemo/v0:1000`](https://gno.land/r/moul/x/daily/sievedemo/v0:1000).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/sievedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sievedemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/sievedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sievedemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/sievedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sievedemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/sievedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sievedemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/sievedemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/sievedemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/sievedemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package sievedemo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Sieve of Eratosthenes\n\t//\n\t// A deterministic on-chain port of Go's classic concurrent prime-sieve example, demoing the [`p/moul/x/daily/sieve`](/p/moul/x/daily/sieve/v0) library.\n\t//\n\t// There are **1229** primes up to 10000.\n\t//\n\t// ## First 100 primes\n\t//\n\t// | · | · | · | · | · | · | · | · | · | · |\n\t// |---|---|---|---|---|---|---|---|---|---|\n\t// | 2 | 3 | 5 | 7 | 11 | 13 | 17 | 19 | 23 | 29 |\n\t// | 31 | 37 | 41 | 43 | 47 | 53 | 59 | 61 | 67 | 71 |\n\t// | 73 | 79 | 83 | 89 | 97 | 101 | 103 | 107 | 109 | 113 |\n\t// | 127 | 131 | 137 | 139 | 149 | 151 | 157 | 163 | 167 | 173 |\n\t// | 179 | 181 | 191 | 193 | 197 | 199 | 211 | 223 | 227 | 229 |\n\t// | 233 | 239 | 241 | 251 | 257 | 263 | 269 | 271 | 277 | 281 |\n\t// | 283 | 293 | 307 | 311 | 313 | 317 | 331 | 337 | 347 | 349 |\n\t// | 353 | 359 | 367 | 373 | 379 | 383 | 389 | 397 | 401 | 409 |\n\t// | 419 | 421 | 431 | 433 | 439 | 443 | 449 | 457 | 461 | 463 |\n\t// | 467 | 479 | 487 | 491 | 499 | 503 | 509 | 521 | 523 | 541 |\n\t//\n\t// \u003e Try `/500` or `/1000` to sieve up to any n (max 10000).\n}\n"},{"name":"sievedemo.gno","body":"// Package sievedemo is a small gnoweb demo of the Sieve of Eratosthenes\n// provided by the [p/moul/x/daily/sieve](/p/moul/x/daily/sieve/v0) library: it\n// renders the primes up to MaxN, the first 100 primes, and an interactive\n// \"primes up to n\" grid.\n//\n// It contains no sieve logic of its own — everything comes from\n// `sieve.PrimesUpTo` and `sieve.MaxN`.\npackage sievedemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/sieve/v0\"\n)\n\n// Render renders the sieve for gnoweb.\n//\n//\tRender(\"\")      / Render(\"/\") -\u003e first 100 primes + total count up to MaxN\n//\tRender(\"/\u003cn\u003e\")               -\u003e every prime \u003c= n, laid out as a grid\nfunc Render(path string) string {\n\tn, hasN := parseN(path)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Sieve of Eratosthenes\\n\\n\")\n\tb.WriteString(\"A deterministic on-chain port of Go's classic concurrent prime-sieve example, \")\n\tb.WriteString(\"demoing the [`p/moul/x/daily/sieve`](/p/moul/x/daily/sieve/v0) library.\\n\\n\")\n\n\tif !hasN {\n\t\tprimes := sieve.PrimesUpTo(sieve.MaxN)\n\t\tb.WriteString(\"There are **\")\n\t\tb.WriteString(strconv.Itoa(len(primes)))\n\t\tb.WriteString(\"** primes up to \")\n\t\tb.WriteString(strconv.Itoa(sieve.MaxN))\n\t\tb.WriteString(\".\\n\\n\")\n\t\tb.WriteString(\"## First 100 primes\\n\\n\")\n\t\tfirst := primes\n\t\tif len(first) \u003e 100 {\n\t\t\tfirst = first[:100]\n\t\t}\n\t\tb.WriteString(grid(first, 10))\n\t\tb.WriteString(\"\\n\u003e Try `/500` or `/1000` to sieve up to any n (max \")\n\t\tb.WriteString(strconv.Itoa(sieve.MaxN))\n\t\tb.WriteString(\").\\n\")\n\t\treturn b.String()\n\t}\n\n\tif n \u003c 2 {\n\t\tb.WriteString(\"No primes \u003c= \")\n\t\tb.WriteString(strconv.Itoa(n))\n\t\tb.WriteString(\".\\n\")\n\t\treturn b.String()\n\t}\n\n\tclamped := n\n\tif clamped \u003e sieve.MaxN {\n\t\tclamped = sieve.MaxN\n\t}\n\tprimes := sieve.PrimesUpTo(clamped)\n\tb.WriteString(\"## Primes up to \")\n\tb.WriteString(strconv.Itoa(clamped))\n\tif clamped != n {\n\t\tb.WriteString(\" (clamped from \")\n\t\tb.WriteString(strconv.Itoa(n))\n\t\tb.WriteString(\")\")\n\t}\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(\"Count: **\")\n\tb.WriteString(strconv.Itoa(len(primes)))\n\tb.WriteString(\"**\\n\\n\")\n\tb.WriteString(grid(primes, 10))\n\treturn b.String()\n}\n\n// parseN extracts n from a Render path like \"/1000\". Returns hasN=false for\n// the empty/root path.\nfunc parseN(path string) (int, bool) {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif s == \"\" {\n\t\treturn 0, false\n\t}\n\t// keep only the first segment\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\tv, err := strconv.Atoi(s)\n\tif err != nil {\n\t\treturn 0, false\n\t}\n\treturn v, true\n}\n\n// grid formats primes into a Markdown table with `cols` columns per row.\nfunc grid(primes []int, cols int) string {\n\tif len(primes) == 0 {\n\t\treturn \"_none_\\n\"\n\t}\n\tif cols \u003c 1 {\n\t\tcols = 1\n\t}\n\n\tvar b strings.Builder\n\t// header + separator so gnoweb renders it as a table\n\tb.WriteString(\"|\")\n\tfor c := 0; c \u003c cols; c++ {\n\t\tb.WriteString(\" · |\")\n\t}\n\tb.WriteString(\"\\n|\")\n\tfor c := 0; c \u003c cols; c++ {\n\t\tb.WriteString(\"---|\")\n\t}\n\tb.WriteString(\"\\n\")\n\n\tfor i := 0; i \u003c len(primes); i += cols {\n\t\tb.WriteString(\"|\")\n\t\tfor c := 0; c \u003c cols; c++ {\n\t\t\tb.WriteString(\" \")\n\t\t\tif i+c \u003c len(primes) {\n\t\t\t\tb.WriteString(strconv.Itoa(primes[i+c]))\n\t\t\t}\n\t\t\tb.WriteString(\" |\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\treturn b.String()\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"28814200","gas_fee":"86442ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"zAPZpRKjJqvvV/H8i6bA6gCF2BRRnX7wy9YFzHxKdSAX2jSlW57IutEn96NE+f7VF6DPsMyauPyxHf2ZuXcCKQ=="}],"memo":""},"metadata":{"timestamp":"1790961387"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"soundexdemo","path":"gno.land/r/moul/x/daily/soundexdemo/v0","files":[{"name":"README.md","body":"# Soundex\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nKeys a small name list and groups it by phonetic key, so the \"sounds alike\"\nclusters are visible.\n\n```\n/r/moul/x/daily/soundexdemo/v0            → the table + clusters\n/r/moul/x/daily/soundexdemo/v0:Ashcroft   → one name's key\n```\n\nDemo of the [`p/moul/x/daily/soundex`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/soundex)\nlibrary — no phonetic logic lives here. Stateless, so `Render` is deterministic:\nnames are grouped in **first-seen order**, never by iterating a map.\n\nThe list is picked for near-collisions — `Robert`/`Rupert` cluster, `Rubin`\ndoes not, and `Pfister`/`Tymczak`/`Ashcraft` are the cases that catch naive\nimplementations.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/soundexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/soundexdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/soundexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/soundexdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/soundexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/soundexdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/soundexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/soundexdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/soundexdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/soundexdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/soundexdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package soundexdemo\n\n// ExampleRender pins the realm's root Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Soundex\n\t//\n\t// Phonetic keys for English names, demoing the [`p/moul/x/daily/soundex`](/p/moul/x/daily/soundex/v0) library.\n\t//\n\t// | name | key |\n\t// |---|---|\n\t// | Robert | `R163` |\n\t// | Rupert | `R163` |\n\t// | Rubin | `R150` |\n\t// | Ashcraft | `A261` |\n\t// | Ashcroft | `A261` |\n\t// | Tymczak | `T522` |\n\t// | Pfister | `P236` |\n\t// | Honeyman | `H555` |\n\t//\n\t// ## Sounds alike\n\t//\n\t// - **R163**: Robert, Rupert\n\t// - **A261**: Ashcraft, Ashcroft\n\t//\n\t// \u003e A *blocking* key for finding candidates, never proof that two names match.\n}\n\n// ExampleRender_noLetters pins the empty-key path: an input with no ASCII\n// letters has no Soundex key at all, and must not be reported as matching.\nfunc ExampleRender_noLetters() {\n\tprint(Render(\"/12345\"))\n\t// Output:\n\t// # Soundex\n\t//\n\t// Phonetic keys for English names, demoing the [`p/moul/x/daily/soundex`](/p/moul/x/daily/soundex/v0) library.\n\t//\n\t// ## `12345`\n\t//\n\t// _No ASCII letters — no key._\n}\n"},{"name":"soundexdemo.gno","body":"// Package soundexdemo is a small gnoweb demo of the Soundex phonetic algorithm\n// provided by the [p/moul/x/daily/soundex](/p/moul/x/daily/soundex/v0) library:\n// it groups a small name list by phonetic key so the \"sounds alike\" clusters\n// are visible.\n//\n// It contains no phonetic logic of its own. Stateless, so Render is\n// deterministic — names are grouped in first-seen order, never by iterating a\n// map.\npackage soundexdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/soundex/v0\"\n)\n\n// names include several deliberate near-collisions.\nvar names = []string{\n\t\"Robert\", \"Rupert\", \"Rubin\",\n\t\"Ashcraft\", \"Ashcroft\",\n\t\"Tymczak\", \"Pfister\", \"Honeyman\",\n}\n\n// Render renders the demo for gnoweb.\n//\n//\tRender(\"\")       / Render(\"/\") -\u003e the name table + clusters\n//\tRender(\"/\u003cname\u003e\")              -\u003e that name's key\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Soundex\\n\\n\")\n\tb.WriteString(\"Phonetic keys for English names, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/soundex`](/p/moul/x/daily/soundex/v0) library.\\n\\n\")\n\n\tif q := parseArg(path); q != \"\" {\n\t\tk := soundex.Encode(q)\n\t\tb.WriteString(\"## `\")\n\t\tb.WriteString(q)\n\t\tb.WriteString(\"`\\n\\n\")\n\t\tif k == \"\" {\n\t\t\tb.WriteString(\"_No ASCII letters — no key._\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"key: **\")\n\t\t\tb.WriteString(k)\n\t\t\tb.WriteString(\"** (normalized: `\")\n\t\t\tb.WriteString(soundex.Normalize(q))\n\t\t\tb.WriteString(\"`)\\n\")\n\t\t}\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| name | key |\\n|---|---|\\n\")\n\tfor _, n := range names {\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(n)\n\t\tb.WriteString(\" | `\")\n\t\tb.WriteString(soundex.Encode(n))\n\t\tb.WriteString(\"` |\\n\")\n\t}\n\n\t// group by key, preserving first-seen order (never iterate a map)\n\tb.WriteString(\"\\n## Sounds alike\\n\\n\")\n\tkeys := []string{}\n\tbyKey := map[string][]string{}\n\tfor _, n := range names {\n\t\tk := soundex.Encode(n)\n\t\tif _, seen := byKey[k]; !seen {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tbyKey[k] = append(byKey[k], n)\n\t}\n\tfor _, k := range keys {\n\t\tif len(byKey[k]) \u003c 2 {\n\t\t\tcontinue\n\t\t}\n\t\tb.WriteString(\"- **\")\n\t\tb.WriteString(k)\n\t\tb.WriteString(\"**: \")\n\t\tb.WriteString(strings.Join(byKey[k], \", \"))\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"\\n\u003e A *blocking* key for finding candidates, never proof that two names match.\\n\")\n\treturn b.String()\n}\n\nfunc parseArg(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"27789800","gas_fee":"83369ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"Izx1rpgE6JOvFAwL/MI7Ww7yhfHZ0c05qYZu80rMNGAC/xfCPdOROlP7dsbjZbY78W/773Ie/I0bu4Zy9jEE+A=="}],"memo":""},"metadata":{"timestamp":"1790961388"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"sparklinedemo","path":"gno.land/r/moul/x/daily/sparklinedemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/sparklinedemo/v0`\n\nA gnoweb demo of the [`p/moul/x/daily/sparkline`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/sparkline)\nlibrary: it sparks a handful of fixed series and shows the three behaviours\nworth knowing before putting one in a realm — a flat series rendering mid-ramp,\na fixed window clamping its outliers, and floor rounding keeping the peak\ndistinct.\n\nIt holds no state and contains no rendering logic of its own; the series are\nhard-coded rather than read from chain state, so `Render` is deterministic and\nits output is pinned by an example test.\n\nRender it at [`/r/moul/x/daily/sparklinedemo/v0`](https://gno.land/r/moul/x/daily/sparklinedemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/sparklinedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sparklinedemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/sparklinedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sparklinedemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/sparklinedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sparklinedemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/sparklinedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/sparklinedemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/sparklinedemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/sparklinedemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/sparklinedemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package sparklinedemo\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Sparklines\n\t//\n\t// A numeric series as one line of block characters, demoing the [`p/moul/x/daily/sparkline`](/p/moul/x/daily/sparkline/v0) library.\n\t//\n\t// ## A series\n\t//\n\t// `▁▁▂▄▃▅█▆▅▃▂▁`\n\t//\n\t// `3, 5, 9, 14, 12, 18, 25, 21, 16, 11, 7, 4`\n\t//\n\t// Scaled between its own bounds, `3` and `25`. The shape is the point; the axis is not.\n\t//\n\t// ## The ramp\n\t//\n\t// `▁▂▃▄▅▆▇█` — eight levels, low to high.\n\t//\n\t// | value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n\t// |---|---|---|---|---|---|---|---|---|\n\t// | level | `▁` | `▂` | `▃` | `▄` | `▅` | `▆` | `▇` | `█` |\n\t//\n\t// ## A flat series\n\t//\n\t// `▅▅▅▅` — `1000, 1000, 1000, 1000`\n\t//\n\t// Mid-ramp, not along the floor. A series that never moves has no shape, but drawing it at the bottom would claim it was *zero*, which is a different thing and a wrong one.\n\t//\n\t// ## Negatives\n\t//\n\t// `▁▃▄▅█▅▂` — `-8, -3, 0, 4, 9, 2, -5`\n\t//\n\t// Nothing special: the window is the minimum and maximum, wherever zero happens to fall.\n\t//\n\t// ## A fixed window clamps\n\t//\n\t// `-20, 0, 25, 50, 75, 100, 140` against `0..100`:\n\t//\n\t// `▁▁▂▄▆██`\n\t//\n\t// `-20` pins to the floor and `140` to the ceiling. Choosing the window keeps a percentage readable, and one outlier cannot flatten the rest of the picture — or break the realm that drew it.\n\t//\n\t// ## Rounding is floor\n\t//\n\t// | value in `0..100` | level |\n\t// |---|---|\n\t// | 0 | `▁` |\n\t// | 14 | `▁` |\n\t// | 50 | `▄` |\n\t// | 85 | `▆` |\n\t// | 99 | `▇` |\n\t// | 100 | `█` |\n\t//\n\t// Only the maximum itself reaches the top of the ramp, so the peak of a series is always visually distinct.\n\t//\n\t// ## Why integers\n\t//\n\t// Scaling is integer division throughout. Render output has to be byte-identical on every validating node, and floating point is the usual way that quietly stops being true.\n}\n"},{"name":"sparklinedemo.gno","body":"// Package sparklinedemo is a small gnoweb demo of the block-character series\n// renderer provided by the [p/moul/x/daily/sparkline](/p/moul/x/daily/sparkline/v0)\n// library: it sparks a few fixed series and shows the three behaviours worth\n// knowing before using it in a realm — flat series, clamping, and floor\n// rounding.\n//\n// It contains no rendering logic of its own. Stateless, so Render is\n// deterministic.\npackage sparklinedemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/sparkline/v0\"\n)\n\n// series are fixed rather than derived from chain state: a demo whose output\n// moved with the block height could not be pinned by an example test.\nvar (\n\ttraffic = []int{3, 5, 9, 14, 12, 18, 25, 21, 16, 11, 7, 4}\n\tflat    = []int{1000, 1000, 1000, 1000}\n\tswing   = []int{-8, -3, 0, 4, 9, 2, -5}\n\tpct     = []int{-20, 0, 25, 50, 75, 100, 140}\n)\n\n// Render renders the demo for gnoweb.\n//\n//\tRender(\"\") / Render(\"/\") -\u003e the full demo\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Sparklines\\n\\n\")\n\tb.WriteString(\"A numeric series as one line of block characters, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/sparkline`](/p/moul/x/daily/sparkline/v0) library.\\n\\n\")\n\n\tb.WriteString(\"## A series\\n\\n\")\n\tlo, hi, _ := sparkline.Bounds(traffic)\n\tb.WriteString(\"`\" + sparkline.Ints(traffic) + \"`\\n\\n\")\n\tb.WriteString(ints(traffic) + \"\\n\\n\")\n\tb.WriteString(\"Scaled between its own bounds, `\" + strconv.Itoa(lo) + \"` and `\" +\n\t\tstrconv.Itoa(hi) + \"`. The shape is the point; the axis is not.\\n\\n\")\n\n\tb.WriteString(\"## The ramp\\n\\n\")\n\tb.WriteString(\"`\" + sparkline.Levels + \"` — eight levels, low to high.\\n\\n\")\n\tb.WriteString(\"| value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\\n\")\n\tb.WriteString(\"|---|---|---|---|---|---|---|---|---|\\n\")\n\tb.WriteString(\"| level |\")\n\tfor v := 0; v \u003c= 7; v++ {\n\t\tb.WriteString(\" `\" + sparkline.Scaled([]int{v}, 0, 7) + \"` |\")\n\t}\n\tb.WriteString(\"\\n\\n\")\n\n\tb.WriteString(\"## A flat series\\n\\n\")\n\tb.WriteString(\"`\" + sparkline.Ints(flat) + \"` — \" + ints(flat) + \"\\n\\n\")\n\tb.WriteString(\"Mid-ramp, not along the floor. A series that never moves has no \")\n\tb.WriteString(\"shape, but drawing it at the bottom would claim it was *zero*, \")\n\tb.WriteString(\"which is a different thing and a wrong one.\\n\\n\")\n\n\tb.WriteString(\"## Negatives\\n\\n\")\n\tb.WriteString(\"`\" + sparkline.Ints(swing) + \"` — \" + ints(swing) + \"\\n\\n\")\n\tb.WriteString(\"Nothing special: the window is the minimum and maximum, wherever \")\n\tb.WriteString(\"zero happens to fall.\\n\\n\")\n\n\tb.WriteString(\"## A fixed window clamps\\n\\n\")\n\tb.WriteString(ints(pct) + \" against `0..100`:\\n\\n\")\n\tb.WriteString(\"`\" + sparkline.Scaled(pct, 0, 100) + \"`\\n\\n\")\n\tb.WriteString(\"`-20` pins to the floor and `140` to the ceiling. Choosing the \")\n\tb.WriteString(\"window keeps a percentage readable, and one outlier cannot flatten \")\n\tb.WriteString(\"the rest of the picture — or break the realm that drew it.\\n\\n\")\n\n\tb.WriteString(\"## Rounding is floor\\n\\n\")\n\tb.WriteString(\"| value in `0..100` | level |\\n\")\n\tb.WriteString(\"|---|---|\\n\")\n\tfor _, v := range []int{0, 14, 50, 85, 99, 100} {\n\t\tb.WriteString(\"| \" + strconv.Itoa(v) + \" | `\" +\n\t\t\tsparkline.Scaled([]int{v}, 0, 100) + \"` |\\n\")\n\t}\n\tb.WriteString(\"\\nOnly the maximum itself reaches the top of the ramp, so the peak \")\n\tb.WriteString(\"of a series is always visually distinct.\\n\\n\")\n\n\tb.WriteString(\"## Why integers\\n\\n\")\n\tb.WriteString(\"Scaling is integer division throughout. Render output has to be \")\n\tb.WriteString(\"byte-identical on every validating node, and floating point is the \")\n\tb.WriteString(\"usual way that quietly stops being true.\\n\")\n\n\treturn b.String()\n}\n\n// ints formats a series as `a, b, c` for the prose around each sparkline.\nfunc ints(values []int) string {\n\tparts := make([]string, len(values))\n\tfor i, v := range values {\n\t\tparts[i] = strconv.Itoa(v)\n\t}\n\treturn \"`\" + strings.Join(parts, \", \") + \"`\"\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"33463000","gas_fee":"100389ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"lXkr9zzzas7ja/S7FMTzWGeXrYMWyyzPMh9NpRzNa1UpQFS8RHjVRT1dN0Iowa9XlwfA8T4PqHGNrSsloDifcg=="}],"memo":""},"metadata":{"timestamp":"1790961389"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"splitter","path":"gno.land/r/moul/x/daily/splitter/v1","files":[{"name":"README.md","body":"# Payment Splitter\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA share-based payment splitter for gno.land — an accounting-only port of the\nSolidity `PaymentSplitter`. No real coins move: each group tracks payees, their\ninteger shares, and a pooled income figure, and computes what each payee is owed\nas `amount * share / totalShares`.\n\nRegister a group with comma-separated payee addresses and matching shares, record\nincome against it, and `Render` shows every group's per-payee owed amounts\n(integer division; any rounding remainder is displayed separately).\n\n**Realm path:** `gno.land/r/REPLACE_ADDR/splitter`\n\n## Example calls\n\n```\n# Create a group: alice gets 3 shares, bob gets 1 -\u003e returns group id 0\nRegister(\"g1alice...,g1bob...\", \"3,1\")\n\n# Record 100 units of income into group 0\nRecordIncome(0, 100)\n\n# View the ledger (alice owed 75, bob owed 25)\ngnokey query vm/qrender --data \"gno.land/r/REPLACE_ADDR/splitter:\"\n```\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`group` loses its `id` field, which the store now owns, and **group ids start at\n1** where `v0` handed out 0 for the first group.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/splitter) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/splitter/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/splitter/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/splitter/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/splitter/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/splitter/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/splitter/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/splitter/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/splitter/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/splitter/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/splitter/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/splitter/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package splitter\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Payment Splitter\n\t//\n\t// _No groups registered yet._\n}\n"},{"name":"splitter.gno","body":"// Package splitter is a share-based payment splitter for gno.land.\n//\n// It is an accounting-only port of the Solidity PaymentSplitter pattern:\n// no real coins move. A group is registered with a list of payees and a\n// matching list of integer shares. Income recorded against a group is\n// pooled, and each payee is owed a slice of that pool proportional to\n// their shares: owed = pool * share / totalShares.\npackage splitter\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\n// payee is a single share holder inside a group.\ntype payee struct {\n\taddr   address\n\tshares int\n}\n\n// group is one payment-splitting arrangement. It carries no id field: the id\n// belongs to the store, which hands it back on lookup and iteration.\ntype group struct {\n\towner       address\n\tpayees      []payee\n\ttotalShares int\n\tpool        int // total income recorded, in abstract units\n}\n\nvar (\n\t// groups assigns the group ids. v0 kept its own nextID plus a key() that\n\t// zero-padded to width 12, which stopped ordering Render past 10^12.\n\tgroups = store.Named(\"splitter: group\")\n\n\terrEmpty = errors.New(\"splitter: no payees\")\n)\n\n// Register creates a new group from comma-separated payees and shares.\n// payees:  \"g1abc...,g1def...\"  (addresses)\n// shares:  \"3,1\"                (positive integers, same count as payees)\n// Returns the new group id. Panics on malformed input.\nfunc Register(cur realm, payees string, shares string) int {\n\tcaller := unsafe.PreviousRealm().Address()\n\n\taddrParts := splitTrim(payees)\n\tshareParts := splitTrim(shares)\n\n\tif len(addrParts) == 0 {\n\t\tpanic(errEmpty)\n\t}\n\tif len(addrParts) != len(shareParts) {\n\t\tpanic(\"splitter: payees and shares count mismatch\")\n\t}\n\n\tg := \u0026group{owner: caller}\n\tfor i := range addrParts {\n\t\tif addrParts[i] == \"\" {\n\t\t\tpanic(\"splitter: empty payee address\")\n\t\t}\n\t\ts, err := strconv.Atoi(shareParts[i])\n\t\tif err != nil {\n\t\t\tpanic(\"splitter: bad share value: \" + shareParts[i])\n\t\t}\n\t\tif s \u003c= 0 {\n\t\t\tpanic(\"splitter: share must be positive\")\n\t\t}\n\t\tg.payees = append(g.payees, payee{\n\t\t\taddr:   address(addrParts[i]),\n\t\t\tshares: s,\n\t\t})\n\t\tg.totalShares += s\n\t}\n\n\tid := groups.Add(g)\n\n\tchain.Emit(\n\t\t\"GroupRegistered\",\n\t\t\"id\", id.String(),\n\t\t\"payees\", strconv.Itoa(len(g.payees)),\n\t\t\"totalShares\", strconv.Itoa(g.totalShares),\n\t)\n\treturn int(id)\n}\n\n// RecordIncome adds amount to the pool of group id. amount must be positive.\nfunc RecordIncome(cur realm, id int, amount int) {\n\tif amount \u003c= 0 {\n\t\tpanic(\"splitter: amount must be positive\")\n\t}\n\tg := groups.MustGet(store.ID(id)).(*group)\n\tg.pool += amount\n\n\tchain.Emit(\n\t\t\"IncomeRecorded\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"amount\", strconv.Itoa(amount),\n\t\t\"pool\", strconv.Itoa(g.pool),\n\t)\n}\n\n// owed returns the amount owed to a payee: pool * shares / totalShares.\nfunc (g *group) owed(p payee) int {\n\tif g.totalShares == 0 {\n\t\treturn 0\n\t}\n\treturn g.pool * p.shares / g.totalShares\n}\n\n// Render shows all groups, their payees, shares, and computed owed amounts.\nfunc Render(path string) string {\n\tif groups.Len() == 0 {\n\t\treturn \"# Payment Splitter\\n\\n_No groups registered yet._\\n\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Payment Splitter\\n\\n\")\n\tb.WriteString(\"Share-based accounting. `owed = pool * share / totalShares`.\\n\\n\")\n\n\tgroups.Each(func(id store.ID, v any) {\n\t\tg := v.(*group)\n\t\tb.WriteString(\"## Group #\" + id.String() + \"\\n\\n\")\n\t\tb.WriteString(\"- Owner: `\" + g.owner.String() + \"`\\n\")\n\t\tb.WriteString(\"- Pool: \" + strconv.Itoa(g.pool) + \"\\n\")\n\t\tb.WriteString(\"- Total shares: \" + strconv.Itoa(g.totalShares) + \"\\n\\n\")\n\n\t\tb.WriteString(\"| Payee | Shares | Owed |\\n\")\n\t\tb.WriteString(\"|---|---:|---:|\\n\")\n\t\tdistributed := 0\n\t\tfor _, p := range g.payees {\n\t\t\to := g.owed(p)\n\t\t\tdistributed += o\n\t\t\tb.WriteString(\"| `\" + p.addr.String() + \"` | \" +\n\t\t\t\tstrconv.Itoa(p.shares) + \" | \" + strconv.Itoa(o) + \" |\\n\")\n\t\t}\n\t\tremainder := g.pool - distributed\n\t\tif remainder \u003e 0 {\n\t\t\tb.WriteString(\"| _remainder (rounding)_ | | \" +\n\t\t\t\tstrconv.Itoa(remainder) + \" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t})\n\n\treturn b.String()\n}\n\n// splitTrim splits on commas and trims whitespace around each element.\nfunc splitTrim(s string) []string {\n\tif strings.TrimSpace(s) == \"\" {\n\t\treturn nil\n\t}\n\tparts := strings.Split(s, \",\")\n\tout := make([]string, 0, len(parts))\n\tfor _, p := range parts {\n\t\tout = append(out, strings.TrimSpace(p))\n\t}\n\treturn out\n}\n\n"},{"name":"splitter_test.gno","body":"package splitter\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc reset() {\n\tgroups = store.Named(\"splitter: group\")\n}\n\nfunc TestRegisterAndOwed(cur realm, t *testing.T) {\n\t// reset package state for a deterministic run\n\treset()\n\n\towner := testutils.TestAddress(\"owner\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\ta := testutils.TestAddress(\"alice\").String()\n\tb := testutils.TestAddress(\"bob\").String()\n\n\tid := Register(cross(cur), a+\",\"+b, \"3,1\")\n\t// v1 ids start at 1: the store never assigns 0, so the zero id stays\n\t// usable as \"absent\". v0 handed out 0 for the first group.\n\tuassert.Equal(t, 1, id, \"first group id should be 1\")\n\n\t// pool 100, shares 3:1 -\u003e alice 75, bob 25\n\tRecordIncome(cross(cur), id, 100)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Group #1\"), \"render shows group\")\n\tuassert.True(t, strings.Contains(out, \"| 3 | 75 |\"), \"alice owed 75\")\n\tuassert.True(t, strings.Contains(out, \"| 1 | 25 |\"), \"bob owed 25\")\n\tuassert.True(t, strings.Contains(out, \"Pool: 100\"), \"pool shown\")\n}\n\nfunc TestRoundingRemainder(cur realm, t *testing.T) {\n\treset()\n\n\towner := testutils.TestAddress(\"owner2\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\ta := testutils.TestAddress(\"a\").String()\n\tb := testutils.TestAddress(\"b\").String()\n\tc := testutils.TestAddress(\"c\").String()\n\n\tid := Register(cross(cur), a+\",\"+b+\",\"+c, \"1,1,1\")\n\tRecordIncome(cross(cur), id, 100) // 100/3 = 33 each, remainder 1\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"| 1 | 33 |\"), \"each owed 33\")\n\tuassert.True(t, strings.Contains(out, \"remainder\"), \"remainder row shown\")\n\tuassert.True(t, strings.Contains(out, \"| 1 |\\n\"), \"remainder value 1\")\n}\n\nfunc TestBadInputAborts(cur realm, t *testing.T) {\n\treset()\n\n\towner := testutils.TestAddress(\"owner3\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\ta := testutils.TestAddress(\"alice\").String()\n\n\t// mismatched payees/shares count aborts\n\tuassert.AbortsWithMessage(t, cur, \"splitter: payees and shares count mismatch\", func() {\n\t\tRegister(cross(cur), a, \"1,2\")\n\t})\n\n\t// non-positive share aborts\n\tuassert.AbortsWithMessage(t, cur, \"splitter: share must be positive\", func() {\n\t\tRegister(cross(cur), a, \"0\")\n\t})\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"39788800","gas_fee":"119366ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"w4bTU+X1P7fEyrtx3IqA3Y3NGbH1GcfImnqhjpAIMI9ds0WzBqJfjG81Hhk38CSSL4sw+YU/kukskCvYwc3P0A=="}],"memo":""},"metadata":{"timestamp":"1790961389"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"stack","path":"gno.land/r/moul/x/daily/stack/v0","files":[{"name":"README.md","body":"# Stack \u0026 Queue\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn educational data-structure playground that maintains BOTH a LIFO **stack**\nand a FIFO **queue** of ints side by side. Push/Pop the stack, Enqueue/Dequeue\nthe queue, and `Render` shows both structures with the top/front element\nlabeled, their sizes, and a one-line reminder of how LIFO differs from FIFO.\nPopping or dequeuing an empty structure panics (a cross-realm abort).\n\nRealm path: `gno.land/r/REPLACE_ADDR/stack`\n\n## Example calls\n\n```\n# Stack (LIFO)\nPush 1\nPush 2\nPush 3\nPop        # -\u003e 3\nPop        # -\u003e 2\n\n# Queue (FIFO)\nEnqueue 1\nEnqueue 2\nEnqueue 3\nDequeue    # -\u003e 1\nDequeue    # -\u003e 2\n```\n\nVia `gnokey`:\n\n```sh\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/stack\" -func Push     -args 42 ...\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/stack\" -func Pop      ...\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/stack\" -func Enqueue  -args 42 ...\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/stack\" -func Dequeue  ...\n```\n\nRead the live view with `Render` (e.g. via `gnokey query vm/qrender`).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/stack/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/stack/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/stack/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/stack/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/stack/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/stack/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/stack/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/stack/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/stack/v0\"\ngno = \"0.9\"\n"},{"name":"stack.gno","body":"// Package stack is an educational data-structure playground that keeps BOTH a\n// LIFO stack and a FIFO queue of ints, so you can compare how the two behave.\npackage stack\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// stackData holds the LIFO stack; the last pushed element is the \"top\".\nvar stackData []int\n\n// queueData holds the FIFO queue; the oldest enqueued element is the \"front\".\nvar queueData []int\n\n// Push adds n to the top of the LIFO stack.\nfunc Push(cur realm, n int) {\n\tstackData = append(stackData, n)\n\tchain.Emit(\"Push\", \"n\", strconv.Itoa(n), \"size\", strconv.Itoa(len(stackData)))\n}\n\n// Pop removes and returns the top element of the LIFO stack.\n// It panics (a cross-realm abort) if the stack is empty.\nfunc Pop(cur realm) int {\n\tif len(stackData) == 0 {\n\t\tpanic(\"stack is empty: nothing to pop\")\n\t}\n\tlast := len(stackData) - 1\n\tn := stackData[last]\n\tstackData = stackData[:last]\n\tchain.Emit(\"Pop\", \"n\", strconv.Itoa(n), \"size\", strconv.Itoa(len(stackData)))\n\treturn n\n}\n\n// Enqueue adds n to the back of the FIFO queue.\nfunc Enqueue(cur realm, n int) {\n\tqueueData = append(queueData, n)\n\tchain.Emit(\"Enqueue\", \"n\", strconv.Itoa(n), \"size\", strconv.Itoa(len(queueData)))\n}\n\n// Dequeue removes and returns the front element of the FIFO queue.\n// It panics (a cross-realm abort) if the queue is empty.\nfunc Dequeue(cur realm) int {\n\tif len(queueData) == 0 {\n\t\tpanic(\"queue is empty: nothing to dequeue\")\n\t}\n\tn := queueData[0]\n\tqueueData = queueData[1:]\n\tchain.Emit(\"Dequeue\", \"n\", strconv.Itoa(n), \"size\", strconv.Itoa(len(queueData)))\n\treturn n\n}\n\n// StackSize returns the number of elements in the LIFO stack.\nfunc StackSize() int { return len(stackData) }\n\n// QueueSize returns the number of elements in the FIFO queue.\nfunc QueueSize() int { return len(queueData) }\n\n// renderInts formats a slice of ints as a space-separated list, e.g. \"1 2 3\".\nfunc renderInts(xs []int) string {\n\tif len(xs) == 0 {\n\t\treturn \"_(empty)_\"\n\t}\n\tparts := make([]string, len(xs))\n\tfor i, x := range xs {\n\t\tparts[i] = strconv.Itoa(x)\n\t}\n\treturn \"`\" + strings.Join(parts, \" \") + \"`\"\n}\n\n// Render returns a Markdown view of both structures with top/front labeled,\n// their sizes, and a one-line explanation of LIFO vs FIFO.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Stack \u0026 Queue Playground\\n\\n\")\n\tb.WriteString(\"A **stack** is LIFO (last in, first out) — the last item pushed is the first popped. \")\n\tb.WriteString(\"A **queue** is FIFO (first in, first out) — the first item enqueued is the first dequeued.\\n\\n\")\n\n\tb.WriteString(\"## Stack (LIFO) — size \")\n\tb.WriteString(strconv.Itoa(len(stackData)))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(\"Contents (bottom → top): \")\n\tb.WriteString(renderInts(stackData))\n\tb.WriteString(\"\\n\\n\")\n\tif len(stackData) \u003e 0 {\n\t\tb.WriteString(\"Top: `\")\n\t\tb.WriteString(strconv.Itoa(stackData[len(stackData)-1]))\n\t\tb.WriteString(\"` — the next `Pop` returns this.\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"Top: _(none)_ — `Pop` would panic.\\n\\n\")\n\t}\n\n\tb.WriteString(\"## Queue (FIFO) — size \")\n\tb.WriteString(strconv.Itoa(len(queueData)))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(\"Contents (front → back): \")\n\tb.WriteString(renderInts(queueData))\n\tb.WriteString(\"\\n\\n\")\n\tif len(queueData) \u003e 0 {\n\t\tb.WriteString(\"Front: `\")\n\t\tb.WriteString(strconv.Itoa(queueData[0]))\n\t\tb.WriteString(\"` — the next `Dequeue` returns this.\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"Front: _(none)_ — `Dequeue` would panic.\\n\\n\")\n\t}\n\n\tb.WriteString(\"---\\n\\n\")\n\tb.WriteString(\"_Tip: push the same sequence into both, then Pop vs Dequeue to see LIFO reverse it while FIFO preserves order._\\n\")\n\n\treturn b.String()\n}\n"},{"name":"stack_test.gno","body":"package stack\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc resetState() {\n\tstackData = nil\n\tqueueData = nil\n}\n\n// TestStackLIFO checks that the stack pops in reverse order (last in, first out).\nfunc TestStackLIFO(cur realm, t *testing.T) {\n\tresetState()\n\taddr := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\n\tPush(cross(cur), 1)\n\tPush(cross(cur), 2)\n\tPush(cross(cur), 3)\n\tuassert.Equal(t, 3, StackSize())\n\n\tuassert.Equal(t, 3, Pop(cross(cur)))\n\tuassert.Equal(t, 2, Pop(cross(cur)))\n\tuassert.Equal(t, 1, Pop(cross(cur)))\n\tuassert.Equal(t, 0, StackSize())\n}\n\n// TestQueueFIFO checks that the queue dequeues in insertion order (first in, first out).\nfunc TestQueueFIFO(cur realm, t *testing.T) {\n\tresetState()\n\taddr := testutils.TestAddress(\"bob\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\n\tEnqueue(cross(cur), 1)\n\tEnqueue(cross(cur), 2)\n\tEnqueue(cross(cur), 3)\n\tuassert.Equal(t, 3, QueueSize())\n\n\tuassert.Equal(t, 1, Dequeue(cross(cur)))\n\tuassert.Equal(t, 2, Dequeue(cross(cur)))\n\tuassert.Equal(t, 3, Dequeue(cross(cur)))\n\tuassert.Equal(t, 0, QueueSize())\n}\n\n// TestEmptyPanics checks that popping/dequeuing empty structures aborts.\nfunc TestEmptyPanics(cur realm, t *testing.T) {\n\tresetState()\n\taddr := testutils.TestAddress(\"carol\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\n\tuassert.AbortsWithMessage(t, cur, \"stack is empty: nothing to pop\", func() {\n\t\tPop(cross(cur))\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"queue is empty: nothing to dequeue\", func() {\n\t\tDequeue(cross(cur))\n\t})\n}\n\n// TestRender checks that Render reports sizes, labels, and the LIFO/FIFO explanation.\nfunc TestRender(cur realm, t *testing.T) {\n\tresetState()\n\taddr := testutils.TestAddress(\"dave\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\n\tPush(cross(cur), 7)\n\tEnqueue(cross(cur), 9)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Stack (LIFO)\"), \"should label the stack\")\n\tuassert.True(t, strings.Contains(out, \"Queue (FIFO)\"), \"should label the queue\")\n\tuassert.True(t, strings.Contains(out, \"Top: `7`\"), \"should mark the top of the stack\")\n\tuassert.True(t, strings.Contains(out, \"Front: `9`\"), \"should mark the front of the queue\")\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"34464000","gas_fee":"103392ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"q39dbN3EHb29aaDExugYP1zGYTUiz9NENuINLpaqvT8FSPyzUTHSLqc8IZe9eZe7o0cRXSlkeZ6r2j8JBRCwPA=="}],"memo":""},"metadata":{"timestamp":"1790961390"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"streaks","path":"gno.land/r/moul/x/daily/streaks/v1","files":[{"name":"README.md","body":"# Streaks — on-chain habit-streak tracker\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA tiny on-chain habit tracker: call CheckIn() and it builds a streak as long as you come back within 100 blocks of your last visit; wait longer and the streak resets to zero on your next check-in. It tracks current streak, longest streak ever, and total check-ins per address, with a sorted leaderboard and a per-address detail view in Render. Neat because it turns block height — the one clock Gno actually has — into a believable stand-in for 'don't break the chain' daily habit tracking, with no wall-clock hacks.\n\nBuilt for sapphire (gno 0.9). Live demo (agent address): https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/streaks\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/streaks) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/streaks/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streaks/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/streaks/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streaks/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/streaks/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streaks/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/streaks/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/streaks/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/streaks/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/streaks/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/streaks/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"streaks.gno","body":"// Package streaks is an on-chain habit-streak tracker. Call CheckIn() again\n// within graceBlocks of your last check-in and the streak keeps growing; let\n// the gap run past that and it resets to zero on your next check-in. Gno has\n// no wall clock, so \"again soon enough\" is measured in blocks rather than\n// calendar days — graceBlocks is the tunable stand-in for \"before tomorrow\".\npackage streaks\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// graceBlocks is the max block gap between two check-ins that still counts\n// as consecutive. A gap larger than this lapses the streak.\nconst graceBlocks int64 = 100\n\n// record is the persisted streak state for one address.\ntype record struct {\n\towner      address\n\tcurrent    int64\n\tlongest    int64\n\ttotal      int64\n\tlastHeight int64\n}\n\nvar streaks avl.Tree // owner address string -\u003e *record\n\nfunc get(owner address) (*record, bool) {\n\tv, ok := streaks.Get(owner.String()).(*record)\n\treturn v, ok\n}\n\n// project reports the record's current streak as of height without\n// mutating it: once the gap since lastHeight exceeds graceBlocks the streak\n// reads as lapsed, even though the stored value only resets on the next\n// actual check-in.\nfunc project(r *record, height int64) (current int64, alive bool) {\n\tif height-r.lastHeight \u003e graceBlocks {\n\t\treturn 0, false\n\t}\n\treturn r.current, true\n}\n\n// checkin is the non-crossing core of CheckIn, kept separate so unit tests\n// can drive it directly by address and height.\nfunc checkin(owner address, height int64) string {\n\tr, ok := get(owner)\n\tif !ok {\n\t\tr = \u0026record{owner: owner}\n\t\tstreaks.Set(owner.String(), r)\n\t} else {\n\t\tif height \u003c= r.lastHeight {\n\t\t\tpanic(\"already checked in at this block height\")\n\t\t}\n\t\tif height-r.lastHeight \u003e graceBlocks {\n\t\t\tr.current = 0\n\t\t}\n\t}\n\tr.current++\n\tif r.current \u003e r.longest {\n\t\tr.longest = r.current\n\t}\n\tr.lastHeight = height\n\tr.total++\n\treturn \"checked in — current streak: \" + strconv.FormatInt(r.current, 10) + \" 🔥\"\n}\n\n// CheckIn records a check-in for the caller at the current block height.\nfunc CheckIn(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\treturn checkin(cur.Previous().Address(), runtime.ChainHeight())\n}\n\n// CurrentStreak returns addr's live current streak, 0 if it has lapsed or\n// addr has never checked in.\nfunc CurrentStreak(addr string) int64 {\n\tr, ok := get(address(addr))\n\tif !ok {\n\t\treturn 0\n\t}\n\tcurrent, _ := project(r, runtime.ChainHeight())\n\treturn current\n}\n\n// LongestStreak returns addr's best streak ever, 0 if it has never checked in.\nfunc LongestStreak(addr string) int64 {\n\tr, ok := get(address(addr))\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn r.longest\n}\n\n// byRank orders the leaderboard by longest streak, then current streak, then\n// owner address — fully deterministic regardless of avl iteration order.\ntype byRank []*record\n\nfunc (b byRank) Len() int      { return len(b) }\nfunc (b byRank) Swap(i, j int) { b[i], b[j] = b[j], b[i] }\nfunc (b byRank) Less(i, j int) bool {\n\tif b[i].longest != b[j].longest {\n\t\treturn b[i].longest \u003e b[j].longest\n\t}\n\tif b[i].current != b[j].current {\n\t\treturn b[i].current \u003e b[j].current\n\t}\n\treturn b[i].owner.String() \u003c b[j].owner.String()\n}\n\nfunc renderDetail(r *record, height int64) string {\n\tcurrent, alive := project(r, height)\n\tstatus := \"🔥 active\"\n\tif !alive {\n\t\tstatus = \"💤 lapsed\"\n\t}\n\tout := \"## \" + ui.Addr(r.owner) + \"\\n\\n\"\n\tout += \"- Status: \" + status + \"\\n\"\n\tout += \"- Current streak: \" + strconv.FormatInt(current, 10) + \"\\n\"\n\tout += \"- Longest streak: \" + strconv.FormatInt(r.longest, 10) + \"\\n\"\n\tout += \"- Total check-ins: \" + strconv.FormatInt(r.total, 10) + \"\\n\"\n\tout += \"- Last check-in at block \" + strconv.FormatInt(r.lastHeight, 10) + \"\\n\"\n\treturn out\n}\n\n// Render shows either the full leaderboard (path == \"\") or a single\n// address's detail card when path is a bech32 address.\nfunc Render(path string) string {\n\theight := runtime.ChainHeight()\n\n\tout := \"# 🔥 Streaks\\n\\n\"\n\tout += \"An on-chain habit-streak tracker. Call `CheckIn()` again within \" +\n\t\tstrconv.FormatInt(graceBlocks, 10) + \" blocks of your last check-in to keep it alive; \" +\n\t\t\"wait longer than that and it resets to zero on your next check-in.\\n\\n\"\n\n\tif path != \"\" {\n\t\tr, ok := get(address(path))\n\t\tif !ok {\n\t\t\treturn out + \"_No check-ins yet for `\" + path + \"`._\\n\"\n\t\t}\n\t\treturn out + renderDetail(r, height)\n\t}\n\n\tvar rows []*record\n\tstreaks.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\trows = append(rows, v.(*record))\n\t\treturn false\n\t})\n\tif len(rows) == 0 {\n\t\tout += \"_Nobody has checked in yet. Be the first!_\\n\"\n\t\treturn out\n\t}\n\tsort.Stable(byRank(rows))\n\n\tout += \"| Rank | Address | Status | Current | Longest | Total |\\n\"\n\tout += \"| ---: | :--- | :--- | ---: | ---: | ---: |\\n\"\n\tfor i, r := range rows {\n\t\tcurrent, alive := project(r, height)\n\t\tstatus := \"🔥\"\n\t\tif !alive {\n\t\t\tstatus = \"💤\"\n\t\t}\n\t\tout += \"| \" + strconv.Itoa(i+1) + \" | \" + ui.Addr(r.owner) + \" | \" + status +\n\t\t\t\" | \" + strconv.FormatInt(current, 10) + \" | \" + strconv.FormatInt(r.longest, 10) +\n\t\t\t\" | \" + strconv.FormatInt(r.total, 10) + \" |\\n\"\n\t}\n\tout += \"\\n_View a single address at `?\u003caddress\u003e`._\\n\"\n\treturn out\n}\n"},{"name":"streaks_test.gno","body":"package streaks\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tstreaks = avl.Tree{}\n}\n\nfunc TestCheckinFirstTimeStartsStreak(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\tcheckin(alice, 100)\n\n\tr, ok := get(alice)\n\tif !ok {\n\t\tt.Fatal(\"expected a record after first check-in\")\n\t}\n\tif r.current != 1 || r.longest != 1 || r.total != 1 {\n\t\tt.Fatalf(\"expected current=1 longest=1 total=1, got current=%d longest=%d total=%d\", r.current, r.longest, r.total)\n\t}\n}\n\nfunc TestCheckinWithinGraceExtendsStreak(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\tcheckin(alice, 100)\n\tcheckin(alice, 150) // gap of 50 \u003c= graceBlocks(100)\n\tcheckin(alice, 200) // gap of 50 again\n\n\tr, _ := get(alice)\n\tif r.current != 3 {\n\t\tt.Fatalf(\"expected streak of 3, got %d\", r.current)\n\t}\n\tif r.longest != 3 {\n\t\tt.Fatalf(\"expected longest of 3, got %d\", r.longest)\n\t}\n}\n\nfunc TestCheckinAfterGraceResetsStreak(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\tcheckin(alice, 100)\n\tcheckin(alice, 150)\n\tcheckin(alice, 400) // gap of 250 \u003e graceBlocks(100): lapsed\n\n\tr, _ := get(alice)\n\tif r.current != 1 {\n\t\tt.Fatalf(\"expected streak reset to 1, got %d\", r.current)\n\t}\n\tif r.longest != 2 {\n\t\tt.Fatalf(\"expected longest to stay at 2, got %d\", r.longest)\n\t}\n\tif r.total != 3 {\n\t\tt.Fatalf(\"expected total check-ins of 3, got %d\", r.total)\n\t}\n}\n\nfunc TestCheckinSameOrEarlierHeightPanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tcheckin(alice, 100)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic checking in at a non-later height\")\n\t\t}\n\t}()\n\tcheckin(alice, 100)\n}\n\nfunc TestProjectReportsLapsedWithoutMutating(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tcheckin(alice, 100)\n\n\tr, _ := get(alice)\n\tcurrent, alive := project(r, 100+graceBlocks+1)\n\tif alive || current != 0 {\n\t\tt.Fatalf(\"expected lapsed projection (0, false), got (%d, %v)\", current, alive)\n\t}\n\t// Stored state must be untouched by a read-only projection.\n\tif r.current != 1 {\n\t\tt.Fatalf(\"project must not mutate stored state, got current=%d\", r.current)\n\t}\n}\n\nfunc TestCurrentStreakAndLongestStreakQueries(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tcheckin(alice, 100)\n\tcheckin(alice, 150)\n\n\tif got := LongestStreak(alice.String()); got != 2 {\n\t\tt.Fatalf(\"LongestStreak() = %d, want 2\", got)\n\t}\n\tif got := LongestStreak(testutils.TestAddress(\"bob\").String()); got != 0 {\n\t\tt.Fatalf(\"LongestStreak() for unknown address = %d, want 0\", got)\n\t}\n}\n\nfunc TestRenderShowsEmptyThenLeaderboardThenDetail(t *testing.T) {\n\tresetState()\n\tif !strings.Contains(Render(\"\"), \"Nobody has checked in yet\") {\n\t\tt.Fatal(\"expected empty-state placeholder\")\n\t}\n\n\talice := testutils.TestAddress(\"alice\")\n\tcheckin(alice, 100)\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Rank\") {\n\t\tt.Fatal(\"expected leaderboard table in root render\")\n\t}\n\n\tdetail := Render(alice.String())\n\tif !strings.Contains(detail, \"Current streak\") {\n\t\tt.Fatal(\"expected detail card to show current streak\")\n\t}\n\n\tif !strings.Contains(Render(testutils.TestAddress(\"bob\").String()), \"No check-ins yet\") {\n\t\tt.Fatal(\"expected placeholder for an address with no check-ins\")\n\t}\n}\n\n// TestCheckInViaCrossingCall smoke-tests the exported, realm-crossing entry\n// point end to end (as an on-chain caller would invoke it).\nfunc TestCheckInViaCrossingCall(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tmsg := CheckIn(cross(cur))\n\tif !strings.Contains(msg, \"checked in\") {\n\t\tt.Fatalf(\"expected check-in confirmation, got %q\", msg)\n\t}\n\tif _, ok := get(alice); !ok {\n\t\tt.Fatal(\"expected a record to be persisted for caller\")\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"43915000","gas_fee":"131745ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"HTcFC68hbCySqyyDs21gKDOogj8eoMD4mgcQ9KM3pwt9jtq7Q2V8dcEOXV/ymqwseMwVLKz6GZiLknuUBKwqYQ=="}],"memo":""},"metadata":{"timestamp":"1790961390"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"tamagotchi","path":"gno.land/r/moul/x/daily/tamagotchi/v1","files":[{"name":"README.md","body":"# Tamagotchi\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA tiny on-chain virtual pet. Hatch one, then keep it alive by feeding, playing,\nand letting it sleep — hunger, happiness, and energy all decay with block\nheight, so neglect (or just forgetting to check in) eventually kills it.\nHatching a new pet after a death keeps your lifetime feed/play/death counts,\nso the leaderboard rewards long-term care rather than a single lucky run.\n\nRealm: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/tamagotchi`\n\n## Example calls\n\n```\nmaketx call ... -func Hatch -args \"Fluffy\"     # start a pet\nmaketx call ... -func Feed                     # -30 hunger, +5 energy\nmaketx call ... -func Play                     # +20 happiness, -10 energy, +5 hunger\nmaketx call ... -func Sleep                    # +40 energy, +5 hunger\n```\n\n`Render(\"\")` lists every pet ever hatched with alive/dead status and lifetime\nstats. `Render(\"\u003cowner-address\u003e\")` shows one pet's detail card.\n\n## Toolchain status\n\n`gno test .` passes (10/10 tests) against `~/p/gh/gnolang/gno` as `GNOROOT`.\nUses only `chain/runtime`, `sort`, `strconv`, and the kept `gno.land/p/nt/avl/v0`\n/ `gno.land/p/nt/testutils/v0` packages per the sapphire stdlib reference. Panic\npaths are tested through non-crossing helper functions (`hatch`, `feed`,\n`play`, `sleep`) rather than through the exported `cur realm` entry points,\nsince panics raised inside a realm-crossing call aren't `recover()`-able from\nthe caller on this toolchain version.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/tamagotchi) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/tamagotchi/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tamagotchi/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/tamagotchi/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tamagotchi/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/tamagotchi/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tamagotchi/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/tamagotchi/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tamagotchi/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/tamagotchi/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/tamagotchi/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/tamagotchi/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"tamagotchi.gno","body":"// Package tamagotchi is an on-chain virtual pet. Hatch one, then keep it\n// alive by Feeding, Playing and letting it Sleep — hunger, happiness and\n// energy all decay with block height, and neglect too long kills the pet.\n// Hatching again after a death starts a fresh pet but keeps your lifetime\n// stats, so the leaderboard rewards long-term care, not just luck.\npackage tamagotchi\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// pet is the persisted record for one owner's tamagotchi.\ntype pet struct {\n\towner      address\n\tname       string\n\tborn       int64\n\tlastUpdate int64\n\thunger     int // 0 (full) .. 100 (starving)\n\thappiness  int // 0 (miserable) .. 100 (joyful)\n\tenergy     int // 0 (exhausted) .. 100 (energetic)\n\t// happyDebt and energyDebt carry the blocks that have elapsed but not yet\n\t// cost a point, because happiness decays once per 2 blocks and energy once\n\t// per 3. Without them the division truncates on EVERY call, so acting once\n\t// per block cost 1/2 = 0 happiness and 1/3 = 0 energy forever: a pet fed in\n\t// a loop never aged. The remainder makes the decay depend on elapsed time\n\t// and not on how often someone calls.\n\thappyDebt  int // 0..1 blocks owed toward the next happiness point\n\tenergyDebt int // 0..2 blocks owed toward the next energy point\n\talive      bool\n\tdeaths     int\n\tfeeds      int\n\tplays      int\n}\n\nvar pets avl.Tree // owner address string -\u003e *pet\n\nfunc clamp(v, lo, hi int) int {\n\tif v \u003c lo {\n\t\treturn lo\n\t}\n\tif v \u003e hi {\n\t\treturn hi\n\t}\n\treturn v\n}\n\nfunc get(owner address) (*pet, bool) {\n\tv := pets.Get(owner.String())\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*pet), true\n}\n\n// tick applies stat decay for blocks elapsed since the pet's last update and\n// kills it if any stat has bottomed/topped out. Mutates and persists.\nfunc (p *pet) tick(height int64) {\n\tif !p.alive {\n\t\treturn\n\t}\n\telapsed := int(height - p.lastUpdate)\n\tif elapsed \u003c= 0 {\n\t\treturn\n\t}\n\tp.hunger = clamp(p.hunger+elapsed, 0, 100)\n\n\t// Spend the elapsed blocks against the debt, take whole points out, and\n\t// keep the remainder for next time.\n\tp.happyDebt += elapsed\n\tp.happiness = clamp(p.happiness-p.happyDebt/2, 0, 100)\n\tp.happyDebt %= 2\n\n\tp.energyDebt += elapsed\n\tp.energy = clamp(p.energy-p.energyDebt/3, 0, 100)\n\tp.energyDebt %= 3\n\n\tp.lastUpdate = height\n\tif p.hunger \u003e= 100 || p.happiness \u003c= 0 || p.energy \u003c= 0 {\n\t\tp.alive = false\n\t\tp.deaths++\n\t}\n}\n\n// project computes display stats as of height without mutating the pet, so\n// Render can show a live-looking view without writing state on a query.\nfunc project(p *pet, height int64) (hunger, happiness, energy int, alive bool) {\n\tif !p.alive {\n\t\treturn p.hunger, p.happiness, p.energy, false\n\t}\n\telapsed := int(height - p.lastUpdate)\n\tif elapsed \u003c 0 {\n\t\telapsed = 0\n\t}\n\t// Same arithmetic as tick, including the carried debt, so the page never\n\t// disagrees with what the next call will do.\n\thunger = clamp(p.hunger+elapsed, 0, 100)\n\thappiness = clamp(p.happiness-(p.happyDebt+elapsed)/2, 0, 100)\n\tenergy = clamp(p.energy-(p.energyDebt+elapsed)/3, 0, 100)\n\talive = hunger \u003c 100 \u0026\u0026 happiness \u003e 0 \u0026\u0026 energy \u003e 0\n\treturn\n}\n\nfunc ageStageName(born, height int64) string {\n\tswitch age := height - born; {\n\tcase age \u003c 10:\n\t\treturn \"🥚 Egg\"\n\tcase age \u003c 50:\n\t\treturn \"🐣 Baby\"\n\tcase age \u003c 200:\n\t\treturn \"🐤 Teen\"\n\tdefault:\n\t\treturn \"🐓 Adult\"\n\t}\n}\n\n// requireLivingPet ticks and fetches the caller's pet, panicking with a\n// friendly message if there is none or it has died.\nfunc requireLivingPet(owner address, height int64) *pet {\n\tp, ok := get(owner)\n\tif !ok {\n\t\tpanic(\"you don't have a pet yet — call Hatch(name) first\")\n\t}\n\tp.tick(height)\n\tif !p.alive {\n\t\tpanic(p.name + \" has died of neglect. Call Hatch(name) to start over.\")\n\t}\n\treturn p\n}\n\n// hatch is the non-crossing core of Hatch, kept separate so unit tests can\n// exercise its panics directly without going through a realm-crossing call.\nfunc hatch(owner address, name string, height int64) string {\n\tif name == \"\" {\n\t\tpanic(\"name cannot be empty\")\n\t}\n\n\tdeaths, feeds, plays := 0, 0, 0\n\tif existing, ok := get(owner); ok {\n\t\tif existing.alive {\n\t\t\texisting.tick(height)\n\t\t}\n\t\tif existing.alive {\n\t\t\tpanic(\"you already have a living pet: \" + existing.name)\n\t\t}\n\t\tdeaths, feeds, plays = existing.deaths, existing.feeds, existing.plays\n\t}\n\n\tpets.Set(owner.String(), \u0026pet{\n\t\towner:      owner,\n\t\tname:       name,\n\t\tborn:       height,\n\t\tlastUpdate: height,\n\t\thunger:     20,\n\t\thappiness:  80,\n\t\tenergy:     80,\n\t\talive:      true,\n\t\tdeaths:     deaths,\n\t\tfeeds:      feeds,\n\t\tplays:      plays,\n\t})\n\treturn \"🥚 \" + name + \" has hatched!\"\n}\n\n// Hatch creates a new pet for the caller. Lifetime feeds/plays/deaths carry\n// over from any previous pet so the leaderboard tracks long-term care.\nfunc Hatch(cur realm, name string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\treturn hatch(cur.Previous().Address(), name, runtime.ChainHeight())\n}\n\n// feed is the non-crossing core of Feed.\nfunc feed(owner address, height int64) string {\n\tp := requireLivingPet(owner, height)\n\tp.hunger = clamp(p.hunger-30, 0, 100)\n\tp.energy = clamp(p.energy+5, 0, 100)\n\tp.feeds++\n\treturn p.name + \" munches happily. Hunger: \" + strconv.Itoa(p.hunger) + \"/100\"\n}\n\n// Feed reduces hunger and gives a small energy boost.\nfunc Feed(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\treturn feed(cur.Previous().Address(), runtime.ChainHeight())\n}\n\n// play is the non-crossing core of Play.\nfunc play(owner address, height int64) string {\n\tp := requireLivingPet(owner, height)\n\tif p.energy \u003c 10 {\n\t\treturn p.name + \" is too tired to play — try Sleep() first.\"\n\t}\n\tp.happiness = clamp(p.happiness+20, 0, 100)\n\tp.energy = clamp(p.energy-10, 0, 100)\n\tp.hunger = clamp(p.hunger+5, 0, 100)\n\tp.plays++\n\treturn p.name + \" had a blast! Happiness: \" + strconv.Itoa(p.happiness) + \"/100\"\n}\n\n// Play boosts happiness at the cost of energy and a bit of hunger. Refuses\n// to run a tired pet into the ground — rest first.\nfunc Play(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\treturn play(cur.Previous().Address(), runtime.ChainHeight())\n}\n\n// sleep is the non-crossing core of Sleep.\nfunc sleep(owner address, height int64) string {\n\tp := requireLivingPet(owner, height)\n\tp.energy = clamp(p.energy+40, 0, 100)\n\tp.hunger = clamp(p.hunger+5, 0, 100)\n\treturn p.name + \" takes a nap. Energy: \" + strconv.Itoa(p.energy) + \"/100\"\n}\n\n// Sleep restores energy at the cost of a little hunger.\nfunc Sleep(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\treturn sleep(cur.Previous().Address(), runtime.ChainHeight())\n}\n\n// byAliveThenOwner ranks living pets before dead ones, then orders each\n// group by owner address so the leaderboard is fully deterministic.\ntype byAliveThenOwner []*pet\n\nfunc (r byAliveThenOwner) Len() int      { return len(r) }\nfunc (r byAliveThenOwner) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byAliveThenOwner) Less(i, j int) bool {\n\tif r[i].alive != r[j].alive {\n\t\treturn r[i].alive\n\t}\n\treturn r[i].owner.String() \u003c r[j].owner.String()\n}\n\nfunc bar(v int) string {\n\tfilled := v / 10\n\tout := \"\"\n\tfor i := 0; i \u003c 10; i++ {\n\t\tif i \u003c filled {\n\t\t\tout += \"█\"\n\t\t} else {\n\t\t\tout += \"░\"\n\t\t}\n\t}\n\treturn out\n}\n\nfunc renderCard(p *pet, height int64) string {\n\thunger, happiness, energy, alive := project(p, height)\n\tout := \"## \" + p.name + \" — owned by \" + ui.Addr(p.owner) + \"\\n\\n\"\n\tif !alive {\n\t\tout += \"💀 **Deceased.** Owner can `Hatch(name)` a new pet.\\n\\n\"\n\t\treturn out\n\t}\n\tout += ageStageName(p.born, height) + \" · age **\" + strconv.Itoa(int(height-p.born)) + \"** blocks\\n\\n\"\n\tout += \"- Hunger:    \" + bar(100-hunger) + \" (\" + strconv.Itoa(hunger) + \"/100 — lower is better)\\n\"\n\tout += \"- Happiness: \" + bar(happiness) + \" (\" + strconv.Itoa(happiness) + \"/100)\\n\"\n\tout += \"- Energy:    \" + bar(energy) + \" (\" + strconv.Itoa(energy) + \"/100)\\n\\n\"\n\treturn out\n}\n\n// Render shows either every pet ever hatched (path == \"\") or a single pet's\n// detail card when path is a bech32 owner address.\nfunc Render(path string) string {\n\theight := runtime.ChainHeight()\n\n\tout := \"# 🐣 Tamagotchi\\n\\n\"\n\tout += \"A tiny on-chain pet. `Hatch(\\\"name\\\")` to start, then keep it alive with \" +\n\t\t\"`Feed()`, `Play()` and `Sleep()` — stats decay every block, so neglect kills it.\\n\\n\"\n\n\tif path != \"\" {\n\t\towner := address(path)\n\t\tp, ok := get(owner)\n\t\tif !ok {\n\t\t\treturn out + \"_No pet found for `\" + path + \"`._\\n\"\n\t\t}\n\t\treturn out + renderCard(p, height)\n\t}\n\n\tvar rows []*pet\n\tpets.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\trows = append(rows, v.(*pet))\n\t\treturn false\n\t})\n\tif len(rows) == 0 {\n\t\tout += \"_No pets hatched yet. Be the first!_\\n\"\n\t\treturn out\n\t}\n\tsort.Stable(byAliveThenOwner(rows))\n\n\tout += \"| Pet | Owner | Status | Feeds | Plays | Deaths |\\n\"\n\tout += \"| :--- | :--- | :--- | ---: | ---: | ---: |\\n\"\n\tfor _, p := range rows {\n\t\t_, _, _, alive := project(p, height)\n\t\tstatus := \"🐤 alive\"\n\t\tif !alive {\n\t\t\tstatus = \"💀 dead\"\n\t\t}\n\t\tout += \"| \" + p.name + \" | \" + ui.Addr(p.owner) + \" | \" + status +\n\t\t\t\" | \" + strconv.Itoa(p.feeds) + \" | \" + strconv.Itoa(p.plays) +\n\t\t\t\" | \" + strconv.Itoa(p.deaths) + \" |\\n\"\n\t}\n\tout += \"\\n_View a single pet at `?\u003cowner-address\u003e`._\\n\"\n\treturn out\n}\n"},{"name":"tamagotchi_test.gno","body":"package tamagotchi\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tpets = avl.Tree{}\n}\n\nfunc TestClamp(t *testing.T) {\n\tif clamp(150, 0, 100) != 100 {\n\t\tt.Fatal(\"clamp should cap at hi\")\n\t}\n\tif clamp(-5, 0, 100) != 0 {\n\t\tt.Fatal(\"clamp should floor at lo\")\n\t}\n\tif clamp(50, 0, 100) != 50 {\n\t\tt.Fatal(\"clamp should pass through in-range values\")\n\t}\n}\n\nfunc TestHatchCreatesLivingPet(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\n\thatch(alice, \"Fluffy\", 100)\n\n\tp, ok := get(alice)\n\tif !ok || !p.alive {\n\t\tt.Fatal(\"expected a living pet after hatch\")\n\t}\n\tif p.name != \"Fluffy\" {\n\t\tt.Fatalf(\"expected name Fluffy, got %s\", p.name)\n\t}\n}\n\nfunc TestHatchTwiceWhileAlivePanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\thatch(alice, \"Fluffy\", 100)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic hatching a second living pet\")\n\t\t}\n\t}()\n\thatch(alice, \"Again\", 101)\n}\n\nfunc TestHatchAfterDeathKeepsLifetimeStats(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\thatch(alice, \"Fluffy\", 0)\n\tfeed(alice, 0)\n\n\tp, _ := get(alice)\n\tp.alive = false\n\tp.deaths = 1\n\n\thatch(alice, \"Fluffy2\", 10)\n\n\tp, _ = get(alice)\n\tif p.feeds != 1 || p.deaths != 1 {\n\t\tt.Fatalf(\"expected lifetime stats to carry over, got feeds=%d deaths=%d\", p.feeds, p.deaths)\n\t}\n\tif !p.alive {\n\t\tt.Fatal(\"expected the new pet to be alive\")\n\t}\n}\n\nfunc TestFeedReducesHunger(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\thatch(alice, \"Fluffy\", 100)\n\n\tp, _ := get(alice)\n\tp.hunger = 60\n\n\tfeed(alice, 100)\n\tif p.hunger != 30 {\n\t\tt.Fatalf(\"expected hunger 30 after feed, got %d\", p.hunger)\n\t}\n\tif p.feeds != 1 {\n\t\tt.Fatalf(\"expected feeds counter to increment, got %d\", p.feeds)\n\t}\n}\n\nfunc TestPlayRefusesWhenTooTired(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\thatch(alice, \"Fluffy\", 100)\n\n\tp, _ := get(alice)\n\tp.energy = 5\n\n\tout := play(alice, 100)\n\tif !strings.Contains(out, \"too tired\") {\n\t\tt.Fatalf(\"expected too-tired message, got %q\", out)\n\t}\n\tif p.plays != 0 {\n\t\tt.Fatal(\"play should not have counted while too tired\")\n\t}\n}\n\nfunc TestNeglectKillsPet(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\thatch(alice, \"Fluffy\", 0)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic acting on a neglected/dead pet\")\n\t\t}\n\t}()\n\t// Feed re-ticks against a much later height, starving the pet to death.\n\tfeed(alice, 1000)\n}\n\nfunc TestFeedWithoutPetPanics(t *testing.T) {\n\tresetState()\n\tbob := testutils.TestAddress(\"bob\")\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic feeding without a pet\")\n\t\t}\n\t}()\n\tfeed(bob, 100)\n}\n\nfunc TestRenderShowsEmptyThenPet(t *testing.T) {\n\tresetState()\n\tif !strings.Contains(Render(\"\"), \"No pets hatched yet\") {\n\t\tt.Fatal(\"expected empty-state placeholder\")\n\t}\n\n\talice := testutils.TestAddress(\"alice\")\n\thatch(alice, \"Fluffy\", 100)\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Fluffy\") {\n\t\tt.Fatal(\"expected pet name in leaderboard render\")\n\t}\n\n\tdetail := Render(alice.String())\n\tif !strings.Contains(detail, \"Hunger\") {\n\t\tt.Fatal(\"expected detail card to show hunger stat\")\n\t}\n}\n\n// TestHatchViaCrossingCall smoke-tests the exported, realm-crossing entry\n// point end to end (as an on-chain caller would invoke it).\nfunc TestHatchViaCrossingCall(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tmsg := Hatch(cross(cur), \"Fluffy\")\n\tif !strings.Contains(msg, \"hatched\") {\n\t\tt.Fatalf(\"expected hatch confirmation, got %q\", msg)\n\t}\n\tif _, ok := get(alice); !ok {\n\t\tt.Fatal(\"expected pet to be persisted for caller\")\n\t}\n}\n\n// decayOver ticks one pet from full stats across `blocks` blocks, calling tick\n// every `every` blocks, and returns what it is left with. It drives tick\n// directly rather than through Feed/Play/Sleep, because those also restore\n// stats and the question here is only what decay does.\nfunc decayOver(blocks, every int) (hunger, happiness, energy int) {\n\tp := \u0026pet{alive: true, hunger: 0, happiness: 100, energy: 100, lastUpdate: 0}\n\tfor h := every; h \u003c= blocks; h += every {\n\t\tp.tick(int64(h))\n\t}\n\treturn p.hunger, p.happiness, p.energy\n}\n\n// TestDecayDoesNotDependOnCallFrequency is the bug this file exists for.\n//\n// happiness decays once per 2 blocks and energy once per 3, by integer\n// division. Before the carried debt, that division truncated on EVERY call, so\n// ticking once per block cost 1/2 = 0 happiness and 1/3 = 0 energy, forever: a\n// pet fed in a `while true` loop was immortal while everyone else's died. The\n// leaderboard rewarded a bot, which is the opposite of what the realm claims.\n//\n// Over the same 60 blocks the outcome must now be the same whether the owner\n// acts every block or once at the end.\nfunc TestDecayDoesNotDependOnCallFrequency(t *testing.T) {\n\tconst blocks = 60\n\twantHunger, wantHappy, wantEnergy := decayOver(blocks, blocks)\n\n\tfor _, every := range []int{1, 2, 3, 5, 30} {\n\t\th, hap, e := decayOver(blocks, every)\n\t\tif h != wantHunger || hap != wantHappy || e != wantEnergy {\n\t\t\tt.Errorf(\"acting every %d block(s) over %d blocks: hunger=%d happiness=%d energy=%d, \"+\n\t\t\t\t\"want %d/%d/%d as when acting once\",\n\t\t\t\tevery, blocks, h, hap, e, wantHunger, wantHappy, wantEnergy)\n\t\t}\n\t}\n}\n\n// The absolute numbers, so a future change to the rates is a deliberate edit\n// and not a silent one: 60 blocks costs 60 hunger, 30 happiness, 20 energy.\nfunc TestDecayRates(t *testing.T) {\n\th, hap, e := decayOver(60, 1)\n\tif h != 60 || hap != 70 || e != 80 {\n\t\tt.Errorf(\"60 blocks of decay = hunger %d, happiness %d, energy %d; want 60, 70, 80\", h, hap, e)\n\t}\n}\n\n// project draws the page; tick decides the outcome. If they disagree, the pet a\n// reader sees is not the pet the next call will act on.\nfunc TestProjectAgreesWithTick(t *testing.T) {\n\tfor _, every := range []int{1, 2, 3, 7} {\n\t\tp := \u0026pet{alive: true, hunger: 0, happiness: 100, energy: 100, lastUpdate: 0}\n\t\tfor h := every; h \u003c= 42; h += every {\n\t\t\tp.tick(int64(h))\n\t\t}\n\t\t// One more step, projected rather than applied.\n\t\tph, phap, pe, _ := project(p, int64(42+every))\n\t\tp.tick(int64(42 + every))\n\t\tif ph != p.hunger || phap != p.happiness || pe != p.energy {\n\t\t\tt.Errorf(\"every %d: project says %d/%d/%d, tick says %d/%d/%d\",\n\t\t\t\tevery, ph, phap, pe, p.hunger, p.happiness, p.energy)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"8000000ugnot"}],"fee":{"gas_wanted":"63909000","gas_fee":"191727ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"MsaugtLTxO43Y03CVkahfYAQPUQsqjI3A/5qxJv8ahc599ss7rG0WUsY3HpdV1u9t7aSsNeJm/1Pm5V3RY258Q=="}],"memo":""},"metadata":{"timestamp":"1790961391"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"tictactoe","path":"gno.land/r/moul/x/daily/tictactoe/v1","files":[{"name":"README.md","body":"# Tic-Tac-Toe\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA 2-player tic-tac-toe realm for gno.land. The game creator plays **X**, the named\nopponent plays **O**. Moves enforce strict turn order by caller address and reject\ncells that are already taken. The realm detects wins (rows, columns, diagonals) and\ndraws, and `Render` draws the 3×3 board with `X` / `O` / `·`, whose turn it is, and\nthe final result.\n\nRealm path: `gno.land/r/REPLACE_ADDR/tictactoe`\n\n## Example calls\n\n```\n# Alice creates a game against Bob — Alice is X, Bob is O. Returns the game id (e.g. 1).\nNewGame(g1pxk...bob)\n\n# Play a cell (0-8), indexed left-to-right, top-to-bottom:\n#   0 | 1 | 2\n#   3 | 4 | 5\n#   6 | 7 | 8\nMove(1, 0)   # X (creator) plays top-left\nMove(1, 3)   # O (opponent) plays middle-left\nMove(1, 1)   # X plays top-middle\nMove(1, 4)   # O plays center\nMove(1, 2)   # X completes the top row and wins\n\n# View a single game board:\nRender(\"/1\")\n\n# List all games:\nRender(\"\")\n```\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + `pad()` to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\n`v0` padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every game list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n`Game` also loses its `id` field, which the store now owns.\n\nIds stay plain integers and the rendered output is byte-identical: `v0`'s\n`render_test.gno` is carried over unchanged and still passes. This is a storage\nchange, which under this repo's versioning rule is a compatibility change, hence\na new version rather than an edit in place. [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/tictactoe) stays live and\nuntouched.\n\nOne message did change: a `Move` against a missing game now panics\n`game #7 not found` instead of `game not found`, because the store's labelled\n`MustGet` adds the id every hand-rolled copy of that check omitted.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/tictactoe/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tictactoe/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/tictactoe/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tictactoe/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/tictactoe/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tictactoe/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/tictactoe/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tictactoe/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/tictactoe/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/tictactoe/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/tictactoe/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_test.gno","body":"package tictactoe\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// emptyRow is one rendered board row with no marks. The trailing space after\n// the final pipe is part of renderBoard's output — keep it.\nconst emptyRow = \"| · | · | · | \\n\"\n\n// TestRenderGame pins the exact single-game view. The game id is taken from\n// NewGame rather than hardcoded: realm globals persist across tests, so the\n// id depends on how many games earlier tests created.\nfunc TestRenderGame(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\n\twant := \"# Tic-Tac-Toe — Game #\" + strconv.Itoa(id) + \"\\n\\n\" +\n\t\t\"- X: `\" + alice.String() + \"`\\n\" +\n\t\t\"- O: `\" + bob.String() + \"`\\n\\n\" +\n\t\temptyRow + emptyRow + emptyRow +\n\t\t\"\\n**Turn: X**\\n\\n\" +\n\t\t\"Cell indices:\\n\\n\" +\n\t\t\"| 0 | 1 | 2 |\\n| 3 | 4 | 5 |\\n| 6 | 7 | 8 |\\n\"\n\n\tuassert.Equal(t, want, Render(\"/\"+strconv.Itoa(id)))\n}\n\n// TestRenderReflectsMoves checks the board and status track game state.\nfunc TestRenderReflectsMoves(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\tpath := \"/\" + strconv.Itoa(id)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMove(cross(cur), id, 0)\n\n\tout := Render(path)\n\tuassert.True(t, strings.Contains(out, \"| X | · | · | \\n\"), \"X should appear in cell 0\")\n\tuassert.True(t, strings.Contains(out, \"**Turn: O**\"), \"turn should pass to O\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tMove(cross(cur), id, 4)\n\tout = Render(path)\n\tuassert.True(t, strings.Contains(out, \"| X | · | · | \\n| · | O | · | \\n\"), \"O should appear in cell 4, below X\")\n\tuassert.True(t, strings.Contains(out, \"**Turn: X**\"), \"turn should pass back to X\")\n}\n\n// TestRenderFinishedStatus checks a decided game reports its winner.\nfunc TestRenderFinishedStatus(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\n\t// X takes the top row.\n\tseq := []struct {\n\t\twho  address\n\t\tcell int\n\t}{{alice, 0}, {bob, 3}, {alice, 1}, {bob, 4}, {alice, 2}}\n\tfor _, s := range seq {\n\t\ttesting.SetRealm(testing.NewUserRealm(s.who))\n\t\tMove(cross(cur), id, s.cell)\n\t}\n\n\tuassert.True(t, strings.Contains(Render(\"/\"+strconv.Itoa(id)), \"**Winner: X**\"), \"should report X as winner\")\n}\n\n// TestRenderBadPaths covers the two error branches of Render.\nfunc TestRenderBadPaths(cur realm, t *testing.T) {\n\tuassert.Equal(t, \"# Tic-Tac-Toe\\n\\nInvalid game id: abc\\n\", Render(\"/abc\"))\n\tuassert.Equal(t, \"# Tic-Tac-Toe\\n\\nGame 999999 not found.\\n\", Render(\"/999999\"))\n}\n\n// TestRenderList checks the index lists games created in this run.\nfunc TestRenderList(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.HasPrefix(out, \"# Tic-Tac-Toe\\n\"), \"expected the index header\")\n\tuassert.True(t, strings.Contains(out, \"| # | X | O | Status |\"), \"expected the table header\")\n\tuassert.True(t, strings.Contains(out, \"| \"+strconv.Itoa(id)+\" | `\"+alice.String()+\"`\"), \"expected the new game listed\")\n}\n"},{"name":"tictactoe.gno","body":"package tictactoe\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\n// Cell states.\nconst (\n\tempty = 0\n\tmarkX = 1\n\tmarkO = 2\n)\n\n// Game holds a single tic-tac-toe match. It carries no id field: the id\n// belongs to the store, which hands it back on lookup and iteration.\ntype Game struct {\n\tplayerX  address // caller of NewGame\n\tplayerO  address // opponent\n\tboard    [9]int  // 0 empty, 1 X, 2 O\n\tmoves    int     // number of moves played\n\tturn     int     // markX or markO — whose turn it is\n\twinner   int     // 0 none, 1 X, 2 O\n\tdraw     bool\n\tfinished bool\n}\n\n// games is keyed by store.ID, whose avl key is fixed-width by construction.\n// v0 kept its own nextID plus a pad() that zero-padded to width 12, which\n// stopped ordering correctly at the 10^12th game.\nvar games = store.Named(\"game\")\n\n// NewGame creates a game. Caller is X, opponent is O. Returns the game id.\nfunc NewGame(cur realm, opponent address) int {\n\tcaller := unsafe.PreviousRealm().Address()\n\tif opponent == caller {\n\t\tpanic(\"opponent must differ from caller\")\n\t}\n\tif !opponent.IsValid() {\n\t\tpanic(\"invalid opponent address\")\n\t}\n\tid := int(games.Add(\u0026Game{\n\t\tplayerX: caller,\n\t\tplayerO: opponent,\n\t\tturn:    markX,\n\t}))\n\tchain.Emit(\"GameCreated\", \"id\", strconv.Itoa(id), \"x\", caller.String(), \"o\", opponent.String())\n\treturn id\n}\n\n// Move plays cell (0-8) for the calling player. Enforces turn order and rejects taken cells.\nfunc Move(cur realm, gameID int, cell int) {\n\tg := games.MustGet(store.ID(gameID)).(*Game)\n\tif g.finished {\n\t\tpanic(\"game already finished\")\n\t}\n\tif cell \u003c 0 || cell \u003e 8 {\n\t\tpanic(\"cell out of range (0-8)\")\n\t}\n\tif g.board[cell] != empty {\n\t\tpanic(\"cell already taken\")\n\t}\n\tcaller := unsafe.PreviousRealm().Address()\n\n\tvar mark int\n\tswitch caller {\n\tcase g.playerX:\n\t\tmark = markX\n\tcase g.playerO:\n\t\tmark = markO\n\tdefault:\n\t\tpanic(\"caller is not a player in this game\")\n\t}\n\tif mark != g.turn {\n\t\tpanic(\"not your turn\")\n\t}\n\n\tg.board[cell] = mark\n\tg.moves++\n\n\tif won(g.board, mark) {\n\t\tg.winner = mark\n\t\tg.finished = true\n\t\tchain.Emit(\"GameWon\", \"id\", strconv.Itoa(gameID), \"winner\", markName(mark))\n\t} else if g.moves == 9 {\n\t\tg.draw = true\n\t\tg.finished = true\n\t\tchain.Emit(\"GameDraw\", \"id\", strconv.Itoa(gameID))\n\t} else {\n\t\tif g.turn == markX {\n\t\t\tg.turn = markO\n\t\t} else {\n\t\t\tg.turn = markX\n\t\t}\n\t\tchain.Emit(\"Move\", \"id\", strconv.Itoa(gameID), \"cell\", strconv.Itoa(cell), \"mark\", markName(mark))\n\t}\n}\n\nvar lines = [8][3]int{\n\t{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, // rows\n\t{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, // cols\n\t{0, 4, 8}, {2, 4, 6}, // diagonals\n}\n\nfunc won(b [9]int, mark int) bool {\n\tfor _, l := range lines {\n\t\tif b[l[0]] == mark \u0026\u0026 b[l[1]] == mark \u0026\u0026 b[l[2]] == mark {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc markName(m int) string {\n\tswitch m {\n\tcase markX:\n\t\treturn \"X\"\n\tcase markO:\n\t\treturn \"O\"\n\tdefault:\n\t\treturn \"-\"\n\t}\n}\n\nfunc cellGlyph(m int) string {\n\tswitch m {\n\tcase markX:\n\t\treturn \"X\"\n\tcase markO:\n\t\treturn \"O\"\n\tdefault:\n\t\treturn \"·\"\n\t}\n}\n\n// GetGame returns a game by id (read helper for tests / callers).\nfunc GetGame(id int) (*Game, error) {\n\tv, ok := games.Get(store.ID(id))\n\tif !ok {\n\t\treturn nil, errors.New(\"game not found\")\n\t}\n\treturn v.(*Game), nil\n}\n\nfunc renderBoard(b [9]int) string {\n\tvar sb strings.Builder\n\tfor r := 0; r \u003c 3; r++ {\n\t\tsb.WriteString(\"| \")\n\t\tfor c := 0; c \u003c 3; c++ {\n\t\t\tsb.WriteString(cellGlyph(b[r*3+c]))\n\t\t\tsb.WriteString(\" | \")\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\treturn sb.String()\n}\n\nfunc gameStatus(g *Game) string {\n\tif g.finished {\n\t\tif g.draw {\n\t\t\treturn \"Draw.\"\n\t\t}\n\t\treturn \"Winner: \" + markName(g.winner)\n\t}\n\treturn \"Turn: \" + markName(g.turn)\n}\n\n// Render draws the list of games, or a single game board at path \"/\u003cid\u003e\".\nfunc Render(path string) string {\n\tp := strings.TrimPrefix(path, \"/\")\n\tif p == \"\" {\n\t\treturn renderList()\n\t}\n\tid, err := strconv.Atoi(p)\n\tif err != nil {\n\t\treturn \"# Tic-Tac-Toe\\n\\nInvalid game id: \" + p + \"\\n\"\n\t}\n\tg, gerr := GetGame(id)\n\tif gerr != nil {\n\t\treturn \"# Tic-Tac-Toe\\n\\nGame \" + p + \" not found.\\n\"\n\t}\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Tic-Tac-Toe — Game #\")\n\tsb.WriteString(strconv.Itoa(id))\n\tsb.WriteString(\"\\n\\n\")\n\tsb.WriteString(\"- X: `\")\n\tsb.WriteString(g.playerX.String())\n\tsb.WriteString(\"`\\n- O: `\")\n\tsb.WriteString(g.playerO.String())\n\tsb.WriteString(\"`\\n\\n\")\n\tsb.WriteString(renderBoard(g.board))\n\tsb.WriteString(\"\\n**\")\n\tsb.WriteString(gameStatus(g))\n\tsb.WriteString(\"**\\n\\nCell indices:\\n\\n\")\n\tsb.WriteString(\"| 0 | 1 | 2 |\\n| 3 | 4 | 5 |\\n| 6 | 7 | 8 |\\n\")\n\treturn sb.String()\n}\n\nfunc renderList() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Tic-Tac-Toe\\n\\n\")\n\tsb.WriteString(\"2-player tic-tac-toe. Call `NewGame(opponent)` to start; view a game at `/\u003cid\u003e`.\\n\\n\")\n\tif games.Len() == 0 {\n\t\tsb.WriteString(\"_No games yet._\\n\")\n\t\treturn sb.String()\n\t}\n\tsb.WriteString(\"| # | X | O | Status |\\n|---|---|---|--------|\\n\")\n\tgames.Each(func(id store.ID, value any) {\n\t\tg := value.(*Game)\n\t\tsb.WriteString(\"| \")\n\t\tsb.WriteString(id.String())\n\t\tsb.WriteString(\" | `\")\n\t\tsb.WriteString(g.playerX.String())\n\t\tsb.WriteString(\"` | `\")\n\t\tsb.WriteString(g.playerO.String())\n\t\tsb.WriteString(\"` | \")\n\t\tsb.WriteString(gameStatus(g))\n\t\tsb.WriteString(\" |\\n\")\n\t})\n\treturn sb.String()\n}\n"},{"name":"tictactoe_test.gno","body":"package tictactoe\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// TestXWins: alice (X) beats bob (O) on the top row.\nfunc TestXWins(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\tuassert.True(t, id \u003e= 1, \"expected a game id\")\n\n\t// alice X -\u003e 0\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMove(cross(cur), id, 0)\n\t// bob O -\u003e 3\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tMove(cross(cur), id, 3)\n\t// alice X -\u003e 1\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMove(cross(cur), id, 1)\n\t// bob O -\u003e 4\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tMove(cross(cur), id, 4)\n\t// alice X -\u003e 2 wins top row\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMove(cross(cur), id, 2)\n\n\tg, err := GetGame(id)\n\tuassert.NoError(t, err)\n\tuassert.True(t, g.finished, \"game should be finished\")\n\tuassert.Equal(t, markX, g.winner)\n\tuassert.False(t, g.draw, \"should not be a draw\")\n}\n\n// TestTurnAndTakenGuards: rejects out-of-turn moves, taken cells, and non-players.\nfunc TestTurnAndTakenGuards(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\n\t// bob (O) cannot move first — it's X's turn.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur, \"not your turn\", func() {\n\t\tMove(cross(cur), id, 0)\n\t})\n\n\t// alice (X) plays 0.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tMove(cross(cur), id, 0)\n\n\t// alice cannot play twice in a row.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"not your turn\", func() {\n\t\tMove(cross(cur), id, 1)\n\t})\n\n\t// bob cannot take an occupied cell.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur, \"cell already taken\", func() {\n\t\tMove(cross(cur), id, 0)\n\t})\n\n\t// carol is not a player.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsWithMessage(t, cur, \"caller is not a player in this game\", func() {\n\t\tMove(cross(cur), id, 5)\n\t})\n}\n\n// TestDraw: fill the board with no winner.\nfunc TestDraw(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := NewGame(cross(cur), bob)\n\n\t// Sequence yielding a full board with no three-in-a-row:\n\t// X:0 O:1 X:2 O:4 X:3 O:5 X:7 O:6 X:8\n\tseq := []struct {\n\t\twho  address\n\t\tcell int\n\t}{\n\t\t{alice, 0}, {bob, 1}, {alice, 2},\n\t\t{bob, 4}, {alice, 3}, {bob, 5},\n\t\t{alice, 7}, {bob, 6}, {alice, 8},\n\t}\n\tfor _, s := range seq {\n\t\ttesting.SetRealm(testing.NewUserRealm(s.who))\n\t\tMove(cross(cur), id, s.cell)\n\t}\n\n\tg, err := GetGame(id)\n\tuassert.NoError(t, err)\n\tuassert.True(t, g.finished, \"game should be finished\")\n\tuassert.True(t, g.draw, \"should be a draw\")\n\tuassert.Equal(t, 0, g.winner)\n}\n\n// The store's labelled MustGet names the game v0's \"game not found\" left out.\nfunc TestMoveOnAMissingGameNamesIt(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"game #999999 not found\", func() {\n\t\tMove(cross(cur), 999999, 0)\n\t})\n}\n"}]},"send":"","max_deposit":"7000000ugnot"}],"fee":{"gas_wanted":"52718600","gas_fee":"158155ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"dJ/CrbumaNDSvnYYt6Cm97yUACkL/kjo/slbsrjg2bJAONA5Xh7nYFFIqx6kGMqLHvqNRfB1yVKI0kzTB8MsEQ=="}],"memo":""},"metadata":{"timestamp":"1790961392"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"HvjBnP2ufJoivCUObwgTvWhcAsgzQkCdPteNwUlmwvQW8oKM/lbPum6J0TVsOlREp6+Ka/kXWpCOIKdwP/ywwg=="}],"memo":""},"metadata":{"timestamp":"1790961392"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"timecapsule","path":"gno.land/r/moul/x/daily/timecapsule/v1","files":[{"name":"README.md","body":"# Time Capsule Guestbook\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA public guestbook with a twist: every message is sealed until a future block\nheight, chosen by its author when they leave it. Until then it's just a locked\nentry showing who sealed it and when it opens; once the chain reaches that\nheight, the message unlocks forever for anyone to read.\n\nRealm: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/timecapsule`\n\n## Example calls\n\n- `Leave(\"see you in 100 blocks\", 100)` — seal a message that opens 100 blocks\n  from now. Returns the capsule id. Only direct EOA (`MsgCall`) calls can seal\n  one; empty messages, messages over 500 bytes, and delays outside\n  `(0, 1_000_000]` blocks are rejected.\n- `Render(\"\")` — home page: counts + every already-unlocked message.\n- `Render(\"sealed\")` — every still-sealed capsule with its unlock height and\n  blocks remaining (message hidden).\n- `Render(\"capsule/\u003cid\u003e\")` — a single capsule's detail page; shows the message\n  only once unlocked.\n\n## Toolchain status\n\nTested locally against a `gnolang/gno` master checkout (`~/p/gh/gnoland/gno`)\nusing its own `gno` binary as GNOROOT, resolving `/p/nt/*` deps through its\n`examples/` workspace. All 5 unit tests pass (`gno test -v .`), and `gno lint .`\nreports no issues. This is newer than sapphire (gno 0.9), but the code only uses\nAPIs documented as current in the project's gno skill (`chain`, `chain/runtime`,\n`gno.land/p/nt/avl/v0`, `gno.land/p/nt/markdown/sanitize/v0`), so it should be\non-chain-valid for sapphire as well.\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`capsule` loses its `id` field, which the store now owns, and **capsule ids\nstart at 1** where `v0` handed out 0 for the first one. `capsule/0` is now\nrejected as an invalid id rather than looked up.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/timecapsule) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/timecapsule/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/timecapsule/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/timecapsule/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render_example_test.gno","body":"package timecapsule\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # ⏳ Time Capsule Guestbook\n\t//\n\t// Leave a message for the future. It stays sealed until its unlock block height, then anyone can read it — call `Leave(message, delayBlocks)`.\n\t//\n\t// 0 capsule(s) total · 0 unlocked · 0 still sealed.\n\t//\n\t// ## Unlocked messages\n\t//\n\t// _None yet. Be the first to leave one that will open later._\n}\n"},{"name":"timecapsule.gno","body":"// Package timecapsule is a public guestbook where every message is sealed\n// until a future block height, then permanently unlocked for anyone to read.\npackage timecapsule\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// capsule carries no id field: the id belongs to the store, which hands it\n// back on lookup and iteration.\ntype capsule struct {\n\tauthor       address\n\tmessage      string\n\tcreatedAt    int64\n\tunlockHeight int64\n}\n\n// capsules assigns the capsule ids. v0 kept its own nextID plus an idKey()\n// that called strings.Repeat WITHOUT the length guard the other realms had, so\n// at the 10^12th capsule it did not mis-sort, it panicked: Repeat rejects a\n// negative count, and the realm would have stopped accepting Leave calls. The\n// store key is 8 fixed bytes with no width to outgrow.\nvar capsules = store.Named(\"capsule\")\n\nconst (\n\tmaxDelayBlocks int64 = 1_000_000\n\tmaxMessageLen  int   = 500\n)\n\n// Leave seals a new message that stays hidden until `delayBlocks` blocks\n// from now, then becomes publicly readable forever. Returns the capsule id.\nfunc Leave(cur realm, message string, delayBlocks int64) int64 {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only direct user calls can leave a capsule\")\n\t}\n\n\tmessage = strings.TrimSpace(message)\n\tif message == \"\" {\n\t\tpanic(\"message must not be empty\")\n\t}\n\tif len(message) \u003e maxMessageLen {\n\t\tpanic(\"message too long\")\n\t}\n\tif delayBlocks \u003c= 0 || delayBlocks \u003e maxDelayBlocks {\n\t\tpanic(\"delayBlocks out of range\")\n\t}\n\n\tnow := runtime.ChainHeight()\n\tc := \u0026capsule{\n\t\tauthor:       cur.Previous().Address(),\n\t\tmessage:      message,\n\t\tcreatedAt:    now,\n\t\tunlockHeight: now + delayBlocks,\n\t}\n\tid := capsules.Add(c)\n\n\tchain.Emit(\"CapsuleSealed\",\n\t\t\"id\", id.String(),\n\t\t\"unlockHeight\", strconv.FormatInt(c.unlockHeight, 10),\n\t)\n\treturn int64(id)\n}\n\nfunc Render(path string) string {\n\tswitch {\n\tcase path == \"\":\n\t\treturn renderHome()\n\tcase path == \"sealed\":\n\t\treturn renderSealed()\n\tcase strings.HasPrefix(path, \"capsule/\"):\n\t\treturn renderCapsule(strings.TrimPrefix(path, \"capsule/\"))\n\tdefault:\n\t\treturn \"\u003e [!WARNING]\\n\u003e Path not found\\n\"\n\t}\n}\n\nfunc renderHome() string {\n\tnow := runtime.ChainHeight()\n\n\trevealed := 0\n\tsealed := 0\n\tcapsules.Each(func(_ store.ID, value any) {\n\t\tif value.(*capsule).unlockHeight \u003c= now {\n\t\t\trevealed++\n\t\t} else {\n\t\t\tsealed++\n\t\t}\n\t})\n\n\tvar out strings.Builder\n\tout.WriteString(\"# ⏳ Time Capsule Guestbook\\n\\n\")\n\tout.WriteString(\"Leave a message for the future. It stays sealed until its unlock block height, then anyone can read it — call `Leave(message, delayBlocks)`.\\n\\n\")\n\tout.WriteString(strconv.Itoa(revealed+sealed) + \" capsule(s) total · \" +\n\t\tstrconv.Itoa(revealed) + \" unlocked · \" + strconv.Itoa(sealed) + \" still sealed\")\n\tif sealed \u003e 0 {\n\t\tout.WriteString(\" (see [sealed](sealed))\")\n\t}\n\tout.WriteString(\".\\n\\n## Unlocked messages\\n\\n\")\n\n\tif revealed == 0 {\n\t\tout.WriteString(\"_None yet. Be the first to leave one that will open later._\\n\")\n\t\treturn out.String()\n\t}\n\n\tcapsules.Each(func(id store.ID, value any) {\n\t\tc := value.(*capsule)\n\t\tif c.unlockHeight \u003c= now {\n\t\t\tout.WriteString(renderEntry(id, c))\n\t\t}\n\t})\n\treturn out.String()\n}\n\nfunc renderSealed() string {\n\tnow := runtime.ChainHeight()\n\n\tvar out strings.Builder\n\tout.WriteString(\"# Sealed Capsules\\n\\n\")\n\n\tfound := false\n\tcapsules.Each(func(id store.ID, value any) {\n\t\tc := value.(*capsule)\n\t\tif c.unlockHeight \u003e now {\n\t\t\tfound = true\n\t\t\tout.WriteString(\"- capsule [#\" + id.String() + \"](capsule/\" +\n\t\t\t\tid.String() + \") by `\" + c.author.String() +\n\t\t\t\t\"` — unlocks at block \" + strconv.FormatInt(c.unlockHeight, 10) +\n\t\t\t\t\" (\" + strconv.FormatInt(c.unlockHeight-now, 10) + \" blocks left)\\n\")\n\t\t}\n\t})\n\tif !found {\n\t\tout.WriteString(\"_No sealed capsules right now._\\n\")\n\t}\n\treturn out.String()\n}\n\nfunc renderCapsule(idStr string) string {\n\tid, ok := store.ParseID(idStr)\n\tif !ok {\n\t\treturn \"\u003e [!WARNING]\\n\u003e Invalid capsule id\\n\"\n\t}\n\tv, ok := capsules.Get(id)\n\tif !ok {\n\t\treturn \"\u003e [!WARNING]\\n\u003e Capsule not found\\n\"\n\t}\n\tc := v.(*capsule)\n\tnow := runtime.ChainHeight()\n\n\tvar out strings.Builder\n\tout.WriteString(\"# Capsule #\" + id.String() + \"\\n\\n\")\n\tout.WriteString(\"Sealed by `\" + c.author.String() + \"` at block \" + strconv.FormatInt(c.createdAt, 10) + \".\\n\\n\")\n\n\tif c.unlockHeight \u003e now {\n\t\tout.WriteString(\"\\U0001f512 Still sealed. Unlocks at block \" + strconv.FormatInt(c.unlockHeight, 10) +\n\t\t\t\" (\" + strconv.FormatInt(c.unlockHeight-now, 10) + \" blocks left).\\n\")\n\t\treturn out.String()\n\t}\n\n\tout.WriteString(\"\\U0001f513 Unlocked at block \" + strconv.FormatInt(c.unlockHeight, 10) + \":\\n\\n\u003e \" +\n\t\tsanitize.InlineText(c.message) + \"\\n\")\n\treturn out.String()\n}\n\nfunc renderEntry(id store.ID, c *capsule) string {\n\treturn \"- **#\" + id.String() + \"** by `\" + c.author.String() +\n\t\t\"` (sealed at block \" + strconv.FormatInt(c.createdAt, 10) +\n\t\t\", opened at block \" + strconv.FormatInt(c.unlockHeight, 10) + \"):\\n  \u003e \" +\n\t\tsanitize.InlineText(c.message) + \"\\n\\n\"\n}\n"},{"name":"timecapsule_test.gno","body":"package timecapsule\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc resetState() {\n\tcapsules = store.Named(\"capsule\")\n}\n\nfunc TestLeaveAndReveal(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// v1 ids start at 1: the store never assigns 0, so the zero id stays\n\t// usable as \"absent\". v0 handed out 0 for the first capsule.\n\tid := Leave(cross(cur), \"hello, future\", 5)\n\tuassert.Equal(t, int64(1), id)\n\n\tif got := Render(\"\"); !strings.Contains(got, \"1 still sealed\") {\n\t\tt.Fatalf(\"expected capsule to still be sealed, got: %s\", got)\n\t}\n\tif got := Render(\"sealed\"); !strings.Contains(got, \"capsule/1\") {\n\t\tt.Fatalf(\"expected capsule 1 listed as sealed, got: %s\", got)\n\t}\n\n\ttesting.SkipHeights(5)\n\n\tif got := Render(\"\"); !strings.Contains(got, \"hello, future\") {\n\t\tt.Fatalf(\"expected capsule to be revealed, got: %s\", got)\n\t}\n\tif got := Render(\"capsule/1\"); !strings.Contains(got, \"hello, future\") {\n\t\tt.Fatalf(\"expected capsule detail to reveal message, got: %s\", got)\n\t}\n\n\t// Id 0 is never assigned, so the path is rejected rather than looked up.\n\tif got := Render(\"capsule/0\"); !strings.Contains(got, \"Invalid capsule id\") {\n\t\tt.Fatalf(\"expected capsule/0 to be rejected, got: %s\", got)\n\t}\n}\n\nfunc TestLeaveRejectsEmptyMessage(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsWithMessage(t, cur, \"message must not be empty\", func() {\n\t\tLeave(cross(cur), \"   \", 5)\n\t})\n}\n\nfunc TestLeaveRejectsBadDelay(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsWithMessage(t, cur, \"delayBlocks out of range\", func() {\n\t\tLeave(cross(cur), \"hi\", 0)\n\t})\n}\n\n// Regression: an intermediate realm (not a direct EOA call) must never be\n// able to seal a capsule as if it were a user.\nfunc TestLeaveRejectsCodeRealm(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/some/attacker\"))\n\n\tuassert.AbortsWithMessage(t, cur, \"only direct user calls can leave a capsule\", func() {\n\t\tLeave(cross(cur), \"hi\", 5)\n\t})\n}\n\nfunc TestRenderNotFound(t *testing.T) {\n\tresetState()\n\tif got := Render(\"nope\"); !strings.Contains(got, \"not found\") {\n\t\tt.Fatalf(\"expected 404-ish message, got: %s\", got)\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"44591000","gas_fee":"133773ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"3Wpo+gdNWvJ4cKPOhirp1ZKaljh5ApbBipDhFIVrV4F/zv5Cv7suQslIxz4gp2xY8uBbfF0Zwf8s+nMbDqXSRA=="}],"memo":""},"metadata":{"timestamp":"1790961446"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"timelock","path":"gno.land/r/moul/x/daily/timelock/v0","files":[{"name":"README.md","body":"# Timelock\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline (Solidity→Gno port). Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\n\nA simplified gno.land port of OpenZeppelin's **TimelockController**. Actions are\nscheduled with a block delay and can only be executed once the chain reaches the\noperation's ready height; before that they can be cancelled. It ports the core\ndelay-enforcement idea idiomatically — block height (`runtime.ChainHeight()`)\nreplaces `block.number`, `panic` replaces `require`, `chain.Emit` replaces\nevents, and an `avl.Tree` replaces the Solidity `mapping` (role-based access\ncontrol is omitted for simplicity).\n\nOperations are terminal once executed or cancelled, and `Render` lists every\noperation with its live state (Pending / Ready / Executed / Cancelled) and the\nnumber of blocks remaining until it becomes ready.\n\n## Example calls\n\n```\n# Schedule an action to run 20 blocks from now; returns the operation id.\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/timelock/v0 \\\n  -func Schedule -args \"upgrade contract\" -args 20 ...\n\n# Once ChainHeight() \u003e= readyHeight, execute it.\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/timelock/v0 \\\n  -func Execute -args 1 ...\n\n# Or cancel it beforehand.\ngnokey maketx call -pkgpath gno.land/r/moul/x/daily/timelock/v0 \\\n  -func Cancel -args 1 ...\n```\n\nView the queue by rendering the realm (`gno.land/r/moul/x/daily/timelock/v0`).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/timelock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timelock/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/timelock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timelock/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/timelock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timelock/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/timelock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timelock/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/timelock/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/timelock/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/timelock/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package timelock\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Timelock Controller\n\t//\n\t// Current chain height: **123**\n\t//\n\t// _No operations scheduled yet._\n\t//\n\t// Call `Schedule(action, delayBlocks)` to queue one.\n}\n"},{"name":"timelock.gno","body":"// Package timelock is a simplified port of OpenZeppelin's TimelockController.\n//\n// Operations are scheduled with a delay (measured in blocks). A scheduled\n// operation becomes executable only once the chain height reaches the\n// operation's ready height. Until then it can be cancelled by anyone (this\n// simplified port omits role-based access control). Once executed or\n// cancelled, an operation is terminal.\n//\n// Solidity mapping:\n//   - block.number      -\u003e runtime.ChainHeight()\n//   - msg.sender        -\u003e unsafe.PreviousRealm().Address()\n//   - require(...)       -\u003e panic(...)\n//   - events            -\u003e chain.Emit(...)\n//   - mapping(id =\u003e op) -\u003e avl.Tree keyed by zero-padded id\npackage timelock\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// State labels for an operation.\nconst (\n\tStatePending   = \"Pending\"   // scheduled, not yet ready\n\tStateReady     = \"Ready\"     // ready height reached, awaiting execution\n\tStateExecuted  = \"Executed\"  // terminal\n\tStateCancelled = \"Cancelled\" // terminal\n)\n\n// Operation is a single scheduled action.\ntype Operation struct {\n\tID          int\n\tAction      string\n\tProposer    address\n\tScheduled   int64 // chain height at scheduling\n\tReadyHeight int64 // executable once ChainHeight() \u003e= ReadyHeight\n\tDone        bool  // executed\n\tCancelled   bool\n}\n\nvar (\n\tops    = avl.NewTree() // key: paddedKey(id) -\u003e *Operation\n\tnextID = 1\n)\n\n// Schedule registers a new operation to run after delayBlocks blocks and\n// returns its id. delayBlocks must be \u003e= 0.\nfunc Schedule(cur realm, action string, delayBlocks int) int {\n\tif action == \"\" {\n\t\tpanic(\"timelock: empty action\")\n\t}\n\tif delayBlocks \u003c 0 {\n\t\tpanic(\"timelock: negative delay\")\n\t}\n\n\th := runtime.ChainHeight()\n\tid := nextID\n\tnextID++\n\n\top := \u0026Operation{\n\t\tID:          id,\n\t\tAction:      action,\n\t\tProposer:    unsafe.PreviousRealm().Address(),\n\t\tScheduled:   h,\n\t\tReadyHeight: h + int64(delayBlocks),\n\t}\n\tops.Set(paddedKey(id), op)\n\n\tchain.Emit(\"Scheduled\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"action\", action,\n\t\t\"readyHeight\", strconv.FormatInt(op.ReadyHeight, 10),\n\t)\n\treturn id\n}\n\n// Execute runs a ready operation. It panics if the operation is unknown,\n// already terminal, or not yet ready.\nfunc Execute(cur realm, id int) {\n\top := mustGet(id)\n\tif op.Done {\n\t\tpanic(\"timelock: already executed\")\n\t}\n\tif op.Cancelled {\n\t\tpanic(\"timelock: operation cancelled\")\n\t}\n\tif runtime.ChainHeight() \u003c op.ReadyHeight {\n\t\tpanic(\"timelock: operation not ready\")\n\t}\n\top.Done = true\n\n\tchain.Emit(\"Executed\", \"id\", strconv.Itoa(id), \"action\", op.Action)\n}\n\n// Cancel drops a pending or ready operation before it executes. It panics if\n// the operation is unknown or already terminal.\nfunc Cancel(cur realm, id int) {\n\top := mustGet(id)\n\tif op.Done {\n\t\tpanic(\"timelock: already executed\")\n\t}\n\tif op.Cancelled {\n\t\tpanic(\"timelock: already cancelled\")\n\t}\n\top.Cancelled = true\n\n\tchain.Emit(\"Cancelled\", \"id\", strconv.Itoa(id), \"action\", op.Action)\n}\n\n// mustGet returns the operation or panics if absent.\nfunc mustGet(id int) *Operation {\n\tv := ops.Get(paddedKey(id))\n\tif v == nil {\n\t\tpanic(\"timelock: unknown operation\")\n\t}\n\treturn v.(*Operation)\n}\n\n// --- pure/read-only helpers (safe to unit-test) ---\n\n// paddedKey returns a fixed-width, lexicographically sortable key for an id so\n// avl iteration yields operations in id order.\nfunc paddedKey(id int) string {\n\ts := strconv.Itoa(id)\n\tfor len(s) \u003c 12 {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n\n// StateOf returns the display state of op at the given chain height.\nfunc StateOf(op *Operation, height int64) string {\n\tswitch {\n\tcase op.Cancelled:\n\t\treturn StateCancelled\n\tcase op.Done:\n\t\treturn StateExecuted\n\tcase height \u003e= op.ReadyHeight:\n\t\treturn StateReady\n\tdefault:\n\t\treturn StatePending\n\t}\n}\n\n// BlocksRemaining returns how many blocks remain before op is ready (0 if\n// already ready or past).\nfunc BlocksRemaining(op *Operation, height int64) int64 {\n\tif height \u003e= op.ReadyHeight {\n\t\treturn 0\n\t}\n\treturn op.ReadyHeight - height\n}\n\n// Render implements the standard realm markdown view.\nfunc Render(path string) string {\n\th := runtime.ChainHeight()\n\tout := \"# Timelock Controller\\n\\n\"\n\tout += ufmt.Sprintf(\"Current chain height: **%d**\\n\\n\", h)\n\n\tif ops.Size() == 0 {\n\t\tout += \"_No operations scheduled yet._\\n\\n\"\n\t\tout += \"Call `Schedule(action, delayBlocks)` to queue one.\\n\"\n\t\treturn out\n\t}\n\n\tout += ufmt.Sprintf(\"Total operations: **%d**\\n\\n\", ops.Size())\n\tout += \"| ID | Action | State | Ready @ | Blocks left | Proposer |\\n\"\n\tout += \"|---:|--------|-------|--------:|------------:|----------|\\n\"\n\n\tops.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\top := v.(*Operation)\n\t\tstate := StateOf(op, h)\n\t\tleft := BlocksRemaining(op, h)\n\t\tout += ufmt.Sprintf(\"| %d | %s | %s | %d | %d | %s |\\n\",\n\t\t\top.ID, op.Action, state, op.ReadyHeight, left, op.Proposer.String())\n\t\treturn false\n\t})\n\treturn out\n}\n"},{"name":"timelock_test.gno","body":"package timelock\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestStateOf(t *testing.T) {\n\tbase := \u0026Operation{ID: 1, Action: \"upgrade\", ReadyHeight: 100}\n\n\t// Before ready height -\u003e Pending.\n\tuassert.Equal(t, StatePending, StateOf(base, 50))\n\t// At/after ready height -\u003e Ready.\n\tuassert.Equal(t, StateReady, StateOf(base, 100))\n\tuassert.Equal(t, StateReady, StateOf(base, 150))\n\n\t// Executed and cancelled are terminal regardless of height.\n\tdone := \u0026Operation{ID: 2, ReadyHeight: 10, Done: true}\n\tuassert.Equal(t, StateExecuted, StateOf(done, 5))\n\tuassert.Equal(t, StateExecuted, StateOf(done, 999))\n\n\tcancelled := \u0026Operation{ID: 3, ReadyHeight: 10, Cancelled: true}\n\tuassert.Equal(t, StateCancelled, StateOf(cancelled, 5))\n\tuassert.Equal(t, StateCancelled, StateOf(cancelled, 999))\n}\n\nfunc TestBlocksRemaining(t *testing.T) {\n\top := \u0026Operation{ID: 1, ReadyHeight: 100}\n\n\tuassert.Equal(t, int64(100), BlocksRemaining(op, 0))\n\tuassert.Equal(t, int64(40), BlocksRemaining(op, 60))\n\t// At ready height and beyond -\u003e 0.\n\tuassert.Equal(t, int64(0), BlocksRemaining(op, 100))\n\tuassert.Equal(t, int64(0), BlocksRemaining(op, 250))\n}\n\nfunc TestPaddedKeyOrdering(t *testing.T) {\n\t// Keys must be fixed-width so lexical order matches numeric id order.\n\tuassert.True(t, paddedKey(2) \u003c paddedKey(10))\n\tuassert.True(t, paddedKey(9) \u003c paddedKey(100))\n\tuassert.Equal(t, len(paddedKey(1)), len(paddedKey(123456)))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"37248600","gas_fee":"111745ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"gZ9Njp/c947geiefsn2ayd48LCsqgPDO48zEDnZYB9M7eggQq33koHFfU8898dzA4IP8dvSJ2g/9n5FhTBJYzQ=="}],"memo":""},"metadata":{"timestamp":"1790961449"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"tipjar","path":"gno.land/r/moul/x/daily/tipjar/v1","files":[{"name":"README.md","body":"# Tip Jar\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA public tip jar realm: anyone can send real ugnot with an optional message via Tip, and the realm tracks a leaderboard of the most generous tippers plus a feed of recent tips, both rendered live in Markdown. Only the deployer (captured as owner at deploy time) can withdraw the accumulated balance. It's a small, complete example of the payment-guard pattern (OriginSend + IsUserCall) paired with a sorted avl.Tree leaderboard.\n\nBuilt for gno 0.9.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/tipjar) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `medal` helper.\n\n**One podium.** `ui.Podium` replaces the medal switch three realms each had a copy of. Same output.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/tipjar/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tipjar/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/tipjar/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tipjar/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/tipjar/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tipjar/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/tipjar/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/tipjar/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/tipjar/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/tipjar/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/tipjar/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"tipjar.gno","body":"// Package tipjar is a public tip jar. Anyone can send real ugnot with an\n// optional message via Tip; the realm keeps a running leaderboard of the\n// most generous tippers and a feed of the most recent tips, both shown in\n// Render. Only the deployer (captured as owner at init time) can Withdraw\n// the accumulated balance. State-mutating functions are crossing functions\n// (`cur realm`) per the gno 0.9 interrealm convention.\npackage tipjar\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst (\n\tdenom         = \"ugnot\"\n\tmaxRecent     = 10\n\tmaxMessageLen = 140\n)\n\n// tipperStats is the persisted, accumulated record for one tipper.\ntype tipperStats struct {\n\taddr        address\n\ttotal       int64\n\tcount       int\n\tlastMessage string\n\tlastHeight  int64\n}\n\n// tipEntry is one line in the recent-tips feed.\ntype tipEntry struct {\n\tfrom    address\n\tamount  int64\n\tmessage string\n\theight  int64\n}\n\nvar (\n\towner address // captured deployer, set once in init\n\n\ttippers avl.Tree // address string -\u003e *tipperStats\n\trecent  []tipEntry\n\n\ttotalReceived int64\n\twithdrawn     int64\n\ttipCount      int\n)\n\nfunc init() {\n\towner = unsafe.OriginCaller()\n}\n\n// get returns the stored *tipperStats for addr, creating one if absent.\nfunc get(addr address) *tipperStats {\n\tkey := addr.String()\n\tif v := tippers.Get(key); v != nil {\n\t\treturn v.(*tipperStats)\n\t}\n\tts := \u0026tipperStats{addr: addr}\n\ttippers.Set(key, ts)\n\treturn ts\n}\n\n// Tip credits the caller's OriginSend ugnot to the jar and records it\n// against their running total. Only an EOA calling directly via MsgCall may\n// tip — see the payment-guard note on IsUserCall vs IsUser.\nfunc Tip(cur realm, message string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tprev := cur.Previous()\n\tif !prev.IsUserCall() {\n\t\tpanic(\"only an EOA via MsgCall can tip\")\n\t}\n\tif len(message) \u003e maxMessageLen {\n\t\tpanic(\"message too long (max \" + strconv.Itoa(maxMessageLen) + \" chars)\")\n\t}\n\n\tamount := unsafe.OriginSend().AmountOf(denom)\n\tif amount \u003c= 0 {\n\t\tpanic(\"send some ugnot to tip\")\n\t}\n\n\tfrom := prev.Address()\n\theight := runtime.ChainHeight()\n\n\tts := get(from)\n\tts.total += amount\n\tts.count++\n\tts.lastMessage = message\n\tts.lastHeight = height\n\n\ttotalReceived += amount\n\ttipCount++\n\n\trecent = append(recent, tipEntry{from: from, amount: amount, message: message, height: height})\n\tif len(recent) \u003e maxRecent {\n\t\trecent = recent[len(recent)-maxRecent:]\n\t}\n\n\tchain.Emit(\"Tip\", \"from\", from.String(), \"amount\", strconv.FormatInt(amount, 10), \"message\", message)\n\treturn \"thanks for the \" + strconv.FormatInt(amount, 10) + \"ugnot tip!\"\n}\n\n// Balance reports the ugnot still held by the jar (received minus withdrawn).\nfunc Balance() int64 {\n\treturn totalReceived - withdrawn\n}\n\n// Withdraw sends amount ugnot from the jar to the owner. Owner-only.\nfunc Withdraw(cur realm, amount int64) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tif cur.Previous().Address() != owner {\n\t\tpanic(\"only the owner can withdraw\")\n\t}\n\tif amount \u003c= 0 {\n\t\tpanic(\"amount must be positive\")\n\t}\n\tif amount \u003e Balance() {\n\t\tpanic(\"amount exceeds available balance\")\n\t}\n\n\tbnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tbnk.SendCoins(cur.Address(), owner, chain.NewCoins(chain.NewCoin(denom, amount)))\n\twithdrawn += amount\n\n\tchain.Emit(\"Withdraw\", \"amount\", strconv.FormatInt(amount, 10))\n}\n\n// byTotal implements sort.Interface, ranking tippers by total tipped\n// descending, ties broken by tip count then address for a fully\n// deterministic order.\ntype byTotal struct {\n\tstats []*tipperStats\n}\n\nfunc (b byTotal) Len() int      { return len(b.stats) }\nfunc (b byTotal) Swap(i, j int) { b.stats[i], b.stats[j] = b.stats[j], b.stats[i] }\nfunc (b byTotal) Less(i, j int) bool {\n\tif b.stats[i].total != b.stats[j].total {\n\t\treturn b.stats[i].total \u003e b.stats[j].total\n\t}\n\tif b.stats[i].count != b.stats[j].count {\n\t\treturn b.stats[i].count \u003e b.stats[j].count\n\t}\n\treturn b.stats[i].addr.String() \u003c b.stats[j].addr.String()\n}\n\n// leaderboard collects all tippers ranked by total tipped descending.\nfunc leaderboard() []*tipperStats {\n\tstats := make([]*tipperStats, 0, tippers.Size())\n\ttippers.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tstats = append(stats, v.(*tipperStats))\n\t\treturn false\n\t})\n\tsort.Stable(byTotal{stats: stats})\n\treturn stats\n}\n\n// display returns a shortened address for table display.\nfunc display(addr address) string {\n\ts := addr.String()\n\tif len(s) \u003e 12 {\n\t\treturn s[:8] + \"…\" + s[len(s)-4:]\n\t}\n\treturn s\n}\n\n// Render shows the jar's balance, the tipper leaderboard, and a feed of the\n// most recent tips.\nfunc Render(path string) string {\n\tout := \"# 🫙 Tip Jar\\n\\n\"\n\tout += \"Send ugnot with `Tip(message)` to leave a tip and a note. \" +\n\t\t\"The owner can withdraw the accumulated balance with `Withdraw(amount)`.\\n\\n\"\n\n\tout += \"**Balance:** \" + strconv.FormatInt(Balance(), 10) + \"ugnot\" +\n\t\t\"  ·  **Total tips:** \" + strconv.Itoa(tipCount) +\n\t\t\"  ·  **All-time received:** \" + strconv.FormatInt(totalReceived, 10) + \"ugnot\\n\\n\"\n\n\tstats := leaderboard()\n\tout += \"## Leaderboard\\n\\n\"\n\tif len(stats) == 0 {\n\t\tout += \"_No tips yet. Be the first!_\\n\\n\"\n\t} else {\n\t\tout += \"| Rank | Tipper | Total tipped | Tips |\\n\"\n\t\tout += \"| ---: | :--- | ---: | ---: |\\n\"\n\t\tfor i, ts := range stats {\n\t\t\trankCell := ui.Podium(i)\n\t\t\tif rankCell == \"\" {\n\t\t\t\trankCell = strconv.Itoa(i + 1)\n\t\t\t}\n\t\t\tout += \"| \" + rankCell +\n\t\t\t\t\" | \" + display(ts.addr) +\n\t\t\t\t\" | \" + strconv.FormatInt(ts.total, 10) + \"ugnot\" +\n\t\t\t\t\" | \" + strconv.Itoa(ts.count) + \" |\\n\"\n\t\t}\n\t\tout += \"\\n\"\n\t}\n\n\tout += \"## Recent tips\\n\\n\"\n\tif len(recent) == 0 {\n\t\tout += \"_Nothing yet._\\n\"\n\t\treturn out\n\t}\n\tfor i := len(recent) - 1; i \u003e= 0; i-- {\n\t\te := recent[i]\n\t\tout += \"- **\" + display(e.from) + \"** tipped \" + strconv.FormatInt(e.amount, 10) +\n\t\t\t\"ugnot at block \" + strconv.FormatInt(e.height, 10)\n\t\tif e.message != \"\" {\n\t\t\tout += \": _\" + e.message + \"_\"\n\t\t}\n\t\tout += \"\\n\"\n\t}\n\treturn out\n}\n"},{"name":"tipjar_test.gno","body":"package tipjar\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nvar realmAddr = chain.PackageAddress(\"gno.land/r/moul/x/daily/tipjar/v1\")\n\n// reset clears package globals between tests, pinning owner to a known test\n// address rather than whatever init() captured from the test harness.\nfunc reset() {\n\towner = testutils.TestAddress(\"owner\")\n\ttippers = avl.Tree{}\n\trecent = nil\n\ttotalReceived = 0\n\twithdrawn = 0\n\ttipCount = 0\n}\n\n// fund simulates a tipper sending `amount` ugnot alongside the tx: the\n// runtime deposits it at the realm's address first, then unsafe.OriginSend\n// reports it to the crossing function. SetRealm is call-frame scoped (see\n// build.md), so the caller must still SetRealm directly before crossing.\nfunc fund(amount int64) {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{denom, amount}})\n}\n\nfunc TestTipCreditsAndTracks(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\n\tfund(500)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTip(cross(cur), \"gm\")\n\n\tif got := Balance(); got != 500 {\n\t\tt.Fatalf(\"Balance() = %d, want 500\", got)\n\t}\n\tif tipCount != 1 {\n\t\tt.Fatalf(\"tipCount = %d, want 1\", tipCount)\n\t}\n\tts := get(alice)\n\tif ts.total != 500 || ts.count != 1 || ts.lastMessage != \"gm\" {\n\t\tt.Fatalf(\"unexpected tipper stats: %+v\", ts)\n\t}\n\n\tfund(250)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTip(cross(cur), \"again\")\n\tif got := get(alice).total; got != 750 {\n\t\tt.Fatalf(\"cumulative total = %d, want 750\", got)\n\t}\n\tif got := Balance(); got != 750 {\n\t\tt.Fatalf(\"Balance() after second tip = %d, want 750\", got)\n\t}\n}\n\nfunc TestTipRejectsZeroAmount(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\trec := revive(func() { Tip(cross(cur), \"freeloading\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when tipping with no ugnot sent\")\n\t}\n}\n\nfunc TestTipRejectsNonUserCall(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/g1attacker/relay\"))\n\n\trec := revive(func() { Tip(cross(cur), \"sneaky\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when the caller isn't an EOA via MsgCall\")\n\t}\n}\n\nfunc TestWithdrawOwnerOnly(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tmallory := testutils.TestAddress(\"mallory\")\n\n\tfund(1000)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTip(cross(cur), \"for the jar\")\n\n\ttesting.SetRealm(testing.NewUserRealm(mallory))\n\trec := revive(func() { Withdraw(cross(cur), 100) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when a non-owner withdraws\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tWithdraw(cross(cur), 400)\n\n\tif got := Balance(); got != 600 {\n\t\tt.Fatalf(\"Balance() after withdraw = %d, want 600\", got)\n\t}\n\tro := banker.NewReadonlyBanker()\n\tif got := ro.GetCoins(owner).AmountOf(denom); got != 400 {\n\t\tt.Fatalf(\"owner received = %d, want 400\", got)\n\t}\n\n\trec = revive(func() { Withdraw(cross(cur), 10000) })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic when withdrawing more than the balance\")\n\t}\n}\n\nfunc TestRenderShowsLeaderboardAndFeed(cur realm, t *testing.T) {\n\treset()\n\tif !strings.Contains(Render(\"\"), \"No tips yet\") {\n\t\tt.Fatal(\"expected empty-jar placeholder\")\n\t}\n\n\talice := testutils.TestAddress(\"alice\")\n\tfund(300)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTip(cross(cur), \"nice work\")\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Leaderboard\") {\n\t\tt.Fatal(\"expected leaderboard section\")\n\t}\n\tif !strings.Contains(out, \"nice work\") {\n\t\tt.Fatal(\"expected the tip message in the recent-tips feed\")\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"44437600","gas_fee":"133312ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"ELwGJDFnrOnPTfJJvBSk48otDOCRZQlYZa9LIlIexKhkyFvxUQOJy3hy+NIL68Z2mUJ3IttAvADNqAkPL6+52w=="}],"memo":""},"metadata":{"timestamp":"1790961450"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"todos","path":"gno.land/r/moul/x/daily/todos/v1","files":[{"name":"README.md","body":"# Shared To-Do Board\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn on-chain, shared to-do list realm for the gno.land **sapphire** testnet (gno 0.9).\nAnyone can add an item to the board; each item records the caller's address as\nits author, and can be toggled open/done or removed. `Render` shows the board as\nMarkdown checkboxes with live open/done counts, newest item first.\n\n- **Realm path:** `gno.land/r/REPLACE_ADDR/todos` (replace `REPLACE_ADDR` with your deploy address)\n\n## Exported transactions\n\n| Function | Effect |\n|---|---|\n| `Add(text string) int` | Adds an item authored by the caller, returns its id |\n| `Toggle(id int)` | Flips an item between open and done |\n| `Remove(id int)` | Deletes an item |\n\nAll three are gno 0.9 crossing functions (`cur realm` first parameter) and must\nbe invoked with `cross(cur)` from another realm, or directly via `MsgCall`.\n\n## Example calls\n\n```sh\n# Add an item (returns the new id)\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/todos\" \\\n  -func Add -args \"buy milk\" -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e mykey\n\n# Mark item #3 done (toggle)\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/todos\" \\\n  -func Toggle -args 3 -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e mykey\n\n# Remove item #3\ngnokey maketx call -pkgpath \"gno.land/r/REPLACE_ADDR/todos\" \\\n  -func Remove -args 3 -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e mykey\n```\n\n## Example render output\n\n```markdown\n# Shared To-Do Board\n\n2 open · 1 done · 3 total\n\n- [ ] #3 walk dog (g1abc…)\n- [x] #2 buy milk (g1abc…)\n- [ ] #1 write realm (g1def…)\n```\n\n## What changed in v1\n\nTwo ports against [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/todos), which stays live and untouched.\n\n### Rendering\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/todos) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nVisible change: addresses now render in monospace.\n\n### Storage\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\n`v0` padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`item` loses its `id` field, which the store now owns. `Render`'s newest-first\nlist also gets shorter: `v0` collected every line into a slice in ascending\norder and then walked it backwards, where the store iterates descending\ndirectly. `Toggle`'s not-found path becomes one line, and `Remove`'s message\ngains the id in the same wording.\n\nIds stay plain integers and the rendered output of the storage port is\nunchanged. Each port changes something `v0` promised, one the rendered output\nand one the storage layout, so under this repo's versioning rule each is a\ncompatibility change and neither could be an edit to `v0` in place.\n\nThey land in the **same** new version because `v1` was never published. A\nversion number is a tag on something that exists on a chain, and until it does\nthere is nothing for a second number to avoid disturbing, so the right move is\nto keep editing the version you have. `gnopm unbump` is what folded the second\nport back down into this one.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/todos/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/todos/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/todos/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/todos/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/todos/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/todos/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/todos/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/todos/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/todos/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/todos/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/todos/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"todos.gno","body":"// Package todos is a shared, on-chain to-do board realm.\n//\n// Anyone can add an item; the caller's address is recorded as the author.\n// Items can be toggled (open/done) or removed. Render exposes the board as\n// Markdown checkboxes with open/done counts, newest item first.\npackage todos\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\n// item is one entry on the board. `address` is the uverse bech32 type — it is\n// persistable (unlike a `realm` value), so it is safe to store across txs.\n// It carries no id field: the id belongs to the store, which hands it back on\n// lookup and iteration.\ntype item struct {\n\ttext   string\n\tdone   bool\n\tauthor address\n}\n\n// items assigns the item ids. v1 kept its own nextID plus an idKey() that\n// zero-padded to width 12, which stopped ordering Render past 10^12.\nvar items = store.Named(\"todos: item\")\n\n// Add appends a new item authored by the caller and returns its id.\n//\n// Crossing function: takes `cur realm` first (gno 0.9 interrealm convention),\n// authenticates with cur.IsCurrent() before trusting cur.Previous().\nfunc Add(cur realm, text string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\ttext = strings.TrimSpace(text)\n\tif text == \"\" {\n\t\tpanic(\"todos: text must not be empty\")\n\t}\n\n\tauthor := cur.Previous().Address()\n\n\treturn int(items.Add(\u0026item{\n\t\ttext:   text,\n\t\tdone:   false,\n\t\tauthor: author,\n\t}))\n}\n\n// Toggle flips the done state of the item with the given id.\nfunc Toggle(cur realm, id int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tit := items.MustGet(store.ID(id)).(*item)\n\tit.done = !it.done\n}\n\n// Remove deletes the item with the given id.\nfunc Remove(cur realm, id int) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tif _, removed := items.Remove(store.ID(id)); !removed {\n\t\tpanic(\"todos: item #\" + strconv.Itoa(id) + \" not found\")\n\t}\n}\n\n// counts returns the number of open and done items.\nfunc counts() (open, done int) {\n\titems.Each(func(_ store.ID, v any) {\n\t\tif v.(*item).done {\n\t\t\tdone++\n\t\t} else {\n\t\t\topen++\n\t\t}\n\t})\n\treturn open, done\n}\n\n// Render returns the board as Markdown. Newest item (highest id) first.\n//\n// Render is NOT a crossing function (no `cur realm` param) — it is read-only\n// and invoked by gnoweb, not via MsgCall.\nfunc Render(path string) string {\n\topen, done := counts()\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Shared To-Do Board\\n\\n\")\n\tb.WriteString(strconv.Itoa(open) + \" open · \")\n\tb.WriteString(strconv.Itoa(done) + \" done · \")\n\tb.WriteString(strconv.Itoa(open+done) + \" total\\n\\n\")\n\n\tif open+done == 0 {\n\t\tb.WriteString(\"_No items yet. Add one with `Add(text)`._\\n\")\n\t\treturn b.String()\n\t}\n\n\t// The store iterates by id, so newest-first is one call rather than a\n\t// collect-then-walk-backwards.\n\titems.EachReverse(func(id store.ID, v any) {\n\t\tit := v.(*item)\n\t\tmark := \" \"\n\t\tif it.done {\n\t\t\tmark = \"x\"\n\t\t}\n\t\tb.WriteString(\"- [\" + mark + \"] #\" + id.String() + \" \" +\n\t\t\tit.text + \" (\" + ui.Addr(it.author) + \")\\n\")\n\t})\n\n\treturn b.String()\n}\n"},{"name":"todos_test.gno","body":"package todos\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// reset clears package globals between tests (t.Run/subtests do not reset them).\nfunc reset() {\n\titems = store.Named(\"todos: item\")\n}\n\n// TestAddToggleRemove exercises the full lifecycle through the crossing API.\n// Crossing test: takes `cur realm` and calls via cross(cur).\nfunc TestAddToggleRemove(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid1 := Add(cross(cur), \"buy milk\")\n\tif id1 != 1 {\n\t\tt.Fatalf(\"Add first id = %d, want 1\", id1)\n\t}\n\tid2 := Add(cross(cur), \"walk dog\")\n\tif id2 != 2 {\n\t\tt.Fatalf(\"Add second id = %d, want 2\", id2)\n\t}\n\n\topen, done := counts()\n\tif open != 2 || done != 0 {\n\t\tt.Fatalf(\"after adds: open=%d done=%d, want 2/0\", open, done)\n\t}\n\n\t// Toggle #1 done.\n\tToggle(cross(cur), 1)\n\topen, done = counts()\n\tif open != 1 || done != 1 {\n\t\tt.Fatalf(\"after toggle: open=%d done=%d, want 1/1\", open, done)\n\t}\n\n\t// Toggle #1 back to open.\n\tToggle(cross(cur), 1)\n\topen, done = counts()\n\tif open != 2 || done != 0 {\n\t\tt.Fatalf(\"after re-toggle: open=%d done=%d, want 2/0\", open, done)\n\t}\n\n\t// Remove #1.\n\tRemove(cross(cur), 1)\n\topen, done = counts()\n\tif open != 1 || done != 0 {\n\t\tt.Fatalf(\"after remove: open=%d done=%d, want 1/0\", open, done)\n\t}\n\tif items.Has(store.ID(1)) {\n\t\tt.Fatalf(\"item #1 still present after Remove\")\n\t}\n}\n\n// TestRender checks the Markdown output shape and counts. Render is not a\n// crossing function, so this is a plain test — but the Add calls that seed\n// state still need a realm, so it also takes `cur realm`.\nfunc TestRender(cur realm, t *testing.T) {\n\treset()\n\n\t// Empty board.\n\tempty := Render(\"\")\n\tif !strings.Contains(empty, \"0 open · 0 done · 0 total\") {\n\t\tt.Fatalf(\"empty render missing zero counts:\\n%s\", empty)\n\t}\n\tif !strings.Contains(empty, \"No items yet\") {\n\t\tt.Fatalf(\"empty render missing placeholder:\\n%s\", empty)\n\t}\n\n\tbob := testutils.TestAddress(\"bob\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\n\tAdd(cross(cur), \"first\")\n\tAdd(cross(cur), \"second\")\n\tAdd(cross(cur), \"third\")\n\tToggle(cross(cur), 2) // mark #2 done\n\n\tout := Render(\"\")\n\n\t// Counts line: 2 open, 1 done, 3 total.\n\tif !strings.Contains(out, \"2 open · 1 done · 3 total\") {\n\t\tt.Fatalf(\"render counts wrong:\\n%s\", out)\n\t}\n\t// Done checkbox for #2.\n\tif !strings.Contains(out, \"- [x] #2 second\") {\n\t\tt.Fatalf(\"render missing done item #2:\\n%s\", out)\n\t}\n\t// Open checkbox for #1.\n\tif !strings.Contains(out, \"- [ ] #1 first\") {\n\t\tt.Fatalf(\"render missing open item #1:\\n%s\", out)\n\t}\n\t// Newest first: #3 must appear before #1.\n\tif strings.Index(out, \"#3 third\") \u003e strings.Index(out, \"#1 first\") {\n\t\tt.Fatalf(\"render not newest-first:\\n%s\", out)\n\t}\n\t// Author short form present.\n\tif !strings.Contains(out, \"(`g1\") {\n\t\tt.Fatalf(\"render missing author short address:\\n%s\", out)\n\t}\n}\n\n// TestIDKeyOrdering verifies the store key sorts numerically. v1 asserted the\n// same thing about its own idKey, which padded to width 12: that held only\n// below the width, since idKey(10^12) is 13 characters and sorts before\n// idKey(10^12-1). The store key is 8 bytes for every id, so there is no\n// ceiling. Non-crossing: plain signature.\nfunc TestIDKeyOrdering(t *testing.T) {\n\tif store.ID(2).Key() \u003e= store.ID(10).Key() {\n\t\tt.Fatal(\"id 2 should sort before id 10\")\n\t}\n\tif store.ID(9).Key() \u003e= store.ID(100).Key() {\n\t\tt.Fatal(\"id 9 should sort before id 100\")\n\t}\n\tif store.ID(999999999999).Key() \u003e= store.ID(1000000000000).Key() {\n\t\tt.Fatal(\"ordering should survive one past v1's width-12 ceiling\")\n\t}\n\tif len(store.ID(1).Key()) != len(store.ID(1000000000000).Key()) {\n\t\tt.Fatal(\"every key is the same width\")\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"44926400","gas_fee":"134779ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"mELjM2HkkoeLnGkE3Cs71bEFbbWzzbZebH972cXGtts3onF46PM006i9Mfivjlk/JWUGK/rkS186SjLDht06Kw=="}],"memo":""},"metadata":{"timestamp":"1790961450"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"toposortdemo","path":"gno.land/r/moul/x/daily/toposortdemo/v0","files":[{"name":"README.md","body":"# Topological Sort\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nShows a small build graph resolved into a safe install order — and a\ndeliberately broken one, to show how a cycle is reported.\n\nDemo of the [`p/moul/x/daily/toposort`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/toposort)\nlibrary — the graph, the ordering and the cycle detection all come from the\npackage; this realm holds no logic of its own. Stateless and read-only, so\n`Render` is fully deterministic.\n\n```\n/r/moul/x/daily/toposortdemo/v0        → the build graph, resolved into an order\n/r/moul/x/daily/toposortdemo/v0:cycle  → a cyclic graph and its failure report\n```\n\nThe interesting part is that the ordering is **unique**: ties are broken\nlexicographically, so this graph will always resolve to the same list. The cycle\npage shows the other half of the contract — the nodes that could not be ordered\nare named rather than silently dropped.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/toposortdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/toposortdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/toposortdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/toposortdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/toposortdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/toposortdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/toposortdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/toposortdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/toposortdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/toposortdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/toposortdemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package toposortdemo\n\n// ExampleRender pins the realm's root Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Topological Sort\n\t//\n\t// Ordering a dependency graph so nothing is built before what it needs, demoing the [`p/moul/x/daily/toposort`](/p/moul/x/daily/toposort/v0) library.\n\t//\n\t// ## The graph\n\t//\n\t// ```\n\t// avl \u003c- strings\n\t// markdown \u003c- strings\n\t// realm \u003c- storage, ui\n\t// storage \u003c- avl\n\t// strings\n\t// ui \u003c- markdown\n\t// ```\n\t//\n\t// ## Install order\n\t//\n\t// 1. `strings`\n\t// 2. `avl`\n\t// 3. `markdown`\n\t// 4. `storage`\n\t// 5. `ui`\n\t// 6. `realm`\n\t//\n\t// Ties are broken lexicographically, so this ordering is the *only* one the library will ever produce for this graph.\n\t//\n\t// \u003e See [`/cycle`](/r/moul/x/daily/toposortdemo/v0:cycle) for what happens when the graph is not a DAG.\n}\n\n// ExampleRender_cycle pins the failure mode: a cycle is reported with the nodes\n// still stuck, rather than silently dropping them.\nfunc ExampleRender_cycle() {\n\tprint(Render(\"/cycle\"))\n\t// Output:\n\t// # Topological Sort\n\t//\n\t// Ordering a dependency graph so nothing is built before what it needs, demoing the [`p/moul/x/daily/toposort`](/p/moul/x/daily/toposort/v0) library.\n\t//\n\t// ## A graph with a cycle\n\t//\n\t// ```\n\t// auth \u003c- session\n\t// server \u003c- auth\n\t// session \u003c- auth\n\t// ```\n\t//\n\t// `Sort` returns an error: **toposort: graph has a cycle**\n\t//\n\t// Ordered before giving up: _nothing_\n\t//\n\t// Stuck on the cycle: `auth`, `server`, `session`\n\t//\n\t// \u003e The nodes still stuck are named rather than silently dropped, so a caller can report exactly which dependencies are tangled.\n}\n"},{"name":"toposortdemo.gno","body":"// Package toposortdemo is a small gnoweb demo of the dependency ordering\n// provided by the [p/moul/x/daily/toposort](/p/moul/x/daily/toposort/v0)\n// library: it shows a build graph resolved into a safe install order, and a\n// deliberately broken graph to show how a cycle is reported.\n//\n// It contains no ordering logic of its own — the graph, the sort and the cycle\n// detection all come from the library. Stateless and read-only, so Render is\n// fully deterministic.\npackage toposortdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/toposort/v0\"\n)\n\n// buildGraph is a small, realistic dependency graph: a realm on top of a couple\n// of libraries, themselves on a shared core.\nfunc buildGraph() *toposort.Graph {\n\treturn toposort.FromPairs([][2]string{\n\t\t{\"realm\", \"ui\"},\n\t\t{\"realm\", \"storage\"},\n\t\t{\"ui\", \"markdown\"},\n\t\t{\"storage\", \"avl\"},\n\t\t{\"markdown\", \"strings\"},\n\t\t{\"avl\", \"strings\"},\n\t})\n}\n\n// cyclicGraph is broken on purpose: auth and session need each other.\nfunc cyclicGraph() *toposort.Graph {\n\treturn toposort.FromPairs([][2]string{\n\t\t{\"server\", \"auth\"},\n\t\t{\"auth\", \"session\"},\n\t\t{\"session\", \"auth\"},\n\t})\n}\n\n// Render renders the demo for gnoweb.\n//\n//\tRender(\"\")       / Render(\"/\") -\u003e the build graph, resolved\n//\tRender(\"/cycle\")               -\u003e the broken graph and its report\nfunc Render(path string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Topological Sort\\n\\n\")\n\tb.WriteString(\"Ordering a dependency graph so nothing is built before what it needs, \")\n\tb.WriteString(\"demoing the [`p/moul/x/daily/toposort`](/p/moul/x/daily/toposort/v0) library.\\n\\n\")\n\n\tif parseArg(path) == \"cycle\" {\n\t\treturn b.String() + renderCycle()\n\t}\n\n\tg := buildGraph()\n\tb.WriteString(\"## The graph\\n\\n```\\n\")\n\tb.WriteString(g.String())\n\tb.WriteString(\"```\\n\\n\")\n\n\torder, err := g.Sort()\n\tif err != nil {\n\t\tb.WriteString(\"_Unexpectedly cyclic._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"## Install order\\n\\n\")\n\tfor i, n := range order {\n\t\tb.WriteString(strconv.Itoa(i + 1))\n\t\tb.WriteString(\". `\")\n\t\tb.WriteString(n)\n\t\tb.WriteString(\"`\\n\")\n\t}\n\tb.WriteString(\"\\nTies are broken lexicographically, so this ordering is the \")\n\tb.WriteString(\"*only* one the library will ever produce for this graph.\\n\\n\")\n\tb.WriteString(\"\u003e See [`/cycle`](/r/moul/x/daily/toposortdemo/v0:cycle) for what happens \")\n\tb.WriteString(\"when the graph is not a DAG.\\n\")\n\treturn b.String()\n}\n\n// renderCycle shows the failure mode.\nfunc renderCycle() string {\n\tg := cyclicGraph()\n\tvar b strings.Builder\n\tb.WriteString(\"## A graph with a cycle\\n\\n```\\n\")\n\tb.WriteString(g.String())\n\tb.WriteString(\"```\\n\\n\")\n\n\torder, err := g.Sort()\n\tif err == nil {\n\t\tb.WriteString(\"_Unexpectedly acyclic._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"`Sort` returns an error: **\")\n\tb.WriteString(err.Error())\n\tb.WriteString(\"**\\n\\n\")\n\tb.WriteString(\"Ordered before giving up: \")\n\tif len(order) == 0 {\n\t\tb.WriteString(\"_nothing_\")\n\t} else {\n\t\tb.WriteString(\"`\" + strings.Join(order, \"`, `\") + \"`\")\n\t}\n\tb.WriteString(\"\\n\\nStuck on the cycle: `\")\n\tb.WriteString(strings.Join(g.CycleNodes(), \"`, `\"))\n\tb.WriteString(\"`\\n\\n\u003e The nodes still stuck are named rather than silently dropped, \")\n\tb.WriteString(\"so a caller can report exactly which dependencies are tangled.\\n\")\n\treturn b.String()\n}\n\n// parseArg extracts the first path segment.\nfunc parseArg(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"32407400","gas_fee":"97222ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"2k7Wz7mwi6gW2gEa3KeOCgs8OMChC87aCrKfqy4ZyQVlUxS0pVgr2EGGUQWG7RWArqbCJ74rTASiFBzYjPNPjg=="}],"memo":""},"metadata":{"timestamp":"1790961451"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"trivia","path":"gno.land/r/moul/x/daily/trivia/v0","files":[{"name":"README.md","body":"# Trivia Quiz\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA rotating on-chain multiple-choice trivia quiz. One question is live at a\ntime; anyone can submit a choice via `Answer`. The first correct answer\nscores a point on the lifetime leaderboard and the quiz immediately advances\nto the next question. The starting question is picked deterministically from\nthe deploy-time block height, so repeated deploys don't always open on\nquestion one.\n\nRealm path: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/trivia`\n\n## Example calls\n\n```\n# answer the live question (choice index 0-3, shown in Render)\ngnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/trivia \\\n  -func Answer -args 2 -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid sapphire-1 \u003ckey\u003e\n```\n\nView `Render(\"\")` (or just the realm path in gnoweb) to see the current\nquestion, its lettered choices, the leaderboard, and the total number of\nquestions answered correctly so far.\n\n## Toolchain status\n\n`gno test .` passes locally against a `gnolang/gno` checkout (`GNOROOT` set\nexplicitly — the default env had a stale `GNOROOT` from an unrelated\ncheckout). Local `gno` is `master.3130+bf5b31eda`, newer than sapphire (gno\n0.9); code sticks to the documented sapphire-safe surface (`chain`,\n`chain/runtime`, crossing functions with `cur realm`, `gno.land/p/nt/avl/v0`)\nper the `gno` skill's stdlib reference.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/trivia/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/trivia/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/trivia/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/trivia/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/trivia/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/trivia/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/trivia/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/trivia/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/trivia/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/trivia/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/trivia/v0\"\ngno = \"0.9\"\n"},{"name":"trivia.gno","body":"// Package trivia is a rotating multiple-choice trivia quiz realm.\n//\n// One question is live at a time. Anyone can call Answer with a choice\n// index; the first caller to answer correctly scores a point and the quiz\n// advances to the next question. The starting question is picked\n// deterministically from the block height at deploy time so repeated\n// deploys don't always open on question one.\npackage trivia\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// question is one fixed trivia entry.\ntype question struct {\n\ttext       string\n\tchoices    [4]string\n\tcorrectIdx int\n}\n\n// round holds the mutable state of the currently open question.\ntype round struct {\n\tnumber   int // 1-based round counter, increments forever\n\tqIdx     int // index into questions for this round\n\tattempts int // guesses made against this round so far\n\tsolved   bool\n\twinner   string\n}\n\nvar (\n\tquestions = []question{\n\t\t{\"What is the smallest prime number?\", [4]string{\"0\", \"1\", \"2\", \"3\"}, 2},\n\t\t{\"Which gas does a plant primarily absorb for photosynthesis?\", [4]string{\"Oxygen\", \"Nitrogen\", \"Carbon dioxide\", \"Hydrogen\"}, 2},\n\t\t{\"How many continents are there on Earth?\", [4]string{\"5\", \"6\", \"7\", \"8\"}, 2},\n\t\t{\"In binary, what is 1 + 1?\", [4]string{\"2\", \"10\", \"11\", \"0\"}, 1},\n\t\t{\"What does 'HTTP' stand for?\", [4]string{\"HyperText Transfer Protocol\", \"High Transfer Text Protocol\", \"Home Tool Transfer Protocol\", \"HyperText Transmission Path\"}, 0},\n\t\t{\"Which planet is known as the Red Planet?\", [4]string{\"Venus\", \"Jupiter\", \"Mars\", \"Saturn\"}, 2},\n\t\t{\"What is the time complexity of binary search?\", [4]string{\"O(n)\", \"O(log n)\", \"O(n^2)\", \"O(1)\"}, 1},\n\t\t{\"Who wrote the original Go proverb 'Don't communicate by sharing memory'?\", [4]string{\"Linus Torvalds\", \"Rob Pike\", \"Guido van Rossum\", \"Brendan Eich\"}, 1},\n\t}\n\n\tcurrent *round\n\tscores  = avl.NewTree() // addr(string) -\u003e *int, points across all rounds\n\n\ttotalCorrect int // lifetime count of correctly-answered questions\n)\n\nfunc init() {\n\tcurrent = newRound(1, runtime.ChainHeight())\n}\n\n// newRound builds a fresh round. The question index cycles through the fixed\n// list, offset by a height-derived starting point so consecutive deploys\n// don't all open on the same question.\nfunc newRound(number int, height int64) *round {\n\treturn \u0026round{\n\t\tnumber: number,\n\t\tqIdx:   questionIndex(number, height),\n\t}\n}\n\n// questionIndex maps a round number and a height (entropy source for the\n// starting offset) to a slot in the questions slice. Deterministic and pure\n// so it's easy to unit test.\nfunc questionIndex(number int, height int64) int {\n\tif height \u003c 0 {\n\t\theight = -height\n\t}\n\tn := len(questions)\n\toffset := int(height % int64(n))\n\treturn (offset + number - 1) % n\n}\n\n// Answer submits a choice (0..3) for the current question. Crossing\n// function: caller invokes as Answer(cross(cur), choiceIdx).\nfunc Answer(cur realm, choiceIdx int) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tq := questions[current.qIdx]\n\tif choiceIdx \u003c 0 || choiceIdx \u003e= len(q.choices) {\n\t\tpanic(\"choice must be in 0..\" + strconv.Itoa(len(q.choices)-1))\n\t}\n\tif current.solved {\n\t\tpanic(\"this question is already solved; the next one is already live\")\n\t}\n\n\tcurrent.attempts++\n\tcaller := cur.Previous().Address().String()\n\n\tif choiceIdx != q.correctIdx {\n\t\treturn \"Wrong — try again.\"\n\t}\n\n\tcurrent.solved = true\n\tcurrent.winner = caller\n\taddScore(caller)\n\ttotalCorrect++\n\n\tchain.Emit(\"QuestionSolved\",\n\t\t\"round\", strconv.Itoa(current.number),\n\t\t\"winner\", caller,\n\t\t\"answer\", q.choices[choiceIdx],\n\t)\n\n\tsolvedRound := current.number\n\tcurrent = newRound(solvedRound+1, runtime.ChainHeight())\n\n\treturn \"Correct! The answer was \\\"\" + q.choices[choiceIdx] + \"\\\". A new question is now live.\"\n}\n\n// addScore bumps addr's lifetime point count.\nfunc addScore(addr string) {\n\tif v := scores.Get(addr); v != nil {\n\t\tp := v.(*int)\n\t\t*p++\n\t\treturn\n\t}\n\tone := 1\n\tscores.Set(addr, \u0026one)\n}\n\nfunc scoreOf(addr string) int {\n\tif v := scores.Get(addr); v != nil {\n\t\treturn *(v.(*int))\n\t}\n\treturn 0\n}\n\n// leaderboardEntry is a snapshot row used only for rendering, sorted by\n// score descending.\ntype leaderboardEntry struct {\n\taddr  string\n\tscore int\n}\n\nfunc leaderboard() []leaderboardEntry {\n\tvar rows []leaderboardEntry\n\tscores.Iterate(\"\", \"\", func(addr string, v any) bool {\n\t\trows = append(rows, leaderboardEntry{addr: addr, score: *(v.(*int))})\n\t\treturn false\n\t})\n\t// simple insertion sort by score desc; leaderboards here stay small.\n\tfor i := 1; i \u003c len(rows); i++ {\n\t\tj := i\n\t\tfor j \u003e 0 \u0026\u0026 rows[j-1].score \u003c rows[j].score {\n\t\t\trows[j-1], rows[j] = rows[j], rows[j-1]\n\t\t\tj--\n\t\t}\n\t}\n\treturn rows\n}\n\n// Render produces the gnoweb Markdown view of the quiz.\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Trivia Quiz\\n\\n\")\n\tb.WriteString(\"A rotating on-chain trivia quiz. Call `Answer(choiceIdx)` with 0-3 \")\n\tb.WriteString(\"to answer the current question — first correct answer scores the point \")\n\tb.WriteString(\"and a new question goes live.\\n\\n\")\n\n\tq := questions[current.qIdx]\n\tb.WriteString(\"## Round \" + strconv.Itoa(current.number) + \"\\n\\n\")\n\tb.WriteString(\"**\" + q.text + \"**\\n\\n\")\n\tletters := [4]string{\"A\", \"B\", \"C\", \"D\"}\n\tfor i, c := range q.choices {\n\t\tb.WriteString(\"- **\" + letters[i] + \"** (\" + strconv.Itoa(i) + \"): \" + c + \"\\n\")\n\t}\n\tb.WriteString(\"\\n- Attempts so far this round: \" + strconv.Itoa(current.attempts) + \"\\n\\n\")\n\n\tb.WriteString(\"## Leaderboard\\n\\n\")\n\trows := leaderboard()\n\tif len(rows) == 0 {\n\t\tb.WriteString(\"_No one has scored yet — be the first!_\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| Player | Points |\\n|---|---|\\n\")\n\t\tfor _, r := range rows {\n\t\t\tb.WriteString(\"| `\" + r.addr + \"` | \" + strconv.Itoa(r.score) + \" |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"Total questions answered correctly across all rounds: \" + strconv.Itoa(totalCorrect) + \"\\n\\n\")\n\n\tb.WriteString(\"## How to play\\n\\n\")\n\tb.WriteString(\"```\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/trivia \\\\\\n\")\n\tb.WriteString(\"  -func Answer -args \u003c0|1|2|3\u003e ...\\n\")\n\tb.WriteString(\"```\\n\")\n\n\treturn b.String()\n}\n"},{"name":"trivia_test.gno","body":"package trivia\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// resetQuiz re-initializes package globals so each test starts clean; init()\n// only runs once for the whole test binary.\nfunc resetQuiz(height int64) {\n\tcurrent = newRound(1, height)\n\tscores = avl.NewTree()\n\ttotalCorrect = 0\n}\n\nfunc TestQuestionIndexDeterministic(t *testing.T) {\n\tn := len(questions)\n\tfor _, h := range []int64{0, 1, 42, 12345, -7} {\n\t\tidx := questionIndex(1, h)\n\t\tif idx \u003c 0 || idx \u003e= n {\n\t\t\tt.Errorf(\"questionIndex(1, %d) = %d, want in 0..%d\", h, idx, n-1)\n\t\t}\n\t\tif again := questionIndex(1, h); again != idx {\n\t\t\tt.Errorf(\"questionIndex(1, %d) non-deterministic: %d != %d\", h, again, idx)\n\t\t}\n\t}\n\t// consecutive rounds should walk sequentially through the list\n\tfirst := questionIndex(1, 0)\n\tsecond := questionIndex(2, 0)\n\tif second != (first+1)%n {\n\t\tt.Errorf(\"round 2 index = %d, want %d\", second, (first+1)%n)\n\t}\n}\n\n// TestAnswerCorrectAdvances exercises the crossing Answer function, so it\n// takes cur realm and calls through cross(cur).\nfunc TestAnswerCorrectAdvances(cur realm, t *testing.T) {\n\tresetQuiz(10)\n\tq := questions[current.qIdx]\n\tprevRound := current.number\n\n\t// wrong answer first: pick any index that isn't correct\n\twrong := (q.correctIdx + 1) % len(q.choices)\n\tgot := Answer(cross(cur), wrong)\n\tif got != \"Wrong — try again.\" {\n\t\tt.Errorf(\"Answer(wrong) = %q, want wrong message\", got)\n\t}\n\tif current.solved {\n\t\tt.Error(\"round should not be solved after a wrong answer\")\n\t}\n\n\tgot = Answer(cross(cur), q.correctIdx)\n\tif !strings.HasPrefix(got, \"Correct!\") {\n\t\tt.Errorf(\"Answer(correct) = %q, want it to start with Correct!\", got)\n\t}\n\tif current.number != prevRound+1 {\n\t\tt.Errorf(\"round number = %d, want %d\", current.number, prevRound+1)\n\t}\n\tif totalCorrect != 1 {\n\t\tt.Errorf(\"totalCorrect = %d, want 1\", totalCorrect)\n\t}\n\tif len(leaderboard()) != 1 {\n\t\tt.Errorf(\"leaderboard len = %d, want 1\", len(leaderboard()))\n\t}\n}\n\n// TestRenderContainsState is a plain read — no cur.\nfunc TestRenderContainsState(t *testing.T) {\n\tresetQuiz(5)\n\tout := Render(\"\")\n\tfor _, want := range []string{\"Trivia Quiz\", \"Round\", \"Leaderboard\"} {\n\t\tif !strings.Contains(out, want) {\n\t\t\tt.Errorf(\"Render() missing %q\", want)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"42357600","gas_fee":"127072ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"lLPxJqVGJQYnyEBBUp/wmI079FuGmTeea0gWLRFzJLwLV5jPoFQpsadqUvYI1FcMtDANUECW5ySGMRmyowX+gg=="}],"memo":""},"metadata":{"timestamp":"1790961452"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"urlshort","path":"gno.land/r/moul/x/daily/urlshort/v1","files":[{"name":"README.md","body":"# URL Shortener\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn on-chain alias registry for gno.land. Each caller can\nregister `alias -\u003e url` mappings they own: an alias is claimed on a first-come\nbasis, only its owner may update or remove it, and every resolution through\n`Render(\"/\u003calias\u003e\")` bumps a per-alias click counter. Aliases must be non-empty\nand alphanumeric.\n\n**Realm path:** `gno.land/r/moul/x/daily/urlshort/v1`\n\n## Example calls\n\n```\n# Register (or update your own) alias -\u003e url\nShorten(\"gno\", \"https://gno.land\", \"the chain\")\n\n# Update the target (must be the same owner)\nShorten(\"gno\", \"https://docs.gno.land\", \"now the docs\")\n\n# Remove an alias you own\nRemove(\"gno\")\n```\n\n## Render paths\n\n- `/` — lists every alias with owner and click count.\n- `/\u003calias\u003e` — shows the target url, owner, note, and click count (and counts the click).\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/urlshort) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `short` helper.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/urlshort/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/urlshort/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/urlshort/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/urlshort/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/urlshort/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/urlshort/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/urlshort/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/urlshort/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/urlshort/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/urlshort/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/urlshort/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"urlshort.gno","body":"// Package urlshort is a simple on-chain URL alias registry.\n//\n// Callers register an `alias -\u003e url` mapping they own. An alias can only be\n// claimed once; the owner may later update the target URL, but nobody else can\n// overwrite an alias they do not own. A per-alias click counter is bumped every\n// time the alias is resolved through Render(\"/\u003calias\u003e\").\npackage urlshort\n\nimport (\n\t\"strings\"\n\n\t\"chain\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/urlshort/v1\"\n\n// entry is the persisted record for a single alias.\ntype entry struct {\n\turl    string\n\towner  address\n\tnote   string\n\tclicks int\n}\n\n// aliases maps alias (string) -\u003e *entry, kept in an avl.Tree for deterministic\n// iteration order in Render.\nvar aliases avl.Tree\n\n// isAlphanumeric reports whether s is non-empty and made only of [0-9A-Za-z].\nfunc isAlphanumeric(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\tfor _, c := range s {\n\t\tswitch {\n\t\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z':\n\t\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'Z':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Shorten registers `alias -\u003e url` owned by the caller.\n//\n// Rules:\n//   - alias must be non-empty and alphanumeric;\n//   - url must be non-empty;\n//   - if the alias is unclaimed, it is created owned by the caller;\n//   - if it is already claimed by the caller, the url/note are updated;\n//   - if it is claimed by someone else, the call aborts.\nfunc Shorten(cur realm, alias string, url string, note string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"urlshort: spoofed realm\")\n\t}\n\tif !isAlphanumeric(alias) {\n\t\tpanic(\"alias must be non-empty and alphanumeric\")\n\t}\n\tif url == \"\" {\n\t\tpanic(\"url must be non-empty\")\n\t}\n\t// The URL is rendered as an \u003cautolink\u003e, so it is checked here rather than\n\t// escaped there: http(s) only, and nothing that could close the brackets.\n\tif !safeURL(url) {\n\t\tpanic(\"url must be http:// or https:// with no spaces or angle brackets\")\n\t}\n\n\tcaller := cur.Previous().Address()\n\n\tif v := aliases.Get(alias); v != nil {\n\t\te := v.(*entry)\n\t\tif e.owner != caller {\n\t\t\tpanic(\"alias already taken by another owner\")\n\t\t}\n\t\te.url = url\n\t\te.note = note\n\t\tchain.Emit(\"AliasUpdated\", \"alias\", alias, \"owner\", caller.String())\n\t\treturn\n\t}\n\n\te := \u0026entry{url: url, owner: caller, note: note, clicks: 0}\n\taliases.Set(alias, e)\n\tchain.Emit(\"AliasCreated\", \"alias\", alias, \"owner\", caller.String())\n}\n\n// Remove deletes an alias owned by the caller. Aborts if the alias does not\n// exist or the caller is not the owner.\nfunc Remove(cur realm, alias string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"urlshort: spoofed realm\")\n\t}\n\tv := aliases.Get(alias)\n\tif v == nil {\n\t\tpanic(\"alias not found\")\n\t}\n\te := v.(*entry)\n\tcaller := cur.Previous().Address()\n\tif e.owner != caller {\n\t\tpanic(\"only the owner can remove an alias\")\n\t}\n\taliases.Remove(alias)\n\tchain.Emit(\"AliasRemoved\", \"alias\", alias, \"owner\", caller.String())\n}\n\n// Lookup returns the target url for an alias and whether it exists. It is a\n// read-only helper and does NOT increment the click counter.\nfunc Lookup(alias string) (string, bool) {\n\tv := aliases.Get(alias)\n\tif v == nil {\n\t\treturn \"\", false\n\t}\n\treturn v.(*entry).url, true\n}\n\n// Render renders Markdown. The root path lists every alias; \"/\u003calias\u003e\" shows a\n// single alias detail and bumps its click counter.\nfunc Render(path string) string {\n\tif path == \"\" || path == \"/\" {\n\t\treturn renderIndex()\n\t}\n\n\talias := strings.TrimPrefix(path, \"/\")\n\tv := aliases.Get(alias)\n\tif v == nil {\n\t\treturn \"# URL Shortener\\n\\nNo alias named \" + md.InlineCode(alias) + \".\\n\\n[← all aliases](\" + selfPath + \")\\n\"\n\t}\n\n\te := v.(*entry)\n\te.clicks++\n\n\tvar b strings.Builder\n\tb.WriteString(\"# 🔗 \" + alias + \"\\n\\n\")\n\tb.WriteString(\"**Target:** \u003c\" + e.url + \"\u003e\\n\\n\")\n\tb.WriteString(\"**Owner:** \" + e.owner.String() + \"\\n\\n\")\n\tif e.note != \"\" {\n\t\tb.WriteString(\"**Note:** \" + ui.Inline(e.note) + \"\\n\\n\")\n\t}\n\tb.WriteString(\"**Clicks:** \" + itoa(e.clicks) + \"\\n\\n\")\n\tb.WriteString(\"[← all aliases](\" + selfPath + \")\\n\")\n\treturn b.String()\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 🔗 URL Shortener\\n\\n\")\n\n\tif aliases.Size() == 0 {\n\t\tb.WriteString(\"_No aliases registered yet._\\n\\n\")\n\t\tb.WriteString(\"Call `Shorten(alias, url, note)` to register one.\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| Alias | Target | Owner | Clicks |\\n\")\n\tb.WriteString(\"|-------|--------|-------|--------|\\n\")\n\taliases.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\te := value.(*entry)\n\t\tb.WriteString(\"| [\" + key + \"](\" + selfPath + \":\" + key + \") | \u003c\" + e.url + \"\u003e | \" +\n\t\t\tui.Addr(e.owner) + \" | \" + itoa(e.clicks) + \" |\\n\")\n\t\treturn false\n\t})\n\tb.WriteString(\"\\nTotal aliases: \" + itoa(aliases.Size()) + \"\\n\")\n\treturn b.String()\n}\n\n// itoa converts a non-negative int to its decimal string without importing\n// strconv (kept minimal \u0026 deterministic).\nfunc itoa(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\tneg := n \u003c 0\n\tif neg {\n\t\tn = -n\n\t}\n\tvar buf [20]byte\n\ti := len(buf)\n\tfor n \u003e 0 {\n\t\ti--\n\t\tbuf[i] = byte('0' + n%10)\n\t\tn /= 10\n\t}\n\tif neg {\n\t\ti--\n\t\tbuf[i] = '-'\n\t}\n\treturn string(buf[i:])\n}\n\n// safeURL reports whether u can be written into a markdown autolink unescaped.\nfunc safeURL(u string) bool {\n\tif !strings.HasPrefix(u, \"https://\") \u0026\u0026 !strings.HasPrefix(u, \"http://\") {\n\t\treturn false\n\t}\n\treturn !strings.ContainsAny(u, \" \\t\\r\\n\u003c\u003e`\\\\\")\n}\n"},{"name":"urlshort_test.gno","body":"package urlshort\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestIsAlphanumeric(t *testing.T) {\n\tcases := []struct {\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"\", false},\n\t\t{\"abc\", true},\n\t\t{\"ABC123\", true},\n\t\t{\"a b\", false},\n\t\t{\"a-b\", false},\n\t\t{\"under_score\", false},\n\t\t{\"9\", true},\n\t}\n\tfor _, c := range cases {\n\t\tif got := isAlphanumeric(c.in); got != c.want {\n\t\t\tt.Errorf(\"isAlphanumeric(%q) = %v, want %v\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestItoa(t *testing.T) {\n\tcases := []struct {\n\t\tin   int\n\t\twant string\n\t}{\n\t\t{0, \"0\"},\n\t\t{7, \"7\"},\n\t\t{42, \"42\"},\n\t\t{1000, \"1000\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := itoa(c.in); got != c.want {\n\t\t\tt.Errorf(\"itoa(%d) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestShortenAndRender(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tShorten(cross(cur), \"gno\", \"https://gno.land\", \"the chain\")\n\n\turl, ok := Lookup(\"gno\")\n\tuassert.True(t, ok, \"alias should exist\")\n\tuassert.Equal(t, \"https://gno.land\", url)\n\n\t// Detail render bumps the click counter.\n\tout := Render(\"/gno\")\n\tuassert.True(t, strings.Contains(out, \"https://gno.land\"), \"detail shows url\")\n\tuassert.True(t, strings.Contains(out, \"Clicks:** 1\"), \"click counted\")\n\n\t// Index lists the alias.\n\tidx := Render(\"/\")\n\tuassert.True(t, strings.Contains(idx, \"[gno](/r/moul/x/daily/urlshort/v1:gno)\"), \"index lists alias\")\n}\n\nfunc TestShortenOwnershipRules(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice2\")\n\tbob := testutils.TestAddress(\"bob2\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tShorten(cross(cur), \"mine\", \"https://a.example\", \"\")\n\n\t// Bob cannot overwrite alice's alias.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur, \"alias already taken by another owner\", func() {\n\t\tShorten(cross(cur), \"mine\", \"https://b.example\", \"\")\n\t})\n\n\t// Alice can update her own.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tShorten(cross(cur), \"mine\", \"https://a2.example\", \"updated\")\n\turl, _ := Lookup(\"mine\")\n\tuassert.Equal(t, \"https://a2.example\", url)\n\n\t// Invalid alias aborts.\n\tuassert.AbortsWithMessage(t, cur, \"alias must be non-empty and alphanumeric\", func() {\n\t\tShorten(cross(cur), \"bad alias\", \"https://x.example\", \"\")\n\t})\n\n\t// Empty url aborts.\n\tuassert.AbortsWithMessage(t, cur, \"url must be non-empty\", func() {\n\t\tShorten(cross(cur), \"okalias\", \"\", \"\")\n\t})\n}\n\nfunc TestRemoveRules(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice3\")\n\tbob := testutils.TestAddress(\"bob3\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tShorten(cross(cur), \"rm\", \"https://rm.example\", \"\")\n\n\t// Bob cannot remove alice's alias.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsWithMessage(t, cur, \"only the owner can remove an alias\", func() {\n\t\tRemove(cross(cur), \"rm\")\n\t})\n\n\t// Alice removes her own.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRemove(cross(cur), \"rm\")\n\t_, ok := Lookup(\"rm\")\n\tuassert.False(t, ok, \"alias should be gone\")\n}\n"},{"name":"zz_escape_test.gno","body":"package urlshort\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The note is escaped, and a target that could close its \u003cautolink\u003e, or is\n// not http(s), is refused when it is written.\nfunc TestNoteIsEscapedAndTargetChecked(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"escaper\")))\n\tShorten(cross(cur), \"esc\", \"https://ok.example\", \"[claim](https://evil.example)\")\n\tpage := Render(\"esc\")\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n\tuassert.AbortsContains(t, cur, \"url must be http\", func() { Shorten(cross(cur), \"esc2\", \"https://a.example\u003e [evil](https://b.example)\", \"\") })\n\tuassert.AbortsContains(t, cur, \"url must be http\", func() { Shorten(cross(cur), \"esc3\", \"javascript:alert(1)\", \"\") })\n}\n\n// A path that names nothing is echoed back on the not-found page. It is the\n// visitor's text, so a backtick in it must not close a code span and let a\n// link through.\nfunc TestNotFoundPathIsEscaped(t *testing.T) {\n\tout := Render(\"x` [claim](https://evil.example) `\")\n\t// Still there, but inside a span md.InlineCode widened past its backticks.\n\tuassert.True(t, strings.Contains(out, md.InlineCode(\"x` [claim](https://evil.example) `\")), out)\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"46967400","gas_fee":"140902ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"fpcYvWCywfqTWJ6DyVY8bNMCDbKWK1EYoyWt9JQ/iTQjqEGjYyK7a46yhA0xfmvQPodffX2eBXQkJb56T2zYeQ=="}],"memo":""},"metadata":{"timestamp":"1790961453"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"vault","path":"gno.land/r/moul/x/daily/vault/v1","files":[{"name":"README.md","body":"# Key-Value Vault\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA per-address key-value store on gno.land. Each caller gets their own private\nnamespace; only the owner can set or delete their own entries. The root render\nlists every address that owns a vault with its entry count, and the `/\u003caddress\u003e`\npath renders that address's keys and values in a table.\n\n**Realm path:** `gno.land/r/moul/x/daily/vault/v1`\n\n## Example calls\n\n```\n# Store a value in your namespace\nSet(\"greeting\", \"hello\")\n\n# Overwrite it\nSet(\"greeting\", \"hi there\")\n\n# Remove it (aborts if the key doesn't exist)\nDelete(\"greeting\")\n```\n\n## Render\n\n- `Render(\"\")` — table of all addresses with a vault and their entry counts.\n- `Render(\"/g1abc...\")` — table of that address's keys and values.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/vault/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vault/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/vault/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vault/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/vault/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vault/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/vault/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/vault/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/vault/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/vault/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/vault/v1\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"vault.gno","body":"package vault\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/vault/v1\"\n\n// vaults maps address string -\u003e *avl.Tree (key string -\u003e value string).\nvar vaults avl.Tree\n\n// The bounds on what a caller may store. Anyone may open a vault, the root\n// page lists every vault, and a vault's page lists every entry.\nconst (\n\tMaxVaults   = 1000\n\tMaxEntries  = 100 // per vault\n\tMaxKeyLen   = 64\n\tMaxValueLen = 512\n)\n\n// vaultFor returns the caller's namespace tree, creating it if needed.\nfunc vaultFor(owner address) *avl.Tree {\n\tk := owner.String()\n\tif v := vaults.Get(k); v != nil {\n\t\treturn v.(*avl.Tree)\n\t}\n\tif vaults.Size() \u003e= MaxVaults {\n\t\tpanic(\"vault is full at \" + strconv.Itoa(MaxVaults) + \" vaults\")\n\t}\n\tt := \u0026avl.Tree{}\n\tvaults.Set(k, t)\n\treturn t\n}\n\n// Set stores value under key in the caller's own namespace.\nfunc Set(cur realm, key string, value string) {\n\twho := caller(cur)\n\tif key == \"\" {\n\t\tpanic(\"key must not be empty\")\n\t}\n\tif len(key) \u003e MaxKeyLen || len(value) \u003e MaxValueLen {\n\t\tpanic(\"key or value too long\")\n\t}\n\tt := vaultFor(who)\n\tif !t.Has(key) \u0026\u0026 t.Size() \u003e= MaxEntries {\n\t\tpanic(\"a vault holds at most \" + strconv.Itoa(MaxEntries) + \" entries\")\n\t}\n\tt.Set(key, value)\n\tchain.Emit(\"VaultSet\", \"owner\", who.String(), \"key\", key)\n}\n\n// Delete removes key from the caller's own namespace.\nfunc Delete(cur realm, key string) {\n\twho := caller(cur)\n\tk := who.String()\n\tv := vaults.Get(k)\n\tif v == nil {\n\t\tpanic(\"no vault for caller\")\n\t}\n\tt := v.(*avl.Tree)\n\tif _, removed := t.Remove(key); !removed {\n\t\tpanic(\"key not found\")\n\t}\n\tif t.Size() == 0 {\n\t\tvaults.Remove(k)\n\t}\n\tchain.Emit(\"VaultDelete\", \"owner\", who.String(), \"key\", key)\n}\n\n// Render shows all vaults (root) or a single address's entries (\"/\u003caddress\u003e\").\nfunc Render(path string) string {\n\tp := strings.TrimPrefix(path, \"/\")\n\tif p == \"\" {\n\t\treturn renderRoot()\n\t}\n\treturn renderAddress(p)\n}\n\nfunc renderRoot() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Key-Value Vault\\n\\n\")\n\tb.WriteString(\"A per-address key-value store. Each caller owns their own namespace; only the owner can mutate their entries.\\n\\n\")\n\tif vaults.Size() == 0 {\n\t\tb.WriteString(\"_No vaults yet. Call `Set(cur, key, value)` to create one._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"## Vaults\\n\\n\")\n\tb.WriteString(\"| Address | Entries |\\n\")\n\tb.WriteString(\"|---|---|\\n\")\n\tvaults.Iterate(\"\", \"\", func(k string, v interface{}) bool {\n\t\tt := v.(*avl.Tree)\n\t\tb.WriteString(\"| [\")\n\t\tb.WriteString(k)\n\t\tb.WriteString(\"](\" + selfPath + \":\")\n\t\t// link back into this realm's render for the address subpage\n\t\tb.WriteString(k)\n\t\tb.WriteString(\") | \")\n\t\tb.WriteString(strconv.Itoa(t.Size()))\n\t\tb.WriteString(\" |\\n\")\n\t\treturn false\n\t})\n\tb.WriteString(\"\\nView an address's entries at path `/\u003caddress\u003e`.\\n\")\n\treturn b.String()\n}\n\nfunc renderAddress(addr string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Vault: \")\n\tb.WriteString(ui.Inline(addr))\n\tb.WriteString(\"\\n\\n\")\n\tv := vaults.Get(addr)\n\tif v == nil {\n\t\tb.WriteString(\"_No vault for this address._\\n\")\n\t\treturn b.String()\n\t}\n\tt := v.(*avl.Tree)\n\tb.WriteString(\"| Key | Value |\\n\")\n\tb.WriteString(\"|---|---|\\n\")\n\tt.Iterate(\"\", \"\", func(k string, val interface{}) bool {\n\t\tb.WriteString(\"| \")\n\t\tb.WriteString(ui.Cell(k))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(ui.Cell(val.(string)))\n\t\tb.WriteString(\" |\\n\")\n\t\treturn false\n\t})\n\tb.WriteString(\"\\nTotal entries: \")\n\tb.WriteString(strconv.Itoa(t.Size()))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\n// caller is the address that crossed into this realm, after checking that the\n// realm token is this frame's own.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"vault: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"vault_test.gno","body":"package vault\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestSetAndRender(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tSet(cross(cur), \"greeting\", \"hello\")\n\tSet(cross(cur), \"lang\", \"gno\")\n\n\tout := renderAddress(alice.String())\n\tuassert.True(t, strings.Contains(out, \"greeting\"), \"should contain key greeting\")\n\tuassert.True(t, strings.Contains(out, \"hello\"), \"should contain value hello\")\n\tuassert.True(t, strings.Contains(out, \"Total entries: 2\"), \"should count 2 entries\")\n\n\troot := Render(\"\")\n\tuassert.True(t, strings.Contains(root, alice.String()), \"root should list alice\")\n}\n\nfunc TestDeleteAndIsolation(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice2\")\n\tbob := testutils.TestAddress(\"bob2\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSet(cross(cur), \"shared\", \"alice-value\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSet(cross(cur), \"shared\", \"bob-value\")\n\n\t// Namespaces are isolated: same key, different owners.\n\tav := vaults.Get(alice.String())\n\tbv := vaults.Get(bob.String())\n\tavVal := av.(*avl.Tree).Get(\"shared\")\n\tbvVal := bv.(*avl.Tree).Get(\"shared\")\n\tuassert.Equal(t, \"alice-value\", avVal.(string))\n\tuassert.Equal(t, \"bob-value\", bvVal.(string))\n\n\t// Bob deletes his own key; alice's remains.\n\tDelete(cross(cur), \"shared\")\n\tbobStill := vaults.Has(bob.String())\n\tuassert.False(t, bobStill, \"bob's vault should be gone after last key removed\")\n\taliceStill := vaults.Has(alice.String())\n\tuassert.True(t, aliceStill, \"alice's vault should remain\")\n\n\t// Deleting a missing key aborts.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsWithMessage(t, cur, \"key not found\", func() {\n\t\tDelete(cross(cur), \"nope\")\n\t})\n}\n"},{"name":"zz_bounds_test.gno","body":"package vault\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A vault holds a bounded number of entries of bounded size; overwriting an\n// existing key is always allowed.\nfunc TestVaultIsBounded(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bounded\")))\n\tuassert.AbortsContains(t, cur, \"too long\", func() { Set(cross(cur), strings.Repeat(\"k\", MaxKeyLen+1), \"v\") })\n\tfor i := 0; i \u003c MaxEntries; i++ {\n\t\tSet(cross(cur), \"k\"+strconv.Itoa(i), \"v\")\n\t}\n\tuassert.AbortsContains(t, cur, \"at most\", func() { Set(cross(cur), \"one-more\", \"v\") })\n\tSet(cross(cur), \"k0\", \"overwritten\")\n}\n\n// The vault count is bounded globally, not just entries per vault.\nfunc TestVaultCountIsBounded(cur realm, t *testing.T) {\n\tvar added []string\n\tfor i := 0; vaults.Size() \u003c MaxVaults; i++ {\n\t\tk := testutils.TestAddress(\"v\" + strconv.Itoa(i)).String()\n\t\tif vaults.Get(k) == nil {\n\t\t\tvaults.Set(k, \u0026avl.Tree{})\n\t\t\tadded = append(added, k)\n\t\t}\n\t}\n\tdefer func() {\n\t\tfor _, k := range added {\n\t\t\tvaults.Remove(k)\n\t\t}\n\t}()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"latecomer\")))\n\tuassert.AbortsContains(t, cur, \"vault is full\", func() { Set(cross(cur), \"k\", \"v\") })\n}\n"},{"name":"zz_escape_test.gno","body":"package vault\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A key and a value are the owner's text, written into table cells: a pipe\n// must not open a column and a link must not go live.\nfunc TestKeysAndValuesAreTableSafe(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"escaper\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tSet(cross(cur), \"k | [claim](https://evil.example)\", \"[claim](https://evil.example)\")\n\tpage := Render(who.String())\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n\tuassert.False(t, strings.Contains(page, \"| k | \"), page)\n}\n\n// A path that names nothing is echoed back on the not-found page. It is the\n// visitor's text, so a backtick in it must not close a code span and let a\n// link through.\nfunc TestNotFoundPathIsEscaped(t *testing.T) {\n\tout := Render(\"x` [claim](https://evil.example) `\")\n\tuassert.False(t, strings.Contains(out, \"[claim](https://evil.example)\"), out)\n}\n"},{"name":"zz_links_test.gno","body":"package vault\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// The index links each vault to this realm's own page. It once linked to\n// the malformed gno.land/r:\u003caddress\u003e.\nfunc TestIndexLinksNameThisRealm(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"linker\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tSet(cross(cur), \"k\", \"v\")\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"](/r/moul/x/daily/vault/v1:\"+who.String()+\")\"), out)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"41159000","gas_fee":"123477ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"5jqTPwhMgF+eZMgH7bXX4XNz9+wQLc6OZ5K/ZqLiCXMAyag8dh8CvZZc3XpsU6Gt7UUDIice5/R67kD+uCvz4w=="}],"memo":""},"metadata":{"timestamp":"1790961453"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"LmvXVgJ0pzfeZr4YZkzkMz5sYQ3UYdzgDlJHB7XBk34ar1RQ+OG2JbicdSxll1IDHEcmsKs52tHTENCy5ZwKYg=="}],"memo":""},"metadata":{"timestamp":"1790961454"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wordle","path":"gno.land/r/moul/x/daily/wordle/v0","files":[{"name":"README.md","body":"# Daily Word Puzzle\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA Wordle-like realm for gno.land (gno 0.9 / sapphire). Every \"day\" — a span of\nblocks derived deterministically from the block height — the realm picks one\nsecret 5-letter word from a built-in 15-word dictionary. Players submit guesses\nand get per-letter emoji feedback (🟩 correct spot, 🟨 wrong spot, ⬜ absent),\nwith up to 6 attempts per day and a per-caller board rendered as Markdown.\n\n## Realm path\n\n`gno.land/r/REPLACE_ADDR/wordle`\n\n## How it works\n\n- The day index is `ChainHeight() / blocksPerDay`; the secret word is\n  `words[day % len(words)]` — fully deterministic, no randomness.\n- `Guess(word)` is a crossing function (`Guess(cross(cur), word)`) that records\n  a guess for the caller against today's word. Boards reset automatically when a\n  new day rolls over.\n- `Render(path)` shows the calling viewer's board, attempts left, win/lose state,\n  and the rules legend.\n\n## Example calls\n\n```sh\n# submit a guess (crossing tx)\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/REPLACE_ADDR/wordle\" \\\n  -func Guess -args \"crane\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 \u003ckeyname\u003e\n```\n\nView the board in gnoweb at:\n\n```\nhttps://gno.land/r/REPLACE_ADDR/wordle\n```\n\n## Test\n\n```sh\ngno test .\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/wordle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wordle/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/wordle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wordle/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/wordle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wordle/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/wordle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/wordle/v0)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/wordle/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package wordle\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # 🟩 Daily Word Puzzle\n\t//\n\t// A Wordle-like game. Everyone gets the same secret 5-letter word each \"day\" (a span of blocks). You have 6 attempts.\n\t//\n\t// **Day #0**\n\t//\n\t// _No guesses yet today._\n\t//\n\t// ## Rules\n\t//\n\t// - Guess the 5-letter word in 6 tries: `Guess(\"crane\")`.\n\t// - 🟩 correct letter, correct spot.\n\t// - 🟨 correct letter, wrong spot.\n\t// - ⬜ letter not in the word.\n\t// - The word changes every day (deterministic from block height).\n}\n"},{"name":"wordle.gno","body":"// Package wordle is a daily five-letter word puzzle realm for gno.land.\n//\n// The day's secret word is picked deterministically from the current block\n// height (a \"day index\"), so every player faces the same word for the same\n// span of blocks. Players submit guesses with Guess; each guess is scored\n// letter-by-letter with emoji feedback (🟩 correct spot, 🟨 wrong spot,\n// ⬜ absent). Render shows the caller's board, attempts left, and rules.\npackage wordle\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strings\"\n)\n\n// maxAttempts is the number of guesses a player gets per day.\nconst maxAttempts = 6\n\n// wordLen is the fixed length of every word / guess.\nconst wordLen = 5\n\n// blocksPerDay controls how many blocks share the same secret word. Testnet\n// blocks are fast, so this is a pragmatic \"day\" for a demo puzzle rather than\n// a wall-clock day. Deterministic: derived only from block height.\nconst blocksPerDay = 17280\n\n// words is the built-in dictionary of candidate secret words. All entries are\n// exactly wordLen lowercase letters.\nvar words = []string{\n\t\"crane\",\n\t\"slate\",\n\t\"pride\",\n\t\"ghost\",\n\t\"lunar\",\n\t\"mango\",\n\t\"vivid\",\n\t\"quilt\",\n\t\"brave\",\n\t\"flame\",\n\t\"storm\",\n\t\"pearl\",\n\t\"trout\",\n\t\"zebra\",\n\t\"cabin\",\n}\n\n// board holds one player's guesses for a given day.\ntype board struct {\n\tday     int64\n\tguesses []string // raw lowercase guessed words, in order\n\twon     bool\n}\n\n// players maps a caller address string to that player's current board.\n// A plain map is fine here: keys are addresses, iteration order is never\n// used for rendering (we only ever look up the caller's own board).\nvar players = map[string]*board{}\n\n// dayIndex returns the deterministic day index for a given block height.\nfunc dayIndex(height int64) int64 {\n\tif height \u003c 0 {\n\t\theight = 0\n\t}\n\treturn height / blocksPerDay\n}\n\n// wordForDay returns the secret word for the given day index. Deterministic:\n// a pure function of the day index and the built-in dictionary.\nfunc wordForDay(day int64) string {\n\tn := int64(len(words))\n\tidx := day % n\n\tif idx \u003c 0 {\n\t\tidx += n\n\t}\n\treturn words[idx]\n}\n\n// currentDay returns today's day index from the chain height.\nfunc currentDay() int64 {\n\treturn dayIndex(runtime.ChainHeight())\n}\n\n// score compares a guess against the secret and returns wordLen emoji tiles:\n// 🟩 right letter right spot, 🟨 right letter wrong spot, ⬜ letter absent.\n// Standard Wordle two-pass scoring so duplicate letters are handled correctly.\nfunc score(guess, secret string) string {\n\tg := []rune(guess)\n\ts := []rune(secret)\n\n\ttiles := make([]string, wordLen)\n\t// counts of each secret letter still available to match as 🟨.\n\tcounts := map[rune]int{}\n\n\t// First pass: greens.\n\tfor i := 0; i \u003c wordLen; i++ {\n\t\tif g[i] == s[i] {\n\t\t\ttiles[i] = \"🟩\"\n\t\t} else {\n\t\t\tcounts[s[i]]++\n\t\t}\n\t}\n\t// Second pass: yellows / greys.\n\tfor i := 0; i \u003c wordLen; i++ {\n\t\tif tiles[i] == \"🟩\" {\n\t\t\tcontinue\n\t\t}\n\t\tif counts[g[i]] \u003e 0 {\n\t\t\ttiles[i] = \"🟨\"\n\t\t\tcounts[g[i]]--\n\t\t} else {\n\t\t\ttiles[i] = \"⬜\"\n\t\t}\n\t}\n\treturn strings.Join(tiles, \"\")\n}\n\n// isFiveLetters reports whether w is exactly wordLen ASCII lowercase letters.\nfunc isFiveLetters(w string) bool {\n\tif len(w) != wordLen {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(w); i++ {\n\t\tc := w[i]\n\t\tif c \u003c 'a' || c \u003e 'z' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Guess records a five-letter guess for the caller against today's word.\n//\n// It is a crossing (state-mutating) function: callers invoke it as\n// Guess(cross(cur), \"crane\"). Identity is taken from the live crossing frame\n// after the IsCurrent authentication check.\nfunc Guess(cur realm, word string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tcaller := cur.Previous().Address().String()\n\n\tword = strings.ToLower(strings.TrimSpace(word))\n\tif !isFiveLetters(word) {\n\t\tpanic(\"guess must be exactly 5 lowercase letters a-z\")\n\t}\n\n\tday := currentDay()\n\tb := players[caller]\n\tif b == nil || b.day != day {\n\t\t// New player, or a new day rolled over: reset the board.\n\t\tb = \u0026board{day: day}\n\t\tplayers[caller] = b\n\t}\n\n\tif b.won {\n\t\tpanic(\"you already solved today's word\")\n\t}\n\tif len(b.guesses) \u003e= maxAttempts {\n\t\tpanic(\"no attempts left today\")\n\t}\n\n\tb.guesses = append(b.guesses, word)\n\tif word == wordForDay(day) {\n\t\tb.won = true\n\t}\n}\n\n// Render returns the caller's board as Markdown. It is NOT a crossing function\n// (no cur realm parameter). It reads the viewer via the stack-walking\n// unsafe.PreviousRealm(); an unknown viewer simply sees an empty board.\nfunc Render(path string) string {\n\tviewer := unsafe.PreviousRealm().Address().String()\n\tday := currentDay()\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"# 🟩 Daily Word Puzzle\\n\\n\")\n\tsb.WriteString(\"A Wordle-like game. Everyone gets the same secret 5-letter word each \")\n\tsb.WriteString(\"\\\"day\\\" (a span of blocks). You have \")\n\tsb.WriteString(itoa(maxAttempts))\n\tsb.WriteString(\" attempts.\\n\\n\")\n\n\tsb.WriteString(\"**Day #\")\n\tsb.WriteString(i64toa(day))\n\tsb.WriteString(\"**\\n\\n\")\n\n\tb := players[viewer]\n\tif b == nil || b.day != day {\n\t\tsb.WriteString(\"_No guesses yet today._\\n\\n\")\n\t\twriteRules(\u0026sb)\n\t\treturn sb.String()\n\t}\n\n\tsecret := wordForDay(day)\n\tsb.WriteString(\"## Your board\\n\\n\")\n\tfor _, g := range b.guesses {\n\t\tsb.WriteString(score(g, secret))\n\t\tsb.WriteString(\"  `\")\n\t\tsb.WriteString(strings.ToUpper(g))\n\t\tsb.WriteString(\"`\\n\\n\")\n\t}\n\n\tleft := maxAttempts - len(b.guesses)\n\tswitch {\n\tcase b.won:\n\t\tsb.WriteString(\"🎉 **You solved it!** Come back next day for a new word.\\n\\n\")\n\tcase left \u003c= 0:\n\t\tsb.WriteString(\"💀 **Out of attempts.** The word was `\")\n\t\tsb.WriteString(strings.ToUpper(secret))\n\t\tsb.WriteString(\"`. Try again next day.\\n\\n\")\n\tdefault:\n\t\tsb.WriteString(\"**Attempts left:** \")\n\t\tsb.WriteString(itoa(left))\n\t\tsb.WriteString(\"\\n\\n\")\n\t}\n\n\twriteRules(\u0026sb)\n\treturn sb.String()\n}\n\n// writeRules appends the legend / how-to-play block.\nfunc writeRules(sb *strings.Builder) {\n\tsb.WriteString(\"## Rules\\n\\n\")\n\tsb.WriteString(\"- Guess the 5-letter word in \")\n\tsb.WriteString(itoa(maxAttempts))\n\tsb.WriteString(\" tries: `Guess(\\\"crane\\\")`.\\n\")\n\tsb.WriteString(\"- 🟩 correct letter, correct spot.\\n\")\n\tsb.WriteString(\"- 🟨 correct letter, wrong spot.\\n\")\n\tsb.WriteString(\"- ⬜ letter not in the word.\\n\")\n\tsb.WriteString(\"- The word changes every day (deterministic from block height).\\n\")\n}\n\n// itoa formats a small non-negative int (attempt counts) without importing\n// strconv, keeping the dependency surface minimal.\nfunc itoa(n int) string {\n\treturn i64toa(int64(n))\n}\n\n// i64toa formats an int64 as decimal.\nfunc i64toa(n int64) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\tneg := n \u003c 0\n\tif neg {\n\t\tn = -n\n\t}\n\tvar digits []byte\n\tfor n \u003e 0 {\n\t\tdigits = append(digits, byte('0'+n%10))\n\t\tn /= 10\n\t}\n\t// reverse\n\tfor i, j := 0, len(digits)-1; i \u003c j; i, j = i+1, j-1 {\n\t\tdigits[i], digits[j] = digits[j], digits[i]\n\t}\n\tif neg {\n\t\treturn \"-\" + string(digits)\n\t}\n\treturn string(digits)\n}\n"},{"name":"wordle_test.gno","body":"package wordle\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestScore(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tguess  string\n\t\tsecret string\n\t\twant   string\n\t}{\n\t\t// all letters correct, correct spots.\n\t\t{\"all correct\", \"crane\", \"crane\", \"🟩🟩🟩🟩🟩\"},\n\t\t// s⬜ l🟨 a🟨 t🟨 e🟩  (secret t,a,b,l,e vs guess s,l,a,t,e)\n\t\t{\"present wrong spot\", \"slate\", \"table\", \"⬜🟨🟨🟨🟩\"},\n\t\t// no shared letters at all.\n\t\t{\"all absent\", \"vivid\", \"champ\", \"⬜⬜⬜⬜⬜\"},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := score(tt.guess, tt.secret)\n\t\tif n := len([]rune(got)); n != wordLen {\n\t\t\tt.Errorf(\"%s: score(%q,%q) produced %d tiles, want %d\", tt.name, tt.guess, tt.secret, n, wordLen)\n\t\t}\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"%s: score(%q,%q) = %q, want %q\", tt.name, tt.guess, tt.secret, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestScoreDuplicateLetters(t *testing.T) {\n\t// guess \"eerie\" vs secret \"there\": guess e,e,r,i,e ; secret t,h,e,r,e\n\t// greens: pos? e-t no, e-h no, r-e no, i-r no, e-e yes(pos4) 🟩\n\t// secret remaining after greens: t,h,e,r (one e consumed at pos4)\n\t// pos0 e: e available -\u003e 🟨, consume e (none left)\n\t// pos1 e: no e left -\u003e ⬜\n\t// pos2 r: r available -\u003e 🟨\n\t// pos3 i: not present -\u003e ⬜\n\tgot := score(\"eerie\", \"there\")\n\twant := \"🟨⬜🟨⬜🟩\"\n\tif got != want {\n\t\tt.Errorf(\"eerie/there: got %q want %q\", got, want)\n\t}\n}\n\nfunc TestIsFiveLetters(t *testing.T) {\n\ttests := []struct {\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"crane\", true},\n\t\t{\"CRANE\", false}, // uppercase rejected (caller lowercases first)\n\t\t{\"cran\", false},  // too short\n\t\t{\"cranes\", false},// too long\n\t\t{\"cr4ne\", false}, // digit\n\t\t{\"cr ne\", false}, // space\n\t\t{\"\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tif got := isFiveLetters(tt.in); got != tt.want {\n\t\t\tt.Errorf(\"isFiveLetters(%q) = %v, want %v\", tt.in, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestDayAndWordDeterminism(t *testing.T) {\n\t// Same day index must yield the same word; word must be a dictionary entry.\n\td := dayIndex(blocksPerDay * 3)\n\tif d != 3 {\n\t\tt.Errorf(\"dayIndex: got %d want 3\", d)\n\t}\n\tw1 := wordForDay(d)\n\tw2 := wordForDay(d)\n\tif w1 != w2 {\n\t\tt.Errorf(\"wordForDay not deterministic: %q vs %q\", w1, w2)\n\t}\n\tfound := false\n\tfor _, w := range words {\n\t\tif w == w1 {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tt.Errorf(\"wordForDay returned %q which is not in the dictionary\", w1)\n\t}\n\tif !isFiveLetters(w1) {\n\t\tt.Errorf(\"dictionary word %q is not 5 lowercase letters\", w1)\n\t}\n}\n\nfunc TestAllDictionaryWordsValid(t *testing.T) {\n\tfor _, w := range words {\n\t\tif !isFiveLetters(w) {\n\t\t\tt.Errorf(\"dictionary word %q is not exactly 5 lowercase letters\", w)\n\t\t}\n\t}\n}\n\nfunc TestRenderContainsRules(t *testing.T) {\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"Daily Word Puzzle\") {\n\t\tt.Errorf(\"Render missing title; got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"Rules\") {\n\t\tt.Errorf(\"Render missing rules section; got:\\n%s\", out)\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"46918000","gas_fee":"140754ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"4ltrihJOlrpOvy7/7tHS/yevgcrrTi4NlGBDU99WQ6w7TCOefrZSU/1H0pb97WtqifTiI9fMWrn6a2r6s7pk/w=="}],"memo":""},"metadata":{"timestamp":"1790961507"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"probe","path":"gno.land/r/moul/x/framelab/probe/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/framelab/probe/v0`\n\nThe realm half of the `p/moul/x/framelab/v0` probe: shaped exactly like a\ngenerated instance realm (state here, logic in the pure package, one-line\nre-exports forwarding `cur`), and used only to assert which realm frame the pure\npackage runs in.\n\nNot useful on chain. It exists so the property the instance-per-realm pattern\ndepends on has a test that fails loudly if a future gno release changes it.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/framelab/probe/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/framelab/probe/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/framelab/probe/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/framelab/probe/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/framelab/probe/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/framelab/probe/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/framelab/probe/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/framelab/probe/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/framelab/probe/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/framelab/probe/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/framelab/probe/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"probe.gno","body":"// Realm probe is shaped exactly like a generated instance realm: it owns the\n// state, and every exported function is a one-line re-export that forwards\n// `cur` into the shared pure package.\npackage probe\n\nimport (\n\t\"gno.land/p/moul/x/framelab/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n)\n\nvar (\n\tToken  *grc20.Token\n\tledger *grc20.PrivateLedger\n)\n\nfunc init(cur realm) {\n\tToken, ledger = grc20.NewToken(\"Probe\", \"PRB\", 6, 0, cur)\n}\n\n// Run is the instance-realm shape under test.\nfunc Run(cur realm, from address, amount int64) address {\n\treturn framelab.Pull(0, cur, Token, from, amount)\n}\n\n// Frame reports what pure-package code sees as its own realm identity.\nfunc Frame(cur realm) (string, address, bool) { return framelab.Who(0, cur) }\n"},{"name":"probe_test.gno","body":"package probe\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst selfPath = \"gno.land/r/moul/x/framelab/probe/v0\"\n\nfunc self() address { return chain.PackageAddress(selfPath) }\n\n// The claim: pure-package code called with a forwarded `cur` still runs in the\n// importing realm's frame, so it reports that realm's path and address and its\n// `cur` is still accepted as current by grc20's spoof check.\nfunc TestPureCodeKeepsImportingRealmFrame(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tpath, addr, isCurrent := Frame(cross(cur))\n\tuassert.Equal(t, selfPath, path)\n\tuassert.Equal(t, self().String(), addr.String())\n\tuassert.True(t, isCurrent)\n}\n\n// The same claim, exercised through the operation that actually matters: a\n// GRC20 pull issued from inside the pure package must credit the instance\n// realm's own address.\nfunc TestPureCodePullsToImportingRealm(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tledger.Mint(alice, 1_000)\n\tledger.Approve(alice, self(), 500)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tbound := Run(cross(cur), alice, 400)\n\n\tuassert.Equal(t, self().String(), bound.String())\n\tuassert.Equal(t, int64(400), Token.BalanceOf(self()))\n\tuassert.Equal(t, int64(600), Token.BalanceOf(alice))\n\tuassert.Equal(t, int64(100), Token.Allowance(alice, self()))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"22730200","gas_fee":"68190ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"el4B5jsIbgDiRq8dvLG9Ie6RE04w91LNA0ZKy+cSdFBjNXH/QbbyB6Ao8NzeKozD+guGHJjiEKGf9V+wUl0drQ=="}],"memo":""},"metadata":{"timestamp":"1790961511"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"idle","path":"gno.land/r/moul/x/games/idle/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/games/idle/v0`\n\n**A mine that keeps working while you are not looking at it**: `Start`, `Claim`, `Upgrade`,\n`Prestige`.\n\n```\nmaketx call ... -func Start      # open a mine at level 1\nmaketx call ... -func Claim      # bank what it dug\nmaketx call ... -func Upgrade    # spend the bank to dig faster\nmaketx call ... -func Prestige   # at level 10: reset for a permanent multiplier\n```\n\nOre accrues at a rate set by your level. There are no turns, no block hook and no keeper:\nthe realm stores what you had and when, and everything else is arithmetic done at the moment\nsomebody asks. `Render(\"\")` is the board, `Render(\"\u003caddress\u003e\")` is one mine's card.\n\n**The numbers move on their own.** Refresh the page a minute later and the mine has dug more,\nwith no transaction in between, because every figure comes from the read-only projection\nrather than from stored state. That is a live dashboard with no frontend, no indexer and no\nJavaScript, which is the one thing this chain gives you that the others charge for\nseparately.\n\nThree decisions make it a game rather than a counter:\n\n- **The mine is small.** It holds 120 periods of production and then spills. Without a\n  ceiling the optimal play is to never log in and claim once at the end, which is a savings\n  account. The ceiling scales with the rate, so the fill time stays two hours at every level\n  and showing up is the only skill. Removing it turns five tests red.\n- **Upgrades are quadratic against linear production.** Level `L` costs `10*L*L` and pays `L`\n  per period, so the next level always takes about `10*L` periods to afford. Linear against\n  linear never ends; exponential against linear dies at level four.\n- **Prestige exists.** Without a reset the leaderboard is settled by whoever started first\n  and nobody else has a reason to join. Trading a level-10 mine for a permanent multiplier\n  means a player starting today has a reachable ceiling. Banked and pending ore burn; the\n  lifetime total does not.\n\n**Nothing rolls dice.** Every outcome is a pure function of when you acted, so there is no\nblock hash to grind and no ordering to front-run, and the card can tell you exactly what an\naction produces before you sign it. Combat games reach for randomness and inherit a\nvalidator-manipulable seed; this one does not need to.\n\nTime is unix seconds from the block, not block height: a height-denominated economy silently\nreprices itself whenever the chain's block time moves.\n\nThe arithmetic is [p/moul/x/games/accrual](/p/moul/x/games/accrual/v0), which owns the rule\nthat makes lazy time honest. Claiming every period and claiming once pay exactly the same,\nright up to the point where the mine fills, and that limit is the design rather than the\narithmetic.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/games/idle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/idle/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/games/idle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/idle/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/games/idle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/idle/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/games/idle/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/idle/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/games/idle/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/games/idle/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/games/idle/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"idle.gno","body":"// Package idle is a mine that keeps working while you are not looking at it.\n//\n// Ore accrues at a rate set by your level. Claim banks it, Upgrade spends the\n// bank to dig faster, and at level 10 you may Prestige: start over at level 1\n// carrying a permanent multiplier. There are no turns, no block hook and no\n// keeper. The realm stores what you had and when, and everything else is\n// arithmetic done at the moment somebody asks.\n//\n// The three decisions that make it a game rather than a counter:\n//\n//  1. THE MINE IS SMALL. It holds two hours of production and then spills.\n//     Without a ceiling the optimal play is to never log in and claim once at\n//     the end, which is not a game, it is a savings account. The ceiling is\n//     what makes showing up the skill, and it scales with the rate, so two\n//     hours stays two hours at every level.\n//  2. UPGRADES ARE QUADRATIC AGAINST LINEAR PRODUCTION. Level L costs\n//     UpgradeBase*L*L and pays L per period, so the next level always takes\n//     about UpgradeBase*L periods to afford: the curve bends without ever\n//     stalling. Linear against linear never ends, and exponential against\n//     linear dies at level four.\n//  3. PRESTIGE EXISTS. Without a reset the leaderboard is settled by whoever\n//     started first and nobody else has a reason to join. Trading a level-10\n//     mine for a permanent multiplier means a player who starts today has a\n//     reachable ceiling.\n//\n// Time is unix seconds from the block, not block height. A height-denominated\n// economy silently repriced itself every time the chain's block time moved,\n// and gno.land's has moved from about 4.1s to 3.405s inside a month.\n//\n// Nothing here rolls dice. Everything a player can do is a pure function of\n// when they did it, so there is no block hash to grind and no ordering to\n// front-run, and the page can tell you exactly what an action will produce\n// before you sign it.\n//\n// The arithmetic is [p/moul/x/games/accrual](/p/moul/x/games/accrual/v0),\n// which owns the one rule that makes lazy time honest: how often you claim\n// must not change what you end up with.\npackage idle\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/games/accrual/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// The economy. Ore is a bare integer: there is no token here, and nothing\n// leaves the realm.\nconst (\n\t// Period is one minute of unix time. A level-1 mine digs one ore a minute.\n\tPeriod = int64(60)\n\t// CapPeriods is how much production the mine holds before it spills, in\n\t// periods. It multiplies the rate, so the fill time is level-independent.\n\tCapPeriods = int64(120)\n\t// UpgradeBase sets the cost curve: level L costs UpgradeBase*L*L to leave.\n\tUpgradeBase = int64(10)\n\t// PrestigeAt is the level at which a reset becomes available.\n\tPrestigeAt = int64(10)\n\t// MaxLevel is a safety rail on the cost curve, not a mechanic: it is far\n\t// beyond anything reachable, and keeps every product inside int64.\n\tMaxLevel = int64(1000)\n\t// MaxPrestige bounds the multiplier for the same reason.\n\tMaxPrestige = int64(100)\n)\n\nvar errNoMine = errors.New(\"idle: you have no mine yet, call Start first\")\n\n// mine is one player's state. pending and anchor are the accrual pair: what\n// was in the mine, and as of when. Everything else is bookkeeping.\ntype mine struct {\n\towner    address\n\tlevel    int64\n\tprestige int64\n\tpending  int64 // ore in the mine at anchor, capped\n\tanchor   int64 // unix seconds; the accrual clock, not \"last seen\"\n\tbanked   int64 // claimed ore, spendable, uncapped\n\tlifetime int64 // every ore ever claimed, never reset by Prestige\n\tclaims   int64\n\tstarted  int64\n}\n\nvar mines avl.Tree // address string -\u003e *mine\n\n// now is the chain's own clock in unix seconds. time.Now() in a realm returns\n// the block timestamp, so it is consensus-deterministic rather than wall time.\nfunc now() int64 { return time.Now().Unix() }\n\n// rate is the accrual Rate for a level and prestige. It is rebuilt on each\n// call rather than stored, so a mine's stored state cannot disagree with the\n// economy after a redeploy changes a constant.\nfunc rate(level, prestige int64) accrual.Rate {\n\tperPeriod := level * (1 + prestige)\n\tr, err := accrual.New(perPeriod, Period, CapPeriods*perPeriod)\n\tif err != nil {\n\t\tpanic(\"idle: \" + err.Error())\n\t}\n\treturn r\n}\n\n// upgradeCost is what it costs to leave the given level.\nfunc upgradeCost(level int64) int64 { return UpgradeBase * level * level }\n\nfunc get(owner address) (*mine, bool) {\n\tv := mines.Get(owner.String())\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*mine), true\n}\n\n// settle moves the mine's clock to at, banking nothing. It is the only place\n// that writes the accrual pair, and it is deliberately the same call Render\n// makes read-only, so the page can never promise a number an action will not\n// honour.\nfunc (m *mine) settle(at int64) {\n\tpending, anchor, err := rate(m.level, m.prestige).Advance(m.pending, m.anchor, at)\n\tif err != nil {\n\t\tpanic(\"idle: \" + err.Error())\n\t}\n\tm.pending, m.anchor = pending, anchor\n}\n\n// view is settle without the write, for Render and for the read helpers.\nfunc (m *mine) view(at int64) int64 {\n\tpending, err := rate(m.level, m.prestige).At(m.pending, m.anchor, at)\n\tif err != nil {\n\t\tpanic(\"idle: \" + err.Error())\n\t}\n\treturn pending\n}\n\n// fullAt is the unix second at which this mine starts wasting production.\nfunc (m *mine) fullAt(at int64) int64 {\n\tpending := m.view(at)\n\tfull, err := rate(m.level, m.prestige).Full(pending, at)\n\tif err != nil {\n\t\tpanic(\"idle: \" + err.Error())\n\t}\n\treturn full\n}\n\n// start opens a mine for owner. Non-crossing so tests can drive the clock.\nfunc start(owner address, at int64) string {\n\tif _, ok := get(owner); ok {\n\t\tpanic(\"idle: you already have a mine\")\n\t}\n\tmines.Set(owner.String(), \u0026mine{\n\t\towner:   owner,\n\t\tlevel:   1,\n\t\tanchor:  at,\n\t\tstarted: at,\n\t})\n\treturn \"Mine opened at level 1. It digs \" + strconv.FormatInt(Period, 10) +\n\t\t\"s per ore and holds \" + strconv.FormatInt(CapPeriods, 10) + \" before it spills.\"\n}\n\nfunc mustGet(owner address) *mine {\n\tm, ok := get(owner)\n\tif !ok {\n\t\tpanic(errNoMine.Error())\n\t}\n\treturn m\n}\n\n// claim banks everything the mine has dug.\nfunc claim(owner address, at int64) string {\n\tm := mustGet(owner)\n\tm.settle(at)\n\tif m.pending == 0 {\n\t\tpanic(\"idle: nothing to claim yet\")\n\t}\n\tgot := m.pending\n\tm.pending = 0\n\tm.banked += got\n\tm.lifetime += got\n\tm.claims++\n\treturn \"Claimed \" + strconv.FormatInt(got, 10) + \" ore. Banked: \" +\n\t\tstrconv.FormatInt(m.banked, 10) + \".\"\n}\n\n// upgrade spends the bank to raise the level.\nfunc upgrade(owner address, at int64) string {\n\tm := mustGet(owner)\n\tm.settle(at)\n\tif m.level \u003e= MaxLevel {\n\t\tpanic(\"idle: this mine is at the maximum level\")\n\t}\n\tcost := upgradeCost(m.level)\n\tif m.banked \u003c cost {\n\t\tpanic(\"idle: upgrade costs \" + strconv.FormatInt(cost, 10) +\n\t\t\t\" ore, you have \" + strconv.FormatInt(m.banked, 10))\n\t}\n\tm.banked -= cost\n\tm.level++\n\treturn \"Level \" + strconv.FormatInt(m.level, 10) + \". Digging \" +\n\t\tstrconv.FormatInt(m.level*(1+m.prestige), 10) + \" ore per period.\"\n}\n\n// prestige trades the mine for a permanent multiplier.\nfunc prestige(owner address, at int64) string {\n\tm := mustGet(owner)\n\tm.settle(at)\n\tif m.level \u003c PrestigeAt {\n\t\tpanic(\"idle: prestige unlocks at level \" + strconv.FormatInt(PrestigeAt, 10) +\n\t\t\t\", you are at \" + strconv.FormatInt(m.level, 10))\n\t}\n\tif m.prestige \u003e= MaxPrestige {\n\t\tpanic(\"idle: this mine is at the maximum prestige\")\n\t}\n\tm.prestige++\n\tm.level = 1\n\tm.pending = 0\n\tm.banked = 0\n\tm.anchor = at\n\treturn \"Prestige \" + strconv.FormatInt(m.prestige, 10) +\n\t\t\". Back to level 1, digging \" + strconv.FormatInt(1+m.prestige, 10) +\n\t\t\" ore per period. Lifetime ore: \" + strconv.FormatInt(m.lifetime, 10) + \".\"\n}\n\n// Start opens a mine for the caller. One per address, forever: Prestige is the\n// only way to start over, and it keeps your lifetime total.\nfunc Start(cur realm) string {\n\treturn start(cur.Previous().Address(), now())\n}\n\n// Claim banks whatever the mine has dug since the last claim. Claiming often\n// and claiming rarely pay exactly the same, by construction: see accrual.\nfunc Claim(cur realm) string {\n\treturn claim(cur.Previous().Address(), now())\n}\n\n// Upgrade spends banked ore to raise the level, which raises both the rate and\n// the ceiling.\nfunc Upgrade(cur realm) string {\n\treturn upgrade(cur.Previous().Address(), now())\n}\n\n// Prestige resets a level-10 mine to level 1 for a permanent +1 multiplier.\n// Banked and pending ore are burned; the lifetime total is not.\nfunc Prestige(cur realm) string {\n\treturn prestige(cur.Previous().Address(), now())\n}\n\n// Pending reports what is sitting in an address's mine right now, unclaimed.\nfunc Pending(owner address) int64 {\n\tm, ok := get(owner)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn m.view(now())\n}\n\n// Banked reports an address's spendable ore.\nfunc Banked(owner address) int64 {\n\tm, ok := get(owner)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn m.banked\n}\n\n// Level reports an address's level and prestige.\nfunc Level(owner address) (int64, int64) {\n\tm, ok := get(owner)\n\tif !ok {\n\t\treturn 0, 0\n\t}\n\treturn m.level, m.prestige\n}\n\n// FullAt reports the unix second at which an address's mine starts wasting\n// what it digs, which is the only deadline in this game.\nfunc FullAt(owner address) int64 {\n\tm, ok := get(owner)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn m.fullAt(now())\n}\n"},{"name":"idle_test.gno","body":"package idle\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// reset clears the realm between tests. Package state carries over from one\n// test to the next even though the block height does not, so every test that\n// looks at the board has to start from a known tree.\nfunc reset() { mines = avl.Tree{} }\n\n// t0 is an arbitrary unix second to hang the tests off. Nothing asserts an\n// absolute time, only differences from this one.\n//\n// It is only legal for the non-crossing helpers, which take the time as an\n// argument. Anything reaching now() (Render and the read helpers) reads the\n// BLOCK timestamp, which in a test is far below t0, so a mine anchored here\n// would make the chain's clock look like it ran backwards. Those tests anchor\n// at now() instead.\nconst t0 = int64(1700000000)\n\nfunc TestStartOpensALevelOneMine(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\n\tout := start(alice, t0)\n\tuassert.True(t, strings.Contains(out, \"level 1\"), \"expected the opening message\")\n\n\tm, ok := get(alice)\n\tuassert.True(t, ok, \"expected a mine\")\n\tuassert.Equal(t, int64(1), m.level)\n\tuassert.Equal(t, int64(0), m.prestige)\n\tuassert.Equal(t, t0, m.anchor)\n\tuassert.Equal(t, int64(0), m.pending)\n}\n\nfunc TestStartTwicePanics(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tuassert.PanicsContains(t, cur, \"already have a mine\", func() { start(alice, t0) })\n}\n\nfunc TestActingWithoutAMinePanics(cur realm, t *testing.T) {\n\treset()\n\tbob := testutils.TestAddress(\"bob\")\n\tuassert.PanicsContains(t, cur, \"no mine yet\", func() { claim(bob, t0) })\n\tuassert.PanicsContains(t, cur, \"no mine yet\", func() { upgrade(bob, t0) })\n\tuassert.PanicsContains(t, cur, \"no mine yet\", func() { prestige(bob, t0) })\n}\n\nfunc TestAccrualAndClaim(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\n\tm, _ := get(alice)\n\tuassert.Equal(t, int64(0), m.view(t0+Period-1), \"nothing before the first whole period\")\n\tuassert.Equal(t, int64(1), m.view(t0+Period), \"one ore after one period\")\n\tuassert.Equal(t, int64(30), m.view(t0+30*Period))\n\n\tout := claim(alice, t0+30*Period)\n\tuassert.True(t, strings.Contains(out, \"Claimed 30 ore\"), \"got: \"+out)\n\tuassert.Equal(t, int64(30), m.banked)\n\tuassert.Equal(t, int64(30), m.lifetime)\n\tuassert.Equal(t, int64(0), m.pending)\n\tuassert.Equal(t, int64(1), m.claims)\n}\n\nfunc TestClaimingNothingPanics(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tuassert.PanicsContains(t, cur, \"nothing to claim\", func() { claim(alice, t0+Period-1) })\n}\n\n// TestClaimCadenceDoesNotMatter is the game-level statement of the invariant\n// the accrual package exists for: two players who dig for the same span end up\n// with the same ore whatever their claiming habits. A realm that re-anchored\n// to now would pay the busy player less, and a realm that decayed would pay\n// them more.\n//\n// \"Whatever their habits\" has exactly one limit, and it is the design rather\n// than the arithmetic: a cadence longer than the mine takes to fill spills,\n// and is meant to. Every cadence here stays under that, and\n// TestTheMineSpills covers the other side.\nfunc TestClaimCadenceDoesNotMatter(t *testing.T) {\n\tconst span = 600 * Period\n\tfill := CapPeriods * Period\n\n\tfor _, cadence := range []int64{Period, 2*Period + 1, 7 * Period, 599, 6001, fill} {\n\t\tif cadence \u003e fill {\n\t\t\tt.Fatalf(\"cadence %d would spill, which is not what this test is about\", cadence)\n\t\t}\n\t\treset()\n\t\talice := testutils.TestAddress(\"alice\")\n\t\tstart(alice, t0)\n\t\tm, _ := get(alice)\n\n\t\tfor at := t0 + cadence; at \u003c= t0+span; at += cadence {\n\t\t\tif m.view(at) \u003e 0 {\n\t\t\t\tclaim(alice, at)\n\t\t\t}\n\t\t}\n\t\tif m.view(t0+span) \u003e 0 {\n\t\t\tclaim(alice, t0+span)\n\t\t}\n\t\tuassert.Equal(t, int64(600), m.lifetime, \"cadence changed the payout\")\n\t}\n}\n\n// TestTheMineSpills pins the ceiling: production past the cap is lost, and\n// coming back late is what costs you, which is decision 1 of the design.\nfunc TestTheMineSpills(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tm, _ := get(alice)\n\n\tuassert.Equal(t, CapPeriods, m.view(t0+CapPeriods*Period), \"full exactly at the cap\")\n\tuassert.Equal(t, CapPeriods, m.view(t0+10*CapPeriods*Period), \"and no more, ever\")\n\n\tclaim(alice, t0+10*CapPeriods*Period)\n\tuassert.Equal(t, CapPeriods, m.lifetime, \"ten cap-fulls of absence paid one\")\n}\n\nfunc TestFullAtIsTheOnlyDeadline(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tm, _ := get(alice)\n\n\tuassert.Equal(t, t0+CapPeriods*Period, m.fullAt(t0), \"an empty mine fills in CapPeriods\")\n\n\thalf := t0 + (CapPeriods/2)*Period\n\tuassert.Equal(t, half+(CapPeriods/2)*Period, m.fullAt(half), \"half full, half the time left\")\n\n\tlate := t0 + 99*CapPeriods*Period\n\tuassert.Equal(t, late, m.fullAt(late), \"already full reads as now\")\n}\n\nfunc TestUpgrade(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tm, _ := get(alice)\n\n\tuassert.Equal(t, UpgradeBase, upgradeCost(1))\n\tuassert.Equal(t, 4*UpgradeBase, upgradeCost(2))\n\n\tclaim(alice, t0+UpgradeBase*Period)\n\tout := upgrade(alice, t0+UpgradeBase*Period)\n\tuassert.True(t, strings.Contains(out, \"Level 2\"), \"got: \"+out)\n\tuassert.Equal(t, int64(2), m.level)\n\tuassert.Equal(t, int64(0), m.banked, \"the upgrade spent the bank\")\n\n\t// The rate and the ceiling both doubled, so the fill time did not move.\n\tuassert.Equal(t, int64(2), rate(m.level, m.prestige).Amount)\n\tuassert.Equal(t, 2*CapPeriods, rate(m.level, m.prestige).Cap)\n}\n\nfunc TestUpgradeTooPoorPanics(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tuassert.PanicsContains(t, cur, \"upgrade costs 10 ore, you have 0\",\n\t\tfunc() { upgrade(alice, t0) })\n}\n\nfunc TestPrestigeIsLockedUntilLevelTen(cur realm, t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tuassert.PanicsContains(t, cur, \"prestige unlocks at level 10\",\n\t\tfunc() { prestige(alice, t0) })\n}\n\nfunc TestPrestigeResetsButKeepsLifetime(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tm, _ := get(alice)\n\n\t// Hand the mine to level 10 rather than grinding it, then bank something\n\t// so the reset has ore to burn.\n\tm.level = PrestigeAt\n\tclaim(alice, t0+50*Period)\n\tbanked, lifetime := m.banked, m.lifetime\n\tuassert.True(t, banked \u003e 0, \"expected ore to burn\")\n\n\tout := prestige(alice, t0+50*Period)\n\tuassert.True(t, strings.Contains(out, \"Prestige 1\"), \"got: \"+out)\n\tuassert.Equal(t, int64(1), m.prestige)\n\tuassert.Equal(t, int64(1), m.level)\n\tuassert.Equal(t, int64(0), m.banked, \"prestige burns the bank\")\n\tuassert.Equal(t, int64(0), m.pending)\n\tuassert.Equal(t, lifetime, m.lifetime, \"lifetime survives the reset\")\n\n\t// A level-1 prestige-1 mine digs what a level-2 mine does.\n\tuassert.Equal(t, int64(2), rate(m.level, m.prestige).Amount)\n}\n\nfunc TestReadHelpersAreSafeOnAStranger(t *testing.T) {\n\treset()\n\tcarol := testutils.TestAddress(\"carol\")\n\tuassert.Equal(t, int64(0), Pending(carol))\n\tuassert.Equal(t, int64(0), Banked(carol))\n\tuassert.Equal(t, int64(0), FullAt(carol))\n\tlvl, pre := Level(carol)\n\tuassert.Equal(t, int64(0), lvl)\n\tuassert.Equal(t, int64(0), pre)\n}\n\nfunc TestSpan(t *testing.T) {\n\tcases := []struct {\n\t\tsecs int64\n\t\twant string\n\t}{\n\t\t{0, \"0s\"},\n\t\t{-5, \"0s\"},\n\t\t{1, \"1s\"},\n\t\t{59, \"59s\"},\n\t\t{60, \"1m\"},\n\t\t{61, \"1m 1s\"},\n\t\t{3600, \"1h\"},\n\t\t{3661, \"1h 1m\"},\n\t\t{86400, \"1d\"},\n\t\t{90061, \"1d 1h\"},\n\t\t{7200, \"2h\"},\n\t}\n\tfor _, tc := range cases {\n\t\tuassert.Equal(t, tc.want, span(tc.secs), \"span(\"+tc.want+\")\")\n\t}\n}\n\nfunc TestRenderBoard(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(board(t0), \"Nobody is digging yet\"),\n\t\t\"expected the empty placeholder\")\n\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\tout := board(t0 + 30*Period)\n\tuassert.True(t, strings.Contains(out, \"The Mine\"), \"expected the title\")\n\tuassert.True(t, strings.Contains(out, \"30\"), \"expected the live pending figure\")\n\tuassert.True(t, strings.Contains(out, \"to spill\"), \"expected the spill countdown\")\n}\n\nfunc TestRenderCard(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\n\tout := card(alice, t0+30*Period)\n\tuassert.True(t, strings.Contains(out, \"Level **1**\"), \"got: \"+out)\n\tuassert.True(t, strings.Contains(out, \"30 / 120\"), \"expected stock over cap\")\n\tuassert.True(t, strings.Contains(out, \"1h 30m\"), \"expected the spill countdown\")\n\tuassert.True(t, strings.Contains(out, \"10 short\"), \"expected the shortfall\")\n\tuassert.True(t, strings.Contains(out, \"9 to go\"), \"expected the prestige distance\")\n\n\tfull := card(alice, t0+999*Period)\n\tuassert.True(t, strings.Contains(full, \"already full\"), \"expected the waste warning\")\n\n\tbob := testutils.TestAddress(\"bob\")\n\tuassert.True(t, strings.Contains(card(bob, t0), \"No mine at\"), \"expected the stranger card\")\n}\n\n// TestRenderIsLive is the property the whole design is for: the page changes\n// with nothing but the passage of time, so gnoweb serves a live dashboard and\n// no transaction was needed to move it.\nfunc TestRenderIsLive(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\tstart(alice, t0)\n\n\tearly := board(t0 + 10*Period)\n\tlater := board(t0 + 20*Period)\n\tuassert.NotEqual(t, early, later, \"the board did not move with time\")\n\tuassert.Equal(t, int64(0), Pending(testutils.TestAddress(\"nobody\")),\n\t\t\"and reading it wrote nothing\")\n}\n"},{"name":"render.gno","body":"package idle\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\n// Render shows every mine, or one mine's card at /r/.../idle:\u003caddress\u003e.\n//\n// The numbers move on their own: the same URL renders differently a minute\n// later because the mine kept digging, and nothing wrote to the chain in\n// between. That is the whole point of the accrual pair, and it is why every\n// figure here comes from the read-only view rather than from stored state.\nfunc Render(path string) string {\n\tat := now()\n\tif addr := strings.TrimSpace(path); addr != \"\" {\n\t\treturn card(address(addr), at)\n\t}\n\treturn board(at)\n}\n\n// byLifetimeThenOwner ranks by lifetime ore, then by address so the order is\n// identical on every node.\ntype byLifetimeThenOwner []*mine\n\nfunc (r byLifetimeThenOwner) Len() int      { return len(r) }\nfunc (r byLifetimeThenOwner) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byLifetimeThenOwner) Less(i, j int) bool {\n\tif r[i].prestige != r[j].prestige {\n\t\treturn r[i].prestige \u003e r[j].prestige\n\t}\n\tif r[i].lifetime != r[j].lifetime {\n\t\treturn r[i].lifetime \u003e r[j].lifetime\n\t}\n\treturn r[i].owner.String() \u003c r[j].owner.String()\n}\n\nfunc board(at int64) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# The Mine\\n\\n\")\n\tb.WriteString(\"Ore accrues while you are away. The mine holds \" +\n\t\tstrconv.FormatInt(CapPeriods, 10) + \" periods of production and then spills, so the only thing that costs you anything is not showing up.\\n\\n\")\n\n\tall := []*mine{}\n\tmines.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tall = append(all, v.(*mine))\n\t\treturn false\n\t})\n\tsort.Sort(byLifetimeThenOwner(all))\n\n\tt := ui.NewTable(\"#\", \"Miner\", \"Lv\", \"Prestige\", \"In the mine\", \"Banked\", \"Lifetime\")\n\tfor i, m := range all {\n\t\tpending := m.view(at)\n\t\tfull := \"\"\n\t\tif r := m.fullAt(at); r \u003e at {\n\t\t\tfull = \" (\" + span(r-at) + \" to spill)\"\n\t\t} else {\n\t\t\tfull = \" (**full**)\"\n\t\t}\n\t\tt.Row(\n\t\t\tui.Podium(i)+strconv.Itoa(i+1),\n\t\t\tui.Addr(m.owner),\n\t\t\tstrconv.FormatInt(m.level, 10),\n\t\t\tstrconv.FormatInt(m.prestige, 10),\n\t\t\tstrconv.FormatInt(pending, 10)+full,\n\t\t\tstrconv.FormatInt(m.banked, 10),\n\t\t\tstrconv.FormatInt(m.lifetime, 10),\n\t\t)\n\t}\n\tb.WriteString(t.OrEmpty(\"Nobody is digging yet.\"))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(ui.Join(\" | \",\n\t\tui.Action(\"Open a mine\", \"Start\"),\n\t\tui.Action(\"Claim\", \"Claim\"),\n\t\tui.Action(\"Upgrade\", \"Upgrade\"),\n\t\tui.Action(\"Prestige\", \"Prestige\"),\n\t))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\nfunc card(owner address, at int64) string {\n\tm, ok := get(owner)\n\tif !ok {\n\t\treturn \"# The Mine\\n\\n\" + ui.Empty(\"No mine at \"+ui.Addr(owner)+\".\")\n\t}\n\n\tpending := m.view(at)\n\tr := rate(m.level, m.prestige)\n\tvar b strings.Builder\n\n\tb.WriteString(\"# \" + ui.Addr(m.owner) + \"'s mine\\n\\n\")\n\tb.WriteString(\"Level **\" + strconv.FormatInt(m.level, 10) + \"**\")\n\tif m.prestige \u003e 0 {\n\t\tb.WriteString(\", prestige **\" + strconv.FormatInt(m.prestige, 10) + \"**\")\n\t}\n\tb.WriteString(\", digging **\" + strconv.FormatInt(r.Amount, 10) + \"** ore every \" +\n\t\tspan(Period) + \".\\n\\n\")\n\n\tt := ui.NewTable(\"\", \"\")\n\tt.Row(\"In the mine\", strconv.FormatInt(pending, 10)+\" / \"+strconv.FormatInt(r.Cap, 10))\n\tif full := m.fullAt(at); full \u003e at {\n\t\tt.Row(\"Spills in\", span(full-at))\n\t} else {\n\t\tt.Row(\"Spills in\", \"**already full, every period is being wasted**\")\n\t}\n\tt.Row(\"Banked\", strconv.FormatInt(m.banked, 10))\n\tt.Row(\"Lifetime ore\", strconv.FormatInt(m.lifetime, 10))\n\tt.Row(\"Claims\", strconv.FormatInt(m.claims, 10))\n\tt.Row(\"Digging for\", span(at-m.started))\n\tif m.level \u003c MaxLevel {\n\t\tcost := upgradeCost(m.level)\n\t\tshort := cost - m.banked\n\t\tnext := strconv.FormatInt(cost, 10) + \" ore\"\n\t\tif short \u003e 0 {\n\t\t\tnext += \" (\" + strconv.FormatInt(short, 10) + \" short)\"\n\t\t} else {\n\t\t\tnext += \" (**affordable now**)\"\n\t\t}\n\t\tt.Row(\"Next level\", next)\n\t}\n\tif m.prestige \u003c MaxPrestige {\n\t\tif m.level \u003e= PrestigeAt {\n\t\t\tt.Row(\"Prestige\", \"**available**, and it burns \"+\n\t\t\t\tstrconv.FormatInt(m.banked+pending, 10)+\" ore\")\n\t\t} else {\n\t\t\tt.Row(\"Prestige\", \"at level \"+strconv.FormatInt(PrestigeAt, 10)+\n\t\t\t\t\", \"+strconv.FormatInt(PrestigeAt-m.level, 10)+\" to go\")\n\t\t}\n\t}\n\tb.WriteString(t.String())\n\tb.WriteString(\"\\n\")\n\tb.WriteString(ui.Join(\" | \",\n\t\tui.Action(\"Claim\", \"Claim\"),\n\t\tui.Action(\"Upgrade\", \"Upgrade\"),\n\t\tui.Action(\"Prestige\", \"Prestige\"),\n\t))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\n// span renders a number of seconds the way a player reads it. It rounds down\n// and stops at two units, because \"2h 3m 11s to spill\" is noise when the\n// question is whether to claim now or after lunch.\nfunc span(secs int64) string {\n\tif secs \u003c= 0 {\n\t\treturn \"0s\"\n\t}\n\tunits := []struct {\n\t\tsize int64\n\t\tname string\n\t}{\n\t\t{86400, \"d\"},\n\t\t{3600, \"h\"},\n\t\t{60, \"m\"},\n\t\t{1, \"s\"},\n\t}\n\tparts := []string{}\n\tfor i, u := range units {\n\t\tif secs \u003c u.size {\n\t\t\tcontinue\n\t\t}\n\t\tn := secs / u.size\n\t\tsecs -= n * u.size\n\t\tparts = append(parts, strconv.FormatInt(n, 10)+u.name)\n\t\tif len(parts) == 2 || i == len(units)-1 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn strings.Join(parts, \" \")\n}\n"},{"name":"render_example_test.gno","body":"package idle\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestRenderRoutes pins that Render dispatches on the path: empty is the\n// board, anything else is read as an address.\nfunc TestRenderRoutes(t *testing.T) {\n\treset()\n\talice := testutils.TestAddress(\"alice\")\n\t// Anchored at the block clock, not at t0: Render reads now().\n\tstart(alice, now())\n\n\tuassert.True(t, strings.Contains(Render(\"\"), \"The Mine\"), \"empty path is the board\")\n\tuassert.True(t, strings.Contains(Render(alice.String()), \"'s mine\"), \"an address is a card\")\n\tuassert.True(t, strings.Contains(Render(\"  \"+alice.String()+\"  \"), \"'s mine\"),\n\t\t\"a padded address is still a card\")\n\tuassert.True(t, strings.Contains(Render(\"g1nobody\"), \"No mine at\"), \"a stranger is handled\")\n}\n\n// ExampleRender pins the realm's empty board. It resets the tree first because\n// examples run after every Test in the package and would otherwise render\n// whatever they left behind.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # The Mine\n\t//\n\t// Ore accrues while you are away. The mine holds 120 periods of production and then spills, so the only thing that costs you anything is not showing up.\n\t//\n\t// *Nobody is digging yet.*\n\t//\n\t// [Open a mine](/r/moul/x/games/idle/v0$help\u0026func=Start) | [Claim](/r/moul/x/games/idle/v0$help\u0026func=Claim) | [Upgrade](/r/moul/x/games/idle/v0$help\u0026func=Upgrade) | [Prestige](/r/moul/x/games/idle/v0$help\u0026func=Prestige)\n}\n"}]},"send":"","max_deposit":"12000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lastwords","path":"gno.land/r/moul/x/games/lastwords/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/games/lastwords/v0`\n\n**One string, on chain, forever.** Pay more than the last writer paid and the\nslot is yours. When the clock runs out, whatever is in it stays there\npermanently.\n\n```\nPrice(\"famous last words\")   # what it costs right now, in ugnot\nWrite(\"famous last words\")   # send that much with the call\nSettle()                     # after the clock runs out, anyone may call it\nWithdraw()                   # sweep what you are owed\n```\n\nThe artefact at the end is the point: this is a bidding war over an epitaph, not\nover a prize. It is also the smallest thing that exercises the two libraries\nunder it, which is why it exists.\n\n**The last writer does not take the pot.** They take the slot, which is what they\nwere bidding for. The pot goes to everyone *else* who wrote, pro rata to what\neach paid. Winner-takes-all makes the second-to-last writer the mark, everybody\ncan see that, and so nobody joins.\n\n**Half of every payment is credited to the writer it displaces**, immediately and\nwhatever happens afterwards. A zero-sum game minus gas gives a second player no\nreason to exist; being overwritten early has to be survivable.\n\n**The clock terminates.** Each write pushes the deadline a fifth of the way\ntoward a hard end fixed when the slot opened, and never past it, and never to\nless than 300 blocks from now. The last stretch stays long enough for a\ntransaction to land in, so the slot is won by paying rather than by being\nunreachable.\n\n**Nothing is ever pushed.** Dividends and settlement shares are credited to a\nledger and swept by `Withdraw`. A realm that pays inside a loop over its roster\nis a gas bomb, and the more successful the game gets the more certain it is to\nbrick.\n\nThree things worth knowing before writing:\n\n- **The message is capped at 280 bytes and priced per byte**, because the message\n  *is* the storage cost and an uncapped one is an unbounded write at a constant\n  price.\n- **`Price` is a query, and an underpaying write is refused, not refunded.** Read\n  it in the same breath as you send.\n- **`Settle` is permissionless.** Leaving settlement to an interested party is\n  how a pot stays unclaimed.\n\nThe realm is the wiring; the parts are libraries:\n[`p/moul/x/games/clock`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/games/clock)\nowns the deadline and its guards,\n[`p/moul/x/games/prorata`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/games/prorata)\nowns the split, and\n[`p/moul/x/daily/pullpayment`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/pullpayment)\nowns the credit ledger.\n\nThe stored message is caller-typed text rendered as markdown on a page that\ncannot be edited afterwards, so it goes through `ui.Inline` before it is shown\nand a newline is refused at write time.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/games/lastwords/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/lastwords/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/games/lastwords/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/lastwords/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/games/lastwords/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/lastwords/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/games/lastwords/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/games/lastwords/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/games/lastwords/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/games/lastwords/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/games/lastwords/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"lastwords.gno","body":"// Package lastwords is one string, on chain, forever.\n//\n// There is a single message slot. Pay more than the last writer paid and the\n// slot is yours; when the clock finally runs out, whatever is in it stays there\n// permanently. The artefact at the end is the point, so the game is a bidding\n// war over an epitaph rather than over a prize.\n//\n// The three rules exist because the obvious version of this game does not end\n// and does not pay:\n//\n//  1. THE CLOCK TERMINATES. Every write pushes the deadline a fifth of the way\n//     to a hard end fixed when the slot opened, and no write can push it past\n//     that. A constant extension per action has no end: the pot grows faster\n//     than the price of the next write, so there is always a rational next\n//     write and the game runs until everyone is bored or broke.\n//  2. THE LAST WRITER DOES NOT TAKE THE POT. They take the slot, which is what\n//     they were bidding for. The pot is split among everyone ELSE who wrote,\n//     pro rata to what they paid. Winner-takes-all makes the second-to-last\n//     writer the mark and everyone knows it, which is why nobody joins.\n//  3. HALF OF EVERY PAYMENT GOES TO THE WRITER BEING DISPLACED, immediately.\n//     A zero-sum game minus gas has no reason for a second player. Overwriting\n//     somebody pays them, so being overwritten early is not a loss.\n//\n// Nothing is ever pushed: payouts are credited to an internal ledger and swept\n// by Withdraw. A realm that pays inside a loop over its roster is a gas bomb\n// that eventually bricks, and the bigger the game gets the more certain that\n// is.\n//\n// The pieces are libraries, and the realm is the wiring:\n// [p/moul/x/games/clock](/p/moul/x/games/clock/v0) owns the deadline and its\n// guards, [p/moul/x/games/prorata](/p/moul/x/games/prorata/v0) owns the split,\n// and [p/moul/x/daily/pullpayment](/p/moul/x/daily/pullpayment/v0) owns the\n// credit ledger.\npackage lastwords\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/x/daily/pullpayment/v0\"\n\t\"gno.land/p/moul/x/games/clock/v0\"\n\t\"gno.land/p/moul/x/games/prorata/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst denom = \"ugnot\"\n\n// The rules, fixed at deploy. Times are block heights.\nconst (\n\t// Window is how long the slot stays open with nobody writing.\n\tWindow = int64(2000)\n\t// Floor is the minimum a write leaves on the clock, so the last stretch\n\t// stays long enough for a transaction to land in. Without it a decaying\n\t// extension shrinks to nothing and whoever holds at that moment wins by\n\t// being unreachable rather than by paying.\n\tFloor = int64(300)\n\t// Life is the hard end. No write can push the deadline past start+Life.\n\tLife = int64(100000)\n\t// BumpPct is how much of the gap to the hard end a write buys.\n\tBumpPct = int64(20)\n\t// DividendPct is the share of a payment credited to the writer being\n\t// displaced; the rest goes to the pot.\n\tDividendPct = int64(50)\n\n\t// MinWrite is the base price of the slot, in ugnot.\n\tMinWrite = int64(1000000)\n\t// PerByte is charged on top, in ugnot per byte of the message. The chain's\n\t// own storage deposit is 100 ugnot per byte, so this is that plus a premium\n\t// for occupying the only slot there is.\n\tPerByte = int64(1000)\n\t// MaxLen caps the message in bytes, because the message IS the storage\n\t// cost and an uncapped one is an unbounded write priced at a constant.\n\tMaxLen = 280\n)\n\nvar (\n\tclk     *clock.Clock\n\tledger  = pullpayment.New()\n\tmessage string\n\tauthor  address\n\tpaid    int64    // what the current holder paid\n\tpot     int64    // what settlement will split\n\twriters avl.Tree // address string -\u003e int64 total paid\n\torder   []string // writers in first-write order, so the split is deterministic\n\twrites  int64\n\tsettled bool\n)\n\nfunc init() {\n\topen(runtime.ChainHeight())\n}\n\n// open resets the game to a fresh slot at height h. It is the only place the\n// clock is built, so tests and init cannot disagree about the rules.\nfunc open(h int64) {\n\tc, err := clock.New(h, Window, Floor, Life)\n\tif err != nil {\n\t\tpanic(\"lastwords: \" + err.Error())\n\t}\n\tclk = c\n\tledger = pullpayment.New()\n\tmessage = \"\"\n\tauthor = \"\"\n\tpaid = 0\n\tpot = 0\n\twriters = avl.Tree{}\n\torder = nil\n\twrites = 0\n\tsettled = false\n}\n\n// Price returns what msg costs to write right now, in ugnot: a base, plus a\n// charge per byte, and always at least one ugnot more than the current holder\n// paid. Query it before sending; an underpaying write is refused, not refunded.\nfunc Price(msg string) int64 {\n\tprice := MinWrite + int64(len(msg))*PerByte\n\tif next := paid + 1; next \u003e price {\n\t\tprice = next\n\t}\n\treturn price\n}\n\n// Write puts msg in the slot and makes the caller its holder. The caller must\n// send at least Price(msg) ugnot with the transaction.\n//\n// Half of the payment is credited to the writer being displaced and the rest\n// joins the pot. The deadline is pushed a fifth of the way toward the hard end,\n// never past it, and never to less than Floor from now.\n//\n// Only a direct user transaction may write, so the payment envelope cannot be\n// spoofed by an ephemeral MsgRun realm.\nfunc Write(cur realm, msg string) {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"lastwords: write must be a direct user transaction\")\n\t}\n\th := runtime.ChainHeight()\n\tif clk.Expired(h) {\n\t\tpanic(\"lastwords: the slot is closed, these are somebody's last words now\")\n\t}\n\tif msg == \"\" {\n\t\tpanic(\"lastwords: message must not be empty\")\n\t}\n\tif len(msg) \u003e MaxLen {\n\t\tpanic(\"lastwords: message must be at most \" + strconv.Itoa(MaxLen) + \" bytes\")\n\t}\n\tif strings.ContainsAny(msg, \"\\n\\r\") {\n\t\tpanic(\"lastwords: message must be a single line\")\n\t}\n\n\tprice := Price(msg)\n\tsent := unsafe.OriginSend().AmountOf(denom)\n\tif sent \u003c price {\n\t\tpanic(\"lastwords: sent \" + strconv.FormatInt(sent, 10) +\n\t\t\t\" ugnot, price is \" + strconv.FormatInt(price, 10))\n\t}\n\n\tcaller := cur.Previous().Address()\n\n\t// The displaced writer is paid first, out of the payment that displaced\n\t// them. Credited, never sent: see the package doc.\n\tdividend := int64(0)\n\tif author != \"\" {\n\t\tdividend = sent * DividendPct / 100\n\t\tif err := ledger.Credit(author.String(), dividend); err != nil {\n\t\t\tpanic(\"lastwords: \" + err.Error())\n\t\t}\n\t}\n\tpot += sent - dividend\n\n\tkey := caller.String()\n\tif _, seen := writers.Get(key).(int64); !seen {\n\t\torder = append(order, key)\n\t}\n\twriters.Set(key, totalPaid(key)+sent)\n\n\tmessage = msg\n\tauthor = caller\n\tpaid = sent\n\twrites++\n\n\tdeadline, err := clk.BumpShare(h, BumpPct)\n\tif err != nil {\n\t\tpanic(\"lastwords: \" + err.Error())\n\t}\n\n\tchain.Emit(\"Write\",\n\t\t\"author\", key,\n\t\t\"paid\", strconv.FormatInt(sent, 10),\n\t\t\"dividend\", strconv.FormatInt(dividend, 10),\n\t\t\"deadline\", strconv.FormatInt(deadline, 10),\n\t)\n}\n\n// Settle closes the game once the clock has run out, splitting the pot among\n// every writer EXCEPT the one holding the slot, pro rata to what each paid.\n//\n// Anyone may call it: leaving settlement to an interested party is how a pot\n// stays unclaimed. It moves no coins, it credits the ledger; Withdraw is what\n// pays. If the holder is the only writer there is nobody else to split with,\n// so the pot returns to them.\nfunc Settle(cur realm) {\n\th := runtime.ChainHeight()\n\tif !clk.Expired(h) {\n\t\tpanic(\"lastwords: still open until height \" + strconv.FormatInt(clk.Deadline(), 10))\n\t}\n\tif settled {\n\t\tpanic(\"lastwords: already settled\")\n\t}\n\tsettled = true\n\tif pot == 0 {\n\t\treturn\n\t}\n\n\tholder := author.String()\n\tpayees := []string{}\n\tweights := []int64{}\n\tfor _, k := range order {\n\t\tif k == holder {\n\t\t\tcontinue\n\t\t}\n\t\tpayees = append(payees, k)\n\t\tweights = append(weights, totalPaid(k))\n\t}\n\tif len(payees) == 0 {\n\t\t// The holder wrote every word there is. Nobody to share with.\n\t\tpayees = []string{holder}\n\t\tweights = []int64{1}\n\t}\n\n\tshares, err := prorata.Split(pot, weights)\n\tif err != nil {\n\t\tpanic(\"lastwords: \" + err.Error())\n\t}\n\n\t// A zero share is dropped: CreditMany refuses a non-positive amount, and\n\t// crediting nothing is not a payment anyway.\n\tdst := []string{}\n\tamounts := []int64{}\n\tfor i, s := range shares {\n\t\tif s \u003e 0 {\n\t\t\tdst = append(dst, payees[i])\n\t\t\tamounts = append(amounts, s)\n\t\t}\n\t}\n\tif len(dst) \u003e 0 {\n\t\tif err := ledger.CreditMany(dst, amounts); err != nil {\n\t\t\tpanic(\"lastwords: \" + err.Error())\n\t\t}\n\t}\n\tpot = 0\n\n\tchain.Emit(\"Settle\",\n\t\t\"holder\", holder,\n\t\t\"writes\", strconv.FormatInt(writes, 10),\n\t\t\"payees\", strconv.Itoa(len(dst)),\n\t)\n}\n\n// Withdraw pays the caller everything credited to them and returns the amount.\n// Dividends are claimable while the game runs; settlement shares only after\n// Settle.\nfunc Withdraw(cur realm) int64 {\n\tcaller := cur.Previous().Address()\n\tamount, err := ledger.Withdraw(caller.String())\n\tif err != nil {\n\t\tpanic(\"lastwords: \" + err.Error())\n\t}\n\tbnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tbnk.SendCoins(cur.Address(), caller, chain.NewCoins(chain.NewCoin(denom, amount)))\n\n\tchain.Emit(\"Withdraw\", \"payee\", caller.String(), \"amount\", strconv.FormatInt(amount, 10))\n\treturn amount\n}\n\n// Message returns the slot's current contents, raw. Render is what escapes it.\nfunc Message() string { return message }\n\n// Author returns who holds the slot.\nfunc Author() address { return author }\n\n// Pot returns what settlement will split.\nfunc Pot() int64 { return pot }\n\n// Deadline returns the height the slot closes at.\nfunc Deadline() int64 { return clk.Deadline() }\n\n// Owed returns what an address can Withdraw right now.\nfunc Owed(addr address) int64 { return ledger.Balance(addr.String()) }\n\n// totalPaid returns what an address has paid in total, zero if it never wrote.\nfunc totalPaid(key string) int64 {\n\tv, ok := writers.Get(key).(int64)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn v\n}\n\nfunc gnot(ugnot int64) string {\n\twhole := ugnot / 1000000\n\tfrac := ugnot % 1000000\n\ts := strconv.FormatInt(whole, 10)\n\tif frac == 0 {\n\t\treturn s\n\t}\n\tf := strconv.FormatInt(frac, 10)\n\tfor len(f) \u003c 6 {\n\t\tf = \"0\" + f\n\t}\n\tfor len(f) \u003e 1 \u0026\u0026 f[len(f)-1] == '0' {\n\t\tf = f[:len(f)-1]\n\t}\n\treturn s + \".\" + f\n}\n"},{"name":"lastwords_test.gno","body":"package lastwords\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar realmAddr = chain.PackageAddress(\"gno.land/r/moul/x/games/lastwords/v0\")\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// reset reopens the slot at the current height. Heights are relative in tests\n// (SkipHeights moves forward from wherever the last test left off and there is\n// no absolute setter), so nothing here asserts an absolute height.\nfunc reset() {\n\topen(runtime.ChainHeight())\n}\n\n// write sends amount ugnot alongside the call, the way a real transaction\n// would: the runtime deposits it at the realm's address, then OriginSend\n// reports it to the crossing function.\nfunc write(cur realm, who address, amount int64, msg string) {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{denom, amount}})\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tWrite(cross(cur), msg)\n}\n\nfunc TestWriteTakesTheSlot(cur realm, t *testing.T) {\n\treset()\n\tuassert.Equal(t, \"\", Message())\n\n\twrite(cur, alice, Price(\"hello\"), \"hello\")\n\tuassert.Equal(t, \"hello\", Message())\n\tuassert.Equal(t, alice.String(), Author().String())\n\tuassert.Equal(t, int64(0), ledger.TotalOwed(), \"nobody was displaced yet\")\n\tuassert.Equal(t, MinWrite+5*PerByte, Pot(), \"the whole first payment is the pot\")\n}\n\n// TestDisplacedWriterIsPaid is rule 3: overwriting somebody pays them, so a\n// second player has a reason to exist.\nfunc TestDisplacedWriterIsPaid(cur realm, t *testing.T) {\n\treset()\n\twrite(cur, alice, Price(\"alice was here\"), \"alice was here\")\n\tpotAfterFirst := Pot()\n\n\tpaidByBob := Price(\"no, bob was\")\n\twrite(cur, bob, paidByBob, \"no, bob was\")\n\n\tdividend := paidByBob * DividendPct / 100\n\tuassert.Equal(t, dividend, Owed(alice), \"half of bob's payment, credited\")\n\tuassert.Equal(t, potAfterFirst+paidByBob-dividend, Pot())\n\tuassert.Equal(t, int64(0), Owed(bob), \"the holder is owed nothing yet\")\n}\n\nfunc TestPriceRisesWithTheHolderAndTheLength(cur realm, t *testing.T) {\n\treset()\n\tuassert.Equal(t, MinWrite, Price(\"\"), \"the base price with an empty slot\")\n\tuassert.Equal(t, MinWrite+10*PerByte, Price(\"0123456789\"), \"ten bytes cost ten byte-prices\")\n\n\tfirst := Price(\"x\")\n\twrite(cur, alice, first, \"x\")\n\tuassert.Equal(t, first+1, Price(\"\"), \"outbidding the holder is the floor\")\n}\n\nfunc TestWriteRejectsBadInput(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetOriginSend(chain.Coins{{denom, MinWrite}})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"must not be empty\", func() { Write(cross(cur), \"\") })\n\n\tlong := strings.Repeat(\"x\", MaxLen+1)\n\ttesting.SetOriginSend(chain.Coins{{denom, Price(long)}})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"at most\", func() { Write(cross(cur), long) })\n\n\ttesting.SetOriginSend(chain.Coins{{denom, Price(\"a\\nb\")}})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"single line\", func() { Write(cross(cur), \"a\\nb\") })\n\n\ttesting.SetOriginSend(chain.Coins{{denom, MinWrite - 1}})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"price is\", func() { Write(cross(cur), \"cheapskate\") })\n\n\tuassert.Equal(t, \"\", Message(), \"none of that took the slot\")\n}\n\n// TestEveryWriteExtendsButNeverPastTheHardEnd is rule 1, the terminator. A\n// constant extension per write is how a pot stays open forever.\nfunc TestEveryWriteExtendsButNeverPastTheHardEnd(cur realm, t *testing.T) {\n\treset()\n\tstart := runtime.ChainHeight()\n\thardEnd := start + Life\n\tuassert.Equal(t, start+Window, Deadline(), \"it opens with the window\")\n\n\tprev := Deadline()\n\tfor i := 0; i \u003c 30; i++ {\n\t\ttesting.SkipHeights(100)\n\t\tif runtime.ChainHeight() \u003e= Deadline() {\n\t\t\tbreak\n\t\t}\n\t\twrite(cur, alice, Price(\"again\"), \"again\")\n\t\tuassert.True(t, Deadline() \u003e= prev, \"a write never shortens the clock\")\n\t\tuassert.True(t, Deadline() \u003c= hardEnd, \"and never passes the hard end\")\n\t\tprev = Deadline()\n\t}\n\tuassert.True(t, Deadline() \u003c= hardEnd)\n\tuassert.True(t, Deadline() \u003e start+Window, \"the writes did buy time\")\n}\n\nfunc TestClosedSlotRefusesAWrite(cur realm, t *testing.T) {\n\treset()\n\twrite(cur, alice, Price(\"famous last words\"), \"famous last words\")\n\ttesting.SkipHeights(Life + 1)\n\n\ttesting.SetOriginSend(chain.Coins{{denom, Price(\"too late\")}})\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"slot is closed\", func() { Write(cross(cur), \"too late\") })\n\tuassert.Equal(t, \"famous last words\", Message(), \"the last words stay last\")\n}\n\n// TestSettleSplitsAmongEveryoneButTheHolder is rule 2, and it is the whole\n// reason this is not a winner-takes-all pot.\nfunc TestSettleSplitsAmongEveryoneButTheHolder(cur realm, t *testing.T) {\n\treset()\n\twrite(cur, alice, Price(\"a\"), \"a\")\n\ttesting.SkipHeights(10)\n\twrite(cur, bob, Price(\"b\"), \"b\")\n\ttesting.SkipHeights(10)\n\twrite(cur, carol, Price(\"c\"), \"c\")\n\n\tbeforeAlice, beforeBob := Owed(alice), Owed(bob)\n\tpot := Pot()\n\tuassert.True(t, pot \u003e 0)\n\n\ttesting.SkipHeights(Life + 1)\n\ttesting.SetRealm(testing.NewUserRealm(bob)) // anyone may settle\n\tSettle(cross(cur))\n\n\tuassert.Equal(t, int64(0), Pot(), \"the pot is fully distributed\")\n\tuassert.Equal(t, int64(0), Owed(carol), \"the holder takes the slot, not the pot\")\n\tuassert.True(t, Owed(alice) \u003e beforeAlice, \"alice got a share\")\n\tuassert.True(t, Owed(bob) \u003e beforeBob, \"bob got a share\")\n\tsplit := (Owed(alice) - beforeAlice) + (Owed(bob) - beforeBob)\n\tuassert.Equal(t, pot, split, \"and the shares add up to exactly the pot\")\n}\n\nfunc TestSettleWithOneWriterReturnsThePot(cur realm, t *testing.T) {\n\treset()\n\twrite(cur, alice, Price(\"alone\"), \"alone\")\n\tpot := Pot()\n\ttesting.SkipHeights(Life + 1)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tSettle(cross(cur))\n\tuassert.Equal(t, pot, Owed(alice), \"nobody else to share with\")\n}\n\nfunc TestSettleRefusesEarlyAndTwice(cur realm, t *testing.T) {\n\treset()\n\twrite(cur, alice, Price(\"tick\"), \"tick\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"still open\", func() { Settle(cross(cur)) })\n\n\ttesting.SkipHeights(Life + 1)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSettle(cross(cur))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"already settled\", func() { Settle(cross(cur)) })\n}\n\n// TestWithdrawPaysRealCoins checks the half nothing else can: the ledger and\n// the realm's balance agree.\nfunc TestWithdrawPaysRealCoins(cur realm, t *testing.T) {\n\treset()\n\twrite(cur, alice, Price(\"first\"), \"first\")\n\ttesting.SkipHeights(10)\n\twrite(cur, bob, Price(\"second\"), \"second\")\n\n\towed := Owed(alice)\n\tuassert.True(t, owed \u003e 0)\n\n\tro := banker.NewReadonlyBanker()\n\tbefore := ro.GetCoins(alice).AmountOf(denom)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tgot := Withdraw(cross(cur))\n\tuassert.Equal(t, owed, got)\n\tuassert.Equal(t, int64(0), Owed(alice), \"the credit is zeroed before the coins move\")\n\n\tafter := banker.NewReadonlyBanker().GetCoins(alice).AmountOf(denom)\n\tuassert.Equal(t, before+owed, after, \"the coins actually arrived\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() { Withdraw(cross(cur)) })\n}\n\n// TestRenderEscapesTheMessage is the one bug a live deploy makes permanent: the\n// realm's entire product is a string somebody else typed.\nfunc TestRenderEscapesTheMessage(cur realm, t *testing.T) {\n\treset()\n\twrite(cur, alice, Price(\"[click](https://evil.example)\"), \"[click](https://evil.example)\")\n\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, \"](https://evil.example)\"), \"no live link\")\n\tuassert.False(t, strings.Contains(out, \"[click]\"), \"the link syntax is dead\")\n\tuassert.True(t, strings.Contains(out, \"click\"), \"the text is still readable\")\n\tuassert.True(t, strings.Contains(out, \"Last Words\"))\n}\n\nfunc TestRenderCoversEveryPhase(cur realm, t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"\"), \"The slot is empty\"))\n\n\twrite(cur, alice, Price(\"open for business\"), \"open for business\")\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"open for business\"))\n\tuassert.True(t, strings.Contains(out, \"Open for another\"))\n\n\ttesting.SkipHeights(Life + 1)\n\tout = Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"**Closed** at height\"))\n\tuassert.True(t, strings.Contains(out, \"may call `Settle`\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSettle(cross(cur))\n\tout = Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"Settled\"))\n\tuassert.True(t, strings.Contains(out, \"Owed\"))\n}\n\nfunc TestGnotFormatting(t *testing.T) {\n\tuassert.Equal(t, \"0\", gnot(0))\n\tuassert.Equal(t, \"1\", gnot(1000000))\n\tuassert.Equal(t, \"1.5\", gnot(1500000))\n\tuassert.Equal(t, \"0.000001\", gnot(1))\n\tuassert.Equal(t, \"12.345678\", gnot(12345678))\n}\n"},{"name":"render.gno","body":"package lastwords\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\n// Render shows the slot, the clock and the money. The message is caller-typed\n// text, so it goes through ui.Inline: a stored string that renders as markdown\n// is a phishing link on a page nobody can edit, and this realm's whole product\n// is a string somebody else wrote.\nfunc Render(path string) string {\n\th := runtime.ChainHeight()\n\tvar b strings.Builder\n\n\tb.WriteString(\"# Last Words\\n\\n\")\n\n\tif message == \"\" {\n\t\tb.WriteString(\"_The slot is empty. Whoever writes last, writes forever._\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"\u003e \" + ui.Inline(message) + \"\\n\\n\")\n\t\tb.WriteString(\"by \" + ui.AddrOf(author.String()) + \", for \" + gnot(paid) + \" GNOT\\n\\n\")\n\t}\n\n\tclosed := clk.Expired(h)\n\tb.WriteString(\"## The clock\\n\\n\")\n\tif closed {\n\t\tb.WriteString(\"**Closed** at height \" + strconv.FormatInt(clk.Deadline(), 10) + \". \")\n\t\tif settled {\n\t\t\tb.WriteString(\"Settled: the pot has been credited, call `Withdraw` to sweep yours.\\n\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"Anyone may call `Settle` to split the pot.\\n\\n\")\n\t\t}\n\t} else {\n\t\tb.WriteString(\"Open for another **\" + strconv.FormatInt(clk.Remaining(h), 10) +\n\t\t\t\"** blocks, until height \" + strconv.FormatInt(clk.Deadline(), 10) + \".\\n\\n\")\n\t\tif clk.Final() {\n\t\t\tb.WriteString(\"This is the **last stretch**: the deadline has reached the hard end at \" +\n\t\t\t\tstrconv.FormatInt(clk.HardEnd(), 10) + \" and no write can move it again.\\n\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"Hard end at height \" + strconv.FormatInt(clk.HardEnd(), 10) +\n\t\t\t\t\". A write buys \" + strconv.FormatInt(BumpPct, 10) +\n\t\t\t\t\"% of the gap to it, never less than \" + strconv.FormatInt(Floor, 10) + \" blocks.\\n\\n\")\n\t\t}\n\t}\n\n\tb.WriteString(\"## The money\\n\\n\")\n\tb.WriteString(\"| | |\\n|---|---|\\n\")\n\tb.WriteString(\"| Pot | \" + gnot(pot) + \" GNOT |\\n\")\n\tb.WriteString(\"| Price of the next write | \" + gnot(Price(\"\")) + \" GNOT, plus \" +\n\t\tstrconv.FormatInt(PerByte, 10) + \" ugnot per byte |\\n\")\n\tb.WriteString(\"| Writes | \" + strconv.FormatInt(writes, 10) + \" |\\n\")\n\tb.WriteString(\"| Writers | \" + strconv.Itoa(len(order)) + \" |\\n\")\n\tb.WriteString(\"| Owed, unswept | \" + gnot(ledger.TotalOwed()) + \" GNOT |\\n\\n\")\n\n\tb.WriteString(\"The holder does **not** take the pot. It goes to everyone else who wrote, \")\n\tb.WriteString(\"pro rata to what they paid. Half of every payment is credited to the writer \")\n\tb.WriteString(\"it displaced, immediately.\\n\\n\")\n\n\tif !ledger.IsEmpty() {\n\t\tb.WriteString(\"## Owed\\n\\n| address | ugnot |\\n|---|---|\\n\")\n\t\tshown := 0\n\t\tledger.Iterate(func(payee string, amount int64) bool {\n\t\t\tb.WriteString(\"| \" + ui.AddrOf(payee) + \" | \" + strconv.FormatInt(amount, 10) + \" |\\n\")\n\t\t\tshown++\n\t\t\treturn shown \u003e= 20\n\t\t})\n\t\tb.WriteString(\"\\nCall `Withdraw` to sweep yours.\\n\")\n\t}\n\n\treturn b.String()\n}\n"}]},"send":"","max_deposit":"11000000ugnot"}],"fee":{"gas_wanted":"168297400","gas_fee":"504892ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"rkSm8TPop8Y0XWsmM3y1qSlxHUMyesne4m1n8AWZgk4sl4Izilc12Mg9VFhVWnA7qUImCRV2KfRyDzE5GYofCg=="}],"memo":""},"metadata":{"timestamp":"1790961512"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"grc20wrapdemo","path":"gno.land/r/moul/x/grc20wrapdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/grc20wrapdemo/v0`\n\n**A permissionless wrapper factory for GRC20 tokens.** Point it at any token\nregistered in [`r/nt/grc20reg`](https://gno.land/r/nt/grc20reg/v0) and it issues a\nnew one backed by it, with a personality you pick. Point it at two and it issues\na meta-token backed by both. No allowlist, no owner, and no authority over\nanybody's balance: every deposit is pulled with an allowance the holder granted.\n\n## Five minutes, start to finish\n\n```\n# 1. play money\nmaketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Claim\n\n# 2. let this realm pull your RED (the address is printed by Home(), and on the\n#    realm's own page)\nmaketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Approve \\\n  -args RED -args \u003cHome()\u003e -args 1000000\n\n# 3. create a wrapper over RED, and deposit into it\nmaketx call -pkgpath gno.land/r/moul/x/grc20wrapdemo/v0 -func NewWrapper \\\n  -args gno.land/r/moul/x/grc20faucet/v0.RED -args pool -args pRED\nmaketx call -pkgpath gno.land/r/moul/x/grc20wrapdemo/v0 -func Deposit \\\n  -args pRED -args 500000\n```\n\nStep 2 is the one people skip. Without it every `Deposit` fails with\n`insufficient allowance`, which is the system working.\n\n## Modes\n\n| mode | what the wrapped token does |\n|---|---|\n| `plain` | 1:1 custody receipt |\n| `kilo` | 1 underlying unit becomes 1000 wrapped, +3 decimals |\n| `soulbound` | wrap and unwrap freely, never transferable |\n| `pool` | shares in the escrow; `Donate` pays every holder at once |\n| `sticky` | `pool` plus a 1% exit fee, left behind for whoever stays |\n\nAnd `NewFusion(keyA, perA, keyB, perB, symbol)`, which bundles two registered\ntokens at a fixed proportion into one meta-token, `Fuse` in and `Defuse` out.\n\n## The parts worth reading the code for\n\n**`pool` is the entire yield-bearing-token pattern in two lines of arithmetic.**\n`Donate` adds escrow and mints nothing, so every outstanding share is worth more,\npermanently and for everyone at once. A fee sink, a staking reward and an airdrop\nto holders are the same operation seen from three angles.\n\n**`soulbound` binds users, not realms.** `MsgCall` cannot build the `realm`\nargument grc20's tellers need, so a signing account can only move the token\nthrough this realm's `Transfer`, where the veto lives. Another realm holding it\ncan always move its own balance. Non-transferable here means \"no user can pass it\non\", and the exit is always open: unwrap, and the underlying moves freely again.\n\n**Wrapping a wrapper works, and nothing special was needed to make it work.**\nEvery token this realm issues is itself registered in `grc20reg`, so its key feeds\nstraight back into `NewWrapper`. A pool over a plain wrap of RED is a good way to\nsee how thin the abstraction is.\n\n**Two wrappers over the same underlying share one escrow account** (this realm's\naddress), and are kept apart only by each vault's own `Held()` counter. `Escrow`\nreports that counter; the render page reports whether the account still covers it.\n\nBuilt on [`p/moul/x/grc20wrap`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/grc20wrap/v0),\nwhich is where the wrapping actually happens. This realm is the chain wiring and\na catalogue.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/grc20wrapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20wrapdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/grc20wrapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20wrapdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/grc20wrapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20wrapdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/grc20wrapdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/grc20wrapdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/grc20wrapdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/grc20wrapdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/grc20wrapdemo/v0\"\ngno = \"0.9\"\n\n# public: Wrap and Basket register the tokens they mint with r/nt/grc20reg,\n# so this realm's own objects have to be reachable from that one. Same\n# measured failure as r/moul/x/grc20faucet when the flag is flipped.\n"},{"name":"render.gno","body":"package grc20wrapdemo\n\nimport (\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderOne(path)\n}\n\nfunc renderIndex() string {\n\ts := \"# GRC20 wrapper factory\\n\\n\"\n\ts += \"Wrap any token registered in [grc20reg](/r/nt/grc20reg/v0) into a new one \"\n\ts += \"with a different personality, or fuse two into one. Permissionless: \"\n\ts += \"no allowlist, no owner, no authority over anybody's balance.\\n\\n\"\n\ts += ufmt.Sprintf(\"Escrow account to approve: `%s`\\n\\n\", home.String())\n\n\ts += \"## Modes\\n\\n\"\n\ts += \"| mode | what the wrapped token does |\\n\"\n\ts += \"|---|---|\\n\"\n\ts += \"| `plain` | 1:1 custody receipt |\\n\"\n\ts += \"| `kilo` | 1 underlying unit becomes 1000 wrapped, +3 decimals |\\n\"\n\ts += \"| `soulbound` | wrap and unwrap freely, never transferable |\\n\"\n\ts += \"| `pool` | shares in the escrow; `Donate` pays every holder at once |\\n\"\n\ts += \"| `sticky` | `pool` plus a 1% exit fee, left behind for whoever stays |\\n\"\n\ts += \"| `fusion` | one meta-token backed by a fixed bundle of two others |\\n\"\n\n\ts += \"\\n## Issued here\\n\\n\"\n\tif len(created) == 0 {\n\t\ts += \"Nothing yet. Be the first.\\n\"\n\t} else {\n\t\ts += \"| symbol | mode | backing | supply | registry key |\\n\"\n\t\ts += \"|---|---|---|---|---|\\n\"\n\t\tfor _, sym := range created {\n\t\t\te := must(sym)\n\t\t\ts += ufmt.Sprintf(\"| [%s](/r/moul/x/grc20wrapdemo/v0:%s) | %s | %s | %d | `%s` |\\n\",\n\t\t\t\te.symbol, e.symbol, e.mode, e.backing(), e.token().TotalSupply(), e.key)\n\t\t}\n\t}\n\n\ts += \"\\n## Try it\\n\\n\"\n\ts += \"Claim play money from [the faucet](/r/moul/x/grc20faucet/v0), let this realm\\n\"\n\ts += \"spend it, then wrap:\\n\\n\"\n\ts += \"```\\n\"\n\ts += \"# 1. get RED and BLUE\\n\"\n\ts += \"maketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Claim\\n\\n\"\n\ts += \"# 2. let this realm pull your RED\\n\"\n\ts += \"maketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Approve \\\\\\n\"\n\ts += ufmt.Sprintf(\"  -args RED -args %s -args 1000000\\n\\n\", home.String())\n\ts += \"# 3. create a pool wrapper over RED, then deposit into it\\n\"\n\ts += \"maketx call -pkgpath gno.land/r/moul/x/grc20wrapdemo/v0 -func NewWrapper \\\\\\n\"\n\ts += \"  -args gno.land/r/moul/x/grc20faucet/v0.RED -args pool -args pRED\\n\"\n\ts += \"maketx call -pkgpath gno.land/r/moul/x/grc20wrapdemo/v0 -func Deposit \\\\\\n\"\n\ts += \"  -args pRED -args 500000\\n\"\n\ts += \"```\\n\\n\"\n\ts += \"Built on [p/moul/x/grc20wrap](/p/moul/x/grc20wrap/v0).\\n\"\n\treturn s\n}\n\nfunc renderOne(symbol string) string {\n\te := byName.Get(symbol)\n\tif e == nil {\n\t\treturn \"# 404\\n\\nThis realm has not issued `\" + symbol + \"`.\\n\"\n\t}\n\ten := e.(*entry)\n\n\ts := ufmt.Sprintf(\"# %s\\n\\n\", en.symbol)\n\tif en.vault != nil {\n\t\ts += en.vault.Summary()\n\t} else {\n\t\ts += en.basket.Summary()\n\t}\n\ts += ufmt.Sprintf(\"\\n- mode: `%s`\\n\", en.mode)\n\ts += ufmt.Sprintf(\"- registry key: `%s`\\n\", en.key)\n\ts += ufmt.Sprintf(\"- created by: `%s` at block %d\\n\", en.creator.String(), en.height)\n\ts += \"\\n[back to the index](/r/moul/x/grc20wrapdemo/v0)\\n\"\n\treturn s\n}\n\n// backing names what an entry is redeemable for, for the index table.\nfunc (e *entry) backing() string {\n\tif e.vault != nil {\n\t\treturn e.vault.Underlying().GetSymbol()\n\t}\n\tout := \"\"\n\tfor i := 0; i \u003c e.basket.Legs(); i++ {\n\t\ttok, per, _ := e.basket.Leg(i)\n\t\tif i \u003e 0 {\n\t\t\tout += \" + \"\n\t\t}\n\t\tout += ufmt.Sprintf(\"%dx%s\", per, tok.GetSymbol())\n\t}\n\treturn out\n}\n"},{"name":"wrapdemo.gno","body":"// Package grc20wrapdemo is a permissionless wrapper factory for GRC20 tokens.\n//\n// Point it at any token registered in gno.land/r/nt/grc20reg/v0 and it issues a\n// new one backed by it, with a personality you pick from a list. Point it at two\n// and it issues a meta-token backed by both. Nothing is whitelisted, nothing is\n// owned, and the realm never gains authority over anybody's balance: every\n// deposit is pulled with an allowance the holder granted to this realm's address.\n//\n// The five wrapper modes, all from gno.land/p/moul/x/grc20wrap/v0:\n//\n//\tplain      1:1 custody. A receipt. The boring one that proves the rest works.\n//\tkilo       1 underlying unit becomes 1000 wrapped ones, +3 decimals.\n//\tsoulbound  wrap and unwrap freely, but the wrapped token never changes hands.\n//\tpool       shares in the escrow: Donate raises what every share redeems for.\n//\tsticky     pool, plus a 1% exit fee that stays behind for whoever holds on.\n//\n// And one fusion mode: NewFusion bundles two registered tokens at a fixed\n// proportion into a single meta-token, redeemable back into both.\n//\n// # Wrapping a wrapper\n//\n// Every token this realm issues is itself registered in grc20reg, so its key can\n// be fed straight back into NewWrapper or NewFusion. A pool over a kilo over a\n// plain wrap of RED is legal, works, and is a good way to see how thin the\n// abstraction really is.\n//\n// # The one thing a caller must do first\n//\n// Approve this realm's address on the underlying token, through THAT token's own\n// realm. Home() prints the address. Without it every Deposit fails with\n// \"insufficient allowance\", which is the system working.\n//\n// Play money to try it on: gno.land/r/moul/x/grc20faucet/v0.\npackage grc20wrapdemo\n\nimport (\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/x/grc20wrap/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\n// entry is one issued token: either a wrapper over a single underlying, or a\n// fusion over several. Exactly one of vault/basket is set.\ntype entry struct {\n\tsymbol  string\n\tmode    string\n\tkey     string // grc20reg key of the issued token\n\tvault   *grc20wrap.Vault\n\tbasket  *grc20wrap.Basket\n\tcreator address\n\theight  int64\n}\n\nvar (\n\tids     seqid.ID\n\tbyName  = avl.NewTree() // symbol -\u003e *entry\n\tcreated []string        // symbols, in creation order, for a stable Render\n\thome    address         // this realm's address: the escrow account\n)\n\nfunc init(cur realm) {\n\thome = cur.Address()\n}\n\n// Home is the address to approve on an underlying token before depositing. It\n// is where every escrow this realm holds actually sits.\nfunc Home() address { return home }\n\n// NewWrapper issues a token wrapping `tokenKey`, a key in grc20reg, under the\n// given mode, and registers it. It returns the new token's own registry key.\n//\n// `symbol` is yours to choose, must be unique in this realm, and follows the\n// GRC20 rules: 1 to 11 characters of [A-Za-z0-9_-].\nfunc NewWrapper(cur realm, tokenKey, mode, symbol string) string {\n\twho := caller(cur)\n\tunder := grc20reg.MustGet(tokenKey)\n\trequireFree(symbol)\n\n\tpol, extraDecimals := modePolicy(mode)\n\tdecimals := under.GetDecimals() + extraDecimals\n\tif decimals \u003e 18 {\n\t\tpanic(ufmt.Sprintf(\"%s already has %d decimals; mode %q would need %d, over the GRC20 limit of 18\",\n\t\t\tunder.GetSymbol(), under.GetDecimals(), mode, decimals))\n\t}\n\tname := ufmt.Sprintf(\"%s (%s wrap of %s)\", symbol, mode, under.GetSymbol())\n\n\tv := grc20wrap.NewVault(under, pol, name, symbol, decimals, ids.Next(), cur)\n\tkey := grc20reg.Register(cross(cur), v.Token(), \"\")\n\trecord(\u0026entry{\n\t\tsymbol:  symbol,\n\t\tmode:    mode,\n\t\tkey:     key,\n\t\tvault:   v,\n\t\tcreator: who,\n\t\theight:  runtime.ChainHeight(),\n\t})\n\treturn key\n}\n\n// NewFusion issues a meta-token backed by two registered tokens at a fixed\n// proportion: one smallest unit of the meta-token is always worth `perA`\n// smallest units of A plus `perB` of B. It returns the new token's registry key.\n//\n// The proportion never changes, and the meta-token is minted and burned only\n// against the real thing, so it cannot drift from its backing or be arbitraged.\n// What it can do is make the pair one transferable object.\nfunc NewFusion(cur realm, keyA string, perA int64, keyB string, perB int64, symbol string) string {\n\twho := caller(cur)\n\ta := grc20reg.MustGet(keyA)\n\tb := grc20reg.MustGet(keyB)\n\trequireFree(symbol)\n\n\tdecimals := a.GetDecimals()\n\tif b.GetDecimals() \u003e decimals {\n\t\tdecimals = b.GetDecimals()\n\t}\n\tname := ufmt.Sprintf(\"%s (%s+%s fusion)\", symbol, a.GetSymbol(), b.GetSymbol())\n\n\tbk := grc20wrap.NewBasket(\n\t\t[]*grc20.Token{a, b},\n\t\t[]int64{perA, perB},\n\t\tname, symbol, decimals, ids.Next(), cur,\n\t)\n\tkey := grc20reg.Register(cross(cur), bk.Token(), \"\")\n\trecord(\u0026entry{\n\t\tsymbol:  symbol,\n\t\tmode:    \"fusion\",\n\t\tkey:     key,\n\t\tbasket:  bk,\n\t\tcreator: who,\n\t\theight:  runtime.ChainHeight(),\n\t})\n\treturn key\n}\n\n// Deposit escrows `amount` of the underlying and mints `symbol` to the caller.\n// It returns how much was minted, which is not `amount` unless the mode is\n// plain. Approve Home() on the underlying first.\nfunc Deposit(cur realm, symbol string, amount int64) int64 {\n\twho := caller(cur)\n\tout, err := mustVault(symbol).Wrap(0, cur, who, amount)\n\tcheckErr(err)\n\treturn out\n}\n\n// Withdraw burns `amount` of `symbol` and returns the underlying to the caller.\n// It returns how much came back.\nfunc Withdraw(cur realm, symbol string, amount int64) int64 {\n\twho := caller(cur)\n\tout, err := mustVault(symbol).Unwrap(0, cur, who, amount)\n\tcheckErr(err)\n\treturn out\n}\n\n// Donate escrows `amount` of the underlying for `symbol` and mints nothing.\n//\n// Under a pool or sticky mode this is a gift to every current holder at once,\n// and it is irreversible: there is no share to redeem it with. Under any other\n// mode it is a gift to nobody, since the rate ignores the escrow.\nfunc Donate(cur realm, symbol string, amount int64) {\n\twho := caller(cur)\n\tcheckErr(mustVault(symbol).Donate(0, cur, who, amount))\n}\n\n// Fuse escrows every leg of `symbol` and mints `units` of it to the caller.\n// Approve Home() on BOTH legs first.\nfunc Fuse(cur realm, symbol string, units int64) {\n\twho := caller(cur)\n\tcheckErr(mustBasket(symbol).Fuse(0, cur, who, units))\n}\n\n// Defuse burns `units` of `symbol` and returns every leg to the caller.\nfunc Defuse(cur realm, symbol string, units int64) {\n\twho := caller(cur)\n\tcheckErr(mustBasket(symbol).Defuse(0, cur, who, units))\n}\n\n// Transfer moves the caller's own units of `symbol`. A soulbound wrapper\n// refuses here, and nowhere else.\nfunc Transfer(cur realm, symbol string, to address, amount int64) {\n\twho := caller(cur)\n\te := must(symbol)\n\tif e.vault != nil {\n\t\tcheckErr(e.vault.Move(who, to, amount))\n\t\treturn\n\t}\n\tcheckErr(e.basket.Move(who, to, amount))\n}\n\n// Approve lets `spender` draw `amount` of `symbol` from the caller's balance.\nfunc Approve(cur realm, symbol string, spender address, amount int64) {\n\twho := caller(cur)\n\te := must(symbol)\n\tif e.vault != nil {\n\t\tcheckErr(e.vault.Allow(who, spender, amount))\n\t\treturn\n\t}\n\tcheckErr(e.basket.Allow(who, spender, amount))\n}\n\n// TransferFrom spends an allowance the caller was granted on `symbol`.\nfunc TransferFrom(cur realm, symbol string, from, to address, amount int64) {\n\twho := caller(cur)\n\te := must(symbol)\n\tif e.vault != nil {\n\t\tcheckErr(e.vault.MoveFrom(who, from, to, amount))\n\t\treturn\n\t}\n\tcheckErr(e.basket.MoveFrom(who, from, to, amount))\n}\n\n// Key returns the grc20reg key of the token this realm issued as `symbol`.\nfunc Key(symbol string) string { return must(symbol).key }\n\n// TotalSupply returns how much of `symbol` is outstanding.\nfunc TotalSupply(symbol string) int64 { return must(symbol).token().TotalSupply() }\n\n// BalanceOf returns `owner`'s balance of `symbol`.\nfunc BalanceOf(symbol string, owner address) int64 {\n\treturn must(symbol).token().BalanceOf(owner)\n}\n\n// Allowance returns what `owner` let `spender` draw of `symbol`.\nfunc Allowance(symbol string, owner, spender address) int64 {\n\treturn must(symbol).token().Allowance(owner, spender)\n}\n\n// Escrow returns the underlying escrowed behind a wrapper.\nfunc Escrow(symbol string) int64 { return mustVault(symbol).Held() }\n\n// Legs returns how many components a fusion has.\nfunc Legs(symbol string) int { return mustBasket(symbol).Legs() }\n\n// Leg describes the i-th component of a fusion: its symbol, the units escrowed\n// per meta unit, and the units escrowed so far.\nfunc Leg(symbol string, i int) (string, int64, int64) {\n\ttok, per, held := mustBasket(symbol).Leg(i)\n\treturn tok.GetSymbol(), per, held\n}\n\n// Count is how many tokens this realm has issued.\nfunc Count() int { return len(created) }\n\n// internals\n//\n\n// modePolicy maps a mode name to its policy and to the extra decimals the\n// wrapped token needs to represent the same value.\nfunc modePolicy(mode string) (grc20wrap.Policy, int) {\n\tswitch mode {\n\tcase \"plain\":\n\t\treturn grc20wrap.OneToOne{}, 0\n\tcase \"kilo\":\n\t\treturn grc20wrap.Ratio{Num: 1_000, Den: 1}, 3\n\tcase \"soulbound\":\n\t\treturn grc20wrap.Soulbound{}, 0\n\tcase \"pool\":\n\t\treturn grc20wrap.Pool{}, 0\n\tcase \"sticky\":\n\t\treturn grc20wrap.Fee{Base: grc20wrap.Pool{}, UnwrapBPS: 100}, 0\n\t}\n\tpanic(\"unknown mode \" + mode + \" (plain, kilo, soulbound, pool, sticky)\")\n}\n\nfunc (e *entry) token() *grc20.Token {\n\tif e.vault != nil {\n\t\treturn e.vault.Token()\n\t}\n\treturn e.basket.Token()\n}\n\nfunc record(e *entry) {\n\tbyName.Set(e.symbol, e)\n\tcreated = append(created, e.symbol)\n}\n\nfunc requireFree(symbol string) {\n\tif byName.Has(symbol) {\n\t\tpanic(\"symbol \" + symbol + \" is already issued by this realm\")\n\t}\n}\n\nfunc must(symbol string) *entry {\n\te := byName.Get(symbol)\n\tif e == nil {\n\t\tpanic(\"this realm has not issued \" + symbol)\n\t}\n\treturn e.(*entry)\n}\n\nfunc mustVault(symbol string) *grc20wrap.Vault {\n\te := must(symbol)\n\tif e.vault == nil {\n\t\tpanic(symbol + \" is a fusion; use Fuse and Defuse\")\n\t}\n\treturn e.vault\n}\n\nfunc mustBasket(symbol string) *grc20wrap.Basket {\n\te := must(symbol)\n\tif e.basket == nil {\n\t\tpanic(symbol + \" is a wrapper; use Deposit and Withdraw\")\n\t}\n\treturn e.basket\n}\n\n// caller is the account or realm that crossed into this one. Every deposit is\n// escrowed from, and every mint credited to, exactly this address.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"grc20wrapdemo: stale realm token\")\n\t}\n\treturn cur.Previous().Address()\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"},{"name":"wrapdemo_test.gno","body":"package grc20wrapdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\tfaucet \"gno.land/r/moul/x/grc20faucet/v0\"\n)\n\n// Realm state carries over between test functions, but the block height does\n// not: every test starts from the same height. The faucet's per-account\n// cooldown would therefore fire on the second test to reuse an account, so each\n// test claims with its own. TestFaucetCooldown covers the cooldown itself.\nfunc fund(cur realm, t *testing.T, name string) address {\n\tt.Helper()\n\twho := testutils.TestAddress(name)\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tfaucet.Claim(cross(cur))\n\tfaucet.Approve(cross(cur), \"RED\", Home(), faucet.ClaimAmount)\n\tfaucet.Approve(cross(cur), \"BLUE\", Home(), faucet.ClaimAmount)\n\treturn who\n}\n\n// testing.SetRealm only governs crossing calls made from the frame that called\n// it: put it in a helper with no crossing call of its own and it is silently\n// ignored, and the caller stays whoever it was. fund() gets away with it\n// because it crosses into the faucet right after; switching accounts mid-test\n// has to be written inline, which is why there is no act() helper here.\n\n// The plain mode is the baseline: it proves custody actually crosses a realm\n// boundary. The RED never belonged to this realm, and it can only ever take\n// what the faucet's Approve handed over.\nfunc TestPlainWrapperRoundTrip(cur realm, t *testing.T) {\n\talice := fund(cur, t, \"w-alice\")\n\tbefore := faucet.BalanceOf(\"RED\", alice)\n\n\tkey := NewWrapper(cross(cur), faucet.RedKey, \"plain\", \"wRED\")\n\tuassert.True(t, strings.HasSuffix(key, \".wRED\"), \"registered under its own symbol: \"+key)\n\n\tminted := Deposit(cross(cur), \"wRED\", 400_000)\n\tuassert.Equal(t, int64(400_000), minted)\n\tuassert.Equal(t, int64(400_000), BalanceOf(\"wRED\", alice))\n\tuassert.Equal(t, int64(400_000), Escrow(\"wRED\"))\n\tuassert.Equal(t, before-400_000, faucet.BalanceOf(\"RED\", alice))\n\t// The escrow really sits at this realm's address, in the faucet's ledger.\n\tuassert.Equal(t, int64(400_000), faucet.BalanceOf(\"RED\", Home()))\n\n\tback := Withdraw(cross(cur), \"wRED\", 150_000)\n\tuassert.Equal(t, int64(150_000), back)\n\tuassert.Equal(t, int64(250_000), TotalSupply(\"wRED\"))\n\tuassert.Equal(t, before-250_000, faucet.BalanceOf(\"RED\", alice))\n}\n\n// Depositing without an allowance is the default state of the world, and it\n// fails. This realm holds no standing authority over anybody's balance.\nfunc TestDepositNeedsAnAllowance(cur realm, t *testing.T) {\n\tfund(cur, t, \"noallow\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"plain\", \"noallow\")\n\n\t// Revoke what fund() granted.\n\tfaucet.Approve(cross(cur), \"RED\", Home(), 0)\n\tuassert.AbortsContains(t, cur, \"insufficient allowance\", func() {\n\t\tDeposit(cross(cur), \"noallow\", 1)\n\t})\n\tuassert.Equal(t, int64(0), TotalSupply(\"noallow\"))\n}\n\n// kilo re-denominates a token whose own realm will never redeploy for it.\nfunc TestKiloWrapperAddsThreeDecimals(cur realm, t *testing.T) {\n\tfund(cur, t, \"kilo\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"kilo\", \"kRED\")\n\n\tminted := Deposit(cross(cur), \"kRED\", 1_000)\n\tuassert.Equal(t, int64(1_000_000), minted)\n\tuassert.Equal(t, int64(1_000), Escrow(\"kRED\"))\n\n\tback := Withdraw(cross(cur), \"kRED\", 999_000)\n\tuassert.Equal(t, int64(999), back)\n\t// 999 wrapped units cannot buy back a whole underlying one, so the\n\t// redemption is refused rather than burning them for nothing.\n\tuassert.AbortsContains(t, cur, \"rounds to zero\", func() {\n\t\tWithdraw(cross(cur), \"kRED\", 999)\n\t})\n}\n\nfunc TestSoulboundWrapperRefusesTransfer(cur realm, t *testing.T) {\n\tfund(cur, t, \"soul\")\n\tbob := testutils.TestAddress(\"soul-bob\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"soulbound\", \"sRED\")\n\tDeposit(cross(cur), \"sRED\", 300_000)\n\n\tuassert.AbortsContains(t, cur, \"soulbound\", func() {\n\t\tTransfer(cross(cur), \"sRED\", bob, 1)\n\t})\n\tuassert.Equal(t, int64(0), BalanceOf(\"sRED\", bob))\n\n\t// The exit stays open: unwrap, and the RED moves as freely as ever.\n\tback := Withdraw(cross(cur), \"sRED\", 300_000)\n\tuassert.Equal(t, int64(300_000), back)\n\tuassert.Equal(t, int64(0), TotalSupply(\"sRED\"))\n}\n\n// Pool: a donation is shared by whoever is holding, and the donor can never\n// take it back out.\nfunc TestPoolWrapperSharesDonations(cur realm, t *testing.T) {\n\talice := fund(cur, t, \"pool-a\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"pool\", \"pRED\")\n\tuassert.Equal(t, int64(100_000), Deposit(cross(cur), \"pRED\", 100_000))\n\n\tbob := fund(cur, t, \"pool-b\")\n\tDonate(cross(cur), \"pRED\", 100_000)\n\tuassert.Equal(t, int64(200_000), Escrow(\"pRED\"))\n\tuassert.Equal(t, int64(100_000), TotalSupply(\"pRED\"))\n\tuassert.Equal(t, int64(0), BalanceOf(\"pRED\", bob)) // a donation mints nothing\n\n\t// Buying in afterwards costs twice as much per share.\n\tuassert.Equal(t, int64(50_000), Deposit(cross(cur), \"pRED\", 100_000))\n\n\t// alice walks away with double what she put in.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tredBefore := faucet.BalanceOf(\"RED\", alice)\n\tuassert.Equal(t, int64(200_000), Withdraw(cross(cur), \"pRED\", 100_000))\n\tuassert.Equal(t, redBefore+200_000, faucet.BalanceOf(\"RED\", alice))\n\n\t// And bob gets back exactly the 100_000 he deposited: his own donation\n\t// was to the holders, and by then that was alice.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.Equal(t, int64(100_000), Withdraw(cross(cur), \"pRED\", 50_000))\n\tuassert.Equal(t, int64(0), Escrow(\"pRED\"))\n}\n\n// Sticky: the 1% exit fee is collected by nobody, it is left in the pool, so\n// whoever stays longest ends up with it.\nfunc TestStickyWrapperChargesOnTheWayOut(cur realm, t *testing.T) {\n\talice := fund(cur, t, \"stick-a\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"sticky\", \"fRED\")\n\tDeposit(cross(cur), \"fRED\", 500_000)\n\n\tbob := fund(cur, t, \"stick-b\")\n\tDeposit(cross(cur), \"fRED\", 500_000)\n\tuassert.Equal(t, int64(1_000_000), TotalSupply(\"fRED\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.Equal(t, int64(495_000), Withdraw(cross(cur), \"fRED\", 500_000))\n\n\t// The 5_000 alice paid on the way out now backs bob's shares.\n\tuassert.Equal(t, int64(505_000), Escrow(\"fRED\"))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.Equal(t, int64(499_950), Withdraw(cross(cur), \"fRED\", 500_000))\n}\n\n// Fusion: one token backed by a fixed bundle of two, and nothing else.\nfunc TestFusionOfRedAndBlue(cur realm, t *testing.T) {\n\talice := fund(cur, t, \"fuse-a\")\n\tbob := testutils.TestAddress(\"fuse-b\")\n\n\tkey := NewFusion(cross(cur), faucet.RedKey, 1, faucet.BlueKey, 2, \"PURPLE\")\n\tuassert.True(t, strings.HasSuffix(key, \".PURPLE\"), key)\n\tuassert.Equal(t, 2, Legs(\"PURPLE\"))\n\n\tredBefore := faucet.BalanceOf(\"RED\", alice)\n\tblueBefore := faucet.BalanceOf(\"BLUE\", alice)\n\tFuse(cross(cur), \"PURPLE\", 100_000)\n\n\tuassert.Equal(t, int64(100_000), BalanceOf(\"PURPLE\", alice))\n\tuassert.Equal(t, redBefore-100_000, faucet.BalanceOf(\"RED\", alice))\n\tuassert.Equal(t, blueBefore-200_000, faucet.BalanceOf(\"BLUE\", alice))\n\n\tsym, per, held := Leg(\"PURPLE\", 1)\n\tuassert.Equal(t, \"BLUE\", sym)\n\tuassert.Equal(t, int64(2), per)\n\tuassert.Equal(t, int64(200_000), held)\n\n\t// PURPLE moves as one object, and whoever ends up with it can split it\n\t// back into both legs without ever having touched the faucet.\n\tTransfer(cross(cur), \"PURPLE\", bob, 40_000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tDefuse(cross(cur), \"PURPLE\", 40_000)\n\tuassert.Equal(t, int64(40_000), faucet.BalanceOf(\"RED\", bob))\n\tuassert.Equal(t, int64(80_000), faucet.BalanceOf(\"BLUE\", bob))\n\tuassert.Equal(t, int64(60_000), TotalSupply(\"PURPLE\"))\n}\n\n// Every token issued here is registered too, so it can be wrapped again.\nfunc TestWrappingAWrapper(cur realm, t *testing.T) {\n\tfund(cur, t, \"nest\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"plain\", \"nRED\")\n\tDeposit(cross(cur), \"nRED\", 800_000)\n\n\t// nRED lives in THIS realm, so the allowance is granted through this\n\t// realm's own Approve. Same shape, one level up.\n\tNewWrapper(cross(cur), Key(\"nRED\"), \"pool\", \"nnRED\")\n\tApprove(cross(cur), \"nRED\", Home(), 800_000)\n\tuassert.Equal(t, int64(600_000), Deposit(cross(cur), \"nnRED\", 600_000))\n\n\t// The outer wrapper escrows the inner token, not the RED.\n\tuassert.Equal(t, int64(600_000), Escrow(\"nnRED\"))\n\tuassert.Equal(t, int64(800_000), Escrow(\"nRED\"))\n\tuassert.Equal(t, int64(600_000), BalanceOf(\"nRED\", Home()))\n\n\t// And it unwinds the whole way back down.\n\tuassert.Equal(t, int64(600_000), Withdraw(cross(cur), \"nnRED\", 600_000))\n\tuassert.Equal(t, int64(800_000), Withdraw(cross(cur), \"nRED\", 800_000))\n\tuassert.Equal(t, int64(0), TotalSupply(\"nRED\"))\n}\n\nfunc TestAllowanceOnAWrappedToken(cur realm, t *testing.T) {\n\talice := fund(cur, t, \"allow-a\")\n\tbob := testutils.TestAddress(\"allow-b\")\n\n\tNewWrapper(cross(cur), faucet.RedKey, \"plain\", \"aRED\")\n\tDeposit(cross(cur), \"aRED\", 500_000)\n\tApprove(cross(cur), \"aRED\", bob, 120_000)\n\tuassert.Equal(t, int64(120_000), Allowance(\"aRED\", alice, bob))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tTransferFrom(cross(cur), \"aRED\", alice, bob, 120_000)\n\tuassert.Equal(t, int64(120_000), BalanceOf(\"aRED\", bob))\n\tuassert.AbortsContains(t, cur, \"insufficient allowance\", func() {\n\t\tTransferFrom(cross(cur), \"aRED\", alice, bob, 1)\n\t})\n}\n\nfunc TestFaucetCooldown(cur realm, t *testing.T) {\n\twho := fund(cur, t, \"cooldown\")\n\tuassert.AbortsContains(t, cur, \"too soon\", func() {\n\t\tfaucet.Claim(cross(cur))\n\t})\n\n\tnext, ok := faucet.NextClaim(who)\n\tuassert.True(t, ok, \"the account has claimed once\")\n\ttesting.SkipHeights(faucet.ClaimEvery + 1)\n\tfaucet.Claim(cross(cur))\n\tuassert.Equal(t, 2*faucet.ClaimAmount, faucet.BalanceOf(\"RED\", who))\n\tuassert.True(t, next \u003e 0, \"a cooldown was recorded\")\n\n\t_, ok = faucet.NextClaim(testutils.TestAddress(\"never\"))\n\tuassert.False(t, ok, \"an account that never claimed has no cooldown\")\n}\n\nfunc TestRejectsBadInput(cur realm, t *testing.T) {\n\tfund(cur, t, \"bad\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"plain\", \"xRED\")\n\tNewFusion(cross(cur), faucet.RedKey, 1, faucet.BlueKey, 1, \"xMIX\")\n\n\tuassert.AbortsContains(t, cur, \"unknown mode\", func() {\n\t\tNewWrapper(cross(cur), faucet.RedKey, \"moon\", \"xMOON\")\n\t})\n\tuassert.AbortsContains(t, cur, \"already issued by this realm\", func() {\n\t\tNewWrapper(cross(cur), faucet.RedKey, \"plain\", \"xRED\")\n\t})\n\tuassert.AbortsContains(t, cur, \"unknown token\", func() {\n\t\tNewWrapper(cross(cur), \"gno.land/r/nope/nope.NOPE\", \"plain\", \"xNOPE\")\n\t})\n\tuassert.AbortsContains(t, cur, \"is a fusion\", func() {\n\t\tDeposit(cross(cur), \"xMIX\", 1)\n\t})\n\tuassert.AbortsContains(t, cur, \"is a wrapper\", func() {\n\t\tFuse(cross(cur), \"xRED\", 1)\n\t})\n\tuassert.AbortsContains(t, cur, \"has not issued\", func() {\n\t\tDeposit(cross(cur), \"GHOST\", 1)\n\t})\n\tuassert.AbortsContains(t, cur, \"unknown symbol\", func() {\n\t\tfaucet.Transfer(cross(cur), \"GREEN\", Home(), 1)\n\t})\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\tfund(cur, t, \"render\")\n\tNewWrapper(cross(cur), faucet.RedKey, \"pool\", \"rRED\")\n\tDeposit(cross(cur), \"rRED\", 250_000)\n\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"# GRC20 wrapper factory\"), \"index heading\")\n\tuassert.True(t, strings.Contains(index, Home().String()), \"index shows the escrow address\")\n\tuassert.True(t, strings.Contains(index, \"| [rRED](/r/moul/x/grc20wrapdemo/v0:rRED) | pool | RED |\"),\n\t\t\"index lists the wrapper:\\n\"+index)\n\n\tdetail := Render(\"rRED\")\n\tuassert.True(t, strings.Contains(detail, \"escrowed underlying: 250000\"), detail)\n\tuassert.True(t, strings.Contains(detail, \"- mode: `pool`\"), detail)\n\tuassert.True(t, strings.Contains(detail, \"solvent: yes\"), detail)\n\n\tuassert.True(t, strings.Contains(Render(\"NOPE\"), \"404\"), \"unknown symbol renders a 404\")\n}\n"}]},"send":"","max_deposit":"13000000ugnot"}],"fee":{"gas_wanted":"90429000","gas_fee":"271287ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"GUldom8KM6viVBn5SkkizYjefnq8Gs1X59yPk/DilRxLRBRJgKgd3XrUThxx+AlZtMCqvKhCpPCyMUQxAnB8Tg=="}],"memo":""},"metadata":{"timestamp":"1790961512"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"tP/0ikgupV6lKw6WPouerYXUHYDx24GQ+fwqW6uWUpElrJMrz87ETdFbkBLLsrdLrUd6vpZ+AxD5F4HXgtRHbg=="}],"memo":""},"metadata":{"timestamp":"1790961513"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"kitindexdemo","path":"gno.land/r/moul/x/kitindexdemo/v0","files":[{"name":"README.md","body":"# kitindexdemo\n\nA notes board whose only job is to show\n[`p/moul/kit/index`](../../../../p/moul/kit/index) doing the thing a realm with\na store always ends up needing: answering \"every note tagged `gno`\" as cheaply\nas it answers \"note 7\".\n\nNo logic of its own. The records are a [`kit/store`](../../../../p/moul/kit/store),\nthe two lookups are `kit/index`, the page is [`kit/ui`](../../../../p/moul/kit/ui).\n\n## What is worth reading\n\n**Every write touches the store and both indexes in ONE function.** That is the\nentire correctness argument for keeping three containers apart instead of\nreaching for a multi-index store: an abort anywhere in `Post` leaves none of the\nthree applied, and `Retract` unwinds all three together.\n\n**The tag is validated at write time, the body is escaped at render time**, and\nthe difference is the point. A tag is also an index key and a path segment, so a\ntag carrying a pipe or a slash breaks the table and the URL as well as the\nsentence; `[a-z0-9-]`, checked once, is narrower and cheaper than escaping it in\nthree places. A body is prose, so it goes through `ui.Cell` at the one call site\nthat renders it.\n\n**The root page is pinned with `uassert.Equal`, not an example.** It carries two\nconsecutive blank lines, and an `// Output:` block can never pin those: gno\ncollapses them, exactly as Go does. The pages without that shape get an\n`ExampleRender`.\n\n## Pages\n\n| path | shows |\n|---|---|\n| `` | every tag with its count, paged |\n| `tag/\u003ctag\u003e` | the notes under one tag |\n| `author/\u003caddress\u003e` | the notes by one address |\n\n## Functions\n\n| | |\n|---|---|\n| `Post(cur, tag, body) int64` | files a note, returns its id |\n| `Retract(cur, id)` | removes one, author only |\n\n`MaxBody` is 280 bytes and `MaxTagLen` is 24, because every byte stored locks a\nstorage deposit this realm's address pays and an unbounded write is an unbounded\nbill a stranger chooses the size of.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/kitindexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/kitindexdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/kitindexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/kitindexdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/kitindexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/kitindexdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/kitindexdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/kitindexdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/kitindexdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/kitindexdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"example_test.gno","body":"package kitindexdemo\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// seed builds a fixed board without crossing anything, so an example can set up\n// its own state.\n//\n// An Example has no realm token, so it cannot call Post, and the state the\n// tests happen to leave is not a contract. Writing the globals directly is the\n// escape hatch AGENTS.md names: same package, no crossing, fully deterministic.\nfunc seed() {\n\treset()\n\tadd := func(who address, tag, body string, height int64) {\n\t\tid := notes.Add(\u0026note{Author: who, Tag: tag, Body: body, Height: height})\n\t\tif err := byTag.Add(tag, id); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif err := byAuthor.Add(who.String(), id); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tadd(alice, \"gno\", \"the index is two containers and one function\", 123)\n\tadd(bob, \"gno\", \"and the function is where the correctness is\", 124)\n\tadd(alice, \"storage\", \"you are charged for objects, not for data\", 125)\n}\n\n// The root page carries TWO consecutive blank lines, which an // Output: block\n// can never pin: gno collapses them, exactly as Go does. So the root is\n// asserted with uassert.Equal and a backtick literal, which preserves them,\n// and only the pages without that shape get an Example.\n//\n// This is the order of preference AGENTS.md names, and the root page is the\n// case that forces the second rung.\nfunc TestRenderRoot(t *testing.T) {\n\tseed()\n\twant := `# Notes by tag\n\n3 note(s) under 2 tag(s), by 2 author(s).\n\n\n| tag | notes |\n| --- | --- |\n| [gno](/r/moul/x/kitindexdemo/v0:tag/gno) | 2 |\n| [storage](/r/moul/x/kitindexdemo/v0:tag/storage) | 1 |\n\n[Post a note](/r/moul/x/kitindexdemo/v0$help\u0026func=Post\u0026body=\u0026tag=)\n\n`\n\tuassert.Equal(t, want, Render(\"\"))\n}\n\n// ExampleRender_tag pins one tag's page, which is the lookup the library is for.\nfunc ExampleRender_tag() {\n\tseed()\n\tprint(Render(\"tag/gno\"))\n\t// Output:\n\t// # #gno\n\t// | # | author | tag | note | height |\n\t// | --- | --- | --- | --- | --- |\n\t// | 1 | `g1v9kxjc…40gh` | `gno` | the index is two containers and one function | 123 |\n\t// | 2 | `g1vfhkyh…vdhu` | `gno` | and the function is where the correctness is | 124 |\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/kitindexdemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"kitindexdemo.gno","body":"// untrusted-render: the tag is charset-checked to [a-z0-9-] at write time and\n// is the only stored string interpolated raw; the body is a caller's text and\n// goes through ui.Cell at every call site that renders it.\n\n// Package kitindexdemo is a notes board whose only job is to show\n// gno.land/p/moul/kit/index doing the thing a realm with a store always ends\n// up needing: answering \"every note tagged gno\" as cheaply as it answers\n// \"note 7\".\n//\n// There is no logic of its own here. The records are a kit/store, the two\n// lookups are kit/index, the page is kit/ui, and what is worth reading is the\n// shape: every write touches the store and both indexes in ONE function, which\n// is the entire correctness argument for keeping them in separate containers.\n//\n// Demo of the p/moul/kit/index library.\npackage kitindexdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/index/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\n// MaxBody is the longest note this realm accepts, in bytes.\n//\n// A bound rather than none: every byte stored here locks a storage deposit,\n// paid by whoever signs the write and refunded to whoever signs the delete\n// (EFFECTIVE_GNO.md section 9.2), and an unbounded write is an unbounded\n// state the realm carries forever.\nconst MaxBody = 280\n\n// MaxTagLen bounds the index key for the same reason, and small because a tag\n// is a label rather than a sentence.\nconst MaxTagLen = 24\n\n// PageSize is how many tags the root page shows.\nconst PageSize = 20\n\n// MaxNotes and MaxPerAuthor bound the WHOLE board, which MaxBody does not.\n//\n// A per-call length limit bounds one write and nothing else: a caller posting\n// one-byte notes in a loop grows the store and both indexes without limit. \"An unbounded container a third party can grow is an\n// unbounded storage deposit someone is paying for\" is a rule this realm exists\n// to demonstrate, so it had better obey it.\n//\n// Two caps rather than one, and what each buys is narrower than it looks.\n// MaxNotes bounds the state, which is the property this realm promises.\n// MaxPerAuthor stops one ADDRESS, not one actor: addresses are free, so fifty\n// fresh ones at twenty notes each still fill the board and lock everyone else\n// out until somebody retracts. Keeping a board open to strangers needs\n// something a griefer cannot mint for free, a deposit or an expiry, which this\n// demo does not carry. Retracting frees a slot, so neither cap is a one-way door.\n//\n// MaxPerAuthor is answered by byAuthor.Count, which is the index doing the job\n// it was added for.\nconst (\n\tMaxNotes     = 1000\n\tMaxPerAuthor = 20\n)\n\ntype note struct {\n\tAuthor address\n\tTag    string\n\tBody   string\n\tHeight int64\n}\n\nvar (\n\tnotes    = store.Named(\"note\")\n\tbyTag    index.Index\n\tbyAuthor index.Index\n)\n\n// Post files a note under a tag and returns its id.\n//\n// The store write and both index writes happen here, in this order, in one\n// frame. An abort anywhere in it leaves none of them applied, which is what\n// makes three containers safe to keep apart.\nfunc Post(cur realm, tag, body string) int64 {\n\twho := caller(cur)\n\ttag = normaliseTag(tag)\n\tassertBody(body)\n\tassertRoom(who)\n\n\tid := notes.Add(\u0026note{\n\t\tAuthor: who,\n\t\tTag:    tag,\n\t\tBody:   body,\n\t\tHeight: runtime.ChainHeight(),\n\t})\n\tmustIndex(byTag.Add(tag, id))\n\tmustIndex(byAuthor.Add(who.String(), id))\n\treturn int64(id)\n}\n\n// Retract removes a note. Only its author may, and the store and both indexes\n// are unwound together.\nfunc Retract(cur realm, id int64) {\n\twho := caller(cur)\n\tsid, ok := store.ParseID(strconv.FormatInt(id, 10))\n\tif !ok {\n\t\tpanic(\"kitindexdemo: not an id: \" + strconv.FormatInt(id, 10))\n\t}\n\tn, ok := notes.Get(sid)\n\tif !ok {\n\t\tpanic(\"kitindexdemo: note #\" + sid.String() + \" not found\")\n\t}\n\trec := n.(*note)\n\tif rec.Author != who {\n\t\tpanic(\"kitindexdemo: note #\" + sid.String() + \" is not yours\")\n\t}\n\tnotes.Remove(sid)\n\tbyTag.Remove(rec.Tag, sid)\n\tbyAuthor.Remove(rec.Author.String(), sid)\n}\n\n// caller is the one place this realm decides who is acting: the realm token is\n// checked before it is walked, because an unchecked token is not a caller.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"kitindexdemo: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n\nfunc mustIndex(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// normaliseTag lowercases and validates the tag.\n//\n// Validated at WRITE time rather than escaped at render time, deliberately: a\n// tag is also an index key and a path segment, so a tag that could carry a\n// pipe or a slash would break the table and the URL as well as the page. The\n// charset is the narrowest thing that still reads as a label.\nfunc normaliseTag(tag string) string {\n\ttag = strings.ToLower(strings.TrimSpace(tag))\n\tif tag == \"\" || len(tag) \u003e MaxTagLen {\n\t\tpanic(\"kitindexdemo: a tag is 1 to \" + strconv.Itoa(MaxTagLen) + \" characters\")\n\t}\n\tfor _, r := range tag {\n\t\tswitch {\n\t\tcase r \u003e= 'a' \u0026\u0026 r \u003c= 'z', r \u003e= '0' \u0026\u0026 r \u003c= '9', r == '-':\n\t\tdefault:\n\t\t\tpanic(\"kitindexdemo: a tag is [a-z0-9-], got \" + strconv.Quote(tag))\n\t\t}\n\t}\n\treturn tag\n}\n\n// assertRoom refuses a write the board has no room for, globally or for this\n// address. Checked before the store write, so a refusal costs the caller the\n// gas of three reads and nothing is half-applied.\nfunc assertRoom(who address) {\n\tif notes.Len() \u003e= MaxNotes {\n\t\tpanic(\"kitindexdemo: the board is full at \" + strconv.Itoa(MaxNotes) +\n\t\t\t\" notes; retract one to free a slot\")\n\t}\n\tif n := byAuthor.Count(who.String()); n \u003e= MaxPerAuthor {\n\t\tpanic(\"kitindexdemo: \" + who.String() + \" already has \" + strconv.Itoa(n) +\n\t\t\t\" notes, the limit is \" + strconv.Itoa(MaxPerAuthor))\n\t}\n}\n\nfunc assertBody(body string) {\n\tif strings.TrimSpace(body) == \"\" {\n\t\tpanic(\"kitindexdemo: the body is empty\")\n\t}\n\tif len(body) \u003e MaxBody {\n\t\tpanic(\"kitindexdemo: the body is \" + strconv.Itoa(len(body)) +\n\t\t\t\" bytes, the limit is \" + strconv.Itoa(MaxBody))\n\t}\n}\n"},{"name":"kitindexdemo_test.gno","body":"package kitindexdemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/index/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\n// reset puts the realm back to its init() state.\n//\n// Realm globals persist for the whole test binary and examples run after every\n// Test, so without this an ExampleRender's pinned output depends silently on\n// which tests ran before it. Assigning the globals directly is allowed here:\n// same package, and it crosses nothing.\nfunc reset() {\n\tnotes = store.Named(\"note\")\n\tbyTag = index.Index{}\n\tbyAuthor = index.Index{}\n}\n\nfunc TestPostIndexesInBothDirections(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Post(cross(cur), \"gno\", \"first\")\n\n\tuassert.Equal(t, 1, notes.Len())\n\tuassert.Equal(t, 1, byTag.Count(\"gno\"))\n\tuassert.Equal(t, 1, byAuthor.Count(alice.String()))\n\n\tgot := byTag.Lookup(\"gno\")\n\turequire.Equal(t, 1, len(got))\n\tuassert.Equal(t, store.ID(id).String(), got[0].String())\n}\n\nfunc TestTagIsNormalisedAtWriteTime(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"  GNO  \", \"mixed case and spaces\")\n\n\tuassert.Equal(t, 1, byTag.Count(\"gno\"))\n\tuassert.Equal(t, 1, byTag.Keys())\n}\n\n// The tag is an index key AND a path segment, so it is validated rather than\n// escaped: a tag carrying a pipe or a slash breaks the table and the URL, not\n// only the sentence.\nfunc TestTagRefusals(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tfor _, tc := range []struct {\n\t\tname string\n\t\ttag  string\n\t\twant string\n\t}{\n\t\t{\"empty\", \"\", \"a tag is 1 to 24 characters\"},\n\t\t{\"blank\", \"   \", \"a tag is 1 to 24 characters\"},\n\t\t{\"too long\", \"aaaaaaaaaaaaaaaaaaaaaaaaa\", \"a tag is 1 to 24 characters\"},\n\t\t{\"a pipe\", \"a|b\", \"a tag is [a-z0-9-]\"},\n\t\t{\"a slash\", \"a/b\", \"a tag is [a-z0-9-]\"},\n\t\t{\"markdown\", \"a]b\", \"a tag is [a-z0-9-]\"},\n\t\t{\"a space inside\", \"a b\", \"a tag is [a-z0-9-]\"},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.AbortsContains(t, cur, tc.want, func() {\n\t\t\t\tPost(cross(cur), tc.tag, \"body\")\n\t\t\t})\n\t\t})\n\t}\n\tuassert.Equal(t, 0, notes.Len())\n}\n\nfunc TestBodyRefusals(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsContains(t, cur, \"the body is empty\", func() {\n\t\tPost(cross(cur), \"gno\", \"   \")\n\t})\n\n\tlong := \"\"\n\tfor i := 0; i \u003c= MaxBody; i++ {\n\t\tlong += \"x\"\n\t}\n\tuassert.AbortsContains(t, cur, \"the limit is 280\", func() {\n\t\tPost(cross(cur), \"gno\", long)\n\t})\n\tuassert.Equal(t, 0, notes.Len())\n}\n\nfunc TestOnlyTheAuthorMayRetract(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Post(cross(cur), \"gno\", \"alice's note\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"is not yours\", func() {\n\t\tRetract(cross(cur), id)\n\t})\n\tuassert.Equal(t, 1, notes.Len())\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRetract(cross(cur), id)\n\tuassert.Equal(t, 0, notes.Len())\n}\n\n// The store and both indexes have to come apart together, or a later Render\n// walks ids the store no longer holds.\nfunc TestRetractUnwindsEveryContainer(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Post(cross(cur), \"gno\", \"one\")\n\tPost(cross(cur), \"gno\", \"two\")\n\n\tRetract(cross(cur), id)\n\n\tuassert.Equal(t, 1, notes.Len())\n\tuassert.Equal(t, 1, byTag.Count(\"gno\"))\n\tuassert.Equal(t, 1, byAuthor.Count(alice.String()))\n}\n\nfunc TestRetractRefusals(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsContains(t, cur, \"not found\", func() { Retract(cross(cur), 99) })\n\tuassert.AbortsContains(t, cur, \"not an id\", func() { Retract(cross(cur), 0) })\n\tuassert.AbortsContains(t, cur, \"not an id\", func() { Retract(cross(cur), -1) })\n}\n\n// A body is a caller's markdown and must not be able to write the page around\n// it. ui.Cell is what stops a pipe from opening a column.\nfunc TestARenderedBodyCannotBreakTheTable(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"gno\", \"a | b [x](http://evil)\")\n\n\tgot := Render(\"tag/gno\")\n\tuassert.False(t, strings.Contains(got, \"| a | b [\"),\n\t\t\"the raw body must not reach the table\")\n\tuassert.True(t, strings.Contains(got, \"\\\\|\"),\n\t\t\"the pipe must be escaped\")\n}\n\nfunc TestRenderOfAnUnknownPage(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"nope\"), \"Not found\"))\n\tuassert.True(t, strings.Contains(Render(\"tag\"), \"No tag given.\"))\n\tuassert.True(t, strings.Contains(Render(\"author\"), \"No author given.\"))\n}\n\n// MaxBody bounds one write. These bound the bill, which is the thing the realm\n// actually pays.\nfunc TestPerAuthorCap(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfor i := 0; i \u003c MaxPerAuthor; i++ {\n\t\tPost(cross(cur), \"gno\", \"note \"+strconv.Itoa(i))\n\t}\n\tuassert.AbortsContains(t, cur, \"the limit is 20\", func() {\n\t\tPost(cross(cur), \"gno\", \"one too many\")\n\t})\n\n\t// Another address is unaffected, which is the whole reason the cap is\n\t// per author and not only global.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tPost(cross(cur), \"gno\", \"bob still fits\")\n\tuassert.Equal(t, MaxPerAuthor+1, notes.Len())\n}\n\n// Retracting frees a slot, so the cap is not a one-way door.\nfunc TestRetractingFreesASlot(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfirst := Post(cross(cur), \"gno\", \"note 0\")\n\tfor i := 1; i \u003c MaxPerAuthor; i++ {\n\t\tPost(cross(cur), \"gno\", \"note \"+strconv.Itoa(i))\n\t}\n\tuassert.AbortsContains(t, cur, \"the limit is 20\", func() {\n\t\tPost(cross(cur), \"gno\", \"blocked\")\n\t})\n\n\tRetract(cross(cur), first)\n\tPost(cross(cur), \"gno\", \"now it fits\")\n\tuassert.Equal(t, MaxPerAuthor, notes.Len())\n}\n\n// The page number is user input on the Render path. One outside 1..Pages is\n// clamped into it, so it never renders an empty board under a footer that\n// says \"page -1 of 2\".\nfunc TestRenderClampsThePageNumber(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfor i := 0; i \u003c PageSize; i++ {\n\t\tPost(cross(cur), \"t\"+strconv.Itoa(i), \"x\")\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tPost(cross(cur), \"t-last\", \"x\")\n\turequire.Equal(t, 2, byTag.Pages(PageSize))\n\n\tfirst, last := Render(\"?page=1\"), Render(\"?page=2\")\n\tuassert.Equal(t, first, Render(\"?page=-1\"))\n\tuassert.Equal(t, first, Render(\"?page=0\"))\n\tuassert.Equal(t, last, Render(\"?page=999\"))\n\tuassert.True(t, strings.Contains(last, \"page 2 of 2\"))\n}\n\n// Links are absolute. gnoweb serves this realm at .../kitindexdemo/v0, so a\n// \"./kitindexdemo:tag/x\" link resolves to .../kitindexdemo/kitindexdemo:tag/x,\n// a package that does not exist.\nfunc TestRenderLinksAreAbsolute(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfor i := 0; i \u003c= PageSize; i++ {\n\t\tif i == MaxPerAuthor {\n\t\t\ttesting.SetRealm(testing.NewUserRealm(bob))\n\t\t}\n\t\tPost(cross(cur), \"t\"+strconv.Itoa(i), \"x\")\n\t}\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"](/r/moul/x/kitindexdemo/v0:tag/t0)\"), out)\n\tuassert.True(t, strings.Contains(out, \"](/r/moul/x/kitindexdemo/v0:?page=2)\"), out)\n\tuassert.False(t, strings.Contains(out, \"](./\"), out)\n}\n\n// realmURL must follow the module line, or a version bump ships dead links.\nfunc TestRealmURLMatchesTheModule(cur realm, t *testing.T) {\n\tuassert.Equal(t, \"gno.land\"+realmURL, cur.PkgPath())\n}\n\n// The global cap is what bounds the realm's whole storage bill, so its\n// refusal is pinned, and pinned as refusing BEFORE any write: the store and\n// both indexes are exactly as full as they were.\nfunc TestTheBoardIsFull(cur realm, t *testing.T) {\n\treset()\n\tfor i := 0; i \u003c MaxNotes; i++ {\n\t\tnotes.Add(\u0026note{Author: bob, Tag: \"gno\", Body: \"x\"})\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"the board is full\", func() {\n\t\tPost(cross(cur), \"gno\", \"one too many\")\n\t})\n\tuassert.Equal(t, MaxNotes, notes.Len())\n\tuassert.Equal(t, 0, byTag.Len())\n\tuassert.Equal(t, 0, byAuthor.Count(alice.String()))\n}\n"},{"name":"render.gno","body":"package kitindexdemo\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n)\n\n// realmURL is this realm as gnoweb serves it. Links are absolute because the\n// path ends in /v0: a relative \"./kitindexdemo:tag/x\" resolves against the\n// parent directory to .../kitindexdemo/kitindexdemo:tag/x, which does not\n// exist. Not derived at runtime: a Render has no cur, and CurrentRealm there\n// is the caller. TestRealmURLMatchesTheModule pins it to the module line.\nconst realmURL = \"/r/moul/x/kitindexdemo/v0\"\n\n// Render is the whole public surface. Three pages: the tag list, one tag, one\n// author.\n//\n// Every row goes through ui.NewTable rather than concatenated pipes, and every\n// caller string through ui.Cell, because a public path is immutable and a\n// Render that ships wrong ships forever.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tswitch req.PathPart(0) {\n\tcase \"\":\n\t\treturn renderIndex(req)\n\tcase \"tag\":\n\t\treturn renderTag(req.PathPart(1))\n\tcase \"author\":\n\t\treturn renderAuthor(req.PathPart(1))\n\tdefault:\n\t\treturn md.H1(\"Not found\") + ui.Empty(\"No such page.\")\n\t}\n}\n\nfunc renderIndex(req *realmpath.Request) string {\n\t// The page number is user input: clamp it into 1..pages, or ?page=-1\n\t// renders an empty board under a footer saying \"page -1 of 2\".\n\tpages := byTag.Pages(PageSize)\n\tpage := 1\n\tif n, err := strconv.Atoi(req.Query.Get(\"page\")); err == nil {\n\t\tpage = n\n\t}\n\tif page \u003c 1 {\n\t\tpage = 1\n\t}\n\tif page \u003e pages {\n\t\tpage = pages\n\t}\n\n\tt := ui.NewTable(\"tag\", \"notes\")\n\tfor _, e := range byTag.Page(page, PageSize) {\n\t\tt.Row(\n\t\t\tmd.Link(e.Key, realmURL+\":tag/\"+e.Key),\n\t\t\tstrconv.Itoa(len(e.IDs)),\n\t\t)\n\t}\n\n\treturn ui.Join(\"\\n\",\n\t\tmd.H1(\"Notes by tag\"),\n\t\tmd.Paragraph(strconv.Itoa(notes.Len())+\" note(s) under \"+\n\t\t\tstrconv.Itoa(byTag.Keys())+\" tag(s), by \"+\n\t\t\tstrconv.Itoa(byAuthor.Keys())+\" author(s).\"),\n\t\tt.OrEmpty(\"Nothing posted yet.\"),\n\t\tpager(page, pages),\n\t\tmd.Paragraph(ui.Action(\"Post a note\", \"Post\", \"tag\", \"\", \"body\", \"\")),\n\t)\n}\n\nfunc renderTag(tag string) string {\n\tif tag == \"\" {\n\t\treturn md.H1(\"Not found\") + ui.Empty(\"No tag given.\")\n\t}\n\treturn md.H1(\"#\"+ui.Cell(tag)) + notesTable(byTag.Lookup(tag), \"No notes under this tag.\")\n}\n\nfunc renderAuthor(addr string) string {\n\tif addr == \"\" {\n\t\treturn md.H1(\"Not found\") + ui.Empty(\"No author given.\")\n\t}\n\treturn md.H1(\"Notes by \"+ui.AddrOf(addr)) +\n\t\tnotesTable(byAuthor.Lookup(addr), \"This address has posted nothing.\")\n}\n\n// notesTable renders a set of ids as rows, skipping any id the store no longer\n// holds.\n//\n// Skipping rather than panicking: an index and a store are two containers, and\n// a reader should see the records that exist rather than a page that aborts.\n// Retract keeps the two in step, so a miss here means a bug worth surviving,\n// not worth hiding.\nfunc notesTable(hits []store.ID, empty string) string {\n\tt := ui.NewTable(\"#\", \"author\", \"tag\", \"note\", \"height\")\n\tfor _, id := range hits {\n\t\tv, ok := notes.Get(id)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tn := v.(*note)\n\t\tt.Row(\n\t\t\tid.String(),\n\t\t\tui.Addr(n.Author),\n\t\t\tmd.InlineCode(n.Tag),\n\t\t\tui.Cell(n.Body),\n\t\t\tstrconv.FormatInt(n.Height, 10),\n\t\t)\n\t}\n\treturn t.OrEmpty(empty)\n}\n\n// pager renders the previous/next links, or nothing when there is one page.\nfunc pager(page, pages int) string {\n\tif pages \u003c 2 {\n\t\treturn \"\"\n\t}\n\tout := \"\"\n\tif page \u003e 1 {\n\t\tout += md.Link(\"previous\", realmURL+\":?page=\"+strconv.Itoa(page-1)) + \" \"\n\t}\n\tout += \"page \" + strconv.Itoa(page) + \" of \" + strconv.Itoa(pages)\n\tif page \u003c pages {\n\t\tout += \" \" + md.Link(\"next\", realmURL+\":?page=\"+strconv.Itoa(page+1))\n\t}\n\treturn out\n}\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"72754200","gas_fee":"218262ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"rOpo0P4cNM7fRwco3YpUxm0QqMXSnTGOdi8+tA696XUK+E9MSOQBsgpLsE++pmTPpC/YoEGTkvUTMdBVtB6/VQ=="}],"memo":""},"metadata":{"timestamp":"1790961570"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"moultest","path":"gno.land/r/moul/x/moultest/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/moultest/v0`\n\n**A native coin called `moultest`, and a faucet with four ceilings on it.**\nNot a GRC20: the chain's own bank holds it, exactly as it holds GNOT.\n\n```\n/gno.land/r/moul/x/moultest/v0:moultest\n```\n\nThat string is the whole coin. There is no name, no symbol, no decimals field, no\nledger in this realm and no entry in any registry, because a native denom has\nnone of those things. 1000 moultest is a thousand moultest.\n\n## Help yourself\n\n```\ngnokey maketx call -pkgpath gno.land/r/moul/x/moultest/v0 -func Claim ...\n```\n\n10,000 per claim, to the caller and never to an address the caller names, once\nevery 100 blocks, 100,000 per address for life, 1,000,000 ever. Burning gives\nnone of it back: issuance is counted monotonically, or claim-burn-claim would be\nan unlimited faucet. The supply ceiling is there so the experiment ends, not so\nthe faucet scales.\n\n## What the coin can do that a GRC20 cannot\n\nMoving it needs nothing from this realm. It is a bank message, so any wallet\nsends it with no realm call, no `Approve`, no allowance outliving the transfer:\n\n```\ngnokey maketx send -to \u003caddress\u003e -send 2500/gno.land/r/moul/x/moultest/v0:moultest ...\n```\n\nIt can also ride a call. The `-send` envelope of a transaction carries coins into\nthe realm being called, before a line of its code runs, which is what `Tip` uses:\n\n```\ngnokey maketx call -pkgpath gno.land/r/moul/x/moultest/v0 -func Tip \\\n  -args \u003caddress\u003e -args \"nice work\" \\\n  -send 1000/gno.land/r/moul/x/moultest/v0:moultest ...\n```\n\n`Tip` forwards that envelope to the recipient and writes the note on a public\nboard. It spends through a `BankerTypeOriginSend` banker, whose entire authority\n*is* the envelope: it cannot touch the realm's own balance, and a test pins\nthat by leaving 5,000 moultest at the realm address and checking that exactly\nthe 250 that arrived leaves again.\n\nThat banker type is only available to a call whose entry frame is the realm\nnamed by the message, so `Tip` needs `maketx call` and does not work under\n`maketx run`.\n\n## What it costs, which is the more interesting half\n\nA GRC20's mint and burn sit behind a ledger this realm chooses to guard. A\nnative coin's sit behind a banker, and `banker.RemoveCoin` takes an **arbitrary\naddress**. Nothing on the chain stops an issuing realm from deleting anybody's\nbalance at any time.\n\nThis realm does not expose that. `Burn` reads the caller from the call frame and\ntakes no address parameter, so it can only destroy the caller's own coins. But\n\"does not expose it\" is the entire protection, and it lasts exactly as long as\nthe code deployed at this path. Worth knowing before treating any realm-issued\nnative coin as something you own.\n\n## Redeploys\n\n`private = true`, so this path can be redeployed with corrected code instead of\nbeing abandoned for a `/v1`. The coins survive that (they are bank state, held at\ntheir owners' addresses, and the denom embeds the package path, which does not\nmove) and everything on the render page does not: claim history, caps consumed\nand the tip board all return to their init values, handing every account a fresh\nlifetime allowance. Acceptable for a coin that is worthless by construction, and\nnot acceptable for one that is not.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/moultest/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/moultest/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/moultest/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/moultest/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/moultest/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/moultest/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/moultest/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/moultest/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/moultest/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/moultest/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/moultest/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"moultest.gno","body":"// Package moultest issues `moultest`, a NATIVE coin, and gives it away.\n//\n// Native here means the chain's own bank holds it, exactly as it holds GNOT.\n// It is not a GRC20: there is no ledger in this realm's storage, no balance\n// map, no Transfer function, no allowance. A realm with the right banker calls\n// IssueCoin once and from that moment the coin is a first-class chain object,\n// and this realm has no further say in who holds it.\n//\n// # What that buys, and what it costs\n//\n// The interesting half is what disappears. Moving moultest needs no code here\n// at all: a plain bank send does it, from any wallet, with no realm call and no\n// approval dance, because the transfer is a tm2 bank message rather than a\n// function call. It can also RIDE a transaction: the `-send` envelope of a call\n// carries it into the realm being called, which is the one thing no GRC20 can\n// do, and [Tip] exists to show it. The account page of any explorer lists it\n// beside GNOT with nothing registered anywhere.\n//\n// The half that is worse is the authority. A GRC20's mint and burn live behind\n// a PrivateLedger this realm chooses to guard; a native coin's live in a banker\n// minted from a realm handle, and banker.RemoveCoin takes an ARBITRARY address.\n// Nothing in the chain stops the issuing realm from deleting anybody's balance\n// at any time. This realm does not expose that (see [Burn], which is scoped to\n// the caller and to nobody else), but \"does not expose it\" is the only\n// protection there is, and it lasts exactly as long as the deployed code. That\n// is the real asymmetry against a GRC20, not the ergonomics.\n//\n// There is no decimals field either, nor a name, nor a symbol: a native denom\n// is a string and nothing else. 1000 moultest is a thousand moultest.\n//\n// # Why it is capped\n//\n// Free money with no ceiling is a spam vector rather than a faucet, so [Claim]\n// is bounded four ways, and the caps are the point of the experiment as much as\n// the coin is:\n//\n//   - [ClaimAmount] per call, to the CALLER only, never to an address the\n//     caller names, so nobody can dust a stranger with it.\n//   - [ClaimEvery] blocks of cooldown between two claims by one account.\n//   - [MaxPerAccount] over that account's lifetime.\n//   - [MaxSupply] over the realm's lifetime.\n//\n// [Burn] does not give any of it back. Issuance is counted monotonically, so\n// claim-burn-claim cannot walk around the per-account cap; what burning moves\n// is the circulating supply, which is why the two numbers are reported\n// separately.\n//\n// # It is a private realm\n//\n// gnomod.toml declares private = true, so this path can be redeployed with\n// corrected code instead of being abandoned for a v1. The price is measured\n// elsewhere in this repo and applies here too: the coins survive a redeploy\n// (they are bank state, held at their owners' addresses, and the denom embeds\n// the package path, which does not move), and everything on this page does not.\n// Claim history, caps consumed and the tip board all return to their init\n// values, which would hand every account a fresh [MaxPerAccount]. For a coin\n// that is worthless by construction that is an acceptable trade; it would not\n// be for one that is not.\npackage moultest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst (\n\t// Name is the coin's base denom: the part after the colon. The chain caps\n\t// it at 16 lowercase characters.\n\tName = \"moultest\"\n\t// Path is this realm's package path. The denom embeds it verbatim, so the\n\t// coin and the code are permanently the same name.\n\tPath = \"gno.land/r/moul/x/moultest/v0\"\n\t// Link is Path as a gnoweb route.\n\tLink = \"/r/moul/x/moultest/v0\"\n)\n\n// Denom is the full chain denom, \"/\" + [Path] + \":\" + [Name]. This is the\n// string a wallet, an explorer or a `-send` flag needs; the bank knows nothing\n// about the realm behind it.\nvar Denom = chain.CoinDenom(Path, Name)\n\nconst (\n\t// ClaimAmount is issued per successful [Claim].\n\tClaimAmount = int64(10_000)\n\t// ClaimEvery is the cooldown, in blocks, between two claims by one account.\n\tClaimEvery = int64(100)\n\t// MaxPerAccount is the lifetime ceiling on what one address can claim here,\n\t// ten claims' worth. Burning does not raise it.\n\tMaxPerAccount = int64(100_000)\n\t// MaxSupply is the lifetime ceiling on what this realm can ever issue: a\n\t// hundred claims' worth, all told. Nothing lowers it, so the coin cannot be\n\t// inflated after the fact, and the experiment has an end rather than a\n\t// budget. A faucet meant to serve a crowd would put the ceiling somewhere\n\t// else; this one is meant to run out.\n\tMaxSupply = int64(1_000_000)\n\n\t// MaxNote is the longest tip note kept, in bytes.\n\tMaxNote = 120\n\t// MaxTips is how many tips the board shows. Older ones fall off.\n\tMaxTips = 20\n)\n\ntype account struct {\n\tlastClaim int64 // block height of the most recent claim\n\tclaims    int64 // how many times this address has claimed\n\tissued    int64 // lifetime total issued to it, never decremented\n}\n\n// Tip is one entry of the public board written by [Tip].\ntype tip struct {\n\tfrom   address\n\tto     address\n\tamount int64\n\tnote   string\n\theight int64\n}\n\nvar (\n\taccounts = avl.NewTree() // address string -\u003e *account\n\n\t// issued and burned are counted here rather than derived from the bank:\n\t// TotalCoin reports what CIRCULATES, and the caps are about what was ever\n\t// minted. The two differ by exactly `burned`, which a test pins.\n\tissued int64\n\tburned int64\n\n\ttips []*tip // most recent last, at most MaxTips\n)\n\n// Claim issues [ClaimAmount] of moultest to the caller and returns it.\n//\n// It never issues to an address the caller names. That is deliberate: a faucet\n// that mints to a third party is a way to spray a denom nobody asked for into\n// strangers' wallets, and their account page then carries it forever.\nfunc Claim(cur realm) int64 {\n\twho := caller(cur)\n\ta := accountOf(who)\n\tnow := runtime.ChainHeight()\n\n\tif a.claims \u003e 0 \u0026\u0026 now \u003c a.lastClaim+ClaimEvery {\n\t\tpanic(ufmt.Sprintf(\"too soon: next claim at block %d, current %d\",\n\t\t\ta.lastClaim+ClaimEvery, now))\n\t}\n\tif a.issued+ClaimAmount \u003e MaxPerAccount {\n\t\tpanic(ufmt.Sprintf(\"account cap reached: %d of %d already claimed by this address\",\n\t\t\ta.issued, MaxPerAccount))\n\t}\n\tif issued+ClaimAmount \u003e MaxSupply {\n\t\tpanic(ufmt.Sprintf(\"supply cap reached: %d of %d already issued\",\n\t\t\tissued, MaxSupply))\n\t}\n\n\ta.lastClaim = now\n\ta.claims++\n\ta.issued += ClaimAmount\n\taccounts.Set(who.String(), a)\n\tissued += ClaimAmount\n\n\tbanker.NewBanker(banker.BankerTypeRealmIssue, cur).IssueCoin(who, Denom, ClaimAmount)\n\treturn ClaimAmount\n}\n\n// Burn destroys `amount` of the CALLER's moultest, and only the caller's.\n//\n// The banker this realm holds could remove coins from any address on the chain\n// without asking, so the `who` here is read from the call frame and is never a\n// parameter. A clawback is what an issuing realm is always able to write; the\n// choice not to is made here, once, and cannot be revisited without a redeploy.\n//\n// Burning lowers what circulates and does not return any cap headroom: see\n// [MaxPerAccount].\nfunc Burn(cur realm, amount int64) {\n\tif amount \u003c= 0 {\n\t\tpanic(\"burn a positive amount\")\n\t}\n\twho := caller(cur)\n\tif bal := BalanceOf(who); bal \u003c amount {\n\t\tpanic(ufmt.Sprintf(\"balance is %d, cannot burn %d\", bal, amount))\n\t}\n\n\tbanker.NewBanker(banker.BankerTypeRealmIssue, cur).RemoveCoin(who, Denom, amount)\n\tburned += amount\n}\n\n// Tip forwards the moultest attached to THIS transaction to `to`, and writes\n// the note on a public board.\n//\n// The coin arrives in the `-send` envelope of the call, credited to this\n// realm's address before a line of this function runs, and leaves through a\n// BankerTypeOriginSend banker, whose whole authority is that envelope: it can\n// spend what this message paid in and not one coin more, not even out of the\n// realm's own balance. So the realm can route a payment it was handed while\n// being structurally unable to touch anything else.\n//\n// A GRC20 has no equivalent. Its tokens cannot ride a message, so the same flow\n// costs an Approve, then a call, then an allowance that outlives both.\n//\n// Anything else in the envelope (the GNOT covering a storage deposit, say) is\n// left alone and stays with the realm.\nfunc Tip(cur realm, to address, note string) int64 {\n\twho := caller(cur)\n\tif !to.IsValid() {\n\t\tpanic(\"tip a valid address\")\n\t}\n\tif to == who {\n\t\tpanic(\"tip somebody else\")\n\t}\n\tif len(note) \u003e MaxNote {\n\t\tpanic(ufmt.Sprintf(\"note is %d bytes, max %d\", len(note), MaxNote))\n\t}\n\n\tamount := unsafe.OriginSend().AmountOf(Denom)\n\tif amount \u003c= 0 {\n\t\tpanic(\"attach moultest to the transaction: -send \" + Denom)\n\t}\n\n\tb := banker.NewBanker(banker.BankerTypeOriginSend, cur)\n\tb.SendCoins(cur.Address(), to, chain.NewCoins(chain.NewCoin(Denom, amount)))\n\n\ttips = append(tips, \u0026tip{\n\t\tfrom:   who,\n\t\tto:     to,\n\t\tamount: amount,\n\t\tnote:   note,\n\t\theight: runtime.ChainHeight(),\n\t})\n\tif len(tips) \u003e MaxTips {\n\t\ttips = tips[len(tips)-MaxTips:]\n\t}\n\treturn amount\n}\n\n// BalanceOf returns what the bank holds of moultest for `who`. It reads the\n// chain, not this realm: a balance this realm never saw counts the same.\nfunc BalanceOf(who address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoin(who, Denom)\n}\n\n// Circulating returns how much moultest exists right now, from the bank.\nfunc Circulating() int64 {\n\treturn banker.NewReadonlyBanker().TotalCoin(Denom)\n}\n\n// Issued returns how much this realm has ever issued. It only grows, and it is\n// what [MaxSupply] caps.\nfunc Issued() int64 { return issued }\n\n// Burned returns how much has been destroyed through [Burn].\nfunc Burned() int64 { return burned }\n\n// NextClaim returns the block height at which `who` may claim again, and\n// whether they have ever claimed at all.\nfunc NextClaim(who address) (int64, bool) {\n\ta := accounts.Get(who.String())\n\tif a == nil {\n\t\treturn 0, false\n\t}\n\treturn a.(*account).lastClaim + ClaimEvery, true\n}\n\n// ClaimedBy returns the lifetime total issued to `who` by this realm, which is\n// what [MaxPerAccount] caps.\nfunc ClaimedBy(who address) int64 {\n\ta := accounts.Get(who.String())\n\tif a == nil {\n\t\treturn 0\n\t}\n\treturn a.(*account).issued\n}\n\n// Accounts returns how many addresses have ever claimed.\nfunc Accounts() int { return accounts.Size() }\n\nfunc accountOf(who address) *account {\n\tif v := accounts.Get(who.String()); v != nil {\n\t\treturn v.(*account)\n\t}\n\treturn \u0026account{}\n}\n\n// caller is the account or realm that crossed into this one.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"moultest: stale realm token\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"moultest_test.gno","body":"package moultest\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// testing.SetRealm governs only the crossing calls made from the frame that\n// called it, so every account switch below is written inline in the test body\n// rather than in a helper.\n\nfunc TestDenom(t *testing.T) {\n\t// The denom is what a wallet, an explorer and a -send flag all type, and it\n\t// is immutable once the first coin exists. Pin the literal: deriving it from\n\t// Path would restate the code rather than check it.\n\tuassert.Equal(t, \"/gno.land/r/moul/x/moultest/v0:moultest\", Denom)\n}\n\nfunc TestClaimIssuesRealCoins(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"mt-alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t_, ever := NextClaim(alice)\n\tuassert.False(t, ever, \"no claim recorded before the first one\")\n\tuassert.Equal(t, int64(0), BalanceOf(alice))\n\n\tbefore := Circulating()\n\tgot := Claim(cross(cur))\n\n\tuassert.Equal(t, ClaimAmount, got)\n\t// The balance comes from the bank, not from realm storage: nothing in this\n\t// realm records who holds what.\n\tuassert.Equal(t, ClaimAmount, BalanceOf(alice))\n\tuassert.Equal(t, before+ClaimAmount, Circulating())\n\tuassert.Equal(t, ClaimAmount, ClaimedBy(alice))\n\n\tnext, ever := NextClaim(alice)\n\tuassert.True(t, ever, \"a cooldown is recorded\")\n\tuassert.Equal(t, ClaimEvery, next-123, \"first test block is 123, so the cooldown lands there\")\n}\n\nfunc TestClaimCooldown(cur realm, t *testing.T) {\n\tbob := testutils.TestAddress(\"mt-bob\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\n\tClaim(cross(cur))\n\tuassert.AbortsContains(t, cur, \"too soon\", func() { Claim(cross(cur)) })\n\n\ttesting.SkipHeights(ClaimEvery - 1)\n\tuassert.AbortsContains(t, cur, \"too soon\", func() { Claim(cross(cur)) })\n\n\ttesting.SkipHeights(1)\n\tClaim(cross(cur))\n\tuassert.Equal(t, 2*ClaimAmount, BalanceOf(bob))\n}\n\nfunc TestAccountCap(cur realm, t *testing.T) {\n\tcarol := testutils.TestAddress(\"mt-carol\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\n\tfor ClaimedBy(carol)+ClaimAmount \u003c= MaxPerAccount {\n\t\tClaim(cross(cur))\n\t\ttesting.SkipHeights(ClaimEvery)\n\t}\n\tuassert.Equal(t, MaxPerAccount, ClaimedBy(carol))\n\tuassert.AbortsContains(t, cur, \"account cap reached\", func() { Claim(cross(cur)) })\n\n\t// Waiting does not help: the cooldown is not what stopped it.\n\ttesting.SkipHeights(ClaimEvery * 10)\n\tuassert.AbortsContains(t, cur, \"account cap reached\", func() { Claim(cross(cur)) })\n}\n\nfunc TestBurnIsScopedToTheCaller(cur realm, t *testing.T) {\n\tdave := testutils.TestAddress(\"mt-dave\")\n\terin := testutils.TestAddress(\"mt-erin\")\n\n\ttesting.SetRealm(testing.NewUserRealm(erin))\n\tClaim(cross(cur))\n\terinBefore := BalanceOf(erin)\n\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tClaim(cross(cur))\n\n\tissuedBefore, burnedBefore, circBefore := Issued(), Burned(), Circulating()\n\tclaimedBefore := ClaimedBy(dave)\n\n\tBurn(cross(cur), 400)\n\n\tuassert.Equal(t, ClaimAmount-400, BalanceOf(dave))\n\tuassert.Equal(t, circBefore-400, Circulating(), \"burning destroys the coin, it is not moved\")\n\tuassert.Equal(t, burnedBefore+400, Burned())\n\t// Issuance is monotonic on purpose: if burning gave cap headroom back,\n\t// claim-burn-claim would be an unlimited faucet.\n\tuassert.Equal(t, issuedBefore, Issued())\n\tuassert.Equal(t, claimedBefore, ClaimedBy(dave))\n\t// Burn takes no address, so erin cannot be reached from dave's call.\n\tuassert.Equal(t, erinBefore, BalanceOf(erin))\n\n\tuassert.AbortsContains(t, cur, \"cannot burn\", func() { Burn(cross(cur), 1_000_000) })\n\tuassert.AbortsContains(t, cur, \"positive amount\", func() { Burn(cross(cur), 0) })\n\tuassert.AbortsContains(t, cur, \"positive amount\", func() { Burn(cross(cur), -5) })\n}\n\nfunc TestTipRidesTheEnvelope(cur realm, t *testing.T) {\n\tfrank := testutils.TestAddress(\"mt-frank\")\n\tgrace := testutils.TestAddress(\"mt-grace\")\n\n\t// On chain the -send envelope is credited to this realm's address before\n\t// the function runs. The test harness has no bank-send primitive, so the\n\t// credit is issued directly here; SetOriginSend is what the banker checks\n\t// against, and it is the half that bounds what Tip may spend.\n\trealmAddr := chain.PackageAddress(Path)\n\tenvelope := chain.NewCoins(chain.NewCoin(Denom, 250))\n\ttesting.IssueCoins(realmAddr, envelope)\n\t// Unrelated coins already sitting at the realm's address. A RealmSend\n\t// banker could spend these; the OriginSend one may not, and that is the\n\t// property being pinned.\n\ttesting.IssueCoins(realmAddr, chain.NewCoins(chain.NewCoin(Denom, 5_000)))\n\trealmBefore := BalanceOf(realmAddr)\n\n\ttesting.SetRealm(testing.NewUserRealm(frank))\n\ttesting.SetOriginSend(envelope)\n\tsent := Tip(cross(cur), grace, \"nice work\")\n\n\tuassert.Equal(t, int64(250), sent)\n\tuassert.Equal(t, int64(250), BalanceOf(grace), \"the tip landed on the recipient\")\n\tuassert.Equal(t, realmBefore-250, BalanceOf(realmAddr),\n\t\t\"exactly the envelope left the realm, and nothing else it was holding\")\n\tuassert.Equal(t, 1, len(tips))\n\tuassert.Equal(t, \"nice work\", tips[0].note)\n\n\ttesting.SetOriginSend(nil)\n}\n\nfunc TestTipRefusals(cur realm, t *testing.T) {\n\theidi := testutils.TestAddress(\"mt-heidi\")\n\tivan := testutils.TestAddress(\"mt-ivan\")\n\n\ttesting.SetRealm(testing.NewUserRealm(heidi))\n\ttesting.SetOriginSend(nil)\n\tuassert.AbortsContains(t, cur, \"attach moultest\", func() { Tip(cross(cur), ivan, \"hi\") })\n\n\tenvelope := chain.NewCoins(chain.NewCoin(Denom, 10))\n\ttesting.IssueCoins(chain.PackageAddress(Path), envelope)\n\ttesting.SetOriginSend(envelope)\n\tuassert.AbortsContains(t, cur, \"tip somebody else\", func() { Tip(cross(cur), heidi, \"me\") })\n\tuassert.AbortsContains(t, cur, \"valid address\", func() { Tip(cross(cur), \"nope\", \"hi\") })\n\tuassert.AbortsContains(t, cur, \"note is\", func() {\n\t\tTip(cross(cur), ivan, strings.Repeat(\"x\", MaxNote+1))\n\t})\n\n\ttesting.SetOriginSend(nil)\n}\n\nfunc TestSupplyCap(cur realm, t *testing.T) {\n\t// Fill the remaining supply with fresh accounts, each capped at\n\t// MaxPerAccount, then check that the next one is refused. Issuance carries\n\t// across tests, so the loop starts from whatever is left rather than from\n\t// MaxSupply.\n\tnames := []string{\"cap-a\", \"cap-b\", \"cap-c\", \"cap-d\", \"cap-e\", \"cap-f\",\n\t\t\"cap-g\", \"cap-h\", \"cap-i\", \"cap-j\", \"cap-k\", \"cap-l\"}\n\tfor _, name := range names {\n\t\tif Issued()+ClaimAmount \u003e MaxSupply {\n\t\t\tbreak\n\t\t}\n\t\twho := testutils.TestAddress(name)\n\t\ttesting.SetRealm(testing.NewUserRealm(who))\n\t\tfor ClaimedBy(who)+ClaimAmount \u003c= MaxPerAccount \u0026\u0026 Issued()+ClaimAmount \u003c= MaxSupply {\n\t\t\tClaim(cross(cur))\n\t\t\ttesting.SkipHeights(ClaimEvery)\n\t\t}\n\t}\n\tuassert.Equal(t, MaxSupply, Issued(), \"the accounts above exhaust the supply exactly\")\n\n\tlate := testutils.TestAddress(\"cap-late\")\n\ttesting.SetRealm(testing.NewUserRealm(late))\n\tuassert.AbortsContains(t, cur, \"supply cap reached\", func() { Claim(cross(cur)) })\n\n\t// Burning does not reopen the faucet either: circulating drops, issued does\n\t// not, and the cap is on issued.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"cap-a\")))\n\tBurn(cross(cur), 500)\n\tuassert.Equal(t, MaxSupply, Issued())\n\ttesting.SetRealm(testing.NewUserRealm(late))\n\tuassert.AbortsContains(t, cur, \"supply cap reached\", func() { Claim(cross(cur)) })\n}\n\nfunc TestRender(t *testing.T) {\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"# moultest\"), \"heading:\\n\"+index)\n\tuassert.True(t, strings.Contains(index, Denom), \"the denom is on the page\")\n\tuassert.True(t, strings.Contains(index, \"| issued, ever |\"), \"supply table:\\n\"+index)\n\tuassert.True(t, strings.Contains(index, \"nice work\"), \"the tip board is shown:\\n\"+index)\n\n\tfrank := testutils.TestAddress(\"mt-frank\")\n\tacct := Render(frank.String())\n\tuassert.True(t, strings.Contains(acct, frank.String()), \"the account section names it:\\n\"+acct)\n\tuassert.True(t, strings.Contains(acct, \"claimed for life\"), acct)\n\n\t// A path that is not an address renders the index without an account block.\n\tuassert.False(t, strings.Contains(Render(\"not-an-address\"), \"claimed for life\"),\n\t\t\"a junk path adds no account section\")\n}\n"},{"name":"render.gno","body":"package moultest\n\nimport (\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Render shows the coin, what is left under each cap, and the tip board.\n// `?\u003caddress\u003e` adds that address's balance and claim state.\nfunc Render(path string) string {\n\tvar sb strings.Builder\n\n\tsb.WriteString(md.H1(\"moultest: a native coin you can help yourself to\"))\n\tsb.WriteString(\"\\nNot a GRC20. The chain's bank holds it, so it moves with a plain send, \" +\n\t\t\"shows up beside GNOT on any account page, and can ride the `-send` envelope of a \" +\n\t\t\"transaction. There is no ledger in this realm and no registry entry anywhere.\\n\\n\")\n\tsb.WriteString(md.LanguageCodeBlock(\"\", Denom))\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(renderSupply())\n\tsb.WriteString(renderAccount(path))\n\tsb.WriteString(renderTips())\n\tsb.WriteString(renderUsage())\n\treturn sb.String()\n}\n\nfunc renderSupply() string {\n\tt := ui.NewTable(\"\", \"amount\", \"cap\", \"left\")\n\tt.Row(\"issued, ever\", ufmt.Sprintf(\"%d\", issued), ufmt.Sprintf(\"%d\", MaxSupply),\n\t\tufmt.Sprintf(\"%d\", MaxSupply-issued))\n\tt.Row(\"circulating\", ufmt.Sprintf(\"%d\", Circulating()), \"\", \"\")\n\tt.Row(\"burned\", ufmt.Sprintf(\"%d\", burned), \"\", \"\")\n\tt.Row(\"accounts\", ufmt.Sprintf(\"%d\", accounts.Size()), \"\", \"\")\n\n\ts := md.H2(\"Supply\") + \"\\n\" + t.String()\n\ts += \"\\n\" + ufmt.Sprintf(\n\t\t\"`%d` per claim, once every `%d` blocks, `%d` per address for life. \"+\n\t\t\t\"Burning lowers what circulates and gives back no headroom, \"+\n\t\t\t\"or claim-burn-claim would be an unlimited faucet.\\n\",\n\t\tClaimAmount, ClaimEvery, MaxPerAccount)\n\treturn s + \"\\n\"\n}\n\nfunc renderAccount(path string) string {\n\twho := address(path)\n\tif path == \"\" || !who.IsValid() {\n\t\treturn \"\"\n\t}\n\n\ts := md.H2(\"Account \"+ui.AddrText(who)) + \"\\n\"\n\tt := ui.NewTable(\"\", \"\")\n\tt.Row(\"address\", ui.AddrFull(who))\n\tt.Row(\"balance\", ufmt.Sprintf(\"%d moultest\", BalanceOf(who)))\n\tt.Row(\"claimed for life\", ufmt.Sprintf(\"%d of %d\", ClaimedBy(who), MaxPerAccount))\n\n\tnext, ever := NextClaim(who)\n\tswitch {\n\tcase !ever:\n\t\tt.Row(\"next claim\", \"now, this address has never claimed\")\n\tcase runtime.ChainHeight() \u003e= next:\n\t\tt.Row(\"next claim\", \"now\")\n\tdefault:\n\t\tt.Row(\"next claim\", ufmt.Sprintf(\"block %d (%d to go)\", next, next-runtime.ChainHeight()))\n\t}\n\treturn s + t.String() + \"\\n\"\n}\n\nfunc renderTips() string {\n\ts := md.H2(\"Tips\") + \"\\n\"\n\tif len(tips) == 0 {\n\t\treturn s + ui.Empty(\"Nobody has tipped anybody yet.\") + \"\\n\"\n\t}\n\tt := ui.NewTable(\"block\", \"from\", \"to\", \"amount\", \"note\")\n\t// Most recent first; the slice keeps them oldest first.\n\tfor i := len(tips) - 1; i \u003e= 0; i-- {\n\t\te := tips[i]\n\t\tt.Row(ufmt.Sprintf(\"%d\", e.height), ui.Addr(e.from), ui.Addr(e.to),\n\t\t\tufmt.Sprintf(\"%d\", e.amount), ui.Cell(e.note))\n\t}\n\treturn s + t.String() + \"\\n\"\n}\n\nfunc renderUsage() string {\n\ts := md.H2(\"Use it\") + \"\\n\"\n\ts += md.BulletItem(ui.Action(\"Claim \"+ufmt.Sprintf(\"%d moultest\", ClaimAmount), \"Claim\"))\n\ts += \"\\n\"\n\ts += \"Then it is an ordinary coin, and moving it needs nothing from this realm:\\n\\n\"\n\ts += md.LanguageCodeBlock(\"\", \"\"+\n\t\t\"# help yourself\\n\"+\n\t\t\"gnokey maketx call -pkgpath \"+Path+\" -func Claim ...\\n\\n\"+\n\t\t\"# send some to a friend: a bank message, no realm call at all\\n\"+\n\t\t\"gnokey maketx send -to \u003caddress\u003e -send 2500\"+Denom+\" ...\\n\\n\"+\n\t\t\"# tip somebody through this realm, note included. The coin rides the\\n\"+\n\t\t\"# envelope, which is the thing a GRC20 cannot do.\\n\"+\n\t\t\"gnokey maketx call -pkgpath \"+Path+\" -func Tip \\\\\\n\"+\n\t\t\"  -args \u003caddress\u003e -args \\\"nice work\\\" -send 1000\"+Denom+\" ...\\n\\n\"+\n\t\t\"# destroy some of your own\\n\"+\n\t\t\"gnokey maketx call -pkgpath \"+Path+\" -func Burn -args 1000 ...\")\n\ts += \"\\n\" + md.Italic(\"Worthless by construction. Do not price it.\") + \"\\n\"\n\treturn s\n}\n"}]},"send":"","max_deposit":"11000000ugnot"}],"fee":{"gas_wanted":"82475600","gas_fee":"247426ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"/2M+i5beWEPEn6Bt6FFMvQBToKjRuk85l5Snrhltuf4HvBMjhKSGegcQ4jea5XtyN+uI0KCiz0qF5Wl0LllnMg=="}],"memo":""},"metadata":{"timestamp":"1790961573"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"nativereg","path":"gno.land/r/moul/x/nativereg/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/nativereg/v0`\n\n**The metadata a native coin does not have.**\n\n`/gno.land/r/moul/x/moultest/v0:moultest` is the entire object. The chain stores a\nstring and a balance: no name, no symbol, no decimals, no icon, no link to the\nissuer. A wallet showing you that balance has only the path to print.\n\nThis realm is where a denom says what it is. It is the mirror of\n[`r/nt/grc20reg`](https://gno.land/r/nt/grc20reg/v0), and the two solve opposite\nproblems: a GRC20 carries its own name and is hard to **find**, so that registry\nmaps a key to an object; a native denom is trivial to find and carries **no**\nname, so this one maps the denom to what it means.\n\n## Registration is proved, not claimed\n\nA denom embeds the package path of the realm allowed to issue it, verbatim:\n`\"/\" + pkgPath + \":\" + baseName`. So the issuer is readable from the string, and\n`Register` simply requires the caller to be it. No allowlist, no owner, no\nsignature scheme.\n\n```go\nimport \"gno.land/r/moul/x/nativereg/v0\"\n\nfunc init(cur realm) {\n    nativereg.Register(cross(cur), Denom, \"My Coin\", \"MINE\", 6,\n        \"one line about what it is for\")\n}\n```\n\nA user account cannot register anything, not even a denom it holds every unit of:\nthere is no package path in a user call to compare against. What is being\ndescribed is the issuance, not the holding.\n\n`IssuerOf(denom)` answers the same question for a denom nobody ever registered,\nwhich is the case that matters: given a balance you did not ask for, that is how\nyou find the code that can take it away.\n\n## Facts and hints\n\n`Denom` and `Issuer` are facts, because the chain enforces the relation between\nthem. Everything else is whatever the issuing realm chose to say, and `Decimals`\nin particular is a **display hint with nothing behind it**: the bank has no notion\nof divisibility, so a coin wrapped out of a 6-decimal GRC20 is still counted in\nwhole units by every balance query.\n\nTrusting an entry means trusting the realm that wrote it, exactly as much as\nholding its coin already means trusting it not to call `RemoveCoin` on you.\n\n`?\u003cdenom\u003e` shows one entry, `?\u003cpkgpath\u003e` shows everything one realm issues.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/nativereg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativereg/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/nativereg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativereg/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/nativereg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativereg/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/nativereg/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativereg/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/nativereg/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/nativereg/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/nativereg/v0\"\ngno = \"0.9\"\n\n# public: it exists to be imported. A realm registers the denom it issues by\n# calling Register from its own frame, which is the whole authorization model,\n# and a private realm cannot be imported at all.\n"},{"name":"nativereg.gno","body":"// Package nativereg is the metadata a native coin does not have.\n//\n// A realm-issued coin is a string and a balance. `/gno.land/r/moul/x/moultest/v0:moultest`\n// is the entire object: no name, no symbol, no decimals, no icon, no link to\n// whoever issues it. The bank knows the number and nothing else, so a wallet or\n// an explorer showing you a balance has only that path to print.\n//\n// This realm is where a denom says what it is. It is the mirror image of\n// `r/nt/grc20reg`, and the two solve opposite problems: a GRC20 is an object\n// that carries its own name and is hard to FIND, so the registry maps a key to\n// the object; a native denom is trivial to find and carries no name, so the\n// registry maps the denom to what it means.\n//\n// # Registration is proved, not claimed\n//\n// A denom embeds the package path of the realm allowed to issue it, verbatim:\n// `\"/\" + pkgPath + \":\" + baseName` (`chain.CoinDenom`). So the issuer is\n// readable from the denom, and [Register] simply requires the caller to be it.\n// A realm registers its own coins and nobody else's, with no allowlist, no\n// owner and no signature scheme.\n//\n// A user account cannot register anything, not even a denom it holds all of:\n// there is no package path in a user call to compare against. That is the\n// intended shape, since the thing being described is the issuance, not the\n// holding.\n//\n// # What is a hint and what is a fact\n//\n// `Denom` and `Issuer` are facts: the chain enforces the relation between them.\n// Everything else is whatever the issuing realm chose to say, and `Decimals` in\n// particular is a DISPLAY hint with nothing behind it. The bank has no notion of\n// divisibility; a coin wrapped out of a 6-decimal GRC20 is still counted in\n// whole units by every balance query. Rendering 1000000 as 1.000000 is a\n// convention between this realm and whoever reads it.\n//\n// So trusting an entry means trusting the realm that wrote it, exactly as much\n// as holding its coin already means trusting it not to call `RemoveCoin` on you.\npackage nativereg\n\nimport (\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Entry is what one denom says about itself.\ntype Entry struct {\n\t// Denom is the full chain denom, the key of this registry.\n\tDenom string\n\t// Issuer is the package path embedded in Denom: the only realm that can\n\t// issue, remove or re-describe this coin.\n\tIssuer string\n\t// Name, Symbol and Decimals are display metadata, chosen by the issuer.\n\t// Decimals is a hint; see the package doc.\n\tName     string\n\tSymbol   string\n\tDecimals int\n\t// Doc is one line about what the coin is for.\n\tDoc string\n\t// Height is when the entry was last written.\n\tHeight int64\n\t// Revisions counts how many times the issuer has rewritten it.\n\tRevisions int\n}\n\nconst (\n\t// MaxName, MaxSymbol and MaxDoc bound what an issuer can store here. The\n\t// registry pays the storage for every byte a caller hands it, so the\n\t// limits are the realm's own cost control, not a style rule.\n\tMaxName   = 40\n\tMaxSymbol = 12\n\tMaxDoc    = 200\n\t// MaxDecimals matches the GRC20 ceiling, which is where a wrapped coin's\n\t// hint comes from in practice.\n\tMaxDecimals = 18\n)\n\nvar (\n\tbyDenom = avl.NewTree() // denom -\u003e *Entry\n\tdenoms  []string        // registration order, for a stable Render\n)\n\n// Register records or rewrites what a denom means. The caller must be the realm\n// the denom names, which is the entire authorization.\n//\n// Calling it again overwrites the entry and bumps [Entry.Revisions]. An issuer\n// can always re-describe its own coin, and can never describe anybody else's.\nfunc Register(cur realm, denom, name, symbol string, decimals int, doc string) {\n\tissuer := issuerOf(denom)\n\tprev := cur.Previous()\n\tif prev.PkgPath() == \"\" {\n\t\tpanic(\"only the issuing realm can register a denom; a user account has no package path to prove\")\n\t}\n\tif prev.PkgPath() != issuer {\n\t\tpanic(ufmt.Sprintf(\"%s is issued by %s, not by %s\", denom, issuer, prev.PkgPath()))\n\t}\n\tassertLen(\"name\", name, MaxName)\n\tassertLen(\"symbol\", symbol, MaxSymbol)\n\tassertLen(\"doc\", doc, MaxDoc)\n\tif decimals \u003c 0 || decimals \u003e MaxDecimals {\n\t\tpanic(ufmt.Sprintf(\"decimals is %d, must be 0 to %d\", decimals, MaxDecimals))\n\t}\n\n\te := \u0026Entry{\n\t\tDenom:    denom,\n\t\tIssuer:   issuer,\n\t\tName:     name,\n\t\tSymbol:   symbol,\n\t\tDecimals: decimals,\n\t\tDoc:      doc,\n\t\tHeight:   runtime.ChainHeight(),\n\t}\n\tif old := byDenom.Get(denom); old != nil {\n\t\te.Revisions = old.(*Entry).Revisions + 1\n\t} else {\n\t\tdenoms = append(denoms, denom)\n\t}\n\tbyDenom.Set(denom, e)\n}\n\n// Get returns the entry for a denom, and whether it has one.\nfunc Get(denom string) (Entry, bool) {\n\tv := byDenom.Get(denom)\n\tif v == nil {\n\t\treturn Entry{}, false\n\t}\n\treturn *v.(*Entry), true\n}\n\n// MustGet is [Get] for a caller that treats an unregistered denom as a bug.\nfunc MustGet(denom string) Entry {\n\te, ok := Get(denom)\n\tif !ok {\n\t\tpanic(\"no entry for \" + denom)\n\t}\n\treturn e\n}\n\n// IsRegistered reports whether a denom has said anything about itself.\nfunc IsRegistered(denom string) bool {\n\treturn byDenom.Get(denom) != nil\n}\n\n// List returns every entry, in registration order.\nfunc List() []Entry {\n\tout := make([]Entry, 0, len(denoms))\n\tfor _, d := range denoms {\n\t\tout = append(out, MustGet(d))\n\t}\n\treturn out\n}\n\n// ByIssuer returns every entry issued by one realm, in registration order.\nfunc ByIssuer(pkgPath string) []Entry {\n\tout := []Entry{}\n\tfor _, d := range denoms {\n\t\tif e := MustGet(d); e.Issuer == pkgPath {\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out\n}\n\n// Count returns how many denoms are registered.\nfunc Count() int { return byDenom.Size() }\n\n// IssuerOf returns the package path embedded in a denom, without consulting the\n// registry: the relation is in the string itself. It aborts on anything that is\n// not a realm denom, which includes `ugnot`.\n//\n// It is exported because it is useful to anybody handling a denom, registered or\n// not: given a balance, this is how you find the code that can take it away.\nfunc IssuerOf(denom string) string { return issuerOf(denom) }\n\nfunc issuerOf(denom string) string {\n\tif !strings.HasPrefix(denom, \"/\") {\n\t\tpanic(\"not a realm denom (it must start with /): \" + denom)\n\t}\n\ti := strings.LastIndex(denom, \":\")\n\tif i \u003c 0 {\n\t\tpanic(\"not a realm denom (it must contain :): \" + denom)\n\t}\n\tissuer := denom[1:i]\n\tif issuer == \"\" || denom[i+1:] == \"\" {\n\t\tpanic(\"malformed denom: \" + denom)\n\t}\n\treturn issuer\n}\n\nfunc assertLen(what, s string, max int) {\n\tif len(s) \u003e max {\n\t\tpanic(ufmt.Sprintf(\"%s is %d bytes, max %d\", what, len(s), max))\n\t}\n}\n"},{"name":"nativereg_test.gno","body":"package nativereg\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst (\n\tissuerPath = \"gno.land/r/test/coiner\"\n\tissuerCoin = \"/gno.land/r/test/coiner:testcoin\"\n\totherPath  = \"gno.land/r/test/stranger\"\n\totherCoin  = \"/gno.land/r/test/stranger:othercoin\"\n)\n\n// testing.SetRealm governs only the crossing calls made from the frame that\n// called it, so each switch below is inline in the test body.\n\nfunc TestOnlyTheIssuerRegisters(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(issuerPath))\n\tRegister(cross(cur), issuerCoin, \"Test Coin\", \"TEST\", 6, \"a coin for a test\")\n\n\te := MustGet(issuerCoin)\n\tuassert.Equal(t, issuerPath, e.Issuer, \"the issuer is read out of the denom, not supplied\")\n\tuassert.Equal(t, \"TEST\", e.Symbol)\n\tuassert.Equal(t, 6, e.Decimals)\n\tuassert.Equal(t, 0, e.Revisions)\n\n\t// The same realm cannot describe somebody else's coin.\n\tuassert.AbortsContains(t, cur, \"is issued by \"+otherPath, func() {\n\t\tRegister(cross(cur), otherCoin, \"Not Mine\", \"NOPE\", 0, \"\")\n\t})\n}\n\nfunc TestAUserAccountCannotRegister(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"nr-alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t// Even for a denom she holds every unit of: what is being described is the\n\t// issuance, and a wallet has no package path to prove.\n\tuassert.AbortsContains(t, cur, \"no package path to prove\", func() {\n\t\tRegister(cross(cur), issuerCoin, \"Mine Now\", \"MINE\", 0, \"\")\n\t})\n}\n\nfunc TestReregisteringBumpsRevisions(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(issuerPath))\n\tbefore := Count()\n\tRegister(cross(cur), issuerCoin, \"Test Coin v2\", \"TEST2\", 4, \"renamed\")\n\n\te := MustGet(issuerCoin)\n\tuassert.Equal(t, \"TEST2\", e.Symbol, \"an issuer can always re-describe its own coin\")\n\tuassert.Equal(t, 1, e.Revisions)\n\tuassert.Equal(t, before, Count(), \"a rewrite is not a second entry\")\n\tuassert.Equal(t, 1, len(ByIssuer(issuerPath)))\n\tuassert.Equal(t, 0, len(ByIssuer(otherPath)))\n}\n\nfunc TestBounds(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(issuerPath))\n\tuassert.AbortsContains(t, cur, \"name is\", func() {\n\t\tRegister(cross(cur), issuerCoin, strings.Repeat(\"x\", MaxName+1), \"T\", 0, \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"symbol is\", func() {\n\t\tRegister(cross(cur), issuerCoin, \"n\", strings.Repeat(\"x\", MaxSymbol+1), 0, \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"doc is\", func() {\n\t\tRegister(cross(cur), issuerCoin, \"n\", \"T\", 0, strings.Repeat(\"x\", MaxDoc+1))\n\t})\n\tuassert.AbortsContains(t, cur, \"decimals is 19\", func() {\n\t\tRegister(cross(cur), issuerCoin, \"n\", \"T\", MaxDecimals+1, \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"decimals is -1\", func() {\n\t\tRegister(cross(cur), issuerCoin, \"n\", \"T\", -1, \"\")\n\t})\n}\n\nfunc TestIssuerOfReadsTheDenom(cur realm, t *testing.T) {\n\t// The relation is in the string, so this answers for a denom nobody ever\n\t// registered, which is the case that matters: given a balance you did not\n\t// ask for, this is how you find the code that can take it away.\n\tuassert.Equal(t, \"gno.land/r/nobody/here/v3\", IssuerOf(\"/gno.land/r/nobody/here/v3:ghost\"))\n\tuassert.Equal(t, issuerPath, IssuerOf(issuerCoin))\n\n\tuassert.PanicsContains(t, cur, \"must start with /\", func() { IssuerOf(\"ugnot\") })\n\tuassert.PanicsContains(t, cur, \"must contain :\", func() { IssuerOf(\"/gno.land/r/a/v0\") })\n\tuassert.PanicsContains(t, cur, \"malformed\", func() { IssuerOf(\"/gno.land/r/a/v0:\") })\n\tuassert.PanicsContains(t, cur, \"malformed\", func() { IssuerOf(\"/:x\") })\n}\n\nfunc TestUnregisteredReadsCleanly(cur realm, t *testing.T) {\n\t_, ok := Get(\"/gno.land/r/nobody/here/v3:ghost\")\n\tuassert.False(t, ok)\n\tuassert.False(t, IsRegistered(\"/gno.land/r/nobody/here/v3:ghost\"))\n\tuassert.PanicsContains(t, cur, \"no entry for\", func() { MustGet(\"/gno.land/r/x/y/v0:zz\") })\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(otherPath))\n\tRegister(cross(cur), otherCoin, \"Other Coin\", \"OTHER\", 0, \"the second one\")\n\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"# nativereg\"), index)\n\tuassert.True(t, strings.Contains(index, \"OTHER\"), \"the index lists entries:\\n\"+index)\n\n\tone := Render(otherCoin)\n\tuassert.True(t, strings.Contains(one, \"the second one\"), one)\n\tuassert.True(t, strings.Contains(one, otherPath), one)\n\n\tbyIssuer := Render(issuerPath)\n\tuassert.True(t, strings.Contains(byIssuer, \"TEST2\"), byIssuer)\n\tuassert.False(t, strings.Contains(byIssuer, \"OTHER\"), \"one issuer's page shows only its own\")\n\n\t// A Render never aborts on a path a reader typed, registered or not.\n\tuassert.True(t, strings.Contains(Render(\"/gno.land/r/x/y/v0:nope\"), \"Not registered\"))\n\tuassert.True(t, strings.Contains(Render(\"ugnot\"), \"registered nothing\"),\n\t\t\"a non-denom path falls through to the issuer view rather than aborting\")\n\tuassert.True(t, strings.Contains(Render(\"/garbage\"), \"not a realm denom\"))\n}\n\nfunc TestRenderEscapesWhatAnIssuerWrote(cur realm, t *testing.T) {\n\t// An issuer's own name and doc are still caller-supplied text, and a realm\n\t// that can register can write a table-breaking pipe as easily as a name.\n\tconst nasty = \"gno.land/r/test/nasty\"\n\ttesting.SetRealm(testing.NewCodeRealm(nasty))\n\tRegister(cross(cur), \"/gno.land/r/test/nasty:nastycoin\", \"a|b\", \"x|y\", 0, \"\")\n\n\tindex := Render(\"\")\n\tuassert.False(t, strings.Contains(index, \"| a|b |\"), \"a raw pipe would open a column:\\n\"+index)\n\tuassert.True(t, strings.Contains(index, \"a\\\\|b\"), \"it is escaped instead:\\n\"+index)\n}\n"},{"name":"render.gno","body":"package nativereg\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Render lists the registry. `?\u003cdenom\u003e` shows one entry, `?\u003cpkgpath\u003e` shows\n// everything one realm issues.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\tif strings.HasPrefix(path, \"/\") {\n\t\treturn renderDenom(path)\n\t}\n\treturn renderIssuer(path)\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(md.H1(\"nativereg: what a native denom means\"))\n\tsb.WriteString(\"\\nA realm-issued coin is a string and a balance. The chain stores no name, \" +\n\t\t\"no symbol and no decimals for it, so this realm does. An issuer registers its own \" +\n\t\t\"denoms and nobody else's: the package path is embedded in the denom, and that is \" +\n\t\t\"the whole authorization.\\n\\n\")\n\n\tt := ui.NewTable(\"denom\", \"symbol\", \"name\", \"decimals\", \"issuer\")\n\tfor _, e := range List() {\n\t\tt.Row(md.InlineCode(ui.ShortN(e.Denom, 22, 12)), ui.Cell(e.Symbol), ui.Cell(e.Name),\n\t\t\tufmt.Sprintf(\"%d\", e.Decimals), md.Link(ui.Short(e.Issuer), \"/\"+strings.TrimPrefix(e.Issuer, \"gno.land/\")))\n\t}\n\tsb.WriteString(md.H2(\"Registered\"))\n\tsb.WriteString(\"\\n\" + t.OrEmpty(\"Nothing registered yet.\") + \"\\n\")\n\n\tsb.WriteString(md.H2(\"Register your own\"))\n\tsb.WriteString(\"\\nFrom inside the realm that issues the coin, never from a wallet:\\n\\n\")\n\tsb.WriteString(md.LanguageCodeBlock(\"go\",\n\t\t\"import \\\"gno.land/r/moul/x/nativereg/v0\\\"\\n\\n\"+\n\t\t\t\"func init(cur realm) {\\n\"+\n\t\t\t\"\\tnativereg.Register(cross(cur), Denom, \\\"My Coin\\\", \\\"MINE\\\", 6,\\n\"+\n\t\t\t\"\\t\\t\\\"one line about what it is for\\\")\\n\"+\n\t\t\t\"}\"))\n\tsb.WriteString(\"\\n\" + md.Italic(\"Decimals is a display hint. The bank counts whole units and \"+\n\t\t\"knows nothing about divisibility.\") + \"\\n\")\n\treturn sb.String()\n}\n\nfunc renderDenom(denom string) string {\n\te, ok := Get(denom)\n\tif !ok {\n\t\treturn md.H1(\"Not registered\") + \"\\n\" + md.InlineCode(denom) +\n\t\t\t\" has said nothing about itself.\\n\\nIts issuer is \" +\n\t\t\tmd.InlineCode(safeIssuer(denom)) + \", and only that realm can change it.\\n\"\n\t}\n\n\tt := ui.NewTable(\"\", \"\")\n\tt.Row(\"denom\", md.InlineCode(e.Denom))\n\tt.Row(\"issuer\", md.InlineCode(e.Issuer))\n\tt.Row(\"name\", ui.Cell(e.Name))\n\tt.Row(\"symbol\", ui.Cell(e.Symbol))\n\tt.Row(\"decimals\", ufmt.Sprintf(\"%d (display hint)\", e.Decimals))\n\tt.Row(\"registered at block\", ufmt.Sprintf(\"%d\", e.Height))\n\tt.Row(\"revisions\", ufmt.Sprintf(\"%d\", e.Revisions))\n\n\ts := md.H1(ui.Inline(e.Symbol)) + \"\\n\"\n\tif e.Doc != \"\" {\n\t\ts += ui.Inline(e.Doc) + \"\\n\\n\"\n\t}\n\ts += t.String() + \"\\n\"\n\ts += md.Blockquote(\"The issuer can rewrite every row but the first two, and can remove \"+\n\t\t\"this coin from any balance at any time. That is what a realm-issued coin is.\") + \"\\n\"\n\treturn s\n}\n\nfunc renderIssuer(pkgPath string) string {\n\tentries := ByIssuer(pkgPath)\n\ts := md.H1(\"Issued by \"+ui.Inline(pkgPath)) + \"\\n\"\n\tt := ui.NewTable(\"denom\", \"symbol\", \"name\")\n\tfor _, e := range entries {\n\t\tt.Row(md.InlineCode(ui.ShortN(e.Denom, 22, 12)), ui.Cell(e.Symbol), ui.Cell(e.Name))\n\t}\n\treturn s + t.OrEmpty(\"This realm has registered nothing here.\") + \"\\n\"\n}\n\n// safeIssuer is IssuerOf for a Render, which must never abort on a path a reader\n// typed into the URL bar.\nfunc safeIssuer(denom string) string {\n\tif !strings.HasPrefix(denom, \"/\") {\n\t\treturn \"unknown (not a realm denom)\"\n\t}\n\ti := strings.LastIndex(denom, \":\")\n\tif i \u003c 1 {\n\t\treturn \"unknown (not a realm denom)\"\n\t}\n\treturn denom[1:i]\n}\n"}]},"send":"","max_deposit":"8000000ugnot"}],"fee":{"gas_wanted":"62177400","gas_fee":"186532ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"/BO08eH2AwY/E8j0DHVrmKBBENXbwlhfnwZdaNCfK4J5CL7mupQCfN0Iz5TLOmFgI6ObNVIj/O6wZcDFTGfVeQ=="}],"memo":""},"metadata":{"timestamp":"1790961574"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"nativeify","path":"gno.land/r/moul/x/nativeify/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/nativeify/v0`\n\n**wugnot, backwards: escrow a GRC20, issue a native coin against it 1:1.**\n\nwugnot takes GNOT, a coin the bank holds, and issues a GRC20 receipt, because a\nGRC20 can be pulled by a contract and a native coin cannot. This realm runs the\nother direction, because a native coin can do four things a GRC20 cannot:\n\n- move with no realm call at all, from any wallet\n- ride the `-send` envelope of a call, so it can **pay** for something\n- sit beside GNOT on an account page, with nothing registered anywhere\n- be named as the gas denom by a chain whose genesis says so\n\n## What you give up, and it is not small\n\nA native coin cannot be pulled. `banker.SendCoins` refuses any `from` that is not\nthe banker's own realm address, so there is no allowance, no `TransferFrom`, and\nno way for an AMM, an escrow or a subscription to take what you approved.\nEverything downstream of `Approve` stops working the moment a coin becomes native.\nA test in this package pins it: the realm holds the strongest banker the chain\noffers, the one that can mint and destroy this denom at will, and it still cannot\nmove a unit it does not already hold.\n\nAnd the issuer of a native coin can always delete a balance, because `RemoveCoin`\ntakes an arbitrary address. This realm never calls it on an address other than its\nown, and it is deployed **public** rather than `private = true` so that the code\nsaying so can never be replaced. Those two together are the entire guarantee;\nthere is no on-chain way to prove a negative about code.\n\n## Use it\n\n```\n# 1. play money\nmaketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Claim\n\n# 2. let this realm pull your RED (Home() prints the address)\nmaketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Approve \\\n  -args RED -args \u003chome\u003e -args 1000000\n\n# 3. create the pair once, then wrap into it\nmaketx call -pkgpath gno.land/r/moul/x/nativeify/v0 -func Nativeify \\\n  -args gno.land/r/moul/x/grc20faucet/v0.RED -args nred\nmaketx call -pkgpath gno.land/r/moul/x/nativeify/v0 -func Wrap -args nred -args 500000\n\n# 4. it is an ordinary coin now\nmaketx send -to \u003caddress\u003e -send 1000/gno.land/r/moul/x/nativeify/v0:nred\n\n# 5. redeem, by sending the coins back\nmaketx call -pkgpath gno.land/r/moul/x/nativeify/v0 -func Unwrap -args nred \\\n  -send 1000/gno.land/r/moul/x/nativeify/v0:nred\n```\n\nStep 5 is the interesting one. This realm could delete your coins directly and\nsave you a flag, and it does not: a realm whose normal operation is to remove\ncoins from addresses that never handed them over has no way left to demonstrate\nthat it only ever does so consensually.\n\n## The rate is 1, and solvency is checkable without trusting this realm\n\nOne smallest unit of the underlying is one unit of the coin. Not `10^decimals`:\nthe bank has no notion of divisibility, so a token with 6 decimals produces a coin\ncounted in the token's own smallest units, and the 6 travels to\n[`nativereg`](https://gno.land/r/moul/x/nativereg/v0) as a display hint and\nnowhere else.\n\n`Solvency` reads the escrow from the GRC20 ledger and the supply from the bank,\nand consults this realm's own bookkeeping for neither. If the two ever disagree,\nthe disagreement is the answer.\n\nOne native denom per underlying token: a second would double the chain's per-denom\nstorage for no new capability, and realm-denom balances live under their own store\nkeys, which are not gas-metered.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/nativeify/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativeify/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/nativeify/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativeify/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/nativeify/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativeify/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/nativeify/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/nativeify/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/nativeify/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/nativeify/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/nativeify/v0\"\ngno = \"0.9\"\n\n# public: it issues coins, and an issuing realm must be immutable. private = true\n# buys a redeploy, and a redeploy of an issuer replaces the code that decided not\n# to claw anybody's balance back while the coins themselves survive. Holders of a\n# coin from here are trusting this code, so this path can never be rewritten.\n"},{"name":"nativeify.gno","body":"// Package nativeify turns a GRC20 into a native coin, which is wugnot run\n// backwards.\n//\n// wugnot takes GNOT, a coin the bank holds, and issues a GRC20 receipt for it,\n// because a GRC20 can be pulled by a contract and a native coin cannot. This\n// realm takes a GRC20, escrows it, and issues a native denom against it 1:1,\n// because a native coin can do four things a GRC20 cannot:\n//\n//   - move with no realm call at all (`gnokey maketx send`, from any wallet)\n//   - ride the `-send` envelope of a call, so it can PAY for something\n//   - sit beside GNOT on an account page, with nothing registered anywhere\n//   - be named as the gas denom by a chain whose genesis says so\n//\n// # What you give up, and it is not small\n//\n// A native coin cannot be pulled. `banker.SendCoins` refuses any `from` that is\n// not the banker's own realm address, so there is no allowance, no\n// `TransferFrom`, and no way for an AMM, an escrow or a subscription to take\n// what you approved. Everything downstream of `Approve` stops working the moment\n// a coin becomes native. That is not a gap in this realm; it is the property\n// that makes the wrapping worth doing in the other direction.\n//\n// And the issuer of a native coin can always delete a balance: `RemoveCoin`\n// takes an arbitrary address. This realm never calls it on an address other than\n// its own, [Unwrap] explains why in detail, and the gnomod.toml explains why this\n// path is public rather than redeployable. Those three together are the entire\n// guarantee. There is no on-chain way to prove a negative about code.\n//\n// # The exchange rate is 1, always\n//\n// One smallest unit of the underlying is one unit of the coin. Not 10^decimals:\n// the bank has no notion of divisibility, so a token with 6 decimals wrapped\n// here produces a coin counted in the token's own smallest units, and the 6 is\n// carried to `r/moul/x/nativereg` as a display hint and nowhere else.\n//\n// Solvency is therefore a plain equality that anybody can check without trusting\n// this realm's bookkeeping: the GRC20 balance at this realm's address equals the\n// total supply of the denom. [Solvency] computes it from both sides.\n//\n// Play money to try it on: `r/moul/x/grc20faucet/v0`.\npackage nativeify\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/envelope/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n\t\"gno.land/r/moul/x/nativereg/v0\"\n)\n\n// Path is this realm's package path, which every denom it issues embeds.\nconst Path = \"gno.land/r/moul/x/nativeify/v0\"\n\n// MinBase and MaxBase bound a base denom name. The chain enforces exactly this\n// (`isValidBaseDenom` in the banker stdlib): a lowercase letter, then 2 to 15\n// more lowercase letters or digits. Validating here rather than letting the\n// banker abort is the difference between a usable error and a stack trace.\nconst (\n\tMinBase = 3\n\tMaxBase = 16\n)\n\ntype pair struct {\n\tbase    string // base denom name, unique in this realm\n\tdenom   string // the full chain denom\n\tkey     string // grc20reg key of the underlying\n\tcreator address\n\theight  int64\n}\n\nvar (\n\tbyBase = avl.NewTree() // base name -\u003e *pair\n\tbyKey  = avl.NewTree() // grc20reg key -\u003e *pair\n\tbases  []string        // creation order, for a stable Render\n\thome   address         // this realm's address: where every escrow sits\n)\n\nfunc init(cur realm) {\n\thome = cur.Address()\n}\n\n// Home is the address to approve on the underlying token before wrapping. Every\n// escrow this realm holds sits there.\nfunc Home() address { return home }\n\n// Nativeify creates the native counterpart of a GRC20 registered in\n// `r/nt/grc20reg`, and returns its denom. It issues nothing: [Wrap] does that.\n//\n// `base` is the part of the denom after the colon, yours to choose, unique in\n// this realm and in the chain's charset. One native denom per underlying token:\n// a second one would double the chain's per-denom storage for no new capability,\n// and realm-denom balances live under their own store keys, which are not\n// gas-metered.\nfunc Nativeify(cur realm, tokenKey, base string) string {\n\tunder := grc20reg.MustGet(tokenKey)\n\tassertBase(base)\n\tif byBase.Get(base) != nil {\n\t\tpanic(\"this realm already issues \" + base)\n\t}\n\tif v := byKey.Get(tokenKey); v != nil {\n\t\tpanic(ufmt.Sprintf(\"%s is already native here as %s\", under.GetSymbol(), v.(*pair).denom))\n\t}\n\n\tp := \u0026pair{\n\t\tbase:    base,\n\t\tdenom:   chain.CoinDenom(Path, base),\n\t\tkey:     tokenKey,\n\t\tcreator: cur.Previous().Address(),\n\t\theight:  runtime.ChainHeight(),\n\t}\n\tbyBase.Set(base, p)\n\tbyKey.Set(tokenKey, p)\n\tbases = append(bases, base)\n\n\t// This realm is the issuer named inside the denom, so it is the only thing\n\t// on the chain that can describe it. The decimals travel as a display hint;\n\t// the bank still counts whole units.\n\tnativereg.Register(cross(cur), p.denom,\n\t\tunder.GetName()+\" (native)\", \"n\"+under.GetSymbol(), under.GetDecimals(),\n\t\t\"1:1 native wrapper of \"+tokenKey+\", redeemable at \"+Path)\n\treturn p.denom\n}\n\n// Wrap escrows `amount` of the underlying and issues the same number of native\n// coins to the caller.\n//\n// You must `Approve` this realm's address on the underlying token first, through\n// that token's own realm. Until you do, this realm has no authority over your\n// balance at all, and Wrap fails with \"insufficient allowance\", which is the\n// system working.\nfunc Wrap(cur realm, base string, amount int64) int64 {\n\tp := mustPair(base)\n\tif amount \u003c= 0 {\n\t\tpanic(\"wrap a positive amount\")\n\t}\n\twho := cur.Previous().Address()\n\n\t// Last point at which nothing has moved.\n\tunder := grc20reg.MustGet(p.key)\n\tif err := under.RealmTeller(0, cur).TransferFrom(0, cur, who, home, amount); err != nil {\n\t\tpanic(err)\n\t}\n\tbanker.NewBanker(banker.BankerTypeRealmIssue, cur).IssueCoin(who, p.denom, amount)\n\treturn amount\n}\n\n// Unwrap destroys the native coins attached to this call and releases the same\n// number of underlying GRC20 units to the caller.\n//\n// # Why you have to send the coins rather than let this realm take them\n//\n// This realm holds a `BankerTypeRealmIssue` banker, and `RemoveCoin` takes an\n// arbitrary address, so it could delete the caller's coins directly and save\n// them a flag. It does not, and the reason is worth stating where somebody\n// copying this will read it: a realm whose normal operation is to remove coins\n// from addresses that did not hand them over has no way left to demonstrate that\n// it only ever does so consensually. Every `RemoveCoin` here names this realm's\n// own address, which anybody can check by reading the source, and the coins get\n// to that address the only way a native coin ever moves, by their holder pushing\n// them.\n//\n// So: attach them.\n//\n//\t-send \u003camount\u003e/gno.land/r/moul/x/nativeify/v0:\u003cbase\u003e\nfunc Unwrap(cur realm, base string) int64 {\n\tp := mustPair(base)\n\t// Reading the envelope is also what makes this call payable at all: MsgCall\n\t// rejects a message whose coins no code looked at.\n\tamount := envelope.Require(p.denom)\n\twho := cur.Previous().Address()\n\n\t// Destroy the receipt before releasing the backing, so a failure between the\n\t// two can only ever leave the pair over-collateralized.\n\tbanker.NewBanker(banker.BankerTypeRealmIssue, cur).RemoveCoin(home, p.denom, amount)\n\tunder := grc20reg.MustGet(p.key)\n\tif err := under.RealmTeller(0, cur).Transfer(0, cur, who, amount); err != nil {\n\t\tpanic(err)\n\t}\n\treturn amount\n}\n\n// Denom returns the denom this realm issues for a base name.\nfunc Denom(base string) string { return mustPair(base).denom }\n\n// TokenKey returns the grc20reg key of the underlying behind a base name.\nfunc TokenKey(base string) string { return mustPair(base).key }\n\n// Bases returns every base name this realm issues, in creation order.\nfunc Bases() []string {\n\tout := make([]string, len(bases))\n\tcopy(out, bases)\n\treturn out\n}\n\n// Solvency returns what is escrowed and what is issued for a base name. They are\n// read from two different places on the chain, the GRC20 ledger and the bank,\n// and this realm's own bookkeeping is not consulted for either: if they ever\n// disagree, the disagreement is the answer.\nfunc Solvency(base string) (escrowed, issued int64) {\n\tp := mustPair(base)\n\tescrowed = grc20reg.MustGet(p.key).BalanceOf(home)\n\tissued = banker.NewReadonlyBanker().TotalCoin(p.denom)\n\treturn escrowed, issued\n}\n\n// IsSolvent reports whether every coin issued for a base name is backed.\n//\n// It allows escrowed \u003e issued, which is what a donation to this realm's address\n// looks like and cannot hurt anybody, and refuses the reverse.\nfunc IsSolvent(base string) bool {\n\tescrowed, issued := Solvency(base)\n\treturn escrowed \u003e= issued\n}\n\n// Underlying returns the underlying token behind a base name, for a caller that\n// wants its name, symbol or decimals.\nfunc Underlying(base string) *grc20.Token {\n\treturn grc20reg.MustGet(mustPair(base).key)\n}\n\nfunc mustPair(base string) *pair {\n\tv := byBase.Get(base)\n\tif v == nil {\n\t\tpanic(\"this realm does not issue \" + base)\n\t}\n\treturn v.(*pair)\n}\n\n// assertBase applies the chain's own base-denom rule before the banker does, so\n// the caller reads a sentence instead of a stack trace.\nfunc assertBase(base string) {\n\tif len(base) \u003c MinBase || len(base) \u003e MaxBase {\n\t\tpanic(ufmt.Sprintf(\"base %q is %d characters, must be %d to %d\",\n\t\t\tbase, len(base), MinBase, MaxBase))\n\t}\n\tfor i := 0; i \u003c len(base); i++ {\n\t\tc := base[i]\n\t\tlower := c \u003e= 'a' \u0026\u0026 c \u003c= 'z'\n\t\tdigit := c \u003e= '0' \u0026\u0026 c \u003c= '9'\n\t\tif lower || (i \u003e 0 \u0026\u0026 digit) {\n\t\t\tcontinue\n\t\t}\n\t\tpanic(ufmt.Sprintf(\"base %q: a base denom is a lowercase letter followed by \"+\n\t\t\t\"lowercase letters or digits, and %q is not\", base, string(c)))\n\t}\n\tif strings.Contains(base, \":\") { // unreachable past the charset loop; belt and braces\n\t\tpanic(\"a base denom cannot contain a colon\")\n\t}\n}\n"},{"name":"nativeify_test.gno","body":"package nativeify\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/envelope/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/moul/x/grc20faucet/v0\"\n\t\"gno.land/r/moul/x/nativereg/v0\"\n)\n\n// Two things about the harness shape every test below.\n//\n// testing.SetRealm governs only the crossing calls made from the frame that\n// called it, so every account switch is inline in the test body.\n//\n// The BANK does not carry over between test functions while realm state does,\n// so native balances, TotalCoin and the escrowed GRC20 cannot be compared\n// across tests. Everything here is asserted as a delta inside one test.\n\nfunc TestNativeifyCreatesThePair(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"nf-alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tdenom := Nativeify(cross(cur), grc20faucet.RedKey, \"nred\")\n\tuassert.Equal(t, \"/gno.land/r/moul/x/nativeify/v0:nred\", denom)\n\tuassert.Equal(t, denom, Denom(\"nred\"))\n\tuassert.Equal(t, grc20faucet.RedKey, TokenKey(\"nred\"))\n\n\t// The denom names this realm, so this realm is the only thing on the chain\n\t// that can describe it, and it did.\n\te := nativereg.MustGet(denom)\n\tuassert.Equal(t, Path, e.Issuer)\n\tuassert.Equal(t, \"nRED\", e.Symbol)\n\tuassert.Equal(t, 4, e.Decimals, \"the underlying's decimals travel as a display hint\")\n\n\tuassert.AbortsContains(t, cur, \"already issues nred\", func() {\n\t\tNativeify(cross(cur), grc20faucet.BlueKey, \"nred\")\n\t})\n\tuassert.AbortsContains(t, cur, \"already native here\", func() {\n\t\tNativeify(cross(cur), grc20faucet.RedKey, \"nred2\")\n\t})\n\tuassert.AbortsContains(t, cur, \"unknown token\", func() {\n\t\tNativeify(cross(cur), \"gno.land/r/nope/nope.NOPE\", \"nnope\")\n\t})\n}\n\nfunc TestBaseNameFollowsTheChainsRule(cur realm, t *testing.T) {\n\tbob := testutils.TestAddress(\"nf-bob\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\n\t// The chain's own rule, applied here so the caller reads a sentence instead\n\t// of a banker stack trace: a lowercase letter, then 2 to 15 more lowercase\n\t// letters or digits.\n\tuassert.AbortsContains(t, cur, \"is 2 characters\", func() {\n\t\tNativeify(cross(cur), grc20faucet.BlueKey, \"ab\")\n\t})\n\tuassert.AbortsContains(t, cur, \"is 17 characters\", func() {\n\t\tNativeify(cross(cur), grc20faucet.BlueKey, strings.Repeat(\"a\", 17))\n\t})\n\tuassert.AbortsContains(t, cur, \"is not\", func() {\n\t\tNativeify(cross(cur), grc20faucet.BlueKey, \"nBLUE\")\n\t})\n\tuassert.AbortsContains(t, cur, \"is not\", func() {\n\t\tNativeify(cross(cur), grc20faucet.BlueKey, \"1blue\")\n\t})\n\tuassert.AbortsContains(t, cur, \"is not\", func() {\n\t\tNativeify(cross(cur), grc20faucet.BlueKey, \"n-blue\")\n\t})\n\n\t// And one that is legal all the way through.\n\tuassert.Equal(t, \"/gno.land/r/moul/x/nativeify/v0:nblue1\",\n\t\tNativeify(cross(cur), grc20faucet.BlueKey, \"nblue1\"))\n}\n\nfunc TestWrapNeedsAnAllowanceFirst(cur realm, t *testing.T) {\n\tcarol := testutils.TestAddress(\"nf-carol\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tgrc20faucet.Claim(cross(cur))\n\n\t// Until the holder names this realm on the underlying token, this realm has\n\t// no authority over their balance whatsoever. That is the GRC20 half of the\n\t// trade, and it is the half a native coin does not have.\n\tuassert.AbortsContains(t, cur, \"allowance\", func() { Wrap(cross(cur), \"nred\", 1_000) })\n\tuassert.Equal(t, int64(0), envelope.BalanceOf(carol, Denom(\"nred\")))\n}\n\nfunc TestWrapEscrowsAndIssues(cur realm, t *testing.T) {\n\tdave := testutils.TestAddress(\"nf-dave\")\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tgrc20faucet.Claim(cross(cur))\n\tgrc20faucet.Approve(cross(cur), \"RED\", Home(), 1_000_000)\n\n\tdenom := Denom(\"nred\")\n\tredBefore := grc20faucet.BalanceOf(\"RED\", dave)\n\tescrowBefore, issuedBefore := Solvency(\"nred\")\n\n\tgot := Wrap(cross(cur), \"nred\", 400_000)\n\n\tuassert.Equal(t, int64(400_000), got)\n\tuassert.Equal(t, redBefore-400_000, grc20faucet.BalanceOf(\"RED\", dave), \"the GRC20 left the holder\")\n\tuassert.Equal(t, escrowBefore+400_000, grc20faucet.BalanceOf(\"RED\", Home()), \"and landed in escrow\")\n\tuassert.Equal(t, int64(400_000), envelope.BalanceOf(dave, denom), \"the native coin is at the bank, 1:1\")\n\n\tescrowAfter, issuedAfter := Solvency(\"nred\")\n\tuassert.Equal(t, escrowBefore+400_000, escrowAfter)\n\tuassert.Equal(t, issuedBefore+400_000, issuedAfter)\n\tuassert.True(t, IsSolvent(\"nred\"), \"every coin issued is backed\")\n\n\tuassert.AbortsContains(t, cur, \"positive amount\", func() { Wrap(cross(cur), \"nred\", 0) })\n\tuassert.AbortsContains(t, cur, \"does not issue\", func() { Wrap(cross(cur), \"ghost\", 1) })\n}\n\nfunc TestUnwrapDestroysTheCoinAndReleasesTheBacking(cur realm, t *testing.T) {\n\terin := testutils.TestAddress(\"nf-erin\")\n\tdenom := Denom(\"nred\")\n\n\ttesting.SetRealm(testing.NewUserRealm(erin))\n\tgrc20faucet.Claim(cross(cur))\n\tgrc20faucet.Approve(cross(cur), \"RED\", Home(), 1_000_000)\n\tWrap(cross(cur), \"nred\", 300_000)\n\n\t// On chain the -send envelope moves the coins to this realm's address before\n\t// Unwrap runs. The harness has no bank-send primitive, so the credit is\n\t// issued here; SetOriginSend is the half the realm actually reads.\n\tsent := chain.NewCoins(chain.NewCoin(denom, 120_000))\n\ttesting.IssueCoins(Home(), sent)\n\ttesting.SetOriginSend(sent)\n\n\tredBefore := grc20faucet.BalanceOf(\"RED\", erin)\n\tescrowBefore := grc20faucet.BalanceOf(\"RED\", Home())\n\t_, issuedBefore := Solvency(\"nred\")\n\n\tgot := Unwrap(cross(cur), \"nred\")\n\n\tuassert.Equal(t, int64(120_000), got)\n\tuassert.Equal(t, redBefore+120_000, grc20faucet.BalanceOf(\"RED\", erin), \"the backing came back\")\n\tuassert.Equal(t, escrowBefore-120_000, grc20faucet.BalanceOf(\"RED\", Home()), \"escrow shrank by the same\")\n\t_, issuedAfter := Solvency(\"nred\")\n\tuassert.Equal(t, issuedBefore-120_000, issuedAfter,\n\t\t\"the coins were destroyed, not moved: total supply fell\")\n\n\ttesting.SetOriginSend(nil)\n\tuassert.AbortsContains(t, cur, \"must be paid\", func() { Unwrap(cross(cur), \"nred\") })\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"# nativeify\"), index)\n\tuassert.True(t, strings.Contains(index, Home().String()), \"the escrow address is on the page\")\n\tuassert.True(t, strings.Contains(index, \"| [nred](/r/moul/x/nativeify/v0:nred) |\"),\n\t\t\"the pair is listed:\\n\"+index)\n\n\tone := Render(\"nred\")\n\tuassert.True(t, strings.Contains(one, \"/gno.land/r/moul/x/nativeify/v0:nred\"), one)\n\tuassert.True(t, strings.Contains(one, \"a display hint only\"), one)\n\n\tuassert.True(t, strings.Contains(Render(\"ghost\"), \"404\"), \"an unknown base renders a 404\")\n}\n\n// attemptPull is the thing a GRC20 facade over a native coin would have to do,\n// written out so it can be shown failing. It is in the test file, so it is not\n// part of the deployed package.\nfunc attemptPull(cur realm, from address, denom string, amount int64) {\n\tbanker.NewBanker(banker.BankerTypeRealmIssue, cur).\n\t\tSendCoins(from, Home(), chain.NewCoins(chain.NewCoin(denom, amount)))\n}\n\nfunc TestARealmCannotPullANativeCoin(cur realm, t *testing.T) {\n\t// The claim the package doc rests on, pinned rather than asserted: this\n\t// realm holds the strongest banker the chain offers, the one that can mint\n\t// and destroy this denom at will, and it still cannot MOVE a unit it does\n\t// not already hold. There is no allowance to grant and no TransferFrom to\n\t// call, which is why a grc20.Teller over a native coin cannot be written and\n\t// why wugnot wraps in the direction it does.\n\tfrank := testutils.TestAddress(\"nf-frank\")\n\tdenom := Denom(\"nred\")\n\ttesting.IssueCoins(frank, chain.NewCoins(chain.NewCoin(denom, 1_000)))\n\n\tmsg := pullError(cur, frank, denom, 1_000)\n\tuassert.True(t, strings.Contains(msg, \"can only send coins from realm that created banker\"),\n\t\t\"got: \"+msg)\n\tuassert.Equal(t, int64(1_000), envelope.BalanceOf(frank, denom), \"and nothing moved\")\n}\n\n// pullError runs attemptPull and returns the refusal as a string.\n//\n// uassert.PanicsContains cannot read this one. banker.SendCoins builds its\n// message as `\"...\" + b.pkgAddr + \"...\"`, and in gno a string concatenated with\n// an `address` has type `address`, so the panic value is an address rather than\n// a string and the helper reports \"recover: unsupported type\". Measured\n// 2026-09-28 against gno master; the message itself is correct, only its type is\n// surprising.\nfunc pullError(cur realm, from address, denom string, amount int64) (msg string) {\n\tdefer func() {\n\t\tswitch r := recover().(type) {\n\t\tcase nil:\n\t\t\tmsg = \"it did not fail at all\"\n\t\tcase address:\n\t\t\tmsg = string(r)\n\t\tcase string:\n\t\t\tmsg = r\n\t\tcase error:\n\t\t\tmsg = r.Error()\n\t\tdefault:\n\t\t\tmsg = \"panicked with an unexpected type\"\n\t\t}\n\t}()\n\tattemptPull(cur, from, denom, amount)\n\treturn \"\"\n}\n\n// ---------------------------------------------------------------------------\n// p/moul/x/envelope's Forward is exercised here rather than in its own package:\n// minting a BankerTypeOriginSend banker calls rlm.Previous(), and a p/ package's\n// test has no realm frame to walk, so it dies with \"frame not found: cannot seek\n// beyond origin caller override\". A p/ helper that needs a realm handle can only\n// be tested from a realm.\n\nfunc forwardDirect(cur realm, to address, coins chain.Coins) {\n\tenvelope.Forward(0, cur, to, coins)\n}\n\nfunc forwardOneDeeper(cur realm, to address, coins chain.Coins) {\n\tforwardDirect(cur, to, coins)\n}\n\nfunc TestForwardIsBoundedByTheEnvelope(cur realm, t *testing.T) {\n\tto := testutils.TestAddress(\"nf-forward-to\")\n\tdenom := Denom(\"nred\")\n\n\t// The realm holds 5,000 of its own, and the envelope carried 250. A\n\t// RealmSend banker could spend all 5,250; this one may spend 250.\n\ttesting.IssueCoins(Home(), chain.NewCoins(chain.NewCoin(denom, 5_000)))\n\tsent := chain.NewCoins(chain.NewCoin(denom, 250))\n\ttesting.IssueCoins(Home(), sent)\n\ttesting.SetOriginSend(sent)\n\n\theldBefore := envelope.BalanceOf(Home(), denom)\n\tforwardDirect(cur, to, sent)\n\n\tuassert.Equal(t, int64(250), envelope.BalanceOf(to, denom))\n\tuassert.Equal(t, heldBefore-250, envelope.BalanceOf(Home(), denom),\n\t\t\"exactly the envelope left, and none of the realm's own balance\")\n\n\t// Spending past the envelope is refused by the VM, not by any check here.\n\tuassert.PanicsContains(t, cur, \"limit\", func() {\n\t\tforwardDirect(cur, to, chain.NewCoins(chain.NewCoin(denom, 5_000)))\n\t})\n\ttesting.SetOriginSend(nil)\n}\n\nfunc TestForwardFromOneFrameDeeper(cur realm, t *testing.T) {\n\t// The frame-depth rule, measured rather than assumed: NewBanker refuses\n\t// BankerTypeOriginSend unless rlm.Previous().IsUserCall(), and IsUserCall\n\t// counts at most two call-boundary frames. Whatever this run reports is what\n\t// the package doc says.\n\tto := testutils.TestAddress(\"nf-deep-to\")\n\tdenom := Denom(\"nred\")\n\tsent := chain.NewCoins(chain.NewCoin(denom, 90))\n\ttesting.IssueCoins(Home(), sent)\n\ttesting.SetOriginSend(sent)\n\n\tforwardOneDeeper(cur, to, sent)\n\tuassert.Equal(t, int64(90), envelope.BalanceOf(to, denom),\n\t\t\"one extra frame between the entry point and Forward\")\n\ttesting.SetOriginSend(nil)\n}\n"},{"name":"render.gno","body":"package nativeify\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Render lists the pairs. `?\u003cbase\u003e` shows one.\nfunc Render(path string) string {\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderOne(path)\n}\n\nfunc renderIndex() string {\n\tvar sb strings.Builder\n\tsb.WriteString(md.H1(\"nativeify: wugnot, backwards\"))\n\tsb.WriteString(\"\\nwugnot takes a native coin and issues a GRC20, because a GRC20 can be \" +\n\t\t\"pulled by a contract and a native coin cannot. This realm does the other one: escrow \" +\n\t\t\"a GRC20, issue a native denom against it 1:1, and hand back something that moves with \" +\n\t\t\"no realm call, rides the `-send` envelope of a transaction, and shows up beside GNOT \" +\n\t\t\"on an account page.\\n\\n\")\n\tsb.WriteString(md.Blockquote(\"What you give up is everything downstream of `Approve`. A \" +\n\t\t\"native coin has no allowance, so nothing can pull it: not an AMM, not an escrow, not \" +\n\t\t\"a subscription. And its issuer can always delete a balance.\"))\n\tsb.WriteString(\"\\n\")\n\tsb.WriteString(ufmt.Sprintf(\"Escrow account to approve: `%s`\\n\\n\", home.String()))\n\n\tsb.WriteString(md.H2(\"Pairs\") + \"\\n\")\n\tt := ui.NewTable(\"base\", \"underlying\", \"denom\", \"escrowed\", \"issued\", \"solvent\")\n\tfor _, b := range bases {\n\t\tp := mustPair(b)\n\t\tescrowed, issued := Solvency(b)\n\t\tsolvent := \"yes\"\n\t\tif escrowed \u003c issued {\n\t\t\tsolvent = \"**NO**\"\n\t\t}\n\t\tt.Row(md.Link(b, \"/r/moul/x/nativeify/v0:\"+b),\n\t\t\tui.Cell(Underlying(b).GetSymbol()),\n\t\t\tmd.InlineCode(ui.ShortN(p.denom, 20, 10)),\n\t\t\tufmt.Sprintf(\"%d\", escrowed), ufmt.Sprintf(\"%d\", issued), solvent)\n\t}\n\tsb.WriteString(t.OrEmpty(\"Nothing wrapped yet.\") + \"\\n\")\n\n\tsb.WriteString(md.H2(\"Try it\") + \"\\n\")\n\tsb.WriteString(\"Claim play money, let this realm pull it, wrap, then send the result \" +\n\t\t\"around like any other coin:\\n\\n\")\n\tsb.WriteString(md.LanguageCodeBlock(\"\",\n\t\t\"# 1. get RED\\n\"+\n\t\t\t\"maketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Claim\\n\\n\"+\n\t\t\t\"# 2. let this realm pull your RED\\n\"+\n\t\t\t\"maketx call -pkgpath gno.land/r/moul/x/grc20faucet/v0 -func Approve \\\\\\n\"+\n\t\t\tufmt.Sprintf(\"  -args RED -args %s -args 1000000\\n\\n\", home.String())+\n\t\t\t\"# 3. create the pair once, then wrap into it\\n\"+\n\t\t\t\"maketx call -pkgpath \"+Path+\" -func Nativeify \\\\\\n\"+\n\t\t\t\"  -args gno.land/r/moul/x/grc20faucet/v0.RED -args nred\\n\"+\n\t\t\t\"maketx call -pkgpath \"+Path+\" -func Wrap -args nred -args 500000\\n\\n\"+\n\t\t\t\"# 4. it is an ordinary coin now: no realm call, no approval\\n\"+\n\t\t\t\"maketx send -to \u003caddress\u003e -send 1000/\"+Path+\":nred\\n\\n\"+\n\t\t\t\"# 5. redeem, by sending the coins back\\n\"+\n\t\t\t\"maketx call -pkgpath \"+Path+\" -func Unwrap -args nred \\\\\\n\"+\n\t\t\t\"  -send 1000/\"+Path+\":nred\"))\n\tsb.WriteString(\"\\nEvery denom here is described in [nativereg](/r/moul/x/nativereg/v0), \" +\n\t\t\"which is where a native coin says what it is, since the chain stores no name for it.\\n\")\n\treturn sb.String()\n}\n\nfunc renderOne(base string) string {\n\tv := byBase.Get(base)\n\tif v == nil {\n\t\treturn md.H1(\"404\") + \"\\nThis realm does not issue \" + md.InlineCode(base) + \".\\n\"\n\t}\n\tp := v.(*pair)\n\tunder := Underlying(base)\n\tescrowed, issued := Solvency(base)\n\n\tt := ui.NewTable(\"\", \"\")\n\tt.Row(\"denom\", md.InlineCode(p.denom))\n\tt.Row(\"underlying\", ui.Cell(under.GetName())+\" (\"+ui.Cell(under.GetSymbol())+\")\")\n\tt.Row(\"registry key\", md.InlineCode(p.key))\n\tt.Row(\"decimals\", ufmt.Sprintf(\"%d, a display hint only\", under.GetDecimals()))\n\tt.Row(\"escrowed\", ufmt.Sprintf(\"%d\", escrowed))\n\tt.Row(\"issued\", ufmt.Sprintf(\"%d\", issued))\n\tt.Row(\"solvent\", ufmt.Sprintf(\"%t\", escrowed \u003e= issued))\n\tt.Row(\"created at block\", ufmt.Sprintf(\"%d\", p.height))\n\tt.Row(\"created by\", ui.Addr(p.creator))\n\n\ts := md.H1(ui.Inline(base)) + \"\\n\" + t.String() + \"\\n\"\n\ts += \"Escrowed and issued are read from the GRC20 ledger and from the bank, not from \" +\n\t\t\"this realm's own bookkeeping. If they disagree, the disagreement is the answer.\\n\\n\"\n\ts += md.LanguageCodeBlock(\"\",\n\t\t\"maketx call -pkgpath \"+Path+\" -func Wrap -args \"+base+\" -args \u003camount\u003e\\n\"+\n\t\t\t\"maketx call -pkgpath \"+Path+\" -func Unwrap -args \"+base+\" \\\\\\n\"+\n\t\t\t\"  -send \u003camount\u003e\"+p.denom)\n\treturn s\n}\n"}]},"send":"","max_deposit":"13000000ugnot"}],"fee":{"gas_wanted":"90176800","gas_fee":"270530ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"2h6QoWmki+IJJ+kfDf180508d+07hZE9rmy1eUyeepNcZ6hEM1SkllX44rQEfZQbm01Yh9tXk2AXY6yT4GUSEA=="}],"memo":""},"metadata":{"timestamp":"1790961574"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"pilotdemo","path":"gno.land/r/moul/x/pilotdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/pilotdemo/v0`\n\nA power for a realm-driven account: a payout module installed into\n[`r/moul/pilot`](../../pilot) after that account was already deployed. Demo of\n[`p/moul/pilot`](../../../p/moul/pilot).\n\nIt shows both delegation modes in one realm, which is the point of the pair:\n\n- `Pay` goes through the account's revocable purse. `Revoke` stops it on the next call even\n  though this realm still holds the purse object.\n- Under an identity grant it acts as `gno.land/r/moul/pilot/v0#payout` toward another realm,\n  and spends the sub-treasury through a banker it mints and **keeps**. That is deliberate:\n  it is what makes the test `TestIdentityGrantOutlivesRevoke` pass, and what an identity\n  grant costs.\n\n`InstallInto` takes the account handle as a value rather than importing one account, so a\nmodule is not bound to a single instance. gno has no dynamic call, so a `gnokey maketx run`\nscript is what passes the handle; `MsgCall` cannot.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/pilotdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pilotdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/pilotdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pilotdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/pilotdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pilotdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/pilotdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/pilotdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/pilotdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/pilotdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/pilotdemo/v0\"\ngno = \"0.9\"\n\n# public: a pilot account persists the module object in its roster, and a\n# value of a type defined in a private realm cannot be persisted by anyone\n# else. Every pilot module has to be public for the same reason.\n"},{"name":"pilotdemo.gno","body":"// Package pilotdemo is a power for a realm-driven account: a payout module\n// installed into gno.land/p/moul/pilot/v0 after the account was deployed.\n//\n// It shows both delegation modes side by side:\n//\n//   - Pay goes through the account's revocable [pilot.Purse]. Revoking the\n//     module stops it on the next call, even though this realm still holds\n//     the purse object.\n//   - Act is only reachable under an identity grant: the account lends its\n//     sub-identity, this realm acts as \"\u003caccount\u003e#\u003csubpath\u003e\" toward another\n//     realm, and spends the sub-treasury through a banker it mints. That\n//     banker is KEPT on purpose, which is what makes an identity grant\n//     permanent: revoking stops Exec, not this.\n//\n// Demo of gno.land/p/moul/pilot/v0. Account instance: r/moul/pilot.\npackage pilotdemo\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\n\t\"gno.land/p/moul/pilot/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\taccount \"gno.land/r/moul/pilot/v0\"\n)\n\ntype payout struct {\n\tpurse *pilot.Purse\n\tkept  banker.Banker // minted from a lent identity, and retained\n\tsub   address\n\tdest  address\n\tpaid  int64\n}\n\nfunc (m *payout) Name() string { return \"payout\" }\n\n// Run is what the account calls. rlm is the account's sub-identity token\n// under an identity grant, and its plain cur otherwise.\nfunc (m *payout) Run(_ int, rlm realm, args string) string {\n\tif !rlm.IsCurrent() {\n\t\tpanic(\"pilotdemo: stale realm value\")\n\t}\n\tif rlm.Subpath() == \"\" {\n\t\t// purse-only grant: no identity to act under\n\t\tm.purse.Pay(m.dest, 100)\n\t\tm.paid += 100\n\t\treturn ufmt.Sprintf(\"paid 100ugnot from the main treasury, %d left\", m.purse.Left())\n\t}\n\n\t// identity grant: act as the account toward another realm...\n\tseen := Echo(cross(rlm))\n\n\t// ...and spend the sub-treasury it owns.\n\tm.sub = rlm.Address()\n\tm.kept = banker.NewBanker(banker.BankerTypeRealmSend, rlm)\n\tm.kept.SendCoins(m.sub, m.dest, chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\tm.paid += 100\n\treturn \"acted as \" + seen\n}\n\nvar self = \u0026payout{}\n\n// Install wires this module into moul's account.\nfunc Install(cur realm, dest address) {\n\tInstallInto(cur, account.Handle(), dest)\n}\n\n// InstallInto wires it into ANY account: a module is not bound to one\n// instance. gno has no dynamic call, so the handle has to be passed as a\n// value, which a `gnokey maketx run` script can do and a MsgCall cannot.\nfunc InstallInto(cur realm, acct *pilot.Account, dest address) {\n\tself.dest = dest\n\tacct.Register(0, cur, self)\n\tself.purse = acct.PurseFor(0, cur)\n}\n\n// Echo reports who called it. A crossing call shifts the previous-realm\n// stack even into the same realm, so this is what the module's borrowed\n// identity looks like from the outside.\nfunc Echo(cur realm) string { return cur.Previous().PkgPath() }\n\n// Payout spends the sub-treasury with the retained banker, reaching the bank\n// without re-entering the account. This is the demonstration that an\n// identity grant cannot be revoked: it keeps working after Revoke.\nfunc Payout(cur realm, to address, amount int64) {\n\tif self.kept == nil {\n\t\tpanic(\"pilotdemo: no identity was ever granted\")\n\t}\n\tself.kept.SendCoins(self.sub, to, chain.NewCoins(chain.NewCoin(\"ugnot\", amount)))\n}\n\n// Paid is what this module has moved in total.\nfunc Paid() int64 { return self.paid }\n\nfunc Render(path string) string {\n\tif self.purse == nil {\n\t\treturn \"# pilotdemo\\n\\nNot installed.\\n\"\n\t}\n\treturn ufmt.Sprintf(\"# pilotdemo\\n\\n| | |\\n|---|---|\\n| destination | %s |\\n| purse left | %d ugnot |\\n\",\n\t\tself.dest.String(), self.purse.Left())\n}\n"},{"name":"pilotdemo_test.gno","body":"package pilotdemo\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\n\taccount \"gno.land/r/moul/pilot/v0\"\n)\n\nconst modPath = \"gno.land/r/moul/x/pilotdemo/v0\"\n\nvar (\n\t// r/moul/pilot pins Claim to this address, so the tests have to use it\n\towner   = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\tdest    = testutils.TestAddress(\"dest\")\n\tclaimed bool\n)\n\n// claim is safe to call from every test: realm state carries over between\n// test functions, so the account is claimed exactly once per run.\nfunc claim(cur realm) {\n\tif claimed {\n\t\treturn\n\t}\n\tclaimed = true\n\taccount.Claim(cross(cur))\n}\n\nfunc balance(addr address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoin(addr, \"ugnot\")\n}\n\nfunc TestPurseGrantIsRevocable(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tclaim(cur)\n\n\ttreasury := account.Address()\n\ttesting.IssueCoins(treasury, chain.NewCoins(chain.NewCoin(\"ugnot\", 10_000)))\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Approve(cross(cur), modPath, \"payout\", false, 250)\n\n\t// the module installs itself; the account reads its path from the runtime\n\tInstall(cross(cur), dest)\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tuassert.Equal(t, \"paid 100ugnot from the main treasury, 150 left\",\n\t\taccount.Exec(cross(cur), modPath, \"\"))\n\tuassert.Equal(t, int64(100), balance(dest))\n\tuassert.Equal(t, int64(9_900), balance(treasury))\n\n\t// the owner revokes. the module still holds the purse object.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Revoke(cross(cur), modPath)\n\tuassert.Equal(t, int64(0), self.purse.Left())\n\n\t// both doors are shut: through the account...\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tuassert.AbortsContains(t, cur, \"revoked\", func() {\n\t\taccount.Exec(cross(cur), modPath, \"\")\n\t})\n\t// ...and through the retained purse, which is the one that matters.\n\tuassert.AbortsContains(t, cur, \"revoked\", func() {\n\t\tself.purse.Pay(dest, 10)\n\t})\n\tuassert.Equal(t, int64(100), balance(dest))\n}\n\nfunc TestIdentityGrantActsAsTheAccount(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tclaim(cur)\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Approve(cross(cur), modPath, \"payout\", true, 250)\n\tInstall(cross(cur), dest)\n\n\tsub := account.SubAddress(modPath)\n\ttesting.IssueCoins(account.Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 10_000)))\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Fund(cross(cur), modPath, 1_000)\n\tuassert.Equal(t, int64(1_000), balance(sub))\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tgot := account.Exec(cross(cur), modPath, \"\")\n\n\t// the module acted as the ACCOUNT's sub-identity, not as itself\n\tuassert.Equal(t, \"acted as gno.land/r/moul/pilot/v0#payout\", got)\n\tuassert.Equal(t, int64(900), balance(sub))\n\tuassert.Equal(t, int64(100), balance(dest))\n}\n\nfunc TestIdentityGrantOutlivesRevoke(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tclaim(cur)\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Approve(cross(cur), modPath, \"payout\", true, 250)\n\tInstall(cross(cur), dest)\n\n\tsub := account.SubAddress(modPath)\n\ttesting.IssueCoins(account.Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 10_000)))\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Fund(cross(cur), modPath, 1_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Exec(cross(cur), modPath, \"\") // mints and keeps a banker on the sub-address\n\tuassert.Equal(t, int64(900), balance(sub))\n\n\t// revoke shuts the account door\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Revoke(cross(cur), modPath)\n\tuassert.AbortsContains(t, cur, \"revoked\", func() {\n\t\taccount.Exec(cross(cur), modPath, \"\")\n\t})\n\n\t// and the retained banker keeps spending anyway. This is the documented\n\t// cost of an identity grant: revoking is not taking it back.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"anyone\")))\n\tPayout(cross(cur), dest, 900)\n\tuassert.Equal(t, int64(0), balance(sub))\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tclaim(cur)\n\n\t// a fresh approval is a fresh allowance, so this reads the same whatever\n\t// ran before it\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Approve(cross(cur), modPath, \"payout\", false, 1_000)\n\tInstall(cross(cur), dest)\n\ttesting.IssueCoins(account.Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 10_000)))\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\taccount.Exec(cross(cur), modPath, \"\")\n\n\tuassert.Equal(t, \"# pilotdemo\\n\\n| | |\\n|---|---|\\n| destination | \"+\n\t\tdest.String()+\" |\\n| purse left | 900 ugnot |\\n\", Render(\"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"40142400","gas_fee":"120427ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"9swAz7hCPAORiLCNQMmDy8dbG7+d399Xf99qVzaURltsQ1tlKgWOkGqI8JM+nftIvcZfkWt02PvCf6n4C7mFsQ=="}],"memo":""},"metadata":{"timestamp":"1790961575"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ns","path":"gno.land/r/moul/x/plan9/ns/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/plan9/ns/v1`\n\n**A Plan 9 namespace server for gno.land.** Every account gets a private,\npersistent namespace: its own RAM root plus a mount table it alone controls.\nRealms publish file trees into `/srv`, accounts `bind` those trees wherever they\nlike, and a read-only `rc` shell renders the whole thing in gnoweb.\n\n```sh\ngnokey maketx call -pkgpath gno.land/r/moul/x/plan9/ns/v1 \\\n  -func Exec -args 'bind -ac /srv/dev /dev; echo hello \u003e /tmp/greeting'\n```\n\nThen browse it at `/r/moul/x/plan9/ns/v1:ns?u=\u003cyour address\u003e`.\n\nThis is the part of Plan 9 that gno does not otherwise have. The chain has a\nsingle global tree of realm paths that looks the same to everybody; here a name\nmeans what *you* bound it to. Composing two realms that were never written to\nwork together stops being a redeploy and becomes a transaction.\n\n## Surface\n\n| call | what it does |\n|---|---|\n| `Post(cur, name, f)` | publish a `ninep.File` tree under `/srv/\u003cname\u003e` |\n| `Unpost(cur, name)` | withdraw it; only the posting realm may |\n| `Exec(cur, line)` | run an `rc` command line against the caller's namespace |\n| `Reset(cur)` | throw the caller's namespace away |\n| `Run(key, line)` | the read-only query side, used by `Render` |\n| `Namespace(key)` | the mount table, in `ns(1)` format |\n\n`Render` routes: `ns`, `ls/\u003cpath\u003e`, `cat/\u003cpath\u003e`, `stat/\u003cpath\u003e`, `walk/\u003cpath\u003e`,\nand `rc?c=\u003ccommand\u003e` for any read-only command line. `?u=` picks whose namespace;\nit defaults to a seeded demo one, so gnoweb shows something live with no\ntransaction.\n\n## The default namespace\n\nThis chain's `/lib/namespace`: a private ram root, the mount points Plan 9\nrequires to exist before anything can be bound onto them, `/srv` mounted, and\n`/dev` bound from it when a device server has been posted.\n\n```\nmount #s /srv\nbind /srv/dev /dev\n```\n\n## Security\n\n**Mounted trees are read-only by construction.** `ninep.File` has no mutating\nmethod, so grafting a foreign realm's tree into your namespace cannot be turned\ninto a write against that realm; writes only ever reach a memfs tree this realm\ncreated for you. A crossing write method would mint *this* realm's frame for the\ncallee, which is the confused-deputy shape `r/gov/dao`'s `Executor` relies on\ndeliberately and `p/nt/grc20`'s `Teller` refuses deliberately. It is out of\nscope for v0, and three abort tests pin the boundary: a second realm cannot\ntake over a `/srv` name, a write to a mounted tree fails with `read-only file\nserver`, and a command line that fails part way aborts the whole call.\n\n`/srv` names are first come, first served, with the posting realm recorded and\nthe only one allowed to unpost. Squatting is possible and accepted for an\nexperiment.\n\nBuilt on [`ninep`](../../../../../p/moul/x/plan9/ninep/v0),\n[`memfs`](../../../../../p/moul/x/plan9/memfs/v0),\n[`ns`](../../../../../p/moul/x/plan9/ns/v0) and\n[`rc`](../../../../../p/moul/x/plan9/rc/v0). Design and analysis:\n[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\n\n---\n\n**Not affiliated with Plan 9.** Plan 9 from Bell Labs is the work of the\nComputing Science Research Center at Bell Labs; the name and the marks are\ntheirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org).\nThis realm borrows the vocabulary and none of the code: it is an independent\nhomage, asking what that ecosystem's spirit looks like on a chain. Full\nattribution: [NOTICE](../../../../../NOTICE.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/plan9/ns/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/ns/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/plan9/ns/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/ns/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/plan9/ns/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/ns/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/plan9/ns/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/ns/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/plan9/ns/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/plan9/ns/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/plan9/ns/v1\"\ngno = \"0.9\"\n\n# public: imported by r/moul/x/plan9/dev, which is what the pair is for\n"},{"name":"ns.gno","body":"// Package ns is a Plan 9 namespace server for gno.land.\n//\n// Every account gets a private, persistent namespace: its own RAM root plus a\n// mount table it alone controls. Realms publish file trees into /srv, accounts\n// bind those trees wherever they like, and a read-only rc shell renders the\n// whole thing in gnoweb.\n//\n// This is the part of Plan 9 that gno does not otherwise have. The chain has a\n// single global tree of realm paths that looks the same to everybody; here a\n// name means what YOU bound it to. Composing two realms that were never\n// written to work together stops being a redeploy and becomes a transaction:\n//\n//\tgnokey maketx call -pkgpath gno.land/r/moul/x/plan9/ns/v1 -func Exec \\\n//\t  -args 'bind -ac /srv/dev /dev; echo hello \u003e /tmp/greeting'\n//\n// SECURITY. Mounted trees are READ-ONLY by construction: ninep.File has no\n// mutating method, so grafting a foreign realm's tree into your namespace\n// cannot be turned into a write against that realm. Writes only ever reach a\n// memfs tree this realm created for you. A crossing write method would mint\n// THIS realm's frame for the callee, which is the confused-deputy shape that\n// r/gov/dao's Executor relies on deliberately and p/nt/grc20's Teller refuses\n// deliberately; it is out of scope for v0. See moul/gno-contracts#136.\n//\n// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research\n// Center at Bell Labs; the name and the marks are theirs, and the copyright is\n// held by the Plan 9 Foundation (https://p9f.org). This realm is not\n// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9\n// code: it borrows the vocabulary so that the design reads without a glossary,\n// and it is an homage, asking what that ecosystem's spirit looks like on a\n// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.\npackage ns\n\nimport (\n\t\"chain/runtime\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\n\t\"gno.land/p/moul/realmpath/v0\"\n\n\tmemfs \"gno.land/p/moul/x/plan9/memfs/v0\"\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n\tnspkg \"gno.land/p/moul/x/plan9/ns/v0\"\n\trc \"gno.land/p/moul/x/plan9/rc/v0\"\n)\n\n// DemoKey names the namespace gnoweb browses when no ?u= is given. It is a\n// plain string rather than an address so it can never collide with one.\nconst DemoKey = \"demo\"\n\n// The bounds on what callers can create. Any realm may Post a service and any\n// account gets a namespace on its first Exec; the home page lists both.\nconst (\n\tMaxServices   = 64\n\tMaxNamespaces = 1000\n\tHomeRecent    = 50 // namespaces the home page lists\n)\n\ntype service struct {\n\tfile  ninep.File\n\towner string  // pkgpath of the realm that posted it\n\taddr  address // that realm's address\n\tsince int64   // block height of the posting\n}\n\ntype space struct {\n\tfs *memfs.FS\n\tns *nspkg.Ns\n}\n\nvar (\n\tservices = avl.NewTree() // name -\u003e *service\n\tspaces   = avl.NewTree() // address string (or DemoKey) -\u003e *space\n)\n\nfunc init() {\n\tseedDemo()\n}\n\n// ---------------------------------------------------------------- /srv\n\n// srvDir is the synthetic directory that makes posted services reachable by\n// name. It is written out by hand rather than built with synfs because its\n// contents change as realms post, and because implementing ninep.File\n// directly is meant to look easy: four methods, no state of its own.\ntype srvDir struct{}\n\nfunc (d *srvDir) Stat() ninep.Stat {\n\treturn ninep.Stat{\n\t\tQid:   ninep.Qid{Type: ninep.QTDIR, Path: 1},\n\t\tMode:  ninep.DMDIR | 0555,\n\t\tMtime: runtime.ChainHeight(),\n\t\tName:  \"srv\",\n\t\tUid:   \"sys\",\n\t\tGid:   \"sys\",\n\t\tMuid:  \"sys\",\n\t}\n}\n\nfunc (d *srvDir) Walk(name string) (ninep.File, error) {\n\tif !ninep.ValidName(name) {\n\t\treturn nil, ninep.ErrBadName\n\t}\n\tv := services.Get(name)\n\tif v == nil {\n\t\treturn nil, ninep.ErrNotExist\n\t}\n\treturn v.(*service).file, nil\n}\n\nfunc (d *srvDir) Read(off, count int64) (string, error) { return \"\", ninep.ErrIsDir }\n\nfunc (d *srvDir) ReadDir() ([]ninep.Stat, error) {\n\tout := []ninep.Stat{}\n\tservices.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tst := v.(*service).file.Stat()\n\t\tst.Name = k // the posted name, not whatever the server calls its root\n\t\tout = append(out, st)\n\t\treturn false\n\t})\n\treturn out, nil\n}\n\nvar srvRoot = \u0026srvDir{}\n\n// ---------------------------------------------------------------- posting\n\n// Post publishes a file tree under name in /srv, where any account can bind\n// it. The posting realm is recorded and is the only one that may Unpost.\n//\n// Names are first come, first served, which is fine for an experiment and\n// would not be for anything else.\nfunc Post(cur realm, name string, f ninep.File) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"post: cur is not the caller's live realm\")\n\t}\n\tif !ninep.ValidName(name) {\n\t\tpanic(\"post: \" + ninep.ErrBadName.Error())\n\t}\n\tif f == nil {\n\t\tpanic(\"post: nil file server\")\n\t}\n\tprev := cur.Previous()\n\tif services.Get(name) == nil \u0026\u0026 services.Size() \u003e= MaxServices {\n\t\tpanic(\"post: /srv is full at \" + strconv.Itoa(MaxServices) + \" services\")\n\t}\n\tif existing := services.Get(name); existing != nil {\n\t\tif existing.(*service).owner != prev.PkgPath() {\n\t\t\tpanic(\"post: \" + name + \" is already posted by \" + existing.(*service).owner)\n\t\t}\n\t}\n\tservices.Set(name, \u0026service{\n\t\tfile:  f,\n\t\towner: prev.PkgPath(),\n\t\taddr:  prev.Address(),\n\t\tsince: runtime.ChainHeight(),\n\t})\n}\n\n// Unpost withdraws a service. Only the realm that posted it may do so.\nfunc Unpost(cur realm, name string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"unpost: cur is not the caller's live realm\")\n\t}\n\tv := services.Get(name)\n\tif v == nil {\n\t\tpanic(\"unpost: \" + ninep.ErrNotExist.Error())\n\t}\n\tif v.(*service).owner != cur.Previous().PkgPath() {\n\t\tpanic(\"unpost: \" + name + \" belongs to \" + v.(*service).owner)\n\t}\n\tservices.Remove(name)\n}\n\n// Services lists the posted service names, in order.\nfunc Services() []string {\n\tout := []string{}\n\tservices.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tout = append(out, k)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// ---------------------------------------------------------------- namespaces\n\n// newSpace builds the default namespace, which is this chain's /lib/namespace:\n// a private ram root, the mount points that Plan 9 requires to exist before\n// anything can be bound onto them, /srv mounted, and /dev bound from it when a\n// device server has been posted.\nfunc newSpace(owner string) *space {\n\tnow := runtime.ChainHeight()\n\tfs := memfs.New(owner, now)\n\tfs.MkdirAll(\"/srv\", now)\n\tfs.MkdirAll(\"/dev\", now)\n\tfs.MkdirAll(\"/tmp\", now)\n\n\tn := nspkg.New(fs.Root())\n\tn.Mount(srvRoot, \"#s\", \"/srv\", nspkg.MREPL)\n\tif services.Has(\"dev\") {\n\t\tn.Bind(\"/srv/dev\", \"/dev\", nspkg.MREPL)\n\t}\n\treturn \u0026space{fs: fs, ns: n}\n}\n\nfunc spaceFor(key string) *space {\n\tif v := spaces.Get(key); v != nil {\n\t\treturn v.(*space)\n\t}\n\tif spaces.Size() \u003e= MaxNamespaces {\n\t\tpanic(\"ns: full at \" + strconv.Itoa(MaxNamespaces) + \" namespaces\")\n\t}\n\tsp := newSpace(key)\n\tspaces.Set(key, sp)\n\treturn sp\n}\n\nfunc peek(key string) *space {\n\tif v := spaces.Get(key); v != nil {\n\t\treturn v.(*space)\n\t}\n\treturn nil\n}\n\n// seedDemo builds the namespace gnoweb shows by default. It is deliberately\n// reproducible: an example test resets it before rendering.\nfunc seedDemo() {\n\tspaces.Remove(DemoKey)\n\tsp := spaceFor(DemoKey)\n\tnow := runtime.ChainHeight()\n\tsp.fs.WriteFile(\"/tmp/greeting\", \"hello from a namespace\\n\", now)\n\tsp.fs.MkdirAll(\"/usr/glenda/bin\", now)\n\tsp.fs.WriteFile(\"/usr/glenda/bin/rc\", \"#!/bin/rc\\n\", now)\n\tsp.fs.MkdirAll(\"/bin\", now)\n\tsp.fs.WriteFile(\"/bin/ls\", \"system ls\\n\", now)\n\tsp.ns.Bind(\"/usr/glenda/bin\", \"/bin\", nspkg.MAFTER|nspkg.MCREATE)\n\tsp.ns.Cd(\"/usr/glenda\")\n}\n\n// ResetDemo rebuilds the demo namespace. Anyone may call it: it is a demo, and\n// the alternative is a demo that the first visitor ruins for everybody.\nfunc ResetDemo(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"resetdemo: cur is not the caller's live realm\")\n\t}\n\tseedDemo()\n}\n\n// ---------------------------------------------------------------- shell\n\n// Exec runs a command line against the CALLER's namespace and returns its\n// output. The namespace belongs to cur.Previous().Address(), so a user gets\n// theirs and a realm gets its own.\n//\n// An error panics, so a half-applied command line reverts with the\n// transaction rather than leaving a namespace nobody asked for.\nfunc Exec(cur realm, line string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"exec: cur is not the caller's live realm\")\n\t}\n\tkey := cur.Previous().Address().String()\n\tsp := spaceFor(key)\n\tsh := rc.New(sp.ns, rc.ReadWrite, runtime.ChainHeight)\n\tout, err := sh.Run(line)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn out\n}\n\n// Reset discards the caller's namespace, so the next use rebuilds the default.\nfunc Reset(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"reset: cur is not the caller's live realm\")\n\t}\n\tspaces.Remove(cur.Previous().Address().String())\n}\n\n// Run executes a READ-ONLY command line against key's namespace. It is the\n// query side of Exec: no transaction, no writes, safe from Render.\nfunc Run(key, line string) (string, error) {\n\tsp := peek(key)\n\tif sp == nil {\n\t\treturn \"\", errors.New(\"no namespace for \" + key)\n\t}\n\tsh := rc.New(sp.ns, rc.ReadOnly, runtime.ChainHeight)\n\treturn sh.Run(line)\n}\n\n// Namespace returns key's mount table, in ns(1) format.\nfunc Namespace(key string) string {\n\tsp := peek(key)\n\tif sp == nil {\n\t\treturn \"\"\n\t}\n\treturn sp.ns.String()\n}\n\n// Keys lists the namespaces that exist, in order.\nfunc Keys() []string {\n\tout := []string{}\n\tspaces.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tout = append(out, k)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// ---------------------------------------------------------------- render\n\n// Render browses a namespace.\n//\n//\tRender(\"\")                  overview, posted services, how to drive it\n//\tRender(\"ns?u=\u003ckey\u003e\")        the mount table\n//\tRender(\"ls/bin?u=\u003ckey\u003e\")    a directory listing (ls -l)\n//\tRender(\"cat/tmp/greeting\")  a file\n//\tRender(\"stat/bin\")          the 9P stat, with the union width\n//\tRender(\"walk/bin/rc\")       how each element of a path resolves\n//\tRender(\"rc?c=\u003ccommand\u003e\")    any read-only rc command line\n//\n// ?u= selects the namespace; it defaults to the demo one.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tkey := req.Query.Get(\"u\")\n\tif key == \"\" {\n\t\tkey = DemoKey\n\t}\n\t// A namespace is keyed by the address that created it, or is the demo one.\n\t// Anything else names no namespace, and refusing it here is also what keeps\n\t// a crafted ?u= out of the links and code spans every page builds from it.\n\tif key != DemoKey \u0026\u0026 !address(key).IsValid() {\n\t\treturn \"# 404\\n\\nno namespace by that name. `?u=` takes an address.\\n\"\n\t}\n\tparts := req.PathParts()\n\tif len(parts) == 0 || parts[0] == \"\" {\n\t\treturn renderHome(key)\n\t}\n\n\tcmd := parts[0]\n\trest := \"/\" + strings.Join(parts[1:], \"/\")\n\tvar line string\n\tswitch cmd {\n\tcase \"ns\":\n\t\treturn renderCmd(key, \"ns\", \"ns\")\n\tcase \"ls\":\n\t\tline = \"ls -l \" + quote(rest)\n\tcase \"cat\":\n\t\tline = \"cat \" + quote(rest)\n\tcase \"stat\":\n\t\tline = \"stat \" + quote(rest)\n\tcase \"walk\":\n\t\tline = \"walk \" + quote(rest)\n\tcase \"rc\":\n\t\tline = req.Query.Get(\"c\")\n\t\tif line == \"\" {\n\t\t\tline = \"help\"\n\t\t}\n\tdefault:\n\t\treturn \"# 404\\n\\nunknown command \" + md.InlineCode(cmd) + \". Try `ls`, `cat`, `stat`, `walk`, `ns` or `rc?c=...`.\\n\"\n\t}\n\treturn renderCmd(key, line, cmd+\" \"+rest)\n}\n\nfunc renderCmd(key, line, title string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + ui.Inline(title) + \"\\n\\n\")\n\tb.WriteString(\"namespace: `\" + key + \"`\\n\\n\")\n\tout, err := Run(key, line)\n\tif err != nil {\n\t\tb.WriteString(md.CodeBlock(err.Error()))\n\t} else if out == \"\" {\n\t\tb.WriteString(\"_(no output)_\\n\")\n\t} else {\n\t\t// The output is a user's file contents: a line of backticks in it\n\t\t// would close a hand-written fence, and md.CodeBlock picks one it cannot.\n\t\tb.WriteString(md.CodeBlock(strings.TrimSuffix(out, \"\\n\")))\n\t}\n\tb.WriteString(\"\\n[namespace](/r/moul/x/plan9/ns/v1:ns?u=\" + key + \") · [root](/r/moul/x/plan9/ns/v1:ls?u=\" + key +\n\t\t\") · [home](/r/moul/x/plan9/ns/v1)\\n\")\n\treturn b.String()\n}\n\nfunc renderHome(key string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# plan9: namespaces for gno\\n\\n\")\n\tb.WriteString(\"A Plan 9 namespace server. Every account owns a private mount table over \")\n\tb.WriteString(\"[9P-shaped](https://9p.io/sys/doc/9.html) file trees: realms post trees \")\n\tb.WriteString(\"into `/srv`, you `bind` them where you want them, and a name means what \")\n\tb.WriteString(\"*you* bound it to.\\n\\n\")\n\n\tb.WriteString(\"## /srv\\n\\n\")\n\tif services.Size() == 0 {\n\t\tb.WriteString(\"_No service is posted yet._\\n\\n\")\n\t} else {\n\t\tb.WriteString(\"| name | posted by | since |\\n|---|---|---|\\n\")\n\t\tservices.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\t\ts := v.(*service)\n\t\t\tb.WriteString(\"| \" + ui.Cell(k) + \" | [`\" + s.owner + \"`](\" +\n\t\t\t\tstrings.TrimPrefix(s.owner, \"gno.land\") + \") | \" +\n\t\t\t\tstrconv.FormatInt(s.since, 10) + \" |\\n\")\n\t\t\treturn false\n\t\t})\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"## The demo namespace\\n\\n\")\n\tb.WriteString(md.CodeBlock(strings.TrimSuffix(Namespace(DemoKey), \"\\n\")) + \"\\n\")\n\tb.WriteString(\"`/bin` is a union: the system `/bin` first, then `/usr/glenda/bin`, \")\n\tb.WriteString(\"with `-c` so new files land in the second. Listing it shows both members \")\n\tb.WriteString(\"because a Plan 9 union is a concatenation, so shadowing stays visible.\\n\\n\")\n\tb.WriteString(\"- [ns](/r/moul/x/plan9/ns/v1:ns) · [ls /](/r/moul/x/plan9/ns/v1:ls) · [ls /bin](/r/moul/x/plan9/ns/v1:ls/bin) · \")\n\tb.WriteString(\"[cat /tmp/greeting](/r/moul/x/plan9/ns/v1:cat/tmp/greeting) · [walk /bin/rc](/r/moul/x/plan9/ns/v1:walk/bin/rc)\\n\")\n\tb.WriteString(\"- any read-only command: [`rc?c=ls -l /srv`](/r/moul/x/plan9/ns/v1:rc?c=ls%20-l%20/srv)\\n\\n\")\n\n\tb.WriteString(\"## Your own namespace\\n\\n\")\n\tb.WriteString(\"```\\n\")\n\tb.WriteString(\"gnokey maketx call -pkgpath gno.land/r/moul/x/plan9/ns/v1 \\\\\\n\")\n\tb.WriteString(\"  -func Exec -args 'bind -ac /srv/dev /dev; echo hi \u003e /tmp/f'\\n\")\n\tb.WriteString(\"```\\n\\n\")\n\tb.WriteString(\"Then browse it with `?u=\u003cyour address\u003e`. `Reset` throws it away.\\n\\n\")\n\n\tb.WriteString(\"## Namespaces\\n\\n\")\n\tkeys := Keys()\n\tif len(keys) \u003e HomeRecent {\n\t\tb.WriteString(strconv.Itoa(len(keys)) + \" namespaces, the first \" + strconv.Itoa(HomeRecent) + \" listed.\\n\\n\")\n\t\tkeys = keys[:HomeRecent]\n\t}\n\tfor _, k := range keys {\n\t\tb.WriteString(\"- [`\" + k + \"`](/r/moul/x/plan9/ns/v1:ns?u=\" + k + \")\\n\")\n\t}\n\tb.WriteString(\"\\nDesign and analysis: \")\n\tb.WriteString(\"[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\\n\")\n\tb.WriteString(\"\\n_Not affiliated with Plan 9. Plan 9 from Bell Labs is the \")\n\tb.WriteString(\"work of the Computing Science Research Center at Bell Labs; the name \")\n\tb.WriteString(\"and the marks are theirs, and the copyright is held by the \")\n\tb.WriteString(\"[Plan 9 Foundation](https://p9f.org). This realm borrows the \")\n\tb.WriteString(\"vocabulary and none of the code: it is an homage, asking what that \")\n\tb.WriteString(\"ecosystem's spirit looks like on a chain._\\n\")\n\treturn b.String()\n}\n\n// quote wraps a path for rc if it needs it.\nfunc quote(s string) string {\n\t// Always quoted: the path comes from the URL, and a route like\n\t// cat/tmp/f;echo must read one file, not run a second command. The shell\n\t// is read-only either way, but a path is data.\n\treturn \"'\" + strings.ReplaceAll(s, \"'\", \"''\") + \"'\"\n}\n"},{"name":"ns_test.gno","body":"package ns\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n\tsynfs \"gno.land/p/moul/x/plan9/synfs/v0\"\n)\n\n// probe is a tiny read-only server, standing in for another realm's tree.\nfunc probe(name, contents string) ninep.File {\n\tt := synfs.New(name, \"sys\", func() int64 { return 1 })\n\tt.Root().Add(\"value\", func() string { return contents })\n\treturn t.Root()\n}\n\nfunc TestDemoNamespaceIsSeeded(t *testing.T) {\n\tseedDemo()\n\tout, err := Run(DemoKey, \"ls -u /bin\")\n\tif err != nil {\n\t\tt.Fatalf(\"ls: %v\", err)\n\t}\n\tif out != \"ls\\nrc\\n\" {\n\t\tt.Errorf(\"the demo /bin should be a union of two directories: %q\", out)\n\t}\n\tif got := Namespace(DemoKey); !strings.Contains(got, \"bind -ac /usr/glenda/bin /bin\") {\n\t\tt.Errorf(\"mount table: %q\", got)\n\t}\n\tif got, _ := Run(DemoKey, \"cat /tmp/greeting\"); got != \"hello from a namespace\\n\" {\n\t\tt.Errorf(\"greeting: %q\", got)\n\t}\n}\n\nfunc TestRunIsReadOnly(t *testing.T) {\n\tseedDemo()\n\tif _, err := Run(DemoKey, \"echo x \u003e /tmp/f\"); err == nil {\n\t\tt.Fatal(\"Render's shell must refuse a write\")\n\t}\n\tif _, err := Run(DemoKey, \"rm /tmp/greeting\"); err == nil {\n\t\tt.Fatal(\"Render's shell must refuse a remove\")\n\t}\n\tif _, err := Run(\"nobody\", \"ls /\"); err == nil {\n\t\tt.Fatal(\"an unknown namespace should not be created by a read\")\n\t}\n}\n\nfunc TestPostAndBind(cur realm, t *testing.T) {\n\tservices.Remove(\"probe\")\n\tPost(cross(cur), \"probe\", probe(\"probe\", \"42\"))\n\n\tfound := false\n\tfor _, s := range Services() {\n\t\tif s == \"probe\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tt.Fatalf(\"probe is not in /srv: %v\", Services())\n\t}\n\n\t// A fresh namespace sees it through /srv without importing anything.\n\tspaces.Remove(\"tester\")\n\tspaceFor(\"tester\")\n\tdefer spaces.Remove(\"tester\")\n\tout, err := Run(\"tester\", \"cat /srv/probe/value\")\n\tif err != nil {\n\t\tt.Fatalf(\"cat through /srv: %v\", err)\n\t}\n\tif out != \"42\" {\n\t\tt.Errorf(\"got %q, want 42\", out)\n\t}\n\tservices.Remove(\"probe\")\n}\n\nfunc TestExecWritesToTheCallersOwnNamespace(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tspaces.Remove(alice.String())\n\tspaces.Remove(bob.String())\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tExec(cross(cur), \"echo 'alice was here' \u003e /tmp/note\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tExec(cross(cur), \"echo 'bob was here' \u003e /tmp/note\")\n\n\tgot, err := Run(alice.String(), \"cat /tmp/note\")\n\tif err != nil {\n\t\tt.Fatalf(\"alice: %v\", err)\n\t}\n\tif got != \"alice was here\\n\" {\n\t\tt.Errorf(\"alice's namespace: %q\", got)\n\t}\n\tif got, _ = Run(bob.String(), \"cat /tmp/note\"); got != \"bob was here\\n\" {\n\t\tt.Errorf(\"bob's namespace: %q\", got)\n\t}\n\n\t// Reset throws a namespace away; the next use rebuilds the default.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReset(cross(cur))\n\tif _, err := Run(alice.String(), \"cat /tmp/note\"); err == nil {\n\t\tt.Error(\"the namespace should be gone after Reset\")\n\t}\n\tspaces.Remove(alice.String())\n\tspaces.Remove(bob.String())\n}\n\nfunc TestExecBindsIntoTheCallersNamespace(cur realm, t *testing.T) {\n\tservices.Remove(\"probe\")\n\tPost(cross(cur), \"probe\", probe(\"probe\", \"42\"))\n\tdefer services.Remove(\"probe\")\n\n\terin := testutils.TestAddress(\"erin\")\n\tspaces.Remove(erin.String())\n\ttesting.SetRealm(testing.NewUserRealm(erin))\n\tExec(cross(cur), \"bind /srv/probe /dev\")\n\n\tif got := mustRun(t, erin.String(), \"cat /dev/value\"); got != \"42\" {\n\t\tt.Errorf(\"read through the mount: %q\", got)\n\t}\n\tif ns := Namespace(erin.String()); !strings.Contains(ns, \"bind /srv/probe /dev\") {\n\t\tt.Errorf(\"mount table: %q\", ns)\n\t}\n\tspaces.Remove(erin.String())\n}\n\nfunc TestSrvListingUsesThePostedName(cur realm, t *testing.T) {\n\tservices.Remove(\"aliased\")\n\t// The server calls its own root \"probe\"; /srv must show it as \"aliased\".\n\tPost(cross(cur), \"aliased\", probe(\"probe\", \"x\"))\n\tdefer services.Remove(\"aliased\")\n\n\tspaces.Remove(\"lister\")\n\tspaceFor(\"lister\")\n\tout := mustRun(t, \"lister\", \"ls /srv\")\n\tif !strings.Contains(out, \"aliased\") {\n\t\tt.Errorf(\"ls /srv: %q\", out)\n\t}\n\tif strings.Contains(out, \"probe\") {\n\t\tt.Errorf(\"/srv leaked the server's own root name: %q\", out)\n\t}\n\tspaces.Remove(\"lister\")\n}\n\nfunc mustRun(t *testing.T, key, line string) string {\n\tt.Helper()\n\tout, err := Run(key, line)\n\tif err != nil {\n\t\tt.Fatalf(\"%s: %v\", line, err)\n\t}\n\treturn out\n}\n\n// --- the boundary. Three properties the suite would be unsafe without. -------\n\n// A /srv name belongs to the realm that posted it: first come, first served,\n// and then locked.\nfunc TestPostRejectsASecondOwner(cur realm, t *testing.T) {\n\tservices.Remove(\"taken\")\n\tPost(cross(cur), \"taken\", probe(\"taken\", \"first\"))\n\tdefer services.Remove(\"taken\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/other/thing/v0\"))\n\tuassert.AbortsWithMessage(t, cur,\n\t\t\"post: taken is already posted by gno.land/r/moul/x/plan9/ns/v1\",\n\t\tfunc() { Post(cross(cur), \"taken\", probe(\"taken\", \"second\")) })\n}\n\n// Grafting another realm's tree into your namespace gives you reads and\n// nothing else. ninep.File has no mutating method, so there is no route from a\n// mount to a write against the realm that posted it.\nfunc TestMountedTreesAreReadOnly(cur realm, t *testing.T) {\n\tservices.Remove(\"probe\")\n\tPost(cross(cur), \"probe\", probe(\"probe\", \"read me\"))\n\tdefer services.Remove(\"probe\")\n\n\tfrank := testutils.TestAddress(\"frank\")\n\tspaces.Remove(frank.String())\n\tdefer spaces.Remove(frank.String())\n\n\ttesting.SetRealm(testing.NewUserRealm(frank))\n\tExec(cross(cur), \"bind /srv/probe /dev\")\n\tuassert.Equal(t, \"read me\", mustRun(t, frank.String(), \"cat /dev/value\"))\n\tuassert.AbortsWithMessage(t, cur, \"echo: read-only file server\",\n\t\tfunc() { Exec(cross(cur), \"echo nope \u003e /dev/value\") })\n}\n\n// A command line stops at the first error and the error leaves the realm as an\n// abort, so a half-applied Exec reverts with its transaction instead of\n// leaving a namespace nobody asked for.\nfunc TestExecAbortsAtTheFirstError(cur realm, t *testing.T) {\n\tgrace := testutils.TestAddress(\"grace\")\n\tspaces.Remove(grace.String())\n\tdefer spaces.Remove(grace.String())\n\n\ttesting.SetRealm(testing.NewUserRealm(grace))\n\tuassert.AbortsWithMessage(t, cur, \"cat: file does not exist\",\n\t\tfunc() { Exec(cross(cur), \"echo ok \u003e /tmp/a; cat /absent; echo never \u003e /tmp/b\") })\n}\n\nfunc TestRenderUnknownCommand(t *testing.T) {\n\tif got := Render(\"nope/x\"); !strings.Contains(got, \"404\") {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n}\n\n// ?u= is the only caller-controlled part of every link the pages build, so a\n// value that is neither an address nor the demo key is refused outright.\nfunc TestRenderRefusesANonAddressNamespace(t *testing.T) {\n\tout := Render(\"ns?u=x%29%20[evil](https://example)\")\n\tuassert.True(t, strings.Contains(out, \"# 404\"), out)\n\tuassert.False(t, strings.Contains(out, \"[evil](https://example)\"), out)\n}\n\n// A file's contents are its owner's text. A line of backticks in one used to\n// close the hand-written fence around `cat`'s output, and everything after it\n// rendered as live markdown on the realm's own page.\nfunc TestCatOutputCannotCloseItsFence(cur realm, t *testing.T) {\n\twho := testutils.TestAddress(\"fencer\")\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tExec(cross(cur), \"echo '```' \u003e /tmp/f; echo '[claim](https://evil.example)' \u003e\u003e /tmp/f\")\n\tout := Render(\"cat/tmp/f?u=\" + who.String())\n\t// md.CodeBlock picks a fence longer than any run of backticks inside, so\n\t// the user's three backticks and the link after them stay inside the block.\n\tuassert.True(t, strings.Contains(out, \"````\\n```\\n[claim](https://evil.example)\\n````\\n\"), out)\n}\n\n// The command name and the rest of the path come from the URL: escaped in the\n// heading and in the unknown-command page.\nfunc TestPathDerivedTextIsEscaped(t *testing.T) {\n\tfor _, path := range []string{\"x` [claim](https://evil.example) `\", \"cat/x` [claim](https://evil.example) `\"} {\n\t\tout := Render(path)\n\t\tuassert.False(t, strings.Contains(out, \"[claim](https://evil.example)\"), out)\n\t}\n}\n\n// A service name is chosen by whichever realm posts it, and ValidName refuses\n// only \"\", \".\", \"..\" and \"/\": the /srv table escapes it as a cell.\nfunc TestServiceNameIsTableSafe(cur realm, t *testing.T) {\n\tname := \"x` | [claim](https://evil.example) |\"\n\tservices.Set(name, \u0026service{owner: \"gno.land/r/someone/poster\"})\n\tdefer services.Remove(name)\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, \"[claim](https://evil.example)\"), out)\n}\n\n// A path route reads what it names: the rest of the path is one quoted\n// argument, so a \";\" in it is part of the file name and runs nothing.\nfunc TestPathRouteIsOneArgument(t *testing.T) {\n\t// Unquoted, rc would cat /tmp/greeting and then run the second command;\n\t// quoted, it looks for one file with a \";\" in its name and finds none.\n\tout := Render(\"cat/tmp/greeting;echo\")\n\tuassert.True(t, strings.Contains(out, \"cat: file does not exist\"), out)\n\tuassert.Equal(t, \"'/a;b'\", quote(\"/a;b\"))\n}\n\n// Namespaces and services are bounded, and the home page lists a fixed number.\nfunc TestNamespacesAndServicesAreBounded(cur realm, t *testing.T) {\n\tvar added []string\n\tfor i := 0; spaces.Size() \u003c MaxNamespaces; i++ {\n\t\tk := testutils.TestAddress(\"ns\" + strconv.Itoa(i)).String()\n\t\tif spaces.Get(k) == nil {\n\t\t\tspaces.Set(k, newSpace(k))\n\t\t\tadded = append(added, k)\n\t\t}\n\t}\n\tdefer func() {\n\t\tfor _, k := range added {\n\t\t\tspaces.Remove(k)\n\t\t}\n\t}()\n\tuassert.PanicsContains(t, cur, \"full at\", func() { spaceFor(testutils.TestAddress(\"one-more\").String()) })\n\tuassert.Equal(t, HomeRecent, strings.Count(Render(\"\"), \"](/r/moul/x/plan9/ns/v1:ns?u=\"))\n}\n\n// /srv is bounded: once MaxServices names are posted, a new one is refused,\n// and re-posting is not how a realm gets around it.\nfunc TestServicesAreBounded(cur realm, t *testing.T) {\n\tvar added []string\n\tfor i := 0; services.Size() \u003c MaxServices; i++ {\n\t\tname := \"svc\" + strconv.Itoa(i)\n\t\tif services.Get(name) == nil {\n\t\t\tservices.Set(name, \u0026service{owner: \"gno.land/r/someone/poster\"})\n\t\t\tadded = append(added, name)\n\t\t}\n\t}\n\tdefer func() {\n\t\tfor _, n := range added {\n\t\t\tservices.Remove(n)\n\t\t}\n\t}()\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/someone/late\"))\n\tuassert.AbortsContains(t, cur, \"/srv is full\", func() { Post(cross(cur), \"late\", probe(\"late\", \"x\")) })\n}\n"},{"name":"render_example_test.gno","body":"package ns\n\nimport \"gno.land/p/nt/avl/v0\"\n\n// resetForExample rebuilds the whole realm state. Realm globals persist for\n// the entire test binary and examples run after every Test, so without this an\n// example would pin whatever the last test happened to leave behind.\nfunc resetForExample() {\n\tservices = avl.NewTree()\n\tspaces = avl.NewTree()\n\tseedDemo()\n}\n\n// ExampleRender pins the realm's front page.\nfunc ExampleRender() {\n\tresetForExample()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # plan9: namespaces for gno\n\t//\n\t// A Plan 9 namespace server. Every account owns a private mount table over [9P-shaped](https://9p.io/sys/doc/9.html) file trees: realms post trees into `/srv`, you `bind` them where you want them, and a name means what *you* bound it to.\n\t//\n\t// ## /srv\n\t//\n\t// _No service is posted yet._\n\t//\n\t// ## The demo namespace\n\t//\n\t// ```\n\t// mount #s /srv\n\t// bind -ac /usr/glenda/bin /bin\n\t// cd /usr/glenda\n\t// ```\n\t//\n\t// `/bin` is a union: the system `/bin` first, then `/usr/glenda/bin`, with `-c` so new files land in the second. Listing it shows both members because a Plan 9 union is a concatenation, so shadowing stays visible.\n\t//\n\t// - [ns](/r/moul/x/plan9/ns/v1:ns) · [ls /](/r/moul/x/plan9/ns/v1:ls) · [ls /bin](/r/moul/x/plan9/ns/v1:ls/bin) · [cat /tmp/greeting](/r/moul/x/plan9/ns/v1:cat/tmp/greeting) · [walk /bin/rc](/r/moul/x/plan9/ns/v1:walk/bin/rc)\n\t// - any read-only command: [`rc?c=ls -l /srv`](/r/moul/x/plan9/ns/v1:rc?c=ls%20-l%20/srv)\n\t//\n\t// ## Your own namespace\n\t//\n\t// ```\n\t// gnokey maketx call -pkgpath gno.land/r/moul/x/plan9/ns/v1 \\\n\t//   -func Exec -args 'bind -ac /srv/dev /dev; echo hi \u003e /tmp/f'\n\t// ```\n\t//\n\t// Then browse it with `?u=\u003cyour address\u003e`. `Reset` throws it away.\n\t//\n\t// ## Namespaces\n\t//\n\t// - [`demo`](/r/moul/x/plan9/ns/v1:ns?u=demo)\n\t//\n\t// Design and analysis: [moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\t//\n\t// _Not affiliated with Plan 9. Plan 9 from Bell Labs is the work of the Computing Science Research Center at Bell Labs; the name and the marks are theirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org). This realm borrows the vocabulary and none of the code: it is an homage, asking what that ecosystem's spirit looks like on a chain._\n}\n\n// ExampleRender_ls pins a union directory listing.\nfunc ExampleRender_ls() {\n\tresetForExample()\n\tprint(Render(\"ls/bin\"))\n\t// Output:\n\t// # ls /bin\n\t//\n\t// namespace: `demo`\n\t//\n\t// ```\n\t// -rw-r--r-- demo         demo          10 ls\n\t// -rw-r--r-- demo         demo          10 rc\n\t// ```\n\t//\n\t// [namespace](/r/moul/x/plan9/ns/v1:ns?u=demo) · [root](/r/moul/x/plan9/ns/v1:ls?u=demo) · [home](/r/moul/x/plan9/ns/v1)\n}\n\n// ExampleRender_walk pins a resolution trace, which is where a bind becomes\n// visible: the union column widens exactly at the bound name.\nfunc ExampleRender_walk() {\n\tresetForExample()\n\tprint(Render(\"walk/bin/rc\"))\n\t// Output:\n\t// # walk /bin/rc\n\t//\n\t// namespace: `demo`\n\t//\n\t// ```\n\t// /                        (1 5 d) drwxr-xr-x union=1\n\t// /bin                     (a 1 d) drwxr-xr-x union=2\n\t// /bin/rc                  (9 1 f) -rw-r--r-- union=1\n\t// ```\n\t//\n\t// [namespace](/r/moul/x/plan9/ns/v1:ns?u=demo) · [root](/r/moul/x/plan9/ns/v1:ls?u=demo) · [home](/r/moul/x/plan9/ns/v1)\n}\n"}]},"send":"","max_deposit":"14000000ugnot"}],"fee":{"gas_wanted":"99926800","gas_fee":"299780ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"QOuS9mXlb9YfngAneDYKLivmSvo22SUz9b0Z0cyfuglB3PtvEYf2d2bPQgeoZ9e4lGjZ9yST/2junlS4Lc5I1w=="}],"memo":""},"metadata":{"timestamp":"1790961576"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"dev","path":"gno.land/r/moul/x/plan9/dev/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/plan9/dev/v1`\n\n**The chain as a Plan 9 device tree.** Everything a realm normally reaches\nthrough an import of `chain/runtime` is published here as a file instead, so it\ncan be read, listed, bound and unioned like anything else.\n\n```\ncat /dev/sysname     the chain id\ncat /dev/height      the block height\ncat /dev/session     what a delegated key is allowed to touch\n```\n\n| device | contents |\n|---|---|\n| `caller` | pkgpath of the realm that crossed into this read |\n| `domain` | the chain domain |\n| `drivers` | the table itself |\n| `height` | current block height |\n| `null` | always empty |\n| `random` | sha256 of chain id and height, hex; block-deterministic, **not** unpredictable |\n| `session` | the calling key's session scope, one `AllowPath` per line |\n| `sysname` | the chain id |\n| `time` | block time, RFC3339 |\n| `user` | the origin caller's address |\n| `zero` | endless NUL bytes; reads exactly what you ask for |\n\nA device is code, not storage: reading `/dev/height` runs a function, so it is\nnever stale.\n\n## The cross-realm mount\n\nThis realm posts its tree to\n[`r/moul/x/plan9/ns`](../../../../../r/moul/x/plan9/ns/v1)'s `/srv` at deploy\ntime, so any account can bind it into their own namespace and nobody has to\nimport this realm to use it:\n\n```\nbind /srv/dev /dev\n```\n\nThat is the mechanism the whole experiment turns on: an interface value\npublished by one realm, stored by another, and called back later from a\nread-only `Render`. Gno has no dynamic dispatch by path, so a mount cannot be a\nclient pulling a server by name; `/srv` is not a convenience here, it is the\nonly available mechanism, which is a pleasing accident.\n\nThe tree is read-only, like every [`synfs`](../../../../../p/moul/x/plan9/synfs/v0)\ntree: the files have no `Write`, so grafting this into a stranger's namespace\ncannot be turned into a write against this realm.\n\n## Why `/dev/session` is the interesting one\n\nA gno.land account session is a delegated key scoped to a list of path\nprefixes. That is Plan 9's \"the namespace *is* the capability set\", rediscovered\nthirty-four years later, minus the ability to look at it as a tree. This file\nprints it.\n\nDesign and analysis:\n[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\n\n---\n\n**Not affiliated with Plan 9.** Plan 9 from Bell Labs is the work of the\nComputing Science Research Center at Bell Labs; the name and the marks are\ntheirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org).\nThis realm borrows the vocabulary and none of the code: it is an independent\nhomage, asking what that ecosystem's spirit looks like on a chain. Full\nattribution: [NOTICE](../../../../../NOTICE.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/plan9/dev/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/dev/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/plan9/dev/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/dev/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/plan9/dev/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/dev/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/plan9/dev/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/plan9/dev/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/plan9/dev/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/plan9/dev/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"dev.gno","body":"// Package dev is the chain as a Plan 9 device tree.\n//\n// In Plan 9 a device is not storage, it is code behind a name: reading\n// /dev/time runs a function. Everything a gno realm normally reaches through\n// an import of chain/runtime is published here as a file instead, so it can be\n// read, listed, bound and unioned like anything else:\n//\n//\tcat /dev/sysname     the chain id\n//\tcat /dev/height      the block height\n//\tcat /dev/session     what a delegated key is allowed to touch\n//\n// The tree is posted to gno.land/r/moul/x/plan9/ns's /srv at deploy time, so\n// any account can bind it into their own namespace, and nobody has to import\n// this realm to use it. That is the cross-realm mount the whole experiment\n// turns on: an interface value published by one realm, stored by another, and\n// called later from a read-only Render.\n//\n// It is READ-ONLY, like every synthetic tree: the files have no Write, so\n// grafting this into a stranger's namespace cannot be turned into a write\n// against this realm.\n//\n// /dev/session is the one to look at. A gno.land account session is a\n// delegated key scoped to a list of path prefixes, which is Plan 9's \"the\n// namespace IS the capability\" rediscovered thirty-four years later. Printing\n// it as a file makes that visible.\n//\n// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research\n// Center at Bell Labs; the name and the marks are theirs, and the copyright is\n// held by the Plan 9 Foundation (https://p9f.org). This realm is not\n// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9\n// code: it borrows the vocabulary so that the design reads without a glossary,\n// and it is an homage, asking what that ecosystem's spirit looks like on a\n// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.\npackage dev\n\nimport (\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n\tsynfs \"gno.land/p/moul/x/plan9/synfs/v0\"\n\n\tnsrealm \"gno.land/r/moul/x/plan9/ns/v1\"\n)\n\nvar tree *synfs.Tree\n\n// docs describes each device, for Render and for /dev/drivers.\nvar docs = [][2]string{\n\t{\"caller\", \"pkgpath of the realm that crossed into this read\"},\n\t{\"domain\", \"the chain domain\"},\n\t{\"drivers\", \"this table\"},\n\t{\"height\", \"current block height\"},\n\t{\"null\", \"always empty; the bit bucket\"},\n\t{\"random\", \"sha256 of chain id and height, hex; block-deterministic, NOT unpredictable\"},\n\t{\"session\", \"the calling key's session scope, one AllowPath per line\"},\n\t{\"sysname\", \"the chain id\"},\n\t{\"time\", \"block time, RFC3339\"},\n\t{\"user\", \"the origin caller's address\"},\n\t{\"zero\", \"endless NUL bytes; reads exactly what you ask for\"},\n}\n\nfunc init(cur realm) {\n\ttree = build()\n\tnsrealm.Post(cross(cur), \"dev\", tree.Root())\n}\n\nfunc build() *synfs.Tree {\n\tt := synfs.New(\"dev\", \"sys\", func() int64 { return runtime.ChainHeight() })\n\tr := t.Root()\n\n\tr.Add(\"sysname\", func() string { return runtime.ChainID() })\n\tr.Add(\"domain\", func() string { return runtime.ChainDomain() })\n\tr.Add(\"height\", func() string { return strconv.FormatInt(runtime.ChainHeight(), 10) })\n\tr.Add(\"time\", func() string { return time.Now().Format(time.RFC3339) })\n\tr.Add(\"user\", func() string { return unsafe.OriginCaller().String() })\n\tr.Add(\"caller\", func() string { return unsafe.PreviousRealm().PkgPath() })\n\tr.Add(\"null\", func() string { return \"\" })\n\tr.Add(\"random\", func() string {\n\t\tsum := sha256.Sum256([]byte(runtime.ChainID() + \":\" +\n\t\t\tstrconv.FormatInt(runtime.ChainHeight(), 10)))\n\t\treturn hex.EncodeToString(sum[:])\n\t})\n\tr.Add(\"session\", session)\n\tr.Add(\"drivers\", drivers)\n\n\t// /dev/zero has no end, so it serves the read window itself rather than\n\t// materialising a value. An unbounded read returns nothing, which is what\n\t// stops `cat /dev/zero` from being a denial of service.\n\tr.AddRange(\"zero\", 0444, func(off, count int64) (string, error) {\n\t\tif count \u003c= 0 {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tif count \u003e 4096 {\n\t\t\tcount = 4096\n\t\t}\n\t\treturn strings.Repeat(\"\\x00\", int(count)), nil\n\t})\n\treturn t\n}\n\n// session prints the calling key's authority. A plain key has none, which is\n// itself worth saying out loud.\nfunc session() string {\n\tpubKeyAddr, expiresAt, allowPaths, isSession := runtime.GetSessionInfo()\n\tif !isSession {\n\t\tvar b strings.Builder\n\t\tb.WriteString(\"session no\\n\")\n\t\tb.WriteString(\"scope full\\n\")\n\t\treturn b.String()\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"session yes\\n\")\n\tb.WriteString(\"key \" + pubKeyAddr.String() + \"\\n\")\n\tb.WriteString(\"expires \" + strconv.FormatInt(expiresAt, 10) + \"\\n\")\n\tfor _, p := range allowPaths {\n\t\tb.WriteString(\"allow \" + p + \"\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc drivers() string {\n\tvar b strings.Builder\n\tfor _, d := range docs {\n\t\tb.WriteString(d[0] + \"\\t\" + d[1] + \"\\n\")\n\t}\n\treturn b.String()\n}\n\n// Root returns the device tree, for a realm that would rather import it than\n// bind it. Reading it is safe from anywhere; it has no mutating method.\nfunc Root() ninep.File { return tree.Root() }\n\n// Render lists the devices, or reads one.\n//\n//\tRender(\"\")            the table of devices\n//\tRender(\"cat/height\")  one device's contents\nfunc Render(path string) string {\n\tparts := strings.Split(strings.Trim(path, \"/\"), \"/\")\n\tif len(parts) \u003e= 2 \u0026\u0026 parts[0] == \"cat\" {\n\t\tname := parts[1]\n\t\tf, err := tree.Root().Walk(name)\n\t\tif err != nil {\n\t\t\treturn \"# /dev/\" + ui.Inline(name) + \"\\n\\n\" + md.CodeBlock(err.Error())\n\t\t}\n\t\tdata, err := ninep.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn \"# /dev/\" + ui.Inline(name) + \"\\n\\n\" + md.CodeBlock(err.Error())\n\t\t}\n\t\treturn \"# /dev/\" + ui.Inline(name) + \"\\n\\n\" + md.CodeBlock(strings.TrimSuffix(data, \"\\n\")) + \"\\n[all devices](/r/moul/x/plan9/dev/v1)\\n\"\n\t}\n\treturn renderIndex()\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# /dev\\n\\n\")\n\tb.WriteString(\"The chain as a Plan 9 device tree. Each file is a function: reading it \")\n\tb.WriteString(\"runs code, so `/dev/height` is never stale.\\n\\n\")\n\tb.WriteString(\"Posted to [`r/moul/x/plan9/ns`](/r/moul/x/plan9/ns/v1)'s `/srv` at deploy \")\n\tb.WriteString(\"time, so no realm has to import this one to use it:\\n\\n\")\n\tb.WriteString(\"```\\nbind /srv/dev /dev\\n```\\n\\n\")\n\tb.WriteString(\"| device | contents |\\n|---|---|\\n\")\n\tfor _, d := range docs {\n\t\tb.WriteString(\"| [`\" + d[0] + \"`](/r/moul/x/plan9/dev/v1:cat/\" + d[0] + \") | \" + d[1] + \" |\\n\")\n\t}\n\tb.WriteString(\"\\nDesign and analysis: \")\n\tb.WriteString(\"[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\\n\")\n\tb.WriteString(\"\\n_Not affiliated with Plan 9. Plan 9 from Bell Labs is the \")\n\tb.WriteString(\"work of the Computing Science Research Center at Bell Labs; the name \")\n\tb.WriteString(\"and the marks are theirs, and the copyright is held by the \")\n\tb.WriteString(\"[Plan 9 Foundation](https://p9f.org). This realm borrows the \")\n\tb.WriteString(\"vocabulary and none of the code: it is an homage, asking what that \")\n\tb.WriteString(\"ecosystem's spirit looks like on a chain._\\n\")\n\treturn b.String()\n}\n"},{"name":"dev_test.gno","body":"package dev\n\nimport (\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\n\tninep \"gno.land/p/moul/x/plan9/ninep/v0\"\n\n\tnsrealm \"gno.land/r/moul/x/plan9/ns/v1\"\n)\n\nfunc read(t *testing.T, name string) string {\n\tt.Helper()\n\tf, err := tree.Root().Walk(name)\n\tif err != nil {\n\t\tt.Fatalf(\"walk %s: %v\", name, err)\n\t}\n\tdata, err := ninep.ReadAll(f)\n\tif err != nil {\n\t\tt.Fatalf(\"read %s: %v\", name, err)\n\t}\n\treturn data\n}\n\nfunc TestDevicesFollowTheChain(t *testing.T) {\n\tif got, want := read(t, \"sysname\"), runtime.ChainID(); got != want {\n\t\tt.Errorf(\"sysname: got %q, want %q\", got, want)\n\t}\n\tif got, want := read(t, \"domain\"), runtime.ChainDomain(); got != want {\n\t\tt.Errorf(\"domain: got %q, want %q\", got, want)\n\t}\n\tif got, want := read(t, \"height\"), strconv.FormatInt(runtime.ChainHeight(), 10); got != want {\n\t\tt.Errorf(\"height: got %q, want %q\", got, want)\n\t}\n\n\t// A device is code, not storage: advance the chain and the file follows.\n\tbefore := read(t, \"height\")\n\ttesting.SkipHeights(5)\n\tafter := read(t, \"height\")\n\tif before == after {\n\t\tt.Errorf(\"height did not move: %q\", after)\n\t}\n\tb, _ := strconv.ParseInt(before, 10, 64)\n\ta, _ := strconv.ParseInt(after, 10, 64)\n\tif a-b != 5 {\n\t\tt.Errorf(\"height moved by %d, want 5\", a-b)\n\t}\n}\n\nfunc TestRandomIsBlockDeterministic(t *testing.T) {\n\ta := read(t, \"random\")\n\tif len(a) != 64 {\n\t\tt.Errorf(\"a sha256 in hex is 64 characters, got %d\", len(a))\n\t}\n\tif a != read(t, \"random\") {\n\t\tt.Error(\"two reads in the same block must agree, or Render is a consensus bug\")\n\t}\n\ttesting.SkipHeights(1)\n\tif a == read(t, \"random\") {\n\t\tt.Error(\"the value should change with the block\")\n\t}\n}\n\nfunc TestNullAndZero(t *testing.T) {\n\tif got := read(t, \"null\"); got != \"\" {\n\t\tt.Errorf(\"null: %q\", got)\n\t}\n\tf, _ := tree.Root().Walk(\"zero\")\n\tgot, _ := f.Read(0, 4)\n\tif got != \"\\x00\\x00\\x00\\x00\" {\n\t\tt.Errorf(\"zero: %q\", got)\n\t}\n\t// An endless file must not answer an unbounded read with an endless value.\n\tif got, _ := f.Read(0, -1); got != \"\" {\n\t\tt.Errorf(\"unbounded read of /dev/zero: %d bytes\", len(got))\n\t}\n\tif got, _ := f.Read(0, 1\u003c\u003c20); len(got) != 4096 {\n\t\tt.Errorf(\"a huge read should cap at 4096, got %d\", len(got))\n\t}\n}\n\nfunc TestSessionReportsAPlainKey(t *testing.T) {\n\tgot := read(t, \"session\")\n\tif got != \"session no\\nscope full\\n\" {\n\t\tt.Errorf(\"a plain key has no session scope: %q\", got)\n\t}\n}\n\nfunc TestDriversListsEveryDevice(t *testing.T) {\n\tgot := read(t, \"drivers\")\n\tents, err := tree.Root().ReadDir()\n\tif err != nil {\n\t\tt.Fatalf(\"readdir: %v\", err)\n\t}\n\tfor _, e := range ents {\n\t\tif !strings.Contains(got, e.Name+\"\\t\") {\n\t\t\tt.Errorf(\"/dev/drivers does not document %q\", e.Name)\n\t\t}\n\t}\n\tif len(ents) != len(docs) {\n\t\tt.Errorf(\"%d devices but %d documented\", len(ents), len(docs))\n\t}\n}\n\nfunc TestTreeIsReadOnly(t *testing.T) {\n\tvar f ninep.File = tree.Root()\n\tif _, ok := f.(ninep.Mutable); ok {\n\t\tt.Error(\"a device tree handed to other realms must not be Mutable\")\n\t}\n}\n\n// TestPostedAtDeployTime is the cross-realm claim the whole suite rests on:\n// this realm pushed an interface value into another realm at init, and that\n// realm can call it back later from a read.\nfunc TestPostedAtDeployTime(t *testing.T) {\n\tfound := false\n\tfor _, s := range nsrealm.Services() {\n\t\tif s == \"dev\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tt.Fatalf(\"dev is not posted in /srv: %v\", nsrealm.Services())\n\t}\n}\n\nfunc TestAFreshNamespaceHasDevBound(cur realm, t *testing.T) {\n\tuser := testutils.TestAddress(\"glenda\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tnsrealm.Reset(cross(cur))\n\t// Touch the namespace so it is built with /dev already bound.\n\tnsrealm.Exec(cross(cur), \"echo hi \u003e /tmp/hi\")\n\n\tout, err := nsrealm.Run(user.String(), \"ls /dev\")\n\tif err != nil {\n\t\tt.Fatalf(\"ls /dev: %v\", err)\n\t}\n\tfor _, d := range docs {\n\t\tif !strings.Contains(out, d[0]) {\n\t\t\tt.Errorf(\"ls /dev is missing %q: %q\", d[0], out)\n\t\t}\n\t}\n\tgot, err := nsrealm.Run(user.String(), \"cat /dev/sysname\")\n\tif err != nil {\n\t\tt.Fatalf(\"cat: %v\", err)\n\t}\n\tif got != runtime.ChainID() {\n\t\tt.Errorf(\"reading this realm's device through another realm's namespace: %q\", got)\n\t}\n\t// And the mount table says where it came from.\n\tif ns := nsrealm.Namespace(user.String()); !strings.Contains(ns, \"bind /srv/dev /dev\") {\n\t\tt.Errorf(\"mount table: %q\", ns)\n\t}\n}\n\n// The device name comes from the URL: escaped in the heading.\nfunc TestDeviceNameIsEscaped(t *testing.T) {\n\t// No slash in the payload: Render splits the path on \"/\".\n\tout := Render(\"cat/x` [claim](evil.example) `\")\n\tuassert.False(t, strings.Contains(out, \"[claim](evil.example)\"), out)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/plan9/dev/v1\"\ngno = \"0.9\"\n\n# public: posts its own tree into r/moul/x/plan9/ns, and a private realm may\n# not persist an object it owns into another realm\n"},{"name":"render_example_test.gno","body":"package dev\n\n// ExampleRender pins the device index. It carries no chain value, so it does\n// not move with the block height the way the devices themselves do.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # /dev\n\t//\n\t// The chain as a Plan 9 device tree. Each file is a function: reading it runs code, so `/dev/height` is never stale.\n\t//\n\t// Posted to [`r/moul/x/plan9/ns`](/r/moul/x/plan9/ns/v1)'s `/srv` at deploy time, so no realm has to import this one to use it:\n\t//\n\t// ```\n\t// bind /srv/dev /dev\n\t// ```\n\t//\n\t// | device | contents |\n\t// |---|---|\n\t// | [`caller`](/r/moul/x/plan9/dev/v1:cat/caller) | pkgpath of the realm that crossed into this read |\n\t// | [`domain`](/r/moul/x/plan9/dev/v1:cat/domain) | the chain domain |\n\t// | [`drivers`](/r/moul/x/plan9/dev/v1:cat/drivers) | this table |\n\t// | [`height`](/r/moul/x/plan9/dev/v1:cat/height) | current block height |\n\t// | [`null`](/r/moul/x/plan9/dev/v1:cat/null) | always empty; the bit bucket |\n\t// | [`random`](/r/moul/x/plan9/dev/v1:cat/random) | sha256 of chain id and height, hex; block-deterministic, NOT unpredictable |\n\t// | [`session`](/r/moul/x/plan9/dev/v1:cat/session) | the calling key's session scope, one AllowPath per line |\n\t// | [`sysname`](/r/moul/x/plan9/dev/v1:cat/sysname) | the chain id |\n\t// | [`time`](/r/moul/x/plan9/dev/v1:cat/time) | block time, RFC3339 |\n\t// | [`user`](/r/moul/x/plan9/dev/v1:cat/user) | the origin caller's address |\n\t// | [`zero`](/r/moul/x/plan9/dev/v1:cat/zero) | endless NUL bytes; reads exactly what you ask for |\n\t//\n\t// Design and analysis: [moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n\t//\n\t// _Not affiliated with Plan 9. Plan 9 from Bell Labs is the work of the Computing Science Research Center at Bell Labs; the name and the marks are theirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org). This realm borrows the vocabulary and none of the code: it is an homage, asking what that ecosystem's spirit looks like on a chain._\n}\n\n// ExampleRender_cat pins one device read. /dev/drivers is the one device whose\n// contents are fixed, which makes it the only one an example can assert; the\n// chain-derived ones are checked against chain/runtime in dev_test.gno.\nfunc ExampleRender_cat() {\n\tprint(Render(\"cat/drivers\"))\n\t// Output:\n\t// # /dev/drivers\n\t//\n\t// ```\n\t// caller\tpkgpath of the realm that crossed into this read\n\t// domain\tthe chain domain\n\t// drivers\tthis table\n\t// height\tcurrent block height\n\t// null\talways empty; the bit bucket\n\t// random\tsha256 of chain id and height, hex; block-deterministic, NOT unpredictable\n\t// session\tthe calling key's session scope, one AllowPath per line\n\t// sysname\tthe chain id\n\t// time\tblock time, RFC3339\n\t// user\tthe origin caller's address\n\t// zero\tendless NUL bytes; reads exactly what you ask for\n\t// ```\n\t//\n\t// [all devices](/r/moul/x/plan9/dev/v1)\n}\n"}]},"send":"","max_deposit":"8000000ugnot"}],"fee":{"gas_wanted":"61025600","gas_fee":"183076ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"tgjYkUQep3AvjFerN7K/v7P4Mo0ccNU8P4DffIgshOISy0Y6RJtTnYU4Gy3ORbLyTXJGmhPl16hXjpGNdL6b2A=="}],"memo":""},"metadata":{"timestamp":"1790961577"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"fXcCNVWlDiz36ACTmPFz4jOL0gr+/BICW+xIpyWKZdNDJeLkajgrF5r8CI1FOgSDZkYAuwdtA7+2iXUlhZjpJA=="}],"memo":""},"metadata":{"timestamp":"1790961577"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"NJT+yWIc7jdWA5PXhzsmR3oYTPsXK+AyQAtiCl08FMAm1TErapdV4Y5ASDZvMpihtp1zm3jT7OpBI4mqB99+pA=="}],"memo":""},"metadata":{"timestamp":"1790961631"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"provable","path":"gno.land/r/moul/x/provable/v0","files":[{"name":"README.md","body":"# provable\n\nWhat gno.land can and cannot prove about itself, demonstrated rather than asserted.\n\nDemo realm for [`p/moul/x/merkle/v0`](../../../../../p/moul/x/merkle/v0) and\n[`p/moul/x/mmr/v0`](../../../../../p/moul/x/mmr/v0).\n\n## The working half\n\nThe realm keeps a small append-only log in a Merkle mountain range and hands out inclusion\nproofs against its root. Appending costs O(log n) hashes and never rebuilds. Verification is\na single native `crypto/merkle` call.\n\n```\nAppend(\"something\")                  → index\nRoot()                               → the current root, hex\nProofOf(index)                       → path, before, after\nVerify(root, index, total, entry, path, before, after) → bool\n```\n\n`Verify` takes the root as an **argument** rather than reading it from state. That is the\nhonest signature: the realm is a verifier, not an oracle. Passing `Root()` checks against the\nlive log; passing an older root checks against that older log.\n\n`VerifyFixed` accepts the other proof encoding, the flat Tendermint sibling list, against the\nsame root. Both work because the log's root **is** the Tendermint simple-tree root over the\nsame entries. `TestVerifyFixedAcceptsTendermintProof` pins that rather than asserting it.\n\n## The half that is the point\n\nA proof from this realm says *this entry is consistent with the root this realm published*.\nIt cannot say *this root is the chain's own*. Two independent reasons, both verifiable in the\nmonorepo source:\n\n**1. Realm state is not merkleized.** `gno.land/pkg/gnoland/app.go` mounts exactly two stores:\n\n```go\nbaseApp.MountStoreWithDB(mainKey, iavl.StoreConstructor, cfg.DB)      // merkleized\nbaseApp.MountStoreWithDB(baseKey, dbadapter.StoreConstructor, cfg.DB) // not\n```\n\nand `tm2/pkg/store/dbadapter/store.go` says it in a comment: *\"Always returns a zero\ncommitID, as dbadapter store doesn't merkleize\"*. The VM keeper takes both, and\n`gnovm/pkg/gnolang/store.go` puts realm objects, types and realm metadata in the **base**\nstore.\n\n| Data | Store | Provable against the app hash |\n|---|---|---|\n| Package source | iavl | yes |\n| Account balances | iavl | yes |\n| Escaped object hashes (cross-realm, refcount \u003e 1) | iavl | yes, the hash only |\n| Realm objects, types, realm metadata | base | **no** |\n| This log | base | **no** |\n\nSo you can prove to a light client that a package has a given source, and that an address\nholds a given balance. You cannot prove that any realm's AVL tree contains any key. Every\nGRC20 balance and every DAO vote on the chain is, today, unprovable.\n\n**2. A realm cannot see a header.** `chain/runtime` exposes `ChainID`, `ChainDomain`,\n`ChainHeight` and `GetSessionInfo`, and nothing else. No app hash, no block hash, no header.\nEven handed a valid Tendermint proof, a realm has no trusted root to check it against.\n\nThe one crack in the wall: an **escaped** object, one referenced across realm boundaries, does\nget its hash written into the IAVL store. Cross-realm objects are partially provable already.\nNothing else is.\n\n## Why say so out loud\n\nMerkle proofs are the part of a chain that most invites overclaiming. \"Verifiable on chain\"\nis true here in a narrow sense and false in the sense a reader assumes. Anything built on\nMerkle proofs in a gno realm is trust-minimised relative to a committed root, never trustless.\nA demo that showed only the working half would be the interesting-sounding part of a true\nstory.\n\n## Bounds\n\n`MaxEntries` is 512 and `MaxEntryLen` is 256 bytes. `Render` lists the last 10 entries, so the\npage stays a fixed size: the chain caps a query at `maxGasQuery` and a reader cannot raise it,\nso an unbounded `Render` is a permanently unreadable page.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/provable/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/provable/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/provable/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/provable/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/provable/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/provable/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/provable/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/provable/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/provable/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/provable/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/provable/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"provable.gno","body":"// Package provable is an honest demonstration of what gno.land can and cannot\n// prove about itself.\n//\n// It keeps a small append-only log in a Merkle mountain range and hands out\n// inclusion proofs against the log's root. That part works, and it is the\n// useful half: a realm can commit to a set and let anyone verify membership\n// cheaply, with one native call.\n//\n// The other half is the point of the realm. A proof here says \"this entry is\n// consistent with the root this realm published\". It cannot say \"this root is\n// the chain's own\", because:\n//\n//  1. gno.land mounts two stores (gno.land/pkg/gnoland/app.go). The IAVL one\n//     is merkleized and holds package source and account balances. The other\n//     is a plain dbadapter whose Commit is documented as\n//     \"Always returns a zero commitID, as dbadapter store doesn't merkleize\",\n//     and THAT is where every realm's objects live. So no realm's state,\n//     including this log, contributes anything to the app hash. There is no\n//     state proof to produce.\n//  2. chain/runtime exposes ChainID, ChainDomain, ChainHeight and\n//     GetSessionInfo, and nothing else. No app hash, no block hash, no header.\n//     So even given a Tendermint proof, a realm has no trusted root to check\n//     it against.\n//\n// The one crack in the wall: an ESCAPED object, one referenced across realm\n// boundaries, does get its hash written into the IAVL store\n// (gnovm/pkg/gnolang/store.go). Cross-realm objects are therefore partially\n// provable already. Nothing else is.\n//\n// Demo of gno.land/p/moul/x/merkle/v0 and gno.land/p/moul/x/mmr/v0.\npackage provable\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n\t\"gno.land/p/moul/x/mmr/v0\"\n)\n\nconst (\n\t// MaxEntries bounds the log. Unbounded append from an untrusted caller is\n\t// a storage-growth hazard even when the caller pays the deposit, and an\n\t// unbounded Render is a permanently unreadable page: the chain caps a\n\t// query at maxGasQuery, and a reader cannot raise it.\n\tMaxEntries = 512\n\n\t// MaxEntryLen bounds one entry.\n\tMaxEntryLen = 256\n\n\t// renderEntries is how many of the most recent entries Render lists, so\n\t// the page stays a fixed size no matter how full the log is.\n\trenderEntries = 10\n)\n\nvar (\n\tlog     = mmr.New()\n\tentries []string\n)\n\nfunc init() { seed() }\n\n// Append adds an entry to the log and returns its index. The root moves, so\n// every previously issued proof stops verifying against the new root: that is\n// the nature of an append-only commitment, not a bug.\nfunc Append(cur realm, entry string) int { return appendEntry(entry) }\n\nfunc appendEntry(entry string) int {\n\tentry = strings.TrimSpace(entry)\n\tif entry == \"\" {\n\t\tpanic(\"provable: empty entry\")\n\t}\n\tif len(entry) \u003e MaxEntryLen {\n\t\tpanic(\"provable: entry longer than \" + strconv.Itoa(MaxEntryLen) + \" bytes\")\n\t}\n\tif len(entries) \u003e= MaxEntries {\n\t\tpanic(\"provable: log is full at \" + strconv.Itoa(MaxEntries) + \" entries\")\n\t}\n\tentries = append(entries, entry)\n\treturn log.Append([]byte(entry))\n}\n\n// Size returns the number of entries.\nfunc Size() int { return log.Size() }\n\n// Root returns the current log root, hex-encoded. It is also the Tendermint\n// simple-tree root over the same entries, so any Tendermint verifier accepts\n// it.\nfunc Root() string { return log.RootHex() }\n\n// Entry returns the entry at index.\nfunc Entry(index int) string {\n\tmustRange(index)\n\treturn entries[index]\n}\n\n// ProofOf returns the inclusion proof for index, as the three comma-separated\n// hex lists Verify expects.\nfunc ProofOf(index int) (path, before, after string) {\n\tmustRange(index)\n\tp, err := log.Proof(index)\n\tif err != nil {\n\t\tpanic(\"provable: \" + err.Error())\n\t}\n\treturn p.Hex()\n}\n\n// Verify checks a proof against a root the caller supplies, which is the\n// honest signature: the realm is a verifier, not an oracle. Pass Root() to\n// check against the live log.\nfunc Verify(root string, index, total int, entry, path, before, after string) bool {\n\trb, err := hexHash(root)\n\tif err != nil {\n\t\treturn false\n\t}\n\tp, err := mmr.ParseProof(index, total, path, before, after)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn mmr.Verify(rb, []byte(entry), p)\n}\n\n// VerifyFixed checks a Tendermint simple-tree proof, the fixed-leaf-set\n// encoding, against a root the caller supplies. Same tree as the log, a\n// different proof shape: siblings are one flat list, leaf first.\n//\n// Both encodings verify against the same root, because the Tendermint tree and\n// a right-bagged mountain range are the same structure.\nfunc VerifyFixed(root string, index, total int, leaf, siblings string) bool {\n\trb, err := hexHash(root)\n\tif err != nil {\n\t\treturn false\n\t}\n\tp, err := merkle.ParseProof(index, total, siblings)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn p.Verify(rb, []byte(leaf))\n}\n\nfunc mustRange(index int) {\n\tif index \u003c 0 || index \u003e= len(entries) {\n\t\tpanic(\"provable: index out of range\")\n\t}\n}\n\nfunc hexHash(s string) ([]byte, error) {\n\tp, err := merkle.ParseProof(0, 1, strings.TrimSpace(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(p.Siblings) != 1 {\n\t\treturn nil, merkle.ErrBadHashSize\n\t}\n\treturn p.Siblings[0], nil\n}\n\n// seed returns the realm to its deployed state: an empty log plus the three\n// demo entries, so a fresh deployment renders something and so the example\n// tests have a fixed starting point.\n//\n// Realm globals persist across a whole test binary and examples run after\n// every Test, so a pinned Render must call this first.\nfunc seed() {\n\tlog = mmr.New()\n\tentries = nil\n\tappendEntry(\"genesis of this log\")\n\tappendEntry(\"a second commitment\")\n\tappendEntry(\"a third commitment\")\n}\n"},{"name":"provable_test.gno","body":"package provable\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/merkle/v0\"\n)\n\nfunc TestAppendAndVerify(cur realm, t *testing.T) {\n\tseed()\n\ti := Append(cross(cur), \"a fourth commitment\")\n\tif i != 3 || Size() != 4 {\n\t\tt.Fatalf(\"Append returned %d with Size %d, want 3 and 4\", i, Size())\n\t}\n\tif Entry(i) != \"a fourth commitment\" {\n\t\tt.Errorf(\"Entry(%d) = %q\", i, Entry(i))\n\t}\n\n\troot := Root()\n\tfor j := 0; j \u003c Size(); j++ {\n\t\tpath, before, after := ProofOf(j)\n\t\tif !Verify(root, j, Size(), Entry(j), path, before, after) {\n\t\t\tt.Errorf(\"entry %d: its own proof does not verify\", j)\n\t\t}\n\t}\n}\n\n// Append trims, so the proof must be over the trimmed entry.\nfunc TestAppendTrims(cur realm, t *testing.T) {\n\tseed()\n\ti := Append(cross(cur), \"  padded  \")\n\tif Entry(i) != \"padded\" {\n\t\tt.Fatalf(\"Entry = %q, want %q\", Entry(i), \"padded\")\n\t}\n\tpath, before, after := ProofOf(i)\n\tif !Verify(Root(), i, Size(), \"padded\", path, before, after) {\n\t\tt.Error(\"trimmed entry does not verify\")\n\t}\n\tif Verify(Root(), i, Size(), \"  padded  \", path, before, after) {\n\t\tt.Error(\"the untrimmed string verified, so the leaf is not what is stored\")\n\t}\n}\n\nfunc TestVerifyRejects(cur realm, t *testing.T) {\n\tseed()\n\troot := Root()\n\tpath, before, after := ProofOf(1)\n\tother := \"0000000000000000000000000000000000000000000000000000000000000000\"\n\n\ttests := []struct {\n\t\tname                       string\n\t\troot                       string\n\t\tindex, total               int\n\t\tentry, path, before, after string\n\t}{\n\t\t{\"wrong entry\", root, 1, 3, \"not in the log\", path, before, after},\n\t\t{\"another real entry\", root, 1, 3, Entry(0), path, before, after},\n\t\t{\"wrong index\", root, 0, 3, Entry(1), path, before, after},\n\t\t{\"wrong total\", root, 1, 4, Entry(1), path, before, after},\n\t\t{\"wrong root\", other, 1, 3, Entry(1), path, before, after},\n\t\t{\"root not hex\", \"zz\", 1, 3, Entry(1), path, before, after},\n\t\t{\"root wrong length\", \"abcd\", 1, 3, Entry(1), path, before, after},\n\t\t{\"empty path\", root, 1, 3, Entry(1), \"\", before, after},\n\t\t{\"peaks swapped\", root, 1, 3, Entry(1), path, after, before},\n\t\t{\"garbage path\", root, 1, 3, Entry(1), \"zz\", before, after},\n\t}\n\tfor _, tc := range tests {\n\t\tif Verify(tc.root, tc.index, tc.total, tc.entry, tc.path, tc.before, tc.after) {\n\t\t\tt.Errorf(\"%s: accepted, must be rejected\", tc.name)\n\t\t}\n\t}\n}\n\n// The log root is also the Tendermint simple-tree root over the same entries,\n// so the fixed-leaf-set proof encoding verifies against it too. This is the\n// claim the realm makes in Render; it is tested, not asserted.\nfunc TestVerifyFixedAcceptsTendermintProof(cur realm, t *testing.T) {\n\tseed()\n\tAppend(cross(cur), \"a fourth commitment\")\n\tAppend(cross(cur), \"a fifth commitment\")\n\n\tleaves := make([][]byte, Size())\n\tfor i := range leaves {\n\t\tleaves[i] = []byte(Entry(i))\n\t}\n\ttree := merkle.New(leaves)\n\tif tree.RootHex() != Root() {\n\t\tt.Fatalf(\"tree root %s, log root %s\", tree.RootHex(), Root())\n\t}\n\tfor i := 0; i \u003c Size(); i++ {\n\t\tp, err := tree.Proof(i)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"i=%d: %v\", i, err)\n\t\t}\n\t\tif !VerifyFixed(Root(), i, Size(), Entry(i), p.Hex()) {\n\t\t\tt.Errorf(\"i=%d: Tendermint proof rejected by the realm\", i)\n\t\t}\n\t\tif VerifyFixed(Root(), i, Size(), \"forged\", p.Hex()) {\n\t\t\tt.Errorf(\"i=%d: forged leaf accepted\", i)\n\t\t}\n\t}\n}\n\nfunc TestCaps(t *testing.T) {\n\tseed()\n\ttests := []struct {\n\t\tname  string\n\t\tentry string\n\t}{\n\t\t{\"empty\", \"\"},\n\t\t{\"whitespace only\", \"   \"},\n\t\t{\"too long\", strings.Repeat(\"x\", MaxEntryLen+1)},\n\t}\n\tfor _, tc := range tests {\n\t\tif got := panicked(func() { appendEntry(tc.entry) }); got == \"\" {\n\t\t\tt.Errorf(\"%s: accepted, must panic\", tc.name)\n\t\t}\n\t}\n\t// A note of exactly MaxEntryLen is fine.\n\tif got := panicked(func() { appendEntry(strings.Repeat(\"x\", MaxEntryLen)) }); got != \"\" {\n\t\tt.Errorf(\"entry of exactly MaxEntryLen panicked: %s\", got)\n\t}\n}\n\nfunc TestLogIsBounded(t *testing.T) {\n\tseed()\n\tfor Size() \u003c MaxEntries {\n\t\tappendEntry(\"filler-\" + strconv.Itoa(Size()))\n\t}\n\tif got := panicked(func() { appendEntry(\"one too many\") }); got == \"\" {\n\t\tt.Error(\"appending past MaxEntries was accepted\")\n\t}\n\tseed()\n}\n\nfunc TestEntryRangeChecked(t *testing.T) {\n\tseed()\n\tfor _, i := range []int{-1, 3, 999} {\n\t\tif got := panicked(func() { Entry(i) }); got == \"\" {\n\t\t\tt.Errorf(\"Entry(%d) did not panic\", i)\n\t\t}\n\t\tif got := panicked(func() { ProofOf(i) }); got == \"\" {\n\t\t\tt.Errorf(\"ProofOf(%d) did not panic\", i)\n\t\t}\n\t}\n}\n\n// panicked runs f and returns the panic message, or \"\" if it returned\n// normally. Safe here because these calls are in-package and do not cross a\n// realm boundary, where a panic would be an unrecoverable abort instead.\nfunc panicked(f func()) (msg string) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif s, ok := r.(string); ok {\n\t\t\t\tmsg = s\n\t\t\t} else {\n\t\t\t\tmsg = \"panic\"\n\t\t\t}\n\t\t}\n\t}()\n\tf()\n\treturn \"\"\n}\n"},{"name":"render.gno","body":"package provable\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Render serves the overview at \"\" and one entry with its proof at\n// \"entry/\u003cindex\u003e\".\n//\n// Output is a fixed size: the entry list is capped at renderEntries, so a full\n// log still renders. The chain caps a query at maxGasQuery and a reader cannot\n// raise it, so an unbounded Render is a permanently unreadable page.\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tif strings.HasPrefix(path, \"entry/\") {\n\t\treturn renderEntry(strings.TrimPrefix(path, \"entry/\"))\n\t}\n\treturn renderIndex()\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# provable\\n\\n\")\n\tb.WriteString(\"What gno.land can and cannot prove about itself, demonstrated rather than asserted.\\n\\n\")\n\n\tb.WriteString(\"## The log\\n\\n\")\n\tb.WriteString(\"An append-only Merkle mountain range. Appending costs O(log n) hashes and never rebuilds.\\n\\n\")\n\tb.WriteString(\"| Field | Value |\\n|---|---|\\n\")\n\tb.WriteString(\"| Entries | \" + strconv.Itoa(log.Size()) + \" / \" + strconv.Itoa(MaxEntries) + \" |\\n\")\n\tb.WriteString(\"| Stored hashes | \" + strconv.Itoa(log.Nodes()) + \" |\\n\")\n\tb.WriteString(\"| Peaks | \" + strconv.Itoa(len(log.PeakHashes())) + \" |\\n\")\n\tb.WriteString(\"| Root | `\" + rootOrDash() + \"` |\\n\\n\")\n\n\tb.WriteString(\"This root is also the Tendermint simple-tree root over the same entries, so any\\n\")\n\tb.WriteString(\"Tendermint verifier accepts it. `Verify` and `VerifyFixed` check the two proof\\n\")\n\tb.WriteString(\"encodings against it.\\n\\n\")\n\n\tb.WriteString(\"## What the chain can prove\\n\\n\")\n\tb.WriteString(\"`gno.land/pkg/gnoland/app.go` mounts exactly two stores. One is IAVL and merkleized,\\n\")\n\tb.WriteString(\"the other is a plain dbadapter whose `Commit` is documented as *\\\"Always returns a zero\\n\")\n\tb.WriteString(\"commitID, as dbadapter store doesn't merkleize\\\"*.\\n\\n\")\n\tb.WriteString(\"| Data | Store | Provable against the app hash |\\n|---|---|---|\\n\")\n\tb.WriteString(\"| Package source | iavl | yes |\\n\")\n\tb.WriteString(\"| Account balances | iavl | yes |\\n\")\n\tb.WriteString(\"| Escaped object hashes (cross-realm) | iavl | yes, the hash only |\\n\")\n\tb.WriteString(\"| Realm objects, types, realm metadata | base | **no** |\\n\")\n\tb.WriteString(\"| **This log** | base | **no** |\\n\\n\")\n\n\tb.WriteString(\"## What that means here\\n\\n\")\n\tb.WriteString(\"A proof from this realm says *this entry is consistent with the root this realm\\n\")\n\tb.WriteString(\"published*. It cannot say *this root is the chain's own*, for two independent reasons:\\n\\n\")\n\tb.WriteString(\"1. Realm state is not merkleized, so there is no state proof to produce.\\n\")\n\tb.WriteString(\"2. `chain/runtime` exposes `ChainID`, `ChainDomain`, `ChainHeight` and `GetSessionInfo`\\n\")\n\tb.WriteString(\"   and nothing else. No app hash, no block hash, no header. A realm has no trusted\\n\")\n\tb.WriteString(\"   root to check anything against.\\n\\n\")\n\tb.WriteString(\"Anything built on Merkle proofs in a gno realm is trust-minimised relative to a\\n\")\n\tb.WriteString(\"committed root, never trustless. Saying otherwise would be the interesting-sounding\\n\")\n\tb.WriteString(\"half of a true story.\\n\\n\")\n\n\tb.WriteString(\"## Entries\\n\\n\")\n\tif log.Size() == 0 {\n\t\tb.WriteString(\"_Empty. Call `Append(\\\"something\\\")`._\\n\")\n\t\treturn b.String()\n\t}\n\tstart := 0\n\tif len(entries) \u003e renderEntries {\n\t\tstart = len(entries) - renderEntries\n\t\tb.WriteString(\"Showing the last \" + strconv.Itoa(renderEntries) + \" of \" + strconv.Itoa(len(entries)) + \".\\n\\n\")\n\t}\n\tb.WriteString(\"| # | Entry |\\n|---|---|\\n\")\n\tfor i := start; i \u003c len(entries); i++ {\n\t\tb.WriteString(\"| [\" + strconv.Itoa(i) + \"](/r/moul/x/provable/v0:entry/\" + strconv.Itoa(i) + \") | \" + entries[i] + \" |\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderEntry(raw string) string {\n\ti, err := strconv.Atoi(raw)\n\tif err != nil || i \u003c 0 || i \u003e= len(entries) {\n\t\treturn \"# provable\\n\\nNo entry `\" + raw + \"`.\\n\"\n\t}\n\tpath, before, after := ProofOf(i)\n\tvar b strings.Builder\n\tb.WriteString(\"# provable: entry \" + strconv.Itoa(i) + \"\\n\\n\")\n\tb.WriteString(\"```\\n\" + entries[i] + \"\\n```\\n\\n\")\n\tb.WriteString(\"## Inclusion proof\\n\\n\")\n\tb.WriteString(\"| Field | Value |\\n|---|---|\\n\")\n\tb.WriteString(\"| Index | \" + strconv.Itoa(i) + \" |\\n\")\n\tb.WriteString(\"| Total | \" + strconv.Itoa(log.Size()) + \" |\\n\")\n\tb.WriteString(\"| Path | `\" + orDash(path) + \"` |\\n\")\n\tb.WriteString(\"| Before | `\" + orDash(before) + \"` |\\n\")\n\tb.WriteString(\"| After | `\" + orDash(after) + \"` |\\n\")\n\tb.WriteString(\"| Root | `\" + rootOrDash() + \"` |\\n\\n\")\n\tb.WriteString(\"Valid against that root only. The next `Append` moves it.\\n\")\n\treturn b.String()\n}\n\nfunc rootOrDash() string { return orDash(Root()) }\n\nfunc orDash(s string) string {\n\tif s == \"\" {\n\t\treturn \"-\"\n\t}\n\treturn s\n}\n"},{"name":"render_example_test.gno","body":"package provable\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tseed()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # provable\n\t//\n\t// What gno.land can and cannot prove about itself, demonstrated rather than asserted.\n\t//\n\t// ## The log\n\t//\n\t// An append-only Merkle mountain range. Appending costs O(log n) hashes and never rebuilds.\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Entries | 3 / 512 |\n\t// | Stored hashes | 4 |\n\t// | Peaks | 2 |\n\t// | Root | `c9d22dd237c668944fde619edb56cc1bee0e988b03ac08694f6d3aba440c0776` |\n\t//\n\t// This root is also the Tendermint simple-tree root over the same entries, so any\n\t// Tendermint verifier accepts it. `Verify` and `VerifyFixed` check the two proof\n\t// encodings against it.\n\t//\n\t// ## What the chain can prove\n\t//\n\t// `gno.land/pkg/gnoland/app.go` mounts exactly two stores. One is IAVL and merkleized,\n\t// the other is a plain dbadapter whose `Commit` is documented as *\"Always returns a zero\n\t// commitID, as dbadapter store doesn't merkleize\"*.\n\t//\n\t// | Data | Store | Provable against the app hash |\n\t// |---|---|---|\n\t// | Package source | iavl | yes |\n\t// | Account balances | iavl | yes |\n\t// | Escaped object hashes (cross-realm) | iavl | yes, the hash only |\n\t// | Realm objects, types, realm metadata | base | **no** |\n\t// | **This log** | base | **no** |\n\t//\n\t// ## What that means here\n\t//\n\t// A proof from this realm says *this entry is consistent with the root this realm\n\t// published*. It cannot say *this root is the chain's own*, for two independent reasons:\n\t//\n\t// 1. Realm state is not merkleized, so there is no state proof to produce.\n\t// 2. `chain/runtime` exposes `ChainID`, `ChainDomain`, `ChainHeight` and `GetSessionInfo`\n\t//    and nothing else. No app hash, no block hash, no header. A realm has no trusted\n\t//    root to check anything against.\n\t//\n\t// Anything built on Merkle proofs in a gno realm is trust-minimised relative to a\n\t// committed root, never trustless. Saying otherwise would be the interesting-sounding\n\t// half of a true story.\n\t//\n\t// ## Entries\n\t//\n\t// | # | Entry |\n\t// |---|---|\n\t// | [0](/r/moul/x/provable/v0:entry/0) | genesis of this log |\n\t// | [1](/r/moul/x/provable/v0:entry/1) | a second commitment |\n\t// | [2](/r/moul/x/provable/v0:entry/2) | a third commitment |\n}\n\n// ExampleRenderEntry pins the per-entry page, including a live proof.\nfunc ExampleRenderEntry() {\n\tseed()\n\tprint(Render(\"entry/1\"))\n\t// Output:\n\t// # provable: entry 1\n\t//\n\t// ```\n\t// a second commitment\n\t// ```\n\t//\n\t// ## Inclusion proof\n\t//\n\t// | Field | Value |\n\t// |---|---|\n\t// | Index | 1 |\n\t// | Total | 3 |\n\t// | Path | `8f88aaa49b43fc28f266ea6b4f18d865933cad3584b59f162b8ce55edd8263fc` |\n\t// | Before | `-` |\n\t// | After | `495f0f3042890e970ad8344ae78ff490806c2b8403282d518e8112044bc43827` |\n\t// | Root | `c9d22dd237c668944fde619edb56cc1bee0e988b03ac08694f6d3aba440c0776` |\n\t//\n\t// Valid against that root only. The next `Append` moves it.\n}\n\n// ExampleRenderMissingEntry pins the not-found page.\nfunc ExampleRenderMissingEntry() {\n\tseed()\n\tprint(Render(\"entry/99\"))\n\t// Output:\n\t// # provable\n\t//\n\t// No entry `99`.\n}\n"}]},"send":"","max_deposit":"10000000ugnot"}],"fee":{"gas_wanted":"72949200","gas_fee":"218847ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"Eey/cTuKjmzS+0c4bAk2gKhB09lUcmuwzI5wNIplnUcsuygso8xTFHsfhiWuUBT5m1dgPW1O9ZG/0SJGgvjMMA=="}],"memo":""},"metadata":{"timestamp":"1790961694"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"facade","path":"gno.land/r/moul/x/upgrade/adminreg/facade/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/adminreg/facade/v0`\n\nThe **permanent facade** of pattern F. Implementations nominate themselves from\n`init` (`Propose`); the owner promotes one by path string (`Accept`). Nothing\nserves until both have happened.\n\nAccepting takes a string on purpose: an interface value cannot travel in a\n`maketx call` argument, so the original \"admin hands the facade an object\" shape\nwas not reachable from a wallet at all.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/adminreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/facade/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/adminreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/facade/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/adminreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/facade/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/adminreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/facade/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/adminreg/facade/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/adminreg/facade/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"facade.gno","body":"// untrusted-render: every path Render echoes was read off a crossing frame in\n// Propose (cur.Previous().PkgPath(), which a caller cannot forge or type), and\n// Accept can only promote a key that is already in that tree.\n//\n// Package facade is the permanent entry point of the \"propose and accept\"\n// upgrade pattern (pattern F of the exploration; see ../../README.md).\n//\n// Pattern E lets a deploy take the realm over on the spot. This one splits that\n// into two steps that different people can hold: an implementation realm\n// NOMINATES itself from its own init, and the owner ACCEPTS a package path in a\n// separate transaction. Nothing serves until both have happened.\n//\n// The split exists because of a mechanical limit, not just a governance\n// preference. An implementation is an interface value, and a wallet cannot put\n// one in a `maketx call` argument: only strings and numbers travel. The\n// original shape of this pattern (the owner hands the facade an object) is\n// therefore reachable only from `maketx run` or from another realm. Proposing\n// from init and accepting by PATH makes both halves ordinary transactions.\npackage facade\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst owner address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\" // @moul\n\n// prefix bounds who may even nominate itself. Accepting is still a separate,\n// owner-gated decision.\nconst prefix = \"gno.land/r/moul/x/upgrade/adminreg/impl/\"\n\n// Impl is the contract an implementation realm must satisfy.\ntype Impl interface {\n\tGreet(name string) string\n\tVersion() string\n}\n\n// The stage ladder, copied in shape from Sui's UpgradeCap: compatible, additive,\n// dependency-only, immutable, where a policy can only ever become MORE\n// restrictive and make_immutable discards the cap. CosmWasm (a contract with no\n// admin) and Solana (an upgrade authority set to None) reach the same place with\n// one bit; the ladder is better because the interesting states are between\n// \"anything may take this over\" and \"nothing may ever change again\".\n//\n// This pattern has an owner and a candidate list, so it has a middle rung the\n// owner-less selfreg cannot express: no new code, but still free to roll back\n// among what is already deployed.\n//\n// What the top rung does NOT do on its own: freezing this realm ends changes to\n// the POINTER, not to the code behind it. A private implementation realm can be\n// re-added at its own path, which would swap behaviour under a frozen facade.\n// It holds here only because every implementation is public by construction:\n// handing the facade its own object is exactly what forbids private (see\n// ../../README.md).\nconst (\n\tStageOpen   = 0 // anything under the prefix may propose, the owner may accept any candidate\n\tStageClosed = 1 // no new candidates; the owner may still accept among those already proposed\n\tStageFrozen = 2 // nothing may be accepted again, whatever is live is final\n)\n\nvar (\n\tOwnable = ownable.NewWithAddress(owner)\n\n\tstage = StageOpen\n\n\tcandidates = avl.NewTree() // pkgpath -\u003e Impl\n\tlive       Impl\n\tlivePath   string\n)\n\n// Propose nominates the calling realm. Called from the implementation's init,\n// so deploying makes a candidate and nothing more.\nfunc Propose(cur realm, impl Impl) {\n\tif stage != StageOpen {\n\t\tpanic(\"adminreg/facade/v0 is \" + StageName() + \", no new candidate may be proposed\")\n\t}\n\tcaller := cur.Previous().PkgPath()\n\tif !strings.HasPrefix(caller, prefix) {\n\t\tpanic(\"unauthorized: \" + caller + \" is not under \" + prefix)\n\t}\n\tif impl == nil {\n\t\tpanic(\"implementation must not be nil\")\n\t}\n\tcandidates.Set(caller, impl)\n}\n\n// Accept promotes a proposed path to live. Owner-gated, and it takes a STRING,\n// so it is callable straight from a wallet.\nfunc Accept(cur realm, pkgPath string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tif stage == StageFrozen {\n\t\tpanic(\"adminreg/facade/v0 is frozen, \" + livePath + \" is final\")\n\t}\n\tv := candidates.Get(pkgPath)\n\tif v == nil {\n\t\tpanic(\"no candidate at \" + pkgPath)\n\t}\n\tlive, livePath = v.(Impl), pkgPath\n}\n\n// Close stops new candidates. The owner may still accept among those already\n// proposed, so a rollback stays possible while new code does not.\nfunc Close(cur realm) {\n\ttighten(cur, StageClosed)\n}\n\n// Freeze ends this realm's upgradeability, forever. There is no rung above it\n// and nothing takes it back: that is the whole point, and it is the only way out\n// of every caller trusting the owner rather than the code.\nfunc Freeze(cur realm) {\n\ttighten(cur, StageFrozen)\n}\n\n// tighten is the ratchet. Owner-gated, and it refuses to loosen: the stage is\n// the one piece of state here that a later owner cannot undo.\nfunc tighten(cur realm, to int) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tif to \u003c= stage {\n\t\tpanic(\"the stage ladder only tightens, and this realm is already \" + StageName())\n\t}\n\tstage = to\n}\n\n// Stage is the rung this realm is on. It only ever goes up.\nfunc Stage() int {\n\treturn stage\n}\n\n// StageName is Stage as the word a caller reads in Render.\nfunc StageName() string {\n\tswitch stage {\n\tcase StageFrozen:\n\t\treturn \"frozen\"\n\tcase StageClosed:\n\t\treturn \"closed\"\n\tdefault:\n\t\treturn \"open\"\n\t}\n}\n\n// Live is the package path currently serving, or \"\" before the first Accept.\nfunc Live() string {\n\treturn livePath\n}\n\n// Candidates lists every path that has nominated itself, in order.\nfunc Candidates() []string {\n\tout := []string{}\n\tcandidates.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tout = append(out, k)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Greet forwards to the accepted implementation.\nfunc Greet(name string) string {\n\tassertLive()\n\treturn live.Greet(name)\n}\n\n// Version reports the accepted implementation's own version string.\nfunc Version() string {\n\tassertLive()\n\treturn live.Version()\n}\n\nfunc assertLive() {\n\tif live == nil {\n\t\tpanic(\"no implementation accepted\")\n\t}\n}\n\nfunc Render(_ string) string {\n\tout := ufmt.Sprintf(\"adminreg/facade/v0 [%s]\\n\", StageName())\n\tif live == nil {\n\t\tout += \"live: none accepted\\n\"\n\t} else {\n\t\tout += ufmt.Sprintf(\"live: %s (%s)\\n%s\\n\", live.Version(), livePath, live.Greet(\"world\"))\n\t}\n\tout += ufmt.Sprintf(\"candidates: %d\\n\", candidates.Size())\n\tfor _, p := range Candidates() {\n\t\tout += \"- \" + p + \"\\n\"\n\t}\n\treturn out\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/adminreg/facade/v0\"\ngno = \"0.9\"\n# public: every implementation realm imports it to nominate itself from init\n"},{"name":"render_example_test.gno","body":"package facade\n\n// ExampleRender pins the facade before any implementation realm exists. Nothing\n// is imported here, so there is no candidate and nothing accepted.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// adminreg/facade/v0 [open]\n\t// live: none accepted\n\t// candidates: 0\n}\n"},{"name":"z_outsider_filetest.gno","body":"// PKGPATH: gno.land/r/moul/main\npackage main\n\nimport \"gno.land/r/moul/x/upgrade/adminreg/facade/v0\"\n\n// Nominating is bounded by path even though accepting is bounded by owner: a\n// realm outside the prefix cannot even fill the candidate list with noise.\nfunc main(cur realm) {\n\tfacade.Propose(cross(cur), nil)\n}\n\n// Error:\n// unauthorized: gno.land/r/moul/main is not under gno.land/r/moul/x/upgrade/adminreg/impl/\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lazy","path":"gno.land/r/moul/x/upgrade/lazy/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/lazy/v0`\n\nVersion 0 of the **lazy migration** pattern (pattern D). An ordinary record\nstore, written without any knowledge of a successor. `Size()` never shrinks:\nmigration copies forward, so this realm keeps paying for every record it ever\nheld.\n\nSee [the pattern](../README.md) and [the exploration](../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/lazy/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/lazy/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/lazy/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/lazy/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/lazy/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/lazy/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/lazy/v0\"\ngno = \"0.9\"\n# public: imported by .../lazy/v1, which reads records out of it to migrate them\n"},{"name":"lazy.gno","body":"// Package lazy is version 0 of the \"lazy migration\" upgrade pattern\n// (pattern D of the exploration; see ../README.md).\n//\n// This version is an ordinary record store. It is written without any\n// knowledge of a successor: what makes the pattern work is only that its\n// records are readable from outside, which any avl-backed realm already is.\npackage lazy\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Record is v0's shape. v1 changes it, which is the whole reason for a new\n// version: a stored-layout change is never done in place.\ntype Record struct {\n\tName  string\n\tScore int\n}\n\nfunc (r *Record) String() string {\n\tif r == nil {\n\t\treturn \"nil\"\n\t}\n\treturn ufmt.Sprintf(\"v0{%s %d}\", r.Name, r.Score)\n}\n\nvar records = avl.NewTree()\n\nfunc init() {\n\trecords.Set(\"ada\", \u0026Record{Name: \"ada\", Score: 1})\n\trecords.Set(\"bob\", \u0026Record{Name: \"bob\", Score: 2})\n}\n\n// Get returns a record or nil. Non-crossing: v1 reads through it while\n// migrating, and gnoweb can call it without a transaction.\nfunc Get(key string) *Record {\n\tv := records.Get(key)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*Record)\n}\n\n// Size is how many records still live here. It never shrinks: lazy migration\n// COPIES forward, it does not move, so v0 keeps paying for every record it\n// ever held.\nfunc Size() int {\n\treturn records.Size()\n}\n\nfunc Render(_ string) string {\n\tout := ufmt.Sprintf(\"lazy/v0: %d records\\n\", records.Size())\n\trecords.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tout += ufmt.Sprintf(\"- %s: %s\\n\", k, v.(*Record).String())\n\t\treturn false\n\t})\n\treturn out\n}\n"},{"name":"render_example_test.gno","body":"package lazy\n\n// ExampleRender pins the render of the seeded v0 store.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// lazy/v0: 2 records\n\t// - ada: v0{ada 1}\n\t// - bob: v0{bob 2}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lock","path":"gno.land/r/moul/x/upgrade/lock/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/lock/v0`\n\nVersion 0 of the **retire the predecessor** upgrade pattern (pattern B).\nWritable until the owner calls `Retire(successor)`, which is one-way: from then\non it is a read-only archive that names where callers should go.\n\nSee [the pattern](../README.md) and [the exploration](../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/lock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/lock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/lock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/lock/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/lock/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/lock/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/lock/v0\"\ngno = \"0.9\"\n# public: imported by .../lock/v1, which folds its frozen total in after retirement\n"},{"name":"lock.gno","body":"// untrusted-render: successor is the only stored string Render echoes, and\n// Retire validates it with assertPkgPath before storing it.\n//\n// Package lock is version 0 of the \"retire the predecessor\" upgrade pattern\n// (pattern B of the exploration; see ../README.md).\n//\n// Unlike pattern A, this version knows it can be superseded. Retire() freezes\n// it and names its successor, and the freeze is one-way: once a successor has\n// absorbed this version's total, re-opening it here would double-count.\npackage lock\n\nimport (\n\t\"strings\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst owner address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\" // @moul\n\nvar (\n\tOwnable = ownable.NewWithAddress(owner)\n\n\tcounter   int\n\tsuccessor string // pkgpath that replaced this one; \"\" while this version is live\n)\n\n// Inc adds n. It aborts once a successor has been declared.\nfunc Inc(cur realm, n int) {\n\tif successor != \"\" {\n\t\tpanic(\"lock/v0 is retired, use \" + successor)\n\t}\n\tcounter += n\n}\n\n// Get returns this version's final (or current) total.\nfunc Get() int {\n\treturn counter\n}\n\n// Successor is the path callers should move to, or \"\" while this version is live.\nfunc Successor() string {\n\treturn successor\n}\n\n// Retire freezes this version and names its replacement. Owner-gated, one-way.\nfunc Retire(cur realm, pkgPath string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tif successor != \"\" {\n\t\tpanic(\"lock/v0 is already retired, successor is \" + successor)\n\t}\n\tassertPkgPath(pkgPath)\n\tsuccessor = pkgPath\n}\n\nfunc Render(_ string) string {\n\tif successor == \"\" {\n\t\treturn ufmt.Sprintf(\"lock/v0: %d (live)\\n\", counter)\n\t}\n\treturn ufmt.Sprintf(\"lock/v0: %d (retired, use %s)\\n\", counter, successor)\n}\n\n// assertPkgPath rejects anything that is not a gno.land realm path.\n//\n// It exists for Render, not for correctness of the upgrade: the stored path is\n// echoed into markdown, so validating it at write time is what lets Render\n// print it raw. ui.Inline would escape the dots in \"gno.land\" and turn the one\n// string a reader needs to copy into \"gno\\.land\".\nfunc assertPkgPath(p string) {\n\tif !strings.HasPrefix(p, \"gno.land/r/\") {\n\t\tpanic(\"not a realm path: \" + p)\n\t}\n\tfor _, c := range p {\n\t\tok := c == '/' || c == '.' || c == '_' || c == '-' ||\n\t\t\t(c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9')\n\t\tif !ok {\n\t\t\tpanic(\"illegal character in realm path\")\n\t\t}\n\t}\n}\n"},{"name":"render_example_test.gno","body":"package lock\n\n// ExampleRender pins the render of a freshly deployed, still-live version.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// lock/v0: 0 (live)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"facade","path":"gno.land/r/moul/x/upgrade/schema/facade/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/schema/facade/v0`\n\nThe **permanent entry point** of pattern G. Holds one `Call(cur, verb, payload)`\nsignature forever and moves the API into data each handler declares: it parses the\nschema, checks arity before dispatch, enumerates verbs without a transaction, and\nrefuses an upgrade whose schema would break an existing caller.\n\nSee [the pattern](../README.md) and [the exploration](../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/schema/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/facade/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/schema/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/facade/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/schema/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/facade/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/schema/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/facade/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/schema/facade/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/schema/facade/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"facade.gno","body":"// untrusted-render: every string Render echoes is either a verb name validated\n// by parseSchema against [a-z0-9_] at accept time, or a package path read off a\n// crossing frame. No caller-typed payload is ever rendered.\n//\n// Package facade is the permanent entry point of the \"API as data\" upgrade\n// pattern (pattern G of the exploration; see ../../README.md).\n//\n// Patterns E and F put a Go interface at the permanent path, which fixes the\n// method set at deploy: adding an operation later needs a whole extra realm.\n// This one puts a single entry point there instead,\n//\n//\tCall(cur realm, verb, payload string) string\n//\n// and moves the API into DATA that each implementation declares. The signature\n// that can never change is that one line; everything the application does can\n// still grow.\n//\n// Three things fall out of the API being data, and they are the reason to pay\n// the price below:\n//\n//  1. Callers can ENUMERATE it. Verbs, Signature and SchemaText answer without\n//     a transaction, so a client discovers the API instead of being compiled\n//     against it.\n//  2. Payloads are CHECKED before the handler runs, so an arity mistake is one\n//     abort with a readable message rather than whatever the handler does with\n//     the wrong number of arguments.\n//  3. Upgrades can be DIFFED. Accept refuses a handler whose schema would drop\n//     or reshape a verb some existing caller depends on, which no amount of Go\n//     interface satisfaction can catch: a handler is free to satisfy Handler\n//     and answer nothing.\n//\n// The price is the type system. Arguments are strings a caller encodes, and a\n// misspelled verb is an abort at runtime rather than a compile error. Pattern F\n// is the other side of that trade and both ship here on purpose.\n//\n// State is deliberately out of scope. These handlers are pure; where an\n// application's data should live is pattern C's question, and the answer does\n// not change because the entry point became a string.\npackage facade\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst owner address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\" // @moul\n\nconst prefix = \"gno.land/r/moul/x/upgrade/schema/impl/\"\n\n// sep is the payload separator. A single byte, because the point here is the\n// shape of the boundary and not the encoding: a real one would need escaping,\n// and choosing it is a decision this pattern does not make for you.\nconst sep = \"|\"\n\n// Handler is the whole interface an implementation satisfies. It never changes,\n// because everything that would have changed it is in Schema instead.\ntype Handler interface {\n\t// Schema declares the API, one verb per line, \"name arg1 arg2\".\n\tSchema() string\n\t// Invoke runs a verb. The facade has already checked that the verb exists\n\t// and that args has exactly the declared arity.\n\tInvoke(verb string, args []string) string\n}\n\ntype verb struct {\n\tname   string\n\tparams []string\n}\n\nvar (\n\tOwnable = ownable.NewWithAddress(owner)\n\n\tcandidates = avl.NewTree() // pkgpath -\u003e Handler\n\tlive       Handler\n\tlivePath   string\n\tliveVerbs  = avl.NewTree() // verb name -\u003e *verb, for lookup\n\tliveOrder  []string        // the same verbs in DECLARATION order, for listing\n)\n\n// Propose nominates the calling realm, exactly as in pattern F. Its schema is\n// parsed here so a malformed one is rejected at proposal rather than at accept.\nfunc Propose(cur realm, h Handler) {\n\tcaller := cur.Previous().PkgPath()\n\tif !strings.HasPrefix(caller, prefix) {\n\t\tpanic(\"unauthorized: \" + caller + \" is not under \" + prefix)\n\t}\n\tif h == nil {\n\t\tpanic(\"handler must not be nil\")\n\t}\n\tparseSchema(h.Schema()) // panics if malformed\n\tcandidates.Set(caller, h)\n}\n\n// Accept promotes a candidate, and refuses one that would break an existing\n// caller. This is the check a Go interface cannot express.\nfunc Accept(cur realm, pkgPath string) {\n\th, next, order := resolve(cur, pkgPath)\n\tassertNoRegression(next)\n\tlive, livePath, liveVerbs, liveOrder = h, pkgPath, next, order\n}\n\n// AcceptBreaking promotes a candidate that Accept refuses.\n//\n// It exists because the diff is SYMMETRIC, which is not obvious until it bites:\n// once v1 has added a verb, rolling back to v0 drops that verb and is a\n// regression by exactly the same rule that protects callers going forward. A\n// pattern that can only move forward is worse than one with no diff at all, so\n// the escape hatch is required, and making it a separate function is the point:\n// the owner has to type a different word, and the audit log shows which one.\n//\n// Use it to roll back, and to retire a verb nobody calls any more. Not to make\n// an upgrade go through.\nfunc AcceptBreaking(cur realm, pkgPath string) {\n\th, next, order := resolve(cur, pkgPath)\n\tlive, livePath, liveVerbs, liveOrder = h, pkgPath, next, order\n}\n\n// resolve is the owner check and the lookup both accepts share.\nfunc resolve(cur realm, pkgPath string) (Handler, *avl.Tree, []string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tv := candidates.Get(pkgPath)\n\tif v == nil {\n\t\tpanic(\"no candidate at \" + pkgPath)\n\t}\n\th := v.(Handler)\n\tt, order := parseSchema(h.Schema())\n\treturn h, t, order\n}\n\n// assertNoRegression is the upgrade diff. A new schema may ADD verbs and may not\n// remove one or change its arity, because a caller compiled against the old one\n// is still out there calling it.\nfunc assertNoRegression(next *avl.Tree) {\n\t// Walk in DECLARATION order, not avl order, so the verb named in the abort\n\t// is the first one a reader of the live schema would reach. Iterating the\n\t// tree reports whichever violation happens to sort first, which makes the\n\t// message depend on a verb's spelling.\n\tfor _, name := range liveOrder {\n\t\told := liveVerbs.Get(name).(*verb)\n\t\tn := next.Get(name)\n\t\tif n == nil {\n\t\t\tpanic(\"schema regression: the candidate drops verb \" + name + \", which an existing caller may still call; AcceptBreaking overrides\")\n\t\t}\n\t\tif len(n.(*verb).params) != len(old.params) {\n\t\t\tpanic(\"schema regression: the candidate changes the arity of verb \" + name + \"; AcceptBreaking overrides\")\n\t\t}\n\t}\n}\n\n// Call is the one signature this realm is committed to forever.\nfunc Call(cur realm, verbName, payload string) string {\n\tassertLive()\n\tv := liveVerbs.Get(verbName)\n\tif v == nil {\n\t\tpanic(\"unknown verb \" + verbName + \", known: \" + strings.Join(Verbs(), \", \"))\n\t}\n\tspec := v.(*verb)\n\targs := []string{}\n\tif payload != \"\" {\n\t\targs = strings.Split(payload, sep)\n\t}\n\tif len(args) != len(spec.params) {\n\t\tpanic(ufmt.Sprintf(\"verb %s takes %d argument(s), got %d, signature is %s\",\n\t\t\tverbName, len(spec.params), len(args), Signature(verbName)))\n\t}\n\treturn live.Invoke(verbName, args)\n}\n\n// Verbs lists the accepted API in DECLARATION order, which is the order the\n// handler wrote it in and the order a reader of the schema expects. Iterating\n// the avl tree instead would list them alphabetically, silently: caught by a\n// test, not by a compiler.\nfunc Verbs() []string {\n\treturn liveOrder\n}\n\n// Signature is one verb's shape, as a caller would write it.\nfunc Signature(name string) string {\n\tv := liveVerbs.Get(name)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn name + \"(\" + strings.Join(v.(*verb).params, \", \") + \")\"\n}\n\n// SchemaText is the whole accepted API in the declaration format, so a client\n// can read back exactly what the handler declared.\nfunc SchemaText() string {\n\tout := \"\"\n\tfor _, n := range Verbs() {\n\t\tv := liveVerbs.Get(n).(*verb)\n\t\tout += n\n\t\tfor _, p := range v.params {\n\t\t\tout += \" \" + p\n\t\t}\n\t\tout += \"\\n\"\n\t}\n\treturn out\n}\n\n// Live is the package path currently serving, or \"\" before the first Accept.\nfunc Live() string {\n\treturn livePath\n}\n\n// Candidates lists every path that has nominated itself, in order.\nfunc Candidates() []string {\n\tout := []string{}\n\tcandidates.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tout = append(out, k)\n\t\treturn false\n\t})\n\treturn out\n}\n\nfunc assertLive() {\n\tif live == nil {\n\t\tpanic(\"no handler accepted\")\n\t}\n}\n\n// parseSchema turns the declaration text into verbs, and is the only validation\n// of a name that Render later echoes.\nfunc parseSchema(text string) (*avl.Tree, []string) {\n\tt := avl.NewTree()\n\torder := []string{}\n\tfor _, line := range strings.Split(text, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfields := strings.Split(line, \" \")\n\t\tname := fields[0]\n\t\tassertIdent(name)\n\t\tparams := []string{}\n\t\tfor _, f := range fields[1:] {\n\t\t\tif f == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tassertIdent(f)\n\t\t\tparams = append(params, f)\n\t\t}\n\t\tif t.Get(name) != nil {\n\t\t\tpanic(\"malformed schema: verb \" + name + \" declared twice\")\n\t\t}\n\t\tt.Set(name, \u0026verb{name: name, params: params})\n\t\torder = append(order, name)\n\t}\n\tif t.Size() == 0 {\n\t\tpanic(\"malformed schema: no verbs declared\")\n\t}\n\treturn t, order\n}\n\nfunc assertIdent(s string) {\n\tif s == \"\" {\n\t\tpanic(\"malformed schema: empty name\")\n\t}\n\tfor _, c := range s {\n\t\tif !(c \u003e= 'a' \u0026\u0026 c \u003c= 'z') \u0026\u0026 !(c \u003e= '0' \u0026\u0026 c \u003c= '9') \u0026\u0026 c != '_' {\n\t\t\tpanic(\"malformed schema: \" + s + \" is not [a-z0-9_]\")\n\t\t}\n\t}\n}\n\nfunc Render(_ string) string {\n\tif live == nil {\n\t\treturn ufmt.Sprintf(\"schema/facade/v0: no handler accepted (%d candidate(s))\\n\", candidates.Size())\n\t}\n\tout := ufmt.Sprintf(\"schema/facade/v0: %s\\n\", livePath)\n\tfor _, n := range Verbs() {\n\t\tout += \"- \" + Signature(n) + \"\\n\"\n\t}\n\treturn out\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/schema/facade/v0\"\ngno = \"0.9\"\n# public: every implementation realm imports it to declare its schema and register\n"},{"name":"render_example_test.gno","body":"package facade\n\n// ExampleRender pins the facade before any handler realm exists. Nothing is\n// imported here, so there is no candidate and nothing accepted.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// schema/facade/v0: no handler accepted (0 candidate(s))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"facade","path":"gno.land/r/moul/x/upgrade/selfreg/facade/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/selfreg/facade/v0`\n\nThe **permanent facade** of pattern E. Holds an `Impl` interface value and\nforwards to it. Implementations register themselves from their own `init`, gated\non an explicit path prefix (`nestedpkg` does not fit version-last paths).\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/selfreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/facade/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/selfreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/facade/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/selfreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/facade/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/selfreg/facade/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/facade/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/selfreg/facade/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/selfreg/facade/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"facade.gno","body":"// Package facade is the permanent entry point of the \"self-registering\n// implementation\" upgrade pattern (pattern E of the exploration; see\n// ../../README.md).\n//\n// The path callers import never changes and holds no business logic: it holds\n// an interface value. A new implementation realm takes over simply by being\n// deployed, because it registers itself from its own init. Nobody has to send\n// a transaction to switch, which is the pattern's whole appeal and also its\n// whole risk: whoever can deploy under the guarded prefix can take the realm.\npackage facade\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Impl is the contract an implementation realm must satisfy. This interface is\n// the one thing here that can never change: it is compiled into every caller.\ntype Impl interface {\n\tGreet(name string) string\n\tVersion() string\n}\n\n// prefix is the only gate. An implementation must live under it.\n//\n// gno ships p/nt/nestedpkg/v0 for exactly this check, but its AssertCallerIsSubPath\n// wants the implementation nested UNDER the facade's own path, and with the\n// version segment last (facade/v0, impl/v0) no sibling is a sub-path of another.\n// IsSameNamespace is the other shipped option and is far too loose: it would let\n// any realm in the whole namespace seize this one. Hence an explicit prefix.\nconst prefix = \"gno.land/r/moul/x/upgrade/selfreg/impl/\"\n\n// The stage ladder. Sui gates package upgrades with an UpgradeCap whose policy\n// runs compatible, additive, dependency-only, immutable, and the rule that makes\n// it worth copying is that a policy can only ever become MORE restrictive.\n// CosmWasm and Solana land on the same primitive from different directions: a\n// contract with no admin, a program whose upgrade authority is None. All three\n// say the same thing, that the way out of \"you are trusting the owner rather\n// than the code\" is an authority you can drop, permanently.\n//\n// This pattern has no owner, so its ladder has two rungs rather than four: the\n// only actor the facade already trusts is whichever implementation is live.\nconst (\n\tStageOpen   = 0 // any realm under the prefix takes over by deploying\n\tStageSealed = 1 // nothing may register again, the live implementation is final\n)\n\nvar (\n\tlive     Impl\n\tlivePath string\n\tstage    = StageOpen\n)\n\n// Register makes the calling realm the live implementation. Called from the\n// implementation's own init, so deploying IS the upgrade.\nfunc Register(cur realm, impl Impl) {\n\tif stage != StageOpen {\n\t\tpanic(\"selfreg/facade/v0 is sealed, \" + livePath + \" is final\")\n\t}\n\tcaller := cur.Previous().PkgPath()\n\tif !strings.HasPrefix(caller, prefix) {\n\t\tpanic(\"unauthorized: \" + caller + \" is not under \" + prefix)\n\t}\n\tif impl == nil {\n\t\tpanic(\"implementation must not be nil\")\n\t}\n\tlive, livePath = impl, caller\n}\n\n// Seal ends this realm's upgradeability, forever. Callable only by the\n// implementation currently serving, because with no owner that is the only\n// actor the facade already trusts. It grants nothing new: whoever could deploy\n// under the prefix could already take the realm over, and this only lets them\n// make that the last word.\n//\n// One-way, and there is no rung above it.\nfunc Seal(cur realm) {\n\tcaller := cur.Previous().PkgPath()\n\tif livePath == \"\" || caller != livePath {\n\t\tpanic(\"unauthorized: only the live implementation may seal, and that is \" + livePath)\n\t}\n\tstage = StageSealed\n}\n\n// Stage is the rung this realm is on. It only ever goes up.\nfunc Stage() int {\n\treturn stage\n}\n\n// StageName is Stage as the word a caller reads in Render.\nfunc StageName() string {\n\tif stage == StageSealed {\n\t\treturn \"sealed\"\n\t}\n\treturn \"open\"\n}\n\n// Live is the package path currently serving, or \"\" before the first deploy.\nfunc Live() string {\n\treturn livePath\n}\n\n// Greet forwards to the live implementation.\nfunc Greet(name string) string {\n\tassertLive()\n\treturn live.Greet(name)\n}\n\n// Version reports the live implementation's own version string.\nfunc Version() string {\n\tassertLive()\n\treturn live.Version()\n}\n\nfunc assertLive() {\n\tif live == nil {\n\t\tpanic(\"no implementation registered\")\n\t}\n}\n\nfunc Render(_ string) string {\n\tif live == nil {\n\t\treturn ufmt.Sprintf(\"selfreg/facade/v0 [%s]: no implementation registered\\n\", StageName())\n\t}\n\treturn ufmt.Sprintf(\"selfreg/facade/v0 [%s]: %s (%s)\\n%s\\n\", StageName(), live.Version(), livePath, live.Greet(\"world\"))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/selfreg/facade/v0\"\ngno = \"0.9\"\n# public: every implementation realm imports it to register itself from init\n"},{"name":"render_example_test.gno","body":"package facade\n\n// ExampleRender pins what the facade renders before anything has registered.\n// No implementation realm is imported here, so the facade stands alone.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// selfreg/facade/v0 [open]: no implementation registered\n}\n"},{"name":"z_outsider_filetest.gno","body":"// PKGPATH: gno.land/r/moul/main\npackage main\n\nimport \"gno.land/r/moul/x/upgrade/selfreg/facade/v0\"\n\n// A realm outside the guarded prefix cannot seize the facade. The path is read\n// off the crossing frame, so there is no argument to lie about.\nfunc main(cur realm) {\n\tfacade.Register(cross(cur), nil)\n}\n\n// Error:\n// unauthorized: gno.land/r/moul/main is not under gno.land/r/moul/x/upgrade/selfreg/impl/\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"root","path":"gno.land/r/moul/x/upgrade/store/root/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/store/root/v0`\n\nThe **data realm** of pattern C. Holds the counter and grants write access to\nexactly one logic realm at a time, identified by the package path read off the\ncrossing frame. `SetLive(path)` is the upgrade.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/store/root/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/root/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/store/root/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/root/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/store/root/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/root/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/store/root/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/root/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/store/root/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/store/root/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/store/root/v0\"\ngno = \"0.9\"\n# public: every logic realm in this pattern imports it; it is the shared store\n"},{"name":"render_example_test.gno","body":"package root\n\n// ExampleRender pins the render of a freshly deployed data realm.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// store/root/v0: 0 (live logic: gno.land/r/moul/x/upgrade/store/logic/v0)\n}\n"},{"name":"root.gno","body":"// untrusted-render: live is the only stored string Render echoes, and SetLive\n// validates it with assertPkgPath before storing it.\n//\n// Package root is the data realm of the \"state realm + swappable logic\" upgrade\n// pattern (pattern C of the exploration; see ../../README.md).\n//\n// root holds the state and nothing else worth changing. It grants write access\n// to exactly one logic realm at a time, identified by package path off the\n// crossing frame rather than passed in as an argument, so a logic realm cannot\n// claim to be a path it does not occupy. Upgrading is a single SetLive call:\n// no migration, no downtime, and the data never moves.\npackage root\n\nimport (\n\t\"strings\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nconst owner address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\" // @moul\n\nvar (\n\tOwnable = ownable.NewWithAddress(owner)\n\n\tcounter int\n\tlive    = \"gno.land/r/moul/x/upgrade/store/logic/v0\"\n)\n\n// Inc adds n to the stored counter. Only the live logic realm may call it.\nfunc Inc(cur realm, n int) int {\n\tassertCallerIsLive(cur)\n\tcounter += n\n\treturn counter\n}\n\n// Get is open to everyone: the data is public, only writes are gated.\nfunc Get() int {\n\treturn counter\n}\n\n// Live is the package path currently allowed to write.\nfunc Live() string {\n\treturn live\n}\n\n// SetLive hands write access to another logic realm. This is the upgrade.\nfunc SetLive(cur realm, pkgPath string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tassertPkgPath(pkgPath)\n\tlive = pkgPath\n}\n\nfunc assertCallerIsLive(cur realm) {\n\tcaller := cur.Previous().PkgPath()\n\tif caller != live {\n\t\tpanic(\"unauthorized: \" + caller + \" is not the live logic realm (\" + live + \")\")\n\t}\n}\n\nfunc Render(_ string) string {\n\treturn ufmt.Sprintf(\"store/root/v0: %d (live logic: %s)\\n\", counter, live)\n}\n\n// assertPkgPath rejects anything that is not a gno.land realm path.\n//\n// It exists for Render, not for correctness of the upgrade: the stored path is\n// echoed into markdown, so validating it at write time is what lets Render\n// print it raw. ui.Inline would escape the dots in \"gno.land\" and turn the one\n// string a reader needs to copy into \"gno\\.land\".\nfunc assertPkgPath(p string) {\n\tif !strings.HasPrefix(p, \"gno.land/r/\") {\n\t\tpanic(\"not a realm path: \" + p)\n\t}\n\tfor _, c := range p {\n\t\tok := c == '/' || c == '.' || c == '_' || c == '-' ||\n\t\t\t(c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9')\n\t\tif !ok {\n\t\t\tpanic(\"illegal character in realm path\")\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wrap","path":"gno.land/r/moul/x/upgrade/wrap/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/wrap/v0`\n\nVersion 0 of the **wrapping versions** upgrade pattern (pattern A). A plain\ncounter that knows nothing about any successor and stays writable forever.\n\nSee [the pattern](../README.md) and [the exploration](../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/wrap/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/wrap/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/wrap/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/wrap/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/wrap/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/wrap/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/wrap/v0\"\ngno = \"0.9\"\n# public: imported by .../wrap/v1, which reads its counter; that import IS the pattern\n"},{"name":"render_example_test.gno","body":"package wrap\n\n// ExampleRender pins the render of a freshly deployed v0.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// wrap/v0: 0\n}\n"},{"name":"wrap.gno","body":"// Package wrap is version 0 of the \"wrapping versions\" upgrade pattern\n// (pattern A of the exploration; see ../README.md).\n//\n// Nothing here knows that a successor exists. v0 keeps its own counter and\n// stays writable forever: callers pinned to this path keep working, and keep\n// diverging from whatever the newer version reports.\npackage wrap\n\nimport \"gno.land/p/nt/ufmt/v0\"\n\nvar counter int\n\n// Inc adds n to this version's own counter.\nfunc Inc(cur realm, n int) {\n\tcounter += n\n}\n\n// Get returns this version's counter. Non-crossing on purpose: a successor\n// reads it without entering this realm as a writer.\nfunc Get() int {\n\treturn counter\n}\n\nfunc Render(_ string) string {\n\treturn ufmt.Sprintf(\"wrap/v0: %d\\n\", counter)\n}\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"197664200","gas_fee":"592992ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"6JiRhFoKpzhnv76kitMbk0W4Vyz1aWvQ3xgyrIDlMjdomMVdTVygR3bN+SQ3NE5fgp8qAbLeG/dI3Aw8F80AMw=="}],"memo":""},"metadata":{"timestamp":"1790961697"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"impl","path":"gno.land/r/moul/x/upgrade/adminreg/impl/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/adminreg/impl/v0`\n\nVersion 0 of the **implementation realm** of pattern F. Nominates itself with\n[the facade](../../facade) from `init`, and serves nothing until the owner\naccepts its path.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/adminreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/adminreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/adminreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/adminreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/adminreg/impl/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/adminreg/impl/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/adminreg/impl/v0\"\ngno = \"0.9\"\n# public: hands its own greeter to the facade; private aborts with \"cannot persist object from the private realm\"\n"},{"name":"impl.gno","body":"// Package impl is version 0 of the implementation realm of the \"propose and\n// accept\" upgrade pattern (pattern F; see ../../README.md).\n//\n// Deploying it only nominates it. It serves nothing until the facade's owner\n// accepts this path.\npackage impl\n\nimport (\n\tfacade \"gno.land/r/moul/x/upgrade/adminreg/facade/v0\"\n)\n\ntype greeter struct{}\n\nfunc (greeter) Greet(name string) string { return \"hello, \" + name }\nfunc (greeter) Version() string          { return \"impl/v0\" }\n\n// Instance exposes the singleton.\nfunc Instance() facade.Impl { return greeter{} }\n\nfunc init(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n\n// Propose re-nominates this implementation. init does it at deploy; exposing it\n// as a transaction lets a candidate be restored without redeploying.\nfunc Propose(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n\n// Path is this realm's own package path, the string the facade owner accepts.\nconst Path = \"gno.land/r/moul/x/upgrade/adminreg/impl/v0\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"impl","path":"gno.land/r/moul/x/upgrade/adminreg/impl/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/adminreg/impl/v1`\n\nVersion 1 of the **implementation realm** of pattern F. Same as [`v0`](../gen0),\ndifferent behaviour, and equally inert until accepted.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/adminreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/adminreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/adminreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/adminreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/adminreg/impl/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/adminreg/impl/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/adminreg/impl/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/adminreg/impl/v1\"\ngno = \"0.9\"\n# public: hands its own greeter to the facade; private aborts with \"cannot persist object from the private realm\"\n"},{"name":"impl.gno","body":"// Package impl is version 1 of the implementation realm of the \"propose and\n// accept\" upgrade pattern (pattern F; see ../../README.md).\n//\n// Deploying it only nominates it. It serves nothing until the facade owner\n// accepts this path.\npackage impl\n\nimport (\n\tfacade \"gno.land/r/moul/x/upgrade/adminreg/facade/v0\"\n)\n\ntype greeter struct{}\n\nfunc (greeter) Greet(name string) string { return \"HELLO, \" + name + \"!\" }\nfunc (greeter) Version() string          { return \"impl/v1\" }\n\n// Instance exposes the singleton.\nfunc Instance() facade.Impl { return greeter{} }\n\nfunc init(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n\n// Propose re-nominates this implementation. init does it at deploy; exposing it\n// as a transaction lets a candidate be restored without redeploying.\nfunc Propose(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n\n// Path is this realm's own package path, the string the facade owner accepts.\nconst Path = \"gno.land/r/moul/x/upgrade/adminreg/impl/v1\"\n"},{"name":"impl_test.gno","body":"package impl\n\nimport (\n\t\"testing\"\n\n\tfacade \"gno.land/r/moul/x/upgrade/adminreg/facade/v0\"\n\timplv0 \"gno.land/r/moul/x/upgrade/adminreg/impl/v0\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestProposeThenAccept checks the two-step shape: deploying nominates, and\n// only an owner transaction naming a path promotes it.\n//\n// Both impl realms are imported here, so both have already nominated themselves\n// by the time this runs, and neither is serving.\nfunc TestProposeThenAccept(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(facade.Ownable.Owner()))\n\n\tuassert.Equal(t, 2, len(facade.Candidates()), \"both versions nominated themselves\")\n\tuassert.Equal(t, \"\", facade.Live(), \"nominating is not serving\")\n\tuassert.AbortsContains(t, cur, \"no implementation accepted\", func() {\n\t\tfacade.Greet(\"world\")\n\t})\n\n\t// Accepting names a path, not an object: this is a plain maketx call.\n\tfacade.Accept(cross(cur), \"gno.land/r/moul/x/upgrade/adminreg/impl/v0\")\n\tuassert.Equal(t, \"impl/v0\", facade.Version())\n\tuassert.Equal(t, \"hello, world\", facade.Greet(\"world\"))\n\n\t// The upgrade, and the rollback, are the same single call.\n\tfacade.Accept(cross(cur), \"gno.land/r/moul/x/upgrade/adminreg/impl/v1\")\n\tuassert.Equal(t, \"HELLO, world!\", facade.Greet(\"world\"))\n\tfacade.Accept(cross(cur), implv0.Path)\n\tuassert.Equal(t, \"hello, world\", facade.Greet(\"world\"))\n\tfacade.Accept(cross(cur), Path)\n\n\t// A path nobody nominated cannot be accepted, however owned you are.\n\tuassert.AbortsContains(t, cur, \"no candidate at\", func() {\n\t\tfacade.Accept(cross(cur), \"gno.land/r/moul/x/upgrade/adminreg/impl/v9\")\n\t})\n\n\t// A non-owner cannot accept even a legitimate candidate.\n\ttesting.SetRealm(testing.NewUserRealm(\"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\"))\n\tuassert.AbortsContains(t, cur, \"caller is not owner\", func() {\n\t\tfacade.Accept(cross(cur), implv0.Path)\n\t})\n\n\tuassert.Equal(t, \"adminreg/facade/v0 [open]\\n\"+\n\t\t\"live: impl/v1 (gno.land/r/moul/x/upgrade/adminreg/impl/v1)\\n\"+\n\t\t\"HELLO, world!\\n\"+\n\t\t\"candidates: 2\\n\"+\n\t\t\"- gno.land/r/moul/x/upgrade/adminreg/impl/v0\\n\"+\n\t\t\"- gno.land/r/moul/x/upgrade/adminreg/impl/v1\\n\", facade.Render(\"\"))\n}\n\n// TestDispatchCost100 does 100 dispatches through this pattern's entry point,\n// so `gno test -print-runtime-metrics` prints a cycle count for a known\n// workload. Its twin is TestDispatchCost100 in schema/impl/gen1.\n//\nfunc TestDispatchCost100(cur realm, t *testing.T) {\n\t// Runs after TestProposeThenAccept, which leaves v1 live, and before\n\t// TestLadder, which freezes. Reads only, so it disturbs neither.\n\tfor i := 0; i \u003c 100; i++ {\n\t\tfacade.Greet(\"world\")\n\t}\n\tuassert.Equal(t, \"HELLO, world!\", facade.Greet(\"world\"))\n}\n\n// TestLadder walks the three rungs and checks the ratchet refuses to loosen.\n//\n// Runs after TestProposeThenAccept on purpose: every rung is one-way, so the\n// tests that need to propose and accept freely must already have run.\nfunc TestLadder(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(facade.Ownable.Owner()))\n\tuassert.Equal(t, facade.StageOpen, facade.Stage())\n\n\t// Rung 2: no new code, but rolling back among what exists still works.\n\tfacade.Close(cross(cur))\n\tuassert.Equal(t, facade.StageClosed, facade.Stage())\n\tuassert.AbortsContains(t, cur, \"no new candidate may be proposed\", func() {\n\t\tPropose(cross(cur))\n\t})\n\tfacade.Accept(cross(cur), implv0.Path)\n\tuassert.Equal(t, \"hello, world\", facade.Greet(\"world\"), \"rollback survives Close\")\n\tfacade.Accept(cross(cur), Path)\n\n\t// The ratchet only turns one way, even for the owner.\n\tuassert.AbortsContains(t, cur, \"only tightens\", func() {\n\t\tfacade.Close(cross(cur))\n\t})\n\n\t// Rung 3: nothing is accepted again.\n\tfacade.Freeze(cross(cur))\n\tuassert.Equal(t, facade.StageFrozen, facade.Stage())\n\tuassert.AbortsContains(t, cur, \"is frozen\", func() {\n\t\tfacade.Accept(cross(cur), implv0.Path)\n\t})\n\tuassert.AbortsContains(t, cur, \"only tightens\", func() {\n\t\tfacade.Freeze(cross(cur))\n\t})\n\n\t// What was live stays live, and the render says which rung it is on.\n\tuassert.Equal(t, \"HELLO, world!\", facade.Greet(\"world\"))\n\tuassert.Equal(t, \"adminreg/facade/v0 [frozen]\\n\"+\n\t\t\"live: impl/v1 (gno.land/r/moul/x/upgrade/adminreg/impl/v1)\\n\"+\n\t\t\"HELLO, world!\\n\"+\n\t\t\"candidates: 2\\n\"+\n\t\t\"- gno.land/r/moul/x/upgrade/adminreg/impl/v0\\n\"+\n\t\t\"- gno.land/r/moul/x/upgrade/adminreg/impl/v1\\n\", facade.Render(\"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lazy","path":"gno.land/r/moul/x/upgrade/lazy/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/lazy/v1`\n\nVersion 1 of the **lazy migration** pattern (pattern D). Declares a new record\nshape and converts each [`v0`](../gen0) record on first touch.\n\nMigrating writes, and writing means crossing, so `Get(cur, key)` is a\ntransaction and is invisible to `vm/qeval` and to `Render`. `Peek(key)` is the\nfree read-only half: same value, no migration.\n\nSee [the pattern](../README.md) and [the exploration](../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/lazy/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/lazy/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/lazy/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/lazy/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lazy/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/lazy/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/lazy/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/lazy/v1\"\ngno = \"0.9\"\n# public: the next layout change must be able to read these records to migrate them\n"},{"name":"lazy.gno","body":"// untrusted-render: records are seeded in init or derived from lazy/v0's own\n// init; this realm exposes no setter, so no caller string ever reaches Render.\n//\n// Package lazy is version 1 of the \"lazy migration\" upgrade pattern\n// (pattern D of the exploration; see ../README.md).\n//\n// v1 changes the stored shape (Score widens, Active is new) and migrates one\n// record at a time, on first touch, paid for by whoever touched it. There is\n// no migration transaction and no pause.\n//\n// The catch on today's gno: migrating on read MUTATES, so the read path has to\n// be a crossing function. Get therefore costs a transaction and is invisible to\n// vm/qeval and to Render. Peek is the honest read-only half, and it reports the\n// pre-migration answer for records that have not been touched yet.\npackage lazy\n\nimport (\n\tv0 \"gno.land/r/moul/x/upgrade/lazy/v0\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Record is v1's shape: Score widened to int64 and scaled by 1000, plus a new\n// Active flag that migrated records get set to true.\ntype Record struct {\n\tName   string\n\tScore  int64\n\tActive bool\n}\n\nfunc (r *Record) String() string {\n\tif r == nil {\n\t\treturn \"nil\"\n\t}\n\treturn ufmt.Sprintf(\"v1{%s %d %t}\", r.Name, r.Score, r.Active)\n}\n\nvar records = avl.NewTree()\n\nfunc init() {\n\trecords.Set(\"cyd\", \u0026Record{Name: \"cyd\", Score: 3000, Active: true})\n}\n\n// migrate converts a v0 record into a v1 one. Kept separate from Get so the\n// conversion is testable without a write.\nfunc migrate(old *v0.Record) *Record {\n\treturn \u0026Record{\n\t\tName:   old.Name + \"-migrated\",\n\t\tScore:  int64(old.Score) * 1000,\n\t\tActive: true,\n\t}\n}\n\n// Get returns a record, migrating it from v0 on first touch.\n//\n// Crossing, because the migration writes. That is the cost of the pattern: the\n// cheapest possible read is now a transaction.\nfunc Get(cur realm, key string) *Record {\n\tif v := records.Get(key); v != nil {\n\t\treturn v.(*Record)\n\t}\n\told := v0.Get(key)\n\tif old == nil {\n\t\treturn nil\n\t}\n\tr := migrate(old)\n\trecords.Set(key, r)\n\treturn r\n}\n\n// Peek is the read-only half: it never migrates, so a record that has not been\n// touched yet reads as its v0 self converted on the fly and NOT stored.\nfunc Peek(key string) *Record {\n\tif v := records.Get(key); v != nil {\n\t\treturn v.(*Record)\n\t}\n\tif old := v0.Get(key); old != nil {\n\t\treturn migrate(old)\n\t}\n\treturn nil\n}\n\n// Migrated is how many records have actually moved over.\nfunc Migrated() int {\n\treturn records.Size()\n}\n\n// Pending is how many v0 records have never been touched. It is only a bound:\n// v0 keeps every record it ever had, migrated or not.\nfunc Pending() int {\n\tn := 0\n\tfor _, k := range []string{\"ada\", \"bob\"} {\n\t\tif records.Get(k) == nil \u0026\u0026 v0.Get(k) != nil {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\nfunc Render(_ string) string {\n\tout := ufmt.Sprintf(\"lazy/v1: %d migrated, %d pending in v0\\n\", Migrated(), Pending())\n\trecords.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tout += ufmt.Sprintf(\"- %s: %s\\n\", k, v.(*Record).String())\n\t\treturn false\n\t})\n\treturn out\n}\n"},{"name":"lazy_test.gno","body":"package lazy\n\nimport (\n\t\"testing\"\n\n\tv0 \"gno.land/r/moul/x/upgrade/lazy/v0\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestLazyMigration walks a record from v0 into v1 on first touch and checks\n// what the two halves of the read path report on either side of it.\nfunc TestLazyMigration(cur realm, t *testing.T) {\n\tuassert.Equal(t, 1, Migrated(), \"only v1's own seed has moved\")\n\tuassert.Equal(t, 2, Pending(), \"both v0 records are untouched\")\n\n\t// Peek converts without storing: the answer is right, the state is not moved.\n\tuassert.Equal(t, \"v1{ada-migrated 1000 true}\", Peek(\"ada\").String())\n\tuassert.Equal(t, 1, Migrated(), \"Peek must not migrate\")\n\n\t// Get migrates.\n\tuassert.Equal(t, \"v1{ada-migrated 1000 true}\", Get(cross(cur), \"ada\").String())\n\tuassert.Equal(t, 2, Migrated(), \"ada has moved over\")\n\tuassert.Equal(t, 1, Pending())\n\n\t// Migrating COPIES: v0 still holds (and still pays for) the original.\n\tuassert.Equal(t, 2, v0.Size(), \"v0 never shrinks\")\n\tuassert.Equal(t, \"v0{ada 1}\", v0.Get(\"ada\").String())\n\n\t// A second Get is a plain hit, not a second migration.\n\tuassert.Equal(t, \"v1{ada-migrated 1000 true}\", Get(cross(cur), \"ada\").String())\n\tuassert.Equal(t, 2, Migrated())\n\n\t// A key in neither version is nil in both halves.\n\tuassert.True(t, Get(cross(cur), \"zoe\") == nil)\n\tuassert.True(t, Peek(\"zoe\") == nil)\n\n\t// v1's own records are untouched by any of this.\n\tuassert.Equal(t, \"v1{cyd 3000 true}\", Get(cross(cur), \"cyd\").String())\n\n\tuassert.Equal(t, \"lazy/v1: 2 migrated, 1 pending in v0\\n\"+\n\t\t\"- ada: v1{ada-migrated 1000 true}\\n\"+\n\t\t\"- cyd: v1{cyd 3000 true}\\n\", Render(\"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"lock","path":"gno.land/r/moul/x/upgrade/lock/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/lock/v1`\n\nVersion 1 of the **retire the predecessor** upgrade pattern (pattern B).\nRefuses every write until [`v0`](../gen0) has been retired onto it, then folds\nv0's frozen total into its own. At most one version is writable at any height,\nso there is a single authoritative answer.\n\nSee [the pattern](../README.md) and [the exploration](../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/lock/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/lock/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/lock/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/lock/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/lock/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/lock/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/lock/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/lock/v1\"\ngno = \"0.9\"\n# public: its successor must import it to read the total it will freeze\n"},{"name":"lock.gno","body":"// Package lock is version 1 of the \"retire the predecessor\" upgrade pattern\n// (pattern B of the exploration; see ../README.md).\n//\n// v1 refuses every write until v0 has been retired. That is the whole point:\n// at most one version is writable at any height, so v1 can safely fold v0's\n// frozen total into its own and report a single authoritative number, the\n// thing pattern A cannot do.\npackage lock\n\nimport (\n\tv0 \"gno.land/r/moul/x/upgrade/lock/v0\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Predecessor is the version this one supersedes.\nconst Predecessor = \"gno.land/r/moul/x/upgrade/lock/v0\"\n\nvar counter int\n\n// Inc adds n once the predecessor is frozen.\nfunc Inc(cur realm, n int) {\n\tassertPredecessorRetired()\n\tcounter += n\n}\n\n// Get returns the predecessor's frozen total plus this version's own.\nfunc Get() int {\n\treturn v0.Get() + counter\n}\n\n// Live reports whether the handover has happened.\nfunc Live() bool {\n\treturn v0.Successor() == \"gno.land/r/moul/x/upgrade/lock/v1\"\n}\n\nfunc assertPredecessorRetired() {\n\tif !Live() {\n\t\tpanic(\"lock/v1 is not live yet, \" + Predecessor + \" must be retired onto it first\")\n\t}\n}\n\nfunc Render(_ string) string {\n\tif !Live() {\n\t\treturn ufmt.Sprintf(\"lock/v1: waiting for %s to retire\\n\", Predecessor)\n\t}\n\treturn ufmt.Sprintf(\"lock/v1: %d (own %d + retired v0 %d)\\n\", Get(), counter, v0.Get())\n}\n"},{"name":"lock_test.gno","body":"package lock\n\nimport (\n\t\"testing\"\n\n\tv0 \"gno.land/r/moul/x/upgrade/lock/v0\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestHandover walks the whole one-writer-at-a-time sequence in order: only v0\n// writes, then the retirement flips it, then only v1 writes.\nfunc TestHandover(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(v0.Ownable.Owner()))\n\n\t// Before the handover: v0 writes, v1 refuses.\n\tv0.Inc(cross(cur), 10)\n\tuassert.False(t, Live(), \"v1 must not be live before the handover\")\n\tuassert.AbortsContains(t, cur, \"not live yet\", func() {\n\t\tInc(cross(cur), 1)\n\t})\n\tuassert.Equal(t, 10, Get(), \"v1 already reports v0's running total\")\n\n\t// The handover itself.\n\tv0.Retire(cross(cur), \"gno.land/r/moul/x/upgrade/lock/v1\")\n\tuassert.True(t, Live(), \"v1 must be live once v0 names it\")\n\n\t// After: v0 refuses, v1 writes, the total is single-valued.\n\tuassert.AbortsContains(t, cur, \"is retired\", func() {\n\t\tv0.Inc(cross(cur), 1)\n\t})\n\tInc(cross(cur), 100)\n\tuassert.Equal(t, 110, Get(), \"v1 folds v0's frozen total into its own\")\n\tuassert.Equal(t, 10, v0.Get(), \"v0's total is frozen where it stopped\")\n\n\t// Retirement is one-way.\n\tuassert.AbortsContains(t, cur, \"already retired\", func() {\n\t\tv0.Retire(cross(cur), \"gno.land/r/moul/x/upgrade/lock/v2\")\n\t})\n\n\tuassert.Equal(t, \"lock/v1: 110 (own 100 + retired v0 10)\\n\", Render(\"\"))\n\tuassert.Equal(t, \"lock/v0: 10 (retired, use gno.land/r/moul/x/upgrade/lock/v1)\\n\", v0.Render(\"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bad","path":"gno.land/r/moul/x/upgrade/schema/impl/bad/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/schema/impl/bad/v0`\n\nThe handler that **exists to be refused**. It satisfies `facade.Handler` exactly as\nwell as the others do, and drops a verb and reshapes another, which only a schema diff\ncan see. Nothing in gnos type system can.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/schema/impl/bad/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/bad/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/schema/impl/bad/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/bad/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/schema/impl/bad/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/bad/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/schema/impl/bad/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/bad/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/schema/impl/bad/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/schema/impl/bad/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bad.gno","body":"// Package bad is the handler realm that exists to be refused (pattern G; see\n// ../../README.md).\n//\n// It satisfies facade.Handler exactly as well as the others do: same methods,\n// same signatures, compiles and proposes itself without complaint. What it does\n// is drop the \"upper\" verb and change \"repeat\" to take one argument instead of\n// two, both of which break a caller already compiled against v0.\n//\n// Nothing in gno's type system can see that. A Go interface says what methods\n// exist, not which verbs the data behind them still answers, which is the whole\n// argument for declaring the API as data and diffing it at accept time.\npackage bad\n\nimport (\n\tfacade \"gno.land/r/moul/x/upgrade/schema/facade/v0\"\n)\n\n// schema drops \"upper\" entirely and gives \"repeat\" the wrong arity.\nconst schema = `repeat s`\n\ntype handler struct{}\n\nfunc (handler) Schema() string { return schema }\n\nfunc (handler) Invoke(verb string, args []string) string {\n\treturn \"this handler never gets to run\"\n}\n\n// Instance exposes the singleton.\nfunc Instance() facade.Handler { return handler{} }\n\n// Path is this realm's own package path.\nconst Path = \"gno.land/r/moul/x/upgrade/schema/impl/bad/v0\"\n\nfunc init(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/schema/impl/bad/v0\"\ngno = \"0.9\"\n# public: hands its own handler to the facade; private aborts with \"cannot persist object from the private realm\"\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"impl","path":"gno.land/r/moul/x/upgrade/schema/impl/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/schema/impl/v0`\n\nVersion 0 of the **handler realm** of pattern G. Two verbs, `upper` and `repeat`,\ndeclared as text rather than as a method set.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/schema/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/schema/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/schema/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/schema/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/schema/impl/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/schema/impl/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/schema/impl/v0\"\ngno = \"0.9\"\n# public: hands its own handler to the facade; private aborts with \"cannot persist object from the private realm\"\n"},{"name":"impl.gno","body":"// Package impl is version 0 of the handler realm of the \"API as data\" upgrade\n// pattern (pattern G; see ../../README.md).\n//\n// Two verbs, declared as text rather than as a method set. Deploying nominates\n// it; the facade owner accepts it by path.\npackage impl\n\nimport (\n\t\"strings\"\n\n\tfacade \"gno.land/r/moul/x/upgrade/schema/facade/v0\"\n)\n\n// schema is this version's whole API. One verb per line, name then parameters.\nconst schema = `upper s\nrepeat s n`\n\ntype handler struct{}\n\nfunc (handler) Schema() string { return schema }\n\nfunc (handler) Invoke(verb string, args []string) string {\n\tswitch verb {\n\tcase \"upper\":\n\t\treturn strings.ToUpper(args[0])\n\tcase \"repeat\":\n\t\treturn strings.Repeat(args[0], atoi(args[1]))\n\t}\n\t// Unreachable: the facade checked the verb against this schema first.\n\tpanic(\"unknown verb \" + verb)\n}\n\n// atoi is hand-rolled to keep the failure message about the ARGUMENT rather\n// than about strconv, which is the whole difference a typed boundary would have\n// made here.\nfunc atoi(s string) int {\n\tif s == \"\" {\n\t\tpanic(\"expected a number, got an empty argument\")\n\t}\n\tn := 0\n\tfor _, c := range s {\n\t\tif c \u003c '0' || c \u003e '9' {\n\t\t\tpanic(\"expected a number, got \" + s)\n\t\t}\n\t\tn = n*10 + int(c-'0')\n\t\tif n \u003e 64 {\n\t\t\tpanic(\"refusing to repeat more than 64 times\")\n\t\t}\n\t}\n\treturn n\n}\n\n// Instance exposes the singleton.\nfunc Instance() facade.Handler { return handler{} }\n\n// Path is this realm's own package path, the string the facade owner accepts.\nconst Path = \"gno.land/r/moul/x/upgrade/schema/impl/v0\"\n\nfunc init(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n\n// Propose re-nominates this handler, so a rollback needs no redeploy.\nfunc Propose(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"impl","path":"gno.land/r/moul/x/upgrade/schema/impl/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/schema/impl/v1`\n\nVersion 1 of the **handler realm** of pattern G. Adds `surround` and keeps both of\n[`v0`](../gen0)s verbs untouched, which is what lets the facade accept it: growing\nthe API costs no new realm and no new signature at the permanent path.\n\nAlso carries the twin of `adminreg`s dispatch-cost test.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/schema/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/schema/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/schema/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/schema/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/schema/impl/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/schema/impl/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/schema/impl/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/schema/impl/v1\"\ngno = \"0.9\"\n# public: hands its own handler to the facade; private aborts with \"cannot persist object from the private realm\"\n"},{"name":"impl.gno","body":"// Package impl is version 1 of the handler realm of the \"API as data\" upgrade\n// pattern (pattern G; see ../../README.md).\n//\n// Three verbs: it ADDS one and keeps both of v0's untouched, which is what\n// lets the facade accept it. Growing the API costs no new realm and no new\n// signature at the permanent path.\npackage impl\n\nimport (\n\t\"strings\"\n\n\tfacade \"gno.land/r/moul/x/upgrade/schema/facade/v0\"\n)\n\n// schema is this version's whole API. One verb per line, name then parameters.\nconst schema = `upper s\nrepeat s n\nsurround s left right`\n\ntype handler struct{}\n\nfunc (handler) Schema() string { return schema }\n\nfunc (handler) Invoke(verb string, args []string) string {\n\tswitch verb {\n\tcase \"upper\":\n\t\treturn strings.ToUpper(args[0])\n\tcase \"repeat\":\n\t\treturn strings.Repeat(args[0], atoi(args[1]))\n\tcase \"surround\":\n\t\treturn args[1] + args[0] + args[2]\n\t}\n\t// Unreachable: the facade checked the verb against this schema first.\n\tpanic(\"unknown verb \" + verb)\n}\n\n// atoi is hand-rolled to keep the failure message about the ARGUMENT rather\n// than about strconv, which is the whole difference a typed boundary would have\n// made here.\nfunc atoi(s string) int {\n\tif s == \"\" {\n\t\tpanic(\"expected a number, got an empty argument\")\n\t}\n\tn := 0\n\tfor _, c := range s {\n\t\tif c \u003c '0' || c \u003e '9' {\n\t\t\tpanic(\"expected a number, got \" + s)\n\t\t}\n\t\tn = n*10 + int(c-'0')\n\t\tif n \u003e 64 {\n\t\t\tpanic(\"refusing to repeat more than 64 times\")\n\t\t}\n\t}\n\treturn n\n}\n\n// Instance exposes the singleton.\nfunc Instance() facade.Handler { return handler{} }\n\n// Path is this realm's own package path, the string the facade owner accepts.\nconst Path = \"gno.land/r/moul/x/upgrade/schema/impl/v1\"\n\nfunc init(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n\n// Propose re-nominates this handler, so a rollback needs no redeploy.\nfunc Propose(cur realm) {\n\tfacade.Propose(cross(cur), Instance())\n}\n"},{"name":"impl_test.gno","body":"package impl\n\nimport (\n\t\"testing\"\n\n\tfacade \"gno.land/r/moul/x/upgrade/schema/facade/v0\"\n\tbad \"gno.land/r/moul/x/upgrade/schema/impl/bad/v0\"\n\timplv0 \"gno.land/r/moul/x/upgrade/schema/impl/v0\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestGrowTheAPI is the whole pattern: three handlers propose themselves, the\n// API is enumerable without a transaction, it grows without a new signature at\n// the permanent path, and the one candidate that would break a caller is\n// refused despite satisfying the interface.\nfunc TestGrowTheAPI(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(facade.Ownable.Owner()))\n\tuassert.Equal(t, 3, len(facade.Candidates()), \"all three handlers nominated themselves\")\n\n\t// v0: two verbs, and a caller can discover them with no transaction.\n\tfacade.Accept(cross(cur), implv0.Path)\n\tuassert.Equal(t, \"upper, repeat\", joinVerbs(facade.Verbs()))\n\tuassert.Equal(t, \"repeat(s, n)\", facade.Signature(\"repeat\"))\n\tuassert.Equal(t, \"GNO\", facade.Call(cross(cur), \"upper\", \"gno\"))\n\tuassert.Equal(t, \"abab\", facade.Call(cross(cur), \"repeat\", \"ab|2\"))\n\n\t// The facade checks arity before the handler runs, so the message names the\n\t// signature rather than whatever the handler would have done.\n\tuassert.AbortsContains(t, cur, \"verb repeat takes 2 argument(s), got 1, signature is repeat(s, n)\", func() {\n\t\tfacade.Call(cross(cur), \"repeat\", \"ab\")\n\t})\n\tuassert.AbortsContains(t, cur, \"unknown verb nope, known: upper, repeat\", func() {\n\t\tfacade.Call(cross(cur), \"nope\", \"\")\n\t})\n\n\t// v1 ADDS a verb and keeps the other two, so it is accepted. No new realm,\n\t// no new signature at the permanent path, and old callers are untouched.\n\tfacade.Accept(cross(cur), Path)\n\tuassert.Equal(t, \"upper, repeat, surround\", joinVerbs(facade.Verbs()))\n\tuassert.Equal(t, \"[gno]\", facade.Call(cross(cur), \"surround\", \"gno|[|]\"))\n\tuassert.Equal(t, \"GNO\", facade.Call(cross(cur), \"upper\", \"gno\"), \"v0's verbs still answer\")\n\n\t// The refusal. bad satisfies Handler exactly as well as the others do; what\n\t// it does is drop a verb and reshape another, which only the schema sees.\n\tuassert.AbortsContains(t, cur, \"schema regression: the candidate drops verb upper\", func() {\n\t\tfacade.Accept(cross(cur), bad.Path)\n\t})\n\tuassert.Equal(t, Path, facade.Live(), \"a refused accept changes nothing\")\n\n\t// The diff is SYMMETRIC, which the first draft of this test got wrong: now\n\t// that v1 has added a verb, rolling back to v0 DROPS it and is a regression\n\t// by the same rule. Accept refuses the rollback.\n\tuassert.AbortsContains(t, cur, \"schema regression: the candidate drops verb surround\", func() {\n\t\tfacade.Accept(cross(cur), implv0.Path)\n\t})\n\tuassert.Equal(t, Path, facade.Live())\n\n\t// Which is why the override exists. A pattern that can only move forward is\n\t// worse than one with no diff at all.\n\tfacade.AcceptBreaking(cross(cur), implv0.Path)\n\tuassert.Equal(t, \"upper, repeat\", joinVerbs(facade.Verbs()))\n\tfacade.Accept(cross(cur), Path)\n\n\tuassert.Equal(t, \"upper s\\nrepeat s n\\nsurround s left right\\n\", facade.SchemaText())\n\tuassert.Equal(t, \"schema/facade/v0: gno.land/r/moul/x/upgrade/schema/impl/v1\\n\"+\n\t\t\"- upper(s)\\n- repeat(s, n)\\n- surround(s, left, right)\\n\", facade.Render(\"\"))\n}\n\n// TestDispatchCost100 does 100 dispatches through this pattern's entry point,\n// so `gno test -print-runtime-metrics` prints a cycle count for a known\n// workload. Its twin is TestDispatchCost100 in adminreg/impl/gen1.\n//\n// It measures what a call costs through each pattern AS SHIPPED, which is the\n// number that decides between them. It is NOT the cost of the string boundary\n// in isolation: this path also crosses a realm and the typed one does not.\nfunc TestDispatchCost100(cur realm, t *testing.T) {\n\t// Runs after TestGrowTheAPI, so v1 is already live. Accepting anything here\n\t// would fight that test's state, and the verb costs the same either way.\n\tfor i := 0; i \u003c 100; i++ {\n\t\tfacade.Call(cross(cur), \"upper\", \"gno\")\n\t}\n\tuassert.Equal(t, \"GNO\", facade.Call(cross(cur), \"upper\", \"gno\"))\n}\n\n// TestMalformedSchemaIsRejectedAtProposal checks the other validation edge: a\n// schema that cannot be parsed never becomes a candidate.\nfunc TestMalformedSchemaIsRejectedAtProposal(cur realm, t *testing.T) {\n\tuassert.AbortsContains(t, cur, \"malformed schema\", func() {\n\t\tfacade.Propose(cross(cur), badSchema{})\n\t})\n}\n\ntype badSchema struct{}\n\nfunc (badSchema) Schema() string                         { return \"Upper s\" } // capital, not [a-z0-9_]\nfunc (badSchema) Invoke(string, []string) string         { return \"\" }\n\nfunc joinVerbs(v []string) string {\n\tout := \"\"\n\tfor i, s := range v {\n\t\tif i \u003e 0 {\n\t\t\tout += \", \"\n\t\t}\n\t\tout += s\n\t}\n\treturn out\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"impl","path":"gno.land/r/moul/x/upgrade/selfreg/impl/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/selfreg/impl/v0`\n\nVersion 0 of the **implementation realm** of pattern E. Registers itself with\n[the facade](../../facade) from `init`, so deploying it is the upgrade.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/selfreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/selfreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/selfreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/selfreg/impl/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/selfreg/impl/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/selfreg/impl/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/selfreg/impl/v0\"\ngno = \"0.9\"\n# public: hands its own greeter to the facade; private aborts with \"cannot persist object from the private realm\"\n"},{"name":"impl.gno","body":"// Package impl is version 0 of the implementation realm of the\n// \"self-registering implementation\" upgrade pattern (pattern E; see\n// ../../README.md).\n//\n// Deploying this realm is the whole upgrade: init registers it with the facade.\npackage impl\n\nimport (\n\tfacade \"gno.land/r/moul/x/upgrade/selfreg/facade/v0\"\n)\n\ntype greeter struct{}\n\nfunc (greeter) Greet(name string) string { return \"hello, \" + name }\nfunc (greeter) Version() string          { return \"impl/v0\" }\n\n// Instance exposes the singleton so a test (or a rollback) can re-register it\n// without redeploying.\nfunc Instance() facade.Impl { return greeter{} }\n\nfunc init(cur realm) {\n\tfacade.Register(cross(cur), Instance())\n}\n\n// Register re-registers this implementation with the facade. init does it once\n// at deploy; exposing it as a transaction is what makes a rollback to an\n// already-deployed version a single call.\nfunc Register(cur realm) {\n\tfacade.Register(cross(cur), Instance())\n}\n\n// Seal asks the facade to end its upgradeability, forever. It only succeeds\n// while this implementation is the live one: the facade reads the caller off\n// the crossing frame, so this cannot be used to seal somebody else's tenure.\nfunc Seal(cur realm) {\n\tfacade.Seal(cross(cur))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"impl","path":"gno.land/r/moul/x/upgrade/selfreg/impl/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/selfreg/impl/v1`\n\nVersion 1 of the **implementation realm** of pattern E. Identical wiring to\n[`v0`](../gen0), different behaviour: deploying it takes the facade over on the\nspot, with no transaction from anybody.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/selfreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/selfreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/selfreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/selfreg/impl/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/selfreg/impl/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/selfreg/impl/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/selfreg/impl/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/selfreg/impl/v1\"\ngno = \"0.9\"\n# public: hands its own greeter to the facade; private aborts with \"cannot persist object from the private realm\"\n"},{"name":"impl.gno","body":"// Package impl is version 1 of the implementation realm of the\n// \"self-registering implementation\" upgrade pattern (pattern E; see\n// ../../README.md).\n//\n// Identical wiring to v0, different behaviour. Deploying it takes the facade\n// over on the spot, with no transaction from anybody.\npackage impl\n\nimport (\n\tfacade \"gno.land/r/moul/x/upgrade/selfreg/facade/v0\"\n)\n\ntype greeter struct{}\n\nfunc (greeter) Greet(name string) string { return \"HELLO, \" + name + \"!\" }\nfunc (greeter) Version() string          { return \"impl/v1\" }\n\n// Instance exposes the singleton so a test (or a rollback) can re-register it\n// without redeploying.\nfunc Instance() facade.Impl { return greeter{} }\n\nfunc init(cur realm) {\n\tfacade.Register(cross(cur), Instance())\n}\n\n// Register re-registers this implementation with the facade. init does it once\n// at deploy; exposing it as a transaction is what makes a rollback to an\n// already-deployed version a single call.\nfunc Register(cur realm) {\n\tfacade.Register(cross(cur), Instance())\n}\n\n// Seal asks the facade to end its upgradeability, forever. It only succeeds\n// while this implementation is the live one: the facade reads the caller off\n// the crossing frame, so this cannot be used to seal somebody else's tenure.\nfunc Seal(cur realm) {\n\tfacade.Seal(cross(cur))\n}\n"},{"name":"impl_test.gno","body":"package impl\n\nimport (\n\t\"testing\"\n\n\tfacade \"gno.land/r/moul/x/upgrade/selfreg/facade/v0\"\n\timplv0 \"gno.land/r/moul/x/upgrade/selfreg/impl/v0\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestTakeoverOnDeploy checks that the last implementation to run its init owns\n// the facade, and that re-registering an older one rolls the behaviour back.\n//\n// Both impl realms are imported here, so both inits have already run by the\n// time this test starts; v1 is imported last and therefore holds the facade.\nfunc TestTakeoverOnDeploy(cur realm, t *testing.T) {\n\tuassert.Equal(t, \"gno.land/r/moul/x/upgrade/selfreg/impl/v1\", facade.Live())\n\tuassert.Equal(t, \"impl/v1\", facade.Version())\n\tuassert.Equal(t, \"HELLO, world!\", facade.Greet(\"world\"))\n\n\t// Rolling back is the same one call: the facade only ever holds a pointer.\n\timplv0.Register(cross(cur))\n\tuassert.Equal(t, \"gno.land/r/moul/x/upgrade/selfreg/impl/v0\", facade.Live())\n\tuassert.Equal(t, \"hello, world\", facade.Greet(\"world\"))\n\n\t// And forward again.\n\tRegister(cross(cur))\n\tuassert.Equal(t, \"impl/v1\", facade.Version())\n\tuassert.Equal(t, \"selfreg/facade/v0 [open]: impl/v1 (gno.land/r/moul/x/upgrade/selfreg/impl/v1)\\nHELLO, world!\\n\", facade.Render(\"\"))\n}\n\n// TestSeal ends the realm's upgradeability and checks that it is terminal.\n//\n// Runs after TestTakeoverOnDeploy on purpose: sealing is one-way, so every test\n// that needs to register must already have run.\nfunc TestSeal(cur realm, t *testing.T) {\n\t// The live implementation is the only actor that may seal, because with no\n\t// owner it is the only one the facade already trusts.\n\tuassert.Equal(t, \"gno.land/r/moul/x/upgrade/selfreg/impl/v1\", facade.Live())\n\tuassert.Equal(t, facade.StageOpen, facade.Stage())\n\tuassert.AbortsContains(t, cur, \"only the live implementation may seal\", func() {\n\t\timplv0.Seal(cross(cur))\n\t})\n\n\tSeal(cross(cur))\n\tuassert.Equal(t, facade.StageSealed, facade.Stage())\n\n\t// Nothing registers again, not even the implementation that sealed it.\n\tuassert.AbortsContains(t, cur, \"is sealed\", func() {\n\t\tRegister(cross(cur))\n\t})\n\tuassert.AbortsContains(t, cur, \"is sealed\", func() {\n\t\timplv0.Register(cross(cur))\n\t})\n\n\t// What was live stays live, and says so.\n\tuassert.Equal(t, \"HELLO, world!\", facade.Greet(\"world\"))\n\tuassert.Equal(t, \"selfreg/facade/v0 [sealed]: impl/v1 (gno.land/r/moul/x/upgrade/selfreg/impl/v1)\\nHELLO, world!\\n\", facade.Render(\"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"logic","path":"gno.land/r/moul/x/upgrade/store/logic/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/store/logic/v0`\n\nVersion 0 of the **logic realm** of pattern C. Owns no state: every write lands\nin [`root/v0`](../../root). Step is 1.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/store/logic/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/store/logic/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/store/logic/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/store/logic/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/store/logic/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/store/logic/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/store/logic/v0\"\ngno = \"0.9\"\n# public: imported by .../store/logic/v1, whose test drives the handover between them\n"},{"name":"logic.gno","body":"// Package logic is version 0 of the logic realm of the \"state realm + swappable\n// logic\" upgrade pattern (pattern C of the exploration; see ../../README.md).\n//\n// It owns no state at all. Everything it writes lands in the root data realm,\n// which is what makes replacing this realm cheap: there is nothing here to\n// migrate.\npackage logic\n\nimport (\n\troot \"gno.land/r/moul/x/upgrade/store/root/v0\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Step is this version's business rule: one call, one unit.\nconst Step = 1\n\n// Inc applies this version's rule to the shared counter.\nfunc Inc(cur realm) int {\n\treturn root.Inc(cross(cur), Step)\n}\n\n// Get reads the shared counter. Same number every version sees.\nfunc Get() int {\n\treturn root.Get()\n}\n\nfunc Render(_ string) string {\n\treturn ufmt.Sprintf(\"store/logic/v0: counter=%d step=%d\\n\", Get(), Step)\n}\n"},{"name":"render_example_test.gno","body":"package logic\n\n// ExampleRender pins the render of the logic realm against an untouched store.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// store/logic/v0: counter=0 step=1\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"logic","path":"gno.land/r/moul/x/upgrade/store/logic/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/store/logic/v1`\n\nVersion 1 of the **logic realm** of pattern C. Same shape as [`v0`](../gen0),\ndifferent rule (step 1000), same data. The upgrade changed the code without\ntouching a byte of state.\n\nSee [the pattern](../../README.md) and [the exploration](../../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/store/logic/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/store/logic/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/store/logic/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/store/logic/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/store/logic/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/store/logic/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/store/logic/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/store/logic/v1\"\ngno = \"0.9\"\n# private on purpose: it holds no state and hands out no object, so the chain lets it\n# be redeployed in place. That is the seventh pattern, and it is measured in the README.\nprivate = true\n"},{"name":"logic.gno","body":"// Package logic is version 1 of the logic realm of the \"state realm + swappable\n// logic\" upgrade pattern (pattern C of the exploration; see ../../README.md).\n//\n// Same shape as v0, different rule. The counter it reads and writes is the same\n// one v0 was using: the upgrade changed the code without touching the data.\npackage logic\n\nimport (\n\troot \"gno.land/r/moul/x/upgrade/store/root/v0\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Step is this version's business rule: the change that justified the upgrade.\nconst Step = 1000\n\n// Inc applies this version's rule to the shared counter.\nfunc Inc(cur realm) int {\n\treturn root.Inc(cross(cur), Step)\n}\n\n// Get reads the shared counter, including everything v0 wrote.\nfunc Get() int {\n\treturn root.Get()\n}\n\nfunc Render(_ string) string {\n\treturn ufmt.Sprintf(\"store/logic/v1: counter=%d step=%d\\n\", Get(), Step)\n}\n"},{"name":"logic_test.gno","body":"package logic\n\nimport (\n\t\"testing\"\n\n\tlogicv0 \"gno.land/r/moul/x/upgrade/store/logic/v0\"\n\troot \"gno.land/r/moul/x/upgrade/store/root/v0\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestSwapLogic shows the upgrade: the counter survives it untouched, and only\n// the realm root currently points at may write.\nfunc TestSwapLogic(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(root.Ownable.Owner()))\n\n\t// v0 is live out of the box.\n\tuassert.Equal(t, 1, logicv0.Inc(cross(cur)))\n\tuassert.Equal(t, 2, logicv0.Inc(cross(cur)))\n\tuassert.AbortsContains(t, cur, \"is not the live logic realm\", func() {\n\t\tInc(cross(cur))\n\t})\n\n\t// The upgrade: one call, no migration.\n\troot.SetLive(cross(cur), \"gno.land/r/moul/x/upgrade/store/logic/v1\")\n\n\t// v1 writes on top of the data v0 left; v0 is locked out by the same gate.\n\tuassert.Equal(t, 1002, Inc(cross(cur)), \"v1 adds its own step to v0's data\")\n\tuassert.AbortsContains(t, cur, \"is not the live logic realm\", func() {\n\t\tlogicv0.Inc(cross(cur))\n\t})\n\n\t// Reads stay open to every version, live or not.\n\tuassert.Equal(t, 1002, logicv0.Get(), \"a retired version still reads the truth\")\n\tuassert.Equal(t, \"store/logic/v1: counter=1002 step=1000\\n\", Render(\"\"))\n\tuassert.Equal(t, \"store/logic/v0: counter=1002 step=1\\n\", logicv0.Render(\"\"))\n}\n"}]},"send":"","max_deposit":"5000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wrap","path":"gno.land/r/moul/x/upgrade/wrap/v1","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/upgrade/wrap/v1`\n\nVersion 1 of the **wrapping versions** upgrade pattern (pattern A). Keeps its\nown counter and adds [`v0`](../gen0)'s on read. Both versions stay writable, so the\ntwo paths report different totals and neither is authoritative.\n\n`z_wrap_filetest.gno` walks that divergence step by step.\n\nSee [the pattern](../README.md) and [the exploration](../../README.md).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/upgrade/wrap/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/upgrade/wrap/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/upgrade/wrap/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/upgrade/wrap/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/upgrade/wrap/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/upgrade/wrap/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/upgrade/wrap/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/upgrade/wrap/v1\"\ngno = \"0.9\"\n# public: a further version must be able to wrap it the same way v1 wraps v0\n"},{"name":"wrap.gno","body":"// Package wrap is version 1 of the \"wrapping versions\" upgrade pattern\n// (pattern A of the exploration; see ../README.md).\n//\n// v1 owns a counter of its own and ADDS v0's on read. Both versions stay live\n// and independently writable, so the two paths report different totals and\n// neither is authoritative. That is the pattern's defining trade-off: no\n// migration, no downtime, no coordination, and no single answer either.\npackage wrap\n\nimport (\n\tv0 \"gno.land/r/moul/x/upgrade/wrap/v0\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar counter int\n\n// Inc adds n to this version's own counter. It does NOT touch v0.\nfunc Inc(cur realm, n int) {\n\tcounter += n\n}\n\n// Get returns v0's counter plus this version's own. Reading across the version\n// boundary is a plain non-crossing call: no realm is entered as a writer, so\n// this stays queryable from vm/qeval and from Render.\nfunc Get() int {\n\treturn v0.Get() + counter\n}\n\nfunc Render(_ string) string {\n\treturn ufmt.Sprintf(\"wrap/v1: %d (own %d + v0 %d)\\n\", Get(), counter, v0.Get())\n}\n"},{"name":"z_wrap_filetest.gno","body":"// PKGPATH: gno.land/r/moul/main\npackage main\n\nimport (\n\tv0 \"gno.land/r/moul/x/upgrade/wrap/v0\"\n\tv1 \"gno.land/r/moul/x/upgrade/wrap/v1\"\n)\n\n// Both versions stay writable, and writing one never moves the other.\nfunc main(cur realm) {\n\tprint(v0.Render(\"\"))\n\tprint(v1.Render(\"\"))\n\n\tv0.Inc(cross(cur), 10)\n\tprint(v0.Render(\"\"))\n\tprint(v1.Render(\"\"))\n\n\tv1.Inc(cross(cur), 100)\n\tprint(v0.Render(\"\"))\n\tprint(v1.Render(\"\"))\n}\n\n// Output:\n// wrap/v0: 0\n// wrap/v1: 0 (own 0 + v0 0)\n// wrap/v0: 10\n// wrap/v1: 10 (own 0 + v0 10)\n// wrap/v0: 10\n// wrap/v1: 110 (own 100 + v0 10)\n"}]},"send":"","max_deposit":"5000000ugnot"}],"fee":{"gas_wanted":"291771000","gas_fee":"875313ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"1Wqp9fMfBkb8YBgw5uNfTVmt3IFLxGZMPw3IfQraZblZh/GNjv0COdMf+GNIhh6L2lz+JqFGuk6sXNSdiJvwFg=="}],"memo":""},"metadata":{"timestamp":"1790961698"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"6pPi0g9Dv1w3YoBB3QiGgfbpoN1+9hM7GLhpxHE1xF06xBgEq7W2elsGEAnXjUN2T6j+vRH75gAVyAR3snYFVg=="}],"memo":""},"metadata":{"timestamp":"1790961698"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"epdKHC4UaPZ9iLix0Nl3kAvjxP6gmN0b6pXIT/xu4HNby6GBFljTvlq+GJrP891d57EbkPXeZ4mTs64FN7JTgw=="}],"memo":""},"metadata":{"timestamp":"1790961755"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bfdemo","path":"gno.land/r/moul/x/vm/bfdemo/v0","files":[{"name":"README.md","body":"# r/moul/x/vm/bfdemo\n\nA realm that runs Brainfuck programs on chain, a slice at a time.\n\nIt is a demo of [`p/moul/x/vm/bf`](/p/moul/x/vm/bf/v0) (the machine) and\n[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, the\ninstance store), and carries no logic of its own.\n\nWhat it exists to show is the thing gno realm code cannot do for itself: a\nprogram that runs out of fuel does not fail, it pauses. The realm keeps the\nsnapshot, and the next caller pays for the next slice. Upload a program, call\n`Step` a few times, and watch one computation finish across several\ntransactions.\n\n## Calls\n\n| function | what |\n|---|---|\n| `Upload(src, input, budget)` | compile and store a program, returns its id. Compilation happens here, so a malformed program is rejected by the transaction that submitted it |\n| `Step(id, fuel)` | run one slice and keep the snapshot. Anyone may pay for a slice, not only the owner |\n| `Remove(id)` | delete an instance. Owner only |\n\n`Render(\"/\")` lists the instances and offers three sample programs.\n`Render(\"/\u003cid\u003e\")` shows one instance: its compiled program, status, fuel, and\noutput.\n\n## Limits\n\nEverything a caller can grow is bounded, because all of it is storage somebody\npays a deposit on: 64 instances, 64 KiB of source, 1 KiB of input, 4 KiB of\noutput, 5,000,000 fuel per slice, 30,000 tape cells. A guest that writes past\nthe output cap is trapped rather than truncated, so the rendered output is never\na lie.\n\n## Untrusted input\n\nA program's source is caller-supplied, and everything outside the eight\noperators is a comment that may hold anything at all. The page never renders it:\nit shows the program the machine actually compiled, which cannot contain a\nbacktick or a newline and so cannot break out of its code fence. Guest output is\narbitrary bytes and is escaped the same way, backtick included.\n\nNo instance is funded, so `Host.Send` always returns `ErrNotGranted`. That is\nthe capability rule doing its job, not a missing feature.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/vm/bfdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/vm/bfdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bfdemo.gno","body":"// Package bfdemo is the playground for the guest-VM work: a realm that runs\n// Brainfuck programs on chain, a slice at a time.\n//\n// It is a demo of two libraries and carries no logic of its own:\n// [p/moul/x/vm/bf](/p/moul/x/vm/bf/v0) is the machine, and\n// [p/moul/x/vm/vmkit](/p/moul/x/vm/vmkit/v0) is the host ABI, the fuel meter\n// and the instance store.\n//\n// What it exists to show is the thing gno realm code cannot do for itself: a\n// program that runs out of fuel does not fail, it pauses. The realm keeps the\n// snapshot, and the next caller pays for the next slice. Upload a program,\n// call Step a few times, and watch one computation finish across several\n// transactions.\npackage bfdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/vm/bf/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Caps. Everything a caller can grow is bounded, because all of it is storage\n// somebody pays a deposit on.\nconst (\n\t// MaxInstances is how many programs the realm keeps at once. Past it,\n\t// an upload has to wait for someone to remove one.\n\tMaxInstances = 64\n\t// MaxOutput caps the bytes one program may write. Past it the guest is\n\t// trapped rather than truncated, so rendered output is never a lie.\n\tMaxOutput = 4096\n\t// MaxInput caps the call input a program can be given.\n\tMaxInput = 1024\n\t// DefaultFuel is the budget an upload gets when it asks for none, and\n\t// the slice size Step uses when asked for none.\n\tDefaultFuel = 100000\n\t// MaxSliceFuel bounds one transaction's work regardless of what the\n\t// caller asked for.\n\tMaxSliceFuel = 5000000\n)\n\nvar (\n\t// store holds the instances: program, snapshot, status, accounting.\n\tstore = vmkit.NewStore()\n\t// inputs holds each instance's call input, keyed by id. It is separate\n\t// from the instance so vmkit.Instance stays the VM-agnostic record it\n\t// is meant to be.\n\tinputs = avl.NewTree()\n\tidgen  seqid.ID\n\tcount  int\n)\n\n// host is the realm-backed [vmkit.Host]. One is built per call, wrapping the\n// instance being stepped, so a guest's output and authority are scoped to it\n// and nothing ambient leaks in.\ntype host struct {\n\tinst    *vmkit.Instance\n\tin      []byte\n\tkv      *avl.Tree\n\toverrun bool // the guest wrote past MaxOutput\n}\n\nfunc (h *host) Caller() address { return h.inst.Owner }\nfunc (h *host) Origin() address { return h.inst.Owner }\nfunc (h *host) Now() int64      { return time.Now().Unix() }\nfunc (h *host) Height() int64   { return runtime.ChainHeight() }\nfunc (h *host) Input() []byte   { return h.in }\n\n// Get and Set are scoped to the instance by construction: the tree belongs to\n// the instance being stepped, so one program cannot reach another's storage\n// even though both live in this one realm. bf never calls them; they are here\n// because the ABI is the point.\nfunc (h *host) Get(key []byte) []byte {\n\tv := h.kv.Get(string(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.([]byte)\n}\n\nfunc (h *host) Set(key, val []byte) { h.kv.Set(string(key), val) }\n\nfunc (h *host) Output(p []byte) {\n\tif len(h.inst.Output)+len(p) \u003e MaxOutput {\n\t\th.overrun = true\n\t\treturn\n\t}\n\th.inst.Output = append(h.inst.Output, p...)\n}\n\nfunc (h *host) Emit(typ string, kv ...string) { chain.Emit(typ, kv...) }\n\n// Send is never granted here. The demo funds no instance, so a guest that\n// tries to move coins is refused. That is the capability rule doing its job,\n// not a missing feature.\nfunc (h *host) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\n\nfunc (h *host) Log(msg string) {}\n\n// Upload compiles src and stores it as a new instance, returning its id.\n//\n// Compilation happens here rather than at the first Step, so an unbalanced\n// program is rejected by the transaction that submitted it instead of costing\n// somebody else the gas later.\nfunc Upload(cur realm, src, input string, budget int64) string {\n\tif count \u003e= MaxInstances {\n\t\tpanic(\"bfdemo: too many instances, remove one first\")\n\t}\n\tif len(input) \u003e MaxInput {\n\t\tpanic(\"bfdemo: input too long\")\n\t}\n\tif _, err := bf.CompileDefault(src); err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\tif budget \u003c= 0 {\n\t\tbudget = DefaultFuel\n\t}\n\n\tid := idgen.Next().String()\n\towner := unsafe.PreviousRealm().Address()\n\tstore.Set(vmkit.NewInstance(id, owner, bf.VMName, []byte(src), budget))\n\tif input != \"\" {\n\t\tinputs.Set(id, input)\n\t}\n\tcount++\n\n\tchain.Emit(\"bf_upload\", \"id\", id, \"bytes\", ufmt.Sprintf(\"%d\", len(src)))\n\treturn id\n}\n\n// Step runs one slice of the instance: up to `fuel` guest ops, then stop and\n// keep the snapshot. Anyone may pay for a slice, not only the owner: a paused\n// program that only its owner can advance is a worse demo and no safer, since\n// the program and its budget were both fixed at upload.\nfunc Step(cur realm, id string, fuel int64) string {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"bfdemo: no such instance\")\n\t}\n\tif inst.Status != vmkit.Running {\n\t\tpanic(\"bfdemo: instance is \" + inst.Status.String())\n\t}\n\tif fuel \u003c= 0 {\n\t\tfuel = DefaultFuel\n\t}\n\tif fuel \u003e MaxSliceFuel {\n\t\tfuel = MaxSliceFuel\n\t}\n\n\tprog, err := bf.CompileDefault(string(inst.Program))\n\tif err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\th := \u0026host{inst: inst, in: []byte(inputOf(id)), kv: avl.NewTree()}\n\tif err := inst.Run(bf.NewMachine(prog), h, fuel); err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\tif h.overrun {\n\t\tinst.Status = vmkit.Trapped\n\t\tinst.Trap = \"output limit reached\"\n\t}\n\n\tchain.Emit(\"bf_step\",\n\t\t\"id\", id,\n\t\t\"status\", inst.Status.String(),\n\t\t\"fuel\", ufmt.Sprintf(\"%d\", inst.FuelUsed),\n\t)\n\treturn inst.Status.String()\n}\n\n// Remove deletes an instance. Owner only.\nfunc Remove(cur realm, id string) {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"bfdemo: no such instance\")\n\t}\n\tif inst.Owner != unsafe.PreviousRealm().Address() {\n\t\tpanic(\"bfdemo: not your instance\")\n\t}\n\tstore.Remove(id)\n\tinputs.Remove(id)\n\tcount--\n}\n\nfunc inputOf(id string) string {\n\tv := inputs.Get(id)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n"},{"name":"bfdemo_test.gno","body":"package bfdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst hello = \"++++++++++[\u003e+++++++\u003e++++++++++\u003e+++\u003e+\u003c\u003c\u003c\u003c-]\u003e++.\u003e+.+++++++..+++.\u003e++.\u003c\u003c+++++++++++++++.\u003e.+++.------.--------.\"\n\n// resetState puts the realm globals back where init() left them. Realm state\n// persists for the whole test binary, so every test that asserts on ids or on\n// the rendered instance list has to start from here.\nfunc resetState() {\n\tstore = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen = seqid.ID(0)\n\tcount = 0\n}\n\nfunc TestUploadAndRunToCompletion(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := Upload(cross(cur), hello, \"\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"Hello World\", string(inst.Output))\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, alice, inst.Owner)\n}\n\n// TestOneProgramAcrossManyTransactions is what the realm exists to\n// demonstrate: the same computation, finished over several calls, each paying\n// for its own slice.\nfunc TestOneProgramAcrossManyTransactions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\tid := Upload(cross(cur), hello, \"\", 0)\n\tstatus := \"\"\n\tslices := 0\n\tfor slices \u003c 500 {\n\t\tstatus = Step(cross(cur), id, 7)\n\t\tslices++\n\t\tif status != \"running\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"halted\", status)\n\tuassert.Equal(t, \"Hello World\", string(inst.Output))\n\tuassert.True(t, inst.Slices \u003e 1, \"took more than one slice\")\n}\n\nfunc TestInputIsReadThroughTheHost(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// \",[.,]\" echoes its input back.\n\tid := Upload(cross(cur), \",[.,]\", \"gno.land\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\tuassert.Equal(t, \"gno.land\", string(store.Get(id).Output))\n}\n\nfunc TestBudgetStopsAProgram(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\tid := Upload(cross(cur), hello, \"\", 12)\n\tuassert.Equal(t, \"out of fuel\", Step(cross(cur), id, 0))\n\tuassert.Equal(t, int64(12), store.Get(id).FuelUsed)\n\n\t// And it stays stopped rather than quietly continuing.\n\tuassert.AbortsContains(t, cur, \"instance is out of fuel\", func() {\n\t\tStep(cross(cur), id, 0)\n\t})\n}\n\nfunc TestUploadRejectsAMalformedProgram(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// Rejected by the transaction that submitted it, not by whoever pays\n\t// for the first slice later.\n\tuassert.AbortsContains(t, cur, \"unmatched\", func() {\n\t\tUpload(cross(cur), \"+++[\", \"\", 0)\n\t})\n\tuassert.Equal(t, 0, count)\n}\n\nfunc TestRemoveIsOwnerOnly(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Upload(cross(cur), hello, \"\", 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"not your instance\", func() {\n\t\tRemove(cross(cur), id)\n\t})\n\n\t// Anyone may pay for a slice, though: the program and its budget were\n\t// both fixed at upload.\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRemove(cross(cur), id)\n\tuassert.Equal(t, 0, count)\n\tuassert.True(t, store.Get(id) == nil)\n}\n\nfunc TestOutputIsCappedAndTrapped(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// A cell set to 1 and printed forever: an infinite writer.\n\tid := Upload(cross(cur), \"+[.]\", \"\", 0)\n\tstatus := Step(cross(cur), id, 0)\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"trapped\", status)\n\tuassert.Equal(t, \"output limit reached\", inst.Trap)\n\tuassert.Equal(t, MaxOutput, len(inst.Output))\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tresetState()\n\tuassert.True(t, strings.Contains(Render(\"/nope\"), \"No such instance\"))\n}\n\n// TestRenderEscapesGuestOutput pins the rule that a realm cannot be fixed in\n// place once it is live: everything a caller controls is escaped before it\n// reaches the page.\nfunc TestRenderEscapesGuestOutput(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// Print a backtick (96), which would otherwise close the code fence.\n\tsrc := strings.Repeat(\"+\", 96) + \".\"\n\tid := Upload(cross(cur), src, \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tpage := Render(\"/\" + id)\n\tuassert.Equal(t, \"`\", string(store.Get(id).Output))\n\tuassert.True(t, strings.Contains(page, \"\\\\x60\"), \"the backtick is escaped\")\n\n\t// The comment text in a program never reaches the page at all: only\n\t// the eight operators do.\n\tuassert.Equal(t, \"+++[-]\u003c\u003e\", operatorsOnly(\"+++ this is a comment [-] \u003c/script\u003e\"))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/vm/bfdemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render.gno","body":"package bfdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/vm/bf/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// samples are the programs the home page offers, so the realm is usable\n// without writing Brainfuck by hand.\nvar samples = []struct {\n\tname  string\n\tsrc   string\n\tinput string\n\tnote  string\n}{\n\t{\n\t\t\"Hello World\",\n\t\t\"++++++++++[\u003e+++++++\u003e++++++++++\u003e+++\u003e+\u003c\u003c\u003c\u003c-]\u003e++.\u003e+.+++++++..+++.\u003e++.\u003c\u003c+++++++++++++++.\u003e.+++.------.--------.\",\n\t\t\"\",\n\t\t\"385 guest ops, five tape cells. Finishes in one slice.\",\n\t},\n\t{\n\t\t\"Echo the input\",\n\t\t\",[.,]\",\n\t\t\"gno.land\",\n\t\t\"Reads through Host.Input, which is what the naive interpreter could not do at all: it panicked on `,`.\",\n\t},\n\t{\n\t\t\"Heavy loop\",\n\t\t\"++++++++++[-\u003e++++++++++[-\u003e++++++++++[-]\u003c]\u003c]\",\n\t\t\"\",\n\t\t\"About 111k guest ops. Give it 20000 fuel and it takes six slices, which is the point.\",\n\t},\n}\n\n// Render is the realm's gnoweb view.\n//\n//   - \"/\"      the samples, the instance list, and how the thing works.\n//   - \"/\u003cid\u003e\"  one instance: its program, status, fuel and output.\nfunc Render(path string) string {\n\tid := strings.TrimPrefix(path, \"/\")\n\tid = strings.TrimSpace(id)\n\tif id == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderInstance(id)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Brainfuck, on chain, a slice at a time\\n\\n\")\n\tsb.WriteString(\"Demo of [`p/moul/x/vm/bf`](/p/moul/x/vm/bf/v0) (the machine) and \")\n\tsb.WriteString(\"[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, \")\n\tsb.WriteString(\"the instance store). This realm holds no logic of its own.\\n\\n\")\n\tsb.WriteString(\"A program here does not run to completion. It runs until its fuel slice is spent, \")\n\tsb.WriteString(\"then pauses: the realm keeps the snapshot and the next caller pays for the next slice. \")\n\tsb.WriteString(\"Realm code cannot pause itself, and a guest can.\\n\\n\")\n\n\tsb.WriteString(\"## Samples\\n\\n\")\n\tfor _, s := range samples {\n\t\tsb.WriteString(\"**\" + ui.Inline(s.name) + \"**: \" + s.note + \"\\n\\n\")\n\t\tsb.WriteString(\"```\\n\" + s.src + \"\\n```\\n\\n\")\n\t\tsb.WriteString(ui.Action(\"Upload \"+s.name, \"Upload\",\n\t\t\t\"src\", s.src, \"input\", s.input, \"budget\", \"0\") + \"\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Instances\\n\\n\")\n\tt := ui.NewTable(\"id\", \"status\", \"fuel used\", \"slices\", \"output\")\n\tstore.ReverseIterate(func(i *vmkit.Instance) bool {\n\t\tt.Row(\n\t\t\t\"[\"+i.ID+\"](/r/moul/x/vm/bfdemo/v0:\"+i.ID+\")\",\n\t\t\ti.Status.String(),\n\t\t\tufmt.Sprintf(\"%d\", i.FuelUsed),\n\t\t\tufmt.Sprintf(\"%d\", i.Slices),\n\t\t\t\"`\"+ui.Cell(printable(i.Output, 24))+\"`\",\n\t\t)\n\t\treturn false\n\t})\n\tsb.WriteString(t.OrEmpty(\"No instances yet. Upload one of the samples above.\"))\n\tsb.WriteString(\"\\n\\n\")\n\n\tsb.WriteString(\"## Limits\\n\\n\")\n\tlt := ui.NewTable(\"limit\", \"value\")\n\tlt.Row(\"instances\", ufmt.Sprintf(\"%d\", MaxInstances))\n\tlt.Row(\"source bytes\", ufmt.Sprintf(\"%d\", bf.MaxSource))\n\tlt.Row(\"input bytes\", ufmt.Sprintf(\"%d\", MaxInput))\n\tlt.Row(\"output bytes\", ufmt.Sprintf(\"%d\", MaxOutput))\n\tlt.Row(\"fuel per slice\", ufmt.Sprintf(\"%d\", MaxSliceFuel))\n\tlt.Row(\"tape cells\", ufmt.Sprintf(\"%d\", bf.TapeSize))\n\tsb.WriteString(lt.String())\n\treturn sb.String()\n}\n\nfunc renderInstance(id string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Instance \" + ui.Inline(id) + \"\\n\\n\")\n\tsb.WriteString(\"[← all instances](/r/moul/x/vm/bfdemo/v0)\\n\\n\")\n\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tsb.WriteString(\"**No such instance.** It was never uploaded, or its owner removed it.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tt := ui.NewTable(\"field\", \"value\")\n\tt.Row(\"owner\", ui.Addr(inst.Owner))\n\tt.Row(\"vm\", ui.Cell(inst.VM))\n\tt.Row(\"status\", inst.Status.String())\n\tif inst.Trap != \"\" {\n\t\tt.Row(\"trap\", ui.Cell(inst.Trap))\n\t}\n\tt.Row(\"fuel used\", ufmt.Sprintf(\"%d\", inst.FuelUsed))\n\tt.Row(\"fuel budget\", fuelText(inst.FuelBudget))\n\tt.Row(\"slices\", ufmt.Sprintf(\"%d\", inst.Slices))\n\tt.Row(\"source bytes\", ufmt.Sprintf(\"%d\", len(inst.Program)))\n\tt.Row(\"snapshot bytes\", ufmt.Sprintf(\"%d\", len(inst.Snapshot)))\n\tsb.WriteString(t.String())\n\tsb.WriteString(\"\\n\")\n\n\t// The source is caller-supplied, and everything outside the eight\n\t// operators is a comment that may hold anything at all. Show the\n\t// program the machine actually compiled, which cannot contain a\n\t// backtick or a newline and so cannot break out of the fence.\n\tsb.WriteString(\"## Program\\n\\n```\\n\" + operatorsOnly(string(inst.Program)) + \"\\n```\\n\\n\")\n\n\tsb.WriteString(\"## Output\\n\\n\")\n\tif len(inst.Output) == 0 {\n\t\tsb.WriteString(ui.Empty(\"Nothing written yet.\"))\n\t} else {\n\t\tsb.WriteString(\"```\\n\" + printable(inst.Output, MaxOutput) + \"\\n```\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tif inst.Status == vmkit.Running {\n\t\tsb.WriteString(ui.Action(\"Run 10000 more fuel\", \"Step\", \"id\", id, \"fuel\", \"10000\"))\n\t\tsb.WriteString(\" · \")\n\t\tsb.WriteString(ui.Action(\"Run 100000 more fuel\", \"Step\", \"id\", id, \"fuel\", \"100000\"))\n\t\tsb.WriteString(\"\\n\")\n\t} else {\n\t\tsb.WriteString(\"This instance is **\" + inst.Status.String() + \"** and cannot be stepped again.\\n\")\n\t}\n\treturn sb.String()\n}\n\nfunc fuelText(n int64) string {\n\tif n == vmkit.Unmetered {\n\t\treturn \"unmetered\"\n\t}\n\treturn ufmt.Sprintf(\"%d\", n)\n}\n\n// operatorsOnly strips a program down to the eight characters the language\n// defines. Everything else is a comment by definition, and a comment is\n// attacker-controlled text that has no business reaching a renderer.\nfunc operatorsOnly(src string) string {\n\tvar sb strings.Builder\n\tfor i := 0; i \u003c len(src); i++ {\n\t\tswitch src[i] {\n\t\tcase '+', '-', '\u003c', '\u003e', '[', ']', '.', ',':\n\t\t\tsb.WriteByte(src[i])\n\t\t}\n\t}\n\tif sb.Len() == 0 {\n\t\treturn \"(no operators: this program does nothing)\"\n\t}\n\treturn sb.String()\n}\n\n// printable renders guest output for a code fence: printable ASCII as itself,\n// everything else as an escape. A guest writes arbitrary bytes, so this is\n// the only form of it that is safe to show.\nfunc printable(b []byte, max int) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tconst hexDigits = \"0123456789abcdef\"\n\tvar sb strings.Builder\n\tfor _, c := range b {\n\t\tswitch {\n\t\tcase c == '\\n':\n\t\t\tsb.WriteString(\"\\\\n\")\n\t\tcase c == '\\t':\n\t\t\tsb.WriteString(\"\\\\t\")\n\t\tcase c == '\\\\':\n\t\t\tsb.WriteString(\"\\\\\\\\\")\n\t\tcase c == '`':\n\t\t\tsb.WriteString(\"\\\\x60\")\n\t\tcase c \u003e= 0x20 \u0026\u0026 c \u003c 0x7f:\n\t\t\tsb.WriteByte(c)\n\t\tdefault:\n\t\t\tsb.WriteString(\"\\\\x\")\n\t\t\tsb.WriteByte(hexDigits[c\u003e\u003e4])\n\t\t\tsb.WriteByte(hexDigits[c\u00260x0f])\n\t\t}\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"…\")\n\t}\n\treturn sb.String()\n}\n"}]},"send":"","max_deposit":"9000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"riscvdemo","path":"gno.land/r/moul/x/vm/riscvdemo/v0","files":[{"name":"README.md","body":"# r/moul/x/vm/riscvdemo\n\nDemo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0), the RV32IM hart, and\n[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0), the host ABI. This realm holds no\nlogic of its own: it stores images, builds a `vmkit.Host`, and renders.\n\nWhat it exists to show is two things realm code cannot do for itself.\n\n**The guest was not written for gno.** The programs on the front page are flat\n`.text` images, the bytes a cross compiler emits for\n`riscv32im-unknown-none-elf`. `Upload` takes hex, so anything you can build with\n`clang`, `rustc`, TinyGo or Zig and strip to its text segment goes in unchanged.\n\nTwo samples are exactly that and neither is a mock up. **Compiled by clang** is\na freestanding C program; **A token, in Rust** is `#![no_std]` Rust that mints,\nsends and burns, linking Rust's real `core` and `compiler_builtins`, so a\n64-bit divide in it runs `__udivdi3` on a machine with no 64-bit divide\ninstruction. Both are shipped as the bytes the compiler emitted, and the page\nshows their source rather than a disassembly, because a disassembly would bury\nthe only interesting fact: nobody wrote the machine code. Sources and build\ncommands: `tools/riscv-guests`.\n\n**A program pauses instead of failing.** It runs until its fuel slice is spent,\nthen stops with a snapshot the realm keeps, and the next caller pays for the\nnext slice. The \"Heavy loop\" sample is 200,006 instructions and takes three\ntransactions at the default slice, which is the whole point.\n\n```\nUploadSample(\"heavy\", \"\", 0)   -\u003e id\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"halted\"\n```\n\n## Reading the instance page\n\nA guest that writes nothing has still computed something, so the instance page\nrestores the snapshot and shows the register file under its ABI names. That is\nthe only place the state is legible: the hart itself does not survive the\ntransaction, only its snapshot does.\n\n## What a slice costs\n\nAn RV32IM instruction costs about **8,500 gas**, measured rather than estimated,\nso a block buys roughly **350,000 guest instructions**. Loading the image costs\nabout **19,600 gas per instruction word** and is paid again on every resume,\nwhich is why `MaxImage` is 8 KiB and not a megabyte. The measurements and how\nthey were taken are in the [library README](/p/moul/x/vm/riscv/v0).\n\n## What this realm does not grant\n\n`Send` always returns `vmkit.ErrNotGranted`. No instance here is funded, so a\nguest that tries to move coins is refused, and that is the capability rule\nworking rather than a missing feature. Guest key-value storage is scoped to the\ninstance being stepped by construction: the tree belongs to the instance, so one\nprogram cannot reach another's even though both live in this realm.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/vm/riscvdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/vm/riscvdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/vm/riscvdemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// regNames are the ABI names, because nobody reading a register dump thinks in\n// x-numbers and every compiler's output is annotated with these.\nvar regNames = [32]string{\n\t\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\t\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\t\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\t\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\",\n}\n\n// Render is the realm's gnoweb view.\n//\n//   - \"/\"      the samples, the instance list, and what the numbers mean.\n//   - \"/\u003cid\u003e\"  one instance: its status, fuel, output and register file.\nfunc Render(path string) string {\n\tid := strings.TrimSpace(strings.TrimPrefix(path, \"/\"))\n\tif id == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderInstance(id)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# RV32IM, on chain, a slice at a time\\n\\n\")\n\tsb.WriteString(\"Demo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0) (the hart) and \")\n\tsb.WriteString(\"[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, \")\n\tsb.WriteString(\"the instance store). This realm holds no logic of its own.\\n\\n\")\n\tsb.WriteString(\"The programs below are flat `.text` images: the same bytes a cross compiler \")\n\tsb.WriteString(\"emits for `riscv32im-unknown-none-elf`. Nothing here was written in a \")\n\tsb.WriteString(\"chain language, and nothing translated it.\\n\\n\")\n\tsb.WriteString(\"A program does not run to completion. It runs until its fuel slice is spent, \")\n\tsb.WriteString(\"then pauses: the realm keeps the snapshot and the next caller pays for the \")\n\tsb.WriteString(\"next slice. Realm code cannot pause itself, and a guest can.\\n\\n\")\n\n\tsb.WriteString(\"## Samples\\n\\n\")\n\tfor i := range samples {\n\t\ts := \u0026samples[i]\n\t\tsb.WriteString(\"**\" + ui.Inline(s.name) + \"**: \" + s.note + \"\\n\\n\")\n\t\tsb.WriteString(\"```\" + s.lang() + \"\\n\" + s.asm + \"\\n```\\n\\n\")\n\t\tsb.WriteString(ui.Action(\"Upload \"+s.name, \"UploadSample\",\n\t\t\t\"name\", s.slug, \"input\", s.input,\n\t\t\t\"budget\", ufmt.Sprintf(\"%d\", s.budget)) + \"\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Instances\\n\\n\")\n\tt := ui.NewTable(\"id\", \"status\", \"instructions\", \"slices\", \"output\")\n\tstore.ReverseIterate(func(i *vmkit.Instance) bool {\n\t\tt.Row(\n\t\t\t\"[\"+i.ID+\"](/r/moul/x/vm/riscvdemo/v0:\"+i.ID+\")\",\n\t\t\ti.Status.String(),\n\t\t\tufmt.Sprintf(\"%d\", i.FuelUsed),\n\t\t\tufmt.Sprintf(\"%d\", i.Slices),\n\t\t\t\"`\"+ui.Cell(printable(i.Output, 24))+\"`\",\n\t\t)\n\t\treturn false\n\t})\n\tsb.WriteString(t.OrEmpty(\"No instances yet. Upload one of the samples above.\"))\n\tsb.WriteString(\"\\n\\n\")\n\n\tsb.WriteString(\"## What a slice costs\\n\\n\")\n\tsb.WriteString(\"An RV32IM instruction costs about **8,500 gas** here, measured rather than \")\n\tsb.WriteString(\"estimated, so a block buys roughly **350,000 guest instructions**. Loading \")\n\tsb.WriteString(\"the image costs about **19,600 gas per instruction word** and is paid again \")\n\tsb.WriteString(\"on every resume, which is why the image cap below is small. The numbers and \")\n\tsb.WriteString(\"how they were taken are in the [library README](/p/moul/x/vm/riscv/v0).\\n\\n\")\n\n\tsb.WriteString(\"## Limits\\n\\n\")\n\tlt := ui.NewTable(\"limit\", \"value\")\n\tlt.Row(\"instances\", ufmt.Sprintf(\"%d\", MaxInstances))\n\tlt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", MaxImage))\n\tlt.Row(\"input bytes\", ufmt.Sprintf(\"%d\", MaxInput))\n\tlt.Row(\"output bytes\", ufmt.Sprintf(\"%d\", MaxOutput))\n\tlt.Row(\"instructions per slice\", ufmt.Sprintf(\"%d\", MaxSliceFuel))\n\tlt.Row(\"address space\", ufmt.Sprintf(\"%d\", riscv.MemSize))\n\tsb.WriteString(lt.String())\n\treturn sb.String()\n}\n\nfunc renderInstance(id string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Instance \" + ui.Inline(id) + \"\\n\\n\")\n\tsb.WriteString(\"[← all instances](/r/moul/x/vm/riscvdemo/v0)\\n\\n\")\n\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tsb.WriteString(\"**No such instance.** It was never uploaded, or its owner removed it.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tt := ui.NewTable(\"field\", \"value\")\n\tt.Row(\"owner\", ui.Addr(inst.Owner))\n\tt.Row(\"vm\", ui.Cell(inst.VM))\n\tt.Row(\"status\", inst.Status.String())\n\tif inst.Trap != \"\" {\n\t\tt.Row(\"trap\", ui.Cell(inst.Trap))\n\t}\n\tt.Row(\"instructions run\", ufmt.Sprintf(\"%d\", inst.FuelUsed))\n\tt.Row(\"budget\", fuelText(inst.FuelBudget))\n\tt.Row(\"slices\", ufmt.Sprintf(\"%d\", inst.Slices))\n\tt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", len(inst.Program)))\n\tt.Row(\"image words\", ufmt.Sprintf(\"%d\", len(inst.Program)/4))\n\tt.Row(\"snapshot bytes\", ufmt.Sprintf(\"%d\", len(inst.Snapshot)))\n\tsb.WriteString(t.String())\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Registers\\n\\n\")\n\tsb.WriteString(renderRegisters(inst))\n\n\tsb.WriteString(\"## Output\\n\\n\")\n\tif len(inst.Output) == 0 {\n\t\tsb.WriteString(ui.Empty(\"Nothing written yet.\"))\n\t} else {\n\t\tsb.WriteString(\"```\\n\" + printable(inst.Output, MaxOutput) + \"\\n```\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Image\\n\\n```\\n\" + hexDump(inst.Program, 64) + \"\\n```\\n\\n\")\n\n\tif inst.Status == vmkit.Running {\n\t\tsb.WriteString(ui.Action(\"Run 25000 instructions\", \"Step\", \"id\", id, \"fuel\", \"25000\"))\n\t\tsb.WriteString(\" · \")\n\t\tsb.WriteString(ui.Action(\"Run 100000 instructions\", \"Step\", \"id\", id, \"fuel\", \"100000\"))\n\t\tsb.WriteString(\"\\n\")\n\t} else {\n\t\tsb.WriteString(\"This instance is **\" + inst.Status.String() + \"** and cannot be stepped again.\\n\")\n\t}\n\treturn sb.String()\n}\n\n// renderRegisters restores the snapshot to read the register file out of it.\n// The hart is not kept between transactions, only its snapshot is, so this is\n// the only place the state is legible, and it is the thing worth seeing: a\n// program that wrote nothing still computed something.\nfunc renderRegisters(inst *vmkit.Instance) string {\n\tif len(inst.Snapshot) == 0 {\n\t\treturn ui.Empty(\"Not started yet: no snapshot to read.\") + \"\\n\\n\"\n\t}\n\tvar m riscv.Machine\n\tif err := m.Restore(inst.Snapshot); err != nil {\n\t\treturn ui.Empty(\"The snapshot could not be read.\") + \"\\n\\n\"\n\t}\n\treg := m.Registers()\n\n\tvar sb strings.Builder\n\tt := ui.NewTable(\"register\", \"hex\", \"unsigned\", \"signed\")\n\tt.Row(\"pc\", ufmt.Sprintf(\"0x%08X\", m.PC()), \"\", \"\")\n\tshown := 0\n\tfor i := 1; i \u003c 32; i++ {\n\t\tif reg[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt.Row(\n\t\t\tregNames[i],\n\t\t\tufmt.Sprintf(\"0x%08X\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", int64(int32(reg[i]))),\n\t\t)\n\t\tshown++\n\t}\n\tsb.WriteString(t.String())\n\tif shown == 0 {\n\t\tsb.WriteString(\"\\nEvery register except `pc` is zero.\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\treturn sb.String()\n}\n\nfunc fuelText(n int64) string {\n\tif n == vmkit.Unmetered {\n\t\treturn \"unmetered\"\n\t}\n\treturn ufmt.Sprintf(\"%d\", n)\n}\n\nconst hexDigits = \"0123456789abcdef\"\n\n// hexDump shows the image as words, which is how anyone reading RV32 reads it.\nfunc hexDump(b []byte, max int) string {\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor i := 0; i+3 \u003c len(b); i += 4 {\n\t\tif i \u003e 0 \u0026\u0026 i%16 == 0 {\n\t\t\tsb.WriteString(\"\\n\")\n\t\t} else if i \u003e 0 {\n\t\t\tsb.WriteString(\" \")\n\t\t}\n\t\tw := uint32(b[i]) | uint32(b[i+1])\u003c\u003c8 | uint32(b[i+2])\u003c\u003c16 | uint32(b[i+3])\u003c\u003c24\n\t\tsb.WriteString(ufmt.Sprintf(\"%08x\", w))\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"\\n...\")\n\t}\n\treturn sb.String()\n}\n\n// printable renders guest output for a code fence: printable ASCII as itself,\n// everything else as an escape. A guest writes arbitrary bytes, so this is the\n// only form of it that is safe to show.\nfunc printable(b []byte, max int) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor _, c := range b {\n\t\tswitch {\n\t\tcase c == '\\n':\n\t\t\tsb.WriteString(\"\\\\n\")\n\t\tcase c == '\\t':\n\t\t\tsb.WriteString(\"\\\\t\")\n\t\tcase c == '\\\\':\n\t\t\tsb.WriteString(\"\\\\\\\\\")\n\t\tcase c == '`':\n\t\t\tsb.WriteString(\"\\\\x60\")\n\t\tcase c \u003e= 0x20 \u0026\u0026 c \u003c 0x7f:\n\t\t\tsb.WriteByte(c)\n\t\tdefault:\n\t\t\tsb.WriteString(\"\\\\x\")\n\t\t\tsb.WriteByte(hexDigits[c\u003e\u003e4])\n\t\t\tsb.WriteByte(hexDigits[c\u00260x0f])\n\t\t}\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"…\")\n\t}\n\treturn sb.String()\n}\n"},{"name":"riscvdemo.gno","body":"// Package riscvdemo runs real compiled machine code on chain, a slice at a\n// time.\n//\n// It is a demo of two libraries and carries no logic of its own:\n// [p/moul/x/vm/riscv](/p/moul/x/vm/riscv/v0) is the RV32IM hart, and\n// [p/moul/x/vm/vmkit](/p/moul/x/vm/vmkit/v0) is the host ABI, the fuel meter\n// and the instance store.\n//\n// What it exists to show is that the guest was not written for gno. The\n// programs on the front page are flat .text images: the same bytes\n// `rustc --target riscv32im-unknown-none-elf` emits, uploaded as hex. The\n// realm holds the snapshot between transactions, so one computation finishes\n// across several of them, and realm code cannot do that for itself.\npackage riscvdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Caps. Everything a caller can grow is bounded, because all of it is storage\n// somebody pays a deposit on.\nconst (\n\t// MaxInstances is how many programs the realm keeps at once.\n\tMaxInstances = 64\n\t// MaxImage caps an uploaded text segment at 2,048 instructions.\n\t//\n\t// This one is not arbitrary. Predecoding costs about 19,600 gas per word\n\t// and is redone on every resume, so the image size is a tax on every\n\t// transaction that touches the instance, not just the upload. 8 KiB works\n\t// out to roughly 40M gas per slice before the guest executes anything,\n\t// which is about 1% of a block.\n\tMaxImage = 8192\n\t// MaxOutput caps the bytes one program may write. Past it the guest is\n\t// trapped rather than truncated, so rendered output is never a lie.\n\tMaxOutput = 4096\n\t// MaxInput caps the call input a program can be given.\n\tMaxInput = 1024\n\t// DefaultFuel is the budget an upload gets when it asks for none, and the\n\t// slice size Step uses when asked for none.\n\tDefaultFuel = 100000\n\t// MaxSliceFuel bounds one transaction's work regardless of what the\n\t// caller asked for, and it is derived from the measurement rather than\n\t// picked: an RV32IM instruction costs about 8,500 gas, so 100,000 of them\n\t// is about 850M, a little under a third of a 3G block. Twice this would\n\t// still be a legal transaction and a rude one, and it would leave no room\n\t// for the predecode and the realm's own storage writes on top.\n\tMaxSliceFuel = 100000\n)\n\nvar (\n\tstore  = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen  seqid.ID\n\tcount  int\n)\n\n// host is the realm-backed [vmkit.Host]. One is built per call, wrapping the\n// instance being stepped, so a guest's output and authority are scoped to it\n// and nothing ambient leaks in.\ntype host struct {\n\tinst    *vmkit.Instance\n\tin      []byte\n\tkv      *avl.Tree\n\toverrun bool // the guest wrote past MaxOutput\n}\n\nfunc (h *host) Caller() address { return h.inst.Owner }\nfunc (h *host) Origin() address { return h.inst.Owner }\nfunc (h *host) Now() int64      { return time.Now().Unix() }\nfunc (h *host) Height() int64   { return runtime.ChainHeight() }\nfunc (h *host) Input() []byte   { return h.in }\n\n// Get and Set are scoped to the instance by construction: the tree belongs to\n// the instance being stepped, so one program cannot reach another's storage\n// even though both live in this one realm.\nfunc (h *host) Get(key []byte) []byte {\n\tv := h.kv.Get(string(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.([]byte)\n}\n\nfunc (h *host) Set(key, val []byte) { h.kv.Set(string(key), val) }\n\nfunc (h *host) Output(p []byte) {\n\tif len(h.inst.Output)+len(p) \u003e MaxOutput {\n\t\th.overrun = true\n\t\treturn\n\t}\n\th.inst.Output = append(h.inst.Output, p...)\n}\n\nfunc (h *host) Emit(typ string, kv ...string) { chain.Emit(typ, kv...) }\n\n// Send is never granted here. The demo funds no instance, so a guest that\n// tries to move coins is refused. That is the capability rule doing its job,\n// not a missing feature.\nfunc (h *host) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\n\nfunc (h *host) Log(msg string) {}\n\n// Upload stores a hex-encoded text image as a new instance and returns its id.\n//\n// The image is loaded here rather than at the first Step, so a misaligned or\n// oversized one is rejected by the transaction that submitted it instead of\n// costing somebody else the gas later.\nfunc Upload(cur realm, hexImage, input string, budget int64) string {\n\timg, ok := decodeHex(hexImage)\n\tif !ok {\n\t\tpanic(\"riscvdemo: image is not valid hex\")\n\t}\n\treturn upload(img, input, budget)\n}\n\n// UploadSample stores one of the programs the front page offers. Writing RV32IM\n// by hand is not the point of this realm, and without this nobody without a\n// cross compiler could press a button.\nfunc UploadSample(cur realm, name, input string, budget int64) string {\n\ts := sampleByName(name)\n\tif s == nil {\n\t\tpanic(\"riscvdemo: no such sample\")\n\t}\n\t// A sample carries its own budget because the default is a total, not a\n\t// slice: the heavy loop needs 200,006 instructions, and offering a button\n\t// that runs out of fuel halfway is a worse demo than no button.\n\tif budget \u003c= 0 {\n\t\tbudget = s.budget\n\t}\n\treturn upload(s.image(), input, budget)\n}\n\nfunc upload(img []byte, input string, budget int64) string {\n\tif count \u003e= MaxInstances {\n\t\tpanic(\"riscvdemo: too many instances, remove one first\")\n\t}\n\tif len(input) \u003e MaxInput {\n\t\tpanic(\"riscvdemo: input too long\")\n\t}\n\tif len(img) == 0 {\n\t\tpanic(\"riscvdemo: empty image\")\n\t}\n\tif len(img) \u003e MaxImage {\n\t\tpanic(\"riscvdemo: image too large\")\n\t}\n\t// Loading it now is the validation: NewMachine is what rejects an image\n\t// that is not a whole number of instructions.\n\tif _, err := riscv.NewMachine(img, riscv.DefaultEntry); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif budget \u003c= 0 {\n\t\tbudget = DefaultFuel\n\t}\n\n\tid := idgen.Next().String()\n\towner := unsafe.PreviousRealm().Address()\n\tstore.Set(vmkit.NewInstance(id, owner, riscv.VMName, img, budget))\n\tif input != \"\" {\n\t\tinputs.Set(id, input)\n\t}\n\tcount++\n\n\tchain.Emit(\"riscv_upload\", \"id\", id, \"bytes\", ufmt.Sprintf(\"%d\", len(img)))\n\treturn id\n}\n\n// Step runs one slice of the instance: up to `fuel` guest instructions, then\n// stop and keep the snapshot. Anyone may pay for a slice, not only the owner:\n// a paused program that only its owner can advance is a worse demo and no\n// safer, since the program and its budget were both fixed at upload.\nfunc Step(cur realm, id string, fuel int64) string {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Status != vmkit.Running {\n\t\tpanic(\"riscvdemo: instance is \" + inst.Status.String())\n\t}\n\tif fuel \u003c= 0 {\n\t\tfuel = DefaultFuel\n\t}\n\tif fuel \u003e MaxSliceFuel {\n\t\tfuel = MaxSliceFuel\n\t}\n\n\tm, err := riscv.NewMachine(inst.Program, riscv.DefaultEntry)\n\tif err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\th := \u0026host{inst: inst, in: []byte(inputOf(id)), kv: avl.NewTree()}\n\tif err := inst.Run(m, h, fuel); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif h.overrun {\n\t\tinst.Status = vmkit.Trapped\n\t\tinst.Trap = \"output limit reached\"\n\t}\n\n\tchain.Emit(\"riscv_step\",\n\t\t\"id\", id,\n\t\t\"status\", inst.Status.String(),\n\t\t\"fuel\", ufmt.Sprintf(\"%d\", inst.FuelUsed),\n\t)\n\treturn inst.Status.String()\n}\n\n// Remove deletes an instance. Owner only.\nfunc Remove(cur realm, id string) {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Owner != unsafe.PreviousRealm().Address() {\n\t\tpanic(\"riscvdemo: not your instance\")\n\t}\n\tstore.Remove(id)\n\tinputs.Remove(id)\n\tcount--\n}\n\nfunc inputOf(id string) string {\n\tv := inputs.Get(id)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n\n// decodeHex accepts the output of any hexdump: an even number of hex digits,\n// with an optional 0x prefix, and whitespace anywhere. Whitespace is allowed\n// because that is what a pasted hexdump has in it; anything else is refused,\n// because a silently mangled image would trap somewhere unrelated later.\nfunc decodeHex(s string) ([]byte, bool) {\n\tif len(s) \u003e= 2 \u0026\u0026 s[0] == '0' \u0026\u0026 (s[1] == 'x' || s[1] == 'X') {\n\t\ts = s[2:]\n\t}\n\tdigits := make([]byte, 0, len(s))\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == ' ' || c == '\\t' || c == '\\n' || c == '\\r' {\n\t\t\tcontinue\n\t\t}\n\t\tv, ok := hexVal(c)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tdigits = append(digits, v)\n\t}\n\tif len(digits) == 0 || len(digits)%2 != 0 {\n\t\treturn nil, false\n\t}\n\tout := make([]byte, len(digits)/2)\n\tfor i := 0; i \u003c len(out); i++ {\n\t\tout[i] = digits[i*2]\u003c\u003c4 | digits[i*2+1]\n\t}\n\treturn out, true\n}\n\nfunc hexVal(c byte) (byte, bool) {\n\tswitch {\n\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn c - '0', true\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'f':\n\t\treturn c - 'a' + 10, true\n\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'F':\n\t\treturn c - 'A' + 10, true\n\t}\n\treturn 0, false\n}\n"},{"name":"riscvdemo_test.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// resetState puts the realm globals back where init() left them. Realm state\n// persists for the whole test binary, so every test that asserts on ids or on\n// the rendered instance list has to start from here.\nfunc resetState() {\n\tstore = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen = seqid.ID(0)\n\tcount = 0\n}\n\nfunc alice() address { return testutils.TestAddress(\"alice\") }\n\nfunc TestUploadAndRunToCompletion(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"hello\", \"\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"Hello, gno.land\\n\", string(inst.Output))\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, alice(), inst.Owner)\n\tuassert.Equal(t, \"riscv32im\", inst.VM)\n}\n\n// Every sample on the front page has to reach its documented answer, or the\n// page offers a button that traps when pressed. The words are assembled\n// outside this repo, so this is the test that catches a mistyped one.\nfunc TestEverySampleReachesItsAnswer(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tcases := []struct {\n\t\tslug   string\n\t\treg    int\n\t\twant   uint32\n\t\toutput string\n\t}{\n\t\t{\"hello\", 0, 0, \"Hello, gno.land\\n\"},\n\t\t{\"sum100\", 5, 5050, \"\"},\n\t\t{\"heavy\", 5, 1250025000, \"\"},\n\t\t{\"mext\", 5, 3000000021, \"\"},\n\t\t{\"clang\", 0, 0, \"fb7ffba0\"},\n\t\t{\"ledger\", 0, 0, \"alice 70\\nbob 80\\n\"},\n\t}\n\tfor _, c := range cases {\n\t\tid := UploadSample(cross(cur), c.slug, sampleByName(c.slug).input, 0)\n\t\tstatus := \"\"\n\t\tfor i := 0; i \u003c 20; i++ {\n\t\t\tstatus = Step(cross(cur), id, 0)\n\t\t\tif status != \"running\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tuassert.Equal(t, \"halted\", status, c.slug+\" must halt\")\n\t\tinst := store.Get(id)\n\t\tuassert.Equal(t, c.output, string(inst.Output), c.slug+\" output\")\n\t\tif c.reg != 0 {\n\t\t\tvar m riscv.Machine\n\t\t\tuassert.NoError(t, m.Restore(inst.Snapshot))\n\t\t\tuassert.Equal(t, uint64(c.want), uint64(m.Registers()[c.reg]), c.slug+\" result\")\n\t\t}\n\t}\n}\n\n// TestOneProgramAcrossManyTransactions is what the realm exists to\n// demonstrate: the same computation, finished over several calls, each paying\n// for its own slice.\nfunc TestOneProgramAcrossManyTransactions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"heavy\", \"\", 0)\n\tstatus := \"\"\n\tfor i := 0; i \u003c 50; i++ {\n\t\tstatus = Step(cross(cur), id, 80000)\n\t\tif status != \"running\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"halted\", status)\n\tuassert.True(t, inst.Slices \u003e 1, \"a 200k instruction program must not finish in one slice\")\n\tuassert.Equal(t, int64(200006), inst.FuelUsed)\n}\n\nfunc TestUploadTakesHex(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// addi a7, zero, 93 ; ecall\n\tid := Upload(cross(cur), \"0x9308d005 73000000\", \"\", 0)\n\t_ = id\n}\n\nfunc TestUploadRejectsBadImages(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// Called without cross(): a panic raised through a crossing call cannot be\n\t// recovered, so uassert would never see it.\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"zzzz\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"abc\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: no such sample\", func() {\n\t\tUploadSample(cur, \"nope\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"riscvdemo: riscv: image length is not a whole number of instructions\",\n\t\tfunc() { Upload(cur, \"0011\", \"\", 0) })\n}\n\nfunc TestDecodeHex(t *testing.T) {\n\tb, ok := decodeHex(\"0xDEADbeef\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\tuassert.Equal(t, uint64(0xDE), uint64(b[0]))\n\tuassert.Equal(t, uint64(0xEF), uint64(b[3]))\n\n\t_, ok = decodeHex(\"\")\n\tuassert.False(t, ok)\n\t_, ok = decodeHex(\"0x\")\n\tuassert.False(t, ok)\n\t// Whitespace is skipped, because a pasted hexdump has it.\n\tb, ok = decodeHex(\"00 11\\n22\\t33\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\t// An odd number of digits is still a refusal, whitespace or not.\n\t_, ok = decodeHex(\"00 1\")\n\tuassert.False(t, ok)\n}\n\nfunc TestRenderHomeOffersEverySample(cur realm, t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"RV32IM, on chain\"), \"the title\")\n\tfor _, s := range samples {\n\t\tuassert.True(t, strings.Contains(out, s.name), \"home must offer \"+s.slug)\n\t}\n\tuassert.True(t, strings.Contains(out, \"No instances yet\"), \"the empty state\")\n}\n\n// The register file is the interesting half of this VM: a program that writes\n// nothing still computed something, and the snapshot is the only place it is\n// legible between transactions.\nfunc TestRenderInstanceShowsTheRegisterFile(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"sum100\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"/\" + id)\n\tuassert.True(t, strings.Contains(out, \"## Registers\"), \"the section\")\n\tuassert.True(t, strings.Contains(out, \"5050\"), \"t0 must show the answer\")\n\tuassert.True(t, strings.Contains(out, \"halted\"), \"the status\")\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tuassert.True(t, strings.Contains(Render(\"/nope\"), \"No such instance\"))\n}\n\n// ExampleRender pins the realm's output for a path whose content cannot drift\n// with the instance list. The home page and the instance page both produce\n// consecutive blank lines, which an example block cannot represent, so they\n// are asserted in the tests above instead.\nfunc ExampleRender() {\n\tprint(Render(\"/missing\"))\n\t// Output:\n\t// # Instance missing\n\t//\n\t// [← all instances](/r/moul/x/vm/riscvdemo/v0)\n\t//\n\t// **No such instance.** It was never uploaded, or its owner removed it.\n}\n"},{"name":"samples.gno","body":"package riscvdemo\n\nimport \"gno.land/p/moul/x/vm/riscv/v0\"\n\n// The programs the front page offers, as the machine words a cross compiler\n// would have emitted. They are assembled outside this repo and pinned here,\n// and riscvdemo_test.gno runs every one of them to the expected answer, so a\n// wrong word is a failing test rather than a page that traps when clicked.\ntype sample struct {\n\tslug   string // what UploadSample takes: short, no punctuation, stable\n\tname   string\n\tbudget int64 // the instance's total instruction budget, not the slice\n\n\t// builtin names an image the library ships compiled, instead of the words\n\t// below. Empty means the words are the program.\n\tbuiltin string\n\twords []uint32\n\tinput string\n\tnote  string\n\tasm   string\n}\n\nvar samples = []sample{\n\t{\n\t\tslug: \"hello\",\n\t\tname: \"Hello, gno.land\",\n\t\twords: []uint32{\n\t\t\t0x00100513, 0x000015B7, 0x02058593, 0x01000613,\n\t\t\t0x04000893, 0x00000073, 0x05D00893, 0x00000073,\n\t\t\t0x6C6C6548, 0x67202C6F, 0x6C2E6F6E, 0x0A646E61,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"Eight instructions and a string constant. The write syscall reads \" +\n\t\t\t\"the bytes straight out of the text segment and hands them to Host.Output.\",\n\t\tasm: `addi a0, zero, 1          # fd\nlui  a1, 0x1000           # buf\naddi a1, a1, 0x20\naddi a2, zero, 16         # len\naddi a7, zero, 64         # write\necall\naddi a7, zero, 93         # exit\necall\n.ascii \"Hello, gno.land\\n\"`,\n\t},\n\t{\n\t\tslug: \"sum100\",\n\t\tname: \"Sum 1 to 100\",\n\t\twords: []uint32{\n\t\t\t0x06400413, 0x00000293, 0x00000313, 0x00130313,\n\t\t\t0x006282B3, 0xFE831CE3, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"A real loop, 303 instructions. Writes nothing: the answer is in t0, \" +\n\t\t\t\"and the instance page shows the register file.\",\n\t\tasm: `addi s0, zero, 100\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"heavy\",\n\t\tname: \"Heavy loop\",\n\t\twords: []uint32{\n\t\t\t0x0000C437, 0x35040413, 0x00000293, 0x00000313,\n\t\t\t0x00130313, 0x006282B3, 0x00000393, 0xFE831AE3,\n\t\t\t0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 250000,\n\t\tnote: \"200,006 instructions, four per iteration. At the largest slice this realm \" +\n\t\t\t\"allows it takes three transactions to finish, which is the thing it exists to show.\",\n\t\tasm: `lui  s0, 0xc000           # s0 = 50000\naddi s0, s0, 0x350\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\naddi t2, zero, 0\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"mext\",\n\t\tname: \"Multiply and divide\",\n\t\twords: []uint32{\n\t\t\t0x3B9AD2B7, 0xA0728293, 0x00300313, 0x026282B3,\n\t\t\t0x00700393, 0x0272D333, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"The M extension. t0 = 1000000007 * 3 truncated to 32 bits, then t1 = t0 / 7. \" +\n\t\t\t\"Division by zero and the one signed overflow case return values here \" +\n\t\t\t\"rather than trapping, which is what the spec says and what a chain needs.\",\n\t\tasm: `lui  t0, 0x3b9ad000       # t0 = 1000000007\naddi t0, t0, -1529\naddi t1, zero, 3\nmul  t0, t0, t1\naddi t2, zero, 7\ndivu t1, t0, t2\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug:   \"clang\",\n\t\tname:   \"Compiled by clang\",\n\t\tinput:  \"gno.land\",\n\t\tbudget: 20000,\n\t\tnote: \"Not written for gno and not written by hand: a freestanding C program, \" +\n\t\t\t\"compiled by clang for riscv32im and shipped as the bytes LLVM emitted. It reads \" +\n\t\t\t\"the call input, hashes it with FNV-1a and writes eight hex digits back. \" +\n\t\t\t\"With the default input it prints fb7ffba0. Source and build command: \" +\n\t\t\t\"tools/riscv-guests/fnv.\",\n\t\tbuiltin: \"fnv\",\n\t\tasm: `long n = syscall3(SYS_READ, 0, (long)in, sizeof(in));\n\nunsigned int h = 2166136261u;\nfor (long i = 0; i \u003c n; i++) {\n\th ^= in[i];\n\th *= 16777619u;      /* the reason this is rv32im */\n}\n\nfor (int i = 0; i \u003c 8; i++) {\n\tunsigned int nib = (h \u003e\u003e (28 - i * 4)) \u0026 0xF;\n\tout[i] = nib \u003c 10 ? '0' + nib : 'a' + (nib - 10);\n}\n\nsyscall3(SYS_WRITE, 1, (long)out, 8);\nsyscall3(SYS_EXIT, 0, 0, 0);`,\n\t},\n\t{\n\t\tslug:   \"ledger\",\n\t\tname:   \"A token, in Rust\",\n\t\tinput:  \"mint alice 100\\nmint bob 50\\nsend alice bob 30\\n\",\n\t\tbudget: 20000,\n\t\tnote: \"no_std Rust, compiled by rustc for riscv32im: mint, send and burn, applied \" +\n\t\t\t\"from the call input. It links Rust's real core and compiler_builtins, so the \" +\n\t\t\t\"balances being 64-bit means a divide runs __udivdi3 here, because RV32 has no \" +\n\t\t\t\"64-bit divide instruction. With the default input it prints alice 70 and bob 80. \" +\n\t\t\t\"Source: tools/riscv-guests/ledger.\",\n\t\tbuiltin: \"ledger\",\n\t\tasm: `match cmd {\n\tb\"send\" =\u003e {\n\t\tlet (from, rest) = field(rest);\n\t\tlet (to, rest) = field(rest);\n\t\tlet (amount, _) = field(rest);\n\t\tlet n = parse_u32(amount).ok_or(\"bad amount\")?;\n\t\tlet fi = led.find(from).ok_or(\"unknown sender\")?;\n\t\tif led.balances[fi] \u003c n {\n\t\t\treturn Err(\"insufficient balance\");\n\t\t}\n\t\tlet ti = led.intern(to).ok_or(\"ledger full or bad name\")?;\n\t\tled.balances[fi] -= n;\n\t\tled.balances[ti] += n;\n\t\tOk(())\n\t}\n\t_ =\u003e Err(\"unknown command\"),\n}`,\n\t},\n}\n\n// image is what gets uploaded: either the words assembled here, or a program\n// the library ships because a compiler produced it.\nfunc (s *sample) image() []byte {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn riscv.GuestFNV()\n\tcase \"ledger\":\n\t\treturn riscv.GuestLedger()\n\t}\n\treturn riscv.Image(s.words)\n}\n\n// lang is the fence tag for what the sample shows. The compiled guest shows\n// its C, because showing a disassembly of what LLVM did with it would bury the\n// only interesting fact: nobody wrote the machine code.\nfunc (s *sample) lang() string {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn \"c\"\n\tcase \"ledger\":\n\t\treturn \"rust\"\n\t}\n\treturn \"asm\"\n}\n\nfunc sampleByName(slug string) *sample {\n\tfor i := range samples {\n\t\tif samples[i].slug == slug {\n\t\t\treturn \u0026samples[i]\n\t\t}\n\t}\n\treturn nil\n}\n"}]},"send":"","max_deposit":"14000000ugnot"}],"fee":{"gas_wanted":"163770800","gas_fee":"491312ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"0ty3HzCJSeY7nU2qEAwgpoYgQdf2VXKFXlClqf6uAFwXx5Bm03RHRFMVO3Y8ZwfyKgwefbIRZ8dwSjiEUTqSMg=="}],"memo":""},"metadata":{"timestamp":"1790961818"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wesh","path":"gno.land/r/moul/x/wesh/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/wesh/v0`\n\n**An on-chain directory and device sigchain for Wesh protocol (weshnet / Berty)\nidentities**, built on [`p/moul/x/wesh`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/wesh/v0).\n\n```\ngnokey maketx call -pkgpath gno.land/r/moul/x/wesh/v0 -func Register \\\n  -args alice -args \u003caccountPK hex\u003e -args \u003cseed hex\u003e -args \"Alice\" -args \u003csig hex\u003e\n```\n\n`Render` then emits a link a Berty client can actually open:\n\n```\nhttps://berty.tech/id#contact/oZBLFpzghxrATkepWvDPNX9pHYqi6BWgP45x…/name=Alice\n```\n\n## What it is for\n\nWesh is peer-to-peer and end-to-end encrypted, and it has three gaps that only\nan authenticated, ordered, publicly auditable record can close:\n\n1. **Resolution.** A Berty identity travels out of band and cannot be looked up.\n   Here a name resolves to a contact, and the realm renders the real link.\n2. **Rotation with a paper trail.** Resetting the rendezvous seed silently kills\n   every link ever shared. Here every rotation is numbered, signed and kept, so\n   a stale link is recognisably stale rather than merely dead.\n3. **Device revocation.** Wesh cannot revoke a device at all. This realm hosts\n   the missing log: hash-chained, account-signed, and verified on chain with\n   `crypto/ed25519` before an entry is accepted.\n\n## API\n\n| call | what it does |\n|---|---|\n| `Register(cur, name, accountPK, seed, displayName, sig)` | claim a name, publishing the rendezvous seed |\n| `RegisterCommitted(cur, name, accountPK, commitment, displayName, sig)` | claim a name, publishing only `H(seed ‖ salt)` |\n| `Rotate(cur, payload, sig)` | publish a new seed/commitment at `revision+1` |\n| `AppendDevice(cur, prev, op, devicePK, sig)` | append `add` or `revoke` to the sigchain |\n| `SetDisplayName(cur, name)` · `Release(cur)` | update the label · free the name |\n| `Resolve` · `Link` · `RendezvousPointAt` · `DeviceStatus` · `SigchainHead` · `NameOf` · `Count` | read-only, for gnoweb and other realms |\n\n## Authentication\n\nEvery state-changing call carries an **ed25519 signature made with the Wesh\naccount key**, over a canonical statement naming the kind, the chain id, the\ncaller's gno address, and a monotonic revision or sequence number. Each field is\nthere to stop one attack:\n\n- without the **kind**, a binding signature could be replayed as a device one;\n- without the **chain id**, a testnet binding replays on mainnet;\n- without the **gno address**, anyone could publish someone else's account key\n  next to a seed they control and harvest the contact requests;\n- without the **revision / sequence**, a superseded statement could roll a\n  rotation back or fork the sigchain.\n\nAll five are covered by a negative test apiece.\n\n## What it never stores\n\nNo group secret, no device chain key, no message key, no ciphertext: the\nlibrary it is built on has no type that can hold one. And it does not pretend to\n*enforce* revocation inside weshnet: a revoked device's ratchets are already\ndistributed. What revocation buys here is that it becomes public, ordered and\nattributable, which is strictly more than weshnet has today.\n\n## Publishing is opt-in exposure\n\nA published seed lets anyone derive the account's rotating rendezvous point.\nThat is the right trade for a support line, a shop or a public channel, and the\nwrong one for a private account, which is what `RegisterCommitted` is for.\n\n**Library:** [`p/moul/x/wesh`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/wesh/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/wesh/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wesh/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/wesh/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wesh/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/wesh/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wesh/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/wesh/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wesh/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/wesh/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/wesh/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/wesh/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render.gno","body":"package wesh\n\nimport (\n\t\"chain/runtime\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/wesh/v0\"\n)\n\n// Render serves the directory index at \"\" and one identity card at \"\u003cname\u003e\".\n//\n// The index deliberately does not compute a Berty link per row: base58 over a\n// 70-byte payload is big-integer work, and it belongs on the page that a human\n// actually asked for.\nfunc Render(path string) string {\n\tpath = strings.Trim(path, \"/\")\n\tif path == \"\" {\n\t\treturn renderIndex()\n\t}\n\treturn renderIdentity(path)\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Wesh directory\\n\\n\")\n\tb.WriteString(\"Resolvable, self-signed [Wesh protocol](https://berty.tech/docs/protocol/) \")\n\tb.WriteString(\"identities, on top of [`p/moul/x/wesh`](/p/moul/x/wesh/v0).\\n\\n\")\n\tb.WriteString(\"A Berty identity normally travels out of band as a QR code, cannot be \")\n\tb.WriteString(\"looked up, cannot announce a seed rotation, and can never revoke a device. \")\n\tb.WriteString(\"This realm addresses those three, and stores no secret of any kind.\\n\\n\")\n\n\tif byName.Size() == 0 {\n\t\tb.WriteString(\"_No identity registered yet._\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| name | owner | rev | mode | devices |\\n\")\n\tb.WriteString(\"|---|---|---|---|---|\\n\")\n\tbyName.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tid := value.(*identity)\n\t\tb.WriteString(\"| [\" + id.name + \"](/r/moul/x/wesh/v0:\" + id.name + \") \")\n\t\tb.WriteString(\"| `\" + id.owner.String() + \"` \")\n\t\tb.WriteString(\"| \" + strconv.Itoa(id.revision) + \" \")\n\t\tb.WriteString(\"| \" + modeLabel(id) + \" \")\n\t\tb.WriteString(\"| \" + strconv.Itoa(activeDevices(id)) + \" active / \" + strconv.Itoa(len(id.devices)) + \" entries |\\n\")\n\t\treturn false\n\t})\n\tn := byName.Size()\n\tif n == 1 {\n\t\tb.WriteString(\"\\n1 identity.\\n\")\n\t} else {\n\t\tb.WriteString(\"\\n\" + strconv.Itoa(n) + \" identities.\\n\")\n\t}\n\treturn b.String()\n}\n\nfunc renderIdentity(name string) string {\n\tid := lookup(name)\n\tif id == nil {\n\t\treturn \"# Not found\\n\\nNo identity named `\" + name + \"`. [Back to the directory](/r/moul/x/wesh/v0).\\n\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + id.name + \"\\n\\n\")\n\tif id.displayName != \"\" {\n\t\tb.WriteString(\"_\" + id.displayName + \"_\\n\\n\")\n\t}\n\tb.WriteString(\"| field | value |\\n|---|---|\\n\")\n\tb.WriteString(\"| owner | `\" + id.owner.String() + \"` |\\n\")\n\tb.WriteString(\"| account key | `\" + hex.EncodeToString(id.accountPK) + \"` |\\n\")\n\tb.WriteString(\"| mode | \" + modeLabel(id) + \" |\\n\")\n\tb.WriteString(\"| revision | \" + strconv.Itoa(id.revision) + \" |\\n\")\n\tb.WriteString(\"| registered | block \" + strconv.FormatInt(id.history[0].height, 10) + \" |\\n\")\n\n\tb.WriteString(\"\\n## Contact\\n\\n\")\n\tif id.committed {\n\t\tb.WriteString(\"This identity publishes a **commitment**, `\")\n\t\tb.WriteString(hex.EncodeToString(id.payload))\n\t\tb.WriteString(\"`, not its rendezvous seed.\\n\\n\")\n\t\tb.WriteString(\"The chain attests that this account key claimed that commitment from \")\n\t\tb.WriteString(\"that gno address. The seed itself is shared out of band, and whoever \")\n\t\tb.WriteString(\"receives it can check it here with `H(seed || salt)` before using it. \")\n\t\tb.WriteString(\"The rendezvous point stays off chain.\\n\")\n\t} else {\n\t\tlink, err := contactOf(id).WebLink()\n\t\tif err != nil {\n\t\t\tb.WriteString(\"_Contact is unrenderable: \" + err.Error() + \"_\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"Scan or open this in Berty to send a contact request:\\n\\n\")\n\t\t\tb.WriteString(\"```\\n\" + link + \"\\n```\\n\\n\")\n\t\t\tb.WriteString(\"| field | value |\\n|---|---|\\n\")\n\t\t\tb.WriteString(\"| rendezvous seed | `\" + hex.EncodeToString(id.payload) + \"` |\\n\")\n\t\t\tnow := time.Now().Unix()\n\t\t\tperiod := wesh.RoundPeriod(now, wesh.DefaultRotationInterval)\n\t\t\tpoint, _ := contactOf(id).RendezvousPointAt(now, wesh.DefaultRotationInterval)\n\t\t\tb.WriteString(\"| rendezvous point, period \" + strconv.FormatInt(period, 10) + \" | `\" + hex.EncodeToString(point) + \"` |\\n\")\n\t\t\tb.WriteString(\"\\nThe point is `HMAC-SHA256(accountPK || seed, be64(period))`, derived \")\n\t\t\tb.WriteString(\"exactly as weshnet derives it, and it rotates every 24h. Anyone can \")\n\t\t\tb.WriteString(\"recompute it and check the DHT, so this entry is verifiable rather \")\n\t\t\tb.WriteString(\"than merely asserted.\\n\")\n\t\t}\n\t}\n\n\tb.WriteString(\"\\n## Devices\\n\\n\")\n\tif len(id.devices) == 0 {\n\t\tb.WriteString(\"No sigchain entry yet. Head is the genesis digest `\")\n\t\tb.WriteString(hex.EncodeToString(id.head) + \"`.\\n\")\n\t} else {\n\t\tb.WriteString(\"Every entry below was signed by the account key and verified on chain, \")\n\t\tb.WriteString(\"and chains to the digest of the one before it.\\n\\n\")\n\t\tb.WriteString(\"| seq | op | device | block | digest |\\n|---|---|---|---|---|\\n\")\n\t\tfor _, e := range id.devices {\n\t\t\tb.WriteString(\"| \" + strconv.Itoa(e.seq) + \" \")\n\t\t\tb.WriteString(\"| \" + e.op + \" \")\n\t\t\tb.WriteString(\"| `\" + short(hex.EncodeToString(e.devicePK)) + \"` \")\n\t\t\tb.WriteString(\"| \" + strconv.FormatInt(e.height, 10) + \" \")\n\t\t\tb.WriteString(\"| `\" + short(hex.EncodeToString(e.digest)) + \"` |\\n\")\n\t\t}\n\t\tb.WriteString(\"\\nHead: `\" + hex.EncodeToString(id.head) + \"`\\n\")\n\t}\n\n\tif len(id.history) \u003e 1 {\n\t\tb.WriteString(\"\\n## Rotation history\\n\\n\")\n\t\tb.WriteString(\"Weshnet has no way to announce that a seed was reset, so every link \")\n\t\tb.WriteString(\"ever shared dies silently. These are the superseded values, kept so a \")\n\t\tb.WriteString(\"stale link can be recognised as stale.\\n\\n\")\n\t\tb.WriteString(\"| rev | value | block |\\n|---|---|---|\\n\")\n\t\tfor _, r := range id.history {\n\t\t\tmark := \"\"\n\t\t\tif r.revision == id.revision {\n\t\t\t\tmark = \" (current)\"\n\t\t\t}\n\t\t\tb.WriteString(\"| \" + strconv.Itoa(r.revision) + mark + \" \")\n\t\t\tb.WriteString(\"| `\" + short(hex.EncodeToString(r.payload)) + \"` \")\n\t\t\tb.WriteString(\"| \" + strconv.FormatInt(r.height, 10) + \" |\\n\")\n\t\t}\n\t}\n\n\tb.WriteString(\"\\n[Back to the directory](/r/moul/x/wesh/v0) · chain `\" + runtime.ChainID() + \"`\\n\")\n\treturn b.String()\n}\n\nfunc modeLabel(id *identity) string {\n\tif id.committed {\n\t\treturn \"committed\"\n\t}\n\treturn \"published\"\n}\n\n// activeDevices counts the distinct devices whose latest sigchain entry is an\n// add. A device can be added, revoked and added again, so only the last entry\n// for each key decides.\nfunc activeDevices(id *identity) int {\n\tseen := []string{}\n\tfor _, e := range id.devices {\n\t\tkey := string(e.devicePK)\n\t\tknown := false\n\t\tfor _, s := range seen {\n\t\t\tif s == key {\n\t\t\t\tknown = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !known {\n\t\t\tseen = append(seen, key)\n\t\t}\n\t}\n\tn := 0\n\tfor _, k := range seen {\n\t\tif deviceIsActive(id, []byte(k)) {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// short abbreviates a long hex string for table cells.\nfunc short(s string) string {\n\tif len(s) \u003c= 16 {\n\t\treturn s\n\t}\n\treturn s[:8] + \"…\" + s[len(s)-8:]\n}\n"},{"name":"render_example_test.gno","body":"package wesh\n\nimport (\n\t\"encoding/hex\"\n\n\t\"gno.land/p/moul/x/wesh/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// seedDemo puts the realm into a fixed state for the examples below.\n//\n// It writes the globals directly instead of going through the crossing API:\n// realm globals persist for the whole test binary and examples run after every\n// Test, so an example that did not reset would pin whatever the last test left\n// behind. Heights are literals for the same reason.\nfunc seedDemo() {\n\tbyName = avl.Tree{}\n\tbyOwner = avl.Tree{}\n\tbyAccount = avl.Tree{}\n\n\tpk, _ := hex.DecodeString(\"2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12\")\n\tseed1, _ := hex.DecodeString(\"abababababababababababababababababababababababababababababababab\")\n\tseed2, _ := hex.DecodeString(\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\")\n\tdev1, _ := hex.DecodeString(\"0707070707070707070707070707070707070707070707070707070707070707\")\n\tdev2, _ := hex.DecodeString(\"0909090909090909090909090909090909090909090909090909090909090909\")\n\td1, _ := hex.DecodeString(\"bc51799b5d012dc7ce806b4c63474b1e2db515e7d1622ecd5900b23e1d6a9519\")\n\td2, _ := hex.DecodeString(\"b0da03f83e5349e92bc524714862daa850750f756ca6fd47264333fbf2175c15\")\n\td3, _ := hex.DecodeString(\"ef0c1d0614420c7d660f8416b18651206118e49e8f46ac0360bef61ae6b9100d\")\n\n\talice := \u0026identity{\n\t\tname:        \"alice\",\n\t\towner:       testutils.TestAddress(\"alice\"),\n\t\taccountPK:   pk,\n\t\tpayload:     seed2,\n\t\trevision:    2,\n\t\tdisplayName: \"Alice, support line\",\n\t\thistory: []rotation{\n\t\t\t{revision: 1, payload: seed1, height: 100},\n\t\t\t{revision: 2, payload: seed2, height: 140},\n\t\t},\n\t\tdevices: []deviceEntry{\n\t\t\t{seq: 0, op: wesh.OpAdd, devicePK: dev1, digest: d1, height: 110},\n\t\t\t{seq: 1, op: wesh.OpAdd, devicePK: dev2, digest: d2, height: 120},\n\t\t\t{seq: 2, op: wesh.OpRevoke, devicePK: dev1, digest: d3, height: 130},\n\t\t},\n\t\thead: d3,\n\t}\n\tbyName.Set(alice.name, alice)\n\tbyOwner.Set(alice.owner.String(), alice.name)\n\tbyAccount.Set(hex.EncodeToString(pk), alice.name)\n}\n\n// ExampleRender pins the directory index.\nfunc ExampleRender() {\n\tseedDemo()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Wesh directory\n\t//\n\t// Resolvable, self-signed [Wesh protocol](https://berty.tech/docs/protocol/) identities, on top of [`p/moul/x/wesh`](/p/moul/x/wesh/v0).\n\t//\n\t// A Berty identity normally travels out of band as a QR code, cannot be looked up, cannot announce a seed rotation, and can never revoke a device. This realm addresses those three, and stores no secret of any kind.\n\t//\n\t// | name | owner | rev | mode | devices |\n\t// |---|---|---|---|---|\n\t// | [alice](/r/moul/x/wesh/v0:alice) | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | 2 | published | 1 active / 3 entries |\n\t//\n\t// 1 identity.\n}\n\n// ExampleRender_identity pins one identity card: the Berty link, today's\n// rendezvous point, the device sigchain and the rotation history.\nfunc ExampleRender_identity() {\n\tseedDemo()\n\tprint(Render(\"alice\"))\n\t// Output:\n\t// # alice\n\t//\n\t// _Alice, support line_\n\t//\n\t// | field | value |\n\t// |---|---|\n\t// | owner | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` |\n\t// | account key | `2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12` |\n\t// | mode | published |\n\t// | revision | 2 |\n\t// | registered | block 100 |\n\t//\n\t// ## Contact\n\t//\n\t// Scan or open this in Berty to send a contact request:\n\t//\n\t// ```\n\t// https://berty.tech/id#contact/oZBLGHCDNRB847rT1zHe1xnon58fpWTUsuNntmAo9TK42aKzt14A1V5W67QoN5YzMouuVcucUiBWjN9d2qzy6gUNM4Jio4M/name=Alice%2C+support+line\n\t// ```\n\t//\n\t// | field | value |\n\t// |---|---|\n\t// | rendezvous seed | `eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee` |\n\t// | rendezvous point, period 1234483200 | `08ab5591fbd91f0251a7efe4856fc736a02d1a2252139483ddc8ca85f4616e07` |\n\t//\n\t// The point is `HMAC-SHA256(accountPK || seed, be64(period))`, derived exactly as weshnet derives it, and it rotates every 24h. Anyone can recompute it and check the DHT, so this entry is verifiable rather than merely asserted.\n\t//\n\t// ## Devices\n\t//\n\t// Every entry below was signed by the account key and verified on chain, and chains to the digest of the one before it.\n\t//\n\t// | seq | op | device | block | digest |\n\t// |---|---|---|---|---|\n\t// | 0 | add | `07070707…07070707` | 110 | `bc51799b…1d6a9519` |\n\t// | 1 | add | `09090909…09090909` | 120 | `b0da03f8…f2175c15` |\n\t// | 2 | revoke | `07070707…07070707` | 130 | `ef0c1d06…e6b9100d` |\n\t//\n\t// Head: `ef0c1d0614420c7d660f8416b18651206118e49e8f46ac0360bef61ae6b9100d`\n\t//\n\t// ## Rotation history\n\t//\n\t// Weshnet has no way to announce that a seed was reset, so every link ever shared dies silently. These are the superseded values, kept so a stale link can be recognised as stale.\n\t//\n\t// | rev | value | block |\n\t// |---|---|---|\n\t// | 1 | `abababab…abababab` | 100 |\n\t// | 2 (current) | `eeeeeeee…eeeeeeee` | 140 |\n\t//\n\t// [Back to the directory](/r/moul/x/wesh/v0) · chain `dev`\n}\n\n// ExampleRender_unknown pins the miss.\nfunc ExampleRender_unknown() {\n\tseedDemo()\n\tprint(Render(\"nobody\"))\n\t// Output:\n\t// # Not found\n\t//\n\t// No identity named `nobody`. [Back to the directory](/r/moul/x/wesh/v0).\n}\n"},{"name":"wesh.gno","body":"// Package wesh is an on-chain directory and device sigchain for Wesh protocol\n// (weshnet / Berty) identities.\n//\n// It exists to give weshnet the three things a peer-to-peer network cannot\n// give itself, and which a chain is uniquely good at:\n//\n//  1. Resolution. A Berty identity travels out of band as a QR code or a\n//     https://berty.tech/id# link, and there is no way to look one up. Here a\n//     name resolves to a contact, and Render emits the real, scannable link.\n//  2. Rotation with a paper trail. Resetting the public rendezvous seed\n//     silently kills every link ever shared; there is no revocation channel.\n//     Here every rotation is a numbered, timestamped, signed entry, and the\n//     superseded seeds stay visible, so a stale link resolves to a redirect\n//     instead of to nothing.\n//  3. Device revocation. The Wesh protocol documentation states plainly that a\n//     device, once linked to an account, can never be revoked: the account\n//     metadata log is append-only and no authority can void an entry. This\n//     realm hosts the log that was missing: a hash-chained, account-signed\n//     roster whose every entry the chain verifies with ed25519 before\n//     accepting it.\n//\n// # What this realm does not do, and will not\n//\n// It never stores a secret. Group secrets, device chain keys, message keys and\n// ciphertexts stay off chain, permanently. The library this realm is built on,\n// [p/moul/x/wesh](/p/moul/x/wesh/v0), has no type that can hold one.\n//\n// It also does not pretend to enforce revocation inside weshnet. A revoked\n// device's ratchets are already distributed and forward secrecy is a local\n// property; no chain can reach into a group and forget them. What revocation\n// buys here is that it becomes public, ordered, and attributable to the\n// account key, which is strictly more than weshnet has today.\n//\n// # Publishing is a deliberate act\n//\n// A published rendezvous seed lets anyone derive the account's rotating\n// rendezvous point and watch the DHT for it. That is the same exposure as\n// printing your Berty QR code on a billboard, and it is the right trade only\n// for an identity that wants to be found: a support line, a shop, a public\n// channel.\n//\n// [RegisterCommitted] is the alternative. It publishes H(seed ‖ salt) instead,\n// so the chain attests that a seed handed over out of band really belongs to\n// the named account, without broadcasting where that account listens.\n//\n// # Authentication\n//\n// Every state-changing call carries an ed25519 signature made with the Wesh\n// account private key over a canonical statement that names this chain, the\n// caller's gno address, and a monotonic revision or sequence number. Without\n// it, anyone could publish anyone else's account key next to a seed of their\n// choosing and harvest the contact requests that followed.\npackage wesh\n\nimport (\n\t\"chain/runtime\"\n\t\"encoding/hex\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/wesh/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst (\n\t// MinNameLen and MaxNameLen bound a directory handle.\n\tMinNameLen = 3\n\tMaxNameLen = 32\n\n\t// MaxDevices bounds one account's sigchain so iteration and Render stay\n\t// affordable. weshnet accounts hold a handful of devices, not hundreds.\n\tMaxDevices = 64\n\n\t// MaxRotations bounds the retained rotation history. Older entries are\n\t// dropped from the front: the point of the history is to let a stale link\n\t// be recognised, not to keep a permanent archive.\n\tMaxRotations = 32\n)\n\n// rotation is one seed (or commitment) an identity has published.\ntype rotation struct {\n\trevision int\n\tpayload  []byte\n\theight   int64\n}\n\n// deviceEntry is one verified sigchain statement.\ntype deviceEntry struct {\n\tseq      int\n\top       string\n\tdevicePK []byte\n\tdigest   []byte\n\theight   int64\n}\n\n// identity is a published Wesh identity bound to one gno address.\n//\n// payload holds the public rendezvous seed when committed is false, and\n// H(seed ‖ salt) when it is true. head is the digest of the last accepted\n// sigchain entry, which the next entry must chain to.\ntype identity struct {\n\tname        string\n\towner       address\n\taccountPK   []byte\n\tpayload     []byte\n\tcommitted   bool\n\trevision    int\n\tdisplayName string\n\tcreatedAt   int64\n\tupdatedAt   int64\n\thistory     []rotation\n\tdevices     []deviceEntry\n\thead        []byte\n}\n\nvar (\n\t// byName is the directory, keyed by handle so avl iteration is alphabetical.\n\tbyName avl.Tree\n\t// byOwner maps a gno address to its handle: one identity per address.\n\tbyOwner avl.Tree\n\t// byAccount maps a hex account key to its handle, so two handles can never\n\t// claim the same Wesh account.\n\tbyAccount avl.Tree\n)\n\n// Register publishes an identity whose rendezvous seed is public.\n//\n// sigHex must be an ed25519 signature by the account private key over\n// wesh.BindStatement(chainID, caller, accountPK, seed, 1). Revision 1 is fixed\n// at registration so a signature captured from a later rotation cannot be\n// replayed to re-register the name after it is released.\nfunc Register(cur realm, name, accountPKHex, seedHex, displayName, sigHex string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tregister(cur.Previous().Address(), name, accountPKHex, seedHex, displayName, sigHex, false)\n}\n\n// RegisterCommitted publishes an identity that keeps its rendezvous point off\n// chain: commitmentHex is wesh.SeedCommitment(seed, salt), and the seed itself\n// is shared out of band.\n//\n// The chain still attests the binding (this account key really did claim this\n// commitment from this gno address), so a seed later disclosed privately can\n// be checked against it. What it does not do is tell the world where the\n// account listens.\nfunc RegisterCommitted(cur realm, name, accountPKHex, commitmentHex, displayName, sigHex string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tregister(cur.Previous().Address(), name, accountPKHex, commitmentHex, displayName, sigHex, true)\n}\n\n// register is shared by Register and RegisterCommitted. It takes the already\n// resolved caller rather than a realm: a helper whose first parameter is\n// `realm` would be a second crossing hop, and Previous() inside it would\n// resolve to this realm rather than to the user who called in.\nfunc register(caller address, name, accountPKHex, payloadHex, displayName, sigHex string, committed bool) {\n\tname = normalizeName(name)\n\tassertNameAvailable(name)\n\tif byOwner.Has(caller.String()) {\n\t\tpanic(\"wesh: this address already owns an identity; release it first\")\n\t}\n\n\taccountPK := mustAccountPK(accountPKHex)\n\tif byAccount.Has(accountPKHex) {\n\t\tpanic(\"wesh: this account key is already published under another name\")\n\t}\n\tpayload := mustPayload(payloadHex, committed)\n\tassertDisplayName(displayName)\n\n\tif err := wesh.VerifyBind(runtime.ChainID(), caller.String(), accountPK, payload, 1, mustSig(sigHex)); err != nil {\n\t\tpanic(\"wesh: \" + err.Error())\n\t}\n\n\tnow := time.Now().Unix()\n\tid := \u0026identity{\n\t\tname:        name,\n\t\towner:       caller,\n\t\taccountPK:   accountPK,\n\t\tpayload:     payload,\n\t\tcommitted:   committed,\n\t\trevision:    1,\n\t\tdisplayName: displayName,\n\t\tcreatedAt:   now,\n\t\tupdatedAt:   now,\n\t\thistory:     []rotation{{revision: 1, payload: payload, height: runtime.ChainHeight()}},\n\t\thead:        wesh.GenesisDigest(),\n\t}\n\tbyName.Set(name, id)\n\tbyOwner.Set(caller.String(), name)\n\tbyAccount.Set(accountPKHex, name)\n}\n\n// Rotate publishes a new seed (or commitment) for the caller's identity.\n//\n// This is the operation weshnet's ContactRequestResetReference has no\n// counterpart for. There, resetting the seed silently invalidates every link\n// ever shared. Here the new value is numbered and the old one stays in the\n// history, so a holder of a stale link can see that it was superseded and when.\n//\n// The signature must be over revision+1, which is what stops a superseded\n// binding being replayed to roll a rotation back.\nfunc Rotate(cur realm, payloadHex, sigHex string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tid := mustOwnIdentity(cur.Previous().Address())\n\n\tpayload := mustPayload(payloadHex, id.committed)\n\tif string(payload) == string(id.payload) {\n\t\tpanic(\"wesh: the new value is identical to the current one\")\n\t}\n\n\tnext := id.revision + 1\n\tif err := wesh.VerifyBind(runtime.ChainID(), id.owner.String(), id.accountPK, payload, next, mustSig(sigHex)); err != nil {\n\t\tpanic(\"wesh: \" + err.Error())\n\t}\n\n\tid.revision = next\n\tid.payload = payload\n\tid.updatedAt = time.Now().Unix()\n\tid.history = append(id.history, rotation{revision: next, payload: payload, height: runtime.ChainHeight()})\n\tif len(id.history) \u003e MaxRotations {\n\t\tid.history = id.history[len(id.history)-MaxRotations:]\n\t}\n}\n\n// AppendDevice adds one entry to the caller's device sigchain.\n//\n// prevHex must be the digest of the current head (all zeros for the first\n// entry), and the signature must cover the whole statement including the\n// sequence number and that digest. Chaining every entry to its predecessor is\n// what stops the log being reordered or having an entry quietly dropped: any\n// gap changes every digest after it.\n//\n// op is \"add\" or \"revoke\". Adding a device that is already active, or revoking\n// one that is not, is refused: an append-only log is only useful if its entries\n// are meaningful.\nfunc AppendDevice(cur realm, prevHex, op, devicePKHex, sigHex string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tid := mustOwnIdentity(cur.Previous().Address())\n\n\tif len(id.devices) \u003e= MaxDevices {\n\t\tpanic(\"wesh: device sigchain is full\")\n\t}\n\tprev, err := wesh.DecodeCommitment(prevHex)\n\tif err != nil {\n\t\tpanic(\"wesh: previous digest: \" + err.Error())\n\t}\n\tif string(prev) != string(id.head) {\n\t\tpanic(\"wesh: previous digest does not match the sigchain head \" + hex.EncodeToString(id.head))\n\t}\n\tdevicePK, err := wesh.DecodeDevicePK(devicePKHex)\n\tif err != nil {\n\t\tpanic(\"wesh: device key: \" + err.Error())\n\t}\n\n\tactive := deviceIsActive(id, devicePK)\n\tswitch op {\n\tcase wesh.OpAdd:\n\t\tif active {\n\t\t\tpanic(\"wesh: device is already active\")\n\t\t}\n\tcase wesh.OpRevoke:\n\t\tif !active {\n\t\t\tpanic(\"wesh: device is not active, nothing to revoke\")\n\t\t}\n\tdefault:\n\t\tpanic(\"wesh: operation must be add or revoke\")\n\t}\n\n\tseq := len(id.devices)\n\tdigest, err := wesh.VerifyDevice(runtime.ChainID(), id.accountPK, seq, prev, op, devicePK, mustSig(sigHex))\n\tif err != nil {\n\t\tpanic(\"wesh: \" + err.Error())\n\t}\n\n\tid.devices = append(id.devices, deviceEntry{\n\t\tseq:      seq,\n\t\top:       op,\n\t\tdevicePK: devicePK,\n\t\tdigest:   digest,\n\t\theight:   runtime.ChainHeight(),\n\t})\n\tid.head = digest\n\tid.updatedAt = time.Now().Unix()\n}\n\n// SetDisplayName updates the identity's free-form label.\n//\n// It carries no signature because it authenticates nothing: the display name\n// is app metadata, and berty's own link format keeps it outside the signed\n// payload for the same reason. Only the owning address may change it.\nfunc SetDisplayName(cur realm, displayName string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tassertDisplayName(displayName)\n\tid := mustOwnIdentity(cur.Previous().Address())\n\tid.displayName = displayName\n\tid.updatedAt = time.Now().Unix()\n}\n\n// Release removes the caller's identity and frees its name and account key.\n//\n// The sigchain goes with it. That is the honest behaviour: a directory entry\n// is a live claim, not an archive, and keeping a dangling roster for a name\n// somebody else can now take would be worse than keeping nothing.\nfunc Release(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\tcaller := cur.Previous().Address()\n\tid := mustOwnIdentity(caller)\n\n\tbyName.Remove(id.name)\n\tbyOwner.Remove(caller.String())\n\tbyAccount.Remove(hex.EncodeToString(id.accountPK))\n}\n\n// --- read-only API, for gnoweb and for other realms ---\n\n// Resolve returns the account key and current payload of a name, both hex, and\n// whether the payload is a commitment rather than a seed. ok is false when the\n// name is not registered.\nfunc Resolve(name string) (accountPKHex, payloadHex string, committed, ok bool) {\n\tid := lookup(name)\n\tif id == nil {\n\t\treturn \"\", \"\", false, false\n\t}\n\treturn hex.EncodeToString(id.accountPK), hex.EncodeToString(id.payload), id.committed, true\n}\n\n// Link returns the shareable Berty web link for a name, or \"\" when the name is\n// unknown or its rendezvous point is committed rather than published.\nfunc Link(name string) string {\n\tid := lookup(name)\n\tif id == nil || id.committed {\n\t\treturn \"\"\n\t}\n\tlink, err := contactOf(id).WebLink()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn link\n}\n\n// RendezvousPointAt returns the hex rendezvous point the named account\n// announces on during the rotation period containing unixSec, or \"\" when the\n// name is unknown or committed.\n//\n// This is what makes a directory entry checkable rather than merely claimed:\n// anyone can compare it against the DHT without trusting this realm.\nfunc RendezvousPointAt(name string, unixSec int64) string {\n\tid := lookup(name)\n\tif id == nil || id.committed {\n\t\treturn \"\"\n\t}\n\tpoint, err := contactOf(id).RendezvousPointAt(unixSec, wesh.DefaultRotationInterval)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(point)\n}\n\n// DeviceStatus reports \"active\", \"revoked\" or \"unknown\" for a device under a\n// name. \"unknown\" also covers an unregistered name: a caller must not be able\n// to tell those apart by status alone.\nfunc DeviceStatus(name, devicePKHex string) string {\n\tid := lookup(name)\n\tif id == nil {\n\t\treturn \"unknown\"\n\t}\n\tdevicePK, err := wesh.DecodeDevicePK(devicePKHex)\n\tif err != nil {\n\t\treturn \"unknown\"\n\t}\n\tif !deviceSeen(id, devicePK) {\n\t\treturn \"unknown\"\n\t}\n\tif deviceIsActive(id, devicePK) {\n\t\treturn \"active\"\n\t}\n\treturn \"revoked\"\n}\n\n// SigchainHead returns the hex digest the next sigchain entry must chain to,\n// or \"\" when the name is unknown. A client builds its next statement from this.\nfunc SigchainHead(name string) string {\n\tid := lookup(name)\n\tif id == nil {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(id.head)\n}\n\n// NameOf returns the handle owned by an address, or \"\".\nfunc NameOf(owner address) string {\n\tv := byOwner.Get(owner.String())\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n\n// Count returns the number of registered identities.\nfunc Count() int { return byName.Size() }\n\n// --- helpers ---\n\nfunc lookup(name string) *identity {\n\tv := byName.Get(normalizeName(name))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*identity)\n}\n\nfunc contactOf(id *identity) wesh.Contact {\n\treturn wesh.Contact{\n\t\tAccountPK:   id.accountPK,\n\t\tSeed:        id.payload,\n\t\tDisplayName: id.displayName,\n\t}\n}\n\nfunc deviceIsActive(id *identity, devicePK []byte) bool {\n\tactive := false\n\tfor _, e := range id.devices {\n\t\tif string(e.devicePK) != string(devicePK) {\n\t\t\tcontinue\n\t\t}\n\t\tactive = e.op == wesh.OpAdd\n\t}\n\treturn active\n}\n\nfunc deviceSeen(id *identity, devicePK []byte) bool {\n\tfor _, e := range id.devices {\n\t\tif string(e.devicePK) == string(devicePK) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc mustOwnIdentity(caller address) *identity {\n\tv := byOwner.Get(caller.String())\n\tif v == nil {\n\t\tpanic(\"wesh: no identity registered for this address\")\n\t}\n\treturn lookup(v.(string))\n}\n\nfunc mustAccountPK(s string) []byte {\n\tpk, err := wesh.DecodeAccountPK(s)\n\tif err != nil {\n\t\tpanic(\"wesh: account key: \" + err.Error())\n\t}\n\treturn pk\n}\n\nfunc mustPayload(s string, committed bool) []byte {\n\tif committed {\n\t\tc, err := wesh.DecodeCommitment(s)\n\t\tif err != nil {\n\t\t\tpanic(\"wesh: commitment: \" + err.Error())\n\t\t}\n\t\treturn c\n\t}\n\tseed, err := wesh.DecodeSeed(s)\n\tif err != nil {\n\t\tpanic(\"wesh: seed: \" + err.Error())\n\t}\n\treturn seed\n}\n\nfunc mustSig(s string) []byte {\n\tsig, err := hex.DecodeString(s)\n\tif err != nil || len(sig) != 64 {\n\t\tpanic(\"wesh: signature must be 64 hex-encoded bytes\")\n\t}\n\treturn sig\n}\n\nfunc assertDisplayName(s string) {\n\tif len(s) \u003e wesh.MaxDisplayNameLen {\n\t\tpanic(\"wesh: display name is too long\")\n\t}\n}\n\nfunc assertNameAvailable(name string) {\n\tif len(name) \u003c MinNameLen || len(name) \u003e MaxNameLen {\n\t\tpanic(\"wesh: name must be between 3 and 32 characters\")\n\t}\n\tfor i := 0; i \u003c len(name); i++ {\n\t\tc := name[i]\n\t\tok := (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9') || c == '-' || c == '_'\n\t\tif !ok {\n\t\t\tpanic(\"wesh: name may only contain a-z, 0-9, '-' and '_'\")\n\t\t}\n\t}\n\tif byName.Has(name) {\n\t\tpanic(\"wesh: name is already taken\")\n\t}\n}\n\n// normalizeName lowercases a handle so lookups are case-insensitive and two\n// handles cannot differ only by case.\nfunc normalizeName(name string) string {\n\treturn strings.ToLower(strings.TrimSpace(name))\n}\n"},{"name":"wesh_test.gno","body":"package wesh\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/wesh/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Signature fixtures. Each was produced with Go's crypto/ed25519 over the exact\n// statement wesh.BindStatement / wesh.DeviceStatement builds, for chain-id\n// \"dev\" (what the test VM reports) and the address named in the constant.\n// Regenerating them means re-signing: that is the point, since the whole\n// scheme rests on the chain being unable to accept anything unsigned.\nconst (\n\t// alice, g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh\n\taliceAccountPKHex = \"2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12\"\n\taliceSeed1Hex     = \"abababababababababababababababababababababababababababababababab\"\n\taliceSeed2Hex     = \"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\"\n\taliceCommitHex    = \"c9744f547763321102debcf355a5652208604d53dba6c77e978ee8077ceb472a\"\n\n\taliceBind1Sig = \"1279475fc9f7423d13e3eeea96a1714754f74c77abbb5859ba899bd3f820f59d\" +\n\t\t\"2b0a16f2f6c436cdafd8e20b0d709a5e247a5bbbf4b34df38c1405aba3645905\"\n\taliceBind2Sig = \"e915b181109936b1ef77ea8e31e512b56ac63a7e690c382e3613df3ef50472ba\" +\n\t\t\"23233442d789c22ad9401cb882f57be737a67e24db207a9856186eda61fdc108\"\n\taliceBind3Sig = \"d04f8733f564ee45f141fb71ecb049078a23215b29a14dafeed6c1ced91511ec\" +\n\t\t\"47b8c3de120f0d23c534c7387e3273e86b50787280ff38a7f1bd31c23ab35f03\"\n\taliceCommitBindSig = \"d467d806145c228ff7b784658f06f8f05e7fa19354ae0bad3a69b40a1a4cf518\" +\n\t\t\"ecb3a679674705017c6dfa1bf0bac3e1ec67a4f417c18a80faf77062b8c1e100\"\n\t// signed by alice's key but naming bob's gno address\n\taliceBindForBobSig = \"7bac691e9da577c6474af269b690a7415f07c4a8e4df486deccf824b41061735\" +\n\t\t\"01cd22af6f1b9654603a866a3a46942ec020714226b01105700eab84cfc08700\"\n\n\t// bob, g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu\n\tbobAccountPKHex = \"332ebe8d27cb7323b3a401c1c13b5dd64bccc0e10ecda1c2b5d11a03779a85e5\"\n\tbobBind1Sig     = \"69653e1bef41150eed026b355d5ee9837455e3432003ca19102075078305fdbe\" +\n\t\t\"b440eedb421056a0e62a182a406cb3394c1225de768dcd114f9d0b9b3501b90f\"\n\n\t// alice's device sigchain: add dev1, add dev2, revoke dev1\n\tdev1Hex = \"0707070707070707070707070707070707070707070707070707070707070707\"\n\tdev2Hex = \"0909090909090909090909090909090909090909090909090909090909090909\"\n\n\tdevAdd1Sig = \"259abde508b8880dd1f53b236d93b08aa1c7511c4308c2b16da2520d5f553a50\" +\n\t\t\"67c24876299b6c3e4d9fb88e043dec1978f8d9328f7ac13d80bfdab536893507\"\n\tdevAdd1Digest = \"bc51799b5d012dc7ce806b4c63474b1e2db515e7d1622ecd5900b23e1d6a9519\"\n\n\tdevAdd2Sig = \"4799b276bf9b713d84855670198a86de8d38bc2644349a554fe0d4dab5fbea9b\" +\n\t\t\"7e90aecfe9b7da74345e61f5016361e92e7c0959fe09665a1f20f604015bea00\"\n\tdevAdd2Digest = \"b0da03f83e5349e92bc524714862daa850750f756ca6fd47264333fbf2175c15\"\n\n\tdevRevoke1Sig = \"47433475efd00ed87769e7bb748a5af9be77cde56817ea9a1ddd9288533e2bf9\" +\n\t\t\"b783d85a025a632466ce8dcf637047c932c9d1a15131187213e1ae354e22df02\"\n\tdevRevoke1Digest = \"ef0c1d0614420c7d660f8416b18651206118e49e8f46ac0360bef61ae6b9100d\"\n\n\t// signed for sequence 5 while the head is still at sequence 1\n\tdevWrongSeqSig = \"c65d9c48c441bf36dcf01c8c0e46fe73a9f7f8d8edffb07bd05f9ca4a8f875bc\" +\n\t\t\"6de7ebe30c1d5ae785fde8bfe7b48705605a6c247a62def9b03d37fb62f6f809\"\n\n\tgenesisDigestHex = \"0000000000000000000000000000000000000000000000000000000000000000\"\n)\n\n// reset clears realm globals: gno subtests do not roll them back.\nfunc reset() {\n\tbyName = avl.Tree{}\n\tbyOwner = avl.Tree{}\n\tbyAccount = avl.Tree{}\n}\n\n// Two gno-specific rules shape every test below, and both cost a red run to\n// learn:\n//\n//   - testing.SetRealm is scoped to the frame that calls it, so it has to be\n//     called in the test body, not in a setUpAlice() helper.\n//   - a helper whose first parameter is `realm` is itself a crossing function,\n//     so routing a call through one makes THIS realm the Previous() the\n//     callee sees, not the user. Crossing calls stay inline.\n//\n// Together they mean the two setup lines are repeated rather than factored.\nfunc aliceAddr() address { return testutils.TestAddress(\"alice\") }\nfunc bobAddr() address   { return testutils.TestAddress(\"bob\") }\n\nfunc TestRegister(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\n\tuassert.Equal(t, 1, Count())\n\tpk, payload, committed, ok := Resolve(\"alice\")\n\tuassert.True(t, ok, \"the name resolves\")\n\tuassert.Equal(t, aliceAccountPKHex, pk)\n\tuassert.Equal(t, aliceSeed1Hex, payload)\n\tuassert.False(t, committed, \"the seed is published, not committed\")\n\tuassert.Equal(t, \"alice\", NameOf(aliceAddr()))\n}\n\n// TestRegisterEmitsARealBertyLink is the payoff: the realm hands back a link a\n// Berty client can actually open.\nfunc TestRegisterEmitsARealBertyLink(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\n\tuassert.Equal(t,\n\t\t\"https://berty.tech/id#contact/oZBLFpzghxrATkepWvDPNX9pHYqi6BWgP45xGWhqxcwmqN2bnMMbU7UcwUuTaCcDyUvMjmWRMDWcP96bXAndcjNiAZ1Vz9X/name=Alice\",\n\t\tLink(\"alice\"))\n\n\t// and the rendezvous point anyone can check against the DHT\n\tuassert.Equal(t,\n\t\t\"aad2926c39dacabaabbbde48522d043557c8945b6a2dc7b08499c112c72587da\",\n\t\tRendezvousPointAt(\"alice\", 1789171200))\n}\n\nfunc TestRegisterIsCaseInsensitive(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"  ALICE  \", aliceAccountPKHex, aliceSeed1Hex, \"\", aliceBind1Sig)\n\n\t_, _, _, ok := Resolve(\"Alice\")\n\tuassert.True(t, ok, \"lookup is case-insensitive\")\n\tuassert.Equal(t, \"alice\", NameOf(aliceAddr()), \"the handle is stored lowercased\")\n}\n\n// TestRegisterRejectsAnUnsignedClaim is the attack the binding signature\n// exists to stop: bob publishing alice's account key next to a seed he\n// controls, and harvesting the contact requests that follow.\nfunc TestRegisterRejectsAnotherAccountsKey(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bobAddr()))\n\tuassert.AbortsContains(t, cur, \"signature does not verify\", func() {\n\t\tRegister(cross(cur), \"notalice\", aliceAccountPKHex, aliceSeed1Hex, \"\", aliceBind1Sig)\n\t}, \"alice's signature does not authorise bob's address\")\n}\n\n// TestRegisterRejectsAReplayedBinding: the statement names the gno address, so\n// a signature harvested from alice's transaction is useless to anyone else.\nfunc TestRegisterRejectsAReplayedBinding(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tuassert.AbortsContains(t, cur, \"signature does not verify\", func() {\n\t\t// this signature names bob's address, alice is calling\n\t\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"\", aliceBindForBobSig)\n\t})\n}\n\nfunc TestRegisterRejectsDuplicates(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\n\ttesting.SetRealm(testing.NewUserRealm(bobAddr()))\n\tuassert.AbortsContains(t, cur, \"name is already taken\", func() {\n\t\tRegister(cross(cur), \"alice\", bobAccountPKHex, aliceSeed1Hex, \"\", bobBind1Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"already published under another name\", func() {\n\t\tRegister(cross(cur), \"alice2\", aliceAccountPKHex, aliceSeed1Hex, \"\", aliceBind1Sig)\n\t}, \"one Wesh account, one directory entry\")\n\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tuassert.AbortsContains(t, cur, \"already owns an identity\", func() {\n\t\tRegister(cross(cur), \"alice2\", aliceAccountPKHex, aliceSeed1Hex, \"\", aliceBind1Sig)\n\t})\n}\n\nfunc TestRegisterValidatesInput(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\n\tuassert.AbortsContains(t, cur, \"between 3 and 32\", func() {\n\t\tRegister(cross(cur), \"ab\", aliceAccountPKHex, aliceSeed1Hex, \"\", aliceBind1Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"a-z, 0-9\", func() {\n\t\tRegister(cross(cur), \"al!ce\", aliceAccountPKHex, aliceSeed1Hex, \"\", aliceBind1Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"account key\", func() {\n\t\tRegister(cross(cur), \"alice\", \"abcd\", aliceSeed1Hex, \"\", aliceBind1Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"seed\", func() {\n\t\tRegister(cross(cur), \"alice\", aliceAccountPKHex, \"abcd\", \"\", aliceBind1Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"signature must be 64\", func() {\n\t\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"\", \"00\")\n\t})\n}\n\nfunc TestRegisterCommitted(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegisterCommitted(cross(cur), \"alice\", aliceAccountPKHex, aliceCommitHex, \"\", aliceCommitBindSig)\n\n\t_, payload, committed, ok := Resolve(\"alice\")\n\tuassert.True(t, ok)\n\tuassert.True(t, committed)\n\tuassert.Equal(t, aliceCommitHex, payload)\n\n\tuassert.Equal(t, \"\", Link(\"alice\"), \"a committed identity publishes no link\")\n\tuassert.Equal(t, \"\", RendezvousPointAt(\"alice\", 1789171200),\n\t\t\"a committed identity does not disclose its rendezvous point\")\n}\n\n// TestCommitmentOpensWithTheOutOfBandSeed: the chain attests the binding, and\n// the seed handed over privately checks against it.\nfunc TestCommitmentOpensWithTheOutOfBandSeed(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegisterCommitted(cross(cur), \"alice\", aliceAccountPKHex, aliceCommitHex, \"\", aliceCommitBindSig)\n\n\t_, payload, _, _ := Resolve(\"alice\")\n\tcommitment, err := wesh.DecodeCommitment(payload)\n\tuassert.NoError(t, err)\n\tseed, err := wesh.DecodeSeed(aliceSeed1Hex)\n\tuassert.NoError(t, err)\n\n\tuassert.True(t, wesh.OpenCommitment(commitment, seed, []byte(\"a-16-byte-salt!!\")),\n\t\t\"the seed shared out of band matches what the chain attested\")\n\tuassert.False(t, wesh.OpenCommitment(commitment, seed, []byte(\"wrong-salt!!!!!!\")))\n}\n\nfunc TestRotate(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\n\tRotate(cross(cur), aliceSeed2Hex, aliceBind2Sig)\n\n\t_, payload, _, _ := Resolve(\"alice\")\n\tuassert.Equal(t, aliceSeed2Hex, payload)\n\n\tid := lookup(\"alice\")\n\tuassert.Equal(t, 2, id.revision)\n\tuassert.Equal(t, 2, len(id.history), \"the superseded seed is kept so a stale link is recognisable\")\n\tuassert.Equal(t, aliceSeed1Hex, hexOf(id.history[0].payload))\n}\n\n// TestRotateRejectsAReplayedRevision is what a monotonic revision buys: an old\n// binding cannot be replayed to roll a rotation back.\nfunc TestRotateRejectsAReplayedRevision(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\tRotate(cross(cur), aliceSeed2Hex, aliceBind2Sig)\n\n\tuassert.AbortsContains(t, cur, \"signature does not verify\", func() {\n\t\tRotate(cross(cur), aliceSeed1Hex, aliceBind1Sig)\n\t}, \"the revision-1 signature is dead once revision 2 exists\")\n\n\t// the correctly-signed revision 3 does go back to the first seed\n\tRotate(cross(cur), aliceSeed1Hex, aliceBind3Sig)\n\tuassert.Equal(t, 3, lookup(\"alice\").revision)\n}\n\nfunc TestRotateRejectsANoOp(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\tuassert.AbortsContains(t, cur, \"identical to the current one\", func() {\n\t\tRotate(cross(cur), aliceSeed1Hex, aliceBind2Sig)\n\t})\n}\n\nfunc TestRotateRequiresAnIdentity(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bobAddr()))\n\tuassert.AbortsContains(t, cur, \"no identity registered\", func() {\n\t\tRotate(cross(cur), aliceSeed2Hex, aliceBind2Sig)\n\t})\n}\n\n// TestDeviceSigchain walks the sequence weshnet itself cannot express:\n// add a device, add a second, then revoke the first.\nfunc TestDeviceSigchain(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\n\tuassert.Equal(t, genesisDigestHex, SigchainHead(\"alice\"), \"an empty chain starts at the genesis digest\")\n\tuassert.Equal(t, \"unknown\", DeviceStatus(\"alice\", dev1Hex))\n\n\tAppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev1Hex, devAdd1Sig)\n\tuassert.Equal(t, devAdd1Digest, SigchainHead(\"alice\"))\n\tuassert.Equal(t, \"active\", DeviceStatus(\"alice\", dev1Hex))\n\n\tAppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, dev2Hex, devAdd2Sig)\n\tuassert.Equal(t, devAdd2Digest, SigchainHead(\"alice\"))\n\n\tAppendDevice(cross(cur), devAdd2Digest, wesh.OpRevoke, dev1Hex, devRevoke1Sig)\n\tuassert.Equal(t, devRevoke1Digest, SigchainHead(\"alice\"))\n\tuassert.Equal(t, \"revoked\", DeviceStatus(\"alice\", dev1Hex), \"revocation is public, ordered and attributable\")\n\tuassert.Equal(t, \"active\", DeviceStatus(\"alice\", dev2Hex))\n\tuassert.Equal(t, 1, activeDevices(lookup(\"alice\")))\n}\n\n// TestDeviceSigchainRejectsAForkedChain: every entry chains to the digest of\n// the one before it, so the log cannot be reordered or have an entry dropped.\nfunc TestDeviceSigchainRejectsAForkedChain(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\tAppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev1Hex, devAdd1Sig)\n\n\tuassert.AbortsContains(t, cur, \"does not match the sigchain head\", func() {\n\t\tAppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev2Hex, devAdd2Sig)\n\t}, \"the second entry must chain to the first\")\n\n\tuassert.AbortsContains(t, cur, \"signature does not verify\", func() {\n\t\tAppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, dev2Hex, devWrongSeqSig)\n\t}, \"a signature made for another sequence number is not accepted at this one\")\n}\n\nfunc TestDeviceSigchainRejectsMeaninglessOps(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\tAppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev1Hex, devAdd1Sig)\n\n\tuassert.AbortsContains(t, cur, \"already active\", func() {\n\t\tAppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, dev1Hex, devAdd1Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"not active, nothing to revoke\", func() {\n\t\tAppendDevice(cross(cur), devAdd1Digest, wesh.OpRevoke, dev2Hex, devAdd2Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"add or revoke\", func() {\n\t\tAppendDevice(cross(cur), devAdd1Digest, \"delete\", dev2Hex, devAdd2Sig)\n\t})\n\tuassert.AbortsContains(t, cur, \"device key\", func() {\n\t\tAppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, \"abcd\", devAdd2Sig)\n\t})\n}\n\nfunc TestSetDisplayName(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\n\tSetDisplayName(cross(cur), \"Alice, support line\")\n\tuassert.Equal(t, \"Alice, support line\", lookup(\"alice\").displayName)\n\n\ttesting.SetRealm(testing.NewUserRealm(bobAddr()))\n\tuassert.AbortsContains(t, cur, \"no identity registered\", func() {\n\t\tSetDisplayName(cross(cur), \"hijacked\")\n\t})\n}\n\nfunc TestRelease(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(aliceAddr()))\n\tRegister(cross(cur), \"alice\", aliceAccountPKHex, aliceSeed1Hex, \"Alice\", aliceBind1Sig)\n\tRelease(cross(cur))\n\n\tuassert.Equal(t, 0, Count())\n\t_, _, _, ok := Resolve(\"alice\")\n\tuassert.False(t, ok)\n\tuassert.Equal(t, \"\", NameOf(aliceAddr()))\n\n\t// the name and the account key are both free again\n\ttesting.SetRealm(testing.NewUserRealm(bobAddr()))\n\tRegister(cross(cur), \"alice\", bobAccountPKHex, aliceSeed1Hex, \"\", bobBind1Sig)\n\tuassert.Equal(t, 1, Count())\n}\n\nfunc TestReadersOnUnknownNames(cur realm, t *testing.T) {\n\treset()\n\tuassert.Equal(t, \"\", Link(\"nope\"))\n\tuassert.Equal(t, \"\", RendezvousPointAt(\"nope\", 0))\n\tuassert.Equal(t, \"\", SigchainHead(\"nope\"))\n\tuassert.Equal(t, \"unknown\", DeviceStatus(\"nope\", dev1Hex))\n\tuassert.Equal(t, \"unknown\", DeviceStatus(\"nope\", \"not-hex\"))\n\t_, _, _, ok := Resolve(\"nope\")\n\tuassert.False(t, ok)\n}\n\nfunc hexOf(b []byte) string {\n\tconst digits = \"0123456789abcdef\"\n\tout := make([]byte, 0, len(b)*2)\n\tfor _, c := range b {\n\t\tout = append(out, digits[c\u003e\u003e4], digits[c\u00260x0f])\n\t}\n\treturn string(out)\n}\n"}]},"send":"","max_deposit":"20000000ugnot"}],"fee":{"gas_wanted":"140692200","gas_fee":"422076ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"dGgqhLTmqa931+MxKPvGq3G2vnys27xkeRcPR5Cz9e90VbALOsmnMqBgujlcmAAgYCFber3WiETU9ty3rmJamA=="}],"memo":""},"metadata":{"timestamp":"1790961821"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"qzvPWgpKogG9Wkuf3luOFSREZUWCLtyeAbOX33CbWMIj9mDdbd01ppy/MFSOLxttpTgXIo88mITqkclDd2nusw=="}],"memo":""},"metadata":{"timestamp":"1790961822"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"wiki","path":"gno.land/r/moul/x/wiki/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/wiki/v0`\n\nAn open, on-chain encyclopedia. Anyone can create or edit a page, every edit is\na signed revision, and the whole history is public and tamper-evident.\n\nA thin realm over [`p/moul/x/wiki/v0`](../../../../../p/moul/x/wiki): the library\nowns content (titles, revisions, wikilinks, categories, diffs, rendering), this\nrealm owns **authority** (who may write what) and the chain wiring (block\nheight, block time, the calling address, transaction links). There is no policy\nin the library and no content logic here.\n\n## Writing\n\n| call | who |\n|---|---|\n| `Edit(title, body, summary)` | anyone, subject to the page's protection |\n| `Revert(title, rev, summary)` | same |\n| `Comment(title, body, replyTo)` | anyone not banned, whatever the protection |\n| `HideComment(title, id)` | steward |\n| `Protect(title, \"open\"\\|\"semi\"\\|\"locked\")` | steward |\n| `Move(from, to, reason)` | steward |\n| `Blank(title, reason)` | steward |\n| `Purge(title)` | steward |\n| `AddEditor` / `RemoveEditor` / `Ban` / `Unban` / `SetCooldown` | steward |\n\n```sh\ngnokey maketx call -pkgpath gno.land/r/moul/x/wiki/v0 -func Edit \\\n  -args 'Gno land' -args 'gno.land is a chain that runs [[Gno]].\n[[Category:Chains]]\n' -args 'expand the intro' \\\n  -gas-fee 200000ugnot -gas-wanted 20000000 -broadcast -chainid \u003cid\u003e \u003ckey\u003e\n```\n\nThe body is markdown plus `[[wikilinks]]`, `[[Category:Name]]` and a\n`#REDIRECT [[Target]]` first line; the syntax table is in the library README.\n\n## Reading\n\n| route | page |\n|---|---|\n| `` | front page: counts and recent changes |\n| `Title` | the article |\n| `Title/history?offset=` | revisions, newest first |\n| `Title/raw` | current source with its SHA-256 |\n| `Title/rev/\u003cid\u003e` | one stored revision |\n| `Title/diff?from=\u0026to=` | a line diff |\n| `Title/talk?offset=` | the page's discussion |\n| `Category:Name` | the category and its members |\n| `Special:AllPages?ns=` · `Special:Categories` · `Special:RecentChanges` · `Special:Backlinks?page=` · `Special:Stats` | listings |\n\n`Render` is total: a malformed path returns a page, never an abort.\n\n## Authority\n\nOne `ownable.Ownable` steward, transferable, so the wiki can be handed to a DAO\nrealm without redeploying. Three protection levels: `open` (anyone), `semi`\n(an explicit editor list), `locked` (steward only). A page that does not exist\nyet is open to anyone.\n\n**Commenting ignores the protection level on purpose.** Locking an article is\nhow a steward stops an edit war; the discussion is where that war is supposed to\nmove, so a locked page still takes comments. A banned address cannot comment,\nand the cooldown still applies.\n\nOn anti-vandalism, the honest version: the storage deposit makes **adding**\nbytes cost the adder, but the chain refunds released storage to whoever frees\nit, at the realm's blended rate, not to whoever paid (see the library README,\n\"Who gets the deposit back\"). So shrinking a page can pay the editor who does\nit, and reverting the damage costs the good actor. That is why `Blank`, `Purge`\nand `HideComment` are steward-gated, and why the ban list, the protection\nlevels and `SetCooldown` are not optional extras.\n\nBlanking is the deletion a chain can honestly offer. The page stops rendering\nand stops costing rent as its bodies age out, while the revision spine stays as\nproof that something was there and who removed it. `Purge` releases the\nretained bytes immediately. Neither removes the transactions that wrote the\ncontent: on a public chain, \"delete\" means \"stop serving\", not \"unhappen\".\n\n## Cost\n\nStorage deposit is 100ugnot per byte, locked while the bytes are held and\nreleased when they are removed. A 5 KB article is therefore about 0.5 GNOT of\ndeposit for its current revision, plus roughly 0.02 GNOT for each revision's\npermanent spine; the default retention window keeps three bodies per page. Every\npage's footer shows its own held bytes and deposit, and `Special:Stats` shows\nthe wiki's.\n\nRetention defaults to 3 rather than 1 so that a revert can reach past two bad\nedits in a row, which is the common vandalism pattern. Raising it costs\nlinearly more deposit per page.\n\n## Seeded content\n\n`init` writes four linked pages (`Gno land`, `Gno`, `Tendermint2`,\n`Help:Editing`) so a fresh deploy renders a connected wiki instead of an empty\nindex.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/wiki/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wiki/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/wiki/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wiki/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/wiki/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wiki/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/wiki/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/wiki/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/wiki/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/wiki/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"example_test.gno","body":"package wiki\n\nimport \"strings\"\n\n// ExampleRender shows what an article looks like once the library has\n// rewritten its wikilinks and hoisted its categories into the footer.\n//\n// It prints only the structural lines: the header carries a timestamp and the\n// footer a byte count, and neither is stable across the package's other tests.\n// The full output is pinned by TestRenderRoutes and by the library's own\n// render tests.\nfunc ExampleRender() {\n\tfor _, line := range strings.Split(Render(\"Tendermint2\"), \"\\n\") {\n\t\tswitch {\n\t\tcase strings.HasPrefix(line, \"# \"),\n\t\t\tstrings.HasPrefix(line, \"**Categories:**\"),\n\t\t\tstrings.HasPrefix(line, \"Tendermint2 is\"):\n\t\t\tprint(line + \"\\n\")\n\t\t}\n\t}\n\t// Output:\n\t// # Tendermint2\n\t// Tendermint2 is the consensus engine under [Gno land](/r/moul/x/wiki/v0:Gno_land).\n\t// **Categories:** [Chains](/r/moul/x/wiki/v0:Category:Chains)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/wiki/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"wiki.gno","body":"// Package wiki is an open, on-chain encyclopedia: anyone can create and edit\n// a page, every edit is a signed revision, and the whole history is public.\n//\n// It is a thin realm over gno.land/p/moul/x/wiki/v0. The library owns content\n// (titles, revisions, wikilinks, categories, diffs, rendering); this realm\n// owns authority (who may edit what) and the chain wiring (block height, block\n// time, the calling address, transaction links).\n//\n// The split matters for reading the code: there is no policy in the library\n// and no content logic here.\npackage wiki\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/addrset/v1\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/p/moul/x/wiki/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// basePath is this realm's render path. It is a constant rather than a lookup\n// so link building stays a pure string operation, and it is asserted against\n// the real path by TestBasePathMatchesTheRealm.\nconst basePath = \"/r/moul/x/wiki/v0\"\n\n// steward is the address that starts out able to protect, move, blank and\n// purge pages. Ownable makes it transferable, so the wiki can be handed to a\n// DAO realm without redeploying.\nconst steward address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\" // @moul\n\nvar (\n\tsite    *wiki.Wiki\n\tOwnable *ownable.Ownable\n\n\t// editors may write to semi-protected pages; banned may write nowhere.\n\teditors addrset.Set\n\tbanned  addrset.Set\n\n\t// cooldown is the minimum number of blocks between two writes by the same\n\t// address, 0 to disable.\n\t//\n\t// The storage deposit makes ADDING bytes cost the adder, but it does not\n\t// make removing them cost anything: the chain refunds released storage to\n\t// the caller of the transaction that frees it, at the realm's blended\n\t// deposit rate, not to whoever originally paid (processStorageDeposit in\n\t// gno.land/pkg/sdk/vm/keeper.go). So replacing a long article with a short\n\t// one can pay the editor who does it. Blank and Purge are steward-gated\n\t// for that reason, and this cooldown plus the ban list and the protection\n\t// levels are what is left for ordinary edits. See #140 Q2.\n\tcooldown  int64\n\tlastEdit  avl.Tree // address -\u003e the height of that address's last edit\n\teditCount int\n)\n\nfunc init() {\n\tOwnable = ownable.NewWithAddress(steward)\n\tsite = wiki.New(wiki.DefaultRetention, wiki.DefaultMaxBody)\n\tseed()\n}\n\n// Edit creates or updates a page and returns the new revision id.\nfunc Edit(cur realm, title, body, summary string) int {\n\tcaller := cur.Previous().Address()\n\tassertMayEdit(caller, title)\n\trev, err := site.Edit(caller, time.Now(), runtime.ChainHeight(), title, body, summary, false)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnoteEdit(caller)\n\treturn int(rev.ID)\n}\n\n// Revert restores an earlier revision of a page as a new revision.\nfunc Revert(cur realm, title string, rev int, summary string) int {\n\tcaller := cur.Previous().Address()\n\tassertMayEdit(caller, title)\n\tr, err := site.Revert(caller, time.Now(), runtime.ChainHeight(), title, uint64(rev), summary)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnoteEdit(caller)\n\treturn int(r.ID)\n}\n\n// Comment appends a message to a page's discussion and returns its id. Pass\n// replyTo = 0 for a new thread, or the id of a top-level message to reply to.\n//\n// Commenting deliberately ignores the page's protection level: locking an\n// article is how a steward stops an edit war, and the discussion is where that\n// war is supposed to move. A banned address still cannot comment, and the\n// cooldown still applies.\nfunc Comment(cur realm, title, body string, replyTo int) int {\n\tcaller := cur.Previous().Address()\n\tassertNotBanned(caller)\n\tc, err := site.Comment(caller, time.Now(), runtime.ChainHeight(), title, body, uint64(replyTo))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnoteEdit(caller)\n\treturn int(c.ID)\n}\n\n// HideComment clears one message's body and returns the bytes released. The\n// message stays in the thread, marked as removed.\nfunc HideComment(cur realm, title string, id int) int {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tn, err := site.HideComment(title, uint64(id))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}\n\n// Protect sets a page's edit gate: \"open\", \"semi\" or \"locked\".\nfunc Protect(cur realm, title, level string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tif err := site.SetProtection(cur.Previous().Address(), time.Now(), runtime.ChainHeight(), title, level); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Move renames a page, keeping its history and leaving a redirect behind.\nfunc Move(cur realm, from, to, reason string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tif err := site.Move(cur.Previous().Address(), time.Now(), runtime.ChainHeight(), from, to, reason); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Blank replaces a page's content with a tombstone revision. The history stays.\nfunc Blank(cur realm, title, reason string) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tif _, err := site.Blank(cur.Previous().Address(), time.Now(), runtime.ChainHeight(), title, reason); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Purge drops every body this realm still holds for a page and returns the\n// number of bytes released. Use it for content that must stop being served\n// from realm state; it cannot remove the transactions that wrote it.\nfunc Purge(cur realm, title string) int {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tn, err := site.Purge(title)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}\n\n// AddEditor lets an address write to semi-protected pages.\nfunc AddEditor(cur realm, addr address) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\teditors.Add(addr)\n}\n\n// RemoveEditor revokes semi-protected write access.\nfunc RemoveEditor(cur realm, addr address) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\teditors.Remove(addr)\n}\n\n// Ban stops an address from editing anything.\nfunc Ban(cur realm, addr address) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tbanned.Add(addr)\n}\n\n// Unban lifts a ban.\nfunc Unban(cur realm, addr address) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tbanned.Remove(addr)\n}\n\n// SetCooldown sets the minimum number of blocks between two edits by the same\n// address; 0 disables it.\nfunc SetCooldown(cur realm, blocks int) {\n\tOwnable.AssertOwnedBy(cur.Previous().Address())\n\tif blocks \u003c 0 {\n\t\tpanic(\"cooldown must not be negative\")\n\t}\n\tcooldown = int64(blocks)\n}\n\n// assertNotBanned is the floor every write shares: the ban list and the\n// per-address cooldown.\nfunc assertNotBanned(caller address) {\n\tif banned.Has(caller) {\n\t\tpanic(\"this address is banned from editing\")\n\t}\n\tif cooldown \u003e 0 {\n\t\tif v := lastEdit.Get(caller.String()); v != nil {\n\t\t\tif wait := cooldown - (runtime.ChainHeight() - v.(int64)); wait \u003e 0 {\n\t\t\t\tpanic(ufmt.Sprintf(\"edit cooldown: wait %d more blocks\", wait))\n\t\t\t}\n\t\t}\n\t}\n}\n\n// assertMayEdit is the whole authority model of this wiki, in one function.\nfunc assertMayEdit(caller address, title string) {\n\tassertNotBanned(caller)\n\n\tp, err := site.Page(title)\n\tif err != nil {\n\t\treturn // a page that does not exist yet is open to anyone\n\t}\n\tswitch p.Protection {\n\tcase wiki.Locked:\n\t\tOwnable.AssertOwnedBy(caller)\n\tcase wiki.SemiProtected:\n\t\tif !editors.Has(caller) \u0026\u0026 !Ownable.OwnedBy(caller) {\n\t\t\tpanic(\"this page is semi-protected: ask a steward for edit access\")\n\t\t}\n\t}\n}\n\nfunc noteEdit(caller address) {\n\tlastEdit.Set(caller.String(), runtime.ChainHeight())\n\teditCount++\n}\n\n// ctx is the render context handed to the library on every read.\nfunc ctx() wiki.Ctx {\n\treturn wiki.Ctx{Base: basePath, Exists: site.Exists}\n}\n\n// Render is the whole read surface of the wiki.\n//\n// Routes:\n//\n//\t                          the front page\n//\tTitle                     an article\n//\tTitle/history[?offset=]   its revisions, newest first\n//\tTitle/raw                 the current source, with its hash\n//\tTitle/rev/\u003cid\u003e            one stored revision\n//\tTitle/diff?from=\u0026to=      a line diff between two revisions\n//\tTitle/talk[?offset=]      the page's discussion\n//\tCategory:Name             a category page and its members\n//\tSpecial:AllPages[?ns=]    the page index for a namespace\n//\tSpecial:Categories        every category with at least one member\n//\tSpecial:RecentChanges     the change feed\n//\tSpecial:Backlinks?page=   what links to a page\n//\tSpecial:Stats             size and storage cost\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tc := ctx()\n\n\tfirst := req.PathPart(0)\n\tif first == \"\" {\n\t\treturn wiki.RenderIndex(c, site, 20)\n\t}\n\n\tt, err := wiki.ParseTitle(first)\n\tif err != nil {\n\t\treturn \"400: \" + err.Error()\n\t}\n\tif t.NS == wiki.NSSpecial {\n\t\treturn renderSpecial(c, t.Name, req)\n\t}\n\n\tp, perr := site.PageByTitle(t)\n\n\t// A category renders its members even with no description page of its\n\t// own: membership is an index, not a page, so \"the page does not exist\"\n\t// would hide every member.\n\tif t.NS == wiki.NSCategory \u0026\u0026 req.PathPart(1) == \"\" {\n\t\tif perr != nil {\n\t\t\tp = nil\n\t\t}\n\t\treturn wiki.RenderCategory(c, site, t, p, txlink.Call)\n\t}\n\tif perr != nil {\n\t\treturn wiki.RenderMissing(c, site, t, txlink.Call)\n\t}\n\n\tswitch req.PathPart(1) {\n\tcase \"\":\n\t\t// Follow a redirect only for a bare read, so history and source\n\t\t// always address the page that was asked for.\n\t\tif dest, _, rerr := site.Resolve(first); rerr == nil {\n\t\t\tp = dest\n\t\t}\n\t\treturn wiki.RenderArticle(c, site, p, txlink.Call)\n\n\tcase \"history\":\n\t\toffset := intParam(req.Query.Get(\"offset\"), 0)\n\t\treturn wiki.RenderHistory(c, p, offset, 20, txlink.Call)\n\n\tcase \"raw\":\n\t\tif p.Head() == nil {\n\t\t\treturn \"404: no revision\"\n\t\t}\n\t\treturn wiki.RenderRaw(c, p, p.Head())\n\n\tcase \"rev\":\n\t\tr := p.Revision(uint64(intParam(req.PathPart(2), 0)))\n\t\tif r == nil {\n\t\t\treturn \"404: no such revision\"\n\t\t}\n\t\treturn wiki.RenderRevision(c, p, r)\n\n\tcase \"talk\":\n\t\toffset := intParam(req.Query.Get(\"offset\"), 0)\n\t\treturn wiki.RenderTalk(c, site, p, offset, 20, txlink.Call)\n\n\tcase \"diff\":\n\t\tfrom := p.Revision(uint64(intParam(req.Query.Get(\"from\"), 0)))\n\t\tto := p.Revision(uint64(intParam(req.Query.Get(\"to\"), 0)))\n\t\tif from == nil || to == nil {\n\t\t\treturn \"404: no such revision\"\n\t\t}\n\t\treturn wiki.RenderDiff(c, p, from, to)\n\t}\n\treturn \"404: unknown route\"\n}\n\nfunc renderSpecial(c wiki.Ctx, name string, req *realmpath.Request) string {\n\tswitch strings.ToLower(name) {\n\tcase \"allpages\":\n\t\tns := wiki.Namespace(intParam(req.Query.Get(\"ns\"), 0))\n\t\toffset := intParam(req.Query.Get(\"offset\"), 0)\n\t\treturn wiki.RenderAllPages(c, site, ns, offset, 50)\n\tcase \"categories\":\n\t\treturn wiki.RenderCategories(c, site)\n\tcase \"recentchanges\":\n\t\treturn wiki.RenderRecent(c, site, 50)\n\tcase \"backlinks\":\n\t\tt, err := wiki.ParseTitle(req.Query.Get(\"page\"))\n\t\tif err != nil {\n\t\t\treturn \"400: \" + err.Error()\n\t\t}\n\t\treturn wiki.RenderBacklinks(c, site, t)\n\tcase \"stats\":\n\t\treturn wiki.RenderStats(c, site) + md.BulletList([]string{\n\t\t\tufmt.Sprintf(\"edits since deploy: %d\", editCount),\n\t\t\tufmt.Sprintf(\"editors on the semi-protected list: %d\", editors.Size()),\n\t\t\tufmt.Sprintf(\"banned addresses: %d\", banned.Size()),\n\t\t\tufmt.Sprintf(\"edit cooldown: %d blocks\", cooldown),\n\t\t\tufmt.Sprintf(\"max comment length: %d bytes\", wiki.MaxCommentLen),\n\t\t\t\"steward: `\" + Ownable.Owner().String() + \"`\",\n\t\t})\n\t}\n\treturn \"404: unknown special page\"\n}\n\n// intParam parses a decimal parameter, falling back to def. It never panics:\n// Render is reached from a URL, and a malformed query must render a page, not\n// abort the query.\nfunc intParam(s string, def int) int {\n\tif s == \"\" {\n\t\treturn def\n\t}\n\tn := 0\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif s[i] \u003c '0' || s[i] \u003e '9' {\n\t\t\treturn def\n\t\t}\n\t\tn = n*10 + int(s[i]-'0')\n\t}\n\treturn n\n}\n\n// seed writes the pages the wiki starts with, so a fresh deploy renders\n// something a reader can follow instead of an empty index.\nfunc seed() {\n\tpages := []struct{ title, body, summary string }{\n\t\t{\n\t\t\t\"Gno land\",\n\t\t\t\"gno.land is a smart-contract platform that runs [[Gno]], a deterministic \" +\n\t\t\t\t\"interpretation of Go, on top of [[Tendermint2]].\\n\\n\" +\n\t\t\t\t\"Realms keep their state as live objects rather than as a key-value blob, \" +\n\t\t\t\t\"which is what lets this wiki store its articles in the contract itself.\\n\\n\" +\n\t\t\t\t\"[[Category:Chains]]\\n\",\n\t\t\t\"seed\",\n\t\t},\n\t\t{\n\t\t\t\"Gno\",\n\t\t\t\"Gno is the language realms are written in: Go's syntax and semantics, minus \" +\n\t\t\t\t\"the sources of non-determinism a chain cannot tolerate.\\n\\n\" +\n\t\t\t\t\"See [[Gno land]].\\n\\n[[Category:Languages]]\\n\",\n\t\t\t\"seed\",\n\t\t},\n\t\t{\n\t\t\t\"Tendermint2\",\n\t\t\t\"Tendermint2 is the consensus engine under [[Gno land]].\\n\\n[[Category:Chains]]\\n\",\n\t\t\t\"seed\",\n\t\t},\n\t\t{\n\t\t\t\"Help:Editing\",\n\t\t\t\"Anyone may create or edit a page by calling `Edit(title, body, summary)`.\\n\\n\" +\n\t\t\t\t\"The body is markdown with two additions:\\n\\n\" +\n\t\t\t\t\"- `[[Target]]` or `[[Target|label]]` links to another page. A link to a \" +\n\t\t\t\t\"page that does not exist yet is marked, and creating that page turns every \" +\n\t\t\t\t\"such link live.\\n\" +\n\t\t\t\t\"- `[[Category:Name]]` puts the page in a category instead of rendering inline.\\n\\n\" +\n\t\t\t\t\"A page whose first line is `#REDIRECT [[Target]]` redirects.\\n\\n\" +\n\t\t\t\t\"Every page has a discussion thread at `\u003cTitle\u003e/talk`, written with \" +\n\t\t\t\t\"`Comment(title, body, replyTo)`. It stays open even when the article \" +\n\t\t\t\t\"itself is locked, because that is where a disagreement should go.\\n\\n\" +\n\t\t\t\t\"Your transaction locks a storage deposit for the bytes you add, and releases \" +\n\t\t\t\t\"it when they are removed, so the wiki charges the author of a page rather \" +\n\t\t\t\t\"than its readers.\\n\\n[[Category:Help]]\\n\",\n\t\t\t\"seed\",\n\t\t},\n\t}\n\tnow := time.Now()\n\th := runtime.ChainHeight()\n\tfor _, p := range pages {\n\t\tif _, err := site.Edit(steward, now, h, p.title, p.body, p.summary, false); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n"},{"name":"wiki_test.gno","body":"package wiki\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/wiki/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\t// carol edits only in TestCooldown: the cooldown is keyed by address and\n\t// by block height, and gno's testing.SkipHeights is relative, so a test\n\t// that reused an address another test already edited with would see a\n\t// zero-height delta and trip the cooldown before it meant to.\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// TestBasePathMatchesTheRealm pins the constant used to build every link\n// against the realm's own path. A wrong basePath produces a page whose links\n// all 404, and nothing else would catch it.\nfunc TestBasePathMatchesTheRealm(t *testing.T) {\n\tuassert.True(t, strings.HasSuffix(basePath, \"/r/moul/x/wiki/v0\"), basePath)\n\tout := Render(\"Gno_land\")\n\tuassert.True(t, strings.Contains(out, \"(\"+basePath+\":Tendermint2)\"), out)\n}\n\nfunc TestRenderRoutes(t *testing.T) {\n\tcases := []struct {\n\t\tpath string\n\t\twant string\n\t}{\n\t\t{\"\", \"# Wiki\"},\n\t\t{\"Gno_land\", \"# Gno land\"},\n\t\t{\"gno_land\", \"# Gno land\"},                      // titles normalize\n\t\t{\"Gno_land/history\", \"# History of Gno land\"},   //\n\t\t{\"Gno_land/raw\", \"# Source of Gno land\"},        //\n\t\t{\"Gno_land/rev/1\", \"revision 1\"},                //\n\t\t{\"Nonexistent_page\", \"does not exist yet\"},      //\n\t\t{\"Special:AllPages\", \"# All pages\"},             //\n\t\t{\"Special:allpages\", \"# All pages\"},             // case-insensitive\n\t\t{\"Special:Categories\", \"# Categories\"},          //\n\t\t{\"Special:RecentChanges\", \"# Recent changes\"},   //\n\t\t{\"Special:Stats\", \"# Wiki stats\"},               //\n\t\t{\"Special:Backlinks?page=Gno\", \"Pages that link to Gno\"},\n\t\t{\"Special:Nope\", \"404\"},\n\t\t{\"Gno_land/nope\", \"404\"},\n\t\t{\"Gno_land/rev/999\", \"404\"},\n\t\t{\"Category:Chains\", \"Pages in this category\"},\n\t\t{\"Gno_land/talk\", \"# Discussion: Gno land\"},\n\t}\n\tfor _, c := range cases {\n\t\tout := Render(c.path)\n\t\tuassert.True(t, strings.Contains(out, c.want),\n\t\t\t\"Render(\"+c.path+\") should contain \"+c.want+\", got: \"+first80(out))\n\t}\n}\n\nfunc TestRenderIsTotal(t *testing.T) {\n\t// Render is reached from a URL, so malformed input must produce a page,\n\t// never an abort that makes the realm unreadable.\n\tfor _, path := range []string{\"Gno|land\", \"Special:Backlinks?page=\", \"Gno_land/diff?from=x\u0026to=y\", \"//\"} {\n\t\tuassert.NotEmpty(t, Render(path), path)\n\t}\n}\n\nfunc TestEditAndRevert(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\trev := Edit(cross(cur), \"Alice page\", \"First body.\\n\", \"create\")\n\tuassert.True(t, rev \u003e 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tEdit(cross(cur), \"Alice page\", \"Vandalized.\\n\", \"oops\")\n\tuassert.True(t, strings.Contains(Render(\"Alice_page\"), \"Vandalized.\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRevert(cross(cur), \"Alice page\", rev, \"rv\")\n\tout := Render(\"Alice_page\")\n\tuassert.True(t, strings.Contains(out, \"First body.\"))\n\t// The vandalism is still in the history: that is the point of a wiki.\n\tuassert.True(t, strings.Contains(Render(\"Alice_page/history\"), \"oops\"))\n}\n\nfunc TestEditRejectsAnEmptyBody(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"empty title\", func() {\n\t\tEdit(cross(cur), \"\", \"body\\n\", \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"empty body\", func() {\n\t\tEdit(cross(cur), \"Some page\", \"\", \"\")\n\t})\n}\n\nfunc TestBannedAddressCannotEdit(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tBan(cross(cur), bob)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"banned\", func() {\n\t\tEdit(cross(cur), \"Ban test\", \"body\\n\", \"\")\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tUnban(cross(cur), bob)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.True(t, Edit(cross(cur), \"Ban test\", \"body\\n\", \"\") \u003e 0)\n}\n\nfunc TestProtectionLevels(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Protected page\", \"body\\n\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tProtect(cross(cur), \"Protected page\", \"semi\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"semi-protected\", func() {\n\t\tEdit(cross(cur), \"Protected page\", \"sneaky\\n\", \"\")\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tAddEditor(cross(cur), alice)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.True(t, Edit(cross(cur), \"Protected page\", \"allowed\\n\", \"\") \u003e 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tProtect(cross(cur), \"Protected page\", \"locked\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"caller is not owner\", func() {\n\t\tEdit(cross(cur), \"Protected page\", \"still sneaky\\n\", \"\")\n\t})\n}\n\nfunc TestStewardOnlyFunctionsRejectOthers(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Steward test\", \"body\\n\", \"\")\n\n\tfor _, call := range []struct {\n\t\tname string\n\t\tfn   func()\n\t}{\n\t\t{\"Protect\", func() { Protect(cross(cur), \"Steward test\", \"locked\") }},\n\t\t{\"Move\", func() { Move(cross(cur), \"Steward test\", \"Elsewhere\", \"\") }},\n\t\t{\"Blank\", func() { Blank(cross(cur), \"Steward test\", \"\") }},\n\t\t{\"Purge\", func() { Purge(cross(cur), \"Steward test\") }},\n\t\t{\"Ban\", func() { Ban(cross(cur), bob) }},\n\t\t{\"SetCooldown\", func() { SetCooldown(cross(cur), 5) }},\n\t} {\n\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\tuassert.AbortsContains(t, cur, \"caller is not owner\", call.fn, call.name)\n\t}\n}\n\nfunc TestCooldown(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tSetCooldown(cross(cur), 5)\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tEdit(cross(cur), \"Cooldown page\", \"one\\n\", \"\")\n\tuassert.AbortsContains(t, cur, \"cooldown\", func() {\n\t\tEdit(cross(cur), \"Cooldown page\", \"two\\n\", \"\")\n\t})\n\n\ttesting.SkipHeights(6)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.True(t, Edit(cross(cur), \"Cooldown page\", \"two\\n\", \"\") \u003e 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tSetCooldown(cross(cur), 0)\n}\n\nfunc TestBlankAndPurgeReleaseBytes(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Purge page\", \"a body worth some bytes\\n\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tBlank(cross(cur), \"Purge page\", \"policy\")\n\tuassert.True(t, strings.Contains(Render(\"Purge_page\"), \"was blanked\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\treleased := Purge(cross(cur), \"Purge page\")\n\tuassert.True(t, released \u003e 0, \"purging a page with a retained body must release bytes\")\n\tuassert.True(t, strings.Contains(Render(\"Purge_page/history\"), \"body evicted\"))\n}\n\nfunc TestMoveLeavesARedirect(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Before move\", \"the body\\n\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tMove(cross(cur), \"Before move\", \"After move\", \"rename\")\n\n\tuassert.True(t, strings.Contains(Render(\"After_move\"), \"the body\"))\n\t// Reading the old title follows the redirect; its history does not.\n\tuassert.True(t, strings.Contains(Render(\"Before_move\"), \"the body\"))\n\tuassert.True(t, strings.Contains(Render(\"Before_move/raw\"), \"#REDIRECT\"))\n}\n\n// TestSeedIsLinkedTogether checks the deployed starting state renders as a\n// connected wiki rather than four orphans.\nfunc TestSeedIsLinkedTogether(t *testing.T) {\n\tuassert.True(t, strings.Contains(Render(\"Gno_land\"), \"(\"+basePath+\":Gno)\"))\n\tuassert.True(t, strings.Contains(Render(\"Special:Backlinks?page=Gno_land\"), \"[Gno]\"))\n\tuassert.True(t, strings.Contains(Render(\"Category:Chains\"), \"[Gno land]\"))\n}\n\n// TestParseTitleIsTheSameOneTheLibraryUses guards against the realm and the\n// library disagreeing about what a title is, which would make a page\n// creatable but unreachable.\nfunc TestParseTitleIsTheSameOneTheLibraryUses(t *testing.T) {\n\ttt := wiki.MustParseTitle(\"Gno land\")\n\tuassert.Equal(t, \"Gno_land\", tt.Slug())\n\tuassert.True(t, strings.Contains(Render(tt.Slug()), \"# Gno land\"))\n}\n\nfunc first80(s string) string {\n\tif len(s) \u003e 80 {\n\t\treturn s[:80]\n\t}\n\treturn s\n}\n\nfunc TestCommentOnALockedPage(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Locked talk\", \"body\\n\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tProtect(cross(cur), \"Locked talk\", \"locked\")\n\n\t// Locking an article is how a steward stops an edit war; the discussion\n\t// is where that war is supposed to move, so it stays open.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"caller is not owner\", func() {\n\t\tEdit(cross(cur), \"Locked talk\", \"sneaky\\n\", \"\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Comment(cross(cur), \"Locked talk\", \"I disagree, and here is why.\\n\", 0)\n\tuassert.True(t, id \u003e 0)\n\tuassert.True(t, strings.Contains(Render(\"Locked_talk/talk\"), \"I disagree\"))\n}\n\nfunc TestCommentRepliesAndModeration(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Talk target\", \"body\\n\", \"\")\n\troot := Comment(cross(cur), \"Talk target\", \"First.\\n\", 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tComment(cross(cur), \"Talk target\", \"Replying.\\n\", root)\n\n\tout := Render(\"Talk_target/talk\")\n\tuassert.True(t, strings.Contains(out, \"First.\"))\n\tuassert.True(t, strings.Contains(out, \"Replying.\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\treleased := HideComment(cross(cur), \"Talk target\", root)\n\tuassert.True(t, released \u003e 0, \"hiding a message releases its bytes\")\n\tout = Render(\"Talk_target/talk\")\n\tuassert.True(t, strings.Contains(out, \"removed by a steward\"))\n\tuassert.False(t, strings.Contains(out, \"First.\"))\n}\n\nfunc TestBannedAddressCannotComment(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Ban talk\", \"body\\n\", \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tBan(cross(cur), bob)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"banned\", func() {\n\t\tComment(cross(cur), \"Ban talk\", \"spam\\n\", 0)\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(steward))\n\tUnban(cross(cur), bob)\n}\n\nfunc TestHideCommentIsStewardOnly(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tEdit(cross(cur), \"Mod talk\", \"body\\n\", \"\")\n\tid := Comment(cross(cur), \"Mod talk\", \"hello\\n\", 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"caller is not owner\", func() {\n\t\tHideComment(cross(cur), \"Mod talk\", id)\n\t})\n}\n"}]},"send":"","max_deposit":"13000000ugnot"}],"fee":{"gas_wanted":"92152800","gas_fee":"276458ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"x0Dp7zq//VTG60oe3LUGMQiUZOwKuNDBMTdm8ZzOHT8fNJOAKd4z4KoJ6J+WGmBNCfnBP/0tz5dWPupbtTmdvg=="}],"memo":""},"metadata":{"timestamp":"1790961879"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"blog","path":"gno.land/r/moul/blog","files":[{"name":"README.md","body":"# `gno.land/r/moul/blog`\n\nmoul's personal blog, on chain. One author, posts stored as data rather than\ncode, and a URL that is meant to survive being pasted into someone else's chat.\n\n```\ngno.land/r/moul/blog             the index, newest first\ngno.land/r/moul/blog:\u003cslug\u003e      one post\ngno.land/r/moul/blog:t/\u003ctag\u003e     every post carrying a tag\n```\n\n## Why private, and why no `/vN`\n\nThese are the same decision seen from two sides.\n\nA post URL leaves this repository the moment it is published: it goes into\nchats, into other people's articles, into a link someone bookmarked. None of\nthose can be rewritten. A `/v1` would break all of them at once, which is the\none failure a blog cannot absorb, so the module line carries no version.\n\nWhat normally pays for a version is the ability to change the code. Here that\ncomes from `private = true` instead: a private package may be re-added at the\nsame path by the address in `[addpkg].creator`\n(`gno.land/pkg/sdk/vm/keeper.go`, `checkRedeployPermission`), and nothing else\nmay import it. So the code can be replaced without the path moving.\n\nThe bill for that arrives as a wipe. A redeploy re-runs `init()` and resets\nevery package-level variable, so **every post is erased**. That is survivable\nonly because the markdown is kept off chain and `tools/gnoblog -all` pushes all\nof it back in one transaction. The chain holds the published copy; it is not\nthe only copy.\n\n`tools/gnocontracts` records the exemption from the repository's \"every path\nends in `/vN`\" rule, next to `r/moul/home`'s, with the reason.\n\n## The API\n\nWrites are restricted to `g1manfred47kzduec920z88wfr64ylksmdcedlf5`.\n\n| function | what it does |\n| --- | --- |\n| `Set(cur, slug, title, date, tags, body)` | create or replace a post, the ordinary publish |\n| `Append(cur, slug, body)` | append, for a body too large for one transaction |\n| `Delete(cur, slug)` | remove a post |\n| `SetIntro(cur, body)` | the markdown above the index; `\"\"` restores the default |\n| `Get(slug)` | one post's raw markdown |\n| `Count()` · `Revision()` | how many posts, and how many writes have been accepted |\n| `Manifest()` | `slug⇥rev⇥date⇥len⇥sha256` per post, the diff surface |\n\nA slug is 1 to 64 bytes of `[a-z0-9._-]`. No `':'` and no `'/'`, so a slug can\nnever break out of its own render path. `intro` is refused, because `intro.md`\nnames the index header on the local side and a post there would have nowhere to\nlive.\n\nA date is exactly `YYYY-MM-DD`, and that is load-bearing rather than cosmetic:\nposts are kept in a second avl tree keyed by `\"\u003cdate\u003e/\u003cslug\u003e\"` and walked in\nreverse, so lexical order has to be chronological order. gno has no\n`sort.Slice`; this is what replaces it.\n\n## `Manifest()` is the whole sync protocol\n\nOne `vm/qeval` returns a line per post carrying a sha256 over the title, date,\ntags and body **together**. So `gnoblog status` can say exactly which local\nfile needs a transaction without downloading a single body, and changing any\none of the four fields changes the hash.\n\nBoth halves build that hashed record the same way, and neither can check the\nother at run time: the realm's test asserts the record, and the tool's test\npins its digest as a literal. If one side ever drifts, the tool reports every\npost as up to date while the chain holds the old text.\n\n## Escaping\n\nThe body renders **verbatim**. It is markdown written by the one address that\ncan call `Set`, and escaping it would turn every heading and link in a post\ninto literal text.\n\nTitles, tags and index excerpts go through `p/moul/kit/ui` anyway. Not because\nthe author is untrusted, but because a title with a `]` in it would otherwise\nbreak the link it sits inside, and that is a rendering bug with no attacker in\nit at all.\n\n## Publishing a post\n\nThe markdown lives outside this repository; `tools/gnoblog` never defaults to a\npath to it.\n\n```sh\ngo -C tools tool gnoblog -content DIR status   # what differs from the chain\ngo -C tools tool gnoblog -content DIR tx       # the transaction that fixes it\n```\n\n`tx` builds one unsigned transaction document and hands it to `gnokey`, which\nsigns and broadcasts it. Several posts go in one document, so publishing three\nis one passphrase prompt and one atomic broadcast. After a redeploy, `tx -all`.\n\n`status` is the review step. `tx -print` writes the commands out and runs\nnothing, for the case where the signing happens somewhere else.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog)\n\n**Dependency graph:**\n\n![gno.land/r/moul/blog dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/blog/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"blog.gno","body":"// Package blog is moul's personal blog on gno.land: one realm, one author,\n// posts that live in chain storage rather than in the code.\n//\n// # The shape\n//\n// A post is markdown plus four fields (slug, title, date, tags). Writing one\n// is a single Set transaction, so publishing never redeploys the realm and\n// fixing a typo costs one small call instead of a new package path.\n//\n// The reader-facing paths are deliberately short, because they get pasted into\n// other people's chats:\n//\n//\tgno.land/r/moul/blog             the index, newest first\n//\tgno.land/r/moul/blog:\u003cslug\u003e      one post\n//\tgno.land/r/moul/blog:t/\u003ctag\u003e     every post carrying a tag\n//\n// # Ordering without sort\n//\n// gno has no sort.Slice, and avl.Tree iterates by key. So posts live in two\n// trees: `posts` keyed by slug, for the O(log n) lookup a permalink needs, and\n// `order` keyed by \"\u003cdate\u003e/\u003cslug\u003e\", walked in reverse for newest-first. The\n// date is YYYY-MM-DD precisely so that lexical order is chronological order,\n// which is what makes the second tree free.\n//\n// # Versioning\n//\n// gnomod.toml declares private = true, which lets the creator re-add the\n// package at this exact path. That redeploy re-runs init() and WIPES every\n// post here, so the markdown kept off chain is the source of truth and\n// tools/gnoblog pushes it back. Trading that risk for a stable URL is the\n// whole design: a /v1 would break every link already shared, a redeploy does\n// not, and Manifest() makes restoring the content one diff.\npackage blog\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// author is the only address allowed to write. Deliberately a constant rather\n// than transferable ownership: this is one person's blog, and the same address\n// is the only one the chain lets redeploy the realm anyway, so a second owner\n// could publish posts it could never restore after a wipe.\nconst author = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\n// realmPath is this realm's own path, used to build the links Render emits.\nconst realmPath = \"gno.land/r/moul/blog\"\n\n// maxSlugLen bounds a slug so a permalink stays typable and a key stays cheap.\nconst maxSlugLen = 64\n\n// excerptLen is how much of a post body the index shows.\nconst excerptLen = 200\n\n// introKey is the manifest key of the index header. It starts with '!', which\n// validSlug rejects, so it can never collide with a post.\nconst introKey = \"!intro\"\n\n// introSlug is refused as a post slug. Not because this realm needs it: the\n// intro lives in its own variable. It is refused so that the local half stays\n// representable, where a post is \u003cslug\u003e.md and the header is intro.md. A post\n// published at this slug by a hand-written transaction would have no file it\n// could live in, and tools/gnoblog would report it as an extra forever.\nconst introSlug = \"intro\"\n\ntype post struct {\n\tslug    string\n\ttitle   string\n\tdate    string // YYYY-MM-DD, the sort key\n\ttags    string // comma-separated, normalized by splitTags\n\tbody    string // raw markdown, authored by `author`, rendered unescaped\n\trev     int    // rev at the time of the last write to this post\n\tupdated int64  // block height of the last write\n}\n\nvar (\n\tposts = avl.NewTree() // slug             -\u003e *post\n\torder = avl.NewTree() // \"\u003cdate\u003e/\u003cslug\u003e\"  -\u003e *post\n\tintro string          // markdown shown above the index\n\trev   int             // total writes accepted, bumped by every mutation\n)\n\nfunc assertAuthor(cur realm) {\n\tif cur.Previous().Address() != author {\n\t\tpanic(\"restricted to the author\")\n\t}\n}\n\n// validSlug reports whether slug is a legal permalink: 1..maxSlugLen bytes of\n// [a-z0-9._-]. The character set excludes ':' and '/' so a slug can never\n// break out of its own render path, and excludes uppercase so a post has\n// exactly one URL.\nfunc validSlug(slug string) bool {\n\tif len(slug) == 0 || len(slug) \u003e maxSlugLen {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(slug); i++ {\n\t\tc := slug[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '-', c == '_', c == '.':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// validDate reports whether date is exactly YYYY-MM-DD. The format is not\n// cosmetic: `order` relies on lexical order being chronological order, so a\n// date of any other shape would silently sort into the wrong place.\nfunc validDate(date string) bool {\n\tif len(date) != 10 {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c 10; i++ {\n\t\tc := date[i]\n\t\tif i == 4 || i == 7 {\n\t\t\tif c != '-' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif c \u003c '0' || c \u003e '9' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// orderKey is the key a post takes in `order`. The slug is appended so two\n// posts published on the same day do not collide.\nfunc orderKey(date, slug string) string { return date + \"/\" + slug }\n\n// splitTags normalizes a comma-separated tag list: trimmed, lowercased,\n// deduplicated, empties dropped. It returns the canonical string that gets\n// stored, so the hash a client computes locally matches the one on chain.\nfunc splitTags(tags string) []string {\n\tvar out []string\n\tfor _, t := range strings.Split(tags, \",\") {\n\t\tt = strings.ToLower(strings.TrimSpace(t))\n\t\tif t == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdup := false\n\t\tfor _, seen := range out {\n\t\t\tif seen == t {\n\t\t\t\tdup = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !dup {\n\t\t\tout = append(out, t)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc joinTags(tags []string) string { return strings.Join(tags, \",\") }\n\n// record is the canonical serialization a post hashes to. Both this realm and\n// tools/gnoblog build it the same way, which is what lets one Manifest() read\n// decide whether a local file needs a transaction at all.\nfunc record(title, date, tags, body string) string {\n\treturn title + \"\\n\" + date + \"\\n\" + tags + \"\\n\" + body\n}\n\nfunc hashOf(s string) string {\n\tsum := sha256.Sum256([]byte(s))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// Set creates or replaces the post at slug. This is the ordinary publish: one\n// post, one transaction, idempotent.\n//\n// Changing the date moves the post in the index, so the old order entry is\n// removed before the new one is written.\nfunc Set(cur realm, slug, title, date, tags, body string) {\n\tassertAuthor(cur)\n\tif !validSlug(slug) {\n\t\tpanic(\"invalid slug: want 1-\" + strconv.Itoa(maxSlugLen) + \" bytes of [a-z0-9._-], got \" + strconv.Quote(slug))\n\t}\n\tif slug == introSlug {\n\t\tpanic(\"reserved slug: \" + introSlug + \" names the index header, set it with SetIntro\")\n\t}\n\tif !validDate(date) {\n\t\tpanic(\"invalid date: want YYYY-MM-DD, got \" + strconv.Quote(date))\n\t}\n\ttitle = strings.TrimSpace(title)\n\tif title == \"\" {\n\t\tpanic(\"a post needs a title\")\n\t}\n\n\tif v := posts.Get(slug); v != nil {\n\t\torder.Remove(orderKey(v.(*post).date, slug))\n\t}\n\n\trev++\n\tp := \u0026post{\n\t\tslug:    slug,\n\t\ttitle:   title,\n\t\tdate:    date,\n\t\ttags:    joinTags(splitTags(tags)),\n\t\tbody:    body,\n\t\trev:     rev,\n\t\tupdated: runtime.ChainHeight(),\n\t}\n\tposts.Set(slug, p)\n\torder.Set(orderKey(date, slug), p)\n}\n\n// Append adds to the end of a post's body. It exists for a body too large to\n// fit in one transaction: Set the first chunk, Append the rest. An ordinary\n// edit uses Set, which is idempotent and therefore safe to retry.\nfunc Append(cur realm, slug, body string) {\n\tassertAuthor(cur)\n\tv := posts.Get(slug)\n\tif v == nil {\n\t\tpanic(\"no such post: \" + strconv.Quote(slug))\n\t}\n\tp := v.(*post)\n\trev++\n\tp.body += body\n\tp.rev = rev\n\tp.updated = runtime.ChainHeight()\n}\n\n// Delete removes a post and its index entry.\nfunc Delete(cur realm, slug string) {\n\tassertAuthor(cur)\n\tv, removed := posts.Remove(slug)\n\tif !removed {\n\t\tpanic(\"no such post: \" + strconv.Quote(slug))\n\t}\n\torder.Remove(orderKey(v.(*post).date, slug))\n\trev++\n}\n\n// SetIntro replaces the markdown shown above the index. Passing \"\" restores\n// the built-in header.\nfunc SetIntro(cur realm, body string) {\n\tassertAuthor(cur)\n\trev++\n\tintro = body\n}\n\n// Get returns a post's raw markdown body, or \"\" when there is no such post.\nfunc Get(slug string) string {\n\tv := posts.Get(slug)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(*post).body\n}\n\n// Count returns the number of published posts.\nfunc Count() int { return posts.Size() }\n\n// Revision returns the total number of writes this realm has accepted. It\n// changes on every mutation, so a client can cheaply tell \"nothing moved\".\nfunc Revision() int { return rev }\n\n// Manifest returns one tab-separated line per post, plus one for the intro:\n//\n//\t\u003cslug\u003e\\t\u003crev\u003e\\t\u003cdate\u003e\\t\u003clen of body\u003e\\t\u003csha256 of the canonical record\u003e\n//\n// It is the diff surface tools/gnoblog reads with a single vm/qeval: the hash\n// covers the title, date, tags and body together, so one read says exactly\n// which local file needs a transaction without downloading a single body.\n//\n// The intro is reported under the key \"!intro\" with an empty date. '!' is not\n// a legal slug character, so that row can never be confused with a post.\nfunc Manifest() string {\n\tvar b strings.Builder\n\n\tb.WriteString(introKey)\n\tb.WriteString(\"\\t0\\t\\t\")\n\tb.WriteString(strconv.Itoa(len(intro)))\n\tb.WriteString(\"\\t\")\n\tb.WriteString(hashOf(intro))\n\tb.WriteString(\"\\n\")\n\n\tposts.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tp := value.(*post)\n\t\tb.WriteString(p.slug)\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.Itoa(p.rev))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(p.date)\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.Itoa(len(p.body)))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(hashOf(record(p.title, p.date, p.tags, p.body)))\n\t\tb.WriteString(\"\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n"},{"name":"blog_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// reset empties every package-level variable. ExampleRender runs after every\n// Test in this package and would otherwise render whatever they left behind,\n// so both the tests and the example start from here.\nfunc reset() {\n\tposts = avl.NewTree()\n\torder = avl.NewTree()\n\tintro = \"\"\n\trev = 0\n}\n\n// seed writes a post without going through Set, so a caller needs no\n// `cur realm` and the example stays a plain function.\nfunc seed(slug, title, date, tags, body string) {\n\trev++\n\tp := \u0026post{\n\t\tslug:  slug,\n\t\ttitle: title,\n\t\tdate:  date,\n\t\ttags:  joinTags(splitTags(tags)),\n\t\tbody:  body,\n\t\trev:   rev,\n\t}\n\tposts.Set(slug, p)\n\torder.Set(orderKey(date, slug), p)\n}\n\nfunc TestValidSlug(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tslug string\n\t\twant bool\n\t}{\n\t\t{\"mygnoscan\", true},\n\t\t{\"a\", true},\n\t\t{\"hello-world.2\", true},\n\t\t{\"under_score\", true},\n\t\t{\"\", false},\n\t\t{\"Caps\", false},\n\t\t{\"has space\", false},\n\t\t{\"colon:here\", false},\n\t\t{\"slash/here\", false},\n\t\t{\"!intro\", false},\n\t\t{strings.Repeat(\"a\", maxSlugLen), true},\n\t\t{strings.Repeat(\"a\", maxSlugLen+1), false},\n\t} {\n\t\tuassert.Equal(t, tc.want, validSlug(tc.slug), \"validSlug(\"+tc.slug+\")\")\n\t}\n}\n\nfunc TestValidDate(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdate string\n\t\twant bool\n\t}{\n\t\t{\"2026-09-23\", true},\n\t\t{\"0000-00-00\", true}, // shape only: ordering is all this field is for\n\t\t{\"2026-9-23\", false},\n\t\t{\"2026/09/23\", false},\n\t\t{\"2026-09-233\", false},\n\t\t{\"\", false},\n\t} {\n\t\tuassert.Equal(t, tc.want, validDate(tc.date), \"validDate(\"+tc.date+\")\")\n\t}\n}\n\nfunc TestSplitTagsNormalizes(t *testing.T) {\n\tfor _, tc := range []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"gno\", \"gno\"},\n\t\t{\" Gno , TOOLING \", \"gno,tooling\"},\n\t\t{\"gno,gno,gno\", \"gno\"},\n\t\t{\"gno,,tooling\", \"gno,tooling\"},\n\t} {\n\t\tuassert.Equal(t, tc.want, joinTags(splitTags(tc.in)), \"splitTags(\"+tc.in+\")\")\n\t}\n}\n\n// A post published earlier must render below one published later, which is\n// the only thing the second tree exists to guarantee.\nfunc TestIndexIsNewestFirst(t *testing.T) {\n\treset()\n\tseed(\"older\", \"Older\", \"2026-01-01\", \"\", \"First.\")\n\tseed(\"newer\", \"Newer\", \"2026-09-23\", \"\", \"Second.\")\n\n\tout := Render(\"\")\n\tiNew := strings.Index(out, \"Newer\")\n\tiOld := strings.Index(out, \"Older\")\n\tuassert.True(t, iNew \u003e= 0 \u0026\u0026 iOld \u003e= 0, \"both posts render\")\n\tuassert.True(t, iNew \u003c iOld, \"the newer post renders first\")\n}\n\n// Re-dating a post has to move it, not leave a ghost entry behind at the old\n// key. Set is the only path that can do this, so it is checked through Set.\nfunc TestRedatingMovesTheIndexEntry(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-01-01\", \"\", \"Body A.\")\n\tuassert.Equal(t, 1, order.Size(), \"one order entry\")\n\n\t// Emulate Set's re-key without needing a realm: remove then re-add.\n\tp := posts.Get(\"a\").(*post)\n\torder.Remove(orderKey(p.date, \"a\"))\n\tp.date = \"2026-12-31\"\n\torder.Set(orderKey(p.date, \"a\"), p)\n\n\tuassert.Equal(t, 1, order.Size(), \"still one order entry, not two\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"2026-12-31\"), \"the new date renders\")\n}\n\nfunc TestRenderPostAndNotFound(t *testing.T) {\n\treset()\n\tseed(\"mygnoscan\", \"Sharing mygnoscan\", \"2026-09-23\", \"mygnoscan,tooling\", \"## Why\\n\\nBecause it is useful.\")\n\n\tout := Render(\"mygnoscan\")\n\tuassert.True(t, strings.Contains(out, \"# Sharing mygnoscan\"), \"title renders as the H1\")\n\tuassert.True(t, strings.Contains(out, \"Because it is useful.\"), \"body renders verbatim\")\n\tuassert.True(t, strings.Contains(out, \"## Why\"), \"markdown in the body is not escaped\")\n\n\tmissing := Render(\"nope\")\n\tuassert.True(t, strings.Contains(missing, \"Not found\"), \"an unknown slug is a 404, not the index\")\n}\n\nfunc TestRenderTagFiltersAndReportsEmpty(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-01-01\", \"tooling\", \"Body A.\")\n\tseed(\"b\", \"B\", \"2026-01-02\", \"chain\", \"Body B.\")\n\n\tout := Render(\"t/tooling\")\n\tuassert.True(t, strings.Contains(out, \"A\"), \"the tagged post is listed\")\n\tuassert.False(t, strings.Contains(out, \"](/r/moul/blog:b)\"), \"the untagged post is not\")\n\n\tempty := Render(\"t/nothing\")\n\tuassert.True(t, strings.Contains(empty, \"No post carries this tag.\"), \"an unused tag says so\")\n}\n\n// The manifest is the whole diff protocol. A change to any of the four fields\n// the record covers has to change the hash, or gnoblog reports a stale post as\n// up to date and the fix never gets pushed.\nfunc TestManifestHashCoversEveryField(t *testing.T) {\n\tbase := record(\"T\", \"2026-01-01\", \"a\", \"body\")\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tgot  string\n\t}{\n\t\t{\"title\", record(\"T2\", \"2026-01-01\", \"a\", \"body\")},\n\t\t{\"date\", record(\"T\", \"2026-01-02\", \"a\", \"body\")},\n\t\t{\"tags\", record(\"T\", \"2026-01-01\", \"b\", \"body\")},\n\t\t{\"body\", record(\"T\", \"2026-01-01\", \"a\", \"body2\")},\n\t} {\n\t\tuassert.NotEqual(t, hashOf(base), hashOf(tc.got), \"changing the \"+tc.name+\" changes the hash\")\n\t}\n}\n\nfunc TestManifestShape(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-01-01\", \"tooling\", \"Body A.\")\n\n\tlines := strings.Split(strings.TrimRight(Manifest(), \"\\n\"), \"\\n\")\n\tuassert.Equal(t, 2, len(lines), \"one intro row plus one post row\")\n\tuassert.True(t, strings.HasPrefix(lines[0], introKey+\"\\t\"), \"the intro row comes first\")\n\n\tf := strings.Split(lines[1], \"\\t\")\n\tuassert.Equal(t, 5, len(f), \"five tab-separated fields\")\n\tuassert.Equal(t, \"a\", f[0], \"slug\")\n\tuassert.Equal(t, \"2026-01-01\", f[2], \"date\")\n\tuassert.Equal(t, \"7\", f[3], \"body length\")\n\tuassert.Equal(t, hashOf(record(\"A\", \"2026-01-01\", \"tooling\", \"Body A.\")), f[4], \"record hash\")\n}\n\nfunc TestFirstLineSkipsHeadings(t *testing.T) {\n\tuassert.Equal(t, \"The prose.\", firstLine(\"# Title\\n\\n## Sub\\n\\nThe prose.\\n\"))\n\tuassert.Equal(t, \"\", firstLine(\"# Only a heading\\n\"))\n}\n\nfunc TestIntroDefaultsAndOverrides(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"\"), \"moul's blog\"), \"the built-in header shows before SetIntro\")\n\n\tintro = \"# Something else\"\n\tuassert.True(t, strings.Contains(Render(\"\"), \"Something else\"), \"a set intro replaces it\")\n\tuassert.False(t, strings.Contains(Render(\"\"), \"moul's blog\"), \"and the default is gone\")\n}\n\n// A markdown link in the first line of a post reached the index as its own\n// source, backslash-escaped, on 2026-09-23. The excerpt is plain text, so the\n// link has to be flattened before ui.Excerpt escapes what is left.\nfunc TestFlattenLinks(t *testing.T) {\n\tfor _, tc := range []struct{ in, want string }{\n\t\t{\"plain text\", \"plain text\"},\n\t\t{\"I built [mygnoscan](https://x.example) in April\", \"I built mygnoscan in April\"},\n\t\t{\"[a](1) and [b](2)\", \"a and b\"},\n\t\t{\"\", \"\"},\n\t\t// Unbalanced: left alone rather than half-parsed.\n\t\t{\"an [unclosed link\", \"an [unclosed link\"},\n\t\t{\"brackets [only] here\", \"brackets [only] here\"},\n\t\t{\"[text](no-close\", \"[text](no-close\"},\n\t} {\n\t\tuassert.Equal(t, tc.want, flattenLinks(tc.in), \"flattenLinks(\"+tc.in+\")\")\n\t}\n}\n\n// The index excerpt must read as a sentence, not as markdown source.\nfunc TestExcerptIsProseNotSource(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-09-23\", \"\", \"I built [mygnoscan](https://mygnoscan.example) in April.\")\n\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, \"\\\\[\"), \"no escaped bracket survives into the index\")\n\tuassert.True(t, strings.Contains(out, \"I built mygnoscan in April\"), \"the excerpt reads as prose\")\n}\n\n// The back link is the realm root, which carries no ':'. linkPrefix with an\n// empty path would produce \"/r/moul/blog:\", which shipped on 2026-09-23.\nfunc TestBackLinkHasNoTrailingColon(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-09-23\", \"tag\", \"Body.\")\n\n\tfor _, view := range []string{\"a\", \"t/tag\", \"nosuchpost\"} {\n\t\tout := Render(view)\n\t\tuassert.True(t, strings.Contains(out, \"](\"+indexLink+\")\"), view+\" links back to the index\")\n\t\tuassert.False(t, strings.Contains(out, \"](\"+indexLink+\":)\"), view+\" must not emit a trailing colon\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/blog\"\ngno = \"0.9\"\n\n# Redeployable by its creator. See README.md § \"Why private, and why no /vN\".\n#\n# A private package may be re-added at the same path by the address recorded in\n# [addpkg].creator (gno.land/pkg/sdk/vm/keeper.go, checkRedeployPermission), and\n# nothing else may import it. A redeploy RE-RUNS init() and resets realm state,\n# so the markdown kept off chain is the source of truth and tools/gnoblog pushes\n# every post back. That wipe is the reason the post URL can stay version-free:\n# a code change is a redeploy of this path, never a /v1 that moves every link\n# already shared.\nprivate = true\n"},{"name":"render.gno","body":"package blog\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// linkPrefix is what a permalink starts with. gnoweb addresses a realm's\n// render path with ':' after the package path, so this is realmPath with the\n// leading \"gno.land\" dropped and the separator appended.\nconst linkPrefix = \"/r/moul/blog:\"\n\n// indexLink is the index, which is the realm root and therefore has NO ':'.\n// Spelled separately rather than reusing linkPrefix, because linkPrefix with\n// an empty path produces a trailing colon and a link nobody wants to paste.\nconst indexLink = \"/r/moul/blog\"\n\n// defaultIntro is the header shown before SetIntro has ever been called, i.e.\n// right after the first deploy or after a redeploy wiped the state.\nconst defaultIntro = \"# moul's blog\\n\\nNotes on gno.land, from the person building on it.\\n\"\n\n// Render serves three views:\n//\n//\t\"\"         the index, newest first\n//\t\"\u003cslug\u003e\"   one post\n//\t\"t/\u003ctag\u003e\"  every post carrying a tag\n// Render wraps every view in the notice blocks from gno.land/r/moul/config: a\n// warning, a changelog line or a bit of news, set either on every realm of\n// moul's at once or on this one alone, plus a pause banner if this realm is\n// ever held back. Both are empty by default, so an unconfigured chain renders\n// exactly what it rendered before.\n//\n// The path is passed explicitly rather than using config's zero-argument\n// helpers. Both work, but this realm already states its own path for its\n// permalinks, and a constant cannot be wrong.\nfunc Render(path string) string {\n\treturn config.TopBlockFor(realmPath) + render(path) + config.BottomBlockFor(realmPath)\n}\n\nfunc render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tswitch {\n\tcase path == \"\":\n\t\treturn renderIndex()\n\tcase strings.HasPrefix(path, \"t/\"):\n\t\treturn renderTag(strings.TrimPrefix(path, \"t/\"))\n\tdefault:\n\t\treturn renderPost(path)\n\t}\n}\n\nfunc header() string {\n\tif intro == \"\" {\n\t\treturn defaultIntro\n\t}\n\treturn strings.TrimRight(intro, \"\\n\") + \"\\n\"\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(header())\n\n\tif posts.Size() == 0 {\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(ui.Empty(\"Nothing published yet.\"))\n\t\treturn b.String()\n\t}\n\n\t// order is keyed by \"\u003cdate\u003e/\u003cslug\u003e\", so walking it backwards is\n\t// newest-first without a sort the language does not have.\n\torder.ReverseIterate(\"\", \"\", func(_ string, value any) bool {\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(entry(value.(*post)))\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\nfunc renderTag(tag string) string {\n\ttag = strings.ToLower(strings.TrimSpace(tag))\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Tagged \")\n\tb.WriteString(ui.Inline(tag))\n\tb.WriteString(\"\\n\")\n\n\tfound := 0\n\torder.ReverseIterate(\"\", \"\", func(_ string, value any) bool {\n\t\tp := value.(*post)\n\t\tif !hasTag(p, tag) {\n\t\t\treturn false\n\t\t}\n\t\tfound++\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(entry(p))\n\t\treturn false\n\t})\n\tif found == 0 {\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(ui.Empty(\"No post carries this tag.\"))\n\t}\n\tb.WriteString(\"\\n[← all posts](\" + indexLink + \")\\n\")\n\treturn b.String()\n}\n\nfunc renderPost(slug string) string {\n\tv := posts.Get(slug)\n\tif v == nil {\n\t\treturn \"# Not found\\n\\nNo post at \" + strconv.Quote(ui.Inline(slug)) +\n\t\t\t\".\\n\\n[← all posts](\" + indexLink + \")\\n\"\n\t}\n\tp := v.(*post)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# \")\n\tb.WriteString(ui.Inline(p.title))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(byline(p))\n\tb.WriteString(\"\\n\\n\")\n\t// The body is markdown written by `author`, who is also the only address\n\t// that can call Set. It is the post, so it renders verbatim: escaping it\n\t// would turn every heading and link in it into literal text.\n\tb.WriteString(strings.TrimRight(p.body, \"\\n\"))\n\tb.WriteString(\"\\n\\n---\\n\\n[← all posts](\" + indexLink + \")\\n\")\n\treturn b.String()\n}\n\n// entry is one row of a listing: linked title, byline, excerpt.\nfunc entry(p *post) string {\n\tvar b strings.Builder\n\tb.WriteString(\"## [\")\n\tb.WriteString(ui.Inline(p.title))\n\tb.WriteString(\"](\")\n\tb.WriteString(linkPrefix)\n\tb.WriteString(p.slug)\n\tb.WriteString(\")\\n\\n\")\n\tb.WriteString(byline(p))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(ui.Excerpt(flattenLinks(firstLine(p.body)), excerptLen))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\n// byline is the date plus the post's tags as links, on one line.\nfunc byline(p *post) string {\n\tvar b strings.Builder\n\tb.WriteString(p.date)\n\tfor _, t := range splitTags(p.tags) {\n\t\tb.WriteString(\" · [#\")\n\t\tb.WriteString(ui.Inline(t))\n\t\tb.WriteString(\"](\")\n\t\tb.WriteString(linkPrefix)\n\t\tb.WriteString(\"t/\")\n\t\tb.WriteString(t)\n\t\tb.WriteString(\")\")\n\t}\n\treturn b.String()\n}\n\nfunc hasTag(p *post, tag string) bool {\n\tfor _, t := range splitTags(p.tags) {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// flattenLinks rewrites \"[text](url)\" to \"text\".\n//\n// An excerpt is plain text: ui.Excerpt escapes what it is given, so a markdown\n// link survives into the index as its own source, backslashes and all, and the\n// reader sees `[mygnoscan](https://...)` where a sentence should be. Shipped\n// exactly that way on 2026-09-23 and it was the first thing on the page.\n//\n// Dropping the URL rather than keeping it bare is deliberate: the title beside\n// it is already a link to the post, and a second URL in a two-line preview is\n// noise. Unbalanced brackets are left alone and escaped as before, because a\n// half-parsed link is worse than an unparsed one.\nfunc flattenLinks(s string) string {\n\tvar b strings.Builder\n\tfor {\n\t\topen := strings.Index(s, \"[\")\n\t\tif open \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\tclose := strings.Index(s[open:], \"](\")\n\t\tif close \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\tclose += open\n\t\tend := strings.Index(s[close:], \")\")\n\t\tif end \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\tend += close\n\t\tb.WriteString(s[:open])\n\t\tb.WriteString(s[open+1 : close])\n\t\ts = s[end+1:]\n\t}\n\tb.WriteString(s)\n\treturn b.String()\n}\n\n// firstLine returns the first non-empty, non-heading line of a body, which is\n// what an excerpt should show: a post that opens with \"## Something\" would\n// otherwise preview its own heading.\nfunc firstLine(body string) string {\n\tfor _, line := range strings.Split(body, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\t\treturn line\n\t}\n\treturn \"\"\n}\n"},{"name":"render_example_test.gno","body":"package blog\n\nimport \"testing\"\n\n// ExampleRender pins the index. It seeds state directly (rather than through\n// Set) so the example takes no `cur realm`, and it resets first because an\n// example runs after every Test in the package and would otherwise render what\n// they left behind.\nfunc ExampleRender() {\n\treset()\n\tseed(\"mygnoscan\", \"Sharing mygnoscan\", \"2026-09-23\", \"mygnoscan,tooling\", \"An unfinished BI tool for gno.land.\")\n\tseed(\"hello\", \"Hello\", \"2026-09-01\", \"meta\", \"Starting a blog on chain.\")\n\tprint(Render(\"\"))\n\t// Output:\n\t// # moul's blog\n\t//\n\t// Notes on gno.land, from the person building on it.\n\t//\n\t// ## [Sharing mygnoscan](/r/moul/blog:mygnoscan)\n\t//\n\t// 2026-09-23 · [#mygnoscan](/r/moul/blog:t/mygnoscan) · [#tooling](/r/moul/blog:t/tooling)\n\t//\n\t// An unfinished BI tool for gno\\.land\\.\n\t//\n\t// ## [Hello](/r/moul/blog:hello)\n\t//\n\t// 2026-09-01 · [#meta](/r/moul/blog:t/meta)\n\t//\n\t// Starting a blog on chain\\.\n}\n\n// TestNoticeBlocksAreTransparentByDefault pins the property that made it safe\n// to wrap every view in them: with nothing set on r/moul/config, Render is\n// byte-for-byte the inner render. If that ever stops holding, every page of\n// this blog gains stray whitespace at the top and the bottom.\nfunc TestNoticeBlocksAreTransparentByDefault(t *testing.T) {\n\tfor _, path := range []string{\"\", \"t/gno\", \"no-such-post\"} {\n\t\tif Render(path) != render(path) {\n\t\t\tt.Fatalf(\"Render(%q) differs from the inner render with no notice configured\", path)\n\t\t}\n\t}\n}\n"},{"name":"write_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar stranger = testutils.TestAddress(\"stranger\")\n\n// Everything here goes through the real crossing functions rather than seed(),\n// because the author check, the re-key on a date change and the panic messages\n// only exist on that path and are exactly what a typo would break on a\n// permanent path.\n\nfunc TestSetPublishesAndRenders(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tSet(cross(cur), \"hello\", \"Hello\", \"2026-09-23\", \"Gno, tooling\", \"The body.\")\n\n\tuassert.Equal(t, 1, Count(), \"one post\")\n\tuassert.Equal(t, \"The body.\", Get(\"hello\"), \"the body round-trips\")\n\tuassert.True(t, strings.Contains(Render(\"hello\"), \"# Hello\"), \"it renders\")\n\t// Tags are normalized on write, not on read, so the hash the tool computed\n\t// locally is the hash the manifest reports.\n\tuassert.True(t, strings.Contains(Manifest(), \"\\t\"+hashOf(record(\"Hello\", \"2026-09-23\", \"gno,tooling\", \"The body.\"))),\n\t\t\"the manifest hashes the normalized record\")\n}\n\nfunc TestOnlyTheAuthorMayWrite(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(stranger))\n\t// AbortsWithMessage, not PanicsWithMessage: a panic that crosses a realm\n\t// boundary becomes an abort, which recover() cannot catch, so asserting it\n\t// as a panic does not fail the assertion, it kills the whole test binary.\n\tuassert.AbortsWithMessage(t, cur, \"restricted to the author\", func() {\n\t\tSet(cross(cur), \"nope\", \"Nope\", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"restricted to the author\", func() {\n\t\tSetIntro(cross(cur), \"mine now\")\n\t})\n\tuassert.Equal(t, 0, Count(), \"nothing was written\")\n}\n\n// The one case a second tree can get wrong: re-dating a post must MOVE its\n// index entry, not leave a ghost at the old key rendering the post twice.\nfunc TestSetRedatingMovesTheIndexEntry(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tSet(cross(cur), \"a\", \"A\", \"2026-01-01\", \"\", \"Body A.\")\n\tSet(cross(cur), \"a\", \"A\", \"2026-12-31\", \"\", \"Body A.\")\n\n\tuassert.Equal(t, 1, Count(), \"still one post\")\n\tout := Render(\"\")\n\tuassert.Equal(t, 1, strings.Count(out, \"](/r/moul/blog:a)\"), \"listed exactly once\")\n\tuassert.True(t, strings.Contains(out, \"2026-12-31\"), \"under the new date\")\n\tuassert.False(t, strings.Contains(out, \"2026-01-01\"), \"and not the old one\")\n}\n\nfunc TestSetRejectsWhatTheToolRejects(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tuassert.AbortsContains(t, cur, \"invalid slug\", func() {\n\t\tSet(cross(cur), \"Caps\", \"T\", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved slug\", func() {\n\t\tSet(cross(cur), introSlug, \"T\", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsContains(t, cur, \"invalid date\", func() {\n\t\tSet(cross(cur), \"ok\", \"T\", \"23-09-2026\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsContains(t, cur, \"a post needs a title\", func() {\n\t\tSet(cross(cur), \"ok\", \"  \", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.Equal(t, 0, Count(), \"none of them was written\")\n}\n\nfunc TestAppendAndDelete(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tSet(cross(cur), \"long\", \"Long\", \"2026-09-23\", \"\", \"First half.\")\n\tAppend(cross(cur), \"long\", \" Second half.\")\n\tuassert.Equal(t, \"First half. Second half.\", Get(\"long\"), \"append concatenates, it does not replace\")\n\n\tuassert.AbortsWithMessage(t, cur, `no such post: \"ghost\"`, func() {\n\t\tAppend(cross(cur), \"ghost\", \"x\")\n\t})\n\n\tDelete(cross(cur), \"long\")\n\tuassert.Equal(t, 0, Count(), \"deleted\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"Nothing published yet.\"), \"and gone from the index\")\n\tuassert.AbortsWithMessage(t, cur, `no such post: \"long\"`, func() {\n\t\tDelete(cross(cur), \"long\")\n\t})\n}\n\nfunc TestRevisionMovesOnEveryWrite(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tuassert.Equal(t, 0, Revision(), \"a fresh realm is at zero\")\n\tSet(cross(cur), \"a\", \"A\", \"2026-09-23\", \"\", \"Body.\")\n\tAppend(cross(cur), \"a\", \"!\")\n\tSetIntro(cross(cur), \"# Header\")\n\tDelete(cross(cur), \"a\")\n\tuassert.Equal(t, 4, Revision(), \"one per mutation, so a client can tell nothing moved\")\n}\n"}]},"send":"","max_deposit":"15000000ugnot"}],"fee":{"gas_wanted":"104583400","gas_fee":"313750ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"6WbyD6o3Jxbf9QY+ChysRmD7uU22uqa/vTtM6g+fHMUHrq2ULe1pI8PP2gmCY9KqhNykeecr/ZGh34Wj7RxYIw=="}],"memo":""},"metadata":{"timestamp":"1790961883"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"home","path":"gno.land/r/moul/home","files":[{"name":"README.md","body":"# `gno.land/r/moul/home`\n\nThe realm behind **https://gno.land/u/moul**. A profile page whose content is\ndata, not code: update a paragraph with one small transaction instead of\nredeploying a realm.\n\n## Why this one has no `/vN`\n\nIt is the only contract in this repo at an unversioned path, and that is forced,\nnot a slip.\n\ngnoweb builds a user profile by calling `Render(\"\")` on the realm at the **exact**\npath `/r/\u003cusername\u003e/home` and embedding the result as the page body\n([`gno.land/pkg/gnoweb/handler_http.go`][handler], `GetUserView`). That lookup does\nno version resolution, so `gno.land/r/moul/home/v0` would never be found. The bare\npath *is* the interface with gnoweb.\n\nVersioning moves inside instead: content lives in slots (below), and the code can\nbe replaced in place because the package is `private`.\n\nThis is also why `gnopm bump` refuses this package: it looks for a trailing\n`/vN` on the module line to increment and there is none. The module line stays\nbare, `gnopm status` and `gnopm verify` accept it, and only `bump` is off the\ntable. A compatibility change here is a redeploy of the same path, not a new\nversion.\n\n### What it replaces: `gno.land/r/moul/home/v0`\n\nThis directory used to hold a different realm: a hand-maintained dashboard with\na todo list, a status string and a meme URL, its state mutable only by the admin\nand its *shape* only by redeploying. It never reached any network\n(`contracts.json` had it `uploaded: false` everywhere), so nothing on chain is\nbeing replaced, only the source.\n\nThat version is not deleted, it is **pinned to history** in `gnomod.lock` the way\n`AGENTS.md` prescribes for a superseded version:\n\n```toml\n[[module]]\nmodule = \"gno.land/r/moul/home/v0\"\nsource = { commit = \"4f2df83869b80470eb81c48a82fdbe82256b8113\", dir = \"r/moul/home\" }\n```\n\nSo it keeps resolving for anything that imports it, `gnopm sync` materializes it\nunder `.gnopm/`, and it is still linted and tested from there. Read the code at\n[`r/moul/home` @ 4f2df83][v0], the last commit where this directory held it.\n\n[handler]: https://github.com/gnolang/gno/blob/master/gno.land/pkg/gnoweb/handler_http.go\n[v0]: https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/home\n\n## Slots\n\nThe page is assembled from **slots**: named markdown fragments in an avl tree.\n\n| function | what it does |\n| --- | --- |\n| `Set(cur, slug, body)` | create or replace one slot, the ordinary update |\n| `Append(cur, slug, body)` | append, for a body too large for one transaction |\n| `Delete(cur, slug)` | remove a slot |\n| `Get(slug)` | read one body |\n| `Manifest()` | `slug⇥rev⇥len⇥sha256` per slot, the diff surface |\n| `Revision()` | total writes accepted, so a client can tell \"nothing moved\" |\n\nWrites are restricted to `g1manfred47kzduec920z88wfr64ylksmdcedlf5`.\n\nA slug is 1–64 bytes of `[a-z0-9._-]`. No `':'`, so a slug can never break out of\nits own `:slug:` placeholder.\n\n## The layout is a slot too\n\n`Render(\"\")` takes the slot named `layout` as its template and fills every\n`:slug:` placeholder in it with `p/moul/dynreplacer`. So the shape of the page\n(headings, order, what appears at all) changes without touching the code:\n\n```\n\u003cgno-columns\u003e\n![Manfred Touron](https://avatars.githubusercontent.com/u/94029?s=400)\n\u003cgno-columns-sep /\u003e\n# Manfred Touron\n\n:bio:\n\n:social:\n\u003c/gno-columns\u003e\n\n## Packages\n\n:packages:\n```\n\n`\u003cgno-columns\u003e` / `\u003cgno-columns-sep /\u003e` are gnoweb's own extension, not HTML:\nraw HTML is not rendered, these are parsed. Adding a section is a **content**\nchange, never a code one: the renderer registers one placeholder per slot by\niterating the tree, so writing `content/social.md` and referencing `:social:`\nis the whole of it.\n\n### The slots this page ships with\n\n`content/` is the source of truth, one file per slot, the slug being the file\nname without `.md`. Nothing registers them: `gnohome` reads the directory and\nthe realm iterates the tree.\n\n| slot | what it is |\n| --- | --- |\n| `bio` | who I am, and what this page is, in the header column |\n| `social` | the links under it |\n| `now` | what I am working on, hand-written, and deliberately free of counts |\n| `stack` | the tools, one line |\n| `packages` | **generated** from contracts.json on `main`; a PR may not carry it |\n| `about` | a collapsed `\u003e [!NOTE]-` explaining that this page is a realm |\n| `layout` | the template all of the above are filled into |\n\n`about` is deliberately last and deliberately collapsed. gnoweb renders an alert\nas `\u003cdetails\u003e`, and a `-` after the type closes it\n(`gno.land/pkg/gnoweb/markdown/ext_alert.go`), so the mechanism is one click away\ninstead of occupying the paragraph where a reader decides whether to keep going.\n\n### `layout` may only reference placeholders that are deployed\n\nAn unmatched placeholder survives into the output verbatim (see below), which\nmakes the layout slot the one file that can be **ahead of the chain in a way\nthat shows**.\n\nRule: before pushing `layout`, every `:slug:` in it is either a file in\n`content/` or a computed placeholder **the deployed code answers**, which is not\nthe same as one this repo implements.\n\n⚠️ **This is currently true of `layout` itself.** It now contains\n`:reactions:`, and `reactions.gno` is in this repo but **not in the deployed\npackage**. The live `gno.land/r/moul/home` holds eight files, `README.md`\n`gnomod.toml` `home.gno` `home_test.gno` `render.gno` `render_example_test.gno`\n`scan.gno` `scan_test.gno`, and `reactions.gno` is not one of them (read from\nthe chain 2026-09-28 with `gnopie INSPECT gno.land/r/moul/home -all`). So\n`layout` must not be pushed on its own. It goes out with the redeploy that\ncarries `reactions.gno`, which also wipes every slot and is therefore followed\nby `gnohome tx -all` anyway.\n\nThat same file list settles the older half of this warning: `scan.gno` **is**\ndeployed, so `:scan.links:` resolves on the live page and the redeploy it was\nwaiting for has happened. Do not re-add it here from memory; the file list is\nthe check.\n\nThe redeploy's one new dependency, [`r/moul/reactions/v0`](../../../r/moul/reactions),\nis not on chain yet and has to be published first. After that what is left is\nthis realm's own `MsgAddPackage`, which no account session may sign.\n\n`gnohome status` is the check, and `tools/gnohome/scan.go` makes `preview`\nrender these links rather than showing a literal `:scan.links:`, so the page\ncan be judged before any of it is signed.\n\n### Images: two gates, and neither is the one you expect\n\nAn image in a slot passes **gnoweb's validator** and then the **CSP the site is\nserved behind**. They block different things, and only the second is a domain\nlist:\n\n- gnoweb's `AllowSvgDataImage` (`gno.land/pkg/gnoweb/render_config.go`, wired in\n  `markdown/ext_imgvalidator.go`)\n  rejects every `data:` URI that is not `image/svg+xml`, and blanks the `src`\n  rather than dropping the tag. Ordinary `https://` URLs are not checked at all.\n- The live `content-security-policy` header on gno.land pins `img-src` to\n  `'self' data:` plus a fixed host list: `*.githubusercontent.com`,\n  `*.github.io`, `github.com`, `imgur.com`, `*.imgur.com`, `assets.gnoteam.com`,\n  `sa.gno.services`, `gnolang.github.io`, `ipfs.io`, `cloudflare-ipfs.com`\n  (read 2026-09-19). Anything else is silently not painted by the browser, with\n  the HTML looking perfectly fine.\n\nSo a GitHub avatar needs no hosting of its own:\n`https://avatars.githubusercontent.com/u/94029?s=400` matches\n`*.githubusercontent.com` and renders as-is. Verified by running this exact\npage through gnoweb's real goldmark pipeline, not by reading the policy.\n\nTwelve placeholders are computed at render time rather than stored, and are\nrefused as slot names so nothing can shadow them.\n\nSix come straight from chain state: `:owner:` `:realm:` `:chainid:` `:height:`\n`:rev:` `:slots:`.\n\nFive are explorer links, built by [`p/moul/mygnoscan`](../../../p/moul/mygnoscan)\n(`scan.gno`): `:scan:` is the explorer base URL as plain text, `:scan.realm:`\n`:scan.me:` `:scan.block:` are markdown links to this realm, to the owner's\naccount and to the block being rendered, and `:scan.links:` is the three of\nthem on one line.\n\nOne is the reaction block: `:reactions:` renders the embeddable widget from\n[`r/moul/reactions`](../../../r/moul/reactions), keyed on this realm's path. It\nis the only thing on this page a reader can act on, and this realm stores\nnothing for it: the tallies live in that realm, so the redeploy that wipes every\nslot here does not touch anyone's reaction. See `reactions.gno`.\n\nWhich explorer the scan links point at is read from\n[`r/moul/config`](../../../r/moul/config), not hardcoded here, so moving every\none of moul's realms to a different instance is one transaction against that\nrealm rather than a redeploy of each. With nothing configured, they fall back\nto `mygnoscan.DefaultBase`, which is what a fresh chain renders.\n\nThree properties worth knowing:\n\n- **Lazy.** dynreplacer only invokes the callbacks whose placeholder actually\n  occurs in the layout, so an unused slot is never read out of the tree.\n- **Single-pass.** A placeholder inside a slot *body* is left alone. No slot can\n  expand into another, so no cycle exists.\n- **Order-independent.** Every placeholder is `:slug:` and a slug cannot contain\n  `':'`, so no placeholder is a prefix of another and the replacer has no\n  ambiguity to resolve.\n\nAn unmatched placeholder survives into the output verbatim. That is deliberate: a\nmissing section should be visible, not silently blank.\n\n### Other render paths\n\n- `:slots`: the slot index (name, size, revision, height of last write)\n- `:slots/\u003cslug\u003e`: one slot's raw markdown, fenced\n\n## Why `private`\n\n`gnomod.toml` declares `private = true`. On gno.land that means two things:\n\n1. **No other realm may import this one.** Fine for a profile page.\n2. **The creator may re-add the package at this path.** `AddPackage` waives its\n   already-exists refusal for a private package and binds the replacement to the\n   address in `[addpkg].creator`.\n\n⚠️ **A redeploy re-runs `init()` and resets all realm state.** The slots are gone.\nThat is why `content/` is the source of truth and why `gnohome tx -all` exists:\nafter a redeploy, push every slot back.\n\nThe intended path is that this never happens. Slots cover content and the layout\nslot covers presentation, so the code should not need to change.\n\n## Local workflow\n\n`tools/gnohome` is the local half: it builds the slots from `content/*.md`, renders\nthe page offline exactly as the realm would, diffs against the chain, and prints\nthe `gnokey` commands for what is outdated, nothing else.\n\n```sh\ngo -C tools tool gnohome preview   # see the page before anyone else does\ngo -C tools tool gnohome status    # what differs from the chain\ngo -C tools tool gnohome tx        # the commands to fix that\n```\n\n⚠️ **`gnohome preview` is the only preview of this realm that means anything.**\nThe CI preview link deploys the package to a fresh dev chain, where there are no\nslots and `content/` never travels (the uploader skips sub-directories), so it\nalways renders `defaultLayout` and is identical on every content-only PR.\nConfirmed on PR #225, whose preview reads \"No layout slot yet\" while the change\nwas six slots. The bot cannot know this and links it anyway.\n\nThe `packages` slot is generated, not written: it is a claim about what is\ndeployed, and `contracts.json` already tracks that per network.\n\n```sh\ngo -C tools tool gnohome packages \u003e r/moul/home/content/packages.md\n```\n\n\nSee [`tools/gnohome/README.md`](../../../tools/gnohome/README.md).\n\n## Deploying\n\nThe realm **is live on mainnet** (`gnoland-1`), serving https://gno.land/u/moul.\nWhat follows applies to a redeploy, or to a first deploy on another network.\n\n⚠️ A redeploy of this path wipes every slot, so it is always followed by\n`gnohome tx -all`. `Set` needs the package on chain first, and a `private`\npackage still needs `MsgAddPackage`, which no account session can sign.\n\n**mainnet deploys in two phases.** `gnoland-1` runs\n`vm:p:code_submission_policy = \"inert\"` (read back from the chain 2026-09-19), so\n`MsgAddPackage` **parks** the bytes under `inert_pkg:\u003cpath\u003e` and returns\n`success: true` without making the package live. `Render` still answers\n`package not found`, `/u/moul` is still blank, and `gnohome tx` cannot land a\nsingle slot until an approver in `vm:p:pkg_approvers` sends `MsgEnablePackage`.\n\nIn practice that gate is an oracle, not a queue: `g1yaaa6rcp4ew5yjzdj4yms596wx2dtrj3a86704`\nenabled the four most recent parked packages after 1 to 4 blocks, 3.3 to 13.2\nseconds. It can still refuse, and a refusal is easy to miss, so check rather than\nassume.\n\n### The whole plan, from gnopm\n\nDeploying is not special to this realm, so it is not this realm's tool that\ndoes it. `gnopm publish` reads the chain, reports whether the package is live,\nparked or absent, checks that every non-test dependency is already up, sizes\ngas, fee and deposit from the real payload, and writes the `gnokey` commands.\nIt never signs.\n\n```sh\ngnopm publish -key moul moul/home     # read the report, read the script\ngnopm publish -key moul moul/home \u003e /tmp/deploy.sh \u0026\u0026 sh /tmp/deploy.sh\n```\n\nThen the content, once the realm answers:\n\n```sh\ngo -C tools tool gnohome tx -all -batch /tmp/home.tx.json\nsh /tmp/home.tx.sh\n```\n\nThat writes one transaction holding every slot and prints the `gnokey sign`\nand `gnokey broadcast` to run: one passphrase instead of one per slot, and\natomic. **Never pipe these into `sh`**: `gnokey` reads the passphrase from\nstdin and a pipe takes stdin away, so the prompt fails with\n`inappropriate ioctl for device`.\n\nRun those rather than copying commands from here: anything written down goes\nstale, and the tools recompute from the files as they are.\n\n### How it sizes them\n\nDeliberately no byte count here. This README **is part of the payload**, so any\nfigure quoted in it invalidates itself the moment the file is edited. The tool\nreads the real numbers off the files; what follows is only the method, so a\nreader can judge it.\n\n**What travels.** `gnokey maketx addpkg` uploads with `MPUserAll`\n(`gno.land/pkg/keyscli/addpkg.go`), so every `.gno`, `.toml` and `.md` in the\npackage directory goes on chain, **test files and this README included**.\nSub-directories are skipped, which is why `content/` never ships. The README is\nusually the single largest file, and you pay gas and storage on it.\n\n**`-gas-wanted`, at 1,800 gas per uploaded byte.** Ten successful mainnet\n`add_package` transactions above h160000 cost **1,014 to 1,781 gas/byte**\n(median 1,393, measured 2026-09-19). The spread is the package's own `init()`\nwork, which a byte count cannot see, so size from the top of the range. It is a\nceiling and a ceiling is not charged.\n\n**`-gas-fee`, at ten times the accepted floor.** What the mempool enforces is\nthe `gas_fee / gas_wanted` **ratio**, not the absolute\n(`EnsureSufficientMempoolFees`), so raising the ceiling raises the required fee\nand headroom is not free. The lowest ratio accepted on mainnet is\n**0.001 ugnot/gas**; comparable `add_package` transactions paid 0.001 to\n0.00125. The tool offers 0.01. **`gas_fee` is deducted in full as offered and\nnever refunded**, so over-offering is a real cost and not insurance: the flat\n`1000000ugnot` this tooling used to emit for a slot write was about ninety times\nthe floor.\n\n**`-max-deposit`, an explicit ceiling.** Omitting it is not opting out: it falls\nback to `vm:p:default_deposit`, **100 GNOT of ceiling per message**. Storage\nlocks 100ugnot per byte. Unlike the gas fee this one is **refundable** and only\nthe measured byte delta is ever locked, so headroom here costs nothing.\n\nRe-measure before a later redeploy: gas is a function of the code, and both the\ngas price and the submission policy are chain parameters.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/home?network=mainnet)](https://gnoscope.com/realm/r/moul/home) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/home?network=mainnet)](https://gnoscope.com/realm/r/moul/home) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/home?network=mainnet)](https://gnoscope.com/realm/r/moul/home) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/home?network=mainnet)](https://gnoscope.com/realm/r/moul/home)\n\n**Dependency graph:**\n\n![gno.land/r/moul/home dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/home/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/home\"\ngno = \"0.9\"\n\n# Redeployable by its creator. See README.md § \"Why private\".\n#\n# A private package may be re-added at the same path by the address recorded in\n# [addpkg].creator (gno.land/pkg/sdk/vm/keeper.go, checkRedeployPermission), and\n# nothing else may import it. A redeploy RE-RUNS init() and resets realm state,\n# so content/ is the source of truth and tools/gnohome pushes the slots back.\nprivate = true\n"},{"name":"home.gno","body":"// Package home is the realm behind https://gno.land/u/moul.\n//\n// gnoweb builds a user profile page by calling Render(\"\") on the realm at the\n// exact path /r/\u003cusername\u003e/home (gno.land/pkg/gnoweb/handler_http.go,\n// GetUserView) and embedding the result as the profile body. There is no\n// version resolution in that lookup, which is why this realm (alone in this\n// repo) carries no /vN suffix: the bare path IS the interface with gnoweb,\n// and gno.land/r/moul/home/v0 would never be found.\n//\n// # Slots\n//\n// The page is not hard-coded. It is assembled from SLOTS: named markdown\n// fragments in an avl tree, each written by its own Set call, so updating one\n// paragraph is one small transaction instead of a redeploy.\n//\n// The layout is itself a slot (\"layout\"), so the shape of the page (headings,\n// order, what appears at all) changes without touching the code.\n// p/moul/dynreplacer fills every :slug: placeholder found in the layout, lazily:\n// a slot whose placeholder is absent from the layout costs nothing to render.\n//\n// Substitution is SINGLE-PASS and non-recursive. A placeholder inside a slot\n// body is left alone, so no slot can expand into another and no cycle exists.\n// Two registered placeholders can never be prefixes of one another either\n// (every one is :slug: and a slug may not contain ':'), so the result does not\n// depend on registration order.\n//\n// A placeholder with no matching slot survives into the output verbatim. That\n// is deliberate: a missing section should be visible, not silently blank.\n//\n// # Versioning\n//\n// gnomod.toml declares private = true, which lets the creator re-add the\n// package at this path. That redeploy re-runs init() and RESETS everything\n// here, so the markdown under content/ is the source of truth and\n// tools/gnohome pushes the slots back afterwards. The intended path is that this\n// never happens: slots cover content, and the layout slot covers presentation.\npackage home\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// admin is the only address allowed to write. Deliberately a constant and not\n// transferable ownership: this realm is one person's profile page, and the\n// same address is the only one the chain lets redeploy it.\nconst admin = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\n// layoutSlug names the slot used as the page template.\nconst layoutSlug = \"layout\"\n\n// realmPath is this realm's own path. Written out rather than read from\n// unsafe.CurrentRealm() because it is also the interface with gnoweb (see the\n// package doc): the constant is the thing that must not drift, so it is stated\n// once and every other use points here.\nconst realmPath = \"gno.land/r/moul/home\"\n\n// maxSlugLen bounds a slug so an index row stays readable and a key stays cheap.\nconst maxSlugLen = 64\n\nvar (\n\tslots = avl.NewTree() // slug -\u003e *slot\n\trev   int             // total number of writes, bumped by every mutation\n)\n\ntype slot struct {\n\tbody    string\n\trev     int   // rev at the time of the last write to this slot\n\tupdated int64 // block height of the last write\n}\n\n// reservedSlugs are placeholder names computed at render time from chain state.\n// A slot may not take one, because it would shadow the computed value and make\n// the page depend on callback registration order.\n//\n// The scan.* half comes from scan.gno's scanPlaceholders and the :reactions:\n// one from reactions.gno, so adding a placeholder in either file reserves it\n// here and cannot be forgotten.\nvar reservedSlugs = append(\n\tappend(\n\t\t[]string{\"chainid\", \"height\", \"owner\", \"realm\", \"rev\", \"slots\"},\n\t\tscanPlaceholders...,\n\t),\n\treactionsPlaceholders...,\n)\n\nfunc assertAdmin(cur realm) {\n\tif cur.Previous().Address() != admin {\n\t\tpanic(\"restricted to admin\")\n\t}\n}\n\n// validSlug reports whether slug is a legal slot name: 1..maxSlugLen bytes of\n// [a-z0-9._-]. The character set excludes ':' so a slug can never break out of\n// its own :slug: placeholder, and excludes uppercase so a slot has one name.\nfunc validSlug(slug string) bool {\n\tif len(slug) == 0 || len(slug) \u003e maxSlugLen {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(slug); i++ {\n\t\tc := slug[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '-', c == '_', c == '.':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc assertWritableSlug(slug string) {\n\tif !validSlug(slug) {\n\t\tpanic(\"invalid slug: want 1-\" + strconv.Itoa(maxSlugLen) + \" bytes of [a-z0-9._-], got \" + strconv.Quote(slug))\n\t}\n\tfor _, r := range reservedSlugs {\n\t\tif slug == r {\n\t\t\tpanic(\"reserved slug: \" + slug + \" is computed at render time\")\n\t\t}\n\t}\n}\n\n// Set creates or replaces the slot named slug. This is the ordinary update: one\n// slot, one transaction. Passing the empty body keeps the slot but empties it;\n// use Delete to remove it.\nfunc Set(cur realm, slug, body string) {\n\tassertAdmin(cur)\n\tassertWritableSlug(slug)\n\trev++\n\tslots.Set(slug, \u0026slot{body: body, rev: rev, updated: chainHeight()})\n}\n\n// Append adds to the end of a slot, creating it when absent. It exists for\n// content too large to fit in one transaction: Set the first chunk, Append the\n// rest. Ordinary updates should use Set, which is idempotent.\nfunc Append(cur realm, slug, body string) {\n\tassertAdmin(cur)\n\tassertWritableSlug(slug)\n\trev++\n\tprev := \"\"\n\tif v := slots.Get(slug); v != nil {\n\t\tprev = v.(*slot).body\n\t}\n\tslots.Set(slug, \u0026slot{body: prev + body, rev: rev, updated: chainHeight()})\n}\n\n// Delete removes a slot. Deleting the layout slot restores the built-in\n// default layout.\nfunc Delete(cur realm, slug string) {\n\tassertAdmin(cur)\n\tif _, removed := slots.Remove(slug); !removed {\n\t\tpanic(\"no such slot: \" + slug)\n\t}\n\trev++\n}\n\n// Get returns a slot body, or \"\" when the slot does not exist.\nfunc Get(slug string) string {\n\tv := slots.Get(slug)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(*slot).body\n}\n\n// Revision returns the total number of writes this realm has accepted. It\n// changes on every mutation, so a client can cheaply tell \"nothing moved\".\nfunc Revision() int {\n\treturn rev\n}\n\n// Manifest returns one tab-separated line per slot:\n//\n//\t\u003cslug\u003e\\t\u003crev\u003e\\t\u003clen\u003e\\t\u003csha256 of body, hex\u003e\n//\n// It is the diff surface tools/gnohome queries with vm/qeval: one read tells it\n// exactly which local file is out of date, without downloading any body.\nfunc Manifest() string {\n\tvar b strings.Builder\n\tslots.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\ts := value.(*slot)\n\t\tsum := sha256.Sum256([]byte(s.body))\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.Itoa(s.rev))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.Itoa(len(s.body)))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(hex.EncodeToString(sum[:]))\n\t\tb.WriteString(\"\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n"},{"name":"home_test.gno","body":"package home\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar stranger = testutils.TestAddress(\"mallory\")\n\n// reset clears realm state. Realm globals live for the whole test binary, so\n// every test that reads Render or Manifest starts from a known tree.\nfunc reset() {\n\tslots = avl.NewTree()\n\trev = 0\n}\n\n// seed writes a slot without going through the admin check, for tests (and the\n// Example) that only care about the rendering side.\nfunc seed(slug, body string) {\n\trev++\n\tslots.Set(slug, \u0026slot{body: body, rev: rev, updated: 0})\n}\n\nfunc TestSetGetDelete(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tSet(cross(cur), \"bio\", \"Building on gno.\")\n\tuassert.Equal(t, \"Building on gno.\", Get(\"bio\"))\n\tuassert.Equal(t, 1, Revision())\n\n\t// Set is idempotent in shape: a second write replaces, never appends.\n\tSet(cross(cur), \"bio\", \"Still building.\")\n\tuassert.Equal(t, \"Still building.\", Get(\"bio\"))\n\tuassert.Equal(t, 2, Revision())\n\n\tDelete(cross(cur), \"bio\")\n\tuassert.Equal(t, \"\", Get(\"bio\"), \"a deleted slot reads as empty\")\n\tuassert.Equal(t, 3, Revision())\n\n\tuassert.AbortsWithMessage(t, cur, \"no such slot: bio\", func() {\n\t\tDelete(cross(cur), \"bio\")\n\t})\n}\n\nfunc TestAppendChunks(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\t// The escape hatch for a body too large for one transaction.\n\tSet(cross(cur), \"long\", \"part one. \")\n\tAppend(cross(cur), \"long\", \"part two.\")\n\tuassert.Equal(t, \"part one. part two.\", Get(\"long\"))\n\n\t// Append creates the slot when it is absent.\n\tAppend(cross(cur), \"fresh\", \"hello\")\n\tuassert.Equal(t, \"hello\", Get(\"fresh\"))\n}\n\nfunc TestWritesAreAdminOnly(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(stranger))\n\n\tuassert.AbortsWithMessage(t, cur, \"restricted to admin\", func() {\n\t\tSet(cross(cur), \"bio\", \"pwned\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"restricted to admin\", func() {\n\t\tAppend(cross(cur), \"bio\", \"pwned\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"restricted to admin\", func() {\n\t\tDelete(cross(cur), \"bio\")\n\t})\n\tuassert.Equal(t, \"\", Get(\"bio\"))\n}\n\nfunc TestSlugRules(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tuassert.True(t, validSlug(\"bio\"))\n\tuassert.True(t, validSlug(\"now.2026-09\"))\n\tuassert.True(t, validSlug(\"latest_packages\"))\n\tuassert.False(t, validSlug(\"\"), \"empty\")\n\tuassert.False(t, validSlug(\"Bio\"), \"uppercase: a slot must have one name\")\n\tuassert.False(t, validSlug(\"a b\"), \"space\")\n\tuassert.False(t, validSlug(\"a:b\"), \"a colon would break out of the :slug: placeholder\")\n\tuassert.False(t, validSlug(strings.Repeat(\"a\", maxSlugLen+1)), \"too long\")\n\n\tuassert.AbortsContains(t, cur, \"invalid slug\", func() {\n\t\tSet(cross(cur), \"Bad Slug\", \"x\")\n\t})\n\n\t// A reserved name would shadow a value computed from chain state.\n\tfor _, name := range reservedSlugs {\n\t\tuassert.AbortsContains(t, cur, \"reserved slug\", func() {\n\t\t\tSet(cross(cur), name, \"x\")\n\t\t})\n\t}\n\n\t// \"layout\" is special but NOT reserved: it is a real, writable slot.\n\tSet(cross(cur), layoutSlug, \"# hi\")\n\tuassert.Equal(t, \"# hi\", Get(layoutSlug))\n}\n\nfunc TestManifestIsTheDiffSurface(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tSet(cross(cur), \"bio\", \"hello\")\n\tSet(cross(cur), \"alpha\", \"\")\n\n\t// Sorted by slug (avl order), one line each, four tab-separated fields.\n\tlines := strings.Split(strings.TrimSuffix(Manifest(), \"\\n\"), \"\\n\")\n\tuassert.Equal(t, 2, len(lines))\n\n\talpha := strings.Split(lines[0], \"\\t\")\n\tuassert.Equal(t, 4, len(alpha))\n\tuassert.Equal(t, \"alpha\", alpha[0])\n\tuassert.Equal(t, \"0\", alpha[2], \"byte length of an empty body\")\n\t// sha256(\"\"), pinning that the hash is over the body, not over a wrapper.\n\tuassert.Equal(t, \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\", alpha[3])\n\n\tbio := strings.Split(lines[1], \"\\t\")\n\tuassert.Equal(t, \"bio\", bio[0])\n\tuassert.Equal(t, \"5\", bio[2])\n\t// sha256(\"hello\")\n\tuassert.Equal(t, \"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\", bio[3])\n}\n\nfunc TestRenderFillsTheLayoutSlot(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tSet(cross(cur), layoutSlug, \"# :owner:\\n\\n:bio:\\n\\n:missing:\\n\")\n\tSet(cross(cur), \"bio\", \"Building on gno.\")\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"# \"+admin.String()),\n\t\t\"a computed placeholder is filled from chain state\")\n\tuassert.True(t, strings.Contains(out, \"Building on gno.\"),\n\t\t\"a slot placeholder is filled from the tree\")\n\tuassert.True(t, strings.Contains(out, \":missing:\"),\n\t\t\"an unmatched placeholder survives verbatim, so a gap is visible\")\n}\n\nfunc TestRenderDoesNotRecurse(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\t// A slot body that looks like a placeholder must not expand: substitution\n\t// is one pass, which is what makes cycles impossible.\n\tSet(cross(cur), layoutSlug, \":a:\")\n\tSet(cross(cur), \"a\", \":b:\")\n\tSet(cross(cur), \"b\", \"should not appear\")\n\n\tuassert.Equal(t, \":b:\", Render(\"\"))\n}\n\nfunc TestRenderUnsetLayoutFallsBack(t *testing.T) {\n\treset()\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"No layout slot yet\"))\n\tuassert.False(t, strings.Contains(out, \":slots:\"),\n\t\t\"the default layout must not leave its own placeholders unresolved\")\n\tuassert.False(t, strings.Contains(out, \":rev:\"))\n\tuassert.False(t, strings.Contains(out, \":height:\"))\n\tuassert.False(t, strings.Contains(out, \":chainid:\"))\n}\n\nfunc TestRenderSubPaths(t *testing.T) {\n\treset()\n\tseed(\"bio\", \"Building on gno.\")\n\n\tidx := Render(\"slots\")\n\tuassert.True(t, strings.Contains(idx, \"| [bio](/r/moul/home:slots/bio) |\"))\n\n\traw := Render(\"slots/bio\")\n\tuassert.True(t, strings.Contains(raw, \"Building on gno.\"))\n\tuassert.True(t, strings.Contains(raw, \"16 bytes\"))\n\n\tuassert.True(t, strings.Contains(Render(\"slots/nope\"), \"No slot named\"))\n\tuassert.True(t, strings.Contains(Render(\"whatever\"), \"No such path\"))\n}\n\nfunc TestRenderEmptyIndex(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"slots\"), \"_no slots yet_\"))\n}\n"},{"name":"reactions.gno","body":"package home\n\nimport (\n\t\"gno.land/p/moul/dynreplacer/v0\"\n\t\"gno.land/r/moul/reactions/v0\"\n)\n\n// This file is the one interactive thing on the page: a :reactions: placeholder\n// that renders the reaction block from gno.land/r/moul/reactions, keyed on this\n// realm's path.\n//\n// Nothing is stored here. The tallies live in the reactions realm, which is why\n// this realm can be redeployed (and wiped, see the package doc) without losing\n// anyone's reaction, and why adding this cost one placeholder rather than a\n// state machine.\n//\n// The block renders its own txlinks, so a reader clicks an emoji here and lands\n// on the reactions realm's $help form with the page prefilled. This realm has\n// no write path of its own for it and does not want one: the point of the\n// indirection is that the same block behaves identically on every page that\n// embeds it.\n\n// reactionsPlaceholders are the reserved slugs this file answers for. Listed in\n// reservedSlugs (home.gno) so a slot can never take one of these names and\n// shadow the computed value.\nvar reactionsPlaceholders = []string{\"reactions\"}\n\n// registerReactionCallbacks adds the reaction placeholder to r.\n//\n// dynreplacer only invokes a callback whose placeholder actually occurs in the\n// layout, so a layout that does not use :reactions: never calls into the\n// reactions realm at all.\n//\n// RenderBlockFor is used rather than the zero-argument RenderBlock, for the\n// same reason config.TopBlockFor is (see render.gno): the zero-argument form\n// reads the caller off the stack, which would be correct here, but this realm\n// already states its own path as a constant and passing it cannot be wrong.\nfunc registerReactionCallbacks(r *dynreplacer.Replacer) {\n\tr.RegisterCallback(\":reactions:\", func() string {\n\t\treturn reactions.RenderBlockFor(realmPath)\n\t})\n}\n"},{"name":"reactions_test.gno","body":"package home\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestReactionBlockRenders exercises the cross-realm call itself, which is the\n// only thing that can find the failure mode this realm is exposed to: it is\n// private = true, and a private realm that hands one of its own objects to\n// another realm panics at RUNTIME with \"cannot persist object from the private\n// realm\", where gno lint sees nothing (AGENTS.md, ADR 0044). Only strings cross\n// here, in both directions, and this test is what says so.\nfunc TestReactionBlockRenders(t *testing.T) {\n\treset()\n\tseed(\"layout\", \"# page\\n\\n:reactions:\\n\")\n\n\tgot := Render(\"\")\n\tuassert.True(t, strings.Contains(got, \"(/r/moul/reactions/v0$help\u0026func=React\u0026\"),\n\t\t\"the block's txlinks target the reactions realm\")\n\tuassert.True(t, strings.Contains(got, \"page=gno.land%2Fr%2Fmoul%2Fhome\"),\n\t\t\"keyed on this realm's path, which is what makes the tally this page's\")\n\tuassert.True(t, strings.Contains(got, \"*no reactions yet*\"))\n}\n\n// TestReactionsIsAReservedSlug: the placeholder is computed, so a slot may not\n// take its name and shadow it. gnohome refuses the same name off chain, before\n// the gas is spent (tools/gnohome/content.go).\nfunc TestReactionsIsAReservedSlug(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tuassert.AbortsWithMessage(t, cur,\n\t\t\"reserved slug: reactions is computed at render time\", func() {\n\t\t\tSet(cross(cur), \"reactions\", \"nope\")\n\t\t})\n}\n\n// TestLayoutWithoutTheBlockCallsNothing is the property that makes the\n// placeholder free: dynreplacer only invokes a callback whose placeholder\n// occurs in the layout, so a layout that drops :reactions: does not reach into\n// the reactions realm at all.\nfunc TestLayoutWithoutTheBlockCallsNothing(t *testing.T) {\n\treset()\n\tseed(\"layout\", \"# page\\n\\nnothing here\\n\")\n\tuassert.Equal(t, \"# page\\n\\nnothing here\\n\", Render(\"\"))\n}\n"},{"name":"render.gno","body":"package home\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/dynreplacer/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// defaultLayout is what renders before a layout slot exists, which is not only\n// the very first deploy: a redeploy re-runs init() and wipes every slot, so\n// this is also the page at the exact moment someone is restoring it. It uses\n// only computed placeholders, so it never shows an unresolved :slug: of its own.\n//\n// It prints no gnokey command and no gas numbers, on purpose. The one it used\n// to print offered 1000000ugnot against 20000000 gas: a ratio of 0.05 against a\n// mainnet floor of 0.001, and gas_fee is deducted in full as offered and never\n// refunded, so it asked for about fifty times what the write costs. The tooling\n// was corrected and this string was not, which is the argument against having\n// it at all. A command baked into a realm cannot be fixed without a redeploy,\n// and the redeploy is the thing that wipes the slots. gnohome recomputes it\n// from content/ and from the chain, so it cannot go stale.\nconst defaultLayout = \"# gno.land/r/moul/home\\n\\n\" +\n\t\"No layout slot yet. A redeploy wipes every slot and `content/` is the source\\n\" +\n\t\"of truth, so push them back with the tool rather than by hand:\\n\\n\" +\n\t\"    go -C tools tool gnohome tx -all\\n\\n\" +\n\t\"No gas numbers here on purpose: a command written into a realm goes stale and\\n\" +\n\t\"cannot be corrected without another redeploy.\\n\\n\" +\n\t\"## Slots\\n\\n:slots:\\n\\n---\\n\\nrev :rev: · height :height: · :chainid:\\n\"\n\nfunc chainHeight() int64 { return runtime.ChainHeight() }\n\n// Render serves three views:\n//\n//\t\"\"            the assembled page, what https://gno.land/u/moul shows\n//\t\"slots\"       the slot index: name, size, revision, last write\n//\t\"slots/\u003cslug\u003e\" one slot's raw markdown, fenced\nfunc Render(path string) string {\n\tswitch {\n\tcase path == \"\":\n\t\treturn renderPage()\n\tcase path == \"slots\":\n\t\treturn renderIndex()\n\tcase strings.HasPrefix(path, \"slots/\"):\n\t\treturn renderSlot(strings.TrimPrefix(path, \"slots/\"))\n\tdefault:\n\t\treturn \"# Not found\\n\\nNo such path: \" + strconv.Quote(path) +\n\t\t\t\"\\n\\nTry [the slot index](/r/moul/home:slots).\\n\"\n\t}\n}\n\n// renderPage fills the layout. dynreplacer only invokes the callbacks whose\n// placeholder actually occurs in the layout, so an unused slot is never even\n// read out of the tree.\nfunc renderPage() string {\n\tlayout := Get(layoutSlug)\n\tif layout == \"\" {\n\t\tlayout = defaultLayout\n\t}\n\n\tr := dynreplacer.New()\n\n\t// Computed from chain state. Registered first; assertWritableSlug keeps a\n\t// slot from ever taking one of these names, so nothing shadows them.\n\tr.RegisterCallback(\":owner:\", func() string { return admin.String() })\n\tr.RegisterCallback(\":realm:\", func() string { return realmPath })\n\tr.RegisterCallback(\":chainid:\", func() string { return runtime.ChainID() })\n\tr.RegisterCallback(\":height:\", func() string { return strconv.FormatInt(runtime.ChainHeight(), 10) })\n\tr.RegisterCallback(\":rev:\", func() string { return strconv.Itoa(rev) })\n\tr.RegisterCallback(\":slots:\", func() string { return slotLinks() })\n\n\t// The explorer links, which are computed the same way but come from\n\t// another realm's configuration. See scan.gno.\n\tregisterScanCallbacks(r)\n\n\t// The reaction block, which is the one thing on this page a reader can\n\t// act on. See reactions.gno.\n\tregisterReactionCallbacks(r)\n\n\t// One callback per slot. The closure captures s, which is re-bound on each\n\t// iteration, so every callback sees its own slot.\n\tslots.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\ts := value.(*slot)\n\t\tr.RegisterCallback(\":\"+key+\":\", func() string { return s.body })\n\t\treturn false\n\t})\n\n\t// The notice blocks, from gno.land/r/moul/config: a warning, a changelog\n\t// line or a bit of news, set either on every realm of moul's at once or on\n\t// this one alone, and empty by default. A pause banner rides along at the\n\t// top, so the page explains itself if this realm is ever held back.\n\t//\n\t// The path is passed explicitly rather than using config's zero-argument\n\t// TopBlock(). That form reads the caller off the stack, which is correct\n\t// here and is covered by config's own tests, but this realm's Render IS\n\t// gno.land/u/moul and it already states its own path: passing the constant\n\t// cannot be wrong, at no cost.\n\treturn config.TopBlockFor(realmPath) + r.Replace(layout) + config.BottomBlockFor(realmPath)\n}\n\n// slotLinks is the :slots: placeholder: a bullet list of every slot, linking to\n// its raw view.\nfunc slotLinks() string {\n\tif slots.Size() == 0 {\n\t\treturn \"_no slots yet_\"\n\t}\n\tvar b strings.Builder\n\tslots.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tb.WriteString(\"- [\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"](/r/moul/home:slots/\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\")\\n\")\n\t\treturn false\n\t})\n\treturn strings.TrimSuffix(b.String(), \"\\n\")\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Slots\\n\\n\")\n\tb.WriteString(\"rev \")\n\tb.WriteString(strconv.Itoa(rev))\n\tb.WriteString(\" · \")\n\tb.WriteString(strconv.Itoa(slots.Size()))\n\tb.WriteString(\" slot(s)\\n\\n\")\n\tif slots.Size() == 0 {\n\t\tb.WriteString(\"_no slots yet_\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(\"| slot | bytes | rev | height |\\n\")\n\tb.WriteString(\"| --- | ---: | ---: | ---: |\\n\")\n\tslots.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\ts := value.(*slot)\n\t\tb.WriteString(\"| [\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"](/r/moul/home:slots/\")\n\t\tb.WriteString(key)\n\t\tb.WriteString(\") | \")\n\t\tb.WriteString(strconv.Itoa(len(s.body)))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.Itoa(s.rev))\n\t\tb.WriteString(\" | \")\n\t\tb.WriteString(strconv.FormatInt(s.updated, 10))\n\t\tb.WriteString(\" |\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\nfunc renderSlot(slug string) string {\n\tv := slots.Get(slug)\n\tif v == nil {\n\t\treturn \"# Not found\\n\\nNo slot named \" + strconv.Quote(slug) +\n\t\t\t\".\\n\\nTry [the slot index](/r/moul/home:slots).\\n\"\n\t}\n\ts := v.(*slot)\n\tvar b strings.Builder\n\tb.WriteString(\"# \")\n\tb.WriteString(slug)\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(strconv.Itoa(len(s.body)))\n\tb.WriteString(\" bytes · rev \")\n\tb.WriteString(strconv.Itoa(s.rev))\n\tb.WriteString(\" · written at height \")\n\tb.WriteString(strconv.FormatInt(s.updated, 10))\n\tb.WriteString(\"\\n\\n```\\n\")\n\tb.WriteString(s.body)\n\tif !strings.HasSuffix(s.body, \"\\n\") {\n\t\tb.WriteString(\"\\n\")\n\t}\n\tb.WriteString(\"```\\n\")\n\treturn b.String()\n}\n"},{"name":"render_example_test.gno","body":"package home\n\n// ExampleRender pins the assembled page. It seeds state directly (rather than\n// through Set) so the example takes no `cur realm`, and it uses only\n// non-volatile placeholders so the golden output does not depend on the test\n// machine's block height or chain id.\nfunc ExampleRender() {\n\treset()\n\tseed(\"layout\", \"# :owner:\\n\\n:bio:\\n\\n## Packages\\n\\n:packages:\\n\")\n\tseed(\"bio\", \"Building on gno.\")\n\tseed(\"packages\", \"- p/moul/dynreplacer\\n- r/moul/home\")\n\tprint(Render(\"\"))\n\t// Output:\n\t// # g1manfred47kzduec920z88wfr64ylksmdcedlf5\n\t//\n\t// Building on gno.\n\t//\n\t// ## Packages\n\t//\n\t// - p/moul/dynreplacer\n\t// - r/moul/home\n}\n"},{"name":"scan.gno","body":"package home\n\nimport (\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/dynreplacer/v0\"\n\t\"gno.land/p/moul/mygnoscan/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// This file is the explorer half of the page: a handful of computed\n// placeholders that turn what this realm already knows (its own path, its\n// owner, the block it is rendering at) into links a reader can click.\n//\n// They are COMPUTED, not slots, so they are always current: the layout slot\n// says where a link goes on the page, and nothing in storage has to be\n// rewritten when the answer changes.\n//\n// The explorer they point at comes from gno.land/r/moul/config, not from a\n// constant here. That is the whole point of the indirection: moving every one\n// of moul's realms to a different explorer is one transaction against config,\n// not a redeploy of each realm that links to one. When config has no setting,\n// mygnoscan.DefaultBase answers, so this realm renders correctly on a chain\n// where nothing was ever configured.\n\n// scanPlaceholders are the reserved slugs this file answers for. They are\n// listed in reservedSlugs (home.gno) so a slot can never take one of these\n// names and shadow the computed value.\nvar scanPlaceholders = []string{\n\t\"scan\",       // the explorer base URL, as plain text\n\t\"scan.realm\", // this realm on the explorer\n\t\"scan.me\",    // the owner's account page\n\t\"scan.block\", // the block this render is happening at\n\t\"scan.links\", // the three above, on one line\n}\n\n// scanner returns the configured link builder.\n//\n// config.Scanner() is a read, and a cheap one: an avl lookup plus a struct.\n// It is called once per render and the result reused, rather than once per\n// placeholder, because dynreplacer may invoke several of the callbacks below\n// and each would otherwise repeat the cross-realm call.\nfunc scanner() mygnoscan.Scanner { return config.Scanner() }\n\n// registerScanCallbacks adds the explorer placeholders to r.\n//\n// dynreplacer only invokes a callback whose placeholder actually occurs in the\n// layout, so a layout using none of these costs one config.Scanner() call and\n// nothing else.\nfunc registerScanCallbacks(r *dynreplacer.Replacer) {\n\ts := scanner()\n\n\tr.RegisterCallback(\":scan:\", func() string { return s.Base() })\n\tr.RegisterCallback(\":scan.realm:\", func() string {\n\t\treturn mygnoscan.Link(\"mygnoscan\", s.Realm(realmPath))\n\t})\n\tr.RegisterCallback(\":scan.me:\", func() string {\n\t\treturn mygnoscan.Link(\"my account\", s.Address(admin))\n\t})\n\tr.RegisterCallback(\":scan.block:\", func() string {\n\t\treturn mygnoscan.Link(\"this block\", s.Block(runtime.ChainHeight()))\n\t})\n\tr.RegisterCallback(\":scan.links:\", func() string { return scanLinks(s) })\n}\n\n// scanLinks is the :scan.links: placeholder: everything above on one line, for\n// a layout that wants the footer and does not want to lay it out by hand.\nfunc scanLinks(s mygnoscan.Scanner) string {\n\tparts := []string{\n\t\tmygnoscan.Link(\"this realm\", s.Realm(realmPath)),\n\t\tmygnoscan.Link(\"my account\", s.Address(admin)),\n\t\tmygnoscan.Link(\"this block\", s.Block(runtime.ChainHeight())),\n\t}\n\treturn strings.Join(parts, \" · \")\n}\n"},{"name":"scan_test.gno","body":"package home\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/mygnoscan/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestScanPlaceholdersAreReserved is the one that actually protects the\n// design: every placeholder scan.gno answers for must also be refused as a\n// slot name, or a slot could take the name and the page would depend on which\n// callback dynreplacer registered last.\nfunc TestScanPlaceholdersAreReserved(t *testing.T) {\n\tfor _, p := range scanPlaceholders {\n\t\tfound := false\n\t\tfor _, r := range reservedSlugs {\n\t\t\tif r == p {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tuassert.True(t, found, \"scan placeholder not reserved: \"+p)\n\t}\n}\n\nfunc TestScanSlugsAreWritableShapes(t *testing.T) {\n\t// A reserved slug still has to be a legal slug, or reserving it is a\n\t// no-op: an illegal name is refused for a different reason and the\n\t// reservation never gets exercised.\n\tfor _, p := range scanPlaceholders {\n\t\tuassert.True(t, validSlug(p), \"scan placeholder is not a valid slug: \"+p)\n\t}\n}\n\nfunc TestSetRefusesScanSlugs(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tuassert.AbortsWithMessage(t, cur, \"reserved slug: scan.realm is computed at render time\", func() {\n\t\tSet(cross(cur), \"scan.realm\", \"anything\")\n\t})\n}\n\n// TestScanLinksFollowConfig is the end-to-end claim of this whole change: what\n// the page renders follows gno.land/r/moul/config, so pointing moul's realms\n// at a different explorer is a transaction and not a redeploy.\n//\n// It cannot set the config from here (that needs config's own authority and a\n// crossing call into another realm), so it asserts the default path: unset\n// config means mygnoscan.DefaultBase, in the page, for real.\nfunc TestScanLinksFollowConfig(t *testing.T) {\n\treset()\n\tseed(\"layout\", \":scan.realm:\")\n\n\tuassert.Equal(t,\n\t\t\"[mygnoscan](\"+mygnoscan.DefaultBase+\"/realm/r/moul/home)\",\n\t\tRender(\"\"),\n\t\t\"with nothing configured the page falls back to the package default\")\n}\n\n// ExampleRender_scan pins the explorer footer as a layout would use it. The\n// block link is deliberately absent: it moves with the chain, and an example\n// that pins it would fail on whichever test ran SkipHeights before it.\nfunc ExampleRender_scan() {\n\treset()\n\tseed(\"layout\", \"# :owner:\\n\\n---\\n\\n:scan.realm: · :scan.me:\\n\")\n\tprint(Render(\"\"))\n\t// Output:\n\t// # g1manfred47kzduec920z88wfr64ylksmdcedlf5\n\t//\n\t// ---\n\t//\n\t// [mygnoscan](https://mygnoscan.moul.p2p.team/realm/r/moul/home) · [my account](https://mygnoscan.moul.p2p.team/address/g1manfred47kzduec920z88wfr64ylksmdcedlf5)\n}\n\n// ExampleRender_scanBase pins the raw base URL placeholder, which is what a\n// slot uses to build a link this realm has no helper for.\nfunc ExampleRender_scanBase() {\n\treset()\n\tseed(\"layout\", \":scan:\\n\")\n\tprint(Render(\"\"))\n\t// Output:\n\t// https://mygnoscan.moul.p2p.team\n}\n"}]},"send":"","max_deposit":"19000000ugnot"}],"fee":{"gas_wanted":"134525000","gas_fee":"403575ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"1LiKHdHiiHuBZ/9Q+cycSEHpr0glM9/2R5zkAzPgvKY15Pn1NujWmWYQxyJghsszEaC/JhIJUMPJB6XvfHR+eA=="}],"memo":""},"metadata":{"timestamp":"1790961913"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"markovdemo","path":"gno.land/r/moul/x/daily/markovdemo/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/daily/markovdemo/v0`\n\nLive demo of the [`p/moul/x/daily/markov`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/markov)\nMarkov-chain text generator.\n\nHolds one package-level `markov.Chain` as the on-chain corpus and wires it to the\nchain — babbling is seeded by `runtime.ChainHeight()`, so `Generate` stays a pure,\nreproducible query that still varies block to block. The realm ships pre-seeded\nwith a couple of sentences, so a fresh deploy already babbles:\n\n- `Feed(cur, text)` — tokenize `text` and fold it into the corpus (the crossing\n  function; any caller may enrich it).\n- `Generate(nWords) string` — babble ~`nWords` words, seeded by the block height.\n- `Stats() (int, int)` — returns `(totalWords, prefixCount)`.\n- `Render(\"/60\")` — a fresh 60-word sample plus corpus stats and a sample of\n  prefix → suffix rows; `Render(\"\")` defaults to 40 words.\n\nAll build/walk math lives in the library; this realm is just the wiring and the\ngnoweb view. Render it at [`/r/moul/x/daily/markovdemo/v0`](https://gno.land/r/moul/x/daily/markovdemo/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/markovdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/markovdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/markovdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/markovdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/markovdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/markovdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/markovdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/markovdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/markovdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/markovdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/markovdemo/v0\"\ngno = \"0.9\"\n"},{"name":"markovdemo.gno","body":"// Package markovdemo is a small on-chain demo of the Markov-chain text\n// generator provided by the [p/moul/x/daily/markov](/p/moul/x/daily/markov/v0)\n// library.\n//\n// It holds a single package-level [markov.Chain] as the corpus and wires it to\n// the chain: Feed appends words to that persistent chain (a crossing function,\n// since it mutates on-chain state), while Generate and Render walk it with a\n// seed derived from runtime.ChainHeight() — so babbling is a pure, reproducible\n// query that still varies block to block. It contains no Markov logic of its\n// own — build/walk math all lives in the library.\npackage markovdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/markov/v0\"\n)\n\n// maxGen clamps Generate / Render so output stays bounded.\nconst maxGen = 200\n\n// mc is the single on-chain corpus, seeded at deploy time.\nvar mc = markov.New()\n\nfunc init() {\n\t// Two seed sentences with heavy two-word-prefix overlap, so a fresh deploy\n\t// already babbles something recognizably chain-like.\n\tmc.Build(\"it was the best of times it was the worst of times \" +\n\t\t\"it was the age of wisdom it was the age of foolishness\")\n\tmc.Build(\"i am a free man i am not a number \" +\n\t\t\"i am the master of my fate i am the captain of my soul\")\n}\n\n// seedFor derives a Generate seed from the current chain height so the babble\n// changes block to block yet stays reproducible for anyone querying the same\n// height.\nfunc seedFor() uint64 {\n\treturn uint64(runtime.ChainHeight())*2654435761 + 0x9e3779b97f4a7c15\n}\n\n// Feed appends text to the on-chain corpus, extending the Markov chain. Any\n// caller may enrich the corpus — this is the open-membership demo model.\nfunc Feed(cur realm, text string) string {\n\tif strings.TrimSpace(text) == \"\" {\n\t\tpanic(\"markov: empty text\")\n\t}\n\tadded := mc.Build(text)\n\twords, prefixes := mc.Stats()\n\tchain.Emit(\"Feed\", \"words\", strconv.Itoa(added), \"total\", strconv.Itoa(words))\n\treturn \"fed \" + strconv.Itoa(added) + \" words; corpus now \" +\n\t\tstrconv.Itoa(words) + \" words across \" +\n\t\tstrconv.Itoa(prefixes) + \" prefixes\"\n}\n\n// Generate babbles up to nWords of Markov text from the current corpus, seeded\n// deterministically by the chain height. Read-only.\nfunc Generate(nWords int) string {\n\tif nWords \u003c= 0 {\n\t\tnWords = 20\n\t}\n\tif nWords \u003e maxGen {\n\t\tnWords = maxGen\n\t}\n\treturn strings.Join(mc.Generate(nWords, seedFor()), \" \")\n}\n\n// Stats returns (totalWords, prefixCount) for the current corpus.\nfunc Stats() (int, int) {\n\treturn mc.Stats()\n}\n\n// parseN pulls a trailing positive integer out of a Render path such as\n// \"/40\" or \"gen/40\"; it returns 0 when there is none.\nfunc parseN(path string) int {\n\tp := strings.Trim(path, \"/\")\n\tif i := strings.LastIndex(p, \"/\"); i \u003e= 0 {\n\t\tp = p[i+1:]\n\t}\n\tn, err := strconv.Atoi(p)\n\tif err != nil || n \u003c 0 {\n\t\treturn 0\n\t}\n\treturn n\n}\n\n// Render shows a freshly generated sample plus corpus stats. The path may\n// carry a word count, e.g. Render(\"/60\").\nfunc Render(path string) string {\n\tn := parseN(path)\n\tif n == 0 {\n\t\tn = 40\n\t}\n\tif n \u003e maxGen {\n\t\tn = maxGen\n\t}\n\n\twords, prefixes := mc.Stats()\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Markov Babbler\\n\\n\")\n\tb.WriteString(\"A demo of the [`p/moul/x/daily/markov`](/p/moul/x/daily/markov/v0) \" +\n\t\t\"library — an on-chain port of Go's classic *\\\"Generating arbitrary text: \" +\n\t\t\"a Markov chain algorithm\\\"* codewalk. Every two-word **prefix** maps to \" +\n\t\t\"the words that followed it; `Generate` walks that chain, picking suffixes \" +\n\t\t\"with a PRNG seeded by the block height — deterministic, yet different each \" +\n\t\t\"block.\\n\\n\")\n\n\tb.WriteString(\"## Fresh sample (\" + strconv.Itoa(n) + \" words, height \" +\n\t\tstrconv.FormatInt(runtime.ChainHeight(), 10) + \")\\n\\n\")\n\tsample := strings.Join(mc.Generate(n, seedFor()), \" \")\n\tif sample == \"\" {\n\t\tsample = \"_(empty corpus)_\"\n\t}\n\tb.WriteString(\"\u003e \" + sample + \"\\n\\n\")\n\n\tb.WriteString(\"## Corpus\\n\\n\")\n\tb.WriteString(\"- **Words:** \" + strconv.Itoa(words) + \"\\n\")\n\tb.WriteString(\"- **Distinct prefixes:** \" + strconv.Itoa(prefixes) + \"\\n\")\n\tb.WriteString(\"- **Prefix length:** \" + strconv.Itoa(markov.PrefixLen) + \" words\\n\\n\")\n\n\tb.WriteString(\"## Some prefixes → suffixes\\n\\n\")\n\tb.WriteString(\"| prefix | can be followed by |\\n|---|---|\\n\")\n\tshown := 0\n\tmc.Iterate(func(k string, suffixes []string) bool {\n\t\tdisp := k\n\t\tif disp == \" \" || disp == \"\" {\n\t\t\tdisp = \"_(start)_\"\n\t\t}\n\t\tb.WriteString(\"| `\" + disp + \"` | \" + strings.Join(suffixes, \", \") + \" |\\n\")\n\t\tshown++\n\t\treturn shown \u003e= 12 // cap the table\n\t})\n\tb.WriteString(\"\\n_Call `Feed(\\\"your text here\\\")` to teach it new words, then \" +\n\t\t\"reload for a new sample._\\n\")\n\n\treturn b.String()\n}\n"},{"name":"render_example_test.gno","body":"package markovdemo\n\n// ExampleRender pins the realm's Render output as a gno testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Markov Babbler\n\t//\n\t// A demo of the [`p/moul/x/daily/markov`](/p/moul/x/daily/markov/v0) library — an on-chain port of Go's classic *\"Generating arbitrary text: a Markov chain algorithm\"* codewalk. Every two-word **prefix** maps to the words that followed it; `Generate` walks that chain, picking suffixes with a PRNG seeded by the block height — deterministic, yet different each block.\n\t//\n\t// ## Fresh sample (40 words, height 123)\n\t//\n\t// \u003e it was the age of foolishness i am the master of my soul\n\t//\n\t// ## Corpus\n\t//\n\t// - **Words:** 48\n\t// - **Distinct prefixes:** 33\n\t// - **Prefix length:** 2 words\n\t//\n\t// ## Some prefixes → suffixes\n\t//\n\t// | prefix | can be followed by |\n\t// |---|---|\n\t// | `_(start)_` | it |\n\t// | ` it` | was |\n\t// | `a free` | man |\n\t// | `a number` | i |\n\t// | `age of` | wisdom, foolishness |\n\t// | `am a` | free |\n\t// | `am not` | a |\n\t// | `am the` | master, captain |\n\t// | `best of` | times |\n\t// | `captain of` | my |\n\t// | `fate i` | am |\n\t// | `foolishness i` | am |\n\t//\n\t// _Call `Feed(\"your text here\")` to teach it new words, then reload for a new sample._\n}\n"}]},"send":"","max_deposit":"30000000ugnot"}],"fee":{"gas_wanted":"51465900","gas_fee":"154397ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"pTXICWo+8h5NxMcvRLxgxWIh7hJE19HxWp6SmknIZxhxwUPTjN4gKT3x1RSqYrvB0uM1IThGTqECeiGUm50SBQ=="}],"memo":""},"metadata":{"timestamp":"1790961949"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402581","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"mvmbBo+S/X0gg4Sj6ApkttqRDX/95sK23eU3KNrpT5l7CpBMH70rsg9swzjrBSdXUnZBPEcwaQkWNzLh8iR7Rw=="}],"memo":""},"metadata":{"timestamp":"1790961960"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"niwQjlgAti1T97xfIrsv1xdlV20T0SAXab4WGYLy7N4JyQlOC+moYLunm9IjvLx261ib7FRNTnXKw/k0lUZoeg=="}],"memo":""},"metadata":{"timestamp":"1790961967"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"BRQXEjqj3pGoRvF6PlOPGS5SWpq8Kjp906CClMaC5+QMiPnd5U+Q/5bk7nlkh4ELkJ0OsgWrb4PSBK0xSzDXKA=="}],"memo":""},"metadata":{"timestamp":"1790962030"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"gWLNGj1G1MxX86/TuX/exL3VA9imQDtFdC6yfinDXfcBl5g9eZdyXaFD38kjCanGDy8Lo4SMiH0rup84hieagg=="}],"memo":""},"metadata":{"timestamp":"1790962092"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"triedemo","path":"gno.land/r/moul/x/daily/triedemo/v0","files":[{"name":"README.md","body":"# Trie Autocomplete\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA gnoweb autocomplete box: type a prefix in the URL and the realm lists every\ndictionary word that completes it, in lexicographic order.\n\nDemo of the [`p/moul/x/daily/trie`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/trie)\nlibrary — the tree, the ordering and the result cap all come from the package;\nthis realm holds no trie logic of its own. The dictionary is a fixed 55-word\nlist of gno/Go vocabulary, so the realm has no mutable state and `Render` is\nfully deterministic.\n\n```\n/r/moul/x/daily/triedemo/v0        → dictionary size + a few prefixes to try\n/r/moul/x/daily/triedemo/v0:co     → the 10 words starting with \"co\"\n/r/moul/x/daily/triedemo/v0:trie   → \"trie\" is itself a word\n/r/moul/x/daily/triedemo/v0:zzz    → no match\n```\n\nRead-only: there are no state-changing functions, so nothing here costs more\nthan a query. Results are capped at 25 per render.\n\nBuilt for gno 0.9.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/triedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/triedemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/triedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/triedemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/triedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/triedemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/triedemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/triedemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/triedemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/triedemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/triedemo/v0\"\ngno = \"0.9\"\n"},{"name":"render_example_test.gno","body":"package triedemo\n\n// ExampleRender pins the realm's root Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Trie Autocomplete\n\t//\n\t// A prefix tree over a 55-word dictionary, demoing the [`p/moul/x/daily/trie`](/p/moul/x/daily/trie/v0) library.\n\t//\n\t// Append a prefix to the path to complete it.\n\t//\n\t// ## Try one\n\t//\n\t// - [`/co`](/r/moul/x/daily/triedemo/v0:co) — 10 words\n\t// - [`/gno`](/r/moul/x/daily/triedemo/v0:gno) — 5 words\n\t// - [`/re`](/r/moul/x/daily/triedemo/v0:re) — 6 words\n\t// - [`/tr`](/r/moul/x/daily/triedemo/v0:tr) — 5 words\n}\n\n// ExampleRender_prefix pins a prefix walk: the completions come out in\n// lexicographic order, and `trie` is flagged as a word in its own right.\nfunc ExampleRender_prefix() {\n\tprint(Render(\"/tr\"))\n\t// Output:\n\t// # Trie Autocomplete\n\t//\n\t// A prefix tree over a 55-word dictionary, demoing the [`p/moul/x/daily/trie`](/p/moul/x/daily/trie/v0) library.\n\t//\n\t// ## Completions for `tr`\n\t//\n\t// **5** matches\n\t//\n\t// - `transaction`\n\t// - `transfer`\n\t// - `traverse`\n\t// - `tree`\n\t// - `trie`\n}\n\n// ExampleRender_unknown pins the miss path.\nfunc ExampleRender_unknown() {\n\tprint(Render(\"/zzz\"))\n\t// Output:\n\t// # Trie Autocomplete\n\t//\n\t// A prefix tree over a 55-word dictionary, demoing the [`p/moul/x/daily/trie`](/p/moul/x/daily/trie/v0) library.\n\t//\n\t// ## Completions for `zzz`\n\t//\n\t// _No word starts with `zzz`._\n\t//\n\t// \u003e Try `/co`, `/gno`, `/tr` or `/re`.\n}\n"},{"name":"triedemo.gno","body":"// Package triedemo is a small gnoweb demo of the prefix tree provided by the\n// [p/moul/x/daily/trie](/p/moul/x/daily/trie/v0) library: type a prefix in the\n// URL and it lists every dictionary word that completes it.\n//\n// It contains no trie logic of its own — the tree, the ordering and the limit\n// all come from the library. The dictionary is a fixed, sorted word list so the\n// realm has no mutable state and Render is fully deterministic.\npackage triedemo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/x/daily/trie/v0\"\n)\n\n// maxResults caps how many completions a single Render lists.\nconst maxResults = 25\n\n// dictionary is the demo corpus: gno/Go vocabulary, deliberately clustered on\n// a few prefixes (\"co\", \"gn\", \"re\", \"tr\") so completions are fun to explore.\nvar dictionary = []string{\n\t\"chain\", \"coin\", \"collection\", \"commit\", \"compile\", \"complete\", \"concurrent\",\n\t\"consensus\", \"constant\", \"contract\", \"counter\", \"crossing\", \"deploy\", \"gas\",\n\t\"genesis\", \"gno\", \"gnodev\", \"gnokey\", \"gnoland\", \"gnoweb\", \"goroutine\",\n\t\"grc20\", \"hash\", \"interface\", \"keeper\", \"ledger\", \"mempool\", \"merkle\",\n\t\"module\", \"namespace\", \"package\", \"panic\", \"pointer\", \"prefix\", \"prove\",\n\t\"realm\", \"receiver\", \"recover\", \"reflect\", \"render\", \"replay\", \"rollback\",\n\t\"slice\", \"stdlib\", \"struct\", \"transaction\", \"transfer\", \"traverse\", \"tree\",\n\t\"trie\", \"type\", \"validator\", \"vault\", \"vm\", \"wallet\",\n}\n\n// dict is built once at init; the library keeps it sorted internally.\nvar dict = trie.FromWords(dictionary)\n\n// Render renders the autocomplete for gnoweb.\n//\n//\tRender(\"\")          / Render(\"/\") -\u003e the whole dictionary + usage\n//\tRender(\"/\u003cprefix\u003e\")               -\u003e every word completing \u003cprefix\u003e\nfunc Render(path string) string {\n\tprefix := parsePrefix(path)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Trie Autocomplete\\n\\n\")\n\tb.WriteString(\"A prefix tree over a \")\n\tb.WriteString(strconv.Itoa(dict.Len()))\n\tb.WriteString(\"-word dictionary, demoing the \")\n\tb.WriteString(\"[`p/moul/x/daily/trie`](/p/moul/x/daily/trie/v0) library.\\n\\n\")\n\n\tif prefix == \"\" {\n\t\tb.WriteString(\"Append a prefix to the path to complete it.\\n\\n\")\n\t\tb.WriteString(\"## Try one\\n\\n\")\n\t\t// Listing all 55 words here would bury the page (and the example test\n\t\t// that pins it); the interesting part is the prefix walk, so show a few\n\t\t// live counts and let /\u003cprefix\u003e do the listing.\n\t\tfor _, p := range []string{\"co\", \"gno\", \"re\", \"tr\"} {\n\t\t\tb.WriteString(\"- [`/\")\n\t\t\tb.WriteString(p)\n\t\t\tb.WriteString(\"`](/r/moul/x/daily/triedemo/v0:\")\n\t\t\tb.WriteString(p)\n\t\t\tb.WriteString(\") — \")\n\t\t\tb.WriteString(strconv.Itoa(len(dict.Complete(p, 0))))\n\t\t\tb.WriteString(\" words\\n\")\n\t\t}\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"## Completions for `\")\n\tb.WriteString(prefix)\n\tb.WriteString(\"`\\n\\n\")\n\n\tif !dict.HasPrefix(prefix) {\n\t\tb.WriteString(\"_No word starts with `\")\n\t\tb.WriteString(prefix)\n\t\tb.WriteString(\"`._\\n\\n\u003e Try `/co`, `/gno`, `/tr` or `/re`.\\n\")\n\t\treturn b.String()\n\t}\n\n\twords := dict.Complete(prefix, maxResults)\n\tb.WriteString(\"**\")\n\tb.WriteString(strconv.Itoa(len(words)))\n\tb.WriteString(\"** match\")\n\tif len(words) != 1 {\n\t\tb.WriteString(\"es\")\n\t}\n\tif len(words) == maxResults {\n\t\tb.WriteString(\" (capped at \")\n\t\tb.WriteString(strconv.Itoa(maxResults))\n\t\tb.WriteString(\")\")\n\t}\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(list(words))\n\n\tif dict.Contains(prefix) {\n\t\tb.WriteString(\"\\n\u003e `\")\n\t\tb.WriteString(prefix)\n\t\tb.WriteString(\"` is itself a word in the dictionary.\\n\")\n\t}\n\treturn b.String()\n}\n\n// parsePrefix extracts the prefix from a Render path like \"/gno\", keeping only\n// the first segment. Returns \"\" for the empty/root path.\nfunc parsePrefix(path string) string {\n\ts := strings.TrimSpace(path)\n\ts = strings.TrimPrefix(s, \"/\")\n\tif i := strings.IndexByte(s, '/'); i \u003e= 0 {\n\t\ts = s[:i]\n\t}\n\treturn s\n}\n\n// list renders words as a Markdown bullet list.\nfunc list(words []string) string {\n\tif len(words) == 0 {\n\t\treturn \"_none_\\n\"\n\t}\n\tvar b strings.Builder\n\tfor _, w := range words {\n\t\tb.WriteString(\"- `\")\n\t\tb.WriteString(w)\n\t\tb.WriteString(\"`\\n\")\n\t}\n\treturn b.String()\n}\n"}]},"send":"","max_deposit":"40000000ugnot"}],"fee":{"gas_wanted":"50026800","gas_fee":"150080ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"rXB57kPs/NKezRt5WNEr2kUP7jem9BI8RcaYeWpWgItF7hvikTLZi06ifM00f45exEGtsY7A84s27sjKK/1XtA=="}],"memo":""},"metadata":{"timestamp":"1790962154"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DT1WC83whOKd4olJvji/4pH1cYteUJJ5vTTkXv6/ekxx45UhbIcgKEYZZ61wblISV8VjG+926OZ3hkCWJLPwyA=="}],"memo":""},"metadata":{"timestamp":"1790962157"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Uf2GpZUD8J0UZH7Nup+4hoWE5PNqDd0xUaGv4gwitBMHlgu8b+deRNmtf40e6jz/KHcgMO/VAdgtihan9aJXhQ=="}],"memo":""},"metadata":{"timestamp":"1790963950"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Q5IfwkuozjTGL27nuAkE+UN8P00Kv5eyb0dQUi2yAVxbps1Cau0wnN8ZeSrWGD9Zh0V76TjfaIfVkbgd4puE8w=="}],"memo":""},"metadata":{"timestamp":"1790964012"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"KbrJ9oHy6SgQ54rgjG+tyMMVx9N6vMSrg3kXMNVpL1ot1AU9RwbQ47SO/odKQLsRtWBoC1yXiNRnvn0chiu1rg=="}],"memo":""},"metadata":{"timestamp":"1790964074"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"QmFgZIu6hwA6Zb4vwPimZQHPSCBaB0QpmMnu/Tt/GeQbjvr1FHNK5kb3Z+jewet7MTLh2wEzW/bAjCufLXOKyw=="}],"memo":""},"metadata":{"timestamp":"1790964136"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"zones","path":"gno.land/p/moul/zones/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/zones/v0`\n\n**The content model of a curated registry of gno.land networks**: `Zone`,\n`Endpoint`, their validation, and the curation state machine, held by a\n`Registry`.\n\n```go\nimport \"gno.land/p/moul/zones/v0\"\n\nr := zones.NewRegistry()\nmust(r.Propose(proposer, height, \"onyx\", zones.Info{ChainID: \"onyx-1\", Title: \"Onyx\",\n\tKind: zones.Testnet, RPCURL: \"https://rpc.onyx.testnets.gno.land\"}))\nz, _ := r.Zone(\"onyx\")\nmust(r.ReviewZone(\"onyx\", zones.Approved, z.Revision, curator, height, \"\"))\nz, _ = r.Zone(\"onyx\") // the approval bumped the revision\nid, err := r.Register(proposer, height, \"onyx\", zones.Peer,\n\t\"g1x5mlj5ava0dw9vkf4j6admjlzswm6f06p44krn@seed-1.onyx.testnets.gno.land:26656\", \"gno core\")\nmust(err)\ne, _ := r.Endpoint(id) // a verification names the zone's revision and the endpoint's\nmust(r.ReviewEndpoint(id, zones.Verified, z.Revision, e.Revision, curator, height, \"answers onyx-1\"))\nr.Endpoints(zones.EndpointFilter{Zone: \"onyx\", Kind: zones.Peer, Status: zones.Verified}) // that one peer\n```\n\nA **zone** is one network: chain id, title, description, kind (`mainnet`,\n`testnet`, `devnet`, `local`), its main RPC, gnoweb and genesis URLs. An\n**endpoint** is one way into a zone: `rpc`, `gnoweb`, `seed`, `peer`, `indexer`,\n`faucet` or `explorer`, `unverified` until a curator says otherwise.\n\nThe live registry is [`r/moul/zones`](../../../r/moul/zones), which holds one\n`Registry` and decides who may write to it.\n\n**It decides nothing about who may act, deliberately.** Every write that\nrecords a decision takes the acting address and the height as arguments (the\ntwo removals take neither: who may remove is the holder's call). Whether that\naddress is a curator, the proposer, or nobody is the holding realm's call, so\nthe same model can move under a DAO or a system realm later without a line\nchanging here.\n\n## The curation policy\n\n| decision | from | reason | also |\n|---|---|---|---|\n| approve | pending, rejected, retired; approved, to restate the reason | optional (required to restate) | |\n| reject | pending; rejected, to restate the reason | **required** | verified endpoints go back to unverified (a restatement resets nothing) |\n| retire | approved; retired, to restate the reason | **required** | verified endpoints go back to unverified (a restatement resets nothing) |\n| edit | pending, approved | none before review, **required** after | a new chain id un-verifies endpoints; leaving `local` drops the private ones, at most `MaxDropPerEdit` (64) in one edit, refused while one carries a curator's ruling |\n| remove | pending, rejected | | endpoints go with it |\n| verify an endpoint | any, the same one only with a new reason | optional | zone pending or approved |\n| unverify an endpoint | any, the same one only with a new reason | optional | |\n| flag an endpoint | any, the same one only with a new reason | **required** | |\n\nEvery endpoint verdict, and every removal of one endpoint, names the endpoint's own\n`Revision`, bumped on registration, on every verdict and on every reset, from\nthe same never-repeating counter zones use: so it fails if another curator\nruled on the endpoint since it was read (a verdict landing unseen would reverse\ntheirs). A verification also names the zone's `Revision`, and fails if the zone\nchanged: what it checks is that the endpoint answers for this zone's chain id.\nA flag or an unverify does not, so editing a zone cannot hold off a warning.\nThe two are named apart, never combined, because a reader who takes them from\ntwo reads at two heights could otherwise combine stale ones into a valid one.\n\n- **Every decision on a zone binds to the zone as read**: its fields and its\n  status. Every edit bumps the\n  zone's `Revision`, registry-wide and never reused (not even by a zone removed\n  and proposed again under the same slug). Approving, rejecting, retiring,\n  editing and removing all name it, so an edit that lands between the reading\n  and the decision makes the decision fail, instead of attaching a name to text\n  nobody read. Every status change bumps it too, so an approval opened before a\n  colleague's rejection fails rather than reversing it. Verifying an endpoint\n  binds the same way, to the revision it was checked against: what was checked\n  is that it answers for this zone's chain id. An edit that changes nothing is\n  refused, so a revision only moves when something did. An endpoint's verdict\n  is not part of the zone and does not move it: a flag on the zone's own main\n  RPC shows on the zone, it does not invalidate an approval in flight.\n- **Only a pending or approved zone is editable.** An edit before review takes\n  no reason. An edit to an approved zone is a curator decision: the reason is\n  required and replaces the review on record. A changed chain id, on any zone,\n  sends every verified endpoint back to unverified, because what was verified\n  was that it answered for the old one. A reset caused by an edit to a pending\n  zone by its own proposer records nobody, because that is not a review:\n  `ReviewedBy` is empty and `Reason` says why. Every other reset records the\n  editor or the reviewer who caused it.\n- **Nothing goes back to pending.** A rejected zone is approved after all,\n  removed, or pushed out by 64 newer rejections.\n- **A zone that was ever official is never removed by a caller.** An approved\n  one is retired, and a retired one is kept until 128 newer retirements push it\n  out, so whoever still holds its chain id can find out what happened to it.\n\n## What a field accepts\n\nValidated at write time, not escaped at render time, for everything that is\nalso an index key, a URL segment or a config-file line:\n\n- **Slug**: 2 to 32 of `[a-z0-9-]`, alphanumeric at both ends.\n- **Chain id**: 1 to 50 of `[A-Za-z0-9._-]`.\n- **URL**: visible ASCII with none of `` \u003c\u003e\"'`()[]{}|\\^# ``, no credentials,\n  no `%` without two hex digits after it, no `\u0026name;` shape, a host that is a\n  DNS name or an IPv4 address (anything a browser would read as IPv4, like\n  `0x7f.1`, must be a valid dotted quad), an optional port of 1 to 65535 with no leading zero, in\n  digits, and a scheme from a short list. A zone's main RPC is `http`, `https`\n  or `tcp` with no path, query or trailing slash, which is what `gnokey -remote`\n  dials; an `rpc` endpoint also takes `ws`, `wss` and a path (a `tcp://` one\n  is host and port only, since gnokey dials it as such), and an `indexer`\n  takes `ws` and `wss` for its subscriptions. A `%` never\n  escapes a character that needs no escaping, and a path has no `.` or `..`\n  segment, so a URL has one spelling. A host that names a different machine\n  for every reader is refused except on a `local` zone: a name with no dot,\n  `.localhost`, `.local`, `.internal`, `.localdomain`, the RFC 6761 names\n  `.test`, `.example` and `.invalid`, the never-delegated `.lan`, `.home`,\n  `.corp`, `.mail`, `.intranet`, `.private`, `.onion`, `.alt`, the\n  service-discovery, container and overlay names `.consul`, `.lxd`, `.incus`,\n  `.docker`, `.podman`, `.localnet`, `.svc` and `.i2p`, every `.arpa`\n  name (infrastructure, never a public service), and IPv4 \"this network\",\n  loopback, private, link-local, CGNAT, IETF-protocol, documentation,\n  benchmarking, 6to4 relay anycast, multicast and reserved ranges.\n  `IsPrivateHost` fails closed: anything but a bare host is private to it. A\n  zone that leaves the `local` kind drops every endpoint on one, in the same\n  edit, and the edit is refused while one of them carries a curator's ruling.\n  An IPv4 host has no terminal dot.\n- **Peer**: `\u003cnode id\u003e@\u003chost\u003e:\u003cport\u003e`, the shape `p2p.persistent_peers` takes,\n  the node id a lowercase g1 address (tm2 compares node ids byte for byte), and\n  no terminal dot on an IPv4 host (Go's dialer cannot use one, so URLs refuse\n  it too).\n- **Address** (proposer, registrant, reviewer): a valid g1 address in lowercase.\n  bech32 also decodes the uppercase form, and here it would be a second identity.\n- **Trimming**: tabs and every Unicode space separator (Zs: U+0020, U+00A0,\n  U+3000 and the like) are trimmed from what a caller types. Anything else at\n  an edge (a line separator, U+0085) reaches the validator and is refused, not\n  cut. A zone's gnoweb and genesis URLs, like an endpoint's, have an empty\n  query's `?` and a bare `/` dropped, as a browser's address bar writes them;\n  the zone's main RPC, which gnokey dials, is refused with them. An endpoint is\n  validated as it will be stored.\n- **Free text** (title, description, label, reason): one line, bounded in\n  characters (so at most four times as many bytes), valid UTF-8, with no control\n  character, no invisible, format, private-use or unassigned character, no\n  variation selector except right after a character it modifies (FE0E or FE0F\n  after a symbol or one of the five emoji whose base is punctuation or a letter\n  by category (‼ ⁉ ℹ 〰 〽), as a phone\n  writes ❤️ or ‼️; a Mongolian free variant; an ideographic variation sequence), no enclosing mark (it draws a badge's frame around any\n  character), no run of more than four nonspacing marks, none of the\n  status glyphs a Render draws nor their look-alikes, and, unless it is empty,\n  something visible. Refused rather than stripped, so what is stored is what is\n  shown. It must still be escaped by whoever renders it. Two consequences:\n  the zero-width joiner and non-joiner are refused, so the Persian and Sinhala\n  spellings and the emoji sequences that need them cannot be written; and\n  \"assigned\" means in the chain's own Unicode tables, 15.0, so a character\n  assigned since is refused on chain though `gno test` (which uses the host's\n  tables) accepts it.\n\nAn endpoint, like a zone's URLs, is stored with its scheme and host lowercased\n(a peer lowercased whole, without its host's terminal dot; a URL without an\nempty query's `?` or a bare `/`, which gnokey would dial), so every later\ncomparison finds nothing to change, and deduplicated on\n`Canonical`: scheme and host lowercased, a terminal dot, a default port, an\nempty path before a query, an empty query's `?` and a bare `/` dropped, `%XX`\nhex uppercased, an rpc `tcp://` read as the `http://` gnokey dials, anything\nmeaningful after the host kept as typed. The same address under two kinds is two\nendpoints.\n\n## Bounds\n\nThe **live registry**, pending and approved zones together, holds at most 256.\nRejected and retired zones are kept for the record but do not count against it:\neach state keeps at most 64 and 128, and the next one in drops the zone that has\nbeen in that state longest, endpoints and all. So no flood, no curator and no\namount of time fills the registry for good.\n\nThe last `ReservedForReviewers` (16) places of each hard cap, the live registry\nand a zone's endpoints, take only the exempt calls: strangers who keep a cap\nfull would otherwise lock out the curators who act under it.\n\n**Per-address caps** make one address cheap to ignore: 4 pending proposals, 16\nendpoints on a zone. Neither stops a flood from many addresses, so **the review\nqueue has an admission gate of its own**: 64 pending zones in all, 64 endpoints\nper zone waiting for a verdict, under a hard 128 per zone. A flagged endpoint\nhas its verdict and leaves the queue, so curators keep warnings instead of\ndeleting them to make room. The gate is checked where something enters, so a\nreview or a reset can push a count past it. A flood fills the queue and never\ncrowds out an approved zone or a verified endpoint, and `ProposeExempt` and\n`RegisterExempt` skip the gate and the per-address caps (not the hard caps) for\nthe reviewers the holding realm trusts, so a full queue never locks out the\npeople who clear it. An endpoint registered that way is marked `Exempt`.\n`Clearable` is an endpoint nobody ruled on that is not `Exempt`, what a bulk\nclear of a flood may remove, and `Registry.Clearable` counts them without\nreading one; since the gate holds the queue, there are never more than 64. Each entry costs its sender a storage deposit, refunded to\nwhoever signs the transaction that frees it (on a chain with transfers locked,\nto the storage fee collector instead), so a flooder who withdraws first gets it\nback: a bond, not a fee.\n\n## Storage\n\nRecords live in a B+ tree, the keyed, ordered container EFFECTIVE_GNO recommends\nfor iteration and pagination (671 B per entry at fanout 32), with ids that are\nnever reused. Every tree here, `kit/index`'s included, is at fanout 32, not 128:\na removal shifts every later value in its leaf, and each shifted value is\nrewritten, about 90k gas apiece for a number and 230k for a pointer on a real\nnode, so a smaller leaf bounds what one removal costs. `kit/store` has that\nshape on an avl tree (2,029 B), and on an immutable path the choice is\npermanent. Three B+ trees hold an id per key: slug, the endpoint dedup key (a\n128-bit hash of the canonical address rather than a second copy of it), and the\norder zones entered their state. Four hold a count per key: pending proposals\nper proposer, endpoints per registrant on a zone, flagged and clearable\nendpoints per zone. The other six are [`kit/index`](../kit/index): status,\napproved-by-chain-id, and for endpoints zone, zone-and-kind, not-verified and\non-a-private-host (so leaving `local` reads only those). Every one is written in\nthe same method as its record; counts come from the indexes without reading a\nrecord, and a page reads the records on it only (the bucket's id list, at most\n256 or 128 ids, is read whole). Measured on a node at the caps, with every text\nfield at full length in the costliest characters and 240-character hosts: the\nheaviest page is a zone page of 25 flagged rows with full reasons, about 1.5B of\nthe 3B query cap. A removal shifts the later records in its B+ tree leaf, and\nborrows from a neighbour when the leaf underflows; endpoint ids are handed out\nregistry-wide, so what a removal of a zone's endpoints costs depends on how they\ninterleave with other zones'. With them registered together, a rejection or\nretirement that evicts a full zone costs about 0.39B; in the worst layout a\nregistrant can arrange, with the shifted neighbours at full size and flagged and\nthe zone's verified endpoints spread across leaves, 2.35B (78% of a 3B block),\nthe heaviest write (an earlier 2.20B layout was sent to a node capped at 3B and\nlanded). That is also why an edit leaving `local` drops at most 64 (2.02B worst,\nwith a chain-id change and both own URLs moved in the same edit).\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/zones/v0\"\ngno = \"0.9\"\n"},{"name":"registry.gno","body":"package zones\n\nimport (\n\t\"crypto/sha256\"\n\t\"errors\"\n\t\"strconv\"\n\n\t\"gno.land/p/moul/kit/index/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\n// Bounds on what the registry holds.\n//\n// The LIVE registry, pending and approved zones, has a hard cap. Rejected and\n// retired zones are kept for the record but do not count against it: each has\n// a cap of its own, and when it is reached the zone that has been in that state\n// longest is dropped to make room (by when it entered the state, not when it\n// was proposed, so a long-lived network retired today is not the next to go).\n// So nothing a proposer or a curator does, and no amount of time, can fill the\n// registry for good: a cap that only ever fills is a lifetime cap, and on an\n// immutable path that is a brick.\n//\n// The per-address caps make one address cheap to ignore. Neither stops a flood\n// from many addresses, because an address is not an identity, so admission to\n// the review queue has a gate of its own (MaxPending zones, MaxUnverifiedPerZone\n// endpoints awaiting a verdict), well under the hard caps: a flood fills the\n// queue and never crowds out an approved zone or a verified endpoint. A\n// flagged endpoint has its verdict and leaves the queue, so curators keep a\n// warning instead of having to delete it to make room. The gate is checked\n// where something enters (Propose, Register); a review or a reset can push a\n// count past it, and never fails for it. ProposeExempt and RegisterExempt skip\n// it, and the per-address caps, for the reviewers a holder trusts: a full\n// queue must not lock out the people who clear it. The queue clears through\n// approval, verification, a flag, rejection, RemoveZone, RemoveEndpoint, an\n// edit leaving the local kind, and eviction. Flagged endpoints still count\n// toward MaxEndpointsPerZone: a flood a curator flags rather than removes can\n// fill the places a gated registration may use (all but the last\n// ReservedForReviewers), and removing it is the answer. Each entry costs its sender a\n// storage deposit, refunded to whoever signs the transaction that\n// frees it (on a chain where ugnot is not transfer-locked; on one that is, the\n// refund goes to the storage fee collector), so a flooder who withdraws first\n// gets it back: a bond, not a fee.\nconst (\n\tMaxZones               = 256 // pending and approved zones together\n\tMaxPending             = 64  // zones awaiting review, all proposers together\n\tMaxPendingPerProposer  = 4   // open proposals one address may have at once\n\tMaxRejected            = 64  // rejected zones kept for the record\n\tMaxRetired             = 128 // retired zones kept for the record\n\tMaxEndpointsPerZone    = 128\n\tMaxUnverifiedPerZone   = 64 // endpoints on one zone still waiting for a verdict (flagged ones have theirs)\n\tMaxEndpointsPerAddress = 16 // endpoints one address may register on one zone\n\t// MaxDropPerEdit bounds how many endpoints one edit off the local kind\n\t// drops, and so its gas: a removal rewrites up to about 45 later values in\n\t// two B+ tree leaves, and a caller can lay ids out so every removal does,\n\t// which at 128 measured 2.6B, close to a 3B block, and at 64 measures\n\t// 2.02B even with a chain-id reset spread across leaves and both own URLs\n\t// moved in the same edit. More waits for removals.\n\tMaxDropPerEdit = 64\n\t// ReservedForReviewers is how much of each hard cap (MaxZones live,\n\t// MaxEndpointsPerZone) only the exempt calls may use: strangers who keep\n\t// a cap full refill it the block after a curator clears it, and a cap a\n\t// curator cannot reach is one they cannot act under.\n\tReservedForReviewers = 16\n)\n\n// The reasons an endpoint carries when its zone changed under it and sent it\n// back to unverified. A reset caused by an edit to a pending zone by its own\n// proposer records nobody, because that is not a review: ReviewedBy is empty\n// and Reason says why. Every other reset (a rejection, a retirement, anybody\n// else's edit, any edit to an approved zone) records whoever caused it.\nconst (\n\tChainIDChanged = \"the zone's chain id changed; verify again\"\n\tZoneRetired    = \"the zone was retired; verify again if it returns\"\n\tZoneRejected   = \"the zone was rejected; verify again if it is approved\"\n)\n\n// IsReset reports whether an unverified endpoint is unverified only because its\n// zone changed under it: its reason is one of the three above. A reset reaches\n// only a verified endpoint, so it says nothing against the endpoint itself.\nfunc IsReset(e Endpoint) bool {\n\treturn e.Status == Unverified \u0026\u0026 (e.Reason == ChainIDChanged || e.Reason == ZoneRetired || e.Reason == ZoneRejected)\n}\n\n// sequences are the registry-wide counters: the last Revision handed out (so\n// none is reused) and the last status-entry sequence (the eviction order).\ntype sequences struct{ rev, seq uint64 }\n\n// fanout is the B+ tree fanout for every container this package builds itself:\n// 32, not the 128 EFFECTIVE_GNO.md measured cheapest in memory. Every value in\n// a B+ tree leaf is a boxed object of its own, and removing (or inserting) a\n// key shifts every later value in the leaf, each shift a store write. Measured\n// on a node, one transaction per step (gno master 3cc494ec4): removing the\n// first key of a fanout-128 leaf filled with 120 cost 15.8M gas, the last 5.1M,\n// about 90k gas per entry shifted for a scalar value (the counters, the unique\n// ids) and about 230k for a pointer (the zone and endpoint tables, kit/index);\n// at fanout 32 each costs the same per shift, on a leaf a quarter the size. Endpoints are removed and their dedup keys inserted at\n// arbitrary positions, so the smaller leaf is worth its larger node overhead\n// (671 B per entry against 592).\nconst fanout = 32\n\n// Registry holds the zones and their endpoints. The zero value is not usable:\n// call [NewRegistry]. All its state is behind pointers, so a copy of the value\n// is the same registry, not a second one sharing half of it.\n//\n// Every write touches its record and all of that record's indexes in one\n// method. The index writes cannot fail as written: every key is validated\n// non-empty and every unique key is checked free before the first write. If a\n// later change made one fail, the method returns the error and the holding\n// realm's abort undoes the half-applied write; that abort, not this method, is\n// the atomicity guarantee.\ntype Registry struct {\n\t// The two sequences live behind a pointer like every container here, so a\n\t// copied Registry value shares them: with them inline, r2 := *r1 would\n\t// share every zone but count revisions on its own, and hand out a revision\n\t// r1 had already used, which a stale decision would then pass.\n\tids *sequences\n\n\tzones      *table\n\tbySlug     *unique      // slug -\u003e zone id\n\tbyStatus   *index.Index // status -\u003e zone ids, so a page reads only its rows\n\tentered    *unique      // status|entry sequence -\u003e zone id: who has been in a state longest\n\tbyProposer *counter     // proposer -\u003e how many PENDING zones they have\n\tapproved   *index.Index // chain id -\u003e ids of APPROVED zones naming it\n\n\tendpoints *table\n\tbyAddress *unique      // slug|kind|hash(canonical address) -\u003e endpoint id\n\tbyZone    *index.Index // slug -\u003e endpoint ids\n\tbyKind    *index.Index // slug|kind -\u003e endpoint ids, so a page reads only its rows\n\tbyOwner   *counter     // slug|registrant -\u003e how many endpoints they registered\n\tunchecked *index.Index // slug -\u003e ids of endpoints that are not Verified\n\tflagged   *counter     // slug -\u003e how many of those are Flagged\n\tfresh     *counter     // slug -\u003e how many endpoints are Clearable\n\tprivate   *index.Index // slug -\u003e ids of endpoints on a private host (a local zone's only)\n}\n\n// NewRegistry returns an empty registry.\nfunc NewRegistry() *Registry {\n\treturn \u0026Registry{\n\t\tids:        \u0026sequences{},\n\t\tzones:      newTable(),\n\t\tbySlug:     newUnique(),\n\t\tbyStatus:   index.New(),\n\t\tentered:    newUnique(),\n\t\tbyProposer: newCounter(),\n\t\tapproved:   index.New(),\n\t\tendpoints:  newTable(),\n\t\tbyAddress:  newUnique(),\n\t\tbyZone:     index.New(),\n\t\tbyKind:     index.New(),\n\t\tbyOwner:    newCounter(),\n\t\tflagged:    newCounter(),\n\t\tfresh:      newCounter(),\n\t\tunchecked:  index.New(),\n\t\tprivate:    index.New(),\n\t}\n}\n\n// Propose files a new zone, Pending, under a slug nobody holds.\nfunc (r *Registry) Propose(by address, at int64, slug string, in Info) error {\n\treturn r.propose(by, at, slug, in, true)\n}\n\n// ProposeExempt is Propose without the admission gates (MaxPending and\n// MaxPendingPerProposer), for the reviewers a holding realm trusts: a flood\n// that fills the queue would otherwise lock out the people who clear it. It\n// also takes the last ReservedForReviewers places of the live registry, which\n// Propose may not; MaxZones itself still holds.\nfunc (r *Registry) ProposeExempt(by address, at int64, slug string, in Info) error {\n\treturn r.propose(by, at, slug, in, false)\n}\n\nfunc (r *Registry) propose(by address, at int64, slug string, in Info, gated bool) error {\n\tin = trimInfo(in)\n\tif err := ValidateSlug(slug); err != nil {\n\t\treturn err\n\t}\n\tif err := ValidateInfo(in); err != nil {\n\t\treturn err\n\t}\n\tif !ValidAddress(by) {\n\t\treturn errors.New(\"zones: the proposer is not a valid lowercase address\")\n\t}\n\tif r.bySlug.has(slug) {\n\t\treturn errors.New(\"zones: the slug \" + strconv.Quote(slug) + \" is taken\")\n\t}\n\tif r.Live() \u003e= MaxZones {\n\t\treturn errors.New(\"zones: the registry is full at \" + strconv.Itoa(MaxZones) + \" pending and approved zones\")\n\t}\n\tif gated \u0026\u0026 r.Live() \u003e= MaxZones-ReservedForReviewers {\n\t\treturn errors.New(\"zones: the registry's last \" + strconv.Itoa(ReservedForReviewers) + \" places are kept for curators\")\n\t}\n\tif gated \u0026\u0026 r.byStatus.Count(string(Pending)) \u003e= MaxPending {\n\t\treturn errors.New(\"zones: \" + strconv.Itoa(MaxPending) + \" proposals are already waiting for review; try again once a curator has cleared some\")\n\t}\n\tif n := r.byProposer.count(by.String()); gated \u0026\u0026 n \u003e= MaxPendingPerProposer {\n\t\treturn errors.New(\"zones: \" + by.String() + \" already has \" + strconv.Itoa(n) +\n\t\t\t\" pending proposals, the limit is \" + strconv.Itoa(MaxPendingPerProposer))\n\t}\n\tz := \u0026Zone{Slug: slug, Proposer: by, ProposedAt: at}\n\tz.setInfo(in)\n\tid := r.zones.add(z)\n\tr.bySlug.set(slug, id)\n\tr.byProposer.inc(by.String())\n\treturn r.enter(z, id, Pending)\n}\n\n// enter files a zone under a status, and bumps its Revision: a decision\n// prepared against the old status must fail too, or an approval opened before\n// a colleague's rejection would quietly reverse it. Only the two states that\n// evict read the entry order, so only they write it. The caller has already\n// taken the zone out of its old status.\nfunc (r *Registry) enter(z *Zone, id store.ID, to Status) error {\n\tr.ids.seq++\n\tr.ids.rev++\n\tz.Status, z.Entered, z.Revision = to, int64(r.ids.seq), int64(r.ids.rev)\n\tif evicts(to) {\n\t\tr.entered.set(enteredKey(to, z.Entered), id)\n\t}\n\treturn r.byStatus.Add(string(to), id)\n}\n\nfunc evicts(st Status) bool { return st == Rejected || st == Retired }\n\n// leave takes a zone out of its current status.\nfunc (r *Registry) leave(z *Zone, id store.ID) {\n\tr.byStatus.Remove(string(z.Status), id)\n\tif evicts(z.Status) {\n\t\tr.entered.remove(enteredKey(z.Status, z.Entered))\n\t}\n\tif z.Status == Pending {\n\t\tr.byProposer.dec(z.Proposer.String())\n\t}\n\tif z.Status == Approved {\n\t\tr.approved.Remove(z.ChainID, id)\n\t}\n}\n\nfunc enteredKey(st Status, seq int64) string { return string(st) + \"|\" + store.ID(seq).Key() }\n\n// Edit replaces a zone's Info: every field but the slug and the status.\n//\n// Only a pending or an approved zone can be edited. A rejected one is removed\n// and proposed again, or approved first; a retired one is a record, and its\n// retirement reason is the thing it is kept for.\n//\n// Every edit bumps the zone's Revision and records who made it and when. On a\n// pending zone that is all, and a reason is refused rather than silently\n// dropped: nobody has reviewed anything yet. On an approved zone an edit is a\n// curator decision of its own: the reviewed values changed, so the review on\n// record is replaced by this one, with a reason required.\n//\n// When the chain id changes, whatever the status, every endpoint verified\n// against the old one goes back to unverified: what was verified was that it\n// answered for a chain this zone no longer names. A reset caused by the\n// proposer's own edit to a pending zone records no reviewer; any other records\n// the editor. An edit that changes nothing is refused, and leaving the local\n// kind removes every endpoint on a private or special-use host (IsPrivateHost),\n// at most MaxDropPerEdit in one edit, and is refused while one of them carries\n// a curator's ruling.\n//\n// An edit names the revision it was written against, like an approval does, so\n// two editors working from the same reading cannot silently undo each other.\nfunc (r *Registry) Edit(slug string, revision int64, in Info, by address, at int64, reason string) error {\n\tz, zid, err := r.zone(slug)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := stale(z, revision); err != nil {\n\t\treturn err\n\t}\n\tif z.Status != Pending \u0026\u0026 z.Status != Approved {\n\t\treturn errors.New(\"zones: \" + slug + \" is \" + string(z.Status) + \"; only a pending or approved zone can be edited\")\n\t}\n\tin = trimInfo(in)\n\tif err := ValidateInfo(in); err != nil {\n\t\treturn err\n\t}\n\tif !ValidAddress(by) {\n\t\treturn errors.New(\"zones: the editor is not a valid lowercase address\")\n\t}\n\treason = TrimSpaces(reason)\n\tif err := ValidateReason(reason); err != nil {\n\t\treturn err\n\t}\n\tswitch {\n\tcase z.Status == Pending \u0026\u0026 reason != \"\":\n\t\treturn errors.New(\"zones: \" + slug + \" is pending, and an edit before review takes no reason\")\n\tcase z.Status == Approved \u0026\u0026 !HasVisible(reason):\n\t\treturn errors.New(\"zones: \" + slug + \" is approved, so an edit needs a reason\")\n\t}\n\t// An edit that changes nothing would still bump the revision, so refusing\n\t// it is what stops a revision being bumped for its own sake.\n\tif in == z.Info() {\n\t\treturn errors.New(\"zones: that edit changes nothing on \" + slug)\n\t}\n\t// Leaving the local kind drops the private hosts only a local zone may\n\t// list, whatever their verdict: they name nothing on the zone it becomes.\n\t// Dropped in the edit itself, not refused until somebody removes them,\n\t// because anybody may register one again between that removal and this\n\t// edit. Only those endpoints are read, from their own index. One a\n\t// curator ruled on (a verdict, or a reset that left a reason) is a\n\t// record, maybe one the editor never saw: the edit fails while one is\n\t// listed, and a curator removes it first, naming its revision. Only a\n\t// curator can rule, so nobody else can block the edit this way.\n\tif z.Kind == Local \u0026\u0026 in.Kind != Local {\n\t\tdrop := r.private.Lookup(slug)\n\t\tif len(drop) \u003e MaxDropPerEdit {\n\t\t\treturn errors.New(\"zones: leaving local would drop \" + strconv.Itoa(len(drop)) + \" endpoints, more than \" +\n\t\t\t\tstrconv.Itoa(MaxDropPerEdit) + \" in one edit; remove some first\")\n\t\t}\n\t\tfor _, eid := range drop {\n\t\t\tv, _ := r.endpoints.get(eid)\n\t\t\t// Every verdict names its reviewer and a reset leaves a reason, so\n\t\t\t// these two say \"ruled on\".\n\t\t\tif e := v.(*Endpoint); e.ReviewedBy != \"\" || e.Reason != \"\" {\n\t\t\t\twho := \"a curator ruled on; a curator must remove it first\"\n\t\t\t\tif e.Status == Verified {\n\t\t\t\t\twho = \"is verified; its registrant or a curator must remove it first\"\n\t\t\t\t}\n\t\t\t\treturn errors.New(\"zones: leaving local would drop endpoint #\" + strconv.FormatInt(e.ID, 10) + \", which \" + who)\n\t\t\t}\n\t\t}\n\t\tfor _, eid := range drop {\n\t\t\tr.removeEndpoint(eid)\n\t\t}\n\t}\n\tif in.ChainID != z.ChainID {\n\t\t// The proposer is not a reviewer; anybody else editing (a curator, on a\n\t\t// pending zone or an approved one) is, and is named on the reset.\n\t\tresetBy := address(\"\")\n\t\tif z.Status == Approved || by != z.Proposer {\n\t\t\tresetBy = by\n\t\t}\n\t\tif z.Status == Approved {\n\t\t\tr.approved.Remove(z.ChainID, zid)\n\t\t\tif err := r.approved.Add(in.ChainID, zid); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif err := r.unverifyAll(slug, resetBy, at, ChainIDChanged); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif z.Status == Approved {\n\t\tz.ReviewedBy, z.ReviewedAt, z.Reason = by, at, reason\n\t}\n\tr.ids.rev++\n\tz.Revision = int64(r.ids.rev)\n\tz.EditedBy, z.EditedAt = by, at\n\tz.setInfo(in)\n\treturn nil\n}\n\n// ReviewZone records a curator's decision on a zone.\n//\n// The transitions are the curation policy, and they are deliberately few:\n//\n//\tapprove  from pending, rejected or retired   reason optional\n//\treject   from pending                        reason REQUIRED\n//\tretire   from approved                       reason REQUIRED\n//\n// and a decision restated: the zone's present status again, with a new\n// visible reason, which records the new reviewer and bumps the revision and\n// does nothing else (no new entry in the state, no eviction, no reset). It is\n// the only way to correct a reason.\n//\n// Every decision names the zone's Revision the curator read, and fails if the\n// zone changed since: otherwise a proposer's edit landing just before an\n// approval would become official under the curator's name, and a rejection's\n// public reason would describe text the curator never saw.\n//\n// Rejecting or retiring sends every verified endpoint back to unverified: a\n// rejected zone was never vouched for, and a retired network's peers may be\n// somebody else's hosts by the time anyone reads them. Each state keeps at most\n// MaxRejected or MaxRetired zones; the next one in drops the zone that entered\n// that state first, with its endpoints. Every transition bumps the zone's\n// Revision, so a decision prepared against the old status fails.\n//\n// Nothing goes back to pending: a rejected zone is approved after all, removed,\n// or pushed out by newer rejections. An official zone is never rejected\n// after the fact, it is retired, so the record of it having been official\n// survives.\nfunc (r *Registry) ReviewZone(slug string, to Status, revision int64, by address, at int64, reason string) error {\n\tz, id, err := r.zone(slug)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !ValidAddress(by) {\n\t\treturn errors.New(\"zones: the reviewer is not a valid lowercase address\")\n\t}\n\treason = TrimSpaces(reason)\n\tif err := ValidateReason(reason); err != nil {\n\t\treturn err\n\t}\n\tif err := stale(z, revision); err != nil {\n\t\treturn err\n\t}\n\tif z.Status == to {\n\t\t// A decision is restated with a new reason, the only way to correct\n\t\t// one: a rejected or retired zone is not editable, and an edit to an\n\t\t// approved zone must change something besides its reason.\n\t\tif (to == Approved || to == Rejected || to == Retired) \u0026\u0026 HasVisible(reason) \u0026\u0026 reason != z.Reason {\n\t\t\tr.ids.rev++\n\t\t\tz.Revision = int64(r.ids.rev)\n\t\t\tz.ReviewedBy, z.ReviewedAt, z.Reason = by, at, reason\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"zones: \" + slug + \" is already \" + string(to))\n\t}\n\tswitch to {\n\tcase Approved:\n\t\tif z.Status != Pending \u0026\u0026 r.Live() \u003e= MaxZones {\n\t\t\treturn errors.New(\"zones: the registry is full at \" + strconv.Itoa(MaxZones) + \" pending and approved zones\")\n\t\t}\n\tcase Rejected:\n\t\tif z.Status == Approved {\n\t\t\treturn errors.New(\"zones: \" + slug + \" is approved; retire it instead of rejecting it\")\n\t\t}\n\t\tif z.Status != Pending {\n\t\t\treturn errors.New(\"zones: only a pending zone can be rejected; \" + slug + \" is \" + string(z.Status))\n\t\t}\n\tcase Retired:\n\t\tif z.Status != Approved {\n\t\t\treturn errors.New(\"zones: only an approved zone can be retired; \" + slug + \" is \" + string(z.Status))\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"zones: a review cannot set a zone to \" + strconv.Quote(string(to)))\n\t}\n\tif (to == Rejected || to == Retired) \u0026\u0026 !HasVisible(reason) {\n\t\treturn errors.New(\"zones: \" + string(to) + \" needs a reason\")\n\t}\n\tswitch to {\n\tcase Rejected:\n\t\tif err := r.unverifyAll(slug, by, at, ZoneRejected); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.makeRoom(Rejected, MaxRejected)\n\tcase Retired:\n\t\tif err := r.unverifyAll(slug, by, at, ZoneRetired); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.makeRoom(Retired, MaxRetired)\n\t}\n\tr.leave(z, id)\n\tif to == Approved {\n\t\tif err := r.approved.Add(z.ChainID, id); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := r.enter(z, id, to); err != nil {\n\t\treturn err\n\t}\n\tz.ReviewedBy, z.ReviewedAt, z.Reason = by, at, reason\n\treturn nil\n}\n\n// stale refuses a decision written against a revision the zone has moved past.\nfunc stale(z *Zone, revision int64) error {\n\tif revision != z.Revision {\n\t\treturn errors.New(\"zones: \" + z.Slug + \" changed since you read it: it is at revision \" +\n\t\t\tstrconv.FormatInt(z.Revision, 10) + \", you acted on revision \" + strconv.FormatInt(revision, 10) +\n\t\t\t\"; read it again\")\n\t}\n\treturn nil\n}\n\n// makeRoom drops the zone that has been in that state longest, when the state\n// is at its cap, so the one about to enter fits.\nfunc (r *Registry) makeRoom(status Status, max int) {\n\tfor r.byStatus.Count(string(status)) \u003e= max {\n\t\tvar oldest store.ID\n\t\tr.entered.tree.Iterate(string(status)+\"|\", string(status)+\"}\", func(_ string, v any) bool {\n\t\t\toldest = v.(store.ID)\n\t\t\treturn true\n\t\t})\n\t\tv, _ := r.zones.get(oldest)\n\t\tr.removeZone(v.(*Zone), oldest)\n\t}\n}\n\n// RemoveZone deletes a pending or rejected zone and every endpoint registered\n// on it, freeing their storage deposit to whoever signs the removal. It names\n// the revision it was decided on, so a removal meant for one proposal cannot\n// land on another proposed again under the same slug. A zone that has ever\n// been official cannot be removed this way: an approved one is retired, and a\n// retired one is kept until MaxRetired newer retirements push it out, so\n// whoever still holds its chain id can find out what happened to it.\nfunc (r *Registry) RemoveZone(slug string, revision int64) error {\n\tz, id, err := r.zone(slug)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := stale(z, revision); err != nil {\n\t\treturn err\n\t}\n\tif z.Status == Approved {\n\t\treturn errors.New(\"zones: \" + slug + \" is approved; retire it instead of removing it\")\n\t}\n\tif z.Status == Retired {\n\t\treturn errors.New(\"zones: \" + slug + \" is retired, and a retired zone is kept on record\")\n\t}\n\tr.removeZone(z, id)\n\treturn nil\n}\n\n// removeZone unwinds a zone, its endpoints and every index. The per-zone index\n// keys go in one RemoveKey each rather than an id at a time, which would copy\n// the bucket once per endpoint.\nfunc (r *Registry) removeZone(z *Zone, id store.ID) {\n\tslug := z.Slug\n\tfor _, eid := range r.byZone.Lookup(slug) {\n\t\tv, ok := r.endpoints.remove(eid)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tr.byOwner.dec(ownerKey(slug, v.(*Endpoint).Registrant))\n\t}\n\t// The zone's dedup keys are one contiguous range (a slug is [a-z0-9-], all\n\t// below \"|\"), so they are dropped without hashing each address again.\n\tkeys := []string{}\n\tr.byAddress.tree.Iterate(slug+\"|\", slug+\"}\", func(k string, _ any) bool {\n\t\tkeys = append(keys, k)\n\t\treturn false\n\t})\n\tfor _, k := range keys {\n\t\tr.byAddress.remove(k)\n\t}\n\tr.flagged.drop(slug)\n\tr.fresh.drop(slug)\n\tr.byZone.RemoveKey(slug)\n\tr.unchecked.RemoveKey(slug)\n\tr.private.RemoveKey(slug)\n\tfor _, k := range EndpointKinds() {\n\t\tr.byKind.RemoveKey(kindKey(slug, k))\n\t}\n\tr.leave(z, id)\n\tr.bySlug.remove(slug)\n\tr.zones.remove(id)\n}\n\n// Register adds an endpoint to a zone, Unverified, and returns its id.\n//\n// A zone takes endpoints while it is pending or approved, and a rejected or\n// retired zone takes none. Who may register on a pending zone is the holding\n// realm's call; a URL is stored with its scheme and host lowercased and\n// without an empty tail (trimEmptyTail), a peer lowercased whole without its\n// host's terminal dot, so what is listed is what dials (Canonical, which also drops default ports and reads tcp as http, is\n// what they are compared in, not what is stored).\nfunc (r *Registry) Register(by address, at int64, slug string, kind EndpointKind, addr, label string) (int64, error) {\n\treturn r.register(by, at, slug, kind, addr, label, true)\n}\n\n// RegisterExempt is Register without the admission gates\n// (MaxUnverifiedPerZone and MaxEndpointsPerAddress), for the reviewers a\n// holding realm trusts, as ProposeExempt is, and also takes a zone's last\n// ReservedForReviewers places; the hard cap, MaxEndpointsPerZone, still holds.\nfunc (r *Registry) RegisterExempt(by address, at int64, slug string, kind EndpointKind, addr, label string) (int64, error) {\n\treturn r.register(by, at, slug, kind, addr, label, false)\n}\n\nfunc (r *Registry) register(by address, at int64, slug string, kind EndpointKind, addr, label string, gated bool) (int64, error) {\n\tz, _, err := r.zone(slug)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif z.Status != Pending \u0026\u0026 z.Status != Approved {\n\t\treturn 0, errors.New(\"zones: \" + slug + \" is \" + string(z.Status) + \" and takes no endpoints\")\n\t}\n\taddr = TrimSpaces(addr)\n\tlabel = TrimSpaces(label)\n\tif kind != Seed \u0026\u0026 kind != Peer {\n\t\t// Validated as it will be stored, so every rule judges the string\n\t\t// that dials, length included.\n\t\taddr = trimEmptyTail(lowerAuthority(addr))\n\t}\n\tif err := ValidateEndpoint(kind, addr); err != nil {\n\t\treturn 0, err\n\t}\n\tif kind == Seed || kind == Peer {\n\t\taddr = Canonical(kind, addr) // lowercase, no terminal dot: what tm2 dials\n\t}\n\tprivate := IsPrivateHost(HostOf(kind, addr))\n\tif z.Kind != Local \u0026\u0026 private {\n\t\treturn 0, errors.New(\"zones: \" + slug + \" is a \" + string(z.Kind) + \" zone, and \" + addr +\n\t\t\t\" names a private or special-use host; only a local zone lists those\")\n\t}\n\tif err := ValidateLabel(label); err != nil {\n\t\treturn 0, err\n\t}\n\tif !ValidAddress(by) {\n\t\treturn 0, errors.New(\"zones: the registrant is not a valid lowercase address\")\n\t}\n\takey := addressKey(slug, kind, addr)\n\tif r.byAddress.has(akey) {\n\t\treturn 0, errors.New(\"zones: \" + slug + \" already lists that \" + string(kind) + \": \" + addr)\n\t}\n\tif n := r.byZone.Count(slug); n \u003e= MaxEndpointsPerZone {\n\t\treturn 0, errors.New(\"zones: \" + slug + \" is full at \" + strconv.Itoa(MaxEndpointsPerZone) + \" endpoints\")\n\t} else if gated \u0026\u0026 n \u003e= MaxEndpointsPerZone-ReservedForReviewers {\n\t\treturn 0, errors.New(\"zones: \" + slug + \"'s last \" + strconv.Itoa(ReservedForReviewers) + \" endpoint places are kept for curators\")\n\t}\n\tif n := r.Awaiting(slug); gated \u0026\u0026 n \u003e= MaxUnverifiedPerZone {\n\t\treturn 0, errors.New(\"zones: \" + slug + \" already has \" + strconv.Itoa(n) +\n\t\t\t\" endpoints waiting for review; try again once a curator has cleared some\")\n\t}\n\tokey := ownerKey(slug, by)\n\tif n := r.byOwner.count(okey); gated \u0026\u0026 n \u003e= MaxEndpointsPerAddress {\n\t\treturn 0, errors.New(\"zones: \" + by.String() + \" already registered \" + strconv.Itoa(n) +\n\t\t\t\" endpoints on \" + slug + \", the limit is \" + strconv.Itoa(MaxEndpointsPerAddress))\n\t}\n\te := \u0026Endpoint{Zone: slug, Kind: kind, Address: addr, Label: label, Registrant: by, RegisteredAt: at, Status: Unverified, Exempt: !gated}\n\tid := r.endpoints.add(e)\n\te.ID = int64(id)\n\tr.ids.rev++\n\te.Revision = int64(r.ids.rev)\n\tr.byAddress.set(akey, id)\n\tif err := r.byZone.Add(slug, id); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := r.byKind.Add(kindKey(slug, kind), id); err != nil {\n\t\treturn 0, err\n\t}\n\tr.byOwner.inc(okey)\n\tif gated {\n\t\tr.fresh.inc(slug)\n\t}\n\tif err := r.unchecked.Add(slug, id); err != nil {\n\t\treturn 0, err\n\t}\n\tif private {\n\t\tif err := r.private.Add(slug, id); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn e.ID, nil\n}\n\n// ReviewEndpoint records a curator's verdict on an endpoint. Any verdict may\n// follow any other, and the same one again with a new reason (so a typo is\n// corrected without passing through a state its registrant may remove it\n// from), with these rules:\n//\n//   - every verdict names the endpoint's Revision as read, and fails if the\n//     endpoint changed since: a verdict landing after another curator's,\n//     unseen, would silently reverse it;\n//   - flagging needs a reason, because \"do not use this\" with no why is not\n//     something an operator can act on;\n//   - a verification also names the zone's Revision it was checked against,\n//     and fails if the zone changed since: what is verified is that the\n//     endpoint answers for THIS zone's chain id, and a proposer could otherwise\n//     switch it while the verdict is in flight. A flag or an unverify does\n//     not, so an edit to the zone cannot hold off a warning;\n//   - only an endpoint of a pending or approved zone can be verified.\nfunc (r *Registry) ReviewEndpoint(id int64, to Verification, zoneRevision, revision int64, by address, at int64, reason string) error {\n\te, err := r.endpoint(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !ValidAddress(by) {\n\t\treturn errors.New(\"zones: the reviewer is not a valid lowercase address\")\n\t}\n\treason = TrimSpaces(reason)\n\tif err := ValidateReason(reason); err != nil {\n\t\treturn err\n\t}\n\tswitch to {\n\tcase Unverified, Verified, Flagged:\n\tcase \"\":\n\t\treturn errors.New(\"zones: a review needs a verdict\")\n\tdefault:\n\t\t// Exact values only: ParseVerification trims, and a \" verified \" stored\n\t\t// as written would match no filter and count as unverified forever.\n\t\treturn errors.New(\"zones: unknown verification \" + strconv.Quote(string(to)) + \", want verified, unverified or flagged\")\n\t}\n\tif e.Status == to \u0026\u0026 (reason == e.Reason || !HasVisible(reason)) {\n\t\treturn errors.New(\"zones: endpoint #\" + strconv.FormatInt(id, 10) + \" is already \" + string(to) +\n\t\t\t\"; restating it needs a new reason\")\n\t}\n\tif to == Flagged \u0026\u0026 !HasVisible(reason) {\n\t\treturn errors.New(\"zones: flagging an endpoint needs a reason\")\n\t}\n\tz, _, err := r.zone(e.Zone)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif revision != e.Revision {\n\t\treturn errors.New(\"zones: endpoint #\" + strconv.FormatInt(id, 10) + \" changed since you checked it: it is at revision \" +\n\t\t\tstrconv.FormatInt(e.Revision, 10) + \", you acted on revision \" + strconv.FormatInt(revision, 10))\n\t}\n\tif to == Verified {\n\t\tif z.Status != Pending \u0026\u0026 z.Status != Approved {\n\t\t\treturn errors.New(\"zones: \" + z.Slug + \" is \" + string(z.Status) + \"; nothing on it can be verified\")\n\t\t}\n\t\tif zoneRevision != z.Revision {\n\t\t\treturn errors.New(\"zones: \" + z.Slug + \" changed since you checked it against it: it is at revision \" +\n\t\t\t\tstrconv.FormatInt(z.Revision, 10) + \", you verified against revision \" + strconv.FormatInt(zoneRevision, 10))\n\t\t}\n\t}\n\tsid := store.ID(id)\n\tif to == Verified {\n\t\tr.unchecked.Remove(e.Zone, sid)\n\t} else if e.Status == Verified {\n\t\tif err := r.unchecked.Add(e.Zone, sid); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif e.Status == Flagged {\n\t\tr.flagged.dec(e.Zone)\n\t}\n\tif to == Flagged {\n\t\tr.flagged.inc(e.Zone)\n\t}\n\tif e.Clearable() {\n\t\tr.fresh.dec(e.Zone) // its first verdict: somebody has ruled on it now\n\t}\n\te.Status = to\n\te.ReviewedBy, e.ReviewedAt, e.Reason = by, at, reason\n\tr.ids.rev++\n\te.Revision = int64(r.ids.rev)\n\treturn nil\n}\n\n// unverifyAll sends every verified endpoint of a zone back to unverified with\n// that reason, and by as the reviewer (\"\" when the proposer's own edit caused\n// it). Flagged ones keep their flag. Only the verified ones are read: their\n// ids are the zone's ids minus the unchecked ones, both kept ascending, so one\n// merge pass finds them without loading the rest.\nfunc (r *Registry) unverifyAll(slug string, by address, at int64, reason string) error {\n\tall := r.byZone.Lookup(slug)\n\tskip := r.unchecked.Lookup(slug)\n\tj := 0\n\tfor _, id := range all {\n\t\tfor j \u003c len(skip) \u0026\u0026 skip[j] \u003c id {\n\t\t\tj++\n\t\t}\n\t\tif j \u003c len(skip) \u0026\u0026 skip[j] == id {\n\t\t\tcontinue\n\t\t}\n\t\tv, ok := r.endpoints.get(id)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\te := v.(*Endpoint)\n\t\tif err := r.unchecked.Add(slug, id); err != nil {\n\t\t\treturn err\n\t\t}\n\t\te.Status = Unverified\n\t\te.ReviewedBy, e.ReviewedAt, e.Reason = by, at, reason\n\t\tr.ids.rev++\n\t\te.Revision = int64(r.ids.rev)\n\t}\n\treturn nil\n}\n\n// RemoveEndpoint deletes an endpoint, freeing its storage deposit to whoever\n// signs the removal. revision is the endpoint's Revision as read: a removal\n// fails if a verdict landed since, rather than delete one nobody saw. Who may\n// is the holding realm's call.\nfunc (r *Registry) RemoveEndpoint(id, revision int64) error {\n\te, err := r.endpoint(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif revision != e.Revision {\n\t\treturn errors.New(\"zones: endpoint #\" + strconv.FormatInt(id, 10) + \" changed since you read it: it is at revision \" +\n\t\t\tstrconv.FormatInt(e.Revision, 10) + \", you acted on revision \" + strconv.FormatInt(revision, 10))\n\t}\n\tr.removeEndpoint(store.ID(id))\n\treturn nil\n}\n\n// removeEndpoint unwinds the record and all eight of its indexes and counters\n// together.\nfunc (r *Registry) removeEndpoint(id store.ID) {\n\tv, ok := r.endpoints.remove(id)\n\tif !ok {\n\t\treturn\n\t}\n\te := v.(*Endpoint)\n\tr.byAddress.remove(addressKey(e.Zone, e.Kind, e.Address))\n\tr.byZone.Remove(e.Zone, id)\n\tr.byKind.Remove(kindKey(e.Zone, e.Kind), id)\n\tr.byOwner.dec(ownerKey(e.Zone, e.Registrant))\n\tr.unchecked.Remove(e.Zone, id)\n\tr.private.Remove(e.Zone, id)\n\tif e.Status == Flagged {\n\t\tr.flagged.dec(e.Zone)\n\t}\n\tif e.Clearable() {\n\t\tr.fresh.dec(e.Zone)\n\t}\n}\n\n// Revision is the last revision handed out, to a zone or an endpoint. Anything\n// that changes after a read gets a later one.\nfunc (r *Registry) Revision() int64 { return int64(r.ids.rev) }\n\n// PrivateEndpoints returns a zone's endpoints on a private host, the ones\n// leaving the local kind drops. Only those are read.\nfunc (r *Registry) PrivateEndpoints(slug string) []Endpoint {\n\tout := []Endpoint{}\n\tfor _, id := range r.private.Lookup(slug) {\n\t\tif v, ok := r.endpoints.get(id); ok {\n\t\t\tout = append(out, *v.(*Endpoint))\n\t\t}\n\t}\n\treturn out\n}\n\n// Zone returns a copy of the zone under slug.\nfunc (r *Registry) Zone(slug string) (Zone, bool) {\n\tz, _, err := r.zone(slug)\n\tif err != nil {\n\t\treturn Zone{}, false\n\t}\n\treturn *z, true\n}\n\n// Endpoint returns a copy of the endpoint with that id.\nfunc (r *Registry) Endpoint(id int64) (Endpoint, bool) {\n\te, err := r.endpoint(id)\n\tif err != nil {\n\t\treturn Endpoint{}, false\n\t}\n\treturn *e, true\n}\n\n// EndpointByAddress returns a copy of the endpoint a zone lists under that kind\n// and address, compared in [Canonical] form.\nfunc (r *Registry) EndpointByAddress(slug string, kind EndpointKind, addr string) (Endpoint, bool) {\n\tid, ok := r.byAddress.get(addressKey(slug, kind, addr))\n\tif !ok {\n\t\treturn Endpoint{}, false\n\t}\n\tv, ok := r.endpoints.get(id)\n\tif !ok {\n\t\treturn Endpoint{}, false\n\t}\n\treturn *v.(*Endpoint), true\n}\n\n// ZoneFilter selects zones. A zero field matches anything.\ntype ZoneFilter struct {\n\tStatus Status\n\tKind   Kind\n}\n\n// Match reports whether z passes the filter.\nfunc (f ZoneFilter) Match(z Zone) bool {\n\treturn (f.Status == \"\" || z.Status == f.Status) \u0026\u0026 (f.Kind == \"\" || z.Kind == f.Kind)\n}\n\n// Zones returns copies of the zones passing f, in the order they were\n// proposed. With a status set it reads that status's zones only.\n//\n// The result, like Endpoints', is capped at its length. A slice handed to\n// another realm is readonly there: an append that fits in spare capacity\n// writes into it and aborts, one that does not copies and succeeds. Uncapped,\n// an importer's append would pass or abort by how many rows the filter\n// dropped, which strangers decide by registering.\nfunc (r *Registry) Zones(f ZoneFilter) []Zone {\n\tif f.Status != \"\" {\n\t\tids := r.byStatus.Lookup(string(f.Status))\n\t\tout := make([]Zone, 0, len(ids))\n\t\tfor _, id := range ids {\n\t\t\tv, _ := r.zones.get(id)\n\t\t\tif z := v.(*Zone); f.Match(*z) {\n\t\t\t\tout = append(out, *z)\n\t\t\t}\n\t\t}\n\t\treturn out[:len(out):len(out)]\n\t}\n\tout := make([]Zone, 0, r.zones.len())\n\tr.zones.each(func(v any) {\n\t\tif z := v.(*Zone); f.Match(*z) {\n\t\t\tout = append(out, *z)\n\t\t}\n\t})\n\treturn out[:len(out):len(out)]\n}\n\n// ZoneCount returns how many zones have that status (\"\" for all), without\n// reading any.\nfunc (r *Registry) ZoneCount(status Status) int {\n\tif status == \"\" {\n\t\treturn r.zones.len()\n\t}\n\treturn r.byStatus.Count(string(status))\n}\n\n// Live returns how many zones are pending or approved: what MaxZones bounds.\nfunc (r *Registry) Live() int {\n\treturn r.byStatus.Count(string(Pending)) + r.byStatus.Count(string(Approved))\n}\n\n// ZonePage returns page (1-based) of the zones with that status (\"\" for every\n// status), size per page, in proposal order. A page past the end is empty.\n//\n// It reads the zones ON the page only; the status's id list (one object, at\n// most MaxZones ids) is read whole and sliced.\nfunc (r *Registry) ZonePage(status Status, page, size int) []Zone {\n\tif status == \"\" {\n\t\tn := r.zones.len()\n\t\tif page \u003c 1 || size \u003c 1 || page-1 \u003e n/size {\n\t\t\treturn []Zone{}\n\t\t}\n\t\tif size \u003e n {\n\t\t\tsize = n\n\t\t}\n\t\tout := make([]Zone, 0, size)\n\t\t//gnovet:ignore page-offset-overflow bounded by page-1 \u003e n/size at the top\n\t\tr.zones.page((page-1)*size, size, func(v any) { out = append(out, *v.(*Zone)) })\n\t\treturn out\n\t}\n\tids := pageOf(r.byStatus.Lookup(string(status)), page, size)\n\tout := make([]Zone, 0, len(ids))\n\tfor _, id := range ids {\n\t\tv, _ := r.zones.get(id)\n\t\tout = append(out, *v.(*Zone))\n\t}\n\treturn out\n}\n\n// ApprovedByChainID returns the approved zones naming that chain id, in\n// proposal order. Usually one, but chain ids are not unique across networks\n// (every gnodev is \"dev\"), so it is a list. Only approved zones are indexed, so\n// proposals naming a real chain id cost a reader of this nothing.\nfunc (r *Registry) ApprovedByChainID(chainID string) []Zone {\n\tids := r.approved.Lookup(chainID)\n\tout := make([]Zone, 0, len(ids))\n\tfor _, id := range ids {\n\t\tv, _ := r.zones.get(id)\n\t\tout = append(out, *v.(*Zone))\n\t}\n\treturn out\n}\n\n// SoleApproved returns the approved zone naming that chain id when there is\n// exactly one, which is the only case a reader can be pointed at it without a\n// guess. It counts first and reads one record at most.\nfunc (r *Registry) SoleApproved(chainID string) (Zone, bool) {\n\tif r.approved.Count(chainID) != 1 {\n\t\treturn Zone{}, false\n\t}\n\tid, _ := r.approved.First(chainID)\n\tv, _ := r.zones.get(id)\n\treturn *v.(*Zone), true\n}\n\n// EndpointFilter selects endpoints. A zero field matches anything.\ntype EndpointFilter struct {\n\tZone       string\n\tKind       EndpointKind\n\tStatus     Verification\n\tRegistrant address\n}\n\n// Match reports whether e passes the filter.\nfunc (f EndpointFilter) Match(e Endpoint) bool {\n\treturn (f.Zone == \"\" || e.Zone == f.Zone) \u0026\u0026\n\t\t(f.Kind == \"\" || e.Kind == f.Kind) \u0026\u0026\n\t\t(f.Status == \"\" || e.Status == f.Status) \u0026\u0026\n\t\t(f.Registrant == \"\" || e.Registrant == f.Registrant)\n}\n\n// Endpoints returns copies of the endpoints passing f, oldest first. With a\n// zone set it reads that zone's ids only (that kind's, with a kind set), so it\n// costs at most MaxEndpointsPerZone records. Without one it reads every\n// endpoint in the registry: bound it yourself.\nfunc (r *Registry) Endpoints(f EndpointFilter) []Endpoint {\n\tif f.Zone != \"\" {\n\t\tvar ids []store.ID\n\t\tif f.Kind != \"\" {\n\t\t\tids = r.byKind.Lookup(kindKey(f.Zone, f.Kind))\n\t\t} else {\n\t\t\tids = r.byZone.Lookup(f.Zone)\n\t\t}\n\t\tout := make([]Endpoint, 0, len(ids))\n\t\tfor _, id := range ids {\n\t\t\tv, _ := r.endpoints.get(id)\n\t\t\tif e := v.(*Endpoint); f.Match(*e) {\n\t\t\t\tout = append(out, *e)\n\t\t\t}\n\t\t}\n\t\treturn out[:len(out):len(out)]\n\t}\n\tout := make([]Endpoint, 0, r.endpoints.len())\n\tr.endpoints.each(func(v any) {\n\t\tif e := v.(*Endpoint); f.Match(*e) {\n\t\t\tout = append(out, *e)\n\t\t}\n\t})\n\treturn out[:len(out):len(out)]\n}\n\n// Count returns how many endpoints a zone has, and how many of them are\n// verified, from the index counts: no endpoint is read.\nfunc (r *Registry) Count(slug string) (verified, total int) {\n\ttotal = r.byZone.Count(slug)\n\treturn total - r.unchecked.Count(slug), total\n}\n\n// EndpointCount returns how many endpoints of that kind a zone has; \"\" is\n// every kind. No endpoint is read.\nfunc (r *Registry) EndpointCount(slug string, kind EndpointKind) int {\n\tif kind == \"\" {\n\t\treturn r.byZone.Count(slug)\n\t}\n\treturn r.byKind.Count(kindKey(slug, kind))\n}\n\n// Awaiting returns how many of a zone's endpoints are waiting for a verdict,\n// what MaxUnverifiedPerZone gates. No endpoint is read.\nfunc (r *Registry) Awaiting(slug string) int {\n\treturn r.unchecked.Count(slug) - r.flagged.count(slug)\n}\n\n// Clearable returns how many of a zone's endpoints are Clearable, what a bulk\n// clear could remove. No endpoint is read.\nfunc (r *Registry) Clearable(slug string) int { return r.fresh.count(slug) }\n\n// OwnerCount returns how many endpoints that address registered on a zone. No\n// endpoint is read.\nfunc (r *Registry) OwnerCount(slug string, who address) int {\n\treturn r.byOwner.count(ownerKey(slug, who))\n}\n\n// EndpointPage returns page (1-based) of a zone's endpoints of that kind, \"\"\n// for every kind, size per page, oldest first. Like [Registry.ZonePage] it reads\n// the records on the page only, and the bucket's id list (at most\n// MaxEndpointsPerZone ids) whole.\nfunc (r *Registry) EndpointPage(slug string, kind EndpointKind, page, size int) []Endpoint {\n\tvar ids []store.ID\n\tif kind != \"\" {\n\t\tids = r.byKind.Lookup(kindKey(slug, kind))\n\t} else {\n\t\tids = r.byZone.Lookup(slug)\n\t}\n\tids = pageOf(ids, page, size)\n\tout := make([]Endpoint, 0, len(ids))\n\tfor _, id := range ids {\n\t\tv, _ := r.endpoints.get(id)\n\t\tout = append(out, *v.(*Endpoint))\n\t}\n\treturn out\n}\n\n// pageOf slices ids to one page, 1-based. Out of range is empty, never a\n// panic: page and size usually come from a reader's query string.\nfunc pageOf(ids []store.ID, page, size int) []store.ID {\n\t// The division comes first so a page number near MaxInt cannot overflow\n\t// the multiplication into a small positive offset.\n\tif page \u003c 1 || size \u003c 1 || page-1 \u003e len(ids)/size {\n\t\treturn nil\n\t}\n\t//gnovet:ignore page-offset-overflow bounded by page-1 \u003e len(ids)/size above\n\tstart := (page - 1) * size\n\tif start \u003e= len(ids) {\n\t\treturn nil\n\t}\n\tend := len(ids)\n\tif len(ids)-start \u003e size {\n\t\tend = start + size\n\t}\n\treturn ids[start:end]\n}\n\n// Len returns how many zones the registry holds, whatever their status.\nfunc (r *Registry) Len() int { return r.zones.len() }\n\nfunc (r *Registry) zone(slug string) (*Zone, store.ID, error) {\n\tid, ok := r.bySlug.get(slug)\n\tif !ok {\n\t\treturn nil, 0, errors.New(\"zones: no zone \" + strconv.Quote(slug))\n\t}\n\tv, _ := r.zones.get(id)\n\treturn v.(*Zone), id, nil\n}\n\nfunc (r *Registry) endpoint(id int64) (*Endpoint, error) {\n\tif id \u003c= 0 {\n\t\treturn nil, errors.New(\"zones: no endpoint #\" + strconv.FormatInt(id, 10))\n\t}\n\tv, ok := r.endpoints.get(store.ID(id))\n\tif !ok {\n\t\treturn nil, errors.New(\"zones: no endpoint #\" + strconv.FormatInt(id, 10))\n\t}\n\treturn v.(*Endpoint), nil\n}\n\n// addressKey is the dedup key: the zone, the kind, and a hash of the address\n// in [Canonical] form. Hashed so the address part of the key is 16 bytes\n// whatever the URL's length,\n// instead of a second copy of up to MaxURLLen bytes the record already holds,\n// and kept raw rather than hex: it is a key, never shown. Truncated to 128\n// bits, which no accidental collision reaches and which only lets a deliberate\n// one refuse its own registration. It is the last field, so a byte that happens\n// to be \"|\" cannot be mistaken for a separator.\nfunc addressKey(slug string, kind EndpointKind, addr string) string {\n\tsum := sha256.Sum256([]byte(Canonical(kind, addr)))\n\treturn slug + \"|\" + string(kind) + \"|\" + string(sum[:16])\n}\n\nfunc kindKey(slug string, kind EndpointKind) string { return slug + \"|\" + string(kind) }\n\nfunc ownerKey(slug string, who address) string { return slug + \"|\" + who.String() }\n\n// trimInfo normalizes what a caller typed before it is validated: spaces\n// around every field, and each URL's scheme and host lowercased in ASCII\n// (both are case-insensitive, gno's link sanitizer is not, so HTTPS:// would\n// render as a dead link), and a gnoweb or genesis URL's empty tail dropped\n// (trimEmptyTail), as an address bar writes it. Nothing else is rewritten:\n// what fails validation is refused, not repaired, and the main RPC with an\n// empty tail is refused.\nfunc trimInfo(in Info) Info {\n\tin.ChainID = TrimSpaces(in.ChainID)\n\tin.Title = TrimSpaces(in.Title)\n\tin.Description = TrimSpaces(in.Description)\n\tin.Kind = Kind(TrimSpaces(string(in.Kind)))\n\tin.GnowebURL = trimEmptyTail(lowerAuthority(TrimSpaces(in.GnowebURL)))\n\tin.RPCURL = lowerAuthority(TrimSpaces(in.RPCURL))\n\tin.GenesisURL = trimEmptyTail(lowerAuthority(TrimSpaces(in.GenesisURL)))\n\treturn in\n}\n\n// table is numbered records in a B+ tree: kit/store's shape (an\n// id that is never reused, keyed by its seqid encoding so the tree iterates in\n// id order) on a B+ tree, the keyed, ordered container EFFECTIVE_GNO.md\n// recommends for iteration and pagination. kit/store/v0 sits on an avl, which\n// it measured at 2,029 B per entry against a B+ tree's 592 to 671, and about\n// six times the gas per entry iterated, and on an immutable path that choice\n// is permanent.\ntype table struct {\n\ttree *bptree.BPTree\n\tlast uint64\n}\n\nfunc newTable() *table { return \u0026table{tree: bptree.NewBPTreeN(fanout)} }\n\nfunc (t *table) add(v any) store.ID {\n\tt.last++\n\tid := store.ID(t.last)\n\tt.tree.Set(id.Key(), v)\n\treturn id\n}\n\nfunc (t *table) get(id store.ID) (any, bool) {\n\tv := t.tree.Get(id.Key())\n\treturn v, v != nil\n}\n\nfunc (t *table) remove(id store.ID) (any, bool) { return t.tree.Remove(id.Key()) }\n\nfunc (t *table) len() int { return t.tree.Size() }\n\nfunc (t *table) each(fn func(v any)) {\n\tt.tree.IterateByOffset(0, t.tree.Size(), func(_ string, v any) bool {\n\t\tfn(v)\n\t\treturn false\n\t})\n}\n\nfunc (t *table) page(offset, count int, fn func(v any)) {\n\tt.tree.IterateByOffset(offset, count, func(_ string, v any) bool {\n\t\tfn(v)\n\t\treturn false\n\t})\n}\n\n// unique is a key -\u003e id map in a B+ tree that holds the id itself. kit/index\n// stores every key as three objects (a box, an entry struct, an ids array), and\n// for a key that only ever has one id two of them say nothing.\ntype unique struct{ tree *bptree.BPTree }\n\nfunc newUnique() *unique { return \u0026unique{tree: bptree.NewBPTreeN(fanout)} }\n\nfunc (u *unique) has(key string) bool { return u.tree.Has(key) }\n\nfunc (u *unique) get(key string) (store.ID, bool) {\n\tv := u.tree.Get(key)\n\tif v == nil {\n\t\treturn 0, false\n\t}\n\treturn v.(store.ID), true\n}\n\nfunc (u *unique) set(key string, id store.ID) { u.tree.Set(key, id) }\n\nfunc (u *unique) remove(key string) { u.tree.Remove(key) }\n\n// counter is a key -\u003e count map in a B+ tree, one object per key. What it\n// answers (pending proposals per proposer and endpoints per registrant per\n// zone for the caps, flagged endpoints per zone for the admission gate,\n// clearable endpoints per zone for the bulk clear) only\n// ever asks how many, so keeping the ids would be two more objects per key,\n// written and deleted for nothing.\ntype counter struct{ tree *bptree.BPTree }\n\nfunc newCounter() *counter { return \u0026counter{tree: bptree.NewBPTreeN(fanout)} }\n\nfunc (c *counter) count(key string) int {\n\tv := c.tree.Get(key)\n\tif v == nil {\n\t\treturn 0\n\t}\n\treturn v.(int)\n}\n\nfunc (c *counter) inc(key string) { c.tree.Set(key, c.count(key)+1) }\n\nfunc (c *counter) dec(key string) {\n\tif n := c.count(key) - 1; n \u003e 0 {\n\t\tc.tree.Set(key, n)\n\t} else {\n\t\tc.tree.Remove(key)\n\t}\n}\n\nfunc (c *counter) drop(key string) { c.tree.Remove(key) }\n"},{"name":"registry_test.gno","body":"package zones\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice   = testutils.TestAddress(\"alice\")\n\tbob     = testutils.TestAddress(\"bob\")\n\tcurator = testutils.TestAddress(\"curator\")\n\tcarol   = testutils.TestAddress(\"carol\")\n)\n\nfunc onyx() Info {\n\treturn Info{\n\t\tChainID:     \"onyx-1\",\n\t\tTitle:       \"Onyx\",\n\t\tDescription: \"The gno.land testnet.\",\n\t\tKind:        Testnet,\n\t\tGnowebURL:   \"https://onyx.testnets.gno.land\",\n\t\tRPCURL:      \"https://rpc.onyx.testnets.gno.land\",\n\t}\n}\n\nfunc TestProposeAndRead(t *testing.T) {\n\tr := NewRegistry()\n\tin := onyx()\n\tin.Title = \"  Onyx  \"\n\tuassert.NoError(t, r.Propose(alice, 10, \"onyx\", in))\n\n\tz, ok := r.Zone(\"onyx\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"Onyx\", z.Title) // trimmed\n\tuassert.Equal(t, string(Pending), string(z.Status))\n\tuassert.Equal(t, alice.String(), z.Proposer.String())\n\tuassert.Equal(t, int64(10), z.ProposedAt)\n\tuassert.True(t, !z.Reviewed())\n\n\t_, ok = r.Zone(\"nope\")\n\tuassert.False(t, ok)\n\n\tuassert.ErrorContains(t, r.Propose(bob, 11, \"onyx\", onyx()), \"is taken\")\n\tuassert.ErrorContains(t, r.Propose(bob, 11, \"On yx\", onyx()), \"slug\")\n\tuassert.ErrorContains(t, r.Propose(\"\", 11, \"other\", onyx()), \"proposer is not a valid lowercase address\")\n\tuassert.Equal(t, 1, r.Len())\n}\n\nfunc TestZoneCopiesAreCopies(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tz, _ := r.Zone(\"onyx\")\n\tz.Title = \"mutated\"\n\tz.Status = Approved\n\tagain, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, \"Onyx\", again.Title)\n\tuassert.Equal(t, string(Pending), string(again.Status))\n}\n\nfunc TestPendingCapPerProposer(t *testing.T) {\n\tr := NewRegistry()\n\tfor i := 0; i \u003c MaxPendingPerProposer; i++ {\n\t\tuassert.NoError(t, r.Propose(alice, 1, \"z\"+strconv.Itoa(i), onyx()))\n\t}\n\tuassert.ErrorContains(t, r.Propose(alice, 1, \"one-more\", onyx()), \"pending proposals, the limit is\")\n\t// Somebody else is not blocked by alice's spam.\n\tuassert.NoError(t, r.Propose(bob, 1, \"bobs\", onyx()))\n\t// A reviewed proposal frees the slot.\n\tuassert.NoError(t, r.ReviewZone(\"z0\", Approved, rev(r, \"z0\"), curator, 2, \"\"))\n\tuassert.NoError(t, r.Propose(alice, 3, \"one-more\", onyx()))\n\t// So does a removed one.\n\tuassert.NoError(t, r.RemoveZone(\"z1\", rev(r, \"z1\")))\n\tuassert.NoError(t, r.Propose(alice, 3, \"and-another\", onyx()))\n}\n\nfunc TestReviewTransitions(t *testing.T) {\n\tcases := []struct {\n\t\tfrom   Status\n\t\tto     Status\n\t\treason string\n\t\terr    string\n\t}{\n\t\t{Pending, Approved, \"\", \"\"},\n\t\t{Pending, Rejected, \"duplicate of onyx\", \"\"},\n\t\t{Pending, Rejected, \"\", \"needs a reason\"},\n\t\t{Pending, Rejected, \"\\u200b\", \"invisible or bidi\"},\n\t\t{Approved, Retired, \"\\u2066\\u2069\", \"invisible or bidi\"},\n\t\t{Pending, Retired, \"gone\", \"only an approved zone can be retired\"},\n\t\t{Pending, Pending, \"\", \"already pending\"},\n\t\t{Approved, Retired, \"the RPC stopped resolving\", \"\"},\n\t\t{Approved, Retired, \"  \", \"needs a reason\"},\n\t\t{Approved, Rejected, \"x\", \"retire it instead\"},\n\t\t{Approved, Approved, \"\", \"already approved\"},\n\t\t{Rejected, Approved, \"reconsidered\", \"\"},\n\t\t{Rejected, Retired, \"x\", \"only an approved zone\"},\n\t\t{Retired, Approved, \"it came back\", \"\"},\n\t\t{Retired, Rejected, \"x\", \"only a pending zone can be rejected\"},\n\t\t{Pending, \"official\", \"\", \"cannot set a zone\"},\n\t}\n\tfor _, c := range cases {\n\t\tr := NewRegistry()\n\t\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\t\t// Walk the zone to the starting state.\n\t\tswitch c.from {\n\t\tcase Approved:\n\t\t\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 2, \"\"))\n\t\tcase Rejected:\n\t\t\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), curator, 2, \"setup\"))\n\t\tcase Retired:\n\t\t\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 2, \"\"))\n\t\t\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 3, \"setup\"))\n\t\t}\n\t\tlabel := string(c.from) + \" -\u003e \" + string(c.to)\n\t\terr := r.ReviewZone(\"onyx\", c.to, rev(r, \"onyx\"), curator, 9, c.reason)\n\t\tz, _ := r.Zone(\"onyx\")\n\t\tif c.err != \"\" {\n\t\t\tuassert.ErrorContains(t, err, c.err, label)\n\t\t\tuassert.Equal(t, string(c.from), string(z.Status), label)\n\t\t\tcontinue\n\t\t}\n\t\tuassert.NoError(t, err, label)\n\t\tuassert.Equal(t, string(c.to), string(z.Status), label)\n\t\tuassert.Equal(t, curator.String(), z.ReviewedBy.String(), label)\n\t\tuassert.Equal(t, int64(9), z.ReviewedAt, label)\n\t\tuassert.Equal(t, c.reason, z.Reason, label)\n\t}\n}\n\nfunc TestEdit(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tin := onyx()\n\tin.GenesisURL = \"https://github.com/gnolang/gno/releases/download/chain/onyx/genesis.json\"\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, \"\", 2, \"\"), \"editor is not a valid lowercase address\")\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, alice, 2, \"\"))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, in.GenesisURL, z.GenesisURL)\n\tuassert.False(t, z.Reviewed()) // pending: just an edit\n\n\tbad := in\n\tbad.RPCURL = \"\"\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), bad, alice, 2, \"\"), \"rpc url is empty\")\n\tuassert.ErrorContains(t, r.Edit(\"nope\", rev(r, \"nope\"), in, alice, 2, \"\"), \"no zone\")\n\tz, _ = r.Zone(\"onyx\")\n\tuassert.Equal(t, \"https://rpc.onyx.testnets.gno.land\", z.RPCURL) // unchanged by the refused edit\n\n\t// Once reviewed, an edit is a decision: it needs a reason and an editor, and\n\t// it replaces the review on record.\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 3, \"probed\"))\n\tin.RPCURL = \"https://rpc2.onyx.example.com\"\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, curator, 4, \"\"), \"an edit needs a reason\")\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, \"\", 4, \"moved\"), \"editor is not a valid lowercase address\")\n\tz, _ = r.Zone(\"onyx\")\n\tuassert.Equal(t, \"https://rpc.onyx.testnets.gno.land\", z.RPCURL)\n\tuassert.Equal(t, \"probed\", z.Reason)\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, bob, 5, \"rpc moved\"))\n\tz, _ = r.Zone(\"onyx\")\n\tuassert.Equal(t, \"https://rpc2.onyx.example.com\", z.RPCURL)\n\tuassert.Equal(t, bob.String(), z.ReviewedBy.String())\n\tuassert.Equal(t, int64(5), z.ReviewedAt)\n\tuassert.Equal(t, \"rpc moved\", z.Reason)\n\tuassert.Equal(t, string(Approved), string(z.Status))\n\n\t// A retired zone is a record: its retirement reason is not editable away.\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 6, \"testnet ended\"))\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, curator, 7, \"typo\"), \"only a pending or approved zone can be edited\")\n\tz, _ = r.Zone(\"onyx\")\n\tuassert.Equal(t, \"testnet ended\", z.Reason)\n\t// Nor is a rejected one.\n\tuassert.NoError(t, r.Propose(alice, 8, \"nope\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"nope\", Rejected, rev(r, \"nope\"), curator, 9, \"dup\"))\n\tuassert.ErrorContains(t, r.Edit(\"nope\", rev(r, \"nope\"), onyx(), alice, 10, \"\"), \"only a pending or approved zone can be edited\")\n}\n\n// What was verified is that an endpoint answered for the zone's chain id, so\n// changing the chain id un-verifies them; changing only the RPC does not.\nfunc TestChainIDEditUnverifiesEndpoints(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(curator, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 1, \"\"))\n\ta, _ := r.Register(alice, 2, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tb, _ := r.Register(alice, 2, \"onyx\", Peer, nodeID+\"@b.example.com:26656\", \"\")\n\tf, _ := r.Register(alice, 2, \"onyx\", RPC, \"https://f.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(a, Verified, zr(r, a), erev(r, a), curator, 3, \"\"))\n\tuassert.NoError(t, r.ReviewEndpoint(b, Verified, zr(r, b), erev(r, b), curator, 3, \"\"))\n\tuassert.NoError(t, r.ReviewEndpoint(f, Flagged, zr(r, f), erev(r, f), curator, 3, \"down\"))\n\n\tin := onyx()\n\tin.RPCURL = \"https://rpc2.onyx.example.com\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, curator, 4, \"rpc moved\"))\n\tuassert.Equal(t, 2, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified})))\n\n\tin.ChainID = \"onyx-2\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, curator, 5, \"relaunched as onyx-2\"))\n\tuassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified})))\n\te, _ := r.Endpoint(a)\n\tuassert.Equal(t, string(Unverified), string(e.Status))\n\tuassert.Equal(t, ChainIDChanged, e.Reason)\n\tuassert.Equal(t, int64(5), e.ReviewedAt)\n\te, _ = r.Endpoint(f)\n\tuassert.Equal(t, string(Flagged), string(e.Status)) // a flag is not undone by an edit\n\tuassert.Equal(t, \"down\", e.Reason)\n\t// And the reset ones count against the review queue again (the flagged\n\t// one has its verdict and stays out): verifying one frees it.\n\tv, _ := r.Count(\"onyx\")\n\tuassert.Equal(t, 0, v)\n\tuassert.Equal(t, 2, r.Awaiting(\"onyx\"), \"both reset endpoints are back in the queue\")\n\tuassert.NoError(t, r.ReviewEndpoint(a, Verified, zr(r, a), erev(r, a), curator, 6, \"answers onyx-2\"))\n\tuassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified})))\n\tv, _ = r.Count(\"onyx\")\n\tuassert.Equal(t, 1, v)\n\n\t// Retiring resets what was verified, at the moment the network stops: a\n\t// retired network's hosts may be somebody else's by the time anyone reads\n\t// them. Approving it again does not restore anything.\n\tuassert.NoError(t, r.ReviewEndpoint(b, Verified, zr(r, b), erev(r, b), curator, 6, \"\"))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 6, \"stopped\"))\n\tuassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified})))\n\te, _ = r.Endpoint(b)\n\tuassert.Equal(t, ZoneRetired, e.Reason)\n\tuassert.Equal(t, curator.String(), e.ReviewedBy.String())\n\tuassert.ErrorContains(t, r.ReviewEndpoint(b, Verified, zr(r, b), erev(r, b), curator, 6, \"\"), \"nothing on it can be verified\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 7, \"back up\"))\n\tuassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified})))\n\te, _ = r.Endpoint(f)\n\tuassert.Equal(t, string(Flagged), string(e.Status))\n\t// A pending zone is no exception: a proposer collecting verdicts for one\n\t// chain id and then switching it gets them all reset.\n\tuassert.NoError(t, r.Propose(alice, 7, \"pend\", onyx()))\n\tpid, _ := r.Register(alice, 7, \"pend\", RPC, \"https://p.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(pid, Verified, zr(r, pid), erev(r, pid), curator, 8, \"\"))\n\tother := onyx()\n\tother.ChainID = \"elsewhere-1\"\n\tuassert.NoError(t, r.Edit(\"pend\", rev(r, \"pend\"), other, alice, 9, \"\"))\n\te, _ = r.Endpoint(pid)\n\tuassert.Equal(t, string(Unverified), string(e.Status))\n\t// The proposer's own edit caused the reset, and the proposer is not a\n\t// reviewer, so none is recorded, and the reason says why.\n\tuassert.Equal(t, \"\", e.ReviewedBy.String())\n\tuassert.Equal(t, ChainIDChanged, e.Reason)\n\tz, _ := r.Zone(\"pend\")\n\tuassert.False(t, z.Reviewed()) // still a pending edit: the zone's own review is untouched\n}\n\nfunc TestRegisterAndFilter(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(curator, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 1, \"\"))\n\n\trpc, err := r.Register(alice, 5, \"onyx\", RPC, \" https://rpc.onyx.testnets.gno.land \", \"gno core\")\n\tuassert.NoError(t, err)\n\tpeer, err := r.Register(bob, 6, \"onyx\", Peer, nodeID+\"@seed-1.onyx.testnets.gno.land:26656\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.True(t, rpc \u003e 0 \u0026\u0026 peer \u003e rpc)\n\n\te, ok := r.Endpoint(rpc)\n\tuassert.True(t, ok)\n\tuassert.Equal(t, rpc, e.ID)\n\tuassert.Equal(t, \"https://rpc.onyx.testnets.gno.land\", e.Address) // trimmed\n\tuassert.Equal(t, string(Unverified), string(e.Status))\n\tuassert.Equal(t, alice.String(), e.Registrant.String())\n\n\t// Dedup is case-insensitive: the same host under another spelling.\n\t_, err = r.Register(bob, 7, \"onyx\", RPC, \"https://RPC.onyx.testnets.gno.land\", \"\")\n\tuassert.ErrorContains(t, err, \"already lists that rpc\")\n\t// ...but a path is case-sensitive, so another path is another endpoint.\n\t_, err = r.Register(bob, 7, \"onyx\", Indexer, \"https://indexer.example.com/API\", \"\")\n\tuassert.NoError(t, err)\n\t_, err = r.Register(bob, 7, \"onyx\", Indexer, \"https://INDEXER.example.com/API\", \"\")\n\tuassert.ErrorContains(t, err, \"already lists that indexer\")\n\t_, err = r.Register(bob, 7, \"onyx\", Indexer, \"https://indexer.example.com/api\", \"\")\n\tuassert.NoError(t, err)\n\t// The same address under another kind is a different endpoint.\n\t_, err = r.Register(bob, 7, \"onyx\", Gnoweb, \"https://rpc.onyx.testnets.gno.land\", \"\")\n\tuassert.NoError(t, err)\n\n\t_, err = r.Register(bob, 7, \"nope\", RPC, \"https://x.y\", \"\")\n\tuassert.ErrorContains(t, err, \"no zone\")\n\t_, err = r.Register(bob, 7, \"onyx\", Peer, \"https://x.y\", \"\")\n\tuassert.ErrorContains(t, err, \"\u003cnode id\u003e@\")\n\t_, err = r.Register(bob, 7, \"onyx\", RPC, \"https://x.y\", \"two\\nlines\")\n\tuassert.ErrorContains(t, err, \"control character\")\n\n\tuassert.Equal(t, 5, len(r.Endpoints(EndpointFilter{Zone: \"onyx\"})))\n\tuassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Kind: Peer})))\n\tuassert.Equal(t, 4, len(r.Endpoints(EndpointFilter{Registrant: bob})))\n\tuassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified})))\n\n\tuassert.NoError(t, r.ReviewEndpoint(rpc, Verified, zr(r, rpc), erev(r, rpc), curator, 8, \"answers onyx-1\"))\n\tvs := r.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified})\n\tuassert.Equal(t, 1, len(vs))\n\tuassert.Equal(t, \"answers onyx-1\", vs[0].Reason)\n\tv, total := r.Count(\"onyx\")\n\tuassert.Equal(t, 1, v)\n\tuassert.Equal(t, 5, total)\n\n\tuassert.ErrorContains(t, r.ReviewEndpoint(rpc, Verified, zr(r, rpc), erev(r, rpc), curator, 8, \"answers onyx-1\"), \"already verified\")\n\tuassert.ErrorContains(t, r.ReviewEndpoint(peer, Flagged, zr(r, peer), erev(r, peer), curator, 8, \"\"), \"needs a reason\")\n\tuassert.ErrorContains(t, r.ReviewEndpoint(peer, \"trusted\", zr(r, peer), erev(r, peer), curator, 8, \"\"), \"unknown verification\")\n\tuassert.ErrorContains(t, r.ReviewEndpoint(peer, \"\", zr(r, peer), erev(r, peer), curator, 8, \"\"), \"needs a verdict\")\n\tuassert.ErrorContains(t, r.ReviewEndpoint(peer, \" verified \", zr(r, peer), erev(r, peer), curator, 8, \"\"), \"unknown verification\")\n\t_, err = r.Register(bob, 7, \"onyx\", \" rpc \", \"not a url\", \"\")\n\tuassert.ErrorContains(t, err, \"unknown endpoint kind\")\n\t// A scheme's case is not a different endpoint.\n\t_, err = r.Register(bob, 7, \"onyx\", Explorer, \"HTTPS://Explorer.example.com/x\", \"\")\n\tuassert.NoError(t, err)\n\t_, err = r.Register(bob, 7, \"onyx\", Explorer, \"https://explorer.example.com/x\", \"\")\n\tuassert.ErrorContains(t, err, \"already lists that explorer\")\n\tuassert.ErrorContains(t, r.ReviewEndpoint(999, Verified, zr(r, 999), erev(r, 999), curator, 8, \"\"), \"no endpoint #999\")\n\tuassert.ErrorContains(t, r.ReviewEndpoint(0, Verified, zr(r, 0), erev(r, 0), curator, 8, \"\"), \"no endpoint #0\")\n\tuassert.NoError(t, r.ReviewEndpoint(peer, Flagged, zr(r, peer), erev(r, peer), curator, 9, \"wrong chain id\"))\n\tuassert.NoError(t, r.ReviewEndpoint(peer, Unverified, zr(r, peer), erev(r, peer), curator, 10, \"fixed, re-checking\"))\n\n\t// Removing frees the dedup key, so the same address can come back.\n\tuassert.NoError(t, r.RemoveEndpoint(rpc, erev(r, rpc)))\n\t_, ok = r.Endpoint(rpc)\n\tuassert.False(t, ok)\n\tuassert.ErrorContains(t, r.RemoveEndpoint(rpc, erev(r, rpc)), \"no endpoint\")\n\t_, err = r.Register(bob, 11, \"onyx\", RPC, \"https://rpc.onyx.testnets.gno.land\", \"\")\n\tuassert.NoError(t, err)\n}\n\nfunc TestRegisterNeedsALiveZone(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\t// Pending takes endpoints: a proposer fills in the peers before review.\n\t_, err := r.Register(alice, 2, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), curator, 3, \"not a gno chain\"))\n\t_, err = r.Register(alice, 4, \"onyx\", RPC, \"https://b.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"is rejected and takes no endpoints\")\n}\n\nfunc TestEndpointCapPerAddress(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tfor i := 0; i \u003c MaxEndpointsPerAddress; i++ {\n\t\t_, err := r.Register(alice, 2, \"onyx\", RPC, \"https://n\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tuassert.NoError(t, err)\n\t}\n\t_, err := r.Register(alice, 2, \"onyx\", RPC, \"https://over.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"the limit is\")\n\t// Bob still can.\n\t_, err = r.Register(bob, 2, \"onyx\", RPC, \"https://over.example.com\", \"\")\n\tuassert.NoError(t, err)\n}\n\nfunc TestRemoveZone(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\t_, err := r.Register(bob, 2, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 3, \"\"))\n\tuassert.ErrorContains(t, r.RemoveZone(\"onyx\", rev(r, \"onyx\")), \"retire it instead\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 4, \"testnet ended\"))\n\tuassert.ErrorContains(t, r.RemoveZone(\"onyx\", rev(r, \"onyx\")), \"kept on record\")\n\t_, ok := r.Zone(\"onyx\")\n\tuassert.True(t, ok)\n\n\t// A rejected zone is removable, endpoints and all.\n\tuassert.NoError(t, r.Propose(alice, 5, \"spam\", onyx()))\n\t_, err = r.Register(bob, 5, \"spam\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.ReviewZone(\"spam\", Rejected, rev(r, \"spam\"), curator, 6, \"not a network\"))\n\tuassert.NoError(t, r.RemoveZone(\"spam\", rev(r, \"spam\")))\n\t_, ok = r.Zone(\"spam\")\n\tuassert.False(t, ok)\n\tuassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: \"spam\"})))\n\tuassert.Equal(t, 1, r.Len())\n\tuassert.ErrorContains(t, r.RemoveZone(\"spam\", rev(r, \"spam\")), \"no zone\")\n\t// The slug and the address are free again.\n\tuassert.NoError(t, r.Propose(bob, 7, \"spam\", onyx()))\n\t_, err = r.Register(bob, 8, \"spam\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n}\n\nfunc TestReviewNeedsAReviewer(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), \"\", 2, \"\"), \"reviewer is not a valid lowercase address\")\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, string(Pending), string(z.Status))\n\tid, err := r.Register(alice, 2, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), \"\", 3, \"\"), \"reviewer is not a valid lowercase address\")\n}\n\n// A flood from many addresses fills the review queue and nothing above it.\nfunc TestFloodCannotCrowdOutReviewedEntries(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(curator, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 1, \"\"))\n\tfor i := 0; i \u003c MaxPending; i++ {\n\t\tuassert.NoError(t, r.Propose(testAddr(i), 2, \"flood-\"+strconv.Itoa(i), onyx()))\n\t}\n\tuassert.ErrorContains(t, r.Propose(bob, 3, \"honest\", onyx()), \"waiting for review\")\n\tuassert.Equal(t, MaxPending+1, r.Len())\n\t// Clearing one makes room.\n\tuassert.NoError(t, r.ReviewZone(\"flood-0\", Rejected, rev(r, \"flood-0\"), curator, 4, \"spam\"))\n\tuassert.NoError(t, r.Propose(bob, 5, \"honest\", onyx()))\n\n\t// Endpoints: those waiting for a verdict have their own gate, and verifying frees it.\n\tids := []int64{}\n\tfor i := 0; i \u003c MaxUnverifiedPerZone; i++ {\n\t\tid, err := r.Register(testAddr(i/MaxEndpointsPerAddress), 6, \"onyx\", RPC, \"https://n\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tuassert.NoError(t, err)\n\t\tids = append(ids, id)\n\t}\n\t_, err := r.Register(bob, 7, \"onyx\", RPC, \"https://honest.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"waiting for review\")\n\tuassert.NoError(t, r.ReviewEndpoint(ids[0], Verified, zr(r, ids[0]), erev(r, ids[0]), curator, 8, \"\"))\n\t_, err = r.Register(bob, 9, \"onyx\", RPC, \"https://honest.example.com\", \"\")\n\tuassert.NoError(t, err)\n\t// The gate is full again (the honest one is waiting). A flag is a verdict,\n\t// so a flagged endpoint leaves the queue: curators keep the warning and\n\t// still make room, instead of deleting the warning to make room.\n\t_, err = r.Register(bob, 11, \"onyx\", RPC, \"https://honest2.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"waiting for review\")\n\tuassert.NoError(t, r.ReviewEndpoint(ids[1], Flagged, zr(r, ids[1]), erev(r, ids[1]), curator, 12, \"spam\"))\n\t_, err = r.Register(bob, 13, \"onyx\", RPC, \"https://honest2.example.com\", \"\")\n\tuassert.NoError(t, err)\n\t// Unflagging puts it back in the queue, and a review is never refused for\n\t// the queue being full, only a registration is.\n\tuassert.NoError(t, r.ReviewEndpoint(ids[1], Unverified, zr(r, ids[1]), erev(r, ids[1]), curator, 14, \"re-checking\"))\n\t_, err = r.Register(bob, 15, \"onyx\", RPC, \"https://honest3.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"waiting for review\")\n\tuassert.NoError(t, r.RemoveEndpoint(ids[2], erev(r, ids[2])))\n\tuassert.NoError(t, r.RemoveEndpoint(ids[3], erev(r, ids[3])))\n\t_, err = r.Register(bob, 16, \"onyx\", RPC, \"https://honest3.example.com\", \"\")\n\tuassert.NoError(t, err)\n}\n\nfunc testAddr(i int) address { return testutils.TestAddress(\"flood\" + strconv.Itoa(i)) }\n\nfunc TestZonesFilterAndOrder(t *testing.T) {\n\tr := NewRegistry()\n\tmainnet := onyx()\n\tmainnet.ChainID, mainnet.Kind = \"gnoland-1\", Mainnet\n\tuassert.NoError(t, r.Propose(curator, 1, \"mainnet\", mainnet))\n\tuassert.NoError(t, r.Propose(curator, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.Propose(alice, 2, \"alices\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"mainnet\", Approved, rev(r, \"mainnet\"), curator, 3, \"\"))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 3, \"\"))\n\n\tslugs := func(zs []Zone) string {\n\t\ts := \"\"\n\t\tfor _, z := range zs {\n\t\t\ts += z.Slug + \" \"\n\t\t}\n\t\treturn s\n\t}\n\tuassert.Equal(t, \"mainnet onyx alices \", slugs(r.Zones(ZoneFilter{})))\n\tuassert.Equal(t, \"mainnet onyx \", slugs(r.Zones(ZoneFilter{Status: Approved})))\n\tuassert.Equal(t, \"alices \", slugs(r.Zones(ZoneFilter{Status: Pending})))\n\tuassert.Equal(t, \"onyx alices \", slugs(r.Zones(ZoneFilter{Kind: Testnet})))\n\tuassert.Equal(t, \"onyx \", slugs(r.Zones(ZoneFilter{Status: Approved, Kind: Testnet})))\n\tuassert.Equal(t, \"\", slugs(r.Zones(ZoneFilter{Kind: Local})))\n}\n\nfunc TestPagesAndCounts(t *testing.T) {\n\tr := NewRegistry()\n\tfor i := 0; i \u003c 7; i++ {\n\t\tuassert.NoError(t, r.Propose(testAddr(i), 1, \"z\"+strconv.Itoa(i), onyx()))\n\t}\n\tuassert.NoError(t, r.ReviewZone(\"z1\", Approved, rev(r, \"z1\"), curator, 2, \"\"))\n\tuassert.NoError(t, r.ReviewZone(\"z3\", Approved, rev(r, \"z3\"), curator, 2, \"\"))\n\tuassert.NoError(t, r.ReviewZone(\"z5\", Approved, rev(r, \"z5\"), curator, 2, \"\"))\n\tuassert.Equal(t, 3, r.ZoneCount(Approved))\n\tuassert.Equal(t, 4, r.ZoneCount(Pending))\n\tuassert.Equal(t, 7, r.ZoneCount(\"\"))\n\n\tpage := func(zs []Zone) string {\n\t\tout := \"\"\n\t\tfor _, z := range zs {\n\t\t\tout += z.Slug + \" \"\n\t\t}\n\t\treturn out\n\t}\n\tuassert.Equal(t, \"z1 z3 \", page(r.ZonePage(Approved, 1, 2)))\n\tuassert.Equal(t, \"z5 \", page(r.ZonePage(Approved, 2, 2)))\n\tuassert.Equal(t, \"\", page(r.ZonePage(Approved, 3, 2)))\n\tuassert.Equal(t, \"\", page(r.ZonePage(Approved, 0, 2)))\n\tuassert.Equal(t, \"\", page(r.ZonePage(Approved, 1, 0)))\n\tuassert.Equal(t, \"\", page(r.ZonePage(Approved, 1\u003c\u003c62, 1\u003c\u003c10)), \"no overflow into a small offset\")\n\tuassert.Equal(t, \"z0 z2 z4 z6 \", page(r.ZonePage(Pending, 1, 10)))\n\t// \"\" is every status, consistent with ZoneCount(\"\") and ZoneFilter{}.\n\tuassert.Equal(t, \"z0 z1 z2 \", page(r.ZonePage(\"\", 1, 3)))\n\tuassert.Equal(t, \"z6 \", page(r.ZonePage(\"\", 3, 3)))\n\tuassert.Equal(t, \"\", page(r.ZonePage(\"\", 4, 3)))\n\tuassert.Equal(t, \"\", page(r.ZonePage(\"\", 0, 3)))\n\tuassert.Equal(t, \"\", page(r.ZonePage(\"\", 1\u003c\u003c62, 1\u003c\u003c10)), \"no overflow into a small offset\")\n\tuassert.Equal(t, \"z0 z1 z2 z3 z4 z5 z6 \", page(r.ZonePage(\"\", 1, 1\u003c\u003c40)))\n\t// The status index follows a review and a removal.\n\tuassert.NoError(t, r.ReviewZone(\"z0\", Rejected, rev(r, \"z0\"), curator, 3, \"dup\"))\n\tuassert.NoError(t, r.RemoveZone(\"z2\", rev(r, \"z2\")))\n\tuassert.Equal(t, \"z4 z6 \", page(r.ZonePage(Pending, 1, 10)))\n\tuassert.Equal(t, \"z0 \", page(r.ZonePage(Rejected, 1, 10)))\n\tuassert.Equal(t, \"z1 z3 z5 \", page(r.Zones(ZoneFilter{Status: Approved})))\n\n\t// Chain ids are not unique, only approved zones are indexed by one (so a\n\t// proposal naming a real chain id costs a reader nothing), and the index\n\t// follows an edit and a retirement.\n\tuassert.Equal(t, \"z1 z3 z5 \", page(r.ApprovedByChainID(\"onyx-1\")))\n\tin := onyx()\n\tin.ChainID = \"onyx-2\"\n\tuassert.NoError(t, r.Edit(\"z1\", rev(r, \"z1\"), in, curator, 4, \"relaunched\"))\n\tuassert.Equal(t, \"z1 \", page(r.ApprovedByChainID(\"onyx-2\")))\n\tuassert.Equal(t, \"z3 z5 \", page(r.ApprovedByChainID(\"onyx-1\")))\n\tuassert.NoError(t, r.Edit(\"z4\", rev(r, \"z4\"), in, alice, 4, \"\")) // pending: not indexed\n\tuassert.Equal(t, \"z1 \", page(r.ApprovedByChainID(\"onyx-2\")))\n\tuassert.NoError(t, r.ReviewZone(\"z5\", Retired, rev(r, \"z5\"), curator, 4, \"gone\"))\n\tuassert.Equal(t, \"z3 \", page(r.ApprovedByChainID(\"onyx-1\")))\n\n\t// Endpoints: counts from the indexes, pages by kind.\n\tfor i := 0; i \u003c 5; i++ {\n\t\t_, err := r.Register(alice, 5, \"z3\", RPC, \"https://e\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tuassert.NoError(t, err)\n\t}\n\tpid, err := r.Register(alice, 5, \"z3\", Peer, nodeID+\"@p.example.com:26656\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.ReviewEndpoint(pid, Verified, zr(r, pid), erev(r, pid), curator, 6, \"\"))\n\tv, total := r.Count(\"z3\")\n\tuassert.Equal(t, 1, v)\n\tuassert.Equal(t, 6, total)\n\tuassert.Equal(t, 5, r.EndpointCount(\"z3\", RPC))\n\tuassert.Equal(t, 1, r.EndpointCount(\"z3\", Peer))\n\tuassert.Equal(t, 0, r.EndpointCount(\"z3\", Faucet))\n\tuassert.Equal(t, 6, r.EndpointCount(\"z3\", \"\"))\n\tuassert.Equal(t, 1, len(r.EndpointPage(\"z3\", RPC, 3, 2))) // page 3 of 5 rpcs at 2 a page holds one\n\tuassert.Equal(t, \"https://e4.example.com\", r.EndpointPage(\"z3\", RPC, 3, 2)[0].Address)\n\tuassert.Equal(t, nodeID+\"@p.example.com:26656\", r.EndpointPage(\"z3\", Peer, 1, 10)[0].Address)\n\tuassert.Equal(t, 6, len(r.EndpointPage(\"z3\", \"\", 1, 10)))\n\tuassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: \"z3\", Kind: Peer})))\n\tuassert.NoError(t, r.RemoveEndpoint(pid, erev(r, pid)))\n\tuassert.Equal(t, 0, r.EndpointCount(\"z3\", Peer))\n\tv, total = r.Count(\"z3\")\n\tuassert.Equal(t, 0, v)\n\tuassert.Equal(t, 5, total)\n}\n\n// rev is a zone's current revision, what a curator who just read it approves.\nfunc rev(r *Registry, slug string) int64 {\n\tz, _ := r.Zone(slug)\n\treturn z.Revision\n}\n\n// erev is an endpoint's revision, what a verdict or a removal names.\nfunc erev(r *Registry, id int64) int64 {\n\te, ok := r.Endpoint(id)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn e.Revision\n}\n\n// zr is the revision of an endpoint's zone, what a verification also names.\nfunc zr(r *Registry, id int64) int64 {\n\te, ok := r.Endpoint(id)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn rev(r, e.Zone)\n}\n\n// An approval names the revision the curator read. An edit landing between the\n// reading and the approval makes the approval fail, rather than making text the\n// curator never saw official under their name. Remove-and-propose-again cannot\n// reuse a revision either.\nfunc TestApprovalBindsToRevision(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tread := rev(r, \"onyx\")\n\n\tswapped := onyx()\n\tswapped.RPCURL = \"https://attacker.example.com\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), swapped, alice, 2, \"\"))\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Approved, read, curator, 3, \"\"), \"changed since you read it\")\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, string(Pending), string(z.Status))\n\tuassert.Equal(t, alice.String(), z.EditedBy.String())\n\tuassert.Equal(t, int64(2), z.EditedAt)\n\n\t// Removed and proposed again under the same slug: a new revision, never the old one.\n\tuassert.NoError(t, r.RemoveZone(\"onyx\", rev(r, \"onyx\")))\n\tuassert.NoError(t, r.Propose(alice, 4, \"onyx\", onyx()))\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Approved, read, curator, 5, \"\"), \"changed since you read it\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 5, \"\"))\n\n\t// Verifying an endpoint binds the same way: to the chain id it was checked against.\n\tid, err := r.Register(alice, 6, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tchecked := zr(r, id)\n\tmoved := onyx()\n\tmoved.ChainID = \"onyx-2\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), moved, curator, 7, \"relaunch\"))\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, checked, erev(r, id), curator, 8, \"\"), \"changed since you checked it against it\")\n\t// A revision from the future is as wrong as a past one.\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id)+1, erev(r, id), curator, 8, \"\"), \"changed since\")\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id)+1, curator, 8, \"\"), \"changed since\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 8, \"\"))\n\t// Every verdict binds to the endpoint as read, too: a verify written before\n\t// another curator's flag fails rather than silently reversing it.\n\tread = erev(r, id)\n\tuassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), read, curator, 9, \"down\"))\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Unverified, zr(r, id), read, alice, 10, \"\"), \"changed since you checked it\")\n\t// The same verdict again, with a new reason, restates it.\n\tuassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 11, \"down since block 9\"))\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 12, \"down since block 9\"), \"restating it needs a new reason\")\n}\n\nfunc TestPendingEditTakesNoReason(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), onyx(), alice, 2, \"fixed a typo\"), \"takes no reason\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 3, \"\"))\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), onyx(), curator, 4, \"\\u200b\"), \"invisible\")\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), onyx(), curator, 4, \"\"), \"needs a reason\")\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), onyx(), curator, 4, \"no change\"), \"changes nothing\")\n\tin := onyx()\n\tin.Title = \"Onyx testnet\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), in, curator, 4, \"retitled\"))\n}\n\n// Rejected and retired zones are kept for the record, each up to a cap of its\n// own, and neither counts against the live registry: nothing a proposer or a\n// curator does, and no amount of time, fills it for good.\nfunc TestRecordsNeverFillTheRegistry(t *testing.T) {\n\tr := NewRegistry()\n\tfor i := 0; i \u003c MaxRejected+3; i++ {\n\t\tslug := \"rej\" + strconv.Itoa(i)\n\t\tuassert.NoError(t, r.Propose(testAddr(i), 1, slug, onyx()))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Rejected, rev(r, slug), curator, 2, \"spam\"))\n\t}\n\tuassert.Equal(t, MaxRejected, r.ZoneCount(Rejected))\n\t// The three that entered the rejected state first made room.\n\t_, ok := r.Zone(\"rej0\")\n\tuassert.False(t, ok)\n\t_, ok = r.Zone(\"rej3\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 0, r.Live())\n\n\tfor i := 0; i \u003c MaxRetired+2; i++ {\n\t\tslug := \"ret\" + strconv.Itoa(i)\n\t\tuassert.NoError(t, r.Propose(curator, 3, slug, onyx()))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 3, \"\"))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Retired, rev(r, slug), curator, 4, \"stopped\"))\n\t}\n\tuassert.Equal(t, MaxRetired, r.ZoneCount(Retired))\n\t_, ok = r.Zone(\"ret0\")\n\tuassert.False(t, ok)\n\tuassert.Equal(t, 0, r.Live())\n\tuassert.Equal(t, MaxRejected+MaxRetired, r.Len())\n\n\t// The live registry is untouched by all of it.\n\tuassert.NoError(t, r.Propose(bob, 5, \"honest\", onyx()))\n\tuassert.Equal(t, 1, r.Live())\n}\n\n// An evicted zone takes its endpoints and every index entry with it, so its\n// slug and its addresses can be used again.\nfunc TestEvictionUnwindsEverything(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"first\", onyx()))\n\t_, err := r.Register(alice, 1, \"first\", RPC, \"https://f.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tfl, err := r.Register(alice, 1, \"first\", RPC, \"https://flagged.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.ReviewEndpoint(fl, Flagged, zr(r, fl), erev(r, fl), curator, 1, \"spam\"))\n\tuassert.NoError(t, r.ReviewZone(\"first\", Rejected, rev(r, \"first\"), curator, 2, \"dup\"))\n\tfor i := 0; i \u003c MaxRejected; i++ {\n\t\tslug := \"rej\" + strconv.Itoa(i)\n\t\tuassert.NoError(t, r.Propose(testAddr(i), 3, slug, onyx()))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Rejected, rev(r, slug), curator, 4, \"spam\"))\n\t}\n\t_, ok := r.Zone(\"first\")\n\tuassert.False(t, ok)\n\t_, total := r.Count(\"first\")\n\tuassert.Equal(t, 0, total)\n\tuassert.Equal(t, 0, r.OwnerCount(\"first\", alice))\n\tuassert.Equal(t, 0, r.EndpointCount(\"first\", RPC))\n\tuassert.NoError(t, r.Propose(alice, 5, \"first\", onyx()))\n\t// Neither the review queue nor the flag count of the evicted zone carries\n\t// over to the slug proposed again.\n\tuassert.Equal(t, 0, r.Awaiting(\"first\"))\n\t_, err = r.Register(alice, 5, \"first\", RPC, \"https://f.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 1, r.Awaiting(\"first\"))\n}\n\n// Approving a rejected or retired zone back into the live registry respects\n// its cap.\nfunc TestReviveRespectsTheLiveCap(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"back\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"back\", Rejected, rev(r, \"back\"), curator, 1, \"not yet\"))\n\tfor i := 0; i \u003c MaxZones; i++ {\n\t\tslug := \"z\" + strconv.Itoa(i)\n\t\tuassert.NoError(t, r.ProposeExempt(curator, 2, slug, onyx()))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 2, \"\"))\n\t}\n\tuassert.Equal(t, MaxZones, r.Live())\n\tuassert.ErrorContains(t, r.ReviewZone(\"back\", Approved, rev(r, \"back\"), curator, 3, \"\"), \"full at\")\n\tuassert.ErrorContains(t, r.Propose(bob, 3, \"more\", onyx()), \"full at\")\n\tuassert.NoError(t, r.ReviewZone(\"z0\", Retired, rev(r, \"z0\"), curator, 3, \"stopped\"))\n\tuassert.NoError(t, r.ReviewZone(\"back\", Approved, rev(r, \"back\"), curator, 4, \"\"))\n}\n\nfunc TestUppercaseAddressesAreRefused(t *testing.T) {\n\tr := NewRegistry()\n\tupper := address(strings.ToUpper(alice.String()))\n\tuassert.True(t, upper.IsValid(), \"bech32 itself decodes the uppercase form\")\n\tuassert.False(t, ValidAddress(upper))\n\tuassert.ErrorContains(t, r.Propose(upper, 1, \"onyx\", onyx()), \"lowercase\")\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\t_, err := r.Register(upper, 1, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"lowercase\")\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), upper, 2, \"\"), \"lowercase\")\n}\n\n// A peer is stored lowercased whole, so the listed form is the one tm2 dials,\n// and two spellings of one host are one peer.\nfunc TestPeerStoredLowercase(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tid, err := r.Register(alice, 1, \"onyx\", Peer, nodeID+\"@SEED-1.Onyx.example.com:26656\", \"\")\n\tuassert.NoError(t, err)\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, nodeID+\"@seed-1.onyx.example.com:26656\", e.Address)\n\t_, err = r.Register(alice, 1, \"onyx\", Peer, nodeID+\"@seed-1.onyx.example.com:26656\", \"\")\n\tuassert.ErrorContains(t, err, \"already lists that peer\")\n\tgot, ok := r.EndpointByAddress(\"onyx\", Peer, nodeID+\"@Seed-1.onyx.example.com:26656\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, id, got.ID)\n}\n\n// Rejecting sends what was verified on the proposal back to unverified: a\n// rejected zone was never vouched for, so nothing on it reads as checked.\nfunc TestRejectUnverifies(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tid, err := r.Register(alice, 1, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 2, \"\"))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), curator, 3, \"not a gno chain\"))\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, string(Unverified), string(e.Status))\n\tuassert.Equal(t, ZoneRejected, e.Reason)\n\tuassert.Equal(t, curator.String(), e.ReviewedBy.String())\n\tv, _ := r.Count(\"onyx\")\n\tuassert.Equal(t, 0, v)\n}\n\n// Eviction goes by when a zone entered its state, not when it was proposed: a\n// long-lived network retired today is not the next record to go.\nfunc TestEvictionIsByEntryOrder(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(curator, 1, \"mainnet\", onyx())) // proposed first\n\tuassert.NoError(t, r.ReviewZone(\"mainnet\", Approved, rev(r, \"mainnet\"), curator, 1, \"\"))\n\tfor i := 0; i \u003c MaxRetired; i++ {\n\t\tslug := \"ret\" + strconv.Itoa(i)\n\t\tuassert.NoError(t, r.Propose(curator, 2, slug, onyx()))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 2, \"\"))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Retired, rev(r, slug), curator, 3, \"stopped\"))\n\t}\n\t// Retiring mainnet now drops ret0, the zone retired longest ago.\n\tuassert.NoError(t, r.ReviewZone(\"mainnet\", Retired, rev(r, \"mainnet\"), curator, 4, \"end of an era\"))\n\t_, ok := r.Zone(\"ret0\")\n\tuassert.False(t, ok)\n\t// And the next retirement drops ret1, not mainnet.\n\tuassert.NoError(t, r.Propose(curator, 5, \"next\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"next\", Approved, rev(r, \"next\"), curator, 5, \"\"))\n\tuassert.NoError(t, r.ReviewZone(\"next\", Retired, rev(r, \"next\"), curator, 6, \"stopped\"))\n\t_, ok = r.Zone(\"mainnet\")\n\tuassert.True(t, ok)\n\t_, ok = r.Zone(\"ret1\")\n\tuassert.False(t, ok)\n}\n\n// Every decision on a zone names the revision it was made on.\nfunc TestEveryZoneDecisionIsRevisionBound(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\told := rev(r, \"onyx\")\n\tedited := onyx()\n\tedited.Title = \"Onyx, edited\"\n\tuassert.NoError(t, r.Edit(\"onyx\", old, edited, alice, 2, \"\"))\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", old, onyx(), curator, 3, \"\"), \"changed since you read it\")\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Rejected, old, curator, 3, \"spam\"), \"changed since you read it\")\n\tuassert.ErrorContains(t, r.RemoveZone(\"onyx\", old), \"changed since you read it\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 3, \"\"))\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Retired, old, curator, 4, \"gone\"), \"changed since you read it\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 4, \"gone\"))\n}\n\nfunc TestCanonicalHostAndTextEdgeCases(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\t// A peer's host loses its terminal dot, so the two spellings are one peer.\n\t_, err := r.Register(alice, 1, \"onyx\", Peer, nodeID+\"@seed-1.onyx.example.com:26656\", \"\")\n\tuassert.NoError(t, err)\n\t_, err = r.Register(alice, 1, \"onyx\", Peer, nodeID+\"@seed-1.onyx.example.com.:26656\", \"\")\n\tuassert.ErrorContains(t, err, \"already lists that peer\")\n\t// An IPv4 host with a terminal dot is refused: Go's dialer cannot use it.\n\tuassert.ErrorContains(t, ValidateEndpoint(RPC, \"http://1.2.3.4.:26657\"), \"DNS name or an IPv4\")\n\tuassert.ErrorContains(t, ValidateEndpoint(Peer, nodeID+\"@1.2.3.4.:26656\"), \"DNS name or an IPv4\")\n\t// A loopback or private host is a local zone's only.\n\t_, err = r.Register(alice, 1, \"onyx\", RPC, \"http://127.0.0.1:26657\", \"\")\n\tuassert.ErrorContains(t, err, \"private or special-use\")\n\t_, err = r.Register(alice, 1, \"onyx\", Peer, nodeID+\"@10.1.2.3:26656\", \"\")\n\tuassert.ErrorContains(t, err, \"private or special-use\")\n\tlocal := onyx()\n\tlocal.Kind, local.RPCURL = Local, \"http://127.0.0.1:26657\"\n\tuassert.NoError(t, r.Propose(alice, 1, \"mine\", local))\n\t_, err = r.Register(alice, 1, \"mine\", Peer, nodeID+\"@127.0.0.1:26656\", \"\")\n\tuassert.NoError(t, err)\n\t// Equivalent URL spellings are one endpoint.\n\tfor _, pair := range [][2]string{\n\t\t{\"https://h.example.com/path\", \"https://h.example.com/path?\"},\n\t\t{\"https://h.example.com?a=1\", \"https://h.example.com/?a=1\"},\n\t\t{\"https://h.example.com/%2F\", \"https://h.example.com/%2f\"},\n\t} {\n\t\tuassert.Equal(t, Canonical(Indexer, pair[0]), Canonical(Indexer, pair[1]), pair[0])\n\t}\n\tuassert.ErrorContains(t, ValidateEndpoint(Indexer, \"https://h.example.com/%7e\"), \"needs no escaping\")\n\tuassert.ErrorContains(t, ValidateEndpoint(Indexer, \"https://h.example.com/%41\"), \"needs no escaping\")\n\t// Look-alike badges and characters that draw nothing.\n\tin := onyx()\n\tfor _, title := range []string{\"✔ official\", \"☑ mainnet\", \"\\U0001D159\", \"main\\U000E0100net\", \"x\\ue000\", \"\\u180b\", \"\\u0378\"} {\n\t\tin.Title = title\n\t\tuassert.Error(t, ValidateInfo(in), title)\n\t}\n}\n\n// The per-proposer and per-registrant caps are counts, and they follow every\n// way a zone or an endpoint leaves.\nfunc TestCountersFollowRemovals(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\ta, _ := r.Register(alice, 1, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\t_, _ = r.Register(alice, 1, \"onyx\", RPC, \"https://b.example.com\", \"\")\n\tuassert.Equal(t, 2, r.OwnerCount(\"onyx\", alice))\n\tuassert.NoError(t, r.RemoveEndpoint(a, erev(r, a)))\n\tuassert.Equal(t, 1, r.OwnerCount(\"onyx\", alice))\n\tuassert.NoError(t, r.RemoveZone(\"onyx\", rev(r, \"onyx\")))\n\tuassert.Equal(t, 0, r.OwnerCount(\"onyx\", alice))\n\tfor i := 0; i \u003c MaxPendingPerProposer; i++ {\n\t\tuassert.NoError(t, r.Propose(alice, 2, \"p\"+strconv.Itoa(i), onyx()))\n\t}\n\tuassert.ErrorContains(t, r.Propose(alice, 2, \"over\", onyx()), \"pending proposals\")\n\tuassert.NoError(t, r.ReviewZone(\"p0\", Approved, rev(r, \"p0\"), curator, 3, \"\"))\n\tuassert.NoError(t, r.Propose(alice, 3, \"over\", onyx()))\n}\n\nfunc TestSoleApproved(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(curator, 1, \"za\", onyx()))\n\t_, ok := r.SoleApproved(\"onyx-1\")\n\tuassert.False(t, ok, \"pending is not approved\")\n\tuassert.NoError(t, r.ReviewZone(\"za\", Approved, rev(r, \"za\"), curator, 1, \"\"))\n\tz, ok := r.SoleApproved(\"onyx-1\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"za\", z.Slug)\n\tuassert.NoError(t, r.Propose(curator, 1, \"zb\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"zb\", Approved, rev(r, \"zb\"), curator, 1, \"\"))\n\t_, ok = r.SoleApproved(\"onyx-1\")\n\tuassert.False(t, ok, \"two approved zones share it: no guess\")\n}\n\n// A status change bumps the revision too: an approval prepared before a\n// colleague's rejection fails instead of quietly reversing it.\nfunc TestStatusChangeBumpsTheRevision(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tread := rev(r, \"onyx\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, read, bob, 2, \"phishing RPC\"))\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Approved, read, curator, 3, \"\"), \"changed since you read it\")\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, \"phishing RPC\", z.Reason)\n}\n\n// Leaving the local kind drops the private endpoints in the same edit, so\n// nobody can block the edit by registering one again after each removal.\nfunc TestLeavingLocalDropsPrivateEndpoints(t *testing.T) {\n\tr := NewRegistry()\n\tlocal := onyx()\n\tlocal.Kind, local.RPCURL = Local, \"http://127.0.0.1:26657\"\n\tuassert.NoError(t, r.Propose(alice, 1, \"mine\", local))\n\tpriv, err := r.Register(alice, 1, \"mine\", Peer, nodeID+\"@10.0.0.5:26656\", \"\")\n\tuassert.NoError(t, err)\n\tflagged, err := r.Register(bob, 1, \"mine\", RPC, \"http://localhost:1\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.ReviewEndpoint(flagged, Flagged, zr(r, flagged), erev(r, flagged), curator, 1, \"squatting\"))\n\tpub, err := r.Register(alice, 1, \"mine\", RPC, \"https://rpc.mine.example.com\", \"\")\n\tuassert.NoError(t, err)\n\t// A ruled one is a record: the edit refuses to drop it unseen, and a\n\t// curator removes it first.\n\tuassert.ErrorContains(t, r.Edit(\"mine\", rev(r, \"mine\"), onyx(), alice, 2, \"\"), \"which a curator ruled on\")\n\tuassert.NoError(t, r.RemoveEndpoint(flagged, erev(r, flagged)))\n\tuassert.NoError(t, r.Edit(\"mine\", rev(r, \"mine\"), onyx(), alice, 2, \"\"))\n\tfor _, id := range []int64{priv, flagged} {\n\t\t_, ok := r.Endpoint(id)\n\t\tuassert.False(t, ok, \"a private endpoint is dropped\")\n\t}\n\t_, ok := r.Endpoint(pub)\n\tuassert.True(t, ok, \"a public one stays\")\n\tuassert.Equal(t, 1, r.EndpointCount(\"mine\", \"\"))\n\tuassert.Equal(t, 0, r.OwnerCount(\"mine\", bob))\n\tuassert.Equal(t, 1, r.Awaiting(\"mine\"))\n}\n\n// A curator's chain-id edit of a pending zone names the curator on the resets;\n// only the proposer's own edit records nobody.\nfunc TestResetNamesACuratorEditor(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tid, _ := r.Register(alice, 1, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 2, \"\"))\n\tmoved := onyx()\n\tmoved.ChainID = \"onyx-2\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), moved, curator, 3, \"\"))\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, curator.String(), e.ReviewedBy.String())\n}\n\nfunc TestPrivateHostsAndURLForms(t *testing.T) {\n\tfor _, h := range []string{\"validator\", \"node\", \"printer.local\", \"metadata.google.internal\", \"router.home.arpa\",\n\t\t\"foo.localdomain\", \"a.localhost\", \"192.0.0.1\", \"198.18.0.1\", \"198.19.255.255\", \"224.0.0.1\", \"255.255.255.255\",\n\t\t\"127.1\", \"0x7f.1\", \"2130706433\",\n\t\t\"rpc.test\", \"node.lan\", \"nas.home\", \"dc.corp\", \"wiki.intranet\", \"box.private\", \"x.onion\", \"y.alt\",\n\t\t\"192.0.2.1\", \"198.51.100.7\", \"203.0.113.255\",\n\t\t\"gno.example\", \"x.invalid\", \"rpc.mail\", \"ipv4only.arpa\", \"gnoland.default.service.arpa\", \"x.arpa\",\n\t\t\"100.127.255.255\", \"172.16.0.1\", \"172.31.255.255\", \"svc.service.consul\", \"node.lxd\", \"x.docker\", \"y.localnet\"} {\n\t\tuassert.True(t, IsPrivateHost(h), h)\n\t}\n\tfor _, h := range []string{\"rpc.gno.land\", \"1.1.1.1\", \"198.20.0.1\", \"172.32.0.1\", \"172.15.255.255\", \"gno.land.\", \"100.128.0.1\",\n\t\t\"a.latest\", \"my.salt\", \"192.0.3.1\", \"198.51.101.1\", \"203.0.114.1\",\n\t\t\"example.com\", \"gmail.com\", \"arpa.example.com\"} {\n\t\tuassert.False(t, IsPrivateHost(h), h)\n\t}\n\t// tcp:// and http:// are one rpc endpoint, the way gnokey dials them.\n\tuassert.Equal(t, Canonical(RPC, \"tcp://h.example.com:26657\"), Canonical(RPC, \"http://h.example.com:26657\"))\n\tuassert.Equal(t, Canonical(RPC, \"tcp://h.example.com:80\"), Canonical(RPC, \"http://h.example.com\"))\n\t// An empty query's ? goes; a query ending in ? keeps it.\n\tuassert.Equal(t, \"https://h.example.com/p?a?\", Canonical(Indexer, \"https://h.example.com/p?a?\"))\n\t// . and .. path segments are another spelling: refused.\n\tfor _, u := range []string{\"https://h.example.com/.\", \"https://h.example.com/./x\", \"https://h.example.com/a/..\", \"https://h.example.com/../a\"} {\n\t\tuassert.ErrorContains(t, ValidateEndpoint(Indexer, u), \"path segment\", u)\n\t}\n\tuassert.NoError(t, ValidateEndpoint(Indexer, \"https://h.example.com/a.b/..c/x.\"))\n\tin := onyx()\n\tfor _, title := range []string{\"⌛ pending\", \"❎ rejected\", \"\\U0001F6D1 stop\", \"☒ no\"} {\n\t\tin.Title = title\n\t\tuassert.ErrorContains(t, ValidateInfo(in), \"status glyph\", title)\n\t}\n}\n\n// A copied Registry value is the same registry: it shares the revision\n// counter with the zones it shares, so no revision is handed out twice. With\n// the counter inline, an edit through the copy and then one through the\n// original would both produce the same revision number, and a decision made on\n// the first content would pass against the second.\nfunc TestCopiedRegistryIsTheSameRegistry(t *testing.T) {\n\tr1 := NewRegistry()\n\tuassert.NoError(t, r1.Propose(alice, 1, \"onyx\", onyx()))\n\tr2 := *r1\n\tin := onyx()\n\tin.Title = \"via the copy\"\n\tuassert.NoError(t, r2.Edit(\"onyx\", rev(r1, \"onyx\"), in, alice, 2, \"\"))\n\tseen := rev(r1, \"onyx\") // what a curator read: the copy's content\n\tin.Title = \"via the original\"\n\tuassert.NoError(t, r1.Edit(\"onyx\", seen, in, alice, 3, \"\"))\n\tuassert.True(t, rev(r1, \"onyx\") != seen, \"a new content, a new revision\")\n\tuassert.ErrorContains(t, r1.ReviewZone(\"onyx\", Approved, seen, curator, 4, \"\"), \"changed since you read it\")\n}\n\n// Editing a local zone that stays local drops nothing, and every Info URL is\n// checked for a private host, not only the main RPC.\nfunc TestOnlyLeavingLocalDrops(t *testing.T) {\n\tr := NewRegistry()\n\tlocal := onyx()\n\tlocal.Kind, local.RPCURL = Local, \"http://127.0.0.1:26657\"\n\tuassert.NoError(t, r.Propose(alice, 1, \"mine\", local))\n\tid, err := r.Register(alice, 1, \"mine\", Peer, nodeID+\"@10.0.0.5:26656\", \"\")\n\tuassert.NoError(t, err)\n\tlocal.Title = \"Mine, renamed\"\n\tuassert.NoError(t, r.Edit(\"mine\", rev(r, \"mine\"), local, alice, 2, \"\"))\n\t_, ok := r.Endpoint(id)\n\tuassert.True(t, ok, \"a local zone keeps its private endpoints\")\n\n\tfor _, set := range []func(*Info){\n\t\tfunc(in *Info) { in.GnowebURL = \"http://192.168.1.2\" },\n\t\tfunc(in *Info) { in.GenesisURL = \"https://files.lan/genesis.json\" },\n\t} {\n\t\tin := onyx()\n\t\tset(\u0026in)\n\t\tuassert.ErrorContains(t, ValidateInfo(in), \"private or special-use\")\n\t}\n}\n\n// Any edit to an approved zone is a review on record, so a chain-id reset it\n// causes names its editor, whoever that is; only a pending zone's own\n// proposer resets as nobody.\nfunc TestApprovedEditResetNamesTheEditor(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 2, \"\"))\n\tid, _ := r.Register(bob, 3, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 4, \"\"))\n\tmoved := onyx()\n\tmoved.ChainID = \"onyx-2\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), moved, alice, 5, \"relaunched\"))\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, alice.String(), e.ReviewedBy.String())\n}\n\n// A curator's exemption is from the review queue, never from the live cap.\nfunc TestExemptStillMeetsTheLiveCap(t *testing.T) {\n\tr := NewRegistry()\n\tfor i := 0; i \u003c MaxZones; i++ {\n\t\tslug := \"z\" + strconv.Itoa(i)\n\t\tuassert.NoError(t, r.ProposeExempt(curator, 1, slug, onyx()))\n\t\tuassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 1, \"\"))\n\t}\n\tuassert.ErrorContains(t, r.ProposeExempt(curator, 2, \"one-more\", onyx()), \"the registry is full\")\n}\n\n// The URL forms each kind dials: a tcp:// rpc is host and port only, an\n// indexer may be a websocket, and IsPrivateHost fails closed on anything but a\n// bare host.\nfunc TestURLFormsPerKind(t *testing.T) {\n\tuassert.ErrorContains(t, ValidateEndpoint(RPC, \"tcp://rpc.example.com:26657/websocket\"), \"host and port only\")\n\tuassert.ErrorContains(t, ValidateEndpoint(RPC, \"tcp://rpc.example.com:26657?x=1\"), \"host and port only\")\n\tuassert.NoError(t, ValidateEndpoint(RPC, \"tcp://rpc.example.com:26657\"))\n\tuassert.NoError(t, ValidateEndpoint(RPC, \"wss://rpc.example.com/websocket\"))\n\tuassert.NoError(t, ValidateEndpoint(Indexer, \"wss://indexer.example.com/graphql/query\"))\n\tuassert.Error(t, ValidateEndpoint(Faucet, \"wss://faucet.example.com\"))\n\tfor _, h := range []string{\"127.0.0.1:26657\", \"10.0.0.1/\", \"foo.local:80\", \"a b\", \"192.88.99.1\"} {\n\t\tuassert.True(t, IsPrivateHost(h), h)\n\t}\n}\n\n// A rejection or a retirement is restated with a new reason, the only way to\n// correct one, without a second eviction or reset.\nfunc TestARejectionReasonCanBeRestated(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), curator, 2, \"wrong netwrok\"))\n\tentered := func() int64 { z, _ := r.Zone(\"onyx\"); return z.Entered }\n\tbefore := entered()\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), bob, 3, \"wrong network\"))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, \"wrong network\", z.Reason)\n\tuassert.Equal(t, bob.String(), z.ReviewedBy.String())\n\tuassert.Equal(t, before, entered(), \"a restatement is not a new entry\")\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), bob, 4, \"wrong network\"), \"already rejected\")\n}\n\n// Flagging a verified endpoint puts it back in the unchecked index, so counts\n// and a later reset see it as what it is.\nfunc TestFlaggingAVerifiedEndpointUnchecksIt(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 1, \"\"))\n\tid, _ := r.Register(bob, 2, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 3, \"\"))\n\tuassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), carol, 4, \"down\"))\n\tv, total := r.Count(\"onyx\")\n\tuassert.Equal(t, 0, v)\n\tuassert.Equal(t, 1, total)\n\tuassert.Equal(t, 0, r.Awaiting(\"onyx\"))\n\t// A retirement then keeps the flag: it resets only what is verified.\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 5, \"shut down\"))\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, string(Flagged), string(e.Status))\n\t// A restated verdict names its new reviewer.\n\tuassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 6, \"down for good\"))\n\te, _ = r.Endpoint(id)\n\tuassert.Equal(t, curator.String(), e.ReviewedBy.String())\n}\n\n// A reset moves the endpoint's revision, so a verdict written against the\n// verified endpoint fails after a retirement reset it.\nfunc TestAResetMovesTheEndpointRevision(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 1, \"\"))\n\tid, _ := r.Register(bob, 2, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 3, \"\"))\n\tread := erev(r, id)\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 4, \"shut down\"))\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Flagged, zr(r, id), read, carol, 5, \"x\"), \"changed since\")\n}\n\n// The package README's example, verbatim but for must and the names: it is\n// the first thing an importer copies, so it is run.\nfunc TestTheReadmeExampleRuns(t *testing.T) {\n\tproposer, height := alice, int64(1)\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(proposer, height, \"onyx\", Info{ChainID: \"onyx-1\", Title: \"Onyx\",\n\t\tKind: Testnet, RPCURL: \"https://rpc.onyx.testnets.gno.land\"}))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, z.Revision, curator, height, \"\"))\n\tz, _ = r.Zone(\"onyx\")\n\tid, err := r.Register(proposer, height, \"onyx\", Peer,\n\t\t\"g1x5mlj5ava0dw9vkf4j6admjlzswm6f06p44krn@seed-1.onyx.testnets.gno.land:26656\", \"gno core\")\n\tuassert.NoError(t, err)\n\te, _ := r.Endpoint(id)\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, z.Revision, e.Revision, curator, height, \"answers onyx-1\"))\n\tuassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: \"onyx\", Kind: Peer, Status: Verified})))\n}\n\n// A verification restated with a new reason names its new reviewer, and a\n// zone removed and proposed again starts with no private endpoints on record.\nfunc TestRestatedVerifyAndARemovedZonesPrivateIndex(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tid, _ := r.Register(alice, 1, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 2, \"answers\"))\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), carol, 3, \"answers, re-probed\"))\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, carol.String(), e.ReviewedBy.String())\n\n\tlocal := onyx()\n\tlocal.Kind, local.RPCURL = Local, \"http://127.0.0.1:26657\"\n\tuassert.NoError(t, r.Propose(alice, 4, \"lab\", local))\n\t_, err := r.Register(alice, 4, \"lab\", RPC, \"http://10.0.0.1:26657\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.NoError(t, r.RemoveZone(\"lab\", rev(r, \"lab\")))\n\tuassert.NoError(t, r.Propose(alice, 5, \"lab\", local))\n\tuassert.Equal(t, 0, len(r.PrivateEndpoints(\"lab\")))\n\tuassert.NoError(t, r.Edit(\"lab\", rev(r, \"lab\"), onyx(), alice, 6, \"\"))\n}\n\n// A zone decision naming a revision from the future fails as a stale one does.\nfunc TestAFutureRevisionIsRefused(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\")+1, curator, 2, \"\"), \"changed since you read it\")\n}\n\n// Restating: any review state with a new visible reason, bumping the\n// revision; never with an empty or the same reason.\nfunc TestRestatementRules(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 2, \"answers onyx-1\"))\n\tread := rev(r, \"onyx\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, read, carol, 3, \"answers onyx-1, re-probed\"))\n\tuassert.True(t, rev(r, \"onyx\") \u003e read, \"a restatement moves the revision\")\n\tuassert.ErrorContains(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), carol, 4, \" \"), \"already approved\")\n\tid, _ := r.Register(bob, 4, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 4, \"down\"))\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 4, \"\"), \"needs a new reason\")\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), curator, 5, \"shut down\"))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Retired, rev(r, \"onyx\"), carol, 6, \"shut down 2026-10-01\"))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, \"shut down 2026-10-01\", z.Reason)\n\n}\n\n// What a URL is stored as: scheme and host lowercased in ASCII only, the path\n// and query as typed; a letter that lowercases into ASCII is refused, not\n// folded. A tcp:// rpc path is refused whatever the scheme's case.\nfunc TestStoredURLForm(t *testing.T) {\n\tr := NewRegistry()\n\tin := onyx()\n\tin.GenesisURL = \"HTTPS://Files.Example.com/G?Q=1\"\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", in))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, \"https://files.example.com/G?Q=1\", z.GenesisURL)\n\tid, err := r.Register(alice, 1, \"onyx\", Indexer, \"HTTPS://Idx.Example.com?Q=1\", \"\")\n\tuassert.NoError(t, err)\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, \"https://idx.example.com?Q=1\", e.Address)\n\tfor _, u := range []string{\"https://Key.example.com\", \"https://rpc.İnfo.example.com\"} {\n\t\tbad := onyx()\n\t\tbad.RPCURL = u\n\t\tuassert.Error(t, r.Propose(bob, 2, \"x\"+strconv.Itoa(len(u)), bad), u)\n\t}\n\tuassert.ErrorContains(t, ValidateEndpoint(RPC, \"TCP://h.example.com:26657/websocket\"), \"host and port only\")\n\tuassert.False(t, IsPrivateHost(\"RPC.GNO.LAND\"))\n\tuassert.ErrorContains(t, ValidateEndpoint(RPC, \"https://café.example.com\"), \"'é'\")\n}\n\n// A curator's leave-local edit is refused while a private endpoint carries a\n// ruling of any kind: a reset's reason, a reasonless unverify, a verification;\n// a curator who proposed the zone included.\nfunc TestLeavingLocalRefusesEveryRuling(t *testing.T) {\n\tsetup := func() (*Registry, int64) {\n\t\tr := NewRegistry()\n\t\tlocal := onyx()\n\t\tlocal.Kind, local.RPCURL = Local, \"http://127.0.0.1:26657\"\n\t\tuassert.NoError(t, r.Propose(curator, 1, \"lab\", local))\n\t\tid, err := r.Register(curator, 1, \"lab\", RPC, \"http://10.0.0.1:26657\", \"\")\n\t\tuassert.NoError(t, err)\n\t\treturn r, id\n\t}\n\tr, id := setup()\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), carol, 2, \"\"))\n\tuassert.ErrorContains(t, r.Edit(\"lab\", rev(r, \"lab\"), onyx(), curator, 3, \"\"), \"is verified\")\n\n\tr, id = setup()\n\tuassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), carol, 2, \"x\"))\n\tuassert.NoError(t, r.ReviewEndpoint(id, Unverified, zr(r, id), erev(r, id), carol, 3, \"\"))\n\tuassert.ErrorContains(t, r.Edit(\"lab\", rev(r, \"lab\"), onyx(), curator, 4, \"\"), \"a curator ruled on\")\n\n\tr, id = setup()\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), carol, 2, \"\"))\n\tmoved := onyx()\n\tmoved.Kind, moved.RPCURL, moved.ChainID = Local, \"http://127.0.0.1:26657\", \"lab-2\"\n\tuassert.NoError(t, r.Edit(\"lab\", rev(r, \"lab\"), moved, curator, 3, \"\")) // the proposer's reset: no reviewer, a reason\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, \"\", e.ReviewedBy.String())\n\tuassert.ErrorContains(t, r.Edit(\"lab\", rev(r, \"lab\"), onyx(), curator, 4, \"\"), \"a curator ruled on\")\n}\n\n// Clearable counts what a bulk clear may remove: registered through the gate,\n// never ruled on. A first verdict or a removal takes one out (a reset cannot:\n// it touches only verified endpoints); an exempt registration never counts.\nfunc TestTheClearableCount(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 1, \"\"))\n\ta, _ := r.Register(bob, 2, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tb, _ := r.Register(bob, 2, \"onyx\", RPC, \"https://b.example.com\", \"\")\n\tc, _ := r.Register(bob, 2, \"onyx\", RPC, \"https://c.example.com\", \"\")\n\tx, _ := r.RegisterExempt(curator, 2, \"onyx\", RPC, \"https://x.example.com\", \"\")\n\tex, _ := r.Endpoint(x)\n\tuassert.True(t, ex.Exempt)\n\tuassert.False(t, ex.Clearable())\n\tuassert.Equal(t, 3, r.Clearable(\"onyx\"))\n\tuassert.NoError(t, r.ReviewEndpoint(a, Verified, zr(r, a), erev(r, a), curator, 3, \"\"))\n\tuassert.Equal(t, 2, r.Clearable(\"onyx\"))\n\tuassert.NoError(t, r.ReviewEndpoint(a, Flagged, zr(r, a), erev(r, a), curator, 3, \"down\"))\n\tuassert.Equal(t, 2, r.Clearable(\"onyx\"), \"a second verdict changes nothing\")\n\tuassert.NoError(t, r.RemoveEndpoint(b, erev(r, b)))\n\tuassert.Equal(t, 1, r.Clearable(\"onyx\"))\n\tmoved := onyx()\n\tmoved.ChainID = \"onyx-2\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), moved, curator, 4, \"relaunch\"))\n\tuassert.Equal(t, 1, r.Clearable(\"onyx\"), \"a reset touches only verified endpoints\")\n\t_ = c\n}\n\n// One edit off the local kind drops at most MaxDropPerEdit endpoints.\nfunc TestLeavingLocalDropsAtMostTheCap(t *testing.T) {\n\tr := NewRegistry()\n\tlocal := onyx()\n\tlocal.Kind, local.RPCURL = Local, \"http://127.0.0.1:26657\"\n\tuassert.NoError(t, r.Propose(curator, 1, \"lab\", local))\n\tfor i := 0; i \u003c= MaxDropPerEdit; i++ {\n\t\t_, err := r.RegisterExempt(curator, 1, \"lab\", RPC, \"http://10.0.0.\"+strconv.Itoa(i%250+1)+\":\"+strconv.Itoa(26000+i), \"\")\n\t\tuassert.NoError(t, err)\n\t}\n\tuassert.ErrorContains(t, r.Edit(\"lab\", rev(r, \"lab\"), onyx(), curator, 2, \"\"), \"more than 64 in one edit\")\n\tids := r.PrivateEndpoints(\"lab\")\n\tuassert.NoError(t, r.RemoveEndpoint(ids[0].ID, ids[0].Revision))\n\tuassert.NoError(t, r.Edit(\"lab\", rev(r, \"lab\"), onyx(), curator, 3, \"\"))\n}\n\n// The numbers the READMEs state, pinned: a change to one is a change to what\n// the docs promise.\nfunc TestTheDocumentedBounds(t *testing.T) {\n\tfor name, got := range map[string]int{\"MaxZones\": MaxZones, \"MaxPending\": MaxPending, \"MaxPendingPerProposer\": MaxPendingPerProposer,\n\t\t\"MaxRejected\": MaxRejected, \"MaxRetired\": MaxRetired, \"MaxEndpointsPerZone\": MaxEndpointsPerZone,\n\t\t\"MaxUnverifiedPerZone\": MaxUnverifiedPerZone, \"MaxEndpointsPerAddress\": MaxEndpointsPerAddress, \"MaxDropPerEdit\": MaxDropPerEdit,\n\t\t\"MaxTitleLen\": MaxTitleLen, \"MaxDescriptionLen\": MaxDescriptionLen, \"MaxLabelLen\": MaxLabelLen, \"MaxReasonLen\": MaxReasonLen, \"MaxURLLen\": MaxURLLen} {\n\t\twant := map[string]int{\"MaxZones\": 256, \"MaxPending\": 64, \"MaxPendingPerProposer\": 4, \"MaxRejected\": 64, \"MaxRetired\": 128,\n\t\t\t\"MaxEndpointsPerZone\": 128, \"MaxUnverifiedPerZone\": 64, \"MaxEndpointsPerAddress\": 16, \"MaxDropPerEdit\": 64,\n\t\t\t\"MaxTitleLen\": 64, \"MaxDescriptionLen\": 512, \"MaxLabelLen\": 64, \"MaxReasonLen\": 280, \"MaxURLLen\": 256}[name]\n\t\tuassert.Equal(t, want, got, name)\n\t}\n}\n\n// Rules the other tests reach only in part.\nfunc TestValidationEdges(t *testing.T) {\n\t// A private host is refused on every kind but local.\n\tfor _, k := range []Kind{Mainnet, Testnet, Devnet} {\n\t\tin := onyx()\n\t\tin.Kind, in.RPCURL = k, \"http://10.0.0.1:26657\"\n\t\tuassert.ErrorContains(t, ValidateInfo(in), \"private or special-use\", string(k))\n\t}\n\t// The combining grapheme joiner draws nothing.\n\tin := onyx()\n\tin.Title = \"On\\u034fyx\"\n\tuassert.ErrorContains(t, ValidateInfo(in), \"invisible\")\n\t// Needless escapes of unreserved characters, and an entity shape.\n\tfor _, u := range []string{\"https://h.example.com/a%5Fb\", \"https://h.example.com/a%2Db\", \"https://h.example.com/%2E%2E/x\",\n\t\t\"https://h.example.com/a\u0026#38;b\"} {\n\t\tuassert.Error(t, ValidateEndpoint(RPC, u), u)\n\t}\n\t// Dot segments are a path rule; a query may hold dots.\n\tuassert.NoError(t, ValidateEndpoint(Explorer, \"https://h.example.com/p?x=../y\"))\n\t// Default websocket ports are dropped like the http ones.\n\tuassert.Equal(t, Canonical(RPC, \"wss://h.example.com/ws\"), Canonical(RPC, \"wss://h.example.com:443/ws\"))\n\tuassert.Equal(t, Canonical(RPC, \"ws://h.example.com/ws\"), Canonical(RPC, \"ws://h.example.com:80/ws\"))\n}\n\n// What a caller types is trimmed before it is used: the kind, a label, a\n// reason; and a restatement of verify or unverify needs a new visible reason.\nfunc TestTrimsAndRestatementReasons(t *testing.T) {\n\tr := NewRegistry()\n\tin := onyx()\n\tin.Kind = \" testnet \"\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", in))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, string(Testnet), string(z.Kind))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Approved, rev(r, \"onyx\"), curator, 1, \"\"))\n\tid, _ := r.Register(bob, 2, \"onyx\", RPC, \"https://a.example.com\", \"  bob's node  \")\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, \"bob's node\", e.Label)\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 3, \"  answers  \"))\n\te, _ = r.Endpoint(id)\n\tuassert.Equal(t, \"answers\", e.Reason)\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 4, \" \"), \"needs a new reason\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Unverified, zr(r, id), erev(r, id), curator, 5, \"x\"))\n\tuassert.ErrorContains(t, r.ReviewEndpoint(id, Unverified, zr(r, id), erev(r, id), curator, 6, \"\"), \"needs a new reason\")\n\tedited := onyx()\n\tedited.Title = \"Onyx, edited\"\n\tuassert.NoError(t, r.Edit(\"onyx\", rev(r, \"onyx\"), edited, curator, 7, \"  retitled  \"))\n\tz, _ = r.Zone(\"onyx\")\n\tuassert.Equal(t, \"retitled\", z.Reason)\n\tuassert.Equal(t, rev(r, \"onyx\"), r.Revision(), \"the last revision handed out\")\n}\n\n// A zone removed and proposed again starts with nothing clearable.\nfunc TestARemovedZonesClearableCountIsGone(t *testing.T) {\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\t_, err := r.Register(alice, 1, \"onyx\", RPC, \"https://a.example.com\", \"\")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 1, r.Clearable(\"onyx\"))\n\tuassert.NoError(t, r.RemoveZone(\"onyx\", rev(r, \"onyx\")))\n\tuassert.NoError(t, r.Propose(alice, 2, \"onyx\", onyx()))\n\tuassert.Equal(t, 0, r.Clearable(\"onyx\"))\n}\n\n// URL characters, escapes, schemes, selectors, Parse trimming, pending\n// restatement and stored tails.\nfunc TestURLAndTextRules(t *testing.T) {\n\t// Every character a URL may not hold, one at a time.\n\tfor _, c := range []string{\"\u003c\", \"\u003e\", \"`\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", \"|\", \"\\\\\", \"^\", \"#\", \"\\\"\", \"'\"} {\n\t\tuassert.Error(t, ValidateEndpoint(RPC, \"https://h.example.com/a\"+c+\"b\"), c)\n\t}\n\t// A needless escape of a digit or a lowercase letter; the hex case of the\n\t// first escape digit.\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://h.example.com/a%30\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://h.example.com/a%61\"))\n\tuassert.Equal(t, Canonical(RPC, \"https://h.example.com/%af\"), Canonical(RPC, \"https://h.example.com/%AF\"))\n\t// A hex last label reads as an IPv4 number.\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://a.0x1\"))\n\tuassert.True(t, IsPrivateHost(\"a.0x1\"))\n\tuassert.True(t, IsPrivateHost(\"PRINTER.LOCAL\"))\n\t// Schemes per field.\n\tin := onyx()\n\tin.GnowebURL = \"tcp://onyx.example.com:26657\"\n\tuassert.Error(t, ValidateInfo(in))\n\tuassert.Error(t, ValidateEndpoint(Indexer, \"tcp://indexer.example.com:8546\"))\n\t// Variation selectors only after a base they modify.\n\tfor _, s := range []string{\"a\\ufe00\", \"᠀\\u180b\"} {\n\t\tin := onyx()\n\t\tin.Title = s\n\t\tuassert.ErrorContains(t, ValidateInfo(in), \"invisible\", s)\n\t}\n\tok := onyx()\n\tok.Title = \"ᠨ\\u180f\"\n\tuassert.NoError(t, ValidateInfo(ok))\n\tuassert.False(t, HasVisible(\"\\u200b\\u200d\"))\n\t// The Parse functions trim.\n\tst, err := ParseStatus(\" approved \")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, string(Approved), string(st))\n\tk, err := ParseEndpointKind(\" rpc \")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, string(RPC), string(k))\n\tv, err := ParseVerification(\" verified \")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, string(Verified), string(v))\n\t// Nothing goes back to pending, not even as a restatement.\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tuassert.Error(t, r.ReviewZone(\"onyx\", Pending, rev(r, \"onyx\"), curator, 2, \"x\"))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, \"\", z.ReviewedBy.String())\n\t// An empty query and a bare \"/\" are not stored, so the dialable spelling\n\t// is the one listed.\n\tid, err := r.Register(alice, 3, \"onyx\", RPC, \"https://rpc2.zz.example.com/?\", \"\")\n\tuassert.NoError(t, err)\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, \"https://rpc2.zz.example.com\", e.Address)\n\t_, err = r.Register(alice, 3, \"onyx\", RPC, \"https://rpc2.zz.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"already lists\")\n\t// More private suffixes, more look-alikes.\n\tfor _, h := range []string{\"rpc.node.incus\", \"web.dns.podman\", \"foo.i2p\", \"gnoland.default.svc\"} {\n\t\tuassert.True(t, IsPrivateHost(h), h)\n\t}\n\tfor _, r := range []rune{0x1FBBD, 0x1F6AD, 0x1F6AF, 0x1F6B1, 0x1F6B3, 0x1F6B7, 0x1F4F5, 0x1F51E, 0x1F10D, 0x1F10F, 0x1F16E} {\n\t\tuassert.Error(t, ValidateLabel(string(r)+\" official\"), string(r))\n\t}\n}\n\n// What is stored canonicalizes as what was typed, so a check made on the\n// typed address (the realm's own-URL reservation) holds for the stored one.\nfunc TestTheStoredFormKeepsItsCanonicalForm(t *testing.T) {\n\tfor _, u := range []string{\"https://h.example.com??\", \"https://h.example.com/??\", \"https://h.example.com?/\",\n\t\t\"https://h.example.com?path=/\", \"https://h.example.com/p?x=?\", \"https://h.example.com/p??\", \"https://h.example.com/?\",\n\t\t\"https://h.example.com/\", \"https://h.example.com?\", \"https://h.example.com/?q=1\", \"https://h.example.com/p/\"} {\n\t\tuassert.Equal(t, Canonical(RPC, u), Canonical(RPC, trimEmptyTail(lowerAuthority(u))), u)\n\t}\n\tuassert.Equal(t, \"https://h.example.com?path=/\", trimEmptyTail(\"https://h.example.com?path=/\"))\n\tuassert.Equal(t, \"https://h.example.com??\", trimEmptyTail(\"https://h.example.com??\"))\n}\n\n// Spaces of every kind (Unicode Zs) and tabs are trimmed; a line separator at\n// an edge reaches the validator and is refused, never silently cut. A zone's\n// gnoweb and genesis URLs have an empty tail repaired, its main RPC is refused\n// with one, and an endpoint is validated as it will be stored.\nfunc TestTrimsSpacesNotLineBreaks(t *testing.T) {\n\tr := NewRegistry()\n\tin := onyx()\n\tin.Title = \"Onyx\\u2028\"\n\tuassert.ErrorContains(t, r.Propose(alice, 1, \"onyx\", in), \"control character\")\n\tin = onyx()\n\tin.Description = \"\\u0085\" + in.Description\n\tuassert.ErrorContains(t, r.Propose(alice, 1, \"onyx\", in), \"control character\")\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\t_, err := r.Register(alice, 2, \"onyx\", RPC, \"https://a.example.com\", \"operator\\u2028\")\n\tuassert.ErrorContains(t, err, \"control character\")\n\tuassert.Equal(t, \"x\", TrimSpaces(\" \\tx\\t \"))\n\tfor _, u := range []string{\"https://g.example.com/\", \"https://g.example.com?\", \"https://g.example.com/?\"} {\n\t\tr := NewRegistry()\n\t\tin := onyx()\n\t\tin.GnowebURL, in.GenesisURL = u, u\n\t\tuassert.NoError(t, r.Propose(alice, 1, \"xz\", in), u)\n\t\tz, _ := r.Zone(\"xz\")\n\t\tuassert.Equal(t, \"https://g.example.com\", z.GnowebURL, u)\n\t\tuassert.Equal(t, \"https://g.example.com\", z.GenesisURL, u)\n\t}\n\tfor _, u := range []string{\"https://rpc.example.com/\", \"https://rpc.example.com?\"} {\n\t\tbad := onyx()\n\t\tbad.RPCURL = u\n\t\tuassert.Error(t, ValidateInfo(bad), u)\n\t\tuassert.Error(t, NewRegistry().Propose(alice, 1, \"xz\", bad), \"the registry refuses it too: \"+u)\n\t}\n\tuassert.Equal(t, \"Onyx\", TrimSpaces(\"\\u00a0Onyx\\u3000\"))\n\tuassert.Equal(t, \"Onyx\\n\", TrimSpaces(\"Onyx\\n\"))\n\t// ValidateEndpoint judges the string it is given; Register stores the\n\t// trimmed form and validates that.\n\tuassert.Error(t, ValidateEndpoint(RPC, \"tcp://rpc.example.com:26657/\"), \"as given, it has a path\")\n\tid, err := r.Register(alice, 2, \"onyx\", RPC, \"tcp://rpc.example.com:26657/\", \"\")\n\tuassert.NoError(t, err)\n\te, _ := r.Endpoint(id)\n\tuassert.Equal(t, \"tcp://rpc.example.com:26657\", e.Address)\n\tlong := \"https://e.example.com/\" + strings.Repeat(\"a\", MaxURLLen-len(\"https://e.example.com/\"))\n\t_, err = r.Register(alice, 2, \"onyx\", Explorer, long+\"?\", \"\")\n\tuassert.NoError(t, err, \"257 bytes as typed, 256 as stored\")\n\t_, err = r.Register(alice, 2, \"onyx\", Explorer, long+\"b\", \"\")\n\tuassert.Error(t, err, \"257 as stored\")\n}\n\n// Chain id charset, text and URL bounds, controls, escapes and trims.\nfunc TestMoreBoundaries(t *testing.T) {\n\tin := onyx()\n\tin.ChainID = \"onyx:1\"\n\tuassert.Error(t, ValidateInfo(in))\n\tuassert.Error(t, ValidateReason(strings.Repeat(\"x\", MaxReasonLen+1)))\n\tuassert.NoError(t, ValidateReason(strings.Repeat(\"x\", MaxReasonLen)))\n\tuassert.Error(t, ValidateLabel(strings.Repeat(\"x\", MaxLabelLen+1)))\n\tuassert.NoError(t, ValidateLabel(strings.Repeat(\"x\", MaxLabelLen)))\n\tfor _, c := range []string{\"\\x1f\", \"\\x7f\", \"\\u009f\"} {\n\t\tuassert.ErrorContains(t, ValidateLabel(\"a\"+c+\"b\"), \"control character\")\n\t}\n\tok := onyx()\n\tok.Title = \"ᠠ\\u180b\"\n\tuassert.NoError(t, ValidateInfo(ok))\n\thost := \"https://\" + strings.Repeat(\"a\", 20) + \".example.com/\"\n\tlong := host + strings.Repeat(\"p\", MaxURLLen-len(host))\n\tuassert.NoError(t, ValidateEndpoint(RPC, long))\n\tuassert.Error(t, ValidateEndpoint(RPC, long+\"p\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://h.example.com/a\\x7fb\"))\n\tuassert.NoError(t, ValidateEndpoint(Explorer, \"https://h.example.com/a\u0026;b\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://h.example.com/a%2z\"))\n\tuassert.NoError(t, ValidateEndpoint(Explorer, \"https://h.example.com/p?a=/../\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://a.0X1\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://256.1.1.1\"))\n\n\tr := NewRegistry()\n\tin = onyx()\n\tin.Description = \" \\t\" + in.Description + \"\\t \"\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", in))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, onyx().Description, z.Description)\n\tedited := onyx()\n\tedited.Title = \"Onyx, edited\"\n\tuassert.ErrorContains(t, r.Edit(\"onyx\", rev(r, \"onyx\"), edited, alice, 2, \"x\"), \"takes no reason\")\n}\n\n// Boundaries the suites reached only in part.\nfunc TestFurtherBoundaries(t *testing.T) {\n\tuassert.ErrorContains(t, ValidateLabel(\"　\"), \"nothing visible\")\n\tuassert.Error(t, ValidateLabel(\"a\\U000E01EF\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://h.example.com/a%2!\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://h.example.com/%2d\"))\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://1.2.3.4.5\"))\n\tuassert.Error(t, ValidateEndpoint(Peer, nodeID+\"@\"+strings.Repeat(\"a\", 250)+\".example.com:26656\"))\n\tuassert.Equal(t, 16, ReservedForReviewers)\n\n\tr := NewRegistry()\n\tin := onyx()\n\tin.ChainID = \" onyx-1 \"\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", in))\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.Equal(t, \"onyx-1\", z.ChainID)\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), curator, 2, \"first\"))\n\tuassert.NoError(t, r.ReviewZone(\"onyx\", Rejected, rev(r, \"onyx\"), carol, 9, \"restated\"))\n\tz, _ = r.Zone(\"onyx\")\n\tuassert.Equal(t, int64(9), z.ReviewedAt, \"a restatement records when\")\n}\n\n// Round 13: rules that had no test of their own.\nfunc TestRoundThirteenBoundaries(t *testing.T) {\n\t// HasVisible is exported, so its filler rule is its own, not checkText's.\n\tuassert.False(t, HasVisible(\"\\u3164\"), \"a Hangul filler is not visible\")\n\tuassert.True(t, HasVisible(\"a\\u3164\"))\n\t// A 0x last label is held to the address rule even when it is not hex.\n\tuassert.Error(t, ValidateEndpoint(RPC, \"https://a.0xyz\"))\n\t// A peer is at most MaxURLLen bytes, exactly.\n\tpeer := func(n int) string {\n\t\thost := strings.Repeat(\"a\", 63) + \".\" + strings.Repeat(\"b\", 63) + \".\" + strings.Repeat(\"c\", 63) + \".\"\n\t\tpre, post := nodeID+\"@\", \".com:26656\"\n\t\treturn pre + host + strings.Repeat(\"d\", n-len(pre)-len(host)-len(post)) + post\n\t}\n\tuassert.Equal(t, MaxURLLen, len(peer(MaxURLLen)))\n\tuassert.NoError(t, ValidateEndpoint(Peer, peer(MaxURLLen)))\n\tuassert.Error(t, ValidateEndpoint(Peer, peer(MaxURLLen+1)))\n\t// A filtered list is capped at its length, so an importer's append copies\n\t// instead of writing into a slice it may not write.\n\tr := NewRegistry()\n\tuassert.NoError(t, r.Propose(alice, 1, \"onyx\", onyx()))\n\tfor i := 0; i \u003c 3; i++ {\n\t\t_, err := r.Register(alice, 1, \"onyx\", RPC, \"https://r\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tuassert.NoError(t, err)\n\t}\n\tid, err := r.Register(alice, 1, \"onyx\", RPC, \"https://v.example.com\", \"\")\n\tuassert.NoError(t, err)\n\te, _ := r.Endpoint(id)\n\tz, _ := r.Zone(\"onyx\")\n\tuassert.NoError(t, r.ReviewEndpoint(id, Verified, z.Revision, e.Revision, alice, 1, \"\"))\n\tfor _, es := range [][]Endpoint{\n\t\tr.Endpoints(EndpointFilter{Zone: \"onyx\", Status: Verified}),\n\t\tr.Endpoints(EndpointFilter{Zone: \"onyx\", Kind: RPC, Status: Verified}),\n\t\tr.Endpoints(EndpointFilter{Status: Verified}),\n\t} {\n\t\tuassert.Equal(t, 1, len(es))\n\t\tuassert.Equal(t, len(es), cap(es))\n\t}\n\tuassert.NoError(t, r.Propose(alice, 1, \"dev\", Info{ChainID: \"dev\", Title: \"D\", Kind: Devnet, RPCURL: \"https://rpc.dev.example.com\"}))\n\tfor _, zs := range [][]Zone{r.Zones(ZoneFilter{Kind: Devnet}), r.Zones(ZoneFilter{Status: Pending, Kind: Devnet})} {\n\t\tuassert.Equal(t, 1, len(zs))\n\t\tuassert.Equal(t, len(zs), cap(zs))\n\t}\n}\n"},{"name":"zones.gno","body":"// Package zones is the content model of a curated registry of gno.land\n// networks: what a zone is, what an endpoint on one is, which strings each\n// field accepts, and the curation states both move through.\n//\n// A zone is one network a person can point a node or a wallet at: mainnet, a\n// testnet, a staging chain, somebody's gnodev. An endpoint is one way in: an\n// RPC, a gnoweb, a seed or persistent peer, an indexer, a faucet, an explorer.\n// Anybody may propose a zone, and register endpoints as the holding realm\n// allows; a curator decides which\n// zones are official and which endpoints are verified. Every decision is\n// recorded with who made it and when; a rejection, a retirement, a flag and an\n// edit to an approved zone also require a reason, which the public reads.\n//\n// The package decides nothing about WHO may act. Every write that records a\n// decision takes the acting address and the height as arguments (the two\n// removals take neither), and the realm holding the [Registry]\n// decides whether that address is a curator, the proposer, or nobody. That is\n// the split that lets the same model move under a different authority later (a\n// DAO, a system realm) without a line changing here.\n//\n// Live registry: r/moul/zones.\npackage zones\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\n// Status is where a zone stands in curation.\ntype Status string\n\nconst (\n\t// Pending is a proposal nobody has reviewed yet. Every zone starts here.\n\tPending Status = \"pending\"\n\t// Approved is an official zone: the one state a reader should trust.\n\tApproved Status = \"approved\"\n\t// Rejected is a proposal a curator turned down, with the reason kept.\n\tRejected Status = \"rejected\"\n\t// Retired is a zone that was official and no longer runs. It stays\n\t// listed, because a node operator holding its chain id deserves to find\n\t// out why nothing answers, until MaxRetired newer retirements push it out.\n\tRetired Status = \"retired\"\n)\n\n// Kind says what sort of network a zone is.\ntype Kind string\n\nconst (\n\tMainnet Kind = \"mainnet\"\n\tTestnet Kind = \"testnet\"\n\tDevnet  Kind = \"devnet\"\n\tLocal   Kind = \"local\"\n)\n\n// EndpointKind says what an endpoint is for, and therefore which address\n// shape it accepts.\ntype EndpointKind string\n\nconst (\n\tRPC      EndpointKind = \"rpc\"      // a tm2 JSON-RPC: http(s) and tcp for gnokey, ws(s) for a subscriber\n\tGnoweb   EndpointKind = \"gnoweb\"   // a gnoweb frontend\n\tSeed     EndpointKind = \"seed\"     // a p2p seed, for p2p.seeds\n\tPeer     EndpointKind = \"peer\"     // a p2p node, for p2p.persistent_peers\n\tIndexer  EndpointKind = \"indexer\"  // a tx-indexer GraphQL endpoint\n\tFaucet   EndpointKind = \"faucet\"   // a faucet page or API\n\tExplorer EndpointKind = \"explorer\" // a block explorer\n)\n\n// Verification is a curator's verdict on an endpoint.\ntype Verification string\n\nconst (\n\t// Unverified is every endpoint until a curator looks at it. Listed, and\n\t// labelled as such, never hidden: an unverified RPC is still an RPC.\n\tUnverified Verification = \"unverified\"\n\t// Verified means a curator checked it answers for this zone.\n\tVerified Verification = \"verified\"\n\t// Flagged means a curator says do not use it, and says why.\n\tFlagged Verification = \"flagged\"\n)\n\n// Statuses, Kinds, EndpointKinds and Verifications list every value of each\n// enum in display order, for a Render that wants one section per value.\nfunc Statuses() []Status { return []Status{Approved, Pending, Rejected, Retired} }\n\nfunc Kinds() []Kind { return []Kind{Mainnet, Testnet, Devnet, Local} }\n\nfunc EndpointKinds() []EndpointKind {\n\treturn []EndpointKind{RPC, Gnoweb, Seed, Peer, Indexer, Faucet, Explorer}\n}\n\nfunc Verifications() []Verification { return []Verification{Verified, Unverified, Flagged} }\n\n// Bounds on every caller-supplied string. A bound rather than none: every\n// stored byte locks a storage deposit, and an unbounded field is a bill a\n// stranger chooses the size of.\nconst (\n\tMinSlugLen        = 2\n\tMaxSlugLen        = 32\n\tMaxChainIDLen     = 50 // tm2's own limit on a chain id\n\tMaxTitleLen       = 64\n\tMaxDescriptionLen = 512\n\tMaxURLLen         = 256\n\tMaxLabelLen       = 64\n\tMaxReasonLen      = 280\n)\n\n// Info is everything a proposer describes about a zone. It is the part that\n// can be edited; the slug, the status and the history cannot.\ntype Info struct {\n\tChainID     string // what a node's genesis and a signer's -chainid say\n\tTitle       string\n\tDescription string\n\tKind        Kind\n\tGnowebURL   string // optional: a local chain may not run one\n\tRPCURL      string // required: the one endpoint every tool needs\n\tGenesisURL  string // optional: where to download genesis.json\n}\n\n// Zone is a network, as the registry holds it.\n//\n// Flat on purpose: every field is a scalar. A nested struct inside a persisted\n// object is stored as an object of its own, and `gnokey query vm/qeval` prints\n// it as an opaque ref(...) instead of its fields, so a reader asking a node for\n// a zone would get the slug and nothing they came for. [Zone.Info] gives the\n// editable part back as one value.\ntype Zone struct {\n\tSlug        string // the key: [a-z0-9-], stable, and what a URL carries\n\tChainID     string\n\tTitle       string\n\tDescription string\n\tKind        Kind\n\tGnowebURL   string\n\tRPCURL      string\n\tGenesisURL  string\n\n\tStatus     Status\n\tProposer   address\n\tProposedAt int64\n\n\t// Revision changes on every edit of the zone's Info, on every status\n\t// change and on every restated decision, and is never reused,\n\t// not even by a zone removed and proposed again under the same slug. A\n\t// curator acting on a zone names the revision they read, so an edit that\n\t// lands between their reading and their decision makes the decision fail\n\t// instead of attaching their name to text they never saw.\n\tRevision int64\n\tEditedBy address // who last edited the Info; empty if nobody has\n\tEditedAt int64\n\tEntered  int64 // when it entered its current status, in registry order: eviction goes oldest first\n\n\t// The latest curator decision, empty until there is one. A curator's edit\n\t// to an approved zone is a decision too, and replaces these.\n\tReviewedBy address\n\tReviewedAt int64\n\tReason     string\n}\n\n// Info returns the part of the zone a proposer described.\nfunc (z Zone) Info() Info {\n\treturn Info{\n\t\tChainID:     z.ChainID,\n\t\tTitle:       z.Title,\n\t\tDescription: z.Description,\n\t\tKind:        z.Kind,\n\t\tGnowebURL:   z.GnowebURL,\n\t\tRPCURL:      z.RPCURL,\n\t\tGenesisURL:  z.GenesisURL,\n\t}\n}\n\n// Reviewed reports whether a curator has decided anything about the zone,\n// including an edit made after its first review.\nfunc (z Zone) Reviewed() bool { return z.ReviewedBy != \"\" }\n\nfunc (z *Zone) setInfo(in Info) {\n\tz.ChainID = in.ChainID\n\tz.Title = in.Title\n\tz.Description = in.Description\n\tz.Kind = in.Kind\n\tz.GnowebURL = in.GnowebURL\n\tz.RPCURL = in.RPCURL\n\tz.GenesisURL = in.GenesisURL\n}\n\n// Endpoint is one way into a zone, as the registry holds it. Flat for the same\n// reason as [Zone].\ntype Endpoint struct {\n\tID           int64\n\tZone         string // the zone's slug\n\tKind         EndpointKind\n\tAddress      string // a URL, or id@host:port for a seed or a peer\n\tLabel        string // who runs it, or what it is, in the registrant's words\n\tRegistrant   address\n\tRegisteredAt int64\n\n\tStatus     Verification\n\tReviewedBy address\n\tReviewedAt int64\n\tReason     string\n\t// Revision is bumped, from the registry-wide counter zones use, when the\n\t// endpoint is registered, on every verdict and on every reset. A verdict\n\t// and a removal name it, so either fails on an endpoint that changed\n\t// after it was read.\n\tRevision int64\n\t// Exempt marks an endpoint registered through RegisterExempt, by a\n\t// reviewer the holder trusts: never clearable as a never-reviewed one,\n\t// whoever is a reviewer later.\n\tExempt bool\n}\n\n// Clearable reports whether nobody has ruled on the endpoint and it was not a\n// reviewer's own registration: no verdict (every verdict names its\n// reviewer), no reset (every reset leaves a reason), not Exempt. It is what\n// a bulk clear of a flood may remove.\nfunc (e Endpoint) Clearable() bool { return !e.Exempt \u0026\u0026 e.ReviewedBy == \"\" \u0026\u0026 e.Reason == \"\" }\n\n// ParseStatus reads a status from a caller's string. \"\" is the zero Status,\n// which a filter reads as \"any\".\nfunc ParseStatus(s string) (Status, error) {\n\tswitch st := Status(TrimSpaces(s)); st {\n\tcase \"\", Pending, Approved, Rejected, Retired:\n\t\treturn st, nil\n\t}\n\treturn \"\", errors.New(\"zones: unknown status \" + strconv.Quote(s) + \", want approved, pending, rejected or retired\")\n}\n\n// ParseKind reads a zone kind. \"\" is the zero Kind, \"any\" to a filter.\nfunc ParseKind(s string) (Kind, error) {\n\tswitch k := Kind(TrimSpaces(s)); k {\n\tcase \"\", Mainnet, Testnet, Devnet, Local:\n\t\treturn k, nil\n\t}\n\treturn \"\", errors.New(\"zones: unknown kind \" + strconv.Quote(s) + \", want mainnet, testnet, devnet or local\")\n}\n\n// ParseEndpointKind reads an endpoint kind. \"\" is \"any\" to a filter.\nfunc ParseEndpointKind(s string) (EndpointKind, error) {\n\tswitch k := EndpointKind(TrimSpaces(s)); k {\n\tcase \"\", RPC, Gnoweb, Seed, Peer, Indexer, Faucet, Explorer:\n\t\treturn k, nil\n\t}\n\treturn \"\", errors.New(\"zones: unknown endpoint kind \" + strconv.Quote(s) +\n\t\t\", want rpc, gnoweb, seed, peer, indexer, faucet or explorer\")\n}\n\n// ParseVerification reads an endpoint verdict. \"\" is \"any\" to a filter.\nfunc ParseVerification(s string) (Verification, error) {\n\tswitch v := Verification(TrimSpaces(s)); v {\n\tcase \"\", Unverified, Verified, Flagged:\n\t\treturn v, nil\n\t}\n\treturn \"\", errors.New(\"zones: unknown verification \" + strconv.Quote(s) + \", want verified, unverified or flagged\")\n}\n\n// ValidateSlug accepts 2 to 32 characters of [a-z0-9-], starting and ending\n// with a letter or a digit.\n//\n// Checked at write time rather than escaped at render time, deliberately: the\n// slug is also an index key and a URL path segment, so one carrying a slash or\n// a pipe would break the link and the table as well as the page.\nfunc ValidateSlug(s string) error {\n\tif len(s) \u003c MinSlugLen || len(s) \u003e MaxSlugLen {\n\t\treturn errors.New(\"zones: a slug is \" + strconv.Itoa(MinSlugLen) + \" to \" +\n\t\t\tstrconv.Itoa(MaxSlugLen) + \" characters, got \" + strconv.Quote(s))\n\t}\n\tfor i, r := range s {\n\t\talnum := (r \u003e= 'a' \u0026\u0026 r \u003c= 'z') || (r \u003e= '0' \u0026\u0026 r \u003c= '9')\n\t\tif alnum || (r == '-' \u0026\u0026 i \u003e 0 \u0026\u0026 i \u003c len(s)-1) {\n\t\t\tcontinue\n\t\t}\n\t\treturn errors.New(\"zones: a slug is [a-z0-9-] and starts and ends alphanumeric, got \" + strconv.Quote(s))\n\t}\n\treturn nil\n}\n\n// ValidateChainID accepts what tm2 accepts for a chain id: 1 to 50\n// characters, here narrowed to [A-Za-z0-9._-] so it is safe raw in a table.\nfunc ValidateChainID(s string) error {\n\tif s == \"\" || len(s) \u003e MaxChainIDLen {\n\t\treturn errors.New(\"zones: a chain id is 1 to \" + strconv.Itoa(MaxChainIDLen) + \" characters\")\n\t}\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase r \u003e= 'a' \u0026\u0026 r \u003c= 'z', r \u003e= 'A' \u0026\u0026 r \u003c= 'Z', r \u003e= '0' \u0026\u0026 r \u003c= '9', r == '.', r == '_', r == '-':\n\t\tdefault:\n\t\t\treturn errors.New(\"zones: a chain id is [A-Za-z0-9._-], got \" + strconv.Quote(s))\n\t\t}\n\t}\n\treturn nil\n}\n\n// ValidateInfo checks every field of a zone's description, and returns the\n// first problem it finds.\nfunc ValidateInfo(in Info) error {\n\tif err := ValidateChainID(in.ChainID); err != nil {\n\t\treturn err\n\t}\n\tif err := checkText(\"title\", in.Title, 1, MaxTitleLen); err != nil {\n\t\treturn err\n\t}\n\tif err := checkText(\"description\", in.Description, 0, MaxDescriptionLen); err != nil {\n\t\treturn err\n\t}\n\t// Exact values only: a Kind(\" testnet \") stored as written would match no\n\t// filter (the Registry trims before it validates; a direct caller must).\n\tswitch in.Kind {\n\tcase Mainnet, Testnet, Devnet, Local:\n\tcase \"\":\n\t\treturn errors.New(\"zones: a zone needs a kind: mainnet, testnet, devnet or local\")\n\tdefault:\n\t\treturn errors.New(\"zones: unknown kind \" + strconv.Quote(string(in.Kind)) + \", want mainnet, testnet, devnet or local\")\n\t}\n\tif err := checkURL(\"rpc url\", in.RPCURL, primarySchemes); err != nil {\n\t\treturn err\n\t}\n\t// gnokey's -remote is \u003cscheme\u003e://\u003chost\u003e[:\u003cport\u003e] and reads anything after\n\t// :// as the socket address: a path, a query, a fragment, even a lone\n\t// trailing slash, prints a command that cannot dial (https://host/ dials\n\t// \"host/:443\"). An rpc ENDPOINT may still carry a path.\n\tif _, rest, _ := strings.Cut(in.RPCURL, \"://\"); strings.IndexAny(rest, \"/?#\") \u003e= 0 {\n\t\treturn errors.New(\"zones: the rpc url is \u003cscheme\u003e://\u003chost\u003e[:\u003cport\u003e], what gnokey -remote takes, with no path, not even a trailing slash: \" +\n\t\t\tstrconv.Quote(in.RPCURL))\n\t}\n\tfor _, u := range [][2]string{{\"gnoweb url\", in.GnowebURL}, {\"genesis url\", in.GenesisURL}} {\n\t\tif u[1] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := checkURL(u[0], u[1], webSchemes); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// A loopback or private address names a different machine for every\n\t// reader. Fine for a local zone, which is exactly that; on any other kind\n\t// it points a config generator at whatever answers inside the reader's own\n\t// network.\n\tif in.Kind != Local {\n\t\tfor _, u := range []string{in.RPCURL, in.GnowebURL, in.GenesisURL} {\n\t\t\tif u != \"\" \u0026\u0026 IsPrivateHost(HostOf(RPC, u)) {\n\t\t\t\treturn errors.New(\"zones: \" + strconv.Quote(u) + \" names a private or special-use host; only a local zone lists those\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// HostOf returns the host of an endpoint address: the part between :// and\n// the port or path of a URL, or between @ and the port of a peer. It assumes\n// an address that already passed validation.\nfunc HostOf(kind EndpointKind, addr string) string {\n\tif kind == Seed || kind == Peer {\n\t\t_, hostport, _ := strings.Cut(addr, \"@\")\n\t\tif i := strings.LastIndexByte(hostport, ':'); i \u003e= 0 {\n\t\t\treturn hostport[:i]\n\t\t}\n\t\treturn hostport\n\t}\n\t_, rest, _ := strings.Cut(addr, \"://\")\n\tif i := strings.IndexAny(rest, \"/?\"); i \u003e= 0 {\n\t\trest = rest[:i]\n\t}\n\tif i := strings.LastIndexByte(rest, ':'); i \u003e= 0 {\n\t\trest = rest[:i]\n\t}\n\treturn rest\n}\n\n// IsPrivateHost reports whether host names a machine that is different for\n// every reader, or no machine at all:\n//\n//   - a name with no dot (resolved through the reader's own search domain), or\n//     one under a suffix reserved for local or private use, or that public DNS\n//     does not delegate: .localhost, .local (mDNS), .internal, .localdomain,\n//     .test, .example, .invalid, .lan, .home, .corp, .mail, .intranet,\n//     .private, .alt, .onion and .i2p, the service-discovery and container names\n//     .consul, .lxd, .incus, .docker, .podman, .localnet and .svc, and every\n//     .arpa name, which is infrastructure\n//     and never a public service (.home.arpa, ipv4only.arpa,\n//     default.service.arpa). Hosts files' localhost4, localhost6,\n//     ip6-localhost and ip6-loopback have no dot and fall under the first rule;\n//   - an IPv4 address in a loopback, private, link-local, carrier-grade NAT,\n//     \"this network\", IETF-protocol, documentation, benchmarking, 6to4 relay\n//     anycast, multicast or reserved range;\n//   - anything else shaped like a number but not a valid dotted quad, so an\n//     outside caller is not told 127.1 is public (validation refuses it anyway).\n//\n// It fails closed: anything but a bare host ([A-Za-z0-9.-] only) is private\n// to it. It looks at the string only; a public name that resolves to a private\n// address is beyond what a registry can know.\nfunc IsPrivateHost(host string) bool {\n\t// Fail closed: anything but a bare host (a port, a path, a stray\n\t// character) is not one this can vouch for.\n\tfor i := 0; i \u003c len(host); i++ {\n\t\tif c := host[i]; !(c \u003e= 'a' \u0026\u0026 c \u003c= 'z' || c \u003e= 'A' \u0026\u0026 c \u003c= 'Z' || c \u003e= '0' \u0026\u0026 c \u003c= '9' || c == '.' || c == '-') {\n\t\t\treturn true\n\t\t}\n\t}\n\th := strings.ToLower(strings.TrimSuffix(host, \".\"))\n\tif !strings.Contains(h, \".\") {\n\t\treturn true\n\t}\n\tfor _, suffix := range []string{\".localhost\", \".local\", \".internal\", \".arpa\", \".localdomain\",\n\t\t\".test\", \".example\", \".invalid\", \".lan\", \".home\", \".corp\", \".mail\", \".intranet\", \".private\", \".onion\", \".alt\",\n\t\t\".consul\", \".lxd\", \".incus\", \".docker\", \".podman\", \".localnet\", \".svc\", \".i2p\"} {\n\t\tif strings.HasSuffix(h, suffix) {\n\t\t\treturn true\n\t\t}\n\t}\n\tlabels := strings.Split(h, \".\")\n\tlast := labels[len(labels)-1]\n\tnumeric := strings.Trim(last, \"0123456789\") == \"\" || strings.HasPrefix(last, \"0x\")\n\tif !numeric {\n\t\treturn false\n\t}\n\tif checkIPv4(h) != nil {\n\t\treturn true\n\t}\n\ta, _ := strconv.Atoi(labels[0])\n\tb, _ := strconv.Atoi(labels[1])\n\tc, _ := strconv.Atoi(labels[2])\n\tswitch {\n\tcase a == 0, a == 10, a == 127, a \u003e= 224:\n\t\treturn true\n\tcase a == 169 \u0026\u0026 b == 254, a == 192 \u0026\u0026 b == 168:\n\t\treturn true\n\tcase a == 172 \u0026\u0026 b \u003e= 16 \u0026\u0026 b \u003c= 31, a == 100 \u0026\u0026 b \u003e= 64 \u0026\u0026 b \u003c= 127:\n\t\treturn true\n\tcase a == 192 \u0026\u0026 b == 0 \u0026\u0026 c == 0, a == 198 \u0026\u0026 (b == 18 || b == 19), a == 192 \u0026\u0026 b == 88 \u0026\u0026 c == 99:\n\t\treturn true\n\tcase a == 192 \u0026\u0026 b == 0 \u0026\u0026 c == 2, a == 198 \u0026\u0026 b == 51 \u0026\u0026 c == 100, a == 203 \u0026\u0026 b == 0 \u0026\u0026 c == 113:\n\t\treturn true // documentation ranges\n\t}\n\treturn false\n}\n\n// ValidateEndpoint checks an endpoint's address against the shape its kind\n// needs: a URL for everything but a seed or a peer, which are id@host:port.\nfunc ValidateEndpoint(kind EndpointKind, addr string) error {\n\tswitch kind {\n\tcase RPC:\n\t\tif err := checkURL(\"rpc address\", addr, rpcSchemes); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// gnokey dials a tcp:// remote as host:port, path and all, so one with\n\t\t// a path is undialable, and Canonical would read it as an http URL\n\t\t// that is a different resource.\n\t\tif scheme, rest, _ := strings.Cut(addr, \"://\"); strings.EqualFold(scheme, \"tcp\") \u0026\u0026\n\t\t\tstrings.IndexAny(rest, \"/?\") \u003e= 0 {\n\t\t\treturn errors.New(\"zones: a tcp:// rpc address is host and port only, no path or query\")\n\t\t}\n\t\treturn nil\n\tcase Indexer:\n\t\t// A tx-indexer serves GraphQL subscriptions over a websocket too.\n\t\treturn checkURL(\"indexer address\", addr, rpcSchemes[:4])\n\tcase Gnoweb, Faucet, Explorer:\n\t\treturn checkURL(string(kind)+\" address\", addr, webSchemes)\n\tcase Seed, Peer:\n\t\treturn checkPeer(addr)\n\tcase \"\":\n\t\treturn errors.New(\"zones: an endpoint needs a kind\")\n\t}\n\t// Exact values only. The Parse functions trim a caller's string, so an\n\t// EndpointKind(\" rpc \") would parse, be stored as written, and then match\n\t// no filter: refused here rather than normalised behind the caller's back.\n\treturn errors.New(\"zones: unknown endpoint kind \" + strconv.Quote(string(kind)) +\n\t\t\", want rpc, gnoweb, seed, peer, indexer, faucet or explorer\")\n}\n\n// ValidateLabel accepts an optional single line of up to 64 characters.\nfunc ValidateLabel(s string) error { return checkText(\"label\", s, 0, MaxLabelLen) }\n\n// ValidateReason accepts an optional single line of up to 280 characters.\n// Whether a reason is REQUIRED depends on the decision; see [Registry].\nfunc ValidateReason(s string) error { return checkText(\"reason\", s, 0, MaxReasonLen) }\n\nvar (\n\t// rpcSchemes is what an rpc ENDPOINT may be: a websocket subscriber is a\n\t// real consumer of one.\n\trpcSchemes = []string{\"https\", \"http\", \"wss\", \"ws\", \"tcp\"}\n\t// primarySchemes is what a zone's main RPC may be, narrower on purpose: it\n\t// is what every tool is pointed at first, gnokey's -remote included, and\n\t// gnokey's query client dials http, https and tcp only, so a wss:// main\n\t// RPC would print a command that cannot run.\n\tprimarySchemes = []string{\"https\", \"http\", \"tcp\"}\n\twebSchemes     = []string{\"https\", \"http\"}\n)\n\n// ValidAddress reports whether a is a valid g1 address in the one spelling the\n// chain uses for it: lowercase. bech32 also decodes an all-uppercase string, so\n// IsValid accepts G1ABC…, but every comparison here (curators, proposers,\n// registrants, node ids) is on the string, and an uppercase spelling of a real\n// address would be a second identity for it.\nfunc ValidAddress(a address) bool {\n\treturn a.IsValid() \u0026\u0026 string(a) == strings.ToLower(string(a))\n}\n\n// HasVisible reports whether s has at least one character a reader can see:\n// not a space, not a combining mark, not an invisible format character, not a\n// blank filler. A\n// required title or reason must, or it passes the \"needs a reason\" check and\n// renders blank.\nfunc HasVisible(s string) bool {\n\tfor _, r := range s {\n\t\tif !unicode.IsSpace(r) \u0026\u0026 !unicode.IsMark(r) \u0026\u0026 !unicode.Is(unicode.Cf, r) \u0026\u0026 !isBlankFiller(r) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// isBlankFiller is the handful of characters that are letters or symbols by\n// category and still draw nothing: the Hangul fillers, the blank Braille cell,\n// the musical null notehead, the Egyptian hieroglyph blanks, and the Khmer\n// inherent vowels and the Khitan filler (marks by category, drawn as nothing). Unicode does not class them as format\n// characters, so they need naming.\nfunc isBlankFiller(r rune) bool {\n\tswitch r {\n\tcase 0x115F, 0x1160, 0x3164, 0xFFA0, 0x2800, 0x1D159, 0x17B4, 0x17B5,\n\t\t0x13441, 0x13442, 0x16FE4:\n\t\treturn true\n\t}\n\treturn false\n}\n\n// isSelector is the variation selectors, all three blocks (U+180E, inside the\n// Mongolian range, is a format character and refused as one): invisible on their\n// own, and an invisible difference between two spellings of a name.\nfunc isSelector(r rune) bool {\n\treturn (r \u003e= 0xFE00 \u0026\u0026 r \u003c= 0xFE0F) || (r \u003e= 0xE0100 \u0026\u0026 r \u003c= 0xE01EF) || (r \u003e= 0x180B \u0026\u0026 r \u003c= 0x180F)\n}\n\n// selects reports whether a variation selector modifies the character before\n// it, the one place it is text rather than an invisible difference: the\n// emoji and text presentation selectors after a symbol (a phone writes ❤️ as\n// U+2764 U+FE0F), the Mongolian free variation selectors after a Mongolian\n// letter, and an ideographic variation sequence after a Han ideograph. A\n// selector cannot make a badge: every symbol that looks like one is refused on\n// its own.\nfunc selects(base, sel rune) bool {\n\tswitch {\n\tcase sel == 0xFE0E || sel == 0xFE0F:\n\t\t// The symbols, and the five emoji whose base is punctuation or a\n\t\t// letter by category: ‼ ⁉ ℹ 〰 〽.\n\t\treturn unicode.In(base, unicode.So, unicode.Sm) ||\n\t\t\tbase == 0x203C || base == 0x2049 || base == 0x2139 || base == 0x3030 || base == 0x303D\n\tcase sel \u003e= 0x180B \u0026\u0026 sel \u003c= 0x180F \u0026\u0026 sel != 0x180E:\n\t\treturn base \u003e= 0x1820 \u0026\u0026 base \u003c= 0x18AA\n\tcase sel \u003e= 0xE0100 \u0026\u0026 sel \u003c= 0xE01EF:\n\t\treturn unicode.Is(unicode.Han, base)\n\t}\n\treturn false\n}\n\n// isBadge is the status glyphs Render draws, and their look-alikes, refused in\n// free text so a title cannot claim \"✔ official\" beside a pending badge.\nfunc isBadge(r rune) bool {\n\tswitch r {\n\tcase 0x2705, 0x26A0, 0x23F3, 0x274C, 0x23F9, // ✅ ⚠ ⏳ ❌ ⏹, what Render draws\n\t\t0x2713, 0x2714, 0x2611, 0x1F5F8, 0x1F5F9, 0x1F197, // check marks, 🆗\n\t\t0x2716, 0x2717, 0x2718, 0x2715, 0x274E, 0x2612, 0x1F6AB, 0x26D4, 0x1F6D1, // crosses, no-entry\n\t\t0x1F5F4, 0x1F5F5, 0x1F5F6, 0x1F5F7, // ballot x and ballot box with x\n\t\t0x231B, 0x23F8, 0x23FA, // ⌛ ⏸ ⏺\n\t\t0x1FBB1, 0x237B, 0x10102, // more check marks\n\t\t0x1F5D9, 0x2A2F, 0x2573, 0x2BBD, 0x2BBE, 0x2BBF, // more crosses and ballot boxes\n\t\t0x29D6, 0x29D7, // hourglasses\n\t\t0x2613, 0x2A09, // saltire, n-ary times (× itself is everyday text: 1920×1080)\n\t\t0x22A0, 0x2327, 0x1F147, 0x1F187, 0x2297, 0x2A02, 0x1F167, // boxed and circled crosses\n\t\t0x1F6C7, 0x2298, 0x29B8, // prohibition signs\n\t\t0x24CD, 0x24E7, 0x24B3, 0x1F127, 0x29BB, 0x2A34, 0x2A35, 0x2A37, 0x292B, 0x292C, // circled, parenthesized and crossing x\n\t\t0x1F532, 0x1F533, // square buttons, beside ⏹\n\t\t0x26DD, 0x1F5BE, 0x2B59, 0x2A36, 0x26D2, 0x1FBC0, 0x1D145, 0x26CC, 0x2A3B, // more boxed, circled and heavy crosses\n\t\t0x1FBBD, 0x1F6AD, 0x1F6AF, 0x1F6B1, 0x1F6B3, 0x1F6B7, 0x1F4F5, 0x1F51E, 0x1F10D, 0x1F10F, 0x1F16E: // more no-entry signs\n\t\treturn true\n\t}\n\treturn r \u003e= 0x1F7A8 \u0026\u0026 r \u003c= 0x1F7AE // the geometric crosses beside ✖\n}\n\n// checkText bounds a free-text field by runes (so at most four times as many\n// bytes) and keeps it to one line of text that shows what it stores:\n//\n//   - no control character: C0, DEL, C1, U+2028, U+2029. Several are line\n//     breaks that ui.Inline folds to a space, the rest draw nothing; either\n//     way the text shown would not be the text stored.\n//   - no invisible or undrawable character: every format character (Unicode\n//     Cf, which covers the bidi controls and isolates, the zero-width\n//     characters, U+061C, word joiners, tags), every character that is not\n//     graphic (private use, unassigned, noncharacters), the blank fillers, a\n//     variation selector except right after a base it modifies (selects), the\n//     combining grapheme joiner. A title made of them\n//     would pass the length check and render blank or as a box.\n//   - no enclosing mark, which draws a badge's frame around any character,\n//     and no run of more than four nonspacing marks, which stack over\n//     neighbouring lines (a spacing mark takes its own width and ends a run,\n//     so Devanagari, Gurmukhi, Burmese and Tibetan words pass), and none of\n//     the status glyphs a Render draws.\n//   - valid UTF-8, because the page would show U+FFFD for a byte stored raw.\n//\n// Refused rather than stripped, so what is stored is what is shown.\nfunc checkText(field, s string, min, max int) error {\n\t// No rune is more than four bytes: anything longer cannot be within max\n\t// characters, and is refused before a per-rune scan the writer pays for.\n\tif len(s) \u003e 4*max {\n\t\treturn errors.New(\"zones: the \" + field + \" is longer than \" + strconv.Itoa(max) + \" characters\")\n\t}\n\tn, marks, prev := 0, 0, rune(0)\n\tfor i, r := range s {\n\t\tif r == utf8.RuneError {\n\t\t\tif _, size := utf8.DecodeRuneInString(s[i:]); size \u003c= 1 {\n\t\t\t\treturn errors.New(\"zones: the \" + field + \" is not valid UTF-8\")\n\t\t\t}\n\t\t}\n\t\tif r \u003c 0x20 || (r \u003e= 0x7f \u0026\u0026 r \u003c= 0x9f) || r == 0x2028 || r == 0x2029 {\n\t\t\treturn errors.New(\"zones: the \" + field + \" contains a control character\")\n\t\t}\n\t\tif unicode.Is(unicode.Cf, r) || isBlankFiller(r) || r == 0x034F || (isSelector(r) \u0026\u0026 !selects(prev, r)) {\n\t\t\treturn errors.New(\"zones: the \" + field + \" contains an invisible or bidi character\")\n\t\t}\n\t\tif !unicode.IsGraphic(r) \u0026\u0026 !unicode.IsSpace(r) {\n\t\t\t// The chain's unicode tables are Unicode 15.0, so a character\n\t\t\t// assigned since then is refused here even where gno test (which\n\t\t\t// uses the host's newer tables) accepts it.\n\t\t\treturn errors.New(\"zones: the \" + field + \" contains \" + strconv.QuoteToASCII(string(r)) +\n\t\t\t\t\", which this chain does not draw: private use, a noncharacter, or unassigned in its Unicode 15.0 tables\")\n\t\t}\n\t\tif isBadge(r) {\n\t\t\treturn errors.New(\"zones: the \" + field + \" contains a status glyph a Render draws, or a look-alike of one: \" + strconv.Quote(string(r)))\n\t\t}\n\t\tif unicode.Is(unicode.Me, r) {\n\t\t\t// An enclosing mark draws a frame around what precedes it: !\\u20E4\n\t\t\t// is a warning triangle, v\\u20DE a checked box. No living script\n\t\t\t// needs one, and keycaps need U+FE0F, refused above.\n\t\t\treturn errors.New(\"zones: the \" + field + \" contains an enclosing mark, which draws a status glyph's frame\")\n\t\t}\n\t\tif unicode.Is(unicode.Mn, r) {\n\t\t\tmarks++\n\t\t\tif marks \u003e 4 {\n\t\t\t\treturn errors.New(\"zones: the \" + field + \" stacks more than four combining marks\")\n\t\t\t}\n\t\t} else {\n\t\t\tmarks = 0\n\t\t}\n\t\tprev = r\n\t\tn++\n\t\tif n \u003e max {\n\t\t\tbreak // refused below; no need to classify the rest\n\t\t}\n\t}\n\tif n \u003e max {\n\t\treturn errors.New(\"zones: the \" + field + \" is longer than \" + strconv.Itoa(max) + \" characters\")\n\t}\n\tif n \u003c min {\n\t\treturn errors.New(\"zones: the \" + field + \" is \" + strconv.Itoa(min) + \" to \" +\n\t\t\tstrconv.Itoa(max) + \" characters, got \" + strconv.Itoa(n))\n\t}\n\tif s != \"\" \u0026\u0026 !HasVisible(s) {\n\t\treturn errors.New(\"zones: the \" + field + \" has nothing visible in it\")\n\t}\n\treturn nil\n}\n\n// checkURL accepts scheme://host[:port][/path][?query], in visible ASCII (no\n// space, no control), with no character that could close a markdown link or\n// open a new construct around it. Narrower than RFC 3986 on purpose: these\n// URLs are rendered as links and copied into config files, and neither wants\n// a quote or a bracket. Also refused:\n//\n//   - a fragment (#): it is never sent to the server, so every #1, #2 would be\n//     another listing of the same endpoint.\n//   - a % not followed by two hex digits, and an \u0026name; shape: the link\n//     sanitizer re-encodes both, so the href would differ from the text shown.\nfunc checkURL(field, s string, schemes []string) error {\n\tif s == \"\" {\n\t\treturn errors.New(\"zones: the \" + field + \" is empty\")\n\t}\n\tif len(s) \u003e MaxURLLen {\n\t\treturn errors.New(\"zones: the \" + field + \" is longer than \" + strconv.Itoa(MaxURLLen) + \" bytes\")\n\t}\n\tn := len(s)\n\tfor i := 0; i \u003c n; i++ {\n\t\tc := s[i]\n\t\tif c \u003c= ' ' || c \u003e= 0x7f || isURLForbidden(c) {\n\t\t\tr, _ := utf8.DecodeRuneInString(s[i:]) // the character, not its first byte\n\t\t\treturn errors.New(\"zones: the \" + field + \" contains \" + strconv.QuoteRune(r) + \": \" + strconv.Quote(s))\n\t\t}\n\t\tif c == '%' \u0026\u0026 (i+2 \u003e= n || !isHex(s[i+1]) || !isHex(s[i+2])) {\n\t\t\treturn errors.New(\"zones: the \" + field + \" has a % that is not followed by two hex digits: \" + strconv.Quote(s))\n\t\t}\n\t\tif c == '%' \u0026\u0026 isUnreserved(unhex(s[i+1])\u003c\u003c4|unhex(s[i+2])) {\n\t\t\t// %7E and ~ are the same URL (RFC 3986): one spelling, so two\n\t\t\t// listings cannot be the same endpoint.\n\t\t\treturn errors.New(\"zones: the \" + field + \" escapes a character that needs no escaping: \" + strconv.Quote(s))\n\t\t}\n\t\tif c == '\u0026' \u0026\u0026 isEntity(s[i+1:]) {\n\t\t\treturn errors.New(\"zones: the \" + field + \" contains an HTML entity shape: \" + strconv.Quote(s))\n\t\t}\n\t}\n\tscheme, rest, ok := strings.Cut(s, \"://\")\n\tif !ok {\n\t\treturn errors.New(\"zones: the \" + field + \" needs a scheme (\" + strings.Join(schemes, \", \") + \"): \" + strconv.Quote(s))\n\t}\n\t// A scheme is case-insensitive, so HTTPS:// is https://; Canonical lowercases\n\t// it the same way, which is what makes the two one endpoint.\n\tknown := false\n\tfor _, sc := range schemes {\n\t\tif strings.ToLower(scheme) == sc {\n\t\t\tknown = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !known {\n\t\treturn errors.New(\"zones: the \" + field + \" scheme is \" + strconv.Quote(scheme) + \", want one of \" +\n\t\t\tstrings.Join(schemes, \", \"))\n\t}\n\tauthority := rest\n\tif i := strings.IndexAny(authority, \"/?#\"); i \u003e= 0 {\n\t\tauthority = authority[:i]\n\t\t// A \".\" or \"..\" path segment is resolved away by every browser and by\n\t\t// RFC 3986, so it would be a second spelling of another URL.\n\t\tpath := rest[i:]\n\t\tif j := strings.IndexByte(path, '?'); j \u003e= 0 {\n\t\t\tpath = path[:j]\n\t\t}\n\t\tfor _, seg := range strings.Split(path, \"/\") {\n\t\t\tif seg == \".\" || seg == \"..\" {\n\t\t\t\treturn errors.New(\"zones: the \" + field + \" has a . or .. path segment: \" + strconv.Quote(s))\n\t\t\t}\n\t\t}\n\t}\n\tif strings.Contains(authority, \"@\") {\n\t\treturn errors.New(\"zones: the \" + field + \" carries credentials: \" + strconv.Quote(s))\n\t}\n\thost, port := authority, \"\"\n\tif i := strings.LastIndexByte(authority, ':'); i \u003e= 0 {\n\t\thost, port = authority[:i], authority[i+1:]\n\t\tif err := checkPort(port); err != nil {\n\t\t\treturn errors.New(\"zones: the \" + field + \"'s port is 1 to 65535, got \" + strconv.Quote(port))\n\t\t}\n\t}\n\tif host == \"\" {\n\t\treturn errors.New(\"zones: the \" + field + \" has no host: \" + strconv.Quote(s))\n\t}\n\tif err := checkHost(host); err != nil {\n\t\treturn errors.New(\"zones: the \" + field + \"'s host is a DNS name or an IPv4 address, got \" + strconv.Quote(host))\n\t}\n\treturn nil\n}\n\n// checkHost accepts a DNS name or a dotted IPv4 address.\n//\n// A DNS name is labels of 1 to 63 characters of [A-Za-z0-9-], alphanumeric at\n// both ends, at most 253 characters in all, with one optional terminal dot.\n// Anything a browser would parse as IPv4 must BE a valid dotted-quad address:\n// under the WHATWG URL parser a host whose last label is numeric (decimal, or\n// 0x hex) is an IPv4 address, so 0x7f.1 opens 127.0.0.1 and a.1 is no URL at\n// all. A last label starting 0x is held to the address rule even when the rest\n// is not hex (a browser would take 0xyz as a name): stricter, never looser.\n// An address takes no terminal dot. Bracketed IPv6 is refused, deliberately: it is the one host shape that\n// needs characters every other field here refuses, and no zone needs it yet.\nfunc checkHost(host string) error {\n\tname := strings.TrimSuffix(host, \".\")\n\tif name == \"\" || len(name) \u003e 253 {\n\t\treturn errors.New(\"bad host\")\n\t}\n\tlabels := strings.Split(name, \".\")\n\tlast := strings.ToLower(labels[len(labels)-1])\n\tif strings.Trim(last, \"0123456789\") == \"\" || strings.HasPrefix(last, \"0x\") {\n\t\t// No terminal dot on an address: browsers accept 1.2.3.4. but Go's\n\t\t// dialer, so gnokey and tm2, look it up as a name and fail.\n\t\tif name != host {\n\t\t\treturn errors.New(\"bad ipv4\")\n\t\t}\n\t\treturn checkIPv4(name)\n\t}\n\tfor _, label := range labels {\n\t\tif label == \"\" || len(label) \u003e 63 || label[0] == '-' || label[len(label)-1] == '-' {\n\t\t\treturn errors.New(\"bad host\")\n\t\t}\n\t\tfor _, r := range label {\n\t\t\tswitch {\n\t\t\tcase r \u003e= 'a' \u0026\u0026 r \u003c= 'z', r \u003e= 'A' \u0026\u0026 r \u003c= 'Z', r \u003e= '0' \u0026\u0026 r \u003c= '9', r == '-':\n\t\t\tdefault:\n\t\t\t\treturn errors.New(\"bad host\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc checkIPv4(s string) error {\n\tparts := strings.Split(s, \".\")\n\tif len(parts) != 4 {\n\t\treturn errors.New(\"bad ipv4\")\n\t}\n\tfor _, p := range parts {\n\t\tif p == \"\" || len(p) \u003e 3 || strings.Trim(p, \"0123456789\") != \"\" || (len(p) \u003e 1 \u0026\u0026 p[0] == '0') {\n\t\t\treturn errors.New(\"bad ipv4\")\n\t\t}\n\t\tif n, _ := strconv.Atoi(p); n \u003e 255 {\n\t\t\treturn errors.New(\"bad ipv4\")\n\t\t}\n\t}\n\treturn nil\n}\n\n// checkPort accepts 1 to 65535, decimal digits only, no leading zero. Digits\n// only because strconv.Atoi takes a sign, and +443 is no port to url.Parse,\n// to a browser, or to tm2's peer parser.\nfunc checkPort(port string) error {\n\tif port == \"\" || strings.Trim(port, \"0123456789\") != \"\" || port[0] == '0' || len(port) \u003e 5 {\n\t\treturn errors.New(\"bad port\")\n\t}\n\tif p, _ := strconv.Atoi(port); p \u003e 65535 {\n\t\treturn errors.New(\"bad port\")\n\t}\n\treturn nil\n}\n\n// isURLForbidden is the visible ASCII a URL here may not carry: what could\n// close a markdown link or open a construct around it, and a fragment.\nfunc isURLForbidden(c byte) bool {\n\tswitch c {\n\tcase '\u003c', '\u003e', '\"', '\\'', '`', '(', ')', '[', ']', '{', '}', '|', '\\\\', '^', '#':\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc isHex(c byte) bool {\n\treturn (c \u003e= '0' \u0026\u0026 c \u003c= '9') || (c \u003e= 'a' \u0026\u0026 c \u003c= 'f') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'F')\n}\n\nfunc unhex(c byte) byte {\n\tswitch {\n\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn c - '0'\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'f':\n\t\treturn c - 'a' + 10\n\t}\n\treturn c - 'A' + 10\n}\n\n// isUnreserved is RFC 3986's unreserved set: what a URL never needs to escape.\nfunc isUnreserved(c byte) bool {\n\treturn (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9') ||\n\t\tc == '-' || c == '.' || c == '_' || c == '~'\n}\n\n// isEntity reports whether s starts with what an HTML entity would follow an\n// ampersand with: a run of [A-Za-z0-9#] closed by a semicolon.\nfunc isEntity(s string) bool {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c == ';':\n\t\t\treturn i \u003e 0\n\t\tcase (c \u003e= 'a' \u0026\u0026 c \u003c= 'z') || (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z') || (c \u003e= '0' \u0026\u0026 c \u003c= '9') || c == '#':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}\n\n// TrimSpaces trims spaces (Unicode Zs: U+0020, no-break space, U+3000 and the\n// like) and tabs from both ends, and nothing else. strings.TrimSpace also\n// strips line breaks and separators (CR, LF, U+0085, U+2028), which free text\n// refuses: trimmed first, they would be accepted silently, changed. A line\n// break a caller types reaches the validator and is refused there.\nfunc TrimSpaces(s string) string {\n\treturn strings.TrimFunc(s, func(r rune) bool { return r == '\\t' || unicode.Is(unicode.Zs, r) })\n}\n\n// lowerAuthority lowercases a URL's scheme and host, both case-insensitive,\n// and leaves the path and query as typed. Stored that way because gno's link\n// sanitizer is not case-insensitive (an HTTPS:// link would render with an\n// empty href), and so every later lowercasing of the host (Canonical,\n// IsPrivateHost) finds nothing to change: a scan, no copy. ASCII only, see\n// asciiLower.\nfunc lowerAuthority(addr string) string {\n\tscheme, rest, ok := strings.Cut(addr, \"://\")\n\tif !ok {\n\t\treturn addr\n\t}\n\thost, tail := rest, \"\"\n\tif i := strings.IndexAny(rest, \"/?\"); i \u003e= 0 {\n\t\thost, tail = rest[:i], rest[i:]\n\t}\n\treturn asciiLower(scheme) + \"://\" + asciiLower(host) + tail\n}\n\n// trimEmptyTail drops an empty tail from a URL, by Canonical's own rules: an\n// empty query's \"?\" (when it is the tail's only \"?\") and a bare \"/\". gnokey\n// would dial a host with them attached, so an endpoint is not stored with them\n// (nor a zone's gnoweb and genesis URLs, which trimInfo repairs the same way, as\n// a browser's address bar writes https://host/; its main RPC is refused with\n// them, ValidateInfo). Canonical\n// drops both too, so Canonical(trimEmptyTail(x)) == Canonical(x), and a check\n// made on what a caller typed holds for what is stored. A path is kept as\n// typed otherwise (\"/?q\" stays: Canonical reads it as \"?q\", a browser too).\nfunc trimEmptyTail(addr string) string {\n\tscheme, rest, ok := strings.Cut(addr, \"://\")\n\tif !ok {\n\t\treturn addr\n\t}\n\ti := strings.IndexAny(rest, \"/?\")\n\tif i \u003c 0 {\n\t\treturn addr\n\t}\n\tauthority, tail := rest[:i], rest[i:]\n\tif strings.HasSuffix(tail, \"?\") \u0026\u0026 strings.Count(tail, \"?\") == 1 {\n\t\ttail = tail[:len(tail)-1]\n\t}\n\tif tail == \"/\" {\n\t\ttail = \"\"\n\t}\n\treturn scheme + \"://\" + authority + tail\n}\n\n// asciiLower lowercases A to Z and nothing else. strings.ToLower also folds\n// a few non-ASCII letters into ASCII ones (U+212A KELVIN SIGN to k, U+0130 to\n// i), which would turn a URL validation refuses into one it accepts, under a\n// spelling the caller never typed.\nfunc asciiLower(s string) string {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif c := s[i]; c \u003e= 'A' \u0026\u0026 c \u003c= 'Z' {\n\t\t\tb := []byte(s)\n\t\t\tfor j := i; j \u003c len(b); j++ {\n\t\t\t\tif b[j] \u003e= 'A' \u0026\u0026 b[j] \u003c= 'Z' {\n\t\t\t\t\tb[j] += 'a' - 'A'\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn string(b)\n\t\t}\n\t}\n\treturn s\n}\n\n// Canonical is the form two addresses are compared in, so one endpoint cannot\n// be listed twice under two spellings: the scheme and the host lowercased (both\n// are case-insensitive), the host's terminal dot dropped, the scheme's default\n// port dropped (:443 for https and wss, :80 for http and ws), an empty path\n// before a query dropped, an empty query's \"?\" and a bare \"/\" dropped, the hex\n// digits of every %XX escape uppercased, and for an rpc endpoint tcp:// read as\n// http://, which is how gnokey dials it. A path or a query that says something\n// is kept as typed: those are case-sensitive and name different resources. A\n// peer is lowercased whole and loses its host's terminal dot: its node id is\n// lowercase bech32 and its host is a name.\nfunc Canonical(kind EndpointKind, addr string) string {\n\tif kind == Seed || kind == Peer {\n\t\tid, hostport, ok := strings.Cut(asciiLower(addr), \"@\")\n\t\tif !ok {\n\t\t\treturn asciiLower(addr)\n\t\t}\n\t\tif i := strings.LastIndexByte(hostport, ':'); i \u003e= 0 {\n\t\t\thostport = strings.TrimSuffix(hostport[:i], \".\") + hostport[i:]\n\t\t}\n\t\treturn id + \"@\" + hostport\n\t}\n\tscheme, rest, ok := strings.Cut(addr, \"://\")\n\tif !ok {\n\t\treturn addr\n\t}\n\tscheme = asciiLower(scheme)\n\tif kind == RPC \u0026\u0026 scheme == \"tcp\" {\n\t\tscheme = \"http\"\n\t}\n\ti := strings.IndexAny(rest, \"/?\")\n\tif i \u003c 0 {\n\t\ti = len(rest)\n\t}\n\tauthority, tail := asciiLower(rest[:i]), rest[i:]\n\thost, port := authority, \"\"\n\tif j := strings.LastIndexByte(authority, ':'); j \u003e= 0 {\n\t\thost, port = authority[:j], authority[j+1:]\n\t}\n\thost = strings.TrimSuffix(host, \".\")\n\tswitch {\n\tcase port == \"443\" \u0026\u0026 (scheme == \"https\" || scheme == \"wss\"),\n\t\tport == \"80\" \u0026\u0026 (scheme == \"http\" || scheme == \"ws\"):\n\t\tport = \"\"\n\t}\n\tif port != \"\" {\n\t\thost += \":\" + port\n\t}\n\tif strings.HasSuffix(tail, \"?\") \u0026\u0026 strings.Count(tail, \"?\") == 1 {\n\t\ttail = tail[:len(tail)-1] // an empty query, not a query ending in \"?\"\n\t}\n\tif strings.HasPrefix(tail, \"/?\") {\n\t\ttail = tail[1:]\n\t}\n\tif tail == \"/\" {\n\t\ttail = \"\"\n\t}\n\treturn scheme + \"://\" + host + upperEscapes(tail)\n}\n\n// upperEscapes uppercases the two hex digits of every %XX in s.\nfunc upperEscapes(s string) string {\n\tif !strings.Contains(s, \"%\") {\n\t\treturn s\n\t}\n\tb := []byte(s)\n\tfor i := 0; i+2 \u003c len(b); i++ {\n\t\tif b[i] == '%' {\n\t\t\tb[i+1] = toUpperHex(b[i+1])\n\t\t\tb[i+2] = toUpperHex(b[i+2])\n\t\t}\n\t}\n\treturn string(b)\n}\n\nfunc toUpperHex(c byte) byte {\n\tif c \u003e= 'a' \u0026\u0026 c \u003c= 'f' {\n\t\treturn c - 'a' + 'A'\n\t}\n\treturn c\n}\n\n// checkPeer accepts a tm2 p2p address: \u003cnode id\u003e@\u003chost\u003e:\u003cport\u003e, where the node\n// id is the node's g1 address, as `gnoland secrets get node_id` prints it.\nfunc checkPeer(s string) error {\n\tid, hostport, ok := strings.Cut(s, \"@\")\n\tif !ok {\n\t\treturn errors.New(\"zones: a peer is \u003cnode id\u003e@\u003chost\u003e:\u003cport\u003e, got \" + strconv.Quote(s))\n\t}\n\tif len(s) \u003e MaxURLLen {\n\t\treturn errors.New(\"zones: a peer is longer than \" + strconv.Itoa(MaxURLLen) + \" bytes\")\n\t}\n\t// Lowercase only: bech32 also decodes an all-uppercase id, but tm2 compares\n\t// node ids byte for byte when it dials, so an uppercase one never connects.\n\tif !ValidAddress(address(id)) {\n\t\treturn errors.New(\"zones: a peer's node id is a lowercase g1 address, got \" + strconv.Quote(id))\n\t}\n\ti := strings.LastIndexByte(hostport, ':')\n\tif i \u003c= 0 {\n\t\treturn errors.New(\"zones: a peer needs a port: \" + strconv.Quote(s))\n\t}\n\thost, port := hostport[:i], hostport[i+1:]\n\tif err := checkPort(port); err != nil {\n\t\treturn errors.New(\"zones: a peer's port is 1 to 65535, got \" + strconv.Quote(port))\n\t}\n\tif err := checkHost(host); err != nil {\n\t\treturn errors.New(\"zones: a peer's host is a DNS name or an IPv4 address, got \" + strconv.Quote(host))\n\t}\n\treturn nil\n}\n"},{"name":"zones_test.gno","body":"package zones\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A real node id, from mainnet's published persistent_peers.\nconst nodeID = \"g15rcv5yqef3kvnmueqvkyw8y05sd40jz9p3n5su\"\n\nfunc TestValidateSlug(t *testing.T) {\n\tcases := []struct {\n\t\tin, err string\n\t}{\n\t\t{\"mainnet\", \"\"},\n\t\t{\"onyx\", \"\"},\n\t\t{\"moul-staging\", \"\"},\n\t\t{\"t1\", \"\"},\n\t\t{\"a\", \"2 to 32\"},\n\t\t{strings.Repeat(\"a\", 33), \"2 to 32\"},\n\t\t{\"Mainnet\", \"[a-z0-9-]\"},\n\t\t{\"-onyx\", \"[a-z0-9-]\"},\n\t\t{\"onyx-\", \"[a-z0-9-]\"},\n\t\t{\"on_yx\", \"[a-z0-9-]\"},\n\t\t{\"on/yx\", \"[a-z0-9-]\"},\n\t\t{\"on|yx\", \"[a-z0-9-]\"},\n\t}\n\tfor _, c := range cases {\n\t\terr := ValidateSlug(c.in)\n\t\tif c.err == \"\" {\n\t\t\tuassert.NoError(t, err, c.in)\n\t\t} else {\n\t\t\tuassert.ErrorContains(t, err, c.err, c.in)\n\t\t}\n\t}\n}\n\nfunc TestValidateChainID(t *testing.T) {\n\tuassert.NoError(t, ValidateChainID(\"gnoland-1\"))\n\tuassert.NoError(t, ValidateChainID(\"moulstaging-1\"))\n\tuassert.NoError(t, ValidateChainID(\"dev\"))\n\tuassert.NoError(t, ValidateChainID(\"test_5.x\"))\n\tuassert.ErrorContains(t, ValidateChainID(\"\"), \"1 to 50\")\n\tuassert.ErrorContains(t, ValidateChainID(strings.Repeat(\"x\", 51)), \"1 to 50\")\n\tuassert.ErrorContains(t, ValidateChainID(\"gno land\"), \"[A-Za-z0-9._-]\")\n\tuassert.ErrorContains(t, ValidateChainID(\"a|b\"), \"[A-Za-z0-9._-]\")\n}\n\nfunc TestValidateEndpoint(t *testing.T) {\n\tcases := []struct {\n\t\tkind EndpointKind\n\t\taddr string\n\t\terr  string\n\t}{\n\t\t{RPC, \"https://rpc.gno.land\", \"\"},\n\t\t{RPC, \"https://rpc.gno.land:443\", \"\"},\n\t\t{RPC, \"http://127.0.0.1:26657\", \"\"},\n\t\t{RPC, \"tcp://127.0.0.1:26657\", \"\"},\n\t\t{RPC, \"wss://rpc.gno.land/websocket\", \"\"},\n\t\t{Gnoweb, \"https://gno.land\", \"\"},\n\t\t{Indexer, \"https://indexer.gno.land/graphql/query\", \"\"},\n\t\t{Faucet, \"https://onyx.testnets.gno.land/faucet\", \"\"},\n\t\t{Explorer, \"https://gnoscan.io/?chainId=onyx-1\", \"\"},\n\t\t{Seed, nodeID + \"@seed-1.gno.land:26656\", \"\"},\n\t\t{Peer, nodeID + \"@10.0.0.1:26656\", \"\"},\n\n\t\t{RPC, \"\", \"is empty\"},\n\t\t{RPC, \"rpc.gno.land\", \"needs a scheme\"},\n\t\t{RPC, \"ftp://rpc.gno.land\", \"scheme is\"},\n\t\t{Gnoweb, \"tcp://gno.land\", \"scheme is\"},\n\t\t{RPC, \"https://\", \"has no host\"},\n\t\t{RPC, \"https:///path\", \"has no host\"},\n\t\t{RPC, \"https://user:pass@rpc.gno.land\", \"credentials\"},\n\t\t{Gnoweb, \"https://gno.land/a b\", \"contains\"},\n\t\t{Gnoweb, \"https://gno.land/)evil\", \"contains\"},\n\t\t{Gnoweb, \"https://gno.land/[x]\", \"contains\"},\n\t\t{Gnoweb, \"https://gno.land/\\\"x\", \"contains\"},\n\t\t{Gnoweb, \"https://gno.land/é\", \"contains\"},\n\t\t{Gnoweb, \"https://gno.land/\" + strings.Repeat(\"a\", MaxURLLen), \"longer than\"},\n\n\t\t{RPC, \"https://:26657\", \"has no host\"},\n\t\t{RPC, \"https://host:not-a-port\", \"port is 1 to 65535\"},\n\t\t{RPC, \"https://host:99999\", \"port is 1 to 65535\"},\n\t\t{RPC, \"https://host:\", \"port is 1 to 65535\"},\n\t\t{RPC, \"https://ho_st\", \"DNS name\"},\n\t\t{RPC, \"https://[::1]:26657\", \"contains\"},\n\t\t{RPC, \"https://rpc.gno.land:443/path?x=1\", \"\"},\n\t\t{RPC, \"https://rpc.gno.land:443/path?x=1#f\", \"contains\"}, // a fragment is never sent: no second listing\n\t\t{RPC, \"https://rpc.gno.land:+443\", \"port is 1 to 65535\"},\n\t\t{Gnoweb, \"https://gno.land/%zz\", \"two hex digits\"},\n\t\t{Gnoweb, \"https://gno.land/%2\", \"two hex digits\"},\n\t\t{Gnoweb, \"https://gno.land/%2F\", \"\"},\n\t\t{Gnoweb, \"https://gno.land/?a=1\u0026b=2\", \"\"},\n\t\t{Gnoweb, \"https://gno.land/?a=1\u0026amp;b=2\", \"entity\"},\n\t\t{Gnoweb, \"https://0x7f.1\", \"DNS name\"},\n\t\t{Gnoweb, \"https://a.1\", \"DNS name\"},\n\t\t{Gnoweb, \"https://foo.123\", \"DNS name\"},\n\t\t{Gnoweb, \"https://1.2.3.4\", \"\"},\n\t\t{Peer, \"G15RCV5YQEF3KVNMUEQVKYW8Y05SD40JZ9P3N5SU@seed-1.gno.land:26656\", \"lowercase g1 address\"},\n\t\t{Peer, nodeID + \"@seed-1.gno.land:+26656\", \"1 to 65535\"},\n\t\t{Peer, nodeID + \"@\" + strings.Repeat(\"a.\", 120) + \"example:26656\", \"longer than\"},\n\t\t{RPC, \"https://rpc.gno.land.\", \"\"},\n\t\t{RPC, \"http://10.0.0.1:26657\", \"\"},\n\t\t{RPC, \"http://localhost:26657\", \"\"},\n\t\t{RPC, \"https://-.example.com\", \"DNS name\"},\n\t\t{RPC, \"https://bad-.example.com\", \"DNS name\"},\n\t\t{RPC, \"https://-bad.example.com\", \"DNS name\"},\n\t\t{RPC, \"https://foo..example.com\", \"DNS name\"},\n\t\t{RPC, \"https://.example.com\", \"DNS name\"},\n\t\t{RPC, \"https://example..\", \"DNS name\"},\n\t\t{RPC, \"https://\" + strings.Repeat(\"a\", 64) + \".example.com\", \"DNS name\"},\n\t\t{RPC, \"https://\" + strings.Repeat(\"a\", 63) + \".example.com\", \"\"},\n\t\t{RPC, \"http://300.1.1.1\", \"DNS name\"},\n\t\t{RPC, \"http://1.2.3\", \"DNS name\"},\n\t\t{RPC, \"http://01.2.3.4\", \"DNS name\"},\n\t\t{Peer, nodeID + \"@bad-.example.com:26656\", \"DNS name\"},\n\n\t\t{Peer, \"seed-1.gno.land:26656\", \"\u003cnode id\u003e@\"},\n\t\t{Peer, \"nope@seed-1.gno.land:26656\", \"g1 address\"},\n\t\t{Peer, nodeID + \"@seed-1.gno.land\", \"needs a port\"},\n\t\t{Peer, nodeID + \"@:26656\", \"needs a port\"},\n\t\t{Peer, nodeID + \"@seed-1.gno.land:0\", \"1 to 65535\"},\n\t\t{Peer, nodeID + \"@seed-1.gno.land:65536\", \"1 to 65535\"},\n\t\t{Peer, nodeID + \"@seed-1.gno.land:080\", \"1 to 65535\"},\n\t\t{Peer, nodeID + \"@seed-1.gno.land:port\", \"1 to 65535\"},\n\t\t{Seed, nodeID + \"@seed_1.gno.land:26656\", \"DNS name\"},\n\t\t{Seed, nodeID + \"@[::1]:26656\", \"DNS name\"},\n\n\t\t{RPC, \"HTTPS://rpc.gno.land\", \"\"},\n\t\t{Gnoweb, \"Https://gno.land\", \"\"},\n\t\t{\" rpc \", \"not a url\", \"unknown endpoint kind\"},\n\t\t{\"RPC\", \"https://rpc.gno.land\", \"unknown endpoint kind\"},\n\t\t{\"\", \"https://gno.land\", \"needs a kind\"},\n\t\t{\"grpc\", \"https://gno.land\", \"unknown endpoint kind\"},\n\t}\n\tfor _, c := range cases {\n\t\terr := ValidateEndpoint(c.kind, c.addr)\n\t\tlabel := string(c.kind) + \" \" + c.addr\n\t\tif c.err == \"\" {\n\t\t\tuassert.NoError(t, err, label)\n\t\t} else {\n\t\t\tuassert.ErrorContains(t, err, c.err, label)\n\t\t}\n\t}\n}\n\nfunc TestValidateInfo(t *testing.T) {\n\tok := Info{ChainID: \"onyx-1\", Title: \"Onyx\", Kind: Testnet, RPCURL: \"https://rpc.onyx.testnets.gno.land\"}\n\tuassert.NoError(t, ValidateInfo(ok))\n\t// A loopback main RPC is a local zone's, and only a local zone's: it names a\n\t// different machine for every reader.\n\ttcp := ok\n\ttcp.RPCURL = \"tcp://127.0.0.1:26657\"\n\tuassert.ErrorContains(t, ValidateInfo(tcp), \"private or special-use\")\n\ttcp.Kind = Local\n\tuassert.NoError(t, ValidateInfo(tcp))\n\tfor _, h := range []string{\"http://localhost:26657\", \"http://10.0.0.1:26657\", \"http://192.168.1.2\", \"http://172.20.0.1\",\n\t\t\"http://169.254.169.254\", \"http://100.64.0.1\", \"http://0.0.0.0:26657\", \"http://api.localhost\"} {\n\t\tin := ok\n\t\tin.RPCURL = h\n\t\tuassert.ErrorContains(t, ValidateInfo(in), \"private or special-use\", h)\n\t}\n\tpub := ok\n\tpub.RPCURL = \"http://172.32.0.1\"\n\tuassert.NoError(t, ValidateInfo(pub))\n\n\tbad := func(mut func(*Info), want string) {\n\t\tin := ok\n\t\tmut(\u0026in)\n\t\tuassert.ErrorContains(t, ValidateInfo(in), want)\n\t}\n\tbad(func(in *Info) { in.ChainID = \"\" }, \"chain id\")\n\tbad(func(in *Info) { in.Title = \"\" }, \"title is 1 to 64\")\n\tbad(func(in *Info) { in.Title = strings.Repeat(\"x\", MaxTitleLen+1) }, \"title is longer than 64\")\n\tbad(func(in *Info) { in.Title = \"two\\nlines\" }, \"control character\")\n\tbad(func(in *Info) { in.Title = \"\\u200b\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Title = \"\\u2060\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Title = \"\\u3164\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Title = \"\\u061cOnyx\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Title = \"Onyx\\U000e0041\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Title = \"\\u2800\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Title = \"x\\u17b4\" }, \"invisible or bidi\")    // Khmer inherent vowels draw nothing\n\tbad(func(in *Info) { in.Description = \"\\u0301\" }, \"nothing visible\") // optional, but not blank\n\tbad(func(in *Info) { in.Title = \"\\ue000 Onyx\" }, \"which this chain does not draw\")\n\tbad(func(in *Info) { in.Title = \"a\\u180bb\" }, \"invisible or bidi\")   // a Mongolian selector after a Latin letter\n\tbad(func(in *Info) { in.Title = \"Onyx\\ufe0f\" }, \"invisible or bidi\") // after a letter it modifies nothing\n\tbad(func(in *Info) { in.Title = \"a\\U000e0100\" }, \"invisible or bidi\")\n\tfor _, r := range []rune{0x115F, 0x1160, 0xFFA0, 0x17B5, 0x13441, 0x13442, 0x16FE4} {\n\t\tr := r\n\t\tbad(func(in *Info) { in.Title = \"on\" + string(r) + \"yx\" }, \"invisible or bidi\")\n\t}\n\t// Enclosing marks draw a badge's frame around any character.\n\tfor _, s := range []string{\"!\\u20e4 flagged\", \"v\\u20de verified\", \"x\\u20e0\", \"x\\u20dd\"} {\n\t\ts := s\n\t\tbad(func(in *Info) { in.Title = s }, \"enclosing mark\")\n\t}\n\t// √ is maths, not a badge; × is everyday text. A variation selector after a\n\t// base it modifies is text: an emoji heart as a phone writes it, a\n\t// Mongolian free variant, an ideographic variation sequence.\n\tfor _, s := range []string{\"fees scale with \\u221an\", \"1920\\u00d71080\", \"made with \\u2764\\ufe0f\",\n\t\t\"\\u2764\\ufe0e text heart\", \"\\u2211\\ufe0f\", \"\\u203c\\ufe0f new\", \"\\u2049\\ufe0f\", \"\\u2139\\ufe0f\", \"\\u3030\\ufe0f\", \"\\u303d\\ufe0f\",\n\t\t\"\\u18aa\\u180b\",\n\t\t\"\\u1828\\u180b\\u1821\", \"\\u845b\\U000e0100\"} {\n\t\tgood := ok\n\t\tgood.Description = s\n\t\tuassert.NoError(t, ValidateInfo(good), s)\n\t}\n\tfor _, r := range []rune{0x2713, 0x2714, 0x2611, 0x1F5F8, 0x1F5F9, 0x1F197, 0x2716, 0x2717, 0x2718, 0x2715,\n\t\t0x274E, 0x2612, 0x1F6AB, 0x26D4, 0x1F6D1, 0x1F5F4, 0x1F5F7, 0x231B, 0x23F8, 0x23FA, 0x2705, 0x26A0,\n\t\t0x23F3, 0x274C, 0x23F9, 0x1FBB1, 0x237B, 0x10102, 0x1F5D9, 0x2A2F, 0x2573, 0x2BBD, 0x2BBF, 0x29D6,\n\t\t0x29D7, 0x1F7A8, 0x1F7AE, 0x2613, 0x2A09, 0x22A0, 0x2327, 0x1F147, 0x1F187, 0x2297, 0x2A02, 0x1F167,\n\t\t0x1F6C7, 0x2298, 0x29B8, 0x24CD, 0x24E7, 0x24B3, 0x1F127, 0x29BB, 0x2A34, 0x2A35, 0x2A37, 0x292B,\n\t\t0x292C, 0x1F532, 0x1F533, 0x26DD, 0x1F5BE, 0x2B59, 0x2A36, 0x26D2, 0x1FBC0, 0x1D145, 0x26CC, 0x2A3B,\n\t\t0x2BBE, 0x1F5F5, 0x1F5F6} {\n\t\tr := r\n\t\tbad(func(in *Info) { in.Title = string(r) + \" official\" }, \"status glyph\")\n\t}\n\tbad(func(in *Info) { in.Title = \"\\u2705 official mainnet\" }, \"status glyph\")\n\tbad(func(in *Info) { in.Title = \"Z\\u0301\\u0301\\u0301\\u0301\\u0301\" }, \"combining marks\")\n\t// The limit is a run: four marks pass, and a base character ends a run, so\n\t// two runs of three are not a stack of six. A spacing mark is not a stack\n\t// either, so real words in these scripts pass.\n\t// A spacing mark (U+093E) between two runs of four ends the first run.\n\tfor _, word := range []string{\"Z\\u0301\\u0301\\u0301\\u0301\", \"a\\u0301\\u0301\\u0301b\\u0301\\u0301\\u0301\",\n\t\t\"\\u0915\\u0301\\u0301\\u0301\\u0301\\u093e\\u0301\\u0301\\u0301\\u0301\",\n\t\t\"ज़िंदगी\", \"ਜ਼ਿੰਦਗੀ\", \"ကြိုး\", \"སྒྲུབ\"} {\n\t\tgood := ok\n\t\tgood.Title = word\n\t\tuassert.NoError(t, ValidateInfo(good), word)\n\t}\n\tbad(func(in *Info) { in.Title = \"\\u0301\" }, \"nothing visible\")\n\tbad(func(in *Info) { in.Title = \"bad\\xffbyte\" }, \"not valid UTF-8\")\n\tbad(func(in *Info) { in.Title = \"alpha\\u2028beta\" }, \"control character\")\n\tbad(func(in *Info) { in.Title = \"alpha\\u2029beta\" }, \"control character\")\n\tbad(func(in *Info) { in.Title = \"alpha\\u0085beta\" }, \"control character\")\n\tbad(func(in *Info) { in.Description = \"x\\u009by\" }, \"control character\")\n\tbad(func(in *Info) { in.Title = \"Onyx\\u202e\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Description = \"fine\\u200dtext\" }, \"invisible or bidi\")\n\tbad(func(in *Info) { in.Description = strings.Repeat(\"x\", MaxDescriptionLen+1) }, \"description is longer than 512\")\n\tbad(func(in *Info) { in.Kind = \"\" }, \"needs a kind\")\n\tbad(func(in *Info) { in.Kind = \"betanet\" }, \"unknown kind\")\n\tbad(func(in *Info) { in.RPCURL = \"\" }, \"rpc url is empty\")\n\t// The main RPC is what gnokey -remote gets, which dials http, https, tcp.\n\tbad(func(in *Info) { in.RPCURL = \"wss://rpc.onyx.testnets.gno.land/websocket\" }, \"rpc url scheme\")\n\tbad(func(in *Info) { in.RPCURL = \"ws://rpc.onyx.testnets.gno.land/websocket\" }, \"rpc url scheme\")\n\tbad(func(in *Info) { in.RPCURL = \"https://rpc.example.com/path\" }, \"no path\")\n\tbad(func(in *Info) { in.RPCURL = \"https://rpc.example.com?x=1\" }, \"no path\")\n\tbad(func(in *Info) { in.RPCURL = \"https://rpc.example.com:443#f\" }, \"contains\")\n\tbad(func(in *Info) { in.RPCURL = \"https://rpc.example.com/\" }, \"no path\")\n\tbad(func(in *Info) { in.Kind = \" testnet \" }, \"unknown kind\")\n\tport := ok\n\tport.RPCURL = \"https://rpc.onyx.testnets.gno.land:443\"\n\tuassert.NoError(t, ValidateInfo(port))\n\tbad(func(in *Info) { in.GnowebURL = \"gno.land\" }, \"gnoweb url needs a scheme\")\n\tbad(func(in *Info) { in.GenesisURL = \"tcp://x\" }, \"genesis url scheme\")\n\n\t// Runes, not bytes: a 64-character title of multi-byte runes is fine.\n\tin := ok\n\tin.Title = strings.Repeat(\"é\", MaxTitleLen)\n\tuassert.NoError(t, ValidateInfo(in))\n}\n\nfunc TestCanonical(t *testing.T) {\n\tuassert.Equal(t, \"https://rpc.gno.land/API?Q=1\", Canonical(RPC, \"HTTPS://RPC.Gno.Land/API?Q=1\"))\n\tuassert.Equal(t, \"https://rpc.gno.land\", Canonical(RPC, \"https://RPC.gno.land\"))\n\t// One endpoint, one key: every spelling below is the same server.\n\tfor _, same := range []string{\"https://rpc.gno.land\", \"https://rpc.gno.land/\", \"https://rpc.gno.land.\",\n\t\t\"https://rpc.gno.land:443\", \"https://rpc.gno.land?\", \"HTTPS://RPC.gno.land.:443/\"} {\n\t\tuassert.Equal(t, \"https://rpc.gno.land\", Canonical(RPC, same), same)\n\t}\n\tuassert.Equal(t, \"http://h.example.com\", Canonical(Gnoweb, \"http://h.example.com:80\"))\n\tuassert.Equal(t, \"http://h.example.com:443\", Canonical(Gnoweb, \"http://h.example.com:443\")) // not http's default\n\tuassert.Equal(t, \"https://h.example.com/api\", Canonical(Indexer, \"https://h.example.com:443/api\"))\n\tuassert.Equal(t, nodeID+\"@seed-1.gno.land:26656\", Canonical(Peer, nodeID+\"@SEED-1.gno.land:26656\"))\n}\n\nfunc TestParse(t *testing.T) {\n\tfor _, s := range []string{\"\", \"approved\", \"pending\", \"rejected\", \"retired\"} {\n\t\t_, err := ParseStatus(s)\n\t\tuassert.NoError(t, err, s)\n\t}\n\t_, err := ParseStatus(\"official\")\n\tuassert.ErrorContains(t, err, \"unknown status\")\n\n\t_, err = ParseKind(\"betanet\")\n\tuassert.ErrorContains(t, err, \"unknown kind\")\n\tk, err := ParseKind(\" testnet \")\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, string(Testnet), string(k))\n\n\t_, err = ParseEndpointKind(\"grpc\")\n\tuassert.ErrorContains(t, err, \"unknown endpoint kind\")\n\t_, err = ParseVerification(\"trusted\")\n\tuassert.ErrorContains(t, err, \"unknown verification\")\n\n\t// Every listed value parses back to itself.\n\tfor _, v := range EndpointKinds() {\n\t\tgot, err := ParseEndpointKind(string(v))\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, string(v), string(got))\n\t}\n\tfor _, v := range Kinds() {\n\t\tgot, _ := ParseKind(string(v))\n\t\tuassert.Equal(t, string(v), string(got))\n\t}\n\tfor _, v := range Statuses() {\n\t\tgot, _ := ParseStatus(string(v))\n\t\tuassert.Equal(t, string(v), string(got))\n\t}\n\tfor _, v := range Verifications() {\n\t\tgot, _ := ParseVerification(string(v))\n\t\tuassert.Equal(t, string(v), string(got))\n\t}\n}\n"}]},"send":"","max_deposit":"78000000ugnot"}],"fee":{"gas_wanted":"516316800","gas_fee":"1548950ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"62SR259FOs2AhZBl3DcekkEqLqsVu/hBDY5WVY24KawX1zJLUDjK+3FzATlmAY3Mr2h7YFuh4UwVsQ0Bat/0lw=="}],"memo":""},"metadata":{"timestamp":"1790964198"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"zones","path":"gno.land/r/moul/zones/v0","files":[{"name":"README.md","body":"# zones\n\nA curated registry of gno.land networks and the endpoints that reach them:\nmainnet, the testnets, staging chains, anybody's gnodev. Anybody proposes a\nzone; a curator approves, rejects or retires it, and verifies or flags its\nendpoints. The latest decision on each is recorded with who made it and when, and a\nrejection, a retirement, a flag or an edit to an approved zone must also say\nwhy, on the zone's page. Nothing is hidden while it waits: proposals and\nunverified endpoints are listed, and labelled.\n\nThe model, validation and state machine are [`p/moul/zones`](../../../p/moul/zones).\nThis realm owns only who may write, and the pages.\n\n## It ships with four zones\n\nAll approved at deploy, every address probed on 2026-10-01. Peers are the\n`persistent_peers` each network's `VALIDATOR.md` publishes in the gnolang/gno\nmonorepo.\n\n| slug | chain id | endpoints |\n|---|---|---|\n| `mainnet` | `gnoland-1` | rpc, gnoweb, 2 peers, indexer, explorer, all verified |\n| `onyx` | `onyx-1` | rpc, gnoweb, 2 peers, indexer, faucet, explorer, all verified |\n| `staging` | `staging` | rpc, gnoweb, **flagged**: neither answered when seeded, and the flag says what each returned |\n| `moul-staging` | `moulstaging-1` | rpc, gnoweb, faucet, all verified |\n\n## Read it from a node\n\nThe reads take plain values, so they work from `gnokey query vm/qeval` and from\nanother realm alike. An empty kind or status matches anything; a slug is\nrequired wherever one is asked for.\n\n```sh\ngnokey query vm/qeval -remote https://rpc.gno.land \\\n  -data 'gno.land/r/moul/zones/v0.ListAddresses(\"onyx\", \"peer\", \"verified\")'\n```\n\n| function | answers |\n|---|---|\n| `ListZones(status, kind)` | the zones, in the order they were proposed; `approved` is the official list |\n| `GetZone(slug)` | one zone, and whether it exists |\n| `ListEndpoints(slug, kind, status)` | one zone's endpoints, oldest first |\n| `ListAddresses(slug, kind, status)` | the same, reduced to the address strings a config file wants |\n| `GetEndpoint(id)` | one endpoint, and whether it exists |\n| `IsCurator(addr)`, `Curators()` | who curates |\n| `IsInvited(addr)`, `Invited()` | who has an open invitation to curate |\n\nTurning these into a node's `config.toml` is deliberately not this realm's job.\nIt is public (`gnomod.toml` says why) so that a separate realm can import it and\ndo that. Two things an importer must know: a slice these return is read-only in\nthe importing realm, elements included (copy it before sorting or changing it;\na struct returned on its own is already the caller's; a slice the importer\nkeeps in its own state stays this realm's object, so copy it before storing it\ntoo), and a kind or status the\n`p/moul/zones` `Parse` functions do not accept, or a blank slug, panics, which no `recover` in the\ncaller catches, so check one taken from a query string with them first.\n\n## Write to it\n\n| function | who |\n|---|---|\n| `ProposeZone(slug, chainID, title, description, kind, gnowebURL, rpcURL, genesisURL)` | anybody; a curator also when the review queue is full, and into the registry's last 16 places |\n| `EditZone(slug, revision, chainID, ..., reason)` | a curator, or the proposer while pending. Before review the reason must be empty; on an approved zone it is required and replaces the review on record. Every edit bumps the zone's revision, and a new chain id sends its verified endpoints back to unverified. Leaving `local` drops every endpoint on a private host, at most 64 in one edit (more, remove some first), and is refused while one carries a curator's ruling (a curator removes it first; a verified one its registrant may withdraw); the proposer's edit only drops endpoints that are theirs and that they could withdraw on their own. A rejected or retired zone is not editable |\n| `ApproveZone(slug, revision, reason)` | a curator |\n| `RejectZone(slug, revision, reason)`, `RetireZone(slug, revision, reason)` | a curator, reason required; the zone's verified endpoints go back to unverified. Rejecting a rejected zone, or retiring a retired one, with a new reason restates it; so does approving an approved one |\n| `RemoveZone(slug, revision)` | a curator, on a pending or rejected zone; or its proposer, on a pending one, 100 blocks after it was proposed or last edited, while every endpoint on it is theirs and one they could withdraw on its own (below). One that was ever official is not removable; a retired one is kept until 128 newer retirements push it out |\n| `RegisterEndpoint(slug, kind, addr, label)` | anybody on an approved zone; on a pending one, its proposer or a curator. The zone's own main RPC under `rpc` and gnoweb under `gnoweb` only a curator lists, or the proposer while the zone is pending (every proposer right ends at approval), since the page marks those URLs by that listing's verdict. An edit cannot make a stranger's listing the zone's own either: when it changes the main RPC or gnoweb to a URL a stranger (on an approved zone, the proposer too) lists under that kind, on a curator's edit the listing is dropped if nobody ruled on it (so pre-listing a zone's next URL cannot hold its move off) and the edit is refused if a curator did; a proposer's edit refuses rather than drop what is not theirs, and a flagged listing refuses the edit whoever holds it. A curator also registers past the review queue and the 16-per-address cap, and into the last 16 of the zone's 128 places, which a registration through the queue may not take |\n| `VerifyEndpoint(id, zoneRevision, revision, reason)` | a curator, naming the endpoint's revision (the endpoint table's column) and the zone's (the zone page's), both as read |\n| `FlagEndpoint(id, revision, reason)`, `UnverifyEndpoint(id, revision, reason)` | a curator, naming the endpoint's revision as read. A flag needs a reason; any verdict given again with a new reason restates it |\n| `ClearUnreviewed(slug, throughRevision)` | a curator: removes, in one call, every endpoint on the zone that nobody ruled on and that was registered through the review queue, not past it by a curator (never more than the 64 the queue holds), up to the revision named, on every page and every kind (the link on the zone's unfiltered page carries the revision it was rendered at, so nothing registered after is touched). For a flood that withdraws and registers again faster than one removal at a time |\n| `RemoveEndpoint(id, revision)` | a curator; or its registrant, on a pending or approved zone, 100 blocks after registering it, unless a curator flagged or unverified it (a reset, which a chain-id edit, a rejection or a retirement makes, leaves the withdrawal a verified one had). Naming the revision means a removal fails if a verdict landed since. A verified endpoint its registrant may take down; a flagged or curator-unverified one is a warning, and everything on a rejected or retired zone is a record: only a curator removes those |\n| `AddCurator(addr)` | a curator; it is an invitation, at most 16 curators and invitations together |\n| `AcceptCurator()` | the invited address, to take up the invitation |\n| `RemoveCurator(addr)` | a curator; it withdraws an invitation, or removes a curator along with every invitation they sent. The last curator cannot be removed |\n\nEvery decision on a zone (edit, approve, reject, retire, remove) takes its\n`revision`, the one you read (the zone page shows it, and its action links carry\nit): if the zone changed since, its content or its status, the call fails and\nyou read it again. A verdict on an endpoint, and its removal, take the\nendpoint's own revision (the endpoint table's column), so they fail if another\ncurator ruled on it since; a verification also takes the zone's. The two are\nnamed apart: one number combined from two reads could pair a stale value with a\nfresh one. The `$help` links fill a revision in; an edit, a verdict, a\nrestated decision and an endpoint's removal have no link, so copy them from the\nzone page. A zone's\nrevision covers its own fields and status, not its endpoints' verdicts. A\nproposer edits or withdraws a pending zone only 100 blocks (`ReviewWindow`)\nafter it was proposed or last edited, by anybody, and a registrant withdraws an\nendpoint only 100 blocks after registering it: a rate bound (100 blocks is\nminutes), so neither can change an entry every block.\n\n**Curators are equals**: any one may remove any other, the admin included. That\nis the trust a curator set is, and it is why there are few of them. A removed curator keeps what they registered, a listing of a zone's own\nURL included, until a curator removes it.\n\nA storage deposit is refunded to whoever signs the transaction that frees it\n(on a chain with transfers locked, it goes to the storage fee collector). That\nis why a proposer cannot remove a zone carrying somebody else's endpoints, and\nwhy a curator's removal collects what the remover did not pay.\n\n## Pages\n\nEvery list is 25 rows a page (`?page=`), and a page reads the records it shows\nplus a bounded handful of lookups (each row's main RPC verdict, the flags on a\nzone's own URLs, the zone serving the current chain for the printed command,\nthe curators), never a whole list: `vm/qrender` is\ngas-metered, and a Render that outgrows it stops answering.\nPaths are exact, up to slashes at either end; anything else is Not found.\n\n| path | shows |\n|---|---|\n| (root) | the official zones; `?status=retired` for the retired ones |\n| `zone/\u003cslug\u003e` | one zone: its facts and revision, its last review, its endpoints; `?kind=peer` narrows them |\n| `proposals` | pending proposals; `?status=rejected` for rejected ones, with the reason |\n\nAn approved zone's gnoweb and genesis URLs are links; any other zone's show as\ncode, to copy and check. A main RPC or gnoweb URL the zone also lists, under\nthat same kind, as a flagged endpoint is code and marked wherever it is shown,\nand the printed `gnokey` line leaves out a main RPC so marked. Only that kind's\nflag counts: a listing under another kind is anybody's to make, so its flag\nnever marks the zone's own URL, and under its own kind only a curator lists it\n(or the proposer, while pending). RPCs and endpoint addresses are always code. An action link\nis shown only when the call could pass the caps, and where a cap is full a note\nsays which cap is full; a full review queue still takes a curator's call,\nso its link stays, labelled for curators, and a zone with endpoints awaiting\nreview offers curators, on its unfiltered page and only while something is\nclearable, a Clear link that says how many it clears and that it reaches all\npages and kinds, bound to the revision the page was rendered at. Where a\nRejection or a Retirement would evict the oldest record of its state, the page\nsays so beside it. Addresses are shown in full everywhere,\nnever shortened: an 8+4 shortening is within reach of a vanity grinder who\nwants to look like a curator. Free text has `@` and bare `g1` addresses\nneutralised, so a label cannot turn into a profile link.\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/zones/v0\"\ngno = \"0.9\"\n\n# public: the registry is meant to be read by other realms (a config generator for node operators first), and a private realm cannot be imported\n"},{"name":"render.gno","body":"package zones\n\nimport (\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/zones/v0\"\n)\n\n// realmURL is this realm as gnoweb serves it. Absolute, because the path ends in\n// /v0 and a relative link would resolve against the parent directory. Not\n// derived at runtime: a Render has no cur, and CurrentRealm there is the caller.\n// TestRealmURLMatchesTheModule pins it to the module line.\nconst realmURL = \"/r/moul/zones/v0\"\n\n// pkgPath is this realm's package path, for the action links.\nconst pkgPath = \"gno.land\" + realmURL\n\n// action is a call link to a function of THIS realm, named explicitly.\n//\n// Not ui.Action: that resolves its target through unsafe.CurrentRealm, which in\n// a borrowed Render is the caller, so a realm embedding this page would get\n// links that call its own functions. filetests/z_borrowed_render_filetest.gno\n// pins it from a caller realm, the only place the difference shows.\nfunc action(title, fn string, args ...string) string {\n\treturn ui.ActionIn(pkgPath, title, fn, args...)\n}\n\n// PageSize is how many rows any table here shows at once. Every list is\n// paginated and every page reads only its own records, because vm/qrender is\n// gas-metered (3B per query) and a Render that outgrows it stops answering\n// instead of slowing down. At the caps a page reads its 25 records, one lookup\n// per URL it may mark flagged (each row's main RPC on the index; the zone's\n// RPC and gnoweb on its page), the zone serving this chain for the printed\n// command, the curators, and a few index nodes. Escaping free text is\n// what dominates: about 97k gas a character on a node, so a page of full-length\n// fields costs on the order of a billion, still under the ceiling.\nconst PageSize = 25\n\n// Render is the whole public surface, three pages: the zone list (official,\n// or retired with ?status=retired), one zone (?kind= narrows its endpoints),\n// and the proposals (pending, or rejected with ?status=rejected). Every list\n// takes ?page=.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\t// Exact paths only: a page that also answers zone/x/approved-by-gno-core\n\t// lends its content to whatever the extra segment claims.\n\tparts := len(req.PathParts())\n\tswitch req.PathPart(0) {\n\tcase \"\":\n\t\tif parts \u003c= 1 {\n\t\t\treturn renderIndex(req)\n\t\t}\n\tcase \"zone\":\n\t\tif parts == 2 {\n\t\t\treturn renderZone(req.PathPart(1), req)\n\t\t}\n\tcase \"proposals\":\n\t\tif parts == 1 {\n\t\t\treturn renderProposals(req)\n\t\t}\n\t}\n\treturn notFound(\"No such page.\")\n}\n\nfunc renderIndex(req *realmpath.Request) string {\n\tstatus, heading := zones.Approved, \"Official\"\n\tswitch req.Query.Get(\"status\") {\n\tcase \"\", \"approved\":\n\tcase \"retired\":\n\t\tstatus, heading = zones.Retired, \"Retired\"\n\tdefault:\n\t\treturn notFound(\"No such list.\")\n\t}\n\tquery := \"\"\n\tif status == zones.Retired {\n\t\tquery = \"status=retired\u0026\"\n\t}\n\ttable, pages := zoneTable(status, req, \"\")\n\n\tlinks := []string{}\n\tif status == zones.Retired {\n\t\tlinks = append(links, md.Link(\"official zones\", realmURL))\n\t} else if n := reg.ZoneCount(zones.Retired); n \u003e 0 {\n\t\tlinks = append(links, md.Link(strconv.Itoa(n)+\" retired zone(s)\", realmURL+\":?status=retired\"))\n\t}\n\tlinks = append(links,\n\t\tmd.Link(strconv.Itoa(reg.ZoneCount(zones.Pending))+\" proposal(s) waiting for review\", realmURL+\":proposals\"))\n\t// Offered only while it can succeed: a link certain to fail is a dead end,\n\t// and the note says which cap is full (not what would free it: that\n\t// depends on who acts, and what frees one cap can fill another). A\n\t// full review queue still takes a curator's proposal, so the link stays,\n\t// labelled for them.\n\tpropose := func(title string) string {\n\t\treturn action(title, \"ProposeZone\",\n\t\t\t\"slug\", \"\", \"chainID\", \"\", \"title\", \"\", \"description\", \"\", \"kind\", \"testnet\",\n\t\t\t\"gnowebURL\", \"\", \"rpcURL\", \"\", \"genesisURL\", \"\")\n\t}\n\tswitch {\n\tcase reg.Live() \u003e= zones.MaxZones:\n\t\tlinks = append(links, \"the registry is full at \"+strconv.Itoa(zones.MaxZones)+\" live zones\")\n\tcase reg.Live() \u003e= zones.MaxZones-zones.ReservedForReviewers:\n\t\tlinks = append(links, \"the registry's last \"+strconv.Itoa(zones.ReservedForReviewers)+\" places are kept for curators\",\n\t\t\tpropose(\"Propose a zone (curators only)\"))\n\tcase reg.ZoneCount(zones.Pending) \u003e= zones.MaxPending:\n\t\tlinks = append(links, \"the review queue is full at \"+strconv.Itoa(zones.MaxPending)+\" proposals\",\n\t\t\tpropose(\"Propose a zone (curators only, while full)\"))\n\tdefault:\n\t\tlinks = append(links, propose(\"Propose a zone\"))\n\t}\n\n\treturn ui.Join(\"\\n\",\n\t\tmd.H1(\"Zones\"),\n\t\tpara(\"A curated registry of gno.land networks and the endpoints that reach them. \"+\n\t\t\t\"Anybody can propose a zone, and register endpoints on an official one; a curator approves, \"+\n\t\t\t\"rejects or retires a zone and verifies or flags its endpoints, and every rejection, \"+\n\t\t\t\"retirement and flag says why, in public.\"),\n\t\tmd.H2(heading),\n\t\ttable,\n\t\tpager(\"\", query, pageNum(req, pages), pages),\n\t\tpara(strings.Join(links, \" · \")),\n\t\tmd.H2(\"Read it from a node\"),\n\t\tpara(\"Every list is a plain function, so a node operator or a script can ask for it directly. \"+\n\t\t\t\"An empty kind or status matches anything.\"),\n\t\tmd.CodeBlock(queryCommand(`ListAddresses(\"`+exampleSlug()+`\", \"peer\", \"verified\")`)),\n\t\tmd.BulletList([]string{\n\t\t\tmd.InlineCode(`ListZones(status, kind)`) + \": `approved` is the official list\",\n\t\t\tmd.InlineCode(`GetZone(slug)`),\n\t\t\tmd.InlineCode(`ListEndpoints(slug, kind, status)`) + \": kind is rpc, gnoweb, seed, peer, indexer, faucet or explorer\",\n\t\t\tmd.InlineCode(`ListAddresses(slug, kind, status)`) + \": the same, reduced to what a config file wants\",\n\t\t}),\n\t\tpara(\"Curated by \"+curatorList()+\".\"),\n\t)\n}\n\n// zoneTable renders one page of the zones with that status, and returns how\n// many pages there are.\nfunc zoneTable(status zones.Status, req *realmpath.Request, empty string) (string, int) {\n\tpages := pageCount(reg.ZoneCount(status))\n\tvar t *ui.Table\n\tswitch status {\n\tcase zones.Approved:\n\t\tt = ui.NewTable(\"zone\", \"chain id\", \"kind\", \"rpc\", \"endpoints\")\n\tcase zones.Pending:\n\t\tt = ui.NewTable(\"zone\", \"chain id\", \"kind\", \"proposed by\", \"review\")\n\tcase zones.Rejected:\n\t\tt = ui.NewTable(\"zone\", \"chain id\", \"proposed by\", \"why\", \"\")\n\tdefault:\n\t\tt = ui.NewTable(\"zone\", \"chain id\", \"proposed by\", \"why\")\n\t}\n\tfor _, z := range reg.ZonePage(status, pageNum(req, pages), PageSize) {\n\t\tswitch status {\n\t\tcase zones.Approved:\n\t\t\tverified, total := reg.Count(z.Slug)\n\t\t\tt.Row(zoneLink(z), md.InlineCode(z.ChainID), string(z.Kind), md.InlineCode(z.RPCURL)+rpcFlag(z),\n\t\t\t\tstrconv.Itoa(verified)+\" verified of \"+strconv.Itoa(total))\n\t\tcase zones.Pending:\n\t\t\t// Review on the zone page, which shows what is being approved; the\n\t\t\t// Approve link there carries the revision it was rendered from.\n\t\t\tt.Row(zoneLink(z), md.InlineCode(z.ChainID), string(z.Kind), ui.AddrFull(z.Proposer),\n\t\t\t\tmd.Link(\"review\", realmURL+\":zone/\"+z.Slug))\n\t\tcase zones.Rejected:\n\t\t\tt.Row(zoneLink(z), md.InlineCode(z.ChainID), ui.AddrFull(z.Proposer), cell(z.Reason),\n\t\t\t\taction(\"Remove\", \"RemoveZone\", \"slug\", z.Slug, \"revision\", revStr(z)))\n\t\tdefault:\n\t\t\tt.Row(zoneLink(z), md.InlineCode(z.ChainID), ui.AddrFull(z.Proposer), cell(z.Reason))\n\t\t}\n\t}\n\tif empty == \"\" {\n\t\tempty = \"No \" + string(status) + \" zone yet.\"\n\t}\n\treturn t.OrEmpty(empty), pages\n}\n\nfunc renderZone(slug string, req *realmpath.Request) string {\n\tz, ok := reg.Zone(slug)\n\tif !ok {\n\t\treturn notFound(\"No such zone.\")\n\t}\n\tkind := zones.EndpointKind(req.Query.Get(\"kind\"))\n\tif kind != \"\" \u0026\u0026 !isKind(kind) {\n\t\treturn notFound(\"No such endpoint kind.\")\n\t}\n\n\tfacts := []string{\n\t\tmd.Bold(\"chain id\") + \": \" + md.InlineCode(z.ChainID),\n\t\tmd.Bold(\"kind\") + \": \" + string(z.Kind),\n\t\tmd.Bold(\"rpc\") + \": \" + md.InlineCode(z.RPCURL) + rpcFlag(z),\n\t}\n\tif z.GnowebURL != \"\" {\n\t\tfacts = append(facts, md.Bold(\"gnoweb\")+\": \"+urlFact(z, zones.Gnoweb, z.GnowebURL))\n\t}\n\tif z.GenesisURL != \"\" {\n\t\tfacts = append(facts, md.Bold(\"genesis\")+\": \"+urlFact(z, \"\", z.GenesisURL))\n\t}\n\t// Addresses in full, here and on every page: an 8+4 shortening is about 50\n\t// bits, within reach of a vanity grinder who wants to look like a curator.\n\tfacts = append(facts, md.Bold(\"proposed\")+\" by \"+ui.AddrFull(z.Proposer)+\" at block \"+strconv.FormatInt(z.ProposedAt, 10))\n\tif z.EditedBy != \"\" {\n\t\tfacts = append(facts, md.Bold(\"edited\")+\" by \"+ui.AddrFull(z.EditedBy)+\" at block \"+strconv.FormatInt(z.EditedAt, 10))\n\t}\n\tfacts = append(facts, md.Bold(\"revision\")+\": \"+strconv.FormatInt(z.Revision, 10))\n\tif z.Reviewed() {\n\t\tfacts = append(facts, md.Bold(\"last reviewed\")+\" \"+reviewText(z.ReviewedBy, z.ReviewedAt, z.Reason))\n\t}\n\n\tparts := []string{\n\t\tmd.H1(prose(z.Title)),\n\t\tpara(statusBadge(z.Status) + \" · \" + md.InlineCode(z.Slug)),\n\t}\n\tif z.Description != \"\" {\n\t\tparts = append(parts, para(prose(z.Description)))\n\t}\n\tparts = append(parts, md.BulletList(facts), md.H2(\"Endpoints\"))\n\n\t// One link per kind the zone has, from the index counts: no endpoint is\n\t// read to draw them.\n\tbase := realmURL + \":zone/\" + z.Slug\n\tkinds := []string{}\n\tif all := reg.EndpointCount(z.Slug, \"\"); all \u003e 0 {\n\t\tkinds = append(kinds, kindLink(\"all\", base, all, kind == \"\"))\n\t\tfor _, k := range zones.EndpointKinds() {\n\t\t\tif n := reg.EndpointCount(z.Slug, k); n \u003e 0 {\n\t\t\t\tkinds = append(kinds, kindLink(string(k), base+\"?kind=\"+string(k), n, kind == k))\n\t\t\t}\n\t\t}\n\t\tparts = append(parts, para(strings.Join(kinds, \" · \")))\n\t}\n\n\tpages := pageCount(reg.EndpointCount(z.Slug, kind))\n\t// The revision column is what a verdict or a removal names; a verification\n\t// also names the zone's revision, shown above.\n\tt := ui.NewTable(\"#\", \"revision\", \"kind\", \"address\", \"label\", \"status\", \"registered by\")\n\tfor _, e := range reg.EndpointPage(z.Slug, kind, pageNum(req, pages), PageSize) {\n\t\tt.Row(\n\t\t\tstrconv.FormatInt(e.ID, 10),\n\t\t\tstrconv.FormatInt(e.Revision, 10),\n\t\t\tstring(e.Kind),\n\t\t\tmd.InlineCode(e.Address),\n\t\t\tcell(e.Label),\n\t\t\tendpointStatus(e),\n\t\t\tui.AddrFull(e.Registrant),\n\t\t)\n\t}\n\tquery := \"\"\n\tif kind != \"\" {\n\t\tquery = \"kind=\" + string(kind) + \"\u0026\"\n\t}\n\tempty := \"No endpoint registered yet.\"\n\tif kind != \"\" {\n\t\tempty = \"No \" + string(kind) + \" endpoint registered yet.\"\n\t}\n\tparts = append(parts, t.OrEmpty(empty), pager(\"zone/\"+z.Slug, query, pageNum(req, pages), pages))\n\n\tactions := []string{}\n\topen := z.Status == zones.Approved || z.Status == zones.Pending\n\tswitch {\n\tcase open \u0026\u0026 reg.EndpointCount(z.Slug, \"\") \u003e= zones.MaxEndpointsPerZone:\n\t\tactions = append(actions, \"endpoints are full at \"+strconv.Itoa(zones.MaxEndpointsPerZone))\n\tcase open \u0026\u0026 reg.EndpointCount(z.Slug, \"\") \u003e= zones.MaxEndpointsPerZone-zones.ReservedForReviewers:\n\t\tactions = append(actions, \"the last \"+strconv.Itoa(zones.ReservedForReviewers)+\" endpoint places are kept for curators\",\n\t\t\taction(\"Register an endpoint (curators only)\", \"RegisterEndpoint\",\n\t\t\t\t\"slug\", z.Slug, \"kind\", \"rpc\", \"addr\", \"\", \"label\", \"\"))\n\tcase open \u0026\u0026 reg.Awaiting(z.Slug) \u003e= zones.MaxUnverifiedPerZone:\n\t\tactions = append(actions, \"the review queue is full at \"+strconv.Itoa(zones.MaxUnverifiedPerZone)+\" endpoints awaiting review\",\n\t\t\taction(\"Register an endpoint (curators only, while full)\", \"RegisterEndpoint\",\n\t\t\t\t\"slug\", z.Slug, \"kind\", \"rpc\", \"addr\", \"\", \"label\", \"\"))\n\tcase z.Status == zones.Approved:\n\t\tactions = append(actions, action(\"Register an endpoint\", \"RegisterEndpoint\",\n\t\t\t\"slug\", z.Slug, \"kind\", \"rpc\", \"addr\", \"\", \"label\", \"\"))\n\tcase z.Status == zones.Pending \u0026\u0026 !curators.Has(z.Proposer) \u0026\u0026 reg.OwnerCount(z.Slug, z.Proposer) \u003e= zones.MaxEndpointsPerAddress:\n\t\t// On a pending zone the proposer is the one gated registrant.\n\t\tactions = append(actions, \"the proposer has registered \"+strconv.Itoa(zones.MaxEndpointsPerAddress)+\" endpoints here, the limit per address\",\n\t\t\taction(\"Register an endpoint (curators only)\", \"RegisterEndpoint\",\n\t\t\t\t\"slug\", z.Slug, \"kind\", \"rpc\", \"addr\", \"\", \"label\", \"\"))\n\tcase z.Status == zones.Pending:\n\t\tactions = append(actions, action(\"Register an endpoint (proposer or curator)\", \"RegisterEndpoint\",\n\t\t\t\"slug\", z.Slug, \"kind\", \"rpc\", \"addr\", \"\", \"label\", \"\"))\n\t}\n\t// A flood clears in one call, on any zone the call takes (a rejected or\n\t// retired zone's records are a curator's to remove too). The call reaches\n\t// every page and every kind, so it is offered only on the unfiltered view,\n\t// only while it would clear something (the clearable count, no endpoint\n\t// read), labelled with its real scope, and bounded in time: an endpoint\n\t// registered after this page was rendered has a later revision and is kept.\n\tif n := reg.Clearable(z.Slug); kind == \"\" \u0026\u0026 n \u003e 0 {\n\t\tactions = append(actions, action(\"Clear \"+strconv.Itoa(n)+\" never-reviewed endpoint(s) registered through the review queue, all pages and kinds (curators only)\", \"ClearUnreviewed\",\n\t\t\t\"slug\", z.Slug, \"throughRevision\", strconv.FormatInt(reg.Revision(), 10)))\n\t}\n\t// Every decision carries the revision this page was rendered from, so acting\n\t// on what you read here fails if the zone changed after you read it.\n\trev := revStr(z)\n\tapprove := action(\"Approve revision \"+rev, \"ApproveZone\", \"slug\", z.Slug, \"revision\", rev, \"reason\", \"\")\n\tremove := action(\"Remove\", \"RemoveZone\", \"slug\", z.Slug, \"revision\", rev)\n\tswitch z.Status {\n\tcase zones.Pending:\n\t\tactions = append(actions, approve,\n\t\t\taction(\"Reject\", \"RejectZone\", \"slug\", z.Slug, \"revision\", rev, \"reason\", \"\"), remove)\n\t\tif reg.ZoneCount(zones.Rejected) \u003e= zones.MaxRejected {\n\t\t\tactions = append(actions, \"rejecting it drops the zone rejected longest ago, endpoints and all\")\n\t\t}\n\tcase zones.Approved:\n\t\tactions = append(actions, action(\"Retire\", \"RetireZone\", \"slug\", z.Slug, \"revision\", rev, \"reason\", \"\"))\n\t\tif reg.ZoneCount(zones.Retired) \u003e= zones.MaxRetired {\n\t\t\tactions = append(actions, \"retiring it drops the zone retired longest ago, endpoints and all\")\n\t\t}\n\tcase zones.Rejected, zones.Retired:\n\t\t// Back into the live registry only while it has room.\n\t\tif reg.Live() \u003c zones.MaxZones {\n\t\t\tactions = append(actions, approve)\n\t\t} else {\n\t\t\tactions = append(actions, \"approving it waits for a free place: the registry is full at \"+strconv.Itoa(zones.MaxZones)+\" live zones\")\n\t\t}\n\t\tif z.Status == zones.Rejected {\n\t\t\tactions = append(actions, remove)\n\t\t}\n\t}\n\tparts = append(parts,\n\t\tpara(strings.Join(actions, \" · \")),\n\t\tmd.CodeBlock(queryCommand(`GetZone(\"`+z.Slug+`\")`)),\n\t\tpara(md.Link(\"All zones\", realmURL)),\n\t)\n\treturn ui.Join(\"\\n\", parts...)\n}\n\nfunc renderProposals(req *realmpath.Request) string {\n\tstatus, heading, other := zones.Pending, \"Pending\", \"\"\n\tswitch req.Query.Get(\"status\") {\n\tcase \"\", \"pending\":\n\t\tif n := reg.ZoneCount(zones.Rejected); n \u003e 0 {\n\t\t\tother = md.Link(strconv.Itoa(n)+\" rejected\", realmURL+\":proposals?status=rejected\")\n\t\t}\n\tcase \"rejected\":\n\t\tstatus, heading = zones.Rejected, \"Rejected\"\n\t\tother = md.Link(\"pending\", realmURL+\":proposals\")\n\tdefault:\n\t\treturn notFound(\"No such list.\")\n\t}\n\tquery := \"\"\n\tif status == zones.Rejected {\n\t\tquery = \"status=rejected\u0026\"\n\t}\n\tempty := \"Nothing waiting for review.\"\n\tif status == zones.Rejected {\n\t\tempty = \"Nothing rejected.\"\n\t}\n\ttable, pages := zoneTable(status, req, empty)\n\tlinks := []string{}\n\tif other != \"\" {\n\t\tlinks = append(links, other)\n\t}\n\tlinks = append(links, md.Link(\"All zones\", realmURL))\n\treturn ui.Join(\"\\n\",\n\t\tmd.H1(\"Proposals\"),\n\t\tpara(\"Zones somebody proposed and no curator has approved. Only an approved zone is official.\"),\n\t\tmd.H2(heading),\n\t\ttable,\n\t\tpager(\"proposals\", query, pageNum(req, pages), pages),\n\t\tpara(strings.Join(links, \" · \")),\n\t)\n}\n\n// pageCount is how many pages n rows make, at least one.\nfunc pageCount(n int) int {\n\tpages := n / PageSize\n\tif n%PageSize != 0 {\n\t\tpages++\n\t}\n\tif pages \u003c 1 {\n\t\tpages = 1\n\t}\n\treturn pages\n}\n\n// pageNum reads ?page= and clamps it into 1..pages: it is a reader's input,\n// and ?page=-1 must not render a footer saying \"page -1 of 2\".\nfunc pageNum(req *realmpath.Request, pages int) int {\n\tpage := 1\n\traw := req.Query.Get(\"page\")\n\tif n, err := strconv.Atoi(raw); err == nil {\n\t\tpage = n\n\t} else if digits := strings.TrimPrefix(raw, \"+\"); digits != \"\" \u0026\u0026 strings.Trim(digits, \"0123456789\") == \"\" {\n\t\t// All digits and still unparseable: a positive number past int. It is\n\t\t// past the last page too, so it lands there, as any big number does.\n\t\tpage = pages\n\t}\n\tif page \u003c 1 {\n\t\tpage = 1\n\t}\n\tif page \u003e pages {\n\t\tpage = pages\n\t}\n\treturn page\n}\n\n// pager links the neighbouring pages of a list, keeping the list's other query\n// parameters (query ends in \"\u0026\" when not empty). One page needs no pager.\nfunc pager(path, query string, page, pages int) string {\n\tif pages \u003c 2 {\n\t\treturn \"\"\n\t}\n\tlink := func(n int) string { return realmURL + \":\" + path + \"?\" + query + \"page=\" + strconv.Itoa(n) }\n\tout := \"\"\n\tif page \u003e 1 {\n\t\tout += md.Link(\"previous\", link(page-1)) + \" · \"\n\t}\n\tout += \"page \" + strconv.Itoa(page) + \" of \" + strconv.Itoa(pages)\n\tif page \u003c pages {\n\t\tout += \" · \" + md.Link(\"next\", link(page+1))\n\t}\n\treturn para(out)\n}\n\nfunc kindLink(label, url string, n int, current bool) string {\n\ttext := label + \" (\" + strconv.Itoa(n) + \")\"\n\tif current {\n\t\treturn md.Bold(text)\n\t}\n\treturn md.Link(text, url)\n}\n\nfunc notFound(msg string) string { return md.H1(\"Not found\") + ui.Empty(msg) }\n\n// queryCommand is the gnokey line that evaluates call against this realm.\n//\n// The remote is looked up in the registry itself, by the chain id this realm is\n// running on, so the command a reader copies points at the chain they are\n// reading. A chain the registry does not list gets no -remote, rather than a\n// guessed one, and so does a chain id two approved zones share (every gnodev\n// is \"dev\"): picking one would be the same guess.\n//\n// A reader pastes this into a shell, so the remote must never carry shell\n// syntax. Two layers make sure: the main RPC is validated down to\n// \u003cscheme\u003e://\u003chost\u003e[:\u003cport\u003e], host [A-Za-z0-9.-] and port digits, which leaves\n// nothing a shell reads as syntax; and it is single-quoted anyway, a quote being\n// the one character no URL here can contain, so a later, wider validator does\n// not reopen it. The call is built from charset-checked slugs and literals.\nfunc queryCommand(call string) string {\n\tremote := \"\"\n\tif z, ok := reg.SoleApproved(runtime.ChainID()); ok \u0026\u0026 !rpcFlagged(z) {\n\t\t// Not one the same page flags: printing a remote the endpoint table says\n\t\t// not to use would contradict the page.\n\t\tremote = \" -remote '\" + z.RPCURL + \"'\"\n\t}\n\treturn \"gnokey query vm/qeval\" + remote + \" -data '\" + pkgPath + \".\" + call + \"'\"\n}\n\n// exampleSlug is the zone the index's example asks for peers of: the one\n// serving the chain this page is read on, when there is exactly one and it\n// lists a peer, else onyx (one zone and an index count read).\nfunc exampleSlug() string {\n\tif z, ok := reg.SoleApproved(runtime.ChainID()); ok \u0026\u0026 reg.EndpointCount(z.Slug, zones.Peer) \u003e 0 {\n\t\treturn z.Slug\n\t}\n\treturn \"onyx\"\n}\n\n// para is one paragraph as a Join part. Not md.Paragraph, whose trailing blank\n// line plus Join's separator makes two in a row, which an example cannot pin.\nfunc para(s string) string { return s + \"\\n\" }\n\n// zoneLink is a zone's title linking to its page, for a TABLE cell. Built by\n// hand rather than with md.Link, whose text escape is for prose and leaves a\n// pipe literal, so a title like \"Alice|official\" would open a column in every\n// zone table. ui.Cell escapes the pipe too; the destination is a constant plus\n// a slug checked to [a-z0-9-] at write time.\nfunc zoneLink(z zones.Zone) string {\n\treturn \"[\" + cell(z.Title) + \"](\" + realmURL + \":zone/\" + z.Slug + \")\"\n}\n\n// urlFact shows a zone's URL as its own text, never behind a label, so a\n// reader sees where it goes: a proposal's \"genesis.json\" link could otherwise\n// open anything, a pre-filled transaction form included, right under the\n// Approve button. Only an approved zone's URLs are links; a proposal's are\n// code, to copy and check, not to click.\n//\n// A URL the zone also lists, under the kind it is shown as, as a flagged\n// endpoint is code and marked, never a link: the page does not offer what its\n// own endpoint table says not to use. kind is what the URL is shown as, \"\"\n// for the genesis URL, which no endpoint kind lists (flaggedAs).\nfunc urlFact(z zones.Zone, kind zones.EndpointKind, url string) string {\n\tif kind != \"\" \u0026\u0026 flaggedAs(z, kind, url) {\n\t\treturn md.InlineCode(url) + \" ⚠️ flagged\"\n\t}\n\tif z.Status == zones.Approved {\n\t\treturn md.Link(url, url)\n\t}\n\treturn md.InlineCode(url)\n}\n\n// prose and cell escape a caller's free text for a sentence and a table cell,\n// plus what ui.Inline and ui.Cell leave alone: gnoweb turns an @name, and a\n// bare g1 address after a space or at the start, into a user-profile link with\n// an icon, so \"run by @gnocore\" or \"run by g1…\" would vouch for an account the\n// registrant chose.\nfunc prose(s string) string { return escapeMentions(ui.Inline(s)) }\n\nfunc cell(s string) string { return escapeMentions(ui.Cell(s)) }\n\n// escapeMentions backslash-escapes every @, and writes the 1 of every g1 as a\n// character reference. It runs after ui.Inline or ui.Cell, which escape every\n// \u0026 the caller typed, so the only reference in the output is this one; goldmark\n// decodes it back to \"1\" after the mention parser has looked and not matched.\n//\n// One pass, and none at all when there is nothing to escape: it runs on every\n// free-text field of every page.\nfunc escapeMentions(s string) string {\n\tif !strings.Contains(s, \"@\") \u0026\u0026 !strings.Contains(s, \"g1\") {\n\t\treturn s\n\t}\n\t// Copy the runs between matches in one piece each: a byte at a time costs a\n\t// native call per byte, every page, on text a stranger chose.\n\tvar b strings.Builder\n\tn, last := len(s), 0\n\tfor i := 0; i \u003c n; i++ {\n\t\tswitch {\n\t\tcase s[i] == '@':\n\t\t\tb.WriteString(s[last:i])\n\t\t\tb.WriteString(\"\\\\@\")\n\t\t\tlast = i + 1\n\t\tcase s[i] == 'g' \u0026\u0026 i+1 \u003c n \u0026\u0026 s[i+1] == '1':\n\t\t\tb.WriteString(s[last:i])\n\t\t\tb.WriteString(\"g\u0026#49;\")\n\t\t\ti++\n\t\t\tlast = i + 1\n\t\t}\n\t}\n\tb.WriteString(s[last:])\n\treturn b.String()\n}\n\n// rpcFlag marks a zone's main RPC when the endpoint table flags it, so the\n// table, the zone page and the printed command never disagree.\nfunc rpcFlag(z zones.Zone) string {\n\tif rpcFlagged(z) {\n\t\treturn \" ⚠️ flagged\"\n\t}\n\treturn \"\"\n}\n\nfunc rpcFlagged(z zones.Zone) bool { return flaggedAs(z, zones.RPC, z.RPCURL) }\n\n// flaggedAs reports whether a URL the page shows as a kind (the main RPC as\n// rpc, the gnoweb URL as gnoweb) is listed under that kind and flagged. Only\n// that kind's verdict counts. A listing under another kind is anybody's to\n// make on an approved zone, so letting its flag mark the zone's own URL would\n// let a stranger's mis-kinded entry, flagged as mis-kinded, mark an official\n// URL; a curator who means the zone's URL flags it under its own kind. The\n// lookup compares in Canonical form, which reads an rpc tcp:// as the http://\n// gnokey dials, so either spelling finds the other.\nfunc flaggedAs(z zones.Zone, shown zones.EndpointKind, url string) bool {\n\te, ok := reg.EndpointByAddress(z.Slug, shown, url)\n\treturn ok \u0026\u0026 e.Status == zones.Flagged\n}\n\nfunc revStr(z zones.Zone) string { return strconv.FormatInt(z.Revision, 10) }\n\nfunc isKind(k zones.EndpointKind) bool {\n\tfor _, x := range zones.EndpointKinds() {\n\t\tif k == x {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc statusBadge(s zones.Status) string {\n\tswitch s {\n\tcase zones.Approved:\n\t\treturn \"✅ \" + md.Bold(\"official\")\n\tcase zones.Pending:\n\t\treturn \"⏳ \" + md.Bold(\"pending review\")\n\tcase zones.Rejected:\n\t\treturn \"❌ \" + md.Bold(\"rejected\")\n\tcase zones.Retired:\n\t\treturn \"⏹️ \" + md.Bold(\"retired\")\n\t}\n\treturn string(s)\n}\n\nfunc endpointStatus(e zones.Endpoint) string {\n\ts := \"\"\n\tswitch e.Status {\n\tcase zones.Verified:\n\t\ts = \"✅ verified\"\n\tcase zones.Flagged:\n\t\ts = \"⚠️ flagged\"\n\tdefault:\n\t\ts = \"unverified\"\n\t}\n\tif e.Reason != \"\" {\n\t\ts += \": \" + cell(e.Reason)\n\t}\n\tif e.ReviewedBy != \"\" {\n\t\ts += \" (\" + ui.AddrFull(e.ReviewedBy) + \", block \" + strconv.FormatInt(e.ReviewedAt, 10) + \")\"\n\t}\n\treturn s\n}\n\nfunc reviewText(by address, at int64, reason string) string {\n\ts := \"by \" + ui.AddrFull(by) + \" at block \" + strconv.FormatInt(at, 10)\n\tif reason != \"\" {\n\t\ts += \": \" + prose(reason)\n\t}\n\treturn s\n}\n\nfunc curatorList() string {\n\tout := []string{}\n\tfor _, a := range Curators() {\n\t\tout = append(out, ui.AddrFull(a))\n\t}\n\treturn strings.Join(out, \", \")\n}\n"},{"name":"render_example_test.gno","body":"package zones\n\n// ExampleRender pins the index: the four seeded zones, official.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Zones\n\t//\n\t// A curated registry of gno.land networks and the endpoints that reach them. Anybody can propose a zone, and register endpoints on an official one; a curator approves, rejects or retires a zone and verifies or flags its endpoints, and every rejection, retirement and flag says why, in public.\n\t//\n\t// ## Official\n\t//\n\t// | zone | chain id | kind | rpc | endpoints |\n\t// | --- | --- | --- | --- | --- |\n\t// | [gno\\.land mainnet](/r/moul/zones/v0:zone/mainnet) | `gnoland-1` | mainnet | `https://rpc.gno.land` | 6 verified of 6 |\n\t// | [Onyx testnet](/r/moul/zones/v0:zone/onyx) | `onyx-1` | testnet | `https://rpc.onyx.testnets.gno.land` | 7 verified of 7 |\n\t// | [gno\\.land staging](/r/moul/zones/v0:zone/staging) | `staging` | devnet | `https://rpc.staging.gno.land` ⚠️ flagged | 0 verified of 2 |\n\t// | [moul's gnodev staging](/r/moul/zones/v0:zone/moul-staging) | `moulstaging-1` | devnet | `https://rpc.gno-staging.moul.p2p.team` | 3 verified of 3 |\n\t//\n\t// [0 proposal\\(s\\) waiting for review](/r/moul/zones/v0:proposals) · [Propose a zone](/r/moul/zones/v0$help\u0026func=ProposeZone\u0026chainID=\u0026description=\u0026genesisURL=\u0026gnowebURL=\u0026kind=testnet\u0026rpcURL=\u0026slug=\u0026title=)\n\t//\n\t// ## Read it from a node\n\t//\n\t// Every list is a plain function, so a node operator or a script can ask for it directly. An empty kind or status matches anything.\n\t//\n\t// ```\n\t// gnokey query vm/qeval -data 'gno.land/r/moul/zones/v0.ListAddresses(\"onyx\", \"peer\", \"verified\")'\n\t// ```\n\t//\n\t// - `ListZones(status, kind)`: `approved` is the official list\n\t// - `GetZone(slug)`\n\t// - `ListEndpoints(slug, kind, status)`: kind is rpc, gnoweb, seed, peer, indexer, faucet or explorer\n\t// - `ListAddresses(slug, kind, status)`: the same, reduced to what a config file wants\n\t//\n\t// Curated by `g1manfred47kzduec920z88wfr64ylksmdcedlf5`.\n}\n\n// ExampleRender_zone pins one zone's page: its facts, a link per endpoint kind,\n// and its endpoints in id order.\nfunc ExampleRender_zone() {\n\treset()\n\tprint(Render(\"zone/onyx\"))\n\t// Output:\n\t// # Onyx testnet\n\t//\n\t// ✅ **official** · `onyx`\n\t//\n\t// The gno\\.land testnet, launched 2026\\-09\\-28: mainnet's code, upgraded whenever mainnet is\\.\n\t//\n\t// - **chain id**: `onyx-1`\n\t// - **kind**: testnet\n\t// - **rpc**: `https://rpc.onyx.testnets.gno.land`\n\t// - **gnoweb**: [https://onyx\\.testnets\\.gno\\.land](https://onyx.testnets.gno.land)\n\t// - **genesis**: [https://github\\.com/gnolang/gno/releases/download/chain/onyx/genesis\\.json](https://github.com/gnolang/gno/releases/download/chain/onyx/genesis.json)\n\t// - **proposed** by `g1manfred47kzduec920z88wfr64ylksmdcedlf5` at block 123\n\t// - **revision**: 16\n\t// - **last reviewed** by `g1manfred47kzduec920z88wfr64ylksmdcedlf5` at block 123: seeded at deploy; probed 2026\\-10\\-01\n\t//\n\t// ## Endpoints\n\t//\n\t// **all (7)** · [rpc \\(1\\)](/r/moul/zones/v0:zone/onyx?kind=rpc) · [gnoweb \\(1\\)](/r/moul/zones/v0:zone/onyx?kind=gnoweb) · [peer \\(2\\)](/r/moul/zones/v0:zone/onyx?kind=peer) · [indexer \\(1\\)](/r/moul/zones/v0:zone/onyx?kind=indexer) · [faucet \\(1\\)](/r/moul/zones/v0:zone/onyx?kind=faucet) · [explorer \\(1\\)](/r/moul/zones/v0:zone/onyx?kind=explorer)\n\t//\n\t// | # | revision | kind | address | label | status | registered by |\n\t// | --- | --- | --- | --- | --- | --- | --- |\n\t// | 7 | 18 | rpc | `https://rpc.onyx.testnets.gno.land` | gno core | ✅ verified: seeded at deploy; probed 2026\\-10\\-01 (`g1manfred47kzduec920z88wfr64ylksmdcedlf5`, block 123) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t// | 8 | 20 | gnoweb | `https://onyx.testnets.gno.land` | gno core | ✅ verified: seeded at deploy; probed 2026\\-10\\-01 (`g1manfred47kzduec920z88wfr64ylksmdcedlf5`, block 123) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t// | 9 | 22 | peer | `g1x5mlj5ava0dw9vkf4j6admjlzswm6f06p44krn@seed-1.onyx.testnets.gno.land:26656` | seed\\-1, gno core | ✅ verified: seeded at deploy; probed 2026\\-10\\-01 (`g1manfred47kzduec920z88wfr64ylksmdcedlf5`, block 123) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t// | 10 | 24 | peer | `g1grq5zswt0dlwwe7clr4359w70k2ewgse0gcwck@seed-2.onyx.testnets.gno.land:26656` | seed\\-2, gno core | ✅ verified: seeded at deploy; probed 2026\\-10\\-01 (`g1manfred47kzduec920z88wfr64ylksmdcedlf5`, block 123) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t// | 11 | 26 | indexer | `https://indexer.onyx.testnets.gno.land/graphql/query` | gno core tx\\-indexer | ✅ verified: seeded at deploy; probed 2026\\-10\\-01 (`g1manfred47kzduec920z88wfr64ylksmdcedlf5`, block 123) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t// | 12 | 28 | faucet | `https://onyx.testnets.gno.land/faucet` | gno core | ✅ verified: seeded at deploy; probed 2026\\-10\\-01 (`g1manfred47kzduec920z88wfr64ylksmdcedlf5`, block 123) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t// | 13 | 30 | explorer | `https://gnoscope.com/?network=onyx` | gnoscope | ✅ verified: seeded at deploy; probed 2026\\-10\\-01 (`g1manfred47kzduec920z88wfr64ylksmdcedlf5`, block 123) | `g1manfred47kzduec920z88wfr64ylksmdcedlf5` |\n\t//\n\t// [Register an endpoint](/r/moul/zones/v0$help\u0026func=RegisterEndpoint\u0026addr=\u0026kind=rpc\u0026label=\u0026slug=onyx) · [Retire](/r/moul/zones/v0$help\u0026func=RetireZone\u0026reason=\u0026revision=16\u0026slug=onyx)\n\t//\n\t// ```\n\t// gnokey query vm/qeval -data 'gno.land/r/moul/zones/v0.GetZone(\"onyx\")'\n\t// ```\n\t//\n\t// [All zones](/r/moul/zones/v0)\n}\n\n// ExampleRender_proposals pins the proposals page with one pending and one\n// rejected zone, written straight to the registry: an Example has no realm\n// token to cross with.\nfunc ExampleRender_proposals() {\n\treset()\n\tmust(reg.Propose(alice, 200, \"alice-dev\", info(\"alicedev-1\", \"Alice's devnet\", \"\", \"devnet\", \"\", \"https://rpc.alice.example.com\", \"\")))\n\tmust(reg.Propose(bob, 201, \"fake-mainnet\", info(\"gnoland-1\", \"Mainnet (faster!)\", \"\", \"mainnet\", \"\", \"https://rpc.fake.example.com\", \"\")))\n\tmust(reg.ReviewZone(\"fake-mainnet\", \"rejected\", zrev(\"fake-mainnet\"), Admin, 202, \"not the mainnet RPC\"))\n\tprint(Render(\"proposals\"))\n\t// Output:\n\t// # Proposals\n\t//\n\t// Zones somebody proposed and no curator has approved. Only an approved zone is official.\n\t//\n\t// ## Pending\n\t//\n\t// | zone | chain id | kind | proposed by | review |\n\t// | --- | --- | --- | --- | --- |\n\t// | [Alice's devnet](/r/moul/zones/v0:zone/alice-dev) | `alicedev-1` | devnet | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | [review](/r/moul/zones/v0:zone/alice-dev) |\n\t//\n\t// [1 rejected](/r/moul/zones/v0:proposals?status=rejected) · [All zones](/r/moul/zones/v0)\n}\n\n// ExampleRender_rejected pins the rejected list, which carries the reasons.\nfunc ExampleRender_rejected() {\n\treset()\n\tmust(reg.Propose(bob, 201, \"fake-mainnet\", info(\"gnoland-1\", \"Mainnet (faster!)\", \"\", \"mainnet\", \"\", \"https://rpc.fake.example.com\", \"\")))\n\tmust(reg.ReviewZone(\"fake-mainnet\", \"rejected\", zrev(\"fake-mainnet\"), Admin, 202, \"not the mainnet RPC\"))\n\tprint(Render(\"proposals?status=rejected\"))\n\t// Output:\n\t// # Proposals\n\t//\n\t// Zones somebody proposed and no curator has approved. Only an approved zone is official.\n\t//\n\t// ## Rejected\n\t//\n\t// | zone | chain id | proposed by | why |  |\n\t// | --- | --- | --- | --- | --- |\n\t// | [Mainnet \\(faster\\!\\)](/r/moul/zones/v0:zone/fake-mainnet) | `gnoland-1` | `g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu` | not the mainnet RPC | [Remove](/r/moul/zones/v0$help\u0026func=RemoveZone\u0026revision=46\u0026slug=fake-mainnet) |\n\t//\n\t// [pending](/r/moul/zones/v0:proposals) · [All zones](/r/moul/zones/v0)\n}\n"},{"name":"seed.gno","body":"package zones\n\nimport (\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/zones/v0\"\n)\n\n// seedReason is the review every seeded zone and endpoint carries, so a reader\n// can tell a deploy-time entry from one a curator reviewed later, and knows how\n// old the check is.\nconst seedReason = \"seeded at deploy; probed 2026-10-01\"\n\n// seedZone is one zone the realm starts with, approved, plus the endpoints it\n// starts with. Every seeded endpoint carries the probe's verdict, which is per\n// zone: verified with seedReason when the zone's endpoints answered, flagged\n// with failed, the observed failure, when they did not. Flagged rather than left unverified, because \"probed and down\"\n// and \"nobody looked\" are different facts and only a review can say which.\ntype seedZone struct {\n\tslug      string\n\tinfo      zones.Info\n\tfailed    string      // empty when every endpoint answered the probe\n\tendpoints [][3]string // kind, address, label\n}\n\n// seeds are the four zones this registry opens with. Every address below was\n// probed on 2026-10-01: each RPC's /status answered with the chain id given\n// here, except staging, whose RPC answered \"temporarily unavailable\" and whose\n// gnoweb answered 503, which is why its endpoints are seeded flagged with that. The\n// peers are the persistent_peers each network's VALIDATOR.md publishes in the\n// gnolang/gno monorepo, under misc/deployments.\n//\n// A function, not a package-level var: a realm's package variables are its\n// database, so a var here would keep every seed stored a second time, forever,\n// beside the registry copy seed() makes of it.\nfunc seeds() []seedZone {\n\treturn []seedZone{\n\t\t{\n\t\t\tslug: \"mainnet\",\n\t\t\tinfo: zones.Info{\n\t\t\t\tChainID:     \"gnoland-1\",\n\t\t\t\tTitle:       \"gno.land mainnet\",\n\t\t\t\tDescription: \"The gno.land mainnet, launched 2026-09-12.\",\n\t\t\t\tKind:        zones.Mainnet,\n\t\t\t\tGnowebURL:   \"https://gno.land\",\n\t\t\t\tRPCURL:      \"https://rpc.gno.land\",\n\t\t\t\tGenesisURL:  \"https://github.com/gnolang/gno/releases/download/chain/mainnet/genesis.json\",\n\t\t\t},\n\t\t\tendpoints: [][3]string{\n\t\t\t\t{\"rpc\", \"https://rpc.gno.land\", \"gno core\"},\n\t\t\t\t{\"gnoweb\", \"https://gno.land\", \"gno core\"},\n\t\t\t\t{\"peer\", \"g15rcv5yqef3kvnmueqvkyw8y05sd40jz9p3n5su@seed-1.gno.land:26656\", \"seed-1, gno core\"},\n\t\t\t\t{\"peer\", \"g1ck2yeyvvnpl92237gcea0z68jx07a4nnyvuaan@seed-2.gno.land:26656\", \"seed-2, gno core\"},\n\t\t\t\t{\"indexer\", \"https://indexer.gno.land/graphql/query\", \"gno core tx-indexer\"},\n\t\t\t\t{\"explorer\", \"https://gnoscope.com/?network=mainnet\", \"gnoscope\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tslug: \"onyx\",\n\t\t\tinfo: zones.Info{\n\t\t\t\tChainID:     \"onyx-1\",\n\t\t\t\tTitle:       \"Onyx testnet\",\n\t\t\t\tDescription: \"The gno.land testnet, launched 2026-09-28: mainnet's code, upgraded whenever mainnet is.\",\n\t\t\t\tKind:        zones.Testnet,\n\t\t\t\tGnowebURL:   \"https://onyx.testnets.gno.land\",\n\t\t\t\tRPCURL:      \"https://rpc.onyx.testnets.gno.land\",\n\t\t\t\tGenesisURL:  \"https://github.com/gnolang/gno/releases/download/chain/onyx/genesis.json\",\n\t\t\t},\n\t\t\tendpoints: [][3]string{\n\t\t\t\t{\"rpc\", \"https://rpc.onyx.testnets.gno.land\", \"gno core\"},\n\t\t\t\t{\"gnoweb\", \"https://onyx.testnets.gno.land\", \"gno core\"},\n\t\t\t\t{\"peer\", \"g1x5mlj5ava0dw9vkf4j6admjlzswm6f06p44krn@seed-1.onyx.testnets.gno.land:26656\", \"seed-1, gno core\"},\n\t\t\t\t{\"peer\", \"g1grq5zswt0dlwwe7clr4359w70k2ewgse0gcwck@seed-2.onyx.testnets.gno.land:26656\", \"seed-2, gno core\"},\n\t\t\t\t{\"indexer\", \"https://indexer.onyx.testnets.gno.land/graphql/query\", \"gno core tx-indexer\"},\n\t\t\t\t{\"faucet\", \"https://onyx.testnets.gno.land/faucet\", \"gno core\"},\n\t\t\t\t{\"explorer\", \"https://gnoscope.com/?network=onyx\", \"gnoscope\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tslug: \"staging\",\n\t\t\tinfo: zones.Info{\n\t\t\t\tChainID:     \"staging\",\n\t\t\t\tTitle:       \"gno.land staging\",\n\t\t\t\tDescription: \"gno core's staging network.\",\n\t\t\t\tKind:        zones.Devnet,\n\t\t\t\tGnowebURL:   \"https://staging.gno.land\",\n\t\t\t\tRPCURL:      \"https://rpc.staging.gno.land\",\n\t\t\t},\n\t\t\tfailed: \"did not answer when probed 2026-10-01: the RPC said temporarily unavailable, gnoweb 503\",\n\t\t\tendpoints: [][3]string{\n\t\t\t\t{\"rpc\", \"https://rpc.staging.gno.land\", \"gno core\"},\n\t\t\t\t{\"gnoweb\", \"https://staging.gno.land\", \"gno core\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tslug: \"moul-staging\",\n\t\t\tinfo: zones.Info{\n\t\t\t\tChainID:     \"moulstaging-1\",\n\t\t\t\tTitle:       \"moul's gnodev staging\",\n\t\t\t\tDescription: \"One gnodev node in staging mode, run by moul: a single validator, no consensus, worthless GNOT. Good for trying a deploy.\",\n\t\t\t\tKind:        zones.Devnet,\n\t\t\t\tGnowebURL:   \"https://gno-staging.moul.p2p.team\",\n\t\t\t\tRPCURL:      \"https://rpc.gno-staging.moul.p2p.team\",\n\t\t\t},\n\t\t\tendpoints: [][3]string{\n\t\t\t\t{\"rpc\", \"https://rpc.gno-staging.moul.p2p.team\", \"moul\"},\n\t\t\t\t{\"gnoweb\", \"https://gno-staging.moul.p2p.team\", \"moul\"},\n\t\t\t\t{\"faucet\", \"https://gno-staging.moul.p2p.team/faucet\", \"moul\"},\n\t\t\t},\n\t\t},\n\t}\n}\n\n// seed files every seed through the same Registry methods a caller's\n// transaction goes through (the gated ones, so a seeded endpoint is not\n// Exempt; each is ruled on at once, so none is clearable), so a seed that\n// would fail validation fails the deploy instead of shipping a zone no later\n// edit could reproduce.\nfunc seed() {\n\tat := runtime.ChainHeight()\n\tfor _, s := range seeds() {\n\t\tmust(reg.Propose(Admin, at, s.slug, s.info))\n\t\tmust(reg.ReviewZone(s.slug, zones.Approved, mustZone(s.slug).Revision, Admin, at, seedReason))\n\t\tfor _, e := range s.endpoints {\n\t\t\tk, err := zones.ParseEndpointKind(e[0])\n\t\t\tmust(err)\n\t\t\tid, err := reg.Register(Admin, at, s.slug, k, e[1], e[2])\n\t\t\tmust(err)\n\t\t\tep, _ := reg.Endpoint(id)\n\t\t\tzrev := mustZone(s.slug).Revision // the approval moved it\n\t\t\tif s.failed == \"\" {\n\t\t\t\tmust(reg.ReviewEndpoint(id, zones.Verified, zrev, ep.Revision, Admin, at, seedReason))\n\t\t\t} else {\n\t\t\t\tmust(reg.ReviewEndpoint(id, zones.Flagged, zrev, ep.Revision, Admin, at, s.failed))\n\t\t\t}\n\t\t}\n\t}\n}\n"},{"name":"z_borrowed_render_filetest.gno","body":"// PKGPATH: gno.land/r/test/main\n//\n// Renders the registry from ANOTHER realm, which is the case a unit test in\n// the package cannot reach: there, CurrentRealm is the zones realm itself.\n// Here Render is borrowed, CurrentRealm is gno.land/r/test/main, and every\n// action link must still call the zones realm, not the one embedding it.\npackage main\n\nimport (\n\t\"strings\"\n\n\tzones \"gno.land/r/moul/zones/v0\"\n)\n\nfunc main() {\n\tpage := zones.Render(\"\") + zones.Render(\"zone/onyx\")\n\tprintln(strings.Contains(page, \"/r/moul/zones/v0$help\u0026func=ProposeZone\"))\n\tprintln(strings.Contains(page, \"/r/moul/zones/v0$help\u0026func=RegisterEndpoint\"))\n\tprintln(strings.Contains(page, \"/r/test/main$help\"))\n}\n\n// Output:\n// true\n// true\n// false\n"},{"name":"zones.gno","body":"// untrusted-render: slugs, chain ids, URLs and peer addresses are charset-checked\n// at write time by p/moul/zones; titles, descriptions, labels and reasons are a\n// caller's free text and go through ui.Inline or ui.Cell at every call site.\n\n// Package zones is a curated registry of gno.land networks: mainnet, the\n// testnets, staging chains, anybody's gnodev. Each zone carries what a node or a\n// wallet needs to join it (chain id, RPC, gnoweb, genesis) plus a growing list of\n// endpoints: RPCs, seeds and peers, indexers, faucets, explorers.\n//\n// Curation is the point. Anybody may propose a zone and register endpoints on\n// an approved one (on a pending one, its proposer or a curator; a zone's own\n// main RPC and gnoweb, only them); a curator approves or rejects a proposal,\n// retires a zone that stopped running, and verifies or flags an endpoint. The\n// latest decision on each is recorded with who made it and when, and a rejection, a retirement, a flag or an edit to an\n// approved zone must also say why, on the zone's page. Nothing is hidden while\n// it waits: proposals and unverified endpoints are listed, and labelled.\n//\n// This realm only manages the information and answers questions about it. The\n// read helpers (GetZone, ListZones, GetEndpoint, ListEndpoints, ListAddresses,\n// IsCurator, Curators, IsInvited, Invited) take plain values so they work from\n// `gnokey query vm/qeval` as well as from another realm, and turning them into a\n// node's config.toml is a separate realm's job.\n//\n// The model, its validation and its state machine are p/moul/zones. This realm\n// owns only who may write.\npackage zones\n\nimport (\n\t\"chain/runtime\"\n\t\"strconv\"\n\n\t\"gno.land/p/moul/addrset/v1\"\n\t\"gno.land/p/moul/zones/v0\"\n)\n\n// Admin is the first curator. More are invited with AddCurator and become\n// curators when they accept.\nconst Admin address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\n// ReviewWindow is how many blocks must pass before the author of a change may\n// change it again, a rate bound rather than a review deadline (100 blocks is\n// minutes): after a zone was proposed or last edited (by anybody) before its\n// proposer may edit or withdraw it, and after an endpoint was registered before\n// its registrant may withdraw it. Every edit bumps the revision a curator's\n// decision must name, and a withdrawal plus a fresh proposal or registration\n// does the same with a new revision or id, so without a wait a proposer or a\n// registrant acting every block would keep their entry out of every curator's\n// reach. Curators are not limited.\nconst ReviewWindow = 100\n\n// MaxCurators bounds curators and open invitations together. The curator list\n// renders on the index page, and only curators can grow it, but a bound costs\n// nothing and an unbounded list on a public page is a page someone can break.\nconst MaxCurators = 16\n\nvar (\n\treg      = zones.NewRegistry()\n\tcurators addrset.Set\n\tinvited  addrset.Set             // invited by a curator, not yet accepted\n\tinviter  = map[address]address{} // invitee -\u003e the curator who invited them; lookups only\n)\n\nfunc init() {\n\tcurators.Add(Admin)\n\tseed()\n}\n\n// ---- proposing and curating zones\n\n// ProposeZone files a new zone for review. Anybody may; it is listed as a\n// proposal until a curator approves or rejects it. The review queue's caps\n// (zones.MaxPending, zones.MaxPendingPerProposer) do not stop a curator, who\n// also has the registry's last zones.ReservedForReviewers places, so neither a\n// flood nor a full registry locks out the people who clear it.\n//\n// kind is mainnet, testnet, devnet or local. gnowebURL and genesisURL may be\n// empty; rpcURL may not, and is \u003cscheme\u003e://\u003chost\u003e[:\u003cport\u003e] with no path, which\n// is what gnokey -remote takes.\nfunc ProposeZone(cur realm, slug, chainID, title, description, kind, gnowebURL, rpcURL, genesisURL string) {\n\twho := caller(cur)\n\tin := info(chainID, title, description, kind, gnowebURL, rpcURL, genesisURL)\n\tif curators.Has(who) {\n\t\t// A flood that fills the review queue must not lock out the people\n\t\t// who clear it.\n\t\tmust(reg.ProposeExempt(who, runtime.ChainHeight(), zones.TrimSpaces(slug), in))\n\t\treturn\n\t}\n\tmust(reg.Propose(who, runtime.ChainHeight(), zones.TrimSpaces(slug), in))\n}\n\n// EditZone replaces a zone's Info, every field but its slug and status. A\n// curator may edit any pending or approved zone; the proposer may edit their\n// own while it is pending. revision is the zone's Revision the edit was written\n// against: it fails if the zone changed in between, its content or its status.\n// Every edit bumps the revision, so a decision prepared against the old one\n// fails too. A proposer edits only ReviewWindow blocks after the zone was\n// proposed or last edited, and an edit that changes nothing is refused. On a\n// pending zone the reason must be empty; on an approved one it is required and\n// replaces the review on record, so the page names who changed the values, and\n// why. A new chain id sends the zone's verified endpoints back to unverified.\n// Leaving the local kind drops every endpoint on a private host, and is refused\n// while one carries a curator's ruling (a verified one its registrant may\n// withdraw first); the proposer's edit only drops endpoints that are theirs and\n// that they could withdraw on their own (RemoveEndpoint), as for RemoveZone. A\n// new main RPC or gnoweb a stranger (on an approved zone, its proposer too)\n// already lists under its kind would make\n// that listing the zone's own: on a curator's edit it is dropped if nobody\n// ruled on it, and refuses the edit if a curator did; a proposer's edit\n// refuses rather than drop what is not theirs; and a flagged listing refuses\n// the edit whoever holds it. The registry validates the edit before it drops\n// or resets anything, and a refusal reverts the edit with it. A rejected or\n// retired zone cannot be edited.\nfunc EditZone(cur realm, slug string, revision int64, chainID, title, description, kind, gnowebURL, rpcURL, genesisURL, reason string) {\n\twho := caller(cur)\n\tslug = zones.TrimSpaces(slug)\n\tz := mustZone(slug)\n\tin := info(chainID, title, description, kind, gnowebURL, rpcURL, genesisURL)\n\tif !curators.Has(who) {\n\t\tif z.Status != zones.Pending || z.Proposer != who {\n\t\t\tpanic(\"zones: only a curator, or the proposer while it is pending, may edit \" + slug)\n\t\t}\n\t\tassertReviewWindow(slug, z)\n\t\tif z.Kind == zones.Local \u0026\u0026 in.Kind != zones.Local {\n\t\t\t// The edit would drop these; dropping is removing, under the\n\t\t\t// rules a removal by the proposer has.\n\t\t\tfor _, e := range reg.PrivateEndpoints(slug) {\n\t\t\t\tif e.Registrant != who {\n\t\t\t\t\tpanic(\"zones: leaving local would drop endpoint #\" + strconv.FormatInt(e.ID, 10) +\n\t\t\t\t\t\t\", which somebody else registered; a curator must remove it first\")\n\t\t\t\t}\n\t\t\t\tassertWithdrawable(e)\n\t\t\t}\n\t\t}\n\t}\n\tmust(reg.Edit(slug, revision, in, who, runtime.ChainHeight(), reason))\n\t// The reservation RegisterEndpoint keeps holds across an edit too: a new\n\t// main RPC or gnoweb already listed under its kind by a stranger would\n\t// make that listing, and its verdict, the zone's own. Checked only for a\n\t// URL the edit changed, after the edit, which has validated everything: a\n\t// refusal here reverts the edit with it, and an edit that cannot pass never\n\t// gets this far. On a curator's edit a stranger's listing nobody ruled on\n\t// is dropped, so listing a zone's likely next URL cannot hold its move\n\t// off; one a curator ruled on refuses the edit, and a curator removes it\n\t// first. A proposer's edit drops nothing that is not theirs.\n\tfor _, own := range []struct {\n\t\tkind     zones.EndpointKind\n\t\turl, was string\n\t}{{zones.RPC, in.RPCURL, z.RPCURL}, {zones.Gnoweb, in.GnowebURL, z.GnowebURL}} {\n\t\tif own.url == \"\" || (own.was != \"\" \u0026\u0026 zones.Canonical(own.kind, own.url) == zones.Canonical(own.kind, own.was)) {\n\t\t\tcontinue\n\t\t}\n\t\te, ok := reg.EndpointByAddress(slug, own.kind, own.url)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif curators.Has(e.Registrant) || (z.Status == zones.Pending \u0026\u0026 e.Registrant == z.Proposer) {\n\t\t\t// Theirs to hold, but a flagged one would mark the zone's own URL\n\t\t\t// the moment it becomes one.\n\t\t\tif e.Status == zones.Flagged {\n\t\t\t\tpanic(\"zones: \" + own.url + \" is listed under \" + string(own.kind) + \" as endpoint #\" + strconv.FormatInt(e.ID, 10) +\n\t\t\t\t\t\", flagged; a curator removes it or rules again before it becomes \" + slug + \"'s own\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif !curators.Has(who) {\n\t\t\t// A proposer's edit (a pending zone) drops nothing that is not\n\t\t\t// theirs: the only other registrant there is a former curator.\n\t\t\tpanic(\"zones: \" + own.url + \" is listed under \" + string(own.kind) + \" by \" + e.Registrant.String() +\n\t\t\t\t\" (endpoint #\" + strconv.FormatInt(e.ID, 10) + \"); a curator removes it before it becomes \" + slug + \"'s own\")\n\t\t}\n\t\tif e.ReviewedBy != \"\" || e.Reason != \"\" { // a ruling, a reset's reason\n\t\t\tpanic(\"zones: \" + own.url + \" is listed under \" + string(own.kind) + \" by \" + e.Registrant.String() +\n\t\t\t\t\" (endpoint #\" + strconv.FormatInt(e.ID, 10) + \"), with a curator's ruling; a curator removes it before it becomes \" + slug + \"'s own\")\n\t\t}\n\t\tmust(reg.RemoveEndpoint(e.ID, e.Revision))\n\t}\n}\n\n// ApproveZone makes a zone official. revision is the zone's Revision as you\n// read it (the zone page's Approve link carries it): if the zone changed since,\n// its content or its status, the approval fails and you read it again. The\n// reason is optional.\nfunc ApproveZone(cur realm, slug string, revision int64, reason string) {\n\treview(cur, slug, zones.Approved, revision, reason)\n}\n\n// RejectZone turns a proposal down. The reason is required, and public.\n// revision is the zone's Revision you read, as for ApproveZone.\nfunc RejectZone(cur realm, slug string, revision int64, reason string) {\n\treview(cur, slug, zones.Rejected, revision, reason)\n}\n\n// RetireZone marks an official zone as no longer running, and sends its\n// verified endpoints back to unverified. The reason is required: it is what an\n// operator still holding the chain id will read. revision is the zone's\n// Revision you read.\nfunc RetireZone(cur realm, slug string, revision int64, reason string) {\n\treview(cur, slug, zones.Retired, revision, reason)\n}\n\n// RemoveZone deletes a pending or rejected zone and its endpoints. revision is\n// the zone's Revision you read: a removal meant for one proposal fails on\n// another proposed again under the same slug. A curator may remove any pending\n// or rejected zone. The proposer may withdraw their own only while it is\n// pending, ReviewWindow blocks after it was proposed or last edited\n// (so withdrawing and proposing again cannot dodge the edit wait), while every\n// endpoint on it is theirs (the deposit is refunded to whoever signs the\n// removal, so removing somebody else's endpoints would collect what they paid)\n// and each one is one they could withdraw on its own (RemoveEndpoint):\n// removing the zone must not wipe a curator's flag or unverify, or skip an endpoint's\n// own wait. A rejected zone is the curators' record: only a curator removes\n// it, or newer rejections push it out, and the rejection's deposit, paid by the\n// curator, is not the proposer's to collect. A zone that was ever official is\n// never removed this way: an approved one is retired, and a retired one is kept\n// until newer retirements push it out.\nfunc RemoveZone(cur realm, slug string, revision int64) {\n\twho := caller(cur)\n\tslug = zones.TrimSpaces(slug)\n\tz := mustZone(slug)\n\tif !curators.Has(who) {\n\t\tif z.Proposer != who || z.Status != zones.Pending {\n\t\t\tpanic(\"zones: only a curator, or the proposer while it is pending, may remove \" + slug)\n\t\t}\n\t\tassertReviewWindow(slug, z)\n\t\t// From the index counts first: nothing is read to answer it.\n\t\tif _, total := reg.Count(slug); reg.OwnerCount(slug, who) != total {\n\t\t\tpanic(\"zones: \" + slug + \" carries endpoints somebody else registered; they must be removed first\")\n\t\t}\n\t\t// Every endpoint is the proposer's: at most MaxEndpointsPerZone (a curator\n\t\t// who proposed it may have registered past the per-address cap).\n\t\tfor _, e := range reg.Endpoints(zones.EndpointFilter{Zone: slug}) {\n\t\t\tassertWithdrawable(e)\n\t\t}\n\t}\n\tmust(reg.RemoveZone(slug, revision))\n}\n\n// ---- registering and curating endpoints\n\n// RegisterEndpoint lists an endpoint on a zone and returns its id. On an\n// approved zone anybody may, except the zone's own main RPC under rpc and\n// gnoweb under gnoweb, which only a curator lists (or the proposer while the\n// zone is pending: every proposer right ends at approval); on a\n// pending one only the proposer or a curator, so a stranger cannot pin a\n// proposal the proposer then cannot withdraw. It shows as unverified until a\n// curator checks it. A curator also registers past the review queue's caps\n// and into the zones.ReservedForReviewers places a gated registration may\n// not take, never past zones.MaxEndpointsPerZone.\n//\n// kind is rpc, gnoweb, seed, peer, indexer, faucet or explorer. addr is a\n// URL, or \u003cnode id\u003e@\u003chost\u003e:\u003cport\u003e for a seed or a peer. label is optional:\n// who runs it, in your words.\nfunc RegisterEndpoint(cur realm, slug, kind, addr, label string) int64 {\n\twho := caller(cur)\n\tslug = zones.TrimSpaces(slug)\n\tz := mustZone(slug)\n\tif z.Status == zones.Pending \u0026\u0026 z.Proposer != who \u0026\u0026 !curators.Has(who) {\n\t\tpanic(\"zones: \" + slug + \" is pending; only its proposer or a curator may register on it\")\n\t}\n\tk, err := zones.ParseEndpointKind(kind)\n\tmust(err)\n\taddr = zones.TrimSpaces(addr) // compared as the registry will store it\n\t// The zone's own main RPC and gnoweb, listed under their own kind, carry\n\t// the verdict its page shows on them, so only a curator lists them, or the\n\t// proposer while the zone is pending (every proposer right ends at\n\t// approval): a stranger's listing, once flagged for its label, would mark\n\t// the zone's own URL.\n\tif !curators.Has(who) \u0026\u0026 !(z.Status == zones.Pending \u0026\u0026 z.Proposer == who) \u0026\u0026\n\t\t((k == zones.RPC \u0026\u0026 zones.Canonical(k, addr) == zones.Canonical(k, z.RPCURL)) ||\n\t\t\t(k == zones.Gnoweb \u0026\u0026 z.GnowebURL != \"\" \u0026\u0026 zones.Canonical(k, addr) == zones.Canonical(k, z.GnowebURL))) {\n\t\tpanic(\"zones: that is \" + slug + \"'s own \" + string(k) + \"; only a curator, or its proposer while it is pending, lists it\")\n\t}\n\tregister := reg.Register\n\tif curators.Has(who) {\n\t\tregister = reg.RegisterExempt // past the review queue, as ProposeZone\n\t}\n\tid, err := register(who, runtime.ChainHeight(), slug, k, addr, label)\n\tmust(err)\n\treturn id\n}\n\n// VerifyEndpoint marks an endpoint as checked against its zone. revision is\n// the endpoint's revision as read (the endpoint table's revision column), and\n// zoneRevision the zone's (the zone page shows it): the verdict fails if\n// either changed since, another curator's verdict on the endpoint, or any\n// edit or status change of the zone (what is verified is that it answers for\n// this zone's chain id). The reason is optional. Each verdict may be given\n// again with a new reason, to restate it.\nfunc VerifyEndpoint(cur realm, id, zoneRevision, revision int64, reason string) {\n\treviewEndpoint(cur, id, zones.Verified, zoneRevision, revision, reason)\n}\n\n// FlagEndpoint tells readers not to use an endpoint. The reason is required.\n// revision is the endpoint's, as for VerifyEndpoint; a flag is not bound to\n// the zone, so editing the zone cannot hold off a warning.\nfunc FlagEndpoint(cur realm, id, revision int64, reason string) {\n\treviewEndpoint(cur, id, zones.Flagged, 0, revision, reason)\n}\n\n// UnverifyEndpoint puts an endpoint back to unverified, for one that changed\n// hands or needs checking again. revision is as for FlagEndpoint.\nfunc UnverifyEndpoint(cur realm, id, revision int64, reason string) {\n\treviewEndpoint(cur, id, zones.Unverified, 0, revision, reason)\n}\n\n// RemoveEndpoint deletes an endpoint. revision is its revision as read: the\n// removal fails if a verdict landed since, rather than delete one nobody saw. A\n// curator may remove any. Its registrant may remove it unless a curator flagged\n// or unverified it (a flag is a warning, an unverify carries why, and removing\n// and registering it again would wipe either; a verified one the registrant may\n// take down, since listing it again starts it unverified, and so one a reset\n// sent back to unverified, since the reset says the zone changed, not it), only while its zone is pending or approved (a rejected\n// or retired zone is a record, endpoints and all), and only ReviewWindow blocks\n// after registering it (removing and registering again every block would give\n// it a new id faster than a curator could flag the old one).\nfunc RemoveEndpoint(cur realm, id, revision int64) {\n\twho := caller(cur)\n\te, ok := reg.Endpoint(id)\n\tif !ok {\n\t\tpanic(\"zones: no endpoint #\" + strconv.FormatInt(id, 10))\n\t}\n\tif !curators.Has(who) {\n\t\tif e.Registrant != who {\n\t\t\tpanic(\"zones: only a curator or its registrant may remove endpoint #\" + strconv.FormatInt(id, 10))\n\t\t}\n\t\tif z := mustZone(e.Zone); z.Status != zones.Pending \u0026\u0026 z.Status != zones.Approved {\n\t\t\tpanic(\"zones: \" + z.Slug + \" is \" + string(z.Status) + \", a record; only a curator may remove its endpoints\")\n\t\t}\n\t\tassertWithdrawable(e)\n\t}\n\tmust(reg.RemoveEndpoint(id, revision))\n}\n\n// ClearUnreviewed removes, in one call, every endpoint on a zone that is\n// zones.Endpoint.Clearable (nobody ruled on it, and no reviewer registered it\n// past the caps), and returns how many. There are never more than\n// zones.MaxUnverifiedPerZone: clearable endpoints are a part of the review\n// queue its gate holds there, and no reset makes one. It is the answer to a\n// flood that cycles: registrants who withdraw and register again each review\n// window keep the queue full, and one removal per transaction lets them refill\n// it before a curator is done. throughRevision bounds it to what the curator\n// read: an endpoint registered after it (a later Revision) is kept. The\n// deposits go to the curator who signs. At most zones.MaxEndpointsPerZone are\n// read.\nfunc ClearUnreviewed(cur realm, slug string, throughRevision int64) int {\n\twho := caller(cur)\n\tassertCurator(who)\n\tslug = zones.TrimSpaces(slug)\n\tmustZone(slug)\n\tn := 0\n\tfor _, e := range reg.Endpoints(zones.EndpointFilter{Zone: slug, Status: zones.Unverified}) {\n\t\tif e.Clearable() \u0026\u0026 e.Revision \u003c= throughRevision {\n\t\t\tmust(reg.RemoveEndpoint(e.ID, e.Revision))\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// assertWithdrawable refuses a non-curator's withdrawal of an endpoint a\n// curator flagged or unverified, or one registered less than ReviewWindow\n// blocks ago. Shared by RemoveEndpoint, the proposer's RemoveZone and the\n// proposer's edit off local, so none can do what another refuses.\nfunc assertWithdrawable(e zones.Endpoint) {\n\tid := strconv.FormatInt(e.ID, 10)\n\t// A verification guards nothing a withdrawal could erase: the registrant\n\t// takes down a node that is going away, and listing it again starts it\n\t// unverified. A flag, or an unverify a curator wrote (a reviewer or a\n\t// reason), is a warning, and removing and registering it again would wipe\n\t// it. A reset is not: it reaches only a verified endpoint and says the zone\n\t// changed, not the endpoint, so it leaves the withdrawal a verified one had.\n\tif e.Status == zones.Flagged || (e.Status == zones.Unverified \u0026\u0026 (e.ReviewedBy != \"\" || e.Reason != \"\") \u0026\u0026 !zones.IsReset(e)) {\n\t\tpanic(\"zones: a curator ruled on endpoint #\" + id + \"; only a curator may remove it now\")\n\t}\n\tif wait := e.RegisteredAt + ReviewWindow - runtime.ChainHeight(); wait \u003e 0 {\n\t\tpanic(\"zones: endpoint #\" + id + \" was registered at block \" +\n\t\t\tstrconv.FormatInt(e.RegisteredAt, 10) + \"; it may be withdrawn in \" +\n\t\t\tstrconv.FormatInt(wait, 10) + \" blocks, so curators can review it\")\n\t}\n}\n\n// ---- curators\n\n// AddCurator invites another address to curate. Only a curator may. The\n// address becomes a curator when it calls AcceptCurator itself.\n//\n// Two steps, deliberately: a curator set is the one thing a mistake here can\n// lose for good. With a one-step add, a sole curator who invites a mistyped\n// address and then steps down leaves a registry nobody controls; accepting is\n// the proof that somebody holds the key. An invitation dies with its inviter:\n// removing a curator withdraws every invitation they sent.\nfunc AddCurator(cur realm, addr address) {\n\twho := caller(cur)\n\tassertCurator(who)\n\tif !zones.ValidAddress(addr) {\n\t\tpanic(\"zones: not a valid lowercase address: \" + addr.String())\n\t}\n\tif curators.Has(addr) {\n\t\tpanic(\"zones: \" + addr.String() + \" is already a curator\")\n\t}\n\tif invited.Has(addr) {\n\t\tpanic(\"zones: \" + addr.String() + \" is already invited\")\n\t}\n\tif curators.Size()+invited.Size() \u003e= MaxCurators {\n\t\tpanic(\"zones: \" + strconv.Itoa(MaxCurators) + \" curators and invitations already; remove one first\")\n\t}\n\tinvited.Add(addr)\n\tinviter[addr] = who\n}\n\n// AcceptCurator makes the caller a curator, if a curator invited it.\nfunc AcceptCurator(cur realm) {\n\twho := caller(cur)\n\tif !invited.Has(who) {\n\t\tpanic(\"zones: \" + who.String() + \" has no curator invitation\")\n\t}\n\tinvited.Remove(who)\n\tdelete(inviter, who)\n\tcurators.Add(who)\n}\n\n// RemoveCurator revokes a curator, along with every invitation they sent, or\n// withdraws one invitation. Only a curator may, and the last curator cannot be\n// removed: a registry nobody can curate can never retire a dead zone.\n//\n// Curators are equals: any one may remove any other, the admin included. That\n// is the trust a curator set is, and it is why there are few of them.\nfunc RemoveCurator(cur realm, addr address) {\n\tassertCurator(caller(cur))\n\tif invited.Remove(addr) {\n\t\tdelete(inviter, addr)\n\t\treturn\n\t}\n\tif !curators.Has(addr) {\n\t\tpanic(\"zones: \" + addr.String() + \" is not a curator\")\n\t}\n\tif curators.Size() == 1 {\n\t\tpanic(\"zones: \" + addr.String() + \" is the last curator\")\n\t}\n\tcurators.Remove(addr)\n\tfor _, a := range Invited() {\n\t\tif inviter[a] == addr {\n\t\t\tinvited.Remove(a)\n\t\t\tdelete(inviter, a)\n\t\t}\n\t}\n}\n\n// ---- reads: plain arguments, so `gnokey query vm/qeval` can call them\n\n// GetZone returns the zone under slug, and whether there is one.\nfunc GetZone(slug string) (zones.Zone, bool) {\n\treturn reg.Zone(zones.TrimSpaces(slug))\n}\n\n// ListZones returns the zones with that status and kind, in the order they\n// were proposed. \"\" matches any; \"approved\" is the official list.\nfunc ListZones(status, kind string) []zones.Zone {\n\tst, err := zones.ParseStatus(status)\n\tmust(err)\n\tk, err := zones.ParseKind(kind)\n\tmust(err)\n\treturn reg.Zones(zones.ZoneFilter{Status: st, Kind: k})\n}\n\n// GetEndpoint returns the endpoint with that id, and whether there is one.\nfunc GetEndpoint(id int64) (zones.Endpoint, bool) {\n\treturn reg.Endpoint(id)\n}\n\n// ListEndpoints returns a zone's endpoints of that kind and verification,\n// oldest first. \"\" matches any kind or verdict, so (\"onyx\", \"\", \"\") is\n// everything on onyx and (\"onyx\", \"peer\", \"verified\") is what a cautious node\n// should dial. The zone is required: one zone is at most MaxEndpointsPerZone\n// rows, every zone together is a response no node should be asked for.\nfunc ListEndpoints(slug, kind, status string) []zones.Endpoint {\n\treturn reg.Endpoints(endpointFilter(slug, kind, status))\n}\n\n// ListAddresses is ListEndpoints reduced to the addresses, which is what a\n// config file wants: ListAddresses(\"onyx\", \"peer\", \"verified\").\nfunc ListAddresses(slug, kind, status string) []string {\n\tes := reg.Endpoints(endpointFilter(slug, kind, status))\n\tout := make([]string, 0, len(es))\n\tfor _, e := range es {\n\t\tout = append(out, e.Address)\n\t}\n\treturn out\n}\n\n// IsInvited reports whether addr holds a curator invitation it has not\n// accepted yet.\nfunc IsInvited(addr address) bool { return invited.Has(addr) }\n\n// IsCurator reports whether addr may curate.\nfunc IsCurator(addr address) bool { return curators.Has(addr) }\n\n// Curators returns every curator, in address order.\nfunc Curators() []address { return members(\u0026curators) }\n\n// Invited returns every open curator invitation, in address order.\nfunc Invited() []address { return members(\u0026invited) }\n\nfunc members(set *addrset.Set) []address {\n\tout := make([]address, 0, set.Size())\n\tset.IterateByOffset(0, set.Size(), func(a address) bool {\n\t\tout = append(out, a)\n\t\treturn false\n\t})\n\treturn out\n}\n\n// ---- helpers\n\nfunc review(cur realm, slug string, to zones.Status, revision int64, reason string) {\n\twho := caller(cur)\n\tassertCurator(who)\n\tmust(reg.ReviewZone(zones.TrimSpaces(slug), to, revision, who, runtime.ChainHeight(), reason))\n}\n\nfunc reviewEndpoint(cur realm, id int64, to zones.Verification, zoneRevision, revision int64, reason string) {\n\twho := caller(cur)\n\tassertCurator(who)\n\tmust(reg.ReviewEndpoint(id, to, zoneRevision, revision, who, runtime.ChainHeight(), reason))\n}\n\nfunc endpointFilter(slug, kind, status string) zones.EndpointFilter {\n\tslug = zones.TrimSpaces(slug)\n\tif slug == \"\" {\n\t\tpanic(\"zones: name a zone; ListZones lists them\")\n\t}\n\tk, err := zones.ParseEndpointKind(kind)\n\tmust(err)\n\tv, err := zones.ParseVerification(status)\n\tmust(err)\n\treturn zones.EndpointFilter{Zone: slug, Kind: k, Status: v}\n}\n\nfunc info(chainID, title, description, kind, gnowebURL, rpcURL, genesisURL string) zones.Info {\n\tk, err := zones.ParseKind(kind)\n\tmust(err)\n\treturn zones.Info{\n\t\tChainID:     zones.TrimSpaces(chainID),\n\t\tTitle:       zones.TrimSpaces(title),\n\t\tDescription: zones.TrimSpaces(description),\n\t\tKind:        k,\n\t\tGnowebURL:   zones.TrimSpaces(gnowebURL),\n\t\tRPCURL:      zones.TrimSpaces(rpcURL),\n\t\tGenesisURL:  zones.TrimSpaces(genesisURL),\n\t}\n}\n\n// caller is the one place this realm decides who is acting: the realm token is\n// checked before it is walked, because an unchecked token is not a caller.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"zones: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n\n// assertReviewWindow refuses a proposer's edit or withdrawal of a pending zone\n// sooner than ReviewWindow blocks after it was proposed or last edited,\n// by anybody.\nfunc assertReviewWindow(slug string, z zones.Zone) {\n\tlast := z.ProposedAt\n\tif z.EditedAt \u003e last {\n\t\tlast = z.EditedAt\n\t}\n\tif wait := last + ReviewWindow - runtime.ChainHeight(); wait \u003e 0 {\n\t\tpanic(\"zones: \" + slug + \" was changed at block \" + strconv.FormatInt(last, 10) +\n\t\t\t\"; its proposer may act on it again in \" + strconv.FormatInt(wait, 10) + \" blocks, so curators can review it\")\n\t}\n}\n\nfunc assertCurator(who address) {\n\tif !curators.Has(who) {\n\t\tpanic(\"zones: \" + who.String() + \" is not a curator\")\n\t}\n}\n\nfunc mustZone(slug string) zones.Zone {\n\tz, ok := reg.Zone(slug)\n\tif !ok {\n\t\tpanic(\"zones: no zone \" + strconv.Quote(slug))\n\t}\n\treturn z\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n"},{"name":"zones_test.gno","body":"package zones\n\nimport (\n\t\"chain/runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/addrset/v1\"\n\t\"gno.land/p/moul/zones/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\nconst nodeID = \"g15rcv5yqef3kvnmueqvkyw8y05sd40jz9p3n5su\"\n\n// reset puts the realm back to its init() state.\n//\n// Realm globals persist for the whole test binary and examples run after every\n// Test, so without this an ExampleRender's pinned output depends silently on\n// which tests ran before it.\nfunc reset() {\n\treg = zones.NewRegistry()\n\tcurators = addrset.Set{}\n\tinvited = addrset.Set{}\n\tinviter = map[address]address{}\n\tcurators.Add(Admin)\n\tseed()\n}\n\nfunc slugs(zs []zones.Zone) string {\n\tout := []string{}\n\tfor _, z := range zs {\n\t\tout = append(out, z.Slug)\n\t}\n\treturn strings.Join(out, \" \")\n}\n\nfunc TestRealmURLMatchesTheModule(cur realm, t *testing.T) {\n\tuassert.Equal(t, \"gno.land\"+realmURL, cur.PkgPath())\n}\n\nfunc TestSeeded(t *testing.T) {\n\treset()\n\tuassert.Equal(t, \"mainnet onyx staging moul-staging\", slugs(ListZones(\"approved\", \"\")))\n\tuassert.Equal(t, \"\", slugs(ListZones(\"pending\", \"\")))\n\tuassert.Equal(t, \"onyx\", slugs(ListZones(\"\", \"testnet\")))\n\tuassert.Equal(t, \"staging moul-staging\", slugs(ListZones(\"approved\", \"devnet\")))\n\n\tz, ok := GetZone(\"onyx\")\n\turequire.True(t, ok)\n\tuassert.Equal(t, \"onyx-1\", z.ChainID)\n\tuassert.Equal(t, Admin.String(), z.ReviewedBy.String())\n\tuassert.Equal(t, seedReason, z.Reason)\n\n\tpeers := ListAddresses(\"onyx\", \"peer\", \"verified\")\n\tuassert.Equal(t, 2, len(peers))\n\tuassert.Equal(t, \"g1x5mlj5ava0dw9vkf4j6admjlzswm6f06p44krn@seed-1.onyx.testnets.gno.land:26656\", peers[0])\n\tuassert.Equal(t, \"https://rpc.gno.land\", strings.Join(ListAddresses(\"mainnet\", \"rpc\", \"\"), \",\"))\n\n\t// staging did not answer when the seed was written, so nothing on it is\n\t// verified, but it is all listed.\n\tuassert.Equal(t, 0, len(ListEndpoints(\"staging\", \"\", \"verified\")))\n\tflagged := ListEndpoints(\"staging\", \"\", \"flagged\")\n\tuassert.Equal(t, 2, len(flagged))\n\tuassert.True(t, strings.Contains(flagged[0].Reason, \"probed 2026-10-01\"))\n\tuassert.Equal(t, Admin.String(), flagged[0].ReviewedBy.String())\n\n\t// Every seed endpoint is filed under its own zone, and only there.\n\tn := 0\n\tfor _, s := range seeds() {\n\t\tuassert.Equal(t, len(s.endpoints), len(ListEndpoints(s.slug, \"\", \"\")), s.slug)\n\t\tfor _, e := range ListEndpoints(s.slug, \"\", \"\") {\n\t\t\tuassert.Equal(t, s.slug, e.Zone)\n\t\t}\n\t\tn += len(s.endpoints)\n\t}\n\tuassert.Equal(t, n, len(reg.Endpoints(zones.EndpointFilter{})))\n}\n\nfunc TestReadsRefuseUnknownFilters(cur realm, t *testing.T) {\n\treset()\n\t// The reads cross nothing, so a refusal is a plain panic, not an abort.\n\tuassert.PanicsContains(t, cur, \"unknown status\", func() { ListZones(\"official\", \"\") })\n\tuassert.PanicsContains(t, cur, \"unknown kind\", func() { ListZones(\"\", \"betanet\") })\n\tuassert.PanicsContains(t, cur, \"unknown endpoint kind\", func() { ListEndpoints(\"onyx\", \"grpc\", \"\") })\n\tuassert.PanicsContains(t, cur, \"unknown verification\", func() { ListAddresses(\"onyx\", \"\", \"trusted\") })\n\t// Every zone at once is not a read a node should be asked for.\n\tuassert.PanicsContains(t, cur, \"name a zone\", func() { ListEndpoints(\"\", \"\", \"\") })\n\tuassert.PanicsContains(t, cur, \"name a zone\", func() { ListAddresses(\"  \", \"rpc\", \"\") })\n\t_, ok := GetZone(\"nope\")\n\tuassert.False(t, ok)\n\t_, ok = GetEndpoint(9999)\n\tuassert.False(t, ok)\n}\n\nfunc TestProposeThenCurate(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tProposeZone(cross(cur), \"alice-dev\", \"alicedev-1\", \"Alice's devnet\", \"for trying things\",\n\t\t\"devnet\", \"\", \"https://rpc.alice.example.com\", \"\")\n\tz, ok := GetZone(\"alice-dev\")\n\turequire.True(t, ok)\n\tuassert.Equal(t, string(zones.Pending), string(z.Status))\n\tuassert.Equal(t, alice.String(), z.Proposer.String())\n\tuassert.Equal(t, \"alice-dev\", slugs(ListZones(\"pending\", \"\")))\n\n\t// The proposer fills in an endpoint and edits the zone (its gnoweb URL)\n\t// while pending.\n\tid := RegisterEndpoint(cross(cur), \"alice-dev\", \"peer\", nodeID+\"@alice.example.com:26656\", \"alice\")\n\t// A proposer waits between their own edits: every edit bumps the revision a\n\t// curator's decision must name, and curators need a window to make one.\n\tuassert.AbortsContains(t, cur, \"may act on it again in\", func() {\n\t\tEditZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"alicedev-1\", \"Alice's devnet\", \"for trying things\",\n\t\t\t\"devnet\", \"https://alice.example.com\", \"https://rpc.alice.example.com\", \"\", \"\")\n\t})\n\ttesting.SkipHeights(ReviewWindow)\n\tEditZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"alicedev-1\", \"Alice's devnet\", \"for trying things\",\n\t\t\"devnet\", \"https://alice.example.com\", \"https://rpc.alice.example.com\", \"\", \"\")\n\tuassert.AbortsContains(t, cur, \"may act on it again in\", func() {\n\t\tEditZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"alicedev-1\", \"Alice's devnet\", \"for trying more\",\n\t\t\t\"devnet\", \"https://alice.example.com\", \"https://rpc.alice.example.com\", \"\", \"\")\n\t})\n\tz, _ = GetZone(\"alice-dev\")\n\tuassert.Equal(t, \"https://alice.example.com\", z.GnowebURL)\n\tuassert.False(t, z.Reviewed()) // a pending edit is just an edit\n\n\t// Nobody but a curator approves, and bob cannot touch alice's proposal.\n\tuassert.AbortsContains(t, cur, \"is not a curator\", func() { ApproveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"\") })\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"only a curator, or the proposer\", func() {\n\t\tEditZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"x\", \"x\", \"\", \"devnet\", \"\", \"https://x.example.com\", \"\", \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"only a curator, or the proposer while it is pending\", func() {\n\t\tRemoveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"))\n\t})\n\tuassert.AbortsContains(t, cur, \"only a curator or its registrant\", func() {\n\t\tRemoveEndpoint(cross(cur), id, erev(id))\n\t})\n\tuassert.AbortsContains(t, cur, \"is not a curator\", func() { VerifyEndpoint(cross(cur), id, zr(id), erev(id), \"\") })\n\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tApproveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"checked the node answers\")\n\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"\")\n\tz, _ = GetZone(\"alice-dev\")\n\tuassert.Equal(t, string(zones.Approved), string(z.Status))\n\tuassert.Equal(t, \"checked the node answers\", z.Reason)\n\tuassert.Equal(t, 1, len(ListAddresses(\"alice-dev\", \"peer\", \"verified\")))\n\n\t// Approved, it is the curator's to edit now, not the proposer's.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"only a curator, or the proposer while it is pending\", func() {\n\t\tEditZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"alicedev-1\", \"renamed\", \"\", \"devnet\", \"\", \"https://rpc.alice.example.com\", \"\", \"x\")\n\t})\n\n\t// A curator's edit to a reviewed zone replaces the review on record, and\n\t// needs a reason, so the page never shows new values under the old review.\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.AbortsContains(t, cur, \"an edit needs a reason\", func() {\n\t\tEditZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"alicedev-1\", \"Alice's devnet\", \"\", \"devnet\", \"\", \"https://rpc2.alice.example.com\", \"\", \"\")\n\t})\n\tEditZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"alicedev-1\", \"Alice's devnet\", \"\", \"devnet\", \"\", \"https://rpc2.alice.example.com\", \"\", \"rpc moved\")\n\tz, _ = GetZone(\"alice-dev\")\n\tuassert.Equal(t, \"https://rpc2.alice.example.com\", z.RPCURL)\n\tuassert.Equal(t, \"rpc moved\", z.Reason)\n\tuassert.Equal(t, string(zones.Approved), string(z.Status))\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t// Nor hers to remove; and not even a curator removes an approved zone: it is\n\t// retired instead.\n\tuassert.AbortsContains(t, cur, \"while it is pending, may remove\", func() { RemoveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\")) })\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.AbortsContains(t, cur, \"retire it instead\", func() { RemoveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\")) })\n\tuassert.AbortsContains(t, cur, \"needs a reason\", func() { RetireZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"\") })\n\tRetireZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"alice turned it off\")\n\tz, _ = GetZone(\"alice-dev\")\n\tuassert.Equal(t, string(zones.Retired), string(z.Status))\n\t_, err := reg.Register(bob, 1, \"alice-dev\", zones.RPC, \"https://late.example.com\", \"\")\n\tuassert.ErrorContains(t, err, \"takes no endpoints\")\n\n\t// Retired, it is a record the curators keep: the proposer cannot erase it.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"while it is pending, may remove\", func() { RemoveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\")) })\n\t// Nor can a curator: a retired zone is kept on record.\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.AbortsContains(t, cur, \"kept on record\", func() { RemoveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\")) })\n\t_, ok = GetZone(\"alice-dev\")\n\tuassert.True(t, ok)\n}\n\n// The printed command is pasted into a shell. The main RPC cannot carry shell\n// syntax at all; the quote is defense in depth.\nfunc TestQueryCommandQuotesTheRemote(t *testing.T) {\n\treset()\n\t// Two layers. The main RPC cannot carry shell syntax at all: its host is\n\t// [A-Za-z0-9.-], its port digits, and a path, query or fragment is refused.\n\t// And the printed remote is single-quoted anyway, in case a later version\n\t// widens the validator.\n\tz, _ := GetZone(\"moul-staging\")\n\tin := zones.Info{ChainID: runtime.ChainID(), Title: z.Title, Kind: z.Kind, RPCURL: \"https://rpc.example.com/;id;\"}\n\tuassert.ErrorContains(t, reg.Edit(\"moul-staging\", zrev(\"moul-staging\"), in, Admin, 1, \"test\"), \"no path\")\n\tin.RPCURL = \"https://rpc.example.com:443\"\n\tmust(reg.Edit(\"moul-staging\", zrev(\"moul-staging\"), in, Admin, 1, \"test\"))\n\tgot := queryCommand(`GetZone(\"onyx\")`)\n\tuassert.Equal(t, `gnokey query vm/qeval -remote 'https://rpc.example.com:443' -data 'gno.land/r/moul/zones/v0.GetZone(\"onyx\")'`, got)\n\n\t// Two approved zones on the same chain id: no -remote, rather than a guess.\n\tmust(reg.Edit(\"staging\", zrev(\"staging\"), zones.Info{ChainID: runtime.ChainID(), Title: \"S\", Kind: zones.Devnet,\n\t\tRPCURL: \"https://other.example.com\"}, Admin, 1, \"test\"))\n\tuassert.Equal(t, `gnokey query vm/qeval -data 'gno.land/r/moul/zones/v0.GetZone(\"onyx\")'`, queryCommand(`GetZone(\"onyx\")`))\n\tuassert.ErrorContains(t, zones.ValidateEndpoint(zones.RPC, \"https://rpc.example.com/'x\"), \"contains\")\n}\n\nfunc TestRejectAndWithdraw(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"fake-mainnet\", \"gnoland-1\", \"Mainnet (faster!)\", \"\",\n\t\t\"mainnet\", \"\", \"https://rpc.fake.example.com\", \"\")\n\tRegisterEndpoint(cross(cur), \"fake-mainnet\", \"rpc\", \"https://bob.example.com\", \"\")\n\t// A stranger cannot pin a pending proposal with an endpoint of their own.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"only its proposer or a curator may register\", func() {\n\t\tRegisterEndpoint(cross(cur), \"fake-mainnet\", \"rpc\", \"https://alice.example.com\", \"\")\n\t})\n\t// A curator can.\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\ttheirs := RegisterEndpoint(cross(cur), \"fake-mainnet\", \"rpc\", \"https://curator.example.com\", \"\")\n\n\tuassert.AbortsContains(t, cur, \"needs a reason\", func() { RejectZone(cross(cur), \"fake-mainnet\", zrev(\"fake-mainnet\"), \"  \") })\n\tRejectZone(cross(cur), \"fake-mainnet\", zrev(\"fake-mainnet\"), \"not the mainnet RPC\")\n\tz, _ := GetZone(\"fake-mainnet\")\n\tuassert.Equal(t, string(zones.Rejected), string(z.Status))\n\tuassert.Equal(t, \"fake-mainnet\", slugs(ListZones(\"rejected\", \"\")))\n\tuassert.Equal(t, \"mainnet onyx staging moul-staging\", slugs(ListZones(\"approved\", \"\")))\n\n\t// A rejected zone is the curators' record: its proposer cannot take it down\n\t// (and so cannot collect the deposit the curator paid to record the\n\t// rejection). A curator can.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"while it is pending, may remove\", func() {\n\t\tRemoveZone(cross(cur), \"fake-mainnet\", zrev(\"fake-mainnet\"))\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRemoveEndpoint(cross(cur), theirs, erev(theirs))\n\tRemoveZone(cross(cur), \"fake-mainnet\", zrev(\"fake-mainnet\"))\n\t_, ok := GetZone(\"fake-mainnet\")\n\tuassert.False(t, ok)\n\n\t// A proposer withdrawing a PENDING zone waits out the review window, and cannot\n\t// while it carries somebody else's endpoint: the refund for it, which they\n\t// paid, would go to the proposer who signs.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bob-again\", \"bob-1\", \"Bob again\", \"\", \"devnet\", \"\", \"https://rpc.bob.example.com\", \"\")\n\tuassert.AbortsContains(t, cur, \"may act on it again in\", func() {\n\t\tRemoveZone(cross(cur), \"bob-again\", zrev(\"bob-again\"))\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRegisterEndpoint(cross(cur), \"bob-again\", \"rpc\", \"https://curator2.example.com\", \"\")\n\ttesting.SkipHeights(ReviewWindow)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"must be removed first\", func() {\n\t\tRemoveZone(cross(cur), \"bob-again\", zrev(\"bob-again\"))\n\t})\n}\n\n// A registrant withdraws their endpoint only after the review window: removing and\n// registering again every block would give it a new id faster than a curator\n// could flag the old one.\nfunc TestRegistrantWithdrawalWaits(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://cycle.example.com\", \"\")\n\tuassert.AbortsContains(t, cur, \"may be withdrawn in\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n\ttesting.SkipHeights(ReviewWindow)\n\tRemoveEndpoint(cross(cur), id, erev(id))\n\t_, ok := GetEndpoint(id)\n\tuassert.False(t, ok)\n}\n\nfunc TestEndpointLifecycle(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://onyx-rpc.bob.example.com\", \"bob's node\")\n\te, ok := GetEndpoint(id)\n\turequire.True(t, ok)\n\tuassert.Equal(t, string(zones.Unverified), string(e.Status))\n\tuassert.Equal(t, bob.String(), e.Registrant.String())\n\n\t// Unverified is listed, and a verified-only read leaves it out.\n\tuassert.Equal(t, 2, len(ListAddresses(\"onyx\", \"rpc\", \"\")))\n\tuassert.Equal(t, 1, len(ListAddresses(\"onyx\", \"rpc\", \"verified\")))\n\n\tuassert.AbortsContains(t, cur, \"already lists that rpc\", func() {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://ONYX-rpc.bob.example.com\", \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"unknown endpoint kind\", func() {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"grpc\", \"https://x.example.com\", \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"no zone\", func() {\n\t\tRegisterEndpoint(cross(cur), \"nope\", \"rpc\", \"https://x.example.com\", \"\")\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.AbortsContains(t, cur, \"needs a reason\", func() { FlagEndpoint(cross(cur), id, erev(id), \"\") })\n\tFlagEndpoint(cross(cur), id, erev(id), \"answers for the wrong chain id\")\n\te, _ = GetEndpoint(id)\n\tuassert.Equal(t, string(zones.Flagged), string(e.Status))\n\tuassert.Equal(t, 1, len(ListEndpoints(\"onyx\", \"rpc\", \"flagged\")))\n\tUnverifyEndpoint(cross(cur), id, erev(id), \"bob fixed it\")\n\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"\")\n\tuassert.Equal(t, 2, len(ListAddresses(\"onyx\", \"rpc\", \"verified\")))\n\n\t// Flagged, it is a warning: its registrant cannot take it down (and so\n\t// cannot wipe it by registering it again).\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tFlagEndpoint(cross(cur), id, erev(id), \"serves the wrong chain\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"a curator ruled on\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n\t// Unverified by a curator, it carries why: still not the registrant's to\n\t// take down, even after the review window, or removing and registering it\n\t// again would wipe the warning. A curator may.\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tUnverifyEndpoint(cross(cur), id, erev(id), \"key was sold; re-checking\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tuassert.AbortsContains(t, cur, \"a curator ruled on\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRemoveEndpoint(cross(cur), id, erev(id))\n\t_, ok = GetEndpoint(id)\n\tuassert.False(t, ok)\n\tuassert.AbortsContains(t, cur, \"no endpoint\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n}\n\nfunc TestCurators(cur realm, t *testing.T) {\n\treset()\n\tuassert.True(t, IsCurator(Admin))\n\tuassert.False(t, IsCurator(alice))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"is not a curator\", func() { AddCurator(cross(cur), alice) })\n\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.AbortsContains(t, cur, \"is the last curator\", func() { RemoveCurator(cross(cur), Admin) })\n\tAddCurator(cross(cur), alice)\n\tuassert.AbortsContains(t, cur, \"already invited\", func() { AddCurator(cross(cur), alice) })\n\t// An invitation is not a seat: until alice accepts, the admin is still the\n\t// last curator, so a mistyped invite cannot strand the registry.\n\tuassert.True(t, IsInvited(alice))\n\tuassert.False(t, IsCurator(alice))\n\tuassert.Equal(t, 1, len(Curators()))\n\tuassert.AbortsContains(t, cur, \"is the last curator\", func() { RemoveCurator(cross(cur), Admin) })\n\t// Withdrawing an invitation works, and a withdrawn one cannot be accepted.\n\tAddCurator(cross(cur), bob)\n\tRemoveCurator(cross(cur), bob)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"has no curator invitation\", func() { AcceptCurator(cross(cur)) })\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAcceptCurator(cross(cur))\n\tuassert.True(t, IsCurator(alice))\n\tuassert.False(t, IsInvited(alice))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.AbortsContains(t, cur, \"already a curator\", func() { AddCurator(cross(cur), alice) })\n\tuassert.Equal(t, 2, len(Curators()))\n\n\t// A curator added by the admin curates on equal terms, the admin included.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tProposeZone(cross(cur), \"alice-dev\", \"alicedev-1\", \"Alice's devnet\", \"\", \"devnet\", \"\", \"https://rpc.alice.example.com\", \"\")\n\tApproveZone(cross(cur), \"alice-dev\", zrev(\"alice-dev\"), \"\")\n\tRemoveCurator(cross(cur), Admin)\n\tuassert.False(t, IsCurator(Admin))\n\tuassert.AbortsContains(t, cur, \"is not a curator\", func() { RemoveCurator(cross(cur), bob) })\n}\n\n// Every caller string a Render interpolates is escaped: a title that is a link,\n// a reason that would open a table column. The shapes that can carry markup at\n// all (slug, chain id, URL) are refused at write time instead, so they never\n// reach a Render.\nfunc TestRenderEscapesCallerText(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tProposeZone(cross(cur), \"evil\", \"evil-1\", \"[click](https://evil.example.com)\", \"**bold** | col\",\n\t\t\"devnet\", \"\", \"https://rpc.evil.example.com\", \"\")\n\tRegisterEndpoint(cross(cur), \"evil\", \"rpc\", \"https://rpc2.evil.example.com\", \"a|b\")\n\n\tpage := Render(\"zone/evil\")\n\tuassert.False(t, strings.Contains(page, \"[click](https://evil.example.com)\"), \"a title renders as text, not a link\")\n\tuassert.False(t, strings.Contains(page, \"**bold**\"), \"a description renders as text, not markup\")\n\tuassert.True(t, strings.Contains(page, `a\\|b`), \"a label cannot open a table column\")\n\n\t// A pipe in a title cannot open a column in the zone tables.\n\tProposeZone(cross(cur), \"evil-pipe\", \"evil-9\", \"Alice|official\", \"\", \"devnet\", \"\", \"https://rpc.pipe.example.com\", \"\")\n\tuassert.True(t, strings.Contains(Render(\"proposals\"), `[Alice\\|official](/r/moul/zones/v0:zone/evil-pipe)`))\n\n\t// A scheme and host are stored lowercased, so the link is live (the\n\t// sanitizer gno's md.Link uses accepts lowercase http and https only) and\n\t// every later lowercasing is free; the path keeps its case.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"upper\", \"upper-1\", \"Upper\", \"\", \"devnet\", \"HTTPS://Upper.example.com/Web\", \"HTTPS://rpc.upper.example.com\", \"\")\n\tz, _ := GetZone(\"upper\")\n\tuassert.Equal(t, \"https://upper.example.com/Web\", z.GnowebURL)\n\tuassert.Equal(t, \"https://rpc.upper.example.com\", z.RPCURL)\n\t// A proposal's URL is shown as code, to copy and check, not as a link.\n\tuassert.True(t, strings.Contains(Render(\"zone/upper\"), \"`https://upper.example.com/Web`\"))\n\tuassert.False(t, strings.Contains(Render(\"zone/upper\"), \"](https://upper.example.com/Web)\"))\n\tid := RegisterEndpoint(cross(cur), \"upper\", \"faucet\", \"HTTP://f.upper.example.com\", \"\")\n\te, _ := GetEndpoint(id)\n\tuassert.Equal(t, \"http://f.upper.example.com\", e.Address)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsContains(t, cur, \"contains\", func() {\n\t\tProposeZone(cross(cur), \"evil2\", \"evil-2\", \"x\", \"\", \"devnet\", \"\", \"https://rpc.evil.example.com/)[x](y\", \"\")\n\t})\n\tuassert.AbortsContains(t, cur, \"slug\", func() {\n\t\tProposeZone(cross(cur), \"evil|3\", \"evil-3\", \"x\", \"\", \"devnet\", \"\", \"https://rpc.evil.example.com\", \"\")\n\t})\n}\n\nfunc TestRenderPagesAnswer(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"zone/nope\"), \"No such zone.\"))\n\tuassert.True(t, strings.Contains(Render(\"nope\"), \"No such page.\"))\n\tuassert.True(t, strings.Contains(Render(\"proposals\"), \"Nothing waiting for review.\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/staging\"), \"⚠️ flagged: did not answer when probed 2026\\\\-10\\\\-01\"))\n}\n\n// Every list is paginated and clamps a reader's ?page=, which is what keeps a\n// full registry inside vm/qrender's gas. What a page reads is measured\n// separately; this test pins only the paging.\nfunc TestRenderPaginates(t *testing.T) {\n\treset()\n\tfor i := 0; i \u003c 2*PageSize; i++ {\n\t\tslug := \"z\" + strconv.Itoa(i)\n\t\tmust(reg.Propose(alice, 1, slug, info(\"c-\"+strconv.Itoa(i), \"Zone \"+strconv.Itoa(i), \"\", \"devnet\", \"\", \"https://r\"+strconv.Itoa(i)+\".example.com\", \"\")))\n\t\tmust(reg.ReviewZone(slug, zones.Approved, zrev(slug), Admin, 2, \"\"))\n\t}\n\t// 4 seeded + 50 = 54 approved, so 3 pages of 25.\n\tfirst := Render(\"\")\n\tuassert.True(t, strings.Contains(first, \"page 1 of 3\"))\n\tuassert.True(t, strings.Contains(first, \"Zone 20\"))\n\tuassert.False(t, strings.Contains(first, \"Zone 21\"), \"row 26 is on page 2\")\n\tlast := Render(\"?page=3\")\n\tuassert.True(t, strings.Contains(last, \"Zone 49\"))\n\tuassert.False(t, strings.Contains(last, \"Zone 45]\"))\n\tuassert.True(t, strings.Contains(last, \"page 3 of 3\"))\n\tuassert.Equal(t, first, Render(\"?page=-1\"))\n\tuassert.Equal(t, last, Render(\"?page=99999999999999999\"))\n\tuassert.Equal(t, last, Render(\"?page=999999999999999999999999999999\"), \"past int is past the end, not page 1\")\n\tuassert.Equal(t, last, Render(\"?page=%2B999999999999999999999999999999\"), \"a + sign does not change that\")\n\tuassert.True(t, strings.Contains(Render(\"?page=%2B2\"), \"page 2 of 3\"))\n\tuassert.Equal(t, first, Render(\"?page=-999999999999999999999999999999\"))\n\tuassert.Equal(t, first, Render(\"?page=nope\"))\n\tuassert.True(t, strings.Contains(Render(\"?status=nope\"), \"No such list.\"))\n\n\tfor i := 0; i \u003c PageSize+3; i++ {\n\t\twho := testutils.TestAddress(\"reg\" + strconv.Itoa(i/10))\n\t\t_, err := reg.Register(who, 3, \"z0\", zones.RPC, \"https://e\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tmust(err)\n\t}\n\t_, err := reg.Register(alice, 3, \"z0\", zones.Peer, nodeID+\"@p.example.com:26656\", \"\")\n\tmust(err)\n\tzp := Render(\"zone/z0\")\n\tuassert.True(t, strings.Contains(zp, \"page 1 of 2\"))\n\tuassert.True(t, strings.Contains(zp, \"**all (29)**\"))\n\tuassert.True(t, strings.Contains(zp, `[rpc \\(28\\)](/r/moul/zones/v0:zone/z0?kind=rpc)`))\n\tpeers := Render(\"zone/z0?kind=peer\")\n\tuassert.True(t, strings.Contains(peers, \"p.example.com\"))\n\tuassert.False(t, strings.Contains(peers, \"e0.example.com\"))\n\tuassert.False(t, strings.Contains(peers, \"page 1 of\"), \"one page needs no pager\")\n\tuassert.True(t, strings.Contains(Render(\"zone/z0?kind=rpc\u0026page=2\"), \"[previous](/r/moul/zones/v0:zone/z0?kind=rpc\u0026page=1)\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/z0?kind=grpc\"), \"No such endpoint kind.\"))\n}\n\n// zrev is a zone's current revision, what a curator who just read it approves.\nfunc zrev(slug string) int64 {\n\tz, _ := GetZone(slug)\n\treturn z.Revision\n}\n\n// erev is an endpoint's revision, what a verdict or a removal names.\nfunc erev(id int64) int64 {\n\te, ok := GetEndpoint(id)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn e.Revision\n}\n\n// zr is the revision of an endpoint's zone, what a verification also names.\nfunc zr(id int64) int64 {\n\te, ok := GetEndpoint(id)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn zrev(e.Zone)\n}\n\n// An invitation dies with its inviter, can be listed, and the set is bounded.\nfunc TestCuratorInvitations(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tupper := address(strings.ToUpper(alice.String()))\n\tuassert.AbortsContains(t, cur, \"lowercase\", func() { AddCurator(cross(cur), upper) })\n\n\tAddCurator(cross(cur), alice)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAcceptCurator(cross(cur))\n\t// alice invites bob, then is removed: bob's invitation goes with her.\n\tAddCurator(cross(cur), bob)\n\tuassert.Equal(t, bob.String(), Invited()[0].String())\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRemoveCurator(cross(cur), alice)\n\tuassert.False(t, IsInvited(bob))\n\tuassert.Equal(t, 0, len(Invited()))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"has no curator invitation\", func() { AcceptCurator(cross(cur)) })\n\n\t// Curators and open invitations together stop at MaxCurators.\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tfor i := 1; i \u003c MaxCurators; i++ {\n\t\tAddCurator(cross(cur), testutils.TestAddress(\"c\"+strconv.Itoa(i)))\n\t}\n\tuassert.AbortsContains(t, cur, \"remove one first\", func() { AddCurator(cross(cur), bob) })\n\tRemoveCurator(cross(cur), testutils.TestAddress(\"c1\"))\n\tAddCurator(cross(cur), bob)\n}\n\nfunc TestRenderRoutesAreExact(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx/approved-by-gno-core\"), \"No such page.\"))\n\tuassert.True(t, strings.Contains(Render(\"proposals/x\"), \"No such page.\"))\n\tuassert.True(t, strings.Contains(Render(\"zone\"), \"No such page.\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx?kind=%20rpc\"), \"No such endpoint kind.\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx?kind=seed\"), \"No seed endpoint registered yet.\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"Approve revision\") == false, \"an approved zone offers no Approve\")\n}\n\n// gnoweb turns an @name into a user-profile link with an icon; free text\n// carries a backslash before every @ so a label cannot vouch for an account.\nfunc TestMentionsAreEscaped(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://m.example.com\", \"run by @gnocore\")\n\tpage := Render(\"zone/onyx?kind=rpc\")\n\tuassert.True(t, strings.Contains(page, `run by \\@gnocore`))\n\tuassert.False(t, strings.Contains(page, \"run by @gnocore\"))\n}\n\n// The printed -remote is never one the same page flags.\nfunc TestQueryCommandSkipsAFlaggedRemote(cur realm, t *testing.T) {\n\treset()\n\tz, _ := GetZone(\"moul-staging\")\n\tin := zones.Info{ChainID: runtime.ChainID(), Title: z.Title, Kind: z.Kind, RPCURL: z.RPCURL, GnowebURL: z.GnowebURL}\n\tmust(reg.Edit(\"moul-staging\", zrev(\"moul-staging\"), in, Admin, 1, \"test\"))\n\tuassert.True(t, strings.Contains(queryCommand(\"X()\"), \"-remote 'https://rpc.gno-staging.moul.p2p.team'\"))\n\te, ok := reg.EndpointByAddress(\"moul-staging\", zones.RPC, z.RPCURL)\n\turequire.True(t, ok)\n\tmust(reg.ReviewEndpoint(e.ID, zones.Flagged, 0, erev(e.ID), Admin, 2, \"down\"))\n\tuassert.False(t, strings.Contains(queryCommand(\"X()\"), \"-remote\"))\n}\n\n// A proposer cannot wipe a curator's verdict by removing the zone and\n// proposing it again.\nfunc TestProposerCannotRemoveOverAVerdict(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tid := RegisterEndpoint(cross(cur), \"bobs\", \"peer\", nodeID+\"@p.bobs.example.com:26656\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tFlagEndpoint(cross(cur), id, erev(id), \"malicious peer\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tuassert.AbortsContains(t, cur, \"a curator ruled on\", func() {\n\t\tRemoveZone(cross(cur), \"bobs\", zrev(\"bobs\"))\n\t})\n}\n\n// A bare g1 address in free text would become a profile link: its 1 is\n// written as a character reference so the mention parser does not match.\nfunc TestBareAddressesAreNotMentions(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://g.example.com\", \"run by \"+Admin.String())\n\tpage := Render(\"zone/onyx?kind=rpc\")\n\tuassert.False(t, strings.Contains(page, \"run by g1manfred\"))\n\tuassert.True(t, strings.Contains(page, \"run by g\u0026#49;manfred\"))\n}\n\n// The main RPC is marked where it is shown when its endpoint is flagged, so the\n// official table and the zone page agree (TestQueryCommandSkipsAFlaggedRemote\n// covers the printed command).\nfunc TestFlaggedMainRPCIsMarked(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"\"), \"`https://rpc.staging.gno.land` ⚠️ flagged\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/staging\"), \"`https://rpc.staging.gno.land` ⚠️ flagged\"))\n\tuassert.False(t, strings.Contains(Render(\"\"), \"`https://rpc.gno.land` ⚠️\"))\n}\n\n// A flagged gnoweb URL is shown as code and marked, never as a link the page's\n// own endpoint table says not to use.\nfunc TestFlaggedGnowebIsNotALink(t *testing.T) {\n\treset()\n\tpage := Render(\"zone/staging\")\n\tuassert.True(t, strings.Contains(page, \"`https://staging.gno.land` ⚠️ flagged\"))\n\tuassert.False(t, strings.Contains(page, \"](https://staging.gno.land)\"))\n}\n\n// A curator's flag on an rpc endpoint under the tcp:// spelling still marks a\n// main RPC written as http://, and the reverse: gnokey dials them alike.\nfunc TestFlaggedRPCMatchesAcrossTcpAndHttp(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ := GetZone(\"onyx\")\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"tcp://rpc.tcp.example.com:26657\", \"\")\n\tFlagEndpoint(cross(cur), id, erev(id), \"down\")\n\tin := zones.Info{ChainID: z.ChainID, Title: z.Title, Description: z.Description, Kind: z.Kind,\n\t\tGnowebURL: z.GnowebURL, RPCURL: \"http://rpc.tcp.example.com:26657\", GenesisURL: z.GenesisURL}\n\tmust(reg.Edit(\"onyx\", zrev(\"onyx\"), in, Admin, 1, \"moved\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"`http://rpc.tcp.example.com:26657` ⚠️ flagged\"))\n\n\tid = RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"http://rpc.http.example.com:26657\", \"\")\n\tFlagEndpoint(cross(cur), id, erev(id), \"down\")\n\tin.RPCURL = \"tcp://rpc.http.example.com:26657\"\n\tmust(reg.Edit(\"onyx\", zrev(\"onyx\"), in, Admin, 2, \"moved back\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"`tcp://rpc.http.example.com:26657` ⚠️ flagged\"))\n}\n\n// A page offers an action only while somebody's call can succeed: with the\n// review queue full, Propose stays for curators only; with the live registry\n// full, Propose and a rejected zone's Approve give way to a note.\nfunc TestFullQueuesSayWhoMayStillAct(t *testing.T) {\n\treset()\n\tin := func(i int) zones.Info {\n\t\treturn zones.Info{ChainID: \"fill-\" + strconv.Itoa(i), Title: \"Fill\", Kind: zones.Testnet,\n\t\t\tRPCURL: \"https://rpc\" + strconv.Itoa(i) + \".example.com\"}\n\t}\n\tslug := func(i int) string { return \"fill-\" + strconv.Itoa(i) }\n\twho := func(i int) address { return testutils.TestAddress(\"p\" + strconv.Itoa(i/zones.MaxPendingPerProposer)) }\n\n\tmust(reg.Propose(alice, 1, \"nope\", in(-1)))\n\tmust(reg.ReviewZone(\"nope\", zones.Rejected, zrev(\"nope\"), Admin, 1, \"no\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/nope\"), \"Approve revision\"))\n\n\tfor i := 0; i \u003c zones.MaxPending; i++ {\n\t\tmust(reg.Propose(who(i), 2, slug(i), in(i)))\n\t}\n\t// The queue is full for everybody but curators: the note says so, and the\n\t// link stays, labelled for them.\n\tuassert.True(t, strings.Contains(Render(\"\"), \"the review queue is full at 64 proposals\"))\n\tuassert.True(t, strings.Contains(Render(\"\"), \"curators only, while full\"))\n\n\t// Approve the queue away, then keep proposing and approving until the live\n\t// registry is full: no proposal is waiting, so Propose is hidden by the\n\t// live cap alone.\n\tfor i := 0; i \u003c zones.MaxPending; i++ {\n\t\tmust(reg.ReviewZone(slug(i), zones.Approved, zrev(slug(i)), Admin, 3, \"\"))\n\t}\n\tuassert.True(t, strings.Contains(Render(\"\"), \"func=ProposeZone\"))\n\tfor i := zones.MaxPending; reg.Live() \u003c zones.MaxZones; i++ {\n\t\tmust(reg.ProposeExempt(who(i), 4, slug(i), in(i)))\n\t\tmust(reg.ReviewZone(slug(i), zones.Approved, zrev(slug(i)), Admin, 4, \"\"))\n\t}\n\tuassert.Equal(t, 0, reg.ZoneCount(zones.Pending))\n\tuassert.False(t, strings.Contains(Render(\"zone/nope\"), \"Approve revision\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/nope\"), \"approving it waits for a free place\"))\n\tuassert.False(t, strings.Contains(Render(\"\"), \"func=ProposeZone\"), \"the live cap binds curators too\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"the registry is full at 256 live zones\"))\n}\n\n// Withdrawing the zone is no way round an endpoint's own review window: the\n// proposer removing it the block an endpoint appears would delete it before a\n// curator could see it.\nfunc TestRemoveZoneWaitsForItsEndpoints(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\ttesting.SkipHeights(ReviewWindow)\n\tRegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://fresh.bobs.example.com\", \"\")\n\tuassert.AbortsContains(t, cur, \"may be withdrawn in\", func() { RemoveZone(cross(cur), \"bobs\", zrev(\"bobs\")) })\n\ttesting.SkipHeights(ReviewWindow)\n\tRemoveZone(cross(cur), \"bobs\", zrev(\"bobs\"))\n\t_, ok := GetZone(\"bobs\")\n\tuassert.False(t, ok)\n}\n\n// A rejected zone is a record, endpoints and all: its registrant cannot strip\n// the evidence a rejection cites.\nfunc TestRejectedZoneKeepsItsEndpoints(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"fake\", \"fake-1\", \"Fake\", \"\", \"devnet\", \"\", \"https://rpc.fake.example.com\", \"\")\n\tid := RegisterEndpoint(cross(cur), \"fake\", \"rpc\", \"https://phish.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRejectZone(cross(cur), \"fake\", zrev(\"fake\"), \"its rpc is a phishing clone\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tuassert.AbortsContains(t, cur, \"is rejected, a record\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n}\n\n// Curators pass the admission gates: a flood that fills the review queue does\n// not lock out the people who clear it. The hard caps still hold.\nfunc TestCuratorsPassTheAdmissionGates(cur realm, t *testing.T) {\n\treset()\n\tin := func(i int) zones.Info {\n\t\treturn zones.Info{ChainID: \"f-\" + strconv.Itoa(i), Title: \"F\", Kind: zones.Testnet,\n\t\t\tRPCURL: \"https://rpc\" + strconv.Itoa(i) + \".example.com\"}\n\t}\n\tfor i := 0; i \u003c zones.MaxPending; i++ {\n\t\tmust(reg.Propose(testutils.TestAddress(\"p\"+strconv.Itoa(i/zones.MaxPendingPerProposer)), 1, \"f-\"+strconv.Itoa(i), in(i)))\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"waiting for review\", func() {\n\t\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tProposeZone(cross(cur), \"admins\", \"admins-1\", \"Admin's\", \"\", \"devnet\", \"\", \"https://rpc.admins.example.com\", \"\")\n\tfor i := 0; i \u003c zones.MaxPendingPerProposer; i++ {\n\t\tProposeZone(cross(cur), \"a-\"+strconv.Itoa(i), \"a-\"+strconv.Itoa(i), \"A\", \"\", \"devnet\", \"\", \"https://rpc.a\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t}\n\n\tfor i := 0; i \u003c zones.MaxUnverifiedPerZone; i++ {\n\t\t_, err := reg.Register(testutils.TestAddress(\"r\"+strconv.Itoa(i/zones.MaxEndpointsPerAddress)), 2, \"onyx\", zones.RPC,\n\t\t\t\"https://n\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tmust(err)\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"waiting for review\", func() {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://bob.example.com\", \"\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tfor i := 0; reg.EndpointCount(\"onyx\", \"\") \u003c zones.MaxEndpointsPerZone; i++ {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://c\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t}\n\tuassert.AbortsContains(t, cur, \"is full at\", func() {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://over.example.com\", \"\")\n\t})\n}\n\n// A flag can be restated with a new reason, so correcting one never passes\n// through a state its registrant could remove it from.\nfunc TestAFlagsReasonCanBeAmended(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://typo.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tFlagEndpoint(cross(cur), id, erev(id), \"srves the wrong chian\")\n\tFlagEndpoint(cross(cur), id, erev(id), \"serves the wrong chain\")\n\te, _ := GetEndpoint(id)\n\tuassert.Equal(t, \"serves the wrong chain\", e.Reason)\n\tuassert.AbortsContains(t, cur, \"already flagged\", func() { FlagEndpoint(cross(cur), id, erev(id), \"serves the wrong chain\") })\n\tuassert.Equal(t, 0, reg.Awaiting(\"onyx\"), \"restating a flag does not count it twice\")\n}\n\n// Only a flag under the kind a URL is shown as marks it: a listing under\n// another kind is anybody's to make, so its flag never marks the zone's own\n// URL. The genesis URL, which no kind lists, is never marked.\nfunc TestOnlyTheShownKindsFlagMarks(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tz, _ := GetZone(\"mainnet\")\n\tmisKinded := []int64{\n\t\tRegisterEndpoint(cross(cur), \"mainnet\", \"explorer\", z.RPCURL, \"\"),\n\t\tRegisterEndpoint(cross(cur), \"mainnet\", \"faucet\", z.GnowebURL, \"\"),\n\t\tRegisterEndpoint(cross(cur), \"mainnet\", \"explorer\", z.GenesisURL, \"\"),\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tfor _, id := range misKinded {\n\t\tFlagEndpoint(cross(cur), id, erev(id), \"not that kind\")\n\t}\n\tpage := Render(\"zone/mainnet\")\n\tuassert.False(t, strings.Contains(page, \"` ⚠️ flagged\"), \"no fact is marked by another kind's flag\")\n\tuassert.True(t, strings.Contains(page, \"](https://gno.land)\"))\n\tuassert.False(t, strings.Contains(Render(\"\"), \"`\"+z.RPCURL+\"` ⚠️\"))\n\n\t// Its own kind's flag does mark it.\n\te, ok := reg.EndpointByAddress(\"mainnet\", zones.Gnoweb, z.GnowebURL)\n\turequire.True(t, ok)\n\tFlagEndpoint(cross(cur), e.ID, erev(e.ID), \"a phishing clone took the name\")\n\tpage = Render(\"zone/mainnet\")\n\tuassert.True(t, strings.Contains(page, \"`https://gno.land` ⚠️ flagged\"))\n\tuassert.False(t, strings.Contains(page, \"](https://gno.land)\"))\n}\n\n// The note in place of an action says which cap is full, and nothing more:\n// advice on what frees it could name the zone the note is shown on.\nfunc TestFullCapsSayWhichIsFull(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tfor i := 0; reg.EndpointCount(\"onyx\", \"\") \u003c zones.MaxEndpointsPerZone; i++ {\n\t\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://c\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tFlagEndpoint(cross(cur), id, erev(id), \"spam\")\n\t}\n\tpage := Render(\"zone/onyx\")\n\tuassert.True(t, strings.Contains(page, \"endpoints are full at 128\"))\n\tuassert.False(t, strings.Contains(page, \"func=RegisterEndpoint\"))\n\n\tfor i := 0; reg.EndpointCount(\"mainnet\", \"\") \u003c zones.MaxUnverifiedPerZone+8; i++ {\n\t\tRegisterEndpoint(cross(cur), \"mainnet\", \"rpc\", \"https://m\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t}\n\tuassert.True(t, reg.Awaiting(\"mainnet\") \u003e= zones.MaxUnverifiedPerZone)\n\tpage = Render(\"zone/mainnet\")\n\tuassert.True(t, strings.Contains(page, \"the review queue is full at 64 endpoints awaiting review\"))\n\tuassert.True(t, strings.Contains(page, \"curators only, while full\"))\n}\n\n// An edited zone names its editor in full, as it does its proposer.\nfunc TestEditorIsShownInFull(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ := GetZone(\"onyx\")\n\tEditZone(cross(cur), \"onyx\", z.Revision, z.ChainID, \"Onyx, edited\", z.Description, string(z.Kind),\n\t\tz.GnowebURL, z.RPCURL, z.GenesisURL, \"a better title\")\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"**edited** by `\"+Admin.String()+\"`\"))\n}\n\n// A curator clears a cycling flood in one call; whatever a curator ruled on\n// stays.\nfunc TestClearUnreviewed(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tspam := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://spam1.example.com\", \"\")\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://spam2.example.com\", \"\")\n\truled := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://ruled.example.com\", \"\")\n\tuassert.AbortsContains(t, cur, \"is not a curator\", func() { ClearUnreviewed(cross(cur), \"onyx\", reg.Revision()) })\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tUnverifyEndpoint(cross(cur), ruled, erev(ruled), \"looking into it\")\n\tuassert.Equal(t, 2, ClearUnreviewed(cross(cur), \"onyx\", reg.Revision()))\n\t_, ok := GetEndpoint(spam)\n\tuassert.False(t, ok)\n\t_, ok = GetEndpoint(ruled)\n\tuassert.True(t, ok, \"a curator's ruling is kept\")\n\tuassert.Equal(t, 1, reg.OwnerCount(\"onyx\", bob))\n\tuassert.Equal(t, 0, ClearUnreviewed(cross(cur), \"onyx\", reg.Revision()))\n}\n\n// The review windows are the full ReviewWindow, a block short is refused, and\n// the zone's runs from its last edit by anybody.\nfunc TestReviewWindowsAreExact(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tid := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://a.bobs.example.com\", \"\")\n\ttesting.SkipHeights(ReviewWindow - 1)\n\tuassert.AbortsContains(t, cur, \"may be withdrawn in 1 blocks\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n\tuassert.AbortsContains(t, cur, \"may act on it again in 1 blocks\", func() {\n\t\tRemoveZone(cross(cur), \"bobs\", zrev(\"bobs\"))\n\t})\n\ttesting.SkipHeights(1)\n\t// A curator's edit restarts the proposer's window: it runs from the last\n\t// edit by anybody.\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ := GetZone(\"bobs\")\n\tEditZone(cross(cur), \"bobs\", z.Revision, z.ChainID, \"Bob's, retitled\", z.Description, string(z.Kind),\n\t\tz.GnowebURL, z.RPCURL, z.GenesisURL, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"may act on it again in\", func() {\n\t\tRemoveZone(cross(cur), \"bobs\", zrev(\"bobs\"))\n\t})\n}\n\n// A proposer's edit off local drops private endpoints only under the rules a\n// removal by the proposer has: never somebody else's, never one a curator\n// ruled on.\nfunc TestProposerLeavingLocalMeetsTheWithdrawalRules(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"lab\", \"lab-1\", \"Lab\", \"\", \"local\", \"\", \"http://127.0.0.1:26657\", \"\")\n\tmine := RegisterEndpoint(cross(cur), \"lab\", \"rpc\", \"http://10.1.2.3:26657\", \"\")\n\tleave := func() {\n\t\tz, _ := GetZone(\"lab\")\n\t\tEditZone(cross(cur), \"lab\", z.Revision, z.ChainID, z.Title, z.Description, \"devnet\",\n\t\t\t\"\", \"https://rpc.lab.example.com\", \"\", \"\")\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\ttheirs := RegisterEndpoint(cross(cur), \"lab\", \"rpc\", \"http://10.9.9.9:26657\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tuassert.AbortsContains(t, cur, \"which somebody else registered\", leave)\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRemoveEndpoint(cross(cur), theirs, erev(theirs))\n\tFlagEndpoint(cross(cur), mine, erev(mine), \"a trap\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"a curator ruled on\", leave)\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tUnverifyEndpoint(cross(cur), mine, erev(mine), \"\")\n\tRemoveEndpoint(cross(cur), mine, erev(mine))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfresh := RegisterEndpoint(cross(cur), \"lab\", \"rpc\", \"http://10.4.4.4:26657\", \"\")\n\t// Dropping it is withdrawing it, so it waits out its own review window.\n\tuassert.AbortsContains(t, cur, \"may be withdrawn in\", leave)\n\ttesting.SkipHeights(ReviewWindow)\n\tleave()\n\t_, ok := GetEndpoint(fresh)\n\tuassert.False(t, ok, \"the proposer's own, never ruled on, is dropped\")\n}\n\n// A reset reaches only a verified endpoint, which its registrant could\n// withdraw, and it says the zone changed, not the endpoint: so it leaves that\n// withdrawal in place, after a chain-id edit and after a retirement undone.\nfunc TestAResetLeavesTheWithdrawal(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tid := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://a.bobs.example.com\", \"\")\n\tid2 := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://b.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"answers bobs-1\")\n\tVerifyEndpoint(cross(cur), id2, zr(id2), erev(id2), \"answers bobs-1\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tz, _ := GetZone(\"bobs\")\n\tEditZone(cross(cur), \"bobs\", z.Revision, \"bobs-2\", z.Title, z.Description, string(z.Kind),\n\t\tz.GnowebURL, z.RPCURL, z.GenesisURL, \"\")\n\te, _ := GetEndpoint(id)\n\tuassert.Equal(t, \"\", e.ReviewedBy.String())\n\tuassert.Equal(t, zones.ChainIDChanged, e.Reason)\n\tRemoveEndpoint(cross(cur), id, erev(id))\n\t_, ok := GetEndpoint(id)\n\tuassert.False(t, ok, \"a chain-id reset leaves the withdrawal\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tVerifyEndpoint(cross(cur), id2, zr(id2), erev(id2), \"answers bobs-2\")\n\tApproveZone(cross(cur), \"bobs\", zr(id2), \"\")\n\tRetireZone(cross(cur), \"bobs\", zr(id2), \"shut down\")\n\tApproveZone(cross(cur), \"bobs\", zr(id2), \"back\")\n\te, _ = GetEndpoint(id2)\n\tuassert.Equal(t, zones.ZoneRetired, e.Reason)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tRemoveEndpoint(cross(cur), id2, erev(id2))\n\t_, ok = GetEndpoint(id2)\n\tuassert.False(t, ok, \"a retirement's reset leaves it too\")\n\n\t// A curator's own unverify is still a warning.\n\tid3 := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://c.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tUnverifyEndpoint(cross(cur), id3, erev(id3), \"answers a different chain\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tuassert.AbortsContains(t, cur, \"a curator ruled on\", func() { RemoveEndpoint(cross(cur), id3, erev(id3)) })\n}\n\n// The zone's own main RPC and gnoweb, under their own kind, are its proposer's\n// or a curator's to list: a stranger's listing, flagged for its label, would\n// mark the zone's own URL.\nfunc TestTheZonesOwnURLsAreReserved(cur realm, t *testing.T) {\n\treset()\n\tz, _ := GetZone(\"onyx\")\n\treg.RemoveEndpoint(mustRPC(t, \"onyx\", z.RPCURL))\n\tge, ok := reg.EndpointByAddress(\"onyx\", zones.Gnoweb, z.GnowebURL)\n\turequire.True(t, ok)\n\treg.RemoveEndpoint(ge.ID, ge.Revision)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfor _, a := range []string{strings.ToUpper(z.RPCURL), \" \" + z.RPCURL, z.RPCURL + \"\\t\"} {\n\t\tuassert.AbortsContains(t, cur, \"onyx's own rpc\", func() {\n\t\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", a, \"moved: use mine\")\n\t\t})\n\t}\n\tuassert.AbortsContains(t, cur, \"onyx's own gnoweb\", func() {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"gnoweb\", z.GnowebURL+\"\\t\", \"\")\n\t})\n\t// Under another kind it is anybody's, and its flag marks nothing.\n\tRegisterEndpoint(cross(cur), \"onyx\", \"explorer\", z.RPCURL, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", z.RPCURL, \"gno core\")\n}\n\n// mustRPC returns the id and revision of the rpc endpoint listing url.\nfunc mustRPC(t *testing.T, slug, url string) (int64, int64) {\n\te, ok := reg.EndpointByAddress(slug, zones.RPC, url)\n\turequire.True(t, ok, url)\n\treturn e.ID, e.Revision\n}\n\n// ClearUnreviewed takes only what the curator read: nothing registered after\n// the revision they name, nothing a curator registered, nothing a curator\n// ruled on (an unverify with no reason included), nothing a reset left.\nfunc TestClearUnreviewedIsBoundToWhatWasRead(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.AbortsContains(t, cur, \"no zone\", func() { ClearUnreviewed(cross(cur), \"nope\", reg.Revision()) })\n\tmine := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://curators-own.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tspam := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://spam.example.com\", \"\")\n\truled := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://ruled.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tFlagEndpoint(cross(cur), ruled, erev(ruled), \"checking\")\n\tUnverifyEndpoint(cross(cur), ruled, erev(ruled), \"\")\n\tread := reg.Revision()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tlate := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://late.example.com\", \"alice's node\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.Equal(t, 1, ClearUnreviewed(cross(cur), \"onyx\", read))\n\tfor id, kept := range map[int64]bool{mine: true, spam: false, ruled: true, late: true} {\n\t\t_, ok := GetEndpoint(id)\n\t\tuassert.Equal(t, kept, ok, strconv.FormatInt(id, 10))\n\t}\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"func=ClearUnreviewed\"))\n}\n\n// A removal names the endpoint's revision: one written before a colleague's\n// verdict fails rather than delete it unseen. A verified endpoint is its\n// registrant's to take down; listing it again starts it unverified.\nfunc TestRemovalIsBoundAndAVerifiedListingIsWithdrawable(cur realm, t *testing.T) {\n\treset()\n\tuassert.Equal(t, int64(100), int64(ReviewWindow))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://bobs-node.example.com\", \"\")\n\tread := erev(id)\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"answers onyx-1\")\n\tuassert.AbortsContains(t, cur, \"changed since you read it\", func() { RemoveEndpoint(cross(cur), id, read) })\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tRemoveEndpoint(cross(cur), id, erev(id))\n\t_, ok := GetEndpoint(id)\n\tuassert.False(t, ok)\n}\n\n// A proposer leaving local keeps every public endpoint, a curator's included:\n// the withdrawal rules apply only to what the edit drops.\nfunc TestLeavingLocalKeepsOthersPublicEndpoints(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"lab\", \"lab-1\", \"Lab\", \"\", \"local\", \"\", \"http://127.0.0.1:26657\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tpub := RegisterEndpoint(cross(cur), \"lab\", \"rpc\", \"https://rpc.lab.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tz, _ := GetZone(\"lab\")\n\tEditZone(cross(cur), \"lab\", z.Revision, z.ChainID, z.Title, z.Description, \"devnet\", \"\", \"https://rpc.lab.example.com\", \"\", \"\")\n\t_, ok := GetEndpoint(pub)\n\tuassert.True(t, ok)\n}\n\n// The index's example falls back to onyx when this chain's zone lists no\n// peer, rather than print a query certain to return nothing.\nfunc TestTheIndexExampleFallsBack(t *testing.T) {\n\treset()\n\tz, _ := GetZone(\"moul-staging\")\n\tin := zones.Info{ChainID: runtime.ChainID(), Title: z.Title, Kind: z.Kind, RPCURL: z.RPCURL, GnowebURL: z.GnowebURL}\n\tmust(reg.Edit(\"moul-staging\", zrev(\"moul-staging\"), in, Admin, 1, \"on this chain\"))\n\tuassert.Equal(t, 0, reg.EndpointCount(\"moul-staging\", zones.Peer))\n\tuassert.True(t, strings.Contains(Render(\"\"), `ListAddresses(\"onyx\", \"peer\", \"verified\")`))\n}\n\n// ClearUnreviewed keeps an endpoint a reset left with a reason: a curator\n// verified it, and the proposer's chain-id edit undid that.\nfunc TestClearKeepsAResetEndpoint(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tid := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://a.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tz, _ := GetZone(\"bobs\")\n\tEditZone(cross(cur), \"bobs\", z.Revision, \"bobs-2\", z.Title, z.Description, string(z.Kind), z.GnowebURL, z.RPCURL, z.GenesisURL, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.Equal(t, 0, ClearUnreviewed(cross(cur), \"bobs\", reg.Revision()))\n}\n\n// The reservation exempts any curator, and the proposer while the zone is\n// pending, each alone: every proposer right ends at approval.\nfunc TestTheReservationsExemptions(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"https://gnoweb.bobs.example.com\", \"https://rpc.bobs.example.com\", \"\")\n\tRegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://rpc.bobs.example.com\", \"mine\") // the proposer, pending\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tApproveZone(cross(cur), \"bobs\", zrev(\"bobs\"), \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"only a curator, or its proposer while it is pending\", func() {\n\t\tRegisterEndpoint(cross(cur), \"bobs\", \"gnoweb\", \"https://gnoweb.bobs.example.com\", \"mine too\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRegisterEndpoint(cross(cur), \"bobs\", \"gnoweb\", \"https://gnoweb.bobs.example.com\", \"\") // a curator, not the proposer\n}\n\n// On an approved zone the proposer's listing of a new own URL is anybody's\n// listing: a curator's edit drops it if nobody ruled on it, rather than adopt\n// it as the zone's own.\nfunc TestApprovedProposersListingIsNotAdopted(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tApproveZone(cross(cur), \"bobs\", zrev(\"bobs\"), \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://rpc2.bobs.example.com\", \"official next\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ := GetZone(\"bobs\")\n\tEditZone(cross(cur), \"bobs\", z.Revision, z.ChainID, z.Title, z.Description, string(z.Kind),\n\t\tz.GnowebURL, \"https://rpc2.bobs.example.com\", z.GenesisURL, \"moved\")\n\t_, ok := GetEndpoint(id)\n\tuassert.False(t, ok, \"the proposer's unruled listing is dropped, not adopted\")\n}\n\n// An edit cannot make a stranger's listing the zone's own. One nobody ruled on\n// is dropped in the edit, so pre-listing a zone's next URL cannot hold its\n// move off; one a curator ruled on refuses the edit until a curator removes\n// it, however the URL is padded. Each case starts fresh: a test does not roll\n// back an aborted call's writes, a transaction does.\nfunc TestAnEditCannotAdoptAStrangersListing(cur realm, t *testing.T) {\n\tsetup := func() zones.Zone {\n\t\treset()\n\t\t_, err := reg.Register(bob, 1, \"onyx\", zones.RPC, \"https://rpc2.onyx.example.com\", \"official onyx rpc\")\n\t\tmust(err)\n\t\tfor _, l := range [][2]string{{\"gnoweb\", \"https://web2.onyx.example.com\"}, {\"rpc\", \"https://rpc3.onyx.example.com\"}} {\n\t\t\tk, _ := zones.ParseEndpointKind(l[0])\n\t\t\tid, err := reg.Register(bob, 1, \"onyx\", k, l[1], \"official onyx\")\n\t\t\tmust(err)\n\t\t\tmust(reg.ReviewEndpoint(id, zones.Flagged, 0, erev(id), Admin, 1, \"not run by the onyx team\"))\n\t\t}\n\t\tz, _ := GetZone(\"onyx\")\n\t\treturn z\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tedit := func(z zones.Zone, gnoweb, rpc string) func() {\n\t\treturn func() {\n\t\t\tEditZone(cross(cur), \"onyx\", zrev(\"onyx\"), z.ChainID, z.Title+\".\", z.Description, string(z.Kind),\n\t\t\t\tgnoweb, rpc, z.GenesisURL, \"moved\")\n\t\t}\n\t}\n\tfor _, c := range [][2]string{{\"https://web2.onyx.example.com\", \"\"}, {\" https://web2.onyx.example.com\\t\", \"\"}, {\"\", \" https://rpc3.onyx.example.com\"}} {\n\t\tz := setup()\n\t\tgw, rpc := c[0], c[1]\n\t\tif gw == \"\" {\n\t\t\tgw = z.GnowebURL\n\t\t}\n\t\tif rpc == \"\" {\n\t\t\trpc = z.RPCURL\n\t\t}\n\t\tuassert.AbortsContains(t, cur, \"with a curator's ruling\", edit(z, gw, rpc))\n\t}\n\tz := setup()\n\tsquat, ok := reg.EndpointByAddress(\"onyx\", zones.RPC, \"https://rpc2.onyx.example.com\")\n\turequire.True(t, ok)\n\tedit(z, z.GnowebURL, \"https://rpc2.onyx.example.com\")()\n\t_, ok = GetEndpoint(squat.ID)\n\tuassert.False(t, ok, \"the unruled squat is dropped in the edit\")\n\tz, _ = GetZone(\"onyx\")\n\tuassert.Equal(t, \"https://rpc2.onyx.example.com\", z.RPCURL)\n}\n\n// A listing of the zone's current URL by a curator since removed does not\n// block an edit that leaves the URL alone.\nfunc TestAnExCuratorsListingDoesNotFreezeTheZone(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tAddCurator(cross(cur), carol)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tAcceptCurator(cross(cur))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tApproveZone(cross(cur), \"bobs\", zrev(\"bobs\"), \"\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tlisted := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://rpc.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRemoveCurator(cross(cur), carol)\n\tz, _ := GetZone(\"bobs\")\n\tEditZone(cross(cur), \"bobs\", z.Revision, z.ChainID, \"Bob's, retitled\", z.Description, string(z.Kind),\n\t\tz.GnowebURL, z.RPCURL, z.GenesisURL, \"a better title\")\n\t_, ok := GetEndpoint(listed)\n\tuassert.True(t, ok, \"an edit that leaves the URL alone touches no listing of it\")\n}\n\n// The Clear link reaches every page and kind, so it is offered only on the\n// unfiltered view of a zone that takes endpoints, bound to the revision the\n// page was rendered at; the call clears an endpoint registered exactly at the\n// revision it names.\nfunc TestTheClearLinksScope(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"faucet\", \"https://spam.example.com\", \"\")\n\tat := strconv.FormatInt(reg.Revision(), 10)\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"throughRevision=\"+at))\n\tuassert.False(t, strings.Contains(Render(\"zone/onyx?kind=rpc\"), \"func=ClearUnreviewed\"))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.Equal(t, 1, ClearUnreviewed(cross(cur), \"onyx\", erev(id)))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"faucet\", \"https://spam2.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRetireZone(cross(cur), \"onyx\", zrev(\"onyx\"), \"shut down\")\n\tuassert.Equal(t, 1, reg.Clearable(\"onyx\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"func=ClearUnreviewed\"), \"a retired zone's flood is a curator's to clear\")\n}\n\n// A registrant cannot withdraw an endpoint a curator unverified, even with no\n// reason: the reviewer is the ruling.\nfunc TestAReasonlessUnverifyIsARuling(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://bob.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tFlagEndpoint(cross(cur), id, erev(id), \"checking\")\n\tUnverifyEndpoint(cross(cur), id, erev(id), \"\")\n\te, _ := GetEndpoint(id)\n\tuassert.Equal(t, \"\", e.Reason)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tuassert.AbortsContains(t, cur, \"a curator ruled on\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n}\n\n// With no listing of its own kind at all, a flag under another kind still\n// does not mark the zone's URL: there is no fallback.\nfunc TestNoCrossKindFallback(cur realm, t *testing.T) {\n\treset()\n\tz, _ := GetZone(\"mainnet\")\n\treg.RemoveEndpoint(mustRPC(t, \"mainnet\", z.RPCURL))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"mainnet\", \"explorer\", z.RPCURL, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tFlagEndpoint(cross(cur), id, erev(id), \"not an explorer\")\n\tuassert.False(t, strings.Contains(Render(\"zone/mainnet\"), \"`\"+z.RPCURL+\"` ⚠️\"))\n}\n\n// Inputs are trimmed where a caller types them, the edit-time reservation\n// exempts the proposer and trims too, and the documented realm bounds hold.\nfunc TestRealmTrimsAndBounds(cur realm, t *testing.T) {\n\treset()\n\tuassert.Equal(t, 16, MaxCurators)\n\t_, ok := GetZone(\" onyx \")\n\tuassert.True(t, ok)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \" bobs \", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\t_, ok = GetZone(\"bobs\")\n\tuassert.True(t, ok)\n\tid := RegisterEndpoint(cross(cur), \" bobs \", \"rpc\", \"https://rpc2.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"\")\n\tuassert.Equal(t, reg.Revision(), erev(id), \"the last revision handed out is this verdict's\")\n\t// The proposer's own listing of the new URL is no stranger's.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tz, _ := GetZone(\"bobs\")\n\tEditZone(cross(cur), \"bobs\", z.Revision, z.ChainID, z.Title, z.Description, string(z.Kind),\n\t\tz.GnowebURL, \" https://rpc2.bobs.example.com \", z.GenesisURL, \"\")\n\t_, ok = GetEndpoint(id)\n\tuassert.True(t, ok, \"the proposer's listing stays\")\n}\n\n// The list routes and their links: the approved alias, the retired list and\n// its link from the index, the pending list, a retired or rejected zone's\n// URLs shown as code, the review-queue note at exactly the gate, and the\n// pending zone's Register label.\nfunc TestRoutesNotesAndLabels(cur realm, t *testing.T) {\n\treset()\n\tuassert.Equal(t, Render(\"\"), Render(\"?status=approved\"))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ := GetZone(\"onyx\")\n\tRetireZone(cross(cur), \"onyx\", zrev(\"onyx\"), \"shut down\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"1 retired zone\"))\n\tpage := Render(\"?status=retired\")\n\tuassert.True(t, strings.Contains(page, \"Onyx\"))\n\tuassert.False(t, strings.Contains(Render(\"zone/onyx\"), \"](\"+z.GnowebURL+\")\"), \"a retired zone's URLs are code\")\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"`\"+z.GnowebURL+\"`\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"https://web.bobs.example.com\", \"https://rpc.bobs.example.com\", \"\")\n\tuassert.True(t, strings.Contains(Render(\"proposals\"), \"bobs\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/bobs\"), \"proposer or curator\"))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRejectZone(cross(cur), \"bobs\", zrev(\"bobs\"), \"no\")\n\tuassert.False(t, strings.Contains(Render(\"zone/bobs\"), \"](https://web.bobs.example.com)\"), \"a rejected zone's URLs are code\")\n\n\tfor i := 0; reg.Awaiting(\"mainnet\") \u003c zones.MaxUnverifiedPerZone; i++ {\n\t\t_, err := reg.Register(testutils.TestAddress(\"q\"+strconv.Itoa(i/zones.MaxEndpointsPerAddress)), 1, \"mainnet\", zones.RPC,\n\t\t\t\"https://q\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tmust(err)\n\t}\n\tuassert.Equal(t, zones.MaxUnverifiedPerZone, reg.Awaiting(\"mainnet\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/mainnet\"), \"the review queue is full at 64 endpoints awaiting review\"))\n}\n\n// The Clear link shows only while something is clearable, and the admission\n// gate bounds how much that can be.\nfunc TestClearIsOfferedOnlyWhenItClears(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://curators.example.com\", \"\")\n\tuassert.False(t, strings.Contains(Render(\"zone/onyx\"), \"func=ClearUnreviewed\"), \"a curator's own listing is not clearable\")\n\tfor i := 0; reg.Clearable(\"mainnet\") \u003c= zones.MaxUnverifiedPerZone; i++ {\n\t\t_, err := reg.Register(testutils.TestAddress(\"c\"+strconv.Itoa(i/zones.MaxEndpointsPerAddress)), 1, \"mainnet\", zones.RPC,\n\t\t\t\"https://c\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tif err != nil {\n\t\t\t// The admission gate holds the queue at 64: this is as full as a flood gets.\n\t\t\tbreak\n\t\t}\n\t}\n\tn := reg.Clearable(\"mainnet\")\n\tuassert.True(t, strings.Contains(Render(\"zone/mainnet\"), \"Clear \"+strconv.Itoa(n)+\" never\"))\n\tuassert.True(t, n \u003c= zones.MaxUnverifiedPerZone)\n\tuassert.Equal(t, n, ClearUnreviewed(cross(cur), \"mainnet\", reg.Revision()))\n\tuassert.Equal(t, 0, reg.Clearable(\"mainnet\"))\n\tuassert.False(t, strings.Contains(Render(\"zone/mainnet\"), \"func=ClearUnreviewed\"))\n}\n\n// Where a decision evicts a record, the page says so beside it.\nfunc TestTheEvictionNote(cur realm, t *testing.T) {\n\treset()\n\tfor i := 0; reg.ZoneCount(zones.Rejected) \u003c zones.MaxRejected; i++ {\n\t\tslug := \"rj\" + strconv.Itoa(i)\n\t\tmust(reg.ProposeExempt(Admin, 1, slug, zones.Info{ChainID: slug, Title: \"R\", Kind: zones.Testnet,\n\t\t\tRPCURL: \"https://rpc\" + strconv.Itoa(i) + \".example.com\"}))\n\t\tmust(reg.ReviewZone(slug, zones.Rejected, zrev(slug), Admin, 1, \"no\"))\n\t}\n\tmust(reg.ProposeExempt(Admin, 2, \"next\", zones.Info{ChainID: \"next\", Title: \"N\", Kind: zones.Testnet, RPCURL: \"https://rpcn.example.com\"}))\n\tuassert.True(t, strings.Contains(Render(\"zone/next\"), \"rejecting it drops the zone rejected longest ago\"))\n\tuassert.False(t, strings.Contains(Render(\"zone/onyx\"), \"retiring it drops\"))\n}\n\n// The last places of each hard cap are curators': strangers who keep a cap\n// full cannot lock out the people who would act under it, and the page says\n// so with a link for them.\nfunc TestTheHardCapsKeepPlacesForCurators(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tfor i := 0; reg.EndpointCount(\"onyx\", \"\") \u003c zones.MaxEndpointsPerZone-zones.ReservedForReviewers; i++ {\n\t\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://v\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"\")\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"kept for curators\", func() {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://bob.example.com\", \"\")\n\t})\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"endpoint places are kept for curators\"))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://curator.example.com\", \"\")\n\n\tfor i := 0; reg.Live() \u003c zones.MaxZones-zones.ReservedForReviewers; i++ {\n\t\ts := \"l\" + strconv.Itoa(i)\n\t\tmust(reg.ProposeExempt(Admin, 1, s, zones.Info{ChainID: s, Title: \"L\", Kind: zones.Testnet, RPCURL: \"https://rpcl\" + strconv.Itoa(i) + \".example.com\"}))\n\t\tmust(reg.ReviewZone(s, zones.Approved, zrev(s), Admin, 1, \"\"))\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"kept for curators\", func() {\n\t\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\t})\n\tuassert.True(t, strings.Contains(Render(\"\"), \"places are kept for curators\"))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tProposeZone(cross(cur), \"admins\", \"admins-1\", \"A\", \"\", \"devnet\", \"\", \"https://rpc.admins.example.com\", \"\")\n}\n\n// Slugs are trimmed, each zone state offers its links, and reasons and titles\n// are escaped in every cell.\nfunc TestRealmTrimsLinksAndEscapes(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\t// Every slug a caller types is trimmed.\n\tRetireZone(cross(cur), \" onyx \", zrev(\"onyx\"), \"shut down\")\n\tApproveZone(cross(cur), \" onyx \", zrev(\"onyx\"), \"\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's | best @moul \"+Admin.String(), \"run by @moul \"+Admin.String(), \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://spam.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tuassert.Equal(t, 1, ClearUnreviewed(cross(cur), \" onyx \", reg.Revision()))\n\t_, ok := GetEndpoint(id)\n\tuassert.False(t, ok)\n\n\t// A pending zone offers Approve and Remove; its title and description\n\t// have no live mention.\n\tpage := Render(\"zone/bobs\")\n\tuassert.True(t, strings.Contains(page, \"func=ApproveZone\"))\n\tuassert.True(t, strings.Contains(page, \"func=RemoveZone\"))\n\tuassert.True(t, strings.Contains(page, \"pending review\"))\n\tuassert.False(t, strings.Contains(page, \" @moul\"))\n\tuassert.False(t, strings.Contains(page, \" \"+Admin.String()))\n\n\t// A rejected zone offers Remove, its reason cell escapes a pipe and has\n\t// no live mention.\n\tRejectZone(cross(cur), \" bobs \", zrev(\"bobs\"), \"a | b, see @moul\")\n\tpage = Render(\"zone/bobs\")\n\tuassert.True(t, strings.Contains(page, \"func=RemoveZone\"))\n\tuassert.True(t, strings.Contains(page, \"rejected\"))\n\tuassert.False(t, strings.Contains(page, \" @moul\"))\n\tuassert.True(t, strings.Contains(Render(\"proposals?status=rejected\"), `a \\| b`))\n\tuassert.True(t, strings.Contains(Render(\"proposals?status=nope\"), \"No such list.\"))\n\n\t// An endpoint reason with a pipe stays in its cell.\n\te := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://r.example.com\", \"\")\n\tFlagEndpoint(cross(cur), e, erev(e), \"x | y\")\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx?kind=rpc\"), `x \\| y`))\n\n\t// A retired zone offers Approve, and its reason cell escapes a pipe.\n\tRetireZone(cross(cur), \"mainnet\", zrev(\"mainnet\"), \"c | d\")\n\tuassert.True(t, strings.Contains(Render(\"zone/mainnet\"), \"func=ApproveZone\"))\n\tuassert.True(t, strings.Contains(Render(\"zone/mainnet\"), \"retired\"))\n\tuassert.True(t, strings.Contains(Render(\"?status=retired\"), `c \\| d`))\n}\n\n// The index's example asks this chain's zone for peers when it lists one, not\n// the onyx fallback.\nfunc TestTheIndexExampleUsesThisChainsZone(t *testing.T) {\n\treset()\n\tm, _ := GetZone(\"mainnet\")\n\tin := zones.Info{ChainID: runtime.ChainID(), Title: m.Title, Kind: m.Kind, RPCURL: m.RPCURL, GnowebURL: m.GnowebURL}\n\tmust(reg.Edit(\"mainnet\", zrev(\"mainnet\"), in, Admin, 1, \"on this chain\"))\n\tuassert.True(t, reg.EndpointCount(\"mainnet\", zones.Peer) \u003e 0)\n\tuassert.True(t, strings.Contains(Render(\"\"), `ListAddresses(\"mainnet\", \"peer\", \"verified\")`))\n}\n\n// Retiring a zone with the retired list full says it evicts the oldest.\nfunc TestTheRetireEvictionNote(t *testing.T) {\n\treset()\n\tfor i := 0; reg.ZoneCount(zones.Retired) \u003c zones.MaxRetired; i++ {\n\t\ts := \"rt\" + strconv.Itoa(i)\n\t\tmust(reg.ProposeExempt(Admin, 1, s, zones.Info{ChainID: s, Title: \"R\", Kind: zones.Testnet, RPCURL: \"https://rpcr\" + strconv.Itoa(i) + \".example.com\"}))\n\t\tmust(reg.ReviewZone(s, zones.Approved, zrev(s), Admin, 1, \"\"))\n\t\tmust(reg.ReviewZone(s, zones.Retired, zrev(s), Admin, 1, \"gone\"))\n\t}\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"retiring it drops the zone retired longest ago\"))\n}\n\n// An edit is validated before it acts: one that cannot pass removes nothing\n// on its way to failing. A former curator's unruled listing of a new URL is\n// dropped like a stranger's: only a ruling refuses.\nfunc TestAnEditValidatesBeforeItRemoves(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tws := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"wss://rpc9.onyx.example.com/websocket\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tFlagEndpoint(cross(cur), ws, erev(ws), \"not ours\")\n\tz, _ := GetZone(\"onyx\")\n\tedit := func(rpc string) func() {\n\t\treturn func() {\n\t\t\tEditZone(cross(cur), \"onyx\", zrev(\"onyx\"), z.ChainID, z.Title+\".\", z.Description, string(z.Kind),\n\t\t\t\tz.GnowebURL, rpc, z.GenesisURL, \"moved\")\n\t\t}\n\t}\n\tuassert.AbortsContains(t, cur, \"rpc url\", edit(\"wss://rpc9.onyx.example.com/websocket\"))\n\t_, ok := GetEndpoint(ws)\n\tuassert.True(t, ok, \"a failing edit removed nothing\")\n\n\tAddCurator(cross(cur), carol)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tAcceptCurator(cross(cur))\n\told := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://next.onyx.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRemoveCurator(cross(cur), carol)\n\tedit(\"https://next.onyx.example.com\")()\n\t_, ok = GetEndpoint(old)\n\tuassert.False(t, ok, \"an unruled former curator's listing is dropped\")\n}\n\n// No tail a registration trims gets a stranger past the own-URL reservation.\nfunc TestTheReservationHoldsWhateverTheTail(cur realm, t *testing.T) {\n\treset()\n\tz, _ := GetZone(\"onyx\")\n\treg.RemoveEndpoint(mustRPC(t, \"onyx\", z.RPCURL))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfor _, tail := range []string{\"/\", \"?\", \"/?\"} {\n\t\tuassert.AbortsContains(t, cur, \"onyx's own rpc\", func() {\n\t\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", z.RPCURL+tail, \"moved: use mine\")\n\t\t})\n\t}\n\t// A tail that is a real query is not the zone's URL, and is stored keyed\n\t// as it was typed (\"/??\" is the same endpoint as \"??\").\n\tfor _, tail := range []string{\"??\", \"?/\"} {\n\t\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", z.RPCURL+tail, \"\")\n\t\te, _ := GetEndpoint(id)\n\t\tuassert.True(t, zones.Canonical(zones.RPC, e.Address) != zones.Canonical(zones.RPC, z.RPCURL), tail)\n\t}\n\tuassert.AbortsContains(t, cur, \"already lists\", func() {\n\t\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", z.RPCURL+\"/??\", \"\")\n\t})\n}\n\n// Curator removal, invitation order, rulings on a stranger's listing, the\n// genesis URL, the status badges and the decision links.\nfunc TestMoreRealmRules(cur realm, t *testing.T) {\n\treset()\n\t// Only a curator removes a curator.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"is not a curator\", func() { RemoveCurator(cross(cur), Admin) })\n\t// Curators and invitations list in address order.\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tAddCurator(cross(cur), carol)\n\tAddCurator(cross(cur), alice)\n\tinv := Invited()\n\tfor i := 1; i \u003c len(inv); i++ {\n\t\tuassert.True(t, inv[i-1].String() \u003c inv[i].String())\n\t}\n\t// A verdict with no reason on a stranger's listing of the new URL is a\n\t// ruling: the edit refuses.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://next.onyx.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tVerifyEndpoint(cross(cur), id, zr(id), erev(id), \"\")\n\tz, _ := GetZone(\"onyx\")\n\tuassert.AbortsContains(t, cur, \"with a curator's ruling\", func() {\n\t\tEditZone(cross(cur), \"onyx\", zrev(\"onyx\"), z.ChainID, z.Title+\".\", z.Description, string(z.Kind),\n\t\t\tz.GnowebURL, \"https://next.onyx.example.com\", z.GenesisURL, \"moved\")\n\t})\n\treset() // a test does not roll back the aborted edit's writes; a transaction does\n\tz, _ = GetZone(\"onyx\")\n\t// The genesis URL is never marked, whatever kind lists it.\n\tg := RegisterEndpoint(cross(cur), \"onyx\", \"gnoweb\", z.GenesisURL, \"\")\n\tFlagEndpoint(cross(cur), g, erev(g), \"not a gnoweb\")\n\tuassert.False(t, strings.Contains(Render(\"zone/onyx\"), \"`\"+z.GenesisURL+\"` ⚠️\"))\n\t// Status badges, exactly.\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"✅ **official**\"))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tuassert.True(t, strings.Contains(Render(\"zone/bobs\"), \"⏳ **pending review**\"))\n\t// The pending zone's decision links carry its revision.\n\trv := strconv.FormatInt(zrev(\"bobs\"), 10)\n\tpage := Render(\"zone/bobs\")\n\tfor _, fn := range []string{\"ApproveZone\", \"RejectZone\", \"RemoveZone\"} {\n\t\tuassert.True(t, regexpLinkCarries(page, fn, rv), fn)\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRejectZone(cross(cur), \"bobs\", zrev(\"bobs\"), \"no\")\n\tuassert.True(t, strings.Contains(Render(\"zone/bobs\"), \"❌ **rejected**\"))\n\tRetireZone(cross(cur), \"onyx\", zrev(\"onyx\"), \"gone\")\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), \"⏹️ **retired**\"))\n}\n\n// Paging clamps a reader's page number and shows every row.\nfunc TestPagingEdges(t *testing.T) {\n\treset()\n\tfor i := 0; reg.EndpointCount(\"mainnet\", \"\") \u003c PageSize+1; i++ {\n\t\t_, err := reg.RegisterExempt(Admin, 1, \"mainnet\", zones.Indexer, \"https://p\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tmust(err)\n\t}\n\tall := reg.Endpoints(zones.EndpointFilter{Zone: \"mainnet\"})\n\tlast := all[len(all)-1].Address\n\tuassert.True(t, strings.Contains(Render(\"zone/mainnet?page=2\"), last), \"the 26th row is on page 2\")\n\tuassert.Equal(t, Render(\"zone/mainnet?page=1\"), Render(\"zone/mainnet?page=0\"))\n\tuassert.Equal(t, Render(\"zone/mainnet?page=2\"), Render(\"zone/mainnet?page=3\"))\n}\n\n// A proposer's edit drops nothing that is not theirs: a former curator's\n// listing on their pending zone refuses the edit instead of being dropped.\nfunc TestAProposersEditDropsNothingNotTheirs(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tAddCurator(cross(cur), carol)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tAcceptCurator(cross(cur))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tid := RegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://b.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRemoveCurator(cross(cur), carol)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tz, _ := GetZone(\"bobs\")\n\tuassert.AbortsContains(t, cur, \"a curator removes it before\", func() {\n\t\tEditZone(cross(cur), \"bobs\", z.Revision, z.ChainID, z.Title, z.Description, string(z.Kind), \"\", \"https://b.example.com\", \"\", \"\")\n\t})\n\t_, ok := GetEndpoint(id)\n\tuassert.True(t, ok)\n}\n\n// regexpLinkCarries reports whether a $help link to fn carries revision rv.\nfunc regexpLinkCarries(page, fn, rv string) bool {\n\tfor _, part := range strings.Split(page, \"$help\u0026\") {\n\t\tend := strings.IndexAny(part, \")\")\n\t\tif end \u003c 0 {\n\t\t\tcontinue\n\t\t}\n\t\tlink := part[:end]\n\t\tif strings.Contains(link, \"func=\"+fn) \u0026\u0026 strings.Contains(link, \"revision=\"+rv) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// A flagged listing of a zone's new URL refuses the edit whoever holds it and\n// whoever edits: it would mark the zone's own URL. Each case starts fresh: a\n// test does not roll back an aborted call's writes.\nfunc TestAFlaggedOwnListingRefusesTheEdit(cur realm, t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname            string\n\t\tapprove         bool\n\t\tholder, editor  address\n\t\tkind, url, want string\n\t}{\n\t\t{\"the proposer's, on a pending zone, by the proposer\", false, bob, bob, \"rpc\", \"https://rpc2.bobs.example.com\", \"flagged; a curator removes it\"},\n\t\t{\"a curator's, under rpc, by a curator\", true, Admin, Admin, \"rpc\", \"https://rpc2.bobs.example.com\", \"flagged; a curator removes it\"},\n\t\t{\"a curator's, under gnoweb, by a curator\", true, Admin, Admin, \"gnoweb\", \"https://web2.bobs.example.com\", \"flagged; a curator removes it\"},\n\t\t{\"the proposer's, on an approved zone, by a curator\", true, bob, Admin, \"rpc\", \"https://rpc2.bobs.example.com\", \"a curator removes it before it becomes\"},\n\t} {\n\t\treset()\n\t\ttesting.SetRealm(testing.NewUserRealm(bob))\n\t\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"https://web.bobs.example.com\", \"https://rpc.bobs.example.com\", \"\")\n\t\tif tc.approve {\n\t\t\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\t\t\tApproveZone(cross(cur), \"bobs\", zrev(\"bobs\"), \"\")\n\t\t}\n\t\tk, _ := zones.ParseEndpointKind(tc.kind)\n\t\tid, err := reg.Register(tc.holder, 1, \"bobs\", k, tc.url, \"spam\")\n\t\tmust(err)\n\t\tmust(reg.ReviewEndpoint(id, zones.Flagged, 0, erev(id), Admin, 1, \"spam label\"))\n\t\ttesting.SkipHeights(ReviewWindow)\n\t\ttesting.SetRealm(testing.NewUserRealm(tc.editor))\n\t\tz, _ := GetZone(\"bobs\")\n\t\tweb, rpc, reason := z.GnowebURL, z.RPCURL, \"\"\n\t\tif tc.kind == \"gnoweb\" {\n\t\t\tweb = tc.url\n\t\t} else {\n\t\t\trpc = tc.url\n\t\t}\n\t\tif tc.approve {\n\t\t\treason = \"moved\"\n\t\t}\n\t\tuassert.AbortsContains(t, cur, tc.want, func() {\n\t\t\tEditZone(cross(cur), \"bobs\", z.Revision, z.ChainID, z.Title, z.Description, string(z.Kind), web, rpc, z.GenesisURL, reason)\n\t\t}, tc.name)\n\t}\n}\n\n// Paging keeps a list's status, and the next link shows on the page before\n// the last; a registrant cannot withdraw from a retired zone.\nfunc TestListPagingAndRetiredRecords(cur realm, t *testing.T) {\n\treset()\n\tfor i := 0; reg.ZoneCount(zones.Retired) \u003c 2*PageSize+1; i++ {\n\t\ts := \"pr\" + strconv.Itoa(i)\n\t\tmust(reg.ProposeExempt(Admin, 1, s, zones.Info{ChainID: s, Title: \"P\", Kind: zones.Testnet, RPCURL: \"https://rpcp\" + strconv.Itoa(i) + \".example.com\"}))\n\t\tmust(reg.ReviewZone(s, zones.Approved, zrev(s), Admin, 1, \"\"))\n\t\tmust(reg.ReviewZone(s, zones.Retired, zrev(s), Admin, 1, \"gone\"))\n\t}\n\tpage := Render(\"?status=retired\u0026page=2\")\n\tuassert.True(t, strings.Contains(page, \"status=retired\u0026page=3\"), \"page 2 of 3 links to page 3, in the same list\")\n\tuassert.True(t, strings.Contains(page, \"status=retired\u0026page=1\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid := RegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://bob.example.com\", \"\")\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tRetireZone(cross(cur), \"onyx\", zrev(\"onyx\"), \"gone\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\ttesting.SkipHeights(ReviewWindow)\n\tuassert.AbortsContains(t, cur, \"a record\", func() { RemoveEndpoint(cross(cur), id, erev(id)) })\n\tuassert.False(t, strings.Contains(Render(\"proposals\"), \"0 rejected\"), \"no link to an empty rejected list\")\n\tuassert.Equal(t, Render(\"proposals\"), Render(\"proposals?status=pending\"))\n}\n\n// The reserve notes come before the queue notes when both caps are full, and\n// every link a non-curator's call would fail on says who it is for.\nfunc TestReserveNotesAreLabelledAndComeFirst(cur realm, t *testing.T) {\n\treset()\n\tfor i := 0; reg.Live() \u003c zones.MaxZones-zones.ReservedForReviewers-zones.MaxPending; i++ {\n\t\ts := \"ap\" + strconv.Itoa(i)\n\t\tmust(reg.ProposeExempt(Admin, 1, s, zones.Info{ChainID: s, Title: \"A\", Kind: zones.Testnet, RPCURL: \"https://rpca\" + strconv.Itoa(i) + \".example.com\"}))\n\t\tmust(reg.ReviewZone(s, zones.Approved, zrev(s), Admin, 1, \"\"))\n\t}\n\tfor i := 0; reg.ZoneCount(zones.Pending) \u003c zones.MaxPending; i++ {\n\t\ts := \"pp\" + strconv.Itoa(i)\n\t\tmust(reg.ProposeExempt(Admin, 1, s, zones.Info{ChainID: s, Title: \"P\", Kind: zones.Testnet, RPCURL: \"https://rpcq\" + strconv.Itoa(i) + \".example.com\"}))\n\t}\n\tuassert.Equal(t, zones.MaxZones-zones.ReservedForReviewers, reg.Live())\n\tpage := Render(\"\")\n\tuassert.True(t, strings.Contains(page, \"the registry's last 16 places are kept for curators\"))\n\tuassert.True(t, strings.Contains(page, `Propose a zone \\(curators only\\)]`))\n\tuassert.False(t, strings.Contains(page, \"the review queue is full\"), \"the reserve binds first\")\n\n\treset()\n\tfor i := 0; reg.Awaiting(\"onyx\") \u003c zones.MaxUnverifiedPerZone; i++ {\n\t\t_, err := reg.RegisterExempt(Admin, 1, \"onyx\", zones.RPC, \"https://u\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tmust(err)\n\t}\n\tfor i := 0; reg.EndpointCount(\"onyx\", \"\") \u003c zones.MaxEndpointsPerZone-zones.ReservedForReviewers; i++ {\n\t\tid, err := reg.RegisterExempt(Admin, 1, \"onyx\", zones.RPC, \"https://f\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tmust(err)\n\t\tmust(reg.ReviewEndpoint(id, zones.Flagged, 0, erev(id), Admin, 1, \"spam\"))\n\t}\n\tpage = Render(\"zone/onyx\")\n\tuassert.True(t, strings.Contains(page, \"the last 16 endpoint places are kept for curators\"))\n\tuassert.True(t, strings.Contains(page, `Register an endpoint \\(curators only\\)]`))\n\tuassert.False(t, strings.Contains(page, \"the review queue is full\"), \"the reserve binds first\")\n\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://bob.example.com\", \"\")\n\tuassert.True(t, strings.Contains(Render(\"zone/onyx\"), `all pages and kinds \\(curators only\\)]`))\n}\n\n// A rejected or retired zone takes no endpoints: no Register link and no cap\n// note, but a curator still clears its never-reviewed endpoints.\nfunc TestARecordZoneOffersNoRegistration(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tRegisterEndpoint(cross(cur), \"onyx\", \"rpc\", \"https://bob.example.com\", \"\")\n\tfor i := 0; reg.EndpointCount(\"onyx\", \"\") \u003c zones.MaxEndpointsPerZone; i++ {\n\t\tid, err := reg.RegisterExempt(Admin, 1, \"onyx\", zones.RPC, \"https://f\"+strconv.Itoa(i)+\".example.com\", \"\")\n\t\tmust(err)\n\t\tmust(reg.ReviewEndpoint(id, zones.Flagged, 0, erev(id), Admin, 1, \"spam\"))\n\t}\n\tmust(reg.ReviewZone(\"onyx\", zones.Retired, zrev(\"onyx\"), Admin, 1, \"gone\"))\n\tpage := Render(\"zone/onyx\")\n\tuassert.False(t, strings.Contains(page, \"func=RegisterEndpoint\"))\n\tuassert.False(t, strings.Contains(page, \"endpoints are full\"))\n\tuassert.True(t, strings.Contains(page, \"func=ClearUnreviewed\"), \"the record's flood is still a curator's to clear\")\n}\n\n// On a pending zone the proposer is the one gated registrant, so once they\n// reach the per-address cap the link is for curators.\nfunc TestThePendingRegisterLinkFollowsTheProposersCap(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tuassert.True(t, strings.Contains(Render(\"zone/bobs\"), `Register an endpoint \\(proposer or curator\\)]`))\n\tfor i := 0; i \u003c zones.MaxEndpointsPerAddress; i++ {\n\t\tRegisterEndpoint(cross(cur), \"bobs\", \"rpc\", \"https://b\"+strconv.Itoa(i)+\".bobs.example.com\", \"\")\n\t}\n\tpage := Render(\"zone/bobs\")\n\tuassert.True(t, strings.Contains(page, \"the proposer has registered 16 endpoints here\"))\n\tuassert.True(t, strings.Contains(page, `Register an endpoint \\(curators only\\)]`))\n}\n\n// The rejected list's pager stays in the rejected list.\nfunc TestTheRejectedPagerKeepsItsList(t *testing.T) {\n\treset()\n\tfor i := 0; reg.ZoneCount(zones.Rejected) \u003c PageSize+1; i++ {\n\t\ts := \"rj\" + strconv.Itoa(i)\n\t\tmust(reg.ProposeExempt(Admin, 1, s, zones.Info{ChainID: s, Title: \"R\", Kind: zones.Testnet, RPCURL: \"https://rpcr\" + strconv.Itoa(i) + \".example.com\"}))\n\t\tmust(reg.ReviewZone(s, zones.Rejected, zrev(s), Admin, 1, \"no\"))\n\t}\n\tuassert.True(t, strings.Contains(Render(\"proposals?status=rejected\"), \"status=rejected\u0026page=2\"))\n}\n\n// A reason on an endpoint is free text: a mention in it stays text.\nfunc TestAnEndpointReasonCannotMention(t *testing.T) {\n\treset()\n\tid, err := reg.Register(bob, 1, \"onyx\", zones.RPC, \"https://bob.example.com\", \"\")\n\tmust(err)\n\tmust(reg.ReviewEndpoint(id, zones.Flagged, 0, erev(id), Admin, 1, \"ask @alice\"))\n\tpage := Render(\"zone/onyx?kind=rpc\")\n\tuassert.True(t, strings.Contains(page, `ask \\@alice`))\n\tuassert.False(t, strings.Contains(page, \"ask @alice\"))\n}\n\n// An edit onto a listing a curator ruled on is refused whatever the ruling\n// left: a reasonless unverify, or a reset's reason with nobody recorded.\nfunc TestAnEditRefusesEveryRuling(cur realm, t *testing.T) {\n\t// A curator's reasonless unverify.\n\treset()\n\tid, err := reg.Register(bob, 1, \"onyx\", zones.RPC, \"https://rpc2.onyx.example.com\", \"\")\n\tmust(err)\n\tmust(reg.ReviewEndpoint(id, zones.Verified, zrev(\"onyx\"), erev(id), Admin, 1, \"\"))\n\tmust(reg.ReviewEndpoint(id, zones.Unverified, 0, erev(id), Admin, 1, \"\"))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ := GetZone(\"onyx\")\n\tuassert.AbortsContains(t, cur, \"with a curator's ruling\", func() {\n\t\tEditZone(cross(cur), \"onyx\", z.Revision, z.ChainID, z.Title, z.Description, string(z.Kind), z.GnowebURL, \"https://rpc2.onyx.example.com\", z.GenesisURL, \"moved\")\n\t})\n\n\t// A proposer's chain-id reset of a former curator's listing: no reviewer,\n\t// a reason.\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tProposeZone(cross(cur), \"bobs\", \"bobs-1\", \"Bob's\", \"\", \"devnet\", \"\", \"https://rpc.bobs.example.com\", \"\")\n\tid, err = reg.RegisterExempt(carol, 1, \"bobs\", zones.RPC, \"https://rpc2.bobs.example.com\", \"\")\n\tmust(err)\n\tmust(reg.ReviewEndpoint(id, zones.Verified, zrev(\"bobs\"), erev(id), Admin, 1, \"\"))\n\ttesting.SkipHeights(ReviewWindow)\n\tz, _ = GetZone(\"bobs\")\n\tEditZone(cross(cur), \"bobs\", z.Revision, \"bobs-2\", z.Title, z.Description, string(z.Kind), z.GnowebURL, z.RPCURL, z.GenesisURL, \"\")\n\te, _ := GetEndpoint(id)\n\tuassert.Equal(t, \"\", e.ReviewedBy.String())\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ = GetZone(\"bobs\")\n\tuassert.AbortsContains(t, cur, \"with a curator's ruling\", func() {\n\t\tEditZone(cross(cur), \"bobs\", z.Revision, z.ChainID, z.Title, z.Description, string(z.Kind), z.GnowebURL, \"https://rpc2.bobs.example.com\", z.GenesisURL, \"\")\n\t})\n}\n\n// Respelling the zone's own URL is no change to it: the edit does not look at\n// listings of it, ruled or not.\nfunc TestRespellingTheOwnURLIsNoMove(cur realm, t *testing.T) {\n\treset()\n\tz, _ := GetZone(\"onyx\")\n\treg.RemoveEndpoint(mustRPC(t, \"onyx\", z.RPCURL))\n\tid, err := reg.Register(bob, 1, \"onyx\", zones.RPC, z.RPCURL, \"\")\n\tmust(err)\n\tmust(reg.ReviewEndpoint(id, zones.Verified, zrev(\"onyx\"), erev(id), Admin, 1, \"\"))\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tz, _ = GetZone(\"onyx\")\n\tEditZone(cross(cur), \"onyx\", z.Revision, z.ChainID, \"Onyx, retitled\", z.Description, string(z.Kind), z.GnowebURL, z.RPCURL+\":443\", z.GenesisURL, \"retitled\")\n\t_, ok := GetEndpoint(id)\n\tuassert.True(t, ok)\n}\n\n// The slug is trimmed on every write, EditZone and RemoveZone included.\nfunc TestEveryWriteTrimsTheSlug(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tProposeZone(cross(cur), \"tz\", \"tz-1\", \"T\", \"\", \"devnet\", \"\", \"https://rpc.tz.example.com\", \"\")\n\tz, _ := GetZone(\"tz\")\n\tEditZone(cross(cur), \" tz\\t\", z.Revision, z.ChainID, \"T, edited\", z.Description, string(z.Kind), z.GnowebURL, z.RPCURL, z.GenesisURL, \"\")\n\tz, _ = GetZone(\"tz\")\n\tuassert.Equal(t, \"T, edited\", z.Title)\n\tRemoveZone(cross(cur), \"\\ttz \", z.Revision)\n\t_, ok := GetZone(\"tz\")\n\tuassert.False(t, ok)\n}\n\n// The seeded endpoints went through the gated registration, so none is\n// Exempt; and a zone with no endpoints draws no kind bar.\nfunc TestSeedsAreGatedAndAnEmptyZoneHasNoKindBar(cur realm, t *testing.T) {\n\treset()\n\tfor _, slug := range []string{\"mainnet\", \"onyx\", \"staging\", \"moul-staging\"} {\n\t\tfor _, e := range ListEndpoints(slug, \"\", \"\") {\n\t\t\tuassert.False(t, e.Exempt, slug+\" #\"+strconv.FormatInt(e.ID, 10))\n\t\t}\n\t}\n\ttesting.SetRealm(testing.NewUserRealm(Admin))\n\tProposeZone(cross(cur), \"tz\", \"tz-1\", \"T\", \"\", \"devnet\", \"\", \"https://rpc.tz.example.com\", \"\")\n\tuassert.False(t, strings.Contains(Render(\"zone/tz\"), \"all (0)\"))\n}\n"}]},"send":"","max_deposit":"67000000ugnot"}],"fee":{"gas_wanted":"1500000000","gas_fee":"4499999ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"qLm6D+9j82EH5ysT+tKiOheKcAgYST7OoRHGOkxiFe1grnNaiy9gKRnjwgnVe70Ssloe4FTsouG7JES6JOlwbQ=="}],"memo":""},"metadata":{"timestamp":"1790964242"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"RfvAdFpdmxNYM900QKHyIicOUkZOhgHnsi2pxs2KMFxVphJBUFiKesCOTdzFsKwDWgS89aHFfs2KxK3CoJbT7g=="}],"memo":""},"metadata":{"timestamp":"1790964253"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"x1KWP4L4Y1O9cOttsfFWFTeMfgvApBG+D/kA0i0ReVUKyckjQg+JiejdHfcj9bqitI3wzLmXS15l73QRYe6okQ=="}],"memo":""},"metadata":{"timestamp":"1791206264"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"44cs1gbINy2KzuE0a/3WVNY8nHrcmllo+tXWckfsM/xIIjRftvEymcw2ukYYgCS1JlouIqxv9KUyvfYQsem0dw=="}],"memo":""},"metadata":{"timestamp":"1791206326"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"ufmt","path":"gno.land/p/moul/vendor/nt/ufmt/v2","files":[{"name":"README.md","body":"# p/moul/vendor/nt/ufmt (v2 preview)\n\n**This is ufmt v2, published here before its real path exists.** The expected\nhome is [`gno.land/p/nt/ufmt/v2`](/p/nt/ufmt/v2), which is not published yet.\nUntil it is, import:\n\n```go\nimport \"gno.land/p/moul/vendor/nt/ufmt/v2\"\n```\n\nWhen `gno.land/p/nt/ufmt/v2` goes live, change the import and nothing else.\nThis path is then frozen: it keeps working, it never gets another fix.\n\n## Why\n\n[`p/nt/ufmt/v0`](/p/nt/ufmt/v0) knows a handful of verbs and no flags, and it\nfails quietly. `Sprintf(\"0x%08X\", pc)` prints `0x(unhandled verb: %X)`,\n`Sprintf(\"%08x\", w)` prints `(unhandled)`, and `Sprintf(\"%03d\", 7)` prints `7`.\n[`r/moul/x/vm/riscvdemo`](/r/moul/x/vm/riscvdemo/v0) shipped a register dump\nthat was nothing but those.\n\nv2 is Go's `fmt`, as far as gno can follow it:\n\n| | |\n|---|---|\n| flags | `+` `-` `#` ` ` `0` |\n| width, precision | `%8d`, `%.2f`, `%*d`, `%.*f`, `%.3s` in runes |\n| argument indexes | `%[2]d %[1]s`, `%[1]*[2]d` |\n| integers | `%b %c %d %o %O %q %x %X %U`, every int and uint type |\n| floats | `%b %e %E %f %F %g %G %x %X`, float32 and float64 |\n| strings, `[]byte` | `%s %q %x %X`, `% x`, `%#q` |\n| methods | `Formatter`, `GoStringer`, `error`, `Stringer`, in Go's order |\n| errors | `Errorf` with `%w`, one or several, seen by `errors.Is` |\n| composites | slices of the basic types, `[]any`, `map[string]T` sorted by key |\n\nA mistake is printed, never panicked, with Go's strings: `%!d(string=hi)`,\n`%!d(MISSING)`, `%!(EXTRA int=1)`, `%!(NOVERB)`. A `Render` cannot be taken down\nby a format string.\n\n## How it is tested\n\n`gofmt_test.gno` is 210 cases whose expected output was produced by running\neach one through Go's `fmt.Sprintf` (go1.27.1), so a failure there is, by\nconstruction, a place v2 and Go disagree. It also costs less gas than v0 on the\ncalls realms make most: about 211k against 254k per `Sprintf(\"id %d is %s\n(%t)\", ...)`, measured with `gno test`.\n\n## What it cannot do\n\ngno has no `reflect`. A struct, a pointer, or a named type without a `String`\nmethod prints `(unhandled)`, and `%T` names only the types it knows. Give the\ntype a `String` method. `%p` is not supported.\n\n## Migrating from v0\n\nMostly a change of import, with these differences, all of them toward Go:\n\n- `Sprint` adds a space only between two operands that are both non-strings.\n- a float prints in its shortest form from `%v` and `Sprint` (`3.14`, not\n  `3.140000`), and `%e` defaults to 6 digits.\n- `%v` of a `[]byte` is `[104 105]`; use `%s` for the text.\n- a missing or extra argument is written into the output instead of panicking.\n- `error` wins over `String` when a value has both.\n"},{"name":"doc.gno","body":"// Package ufmt is a preview of gno.land/p/nt/ufmt/v2, published here before\n// that path exists.\n//\n// This is v2 of ufmt. It is not yet published at its expected path,\n// gno.land/p/nt/ufmt/v2. Until it is, import it from\n// gno.land/p/moul/vendor/nt/ufmt/v2; once gno.land/p/nt/ufmt/v2 is live,\n// switch the import and nothing else, because the API is meant to be the same.\n// This path is then frozen and never updated again.\n//\n// v0 (gno.land/p/nt/ufmt/v0) supports a handful of verbs and no flags, so\n// \"%08x\", \"%X\" and \"%-10s\" print \"(unhandled)\" or drop their padding without a\n// word. v2 follows Go's fmt instead: the same flags, widths, precisions and\n// verbs, and the same error strings in place of panics. Where it cannot follow\n// Go, because gno has no reflect, it says so below.\n//\n// Supported, as in Go's fmt:\n//\n//\tflags      '+' '-' '#' ' ' '0'\n//\twidth      %8d, %*d, and a negative * width left-justifies\n//\tprecision  %.2f, %.*f, %.3s (in runes)\n//\tindexes    %[2]d %[1]s, %[1]*[2]d\n//\tgeneral    %v %+v %#v %T %%\n//\tbool       %t\n//\tinteger    %b %c %d %o %O %q %x %X %U, every int and uint type\n//\tfloat      %b %e %E %f %F %g %G %x %X, float32 and float64\n//\tstring     %s %q %x %X, and []byte the same way\n//\terrors     %w in Errorf, unwrapped by errors.Unwrap and errors.Is\n//\tmethods    Formatter, GoStringer, error, Stringer, in Go's order\n//\tcomposite  []T of the basic types, []any, []error, and map[string]T\n//\t           with its keys sorted, as Go prints them\n//\n// Errors are written into the output, never panicked: \"%!d(string=hi)\" for a\n// wrong type, \"%!d(MISSING)\" for a missing argument, \"%!(EXTRA int=1)\" for an\n// unused one, \"%!(NOVERB)\" for a trailing '%'.\n//\n// What gno cannot do, and what v2 prints instead:\n//\n//   - no reflect, so a struct, a pointer, a named type without a String\n//     method, or a slice or map of anything other than the types listed above\n//     prints \"(unhandled)\", and %T names only the types it knows (\"unknown\"\n//     otherwise). Give the type a String method.\n//   - %p is not supported.\n//\n// What changed from v0, so a migration is a review and not a find-and-replace:\n//\n//   - Sprint adds a space only between two operands when neither is a string,\n//     as Go does; v0 put a space between every pair.\n//   - %v of a float, and Sprint of one, is the shortest representation (\"3.14\"),\n//     as Go does; v0 printed \"%f\" (\"3.140000\") from Sprint.\n//   - %e defaults to 6 digits after the point, as Go does; v0 used 2.\n//   - %v of a []byte prints \"[104 105]\", as Go does; v0 wrote the raw bytes.\n//     Use %s for the string.\n//   - a missing or extra argument, or a trailing '%', is written into the\n//     output instead of panicking.\n//   - an error is preferred to a String method when a value has both.\npackage ufmt\n"},{"name":"format.gno","body":"package ufmt\n\nimport (\n\t\"strconv\"\n\t\"unicode/utf8\"\n)\n\n// This file is the low level: padding, integers, floats, strings. It is a port\n// of format.go in Go's fmt, kept close enough to read side by side.\n\nconst (\n\tldigits = \"0123456789abcdefx\"\n\tudigits = \"0123456789ABCDEFX\"\n)\n\n// clearFlags resets everything a verb's specifier sets.\nfunc (p *printer) clearFlags() {\n\tp.plus, p.minus, p.sharp, p.space, p.zero = false, false, false, false, false\n\tp.plusV, p.sharpV = false, false\n\tp.wid, p.prec = 0, 0\n\tp.widPresent, p.precPresent = false, false\n}\n\n// writePadding writes n pad bytes: zeros when the 0 flag is set, else spaces.\nfunc (p *printer) writePadding(n int) {\n\tif n \u003c= 0 {\n\t\treturn\n\t}\n\tc := byte(' ')\n\tif p.zero {\n\t\tc = '0'\n\t}\n\tfor i := 0; i \u003c n; i++ {\n\t\tp.buf = append(p.buf, c)\n\t}\n}\n\n// pad writes b, padded to the width in runes, on the side the - flag says.\nfunc (p *printer) pad(b []byte) {\n\tif !p.widPresent || p.wid == 0 {\n\t\tp.buf = append(p.buf, b...)\n\t\treturn\n\t}\n\twidth := p.wid - utf8.RuneCount(b)\n\tif !p.minus {\n\t\tp.writePadding(width)\n\t\tp.buf = append(p.buf, b...)\n\t} else {\n\t\tp.buf = append(p.buf, b...)\n\t\tp.writePadding(width)\n\t}\n}\n\n// padString is pad for a string.\nfunc (p *printer) padString(s string) {\n\tif !p.widPresent || p.wid == 0 {\n\t\tp.buf = append(p.buf, s...)\n\t\treturn\n\t}\n\twidth := p.wid - utf8.RuneCountInString(s)\n\tif !p.minus {\n\t\tp.writePadding(width)\n\t\tp.buf = append(p.buf, s...)\n\t} else {\n\t\tp.buf = append(p.buf, s...)\n\t\tp.writePadding(width)\n\t}\n}\n\n// padNoZero pads with spaces whatever the 0 flag says.\nfunc (p *printer) padNoZero(b []byte) {\n\toldZero := p.zero\n\tp.zero = false\n\tp.pad(b)\n\tp.zero = oldZero\n}\n\nfunc (p *printer) fmtBoolean(v bool) {\n\tif v {\n\t\tp.padString(\"true\")\n\t} else {\n\t\tp.padString(\"false\")\n\t}\n}\n\n// fmtInteger formats u, the magnitude, in base, with a '-' when negative.\nfunc (p *printer) fmtInteger(u uint64, negative bool, base int, verb rune, digits string) {\n\t// Fast path: no flags, width or precision, lowercase digits.\n\tif !p.widPresent \u0026\u0026 !p.precPresent \u0026\u0026 !p.plus \u0026\u0026 !p.space \u0026\u0026 !p.sharp \u0026\u0026\n\t\tverb != 'O' \u0026\u0026 (base != 16 || digits[10] == 'a') {\n\t\tif negative {\n\t\t\tp.buf = append(p.buf, '-')\n\t\t}\n\t\tp.buf = strconv.AppendUint(p.buf, u, base)\n\t\treturn\n\t}\n\n\tprec := 0\n\tif p.precPresent {\n\t\tprec = p.prec\n\t\t// %.0d of zero prints nothing but its padding.\n\t\tif prec == 0 \u0026\u0026 u == 0 {\n\t\t\toldZero := p.zero\n\t\t\tp.zero = false\n\t\t\tp.writePadding(p.wid)\n\t\t\tp.zero = oldZero\n\t\t\treturn\n\t\t}\n\t} else if p.zero \u0026\u0026 !p.minus \u0026\u0026 p.widPresent {\n\t\t// Zero padding is a precision in disguise, minus room for the sign.\n\t\tprec = p.wid\n\t\tif negative || p.plus || p.space {\n\t\t\tprec--\n\t\t}\n\t}\n\n\tsize := 68 // 64 binary digits, a sign and a 0b/0x/0o prefix\n\tif prec+4 \u003e size {\n\t\tsize = prec + 4\n\t}\n\tbuf := make([]byte, size)\n\ti := size\n\n\tswitch base {\n\tcase 10:\n\t\tfor u \u003e= 10 {\n\t\t\ti--\n\t\t\tnext := u / 10\n\t\t\tbuf[i] = byte('0' + u - next*10)\n\t\t\tu = next\n\t\t}\n\tcase 16:\n\t\tfor u \u003e= 16 {\n\t\t\ti--\n\t\t\tbuf[i] = digits[u\u00260xF]\n\t\t\tu \u003e\u003e= 4\n\t\t}\n\tcase 8:\n\t\tfor u \u003e= 8 {\n\t\t\ti--\n\t\t\tbuf[i] = byte('0' + u\u00267)\n\t\t\tu \u003e\u003e= 3\n\t\t}\n\tcase 2:\n\t\tfor u \u003e= 2 {\n\t\t\ti--\n\t\t\tbuf[i] = byte('0' + u\u00261)\n\t\t\tu \u003e\u003e= 1\n\t\t}\n\t}\n\ti--\n\tbuf[i] = digits[u]\n\tfor i \u003e 0 \u0026\u0026 prec \u003e size-i {\n\t\ti--\n\t\tbuf[i] = '0'\n\t}\n\n\tif p.sharp {\n\t\tswitch base {\n\t\tcase 2:\n\t\t\ti--\n\t\t\tbuf[i] = 'b'\n\t\t\ti--\n\t\t\tbuf[i] = '0'\n\t\tcase 8:\n\t\t\tif buf[i] != '0' {\n\t\t\t\ti--\n\t\t\t\tbuf[i] = '0'\n\t\t\t}\n\t\tcase 16:\n\t\t\ti--\n\t\t\tbuf[i] = digits[16]\n\t\t\ti--\n\t\t\tbuf[i] = '0'\n\t\t}\n\t}\n\tif verb == 'O' {\n\t\ti--\n\t\tbuf[i] = 'o'\n\t\ti--\n\t\tbuf[i] = '0'\n\t}\n\n\tif negative {\n\t\ti--\n\t\tbuf[i] = '-'\n\t} else if p.plus {\n\t\ti--\n\t\tbuf[i] = '+'\n\t} else if p.space {\n\t\ti--\n\t\tbuf[i] = ' '\n\t}\n\n\t// The zeros, if any, are already in buf: pad the rest with spaces.\n\tp.padNoZero(buf[i:])\n}\n\n// fmtUnicode formats u as \"U+0078\", or \"U+0078 'x'\" with the # flag.\nfunc (p *printer) fmtUnicode(u uint64) {\n\tprec := 4\n\tif p.precPresent \u0026\u0026 p.prec \u003e 4 {\n\t\tprec = p.prec\n\t}\n\thex := strconv.FormatUint(u, 16)\n\tb := []byte(\"U+\")\n\tfor n := len(hex); n \u003c prec; n++ {\n\t\tb = append(b, '0')\n\t}\n\tfor i := 0; i \u003c len(hex); i++ {\n\t\tc := hex[i]\n\t\tif c \u003e= 'a' {\n\t\t\tc -= 'a' - 'A'\n\t\t}\n\t\tb = append(b, c)\n\t}\n\tif p.sharp \u0026\u0026 u \u003c= utf8.MaxRune \u0026\u0026 strconv.IsPrint(rune(u)) {\n\t\tb = append(b, ' ', '\\'')\n\t\tb = utf8.AppendRune(b, rune(u))\n\t\tb = append(b, '\\'')\n\t}\n\tp.padNoZero(b)\n}\n\n// fmtC formats u as the rune it encodes, or U+FFFD when it encodes none.\nfunc (p *printer) fmtC(u uint64) {\n\tr := rune(utf8.RuneError)\n\tif u \u003c= utf8.MaxRune {\n\t\tr = rune(u)\n\t}\n\tp.pad(utf8.AppendRune(nil, r))\n}\n\n// fmtQc formats u as a single-quoted rune literal.\nfunc (p *printer) fmtQc(u uint64) {\n\tr := rune(utf8.RuneError)\n\tif u \u003c= utf8.MaxRune {\n\t\tr = rune(u)\n\t}\n\tif p.plus {\n\t\tp.pad(strconv.AppendQuoteRuneToASCII(nil, r))\n\t} else {\n\t\tp.pad(strconv.AppendQuoteRune(nil, r))\n\t}\n}\n\n// fmtFloat formats v, with prec digits (-1 for the shortest) unless the verb\n// set its own precision.\nfunc (p *printer) fmtFloat(v float64, size int, verb rune, prec int) {\n\tif p.precPresent {\n\t\tprec = p.prec\n\t}\n\t// num[0] is reserved for the sign.\n\tnum := strconv.AppendFloat([]byte{0}, v, byte(verb), prec, size)\n\tif num[1] == '-' || num[1] == '+' {\n\t\tnum = num[1:]\n\t} else {\n\t\tnum[0] = '+'\n\t}\n\tif p.space \u0026\u0026 num[0] == '+' \u0026\u0026 !p.plus {\n\t\tnum[0] = ' '\n\t}\n\t// Infinities and NaN do not look like numbers, so they are never zero padded.\n\tif num[1] == 'I' || num[1] == 'N' {\n\t\toldZero := p.zero\n\t\tp.zero = false\n\t\tif num[1] == 'N' \u0026\u0026 !p.space \u0026\u0026 !p.plus {\n\t\t\tnum = num[1:]\n\t\t}\n\t\tp.pad(num)\n\t\tp.zero = oldZero\n\t\treturn\n\t}\n\n\t// The # flag keeps the decimal point, and for %g the trailing zeros.\n\tif p.sharp \u0026\u0026 verb != 'b' {\n\t\tdigits := 0\n\t\tif verb == 'v' || verb == 'g' || verb == 'G' || verb == 'x' {\n\t\t\tdigits = prec\n\t\t\tif digits == -1 {\n\t\t\t\tdigits = 6\n\t\t\t}\n\t\t}\n\t\tvar tail []byte\n\t\thasDecimalPoint := false\n\t\tsawNonzeroDigit := false\n\t\tfor i := 1; i \u003c len(num); i++ {\n\t\t\tc := num[i]\n\t\t\tif c == '.' {\n\t\t\t\thasDecimalPoint = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif c == 'p' || c == 'P' || ((c == 'e' || c == 'E') \u0026\u0026 verb != 'x' \u0026\u0026 verb != 'X') {\n\t\t\t\ttail = append(tail, num[i:]...)\n\t\t\t\tnum = num[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif c != '0' {\n\t\t\t\tsawNonzeroDigit = true\n\t\t\t}\n\t\t\tif sawNonzeroDigit {\n\t\t\t\tdigits--\n\t\t\t}\n\t\t}\n\t\tif !hasDecimalPoint {\n\t\t\t// A lone leading zero counts as one significant digit.\n\t\t\tif len(num) == 2 \u0026\u0026 num[1] == '0' {\n\t\t\t\tdigits--\n\t\t\t}\n\t\t\tnum = append(num, '.')\n\t\t}\n\t\tfor digits \u003e 0 {\n\t\t\tnum = append(num, '0')\n\t\t\tdigits--\n\t\t}\n\t\tnum = append(num, tail...)\n\t}\n\n\tif p.plus || num[0] != '+' {\n\t\t// Zero padding goes after the sign.\n\t\tif p.zero \u0026\u0026 !p.minus \u0026\u0026 p.widPresent \u0026\u0026 p.wid \u003e len(num) {\n\t\t\tp.buf = append(p.buf, num[0])\n\t\t\tp.writePadding(p.wid - len(num))\n\t\t\tp.buf = append(p.buf, num[1:]...)\n\t\t\treturn\n\t\t}\n\t\tp.pad(num)\n\t\treturn\n\t}\n\tp.pad(num[1:])\n}\n\n// truncate cuts s to the precision, counted in runes.\nfunc (p *printer) truncate(s string) string {\n\tif p.precPresent {\n\t\tn := p.prec\n\t\tfor i := range s {\n\t\t\tn--\n\t\t\tif n \u003c 0 {\n\t\t\t\treturn s[:i]\n\t\t\t}\n\t\t}\n\t}\n\treturn s\n}\n\nfunc (p *printer) fmtS(s string) {\n\tp.padString(p.truncate(s))\n}\n\n// fmtSx formats s as hex, two digits a byte. The space flag separates bytes,\n// and # prefixes 0x, once or before each byte when spaced.\nfunc (p *printer) fmtSx(s string, digits string) {\n\tlength := len(s)\n\tif p.precPresent \u0026\u0026 p.prec \u003c length {\n\t\tlength = p.prec\n\t}\n\twidth := 2 * length\n\tif width \u003e 0 {\n\t\tif p.space {\n\t\t\tif p.sharp {\n\t\t\t\twidth *= 2\n\t\t\t}\n\t\t\twidth += length - 1\n\t\t} else if p.sharp {\n\t\t\twidth += 2\n\t\t}\n\t} else {\n\t\tif p.widPresent {\n\t\t\tp.writePadding(p.wid)\n\t\t}\n\t\treturn\n\t}\n\tif p.widPresent \u0026\u0026 p.wid \u003e width \u0026\u0026 !p.minus {\n\t\tp.writePadding(p.wid - width)\n\t}\n\tif p.sharp {\n\t\tp.buf = append(p.buf, '0', digits[16])\n\t}\n\tfor i := 0; i \u003c length; i++ {\n\t\tif p.space \u0026\u0026 i \u003e 0 {\n\t\t\tp.buf = append(p.buf, ' ')\n\t\t\tif p.sharp {\n\t\t\t\tp.buf = append(p.buf, '0', digits[16])\n\t\t\t}\n\t\t}\n\t\tc := s[i]\n\t\tp.buf = append(p.buf, digits[c\u003e\u003e4], digits[c\u00260xF])\n\t}\n\tif p.widPresent \u0026\u0026 p.wid \u003e width \u0026\u0026 p.minus {\n\t\tp.writePadding(p.wid - width)\n\t}\n}\n\n// fmtQ formats s as a double-quoted Go string, backquoted with the # flag when\n// it can be, and ASCII only with the + flag.\nfunc (p *printer) fmtQ(s string) {\n\ts = p.truncate(s)\n\tif p.sharp \u0026\u0026 strconv.CanBackquote(s) {\n\t\tp.padString(\"`\" + s + \"`\")\n\t\treturn\n\t}\n\tif p.plus {\n\t\tp.pad(strconv.AppendQuoteToASCII(nil, s))\n\t} else {\n\t\tp.pad(strconv.AppendQuote(nil, s))\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/vendor/nt/ufmt/v2\"\ngno = \"0.9\"\n"},{"name":"gofmt_test.gno","body":"package ufmt\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n// goCases were generated by running each row through Go's fmt.Sprintf\n// (go1.27.1), so a row that fails here is a place v2 differs from Go.\nvar goCases = []struct {\n\tformat string\n\targs   []any\n\twant   string\n}{\n\t{\"%d\", []any{7}, \"7\"},\n\t{\"%03d\", []any{7}, \"007\"},\n\t{\"%08X\", []any{uint32(0xdead)}, \"0000DEAD\"},\n\t{\"0x%08X\", []any{uint32(0x10074)}, \"0x00010074\"},\n\t{\"%08x\", []any{uint32(0x00a00513)}, \"00a00513\"},\n\t{\"%x\", []any{uint32(255)}, \"ff\"},\n\t{\"%X\", []any{-255}, \"-FF\"},\n\t{\"%#x\", []any{255}, \"0xff\"},\n\t{\"%#X\", []any{255}, \"0XFF\"},\n\t{\"%#08x\", []any{255}, \"0x000000ff\"},\n\t{\"%#o\", []any{8}, \"010\"},\n\t{\"%O\", []any{8}, \"0o10\"},\n\t{\"%b\", []any{5}, \"101\"},\n\t{\"%#b\", []any{5}, \"0b101\"},\n\t{\"%o\", []any{-8}, \"-10\"},\n\t{\"%5d\", []any{42}, \"   42\"},\n\t{\"%-5d|\", []any{42}, \"42   |\"},\n\t{\"%+d\", []any{42}, \"+42\"},\n\t{\"% d\", []any{42}, \" 42\"},\n\t{\"%+05d\", []any{42}, \"+0042\"},\n\t{\"%-05d|\", []any{42}, \"42   |\"},\n\t{\"%.3d\", []any{7}, \"007\"},\n\t{\"%8.3d\", []any{-7}, \"    -007\"},\n\t{\"%.0d\", []any{0}, \"\"},\n\t{\"%5.0d|\", []any{0}, \"     |\"},\n\t{\"%d\", []any{int64(-9223372036854775808)}, \"-9223372036854775808\"},\n\t{\"%x\", []any{int64(-9223372036854775808)}, \"-8000000000000000\"},\n\t{\"%d\", []any{uint64(18446744073709551615)}, \"18446744073709551615\"},\n\t{\"%x\", []any{uint64(18446744073709551615)}, \"ffffffffffffffff\"},\n\t{\"%d\", []any{int8(-128)}, \"-128\"},\n\t{\"%d\", []any{uint8(200)}, \"200\"},\n\t{\"%x\", []any{int16(-1)}, \"-1\"},\n\t{\"%d\", []any{\"hi\"}, \"%!d(string=hi)\"},\n\t{\"%s\", []any{42}, \"%!s(int=42)\"},\n\t{\"%c\", []any{'x'}, \"x\"},\n\t{\"%c\", []any{0x1F600}, \"😀\"},\n\t{\"%q\", []any{'x'}, \"'x'\"},\n\t{\"%+q\", []any{'é'}, \"'\\\\u00e9'\"},\n\t{\"%U\", []any{0x1F600}, \"U+1F600\"},\n\t{\"%#U\", []any{'x'}, \"U+0078 'x'\"},\n\t{\"%U\", []any{1}, \"U+0001\"},\n\t{\"%.6U\", []any{1}, \"U+000001\"},\n\t{\"%c\", []any{-1}, \"�\"},\n\t{\"%s\", []any{\"hello\"}, \"hello\"},\n\t{\"%10s|\", []any{\"hello\"}, \"     hello|\"},\n\t{\"%-10s|\", []any{\"hello\"}, \"hello     |\"},\n\t{\"%.2s\", []any{\"hello\"}, \"he\"},\n\t{\"%.2s\", []any{\"héllo\"}, \"hé\"},\n\t{\"%5.1s|\", []any{\"héllo\"}, \"    h|\"},\n\t{\"%05s\", []any{\"ab\"}, \"000ab\"},\n\t{\"%q\", []any{\"hi\\n\"}, \"\\\"hi\\\\n\\\"\"},\n\t{\"%+q\", []any{\"héllo\"}, \"\\\"h\\\\u00e9llo\\\"\"},\n\t{\"%#q\", []any{\"back`tick\"}, \"\\\"back`tick\\\"\"},\n\t{\"%#q\", []any{\"plain\"}, \"`plain`\"},\n\t{\"%x\", []any{\"hello\"}, \"68656c6c6f\"},\n\t{\"%X\", []any{\"hello\"}, \"68656C6C6F\"},\n\t{\"% x\", []any{\"hello\"}, \"68 65 6c 6c 6f\"},\n\t{\"%# x\", []any{\"hi\"}, \"0x68 0x69\"},\n\t{\"%#x\", []any{\"hi\"}, \"0x6869\"},\n\t{\"%10x|\", []any{\"hi\"}, \"      6869|\"},\n\t{\"%-10x|\", []any{\"hi\"}, \"6869      |\"},\n\t{\"%x\", []any{\"\"}, \"\"},\n\t{\"%5x|\", []any{\"\"}, \"     |\"},\n\t{\"%.1x\", []any{\"hi\"}, \"68\"},\n\t{\"%s\", []any{[]byte(\"bytes\")}, \"bytes\"},\n\t{\"%x\", []any{[]byte{1, 171}}, \"01ab\"},\n\t{\"%X\", []any{[]byte{1, 171}}, \"01AB\"},\n\t{\"%v\", []any{[]byte{1, 2}}, \"[1 2]\"},\n\t{\"%d\", []any{[]byte{1, 2}}, \"[1 2]\"},\n\t{\"%#v\", []any{[]byte{1, 2}}, \"[]byte{0x1, 0x2}\"},\n\t{\"%q\", []any{[]byte(\"q\")}, \"\\\"q\\\"\"},\n\t{\"%b\", []any{[]byte{3}}, \"[11]\"},\n\t{\"%t\", []any{true}, \"true\"},\n\t{\"%v\", []any{false}, \"false\"},\n\t{\"%5t|\", []any{true}, \" true|\"},\n\t{\"%d\", []any{true}, \"%!d(bool=true)\"},\n\t{\"%f\", []any{3.14159}, \"3.141590\"},\n\t{\"%.2f\", []any{3.14159}, \"3.14\"},\n\t{\"%8.3f|\", []any{3.14159}, \"   3.142|\"},\n\t{\"%-8.3f|\", []any{3.14159}, \"3.142   |\"},\n\t{\"%08.3f\", []any{-3.14159}, \"-003.142\"},\n\t{\"%+.1f\", []any{2.0}, \"+2.0\"},\n\t{\"% .1f\", []any{2.0}, \" 2.0\"},\n\t{\"%e\", []any{1234.5678}, \"1.234568e+03\"},\n\t{\"%E\", []any{1234.5678}, \"1.234568E+03\"},\n\t{\"%.2e\", []any{1234.5678}, \"1.23e+03\"},\n\t{\"%g\", []any{1234.5678}, \"1234.5678\"},\n\t{\"%g\", []any{1e21}, \"1e+21\"},\n\t{\"%g\", []any{0.00001}, \"1e-05\"},\n\t{\"%G\", []any{1e-10}, \"1E-10\"},\n\t{\"%v\", []any{3.14}, \"3.14\"},\n\t{\"%v\", []any{1e6}, \"1e+06\"},\n\t{\"%v\", []any{100000.0}, \"100000\"},\n\t{\"%v\", []any{float32(0.1)}, \"0.1\"},\n\t{\"%F\", []any{1.5}, \"1.500000\"},\n\t{\"%#g\", []any{1.0}, \"1.00000\"},\n\t{\"%#.3g\", []any{1.0}, \"1.00\"},\n\t{\"%#f\", []any{1.0}, \"1.000000\"},\n\t{\"%#.0f\", []any{1.0}, \"1.\"},\n\t{\"%#.0e\", []any{1.0}, \"1.e+00\"},\n\t{\"%x\", []any{1.0}, \"0x1p+00\"},\n\t{\"%X\", []any{1.0}, \"0X1P+00\"},\n\t{\"%b\", []any{1.0}, \"4503599627370496p-52\"},\n\t{\"%.3x\", []any{3.14159}, \"0x1.922p+01\"},\n\t{\"%f\", []any{math.Inf(1)}, \"+Inf\"},\n\t{\"%+f\", []any{math.Inf(1)}, \"+Inf\"},\n\t{\"%08f\", []any{math.Inf(-1)}, \"    -Inf\"},\n\t{\"%f\", []any{math.NaN()}, \"NaN\"},\n\t{\"%+f\", []any{math.NaN()}, \"+NaN\"},\n\t{\"%010.2f\", []any{12.5}, \"0000012.50\"},\n\t{\"%s\", []any{1.5}, \"%!s(float64=1.5)\"},\n\t{\"%v\", []any{nil}, \"\u003cnil\u003e\"},\n\t{\"%d\", []any{nil}, \"%!d(\u003cnil\u003e)\"},\n\t{\"%s\", []any{nil}, \"%!s(\u003cnil\u003e)\"},\n\t{\"%T\", []any{nil}, \"\u003cnil\u003e\"},\n\t{\"%T\", []any{42}, \"int\"},\n\t{\"%T\", []any{\"s\"}, \"string\"},\n\t{\"%T\", []any{[]byte(\"x\")}, \"[]uint8\"},\n\t{\"%T\", []any{3.0}, \"float64\"},\n\t{\"%T\", []any{int8(1)}, \"int8\"},\n\t{\"%T\", []any{[]string{\"a\"}}, \"[]string\"},\n\t{\"%T\", []any{map[string]int{}}, \"map[string]int\"},\n\t{\"%5T|\", []any{1}, \"  int|\"},\n\t{\"%v\", []any{[]string{\"a\", \"b\"}}, \"[a b]\"},\n\t{\"%q\", []any{[]string{\"a\", \"b\"}}, \"[\\\"a\\\" \\\"b\\\"]\"},\n\t{\"%#v\", []any{[]string{\"a\", \"b\"}}, \"[]string{\\\"a\\\", \\\"b\\\"}\"},\n\t{\"%#v\", []any{[]string(nil)}, \"[]string(nil)\"},\n\t{\"%v\", []any{[]int{1, 2, 3}}, \"[1 2 3]\"},\n\t{\"%3d\", []any{[]int{1, 2}}, \"[  1   2]\"},\n\t{\"%x\", []any{[]int{10, 255}}, \"[a ff]\"},\n\t{\"%d\", []any{[]string{\"a\"}}, \"[%!d(string=a)]\"},\n\t{\"%v\", []any{[]any{1, \"a\", nil, true}}, \"[1 a \u003cnil\u003e true]\"},\n\t{\"%#v\", []any{[]any{1, \"a\", nil}}, \"[]interface {}{1, \\\"a\\\", interface {}(nil)}\"},\n\t{\"%v\", []any{[]float64{1.5, 2}}, \"[1.5 2]\"},\n\t{\"%v\", []any{map[string]int{\"b\": 2, \"a\": 1, \"c\": 3}}, \"map[a:1 b:2 c:3]\"},\n\t{\"%#v\", []any{map[string]int{\"b\": 2, \"a\": 1}}, \"map[string]int{\\\"a\\\":1, \\\"b\\\":2}\"},\n\t{\"%v\", []any{map[string]string{\"k\": \"v\"}}, \"map[k:v]\"},\n\t{\"%v\", []any{map[string]any{\"x\": nil, \"y\": 1}}, \"map[x:\u003cnil\u003e y:1]\"},\n\t{\"%v\", []any{map[string]bool{}}, \"map[]\"},\n\t{\"%#v\", []any{\"str\"}, \"\\\"str\\\"\"},\n\t{\"%#v\", []any{42}, \"42\"},\n\t{\"%#v\", []any{uint(42)}, \"0x2a\"},\n\t{\"%#v\", []any{3.0}, \"3\"},\n\t{\"%#v\", []any{true}, \"true\"},\n\t{\"%#v\", []any{nil}, \"\u003cnil\u003e\"},\n\t{\"%+v\", []any{42}, \"42\"},\n\t{\"%+v\", []any{\"x\"}, \"x\"},\n\t{\"%%\", []any{}, \"%\"},\n\t{\"100%%\", []any{}, \"100%\"},\n\t{\"%5%\", []any{}, \"%\"},\n\t{\"%\", []any{}, \"%!(NOVERB)\"},\n\t{\"abc%\", []any{}, \"abc%!(NOVERB)\"},\n\t{\"%!\", []any{}, \"%!!(MISSING)\"},\n\t{\"%z\", []any{1}, \"%!z(int=1)\"},\n\t{\"%d\", []any{}, \"%!d(MISSING)\"},\n\t{\"%d %d\", []any{1}, \"1 %!d(MISSING)\"},\n\t{\"%d\", []any{1, 2}, \"1%!(EXTRA int=2)\"},\n\t{\"%s\", []any{\"a\", 3, nil}, \"a%!(EXTRA int=3, \u003cnil\u003e)\"},\n\t{\"%[2]d %[1]d\", []any{1, 2}, \"2 1\"},\n\t{\"%[1]d %[1]x\", []any{255}, \"255 ff\"},\n\t{\"%[3]d\", []any{1, 2}, \"%!d(BADINDEX)\"},\n\t{\"%[0]d\", []any{1}, \"%!d(BADINDEX)\"},\n\t{\"%[x]d\", []any{1}, \"%!d(BADINDEX)\"},\n\t{\"%[1]*d|\", []any{5, 42}, \"   42|\"},\n\t{\"%[2]*[1]d|\", []any{42, 6}, \"    42|\"},\n\t{\"%*d|\", []any{5, 42}, \"   42|\"},\n\t{\"%-*d|\", []any{5, 42}, \"42   |\"},\n\t{\"%*d|\", []any{-5, 42}, \"42   |\"},\n\t{\"%.*f\", []any{2, 3.14159}, \"3.14\"},\n\t{\"%.*f\", []any{-1, 3.14159}, \"%!(BADPREC)3.141590\"},\n\t{\"%*d\", []any{\"x\", 1}, \"%!(BADWIDTH)1\"},\n\t{\"%.*d\", []any{\"x\", 1}, \"%!(BADPREC)1\"},\n\t{\"%*.*f|\", []any{8, 2, 3.14159}, \"    3.14|\"},\n\t{\"%d %s\", []any{1}, \"1 %!s(MISSING)\"},\n\t{\"%[2]d\", []any{1}, \"%!d(BADINDEX)\"},\n\t{\"%5.2v|\", []any{3.14159}, \"  3.1|\"},\n\t{\"%v %v\", []any{\"a\", \"b\"}, \"a b\"},\n\t{\"%-+5d|\", []any{3}, \"+3   |\"},\n\t{\"%+-5d|\", []any{3}, \"+3   |\"},\n\t{\"%0-5d|\", []any{3}, \"3    |\"},\n\t{\"%x\", []any{-1}, \"-1\"},\n\t{\"%#v\", []any{[]byte(nil)}, \"[]byte(nil)\"},\n\t{\"%v\", []any{[]byte{}}, \"[]\"},\n\t{\"%v\", []any{[]string{}}, \"[]\"},\n\t{\"%d\", []any{[]any{1, \"x\"}}, \"[1 %!d(string=x)]\"},\n\t{\"%v\", []any{int32(-5)}, \"-5\"},\n\t{\"%c\", []any{65}, \"A\"},\n\t{\"%x\", []any{\"\\xff\\x00\"}, \"ff00\"},\n\t{\"%s\", []any{\"日本語\"}, \"日本語\"},\n\t{\"%6s|\", []any{\"日本語\"}, \"   日本語|\"},\n\t{\"%-6s|\", []any{\"日本語\"}, \"日本語   |\"},\n\t{\"%q\", []any{\"日本語\"}, \"\\\"日本語\\\"\"},\n\t{\"%+q\", []any{\"日本語\"}, \"\\\"\\\\u65e5\\\\u672c\\\\u8a9e\\\"\"},\n\t{\"%x\", []any{\"日本\"}, \"e697a5e69cac\"},\n\t{\"%v\", []any{\"\\x00\"}, \"\\x00\"},\n\t{\"%q\", []any{'\\n'}, \"'\\\\n'\"},\n\t{\"%q\", []any{0x110000}, \"'�'\"},\n\t{\"%U\", []any{-1}, \"U+FFFFFFFFFFFFFFFF\"},\n\t{\"%10.4f|\", []any{1234.56789}, \" 1234.5679|\"},\n\t{\"%-10.1e|\", []any{1234.56789}, \"1.2e+03   |\"},\n\t{\"%+e\", []any{0.0}, \"+0.000000e+00\"},\n\t{\"%g\", []any{-0.0}, \"0\"},\n\t{\"%.3g\", []any{123456.0}, \"1.23e+05\"},\n\t{\"%.10g\", []any{1.0 / 3}, \"0.3333333333\"},\n\t{\"%e\", []any{float32(1.0) / 3}, \"3.333333e-01\"},\n\t{\"%v\", []any{float32(16777216.0)}, \"1.6777216e+07\"},\n\t{\"%v\", []any{1e100}, \"1e+100\"},\n\t{\"%v\", []any{123456789.0}, \"1.23456789e+08\"},\n\t{\"%v\", []any{0.000001}, \"1e-06\"},\n\t{\"%v\", []any{0.0000001}, \"1e-07\"},\n}\n\nfunc TestSprintfMatchesGo(t *testing.T) {\n\tfor _, c := range goCases {\n\t\tif got := Sprintf(c.format, c.args...); got != c.want {\n\t\t\tt.Errorf(\"Sprintf(%q, %v) = %q, want %q\", c.format, c.args, got, c.want)\n\t\t}\n\t}\n}\n"},{"name":"methods_test.gno","body":"package ufmt\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"testing\"\n)\n\ntype str struct{ s string }\n\nfunc (v str) String() string { return v.s }\n\ntype errT struct{}\n\nfunc (errT) Error() string  { return \"boom\" }\nfunc (errT) String() string { return \"stringer\" }\n\ntype goStr struct{}\n\nfunc (goStr) GoString() string { return \"goStr{}\" }\nfunc (goStr) String() string   { return \"plain\" }\n\ntype formatter struct{}\n\nfunc (formatter) Format(f State, verb rune) {\n\tw, wok := f.Width()\n\tp, pok := f.Precision()\n\tFprintf(f, \"F[%c w=%d/%t p=%d/%t minus=%t plus=%t sharp=%t]\",\n\t\tverb, w, wok, p, pok, f.Flag('-'), f.Flag('+'), f.Flag('#'))\n}\n\ntype panicky struct{}\n\nfunc (panicky) String() string { panic(\"nope\") }\n\ntype opaque struct{ n int }\n\n// Every want below is what Go's fmt prints for the same call (go1.27.1),\n// except where a comment says gno cannot see what Go sees.\nfunc TestMethods(t *testing.T) {\n\tcases := []struct{ got, want string }{\n\t\t{Sprintf(\"%v|%s|%q|%x|%10s|%-6v|\", str{\"hi\"}, str{\"hi\"}, str{\"hi\"}, str{\"hi\"}, str{\"hi\"}, str{\"hi\"}),\n\t\t\t`hi|hi|\"hi\"|6869|        hi|hi    |`},\n\t\t{Sprintf(\"%v %s\", errT{}, errT{}), \"boom boom\"}, // Error wins over String\n\t\t{Sprintf(\"%#v %v\", goStr{}, goStr{}), \"goStr{} plain\"},\n\t\t{Sprintf(\"%v|%-8.3s|%+#x\", formatter{}, formatter{}, formatter{}),\n\t\t\t\"F[v w=0/false p=0/false minus=false plus=false sharp=false]|\" +\n\t\t\t\t\"F[s w=8/true p=3/true minus=true plus=false sharp=false]|\" +\n\t\t\t\t\"F[x w=0/false p=0/false minus=false plus=true sharp=true]\"},\n\t\t{Sprintf(\"%v\", panicky{}), \"%!v(PANIC=String method: nope)\"},\n\t\t{Sprintf(\"%v\", []any{str{\"a\"}, errT{}}), \"[a boom]\"},\n\t\t{Sprintf(\"%s\", []error{errors.New(\"base\"), errT{}}), \"[base boom]\"},\n\t\t{Sprint(\"a\", 1, 2, \"b\", \"c\", 3.5, true, nil), \"a1 2bc3.5 true \u003cnil\u003e\"},\n\t\t{Sprint(str{\"x\"}, str{\"y\"}), \"x y\"},\n\t\t{Sprintln(\"a\", 1, 2, \"b\"), \"a 1 2 b\\n\"},\n\n\t\t// Go reflects into the struct and prints \"{%!d(string=hi)}\" and\n\t\t// \"{7}\"; gno has no reflect, so v2 says so instead of guessing.\n\t\t{Sprintf(\"%d\", str{\"hi\"}), \"%!d(unhandled)\"},\n\t\t{Sprintf(\"%v\", opaque{7}), \"(unhandled)\"},\n\t\t{Sprintf(\"%T\", opaque{7}), \"unknown\"},\n\t\t// Go prints \"%!w(*errors.errorString=\u0026{base})\": the type is not\n\t\t// nameable here either.\n\t\t{Sprintf(\"%w\", errors.New(\"base\")), \"%!w(unhandled)\"},\n\t}\n\tfor i, c := range cases {\n\t\tif c.got != c.want {\n\t\t\tt.Errorf(\"case %d: got %q, want %q\", i, c.got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestErrorf(t *testing.T) {\n\tbase := errors.New(\"base\")\n\n\te := Errorf(\"wrap: %w\", base)\n\tif e.Error() != \"wrap: base\" || !errors.Is(e, base) || errors.Unwrap(e) != base {\n\t\tt.Errorf(\"single %%w: %q, Is=%t\", e.Error(), errors.Is(e, base))\n\t}\n\n\te2 := Errorf(\"two: %w and %w\", base, errT{})\n\tif e2.Error() != \"two: base and boom\" || !errors.Is(e2, base) || errors.Unwrap(e2) != nil {\n\t\tt.Errorf(\"two %%w: %q, Is=%t\", e2.Error(), errors.Is(e2, base))\n\t}\n\n\tif got := Errorf(\"%w\", \"notanerror\").Error(); got != \"%!w(string=notanerror)\" {\n\t\tt.Errorf(\"non-error %%w: %q\", got)\n\t}\n\n\tplain := Errorf(\"plain %d\", 1)\n\tif plain.Error() != \"plain 1\" || errors.Unwrap(plain) != nil {\n\t\tt.Errorf(\"plain: %q\", plain.Error())\n\t}\n}\n\nfunc TestWriters(t *testing.T) {\n\tvar sb strings.Builder\n\tn, err := Fprintf(\u0026sb, \"%04d|\", 7)\n\tFprint(\u0026sb, \"a\", 1)\n\tFprintln(\u0026sb, \"!\", 2)\n\tif sb.String() != \"0007|a1! 2\\n\" || n != 5 || err != nil {\n\t\tt.Errorf(\"Fprint*: %q n=%d err=%v\", sb.String(), n, err)\n\t}\n\n\tb := Appendf([]byte(\"x=\"), \"%x\", 255)\n\tb = Append(b, \" \", true)\n\tb = Appendln(b, \"\", 1)\n\tif string(b) != \"x=ff true 1\\n\" {\n\t\tt.Errorf(\"Append*: %q\", string(b))\n\t}\n}\n\n// The register dump that v0 could not print: \"0x(unhandled verb: %X)\".\nfunc TestRegisterDump(t *testing.T) {\n\tgot := Sprintf(\"0x%08X %08x\", uint32(0x1004), uint32(0xa00513))\n\tif got != \"0x00001004 00a00513\" {\n\t\tt.Errorf(\"got %q\", got)\n\t}\n}\n"},{"name":"print.gno","body":"package ufmt\n\nimport (\n\t\"sort\"\n\t\"unicode/utf8\"\n)\n\n// This file is the high level: parsing the format, and choosing how each\n// operand prints. It is a port of print.go in Go's fmt, minus reflect.\n\nconst (\n\tcommaSpace  = \", \"\n\tnilAngle    = \"\u003cnil\u003e\"\n\tnilParen    = \"(nil)\"\n\tunhandled   = \"(unhandled)\"\n\tpercentBang = \"%!\"\n\tmissing     = \"(MISSING)\"\n\tbadIndex    = \"(BADINDEX)\"\n\textra       = \"%!(EXTRA \"\n\tbadWidth    = \"%!(BADWIDTH)\"\n\tbadPrec     = \"%!(BADPREC)\"\n\tnoVerb      = \"%!(NOVERB)\"\n)\n\n// printer holds the output and the state of the verb being printed.\ntype printer struct {\n\tbuf []byte\n\n\t// The flags, width and precision of the current verb.\n\tplus, minus, sharp, space, zero bool\n\tplusV, sharpV                   bool // %+v and %#v\n\twid, prec                       int\n\twidPresent, precPresent         bool\n\n\targ        any  // the operand being printed, for error messages\n\terroring   bool // printing an error message: do not call methods\n\treordered  bool // an explicit index was used\n\tgoodArgNum bool // the last index was valid\n\twrapErrs   bool // Errorf: %w is allowed\n\twrapped    []int\n}\n\nfunc newPrinter() *printer {\n\treturn \u0026printer{}\n}\n\n// Write implements State, so a Formatter can write.\nfunc (p *printer) Write(b []byte) (int, error) {\n\tp.buf = append(p.buf, b...)\n\treturn len(b), nil\n}\n\n// WriteString lets a Formatter write a string without a conversion.\nfunc (p *printer) WriteString(s string) (int, error) {\n\tp.buf = append(p.buf, s...)\n\treturn len(s), nil\n}\n\n// Width implements State.\nfunc (p *printer) Width() (int, bool) { return p.wid, p.widPresent }\n\n// Precision implements State.\nfunc (p *printer) Precision() (int, bool) { return p.prec, p.precPresent }\n\n// Flag implements State.\nfunc (p *printer) Flag(c int) bool {\n\tswitch c {\n\tcase '-':\n\t\treturn p.minus\n\tcase '+':\n\t\treturn p.plus || p.plusV\n\tcase '#':\n\t\treturn p.sharp || p.sharpV\n\tcase ' ':\n\t\treturn p.space\n\tcase '0':\n\t\treturn p.zero\n\t}\n\treturn false\n}\n\nfunc (p *printer) writeString(s string) { p.buf = append(p.buf, s...) }\nfunc (p *printer) writeByte(c byte)     { p.buf = append(p.buf, c) }\nfunc (p *printer) writeRune(r rune)     { p.buf = utf8.AppendRune(p.buf, r) }\n\n// doPrint is Sprint: %v, with a space between two operands neither of which is\n// a string.\nfunc (p *printer) doPrint(a []any) {\n\tprevString := false\n\tfor argNum, arg := range a {\n\t\t_, isString := arg.(string)\n\t\tif argNum \u003e 0 \u0026\u0026 !isString \u0026\u0026 !prevString {\n\t\t\tp.writeByte(' ')\n\t\t}\n\t\tp.printArg(arg, 'v')\n\t\tprevString = isString\n\t}\n}\n\n// doPrintln is Sprintln: %v, always a space between operands, then a newline.\nfunc (p *printer) doPrintln(a []any) {\n\tfor argNum, arg := range a {\n\t\tif argNum \u003e 0 {\n\t\t\tp.writeByte(' ')\n\t\t}\n\t\tp.printArg(arg, 'v')\n\t}\n\tp.writeByte('\\n')\n}\n\n// parsenum reads a decimal number at s[start:end].\nfunc parsenum(s string, start, end int) (num int, isnum bool, newi int) {\n\tif start \u003e= end {\n\t\treturn 0, false, end\n\t}\n\tfor newi = start; newi \u003c end \u0026\u0026 '0' \u003c= s[newi] \u0026\u0026 s[newi] \u003c= '9'; newi++ {\n\t\tif num \u003e 1e6 {\n\t\t\treturn 0, false, end // absurdly large: refuse rather than allocate\n\t\t}\n\t\tnum = num*10 + int(s[newi]-'0')\n\t\tisnum = true\n\t}\n\treturn\n}\n\n// intFromArg reads a * width or precision from a[argNum].\nfunc intFromArg(a []any, argNum int) (num int, isInt bool, newArgNum int) {\n\tnewArgNum = argNum\n\tif argNum \u003e= len(a) {\n\t\treturn\n\t}\n\tisInt = true\n\tswitch v := a[argNum].(type) {\n\tcase int:\n\t\tnum = v\n\tcase int8:\n\t\tnum = int(v)\n\tcase int16:\n\t\tnum = int(v)\n\tcase int32:\n\t\tnum = int(v)\n\tcase int64:\n\t\tnum = int(v)\n\tcase uint:\n\t\tnum = int(v)\n\tcase uint8:\n\t\tnum = int(v)\n\tcase uint16:\n\t\tnum = int(v)\n\tcase uint32:\n\t\tnum = int(v)\n\tcase uint64:\n\t\tnum = int(v)\n\tdefault:\n\t\tisInt = false\n\t}\n\tnewArgNum = argNum + 1\n\tif num \u003e 1e6 || num \u003c -1e6 {\n\t\tnum = 0\n\t\tisInt = false\n\t}\n\treturn\n}\n\n// argNumber reads an explicit index, \"[3]\", at format[i:].\nfunc (p *printer) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {\n\tif len(format) \u003c= i || format[i] != '[' {\n\t\treturn argNum, i, false\n\t}\n\tp.reordered = true\n\tfor j := 1; j \u003c len(format)-i; j++ {\n\t\tif format[i+j] == ']' {\n\t\t\twidth, ok, newi := parsenum(format, i+1, i+j)\n\t\t\tif !ok || newi != i+j {\n\t\t\t\tp.goodArgNum = false\n\t\t\t\treturn argNum, i + j + 1, true\n\t\t\t}\n\t\t\tindex := width - 1\n\t\t\tif index \u003e= 0 \u0026\u0026 index \u003c numArgs {\n\t\t\t\treturn index, i + j + 1, true\n\t\t\t}\n\t\t\tp.goodArgNum = false\n\t\t\treturn argNum, i + j + 1, true\n\t\t}\n\t}\n\tp.goodArgNum = false\n\treturn argNum, i + 1, false\n}\n\n// doPrintf is Sprintf.\nfunc (p *printer) doPrintf(format string, a []any) {\n\tend := len(format)\n\targNum := 0\n\tafterIndex := false // the previous item was an index like [3]\n\tp.reordered = false\n\n\tfor i := 0; i \u003c end; {\n\t\tp.goodArgNum = true\n\t\tlasti := i\n\t\tfor i \u003c end \u0026\u0026 format[i] != '%' {\n\t\t\ti++\n\t\t}\n\t\tif i \u003e lasti {\n\t\t\tp.writeString(format[lasti:i])\n\t\t}\n\t\tif i \u003e= end {\n\t\t\tbreak\n\t\t}\n\t\ti++ // skip '%'\n\n\t\tp.clearFlags()\n\n\t\t// Fast path: a bare lowercase verb, \"%d\" or \"%s\", is most of what any\n\t\t// realm prints, and skips the specifier parsing entirely.\n\t\tif i \u003c end \u0026\u0026 'a' \u003c= format[i] \u0026\u0026 format[i] \u003c= 'z' \u0026\u0026 argNum \u003c len(a) {\n\t\t\tverb := rune(format[i])\n\t\t\tif verb == 'w' {\n\t\t\t\tp.wrapped = append(p.wrapped, argNum)\n\t\t\t}\n\t\t\tp.printArg(a[argNum], verb)\n\t\t\targNum++\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\n\tflags:\n\t\tfor ; i \u003c end; i++ {\n\t\t\tswitch format[i] {\n\t\t\tcase '#':\n\t\t\t\tp.sharp = true\n\t\t\tcase '0':\n\t\t\t\tp.zero = !p.minus // zero padding only ever goes on the left\n\t\t\tcase '+':\n\t\t\t\tp.plus = true\n\t\t\tcase '-':\n\t\t\t\tp.minus = true\n\t\t\t\tp.zero = false\n\t\t\tcase ' ':\n\t\t\t\tp.space = true\n\t\t\tdefault:\n\t\t\t\tbreak flags\n\t\t\t}\n\t\t}\n\n\t\targNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))\n\n\t\t// Width.\n\t\tif i \u003c end \u0026\u0026 format[i] == '*' {\n\t\t\ti++\n\t\t\tp.wid, p.widPresent, argNum = intFromArg(a, argNum)\n\t\t\tif !p.widPresent {\n\t\t\t\tp.writeString(badWidth)\n\t\t\t}\n\t\t\tif p.wid \u003c 0 {\n\t\t\t\tp.wid = -p.wid\n\t\t\t\tp.minus = true\n\t\t\t\tp.zero = false\n\t\t\t}\n\t\t\tafterIndex = false\n\t\t} else {\n\t\t\tp.wid, p.widPresent, i = parsenum(format, i, end)\n\t\t\tif afterIndex \u0026\u0026 p.widPresent { // \"%[3]2d\"\n\t\t\t\tp.goodArgNum = false\n\t\t\t}\n\t\t}\n\n\t\t// Precision.\n\t\tif i+1 \u003c end \u0026\u0026 format[i] == '.' {\n\t\t\ti++\n\t\t\tif afterIndex { // \"%[3].2d\"\n\t\t\t\tp.goodArgNum = false\n\t\t\t}\n\t\t\targNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))\n\t\t\tif i \u003c end \u0026\u0026 format[i] == '*' {\n\t\t\t\ti++\n\t\t\t\tp.prec, p.precPresent, argNum = intFromArg(a, argNum)\n\t\t\t\tif p.prec \u003c 0 {\n\t\t\t\t\tp.prec = 0\n\t\t\t\t\tp.precPresent = false\n\t\t\t\t}\n\t\t\t\tif !p.precPresent {\n\t\t\t\t\tp.writeString(badPrec)\n\t\t\t\t}\n\t\t\t\tafterIndex = false\n\t\t\t} else {\n\t\t\t\tp.prec, p.precPresent, i = parsenum(format, i, end)\n\t\t\t\tif !p.precPresent {\n\t\t\t\t\tp.prec = 0\n\t\t\t\t\tp.precPresent = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !afterIndex {\n\t\t\targNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))\n\t\t}\n\n\t\tif i \u003e= end {\n\t\t\tp.writeString(noVerb)\n\t\t\tbreak\n\t\t}\n\n\t\tverb, size := rune(format[i]), 1\n\t\tif verb \u003e= utf8.RuneSelf {\n\t\t\tverb, size = utf8.DecodeRuneInString(format[i:])\n\t\t}\n\t\ti += size\n\n\t\tswitch {\n\t\tcase verb == '%': // takes no operand, ignores width and precision\n\t\t\tp.writeByte('%')\n\t\tcase !p.goodArgNum:\n\t\t\tp.badArgNum(verb)\n\t\tcase argNum \u003e= len(a):\n\t\t\tp.missingArg(verb)\n\t\tdefault:\n\t\t\tif verb == 'w' {\n\t\t\t\tp.wrapped = append(p.wrapped, argNum)\n\t\t\t}\n\t\t\tif verb == 'v' || verb == 'w' {\n\t\t\t\tp.sharpV, p.sharp = p.sharp, false\n\t\t\t\tp.plusV, p.plus = p.plus, false\n\t\t\t}\n\t\t\tp.printArg(a[argNum], verb)\n\t\t\targNum++\n\t\t}\n\t}\n\n\t// Report unused operands, unless an index made the count meaningless.\n\tif !p.reordered \u0026\u0026 argNum \u003c len(a) {\n\t\tp.clearFlags()\n\t\tp.writeString(extra)\n\t\tfor i, arg := range a[argNum:] {\n\t\t\tif i \u003e 0 {\n\t\t\t\tp.writeString(commaSpace)\n\t\t\t}\n\t\t\tif arg == nil {\n\t\t\t\tp.writeString(nilAngle)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tp.writeString(typeName(arg))\n\t\t\tp.writeByte('=')\n\t\t\tp.printArg(arg, 'v')\n\t\t}\n\t\tp.writeByte(')')\n\t}\n}\n\nfunc (p *printer) badArgNum(verb rune) {\n\tp.writeString(percentBang)\n\tp.writeRune(verb)\n\tp.writeString(badIndex)\n}\n\nfunc (p *printer) missingArg(verb rune) {\n\tp.writeString(percentBang)\n\tp.writeRune(verb)\n\tp.writeString(missing)\n}\n\n// badVerb writes \"%!d(string=hi)\": the verb, the operand's type and its value.\nfunc (p *printer) badVerb(verb rune) {\n\tp.erroring = true\n\tp.writeString(percentBang)\n\tp.writeRune(verb)\n\tp.writeByte('(')\n\tswitch {\n\tcase p.arg == nil:\n\t\tp.writeString(nilAngle)\n\tdefault:\n\t\tif t := typeName(p.arg); t != \"unknown\" {\n\t\t\tp.writeString(t)\n\t\t\tp.writeByte('=')\n\t\t\tp.printArg(p.arg, 'v')\n\t\t} else {\n\t\t\tp.writeString(\"unhandled\")\n\t\t}\n\t}\n\tp.writeByte(')')\n\tp.erroring = false\n}\n\n// printArg prints one operand.\nfunc (p *printer) printArg(arg any, verb rune) {\n\tp.arg = arg\n\n\tif arg == nil {\n\t\tswitch verb {\n\t\tcase 'T', 'v':\n\t\t\tp.padString(nilAngle)\n\t\tdefault:\n\t\t\tp.badVerb(verb)\n\t\t}\n\t\treturn\n\t}\n\n\tswitch verb {\n\tcase 'T':\n\t\tp.fmtS(typeName(arg))\n\t\treturn\n\tcase 'p':\n\t\tp.badVerb(verb)\n\t\treturn\n\t}\n\n\t// The basic types first, exactly as Go: a named type never matches these,\n\t// so its methods are still found below.\n\tswitch f := arg.(type) {\n\tcase bool:\n\t\tp.fmtBool(f, verb)\n\tcase float32:\n\t\tp.fmtFloatVerb(float64(f), 32, verb)\n\tcase float64:\n\t\tp.fmtFloatVerb(f, 64, verb)\n\tcase int:\n\t\tp.fmtSigned(int64(f), verb)\n\tcase int8:\n\t\tp.fmtSigned(int64(f), verb)\n\tcase int16:\n\t\tp.fmtSigned(int64(f), verb)\n\tcase int32:\n\t\tp.fmtSigned(int64(f), verb)\n\tcase int64:\n\t\tp.fmtSigned(f, verb)\n\tcase uint:\n\t\tp.fmtUnsigned(uint64(f), verb)\n\tcase uint8:\n\t\tp.fmtUnsigned(uint64(f), verb)\n\tcase uint16:\n\t\tp.fmtUnsigned(uint64(f), verb)\n\tcase uint32:\n\t\tp.fmtUnsigned(uint64(f), verb)\n\tcase uint64:\n\t\tp.fmtUnsigned(f, verb)\n\tcase string:\n\t\tp.fmtString(f, verb)\n\tcase []byte:\n\t\tp.fmtBytes(f, verb)\n\tdefault:\n\t\tif !p.handleMethods(verb) {\n\t\t\tp.printComposite(arg, verb)\n\t\t}\n\t}\n}\n\n// handleMethods prints arg with its own Format, GoString, Error or String\n// method, in Go's order, and reports whether it did.\nfunc (p *printer) handleMethods(verb rune) (handled bool) {\n\tif p.erroring {\n\t\treturn false\n\t}\n\tif verb == 'w' {\n\t\t// %w is for Errorf, and for an error.\n\t\tif _, ok := p.arg.(error); !ok || !p.wrapErrs {\n\t\t\tp.badVerb(verb)\n\t\t\treturn true\n\t\t}\n\t\tverb = 'v'\n\t}\n\n\tif f, ok := p.arg.(Formatter); ok {\n\t\thandled = true // stays true if the method panics\n\t\tdefer p.catchPanic(p.arg, verb, \"Format\")\n\t\tf.Format(p, verb)\n\t\treturn\n\t}\n\n\tif p.sharpV {\n\t\tif g, ok := p.arg.(GoStringer); ok {\n\t\t\thandled = true\n\t\t\tdefer p.catchPanic(p.arg, verb, \"GoString\")\n\t\t\tp.fmtS(g.GoString())\n\t\t\treturn\n\t\t}\n\t\treturn false\n\t}\n\n\tswitch verb {\n\tcase 'v', 's', 'x', 'X', 'q':\n\t\tswitch v := p.arg.(type) {\n\t\tcase error:\n\t\t\thandled = true\n\t\t\tdefer p.catchPanic(p.arg, verb, \"Error\")\n\t\t\tp.fmtString(v.Error(), verb)\n\t\t\treturn\n\t\tcase Stringer:\n\t\t\thandled = true\n\t\t\tdefer p.catchPanic(p.arg, verb, \"String\")\n\t\t\tp.fmtString(v.String(), verb)\n\t\t\treturn\n\t\t}\n\t}\n\treturn false\n}\n\n// catchPanic turns a panicking method into \"%!v(PANIC=String method: msg)\".\nfunc (p *printer) catchPanic(arg any, verb rune, method string) {\n\tr := recover()\n\tif r == nil {\n\t\treturn\n\t}\n\tif p.erroring {\n\t\tpanic(r) // the method panicked again while printing its own panic\n\t}\n\tp.clearFlags()\n\tp.writeString(percentBang)\n\tp.writeRune(verb)\n\tp.writeString(\"(PANIC=\")\n\tp.writeString(method)\n\tp.writeString(\" method: \")\n\tp.erroring = true\n\tp.printArg(r, 'v')\n\tp.erroring = false\n\tp.writeByte(')')\n}\n\nfunc (p *printer) fmtBool(v bool, verb rune) {\n\tswitch verb {\n\tcase 't', 'v':\n\t\tp.fmtBoolean(v)\n\tdefault:\n\t\tp.badVerb(verb)\n\t}\n}\n\n// fmtSigned prints a signed integer. The magnitude of math.MinInt64 does not\n// fit an int64, so it is computed without ever negating v itself.\nfunc (p *printer) fmtSigned(v int64, verb rune) {\n\tif v \u003e= 0 {\n\t\tp.fmtIntegerVerb(uint64(v), false, true, verb)\n\t\treturn\n\t}\n\tmag := uint64(-(v + 1)) + 1\n\tp.fmtIntegerVerb(mag, true, true, verb)\n}\n\nfunc (p *printer) fmtUnsigned(u uint64, verb rune) {\n\tp.fmtIntegerVerb(u, false, false, verb)\n}\n\nfunc (p *printer) fmtIntegerVerb(u uint64, negative, isSigned bool, verb rune) {\n\tswitch verb {\n\tcase 'v':\n\t\tif p.sharpV \u0026\u0026 !isSigned {\n\t\t\tp.fmt0x64(u, true)\n\t\t} else {\n\t\t\tp.fmtInteger(u, negative, 10, verb, ldigits)\n\t\t}\n\tcase 'd':\n\t\tp.fmtInteger(u, negative, 10, verb, ldigits)\n\tcase 'b':\n\t\tp.fmtInteger(u, negative, 2, verb, ldigits)\n\tcase 'o', 'O':\n\t\tp.fmtInteger(u, negative, 8, verb, ldigits)\n\tcase 'x':\n\t\tp.fmtInteger(u, negative, 16, verb, ldigits)\n\tcase 'X':\n\t\tp.fmtInteger(u, negative, 16, verb, udigits)\n\tcase 'c', 'q', 'U':\n\t\tif negative {\n\t\t\tu = ^u + 1 // back to two's complement, as Go sees it: never a rune\n\t\t}\n\t\tswitch verb {\n\t\tcase 'c':\n\t\t\tp.fmtC(u)\n\t\tcase 'q':\n\t\t\tp.fmtQc(u)\n\t\tdefault:\n\t\t\tp.fmtUnicode(u)\n\t\t}\n\tdefault:\n\t\tp.badVerb(verb)\n\t}\n}\n\n// fmt0x64 prints u in hex with a 0x prefix (leading0x) or without one.\nfunc (p *printer) fmt0x64(u uint64, leading0x bool) {\n\tsharp := p.sharp\n\tp.sharp = leading0x\n\tp.fmtInteger(u, false, 16, 'v', ldigits)\n\tp.sharp = sharp\n}\n\nfunc (p *printer) fmtFloatVerb(v float64, size int, verb rune) {\n\tswitch verb {\n\tcase 'v':\n\t\tp.fmtFloat(v, size, 'g', -1)\n\tcase 'b', 'g', 'G', 'x', 'X':\n\t\tp.fmtFloat(v, size, verb, -1)\n\tcase 'f', 'e', 'E':\n\t\tp.fmtFloat(v, size, verb, 6)\n\tcase 'F':\n\t\tp.fmtFloat(v, size, 'f', 6)\n\tdefault:\n\t\tp.badVerb(verb)\n\t}\n}\n\nfunc (p *printer) fmtString(v string, verb rune) {\n\tswitch verb {\n\tcase 'v':\n\t\tif p.sharpV {\n\t\t\tp.fmtQ(v)\n\t\t} else {\n\t\t\tp.fmtS(v)\n\t\t}\n\tcase 's':\n\t\tp.fmtS(v)\n\tcase 'x':\n\t\tp.fmtSx(v, ldigits)\n\tcase 'X':\n\t\tp.fmtSx(v, udigits)\n\tcase 'q':\n\t\tp.fmtQ(v)\n\tdefault:\n\t\tp.badVerb(verb)\n\t}\n}\n\nfunc (p *printer) fmtBytes(v []byte, verb rune) {\n\tswitch verb {\n\tcase 'v', 'd':\n\t\tif p.sharpV {\n\t\t\tp.writeString(\"[]byte\")\n\t\t\tif v == nil {\n\t\t\t\tp.writeString(nilParen)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tp.writeByte('{')\n\t\t\tfor i, c := range v {\n\t\t\t\tif i \u003e 0 {\n\t\t\t\t\tp.writeString(commaSpace)\n\t\t\t\t}\n\t\t\t\tp.fmt0x64(uint64(c), true)\n\t\t\t}\n\t\t\tp.writeByte('}')\n\t\t\treturn\n\t\t}\n\t\tp.writeByte('[')\n\t\tfor i, c := range v {\n\t\t\tif i \u003e 0 {\n\t\t\t\tp.writeByte(' ')\n\t\t\t}\n\t\t\tp.fmtInteger(uint64(c), false, 10, verb, ldigits)\n\t\t}\n\t\tp.writeByte(']')\n\tcase 's':\n\t\tp.fmtS(string(v))\n\tcase 'x':\n\t\tp.fmtSx(string(v), ldigits)\n\tcase 'X':\n\t\tp.fmtSx(string(v), udigits)\n\tcase 'q':\n\t\tp.fmtQ(string(v))\n\tdefault:\n\t\t// Every other verb applies to each byte, as for any slice.\n\t\tp.writeByte('[')\n\t\tfor i, c := range v {\n\t\t\tif i \u003e 0 {\n\t\t\t\tp.writeByte(' ')\n\t\t\t}\n\t\t\tp.fmtUnsigned(uint64(c), verb)\n\t\t}\n\t\tp.writeByte(']')\n\t}\n}\n\n// printComposite prints the slices and maps gno can see without reflect.\nfunc (p *printer) printComposite(arg any, verb rune) {\n\tswitch v := arg.(type) {\n\tcase []any:\n\t\tp.printSlice(\"[]interface {}\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []string:\n\t\tp.printSlice(\"[]string\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []error:\n\t\tp.printSlice(\"[]error\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []bool:\n\t\tp.printSlice(\"[]bool\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []int:\n\t\tp.printSlice(\"[]int\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []int8:\n\t\tp.printSlice(\"[]int8\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []int16:\n\t\tp.printSlice(\"[]int16\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []int32:\n\t\tp.printSlice(\"[]int32\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []int64:\n\t\tp.printSlice(\"[]int64\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []uint:\n\t\tp.printSlice(\"[]uint\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []uint16:\n\t\tp.printSlice(\"[]uint16\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []uint32:\n\t\tp.printSlice(\"[]uint32\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []uint64:\n\t\tp.printSlice(\"[]uint64\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []float32:\n\t\tp.printSlice(\"[]float32\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase []float64:\n\t\tp.printSlice(\"[]float64\", v == nil, len(v), func(i int) any { return v[i] }, verb)\n\tcase map[string]string:\n\t\tkeys := sortedKeys(len(v), func(add func(string)) {\n\t\t\tfor k := range v {\n\t\t\t\tadd(k)\n\t\t\t}\n\t\t})\n\t\tp.printMap(\"map[string]string\", v == nil, keys, func(k string) any { return v[k] }, verb)\n\tcase map[string]any:\n\t\tkeys := sortedKeys(len(v), func(add func(string)) {\n\t\t\tfor k := range v {\n\t\t\t\tadd(k)\n\t\t\t}\n\t\t})\n\t\tp.printMap(\"map[string]interface {}\", v == nil, keys, func(k string) any { return v[k] }, verb)\n\tcase map[string]int:\n\t\tkeys := sortedKeys(len(v), func(add func(string)) {\n\t\t\tfor k := range v {\n\t\t\t\tadd(k)\n\t\t\t}\n\t\t})\n\t\tp.printMap(\"map[string]int\", v == nil, keys, func(k string) any { return v[k] }, verb)\n\tcase map[string]bool:\n\t\tkeys := sortedKeys(len(v), func(add func(string)) {\n\t\t\tfor k := range v {\n\t\t\t\tadd(k)\n\t\t\t}\n\t\t})\n\t\tp.printMap(\"map[string]bool\", v == nil, keys, func(k string) any { return v[k] }, verb)\n\tdefault:\n\t\tif verb == 'v' {\n\t\t\tp.padString(unhandled)\n\t\t} else {\n\t\t\tp.badVerb(verb)\n\t\t}\n\t}\n}\n\n// printSlice prints \"[a b]\", or \"[]T{a, b}\" for %#v, each element with verb.\nfunc (p *printer) printSlice(typ string, isNil bool, n int, at func(int) any, verb rune) {\n\tif p.sharpV {\n\t\tp.writeString(typ)\n\t\tif isNil {\n\t\t\tp.writeString(nilParen)\n\t\t\treturn\n\t\t}\n\t\tp.writeByte('{')\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\tif i \u003e 0 {\n\t\t\t\tp.writeString(commaSpace)\n\t\t\t}\n\t\t\tp.printElem(at(i), verb)\n\t\t}\n\t\tp.writeByte('}')\n\t\treturn\n\t}\n\tp.writeByte('[')\n\tfor i := 0; i \u003c n; i++ {\n\t\tif i \u003e 0 {\n\t\t\tp.writeByte(' ')\n\t\t}\n\t\tp.printElem(at(i), verb)\n\t}\n\tp.writeByte(']')\n}\n\n// printMap prints \"map[a:1 b:2]\", or \"map[string]int{\"a\":1, \"b\":2}\" for %#v,\n// keys sorted as Go sorts them.\nfunc (p *printer) printMap(typ string, isNil bool, keys []string, at func(string) any, verb rune) {\n\tif p.sharpV {\n\t\tp.writeString(typ)\n\t\tif isNil {\n\t\t\tp.writeString(nilParen)\n\t\t\treturn\n\t\t}\n\t\tp.writeByte('{')\n\t} else {\n\t\tp.writeString(\"map[\")\n\t}\n\tfor i, k := range keys {\n\t\tif i \u003e 0 {\n\t\t\tif p.sharpV {\n\t\t\t\tp.writeString(commaSpace)\n\t\t\t} else {\n\t\t\t\tp.writeByte(' ')\n\t\t\t}\n\t\t}\n\t\tp.printElem(k, verb)\n\t\tp.writeByte(':')\n\t\tp.printElem(at(k), verb)\n\t}\n\tif p.sharpV {\n\t\tp.writeByte('}')\n\t} else {\n\t\tp.writeByte(']')\n\t}\n}\n\n// printElem prints one element of a composite, keeping the outer operand for\n// error messages. A nil element prints \"\u003cnil\u003e\" whatever the verb, as in Go.\nfunc (p *printer) printElem(v any, verb rune) {\n\touter := p.arg\n\tif v == nil {\n\t\tif p.sharpV {\n\t\t\tp.writeString(\"interface {}(nil)\")\n\t\t} else {\n\t\t\tp.padString(nilAngle)\n\t\t}\n\t} else {\n\t\tp.printArg(v, verb)\n\t}\n\tp.arg = outer\n}\n\nfunc sortedKeys(n int, each func(add func(string))) []string {\n\tkeys := make([]string, 0, n)\n\teach(func(k string) { keys = append(keys, k) })\n\tsort.Strings(keys)\n\treturn keys\n}\n\n// typeName is %T for the types gno can name without reflect.\nfunc typeName(v any) string {\n\tswitch v.(type) {\n\tcase bool:\n\t\treturn \"bool\"\n\tcase int:\n\t\treturn \"int\"\n\tcase int8:\n\t\treturn \"int8\"\n\tcase int16:\n\t\treturn \"int16\"\n\tcase int32:\n\t\treturn \"int32\"\n\tcase int64:\n\t\treturn \"int64\"\n\tcase uint:\n\t\treturn \"uint\"\n\tcase uint8:\n\t\treturn \"uint8\"\n\tcase uint16:\n\t\treturn \"uint16\"\n\tcase uint32:\n\t\treturn \"uint32\"\n\tcase uint64:\n\t\treturn \"uint64\"\n\tcase float32:\n\t\treturn \"float32\"\n\tcase float64:\n\t\treturn \"float64\"\n\tcase string:\n\t\treturn \"string\"\n\tcase []byte:\n\t\treturn \"[]uint8\"\n\tcase []any:\n\t\treturn \"[]interface {}\"\n\tcase []string:\n\t\treturn \"[]string\"\n\tcase []error:\n\t\treturn \"[]error\"\n\tcase []bool:\n\t\treturn \"[]bool\"\n\tcase []int:\n\t\treturn \"[]int\"\n\tcase []int8:\n\t\treturn \"[]int8\"\n\tcase []int16:\n\t\treturn \"[]int16\"\n\tcase []int32:\n\t\treturn \"[]int32\"\n\tcase []int64:\n\t\treturn \"[]int64\"\n\tcase []uint:\n\t\treturn \"[]uint\"\n\tcase []uint16:\n\t\treturn \"[]uint16\"\n\tcase []uint32:\n\t\treturn \"[]uint32\"\n\tcase []uint64:\n\t\treturn \"[]uint64\"\n\tcase []float32:\n\t\treturn \"[]float32\"\n\tcase []float64:\n\t\treturn \"[]float64\"\n\tcase map[string]string:\n\t\treturn \"map[string]string\"\n\tcase map[string]any:\n\t\treturn \"map[string]interface {}\"\n\tcase map[string]int:\n\t\treturn \"map[string]int\"\n\tcase map[string]bool:\n\t\treturn \"map[string]bool\"\n\t}\n\treturn \"unknown\"\n}\n"},{"name":"ufmt.gno","body":"package ufmt\n\nimport (\n\t\"io\"\n\t\"strings\"\n)\n\n// State is what a Formatter's Format method is handed: the flags, width and\n// precision of the verb being printed, and somewhere to write.\ntype State interface {\n\t// Write emits formatted output.\n\tWrite(b []byte) (n int, err error)\n\t// Width returns the width and whether one was set.\n\tWidth() (wid int, ok bool)\n\t// Precision returns the precision and whether one was set.\n\tPrecision() (prec int, ok bool)\n\t// Flag reports whether the flag c, a character, was set.\n\tFlag(c int) bool\n}\n\n// Formatter is implemented by a value that formats itself. Format is called\n// for every verb, and its output replaces what ufmt would have printed.\ntype Formatter interface {\n\tFormat(f State, verb rune)\n}\n\n// Stringer is implemented by a value that has a natural string form. It is\n// used for %v, %s, %q, %x and %X, and by Print.\ntype Stringer interface {\n\tString() string\n}\n\n// GoStringer is implemented by a value that has a Go-syntax form, used for %#v.\ntype GoStringer interface {\n\tGoString() string\n}\n\n// Sprintf formats according to a format specifier and returns the string.\nfunc Sprintf(format string, a ...any) string {\n\tp := newPrinter()\n\tp.doPrintf(format, a)\n\treturn string(p.buf)\n}\n\n// Appendf formats according to a format specifier and appends the result to b.\nfunc Appendf(b []byte, format string, a ...any) []byte {\n\tp := newPrinter()\n\tp.doPrintf(format, a)\n\treturn append(b, p.buf...)\n}\n\n// Fprintf formats according to a format specifier and writes to w.\nfunc Fprintf(w io.Writer, format string, a ...any) (n int, err error) {\n\tp := newPrinter()\n\tp.doPrintf(format, a)\n\treturn w.Write(p.buf)\n}\n\n// Printf formats according to a format specifier and prints the result with\n// the print builtin, which is what a test or a filetest captures.\nfunc Printf(format string, a ...any) (n int, err error) {\n\treturn printOut(Sprintf(format, a...))\n}\n\n// Sprint formats its operands with %v and returns the string. A space is added\n// between two operands when neither is a string.\nfunc Sprint(a ...any) string {\n\tp := newPrinter()\n\tp.doPrint(a)\n\treturn string(p.buf)\n}\n\n// Append formats its operands as Sprint does and appends the result to b.\nfunc Append(b []byte, a ...any) []byte {\n\tp := newPrinter()\n\tp.doPrint(a)\n\treturn append(b, p.buf...)\n}\n\n// Fprint formats its operands as Sprint does and writes to w.\nfunc Fprint(w io.Writer, a ...any) (n int, err error) {\n\tp := newPrinter()\n\tp.doPrint(a)\n\treturn w.Write(p.buf)\n}\n\n// Print formats its operands as Sprint does and prints the result.\nfunc Print(a ...any) (n int, err error) {\n\treturn printOut(Sprint(a...))\n}\n\n// Sprintln formats its operands with %v, always separated by a space, and\n// appends a newline.\nfunc Sprintln(a ...any) string {\n\tp := newPrinter()\n\tp.doPrintln(a)\n\treturn string(p.buf)\n}\n\n// Appendln formats its operands as Sprintln does and appends the result to b.\nfunc Appendln(b []byte, a ...any) []byte {\n\tp := newPrinter()\n\tp.doPrintln(a)\n\treturn append(b, p.buf...)\n}\n\n// Fprintln formats its operands as Sprintln does and writes to w.\nfunc Fprintln(w io.Writer, a ...any) (n int, err error) {\n\tp := newPrinter()\n\tp.doPrintln(a)\n\treturn w.Write(p.buf)\n}\n\n// Println formats its operands as Sprintln does and prints the result.\nfunc Println(a ...any) (n int, err error) {\n\treturn printOut(Sprintln(a...))\n}\n\nfunc printOut(s string) (int, error) {\n\tvar sb strings.Builder\n\tn, err := sb.WriteString(s)\n\tprint(sb.String())\n\treturn n, err\n}\n\n// Errorf formats according to a format specifier and returns the string as an\n// error. Each %w operand must be an error; it is printed as %v and returned by\n// the error's Unwrap method, so errors.Is and errors.Unwrap can find it. One %w\n// gives an Unwrap() error, several give an Unwrap() []error, as in Go.\nfunc Errorf(format string, a ...any) error {\n\tp := newPrinter()\n\tp.wrapErrs = true\n\tp.doPrintf(format, a)\n\ts := string(p.buf)\n\n\tswitch len(p.wrapped) {\n\tcase 0:\n\t\treturn \u0026errorString{s}\n\tcase 1:\n\t\tw := \u0026wrapError{msg: s}\n\t\tw.err, _ = a[p.wrapped[0]].(error)\n\t\treturn w\n\tdefault:\n\t\tif p.reordered {\n\t\t\tsortInts(p.wrapped)\n\t\t}\n\t\tvar errs []error\n\t\tfor i, argNum := range p.wrapped {\n\t\t\tif i \u003e 0 \u0026\u0026 p.wrapped[i-1] == argNum {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif e, ok := a[argNum].(error); ok {\n\t\t\t\terrs = append(errs, e)\n\t\t\t}\n\t\t}\n\t\treturn \u0026wrapErrors{s, errs}\n\t}\n}\n\ntype errorString struct {\n\ts string\n}\n\nfunc (e *errorString) Error() string { return e.s }\n\ntype wrapError struct {\n\tmsg string\n\terr error\n}\n\nfunc (e *wrapError) Error() string { return e.msg }\nfunc (e *wrapError) Unwrap() error { return e.err }\n\ntype wrapErrors struct {\n\tmsg  string\n\terrs []error\n}\n\nfunc (e *wrapErrors) Error() string   { return e.msg }\nfunc (e *wrapErrors) Unwrap() []error { return e.errs }\n\n// sortInts is an insertion sort: the slice holds one entry per %w.\nfunc sortInts(a []int) {\n\tfor i := 1; i \u003c len(a); i++ {\n\t\tfor j := i; j \u003e 0 \u0026\u0026 a[j] \u003c a[j-1]; j-- {\n\t\t\ta[j], a[j-1] = a[j-1], a[j]\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"21000000ugnot"}],"fee":{"gas_wanted":"144610400","gas_fee":"433831ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"fQrs3ZftzHgiapHQVPUHZ5uGAwLXOc9ppqDfWbLce7EkQ4lv53OIP3R4zNEB+Zbe5cDwNsyMP+elHckBi0W0rQ=="}],"memo":""},"metadata":{"timestamp":"1791206388"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"riscvdemo","path":"gno.land/r/moul/x/vm/riscvdemo/v0","files":[{"name":"README.md","body":"# r/moul/x/vm/riscvdemo\n\nDemo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0), the RV32IM hart, and\n[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0), the host ABI. This realm holds no\nlogic of its own: it stores images, builds a `vmkit.Host`, and renders.\n\nWhat it exists to show is two things realm code cannot do for itself.\n\n**The guest was not written for gno.** The programs on the front page are flat\n`.text` images, the bytes a cross compiler emits for\n`riscv32im-unknown-none-elf`. `Upload` takes hex, so anything you can build with\n`clang`, `rustc`, TinyGo or Zig and strip to its text segment goes in unchanged.\n\nTwo samples are exactly that and neither is a mock up. **Compiled by clang** is\na freestanding C program; **A token, in Rust** is `#![no_std]` Rust that mints,\nsends and burns, linking Rust's real `core` and `compiler_builtins`, so a\n64-bit divide in it runs `__udivdi3` on a machine with no 64-bit divide\ninstruction. Both are shipped as the bytes the compiler emitted, and the page\nshows their source rather than a disassembly, because a disassembly would bury\nthe only interesting fact: nobody wrote the machine code. Sources and build\ncommands: `tools/riscv-guests`.\n\n**A program pauses instead of failing.** It runs until its fuel slice is spent,\nthen stops with a snapshot the realm keeps, and the next caller pays for the\nnext slice. The \"Heavy loop\" sample is 200,006 instructions and takes three\ntransactions at the default slice, which is the whole point.\n\n```\nUploadSample(\"heavy\", \"\", 0)   -\u003e id\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"halted\"\n```\n\n## Reading the instance page\n\nA guest that writes nothing has still computed something, so the instance page\nrestores the snapshot and shows the register file under its ABI names. That is\nthe only place the state is legible: the hart itself does not survive the\ntransaction, only its snapshot does.\n\n## What a slice costs\n\nAn RV32IM instruction costs about **8,500 gas**, measured rather than estimated,\nso a block buys roughly **350,000 guest instructions**. Loading the image costs\nabout **19,600 gas per instruction word** and is paid again on every resume,\nwhich is why `MaxImage` is 8 KiB and not a megabyte. The measurements and how\nthey were taken are in the [library README](/p/moul/x/vm/riscv/v0).\n\n## What this realm does not grant\n\n`Send` always returns `vmkit.ErrNotGranted`. No instance here is funded, so a\nguest that tries to move coins is refused, and that is the capability rule\nworking rather than a missing feature. Guest key-value storage is scoped to the\ninstance being stepped by construction: the tree belongs to the instance, so one\nprogram cannot reach another's even though both live in this realm.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/vm/riscvdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/vm/riscvdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/vm/riscvdemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/moul/vendor/nt/ufmt/v2\"\n)\n\n// regNames are the ABI names, because nobody reading a register dump thinks in\n// x-numbers and every compiler's output is annotated with these.\nvar regNames = [32]string{\n\t\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\t\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\t\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\t\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\",\n}\n\n// Render is the realm's gnoweb view.\n//\n//   - \"/\"      the samples, the instance list, and what the numbers mean.\n//   - \"/\u003cid\u003e\"  one instance: its status, fuel, output and register file.\nfunc Render(path string) string {\n\tid := strings.TrimSpace(strings.TrimPrefix(path, \"/\"))\n\tif id == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderInstance(id)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# RV32IM, on chain, a slice at a time\\n\\n\")\n\tsb.WriteString(\"Demo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0) (the hart) and \")\n\tsb.WriteString(\"[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, \")\n\tsb.WriteString(\"the instance store). This realm holds no logic of its own.\\n\\n\")\n\tsb.WriteString(\"The programs below are flat `.text` images: the same bytes a cross compiler \")\n\tsb.WriteString(\"emits for `riscv32im-unknown-none-elf`. Nothing here was written in a \")\n\tsb.WriteString(\"chain language, and nothing translated it.\\n\\n\")\n\tsb.WriteString(\"A program does not run to completion. It runs until its fuel slice is spent, \")\n\tsb.WriteString(\"then pauses: the realm keeps the snapshot and the next caller pays for the \")\n\tsb.WriteString(\"next slice. Realm code cannot pause itself, and a guest can.\\n\\n\")\n\n\tsb.WriteString(\"## Samples\\n\\n\")\n\tfor i := range samples {\n\t\ts := \u0026samples[i]\n\t\tsb.WriteString(\"**\" + ui.Inline(s.name) + \"**: \" + s.note + \"\\n\\n\")\n\t\tsb.WriteString(\"```\" + s.lang() + \"\\n\" + s.asm + \"\\n```\\n\\n\")\n\t\tsb.WriteString(ui.Action(\"Upload \"+s.name, \"UploadSample\",\n\t\t\t\"name\", s.slug, \"input\", s.input,\n\t\t\t\"budget\", ufmt.Sprintf(\"%d\", s.budget)) + \"\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Instances\\n\\n\")\n\tt := ui.NewTable(\"id\", \"status\", \"instructions\", \"slices\", \"output\")\n\tstore.ReverseIterate(func(i *vmkit.Instance) bool {\n\t\tt.Row(\n\t\t\t\"[\"+i.ID+\"](/r/moul/x/vm/riscvdemo/v0:\"+i.ID+\")\",\n\t\t\ti.Status.String(),\n\t\t\tufmt.Sprintf(\"%d\", i.FuelUsed),\n\t\t\tufmt.Sprintf(\"%d\", i.Slices),\n\t\t\t\"`\"+ui.Cell(printable(i.Output, 24))+\"`\",\n\t\t)\n\t\treturn false\n\t})\n\tsb.WriteString(t.OrEmpty(\"No instances yet. Upload one of the samples above.\"))\n\tsb.WriteString(\"\\n\\n\")\n\n\tsb.WriteString(\"## What a slice costs\\n\\n\")\n\tsb.WriteString(\"An RV32IM instruction costs about **8,500 gas** here, measured rather than \")\n\tsb.WriteString(\"estimated, so a block buys roughly **350,000 guest instructions**. Loading \")\n\tsb.WriteString(\"the image costs about **19,600 gas per instruction word** and is paid again \")\n\tsb.WriteString(\"on every resume, which is why the image cap below is small. The numbers and \")\n\tsb.WriteString(\"how they were taken are in the [library README](/p/moul/x/vm/riscv/v0).\\n\\n\")\n\n\tsb.WriteString(\"## Limits\\n\\n\")\n\tlt := ui.NewTable(\"limit\", \"value\")\n\tlt.Row(\"instances\", ufmt.Sprintf(\"%d\", MaxInstances))\n\tlt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", MaxImage))\n\tlt.Row(\"input bytes\", ufmt.Sprintf(\"%d\", MaxInput))\n\tlt.Row(\"output bytes\", ufmt.Sprintf(\"%d\", MaxOutput))\n\tlt.Row(\"instructions per slice\", ufmt.Sprintf(\"%d\", MaxSliceFuel))\n\tlt.Row(\"address space\", ufmt.Sprintf(\"%d\", riscv.MemSize))\n\tsb.WriteString(lt.String())\n\treturn sb.String()\n}\n\nfunc renderInstance(id string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Instance \" + ui.Inline(id) + \"\\n\\n\")\n\tsb.WriteString(\"[← all instances](/r/moul/x/vm/riscvdemo/v0)\\n\\n\")\n\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tsb.WriteString(\"**No such instance.** It was never uploaded, or its owner removed it.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tt := ui.NewTable(\"field\", \"value\")\n\tt.Row(\"owner\", ui.Addr(inst.Owner))\n\tt.Row(\"vm\", ui.Cell(inst.VM))\n\tt.Row(\"status\", inst.Status.String())\n\tif inst.Trap != \"\" {\n\t\tt.Row(\"trap\", ui.Cell(inst.Trap))\n\t}\n\tt.Row(\"instructions run\", ufmt.Sprintf(\"%d\", inst.FuelUsed))\n\tt.Row(\"budget\", fuelText(inst.FuelBudget))\n\tt.Row(\"slices\", ufmt.Sprintf(\"%d\", inst.Slices))\n\tt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", len(inst.Program)))\n\tt.Row(\"image words\", ufmt.Sprintf(\"%d\", len(inst.Program)/4))\n\tt.Row(\"snapshot bytes\", ufmt.Sprintf(\"%d\", len(inst.Snapshot)))\n\tsb.WriteString(t.String())\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Registers\\n\\n\")\n\tsb.WriteString(renderRegisters(inst))\n\n\tsb.WriteString(\"## Output\\n\\n\")\n\tif len(inst.Output) == 0 {\n\t\tsb.WriteString(ui.Empty(\"Nothing written yet.\"))\n\t} else {\n\t\tsb.WriteString(\"```\\n\" + printable(inst.Output, MaxOutput) + \"\\n```\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Image\\n\\n```\\n\" + hexDump(inst.Program, 64) + \"\\n```\\n\\n\")\n\n\tif inst.Status == vmkit.Running {\n\t\tsb.WriteString(ui.Action(\"Run 25000 instructions\", \"Step\", \"id\", id, \"fuel\", \"25000\"))\n\t\tsb.WriteString(\" · \")\n\t\tsb.WriteString(ui.Action(\"Run 100000 instructions\", \"Step\", \"id\", id, \"fuel\", \"100000\"))\n\t\tsb.WriteString(\"\\n\")\n\t} else {\n\t\tsb.WriteString(\"This instance is **\" + inst.Status.String() + \"** and cannot be stepped again.\\n\")\n\t}\n\treturn sb.String()\n}\n\n// renderRegisters restores the snapshot to read the register file out of it.\n// The hart is not kept between transactions, only its snapshot is, so this is\n// the only place the state is legible, and it is the thing worth seeing: a\n// program that wrote nothing still computed something.\nfunc renderRegisters(inst *vmkit.Instance) string {\n\tif len(inst.Snapshot) == 0 {\n\t\treturn ui.Empty(\"Not started yet: no snapshot to read.\") + \"\\n\\n\"\n\t}\n\tvar m riscv.Machine\n\tif err := m.Restore(inst.Snapshot); err != nil {\n\t\treturn ui.Empty(\"The snapshot could not be read.\") + \"\\n\\n\"\n\t}\n\treg := m.Registers()\n\n\tvar sb strings.Builder\n\tt := ui.NewTable(\"register\", \"hex\", \"unsigned\", \"signed\")\n\tt.Row(\"pc\", ufmt.Sprintf(\"0x%08X\", m.PC()), \"\", \"\")\n\tshown := 0\n\tfor i := 1; i \u003c 32; i++ {\n\t\tif reg[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt.Row(\n\t\t\tregNames[i],\n\t\t\tufmt.Sprintf(\"0x%08X\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", int64(int32(reg[i]))),\n\t\t)\n\t\tshown++\n\t}\n\tsb.WriteString(t.String())\n\tif shown == 0 {\n\t\tsb.WriteString(\"\\nEvery register except `pc` is zero.\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\treturn sb.String()\n}\n\nfunc fuelText(n int64) string {\n\tif n == vmkit.Unmetered {\n\t\treturn \"unmetered\"\n\t}\n\treturn ufmt.Sprintf(\"%d\", n)\n}\n\nconst hexDigits = \"0123456789abcdef\"\n\n// hexDump shows the image as words, which is how anyone reading RV32 reads it.\nfunc hexDump(b []byte, max int) string {\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor i := 0; i+3 \u003c len(b); i += 4 {\n\t\tif i \u003e 0 \u0026\u0026 i%16 == 0 {\n\t\t\tsb.WriteString(\"\\n\")\n\t\t} else if i \u003e 0 {\n\t\t\tsb.WriteString(\" \")\n\t\t}\n\t\tw := uint32(b[i]) | uint32(b[i+1])\u003c\u003c8 | uint32(b[i+2])\u003c\u003c16 | uint32(b[i+3])\u003c\u003c24\n\t\tsb.WriteString(ufmt.Sprintf(\"%08x\", w))\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"\\n...\")\n\t}\n\treturn sb.String()\n}\n\n// printable renders guest output for a code fence: printable ASCII as itself,\n// everything else as an escape. A guest writes arbitrary bytes, so this is the\n// only form of it that is safe to show.\nfunc printable(b []byte, max int) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor _, c := range b {\n\t\tswitch {\n\t\tcase c == '\\n':\n\t\t\tsb.WriteString(\"\\\\n\")\n\t\tcase c == '\\t':\n\t\t\tsb.WriteString(\"\\\\t\")\n\t\tcase c == '\\\\':\n\t\t\tsb.WriteString(\"\\\\\\\\\")\n\t\tcase c == '`':\n\t\t\tsb.WriteString(\"\\\\x60\")\n\t\tcase c \u003e= 0x20 \u0026\u0026 c \u003c 0x7f:\n\t\t\tsb.WriteByte(c)\n\t\tdefault:\n\t\t\tsb.WriteString(\"\\\\x\")\n\t\t\tsb.WriteByte(hexDigits[c\u003e\u003e4])\n\t\t\tsb.WriteByte(hexDigits[c\u00260x0f])\n\t\t}\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"…\")\n\t}\n\treturn sb.String()\n}\n"},{"name":"riscvdemo.gno","body":"// Package riscvdemo runs real compiled machine code on chain, a slice at a\n// time.\n//\n// It is a demo of two libraries and carries no logic of its own:\n// [p/moul/x/vm/riscv](/p/moul/x/vm/riscv/v0) is the RV32IM hart, and\n// [p/moul/x/vm/vmkit](/p/moul/x/vm/vmkit/v0) is the host ABI, the fuel meter\n// and the instance store.\n//\n// What it exists to show is that the guest was not written for gno. The\n// programs on the front page are flat .text images: the same bytes\n// `rustc --target riscv32im-unknown-none-elf` emits, uploaded as hex. The\n// realm holds the snapshot between transactions, so one computation finishes\n// across several of them, and realm code cannot do that for itself.\npackage riscvdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/moul/vendor/nt/ufmt/v2\"\n)\n\n// Caps. Everything a caller can grow is bounded, because all of it is storage\n// somebody pays a deposit on.\nconst (\n\t// MaxInstances is how many programs the realm keeps at once.\n\tMaxInstances = 64\n\t// MaxImage caps an uploaded text segment at 2,048 instructions.\n\t//\n\t// This one is not arbitrary. Predecoding costs about 19,600 gas per word\n\t// and is redone on every resume, so the image size is a tax on every\n\t// transaction that touches the instance, not just the upload. 8 KiB works\n\t// out to roughly 40M gas per slice before the guest executes anything,\n\t// which is about 1% of a block.\n\tMaxImage = 8192\n\t// MaxOutput caps the bytes one program may write. Past it the guest is\n\t// trapped rather than truncated, so rendered output is never a lie.\n\tMaxOutput = 4096\n\t// MaxInput caps the call input a program can be given.\n\tMaxInput = 1024\n\t// DefaultFuel is the budget an upload gets when it asks for none, and the\n\t// slice size Step uses when asked for none.\n\tDefaultFuel = 100000\n\t// MaxSliceFuel bounds one transaction's work regardless of what the\n\t// caller asked for, and it is derived from the measurement rather than\n\t// picked: an RV32IM instruction costs about 8,500 gas, so 100,000 of them\n\t// is about 850M, a little under a third of a 3G block. Twice this would\n\t// still be a legal transaction and a rude one, and it would leave no room\n\t// for the predecode and the realm's own storage writes on top.\n\tMaxSliceFuel = 100000\n)\n\nvar (\n\tstore  = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen  seqid.ID\n\tcount  int\n)\n\n// host is the realm-backed [vmkit.Host]. One is built per call, wrapping the\n// instance being stepped, so a guest's output and authority are scoped to it\n// and nothing ambient leaks in.\ntype host struct {\n\tinst    *vmkit.Instance\n\tin      []byte\n\tkv      *avl.Tree\n\toverrun bool // the guest wrote past MaxOutput\n}\n\nfunc (h *host) Caller() address { return h.inst.Owner }\nfunc (h *host) Origin() address { return h.inst.Owner }\nfunc (h *host) Now() int64      { return time.Now().Unix() }\nfunc (h *host) Height() int64   { return runtime.ChainHeight() }\nfunc (h *host) Input() []byte   { return h.in }\n\n// Get and Set are scoped to the instance by construction: the tree belongs to\n// the instance being stepped, so one program cannot reach another's storage\n// even though both live in this one realm.\nfunc (h *host) Get(key []byte) []byte {\n\tv := h.kv.Get(string(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.([]byte)\n}\n\nfunc (h *host) Set(key, val []byte) { h.kv.Set(string(key), val) }\n\nfunc (h *host) Output(p []byte) {\n\tif len(h.inst.Output)+len(p) \u003e MaxOutput {\n\t\th.overrun = true\n\t\treturn\n\t}\n\th.inst.Output = append(h.inst.Output, p...)\n}\n\nfunc (h *host) Emit(typ string, kv ...string) { chain.Emit(typ, kv...) }\n\n// Send is never granted here. The demo funds no instance, so a guest that\n// tries to move coins is refused. That is the capability rule doing its job,\n// not a missing feature.\nfunc (h *host) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\n\nfunc (h *host) Log(msg string) {}\n\n// Upload stores a hex-encoded text image as a new instance and returns its id.\n//\n// The image is loaded here rather than at the first Step, so a misaligned or\n// oversized one is rejected by the transaction that submitted it instead of\n// costing somebody else the gas later.\nfunc Upload(cur realm, hexImage, input string, budget int64) string {\n\timg, ok := decodeHex(hexImage)\n\tif !ok {\n\t\tpanic(\"riscvdemo: image is not valid hex\")\n\t}\n\treturn upload(img, input, budget)\n}\n\n// UploadSample stores one of the programs the front page offers. Writing RV32IM\n// by hand is not the point of this realm, and without this nobody without a\n// cross compiler could press a button.\nfunc UploadSample(cur realm, name, input string, budget int64) string {\n\ts := sampleByName(name)\n\tif s == nil {\n\t\tpanic(\"riscvdemo: no such sample\")\n\t}\n\t// A sample carries its own budget because the default is a total, not a\n\t// slice: the heavy loop needs 200,006 instructions, and offering a button\n\t// that runs out of fuel halfway is a worse demo than no button.\n\tif budget \u003c= 0 {\n\t\tbudget = s.budget\n\t}\n\treturn upload(s.image(), input, budget)\n}\n\nfunc upload(img []byte, input string, budget int64) string {\n\tif count \u003e= MaxInstances {\n\t\tpanic(\"riscvdemo: too many instances, remove one first\")\n\t}\n\tif len(input) \u003e MaxInput {\n\t\tpanic(\"riscvdemo: input too long\")\n\t}\n\tif len(img) == 0 {\n\t\tpanic(\"riscvdemo: empty image\")\n\t}\n\tif len(img) \u003e MaxImage {\n\t\tpanic(\"riscvdemo: image too large\")\n\t}\n\t// Loading it now is the validation: NewMachine is what rejects an image\n\t// that is not a whole number of instructions.\n\tif _, err := riscv.NewMachine(img, riscv.DefaultEntry); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif budget \u003c= 0 {\n\t\tbudget = DefaultFuel\n\t}\n\n\tid := idgen.Next().String()\n\towner := unsafe.PreviousRealm().Address()\n\tstore.Set(vmkit.NewInstance(id, owner, riscv.VMName, img, budget))\n\tif input != \"\" {\n\t\tinputs.Set(id, input)\n\t}\n\tcount++\n\n\tchain.Emit(\"riscv_upload\", \"id\", id, \"bytes\", ufmt.Sprintf(\"%d\", len(img)))\n\treturn id\n}\n\n// Step runs one slice of the instance: up to `fuel` guest instructions, then\n// stop and keep the snapshot. Anyone may pay for a slice, not only the owner:\n// a paused program that only its owner can advance is a worse demo and no\n// safer, since the program and its budget were both fixed at upload.\nfunc Step(cur realm, id string, fuel int64) string {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Status != vmkit.Running {\n\t\tpanic(\"riscvdemo: instance is \" + inst.Status.String())\n\t}\n\tif fuel \u003c= 0 {\n\t\tfuel = DefaultFuel\n\t}\n\tif fuel \u003e MaxSliceFuel {\n\t\tfuel = MaxSliceFuel\n\t}\n\n\tm, err := riscv.NewMachine(inst.Program, riscv.DefaultEntry)\n\tif err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\th := \u0026host{inst: inst, in: []byte(inputOf(id)), kv: avl.NewTree()}\n\tif err := inst.Run(m, h, fuel); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif h.overrun {\n\t\tinst.Status = vmkit.Trapped\n\t\tinst.Trap = \"output limit reached\"\n\t}\n\n\tchain.Emit(\"riscv_step\",\n\t\t\"id\", id,\n\t\t\"status\", inst.Status.String(),\n\t\t\"fuel\", ufmt.Sprintf(\"%d\", inst.FuelUsed),\n\t)\n\treturn inst.Status.String()\n}\n\n// Remove deletes an instance. Owner only.\nfunc Remove(cur realm, id string) {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Owner != unsafe.PreviousRealm().Address() {\n\t\tpanic(\"riscvdemo: not your instance\")\n\t}\n\tstore.Remove(id)\n\tinputs.Remove(id)\n\tcount--\n}\n\nfunc inputOf(id string) string {\n\tv := inputs.Get(id)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n\n// decodeHex accepts the output of any hexdump: an even number of hex digits,\n// with an optional 0x prefix, and whitespace anywhere. Whitespace is allowed\n// because that is what a pasted hexdump has in it; anything else is refused,\n// because a silently mangled image would trap somewhere unrelated later.\nfunc decodeHex(s string) ([]byte, bool) {\n\tif len(s) \u003e= 2 \u0026\u0026 s[0] == '0' \u0026\u0026 (s[1] == 'x' || s[1] == 'X') {\n\t\ts = s[2:]\n\t}\n\tdigits := make([]byte, 0, len(s))\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == ' ' || c == '\\t' || c == '\\n' || c == '\\r' {\n\t\t\tcontinue\n\t\t}\n\t\tv, ok := hexVal(c)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tdigits = append(digits, v)\n\t}\n\tif len(digits) == 0 || len(digits)%2 != 0 {\n\t\treturn nil, false\n\t}\n\tout := make([]byte, len(digits)/2)\n\tfor i := 0; i \u003c len(out); i++ {\n\t\tout[i] = digits[i*2]\u003c\u003c4 | digits[i*2+1]\n\t}\n\treturn out, true\n}\n\nfunc hexVal(c byte) (byte, bool) {\n\tswitch {\n\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn c - '0', true\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'f':\n\t\treturn c - 'a' + 10, true\n\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'F':\n\t\treturn c - 'A' + 10, true\n\t}\n\treturn 0, false\n}\n"},{"name":"riscvdemo_test.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// resetState puts the realm globals back where init() left them. Realm state\n// persists for the whole test binary, so every test that asserts on ids or on\n// the rendered instance list has to start from here.\nfunc resetState() {\n\tstore = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen = seqid.ID(0)\n\tcount = 0\n}\n\nfunc alice() address { return testutils.TestAddress(\"alice\") }\n\nfunc TestUploadAndRunToCompletion(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"hello\", \"\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"Hello, gno.land\\n\", string(inst.Output))\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, alice(), inst.Owner)\n\tuassert.Equal(t, \"riscv32im\", inst.VM)\n}\n\n// Every sample on the front page has to reach its documented answer, or the\n// page offers a button that traps when pressed. The words are assembled\n// outside this repo, so this is the test that catches a mistyped one.\nfunc TestEverySampleReachesItsAnswer(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tcases := []struct {\n\t\tslug   string\n\t\treg    int\n\t\twant   uint32\n\t\toutput string\n\t}{\n\t\t{\"hello\", 0, 0, \"Hello, gno.land\\n\"},\n\t\t{\"sum100\", 5, 5050, \"\"},\n\t\t{\"heavy\", 5, 1250025000, \"\"},\n\t\t{\"mext\", 5, 3000000021, \"\"},\n\t\t{\"clang\", 0, 0, \"fb7ffba0\"},\n\t\t{\"ledger\", 0, 0, \"alice 70\\nbob 80\\n\"},\n\t}\n\tfor _, c := range cases {\n\t\tid := UploadSample(cross(cur), c.slug, sampleByName(c.slug).input, 0)\n\t\tstatus := \"\"\n\t\tfor i := 0; i \u003c 20; i++ {\n\t\t\tstatus = Step(cross(cur), id, 0)\n\t\t\tif status != \"running\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tuassert.Equal(t, \"halted\", status, c.slug+\" must halt\")\n\t\tinst := store.Get(id)\n\t\tuassert.Equal(t, c.output, string(inst.Output), c.slug+\" output\")\n\t\tif c.reg != 0 {\n\t\t\tvar m riscv.Machine\n\t\t\tuassert.NoError(t, m.Restore(inst.Snapshot))\n\t\t\tuassert.Equal(t, uint64(c.want), uint64(m.Registers()[c.reg]), c.slug+\" result\")\n\t\t}\n\t}\n}\n\n// TestOneProgramAcrossManyTransactions is what the realm exists to\n// demonstrate: the same computation, finished over several calls, each paying\n// for its own slice.\nfunc TestOneProgramAcrossManyTransactions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"heavy\", \"\", 0)\n\tstatus := \"\"\n\tfor i := 0; i \u003c 50; i++ {\n\t\tstatus = Step(cross(cur), id, 80000)\n\t\tif status != \"running\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"halted\", status)\n\tuassert.True(t, inst.Slices \u003e 1, \"a 200k instruction program must not finish in one slice\")\n\tuassert.Equal(t, int64(200006), inst.FuelUsed)\n}\n\nfunc TestUploadTakesHex(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// addi a7, zero, 93 ; ecall\n\tid := Upload(cross(cur), \"0x9308d005 73000000\", \"\", 0)\n\t_ = id\n}\n\nfunc TestUploadRejectsBadImages(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// Called without cross(): a panic raised through a crossing call cannot be\n\t// recovered, so uassert would never see it.\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"zzzz\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"abc\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: no such sample\", func() {\n\t\tUploadSample(cur, \"nope\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"riscvdemo: riscv: image length is not a whole number of instructions\",\n\t\tfunc() { Upload(cur, \"0011\", \"\", 0) })\n}\n\nfunc TestDecodeHex(t *testing.T) {\n\tb, ok := decodeHex(\"0xDEADbeef\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\tuassert.Equal(t, uint64(0xDE), uint64(b[0]))\n\tuassert.Equal(t, uint64(0xEF), uint64(b[3]))\n\n\t_, ok = decodeHex(\"\")\n\tuassert.False(t, ok)\n\t_, ok = decodeHex(\"0x\")\n\tuassert.False(t, ok)\n\t// Whitespace is skipped, because a pasted hexdump has it.\n\tb, ok = decodeHex(\"00 11\\n22\\t33\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\t// An odd number of digits is still a refusal, whitespace or not.\n\t_, ok = decodeHex(\"00 1\")\n\tuassert.False(t, ok)\n}\n\nfunc TestRenderHomeOffersEverySample(cur realm, t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"RV32IM, on chain\"), \"the title\")\n\tfor _, s := range samples {\n\t\tuassert.True(t, strings.Contains(out, s.name), \"home must offer \"+s.slug)\n\t}\n\tuassert.True(t, strings.Contains(out, \"No instances yet\"), \"the empty state\")\n}\n\n// The register file is the interesting half of this VM: a program that writes\n// nothing still computed something, and the snapshot is the only place it is\n// legible between transactions.\nfunc TestRenderInstanceShowsTheRegisterFile(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"sum100\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"/\" + id)\n\tuassert.True(t, strings.Contains(out, \"## Registers\"), \"the section\")\n\tuassert.True(t, strings.Contains(out, \"5050\"), \"t0 must show the answer\")\n\tuassert.True(t, strings.Contains(out, \"halted\"), \"the status\")\n}\n\n// The instance page is all hex: the pc, every register, the image dump.\n// gno.land/p/nt/ufmt/v0 has no %X and no width flags, so this page shipped\n// printing \"0x(unhandled verb: %X)\" in every cell; the test pins the fix.\nfunc TestRenderInstanceHex(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// addi a7, zero, 93 ; ecall (exit)\n\tid := Upload(cross(cur), \"0x9308d005 73000000\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"/\" + id)\n\tuassert.False(t, strings.Contains(out, \"unhandled\"), out)\n\tuassert.True(t, strings.Contains(out, \"| a7 | 0x0000005D | 93 | 93 |\"), out)\n\tuassert.True(t, strings.Contains(out, \"05d00893 00000073\"), out)\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tuassert.True(t, strings.Contains(Render(\"/nope\"), \"No such instance\"))\n}\n\n// ExampleRender pins the realm's output for a path whose content cannot drift\n// with the instance list. The home page and the instance page both produce\n// consecutive blank lines, which an example block cannot represent, so they\n// are asserted in the tests above instead.\nfunc ExampleRender() {\n\tprint(Render(\"/missing\"))\n\t// Output:\n\t// # Instance missing\n\t//\n\t// [← all instances](/r/moul/x/vm/riscvdemo/v0)\n\t//\n\t// **No such instance.** It was never uploaded, or its owner removed it.\n}\n"},{"name":"samples.gno","body":"package riscvdemo\n\nimport \"gno.land/p/moul/x/vm/riscv/v0\"\n\n// The programs the front page offers, as the machine words a cross compiler\n// would have emitted. They are assembled outside this repo and pinned here,\n// and riscvdemo_test.gno runs every one of them to the expected answer, so a\n// wrong word is a failing test rather than a page that traps when clicked.\ntype sample struct {\n\tslug   string // what UploadSample takes: short, no punctuation, stable\n\tname   string\n\tbudget int64 // the instance's total instruction budget, not the slice\n\n\t// builtin names an image the library ships compiled, instead of the words\n\t// below. Empty means the words are the program.\n\tbuiltin string\n\twords []uint32\n\tinput string\n\tnote  string\n\tasm   string\n}\n\nvar samples = []sample{\n\t{\n\t\tslug: \"hello\",\n\t\tname: \"Hello, gno.land\",\n\t\twords: []uint32{\n\t\t\t0x00100513, 0x000015B7, 0x02058593, 0x01000613,\n\t\t\t0x04000893, 0x00000073, 0x05D00893, 0x00000073,\n\t\t\t0x6C6C6548, 0x67202C6F, 0x6C2E6F6E, 0x0A646E61,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"Eight instructions and a string constant. The write syscall reads \" +\n\t\t\t\"the bytes straight out of the text segment and hands them to Host.Output.\",\n\t\tasm: `addi a0, zero, 1          # fd\nlui  a1, 0x1000           # buf\naddi a1, a1, 0x20\naddi a2, zero, 16         # len\naddi a7, zero, 64         # write\necall\naddi a7, zero, 93         # exit\necall\n.ascii \"Hello, gno.land\\n\"`,\n\t},\n\t{\n\t\tslug: \"sum100\",\n\t\tname: \"Sum 1 to 100\",\n\t\twords: []uint32{\n\t\t\t0x06400413, 0x00000293, 0x00000313, 0x00130313,\n\t\t\t0x006282B3, 0xFE831CE3, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"A real loop, 303 instructions. Writes nothing: the answer is in t0, \" +\n\t\t\t\"and the instance page shows the register file.\",\n\t\tasm: `addi s0, zero, 100\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"heavy\",\n\t\tname: \"Heavy loop\",\n\t\twords: []uint32{\n\t\t\t0x0000C437, 0x35040413, 0x00000293, 0x00000313,\n\t\t\t0x00130313, 0x006282B3, 0x00000393, 0xFE831AE3,\n\t\t\t0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 250000,\n\t\tnote: \"200,006 instructions, four per iteration. At the largest slice this realm \" +\n\t\t\t\"allows it takes three transactions to finish, which is the thing it exists to show.\",\n\t\tasm: `lui  s0, 0xc000           # s0 = 50000\naddi s0, s0, 0x350\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\naddi t2, zero, 0\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"mext\",\n\t\tname: \"Multiply and divide\",\n\t\twords: []uint32{\n\t\t\t0x3B9AD2B7, 0xA0728293, 0x00300313, 0x026282B3,\n\t\t\t0x00700393, 0x0272D333, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"The M extension. t0 = 1000000007 * 3 truncated to 32 bits, then t1 = t0 / 7. \" +\n\t\t\t\"Division by zero and the one signed overflow case return values here \" +\n\t\t\t\"rather than trapping, which is what the spec says and what a chain needs.\",\n\t\tasm: `lui  t0, 0x3b9ad000       # t0 = 1000000007\naddi t0, t0, -1529\naddi t1, zero, 3\nmul  t0, t0, t1\naddi t2, zero, 7\ndivu t1, t0, t2\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug:   \"clang\",\n\t\tname:   \"Compiled by clang\",\n\t\tinput:  \"gno.land\",\n\t\tbudget: 20000,\n\t\tnote: \"Not written for gno and not written by hand: a freestanding C program, \" +\n\t\t\t\"compiled by clang for riscv32im and shipped as the bytes LLVM emitted. It reads \" +\n\t\t\t\"the call input, hashes it with FNV-1a and writes eight hex digits back. \" +\n\t\t\t\"With the default input it prints fb7ffba0. Source and build command: \" +\n\t\t\t\"tools/riscv-guests/fnv.\",\n\t\tbuiltin: \"fnv\",\n\t\tasm: `long n = syscall3(SYS_READ, 0, (long)in, sizeof(in));\n\nunsigned int h = 2166136261u;\nfor (long i = 0; i \u003c n; i++) {\n\th ^= in[i];\n\th *= 16777619u;      /* the reason this is rv32im */\n}\n\nfor (int i = 0; i \u003c 8; i++) {\n\tunsigned int nib = (h \u003e\u003e (28 - i * 4)) \u0026 0xF;\n\tout[i] = nib \u003c 10 ? '0' + nib : 'a' + (nib - 10);\n}\n\nsyscall3(SYS_WRITE, 1, (long)out, 8);\nsyscall3(SYS_EXIT, 0, 0, 0);`,\n\t},\n\t{\n\t\tslug:   \"ledger\",\n\t\tname:   \"A token, in Rust\",\n\t\tinput:  \"mint alice 100\\nmint bob 50\\nsend alice bob 30\\n\",\n\t\tbudget: 20000,\n\t\tnote: \"no_std Rust, compiled by rustc for riscv32im: mint, send and burn, applied \" +\n\t\t\t\"from the call input. It links Rust's real core and compiler_builtins, so the \" +\n\t\t\t\"balances being 64-bit means a divide runs __udivdi3 here, because RV32 has no \" +\n\t\t\t\"64-bit divide instruction. With the default input it prints alice 70 and bob 80. \" +\n\t\t\t\"Source: tools/riscv-guests/ledger.\",\n\t\tbuiltin: \"ledger\",\n\t\tasm: `match cmd {\n\tb\"send\" =\u003e {\n\t\tlet (from, rest) = field(rest);\n\t\tlet (to, rest) = field(rest);\n\t\tlet (amount, _) = field(rest);\n\t\tlet n = parse_u32(amount).ok_or(\"bad amount\")?;\n\t\tlet fi = led.find(from).ok_or(\"unknown sender\")?;\n\t\tif led.balances[fi] \u003c n {\n\t\t\treturn Err(\"insufficient balance\");\n\t\t}\n\t\tlet ti = led.intern(to).ok_or(\"ledger full or bad name\")?;\n\t\tled.balances[fi] -= n;\n\t\tled.balances[ti] += n;\n\t\tOk(())\n\t}\n\t_ =\u003e Err(\"unknown command\"),\n}`,\n\t},\n}\n\n// image is what gets uploaded: either the words assembled here, or a program\n// the library ships because a compiler produced it.\nfunc (s *sample) image() []byte {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn riscv.GuestFNV()\n\tcase \"ledger\":\n\t\treturn riscv.GuestLedger()\n\t}\n\treturn riscv.Image(s.words)\n}\n\n// lang is the fence tag for what the sample shows. The compiled guest shows\n// its C, because showing a disassembly of what LLVM did with it would bury the\n// only interesting fact: nobody wrote the machine code.\nfunc (s *sample) lang() string {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn \"c\"\n\tcase \"ledger\":\n\t\treturn \"rust\"\n\t}\n\treturn \"asm\"\n}\n\nfunc sampleByName(slug string) *sample {\n\tfor i := range samples {\n\t\tif samples[i].slug == slug {\n\t\t\treturn \u0026samples[i]\n\t\t}\n\t}\n\treturn nil\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":"20000000ugnot"}],"fee":{"gas_wanted":"150000000","gas_fee":"450000ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"FFOKW14jFdw3SrY30KvjQS90Eo1/ey+i6CpIAjr84kon2P3wR01d1dH87lkBP9QKezf1EU1GfVOOLMV989/56g=="}],"memo":""},"metadata":{"timestamp":"1791206391"}},{"tx":{"msg":[{"@type":"/vm.m_call","caller":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","send":"","max_deposit":"5000000ugnot","pkg_path":"gno.land/r/moul/x/vm/riscvdemo/v0","func":"UploadSample","args":["hello","","0"]},{"@type":"/vm.m_call","caller":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","send":"","max_deposit":"5000000ugnot","pkg_path":"gno.land/r/moul/x/vm/riscvdemo/v0","func":"Step","args":["0000001","0"]}],"fee":{"gas_wanted":"60000000","gas_fee":"200000ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"4fHBzz7Kv3sfLwj4K5Pd/usoYvpou/h/LDVMc077BGAxbtPOHK+Z0/2LCq1Hp+a2RtlZf5Y4vAPVyn9mvk4jkQ=="}],"memo":""},"metadata":{"timestamp":"1791206434"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Jxy+nAPTt5Pq+pIyOjuDyhvISRrTX/OBOqCN268tEBg+maLeJusnnsj1QNhVJSFbZbwb0vgjLXIw/EKATfwjUg=="}],"memo":""},"metadata":{"timestamp":"1791206455"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bfdemo","path":"gno.land/r/moul/x/vm/bfdemo/v0","files":[{"name":"README.md","body":"# r/moul/x/vm/bfdemo\n\nA realm that runs Brainfuck programs on chain, a slice at a time.\n\nIt is a demo of [`p/moul/x/vm/bf`](/p/moul/x/vm/bf/v0) (the machine) and\n[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, the\ninstance store), and carries no logic of its own.\n\nWhat it exists to show is the thing gno realm code cannot do for itself: a\nprogram that runs out of fuel does not fail, it pauses. The realm keeps the\nsnapshot, and the next caller pays for the next slice. Upload a program, call\n`Step` a few times, and watch one computation finish across several\ntransactions.\n\n## Calls\n\n| function | what |\n|---|---|\n| `Upload(src, input, budget)` | compile and store a program, returns its id. Compilation happens here, so a malformed program is rejected by the transaction that submitted it |\n| `Step(id, fuel)` | run one slice and keep the snapshot. Anyone may pay for a slice, not only the owner |\n| `Remove(id)` | delete an instance. Owner only |\n\n`Render(\"/\")` lists the instances and offers three sample programs.\n`Render(\"/\u003cid\u003e\")` shows one instance: its compiled program, status, fuel, and\noutput.\n\n## Limits\n\nEverything a caller can grow is bounded, because all of it is storage somebody\npays a deposit on: 64 instances, 64 KiB of source, 1 KiB of input, 4 KiB of\noutput, 5,000,000 fuel per slice, 30,000 tape cells. A guest that writes past\nthe output cap is trapped rather than truncated, so the rendered output is never\na lie.\n\n## Untrusted input\n\nA program's source is caller-supplied, and everything outside the eight\noperators is a comment that may hold anything at all. The page never renders it:\nit shows the program the machine actually compiled, which cannot contain a\nbacktick or a newline and so cannot break out of its code fence. Guest output is\narbitrary bytes and is escaped the same way, backtick included.\n\nNo instance is funded, so `Host.Send` always returns `ErrNotGranted`. That is\nthe capability rule doing its job, not a missing feature.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/vm/bfdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/vm/bfdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bfdemo.gno","body":"// Package bfdemo is the playground for the guest-VM work: a realm that runs\n// Brainfuck programs on chain, a slice at a time.\n//\n// It is a demo of two libraries and carries no logic of its own:\n// [p/moul/x/vm/bf](/p/moul/x/vm/bf/v0) is the machine, and\n// [p/moul/x/vm/vmkit](/p/moul/x/vm/vmkit/v0) is the host ABI, the fuel meter\n// and the instance store.\n//\n// What it exists to show is the thing gno realm code cannot do for itself: a\n// program that runs out of fuel does not fail, it pauses. The realm keeps the\n// snapshot, and the next caller pays for the next slice. Upload a program,\n// call Step a few times, and watch one computation finish across several\n// transactions.\npackage bfdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/vm/bf/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Caps. Everything a caller can grow is bounded, because all of it is storage\n// somebody pays a deposit on.\nconst (\n\t// MaxInstances is how many programs the realm keeps at once. Past it,\n\t// an upload has to wait for someone to remove one.\n\tMaxInstances = 64\n\t// MaxOutput caps the bytes one program may write. Past it the guest is\n\t// trapped rather than truncated, so rendered output is never a lie.\n\tMaxOutput = 4096\n\t// MaxInput caps the call input a program can be given.\n\tMaxInput = 1024\n\t// DefaultFuel is the budget an upload gets when it asks for none, and\n\t// the slice size Step uses when asked for none.\n\tDefaultFuel = 100000\n\t// MaxSliceFuel bounds one transaction's work regardless of what the\n\t// caller asked for.\n\tMaxSliceFuel = 5000000\n)\n\nvar (\n\t// store holds the instances: program, snapshot, status, accounting.\n\tstore = vmkit.NewStore()\n\t// inputs holds each instance's call input, keyed by id. It is separate\n\t// from the instance so vmkit.Instance stays the VM-agnostic record it\n\t// is meant to be.\n\tinputs = avl.NewTree()\n\tidgen  seqid.ID\n\tcount  int\n)\n\n// host is the realm-backed [vmkit.Host]. One is built per call, wrapping the\n// instance being stepped, so a guest's output and authority are scoped to it\n// and nothing ambient leaks in.\ntype host struct {\n\tinst    *vmkit.Instance\n\tin      []byte\n\tkv      *avl.Tree\n\toverrun bool // the guest wrote past MaxOutput\n}\n\nfunc (h *host) Caller() address { return h.inst.Owner }\nfunc (h *host) Origin() address { return h.inst.Owner }\nfunc (h *host) Now() int64      { return time.Now().Unix() }\nfunc (h *host) Height() int64   { return runtime.ChainHeight() }\nfunc (h *host) Input() []byte   { return h.in }\n\n// Get and Set are scoped to the instance by construction: the tree belongs to\n// the instance being stepped, so one program cannot reach another's storage\n// even though both live in this one realm. bf never calls them; they are here\n// because the ABI is the point.\nfunc (h *host) Get(key []byte) []byte {\n\tv := h.kv.Get(string(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.([]byte)\n}\n\nfunc (h *host) Set(key, val []byte) { h.kv.Set(string(key), val) }\n\nfunc (h *host) Output(p []byte) {\n\tif len(h.inst.Output)+len(p) \u003e MaxOutput {\n\t\th.overrun = true\n\t\treturn\n\t}\n\th.inst.Output = append(h.inst.Output, p...)\n}\n\nfunc (h *host) Emit(typ string, kv ...string) { chain.Emit(typ, kv...) }\n\n// Send is never granted here. The demo funds no instance, so a guest that\n// tries to move coins is refused. That is the capability rule doing its job,\n// not a missing feature.\nfunc (h *host) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\n\nfunc (h *host) Log(msg string) {}\n\n// Upload compiles src and stores it as a new instance, returning its id.\n//\n// Compilation happens here rather than at the first Step, so an unbalanced\n// program is rejected by the transaction that submitted it instead of costing\n// somebody else the gas later.\nfunc Upload(cur realm, src, input string, budget int64) string {\n\tif count \u003e= MaxInstances {\n\t\tpanic(\"bfdemo: too many instances, remove one first\")\n\t}\n\tif len(input) \u003e MaxInput {\n\t\tpanic(\"bfdemo: input too long\")\n\t}\n\tif _, err := bf.CompileDefault(src); err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\tif budget \u003c= 0 {\n\t\tbudget = DefaultFuel\n\t}\n\n\tid := idgen.Next().String()\n\towner := unsafe.PreviousRealm().Address()\n\tstore.Set(vmkit.NewInstance(id, owner, bf.VMName, []byte(src), budget))\n\tif input != \"\" {\n\t\tinputs.Set(id, input)\n\t}\n\tcount++\n\n\tchain.Emit(\"bf_upload\", \"id\", id, \"bytes\", ufmt.Sprintf(\"%d\", len(src)))\n\treturn id\n}\n\n// Step runs one slice of the instance: up to `fuel` guest ops, then stop and\n// keep the snapshot. Anyone may pay for a slice, not only the owner: a paused\n// program that only its owner can advance is a worse demo and no safer, since\n// the program and its budget were both fixed at upload.\nfunc Step(cur realm, id string, fuel int64) string {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"bfdemo: no such instance\")\n\t}\n\tif inst.Status != vmkit.Running {\n\t\tpanic(\"bfdemo: instance is \" + inst.Status.String())\n\t}\n\tif fuel \u003c= 0 {\n\t\tfuel = DefaultFuel\n\t}\n\tif fuel \u003e MaxSliceFuel {\n\t\tfuel = MaxSliceFuel\n\t}\n\n\tprog, err := bf.CompileDefault(string(inst.Program))\n\tif err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\th := \u0026host{inst: inst, in: []byte(inputOf(id)), kv: avl.NewTree()}\n\tif err := inst.Run(bf.NewMachine(prog), h, fuel); err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\tif h.overrun {\n\t\tinst.Status = vmkit.Trapped\n\t\tinst.Trap = \"output limit reached\"\n\t}\n\n\tchain.Emit(\"bf_step\",\n\t\t\"id\", id,\n\t\t\"status\", inst.Status.String(),\n\t\t\"fuel\", ufmt.Sprintf(\"%d\", inst.FuelUsed),\n\t)\n\treturn inst.Status.String()\n}\n\n// Remove deletes an instance. Owner only.\nfunc Remove(cur realm, id string) {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"bfdemo: no such instance\")\n\t}\n\tif inst.Owner != unsafe.PreviousRealm().Address() {\n\t\tpanic(\"bfdemo: not your instance\")\n\t}\n\tstore.Remove(id)\n\tinputs.Remove(id)\n\tcount--\n}\n\nfunc inputOf(id string) string {\n\tv := inputs.Get(id)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n"},{"name":"bfdemo_test.gno","body":"package bfdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst hello = \"++++++++++[\u003e+++++++\u003e++++++++++\u003e+++\u003e+\u003c\u003c\u003c\u003c-]\u003e++.\u003e+.+++++++..+++.\u003e++.\u003c\u003c+++++++++++++++.\u003e.+++.------.--------.\"\n\n// resetState puts the realm globals back where init() left them. Realm state\n// persists for the whole test binary, so every test that asserts on ids or on\n// the rendered instance list has to start from here.\nfunc resetState() {\n\tstore = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen = seqid.ID(0)\n\tcount = 0\n}\n\nfunc TestUploadAndRunToCompletion(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := Upload(cross(cur), hello, \"\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"Hello World\", string(inst.Output))\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, alice, inst.Owner)\n}\n\n// TestOneProgramAcrossManyTransactions is what the realm exists to\n// demonstrate: the same computation, finished over several calls, each paying\n// for its own slice.\nfunc TestOneProgramAcrossManyTransactions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\tid := Upload(cross(cur), hello, \"\", 0)\n\tstatus := \"\"\n\tslices := 0\n\tfor slices \u003c 500 {\n\t\tstatus = Step(cross(cur), id, 7)\n\t\tslices++\n\t\tif status != \"running\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"halted\", status)\n\tuassert.Equal(t, \"Hello World\", string(inst.Output))\n\tuassert.True(t, inst.Slices \u003e 1, \"took more than one slice\")\n}\n\nfunc TestInputIsReadThroughTheHost(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// \",[.,]\" echoes its input back.\n\tid := Upload(cross(cur), \",[.,]\", \"gno.land\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\tuassert.Equal(t, \"gno.land\", string(store.Get(id).Output))\n}\n\nfunc TestBudgetStopsAProgram(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\tid := Upload(cross(cur), hello, \"\", 12)\n\tuassert.Equal(t, \"out of fuel\", Step(cross(cur), id, 0))\n\tuassert.Equal(t, int64(12), store.Get(id).FuelUsed)\n\n\t// And it stays stopped rather than quietly continuing.\n\tuassert.AbortsContains(t, cur, \"instance is out of fuel\", func() {\n\t\tStep(cross(cur), id, 0)\n\t})\n}\n\nfunc TestUploadRejectsAMalformedProgram(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// Rejected by the transaction that submitted it, not by whoever pays\n\t// for the first slice later.\n\tuassert.AbortsContains(t, cur, \"unmatched\", func() {\n\t\tUpload(cross(cur), \"+++[\", \"\", 0)\n\t})\n\tuassert.Equal(t, 0, count)\n}\n\nfunc TestRemoveIsOwnerOnly(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Upload(cross(cur), hello, \"\", 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"not your instance\", func() {\n\t\tRemove(cross(cur), id)\n\t})\n\n\t// Anyone may pay for a slice, though: the program and its budget were\n\t// both fixed at upload.\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRemove(cross(cur), id)\n\tuassert.Equal(t, 0, count)\n\tuassert.True(t, store.Get(id) == nil)\n}\n\nfunc TestOutputIsCappedAndTrapped(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// A cell set to 1 and printed forever: an infinite writer.\n\tid := Upload(cross(cur), \"+[.]\", \"\", 0)\n\tstatus := Step(cross(cur), id, 0)\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"trapped\", status)\n\tuassert.Equal(t, \"output limit reached\", inst.Trap)\n\tuassert.Equal(t, MaxOutput, len(inst.Output))\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tresetState()\n\tuassert.True(t, strings.Contains(Render(\"/nope\"), \"No such instance\"))\n}\n\n// TestRenderEscapesGuestOutput pins the rule that a realm cannot be fixed in\n// place once it is live: everything a caller controls is escaped before it\n// reaches the page.\nfunc TestRenderEscapesGuestOutput(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// Print a backtick (96), which would otherwise close the code fence.\n\tsrc := strings.Repeat(\"+\", 96) + \".\"\n\tid := Upload(cross(cur), src, \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tpage := Render(\"/\" + id)\n\tuassert.Equal(t, \"`\", string(store.Get(id).Output))\n\tuassert.True(t, strings.Contains(page, \"\\\\x60\"), \"the backtick is escaped\")\n\n\t// The comment text in a program never reaches the page at all: only\n\t// the eight operators do.\n\tuassert.Equal(t, \"+++[-]\u003c\u003e\", operatorsOnly(\"+++ this is a comment [-] \u003c/script\u003e\"))\n}\n\n// Output sits in a code span, where markdown escapes show verbatim: only the\n// pipe is escaped there, and nothing else.\nfunc TestCodeCell(t *testing.T) {\n\tuassert.Equal(t, \"`Hello, gno.land\\\\n`\", codeCell(\"Hello, gno.land\\\\n\"))\n\tuassert.Equal(t, \"`a\\\\|b`\", codeCell(\"a|b\"))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/vm/bfdemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render.gno","body":"package bfdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/vm/bf/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// samples are the programs the home page offers, so the realm is usable\n// without writing Brainfuck by hand.\nvar samples = []struct {\n\tname  string\n\tsrc   string\n\tinput string\n\tnote  string\n}{\n\t{\n\t\t\"Hello World\",\n\t\t\"++++++++++[\u003e+++++++\u003e++++++++++\u003e+++\u003e+\u003c\u003c\u003c\u003c-]\u003e++.\u003e+.+++++++..+++.\u003e++.\u003c\u003c+++++++++++++++.\u003e.+++.------.--------.\",\n\t\t\"\",\n\t\t\"385 guest ops, five tape cells. Finishes in one slice.\",\n\t},\n\t{\n\t\t\"Echo the input\",\n\t\t\",[.,]\",\n\t\t\"gno.land\",\n\t\t\"Reads through Host.Input, which is what the naive interpreter could not do at all: it panicked on `,`.\",\n\t},\n\t{\n\t\t\"Heavy loop\",\n\t\t\"++++++++++[-\u003e++++++++++[-\u003e++++++++++[-]\u003c]\u003c]\",\n\t\t\"\",\n\t\t\"About 111k guest ops. Give it 20000 fuel and it takes six slices, which is the point.\",\n\t},\n}\n\n// Render is the realm's gnoweb view.\n//\n//   - \"/\"      the samples, the instance list, and how the thing works.\n//   - \"/\u003cid\u003e\"  one instance: its program, status, fuel and output.\nfunc Render(path string) string {\n\tid := strings.TrimPrefix(path, \"/\")\n\tid = strings.TrimSpace(id)\n\tif id == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderInstance(id)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Brainfuck, on chain, a slice at a time\\n\\n\")\n\tsb.WriteString(\"Demo of [`p/moul/x/vm/bf`](/p/moul/x/vm/bf/v0) (the machine) and \")\n\tsb.WriteString(\"[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, \")\n\tsb.WriteString(\"the instance store). This realm holds no logic of its own.\\n\\n\")\n\tsb.WriteString(\"A program here does not run to completion. It runs until its fuel slice is spent, \")\n\tsb.WriteString(\"then pauses: the realm keeps the snapshot and the next caller pays for the next slice. \")\n\tsb.WriteString(\"Realm code cannot pause itself, and a guest can.\\n\\n\")\n\n\tsb.WriteString(\"## Samples\\n\\n\")\n\tfor _, s := range samples {\n\t\tsb.WriteString(\"**\" + ui.Inline(s.name) + \"**: \" + s.note + \"\\n\\n\")\n\t\tsb.WriteString(\"```\\n\" + s.src + \"\\n```\\n\\n\")\n\t\tsb.WriteString(ui.Action(\"Upload \"+s.name, \"Upload\",\n\t\t\t\"src\", s.src, \"input\", s.input, \"budget\", \"0\") + \"\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Instances\\n\\n\")\n\tt := ui.NewTable(\"id\", \"status\", \"fuel used\", \"slices\", \"output\")\n\tstore.ReverseIterate(func(i *vmkit.Instance) bool {\n\t\tt.Row(\n\t\t\t\"[\"+i.ID+\"](/r/moul/x/vm/bfdemo/v0:\"+i.ID+\")\",\n\t\t\ti.Status.String(),\n\t\t\tufmt.Sprintf(\"%d\", i.FuelUsed),\n\t\t\tufmt.Sprintf(\"%d\", i.Slices),\n\t\t\tcodeCell(printable(i.Output, 24)),\n\t\t)\n\t\treturn false\n\t})\n\tsb.WriteString(t.OrEmpty(\"No instances yet. Upload one of the samples above.\"))\n\tsb.WriteString(\"\\n\\n\")\n\n\tsb.WriteString(\"## Limits\\n\\n\")\n\tlt := ui.NewTable(\"limit\", \"value\")\n\tlt.Row(\"instances\", ufmt.Sprintf(\"%d\", MaxInstances))\n\tlt.Row(\"source bytes\", ufmt.Sprintf(\"%d\", bf.MaxSource))\n\tlt.Row(\"input bytes\", ufmt.Sprintf(\"%d\", MaxInput))\n\tlt.Row(\"output bytes\", ufmt.Sprintf(\"%d\", MaxOutput))\n\tlt.Row(\"fuel per slice\", ufmt.Sprintf(\"%d\", MaxSliceFuel))\n\tlt.Row(\"tape cells\", ufmt.Sprintf(\"%d\", bf.TapeSize))\n\tsb.WriteString(lt.String())\n\treturn sb.String()\n}\n\nfunc renderInstance(id string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Instance \" + ui.Inline(id) + \"\\n\\n\")\n\tsb.WriteString(\"[← all instances](/r/moul/x/vm/bfdemo/v0)\\n\\n\")\n\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tsb.WriteString(\"**No such instance.** It was never uploaded, or its owner removed it.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tt := ui.NewTable(\"field\", \"value\")\n\tt.Row(\"owner\", ui.Addr(inst.Owner))\n\tt.Row(\"vm\", ui.Cell(inst.VM))\n\tt.Row(\"status\", inst.Status.String())\n\tif inst.Trap != \"\" {\n\t\tt.Row(\"trap\", ui.Cell(inst.Trap))\n\t}\n\tt.Row(\"fuel used\", ufmt.Sprintf(\"%d\", inst.FuelUsed))\n\tt.Row(\"fuel budget\", fuelText(inst.FuelBudget))\n\tt.Row(\"slices\", ufmt.Sprintf(\"%d\", inst.Slices))\n\tt.Row(\"source bytes\", ufmt.Sprintf(\"%d\", len(inst.Program)))\n\tt.Row(\"snapshot bytes\", ufmt.Sprintf(\"%d\", len(inst.Snapshot)))\n\tsb.WriteString(t.String())\n\tsb.WriteString(\"\\n\")\n\n\t// The source is caller-supplied, and everything outside the eight\n\t// operators is a comment that may hold anything at all. Show the\n\t// program the machine actually compiled, which cannot contain a\n\t// backtick or a newline and so cannot break out of the fence.\n\tsb.WriteString(\"## Program\\n\\n```\\n\" + operatorsOnly(string(inst.Program)) + \"\\n```\\n\\n\")\n\n\tsb.WriteString(\"## Output\\n\\n\")\n\tif len(inst.Output) == 0 {\n\t\tsb.WriteString(ui.Empty(\"Nothing written yet.\"))\n\t} else {\n\t\tsb.WriteString(\"```\\n\" + printable(inst.Output, MaxOutput) + \"\\n```\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tif inst.Status == vmkit.Running {\n\t\tsb.WriteString(ui.Action(\"Run 10000 more fuel\", \"Step\", \"id\", id, \"fuel\", \"10000\"))\n\t\tsb.WriteString(\" · \")\n\t\tsb.WriteString(ui.Action(\"Run 100000 more fuel\", \"Step\", \"id\", id, \"fuel\", \"100000\"))\n\t\tsb.WriteString(\"\\n\")\n\t} else {\n\t\tsb.WriteString(\"This instance is **\" + inst.Status.String() + \"** and cannot be stepped again.\\n\")\n\t}\n\treturn sb.String()\n}\n\nfunc fuelText(n int64) string {\n\tif n == vmkit.Unmetered {\n\t\treturn \"unmetered\"\n\t}\n\treturn ufmt.Sprintf(\"%d\", n)\n}\n\n// operatorsOnly strips a program down to the eight characters the language\n// defines. Everything else is a comment by definition, and a comment is\n// attacker-controlled text that has no business reaching a renderer.\nfunc operatorsOnly(src string) string {\n\tvar sb strings.Builder\n\tfor i := 0; i \u003c len(src); i++ {\n\t\tswitch src[i] {\n\t\tcase '+', '-', '\u003c', '\u003e', '[', ']', '.', ',':\n\t\t\tsb.WriteByte(src[i])\n\t\t}\n\t}\n\tif sb.Len() == 0 {\n\t\treturn \"(no operators: this program does nothing)\"\n\t}\n\treturn sb.String()\n}\n\n// printable renders guest output for a code fence: printable ASCII as itself,\n// everything else as an escape. A guest writes arbitrary bytes, so this is\n// the only form of it that is safe to show.\nfunc printable(b []byte, max int) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tconst hexDigits = \"0123456789abcdef\"\n\tvar sb strings.Builder\n\tfor _, c := range b {\n\t\tswitch {\n\t\tcase c == '\\n':\n\t\t\tsb.WriteString(\"\\\\n\")\n\t\tcase c == '\\t':\n\t\t\tsb.WriteString(\"\\\\t\")\n\t\tcase c == '\\\\':\n\t\t\tsb.WriteString(\"\\\\\\\\\")\n\t\tcase c == '`':\n\t\t\tsb.WriteString(\"\\\\x60\")\n\t\tcase c \u003e= 0x20 \u0026\u0026 c \u003c 0x7f:\n\t\t\tsb.WriteByte(c)\n\t\tdefault:\n\t\t\tsb.WriteString(\"\\\\x\")\n\t\t\tsb.WriteByte(hexDigits[c\u003e\u003e4])\n\t\t\tsb.WriteByte(hexDigits[c\u00260x0f])\n\t\t}\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"…\")\n\t}\n\treturn sb.String()\n}\n\n// codeCell puts already-printable text in a code span inside a table cell.\n// Inside backticks markdown escapes are not applied, so ui.Cell's backslashes\n// would reach the reader verbatim (\"Hello, gno\\.land\"); the one character a\n// table cell still needs escaped there is the pipe. printable has already\n// removed the backtick and the newline, the other two that could break out.\nfunc codeCell(s string) string {\n\treturn \"`\" + strings.ReplaceAll(s, \"|\", \"\\\\|\") + \"`\"\n}\n"}]},"send":"","max_deposit":"9000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"riscvdemo","path":"gno.land/r/moul/x/vm/riscvdemo/v0","files":[{"name":"README.md","body":"# r/moul/x/vm/riscvdemo\n\nDemo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0), the RV32IM hart, and\n[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0), the host ABI. This realm holds no\nlogic of its own: it stores images, builds a `vmkit.Host`, and renders.\n\nWhat it exists to show is two things realm code cannot do for itself.\n\n**The guest was not written for gno.** The programs on the front page are flat\n`.text` images, the bytes a cross compiler emits for\n`riscv32im-unknown-none-elf`. `Upload` takes hex, so anything you can build with\n`clang`, `rustc`, TinyGo or Zig and strip to its text segment goes in unchanged.\n\nTwo samples are exactly that and neither is a mock up. **Compiled by clang** is\na freestanding C program; **A token, in Rust** is `#![no_std]` Rust that mints,\nsends and burns, linking Rust's real `core` and `compiler_builtins`, so a\n64-bit divide in it runs `__udivdi3` on a machine with no 64-bit divide\ninstruction. Both are shipped as the bytes the compiler emitted, and the page\nshows their source rather than a disassembly, because a disassembly would bury\nthe only interesting fact: nobody wrote the machine code. Sources and build\ncommands: `tools/riscv-guests`.\n\n**A program pauses instead of failing.** It runs until its fuel slice is spent,\nthen stops with a snapshot the realm keeps, and the next caller pays for the\nnext slice. The \"Heavy loop\" sample is 200,006 instructions and takes three\ntransactions at the default slice, which is the whole point.\n\n```\nUploadSample(\"heavy\", \"\", 0)   -\u003e id\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"halted\"\n```\n\n## Reading the instance page\n\nA guest that writes nothing has still computed something, so the instance page\nrestores the snapshot and shows the register file under its ABI names. That is\nthe only place the state is legible: the hart itself does not survive the\ntransaction, only its snapshot does.\n\n## What a slice costs\n\nAn RV32IM instruction costs about **8,500 gas**, measured rather than estimated,\nso a block buys roughly **350,000 guest instructions**. Loading the image costs\nabout **19,600 gas per instruction word** and is paid again on every resume,\nwhich is why `MaxImage` is 8 KiB and not a megabyte. The measurements and how\nthey were taken are in the [library README](/p/moul/x/vm/riscv/v0).\n\n## What this realm does not grant\n\n`Send` always returns `vmkit.ErrNotGranted`. No instance here is funded, so a\nguest that tries to move coins is refused, and that is the capability rule\nworking rather than a missing feature. Guest key-value storage is scoped to the\ninstance being stepped by construction: the tree belongs to the instance, so one\nprogram cannot reach another's even though both live in this realm.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/vm/riscvdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/vm/riscvdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/vm/riscvdemo/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"render.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/moul/vendor/nt/ufmt/v2\"\n)\n\n// regNames are the ABI names, because nobody reading a register dump thinks in\n// x-numbers and every compiler's output is annotated with these.\nvar regNames = [32]string{\n\t\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\t\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\t\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\t\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\",\n}\n\n// Render is the realm's gnoweb view.\n//\n//   - \"/\"      the samples, the instance list, and what the numbers mean.\n//   - \"/\u003cid\u003e\"  one instance: its status, fuel, output and register file.\nfunc Render(path string) string {\n\tid := strings.TrimSpace(strings.TrimPrefix(path, \"/\"))\n\tif id == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderInstance(id)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# RV32IM, on chain, a slice at a time\\n\\n\")\n\tsb.WriteString(\"Demo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0) (the hart) and \")\n\tsb.WriteString(\"[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, \")\n\tsb.WriteString(\"the instance store). This realm holds no logic of its own.\\n\\n\")\n\tsb.WriteString(\"The programs below are flat `.text` images: the same bytes a cross compiler \")\n\tsb.WriteString(\"emits for `riscv32im-unknown-none-elf`. Nothing here was written in a \")\n\tsb.WriteString(\"chain language, and nothing translated it.\\n\\n\")\n\tsb.WriteString(\"A program does not run to completion. It runs until its fuel slice is spent, \")\n\tsb.WriteString(\"then pauses: the realm keeps the snapshot and the next caller pays for the \")\n\tsb.WriteString(\"next slice. Realm code cannot pause itself, and a guest can.\\n\\n\")\n\n\tsb.WriteString(\"## Samples\\n\\n\")\n\tfor i := range samples {\n\t\ts := \u0026samples[i]\n\t\tsb.WriteString(\"**\" + ui.Inline(s.name) + \"**: \" + s.note + \"\\n\\n\")\n\t\tsb.WriteString(\"```\" + s.lang() + \"\\n\" + s.asm + \"\\n```\\n\\n\")\n\t\tsb.WriteString(ui.Action(\"Upload \"+s.name, \"UploadSample\",\n\t\t\t\"name\", s.slug, \"input\", s.input,\n\t\t\t\"budget\", ufmt.Sprintf(\"%d\", s.budget)) + \"\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Instances\\n\\n\")\n\tt := ui.NewTable(\"id\", \"status\", \"instructions\", \"slices\", \"output\")\n\tstore.ReverseIterate(func(i *vmkit.Instance) bool {\n\t\tt.Row(\n\t\t\t\"[\"+i.ID+\"](/r/moul/x/vm/riscvdemo/v0:\"+i.ID+\")\",\n\t\t\ti.Status.String(),\n\t\t\tufmt.Sprintf(\"%d\", i.FuelUsed),\n\t\t\tufmt.Sprintf(\"%d\", i.Slices),\n\t\t\tcodeCell(printable(i.Output, 24)),\n\t\t)\n\t\treturn false\n\t})\n\tsb.WriteString(t.OrEmpty(\"No instances yet. Upload one of the samples above.\"))\n\tsb.WriteString(\"\\n\\n\")\n\n\tsb.WriteString(\"## What a slice costs\\n\\n\")\n\tsb.WriteString(\"An RV32IM instruction costs about **8,500 gas** here, measured rather than \")\n\tsb.WriteString(\"estimated, so a block buys roughly **350,000 guest instructions**. Loading \")\n\tsb.WriteString(\"the image costs about **19,600 gas per instruction word** and is paid again \")\n\tsb.WriteString(\"on every resume, which is why the image cap below is small. The numbers and \")\n\tsb.WriteString(\"how they were taken are in the [library README](/p/moul/x/vm/riscv/v0).\\n\\n\")\n\n\tsb.WriteString(\"## Limits\\n\\n\")\n\tlt := ui.NewTable(\"limit\", \"value\")\n\tlt.Row(\"instances\", ufmt.Sprintf(\"%d\", MaxInstances))\n\tlt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", MaxImage))\n\tlt.Row(\"input bytes\", ufmt.Sprintf(\"%d\", MaxInput))\n\tlt.Row(\"output bytes\", ufmt.Sprintf(\"%d\", MaxOutput))\n\tlt.Row(\"instructions per slice\", ufmt.Sprintf(\"%d\", MaxSliceFuel))\n\tlt.Row(\"address space\", ufmt.Sprintf(\"%d\", riscv.MemSize))\n\tsb.WriteString(lt.String())\n\treturn sb.String()\n}\n\nfunc renderInstance(id string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Instance \" + ui.Inline(id) + \"\\n\\n\")\n\tsb.WriteString(\"[← all instances](/r/moul/x/vm/riscvdemo/v0)\\n\\n\")\n\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tsb.WriteString(\"**No such instance.** It was never uploaded, or its owner removed it.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tt := ui.NewTable(\"field\", \"value\")\n\tt.Row(\"owner\", ui.Addr(inst.Owner))\n\tt.Row(\"vm\", ui.Cell(inst.VM))\n\tt.Row(\"status\", inst.Status.String())\n\tif inst.Trap != \"\" {\n\t\tt.Row(\"trap\", ui.Cell(inst.Trap))\n\t}\n\tt.Row(\"instructions run\", ufmt.Sprintf(\"%d\", inst.FuelUsed))\n\tt.Row(\"budget\", fuelText(inst.FuelBudget))\n\tt.Row(\"slices\", ufmt.Sprintf(\"%d\", inst.Slices))\n\tt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", len(inst.Program)))\n\tt.Row(\"image words\", ufmt.Sprintf(\"%d\", len(inst.Program)/4))\n\tt.Row(\"snapshot bytes\", ufmt.Sprintf(\"%d\", len(inst.Snapshot)))\n\tsb.WriteString(t.String())\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Registers\\n\\n\")\n\tsb.WriteString(renderRegisters(inst))\n\n\tsb.WriteString(\"## Output\\n\\n\")\n\tif len(inst.Output) == 0 {\n\t\tsb.WriteString(ui.Empty(\"Nothing written yet.\"))\n\t} else {\n\t\tsb.WriteString(\"```\\n\" + printable(inst.Output, MaxOutput) + \"\\n```\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Image\\n\\n```\\n\" + hexDump(inst.Program, 64) + \"\\n```\\n\\n\")\n\n\tif inst.Status == vmkit.Running {\n\t\tsb.WriteString(ui.Action(\"Run 25000 instructions\", \"Step\", \"id\", id, \"fuel\", \"25000\"))\n\t\tsb.WriteString(\" · \")\n\t\tsb.WriteString(ui.Action(\"Run 100000 instructions\", \"Step\", \"id\", id, \"fuel\", \"100000\"))\n\t\tsb.WriteString(\"\\n\")\n\t} else {\n\t\tsb.WriteString(\"This instance is **\" + inst.Status.String() + \"** and cannot be stepped again.\\n\")\n\t}\n\treturn sb.String()\n}\n\n// renderRegisters restores the snapshot to read the register file out of it.\n// The hart is not kept between transactions, only its snapshot is, so this is\n// the only place the state is legible, and it is the thing worth seeing: a\n// program that wrote nothing still computed something.\nfunc renderRegisters(inst *vmkit.Instance) string {\n\tif len(inst.Snapshot) == 0 {\n\t\treturn ui.Empty(\"Not started yet: no snapshot to read.\") + \"\\n\\n\"\n\t}\n\tvar m riscv.Machine\n\tif err := m.Restore(inst.Snapshot); err != nil {\n\t\treturn ui.Empty(\"The snapshot could not be read.\") + \"\\n\\n\"\n\t}\n\treg := m.Registers()\n\n\tvar sb strings.Builder\n\tt := ui.NewTable(\"register\", \"hex\", \"unsigned\", \"signed\")\n\tt.Row(\"pc\", ufmt.Sprintf(\"0x%08X\", m.PC()), \"\", \"\")\n\tshown := 0\n\tfor i := 1; i \u003c 32; i++ {\n\t\tif reg[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt.Row(\n\t\t\tregNames[i],\n\t\t\tufmt.Sprintf(\"0x%08X\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", int64(int32(reg[i]))),\n\t\t)\n\t\tshown++\n\t}\n\tsb.WriteString(t.String())\n\tif shown == 0 {\n\t\tsb.WriteString(\"\\nEvery register except `pc` is zero.\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\treturn sb.String()\n}\n\nfunc fuelText(n int64) string {\n\tif n == vmkit.Unmetered {\n\t\treturn \"unmetered\"\n\t}\n\treturn ufmt.Sprintf(\"%d\", n)\n}\n\nconst hexDigits = \"0123456789abcdef\"\n\n// hexDump shows the image as words, which is how anyone reading RV32 reads it.\nfunc hexDump(b []byte, max int) string {\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor i := 0; i+3 \u003c len(b); i += 4 {\n\t\tif i \u003e 0 \u0026\u0026 i%16 == 0 {\n\t\t\tsb.WriteString(\"\\n\")\n\t\t} else if i \u003e 0 {\n\t\t\tsb.WriteString(\" \")\n\t\t}\n\t\tw := uint32(b[i]) | uint32(b[i+1])\u003c\u003c8 | uint32(b[i+2])\u003c\u003c16 | uint32(b[i+3])\u003c\u003c24\n\t\tsb.WriteString(ufmt.Sprintf(\"%08x\", w))\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"\\n...\")\n\t}\n\treturn sb.String()\n}\n\n// printable renders guest output for a code fence: printable ASCII as itself,\n// everything else as an escape. A guest writes arbitrary bytes, so this is the\n// only form of it that is safe to show.\nfunc printable(b []byte, max int) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor _, c := range b {\n\t\tswitch {\n\t\tcase c == '\\n':\n\t\t\tsb.WriteString(\"\\\\n\")\n\t\tcase c == '\\t':\n\t\t\tsb.WriteString(\"\\\\t\")\n\t\tcase c == '\\\\':\n\t\t\tsb.WriteString(\"\\\\\\\\\")\n\t\tcase c == '`':\n\t\t\tsb.WriteString(\"\\\\x60\")\n\t\tcase c \u003e= 0x20 \u0026\u0026 c \u003c 0x7f:\n\t\t\tsb.WriteByte(c)\n\t\tdefault:\n\t\t\tsb.WriteString(\"\\\\x\")\n\t\t\tsb.WriteByte(hexDigits[c\u003e\u003e4])\n\t\t\tsb.WriteByte(hexDigits[c\u00260x0f])\n\t\t}\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"…\")\n\t}\n\treturn sb.String()\n}\n\n// codeCell puts already-printable text in a code span inside a table cell.\n// Inside backticks markdown escapes are not applied, so ui.Cell's backslashes\n// would reach the reader verbatim (\"Hello, gno\\.land\"); the one character a\n// table cell still needs escaped there is the pipe. printable has already\n// removed the backtick and the newline, the other two that could break out.\nfunc codeCell(s string) string {\n\treturn \"`\" + strings.ReplaceAll(s, \"|\", \"\\\\|\") + \"`\"\n}\n"},{"name":"riscvdemo.gno","body":"// Package riscvdemo runs real compiled machine code on chain, a slice at a\n// time.\n//\n// It is a demo of two libraries and carries no logic of its own:\n// [p/moul/x/vm/riscv](/p/moul/x/vm/riscv/v0) is the RV32IM hart, and\n// [p/moul/x/vm/vmkit](/p/moul/x/vm/vmkit/v0) is the host ABI, the fuel meter\n// and the instance store.\n//\n// What it exists to show is that the guest was not written for gno. The\n// programs on the front page are flat .text images: the same bytes\n// `rustc --target riscv32im-unknown-none-elf` emits, uploaded as hex. The\n// realm holds the snapshot between transactions, so one computation finishes\n// across several of them, and realm code cannot do that for itself.\npackage riscvdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/moul/vendor/nt/ufmt/v2\"\n)\n\n// Caps. Everything a caller can grow is bounded, because all of it is storage\n// somebody pays a deposit on.\nconst (\n\t// MaxInstances is how many programs the realm keeps at once.\n\tMaxInstances = 64\n\t// MaxImage caps an uploaded text segment at 2,048 instructions.\n\t//\n\t// This one is not arbitrary. Predecoding costs about 19,600 gas per word\n\t// and is redone on every resume, so the image size is a tax on every\n\t// transaction that touches the instance, not just the upload. 8 KiB works\n\t// out to roughly 40M gas per slice before the guest executes anything,\n\t// which is about 1% of a block.\n\tMaxImage = 8192\n\t// MaxOutput caps the bytes one program may write. Past it the guest is\n\t// trapped rather than truncated, so rendered output is never a lie.\n\tMaxOutput = 4096\n\t// MaxInput caps the call input a program can be given.\n\tMaxInput = 1024\n\t// DefaultFuel is the budget an upload gets when it asks for none, and the\n\t// slice size Step uses when asked for none.\n\tDefaultFuel = 100000\n\t// MaxSliceFuel bounds one transaction's work regardless of what the\n\t// caller asked for, and it is derived from the measurement rather than\n\t// picked: an RV32IM instruction costs about 8,500 gas, so 100,000 of them\n\t// is about 850M, a little under a third of a 3G block. Twice this would\n\t// still be a legal transaction and a rude one, and it would leave no room\n\t// for the predecode and the realm's own storage writes on top.\n\tMaxSliceFuel = 100000\n)\n\nvar (\n\tstore  = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen  seqid.ID\n\tcount  int\n)\n\n// host is the realm-backed [vmkit.Host]. One is built per call, wrapping the\n// instance being stepped, so a guest's output and authority are scoped to it\n// and nothing ambient leaks in.\ntype host struct {\n\tinst    *vmkit.Instance\n\tin      []byte\n\tkv      *avl.Tree\n\toverrun bool // the guest wrote past MaxOutput\n}\n\nfunc (h *host) Caller() address { return h.inst.Owner }\nfunc (h *host) Origin() address { return h.inst.Owner }\nfunc (h *host) Now() int64      { return time.Now().Unix() }\nfunc (h *host) Height() int64   { return runtime.ChainHeight() }\nfunc (h *host) Input() []byte   { return h.in }\n\n// Get and Set are scoped to the instance by construction: the tree belongs to\n// the instance being stepped, so one program cannot reach another's storage\n// even though both live in this one realm.\nfunc (h *host) Get(key []byte) []byte {\n\tv := h.kv.Get(string(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.([]byte)\n}\n\nfunc (h *host) Set(key, val []byte) { h.kv.Set(string(key), val) }\n\nfunc (h *host) Output(p []byte) {\n\tif len(h.inst.Output)+len(p) \u003e MaxOutput {\n\t\th.overrun = true\n\t\treturn\n\t}\n\th.inst.Output = append(h.inst.Output, p...)\n}\n\nfunc (h *host) Emit(typ string, kv ...string) { chain.Emit(typ, kv...) }\n\n// Send is never granted here. The demo funds no instance, so a guest that\n// tries to move coins is refused. That is the capability rule doing its job,\n// not a missing feature.\nfunc (h *host) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\n\nfunc (h *host) Log(msg string) {}\n\n// Upload stores a hex-encoded text image as a new instance and returns its id.\n//\n// The image is loaded here rather than at the first Step, so a misaligned or\n// oversized one is rejected by the transaction that submitted it instead of\n// costing somebody else the gas later.\nfunc Upload(cur realm, hexImage, input string, budget int64) string {\n\timg, ok := decodeHex(hexImage)\n\tif !ok {\n\t\tpanic(\"riscvdemo: image is not valid hex\")\n\t}\n\treturn upload(img, input, budget)\n}\n\n// UploadSample stores one of the programs the front page offers. Writing RV32IM\n// by hand is not the point of this realm, and without this nobody without a\n// cross compiler could press a button.\nfunc UploadSample(cur realm, name, input string, budget int64) string {\n\ts := sampleByName(name)\n\tif s == nil {\n\t\tpanic(\"riscvdemo: no such sample\")\n\t}\n\t// A sample carries its own budget because the default is a total, not a\n\t// slice: the heavy loop needs 200,006 instructions, and offering a button\n\t// that runs out of fuel halfway is a worse demo than no button.\n\tif budget \u003c= 0 {\n\t\tbudget = s.budget\n\t}\n\treturn upload(s.image(), input, budget)\n}\n\nfunc upload(img []byte, input string, budget int64) string {\n\tif count \u003e= MaxInstances {\n\t\tpanic(\"riscvdemo: too many instances, remove one first\")\n\t}\n\tif len(input) \u003e MaxInput {\n\t\tpanic(\"riscvdemo: input too long\")\n\t}\n\tif len(img) == 0 {\n\t\tpanic(\"riscvdemo: empty image\")\n\t}\n\tif len(img) \u003e MaxImage {\n\t\tpanic(\"riscvdemo: image too large\")\n\t}\n\t// Loading it now is the validation: NewMachine is what rejects an image\n\t// that is not a whole number of instructions.\n\tif _, err := riscv.NewMachine(img, riscv.DefaultEntry); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif budget \u003c= 0 {\n\t\tbudget = DefaultFuel\n\t}\n\n\tid := idgen.Next().String()\n\towner := unsafe.PreviousRealm().Address()\n\tstore.Set(vmkit.NewInstance(id, owner, riscv.VMName, img, budget))\n\tif input != \"\" {\n\t\tinputs.Set(id, input)\n\t}\n\tcount++\n\n\tchain.Emit(\"riscv_upload\", \"id\", id, \"bytes\", ufmt.Sprintf(\"%d\", len(img)))\n\treturn id\n}\n\n// Step runs one slice of the instance: up to `fuel` guest instructions, then\n// stop and keep the snapshot. Anyone may pay for a slice, not only the owner:\n// a paused program that only its owner can advance is a worse demo and no\n// safer, since the program and its budget were both fixed at upload.\nfunc Step(cur realm, id string, fuel int64) string {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Status != vmkit.Running {\n\t\tpanic(\"riscvdemo: instance is \" + inst.Status.String())\n\t}\n\tif fuel \u003c= 0 {\n\t\tfuel = DefaultFuel\n\t}\n\tif fuel \u003e MaxSliceFuel {\n\t\tfuel = MaxSliceFuel\n\t}\n\n\tm, err := riscv.NewMachine(inst.Program, riscv.DefaultEntry)\n\tif err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\th := \u0026host{inst: inst, in: []byte(inputOf(id)), kv: avl.NewTree()}\n\tif err := inst.Run(m, h, fuel); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif h.overrun {\n\t\tinst.Status = vmkit.Trapped\n\t\tinst.Trap = \"output limit reached\"\n\t}\n\n\tchain.Emit(\"riscv_step\",\n\t\t\"id\", id,\n\t\t\"status\", inst.Status.String(),\n\t\t\"fuel\", ufmt.Sprintf(\"%d\", inst.FuelUsed),\n\t)\n\treturn inst.Status.String()\n}\n\n// Remove deletes an instance. Owner only.\nfunc Remove(cur realm, id string) {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Owner != unsafe.PreviousRealm().Address() {\n\t\tpanic(\"riscvdemo: not your instance\")\n\t}\n\tstore.Remove(id)\n\tinputs.Remove(id)\n\tcount--\n}\n\nfunc inputOf(id string) string {\n\tv := inputs.Get(id)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n\n// decodeHex accepts the output of any hexdump: an even number of hex digits,\n// with an optional 0x prefix, and whitespace anywhere. Whitespace is allowed\n// because that is what a pasted hexdump has in it; anything else is refused,\n// because a silently mangled image would trap somewhere unrelated later.\nfunc decodeHex(s string) ([]byte, bool) {\n\tif len(s) \u003e= 2 \u0026\u0026 s[0] == '0' \u0026\u0026 (s[1] == 'x' || s[1] == 'X') {\n\t\ts = s[2:]\n\t}\n\tdigits := make([]byte, 0, len(s))\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == ' ' || c == '\\t' || c == '\\n' || c == '\\r' {\n\t\t\tcontinue\n\t\t}\n\t\tv, ok := hexVal(c)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tdigits = append(digits, v)\n\t}\n\tif len(digits) == 0 || len(digits)%2 != 0 {\n\t\treturn nil, false\n\t}\n\tout := make([]byte, len(digits)/2)\n\tfor i := 0; i \u003c len(out); i++ {\n\t\tout[i] = digits[i*2]\u003c\u003c4 | digits[i*2+1]\n\t}\n\treturn out, true\n}\n\nfunc hexVal(c byte) (byte, bool) {\n\tswitch {\n\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn c - '0', true\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'f':\n\t\treturn c - 'a' + 10, true\n\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'F':\n\t\treturn c - 'A' + 10, true\n\t}\n\treturn 0, false\n}\n"},{"name":"riscvdemo_test.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// resetState puts the realm globals back where init() left them. Realm state\n// persists for the whole test binary, so every test that asserts on ids or on\n// the rendered instance list has to start from here.\nfunc resetState() {\n\tstore = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen = seqid.ID(0)\n\tcount = 0\n}\n\nfunc alice() address { return testutils.TestAddress(\"alice\") }\n\nfunc TestUploadAndRunToCompletion(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"hello\", \"\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"Hello, gno.land\\n\", string(inst.Output))\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, alice(), inst.Owner)\n\tuassert.Equal(t, \"riscv32im\", inst.VM)\n}\n\n// Every sample on the front page has to reach its documented answer, or the\n// page offers a button that traps when pressed. The words are assembled\n// outside this repo, so this is the test that catches a mistyped one.\nfunc TestEverySampleReachesItsAnswer(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tcases := []struct {\n\t\tslug   string\n\t\treg    int\n\t\twant   uint32\n\t\toutput string\n\t}{\n\t\t{\"hello\", 0, 0, \"Hello, gno.land\\n\"},\n\t\t{\"sum100\", 5, 5050, \"\"},\n\t\t{\"heavy\", 5, 1250025000, \"\"},\n\t\t{\"mext\", 5, 3000000021, \"\"},\n\t\t{\"clang\", 0, 0, \"fb7ffba0\"},\n\t\t{\"ledger\", 0, 0, \"alice 70\\nbob 80\\n\"},\n\t}\n\tfor _, c := range cases {\n\t\tid := UploadSample(cross(cur), c.slug, sampleByName(c.slug).input, 0)\n\t\tstatus := \"\"\n\t\tfor i := 0; i \u003c 20; i++ {\n\t\t\tstatus = Step(cross(cur), id, 0)\n\t\t\tif status != \"running\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tuassert.Equal(t, \"halted\", status, c.slug+\" must halt\")\n\t\tinst := store.Get(id)\n\t\tuassert.Equal(t, c.output, string(inst.Output), c.slug+\" output\")\n\t\tif c.reg != 0 {\n\t\t\tvar m riscv.Machine\n\t\t\tuassert.NoError(t, m.Restore(inst.Snapshot))\n\t\t\tuassert.Equal(t, uint64(c.want), uint64(m.Registers()[c.reg]), c.slug+\" result\")\n\t\t}\n\t}\n}\n\n// TestOneProgramAcrossManyTransactions is what the realm exists to\n// demonstrate: the same computation, finished over several calls, each paying\n// for its own slice.\nfunc TestOneProgramAcrossManyTransactions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"heavy\", \"\", 0)\n\tstatus := \"\"\n\tfor i := 0; i \u003c 50; i++ {\n\t\tstatus = Step(cross(cur), id, 80000)\n\t\tif status != \"running\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"halted\", status)\n\tuassert.True(t, inst.Slices \u003e 1, \"a 200k instruction program must not finish in one slice\")\n\tuassert.Equal(t, int64(200006), inst.FuelUsed)\n}\n\nfunc TestUploadTakesHex(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// addi a7, zero, 93 ; ecall\n\tid := Upload(cross(cur), \"0x9308d005 73000000\", \"\", 0)\n\t_ = id\n}\n\nfunc TestUploadRejectsBadImages(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// Called without cross(): a panic raised through a crossing call cannot be\n\t// recovered, so uassert would never see it.\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"zzzz\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"abc\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: no such sample\", func() {\n\t\tUploadSample(cur, \"nope\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"riscvdemo: riscv: image length is not a whole number of instructions\",\n\t\tfunc() { Upload(cur, \"0011\", \"\", 0) })\n}\n\nfunc TestDecodeHex(t *testing.T) {\n\tb, ok := decodeHex(\"0xDEADbeef\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\tuassert.Equal(t, uint64(0xDE), uint64(b[0]))\n\tuassert.Equal(t, uint64(0xEF), uint64(b[3]))\n\n\t_, ok = decodeHex(\"\")\n\tuassert.False(t, ok)\n\t_, ok = decodeHex(\"0x\")\n\tuassert.False(t, ok)\n\t// Whitespace is skipped, because a pasted hexdump has it.\n\tb, ok = decodeHex(\"00 11\\n22\\t33\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\t// An odd number of digits is still a refusal, whitespace or not.\n\t_, ok = decodeHex(\"00 1\")\n\tuassert.False(t, ok)\n}\n\nfunc TestRenderHomeOffersEverySample(cur realm, t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"RV32IM, on chain\"), \"the title\")\n\tfor _, s := range samples {\n\t\tuassert.True(t, strings.Contains(out, s.name), \"home must offer \"+s.slug)\n\t}\n\tuassert.True(t, strings.Contains(out, \"No instances yet\"), \"the empty state\")\n}\n\n// The register file is the interesting half of this VM: a program that writes\n// nothing still computed something, and the snapshot is the only place it is\n// legible between transactions.\nfunc TestRenderInstanceShowsTheRegisterFile(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"sum100\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"/\" + id)\n\tuassert.True(t, strings.Contains(out, \"## Registers\"), \"the section\")\n\tuassert.True(t, strings.Contains(out, \"5050\"), \"t0 must show the answer\")\n\tuassert.True(t, strings.Contains(out, \"halted\"), \"the status\")\n}\n\n// The instance page is all hex: the pc, every register, the image dump.\n// gno.land/p/nt/ufmt/v0 has no %X and no width flags, so this page shipped\n// printing \"0x(unhandled verb: %X)\" in every cell; the test pins the fix.\nfunc TestRenderInstanceHex(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// addi a7, zero, 93 ; ecall (exit)\n\tid := Upload(cross(cur), \"0x9308d005 73000000\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"/\" + id)\n\tuassert.False(t, strings.Contains(out, \"unhandled\"), out)\n\tuassert.True(t, strings.Contains(out, \"| a7 | 0x0000005D | 93 | 93 |\"), out)\n\tuassert.True(t, strings.Contains(out, \"05d00893 00000073\"), out)\n}\n\n// The instance list shows output in a code span, where markdown escapes do\n// not apply: ui.Cell's backslashes used to reach the reader as\n// `Hello, gno\\.land\\\\n`. Only the pipe needs escaping inside the span.\nfunc TestRenderOutputCell(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"hello\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"| `Hello, gno.land\\\\n` |\"), out)\n\tuassert.Equal(t, \"`a\\\\|b`\", codeCell(\"a|b\"))\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tuassert.True(t, strings.Contains(Render(\"/nope\"), \"No such instance\"))\n}\n\n// ExampleRender pins the realm's output for a path whose content cannot drift\n// with the instance list. The home page and the instance page both produce\n// consecutive blank lines, which an example block cannot represent, so they\n// are asserted in the tests above instead.\nfunc ExampleRender() {\n\tprint(Render(\"/missing\"))\n\t// Output:\n\t// # Instance missing\n\t//\n\t// [← all instances](/r/moul/x/vm/riscvdemo/v0)\n\t//\n\t// **No such instance.** It was never uploaded, or its owner removed it.\n}\n"},{"name":"samples.gno","body":"package riscvdemo\n\nimport \"gno.land/p/moul/x/vm/riscv/v0\"\n\n// The programs the front page offers, as the machine words a cross compiler\n// would have emitted. They are assembled outside this repo and pinned here,\n// and riscvdemo_test.gno runs every one of them to the expected answer, so a\n// wrong word is a failing test rather than a page that traps when clicked.\ntype sample struct {\n\tslug   string // what UploadSample takes: short, no punctuation, stable\n\tname   string\n\tbudget int64 // the instance's total instruction budget, not the slice\n\n\t// builtin names an image the library ships compiled, instead of the words\n\t// below. Empty means the words are the program.\n\tbuiltin string\n\twords []uint32\n\tinput string\n\tnote  string\n\tasm   string\n}\n\nvar samples = []sample{\n\t{\n\t\tslug: \"hello\",\n\t\tname: \"Hello, gno.land\",\n\t\twords: []uint32{\n\t\t\t0x00100513, 0x000015B7, 0x02058593, 0x01000613,\n\t\t\t0x04000893, 0x00000073, 0x05D00893, 0x00000073,\n\t\t\t0x6C6C6548, 0x67202C6F, 0x6C2E6F6E, 0x0A646E61,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"Eight instructions and a string constant. The write syscall reads \" +\n\t\t\t\"the bytes straight out of the text segment and hands them to Host.Output.\",\n\t\tasm: `addi a0, zero, 1          # fd\nlui  a1, 0x1000           # buf\naddi a1, a1, 0x20\naddi a2, zero, 16         # len\naddi a7, zero, 64         # write\necall\naddi a7, zero, 93         # exit\necall\n.ascii \"Hello, gno.land\\n\"`,\n\t},\n\t{\n\t\tslug: \"sum100\",\n\t\tname: \"Sum 1 to 100\",\n\t\twords: []uint32{\n\t\t\t0x06400413, 0x00000293, 0x00000313, 0x00130313,\n\t\t\t0x006282B3, 0xFE831CE3, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"A real loop, 303 instructions. Writes nothing: the answer is in t0, \" +\n\t\t\t\"and the instance page shows the register file.\",\n\t\tasm: `addi s0, zero, 100\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"heavy\",\n\t\tname: \"Heavy loop\",\n\t\twords: []uint32{\n\t\t\t0x0000C437, 0x35040413, 0x00000293, 0x00000313,\n\t\t\t0x00130313, 0x006282B3, 0x00000393, 0xFE831AE3,\n\t\t\t0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 250000,\n\t\tnote: \"200,006 instructions, four per iteration. At the largest slice this realm \" +\n\t\t\t\"allows it takes three transactions to finish, which is the thing it exists to show.\",\n\t\tasm: `lui  s0, 0xc000           # s0 = 50000\naddi s0, s0, 0x350\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\naddi t2, zero, 0\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"mext\",\n\t\tname: \"Multiply and divide\",\n\t\twords: []uint32{\n\t\t\t0x3B9AD2B7, 0xA0728293, 0x00300313, 0x026282B3,\n\t\t\t0x00700393, 0x0272D333, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"The M extension. t0 = 1000000007 * 3 truncated to 32 bits, then t1 = t0 / 7. \" +\n\t\t\t\"Division by zero and the one signed overflow case return values here \" +\n\t\t\t\"rather than trapping, which is what the spec says and what a chain needs.\",\n\t\tasm: `lui  t0, 0x3b9ad000       # t0 = 1000000007\naddi t0, t0, -1529\naddi t1, zero, 3\nmul  t0, t0, t1\naddi t2, zero, 7\ndivu t1, t0, t2\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug:   \"clang\",\n\t\tname:   \"Compiled by clang\",\n\t\tinput:  \"gno.land\",\n\t\tbudget: 20000,\n\t\tnote: \"Not written for gno and not written by hand: a freestanding C program, \" +\n\t\t\t\"compiled by clang for riscv32im and shipped as the bytes LLVM emitted. It reads \" +\n\t\t\t\"the call input, hashes it with FNV-1a and writes eight hex digits back. \" +\n\t\t\t\"With the default input it prints fb7ffba0. Source and build command: \" +\n\t\t\t\"tools/riscv-guests/fnv.\",\n\t\tbuiltin: \"fnv\",\n\t\tasm: `long n = syscall3(SYS_READ, 0, (long)in, sizeof(in));\n\nunsigned int h = 2166136261u;\nfor (long i = 0; i \u003c n; i++) {\n\th ^= in[i];\n\th *= 16777619u;      /* the reason this is rv32im */\n}\n\nfor (int i = 0; i \u003c 8; i++) {\n\tunsigned int nib = (h \u003e\u003e (28 - i * 4)) \u0026 0xF;\n\tout[i] = nib \u003c 10 ? '0' + nib : 'a' + (nib - 10);\n}\n\nsyscall3(SYS_WRITE, 1, (long)out, 8);\nsyscall3(SYS_EXIT, 0, 0, 0);`,\n\t},\n\t{\n\t\tslug:   \"ledger\",\n\t\tname:   \"A token, in Rust\",\n\t\tinput:  \"mint alice 100\\nmint bob 50\\nsend alice bob 30\\n\",\n\t\tbudget: 20000,\n\t\tnote: \"no_std Rust, compiled by rustc for riscv32im: mint, send and burn, applied \" +\n\t\t\t\"from the call input. It links Rust's real core and compiler_builtins, so the \" +\n\t\t\t\"balances being 64-bit means a divide runs __udivdi3 here, because RV32 has no \" +\n\t\t\t\"64-bit divide instruction. With the default input it prints alice 70 and bob 80. \" +\n\t\t\t\"Source: tools/riscv-guests/ledger.\",\n\t\tbuiltin: \"ledger\",\n\t\tasm: `match cmd {\n\tb\"send\" =\u003e {\n\t\tlet (from, rest) = field(rest);\n\t\tlet (to, rest) = field(rest);\n\t\tlet (amount, _) = field(rest);\n\t\tlet n = parse_u32(amount).ok_or(\"bad amount\")?;\n\t\tlet fi = led.find(from).ok_or(\"unknown sender\")?;\n\t\tif led.balances[fi] \u003c n {\n\t\t\treturn Err(\"insufficient balance\");\n\t\t}\n\t\tlet ti = led.intern(to).ok_or(\"ledger full or bad name\")?;\n\t\tled.balances[fi] -= n;\n\t\tled.balances[ti] += n;\n\t\tOk(())\n\t}\n\t_ =\u003e Err(\"unknown command\"),\n}`,\n\t},\n}\n\n// image is what gets uploaded: either the words assembled here, or a program\n// the library ships because a compiler produced it.\nfunc (s *sample) image() []byte {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn riscv.GuestFNV()\n\tcase \"ledger\":\n\t\treturn riscv.GuestLedger()\n\t}\n\treturn riscv.Image(s.words)\n}\n\n// lang is the fence tag for what the sample shows. The compiled guest shows\n// its C, because showing a disassembly of what LLVM did with it would bury the\n// only interesting fact: nobody wrote the machine code.\nfunc (s *sample) lang() string {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn \"c\"\n\tcase \"ledger\":\n\t\treturn \"rust\"\n\t}\n\treturn \"asm\"\n}\n\nfunc sampleByName(slug string) *sample {\n\tfor i := range samples {\n\t\tif samples[i].slug == slug {\n\t\t\treturn \u0026samples[i]\n\t\t}\n\t}\n\treturn nil\n}\n"}]},"send":"","max_deposit":"14000000ugnot"}],"fee":{"gas_wanted":"170200600","gas_fee":"510601ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"dDFXzU0eTkGLY9YajP0UFcnUL+fn22DRdbP4h/KsocAJXiHIstgjydT0LjUofYM7Qil7Z8+7S6e4zPnzC/fGzQ=="}],"memo":""},"metadata":{"timestamp":"1791217510"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1857727","gas_fee":"3716ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"I0LtEVsfycKPCMxJKEGmU0NsDYmRl1F23PqTDsOUMVp2CtGAYgva6KcILBWcExF2zYEPbDNcfVn5eAlKMhnU2A=="}],"memo":""},"metadata":{"timestamp":"1791217514"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"uuLm2PWdngvf3r4AyqeQChXfs3+931JB9TuWk3uWbOlo/nPkRFdcgKGv4D015WxUJWLpqi/T5ncZo0+9UFSbvg=="}],"memo":""},"metadata":{"timestamp":"1791257436"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"5JphwK3Jj1bZdVngMHyTgw2Dq5vPDia5vrn4P2xe9RMTnQRNE+LATZtfd3Cv6cKeNT3urhDF1h+u3NS429dYbg=="}],"memo":""},"metadata":{"timestamp":"1791257498"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"0WGlBnMqhZdNU6ErK8fmaumBCEPREBOROe8Yw2lVjLA/lwlQaEHawzvl4ZFZQjHOSg+pfbFAjL6hVTSpTpBz5A=="}],"memo":""},"metadata":{"timestamp":"1791257560"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1399677","gas_fee":"2800ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"yDU9JkHnRCRqwsWBPlYzVY7d1qKFpaX7SnwwnbNpl3Eeqqzproe+jZPJ7ASOH2bx5hU+dfCIGHu4v/Gy/naIkQ=="}],"memo":""},"metadata":{"timestamp":"1791257622"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"coin","path":"gno.land/p/moul/x/social/coin/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/social/coin/v0`\n\n**A GRC20 that refuses to exist until its mint rule, its sink and its buyer are\nwritten down**: `New`, `Earn`, `Spend`, `Supply`, `Earned`, `Spent`, `Render`.\n\n```go\nimport \"gno.land/p/moul/x/social/coin/v0\"\n\nvar points = coin.New(\"Thread Points\", \"THREAD\", 0, 0, coin.Policy{\n\tMint:  \"1 per distinct address that replies to your thread\",\n\tSink:  \"burned to pin a thread to the top of its page\",\n\tBuyer: \"anyone who wants placement and has not earned it\",\n}, 0, cur)\n\npoints.Earn(author, 1)   // the mint rule, with exactly one call site\npoints.Spend(buyer, 10)  // the sink, which is the only thing that removes supply\n```\n\nThe three strings are the whole point. `New` panics on a blank one, so the\ndeclaration happens before the first unit exists rather than in a README written\nafterwards, and `Render` prints all three on the issuing realm's own page, where\nbeing wrong about them is visible to the people holding the token.\n\n**A mint rule with no sink is a scoreboard with a price.** Supply only grows, the\nnumber is the product, and a holder has no reason to buy one from an earner.\nNothing in a package can check that a declared sink is real, which is exactly why\nit is a declaration and not a validation: the cheap failure is forgetting to\ndecide, not lying.\n\n`Earned` and `Spent` are kept separately from the supply because a sink that\nnever fires is invisible in the supply alone. A flat line reads the same as no\nsink at all; two counters say which it is.\n\n`Earn` of a non-positive amount is a no-op rather than an abort. A mint rule that\ncomputes zero means nothing new happened, and that should not fail the\ntransaction that discovered it. `Spend` is the opposite and aborts naming both\nnumbers, because its caller is a user about to be told they cannot afford\nsomething.\n\nEverything else is the embedded [`p/nt/grc20`](https://gno.land/p/nt/grc20/v0):\ntransfers, approvals, balances and events are an ordinary GRC20, so wallets and\nindexers need to know nothing about this package. `Token()` hands it over for the\nrealm to expose and to register with a token registry.\n\nThe trailing `_ int, rlm realm` on `New` is the shape a pure package has to use\nto reach the caller's frame: a `p/` may not declare a crossing function, so the\nrealm token is threaded as a later parameter, exactly as grc20's own tellers do.\n\n**Live user:** [`r/moul/x/social/threads`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/social/threads).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/social/coin/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/social/coin/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"coin.gno","body":"// Package coin is a GRC20 that cannot exist until its author has answered the\n// three questions a social app's token usually dodges: what mints it, what\n// burns it, and who has a reason to buy it.\n//\n// # Why a package and not a convention\n//\n// Every app in the x/social family is asked the same question, \"and can it\n// have a token\", and the honest answer is only yes when all three of those\n// have an answer. A token with a mint rule and no sink is a scoreboard with a\n// price: supply grows, nothing consumes it, and the number on the leaderboard\n// is the whole product. That is the shape a chain-wide measurement keeps\n// finding, and it is cheap to avoid, so [New] refuses a [Policy] with a blank\n// field rather than letting the omission ship.\n//\n// The three strings are not validated beyond being non-empty, because no\n// package can check that a sink is real. They are a declaration, rendered on\n// the realm's own page by [Coin.Render], where being wrong is visible.\n//\n// # The model\n//\n//\tearned  minted by the app, for the behaviour the app wants more of\n//\tspent   burned by the app, for the thing holders actually want\n//\ttraded  a plain GRC20 transfer, which is what makes the sink a market\n//\n// Earning and spending are the app's business and go through [Coin.Earn] and\n// [Coin.Spend], which keep running totals so a reader can see the two halves\n// against each other. Transfers, approvals and balances are the embedded\n// [grc20.Token]'s, unchanged, so wallets and indexers see an ordinary GRC20.\n//\n// # Usage\n//\n// A realm holds one Coin and never exports the ledger:\n//\n//\tvar points = coin.New(\"Thread Points\", \"THREAD\", 0, 0, coin.Policy{\n//\t\tMint:  \"1 per distinct address that replies to your thread\",\n//\t\tSink:  \"burned to pin a thread to the top of its page\",\n//\t\tBuyer: \"anyone who wants placement and has not earned it\",\n//\t}, 0, cur)\n//\n// The trailing `_ int, rlm realm` is the shape a pure package has to use to\n// reach the caller's frame: a p/ package may not declare a crossing function,\n// so the realm token is threaded as a later parameter, exactly as grc20's own\n// tellers do.\npackage coin\n\nimport (\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/grc20/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Policy is the three declarations a Coin cannot be created without.\n//\n// Each one is a sentence for a human: it is rendered on the issuing realm's\n// page and nothing branches on it.\ntype Policy struct {\n\t// Mint says what behaviour earns the token, precisely enough that a\n\t// reader can work out whether they can farm it.\n\tMint string\n\n\t// Sink says what destroys it. \"Nothing\" is not an answer; if there is\n\t// no sink, there is no reason for the token to exist.\n\tSink string\n\n\t// Buyer says who wants it badly enough to acquire it from someone who\n\t// earned it. This is the one most often left blank, and the one that\n\t// decides whether the other two matter.\n\tBuyer string\n}\n\n// Valid reports whether every field is filled in.\nfunc (p Policy) Valid() bool {\n\treturn p.Mint != \"\" \u0026\u0026 p.Sink != \"\" \u0026\u0026 p.Buyer != \"\"\n}\n\n// Coin is a GRC20 plus the policy it was issued under and the running totals\n// of the two flows the policy describes.\ntype Coin struct {\n\ttok    *grc20.Token\n\tled    *grc20.PrivateLedger\n\tpolicy Policy\n\n\tearned int64 // cumulative minted\n\tspent  int64 // cumulative burned\n}\n\n// New issues the token. It panics when the policy is incomplete, which is the\n// whole point of the package: the declaration happens before the first unit\n// exists, not in a README written afterwards.\n//\n// name, symbol, decimals and id are grc20's own; id distinguishes two tokens\n// issued by the same realm.\nfunc New(name, symbol string, decimals int, id seqid.ID, policy Policy, _ int, rlm realm) *Coin {\n\tif !policy.Valid() {\n\t\tpanic(\"coin: a token needs a mint rule, a sink and a buyer; one of the three is empty\")\n\t}\n\ttok, led := grc20.NewToken(name, symbol, decimals, id, rlm)\n\treturn \u0026Coin{tok: tok, led: led, policy: policy}\n}\n\n// Token returns the GRC20 itself, for the realm to expose as its read API and\n// to register with a token registry.\nfunc (c *Coin) Token() *grc20.Token { return c.tok }\n\n// CallerTeller is the teller that acts as the user who called the realm: it\n// moves their own balance and nothing else.\n//\n// It is exposed, where the ledger is not, because transfer and approve are\n// what make the sink a market. Mint and burn stay behind [Coin.Earn] and\n// [Coin.Spend] so the mint rule keeps exactly one call site.\nfunc (c *Coin) CallerTeller() grc20.Teller { return c.led.CallerTeller() }\n\n// Policy returns the declarations the token was issued under.\nfunc (c *Coin) Policy() Policy { return c.policy }\n\n// Earn mints amount to addr. The realm calls it from the one place its mint\n// rule is implemented, so that rule has exactly one call site.\n//\n// A non-positive amount is a no-op rather than an abort: a mint rule that\n// computes zero (nothing new happened) is a normal outcome and should not\n// fail the transaction that discovered it.\nfunc (c *Coin) Earn(to address, amount int64) {\n\tif amount \u003c= 0 {\n\t\treturn\n\t}\n\tif err := c.led.Mint(to, amount); err != nil {\n\t\tpanic(\"coin: mint: \" + err.Error())\n\t}\n\tc.earned += amount\n}\n\n// Spend burns amount from addr, which is how the sink consumes supply.\n//\n// It aborts when the balance is short, naming both numbers, because the\n// caller is a user who is about to be told they cannot afford something.\nfunc (c *Coin) Spend(from address, amount int64) {\n\tif amount \u003c= 0 {\n\t\tpanic(\"coin: spend: amount must be positive\")\n\t}\n\tif bal := c.tok.BalanceOf(from); bal \u003c amount {\n\t\tpanic(ufmt.Sprintf(\"coin: balance %d is short of %d %s\", bal, amount, c.tok.GetSymbol()))\n\t}\n\tif err := c.led.Burn(from, amount); err != nil {\n\t\tpanic(\"coin: burn: \" + err.Error())\n\t}\n\tc.spent += amount\n}\n\n// BalanceOf is the holder's balance.\nfunc (c *Coin) BalanceOf(addr address) int64 { return c.tok.BalanceOf(addr) }\n\n// Supply is what exists right now, that is, earned minus spent.\nfunc (c *Coin) Supply() int64 { return c.tok.TotalSupply() }\n\n// Earned and Spent are the cumulative flows. Their difference is [Coin.Supply]\n// and they are kept separately because a sink that never fires is invisible in\n// the supply alone: a flat line reads the same as no sink at all.\nfunc (c *Coin) Earned() int64 { return c.earned }\n\n// Spent is the cumulative amount burned through [Coin.Spend].\nfunc (c *Coin) Spent() int64 { return c.spent }\n\n// Holders is how many addresses the ledger knows about.\nfunc (c *Coin) Holders() int { return c.tok.KnownAccounts() }\n\n// Render is the block a realm puts on its own page: the three declarations,\n// then the two flows against each other.\n//\n// The policy strings are escaped: they are constants in practice, but a realm\n// could build one from configuration, and this package cannot tell.\nfunc (c *Coin) Render() string {\n\tout := md.H3(ui.Inline(c.tok.GetName()) + \" (\" + ui.Inline(c.tok.GetSymbol()) + \")\")\n\n\tt := ui.NewTable(\"\", \"\")\n\tt.Row(\"earns\", ui.Cell(c.policy.Mint))\n\tt.Row(\"burns\", ui.Cell(c.policy.Sink))\n\tt.Row(\"bought by\", ui.Cell(c.policy.Buyer))\n\tout += t.String()\n\n\ts := ui.NewTable(\"supply\", \"earned\", \"burned\", \"holders\")\n\ts.Row(\n\t\tnum.Dec(c.Supply(), c.tok.GetDecimals()),\n\t\tnum.Dec(c.earned, c.tok.GetDecimals()),\n\t\tnum.Dec(c.spent, c.tok.GetDecimals()),\n\t\tufmt.Sprintf(\"%d\", c.Holders()),\n\t)\n\tout += s.String()\n\n\treturn out\n}\n"},{"name":"coin_test.gno","body":"package coin\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar fullPolicy = Policy{\n\tMint:  \"1 per distinct replier\",\n\tSink:  \"burned to pin a thread\",\n\tBuyer: \"anyone who wants placement\",\n}\n\n// newTestCoin builds a Coin from a test. The same-realm cross promotes the\n// test's EOA-origin cur into a code realm frame, which is what grc20.NewToken\n// requires: it is the shape grc20's own tests use (vendor/.../token_test.gno).\nfunc newTestCoin(t *testing.T, policy Policy, id seqid.ID, rlm realm) (c *Coin) {\n\tt.Helper()\n\tfunc(cur realm) {\n\t\tc = New(\"Test Points\", \"TEST\", 0, id, policy, 0, cur)\n\t}(cross(rlm))\n\treturn\n}\n\nfunc TestPolicyValid(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tp    Policy\n\t\twant bool\n\t}{\n\t\t{\"complete\", fullPolicy, true},\n\t\t{\"no mint rule\", Policy{Sink: \"s\", Buyer: \"b\"}, false},\n\t\t{\"no sink\", Policy{Mint: \"m\", Buyer: \"b\"}, false},\n\t\t{\"no buyer\", Policy{Mint: \"m\", Sink: \"s\"}, false},\n\t\t{\"empty\", Policy{}, false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, tt.p.Valid(), tt.name)\n\t}\n}\n\n// New's refusal is asserted with AbortsContains and not PanicsContains: the\n// constructor runs behind a same-realm cross (the frame grc20.NewToken\n// requires), and a panic raised across a crossing call is an abort that no\n// recover() in the caller can catch.\nfunc TestNewRefusesAnIncompletePolicy(cur realm, t *testing.T) {\n\tuassert.AbortsContains(t, cur, \"mint rule, a sink and a buyer\", func() {\n\t\tnewTestCoin(t, Policy{Mint: \"m\", Sink: \"s\"}, 0, cur)\n\t})\n}\n\nfunc TestEarnAndSpendMoveSupplyInOppositeDirections(cur realm, t *testing.T) {\n\tc := newTestCoin(t, fullPolicy, 1, cur)\n\talice := testutils.TestAddress(\"alice\")\n\n\tc.Earn(alice, 10)\n\tuassert.Equal(t, int64(10), c.BalanceOf(alice))\n\tuassert.Equal(t, int64(10), c.Supply())\n\n\tc.Spend(alice, 4)\n\tuassert.Equal(t, int64(6), c.BalanceOf(alice))\n\tuassert.Equal(t, int64(6), c.Supply())\n\n\t// The flows stay visible after the fact, which the supply alone cannot\n\t// show: 6 in supply could be 6 earned and nothing burned.\n\tuassert.Equal(t, int64(10), c.Earned())\n\tuassert.Equal(t, int64(4), c.Spent())\n}\n\nfunc TestEarnOfNothingIsANoOp(cur realm, t *testing.T) {\n\tc := newTestCoin(t, fullPolicy, 2, cur)\n\talice := testutils.TestAddress(\"alice\")\n\n\tc.Earn(alice, 0)\n\tc.Earn(alice, -5)\n\tuassert.Equal(t, int64(0), c.Supply())\n\tuassert.Equal(t, int64(0), c.Earned())\n\tuassert.Equal(t, 0, c.Holders())\n}\n\nfunc TestSpendNamesBothNumbersWhenShort(cur realm, t *testing.T) {\n\tc := newTestCoin(t, fullPolicy, 3, cur)\n\talice := testutils.TestAddress(\"alice\")\n\tc.Earn(alice, 2)\n\n\tuassert.PanicsContains(t, cur, \"balance 2 is short of 5\", func() {\n\t\tc.Spend(alice, 5)\n\t})\n\tuassert.PanicsContains(t, cur, \"must be positive\", func() {\n\t\tc.Spend(alice, 0)\n\t})\n\tuassert.Equal(t, int64(2), c.BalanceOf(alice))\n}\n\nfunc TestRenderCarriesTheThreeDeclarations(cur realm, t *testing.T) {\n\tc := newTestCoin(t, fullPolicy, 4, cur)\n\tc.Earn(testutils.TestAddress(\"alice\"), 7)\n\tc.Spend(testutils.TestAddress(\"alice\"), 3)\n\n\tout := c.Render()\n\tfor _, want := range []string{\n\t\t\"Test Points\",\n\t\t\"TEST\",\n\t\tfullPolicy.Mint,\n\t\tfullPolicy.Sink,\n\t\tfullPolicy.Buyer,\n\t} {\n\t\tuassert.True(t, strings.Contains(out, want), \"render is missing \"+want)\n\t}\n\t// 4 in supply, 7 earned, 3 burned, 1 holder.\n\tuassert.True(t, strings.Contains(out, \"| 4 | 7 | 3 | 1 |\"), \"render is missing the flow row: \"+out)\n}\n\nfunc TestTokenIsAnOrdinaryGRC20(cur realm, t *testing.T) {\n\tc := newTestCoin(t, fullPolicy, 5, cur)\n\talice := testutils.TestAddress(\"alice\")\n\tc.Earn(alice, 3)\n\n\ttok := c.Token()\n\turequire.False(t, tok == nil, \"token should not be nil\")\n\tuassert.Equal(t, \"TEST\", tok.GetSymbol())\n\tuassert.Equal(t, int64(3), tok.TotalSupply())\n\tuassert.Equal(t, int64(3), tok.BalanceOf(alice))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/social/coin/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"6000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"crew","path":"gno.land/p/moul/x/social/crew/v0","files":[{"name":"README.md","body":"# crew\n\nSmall-group coordination as a product rather than as a framework: three to\nfifteen people with a shared pot, a way to decide, and a way to leave with their\nshare. The pure engine behind\n[`r/moul/x/social/crews`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/social/crews), which is the chain wiring.\n\nThe targets are real and already exist: a validator set, a working group, a\nhackathon team, a five-person company. `p/moul/grants` and daokit are the\nframework layer; this is the thing you can create in one transaction.\n\n## The API\n\n```go\ncs := crew.New()\n\nid, err := cs.Create(\"validators\", founder, amount, height)  // founder gets amount/InitialPricePerShare shares\nshares, err := cs.Join(id, who, amount)                      // minted at the CURRENT per-share value\nerr := cs.Fund(id, amount)                                   // mints nothing, every share is worth more\npid, err := cs.Propose(id, who, \"ship v1\", height)           // any member, open for VoteBlocks\nerr := cs.Vote(pid, who, true, height)                       // weighted by shares held right now\npassed, err := cs.Close(pid, height)                         // anyone, after the deadline\nshares, amount, err := cs.Ragequit(id, who)                  // burn the shares, be credited the slice\namount, err := cs.Withdraw(who)                              // collect, zeroed before it returns\n```\n\nReads: `Get`, `Proposal`, `Len`, `ProposalCount`, `List`, `CreditOf`,\n`TotalOwed`, and on a `*Crew`: `SharesOf`, `IsMember`, `MemberCount`, `Members`,\n`Proposals`, `ValuePerShare`, `PricePerShare`.\n\nIt returns errors and declares no crossing function. The caller, the height and\nthe amount all arrive as plain arguments, and the realm decides what to abort\non.\n\n## Shares are the token\n\nA share is the vote weight and the claim on the treasury at the same moment,\nminted by paying in and burned by leaving. There is no second asset to issue,\ndistribute, or fail to make meaningful, and the exit price is the same number\nthat votes: a member outvoted on everything can still leave with their part of\nwhat the crew built, and nobody has to agree to let them.\n\n## The trap it avoids: which way the division rounds\n\nBoth divisions round **down**, so both round in the crew's favour.\n\n| | |\n|---|---|\n| joining | `amount * totalShares / treasury`, so a late joiner buys at what a share is worth **now**. Rounding up would hand them a sliver of value the existing members built. |\n| ragequitting | `shares * treasury / totalShares`, so a leaver takes no more than their slice and the remainder stays with the people who stayed. |\n\nBoth go through `xmath.MulDiv`, which computes through a 128-bit intermediate\nand refuses rather than returning a wrong number: the naive `a*b/c` wraps to a\nplausible-looking figure, which is how a payout split leaks money without\nanything failing.\n\nThe dust that accrues is never stranded. The last member out holds every\noutstanding share, so their division is exact and the treasury empties to the\nlast ugnot. `TestEveryoneRagequittingEmptiesTheTreasury` pins it on a treasury\nof 3002 over three shares, which divides by nothing.\n\n## What v0 does not do\n\nA proposal is **advisory text**. Passing one records that the crew agreed by\nshare weight and executes nothing: it moves no coins, changes no membership and\nbinds no code. Executing a payout is the next step, and it is what turns this\ninto a treasury contract rather than a notice board.\n\nA vote keeps the weight it was cast with. A member who votes and then ragequits\nleaves their weight behind in the tally, because unwinding it would mean\nreweighing every ballot on every share change.\n\nThere is no quorum. A crew where one member votes and the rest ignore it passes\nthe proposal, which is exactly as advisory as the text it carries. A tie fails.\n\n## Two write-time rules worth knowing\n\n`ValidName` refuses a pipe. A name is rendered as the title of a link inside a\ntable cell, `md.Link` escapes with the inline-text escaper, and that escaper\ndeliberately leaves `|` alone because a pipe is markdown-inert outside a table.\nWrapping the title in `ui.Cell` on top would double-escape and render the\nbackslashes, so the character is refused at write time instead.\n\n`ValidText` allows a pipe, because free prose legitimately contains one, and\nthe render escapes it with `ui.Cell`. A validator and an escaper protect\nagainst different mistakes.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/social/crew/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/social/crew/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"crew.gno","body":"// Package crew is small-group coordination as a product rather than as a\n// framework: three to fifteen people with a shared pot, a way to decide, and a\n// way to leave with their share.\n//\n// # Why not a DAO framework\n//\n// A framework asks you to pick a governance module, a voting strategy and a\n// treasury adapter before anybody has put in a single ugnot. The targets here\n// are real and already exist: a validator set, a working group, a hackathon\n// team, a five-person company. They want the thing you can create in one\n// transaction. [gno.land/p/moul/grants] and daokit are the framework layer, and\n// this package is deliberately underneath them: one call to open a crew, one to\n// join it, one to leave with what your shares are worth.\n//\n// # The model\n//\n//\tCrews     every crew, plus the credit ledger every payout goes through\n//\tCrew      a name, a creation height, members with shares, a treasury, proposals\n//\tProposal  advisory text with a deadline and a share-weighted tally\n//\n// Shares are the whole design. They are the vote weight and the claim on the\n// treasury at the same time, minted by [Crews.Join] and burned by\n// [Crews.Ragequit], so leaving is priced by the same number that decides. There\n// is no separate token to issue, distribute or forget to make meaningful.\n//\n// # Rounding, which is the part that has to be right\n//\n// Every division here rounds DOWN, and both of them therefore round in the\n// crew's favour:\n//\n//   - joining mints amount * totalShares / treasury, so a late joiner buys\n//     exactly what they paid for at the CURRENT per-share value and never a\n//     share more. Rounding up would hand them a sliver of value the existing\n//     members built, which is the whole reason a flat price is wrong here.\n//   - ragequitting credits shares * treasury / totalShares, so a leaver takes\n//     no more than their slice and the remainder stays with the people who\n//     stayed.\n//\n// The dust that accrues from both is never stranded: the last member to\n// ragequit holds every outstanding share, so their MulDiv is exact and the\n// treasury empties to the last ugnot. [Crews.Ragequit] has a test for that.\n//\n// # What v0 deliberately does not do\n//\n// A proposal is advisory text. Passing one executes nothing, moves nothing and\n// binds nothing; it records that the crew agreed by share weight at a point in\n// time. Executing a payout is the obvious next step and the one that turns this\n// into a treasury contract rather than a notice board.\n//\n// A vote is weighed at the moment it is cast. A member who votes and then\n// ragequits leaves their weight behind in the tally, because unwinding it would\n// mean re-weighing every ballot on every share change.\n//\n// # Errors, not aborts\n//\n// This is a p/, so it returns errors and declares no crossing function: the\n// caller, the height and the amount all arrive as plain arguments and the realm\n// that wires it to the chain decides what to abort on.\npackage crew\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/xmath/v1\"\n)\n\nconst (\n\t// MaxMembers is the upper end of \"three to fifteen people\". It is a\n\t// product constraint and not a technical one: above it the share math\n\t// still works and the thing stops being a crew.\n\tMaxMembers = 15\n\n\t// InitialPricePerShare is what a share costs in ugnot before the crew\n\t// has a treasury to price against: at creation, and again if every\n\t// member has left. 1000 ugnot makes 1 GNOT worth 1000 shares, which\n\t// keeps the integer arithmetic far away from both zero and overflow.\n\tInitialPricePerShare = int64(1000)\n\n\t// VoteBlocks is how long a proposal stays open, in blocks.\n\tVoteBlocks = int64(1000)\n\n\t// MaxNameLen and MaxTextLen bound what one call can make the crew's\n\t// members pay a storage deposit on.\n\tMaxNameLen = 60\n\tMaxTextLen = 500\n\n\t// ExcerptLen is how much of a proposal a listing shows.\n\tExcerptLen = 60\n)\n\n// maxInt64 is the largest int64, spelled out because the overflow guards\n// compare against it directly.\nconst maxInt64 = int64(9223372036854775807)\n\n// The errors a caller can get back.\nvar (\n\tErrBadName     = errors.New(\"crew: name is empty, too long, or has control characters\")\n\tErrBadText     = errors.New(\"crew: text is empty, too long, or has control characters\")\n\tErrBadAmount   = errors.New(\"crew: amount must be positive\")\n\tErrNoCrew      = errors.New(\"crew: no such crew\")\n\tErrNoProposal  = errors.New(\"crew: no such proposal\")\n\tErrNotMember   = errors.New(\"crew: not a member of this crew\")\n\tErrIsMember    = errors.New(\"crew: already a member of this crew\")\n\tErrFull        = errors.New(\"crew: the crew is full\")\n\tErrNoShares    = errors.New(\"crew: the amount sent buys no whole share\")\n\tErrVoteClosed  = errors.New(\"crew: the proposal is no longer open\")\n\tErrVoteOpen    = errors.New(\"crew: the proposal is still open\")\n\tErrNothing     = errors.New(\"crew: nothing to withdraw\")\n\tErrWouldExceed = errors.New(\"crew: the amount would overflow the ledger\")\n)\n\n// Crew is one group: who is in it, what it holds, and what it is deciding.\ntype Crew struct {\n\tName      string\n\tCreatedAt int64 // block height\n\tTreasury  int64 // ugnot, accounted here and held at the realm's address\n\n\t// TotalShares is every share outstanding. It is the denominator of both\n\t// the join price and the ragequit payout, so it is maintained here\n\t// rather than summed over the members on demand.\n\tTotalShares int64\n\n\tshares    map[string]int64 // address -\u003e shares held\n\torder     []address        // members in join order, so output never iterates a map\n\tproposals []store.ID\n}\n\n// SharesOf is how many shares who holds, zero when they hold none.\nfunc (c *Crew) SharesOf(who address) int64 {\n\tif c == nil {\n\t\treturn 0\n\t}\n\treturn c.shares[who.String()]\n}\n\n// IsMember reports whether who holds any share.\nfunc (c *Crew) IsMember(who address) bool { return c.SharesOf(who) \u003e 0 }\n\n// MemberCount is how many addresses hold shares.\nfunc (c *Crew) MemberCount() int {\n\tif c == nil {\n\t\treturn 0\n\t}\n\treturn len(c.order)\n}\n\n// Members returns the members in join order. The slice is a copy, so a caller\n// rendering it cannot reorder the crew.\nfunc (c *Crew) Members() []address {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tout := make([]address, len(c.order))\n\tcopy(out, c.order)\n\treturn out\n}\n\n// Proposals returns this crew's proposal ids, oldest first, as a copy.\nfunc (c *Crew) Proposals() []store.ID {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tout := make([]store.ID, len(c.proposals))\n\tcopy(out, c.proposals)\n\treturn out\n}\n\n// ValuePerShare is what one share is worth in ugnot right now, rounded down.\n//\n// It is a display figure and nothing computes against it: [Crews.Join] and\n// [Crews.Ragequit] divide by the real totals, so a crew whose treasury is\n// smaller than its share count still prices both correctly while this reads 0.\nfunc (c *Crew) ValuePerShare() int64 {\n\tif c == nil || c.TotalShares == 0 {\n\t\treturn 0\n\t}\n\treturn c.Treasury / c.TotalShares\n}\n\n// PricePerShare is what the next share costs a joiner, rounded down, which is\n// [Crew.ValuePerShare] except on a crew nobody holds a share in.\nfunc (c *Crew) PricePerShare() int64 {\n\tif c == nil || c.TotalShares == 0 || c.Treasury == 0 {\n\t\treturn InitialPricePerShare\n\t}\n\treturn c.Treasury / c.TotalShares\n}\n\n// ballot is one member's vote: which way, and what it weighed when cast.\ntype ballot struct {\n\tyes    bool\n\tweight int64\n}\n\n// Proposal is a question put to a crew. v0 proposals are advisory text and\n// execute nothing: see the package doc.\ntype Proposal struct {\n\tCrewID   store.ID\n\tAuthor   address\n\tText     string\n\tOpenedAt int64\n\tDeadline int64 // OpenedAt + VoteBlocks, exclusive\n\n\t// Yes and No are the running share-weighted tally, maintained on every\n\t// vote so reading it never walks the ballots.\n\tYes int64\n\tNo  int64\n\n\tClosed bool\n\tPassed bool\n\n\tvotes map[string]ballot\n}\n\n// Open reports whether the proposal still accepts votes at height now.\nfunc (p *Proposal) Open(now int64) bool {\n\treturn p != nil \u0026\u0026 !p.Closed \u0026\u0026 now \u003c p.Deadline\n}\n\n// VoteOf reports how who voted and what it weighed, and whether they voted at\n// all.\nfunc (p *Proposal) VoteOf(who address) (yes bool, weight int64, voted bool) {\n\tif p == nil {\n\t\treturn false, 0, false\n\t}\n\tb, ok := p.votes[who.String()]\n\treturn b.yes, b.weight, ok\n}\n\n// Voters is how many members have cast a ballot.\nfunc (p *Proposal) Voters() int {\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn len(p.votes)\n}\n\n// Crews holds every crew, every proposal, and the credit ledger each payout\n// goes through.\ntype Crews struct {\n\tcrews *store.Store\n\tprops *store.Store\n\n\tcredit map[string]int64 // address -\u003e ugnot owed\n\towed   int64            // the sum of the above, which the holder must reserve\n}\n\n// New returns an empty Crews.\nfunc New() *Crews {\n\treturn \u0026Crews{\n\t\tcrews:  store.Named(\"crew\"),\n\t\tprops:  store.Named(\"proposal\"),\n\t\tcredit: map[string]int64{},\n\t}\n}\n\n// Create opens a crew with founder as its only member, their shares bought out\n// of amount at [InitialPricePerShare].\n//\n// The remainder below one whole share stays in the treasury rather than being\n// refunded, which is the same direction every other division here rounds.\nfunc (cs *Crews) Create(name string, founder address, amount, at int64) (store.ID, error) {\n\tif !ValidName(name) {\n\t\treturn 0, ErrBadName\n\t}\n\tif amount \u003c= 0 {\n\t\treturn 0, ErrBadAmount\n\t}\n\tshares := amount / InitialPricePerShare\n\tif shares \u003c 1 {\n\t\treturn 0, ErrNoShares\n\t}\n\tc := \u0026Crew{\n\t\tName:        name,\n\t\tCreatedAt:   at,\n\t\tTreasury:    amount,\n\t\tTotalShares: shares,\n\t\tshares:      map[string]int64{founder.String(): shares},\n\t\torder:       []address{founder},\n\t}\n\treturn cs.crews.Add(c), nil\n}\n\n// Join mints who shares at the crew's CURRENT per-share value and adds amount\n// to its treasury.\n//\n// amount * totalShares / treasury, rounded down. That is the whole anti-dilution\n// rule: a crew that turned 10 GNOT into 20 sells the next share for what a share\n// is worth now, not for what the founders paid, and the rounding remainder stays\n// with the crew rather than with the joiner.\nfunc (cs *Crews) Join(id store.ID, who address, amount int64) (int64, error) {\n\tc, ok := cs.Get(id)\n\tif !ok {\n\t\treturn 0, ErrNoCrew\n\t}\n\tif amount \u003c= 0 {\n\t\treturn 0, ErrBadAmount\n\t}\n\tif c.IsMember(who) {\n\t\treturn 0, ErrIsMember\n\t}\n\tif len(c.order) \u003e= MaxMembers {\n\t\treturn 0, ErrFull\n\t}\n\tif c.Treasury \u003e maxInt64-amount {\n\t\treturn 0, ErrWouldExceed\n\t}\n\n\tvar shares int64\n\tif c.TotalShares == 0 || c.Treasury == 0 {\n\t\t// Nobody holds a share, so there is no value to price against and\n\t\t// the crew is back at its opening price.\n\t\tshares = amount / InitialPricePerShare\n\t} else {\n\t\tshares = xmath.MulDiv(amount, c.TotalShares, c.Treasury)\n\t}\n\tif shares \u003c 1 {\n\t\treturn 0, ErrNoShares\n\t}\n\tif c.TotalShares \u003e maxInt64-shares {\n\t\treturn 0, ErrWouldExceed\n\t}\n\n\tc.shares[who.String()] = shares\n\tc.order = append(c.order, who)\n\tc.TotalShares += shares\n\tc.Treasury += amount\n\treturn shares, nil\n}\n\n// Fund adds amount to a crew's treasury and mints nothing.\n//\n// It is what makes the join price mean anything: a crew whose treasury only\n// ever moves with its share count prices every joiner identically forever, and\n// the anti-dilution rule in [Crews.Join] would be decorative. Revenue, a grant\n// and a member topping the pot up all arrive this way, and every existing share\n// is worth more afterwards.\nfunc (cs *Crews) Fund(id store.ID, amount int64) error {\n\tc, ok := cs.Get(id)\n\tif !ok {\n\t\treturn ErrNoCrew\n\t}\n\tif amount \u003c= 0 {\n\t\treturn ErrBadAmount\n\t}\n\tif c.Treasury \u003e maxInt64-amount {\n\t\treturn ErrWouldExceed\n\t}\n\tc.Treasury += amount\n\treturn nil\n}\n\n// Propose opens an advisory question, open for [VoteBlocks] blocks. Any member\n// may propose.\nfunc (cs *Crews) Propose(id store.ID, who address, text string, at int64) (store.ID, error) {\n\tc, ok := cs.Get(id)\n\tif !ok {\n\t\treturn 0, ErrNoCrew\n\t}\n\tif !c.IsMember(who) {\n\t\treturn 0, ErrNotMember\n\t}\n\tif !ValidText(text) {\n\t\treturn 0, ErrBadText\n\t}\n\tp := \u0026Proposal{\n\t\tCrewID:   id,\n\t\tAuthor:   who,\n\t\tText:     text,\n\t\tOpenedAt: at,\n\t\tDeadline: at + VoteBlocks,\n\t\tvotes:    map[string]ballot{},\n\t}\n\tpid := cs.props.Add(p)\n\tc.proposals = append(c.proposals, pid)\n\treturn pid, nil\n}\n\n// Vote records who's ballot, weighted by the shares they hold right now.\n//\n// One ballot per member, changeable while the proposal is open: a second call\n// replaces the first, tally and weight both, so changing your mind after buying\n// more shares counts the shares you now hold.\nfunc (cs *Crews) Vote(pid store.ID, who address, yes bool, at int64) error {\n\tp, ok := cs.Proposal(pid)\n\tif !ok {\n\t\treturn ErrNoProposal\n\t}\n\tif !p.Open(at) {\n\t\treturn ErrVoteClosed\n\t}\n\tc, ok := cs.Get(p.CrewID)\n\tif !ok {\n\t\treturn ErrNoCrew\n\t}\n\tweight := c.SharesOf(who)\n\tif weight \u003c= 0 {\n\t\treturn ErrNotMember\n\t}\n\n\tkey := who.String()\n\tif prev, voted := p.votes[key]; voted {\n\t\tif prev.yes {\n\t\t\tp.Yes -= prev.weight\n\t\t} else {\n\t\t\tp.No -= prev.weight\n\t\t}\n\t}\n\tp.votes[key] = ballot{yes: yes, weight: weight}\n\tif yes {\n\t\tp.Yes += weight\n\t} else {\n\t\tp.No += weight\n\t}\n\treturn nil\n}\n\n// Close records a proposal as passed or failed by share weight, once its\n// deadline has gone by. Anyone may call it: closing is bookkeeping, not\n// authority, and a proposal nobody closes is simply never recorded.\n//\n// A tie fails. There is no quorum in v0: a crew where one member votes and the\n// rest ignore it passes the proposal, which is exactly as advisory as the text\n// it carries.\nfunc (cs *Crews) Close(pid store.ID, at int64) (bool, error) {\n\tp, ok := cs.Proposal(pid)\n\tif !ok {\n\t\treturn false, ErrNoProposal\n\t}\n\tif p.Closed {\n\t\treturn p.Passed, ErrVoteClosed\n\t}\n\tif at \u003c p.Deadline {\n\t\treturn false, ErrVoteOpen\n\t}\n\tp.Closed = true\n\tp.Passed = p.Yes \u003e p.No\n\treturn p.Passed, nil\n}\n\n// Ragequit burns every share who holds, credits them their pro-rata slice of\n// the treasury and removes them from the crew.\n//\n// shares * treasury / totalShares, rounded down, so the remainder stays with\n// the members who stayed. This is what makes a share mean something: the exit\n// is priced by the same number that votes, and nobody has to agree to let you\n// out.\n//\n// The payout is credited, never sent. The caller moves the coins after this\n// returns, which is the ordering the pull-payment pattern exists for.\nfunc (cs *Crews) Ragequit(id store.ID, who address) (shares, amount int64, err error) {\n\tc, ok := cs.Get(id)\n\tif !ok {\n\t\treturn 0, 0, ErrNoCrew\n\t}\n\tshares = c.SharesOf(who)\n\tif shares \u003c= 0 {\n\t\treturn 0, 0, ErrNotMember\n\t}\n\n\tamount = xmath.MulDiv(shares, c.Treasury, c.TotalShares)\n\tc.TotalShares -= shares\n\tc.Treasury -= amount\n\tdelete(c.shares, who.String())\n\tc.order = dropAddress(c.order, who)\n\n\tif amount \u003e 0 {\n\t\tif err := cs.credits(who, amount); err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\treturn shares, amount, nil\n}\n\n// credits adds to an address's withdrawable balance.\nfunc (cs *Crews) credits(who address, amount int64) error {\n\tkey := who.String()\n\tif cs.credit[key] \u003e maxInt64-amount || cs.owed \u003e maxInt64-amount {\n\t\treturn ErrWouldExceed\n\t}\n\tcs.credit[key] += amount\n\tcs.owed += amount\n\treturn nil\n}\n\n// Withdraw zeroes who's credit and returns what they were owed.\n//\n// The balance is gone from the ledger before this returns, so the caller can\n// move the coins afterwards and a reentrant call finds nothing: effects, then\n// interactions.\nfunc (cs *Crews) Withdraw(who address) (int64, error) {\n\tkey := who.String()\n\tamount, ok := cs.credit[key]\n\tif !ok || amount == 0 {\n\t\treturn 0, ErrNothing\n\t}\n\tdelete(cs.credit, key)\n\tcs.owed -= amount\n\treturn amount, nil\n}\n\n// CreditOf is what who can withdraw right now.\nfunc (cs *Crews) CreditOf(who address) int64 { return cs.credit[who.String()] }\n\n// TotalOwed is the sum of every outstanding credit, which is what the holding\n// realm must keep in reserve on top of every crew's treasury.\nfunc (cs *Crews) TotalOwed() int64 { return cs.owed }\n\n// Get returns a crew by id.\nfunc (cs *Crews) Get(id store.ID) (*Crew, bool) {\n\tv, ok := cs.crews.Get(id)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn v.(*Crew), true\n}\n\n// Proposal returns a proposal by id.\nfunc (cs *Crews) Proposal(pid store.ID) (*Proposal, bool) {\n\tv, ok := cs.props.Get(pid)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn v.(*Proposal), true\n}\n\n// Len is how many crews exist.\nfunc (cs *Crews) Len() int { return cs.crews.Len() }\n\n// ProposalCount is how many proposals exist, across every crew.\nfunc (cs *Crews) ProposalCount() int { return cs.props.Len() }\n\n// Listing is one row of [Crews.List]: the crew and the id a link needs.\ntype Listing struct {\n\tID   store.ID\n\tCrew *Crew\n}\n\n// List returns up to limit crews, newest first. limit below 1 returns nothing.\nfunc (cs *Crews) List(limit int) []Listing {\n\tvar out []Listing\n\tfor _, e := range cs.crews.PageReverse(1, limit) {\n\t\tout = append(out, Listing{ID: e.ID, Crew: e.Value.(*Crew)})\n\t}\n\treturn out\n}\n\n// ValidName reports whether name can be stored: non-empty after trimming,\n// within [MaxNameLen], free of control characters including newlines, and\n// free of the pipe character.\n//\n// The pipe is the one restriction that is not obvious, and it is here because\n// a name is rendered as the TITLE of a link inside a table cell. md.Link\n// escapes its title with the inline-text escaper, which deliberately leaves\n// \"|\" alone because a pipe is markdown-inert outside a table, and wrapping the\n// title in ui.Cell on top of that would double-escape and render the\n// backslashes. Refusing the character at write time is the only place left\n// where the fix is one rule rather than one exception per call site.\n//\n// A proposal's text has no such restriction: [ValidText] allows a pipe and the\n// render escapes it with ui.Cell, because free prose legitimately contains one\n// and a name does not.\nfunc ValidName(name string) bool {\n\tif len(name) \u003e MaxNameLen || strings.TrimSpace(name) == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(name); i++ {\n\t\tc := name[i]\n\t\tif c \u003c 0x20 || c == 0x7f || c == '|' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidText reports whether a proposal body can be stored: non-empty after\n// trimming, within [MaxTextLen], and free of control characters other than\n// newline and tab.\n//\n// Control characters are refused rather than stripped because the text is shown\n// back to its author, and silently rewriting what somebody wrote is worse than\n// telling them it was refused. Everything else is allowed and escaped at render\n// time: a validator and an escaper protect against different mistakes.\nfunc ValidText(text string) bool {\n\tif len(text) \u003e MaxTextLen || strings.TrimSpace(text) == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(text); i++ {\n\t\tc := text[i]\n\t\tif c \u003c 0x20 \u0026\u0026 c != '\\n' \u0026\u0026 c != '\\t' || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// dropAddress returns addrs without who, in a freshly allocated slice.\n//\n// It allocates rather than shortening in place: a slice is one persisted object\n// and the storage deposit only comes back when that object is dropped, so\n// append(s[:i], s[i+1:]...) would keep the peak allocation charged forever.\nfunc dropAddress(addrs []address, who address) []address {\n\tout := make([]address, 0, len(addrs))\n\tfor _, a := range addrs {\n\t\tif a != who {\n\t\t\tout = append(out, a)\n\t\t}\n\t}\n\treturn out\n}\n"},{"name":"crew_test.gno","body":"package crew\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\tdave  = testutils.TestAddress(\"dave\")\n)\n\n// join is Join with the minted share count dropped, for the cases that only\n// care that it worked.\nfunc join(t *testing.T, cs *Crews, id store.ID, who address, amount int64) {\n\tt.Helper()\n\t_, err := cs.Join(id, who, amount)\n\turequire.NoError(t, err)\n}\n\n// tenGNOT is the amount every founder in these tests puts in, chosen so the\n// share count is a round 10,000 and a halved or doubled price is still exact.\nconst tenGNOT = int64(10000000)\n\nfunc TestValidName(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant bool\n\t}{\n\t\t{\"validators\", true},\n\t\t{\"The Hackathon Team\", true},\n\t\t{\"a\", true},\n\t\t{strings.Repeat(\"x\", MaxNameLen), true},\n\t\t{\"\", false},\n\t\t{\"   \", false},\n\t\t{strings.Repeat(\"x\", MaxNameLen+1), false},\n\t\t{\"two\\nlines\", false},\n\t\t{\"a\\tb\", false},\n\t\t{\"a\\x7fb\", false},\n\t\t{\"a | pipe\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidName(tt.name), tt.name)\n\t}\n}\n\nfunc TestValidText(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\ttext string\n\t\twant bool\n\t}{\n\t\t{\"plain\", \"ship v1 before the conference\", true},\n\t\t{\"newlines and tabs are content\", \"a\\nb\\tc\", true},\n\t\t{\"markdown is allowed and escaped later\", \"[x](y) | z\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"blank\", \"  \\n \", false},\n\t\t{\"too long\", strings.Repeat(\"x\", MaxTextLen+1), false},\n\t\t{\"control character\", \"a\\x01b\", false},\n\t\t{\"delete character\", \"a\\x7fb\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidText(tt.text), tt.name)\n\t}\n}\n\nfunc TestCreateMintsAtTheOpeningPrice(t *testing.T) {\n\tcs := New()\n\tid, err := cs.Create(\"validators\", alice, tenGNOT, 100)\n\turequire.NoError(t, err)\n\n\tc, ok := cs.Get(id)\n\turequire.True(t, ok, \"the crew exists\")\n\tuassert.Equal(t, \"validators\", c.Name)\n\tuassert.Equal(t, int64(100), c.CreatedAt)\n\tuassert.Equal(t, tenGNOT/InitialPricePerShare, c.TotalShares)\n\tuassert.Equal(t, tenGNOT, c.Treasury)\n\tuassert.Equal(t, c.TotalShares, c.SharesOf(alice))\n\tuassert.Equal(t, 1, c.MemberCount())\n\tuassert.Equal(t, InitialPricePerShare, c.ValuePerShare())\n\tuassert.Equal(t, 1, cs.Len())\n}\n\n// The remainder below one whole share stays in the treasury, which is the same\n// direction every other division here rounds.\nfunc TestCreateKeepsTheRemainder(t *testing.T) {\n\tcs := New()\n\tid, err := cs.Create(\"crew\", alice, 2999, 100)\n\turequire.NoError(t, err)\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, int64(2), c.TotalShares, \"2999 ugnot buys two whole shares\")\n\tuassert.Equal(t, int64(2999), c.Treasury, \"and the 999 left over is the crew's\")\n}\n\nfunc TestCreateRefusals(t *testing.T) {\n\ttests := []struct {\n\t\tlabel  string\n\t\tname   string\n\t\tamount int64\n\t\twant   error\n\t}{\n\t\t{\"empty name\", \"\", tenGNOT, ErrBadName},\n\t\t{\"name with a newline\", \"two\\nlines\", tenGNOT, ErrBadName},\n\t\t{\"name with a pipe\", \"a | pipe\", tenGNOT, ErrBadName},\n\t\t{\"nothing sent\", \"crew\", 0, ErrBadAmount},\n\t\t{\"negative\", \"crew\", -1, ErrBadAmount},\n\t\t{\"under one share\", \"crew\", InitialPricePerShare - 1, ErrNoShares},\n\t}\n\tfor _, tt := range tests {\n\t\tcs := New()\n\t\t_, err := cs.Create(tt.name, alice, tt.amount, 100)\n\t\tuassert.ErrorIs(t, err, tt.want, tt.label)\n\t\tuassert.Equal(t, 0, cs.Len(), tt.label+\": nothing was stored\")\n\t}\n}\n\n// A second joiner at the same per-share value gets the same shares. This is the\n// baseline the anti-dilution rule is measured against.\nfunc TestASecondJoinerAtTheSamePriceGetsTheSameShares(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\n\tgot, err := cs.Join(id, bob, tenGNOT)\n\turequire.NoError(t, err)\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, c.SharesOf(alice), got, \"same money, same shares\")\n\tuassert.Equal(t, tenGNOT/InitialPricePerShare, got)\n\tuassert.Equal(t, 2*tenGNOT, c.Treasury)\n\tuassert.Equal(t, 2*(tenGNOT/InitialPricePerShare), c.TotalShares)\n\tuassert.Equal(t, InitialPricePerShare, c.ValuePerShare(), \"the value per share did not move\")\n\tuassert.Equal(t, 2, c.MemberCount())\n}\n\n// A joiner arriving after the treasury grew gets FEWER shares for the same\n// money, because they are buying at what a share is worth now. That is the\n// whole point: a late joiner cannot buy into value the existing members built.\nfunc TestAJoinerAfterTheTreasuryGrewGetsFewer(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\turequire.NoError(t, cs.Fund(id, tenGNOT)) // the crew doubled its money\n\n\tc, _ := cs.Get(id)\n\turequire.Equal(t, 2*InitialPricePerShare, c.ValuePerShare())\n\n\tgot, err := cs.Join(id, bob, tenGNOT)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, c.SharesOf(alice)/2, got, \"the same money buys half as much\")\n\tuassert.Equal(t, 2*InitialPricePerShare, c.ValuePerShare(),\n\t\t\"and joining did not move the value for anybody else\")\n}\n\n// Rounding down on the way in means a joiner never gets a share they did not\n// fully pay for, and the fractional remainder accrues to the crew.\nfunc TestJoinRoundsInTheCrewsFavour(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, 1000, 100) // 1 share, treasury 1000\n\turequire.NoError(t, cs.Fund(id, 500))        // treasury 1500, still 1 share\n\n\t// 1499 ugnot is 0.999 of a share. Rounding up would hand bob a whole\n\t// one and half of alice's money with it.\n\t_, err := cs.Join(id, bob, 1499)\n\tuassert.ErrorIs(t, err, ErrNoShares)\n\n\tgot, err := cs.Join(id, bob, 2999)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1), got, \"1.999 shares' worth buys one share\")\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, int64(4499), c.Treasury, \"the 1499 ugnot of remainder stayed\")\n\tuassert.Equal(t, int64(2), c.TotalShares)\n}\n\nfunc TestJoinRefusals(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\n\t_, err := cs.Join(999, bob, tenGNOT)\n\tuassert.ErrorIs(t, err, ErrNoCrew)\n\n\t_, err = cs.Join(id, alice, tenGNOT)\n\tuassert.ErrorIs(t, err, ErrIsMember, \"a member cannot buy in twice\")\n\n\t_, err = cs.Join(id, bob, 0)\n\tuassert.ErrorIs(t, err, ErrBadAmount)\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, 1, c.MemberCount(), \"no refusal changed the roster\")\n\tuassert.Equal(t, tenGNOT, c.Treasury)\n}\n\n// Fifteen people is the product constraint, and the sixteenth is refused rather\n// than quietly allowed.\nfunc TestACrewIsFullAtMaxMembers(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tfor i := 1; i \u003c MaxMembers; i++ {\n\t\twho := testutils.TestAddress(\"m\" + strconv.Itoa(i))\n\t\t_, err := cs.Join(id, who, tenGNOT)\n\t\turequire.NoError(t, err)\n\t}\n\n\tc, _ := cs.Get(id)\n\turequire.Equal(t, MaxMembers, c.MemberCount())\n\n\t_, err := cs.Join(id, testutils.TestAddress(\"one too many\"), tenGNOT)\n\tuassert.ErrorIs(t, err, ErrFull)\n\tuassert.Equal(t, MaxMembers, c.MemberCount())\n}\n\nfunc TestProposeAndTallyByShareWeight(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100) // alice: 10000 shares\n\tcs.Join(id, bob, tenGNOT/2)                     // bob: 5000 shares\n\n\tpid, err := cs.Propose(id, bob, \"ship v1 before the conference\", 200)\n\turequire.NoError(t, err)\n\n\tp, ok := cs.Proposal(pid)\n\turequire.True(t, ok, \"the proposal exists\")\n\tuassert.Equal(t, uint64(id), uint64(p.CrewID))\n\tuassert.Equal(t, int64(200+VoteBlocks), p.Deadline)\n\tuassert.True(t, p.Open(200))\n\tuassert.False(t, p.Open(200+VoteBlocks), \"the deadline is exclusive\")\n\n\turequire.NoError(t, cs.Vote(pid, bob, true, 210))\n\turequire.NoError(t, cs.Vote(pid, alice, false, 211))\n\tuassert.Equal(t, int64(5000), p.Yes)\n\tuassert.Equal(t, int64(10000), p.No, \"a bigger holder outvotes a smaller one\")\n\tuassert.Equal(t, 2, p.Voters())\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, 1, len(c.Proposals()))\n}\n\n// One ballot per member, replaced in place while the proposal is open, and\n// reweighed from the shares held at the moment it is recast.\nfunc TestAVoteIsChangeableWhileOpen(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tpid, _ := cs.Propose(id, alice, \"a question\", 200)\n\tp, _ := cs.Proposal(pid)\n\n\turequire.NoError(t, cs.Vote(pid, alice, true, 210))\n\tuassert.Equal(t, int64(10000), p.Yes)\n\tuassert.Equal(t, int64(0), p.No)\n\n\turequire.NoError(t, cs.Vote(pid, alice, false, 211))\n\tuassert.Equal(t, int64(0), p.Yes, \"the old ballot is removed, not added to\")\n\tuassert.Equal(t, int64(10000), p.No)\n\tuassert.Equal(t, 1, p.Voters(), \"still one voter\")\n\n\tyes, weight, voted := p.VoteOf(alice)\n\tuassert.True(t, voted)\n\tuassert.False(t, yes)\n\tuassert.Equal(t, int64(10000), weight)\n}\n\nfunc TestProposeAndVoteRefusals(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\n\t_, err := cs.Propose(999, alice, \"text\", 200)\n\tuassert.ErrorIs(t, err, ErrNoCrew)\n\t_, err = cs.Propose(id, bob, \"text\", 200)\n\tuassert.ErrorIs(t, err, ErrNotMember, \"only a member proposes\")\n\t_, err = cs.Propose(id, alice, \"   \", 200)\n\tuassert.ErrorIs(t, err, ErrBadText)\n\n\tpid, _ := cs.Propose(id, alice, \"a question\", 200)\n\tuassert.ErrorIs(t, cs.Vote(999, alice, true, 210), ErrNoProposal)\n\tuassert.ErrorIs(t, cs.Vote(pid, bob, true, 210), ErrNotMember)\n\tuassert.ErrorIs(t, cs.Vote(pid, alice, true, 200+VoteBlocks), ErrVoteClosed,\n\t\t\"the deadline is exclusive\")\n}\n\nfunc TestCloseRecordsTheResult(t *testing.T) {\n\ttests := []struct {\n\t\tlabel      string\n\t\taliceVotes bool\n\t\tbobVotes   bool\n\t\twant       bool\n\t}{\n\t\t{\"the bigger holder carries it\", true, false, true},\n\t\t{\"and blocks it\", false, true, false},\n\t\t{\"unanimous yes\", true, true, true},\n\t\t{\"unanimous no\", false, false, false},\n\t}\n\tfor _, tt := range tests {\n\t\tcs := New()\n\t\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100) // 10000 shares\n\t\tcs.Join(id, bob, tenGNOT/2)                     // 5000 shares\n\t\tpid, _ := cs.Propose(id, alice, \"a question\", 200)\n\n\t\turequire.NoError(t, cs.Vote(pid, alice, tt.aliceVotes, 210))\n\t\turequire.NoError(t, cs.Vote(pid, bob, tt.bobVotes, 211))\n\n\t\tpassed, err := cs.Close(pid, 200+VoteBlocks)\n\t\turequire.NoError(t, err)\n\t\tuassert.Equal(t, tt.want, passed, tt.label)\n\n\t\tp, _ := cs.Proposal(pid)\n\t\tuassert.True(t, p.Closed, tt.label)\n\t\tuassert.Equal(t, tt.want, p.Passed, tt.label)\n\t}\n}\n\n// A tie fails, and a proposal nobody voted on is a tie at zero.\nfunc TestATieFails(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tcs.Join(id, bob, tenGNOT)\n\tpid, _ := cs.Propose(id, alice, \"a question\", 200)\n\n\turequire.NoError(t, cs.Vote(pid, alice, true, 210))\n\turequire.NoError(t, cs.Vote(pid, bob, false, 211))\n\n\tpassed, err := cs.Close(pid, 200+VoteBlocks)\n\turequire.NoError(t, err)\n\tuassert.False(t, passed, \"equal weight on both sides is not agreement\")\n\n\tsilent, _ := cs.Propose(id, alice, \"nobody cares\", 200)\n\tpassed, err = cs.Close(silent, 200+VoteBlocks)\n\turequire.NoError(t, err)\n\tuassert.False(t, passed, \"0 to 0 is not agreement either\")\n}\n\nfunc TestCloseRefusals(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tpid, _ := cs.Propose(id, alice, \"a question\", 200)\n\n\t_, err := cs.Close(999, 5000)\n\tuassert.ErrorIs(t, err, ErrNoProposal)\n\n\t_, err = cs.Close(pid, 200+VoteBlocks-1)\n\tuassert.ErrorIs(t, err, ErrVoteOpen, \"one block early is early\")\n\n\t_, err = cs.Close(pid, 200+VoteBlocks)\n\turequire.NoError(t, err)\n\t_, err = cs.Close(pid, 200+VoteBlocks)\n\tuassert.ErrorIs(t, err, ErrVoteClosed, \"closing twice does not re-tally\")\n}\n\n// A vote keeps the weight it was cast with. Ragequitting afterwards does not\n// unwind it, which is a v0 caveat stated in the package doc rather than a bug.\nfunc TestAVoteKeepsTheWeightItWasCastWith(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tcs.Join(id, bob, tenGNOT)\n\tpid, _ := cs.Propose(id, alice, \"a question\", 200)\n\n\turequire.NoError(t, cs.Vote(pid, bob, true, 210))\n\t_, _, err := cs.Ragequit(id, bob)\n\turequire.NoError(t, err)\n\n\tp, _ := cs.Proposal(pid)\n\tuassert.Equal(t, int64(10000), p.Yes, \"bob's ballot stayed behind\")\n\tuassert.ErrorIs(t, cs.Vote(pid, bob, false, 220), ErrNotMember,\n\t\t\"but he cannot touch it again\")\n}\n\nfunc TestRagequitTakesAProRataSlice(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tcs.Join(id, bob, tenGNOT)\n\turequire.NoError(t, cs.Fund(id, 2*tenGNOT)) // the crew doubled its money\n\n\tshares, amount, err := cs.Ragequit(id, bob)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, tenGNOT/InitialPricePerShare, shares, \"every share is burned\")\n\tuassert.Equal(t, 2*tenGNOT, amount, \"half of a treasury worth four, for half the shares\")\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, 1, c.MemberCount())\n\tuassert.Equal(t, int64(0), c.SharesOf(bob))\n\tuassert.False(t, c.IsMember(bob))\n\tuassert.Equal(t, 2*tenGNOT, c.Treasury)\n\tuassert.Equal(t, tenGNOT/InitialPricePerShare, c.TotalShares)\n\n\tuassert.Equal(t, 2*tenGNOT, cs.CreditOf(bob), \"credited, never sent\")\n\tuassert.Equal(t, 2*tenGNOT, cs.TotalOwed())\n\n\t_, _, err = cs.Ragequit(id, bob)\n\tuassert.ErrorIs(t, err, ErrNotMember, \"there is nothing left to burn\")\n\t_, _, err = cs.Ragequit(999, alice)\n\tuassert.ErrorIs(t, err, ErrNoCrew)\n}\n\n// A one-member crew ragequitting takes everything: their shares ARE the total,\n// so the division is exact whatever the numbers are.\nfunc TestAOneMemberCrewTakesEverything(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, 5001, 100) // 5 shares, a treasury of 5001\n\n\tshares, amount, err := cs.Ragequit(id, alice)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(5), shares)\n\tuassert.Equal(t, int64(5001), amount, \"including the ugnot that bought no share\")\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, int64(0), c.Treasury)\n\tuassert.Equal(t, int64(0), c.TotalShares)\n\tuassert.Equal(t, 0, c.MemberCount())\n}\n\n// Everyone ragequitting empties the treasury to the last ugnot, even when no\n// single division is exact: the dust each leaver rounds away belongs to whoever\n// is still in, and the last one out holds every share.\nfunc TestEveryoneRagequittingEmptiesTheTreasury(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, 1000, 100)\n\tjoin(t, cs, id, bob, 1000)\n\tjoin(t, cs, id, carol, 1000)\n\turequire.NoError(t, cs.Fund(id, 2)) // 3002 ugnot over 3 shares, divides by nothing\n\n\tc, _ := cs.Get(id)\n\turequire.Equal(t, int64(3002), c.Treasury)\n\turequire.Equal(t, int64(3), c.TotalShares)\n\n\tvar paid int64\n\tfor _, who := range []address{alice, bob, carol} {\n\t\t_, amount, err := cs.Ragequit(id, who)\n\t\turequire.NoError(t, err)\n\t\tpaid += amount\n\t}\n\n\tuassert.Equal(t, int64(3002), paid, \"every ugnot left with somebody\")\n\tuassert.Equal(t, int64(0), c.Treasury, \"to the last one\")\n\tuassert.Equal(t, int64(0), c.TotalShares)\n\tuassert.Equal(t, 0, c.MemberCount())\n\tuassert.Equal(t, int64(3002), cs.TotalOwed())\n\n\t// The dust did not land evenly, which is the point: the people who\n\t// stayed longest absorbed it.\n\tuassert.Equal(t, int64(1000), cs.CreditOf(alice), \"first out, rounded down hardest\")\n\tuassert.Equal(t, int64(1001), cs.CreditOf(bob))\n\tuassert.Equal(t, int64(1001), cs.CreditOf(carol))\n}\n\n// An emptied crew is not a dead one. With no shares outstanding there is no\n// value to price against, so it reopens at the price it opened at.\nfunc TestRejoiningAnEmptiedCrewIsBackAtTheOpeningPrice(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\t_, _, err := cs.Ragequit(id, alice)\n\turequire.NoError(t, err)\n\n\tc, _ := cs.Get(id)\n\turequire.Equal(t, int64(0), c.TotalShares)\n\tuassert.Equal(t, int64(0), c.ValuePerShare(), \"nothing is worth anything yet\")\n\tuassert.Equal(t, InitialPricePerShare, c.PricePerShare(), \"but a share still has a price\")\n\n\tgot, err := cs.Join(id, dave, tenGNOT)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, tenGNOT/InitialPricePerShare, got)\n\tuassert.Equal(t, tenGNOT, c.Treasury)\n}\n\nfunc TestWithdrawZeroesTheCreditBeforeItReturns(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tcs.Join(id, bob, tenGNOT)\n\t_, owed, _ := cs.Ragequit(id, bob)\n\turequire.True(t, owed \u003e 0, \"bob is owed something\")\n\n\tgot, err := cs.Withdraw(bob)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, owed, got)\n\tuassert.Equal(t, int64(0), cs.CreditOf(bob), \"zeroed, so a reentrant call finds nothing\")\n\tuassert.Equal(t, int64(0), cs.TotalOwed())\n\n\t_, err = cs.Withdraw(bob)\n\tuassert.ErrorIs(t, err, ErrNothing)\n\t_, err = cs.Withdraw(carol)\n\tuassert.ErrorIs(t, err, ErrNothing)\n}\n\n// Credits accumulate across crews, because one ledger serves all of them.\nfunc TestCreditsAccumulateAcrossCrews(t *testing.T) {\n\tcs := New()\n\tfirst, _ := cs.Create(\"first\", alice, tenGNOT, 100)\n\tsecond, _ := cs.Create(\"second\", bob, tenGNOT, 100)\n\tjoin(t, cs, second, alice, tenGNOT)\n\n\t_, a, _ := cs.Ragequit(first, alice)\n\t_, b, _ := cs.Ragequit(second, alice)\n\tuassert.Equal(t, a+b, cs.CreditOf(alice), \"one withdrawal collects both\")\n\tuassert.Equal(t, 2, cs.Len())\n}\n\nfunc TestListIsNewestFirst(t *testing.T) {\n\tcs := New()\n\tfirst, _ := cs.Create(\"first\", alice, tenGNOT, 100)\n\tsecond, _ := cs.Create(\"second\", bob, tenGNOT, 101)\n\tthird, _ := cs.Create(\"third\", carol, tenGNOT, 102)\n\n\tgot := cs.List(10)\n\turequire.Equal(t, 3, len(got))\n\tuassert.Equal(t, uint64(third), uint64(got[0].ID))\n\tuassert.Equal(t, uint64(second), uint64(got[1].ID))\n\tuassert.Equal(t, uint64(first), uint64(got[2].ID))\n\tuassert.Equal(t, \"third\", got[0].Crew.Name)\n\n\tuassert.Equal(t, 1, len(cs.List(1)))\n\tuassert.Equal(t, 0, len(cs.List(0)))\n}\n\n// Members comes back in join order and as a copy, so a Render can never\n// reshuffle the roster it is reading.\nfunc TestMembersAreAnOrderedCopy(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\tcs.Join(id, bob, tenGNOT)\n\tcs.Join(id, carol, tenGNOT)\n\n\tc, _ := cs.Get(id)\n\tgot := c.Members()\n\turequire.Equal(t, 3, len(got))\n\tuassert.Equal(t, alice.String(), got[0].String())\n\tuassert.Equal(t, bob.String(), got[1].String())\n\tuassert.Equal(t, carol.String(), got[2].String())\n\n\tgot[0] = dave\n\tuassert.Equal(t, alice.String(), c.Members()[0].String(), \"the caller got a copy\")\n\n\t// Ragequitting removes the leaver and keeps the rest in order.\n\tcs.Ragequit(id, bob)\n\tgot = c.Members()\n\turequire.Equal(t, 2, len(got))\n\tuassert.Equal(t, alice.String(), got[0].String())\n\tuassert.Equal(t, carol.String(), got[1].String())\n}\n\nfunc TestFundRefusals(t *testing.T) {\n\tcs := New()\n\tid, _ := cs.Create(\"crew\", alice, tenGNOT, 100)\n\n\tuassert.ErrorIs(t, cs.Fund(999, 100), ErrNoCrew)\n\tuassert.ErrorIs(t, cs.Fund(id, 0), ErrBadAmount)\n\tuassert.ErrorIs(t, cs.Fund(id, -1), ErrBadAmount)\n\n\tc, _ := cs.Get(id)\n\tuassert.Equal(t, tenGNOT, c.Treasury, \"no refusal moved the treasury\")\n\tuassert.Equal(t, 0, cs.ProposalCount())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/social/crew/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"18000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"curated","path":"gno.land/p/moul/x/social/curated/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/social/curated/v0`\n\n**The engine behind a list where being on it costs something**: `New`, `Apply`,\n`Challenge`, `Vote`, `Resolve`, `Unlist`, `Withdraw`, plus the reads a page\nneeds.\n\n```go\nr := curated.New(1_000_000, 1000)              // deposit, challenge window\nr.Apply(\"gnoswap\", \"/r/gnoswap\", \"the DEX\", owner, paid, height)\nr.Challenge(\"gnoswap\", challenger, bond, height) // bond matches the deposit\nr.Vote(\"gnoswap\", voter, false, height)\nr.Resolve(\"gnoswap\", height+1001)                // credits the winner\n```\n\n**A list anybody can write to for free is a list nobody can read**, because the\ncheapest way to be on it is to be on it a thousand times. A deposit does not\nmake an entry good. It makes a bad entry expensive to leave standing, because\nsomebody who disagrees can put the same amount at risk and take yours. The list\nis worth reading in proportion to what it would cost to pollute it.\n\n**This package moves no coins.** Every payout is a credit in an internal ledger\nthe payee collects with `Withdraw`, which zeroes it before returning the amount;\nthe realm sends afterwards. A registry that looped over winners and sent to each\none would fail entirely when one of them could not be paid.\n\nThree rules worth knowing before you read the code:\n\n- **A tie keeps the entry.** The incumbent wins ties, so a challenge that\n  convinces nobody costs the challenger their bond. A challenge has to be worth\n  making, which means losing one has to hurt.\n- **An owner may not challenge their own entry.** It is free for them (a kept\n  entry credits the owner the bond, which would be their own money back) and it\n  would make the entry immune to a real challenge for the whole window.\n- **A removed key is free to apply for again.** Burning the name forever\n  punishes the name rather than the entry.\n\n**Votes are one address, one vote, and that is sybil-prone**: a hundred\naddresses are cheap and nothing here can tell them apart. Gating who counts is\nthe job of a vouch graph, `r/moul/x/social/vouch` in this family, and wiring the\ntwo together is the first real upgrade this package wants. Voters are also paid\nnothing in v0, which is the second.\n\n`Locked()` plus `Owed()` is the solvency invariant: what the registry is holding\nas deposits and bonds, plus what it owes people who have not collected yet,\nshould equal the realm's balance. The realm's test suite asserts exactly that\nagainst the chain at every step of a full round.\n\n**Live realm:** [`r/moul/x/social/curated`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/social/curated),\nwhich carries the reasoning for why the bonds are GNOT and not a token of its own.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"curated.gno","body":"// Package curated is the engine behind a curated list where being on the list\n// costs something: anyone may list an entry by locking a deposit, anyone may\n// challenge an entry by matching that deposit with a bond, and the loser of the\n// challenge pays the winner.\n//\n// # Why a deposit\n//\n// A list anybody can write to for free is a list nobody can read, because the\n// cheapest way to be on it is to be on it a thousand times. A deposit does not\n// make an entry good; it makes a bad entry expensive to leave standing, because\n// somebody who disagrees can put the same amount at risk and take yours. The\n// list is worth reading in proportion to what it would cost to pollute it.\n//\n// # The model\n//\n//\tRegistry  every entry, plus the credit ledger the payouts land in\n//\tEntry     a key, a URL, a description, an owner, the deposit, the height\n//\t          it was listed at, and one of three states\n//\tChallenge a challenger, a matching bond, a deadline, and the votes\n//\n// A key is unique while it is on the list ([ValidKey] bounds it to a\n// slug), and a removed key is free again: a challenge that wins removes an\n// entry, it does not burn the name forever.\n//\n// # The money, and why nothing is ever sent from here\n//\n// This package moves no coins. Every payout is a credit in an internal ledger\n// that the payee collects with [Registry.Withdraw], which is the pull-payment\n// shape: a realm that loops over winners and sends to each one fails entirely\n// when one of them cannot be paid, and hands a griefer a cheap denial of\n// service. [Registry.Locked] plus [Registry.Owed] is what the holding realm\n// must have at its address, and a realm can assert exactly that.\n//\n// # Voting is sybil-prone, deliberately and visibly\n//\n// [Registry.Vote] is one address, one vote, unweighted. An address is free, so\n// a challenge outcome is a poll of whoever bothered to make keys, not of\n// anybody in particular. That is not a gap this package can close: deciding who\n// counts as a person is a different problem with a different realm behind it,\n// r/moul/x/social/vouch, a sibling in this family. Until a vote is\n// gated on a vouched identity, read a resolution as \"nobody with a stake\n// objected enough\", not as a verdict.\n//\n// # What v0 does not do, in the order it should be fixed\n//\n//  1. Voters are paid nothing. Voting costs gas and returns nothing, so the\n//     only addresses with a reason to vote are the two with money on the\n//     outcome. A share of the loser's stake for the winning side is the\n//     standard answer and it is the first thing to add.\n//  2. There is no application period: [Registry.Apply] lists immediately, so a\n//     bad entry is visible until somebody challenges it.\n//  3. A challenge cannot be withdrawn, and a vote cannot be changed.\npackage curated\n\nimport (\n\t\"errors\"\n\t\"strings\"\n)\n\nconst (\n\t// MaxKeyLen is the longest key accepted. A key is a name people type and\n\t// link to, not a payload.\n\tMaxKeyLen = 64\n\n\t// MaxURLLen and MaxDescLen bound what one entry can lock up of somebody\n\t// else's storage deposit.\n\tMaxURLLen  = 240\n\tMaxDescLen = 240\n\n\t// MaxEntries bounds the registry so a listing stays predictable in gas.\n\tMaxEntries = 4096\n\n\t// MaxPayees bounds the credit ledger for the same reason.\n\tMaxPayees = 4096\n)\n\nconst maxInt64 = int64(9223372036854775807)\n\n// The errors a caller can get back. A p/ returns them; the realm decides to\n// abort.\nvar (\n\tErrBadKey         = errors.New(\"curated: not a key: 1 to 64 bytes of a-z 0-9 - _ . starting alphanumeric\")\n\tErrBadURL         = errors.New(\"curated: url is empty, too long, or has a space or a control character\")\n\tErrBadDescription = errors.New(\"curated: description is empty, too long, or not a single line\")\n\tErrTaken          = errors.New(\"curated: that key is already on the list\")\n\tErrNoEntry        = errors.New(\"curated: no such entry\")\n\tErrWrongDeposit   = errors.New(\"curated: the deposit must be paid exactly\")\n\tErrWrongBond      = errors.New(\"curated: the bond must match the entry's deposit\")\n\tErrChallenged     = errors.New(\"curated: that entry is under challenge\")\n\tErrSelfChallenge  = errors.New(\"curated: an owner cannot challenge their own entry\")\n\tErrNoChallenge    = errors.New(\"curated: that entry is not under challenge\")\n\tErrVotingClosed   = errors.New(\"curated: the challenge deadline has passed\")\n\tErrAlreadyVoted   = errors.New(\"curated: one address, one vote\")\n\tErrTooEarly       = errors.New(\"curated: the challenge is still open\")\n\tErrNotOwner       = errors.New(\"curated: only the entry's owner can do that\")\n\tErrNothingOwed    = errors.New(\"curated: nothing to withdraw\")\n\tErrFull           = errors.New(\"curated: the registry is full\")\n\tErrOverflow       = errors.New(\"curated: the credit would overflow\")\n\tErrBadAmount      = errors.New(\"curated: amount must be positive\")\n)\n\n// State is where an entry stands.\ntype State uint8\n\nconst (\n\t// StateListed is on the list and unchallenged.\n\tStateListed State = iota\n\n\t// StateChallenged is on the list with a challenge open against it. It\n\t// still renders: a challenge is an objection, not a verdict.\n\tStateChallenged\n\n\t// StateRemoved is off the list, either lost to a challenge or taken down\n\t// by its own owner. The key is free for anyone to apply for again.\n\tStateRemoved\n)\n\n// String names the state for a reader and for an event.\nfunc (s State) String() string {\n\tswitch s {\n\tcase StateListed:\n\t\treturn \"listed\"\n\tcase StateChallenged:\n\t\treturn \"challenged\"\n\tcase StateRemoved:\n\t\treturn \"removed\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\n// Challenge is an open objection to one entry.\ntype Challenge struct {\n\tChallenger address\n\tBond       int64\n\tDeadline   int64 // block height the voting stops at, exclusive\n\n\t// Keep and Remove are the unweighted vote counts. See the package doc on\n\t// what they are and are not worth.\n\tKeep   int64\n\tRemove int64\n\n\t// voters is the set of addresses that have voted, so one address votes\n\t// once. It is unexported: a caller reads [Challenge.Voters].\n\tvoters map[string]bool\n}\n\n// Voters is how many distinct addresses have voted.\nfunc (c *Challenge) Voters() int {\n\tif c == nil {\n\t\treturn 0\n\t}\n\treturn len(c.voters)\n}\n\n// HasVoted reports whether who has already voted in this challenge.\nfunc (c *Challenge) HasVoted(who address) bool {\n\tif c == nil {\n\t\treturn false\n\t}\n\treturn c.voters[who.String()]\n}\n\n// Open reports whether votes are still being taken at height now.\nfunc (c *Challenge) Open(now int64) bool { return c != nil \u0026\u0026 now \u003c c.Deadline }\n\n// Entry is one row of the list.\ntype Entry struct {\n\tKey         string\n\tURL         string\n\tDescription string\n\tOwner       address\n\tDeposit     int64 // what the owner locked to list it\n\tAt          int64 // the block height it was listed at\n\tState       State\n\n\t// challenge is the open objection, or nil. It is cleared on resolution:\n\t// the outcome is in the entry's state and in the ledger, and keeping a\n\t// resolved challenge would be a second place to read it from.\n\tchallenge *Challenge\n}\n\n// Live reports whether the entry is on the list, challenged or not.\nfunc (e *Entry) Live() bool { return e != nil \u0026\u0026 e.State != StateRemoved }\n\n// Registry is the whole list: the entries, and the credits waiting to be\n// withdrawn.\ntype Registry struct {\n\tdeposit         int64\n\tchallengeBlocks int64\n\n\tentries map[string]*Entry\n\torder   []string // keys in the order they were first listed\n\n\tcredits map[string]int64\n\towed    int64\n\tlocked  int64\n}\n\n// New returns an empty registry where listing costs deposit and a challenge\n// runs for challengeBlocks blocks.\n//\n// Both are fixed for the life of the registry. An entry remembers the deposit\n// it actually paid, so a future registry that can reprice itself still charges\n// a challenger what the owner of that entry risked, and not today's number.\nfunc New(deposit, challengeBlocks int64) *Registry {\n\treturn \u0026Registry{\n\t\tdeposit:         deposit,\n\t\tchallengeBlocks: challengeBlocks,\n\t\tentries:         map[string]*Entry{},\n\t\tcredits:         map[string]int64{},\n\t}\n}\n\n// Deposit is what listing costs.\nfunc (r *Registry) Deposit() int64 { return r.deposit }\n\n// ChallengeBlocks is how long a challenge takes to resolve.\nfunc (r *Registry) ChallengeBlocks() int64 { return r.challengeBlocks }\n\n// Apply lists an entry immediately, in exchange for exactly the deposit.\n//\n// There is no application period in v0: the entry is on the list the moment the\n// deposit is paid, and the check on it is that anybody can challenge it.\n//\n// A key whose entry was removed is free again, and applying for it writes a\n// fresh entry in the same position in the listing order.\nfunc (r *Registry) Apply(key, url, description string, owner address, paid, now int64) error {\n\tif !ValidKey(key) {\n\t\treturn ErrBadKey\n\t}\n\tif !ValidURL(url) {\n\t\treturn ErrBadURL\n\t}\n\tif !ValidDescription(description) {\n\t\treturn ErrBadDescription\n\t}\n\tif paid != r.deposit {\n\t\treturn ErrWrongDeposit\n\t}\n\told, seen := r.entries[key]\n\tif seen \u0026\u0026 old.Live() {\n\t\treturn ErrTaken\n\t}\n\tif !seen {\n\t\tif len(r.order) \u003e= MaxEntries {\n\t\t\treturn ErrFull\n\t\t}\n\t\tr.order = append(r.order, key)\n\t}\n\tr.entries[key] = \u0026Entry{\n\t\tKey:         key,\n\t\tURL:         url,\n\t\tDescription: description,\n\t\tOwner:       owner,\n\t\tDeposit:     paid,\n\t\tAt:          now,\n\t\tState:       StateListed,\n\t}\n\tr.locked += paid\n\treturn nil\n}\n\n// BondFor is what challenging key would cost, and whether it can be challenged\n// at all.\n//\n// The realm reads this BEFORE it reads the envelope, so a caller who attaches\n// coins to a challenge of something unchallengeable is refused on the entry and\n// not on the amount.\nfunc (r *Registry) BondFor(key string) (int64, bool) {\n\te, ok := r.entries[key]\n\tif !ok || e.State != StateListed {\n\t\treturn 0, false\n\t}\n\treturn e.Deposit, true\n}\n\n// Challenge opens an objection to an entry, against a bond equal to that\n// entry's deposit, and sets the deadline at now + ChallengeBlocks.\n//\n// An owner may not challenge their own entry. It would cost nothing (a kept\n// entry credits its owner the bond, which here is their own) and it would make\n// the entry immune to a real challenge for the whole window.\nfunc (r *Registry) Challenge(key string, challenger address, bond, now int64) error {\n\te, ok := r.entries[key]\n\tif !ok || !e.Live() {\n\t\treturn ErrNoEntry\n\t}\n\tif e.State == StateChallenged {\n\t\treturn ErrChallenged\n\t}\n\tif challenger == e.Owner {\n\t\treturn ErrSelfChallenge\n\t}\n\tif bond != e.Deposit {\n\t\treturn ErrWrongBond\n\t}\n\te.State = StateChallenged\n\te.challenge = \u0026Challenge{\n\t\tChallenger: challenger,\n\t\tBond:       bond,\n\t\tDeadline:   now + r.challengeBlocks,\n\t\tvoters:     map[string]bool{},\n\t}\n\tr.locked += bond\n\treturn nil\n}\n\n// Vote records one address's opinion on an open challenge: keep the entry, or\n// remove it.\n//\n// One address, one vote, unweighted, and it cannot be changed. Anyone may vote,\n// including the owner and the challenger, because excluding them would only\n// move their vote to another address they control. See the package doc: this is\n// sybil-prone on purpose rather than by oversight, and gating it is the job of\n// the vouch realm.\nfunc (r *Registry) Vote(key string, voter address, keep bool, now int64) error {\n\te, ok := r.entries[key]\n\tif !ok {\n\t\treturn ErrNoEntry\n\t}\n\tc := e.challenge\n\tif e.State != StateChallenged || c == nil {\n\t\treturn ErrNoChallenge\n\t}\n\tif !c.Open(now) {\n\t\treturn ErrVotingClosed\n\t}\n\tk := voter.String()\n\tif c.voters[k] {\n\t\treturn ErrAlreadyVoted\n\t}\n\tc.voters[k] = true\n\tif keep {\n\t\tc.Keep++\n\t} else {\n\t\tc.Remove++\n\t}\n\treturn nil\n}\n\n// Outcome is what a resolution decided and who it paid.\ntype Outcome struct {\n\tKey    string\n\tKept   bool\n\tWinner address\n\tAmount int64 // credited to the winner\n\tKeep   int64\n\tRemove int64\n}\n\n// Resolve closes a challenge whose deadline has passed. Anyone may call it: the\n// two parties both have a reason to and neither can stall the other.\n//\n// A majority of keep votes keeps the entry and credits its owner the\n// challenger's bond. Otherwise the entry is removed and the challenger is\n// credited the bond plus the deposit.\n//\n// A TIE KEEPS THE ENTRY, including the tie of nobody voting at all. The\n// incumbent paid first and is already at risk, so the burden is on the\n// challenger to produce a reason; if ties went the other way, a challenge that\n// convinced nobody would still win, and listing anything would be pointless.\n// The cost of that choice is the one a challenger signs up for: being wrong\n// costs the bond.\nfunc (r *Registry) Resolve(key string, now int64) (Outcome, error) {\n\te, ok := r.entries[key]\n\tif !ok {\n\t\treturn Outcome{}, ErrNoEntry\n\t}\n\tc := e.challenge\n\tif e.State != StateChallenged || c == nil {\n\t\treturn Outcome{}, ErrNoChallenge\n\t}\n\tif c.Open(now) {\n\t\treturn Outcome{}, ErrTooEarly\n\t}\n\n\tout := Outcome{Key: key, Kept: c.Keep \u003e= c.Remove, Keep: c.Keep, Remove: c.Remove}\n\tif out.Kept {\n\t\tout.Winner, out.Amount = e.Owner, c.Bond\n\t} else {\n\t\tout.Winner, out.Amount = c.Challenger, c.Bond+e.Deposit\n\t}\n\n\t// Credit first: it is the only step that can fail, and a half-applied\n\t// resolution would leave an entry with no challenge and nobody paid.\n\tif err := r.credit(out.Winner, out.Amount); err != nil {\n\t\treturn Outcome{}, err\n\t}\n\tif out.Kept {\n\t\te.State = StateListed\n\t\tr.locked -= c.Bond\n\t} else {\n\t\te.State = StateRemoved\n\t\tr.locked -= c.Bond + e.Deposit\n\t}\n\te.challenge = nil\n\treturn out, nil\n}\n\n// Unlist takes an owner's own entry down and credits them the deposit back.\n//\n// It is refused while a challenge is open, which is the whole point of the\n// bond: an owner who could walk away mid-challenge would be risking nothing.\nfunc (r *Registry) Unlist(key string, owner address) error {\n\te, ok := r.entries[key]\n\tif !ok || !e.Live() {\n\t\treturn ErrNoEntry\n\t}\n\tif e.Owner != owner {\n\t\treturn ErrNotOwner\n\t}\n\tif e.State == StateChallenged {\n\t\treturn ErrChallenged\n\t}\n\tif err := r.credit(owner, e.Deposit); err != nil {\n\t\treturn err\n\t}\n\te.State = StateRemoved\n\tr.locked -= e.Deposit\n\treturn nil\n}\n\n// Withdraw zeroes who's credit and returns what they were owed.\n//\n// The holding realm sends the coins AFTER this returns. That ordering is the\n// pattern: the credit is already gone from the ledger when control passes to\n// the recipient, so a reentrant withdrawal finds ErrNothingOwed.\nfunc (r *Registry) Withdraw(who address) (int64, error) {\n\tk := who.String()\n\tamount := r.credits[k]\n\tif amount \u003c= 0 {\n\t\treturn 0, ErrNothingOwed\n\t}\n\tdelete(r.credits, k) // effects before interactions\n\tr.owed -= amount\n\treturn amount, nil\n}\n\n// credit records that who is owed amount more.\nfunc (r *Registry) credit(who address, amount int64) error {\n\tif amount \u003c= 0 {\n\t\treturn ErrBadAmount\n\t}\n\tk := who.String()\n\thave, seen := r.credits[k]\n\tif !seen \u0026\u0026 len(r.credits) \u003e= MaxPayees {\n\t\treturn ErrFull\n\t}\n\tif have \u003e maxInt64-amount || r.owed \u003e maxInt64-amount {\n\t\treturn ErrOverflow\n\t}\n\tr.credits[k] = have + amount\n\tr.owed += amount\n\treturn nil\n}\n\n// Get returns an entry by key, whatever its state, and whether it ever existed.\nfunc (r *Registry) Get(key string) (*Entry, bool) {\n\te, ok := r.entries[key]\n\treturn e, ok\n}\n\n// IsListed reports whether key is on the list right now. A challenged entry is\n// still listed.\nfunc (r *Registry) IsListed(key string) bool {\n\te, ok := r.entries[key]\n\treturn ok \u0026\u0026 e.Live()\n}\n\n// Count is how many entries are on the list right now.\nfunc (r *Registry) Count() int {\n\tn := 0\n\tfor _, key := range r.order {\n\t\tif r.entries[key].Live() {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// Records is how many keys the registry has ever held, removed ones included.\nfunc (r *Registry) Records() int { return len(r.order) }\n\n// Listed returns every entry on the list, oldest first.\n//\n// The order comes from a slice and not from iterating the map, so it is a\n// stable sequence a Render can be pinned against rather than an insertion order\n// that a delete-and-re-add would reshuffle.\nfunc (r *Registry) Listed() []*Entry {\n\tout := []*Entry{}\n\tfor _, key := range r.order {\n\t\tif e := r.entries[key]; e.Live() {\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out\n}\n\n// Challenged returns every entry with a challenge open against it, oldest\n// listing first.\nfunc (r *Registry) Challenged() []*Entry {\n\tout := []*Entry{}\n\tfor _, key := range r.order {\n\t\tif e := r.entries[key]; e.State == StateChallenged {\n\t\t\tout = append(out, e)\n\t\t}\n\t}\n\treturn out\n}\n\n// ChallengeOf returns the open challenge against key, if there is one.\nfunc (r *Registry) ChallengeOf(key string) (*Challenge, bool) {\n\te, ok := r.entries[key]\n\tif !ok || e.challenge == nil {\n\t\treturn nil, false\n\t}\n\treturn e.challenge, true\n}\n\n// CreditOf is what who can withdraw right now.\nfunc (r *Registry) CreditOf(who address) int64 { return r.credits[who.String()] }\n\n// Owed is every credit not yet withdrawn.\nfunc (r *Registry) Owed() int64 { return r.owed }\n\n// Locked is the deposits behind live entries plus the bonds behind open\n// challenges.\n//\n// Locked plus [Registry.Owed] is what the holding realm must have at its\n// address: every ugnot it ever took is either still backing something or\n// already assigned to somebody. A realm can assert that equality against its\n// own balance, and this package's tests do.\nfunc (r *Registry) Locked() int64 { return r.locked }\n\n// ValidKey reports whether key is usable: 1 to [MaxKeyLen] bytes of lowercase\n// ASCII letters, digits, '-', '_' and '.', starting with a letter or a digit.\n//\n// The leading-alphanumeric rule is what stops \".\" and \"..\", and what stops a\n// key that reads as punctuation in the list it is shown in. The charset is\n// narrow so a key can be typed, linked and compared without surprises; it is\n// still escaped at render time, because a validator and an escaper protect\n// against different mistakes.\nfunc ValidKey(key string) bool {\n\tif key == \"\" || len(key) \u003e MaxKeyLen {\n\t\treturn false\n\t}\n\tif c := key[0]; !(c \u003e= 'a' \u0026\u0026 c \u003c= 'z' || c \u003e= '0' \u0026\u0026 c \u003c= '9') {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(key); i++ {\n\t\tc := key[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '-' || c == '_' || c == '.':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidURL reports whether url can be stored: non-empty, within [MaxURLLen],\n// and free of spaces and control characters.\n//\n// No scheme is required, because a list of on-chain things is the obvious use\n// and those have no host. A renderer treats a schemeless URL as a path\n// relative to the chain's web root, so an on-chain target is written\n// \"/r/moul/home\" and an off-chain one carries its own \"https://\".\n//\n// Nothing here checks that the target exists: a deposit backs the claim that\n// the entry is worth listing, not the claim that it resolves.\nfunc ValidURL(url string) bool {\n\tif url == \"\" || len(url) \u003e MaxURLLen {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(url); i++ {\n\t\tif c := url[i]; c \u003c= 0x20 || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidDescription reports whether description can be stored: non-empty after\n// trimming, within [MaxDescLen], and a single line.\n//\n// Newlines and tabs are refused rather than stripped, because a description is\n// shown back to the person who wrote it and silently rewriting it is worse than\n// telling them it was refused. It lives in a table cell, which a newline would\n// break out of and an escaper would then have to repair.\nfunc ValidDescription(description string) bool {\n\tif len(description) \u003e MaxDescLen || strings.TrimSpace(description) == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(description); i++ {\n\t\tif c := description[i]; c \u003c 0x20 || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"},{"name":"curated_test.gno","body":"package curated\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\tdeposit = int64(1000)\n\twindow  = int64(100)\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\tdave  = testutils.TestAddress(\"dave\")\n)\n\n// list returns a registry holding one entry owned by alice, listed at height\n// 100, which is the starting point of most cases below.\nfunc list(t *testing.T) *Registry {\n\tt.Helper()\n\tr := New(deposit, window)\n\turequire.NoError(t, r.Apply(\"gnoswap\", \"https://gnoswap.io\", \"an AMM\", alice, deposit, 100))\n\treturn r\n}\n\nfunc TestValidKey(t *testing.T) {\n\ttests := []struct {\n\t\tkey  string\n\t\twant bool\n\t}{\n\t\t{\"gnoswap\", true},\n\t\t{\"a\", true},\n\t\t{\"0\", true},\n\t\t{\"gno-swap_v2.1\", true},\n\t\t{strings.Repeat(\"x\", MaxKeyLen), true},\n\t\t{\"\", false},\n\t\t{strings.Repeat(\"x\", MaxKeyLen+1), false},\n\t\t{\"GnoSwap\", false},\n\t\t{\"gno swap\", false},\n\t\t{\"gno/swap\", false},\n\t\t{\"gno:swap\", false},\n\t\t{\".\", false},\n\t\t{\"..\", false},\n\t\t{\"-leading\", false},\n\t\t{\"_leading\", false},\n\t\t{\"émoji\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidKey(tt.key), tt.key)\n\t}\n}\n\nfunc TestValidURL(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\turl  string\n\t\twant bool\n\t}{\n\t\t{\"https\", \"https://gnoswap.io/pools\", true},\n\t\t{\"an on-chain path, which has no scheme to carry\", \"/r/moul/home\", true},\n\t\t{\"query and fragment\", \"https://x.io/a?b=c#d\", true},\n\t\t{\"a pipe is escaped at render time, not refused\", \"https://x.io/a|b\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"too long\", \"https://x.io/\" + strings.Repeat(\"x\", MaxURLLen), false},\n\t\t{\"a space\", \"https://x.io/a b\", false},\n\t\t{\"a newline\", \"https://x.io/a\\nb\", false},\n\t\t{\"a control character\", \"https://x.io/a\\x01b\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidURL(tt.url), tt.name)\n\t}\n}\n\nfunc TestValidDescription(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdesc string\n\t\twant bool\n\t}{\n\t\t{\"plain\", \"an AMM on gno.land\", true},\n\t\t{\"markdown is allowed and escaped later\", \"[x](y) | z\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"blank\", \"   \", false},\n\t\t{\"too long\", strings.Repeat(\"x\", MaxDescLen+1), false},\n\t\t{\"a newline would break its own table cell\", \"a\\nb\", false},\n\t\t{\"a tab, same reason\", \"a\\tb\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidDescription(tt.desc), tt.name)\n\t}\n}\n\nfunc TestApplyRefusesWhatItCannotStore(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tkey  string\n\t\turl  string\n\t\tdesc string\n\t\tpaid int64\n\t\twant error\n\t}{\n\t\t{\"bad key\", \"Gnoswap\", \"https://x.io\", \"an AMM\", deposit, ErrBadKey},\n\t\t{\"bad url\", \"gnoswap\", \"\", \"an AMM\", deposit, ErrBadURL},\n\t\t{\"bad description\", \"gnoswap\", \"https://x.io\", \" \", deposit, ErrBadDescription},\n\t\t{\"underpaid\", \"gnoswap\", \"https://x.io\", \"an AMM\", deposit - 1, ErrWrongDeposit},\n\t\t{\"overpaid\", \"gnoswap\", \"https://x.io\", \"an AMM\", deposit + 1, ErrWrongDeposit},\n\t\t{\"nothing attached\", \"gnoswap\", \"https://x.io\", \"an AMM\", 0, ErrWrongDeposit},\n\t}\n\tfor _, tt := range tests {\n\t\tr := New(deposit, window)\n\t\terr := r.Apply(tt.key, tt.url, tt.desc, alice, tt.paid, 100)\n\t\tuassert.ErrorIs(t, err, tt.want, tt.name)\n\t\tuassert.Equal(t, 0, r.Count(), tt.name+\": nothing was listed\")\n\t\tuassert.Equal(t, int64(0), r.Locked(), tt.name+\": nothing was locked\")\n\t}\n}\n\nfunc TestApplyListsImmediately(t *testing.T) {\n\tr := list(t)\n\n\te, ok := r.Get(\"gnoswap\")\n\turequire.True(t, ok, \"the entry exists\")\n\tuassert.Equal(t, \"https://gnoswap.io\", e.URL)\n\tuassert.Equal(t, \"an AMM\", e.Description)\n\tuassert.Equal(t, alice.String(), e.Owner.String())\n\tuassert.Equal(t, deposit, e.Deposit)\n\tuassert.Equal(t, int64(100), e.At)\n\tuassert.Equal(t, \"listed\", e.State.String())\n\n\tuassert.True(t, r.IsListed(\"gnoswap\"))\n\tuassert.False(t, r.IsListed(\"nothing\"))\n\tuassert.Equal(t, 1, r.Count())\n\tuassert.Equal(t, 1, r.Records())\n\tuassert.Equal(t, deposit, r.Locked())\n\tuassert.Equal(t, int64(0), r.Owed())\n}\n\n// A key is unique while it is on the list, and free again once it is off it: a\n// challenge removes an entry, it does not burn the name.\nfunc TestAKeyIsTakenUntilItIsRemoved(t *testing.T) {\n\tr := list(t)\n\n\tuassert.ErrorIs(t, r.Apply(\"gnoswap\", \"https://other.io\", \"mine now\", bob, deposit, 101), ErrTaken)\n\turequire.NoError(t, r.Unlist(\"gnoswap\", alice))\n\tuassert.False(t, r.IsListed(\"gnoswap\"))\n\n\turequire.NoError(t, r.Apply(\"gnoswap\", \"https://other.io\", \"mine now\", bob, deposit, 102))\n\te, _ := r.Get(\"gnoswap\")\n\tuassert.Equal(t, bob.String(), e.Owner.String())\n\tuassert.Equal(t, int64(102), e.At, \"a re-application is a fresh entry\")\n\tuassert.Equal(t, 1, r.Count())\n\tuassert.Equal(t, 1, r.Records(), \"and it reuses its place in the listing order\")\n}\n\nfunc TestListedIsOldestFirstAndSkipsTheRemoved(t *testing.T) {\n\tr := New(deposit, window)\n\turequire.NoError(t, r.Apply(\"one\", \"https://1.io\", \"first\", alice, deposit, 100))\n\turequire.NoError(t, r.Apply(\"two\", \"https://2.io\", \"second\", alice, deposit, 101))\n\turequire.NoError(t, r.Apply(\"three\", \"https://3.io\", \"third\", alice, deposit, 102))\n\n\tgot := r.Listed()\n\turequire.Equal(t, 3, len(got))\n\tuassert.Equal(t, \"one\", got[0].Key)\n\tuassert.Equal(t, \"two\", got[1].Key)\n\tuassert.Equal(t, \"three\", got[2].Key)\n\n\turequire.NoError(t, r.Unlist(\"two\", alice))\n\tgot = r.Listed()\n\turequire.Equal(t, 2, len(got))\n\tuassert.Equal(t, \"one\", got[0].Key)\n\tuassert.Equal(t, \"three\", got[1].Key)\n\tuassert.Equal(t, 0, len(r.Challenged()))\n}\n\nfunc TestChallengeRefusals(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tkey  string\n\t\twho  address\n\t\tbond int64\n\t\twant error\n\t}{\n\t\t{\"no such entry\", \"nothing\", bob, deposit, ErrNoEntry},\n\t\t{\"the bond must match\", \"gnoswap\", bob, deposit - 1, ErrWrongBond},\n\t\t{\"and may not exceed it either\", \"gnoswap\", bob, deposit + 1, ErrWrongBond},\n\t\t{\"an owner cannot shield their own entry\", \"gnoswap\", alice, deposit, ErrSelfChallenge},\n\t}\n\tfor _, tt := range tests {\n\t\tr := list(t)\n\t\tuassert.ErrorIs(t, r.Challenge(tt.key, tt.who, tt.bond, 200), tt.want, tt.name)\n\t\tuassert.Equal(t, deposit, r.Locked(), tt.name+\": no bond was taken\")\n\t\t_, open := r.ChallengeOf(\"gnoswap\")\n\t\tuassert.False(t, open, tt.name+\": no challenge was opened\")\n\t}\n}\n\nfunc TestChallengeOpensOnceAndSetsTheDeadline(t *testing.T) {\n\tr := list(t)\n\n\tbond, ok := r.BondFor(\"gnoswap\")\n\turequire.True(t, ok, \"it is challengeable\")\n\tuassert.Equal(t, deposit, bond, \"the bond matches that entry's own deposit\")\n\n\turequire.NoError(t, r.Challenge(\"gnoswap\", bob, bond, 200))\n\tc, open := r.ChallengeOf(\"gnoswap\")\n\turequire.True(t, open, \"the challenge is readable\")\n\tuassert.Equal(t, bob.String(), c.Challenger.String())\n\tuassert.Equal(t, int64(200+window), c.Deadline)\n\tuassert.True(t, c.Open(200+window-1))\n\tuassert.False(t, c.Open(200+window), \"the deadline is exclusive\")\n\tuassert.Equal(t, \"challenged\", mustGet(t, r, \"gnoswap\").State.String())\n\tuassert.True(t, r.IsListed(\"gnoswap\"), \"a challenge is an objection, not a verdict\")\n\tuassert.Equal(t, 2*deposit, r.Locked(), \"the deposit and the bond\")\n\n\t// A second challenge would be a second bond on one entry.\n\tuassert.ErrorIs(t, r.Challenge(\"gnoswap\", carol, deposit, 201), ErrChallenged)\n\t_, ok = r.BondFor(\"gnoswap\")\n\tuassert.False(t, ok, \"and BondFor says so before any money is read\")\n}\n\nfunc TestVoteIsOneAddressOneVoteWhileTheChallengeIsOpen(t *testing.T) {\n\tr := list(t)\n\tuassert.ErrorIs(t, r.Vote(\"gnoswap\", carol, true, 200), ErrNoChallenge)\n\tuassert.ErrorIs(t, r.Vote(\"nothing\", carol, true, 200), ErrNoEntry)\n\n\turequire.NoError(t, r.Challenge(\"gnoswap\", bob, deposit, 200))\n\turequire.NoError(t, r.Vote(\"gnoswap\", carol, true, 210))\n\tuassert.ErrorIs(t, r.Vote(\"gnoswap\", carol, false, 211), ErrAlreadyVoted)\n\tuassert.ErrorIs(t, r.Vote(\"gnoswap\", carol, true, 212), ErrAlreadyVoted)\n\turequire.NoError(t, r.Vote(\"gnoswap\", dave, false, 213))\n\n\tc, _ := r.ChallengeOf(\"gnoswap\")\n\tuassert.Equal(t, int64(1), c.Keep)\n\tuassert.Equal(t, int64(1), c.Remove)\n\tuassert.Equal(t, 2, c.Voters())\n\tuassert.True(t, c.HasVoted(carol))\n\tuassert.False(t, c.HasVoted(alice))\n\n\t// Past the deadline the poll is shut, and so is the deadline itself.\n\tuassert.ErrorIs(t, r.Vote(\"gnoswap\", alice, true, 200+window), ErrVotingClosed)\n\tuassert.Equal(t, 2, c.Voters())\n}\n\n// The outcome table: who wins, and what the loser pays. A tie keeps the entry.\nfunc TestResolvePaysTheWinnerAndTiesKeep(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tkeep       []address\n\t\tremove     []address\n\t\twantKept   bool\n\t\twantWinner address\n\t\twantAmount int64\n\t}{\n\t\t{\"nobody voted, the incumbent keeps it\", nil, nil, true, alice, deposit},\n\t\t{\"a tie keeps it\", []address{carol}, []address{dave}, true, alice, deposit},\n\t\t{\"a majority to keep\", []address{carol, dave}, nil, true, alice, deposit},\n\t\t{\"a majority to remove\", nil, []address{carol, dave}, false, bob, 2 * deposit},\n\t}\n\tfor _, tt := range tests {\n\t\tr := list(t)\n\t\turequire.NoError(t, r.Challenge(\"gnoswap\", bob, deposit, 200))\n\t\tfor _, who := range tt.keep {\n\t\t\turequire.NoError(t, r.Vote(\"gnoswap\", who, true, 210))\n\t\t}\n\t\tfor _, who := range tt.remove {\n\t\t\turequire.NoError(t, r.Vote(\"gnoswap\", who, false, 210))\n\t\t}\n\n\t\tout, err := r.Resolve(\"gnoswap\", 200+window)\n\t\turequire.NoError(t, err, tt.name)\n\t\tuassert.Equal(t, tt.wantKept, out.Kept, tt.name)\n\t\tuassert.Equal(t, tt.wantWinner.String(), out.Winner.String(), tt.name)\n\t\tuassert.Equal(t, tt.wantAmount, out.Amount, tt.name)\n\t\tuassert.Equal(t, tt.wantAmount, r.CreditOf(tt.wantWinner), tt.name+\": credited, not sent\")\n\t\tuassert.Equal(t, tt.wantKept, r.IsListed(\"gnoswap\"), tt.name)\n\n\t\t// Whatever happened, every ugnot is either still backing the entry or\n\t\t// assigned to somebody.\n\t\tuassert.Equal(t, 2*deposit, r.Locked()+r.Owed(), tt.name+\": the books balance\")\n\n\t\t// The challenge is gone either way, so nothing resolves twice.\n\t\t_, open := r.ChallengeOf(\"gnoswap\")\n\t\tuassert.False(t, open, tt.name)\n\t\t_, err = r.Resolve(\"gnoswap\", 200+window)\n\t\tuassert.ErrorIs(t, err, ErrNoChallenge, tt.name)\n\t}\n}\n\nfunc TestResolveRefusesBeforeTheDeadline(t *testing.T) {\n\tr := list(t)\n\t_, err := r.Resolve(\"gnoswap\", 200)\n\tuassert.ErrorIs(t, err, ErrNoChallenge, \"an unchallenged entry has nothing to resolve\")\n\t_, err = r.Resolve(\"nothing\", 200)\n\tuassert.ErrorIs(t, err, ErrNoEntry)\n\n\turequire.NoError(t, r.Challenge(\"gnoswap\", bob, deposit, 200))\n\t_, err = r.Resolve(\"gnoswap\", 200+window-1)\n\tuassert.ErrorIs(t, err, ErrTooEarly)\n\tuassert.Equal(t, int64(0), r.Owed(), \"nothing was paid out early\")\n\tuassert.Equal(t, \"challenged\", mustGet(t, r, \"gnoswap\").State.String())\n}\n\n// Losing a challenge frees the key, and the deposit that backed it has already\n// gone to the challenger, so re-listing it costs a fresh deposit.\nfunc TestAnEntryThatLosesIsRemovedAndItsDepositIsGone(t *testing.T) {\n\tr := list(t)\n\turequire.NoError(t, r.Challenge(\"gnoswap\", bob, deposit, 200))\n\turequire.NoError(t, r.Vote(\"gnoswap\", carol, false, 210))\n\t_, err := r.Resolve(\"gnoswap\", 200+window)\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, \"removed\", mustGet(t, r, \"gnoswap\").State.String())\n\tuassert.Equal(t, 0, r.Count())\n\tuassert.Equal(t, int64(0), r.Locked())\n\tuassert.Equal(t, 2*deposit, r.Owed())\n\tuassert.Equal(t, int64(0), r.CreditOf(alice), \"the owner lost the deposit\")\n\tuassert.ErrorIs(t, r.Unlist(\"gnoswap\", alice), ErrNoEntry, \"there is nothing left to take down\")\n}\n\nfunc TestUnlistIsTheOwnersAndNotWhileChallenged(t *testing.T) {\n\tr := list(t)\n\tuassert.ErrorIs(t, r.Unlist(\"nothing\", alice), ErrNoEntry)\n\tuassert.ErrorIs(t, r.Unlist(\"gnoswap\", bob), ErrNotOwner)\n\n\turequire.NoError(t, r.Challenge(\"gnoswap\", bob, deposit, 200))\n\tuassert.ErrorIs(t, r.Unlist(\"gnoswap\", alice), ErrChallenged,\n\t\t\"an owner who could walk away mid-challenge would be risking nothing\")\n\tuassert.Equal(t, int64(0), r.CreditOf(alice))\n\n\t// Once the challenge is behind it, the entry is the owner's to take down.\n\turequire.NoError(t, r.Vote(\"gnoswap\", carol, true, 210))\n\t_, err := r.Resolve(\"gnoswap\", 200+window)\n\turequire.NoError(t, err)\n\turequire.NoError(t, r.Unlist(\"gnoswap\", alice))\n\tuassert.Equal(t, 2*deposit, r.CreditOf(alice), \"the bond she won, plus her own deposit back\")\n\tuassert.Equal(t, int64(0), r.Locked())\n}\n\nfunc TestWithdrawZeroesTheCreditBeforeItIsPaid(t *testing.T) {\n\tr := list(t)\n\turequire.NoError(t, r.Unlist(\"gnoswap\", alice))\n\tuassert.Equal(t, deposit, r.Owed())\n\n\t_, err := r.Withdraw(bob)\n\tuassert.ErrorIs(t, err, ErrNothingOwed, \"bob is owed nothing\")\n\n\tgot, err := r.Withdraw(alice)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, deposit, got)\n\tuassert.Equal(t, int64(0), r.CreditOf(alice))\n\tuassert.Equal(t, int64(0), r.Owed())\n\n\t// A second call, which is what a reentrant one would be, finds nothing.\n\t_, err = r.Withdraw(alice)\n\tuassert.ErrorIs(t, err, ErrNothingOwed)\n}\n\nfunc TestCreditsAccumulateAcrossEntries(t *testing.T) {\n\tr := list(t)\n\turequire.NoError(t, r.Apply(\"gnoscan\", \"https://gnoscan.io\", \"an explorer\", alice, deposit, 101))\n\turequire.NoError(t, r.Unlist(\"gnoswap\", alice))\n\turequire.NoError(t, r.Unlist(\"gnoscan\", alice))\n\n\tuassert.Equal(t, 2*deposit, r.CreditOf(alice), \"crediting twice owes the sum\")\n\tgot, err := r.Withdraw(alice)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 2*deposit, got, \"and one withdrawal collects both\")\n}\n\n// Everything the registry ever took in is either locked behind something live\n// or owed to somebody, at every step of a full round.\nfunc TestTheBooksBalanceAtEveryStep(t *testing.T) {\n\tr := New(deposit, window)\n\tpaidIn := int64(0)\n\n\tcheck := func(step string) {\n\t\tt.Helper()\n\t\tuassert.Equal(t, paidIn, r.Locked()+r.Owed(), step)\n\t}\n\tcheck(\"empty\")\n\n\turequire.NoError(t, r.Apply(\"one\", \"https://1.io\", \"first\", alice, deposit, 100))\n\tpaidIn += deposit\n\tcheck(\"after a listing\")\n\n\turequire.NoError(t, r.Challenge(\"one\", bob, deposit, 200))\n\tpaidIn += deposit\n\tcheck(\"after a challenge\")\n\n\turequire.NoError(t, r.Vote(\"one\", carol, false, 210))\n\tcheck(\"after a vote\")\n\n\t_, err := r.Resolve(\"one\", 200+window)\n\turequire.NoError(t, err)\n\tcheck(\"after a resolution\")\n\n\t_, err = r.Withdraw(bob)\n\turequire.NoError(t, err)\n\tpaidIn -= 2 * deposit\n\tcheck(\"after the winner collected\")\n\tuassert.Equal(t, int64(0), r.Locked()+r.Owed(), \"and the realm owes nothing\")\n}\n\nfunc mustGet(t *testing.T, r *Registry, key string) *Entry {\n\tt.Helper()\n\te, ok := r.Get(key)\n\turequire.True(t, ok, \"entry \"+key+\" exists\")\n\treturn e\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/social/curated/v0\"\ngno = \"0.9\"\n"}]},"send":"","max_deposit":"15000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"patron","path":"gno.land/p/moul/x/social/patron/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/social/patron/v0`\n\n**The engine behind recurring support for a builder**: a plan somebody\nsubscribes to, period after period, paid in ugnot. `NewRegistry`, `Open`,\n`Subscribe`, `Close`, `Reopen`, `Withdraw`, plus the reads a page needs.\n\n```go\nr := patron.NewRegistry()\nid, _ := r.Open(creator, \"monthly support\", \"what you get\", 1_000_000, 43_200)\n\npay, _ := r.Subscribe(id, supporter, 2_500_000, height) // 2 periods, 500000 change\nplan, _ := r.Get(id)\nplan.IsActive(supporter, height)                        // true until pay.PaidThrough\n\nr.Withdraw(creator)   // the earnings\nr.Withdraw(supporter) // the change\n```\n\n**There is no cron on chain, so a renewal is a pull and not a push.** Nothing\nhere can charge anybody, and nothing could: a native coin cannot be pulled at\nall, since a banker may only spend its own realm's address. A supporter renews\nby signing another payment. That is the one sentence a reader arriving from\nweb2 needs, because the thing they are picturing, a standing mandate on a card,\ndoes not exist anywhere on this chain.\n\n**What it adds over a tip jar.**\n[`r/moul/x/daily/tipjar`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/daily/tipjar)\nis the one-shot version and is already live: one payment, a leaderboard, done.\nThe recurrence is the whole difference here. A plan carries a price per period\nand a period measured in **blocks**, a payment buys whole periods of it, and\nthe registry answers \"is this address active right now\" at any height. It is\nthe one piece of the `x/social` family that produces a recurring write rather\nthan a one-off.\n\n**The period arithmetic is the part that has to be right**, so it is stated\nrather than left to the reader:\n\n- A payment buys `floor(sent / price)` **whole** periods and refuses anything\n  short of one. Rounding is **down**, and the remainder under one period is\n  credited back to the supporter rather than kept. Keeping it would be a fee\n  nobody agreed to, and a silent fee is the thing a subscription realm must not\n  have.\n- The extension starts from **whichever is later, now or the current\n  `paidThrough`**. Renewing early therefore adds a whole period on top of what\n  is left instead of discarding it; renewing after a lapse starts from now,\n  because the gap was never paid for.\n- `IsActive` is strict: an address paid through height `h` is active at `h-1`\n  and not at `h`. One rule at both edges, so two periods never overlap by a\n  block.\n- `Subscribe` computes the extension through\n  [`xmath.MulDiv`](https://github.com/moul/gno-contracts/tree/main/p/moul/xmath).\n  The division there is exact by construction, so nothing is rounded a second\n  time; what it buys is the 128-bit intermediate, because `spent *\n  periodBlocks` overflows an `int64` for a plan priced in whole GNOT with a\n  period measured in months, and the naive product wraps to a plausible-looking\n  height rather than an obviously wrong one.\n\n**Earnings are credited at the moment of payment, not streamed.** The creator\ncan withdraw the whole price the instant it arrives, so a supporter who stops\nbeing active is **not** refunded and no part of a paid period ever comes back.\nThat is a real limitation, and it is v0 on purpose: escrowed streaming, where\nthe creator claims only what has elapsed and the supporter cancels and reclaims\nthe rest, needs a claim schedule and a refund path. That is a larger realm than\nthis one, not a flag on it, and it is the v1.\n\n**The trap it avoids: money leaves by pull, never by a push loop.** Nothing\nhere moves a coin. `Subscribe` credits a\n[`pullpayment`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/daily/pullpayment)\nledger, and `Withdraw` zeroes a credit and reports what was owed so the holding\nrealm transfers afterwards, with the balance already gone when control leaves.\nA realm that looped over payees instead would fail entirely on one unpayable\naddress and hand a griefer a cheap denial of service.\n\n**A title and a description are attacker-controlled markdown.** `ValidTitle`\nand `ValidDescription` bound them and refuse control characters, which is a\ndifferent protection from escaping and not a substitute for it. One note for\nwhoever renders them: `md.Link` escapes its text with the *inline* escaper, and\nthe inline escaper does not touch a pipe, so a caller's title carried inside a\nlink inside a table cell still opens a column. In a table, the link text has to\nbe something the realm owns and the title gets `ui.Cell`.\n\n## v0 ships no token, and that is the answer rather than a gap\n\nA creator coin minted per period paid is the easy half. The sink is not: what a\nsupporter would redeem it for is a promise the creator makes off chain, and a\ntoken whose only sink is a promise is a scoreboard with a price. It would also\ncompete with the thing that already works here, which is that a period is paid\nin ugnot and either active or not.\n\nWhat would change the answer is a **redeem the creator can be held to on\nchain**: a queue position the realm enforces, an allocation it hands out, an\naccess gate another realm checks before it lets somebody in. Any of those turns\nthe coin into a claim rather than a souvenir, and at that point the mint rule,\nthe sink and the buyer can all be named.\n\nUntil one of them exists, the condition is the deliverable. The sibling package\n`gno.land/p/moul/x/social/coin/v0` is where that gets enforced: a GRC20 that\nrefuses to exist until its mint rule, its sink and its buyer are declared. This\npackage does not import it, and will not until there is something true to\ndeclare.\n\n**Live realm:** [`r/moul/x/social/patron`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/social/patron)\n· render it at [`/r/moul/x/social/patron/v0`](https://gno.land/r/moul/x/social/patron/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/social/patron/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/social/patron/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/social/patron/v0\"\ngno = \"0.9\"\n"},{"name":"patron.gno","body":"// Package patron is the engine behind recurring support for a builder: a plan\n// somebody subscribes to, period after period, paid in ugnot on chain.\n//\n// # There is no cron on chain, so a renewal is a pull and not a push\n//\n// Nothing here can charge anybody. The supporter sends another payment and\n// their paid-through height moves forward; there is no scheduler, no keeper,\n// and no standing authority over anybody's balance. There is no way to write\n// one either, because a native coin cannot be pulled at all: a banker may only\n// spend its own realm's address, so the inbound path is always the holder\n// signing. A reader arriving from web2 expects the opposite, and that is the\n// one expectation to unlearn before reading the rest of this package.\n//\n// # What this adds over a tip jar\n//\n// A tip jar is one payment and then nothing, and the one-shot version is\n// already live at gno.land/r/moul/x/daily/tipjar. The recurrence is the only\n// reason this exists: a plan carries a price per period and a period measured\n// in BLOCKS, a supporter buys whole periods, and anybody can ask at any height\n// whether a given address is still active. It is the one piece of the x/social\n// family that produces a recurring write rather than a one-off.\n//\n// # The model\n//\n//\tRegistry  every plan, plus the credit ledger money leaves through\n//\tPlan      a creator, a title, a description, a price, a period, open or not\n//\tPayment   what one Subscribe call bought: periods, spent, change, through\n//\n// # Renewing early never loses time already paid for\n//\n// [Registry.Subscribe] extends from whichever is LATER, now or the supporter's\n// current paid-through height. Renewing two blocks before a lapse adds a whole\n// period on top of what is left. Renewing after a lapse starts from now,\n// because the gap was never paid for and nothing backdates it.\n//\n// # The change is credited back, never kept\n//\n// A payment buys floor(sent / price) whole periods, and the remainder under\n// one period is credited to the SUPPORTER's own withdrawable balance. Keeping\n// it would be a fee nobody agreed to, and a silent fee is the thing a\n// subscription realm must not have. The supporter takes it back through the\n// same [Registry.Withdraw] a creator uses.\n//\n// # Earnings are credited at the moment of payment, not streamed\n//\n// The creator can withdraw the whole price the instant it is paid. A supporter\n// who stops being active is therefore NOT refunded, and no part of a paid\n// period is ever returned. That is a real limitation and it is v0 on purpose:\n// escrowed streaming, where the creator claims only what has elapsed and the\n// supporter can cancel and reclaim the rest, needs a claim schedule and a\n// refund path, which is a bigger realm than this one. It is the v1, and it is\n// not a line that can be bolted onto this one.\n//\n// # Money leaves by pull, never by a push loop\n//\n// Nothing here moves coins. [Registry.Subscribe] credits a\n// gno.land/p/moul/x/daily/pullpayment ledger, and [Registry.Withdraw] zeroes a\n// credit and reports what was owed so the holding realm can transfer after\n// that call, with the balance already gone when control leaves. A realm that\n// looped over payees instead would fail entirely on one unpayable address and\n// hand a griefer a cheap denial of service.\n//\n// # A title and a description are attacker-controlled markdown\n//\n// Both are free text. [ValidTitle] and [ValidDescription] bound them and\n// refuse control characters, which is a different protection from escaping and\n// not a substitute for it: a realm that renders either one escapes it with\n// ui.Inline in prose or ui.Cell in a table cell.\npackage patron\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/x/daily/pullpayment/v0\"\n\t\"gno.land/p/moul/xmath/v1\"\n)\n\nconst (\n\t// MaxTitleLen and MaxDescriptionLen bound the two free-text fields. Long\n\t// enough to say what the plan is, short enough that opening one cannot\n\t// lock an unbounded storage deposit somebody else is paying for.\n\tMaxTitleLen       = 80\n\tMaxDescriptionLen = 500\n\n\t// MinPeriodBlocks and MaxPeriodBlocks bound a period both ways. A period\n\t// of zero blocks is not a subscription, it is a division by zero wearing\n\t// a price tag. The ceiling is about a year at the five second blocks the\n\t// test chain runs, past which \"recurring\" stops meaning anything and the\n\t// plan is a one-off with extra steps.\n\tMinPeriodBlocks = int64(10)\n\tMaxPeriodBlocks = int64(6307200)\n\n\t// MinPricePerPeriod is one ugnot, because a free plan is a tip jar\n\t// (gno.land/r/moul/x/daily/tipjar) and not a subscription: at a price of\n\t// zero there is nothing to buy a period with and every address would be\n\t// active forever.\n\tMinPricePerPeriod = int64(1)\n\n\t// MaxPeriodsPerPayment bounds what one payment may buy. It keeps\n\t// periods * PeriodBlocks inside an int64 by construction rather than by\n\t// hope, and it stops a single send from parking a paid-through height so\n\t// far ahead that no later arithmetic on it means anything.\n\tMaxPeriodsPerPayment = int64(10000)\n)\n\n// The errors a caller can get back. A p/ package returns them and the realm\n// decides to abort.\nvar (\n\tErrBadTitle          = errors.New(\"patron: title is empty, too long, or has control characters\")\n\tErrBadDescription    = errors.New(\"patron: description is too long or has control characters\")\n\tErrBadPrice          = errors.New(\"patron: a plan needs a price of at least one ugnot per period\")\n\tErrBadPeriod         = errors.New(\"patron: period out of range\")\n\tErrNoPlan            = errors.New(\"patron: no such plan\")\n\tErrPlanClosed        = errors.New(\"patron: this plan is closed to new subscriptions\")\n\tErrNotCreator        = errors.New(\"patron: only the plan's creator can do that\")\n\tErrAlreadyOpen       = errors.New(\"patron: the plan is already open\")\n\tErrAlreadyClosed     = errors.New(\"patron: the plan is already closed\")\n\tErrShortOfOnePeriod  = errors.New(\"patron: the payment does not cover one whole period\")\n\tErrTooManyPeriods    = errors.New(\"patron: one payment cannot buy that many periods\")\n\tErrNothingToWithdraw = errors.New(\"patron: nothing to withdraw\")\n)\n\n// Plan is one creator's recurring support plan.\ntype Plan struct {\n\tCreator     address\n\tTitle       string\n\tDescription string\n\n\t// PricePerPeriod is what one period costs, in ugnot.\n\tPricePerPeriod int64\n\n\t// PeriodBlocks is how long a period lasts, in blocks. Blocks and not\n\t// seconds: height is the clock consensus agrees on, and a block timestamp\n\t// is set by proposers and is not something to build a billing cliff out\n\t// of at second resolution.\n\tPeriodBlocks int64\n\n\t// Open reports whether the plan takes NEW payments. Closing it never\n\t// touches a subscription already paid for, which runs to its own\n\t// paid-through height.\n\tOpen bool\n\n\t// Received is the lifetime ugnot this plan credited to its creator.\n\tReceived int64\n\n\t// paidThrough is the first height at which a supporter is no longer\n\t// active. A supporter is active while now \u003c paidThrough, so a period\n\t// bought at height h ends at h+PeriodBlocks and the holder is inactive\n\t// at exactly that height.\n\tpaidThrough map[string]int64\n\n\t// supporters is every address that has ever paid, in first-payment\n\t// order. It exists so a listing is deterministic without iterating a map\n\t// as if insertion order were a sort.\n\tsupporters []address\n}\n\n// PaidThrough is the height who stops being active at, or zero if they never\n// paid.\nfunc (p *Plan) PaidThrough(who address) int64 {\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.paidThrough[who.String()]\n}\n\n// IsActive reports whether who is paid up at height now.\n//\n// The comparison is strict: a supporter paid through height h is active at\n// h-1 and not at h. One rule, applied at both edges, so a period never\n// overlaps the next one by a block.\nfunc (p *Plan) IsActive(who address, now int64) bool {\n\treturn p.PaidThrough(who) \u003e now\n}\n\n// SupporterCount is how many distinct addresses have ever paid, active or not.\nfunc (p *Plan) SupporterCount() int {\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn len(p.supporters)\n}\n\n// Supporters is every address that has ever paid, in first-payment order.\n//\n// It returns a copy. Handing out the stored slice would be a live mutation\n// handle on realm state, which is the cheapest way for a reader to become a\n// writer.\nfunc (p *Plan) Supporters() []address {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tout := make([]address, len(p.supporters))\n\tcopy(out, p.supporters)\n\treturn out\n}\n\n// ActiveCount is how many supporters are paid up at height now.\nfunc (p *Plan) ActiveCount(now int64) int {\n\tif p == nil {\n\t\treturn 0\n\t}\n\tn := 0\n\tfor _, who := range p.supporters {\n\t\tif p.IsActive(who, now) {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// Payment is what one [Registry.Subscribe] call bought.\ntype Payment struct {\n\t// Periods is how many whole periods the payment covered.\n\tPeriods int64\n\n\t// Spent is the ugnot those periods cost, credited to the creator.\n\tSpent int64\n\n\t// Change is the remainder under one period, credited back to the\n\t// supporter rather than kept.\n\tChange int64\n\n\t// PaidThrough is the supporter's new paid-through height.\n\tPaidThrough int64\n\n\t// NewSupporter reports whether this address had never paid this plan\n\t// before, which is the signal a realm wants for an event or a counter.\n\tNewSupporter bool\n}\n\n// Registry holds every plan and the credit ledger money leaves through.\ntype Registry struct {\n\tplans  *store.Store\n\tledger *pullpayment.Ledger\n\n\t// earned is lifetime ugnot credited per creator, which survives a\n\t// withdrawal. The ledger only knows what is owed RIGHT NOW, and a page\n\t// showing a creator zero the moment they cash out would be telling the\n\t// truth about the wrong question.\n\tearned map[string]int64\n}\n\n// NewRegistry returns an empty registry.\nfunc NewRegistry() *Registry {\n\treturn \u0026Registry{\n\t\tplans:  store.Named(\"plan\"),\n\t\tledger: pullpayment.New(),\n\t\tearned: map[string]int64{},\n\t}\n}\n\n// Open creates a plan and returns its id. Anyone may open one.\nfunc (r *Registry) Open(creator address, title, description string, pricePerPeriod, periodBlocks int64) (store.ID, error) {\n\tif !ValidTitle(title) {\n\t\treturn 0, ErrBadTitle\n\t}\n\tif !ValidDescription(description) {\n\t\treturn 0, ErrBadDescription\n\t}\n\tif pricePerPeriod \u003c MinPricePerPeriod {\n\t\treturn 0, ErrBadPrice\n\t}\n\tif periodBlocks \u003c MinPeriodBlocks || periodBlocks \u003e MaxPeriodBlocks {\n\t\treturn 0, ErrBadPeriod\n\t}\n\treturn r.plans.Add(\u0026Plan{\n\t\tCreator:        creator,\n\t\tTitle:          title,\n\t\tDescription:    description,\n\t\tPricePerPeriod: pricePerPeriod,\n\t\tPeriodBlocks:   periodBlocks,\n\t\tOpen:           true,\n\t\tpaidThrough:    map[string]int64{},\n\t}), nil\n}\n\n// Subscribe buys whole periods on a plan with sent ugnot, at height now.\n//\n// It refuses anything short of one period, buys floor(sent / price) of them,\n// and credits the remainder back to the supporter. The extension starts from\n// whichever is LATER, now or the supporter's current paid-through height, so\n// renewing early never discards time already paid for and renewing after a\n// lapse never backdates the gap.\n//\n// The creator is credited at the moment of payment, not as the periods\n// elapse. See the package doc for why that is v0 and what v1 would have to\n// carry instead.\nfunc (r *Registry) Subscribe(id store.ID, who address, sent, now int64) (Payment, error) {\n\tp, ok := r.Get(id)\n\tif !ok {\n\t\treturn Payment{}, ErrNoPlan\n\t}\n\tif !p.Open {\n\t\treturn Payment{}, ErrPlanClosed\n\t}\n\tif sent \u003c p.PricePerPeriod {\n\t\treturn Payment{}, ErrShortOfOnePeriod\n\t}\n\n\t// The one rounding decision in this function: periods is floor, so a\n\t// supporter is never sold a period they did not fully fund, and the\n\t// remainder is handed back below rather than kept. Neither side keeps a\n\t// fraction of a period.\n\tperiods := sent / p.PricePerPeriod\n\tif periods \u003e MaxPeriodsPerPayment {\n\t\treturn Payment{}, ErrTooManyPeriods\n\t}\n\tspent := sent - sent%p.PricePerPeriod\n\tchange := sent - spent\n\n\t// spent is an exact whole number of periods, so this division leaves no\n\t// remainder and there is no second rounding direction to choose. MulDiv\n\t// is here for the intermediate: spent * PeriodBlocks overflows an int64\n\t// for a plan priced in whole GNOT with a period measured in months, and\n\t// the naive product wraps to a plausible-looking height rather than to an\n\t// obvious one. MulDivUp would be identical on an exact division; MulDiv\n\t// says plainly that nothing is being rounded up.\n\tadded := xmath.MulDiv(spent, p.PeriodBlocks, p.PricePerPeriod)\n\n\tfrom := now\n\tif pt := p.PaidThrough(who); pt \u003e from {\n\t\tfrom = pt\n\t}\n\tthrough := from + added\n\n\tkey := who.String()\n\n\t// Both credits happen before the plan is touched, and both can fail: the\n\t// ledger is bounded and guards its own overflow. A realm calling this\n\t// aborts on the error, which reverts everything written in the same\n\t// frame, so a half-applied subscription is not reachable from a crossing\n\t// call. The ordering is what makes that true for every other caller too.\n\tif err := r.ledger.Credit(p.Creator.String(), spent); err != nil {\n\t\treturn Payment{}, err\n\t}\n\tif change \u003e 0 {\n\t\tif err := r.ledger.Credit(key, change); err != nil {\n\t\t\treturn Payment{}, err\n\t\t}\n\t}\n\tr.earned[p.Creator.String()] += spent\n\n\t_, seen := p.paidThrough[key]\n\tif !seen {\n\t\tp.supporters = append(p.supporters, who)\n\t}\n\tp.paidThrough[key] = through\n\tp.Received += spent\n\n\treturn Payment{\n\t\tPeriods:      periods,\n\t\tSpent:        spent,\n\t\tChange:       change,\n\t\tPaidThrough:  through,\n\t\tNewSupporter: !seen,\n\t}, nil\n}\n\n// Close stops a plan taking new subscriptions. Creator only.\n//\n// It does not touch anything already paid for: existing supporters run to\n// their own paid-through height, which is the only behaviour that does not\n// turn closing a plan into taking money back.\nfunc (r *Registry) Close(id store.ID, who address) error {\n\tp, err := r.ownPlan(id, who)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !p.Open {\n\t\treturn ErrAlreadyClosed\n\t}\n\tp.Open = false\n\treturn nil\n}\n\n// Reopen lets a closed plan take subscriptions again. Creator only.\nfunc (r *Registry) Reopen(id store.ID, who address) error {\n\tp, err := r.ownPlan(id, who)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif p.Open {\n\t\treturn ErrAlreadyOpen\n\t}\n\tp.Open = true\n\treturn nil\n}\n\n// ownPlan is the shared lookup plus authority check, so Close and Reopen\n// cannot drift apart on who is allowed to call them.\nfunc (r *Registry) ownPlan(id store.ID, who address) (*Plan, error) {\n\tp, ok := r.Get(id)\n\tif !ok {\n\t\treturn nil, ErrNoPlan\n\t}\n\tif p.Creator != who {\n\t\treturn nil, ErrNotCreator\n\t}\n\treturn p, nil\n}\n\n// Withdraw zeroes who's credit and reports what they were owed.\n//\n// It moves no coins. The holding realm transfers the returned amount AFTER\n// this call, which is the whole point of the pattern: the credit is already\n// gone from the ledger when control passes to the payee, so a reentrant call\n// finds nothing and gets [ErrNothingToWithdraw].\nfunc (r *Registry) Withdraw(who address) (int64, error) {\n\tamount, err := r.ledger.Withdraw(who.String())\n\tif err != nil {\n\t\treturn 0, ErrNothingToWithdraw\n\t}\n\treturn amount, nil\n}\n\n// CreditOf is what addr can withdraw right now: earnings as a creator, change\n// as a supporter, or both.\nfunc (r *Registry) CreditOf(addr address) int64 { return r.ledger.Balance(addr.String()) }\n\n// EarnedBy is the lifetime ugnot credited to creator across every plan,\n// whether or not it has been withdrawn.\nfunc (r *Registry) EarnedBy(creator address) int64 { return r.earned[creator.String()] }\n\n// TotalOwed is everything the holding realm must keep in reserve.\nfunc (r *Registry) TotalOwed() int64 { return r.ledger.TotalOwed() }\n\n// Get returns a plan by id.\nfunc (r *Registry) Get(id store.ID) (*Plan, bool) {\n\tv, ok := r.plans.Get(id)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn v.(*Plan), true\n}\n\n// Count is how many plans exist.\nfunc (r *Registry) Count() int { return r.plans.Len() }\n\n// Listing is one row of [Registry.List]: the plan and the id a link needs.\ntype Listing struct {\n\tID   store.ID\n\tPlan *Plan\n}\n\n// List returns one page of plans, newest first.\nfunc (r *Registry) List(page, size int) []Listing {\n\tvar out []Listing\n\tfor _, e := range r.plans.PageReverse(page, size) {\n\t\tout = append(out, Listing{ID: e.ID, Plan: e.Value.(*Plan)})\n\t}\n\treturn out\n}\n\n// Pages is how many pages of the given size the registry holds.\nfunc (r *Registry) Pages(size int) int { return r.plans.Pages(size) }\n\n// ValidTitle reports whether title can be stored: non-empty after trimming,\n// within [MaxTitleLen], and free of control characters including newlines.\n//\n// A title is one line by construction, so a newline in one is refused rather\n// than stripped: silently rewriting what somebody typed is worse than telling\n// them it was refused.\nfunc ValidTitle(title string) bool {\n\tif len(title) \u003e MaxTitleLen || strings.TrimSpace(title) == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(title); i++ {\n\t\tif c := title[i]; c \u003c 0x20 || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidDescription reports whether description can be stored: within\n// [MaxDescriptionLen] and free of control characters other than newline and\n// tab. Empty is allowed, because a plan whose title says it all should not\n// have to invent prose.\nfunc ValidDescription(description string) bool {\n\tif len(description) \u003e MaxDescriptionLen {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(description); i++ {\n\t\tc := description[i]\n\t\tif c \u003c 0x20 \u0026\u0026 c != '\\n' \u0026\u0026 c != '\\t' || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// PlanURL is the gnoweb path of one plan on the hosting realm.\nfunc PlanURL(realmPath string, id store.ID) string {\n\treturn RealmURL(realmPath) + \":plan/\" + id.String()\n}\n\n// RealmURL is the gnoweb path of a realm given as a package path.\n//\n// The chain domain is the first element of a package path and a gnoweb path is\n// the rest of it, so this is a prefix strip and not a hostname this package\n// has to know.\nfunc RealmURL(realmPath string) string {\n\tif i := strings.Index(realmPath, \"/\"); i \u003e= 0 {\n\t\treturn realmPath[i:]\n\t}\n\treturn \"/\" + realmPath\n}\n"},{"name":"patron_test.gno","body":"package patron\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// plan opens one plan with the given price and period and returns its id,\n// failing the test rather than returning an error nobody reads.\nfunc plan(t *testing.T, r *Registry, price, period int64) store.ID {\n\tt.Helper()\n\tid, err := r.Open(alice, \"a plan\", \"every period, forever\", price, period)\n\turequire.NoError(t, err)\n\treturn id\n}\n\n// planOf reads a plan back, failing the test when it is not there.\nfunc planOf(t *testing.T, r *Registry, id store.ID) *Plan {\n\tt.Helper()\n\tp, ok := r.Get(id)\n\turequire.True(t, ok, \"plan #\"+id.String()+\" exists\")\n\treturn p\n}\n\nfunc TestValidTitle(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\ttitle string\n\t\twant  bool\n\t}{\n\t\t{\"plain\", \"monthly support\", true},\n\t\t{\"markdown is allowed and escaped later\", \"[x](y) | z\", true},\n\t\t{\"at the limit\", strings.Repeat(\"x\", MaxTitleLen), true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"blank\", \"   \", false},\n\t\t{\"too long\", strings.Repeat(\"x\", MaxTitleLen+1), false},\n\t\t{\"a title is one line\", \"two\\nlines\", false},\n\t\t{\"tab is a control character here\", \"a\\tb\", false},\n\t\t{\"delete character\", \"a\\x7fb\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidTitle(tt.title), tt.name)\n\t}\n}\n\nfunc TestValidDescription(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdesc string\n\t\twant bool\n\t}{\n\t\t{\"empty is fine, the title may say it all\", \"\", true},\n\t\t{\"newlines and tabs are content\", \"a\\nb\\tc\", true},\n\t\t{\"at the limit\", strings.Repeat(\"x\", MaxDescriptionLen), true},\n\t\t{\"too long\", strings.Repeat(\"x\", MaxDescriptionLen+1), false},\n\t\t{\"control character\", \"a\\x01b\", false},\n\t\t{\"delete character\", \"a\\x7fb\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidDescription(tt.desc), tt.name)\n\t}\n}\n\nfunc TestOpenRejectsWhatItCannotStore(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\ttitle  string\n\t\tdesc   string\n\t\tprice  int64\n\t\tperiod int64\n\t\twant   error\n\t}{\n\t\t{\"no title\", \"\", \"d\", 100, 100, ErrBadTitle},\n\t\t{\"description too long\", \"t\", strings.Repeat(\"x\", MaxDescriptionLen+1), 100, 100, ErrBadDescription},\n\t\t{\"a free plan is a tip jar\", \"t\", \"d\", 0, 100, ErrBadPrice},\n\t\t{\"a negative price\", \"t\", \"d\", -1, 100, ErrBadPrice},\n\t\t{\"no period at all\", \"t\", \"d\", 100, 0, ErrBadPeriod},\n\t\t{\"under the floor\", \"t\", \"d\", 100, MinPeriodBlocks - 1, ErrBadPeriod},\n\t\t{\"over the ceiling\", \"t\", \"d\", 100, MaxPeriodBlocks + 1, ErrBadPeriod},\n\t}\n\tr := NewRegistry()\n\tfor _, tt := range tests {\n\t\t_, err := r.Open(alice, tt.title, tt.desc, tt.price, tt.period)\n\t\tuassert.ErrorIs(t, err, tt.want, tt.name)\n\t}\n\tuassert.Equal(t, 0, r.Count(), \"nothing refused was stored\")\n\n\t// The edges themselves are accepted.\n\t_, err := r.Open(alice, \"t\", \"\", MinPricePerPeriod, MinPeriodBlocks)\n\tuassert.NoError(t, err)\n\t_, err = r.Open(alice, \"t\", \"\", MinPricePerPeriod, MaxPeriodBlocks)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, 2, r.Count())\n}\n\nfunc TestOnePeriodBuysExactlyOnePeriod(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\tpay, err := r.Subscribe(id, bob, 1000, 500)\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, int64(1), pay.Periods)\n\tuassert.Equal(t, int64(1000), pay.Spent)\n\tuassert.Equal(t, int64(0), pay.Change)\n\tuassert.Equal(t, int64(600), pay.PaidThrough, \"500 + one period of 100 blocks\")\n\tuassert.True(t, pay.NewSupporter)\n\n\tuassert.Equal(t, int64(1000), r.CreditOf(alice), \"the creator is credited at payment time\")\n\tuassert.Equal(t, int64(1000), r.EarnedBy(alice))\n\tuassert.Equal(t, int64(0), r.CreditOf(bob), \"an exact payment leaves no change\")\n\tuassert.Equal(t, int64(1000), r.TotalOwed())\n}\n\nfunc TestThreePeriodsAtOnce(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\tpay, err := r.Subscribe(id, bob, 3000, 500)\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, int64(3), pay.Periods)\n\tuassert.Equal(t, int64(3000), pay.Spent)\n\tuassert.Equal(t, int64(0), pay.Change)\n\tuassert.Equal(t, int64(800), pay.PaidThrough, \"three periods of 100 blocks from 500\")\n}\n\n// Renewing before the current period ends adds a whole period on top of what\n// is left, rather than restarting the clock and discarding it.\nfunc TestRenewingEarlyExtendsFromPaidThrough(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\tfirst, err := r.Subscribe(id, bob, 1000, 500)\n\turequire.NoError(t, err)\n\turequire.Equal(t, int64(600), first.PaidThrough)\n\n\t// Two blocks before the lapse, with 98 blocks still paid for.\n\tsecond, err := r.Subscribe(id, bob, 1000, 502)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(700), second.PaidThrough, \"600 + 100, not 502 + 100\")\n\tuassert.False(t, second.NewSupporter, \"bob was already a supporter\")\n\tuassert.Equal(t, 1, planOf(t, r, id).SupporterCount(), \"renewing is not a second supporter\")\n}\n\n// Renewing after a lapse starts from now: the gap was never paid for and\n// nothing backdates it.\nfunc TestRenewingAfterLapseStartsFromNow(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\t_, err := r.Subscribe(id, bob, 1000, 500)\n\turequire.NoError(t, err)\n\n\t// 900 is long past the 600 the first period ran to.\n\tsecond, err := r.Subscribe(id, bob, 1000, 900)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1000), second.PaidThrough, \"900 + 100, the gap is not backdated\")\n}\n\n// Paying exactly at the paid-through height is the boundary between the two\n// rules above, and it resolves the same way either way: 600 is not later than\n// 600, so the extension runs from 600.\nfunc TestRenewingAtTheBoundary(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\t_, err := r.Subscribe(id, bob, 1000, 500)\n\turequire.NoError(t, err)\n\tsecond, err := r.Subscribe(id, bob, 1000, 600)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(700), second.PaidThrough)\n}\n\nfunc TestAPaymentShortOfOnePeriodIsRefused(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\tfor _, sent := range []int64{0, 1, 999} {\n\t\t_, err := r.Subscribe(id, bob, sent, 500)\n\t\tuassert.ErrorIs(t, err, ErrShortOfOnePeriod)\n\t}\n\tuassert.Equal(t, int64(0), r.CreditOf(alice), \"a refused payment credits nobody\")\n\tuassert.Equal(t, int64(0), planOf(t, r, id).PaidThrough(bob))\n\tuassert.Equal(t, 0, planOf(t, r, id).SupporterCount())\n}\n\n// The remainder under one period is the supporter's, not the realm's: keeping\n// it would be a fee nobody agreed to.\nfunc TestChangeIsCreditedBackAndIsWithdrawable(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\tpay, err := r.Subscribe(id, bob, 2500, 500)\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, int64(2), pay.Periods)\n\tuassert.Equal(t, int64(2000), pay.Spent)\n\tuassert.Equal(t, int64(500), pay.Change)\n\tuassert.Equal(t, int64(700), pay.PaidThrough)\n\n\tuassert.Equal(t, int64(500), r.CreditOf(bob), \"the change is the supporter's\")\n\tuassert.Equal(t, int64(2000), r.CreditOf(alice))\n\tuassert.Equal(t, int64(2500), r.TotalOwed(), \"every ugnot that came in is owed to somebody\")\n\tuassert.Equal(t, int64(0), r.EarnedBy(bob), \"change is not earnings\")\n\n\tgot, err := r.Withdraw(bob)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(500), got)\n\tuassert.Equal(t, int64(0), r.CreditOf(bob))\n\tuassert.Equal(t, int64(2000), r.TotalOwed())\n}\n\n// Withdraw zeroes the credit before it reports it, so the second call of a\n// reentrant pair finds nothing.\nfunc TestWithdrawZeroesBeforeItPays(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\t_, err := r.Subscribe(id, bob, 1000, 500)\n\turequire.NoError(t, err)\n\n\tgot, err := r.Withdraw(alice)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1000), got)\n\n\t_, err = r.Withdraw(alice)\n\tuassert.ErrorIs(t, err, ErrNothingToWithdraw)\n\n\t_, err = r.Withdraw(carol)\n\tuassert.ErrorIs(t, err, ErrNothingToWithdraw, \"an address owed nothing withdraws nothing\")\n\n\tuassert.Equal(t, int64(1000), r.EarnedBy(alice), \"earnings outlive the withdrawal\")\n\tuassert.Equal(t, int64(0), r.CreditOf(alice))\n}\n\n// IsActive is strict on both sides: active at paidThrough-1, not at\n// paidThrough.\nfunc TestIsActiveFlipsAtTheRightHeight(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\t_, err := r.Subscribe(id, bob, 1000, 500)\n\turequire.NoError(t, err)\n\tp := planOf(t, r, id)\n\n\ttests := []struct {\n\t\tname string\n\t\tnow  int64\n\t\twant bool\n\t}{\n\t\t{\"the block it was bought in\", 500, true},\n\t\t{\"one before the end\", 599, true},\n\t\t{\"the end itself\", 600, false},\n\t\t{\"after\", 601, false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, p.IsActive(bob, tt.now), tt.name)\n\t}\n\n\tuassert.False(t, p.IsActive(carol, 500), \"an address that never paid is never active\")\n\tuassert.Equal(t, int64(600), p.PaidThrough(bob))\n\tuassert.Equal(t, int64(0), p.PaidThrough(carol))\n\tuassert.Equal(t, 1, p.ActiveCount(599))\n\tuassert.Equal(t, 0, p.ActiveCount(600))\n}\n\nfunc TestCloseStopsNewMoneyAndNotPaidTime(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\t_, err := r.Subscribe(id, bob, 1000, 500)\n\turequire.NoError(t, err)\n\n\tuassert.ErrorIs(t, r.Close(id, bob), ErrNotCreator)\n\turequire.NoError(t, r.Close(id, alice))\n\tuassert.ErrorIs(t, r.Close(id, alice), ErrAlreadyClosed)\n\n\t_, err = r.Subscribe(id, carol, 1000, 501)\n\tuassert.ErrorIs(t, err, ErrPlanClosed)\n\n\tp := planOf(t, r, id)\n\tuassert.False(t, p.Open)\n\tuassert.True(t, p.IsActive(bob, 599), \"a closed plan does not take back a paid period\")\n\n\tuassert.ErrorIs(t, r.Reopen(id, bob), ErrNotCreator)\n\turequire.NoError(t, r.Reopen(id, alice))\n\tuassert.ErrorIs(t, r.Reopen(id, alice), ErrAlreadyOpen)\n\n\t_, err = r.Subscribe(id, carol, 1000, 501)\n\tuassert.NoError(t, err)\n}\n\nfunc TestNothingWorksOnAPlanThatIsNotThere(t *testing.T) {\n\tr := NewRegistry()\n\t_, err := r.Subscribe(4242, bob, 1000, 500)\n\tuassert.ErrorIs(t, err, ErrNoPlan)\n\tuassert.ErrorIs(t, r.Close(4242, alice), ErrNoPlan)\n\tuassert.ErrorIs(t, r.Reopen(4242, alice), ErrNoPlan)\n\n\t_, ok := r.Get(4242)\n\tuassert.False(t, ok)\n}\n\nfunc TestOnePaymentCannotBuyUnboundedTime(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1, MaxPeriodBlocks)\n\n\t_, err := r.Subscribe(id, bob, MaxPeriodsPerPayment+1, 500)\n\tuassert.ErrorIs(t, err, ErrTooManyPeriods)\n\tuassert.Equal(t, int64(0), planOf(t, r, id).PaidThrough(bob))\n\n\t// The ceiling itself is accepted, and the product is the one place the\n\t// naive arithmetic would have wrapped.\n\tpay, err := r.Subscribe(id, bob, MaxPeriodsPerPayment, 500)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 500+MaxPeriodsPerPayment*MaxPeriodBlocks, pay.PaidThrough)\n}\n\nfunc TestSupportersAreDistinctAndInFirstPaymentOrder(t *testing.T) {\n\tr := NewRegistry()\n\tid := plan(t, r, 1000, 100)\n\n\t_, err := r.Subscribe(id, carol, 1000, 500)\n\turequire.NoError(t, err)\n\t_, err = r.Subscribe(id, bob, 1000, 501)\n\turequire.NoError(t, err)\n\t_, err = r.Subscribe(id, carol, 1000, 502)\n\turequire.NoError(t, err)\n\n\tp := planOf(t, r, id)\n\tgot := p.Supporters()\n\turequire.Equal(t, 2, len(got))\n\tuassert.Equal(t, carol.String(), got[0].String(), \"first payment wins the first slot\")\n\tuassert.Equal(t, bob.String(), got[1].String())\n\tuassert.Equal(t, 2, p.SupporterCount())\n\n\t// The slice handed out is a copy: writing to it cannot reach the plan.\n\tgot[0] = bob\n\tuassert.Equal(t, carol.String(), p.Supporters()[0].String())\n}\n\nfunc TestEarningsAccumulateAcrossPlansAndSupporters(t *testing.T) {\n\tr := NewRegistry()\n\tfirst := plan(t, r, 1000, 100)\n\tsecond := plan(t, r, 2000, 200)\n\n\t_, err := r.Subscribe(first, bob, 1000, 500)\n\turequire.NoError(t, err)\n\t_, err = r.Subscribe(second, carol, 4000, 500)\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, int64(5000), r.EarnedBy(alice))\n\tuassert.Equal(t, int64(5000), r.CreditOf(alice))\n\tuassert.Equal(t, int64(1000), planOf(t, r, first).Received)\n\tuassert.Equal(t, int64(4000), planOf(t, r, second).Received)\n\tuassert.Equal(t, 2, r.Count())\n}\n\nfunc TestListIsNewestFirst(t *testing.T) {\n\tr := NewRegistry()\n\tfirst := plan(t, r, 1000, 100)\n\tsecond := plan(t, r, 1000, 100)\n\tthird := plan(t, r, 1000, 100)\n\n\tgot := r.List(1, 10)\n\turequire.Equal(t, 3, len(got))\n\tuassert.Equal(t, uint64(third), uint64(got[0].ID))\n\tuassert.Equal(t, uint64(second), uint64(got[1].ID))\n\tuassert.Equal(t, uint64(first), uint64(got[2].ID))\n\tuassert.Equal(t, 2, r.Pages(2))\n\tuassert.Equal(t, 0, len(r.List(9, 10)))\n}\n\nfunc TestURLsStripTheChainDomain(t *testing.T) {\n\tuassert.Equal(t, \"/r/moul/x/social/patron/v0\", RealmURL(\"gno.land/r/moul/x/social/patron/v0\"))\n\tuassert.Equal(t, \"/r/a/b:plan/7\", PlanURL(\"gno.land/r/a/b\", 7))\n}\n"}]},"send":"","max_deposit":"15000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"threads","path":"gno.land/p/moul/x/social/threads/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/social/threads/v0`\n\n**The engine behind an embeddable discussion block**, keyed on the page it is\nshown under rather than on the realm that stores it: `NewBoard`, `Post`,\n`Reply`, `Pin`, `List`, `Recent`, `Block`.\n\n```go\nb := threads.NewBoard()\nid, _ := b.Post(\"gno.land/r/moul/home\", author, \"worth discussing\", height)\nisNew, _ := b.Reply(id, replier, \"it is\", height)   // isNew is the mint signal\nb.Pin(id, height+1000)                              // placement, bought elsewhere\nthreads.Block(realmPath, page, b.List(page, height, 5), b.PageLen(page), height)\n```\n\n**A forum is a destination and has to earn its traffic before anybody writes\nthe first post. A block does not.** It is dropped into pages that already have\nreaders, and the discussion attaches to the object it is about: a realm page, a\nproposal, an address. One realm holds every thread, every host realm ships the\nsame two lines, and no host realm stores anything. That is the shape the web\nsettled on for comments in 2010, and the same one\n[`p/moul/reactions`](https://github.com/moul/gno-contracts/tree/main/p/moul/reactions)\nuses for the tally. The two are deliberate neighbours and share a page key\nformat: reactions are a closed palette and need no moderation, text needs some,\nso a realm can take the cheap one alone.\n\n**`Reply` reports whether the replier was new to that thread**, and that boolean\nis the whole reason the package keeps a replier set. A realm paying an author\nfor attention wants distinct people, not distinct messages, and a thread's own\nauthor replying to themselves is never new. The mint rule then has exactly one\nsignal and exactly one call site.\n\n**`List` is a partition, not a sort**: pinned first, then the rest, both newest\nfirst. No comparator, no tie to break, and two identical calls always produce\nthe same page, which is what a `Render` needs. A pin is an absolute height, so\nit expires on its own and nothing has to sweep it. `Pin` refuses to move a pin\nbackwards, so a cheap pin cannot cut an expensive one short; what a pin costs is\nthe realm's decision, not this package's.\n\n**A body is free text and therefore attacker-controlled markdown.** `ValidBody`\nbounds it and refuses control characters, which is a different protection from\nescaping and not a substitute for it: everything rendered here goes through\n`ui.Inline` or `ui.Cell`, and so must any realm that renders a body itself. Note\n`Block` truncates with `ui.ShortN` and then hands the result to `md.Link`, which\nescapes: `ui.Excerpt` there would escape twice and render the backslashes.\n\nA page key is a package path, validated by `ValidPage` to the same rule\n`p/moul/reactions` uses, so a realm embedding both blocks passes one key to both.\n\n**Live realm:** [`r/moul/x/social/threads`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/social/threads)\n· render it at [`/r/moul/x/social/threads/v0`](https://gno.land/r/moul/x/social/threads/v0).\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/social/threads/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/social/threads/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/social/threads/v0\"\ngno = \"0.9\"\n"},{"name":"threads.gno","body":"// Package threads is the engine behind an embeddable discussion block: the\n// text half of what a reaction bar does, keyed on the PAGE it is shown under\n// rather than on the realm that stores it.\n//\n// # Why not a forum\n//\n// A forum is a destination, and a destination has to earn its traffic before\n// anybody writes the first post. A block does not: it is dropped into pages\n// that already have readers, and the discussion attaches to the object it is\n// about. One realm holds every thread, every host realm ships the same two\n// lines, and no host realm stores anything.\n//\n// That is the shape the web settled on for comments in 2010, and the same one\n// [gno.land/p/moul/reactions] uses for the tally. This package is deliberately\n// its neighbour: reactions are a closed palette and need no moderation, text\n// needs some, and the two are separate so a realm can take the cheap one alone.\n//\n// # The model\n//\n//\tBoard    every thread, across every page\n//\tThread   a root post: page, author, body, height, pin, replies\n//\tReply    an author, a body and a height, and nothing else\n//\n// A thread remembers the set of addresses that have replied to it, which is\n// what lets a realm implement \"earned by being replied to\" without counting\n// one person twice. [Board.Reply] reports whether the replier was new, so the\n// mint rule has exactly one signal and exactly one call site.\n//\n// # Ordering, and the pin\n//\n// [Board.List] returns pinned threads first, then the rest, both newest first,\n// which is a partition and not a sort: no comparator, no tie to break, and the\n// same input always produces the same page. A pin is an absolute height, so it\n// expires on its own and nothing has to be swept.\n//\n// The realm decides what a pin costs. This package only enforces that a pin\n// cannot be moved backwards, so buying one does not shorten somebody else's.\n//\n// # Page keys and bodies\n//\n// A page key is a package path, the full one, chain domain included.\n// [ValidPage] bounds it to a path-shaped lowercase ASCII string of at most\n// [MaxPageLen] bytes, so a stored key can never be a markdown payload. A body\n// is bounded by [MaxBodyLen] and rejected when it carries a control character,\n// but it is otherwise free text and therefore attacker-controlled markdown:\n// everything here escapes it with ui.Inline or ui.Cell, and so must any realm\n// that renders one itself.\npackage threads\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n)\n\nconst (\n\t// MaxPageLen is the longest page key accepted, matching\n\t// gno.land/p/moul/reactions so the two blocks agree on what a page is.\n\tMaxPageLen = 120\n\n\t// MaxBodyLen is the longest post or reply accepted, in bytes. Long\n\t// enough for a real comment, short enough that one call cannot lock an\n\t// unbounded storage deposit somebody else is paying for.\n\tMaxBodyLen = 1000\n\n\t// ExcerptLen is how much of a body a listing shows.\n\tExcerptLen = 60\n)\n\n// The errors a caller can get back. A p/ returns them; the realm decides to\n// abort.\nvar (\n\tErrBadPage   = errors.New(\"threads: not a page key\")\n\tErrBadBody   = errors.New(\"threads: body is empty, too long, or has control characters\")\n\tErrNoThread  = errors.New(\"threads: no such thread\")\n\tErrPinIsPast = errors.New(\"threads: a pin cannot be moved backwards\")\n)\n\n// Reply is one answer under a thread.\ntype Reply struct {\n\tAuthor address\n\tBody   string\n\tAt     int64 // block height\n}\n\n// Thread is a root post and everything under it.\ntype Thread struct {\n\tPage    string\n\tAuthor  address\n\tBody    string\n\tAt      int64 // block height\n\tReplies []Reply\n\n\t// PinnedUntil is the height the thread stops being pinned at. Zero is\n\t// never pinned, and a past height is an expired pin: nothing has to\n\t// sweep it.\n\tPinnedUntil int64\n\n\t// repliers is the set of addresses that have replied, so a thread can\n\t// be scored on people rather than on messages.\n\trepliers map[string]bool\n}\n\n// Pinned reports whether the thread is pinned at height now.\nfunc (t *Thread) Pinned(now int64) bool { return t != nil \u0026\u0026 t.PinnedUntil \u003e now }\n\n// Repliers is how many distinct addresses have replied.\nfunc (t *Thread) Repliers() int {\n\tif t == nil {\n\t\treturn 0\n\t}\n\treturn len(t.repliers)\n}\n\n// HasReplied reports whether who has already replied to this thread.\nfunc (t *Thread) HasReplied(who address) bool {\n\tif t == nil {\n\t\treturn false\n\t}\n\treturn t.repliers[who.String()]\n}\n\n// Board holds every thread, indexed by the page it was posted under.\ntype Board struct {\n\tthreads *store.Store\n\tpages   map[string][]store.ID // page key -\u003e ids, oldest first\n}\n\n// NewBoard returns an empty board.\nfunc NewBoard() *Board {\n\treturn \u0026Board{threads: store.Named(\"thread\"), pages: map[string][]store.ID{}}\n}\n\n// Post opens a thread on page and returns its id.\nfunc (b *Board) Post(page string, author address, body string, at int64) (store.ID, error) {\n\tif !ValidPage(page) {\n\t\treturn 0, ErrBadPage\n\t}\n\tif !ValidBody(body) {\n\t\treturn 0, ErrBadBody\n\t}\n\tid := b.threads.Add(\u0026Thread{\n\t\tPage:     page,\n\t\tAuthor:   author,\n\t\tBody:     body,\n\t\tAt:       at,\n\t\trepliers: map[string]bool{},\n\t})\n\tb.pages[page] = append(b.pages[page], id)\n\treturn id, nil\n}\n\n// Reply appends to a thread and reports whether this author had never replied\n// to it before.\n//\n// That boolean is the mint signal: a realm that pays an author for attention\n// wants distinct people, not distinct messages, and a thread's own author\n// replying to themselves is never new.\nfunc (b *Board) Reply(id store.ID, author address, body string, at int64) (isNewReplier bool, err error) {\n\tt, ok := b.Get(id)\n\tif !ok {\n\t\treturn false, ErrNoThread\n\t}\n\tif !ValidBody(body) {\n\t\treturn false, ErrBadBody\n\t}\n\tt.Replies = append(t.Replies, Reply{Author: author, Body: body, At: at})\n\n\tkey := author.String()\n\tif author == t.Author || t.repliers[key] {\n\t\treturn false, nil\n\t}\n\tt.repliers[key] = true\n\treturn true, nil\n}\n\n// Pin keeps a thread at the top of its page until height until.\n//\n// It refuses to move a pin backwards, so a cheap pin cannot cut short an\n// expensive one, and extends from whichever is later: the current pin or now.\nfunc (b *Board) Pin(id store.ID, until int64) error {\n\tt, ok := b.Get(id)\n\tif !ok {\n\t\treturn ErrNoThread\n\t}\n\tif until \u003c= t.PinnedUntil {\n\t\treturn ErrPinIsPast\n\t}\n\tt.PinnedUntil = until\n\treturn nil\n}\n\n// Get returns a thread by id.\nfunc (b *Board) Get(id store.ID) (*Thread, bool) {\n\tv, ok := b.threads.Get(id)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn v.(*Thread), true\n}\n\n// Len is how many threads exist, across every page.\nfunc (b *Board) Len() int { return b.threads.Len() }\n\n// Pages is how many pages have ever been posted on.\nfunc (b *Board) Pages() int { return len(b.pages) }\n\n// PageLen is how many threads a page holds.\nfunc (b *Board) PageLen(page string) int { return len(b.pages[page]) }\n\n// Listing is one row of [Board.List]: the thread and the id a link needs.\ntype Listing struct {\n\tID     store.ID\n\tThread *Thread\n}\n\n// List returns up to limit threads on page: pinned first, then the rest, both\n// newest first.\n//\n// It is a partition and not a sort. There is no comparator and no tie to\n// break, so two identical calls always produce the same page, which is what a\n// Render needs. limit \u003c= 0 returns everything.\nfunc (b *Board) List(page string, now int64, limit int) []Listing {\n\tids := b.pages[page]\n\tvar pinned, rest []Listing\n\tfor i := len(ids) - 1; i \u003e= 0; i-- {\n\t\tt, ok := b.Get(ids[i])\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\titem := Listing{ID: ids[i], Thread: t}\n\t\tif t.Pinned(now) {\n\t\t\tpinned = append(pinned, item)\n\t\t} else {\n\t\t\trest = append(rest, item)\n\t\t}\n\t}\n\tout := append(pinned, rest...)\n\tif limit \u003e 0 \u0026\u0026 len(out) \u003e limit {\n\t\tout = out[:limit]\n\t}\n\treturn out\n}\n\n// Recent returns up to limit threads from every page, newest first. It is what\n// the hosting realm's own homepage shows.\nfunc (b *Board) Recent(limit int) []Listing {\n\tvar out []Listing\n\tfor _, e := range b.threads.PageReverse(1, limit) {\n\t\tout = append(out, Listing{ID: e.ID, Thread: e.Value.(*Thread)})\n\t}\n\treturn out\n}\n\n// ValidPage reports whether page is a usable page key: path-shaped, lowercase\n// ASCII, no leading, trailing or doubled slash, at most [MaxPageLen] bytes.\n//\n// Same rule as gno.land/p/moul/reactions, deliberately: a realm embedding both\n// blocks passes one key to both.\nfunc ValidPage(page string) bool {\n\tif page == \"\" || len(page) \u003e MaxPageLen {\n\t\treturn false\n\t}\n\tif strings.HasPrefix(page, \"/\") || strings.HasSuffix(page, \"/\") ||\n\t\tstrings.Contains(page, \"//\") || !strings.Contains(page, \"/\") {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(page); i++ {\n\t\tc := page[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '/' || c == '.' || c == '-' || c == '_' || c == ':':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ValidBody reports whether body can be stored: non-empty after trimming,\n// within [MaxBodyLen], and free of control characters.\n//\n// Control characters are refused rather than stripped because a body is shown\n// back to its author: silently rewriting what somebody wrote is worse than\n// telling them it was refused. Everything else is allowed and escaped at\n// render time, since a validator and an escaper protect against different\n// mistakes.\nfunc ValidBody(body string) bool {\n\tif len(body) \u003e MaxBodyLen || strings.TrimSpace(body) == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(body); i++ {\n\t\tc := body[i]\n\t\tif c \u003c 0x20 \u0026\u0026 c != '\\n' \u0026\u0026 c != '\\t' || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Block renders the embeddable widget: the page's threads, then the button\n// that opens a new one.\n//\n// realmPath is the realm that owns Post and Reply, given as the full package\n// path from its gnomod.toml module line. It is a parameter and not a constant\n// because this package is the engine and not the deployment.\nfunc Block(realmPath, page string, items []Listing, total int, now int64) string {\n\tout := \"\"\n\tif len(items) == 0 {\n\t\tout += ui.Empty(\"No discussion yet.\")\n\t} else {\n\t\tt := ui.NewTable(\"\", \"#\", \"thread\", \"by\", \"replies\")\n\t\tfor _, it := range items {\n\t\t\tmark := \"\"\n\t\t\tif it.Thread.Pinned(now) {\n\t\t\t\tmark = \"📌\"\n\t\t\t}\n\t\t\tt.Row(\n\t\t\t\tmark,\n\t\t\t\t// The link title is the id and never the body. md.Link\n\t\t\t\t// escapes markdown but NOT a pipe (sanitize.InlineText\n\t\t\t\t// leaves it; only ui.Cell rewrites it), so a body used as\n\t\t\t\t// a link title inside a table opens a column.\n\t\t\t\tmd.Link(\"#\"+it.ID.String(), ThreadURL(realmPath, it.ID)),\n\t\t\t\t// Cut first, escape second: the other order can strand a\n\t\t\t\t// trailing backslash that escapes the chrome after it.\n\t\t\t\tui.Cell(ui.ShortN(it.Thread.Body, ExcerptLen, 0)),\n\t\t\t\tui.Addr(it.Thread.Author),\n\t\t\t\tstrconv.Itoa(len(it.Thread.Replies)),\n\t\t\t)\n\t\t}\n\t\tout += t.String()\n\t}\n\n\tout += \"\\n\" + ui.ActionIn(realmPath, \"💬 Post\", \"Post\", \"page\", page, \"body\", \"\")\n\tif total \u003e len(items) {\n\t\tout += \" · \" + md.Link(\n\t\t\tstrconv.Itoa(total)+\" threads\",\n\t\t\tPageURL(realmPath, page),\n\t\t)\n\t}\n\treturn out + \"\\n\"\n}\n\n// ThreadURL is the gnoweb path of one thread on the hosting realm.\nfunc ThreadURL(realmPath string, id store.ID) string {\n\treturn RealmURL(realmPath) + \":thread/\" + id.String()\n}\n\n// PageURL is the gnoweb path of a page's full thread list.\nfunc PageURL(realmPath, page string) string {\n\treturn RealmURL(realmPath) + \":page/\" + page\n}\n\n// RealmURL is the gnoweb path of a realm given as a package path.\n//\n// The chain domain is the first element of a package path and a gnoweb path is\n// the rest of it, so this is a prefix strip and not a hostname this package\n// has to know.\nfunc RealmURL(realmPath string) string {\n\tif i := strings.Index(realmPath, \"/\"); i \u003e= 0 {\n\t\treturn realmPath[i:]\n\t}\n\treturn \"/\" + realmPath\n}\n"},{"name":"threads_test.gno","body":"package threads\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\n\thome = \"gno.land/r/moul/home\"\n)\n\nfunc TestValidPage(t *testing.T) {\n\ttests := []struct {\n\t\tpage string\n\t\twant bool\n\t}{\n\t\t{\"gno.land/r/moul/home\", true},\n\t\t{\"gno.land/r/gov/dao:proposal/42\", true},\n\t\t{\"a/b\", true},\n\t\t{\"\", false},\n\t\t{\"nopath\", false},\n\t\t{\"/leading\", false},\n\t\t{\"trailing/\", false},\n\t\t{\"double//slash\", false},\n\t\t{\"gno.land/r/Moul/home\", false},\n\t\t{\"gno.land/r/moul/home?x=1\", false},\n\t\t{\"gno.land/r/moul/\" + strings.Repeat(\"x\", MaxPageLen), false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidPage(tt.page), tt.page)\n\t}\n}\n\nfunc TestValidBody(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tbody string\n\t\twant bool\n\t}{\n\t\t{\"plain\", \"hello\", true},\n\t\t{\"newlines and tabs are content\", \"a\\nb\\tc\", true},\n\t\t{\"markdown is allowed and escaped later\", \"[x](y) | z\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"blank\", \"   \\n \", false},\n\t\t{\"too long\", strings.Repeat(\"x\", MaxBodyLen+1), false},\n\t\t{\"control character\", \"a\\x01b\", false},\n\t\t{\"delete character\", \"a\\x7fb\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidBody(tt.body), tt.name)\n\t}\n}\n\nfunc TestPostRejectsWhatItCannotStore(t *testing.T) {\n\tb := NewBoard()\n\n\t_, err := b.Post(\"nopath\", alice, \"hi\", 100)\n\tuassert.ErrorIs(t, err, ErrBadPage)\n\n\t_, err = b.Post(home, alice, \"\", 100)\n\tuassert.ErrorIs(t, err, ErrBadBody)\n\n\tuassert.Equal(t, 0, b.Len())\n\tuassert.Equal(t, 0, b.Pages())\n}\n\nfunc TestReplyCountsPeopleAndNotMessages(t *testing.T) {\n\tb := NewBoard()\n\tid, err := b.Post(home, alice, \"root\", 100)\n\turequire.NoError(t, err)\n\n\t// A new address is the mint signal, exactly once.\n\tisNew, err := b.Reply(id, bob, \"first\", 101)\n\turequire.NoError(t, err)\n\tuassert.True(t, isNew, \"bob is a new replier\")\n\n\tisNew, err = b.Reply(id, bob, \"again\", 102)\n\turequire.NoError(t, err)\n\tuassert.False(t, isNew, \"bob replying twice is not two people\")\n\n\t// The author replying to their own thread never counts.\n\tisNew, err = b.Reply(id, alice, \"mine\", 103)\n\turequire.NoError(t, err)\n\tuassert.False(t, isNew, \"the author is not an audience\")\n\n\tisNew, err = b.Reply(id, carol, \"hello\", 104)\n\turequire.NoError(t, err)\n\tuassert.True(t, isNew, \"carol is a new replier\")\n\n\tth, ok := b.Get(id)\n\turequire.True(t, ok, \"thread exists\")\n\tuassert.Equal(t, 4, len(th.Replies))\n\tuassert.Equal(t, 2, th.Repliers())\n\tuassert.True(t, th.HasReplied(bob))\n\tuassert.False(t, th.HasReplied(alice), \"the author is never in the replier set\")\n}\n\nfunc TestReplyToNothing(t *testing.T) {\n\tb := NewBoard()\n\t_, err := b.Reply(42, bob, \"hi\", 100)\n\tuassert.ErrorIs(t, err, ErrNoThread)\n}\n\nfunc TestPinOnlyEverMovesForward(t *testing.T) {\n\tb := NewBoard()\n\tid, _ := b.Post(home, alice, \"root\", 100)\n\n\turequire.NoError(t, b.Pin(id, 1000))\n\tth, _ := b.Get(id)\n\tuassert.True(t, th.Pinned(999))\n\tuassert.False(t, th.Pinned(1000), \"the pin is exclusive at its own height\")\n\n\t// A cheaper pin cannot cut an expensive one short.\n\tuassert.ErrorIs(t, b.Pin(id, 500), ErrPinIsPast)\n\tuassert.ErrorIs(t, b.Pin(id, 1000), ErrPinIsPast)\n\tuassert.Equal(t, int64(1000), th.PinnedUntil)\n\n\turequire.NoError(t, b.Pin(id, 1200))\n\tuassert.Equal(t, int64(1200), th.PinnedUntil)\n}\n\nfunc TestListIsPinnedThenNewest(t *testing.T) {\n\tb := NewBoard()\n\tfirst, _ := b.Post(home, alice, \"first\", 100)\n\tsecond, _ := b.Post(home, bob, \"second\", 101)\n\tthird, _ := b.Post(home, carol, \"third\", 102)\n\n\t// Newest first, nothing pinned.\n\tgot := b.List(home, 200, 0)\n\turequire.Equal(t, 3, len(got))\n\tuassert.Equal(t, uint64(third), uint64(got[0].ID))\n\tuassert.Equal(t, uint64(second), uint64(got[1].ID))\n\tuassert.Equal(t, uint64(first), uint64(got[2].ID))\n\n\t// Pinning the oldest moves it to the top and leaves the rest in order.\n\turequire.NoError(t, b.Pin(first, 500))\n\tgot = b.List(home, 200, 0)\n\tuassert.Equal(t, uint64(first), uint64(got[0].ID))\n\tuassert.Equal(t, uint64(third), uint64(got[1].ID))\n\tuassert.Equal(t, uint64(second), uint64(got[2].ID))\n\n\t// The pin expires on its own, with nothing to sweep.\n\tgot = b.List(home, 500, 0)\n\tuassert.Equal(t, uint64(third), uint64(got[0].ID))\n\n\t// limit truncates after the partition, so a pin is never cut off.\n\tgot = b.List(home, 200, 1)\n\turequire.Equal(t, 1, len(got))\n\tuassert.Equal(t, uint64(first), uint64(got[0].ID))\n}\n\nfunc TestPagesAreIndependent(t *testing.T) {\n\tb := NewBoard()\n\tb.Post(home, alice, \"on home\", 100)\n\tb.Post(\"gno.land/r/moul/blog\", bob, \"on the blog\", 101)\n\n\tuassert.Equal(t, 2, b.Len())\n\tuassert.Equal(t, 2, b.Pages())\n\tuassert.Equal(t, 1, b.PageLen(home))\n\tuassert.Equal(t, 0, b.PageLen(\"gno.land/r/nobody/here\"))\n\tuassert.Equal(t, 0, len(b.List(\"gno.land/r/nobody/here\", 100, 0)))\n}\n\nfunc TestRecentCrossesPages(t *testing.T) {\n\tb := NewBoard()\n\tb.Post(home, alice, \"one\", 100)\n\tb.Post(\"gno.land/r/moul/blog\", bob, \"two\", 101)\n\tthird, _ := b.Post(home, carol, \"three\", 102)\n\n\tgot := b.Recent(2)\n\turequire.Equal(t, 2, len(got))\n\tuassert.Equal(t, uint64(third), uint64(got[0].ID), \"newest first\")\n}\n\nfunc TestBlockEscapesTheBodyItShows(t *testing.T) {\n\tb := NewBoard()\n\tid, _ := b.Post(home, alice, \"a | pipe and [a link](x)\", 100)\n\n\tout := Block(\"gno.land/r/moul/x/social/threads/v0\", home, b.List(home, 200, 10), 1, 200)\n\n\t// The assertion has to be on what IS there, not on what is not: an\n\t// escaped cell contains the backslash form, and a row that silently lost\n\t// the body entirely would satisfy any \"does not contain\" check.\n\tuassert.True(t, strings.Contains(out, `a \\| pipe and \\[a link\\]\\(x\\)`),\n\t\t\"the body is cut and escaped once, pipe included: \"+out)\n\tuassert.False(t, strings.Contains(out, \"| a | pipe\"), \"a raw pipe would open a column: \"+out)\n\tuassert.True(t, strings.Contains(out, ThreadURL(\"gno.land/r/moul/x/social/threads/v0\", id)))\n\tuassert.True(t, strings.Contains(out, \"func=Post\"), \"the block offers the transaction\")\n}\n\nfunc TestBlockOnAnEmptyPageSaysSo(t *testing.T) {\n\tout := Block(\"gno.land/r/moul/x/social/threads/v0\", home, nil, 0, 200)\n\tuassert.True(t, strings.Contains(out, \"No discussion yet.\"), out)\n}\n\nfunc TestURLsStripTheChainDomain(t *testing.T) {\n\tuassert.Equal(t, \"/r/moul/x/social/threads/v0\", RealmURL(\"gno.land/r/moul/x/social/threads/v0\"))\n\tuassert.Equal(t, \"/r/a/b:thread/7\", ThreadURL(\"gno.land/r/a/b\", 7))\n\tuassert.Equal(t, \"/r/a/b:page/gno.land/r/moul/home\", PageURL(\"gno.land/r/a/b\", home))\n}\n"}]},"send":"","max_deposit":"9000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"vouch","path":"gno.land/p/moul/x/social/vouch/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/x/social/vouch/v0`\n\n**The engine behind a web of trust**: `NewGraph`, `Record`, `Revoke`,\n`Withdraw`, `ScoreOf`, `IsTrusted`, `VouchedBy`, `VouchesOf`, `Mutual`,\n`Leaderboard`.\n\n```go\ng := vouch.NewGraph()\ng.Record(alice, bob, \"worked with them for a year\", 1_000_000, height)\ng.IsTrusted(bob, 2)   // the one call another realm makes\ng.Revoke(alice, bob)  // credits the bond back, withdrawn separately\n```\n\n**It is a sybil gate, and it exists because the apps around it do not have\none.** A realm that mints a point per distinct replier is farmed by two\naddresses replying to each other; a realm that counts one vote per address is\nfarmed by holding a hundred. Neither can fix that alone, because neither knows\nanything about the people behind the addresses. This package knows one thing:\nwho was willing to say, on chain and under their own name, that an address is\nsomebody they stand behind.\n\n**A score counts people, not transactions.** A vouch is directed and at most one\nexists per ordered pair, so a second `Record` from the same address to the same\ntarget updates the reason and adds to the bond rather than counting twice. An\naddress cannot vouch for itself. A pair vouching for each other both reach a\nscore of one, which is exactly why a real gate asks for two.\n\n**The engine counts the bond, it never moves it.** The amount arrives as an\nargument, `Revoke` moves it into a withdrawal ledger, and the realm holding the\ncoins transfers only after `Withdraw` has zeroed the credit. That ordering is\nthe pull-payment pattern and it is not optional.\n\n**There is no slashing in v0, and the missing half is not the accounting.**\nSlashing needs an arbiter: somebody has to decide that a vouch was a lie. A DAO\nvote is a popularity contest against whoever is unpopular this month, a\nchallenge market pays whoever is loudest, an oracle is one key that can\nconfiscate anybody's money. Shipping any of them by default is shipping the\nwrong one. The bond is still worth having: an illiquid deposit is a cost a\nhundred throwaway addresses cannot all pay at once.\n\nOrdering is a total order on the address everywhere it matters, so two identical\n`Render` calls produce identical bytes: the sets are `p/moul/addrset`, the\nleaderboard breaks ties on the address, and nothing is built by ranging a map.\nA reason is free text, bounded to one line of `MaxReasonLen` bytes with control\ncharacters refused, and still has to be escaped where it is shown.\n\n**Live realm:** [`r/moul/x/social/vouch`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/social/vouch),\nwhich also carries the reasoning for why this one issues no token.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**Dependency graph:**\n\n![gno.land/p/moul/x/social/vouch/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/p/moul/x/social/vouch/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/x/social/vouch/v0\"\ngno = \"0.9\"\n"},{"name":"vouch.gno","body":"// Package vouch is the engine behind a web of trust: one address says it\n// stands behind another, in writing, optionally with its own money locked\n// against the claim.\n//\n// # What it is for\n//\n// It is a sybil gate, and it exists because the apps around it do not have\n// one. A realm that mints a point per distinct replier is farmed by two\n// addresses replying to each other; a realm that counts one vote per address\n// is farmed by holding a hundred addresses. Neither can fix that alone,\n// because neither knows anything about the people behind the addresses.\n//\n// This package knows one thing: who was willing to say, on chain and under\n// their own name, that an address is a person they stand behind. A realm asks\n// [Graph.IsTrusted] and gates on the answer. That is the whole product, and\n// every other read here exists to make that one legible.\n//\n// # The model\n//\n//\tGraph   every vouch, in both directions, plus the refund ledger\n//\tVouch   a directed statement: from, for, reason, bond, heights\n//\n// A vouch is directed and at most one exists per ordered pair. A second\n// [Graph.Record] from the same address to the same target UPDATES the reason\n// and ADDS to the bond rather than counting twice, which is what makes the\n// score a count of people instead of a count of transactions. An address\n// cannot vouch for itself.\n//\n// # The bond\n//\n// A vouch may lock coins. The engine only counts them: it takes the amount as\n// an argument, tracks who posted how much on whom, and on [Graph.Revoke] moves\n// that amount into a withdrawal ledger the voucher pulls from. It moves\n// nothing itself. The realm holding the coins performs the transfer AFTER\n// [Graph.Withdraw] has zeroed the credit, which is the ordering the\n// pull-payment pattern demands.\n//\n// # No slashing, and why that is the hard part\n//\n// A bond here is value at risk only in the sense that it is illiquid: it can\n// be withdrawn by revoking, and nothing can take it away. That is deliberate\n// for a v0, and the missing half is not the accounting.\n//\n// Slashing needs an arbiter: somebody has to decide that a vouch was a lie.\n// Every candidate is a design question with teeth. A DAO vote is a popularity\n// contest against whoever is unpopular this month. A challenge market pays\n// whoever is loudest and turns the graph into a griefing surface. An oracle is\n// one key that can confiscate anyone's money. Shipping any of them by default\n// would be shipping the wrong one, so this version ships the part that is\n// uncontroversial: who said what, who put money behind it, and the gate that\n// reads it.\n//\n// # Reasons are attacker-controlled markdown\n//\n// A reason is free text. [ValidReason] bounds it to [MaxReasonLen] bytes on\n// one line and refuses control characters, but everything inside that is\n// allowed and must be escaped where it is shown: ui.Inline in prose, ui.Cell\n// in a table cell.\npackage vouch\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/addrset/v1\"\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/tally/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/x/daily/pullpayment/v0\"\n)\n\n// MaxReasonLen is the longest reason accepted, in bytes. Long enough to say\n// how you know somebody, short enough that one call cannot lock an unbounded\n// storage deposit the realm's deployer is paying for.\nconst MaxReasonLen = 200\n\nconst maxInt64 = int64(9223372036854775807)\n\n// The errors a caller can get back. A p/ returns them; the realm decides to\n// abort.\nvar (\n\tErrSelfVouch   = errors.New(\"vouch: an address cannot vouch for itself\")\n\tErrBadReason   = errors.New(\"vouch: reason is empty, too long, multi-line, or has control characters\")\n\tErrBadBond     = errors.New(\"vouch: a bond cannot be negative\")\n\tErrNoVouch     = errors.New(\"vouch: no such vouch\")\n\tErrNothingOwed = errors.New(\"vouch: nothing to withdraw\")\n\tErrOverflow    = errors.New(\"vouch: bond would overflow\")\n)\n\n// Vouch is one directed statement of trust.\ntype Vouch struct {\n\tFrom   address\n\tFor    address\n\tReason string\n\n\t// Bond is the amount locked on this vouch, in the realm's denom. It is\n\t// the sum of every bond sent with this pair, since a repeated vouch\n\t// adds to it rather than replacing it.\n\tBond int64\n\n\t// At is the height the vouch was first made, UpdatedAt the height it\n\t// last changed. They are equal until the voucher restates it.\n\tAt        int64\n\tUpdatedAt int64\n}\n\n// Graph is the whole web of trust: every vouch, both directions of every\n// edge, what is bonded on whom, and what revoking owes back to whom.\ntype Graph struct {\n\tedges    map[string]*Vouch       // \"from|for\" -\u003e the vouch\n\tinbound  map[string]*addrset.Set // target -\u003e who vouches for them\n\toutbound map[string]*addrset.Set // voucher -\u003e who they vouch for\n\tbonded   map[string]int64        // target -\u003e total bonded on them\n\n\t// people is every address with at least one inbound vouch, sorted, so\n\t// a listing never has to iterate a map to build rendered output.\n\tpeople addrset.Set\n\n\trefunds     *pullpayment.Ledger\n\tcount       int\n\ttotalBonded int64\n}\n\n// NewGraph returns an empty graph.\nfunc NewGraph() *Graph {\n\treturn \u0026Graph{\n\t\tedges:    map[string]*Vouch{},\n\t\tinbound:  map[string]*addrset.Set{},\n\t\toutbound: map[string]*addrset.Set{},\n\t\tbonded:   map[string]int64{},\n\t\trefunds:  pullpayment.New(),\n\t}\n}\n\n// Record writes from's vouch for target and reports whether it replaced one\n// that already existed.\n//\n// A repeated vouch is an update and not a second voice: the reason is\n// replaced, the bond is added to the one already posted, and the score does\n// not move. bond may be zero, which is the ordinary case.\nfunc (g *Graph) Record(from, target address, reason string, bond, at int64) (updated bool, err error) {\n\tif from == target {\n\t\treturn false, ErrSelfVouch\n\t}\n\tif !ValidReason(reason) {\n\t\treturn false, ErrBadReason\n\t}\n\tif bond \u003c 0 {\n\t\treturn false, ErrBadBond\n\t}\n\ttk := target.String()\n\tif g.bonded[tk] \u003e maxInt64-bond || g.totalBonded \u003e maxInt64-bond {\n\t\treturn false, ErrOverflow\n\t}\n\n\tif v, ok := g.edges[key(from, target)]; ok {\n\t\tif v.Bond \u003e maxInt64-bond {\n\t\t\treturn false, ErrOverflow\n\t\t}\n\t\tv.Reason = reason\n\t\tv.Bond += bond\n\t\tv.UpdatedAt = at\n\t\tg.bonded[tk] += bond\n\t\tg.totalBonded += bond\n\t\treturn true, nil\n\t}\n\n\tg.edges[key(from, target)] = \u0026Vouch{\n\t\tFrom:      from,\n\t\tFor:       target,\n\t\tReason:    reason,\n\t\tBond:      bond,\n\t\tAt:        at,\n\t\tUpdatedAt: at,\n\t}\n\tg.set(g.inbound, tk).Add(from)\n\tg.set(g.outbound, from.String()).Add(target)\n\tg.people.Add(target)\n\tg.bonded[tk] += bond\n\tg.totalBonded += bond\n\tg.count++\n\treturn false, nil\n}\n\n// Revoke removes from's vouch for target and credits the bond back to from,\n// returning the amount credited.\n//\n// The coins are not sent here and this package never holds any: the credit\n// waits in the refund ledger until from calls [Graph.Withdraw].\nfunc (g *Graph) Revoke(from, target address) (refund int64, err error) {\n\tv, ok := g.edges[key(from, target)]\n\tif !ok {\n\t\treturn 0, ErrNoVouch\n\t}\n\t// Credit first, because it is the only step that can fail. Nothing is\n\t// mutated until the refund is certain, so a full ledger leaves the\n\t// graph exactly as it was rather than half revoked.\n\tif v.Bond \u003e 0 {\n\t\tif err := g.refunds.Credit(from.String(), v.Bond); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tdelete(g.edges, key(from, target))\n\ttk, fk := target.String(), from.String()\n\n\tif in, ok := g.inbound[tk]; ok {\n\t\tin.Remove(from)\n\t\tif in.Size() == 0 {\n\t\t\tdelete(g.inbound, tk)\n\t\t\tg.people.Remove(target)\n\t\t}\n\t}\n\tif out, ok := g.outbound[fk]; ok {\n\t\tout.Remove(target)\n\t\tif out.Size() == 0 {\n\t\t\tdelete(g.outbound, fk)\n\t\t}\n\t}\n\n\tg.bonded[tk] -= v.Bond\n\tif g.bonded[tk] == 0 {\n\t\tdelete(g.bonded, tk)\n\t}\n\tg.totalBonded -= v.Bond\n\tg.count--\n\treturn v.Bond, nil\n}\n\n// Withdraw zeroes what the graph owes who and returns it, so the realm can\n// send exactly that much.\n//\n// The credit is gone from the ledger before this returns, which is what makes\n// a reentrant call find nothing: the realm transfers after, never before.\nfunc (g *Graph) Withdraw(who address) (int64, error) {\n\tamount, err := g.refunds.Withdraw(who.String())\n\tif err != nil {\n\t\treturn 0, ErrNothingOwed\n\t}\n\treturn amount, nil\n}\n\n// Get returns one vouch.\nfunc (g *Graph) Get(from, target address) (*Vouch, bool) {\n\tv, ok := g.edges[key(from, target)]\n\treturn v, ok\n}\n\n// ScoreOf is how many distinct addresses vouch for addr.\n//\n// It counts people and not statements: restating a vouch does not raise it,\n// and revoking lowers it.\nfunc (g *Graph) ScoreOf(addr address) int {\n\tif in, ok := g.inbound[addr.String()]; ok {\n\t\treturn in.Size()\n\t}\n\treturn 0\n}\n\n// BondedFor is the total locked on addr by everyone vouching for them.\nfunc (g *Graph) BondedFor(addr address) int64 { return g.bonded[addr.String()] }\n\n// IsTrusted reports whether addr is vouched for by at least min distinct\n// addresses. It is the gate another realm calls, and the reason this package\n// exists.\n//\n// A min below one is raised to one. A gate that lets everybody through is a\n// bug at the call site rather than an answer worth returning, and silently\n// agreeing with it is how a sybil check ships disabled.\n//\n// What it cannot tell you is whether those vouchers are distinct PEOPLE. Two\n// addresses vouching for each other both reach a score of one for the price of\n// two transactions, which is why [Graph.Mutual] is exported and why a gate\n// that matters should ask for more than one.\nfunc (g *Graph) IsTrusted(addr address, min int) bool {\n\tif min \u003c 1 {\n\t\tmin = 1\n\t}\n\treturn g.ScoreOf(addr) \u003e= min\n}\n\n// VouchedBy is every address that vouches for addr, sorted.\n//\n// Sorted and not chronological: the set is the storage, the order is a total\n// order on the address, and two identical calls therefore render identically.\nfunc (g *Graph) VouchedBy(addr address) []address {\n\treturn collect(g.inbound[addr.String()])\n}\n\n// VouchesOf is every address addr vouches for, sorted. It is the other\n// direction of [Graph.VouchedBy].\nfunc (g *Graph) VouchesOf(addr address) []address {\n\treturn collect(g.outbound[addr.String()])\n}\n\n// Mutual reports whether a and b vouch for each other.\n//\n// A mutual pair is the cheapest sybil shape there is, so this is here to be\n// discounted by a caller that cares, not as a badge.\nfunc (g *Graph) Mutual(a, b address) bool {\n\tif a == b {\n\t\treturn false\n\t}\n\t_, there := g.edges[key(a, b)]\n\t_, back := g.edges[key(b, a)]\n\treturn there \u0026\u0026 back\n}\n\n// ReasonFrom is what from wrote about target, or the empty string when there\n// is no such vouch. It is raw caller text: escape it where it is shown.\nfunc (g *Graph) ReasonFrom(from, target address) string {\n\tif v, ok := g.edges[key(from, target)]; ok {\n\t\treturn v.Reason\n\t}\n\treturn \"\"\n}\n\n// BondFrom is what from locked on target, or zero.\nfunc (g *Graph) BondFrom(from, target address) int64 {\n\tif v, ok := g.edges[key(from, target)]; ok {\n\t\treturn v.Bond\n\t}\n\treturn 0\n}\n\n// Count is how many vouches exist, across everybody.\nfunc (g *Graph) Count() int { return g.count }\n\n// People is how many addresses have at least one vouch for them.\nfunc (g *Graph) People() int { return g.people.Size() }\n\n// Owed is what revoking has credited to addr and nobody has withdrawn yet.\nfunc (g *Graph) Owed(addr address) int64 { return g.refunds.Balance(addr.String()) }\n\n// TotalOwed is every unwithdrawn refund. The realm must hold at least\n// TotalOwed plus [Graph.TotalBonded] to be solvent.\nfunc (g *Graph) TotalOwed() int64 { return g.refunds.TotalOwed() }\n\n// TotalBonded is everything locked on every vouch that still stands.\nfunc (g *Graph) TotalBonded() int64 { return g.totalBonded }\n\n// Ranked is one row of [Graph.Leaderboard].\ntype Ranked struct {\n\tAddr   address\n\tScore  int\n\tBonded int64\n}\n\n// Leaderboard is the most vouched for addresses, highest score first, ties\n// broken by address so the order is total and a Render never reshuffles.\n//\n// limit at or below zero returns nothing.\nfunc (g *Graph) Leaderboard(limit int) []Ranked {\n\tif limit \u003c= 0 || g.people.Size() == 0 {\n\t\treturn nil\n\t}\n\tentries := make([]tally.Entry, 0, g.people.Size())\n\tg.people.IterateByOffset(0, g.people.Size(), func(a address) bool {\n\t\tentries = append(entries, tally.Entry{Key: a.String(), Score: int64(g.ScoreOf(a))})\n\t\treturn false\n\t})\n\ttop := tally.Top(entries, limit)\n\n\tout := make([]Ranked, 0, len(top))\n\tfor _, e := range top {\n\t\ta := address(e.Key)\n\t\tout = append(out, Ranked{Addr: a, Score: int(e.Score), Bonded: g.bonded[e.Key]})\n\t}\n\treturn out\n}\n\n// ValidReason reports whether reason can be stored: non-empty after trimming,\n// within [MaxReasonLen], on one line, and free of control characters.\n//\n// One line is a deliberate bound rather than a rendering workaround. A reason\n// is shown in a table cell beside the address it is about, and a writer who\n// needs a second paragraph is writing something other than a reason.\n//\n// Control characters are refused rather than stripped because the text is\n// shown back to whoever wrote it, and silently rewriting what somebody said is\n// worse than telling them it was refused. Everything else is allowed and\n// escaped at render time, since a validator and an escaper protect against\n// different mistakes.\nfunc ValidReason(reason string) bool {\n\tif len(reason) \u003e MaxReasonLen || strings.TrimSpace(reason) == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(reason); i++ {\n\t\tif c := reason[i]; c \u003c 0x20 || c == 0x7f {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Badge is the one-line trust mark, for a realm that wants to show what the\n// gate it just called was reading.\n//\n// It takes the numbers rather than the graph because the realm holding the\n// graph is the only one that can read it: everybody else has the two integers\n// from a cross-realm call and needs nothing more to render them.\nfunc Badge(realmPath string, addr address, score int, bonded int64) string {\n\tif score == 0 {\n\t\treturn md.Link(\"not vouched for\", AddrURL(realmPath, addr))\n\t}\n\tword := \" vouchers\"\n\tif score == 1 {\n\t\tword = \" voucher\"\n\t}\n\tout := \"\\U0001F91D \" + md.Link(strconv.Itoa(score)+word, AddrURL(realmPath, addr))\n\tif bonded \u003e 0 {\n\t\tout += \" · \" + num.GNOTf(bonded) + \" bonded\"\n\t}\n\treturn out\n}\n\n// AddrURL is the gnoweb path of one address's page on the hosting realm.\nfunc AddrURL(realmPath string, addr address) string {\n\treturn RealmURL(realmPath) + \":addr/\" + addr.String()\n}\n\n// RealmURL is the gnoweb path of a realm given as a package path.\n//\n// The chain domain is the first element of a package path and a gnoweb path is\n// the rest of it, so this is a prefix strip and not a hostname this package\n// has to know.\nfunc RealmURL(realmPath string) string {\n\tif i := strings.Index(realmPath, \"/\"); i \u003e= 0 {\n\t\treturn realmPath[i:]\n\t}\n\treturn \"/\" + realmPath\n}\n\n// key is the storage key of one directed edge. Addresses are fixed-length\n// bech32, so the separator is belt and braces rather than load-bearing.\nfunc key(from, target address) string { return from.String() + \"|\" + target.String() }\n\n// set returns the address set stored under k, creating it on first use.\nfunc (g *Graph) set(m map[string]*addrset.Set, k string) *addrset.Set {\n\tif s, ok := m[k]; ok {\n\t\treturn s\n\t}\n\ts := \u0026addrset.Set{}\n\tm[k] = s\n\treturn s\n}\n\n// collect reads a set out in sorted order.\nfunc collect(s *addrset.Set) []address {\n\tif s == nil || s.Size() == 0 {\n\t\treturn nil\n\t}\n\tout := make([]address, 0, s.Size())\n\ts.IterateByOffset(0, s.Size(), func(a address) bool {\n\t\tout = append(out, a)\n\t\treturn false\n\t})\n\treturn out\n}\n"},{"name":"vouch_test.gno","body":"package vouch\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\tdave  = testutils.TestAddress(\"dave\")\n)\n\nconst realmPath = \"gno.land/r/moul/x/social/vouch/v0\"\n\nfunc TestValidReason(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\treason string\n\t\twant   bool\n\t}{\n\t\t{\"plain\", \"worked with them for a year\", true},\n\t\t{\"markdown is allowed and escaped later\", \"[x](y) | z\", true},\n\t\t{\"at the limit\", strings.Repeat(\"x\", MaxReasonLen), true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"blank\", \"   \", false},\n\t\t{\"too long\", strings.Repeat(\"x\", MaxReasonLen+1), false},\n\t\t{\"a reason is one line\", \"met them\\nat a conference\", false},\n\t\t{\"no tabs either\", \"met them\\there\", false},\n\t\t{\"control character\", \"a\\x01b\", false},\n\t\t{\"delete character\", \"a\\x7fb\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, ValidReason(tt.reason), tt.name)\n\t}\n}\n\nfunc TestRecordRefusesWhatItCannotStore(t *testing.T) {\n\tg := NewGraph()\n\n\t_, err := g.Record(alice, alice, \"myself\", 0, 100)\n\tuassert.ErrorIs(t, err, ErrSelfVouch)\n\n\t_, err = g.Record(alice, bob, \"\", 0, 100)\n\tuassert.ErrorIs(t, err, ErrBadReason)\n\n\t_, err = g.Record(alice, bob, \"fine\", -1, 100)\n\tuassert.ErrorIs(t, err, ErrBadBond)\n\n\tuassert.Equal(t, 0, g.Count())\n\tuassert.Equal(t, 0, g.People())\n\tuassert.Equal(t, 0, g.ScoreOf(alice))\n}\n\n// A score counts people. This is the property every caller of IsTrusted is\n// relying on, so it is the one worth pinning hardest.\nfunc TestScoreCountsPeopleAndNotVouches(t *testing.T) {\n\tg := NewGraph()\n\n\tupdated, err := g.Record(bob, alice, \"known them for years\", 0, 100)\n\turequire.NoError(t, err)\n\tuassert.False(t, updated, \"the first vouch is not an update\")\n\tuassert.Equal(t, 1, g.ScoreOf(alice))\n\n\t// Saying it again is an edit, not a second voice.\n\tupdated, err = g.Record(bob, alice, \"still true\", 0, 101)\n\turequire.NoError(t, err)\n\tuassert.True(t, updated, \"the second vouch replaced the first\")\n\tuassert.Equal(t, 1, g.ScoreOf(alice), \"one person is one point, however often they say it\")\n\tuassert.Equal(t, \"still true\", g.ReasonFrom(bob, alice), \"the reason was updated\")\n\tuassert.Equal(t, 1, g.Count())\n\n\t// A different person does move it.\n\t_, err = g.Record(carol, alice, \"we shipped together\", 0, 102)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 2, g.ScoreOf(alice))\n\tuassert.Equal(t, 2, g.Count())\n\tuassert.Equal(t, 1, g.People(), \"one address has been vouched for\")\n\n\t// And revoking lowers it.\n\t_, err = g.Revoke(carol, alice)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 1, g.ScoreOf(alice))\n\tuassert.Equal(t, 1, g.Count())\n}\n\nfunc TestIsTrusted(t *testing.T) {\n\tg := NewGraph()\n\tg.Record(bob, alice, \"one\", 0, 100)\n\tg.Record(carol, alice, \"two\", 0, 100)\n\n\ttests := []struct {\n\t\tname string\n\t\taddr address\n\t\tmin  int\n\t\twant bool\n\t}{\n\t\t{\"below the score\", alice, 1, true},\n\t\t{\"at the score\", alice, 2, true},\n\t\t{\"above the score\", alice, 3, false},\n\t\t{\"zero is read as one\", alice, 0, true},\n\t\t{\"zero does not open the gate for nobody\", dave, 0, false},\n\t\t{\"a negative min is read as one too\", dave, -5, false},\n\t\t{\"nobody vouches for dave\", dave, 1, false},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, g.IsTrusted(tt.addr, tt.min), tt.name)\n\t}\n}\n\nfunc TestTheBondFollowsTheVouchInBothDirections(t *testing.T) {\n\tg := NewGraph()\n\n\t_, err := g.Record(bob, alice, \"staking 1 GNOT on this\", 1_000_000, 100)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1_000_000), g.BondedFor(alice))\n\tuassert.Equal(t, int64(1_000_000), g.TotalBonded())\n\tuassert.Equal(t, int64(0), g.Owed(bob), \"nothing is owed while the vouch stands\")\n\n\t// A repeated vouch adds to the bond rather than replacing it.\n\t_, err = g.Record(bob, alice, \"doubling down\", 500_000, 101)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1_500_000), g.BondedFor(alice))\n\tuassert.Equal(t, int64(1_500_000), g.BondFrom(bob, alice))\n\n\t// A second voucher's bond piles on top.\n\tg.Record(carol, alice, \"and me\", 250_000, 102)\n\tuassert.Equal(t, int64(1_750_000), g.BondedFor(alice))\n\n\t// Revoking returns exactly what that voucher put in, and nothing else.\n\trefund, err := g.Revoke(bob, alice)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1_500_000), refund)\n\tuassert.Equal(t, int64(250_000), g.BondedFor(alice), \"carol's bond stays\")\n\tuassert.Equal(t, int64(250_000), g.TotalBonded())\n\tuassert.Equal(t, int64(1_500_000), g.Owed(bob))\n\tuassert.Equal(t, int64(1_500_000), g.TotalOwed())\n\n\t// Withdrawing zeroes the credit before the realm sends anything.\n\tgot, err := g.Withdraw(bob)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, int64(1_500_000), got)\n\tuassert.Equal(t, int64(0), g.Owed(bob))\n\tuassert.Equal(t, int64(0), g.TotalOwed())\n\n\t// A reentrant withdrawal finds nothing.\n\t_, err = g.Withdraw(bob)\n\tuassert.ErrorIs(t, err, ErrNothingOwed)\n}\n\nfunc TestRevokeRefusesWhatWasNeverThere(t *testing.T) {\n\tg := NewGraph()\n\t_, err := g.Revoke(alice, bob)\n\tuassert.ErrorIs(t, err, ErrNoVouch)\n\n\tg.Record(alice, bob, \"fine\", 0, 100)\n\t_, err = g.Revoke(bob, alice)\n\tuassert.ErrorIs(t, err, ErrNoVouch, \"a vouch is directed, so the other way round is not one\")\n}\n\nfunc TestTheTwoDirections(t *testing.T) {\n\tg := NewGraph()\n\tg.Record(alice, bob, \"a to b\", 0, 100)\n\tg.Record(alice, carol, \"a to c\", 0, 100)\n\tg.Record(bob, carol, \"b to c\", 0, 100)\n\n\tuassert.Equal(t, 0, len(g.VouchedBy(alice)), \"nobody vouches for alice\")\n\tuassert.Equal(t, 2, len(g.VouchesOf(alice)))\n\tuassert.Equal(t, 2, len(g.VouchedBy(carol)))\n\tuassert.Equal(t, 0, len(g.VouchesOf(carol)))\n\n\t// Sorted by address, so two identical calls render identically.\n\tin := g.VouchedBy(carol)\n\tuassert.True(t, in[0].String() \u003c in[1].String(), \"inbound is sorted\")\n\n\tuassert.Equal(t, \"a to c\", g.ReasonFrom(alice, carol))\n\tuassert.Equal(t, \"\", g.ReasonFrom(carol, alice), \"no vouch, no reason\")\n}\n\nfunc TestMutual(t *testing.T) {\n\tg := NewGraph()\n\tg.Record(alice, bob, \"a to b\", 0, 100)\n\n\tuassert.False(t, g.Mutual(alice, bob), \"one direction is not mutual\")\n\tuassert.False(t, g.Mutual(alice, alice), \"an address is never mutual with itself\")\n\n\tg.Record(bob, alice, \"b to a\", 0, 101)\n\tuassert.True(t, g.Mutual(alice, bob))\n\tuassert.True(t, g.Mutual(bob, alice), \"mutual is symmetric\")\n\tuassert.False(t, g.Mutual(alice, carol))\n\n\t// The cheapest sybil shape: two addresses, two transactions, both pass a\n\t// gate set at one. That is the whole reason Mutual is exported.\n\tuassert.True(t, g.IsTrusted(alice, 1))\n\tuassert.True(t, g.IsTrusted(bob, 1))\n\tuassert.False(t, g.IsTrusted(alice, 2))\n}\n\nfunc TestLeaderboardIsATotalOrder(t *testing.T) {\n\tg := NewGraph()\n\tg.Record(alice, carol, \"one\", 0, 100)\n\tg.Record(bob, carol, \"two\", 0, 100)\n\tg.Record(alice, bob, \"three\", 100, 100)\n\n\trows := g.Leaderboard(10)\n\turequire.Equal(t, 2, len(rows))\n\tuassert.Equal(t, carol.String(), rows[0].Addr.String(), \"highest score first\")\n\tuassert.Equal(t, 2, rows[0].Score)\n\tuassert.Equal(t, int64(100), rows[1].Bonded)\n\n\tuassert.Equal(t, 1, len(g.Leaderboard(1)), \"limit truncates\")\n\tuassert.Equal(t, 0, len(g.Leaderboard(0)))\n\tuassert.Equal(t, 0, len(NewGraph().Leaderboard(10)), \"an empty graph ranks nobody\")\n\n\t// Revoking the last vouch for an address drops it off the board.\n\tg.Revoke(alice, bob)\n\tuassert.Equal(t, 1, len(g.Leaderboard(10)))\n\tuassert.Equal(t, 0, g.ScoreOf(bob))\n}\n\nfunc TestBadge(t *testing.T) {\n\tg := NewGraph()\n\tuassert.True(t, strings.Contains(Badge(realmPath, alice, g.ScoreOf(alice), 0), \"not vouched for\"))\n\n\tg.Record(bob, alice, \"one\", 2_000_000, 100)\n\tgot := Badge(realmPath, alice, g.ScoreOf(alice), g.BondedFor(alice))\n\tuassert.True(t, strings.Contains(got, \"1 voucher]\"), \"singular: \"+got)\n\tuassert.True(t, strings.Contains(got, \"2 GNOT bonded\"), got)\n\tuassert.True(t, strings.Contains(got, AddrURL(realmPath, alice)), got)\n\n\tg.Record(carol, alice, \"two\", 0, 101)\n\tuassert.True(t, strings.Contains(Badge(realmPath, alice, g.ScoreOf(alice), 0), \"2 vouchers]\"))\n}\n\nfunc TestURLsStripTheChainDomain(t *testing.T) {\n\tuassert.Equal(t, \"/r/moul/x/social/vouch/v0\", RealmURL(realmPath))\n\tuassert.Equal(t, \"/r/a/b:addr/\"+alice.String(), AddrURL(\"gno.land/r/a/b\", alice))\n}\n"}]},"send":"","max_deposit":"11000000ugnot"}],"fee":{"gas_wanted":"543588000","gas_fee":"1630764ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"AjZyqpH4vJ3WLLVeLtRl+F2StxRT+LawNoGVosjVwS/F"},"signature":"Y4W01qgWKwhU9qRhCZIWEG6yVrmknbeBwZ+3nxDZkvUMDlfKqU+YTddB+R9Blz1P0eUTKk08lK28Id3uq8V2CA=="}],"memo":""},"metadata":{"timestamp":"1791257684"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"crews","path":"gno.land/r/moul/x/social/crews/v0","files":[{"name":"README.md","body":"# crews\n\nA crew is three to fifteen people with a shared pot, a way to decide, and a way\nto leave with their share. One transaction to start one.\n\nThe chain wiring for [`p/moul/x/social/crew`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/social/crew), which\nholds the share math and the proposal state. This realm reads the caller, reads\nthe coins attached to the call, asks the engine, and renders the result.\n\n## The API\n\n| call | |\n|---|---|\n| `Create(name)` | payable. You become the crew's first member, your shares bought out of what you sent at `InitialPricePerShare`. |\n| `Join(crewID)` | payable. Mints shares at what a share is worth **now**: `amount * totalShares / treasury`, rounded down. |\n| `Fund(crewID)` | payable. Adds to the treasury and mints nothing, so every existing share is worth more. |\n| `Propose(crewID, text)` | any member. Open for `VoteBlocks` blocks. |\n| `Vote(proposalID, yes)` | weighted by the shares you hold right now, changeable while it is open. |\n| `Close(proposalID)` | anyone, after the deadline. Records passed or failed by share weight. |\n| `Ragequit(crewID)` | burn every share you hold, be credited your pro-rata of the treasury, leave. |\n| `Withdraw()` | collect what you were credited. |\n\nReads: `Get`, `Count`, `SharesOf`, `MemberCount`, `Treasury`, `ValuePerShare`,\n`ProposalOf`, `Tally`, `CreditOf`, `TotalOwed`.\n\n`Render` serves three views: the index, `:crew/\u003cid\u003e`, and `:proposal/\u003cid\u003e`.\n\n## Shares are the token, and that is the answer\n\nThe shares **are** the token. They are the vote weight and the claim on the\ntreasury at once, minted by joining and burned by leaving, so nothing about\nthem is decorative and nobody has to be persuaded they are worth something.\n\nv0 keeps them as an internal ledger rather than one GRC20 per crew, because a\nGRC20 per crew means a realm per crew. A transferable share belongs in\n[`p/moul/x/social/coin`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/social/coin), the sibling that refuses to\nexist until its mint rule, sink and buyer are declared. This realm does not\nimport it.\n\n## The custody caveat, which is real\n\n**One realm address holds every crew's treasury**, with per-crew accounting\ninside it. The chain sees one balance; which crew owns which part of it is a\nnumber in this realm's state.\n\nSo a bug in that accounting is a bug **across** crews, not inside one. An\narithmetic error that over-credits one crew's ragequit pays it out of another\ncrew's money, and nothing at the bank layer would refuse that transfer: as far\nas the chain is concerned it is all the same address paying itself out.\n\nThe fix is the instance-per-realm pattern\n(`EFFECTIVE_GNO.md` section 1.4, in this repository): one realm\nper crew, each holding its own coins at its own address, with\n`p/moul/x/social/crew` as the shared engine. That is v1. It is not v0 because\ndeploying a realm per crew is a publish per crew, which is the opposite of\n\"create it in one transaction\", and the one transaction is the whole product\nclaim.\n\n## Payouts are pulled, never pushed\n\nA ragequit credits an internal ledger and the leaver calls `Withdraw`\nthemselves. One address that cannot be paid cannot wedge anybody else, and the\ncredit is zeroed before the coins move, so a reentrant call finds nothing left\nto take.\n\n## What a proposal does not do\n\nNothing. A v0 proposal is advisory text: passing one records that the crew\nagreed by share weight at a point in time, and moves no coins, changes no\nmembership and binds no code. Executing a payout is the next step, and it is\nwhat would turn this into a treasury contract rather than a notice board.\n\n## Why this realm is private\n\n`private = true`, so it can be redeployed at this path by its creator, and no\nother realm may import it. The trade is the usual one: a redeploy wipes every\npackage-level variable, so every crew, every share and every credit would go\nwith it while the coins stayed at the address. Nothing imports this realm and\nnothing is meant to, so the redeploy door is worth more than the import one\nwhile the design is still moving. The v1 above is the move that closes it.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/social/crews/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/crews/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/social/crews/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/crews/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/social/crews/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/crews/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/social/crews/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/crews/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/social/crews/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/social/crews/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"crews.gno","body":"// Package crews is small-group coordination you can create in one\n// transaction: three to fifteen people with a shared pot, a way to decide, and\n// a way to leave with their share.\n//\n// It is the chain wiring for [gno.land/p/moul/x/social/crew], which holds the\n// share math and the proposal state. This realm reads the caller, reads the\n// coins attached to the call, asks the engine, and renders the result.\n//\n//\tCreate    pay in, and you are the crew's first member\n//\tJoin      pay in at what a share is worth NOW, not at what it cost them\n//\tFund      pay in and mint nothing, so every existing share is worth more\n//\tPropose   any member opens an advisory question\n//\tVote      weighted by the shares you hold, changeable while it is open\n//\tClose     anyone, once the deadline has gone by\n//\tRagequit  burn your shares, be credited your slice, leave\n//\tWithdraw  collect what you were credited\n//\n// # The shares are the token\n//\n// There is no second asset to issue. A share is the vote weight and the claim\n// on the treasury at the same moment, minted by paying in and burned by\n// leaving, so nothing about it is decorative and nobody has to be persuaded it\n// is worth something. v0 keeps the shares as an internal ledger rather than one\n// GRC20 per crew, because a GRC20 per crew means a realm per crew. A\n// transferable share belongs in [gno.land/p/moul/x/social/coin], the sibling\n// that refuses to exist until its mint rule, sink and buyer are declared; this\n// realm does not import it.\n//\n// # The custody caveat, which is real\n//\n// ONE realm address holds EVERY crew's treasury, with per-crew accounting\n// inside it. The chain sees one balance; which crew owns which part of it is a\n// number in this realm's state. So a bug in the accounting is a bug across\n// crews, not inside one: an arithmetic error that over-credits one crew's\n// ragequit pays it out of another crew's money, and nothing at the bank layer\n// would refuse that transfer.\n//\n// The fix is the instance-per-realm pattern (EFFECTIVE_GNO.md section 1.4): one\n// realm per crew, each holding its own coins at its own address, with this\n// package as the shared engine. That is v1. It is not v0 because deploying a\n// realm per crew is a publish per crew, which is the opposite of \"create it in\n// one transaction\", and the whole product claim here is the one transaction.\n//\n// # Payouts are pulled\n//\n// Nothing is ever pushed. A ragequit credits an internal ledger and the leaver\n// calls [Withdraw] themselves, so one address that cannot be paid cannot wedge\n// anybody else, and the credit is zeroed before the coins move.\npackage crews\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/x/envelope/v0\"\n\t\"gno.land/p/moul/x/social/crew/v0\"\n)\n\n// realmPath is this realm's own path, the one its gnomod.toml module line\n// declares. It is written out rather than read from the runtime, because every\n// plain read this realm exports reports its CALLER and would build every link\n// against the wrong realm.\nconst realmPath = \"gno.land/r/moul/x/social/crews/v0\"\n\n// denom is the only coin a crew holds. ugnot and nothing else: a treasury that\n// can hold several denominations needs a per-denomination share price, which is\n// a different product.\nconst denom = \"ugnot\"\n\n// IndexCrews is how many crews the index page lists.\nconst IndexCrews = 20\n\n// crews holds every crew, every proposal and the credit ledger. A redeploy\n// wipes it, which is the trade gnomod.toml's private = true makes: see the\n// comment there.\nvar crews = crew.New()\n\n// Create opens a crew and makes the caller its first member.\n//\n// Send ugnot with the call: the founder's shares are bought out of it at\n// crew.InitialPricePerShare, and the whole amount, remainder included, becomes\n// the treasury. Returns the new crew's id.\nfunc Create(cur realm, name string) int64 {\n\t// Both checks have to be here and not behind a helper. cur.IsCurrent()\n\t// before cur.Previous() is the realm-token rule; IsUserCall before the\n\t// envelope read is the payment one, because the envelope reports what\n\t// the SIGNER attached to the transaction and not what reached this\n\t// realm. Without it a realm the user called keeps the coins and calls\n\t// in here as many times as it likes, every call reading the same send.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"crews: paying in must be a direct user transaction\")\n\t}\n\twho := cur.Previous().Address()\n\tamount := envelope.RequireAtLeast(denom, crew.InitialPricePerShare)\n\n\tid, err := crews.Create(name, who, amount, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Create\",\n\t\t\"crew\", id.String(),\n\t\t\"founder\", who.String(),\n\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t)\n\treturn int64(id)\n}\n\n// Join mints the caller shares at what a share is worth right now and adds what\n// they sent to the treasury. Returns the shares minted.\n//\n// The price is amount * totalShares / treasury, rounded down, so somebody\n// joining a crew that has tripled its money pays three times what the founders\n// did. Send at least ValuePerShare ugnot, or there is no whole share to mint.\nfunc Join(cur realm, crewID int64) int64 {\n\t// The two guards every payable call needs; see Create.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"crews: paying in must be a direct user transaction\")\n\t}\n\twho := cur.Previous().Address()\n\tid := store.ID(crewID)\n\tc, ok := crews.Get(id)\n\tif !ok {\n\t\tpanic(crew.ErrNoCrew.Error())\n\t}\n\tamount := envelope.RequireAtLeast(denom, c.PricePerShare())\n\n\tshares, err := crews.Join(id, who, amount)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Join\",\n\t\t\"crew\", id.String(),\n\t\t\"member\", who.String(),\n\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t\t\"shares\", strconv.FormatInt(shares, 10),\n\t)\n\treturn shares\n}\n\n// Fund adds what the caller sent to a crew's treasury and mints nothing, so\n// every existing share is worth more afterwards.\n//\n// It is how revenue, a grant or a member topping the pot up arrives. Anyone may\n// fund any crew, member or not: there is no way to refuse a transfer on this\n// chain anyway, and pretending otherwise would only move the donation to a bank\n// send the realm cannot account for.\nfunc Fund(cur realm, crewID int64) int64 {\n\t// The two guards every payable call needs; see Create.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"crews: paying in must be a direct user transaction\")\n\t}\n\twho := cur.Previous().Address()\n\tamount := envelope.RequireAtLeast(denom, 1)\n\n\tif err := crews.Fund(store.ID(crewID), amount); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Fund\",\n\t\t\"crew\", store.ID(crewID).String(),\n\t\t\"from\", who.String(),\n\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t)\n\treturn amount\n}\n\n// Propose opens an advisory question on a crew. Any member may propose, and it\n// stays open for crew.VoteBlocks blocks. Returns the proposal's id.\n//\n// A proposal EXECUTES NOTHING. Passing one records that the crew agreed by\n// share weight, and moves no coins, changes no membership and binds no code.\n// Executing a payout is the next step and it is not in v0.\nfunc Propose(cur realm, crewID int64, text string) int64 {\n\twho := caller(cur)\n\tpid, err := crews.Propose(store.ID(crewID), who, text, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Propose\",\n\t\t\"crew\", store.ID(crewID).String(),\n\t\t\"proposal\", pid.String(),\n\t\t\"author\", who.String(),\n\t)\n\treturn int64(pid)\n}\n\n// Vote records the caller's ballot, weighted by the shares they hold at this\n// moment. One ballot per member, changeable while the proposal is open.\nfunc Vote(cur realm, proposalID int64, yes bool) {\n\twho := caller(cur)\n\tpid := store.ID(proposalID)\n\tif err := crews.Vote(pid, who, yes, runtime.ChainHeight()); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Vote\",\n\t\t\"proposal\", pid.String(),\n\t\t\"voter\", who.String(),\n\t\t\"yes\", strconv.FormatBool(yes),\n\t)\n}\n\n// Close records a proposal as passed or failed once its deadline has gone by,\n// and returns which. Anyone may call it: closing is bookkeeping, not authority.\nfunc Close(cur realm, proposalID int64) bool {\n\tpid := store.ID(proposalID)\n\tpassed, err := crews.Close(pid, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Close\", \"proposal\", pid.String(), \"passed\", strconv.FormatBool(passed))\n\treturn passed\n}\n\n// Ragequit burns every share the caller holds, credits them their pro-rata\n// slice of the treasury and removes them from the crew. Returns the amount\n// credited, which [Withdraw] collects.\n//\n// Nobody has to agree. That is what makes a share mean something: the exit is\n// priced by the same number that votes, and a member outvoted on everything can\n// still leave with what they put in plus their part of what the crew built.\nfunc Ragequit(cur realm, crewID int64) int64 {\n\twho := caller(cur)\n\tid := store.ID(crewID)\n\tshares, amount, err := crews.Ragequit(id, who)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Ragequit\",\n\t\t\"crew\", id.String(),\n\t\t\"member\", who.String(),\n\t\t\"shares\", strconv.FormatInt(shares, 10),\n\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t)\n\treturn amount\n}\n\n// Withdraw sends the caller everything they have been credited, and returns it.\n//\n// The credit is zeroed before the coins move, so a reentrant call finds nothing\n// left to take. Nothing in this realm ever pushes value: one address that\n// cannot be paid must not be able to wedge everybody else.\nfunc Withdraw(cur realm) int64 {\n\twho := caller(cur)\n\tamount, err := crews.Withdraw(who)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tbnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tbnk.SendCoins(cur.Address(), who, chain.NewCoins(chain.NewCoin(denom, amount)))\n\n\tchain.Emit(\"Withdraw\", \"payee\", who.String(), \"amount\", strconv.FormatInt(amount, 10))\n\treturn amount\n}\n\n// Get returns a crew's name, the height it was created at, how many members it\n// has, its total shares and its treasury in ugnot.\n//\n// Flat values rather than the crew itself: handing out a pointer to live state\n// is a mutation handle nothing checks, and a struct is not something a wallet\n// can decode anyway.\nfunc Get(crewID int64) (string, int64, int, int64, int64) {\n\tc, ok := crews.Get(store.ID(crewID))\n\tif !ok {\n\t\treturn \"\", 0, 0, 0, 0\n\t}\n\treturn c.Name, c.CreatedAt, c.MemberCount(), c.TotalShares, c.Treasury\n}\n\n// Count is how many crews exist.\nfunc Count() int { return crews.Len() }\n\n// SharesOf is how many shares who holds in a crew.\nfunc SharesOf(crewID int64, who address) int64 {\n\tc, _ := crews.Get(store.ID(crewID))\n\treturn c.SharesOf(who)\n}\n\n// MemberCount is how many people are in a crew.\nfunc MemberCount(crewID int64) int {\n\tc, _ := crews.Get(store.ID(crewID))\n\treturn c.MemberCount()\n}\n\n// Treasury is what a crew holds, in ugnot. The coins themselves sit at this\n// realm's single address: see the package doc on custody.\nfunc Treasury(crewID int64) int64 {\n\tc, _ := crews.Get(store.ID(crewID))\n\tif c == nil {\n\t\treturn 0\n\t}\n\treturn c.Treasury\n}\n\n// ValuePerShare is what one of a crew's shares is worth in ugnot, rounded down.\nfunc ValuePerShare(crewID int64) int64 {\n\tc, _ := crews.Get(store.ID(crewID))\n\treturn c.ValuePerShare()\n}\n\n// ProposalOf returns a proposal's crew, author, text, deadline and whether it\n// has been closed and passed.\nfunc ProposalOf(proposalID int64) (int64, address, string, int64, bool, bool) {\n\tp, ok := crews.Proposal(store.ID(proposalID))\n\tif !ok {\n\t\treturn 0, \"\", \"\", 0, false, false\n\t}\n\treturn int64(p.CrewID), p.Author, p.Text, p.Deadline, p.Closed, p.Passed\n}\n\n// Tally is a proposal's share-weighted yes and no.\nfunc Tally(proposalID int64) (int64, int64) {\n\tp, ok := crews.Proposal(store.ID(proposalID))\n\tif !ok {\n\t\treturn 0, 0\n\t}\n\treturn p.Yes, p.No\n}\n\n// CreditOf is what an address can withdraw right now, in ugnot.\nfunc CreditOf(who address) int64 { return crews.CreditOf(who) }\n\n// TotalOwed is every outstanding credit, which is the part of this realm's\n// balance that belongs to people who have already left.\nfunc TotalOwed() int64 { return crews.TotalOwed() }\n\n// caller is the address that called us, checked the one way that is safe.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"crews_test.gno","body":"package crews\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\n\t\"gno.land/p/moul/x/social/crew/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar realmAddr = chain.PackageAddress(realmPath)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// tenGNOT is what every founder here puts in: 10,000 shares at the opening\n// price, so halving and doubling stay exact and the rounding tests can use\n// deliberately awkward numbers instead.\nconst tenGNOT = int64(10000000)\n\n// reset clears realm state. Realm globals live for the whole test binary, so\n// everything a later test reads starts here.\nfunc reset() {\n\tcrews = crew.New()\n}\n\n// create calls Create the way a real transaction would: the runtime credits\n// the realm's address, then the envelope reports the send to the crossing\n// function. The account switch and the cross are in the same frame on purpose,\n// since testing.SetRealm governs nothing else.\nfunc create(cur realm, who address, amount int64, name string) int64 {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{denom, amount}})\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\treturn Create(cross(cur), name)\n}\n\n// join is [create] for Join.\nfunc join(cur realm, who address, amount, crewID int64) int64 {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{denom, amount}})\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\treturn Join(cross(cur), crewID)\n}\n\n// fund is [create] for Fund.\nfunc fund(cur realm, who address, amount, crewID int64) int64 {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{denom, amount}})\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\treturn Fund(cross(cur), crewID)\n}\n\nfunc TestCreateMakesTheFounderTheOnlyMember(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, tenGNOT, \"validators\")\n\n\tname, at, members, shares, treasury := Get(id)\n\tuassert.Equal(t, \"validators\", name)\n\tuassert.Equal(t, int64(123), at, \"tests start at height 123\")\n\tuassert.Equal(t, 1, members)\n\tuassert.Equal(t, tenGNOT/crew.InitialPricePerShare, shares)\n\tuassert.Equal(t, tenGNOT, treasury)\n\n\tuassert.Equal(t, shares, SharesOf(id, alice))\n\tuassert.Equal(t, int64(0), SharesOf(id, bob))\n\tuassert.Equal(t, crew.InitialPricePerShare, ValuePerShare(id))\n\tuassert.Equal(t, 1, Count())\n\tuassert.Equal(t, tenGNOT, Treasury(id))\n}\n\n// A second joiner at the same per-share value gets the same shares, which is\n// the baseline the anti-dilution rule is measured against.\nfunc TestASecondJoinerAtTheSamePriceGetsTheSameShares(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, tenGNOT, \"crew\")\n\tgot := join(cur, bob, tenGNOT, id)\n\n\tuassert.Equal(t, SharesOf(id, alice), got, \"same money, same shares\")\n\tuassert.Equal(t, crew.InitialPricePerShare, ValuePerShare(id), \"the price did not move\")\n\tuassert.Equal(t, 2, MemberCount(id))\n\tuassert.Equal(t, 2*tenGNOT, Treasury(id))\n}\n\n// A joiner arriving after the treasury grew gets FEWER shares for the same\n// money: they buy at what a share is worth now, not at what the founders paid.\nfunc TestAJoinerAfterTheTreasuryGrewGetsFewer(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, tenGNOT, \"crew\")\n\tfund(cur, carol, tenGNOT, id) // the crew doubled its money\n\turequire.Equal(t, 2*crew.InitialPricePerShare, ValuePerShare(id))\n\n\tgot := join(cur, bob, tenGNOT, id)\n\tuassert.Equal(t, SharesOf(id, alice)/2, got, \"the same money buys half as much\")\n\tuassert.Equal(t, 2*crew.InitialPricePerShare, ValuePerShare(id),\n\t\t\"and joining moved the value for nobody\")\n\tuassert.Equal(t, int64(0), SharesOf(id, carol), \"funding mints nothing\")\n}\n\n// Ragequit credits, Withdraw pays, and the coins actually move.\nfunc TestRagequitCreditsAndWithdrawPays(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, tenGNOT, \"crew\")\n\tjoin(cur, bob, tenGNOT, id)\n\tfund(cur, carol, 2*tenGNOT, id) // treasury 4x, still 2x the shares\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\towed := Ragequit(cross(cur), id)\n\tuassert.Equal(t, 2*tenGNOT, owed, \"half the shares of a treasury worth four\")\n\tuassert.Equal(t, owed, CreditOf(bob), \"credited, never sent\")\n\tuassert.Equal(t, owed, TotalOwed())\n\tuassert.Equal(t, 1, MemberCount(id))\n\tuassert.Equal(t, int64(0), SharesOf(id, bob))\n\tuassert.Equal(t, 2*tenGNOT, Treasury(id))\n\n\tbefore := banker.NewReadonlyBanker().GetCoins(bob).AmountOf(denom)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tgot := Withdraw(cross(cur))\n\tuassert.Equal(t, owed, got)\n\tuassert.Equal(t, int64(0), CreditOf(bob), \"zeroed before the coins moved\")\n\tuassert.Equal(t, int64(0), TotalOwed())\n\n\tafter := banker.NewReadonlyBanker().GetCoins(bob).AmountOf(denom)\n\tuassert.Equal(t, before+owed, after, \"the coins actually arrived\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() { Withdraw(cross(cur)) })\n}\n\n// Everyone ragequitting empties the treasury to the last ugnot, even when no\n// single division is exact: the dust a leaver rounds away belongs to whoever is\n// still in, and the last one out holds every share.\nfunc TestEveryoneRagequittingEmptiesTheTreasury(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, 1000, \"crew\")\n\tjoin(cur, bob, 1000, id)\n\tjoin(cur, carol, 1000, id)\n\tfund(cur, alice, 2, id) // 3002 ugnot over 3 shares, divides by nothing\n\n\turequire.Equal(t, int64(3002), Treasury(id))\n\n\tvar paid int64\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tpaid += Ragequit(cross(cur), id)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tpaid += Ragequit(cross(cur), id)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tpaid += Ragequit(cross(cur), id)\n\n\tuassert.Equal(t, int64(3002), paid, \"every ugnot left with somebody\")\n\tuassert.Equal(t, int64(0), Treasury(id), \"to the last one\")\n\tuassert.Equal(t, 0, MemberCount(id))\n\tuassert.Equal(t, int64(3002), TotalOwed())\n\tuassert.Equal(t, int64(1000), CreditOf(alice), \"first out, rounded down hardest\")\n\tuassert.Equal(t, int64(1001), CreditOf(carol), \"last out takes the dust\")\n}\n\n// A one-member crew ragequitting takes everything, including the ugnot that\n// bought no whole share: their shares ARE the total, so the division is exact.\nfunc TestAOneMemberCrewTakesEverything(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, 5001, \"solo\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tgot := Ragequit(cross(cur), id)\n\tuassert.Equal(t, int64(5001), got)\n\tuassert.Equal(t, int64(0), Treasury(id))\n\tuassert.Equal(t, 0, MemberCount(id))\n\n\t// An emptied crew is not a dead one: with nothing outstanding there is\n\t// no value to price against, so it reopens at the opening price.\n\tuassert.Equal(t, int64(0), ValuePerShare(id))\n\tgot = join(cur, bob, tenGNOT, id)\n\tuassert.Equal(t, tenGNOT/crew.InitialPricePerShare, got)\n}\n\nfunc TestProposalsAreAdvisoryAndShareWeighted(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, tenGNOT, \"crew\") // alice: 10000 shares\n\tjoin(cur, bob, tenGNOT/2, id)             // bob:    5000 shares\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tpid := Propose(cross(cur), id, \"ship v1 before the conference\")\n\n\t_, author, text, deadline, closed, passed := ProposalOf(pid)\n\tuassert.Equal(t, bob.String(), author.String())\n\tuassert.Equal(t, \"ship v1 before the conference\", text)\n\tuassert.Equal(t, int64(123+crew.VoteBlocks), deadline)\n\tuassert.False(t, closed)\n\tuassert.False(t, passed)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVote(cross(cur), pid, true)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tVote(cross(cur), pid, false)\n\n\tyes, no := Tally(pid)\n\tuassert.Equal(t, int64(5000), yes)\n\tuassert.Equal(t, int64(10000), no, \"a bigger holder outvotes a smaller one\")\n\n\t// Changing your mind while it is open replaces the ballot.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tVote(cross(cur), pid, true)\n\tyes, no = Tally(pid)\n\tuassert.Equal(t, int64(15000), yes)\n\tuassert.Equal(t, int64(0), no, \"the old ballot is removed, not added to\")\n\n\ttesting.SkipHeights(crew.VoteBlocks)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.True(t, Close(cross(cur), pid), \"anyone may close it\")\n\n\t_, _, _, _, closed, passed = ProposalOf(pid)\n\tuassert.True(t, closed)\n\tuassert.True(t, passed)\n\n\t// Passing it moved nothing. That is the whole v0 claim.\n\tuassert.Equal(t, tenGNOT+tenGNOT/2, Treasury(id))\n\tuassert.Equal(t, int64(0), TotalOwed())\n}\n\nfunc TestRefusals(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, tenGNOT, \"crew\")\n\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, tenGNOT}})\n\ttesting.SetOriginSend(chain.Coins{{denom, tenGNOT}})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"already a member\", func() { Join(cross(cur), id) })\n\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, tenGNOT}})\n\ttesting.SetOriginSend(chain.Coins{{denom, tenGNOT}})\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"no such crew\", func() { Join(cross(cur), 4242) })\n\n\t// Create with nothing attached is refused by the envelope, which names\n\t// the flag the caller has to fix.\n\ttesting.SetOriginSend(chain.Coins{})\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"send\", func() { Create(cross(cur), \"broke\") })\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"not a member\", func() {\n\t\tPropose(cross(cur), id, \"let me in\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"not a member\", func() { Ragequit(cross(cur), id) })\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tpid := Propose(cross(cur), id, \"a question\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"not a member\", func() { Vote(cross(cur), pid, true) })\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"still open\", func() { Close(cross(cur), pid) })\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"name is empty\", func() {\n\t\tcreate(cur, alice, tenGNOT, \"  \")\n\t})\n\t// A pipe in a name would open a column where the name is a link title\n\t// in a table cell, which md.Link's escaper does not cover.\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"name is empty\", func() {\n\t\tcreate(cur, alice, tenGNOT, \"a | pipe\")\n\t})\n\n\tuassert.Equal(t, 1, Count(), \"no refusal created anything\")\n\tuassert.Equal(t, 1, MemberCount(id))\n}\n\n// TestRender uses uassert rather than an Example because every view contains\n// consecutive blank lines, which gno collapses inside an // Output: block.\nfunc TestRender(cur realm, t *testing.T) {\n\treset()\n\tid := create(cur, alice, tenGNOT, \"a crew [with](markdown)\")\n\tjoin(cur, bob, tenGNOT, id)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tpid := Propose(cross(cur), id, \"ship v1 | before the conference\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tVote(cross(cur), pid, true)\n\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"# Crews\"), index)\n\tuassert.True(t, strings.Contains(index, \"| 1 | 1 | 0 GNOT |\"), \"crews, proposals, owed\")\n\tuassert.True(t, strings.Contains(index, \"func=Create\"), index)\n\tuassert.True(t, strings.Contains(index, \"One realm address holds every crew's treasury\"),\n\t\t\"the index states the custody caveat\")\n\tuassert.True(t, strings.Contains(index,\n\t\t\"[a crew \\\\[with\\\\]\\\\(markdown\\\\)](/r/moul/x/social/crews/v0:crew/1)\"),\n\t\t\"md.Link escapes the title exactly once: \"+index)\n\n\tsid := strconv.FormatInt(id, 10)\n\tpage := Render(\"crew/\" + sid)\n\tuassert.True(t, strings.Contains(page, \"# a crew \\\\[with\\\\]\\\\(markdown\\\\)\"),\n\t\t\"the name is escaped where it is shown as prose: \"+page)\n\tuassert.True(t, strings.Contains(page, \"| 2 of 15 | 20000 | 20 GNOT | 0.001 GNOT |\"), page)\n\tuassert.True(t, strings.Contains(page, \"| 10000 | 50% | 10 GNOT |\"),\n\t\t\"each member holds half the shares and half the money\")\n\tuassert.True(t, strings.Contains(page, \"func=Ragequit\"), page)\n\tuassert.True(t, strings.Contains(page, \"executes nothing\"), page)\n\n\t// A pipe in a proposal's text must not open a column in the crew's\n\t// proposal table. It goes through ui.Cell for exactly this.\n\tuassert.True(t, strings.Contains(page, \"ship v1 \\\\| before the conference\"),\n\t\t\"the cell is escaped: \"+page)\n\tuassert.False(t, strings.Contains(page, \"| ship v1 | before\"),\n\t\t\"a raw pipe would open a column: \"+page)\n\n\tspid := strconv.FormatInt(pid, 10)\n\tprop := Render(\"proposal/\" + spid)\n\tuassert.True(t, strings.Contains(prop, \"# Proposal #\"+spid), prop)\n\tuassert.True(t, strings.Contains(prop, \"\u003e ship v1 | before the conference\"),\n\t\t\"a blockquote is prose, where a pipe is inert and must not grow a backslash\")\n\tuassert.True(t, strings.Contains(prop, \"| open until 1123 | 10000 | 0 | 1 |\"), prop)\n\tuassert.True(t, strings.Contains(prop, \"func=Vote\"), prop)\n\n\t// Past the deadline the page offers the close instead of the vote.\n\ttesting.SkipHeights(crew.VoteBlocks)\n\tprop = Render(\"proposal/\" + spid)\n\tuassert.True(t, strings.Contains(prop, \"awaiting a close\"), prop)\n\tuassert.True(t, strings.Contains(prop, \"func=Close\"), prop)\n\tuassert.False(t, strings.Contains(prop, \"func=Vote\"), prop)\n\n\tuassert.Equal(t, \"# Crews\\nNo crew #4242\", Render(\"crew/4242\"))\n\tuassert.Equal(t, \"# Crews\\nNot a crew id: nope\", Render(\"crew/nope\"))\n\tuassert.Equal(t, \"# Crews\\nNo proposal #4242\", Render(\"proposal/4242\"))\n\tuassert.Equal(t, \"# Crews\\nNot a proposal id: nope\", Render(\"proposal/nope\"))\n\tuassert.True(t, strings.HasPrefix(Render(\"elsewhere\"), \"# Not found\"))\n}\n\n// An empty realm still renders something a reader can act on.\nfunc TestRenderWithNothingInIt(cur realm, t *testing.T) {\n\treset()\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"No crews yet.\"), index)\n\tuassert.True(t, strings.Contains(index, \"func=Create\"), index)\n}\n\n// Links are rooted at the realm's own path, so they resolve from any page\n// gnoweb serves them on.\nfunc TestLinksAreRootRelative(t *testing.T) {\n\tuassert.Equal(t, \"/r/moul/x/social/crews/v0\", realmURL())\n\tuassert.Equal(t, \"/r/moul/x/social/crews/v0:crew/7\", crewURL(7))\n\tuassert.Equal(t, \"/r/moul/x/social/crews/v0:proposal/7\", proposalURL(7))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/social/crews/v0\"\ngno = \"0.9\"\nprivate = true\n\n# private: nothing imports this realm and nothing is meant to. The trade is the\n# usual one, a redeploy wipes every crew, share and credit while the coins stay\n# at the address, and it is worth taking while the design is still moving. The\n# v1 in README.md, one realm per crew, is the move that closes the door.\n"},{"name":"render.gno","body":"package crews\n\nimport (\n\t\"strconv\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/x/social/crew/v0\"\n\t\"gno.land/p/moul/xmath/v1\"\n)\n\n// Render routes three views: the index, one crew, and one proposal.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tswitch req.PathPart(0) {\n\tcase \"\":\n\t\treturn renderIndex()\n\tcase \"crew\":\n\t\treturn renderCrew(req.PathPart(1))\n\tcase \"proposal\":\n\t\treturn renderProposal(req.PathPart(1))\n\tdefault:\n\t\treturn md.H1(\"Not found\") + \"No such view: \" + ui.Inline(req.Path)\n\t}\n}\n\nfunc renderIndex() string {\n\tout := md.H1(\"Crews\")\n\tout += \"Three to fifteen people with a shared pot, a way to decide, and a way to \" +\n\t\t\"leave with their share. One transaction to start one.\\n\\n\"\n\n\tt := ui.NewTable(\"crews\", \"proposals\", \"owed to people who left\")\n\tt.Row(\n\t\tstrconv.Itoa(crews.Len()),\n\t\tstrconv.Itoa(crews.ProposalCount()),\n\t\tnum.GNOTf(crews.TotalOwed()),\n\t)\n\tout += t.String()\n\n\tout += md.H2(\"The crews\")\n\tout += crewTable(crews.List(IndexCrews))\n\n\tout += \"\\n\" + ui.Action(\"Start a crew\", \"Create\", \"name\", \"\") + \"\\n\"\n\n\tout += md.H2(\"How a share works\")\n\tout += md.BulletList([]string{\n\t\t\"A share is the vote weight and the claim on the treasury at once. There is no second token.\",\n\t\t\"Joining mints shares at what a share is worth NOW: \" +\n\t\t\tmd.InlineCode(\"amount * totalShares / treasury\") +\n\t\t\t\", rounded down, so a late joiner cannot buy into value the others built.\",\n\t\t\"Ragequitting burns every share you hold and credits you \" +\n\t\t\tmd.InlineCode(\"shares * treasury / totalShares\") +\n\t\t\t\", rounded down. Nobody has to agree.\",\n\t\t\"Both round in the crew's favour. The last member out holds every share, \" +\n\t\t\t\"so the treasury still empties to the last ugnot.\",\n\t\t\"A proposal is advisory text. Passing one records agreement and executes nothing.\",\n\t})\n\n\tout += md.H2(\"Custody\")\n\tout += \"One realm address holds every crew's treasury, with per-crew accounting \" +\n\t\t\"inside. A bug in that accounting is a bug across crews, not inside one. \" +\n\t\t\"The fix is one realm per crew, and it is v1.\\n\"\n\n\treturn out\n}\n\nfunc renderCrew(raw string) string {\n\tid, ok := store.ParseID(raw)\n\tif !ok {\n\t\treturn md.H1(\"Crews\") + \"Not a crew id: \" + ui.Inline(raw)\n\t}\n\tc, found := crews.Get(id)\n\tif !found {\n\t\treturn md.H1(\"Crews\") + \"No crew #\" + id.String()\n\t}\n\n\tout := md.H1(ui.Inline(c.Name))\n\tout += md.Italic(\"crew #\"+id.String()+\" · opened at block \"+\n\t\tstrconv.FormatInt(c.CreatedAt, 10)) + \"\\n\\n\"\n\n\tt := ui.NewTable(\"members\", \"shares\", \"treasury\", \"per share\")\n\tt.Row(\n\t\tstrconv.Itoa(c.MemberCount())+\" of \"+strconv.Itoa(crew.MaxMembers),\n\t\tstrconv.FormatInt(c.TotalShares, 10),\n\t\tnum.GNOTf(c.Treasury),\n\t\tnum.GNOTf(c.ValuePerShare()),\n\t)\n\tout += t.String()\n\n\tout += md.H2(\"Members\")\n\tif c.MemberCount() == 0 {\n\t\tout += ui.Empty(\"Everybody has left. The next member in pays the opening price again.\")\n\t} else {\n\t\tm := ui.NewTable(\"member\", \"shares\", \"weight\", \"worth\")\n\t\tfor _, who := range c.Members() {\n\t\t\tshares := c.SharesOf(who)\n\t\t\tm.Row(\n\t\t\t\tui.Addr(who),\n\t\t\t\tstrconv.FormatInt(shares, 10),\n\t\t\t\tnum.Pct(xmath.MulDiv(shares, 10000, c.TotalShares)),\n\t\t\t\tnum.GNOTf(xmath.MulDiv(shares, c.Treasury, c.TotalShares)),\n\t\t\t)\n\t\t}\n\t\tout += m.String()\n\t}\n\n\tout += md.H2(\"Proposals\")\n\tout += proposalTable(c.Proposals())\n\tout += \"\\nA proposal is advisory text. Passing one records that the crew agreed \" +\n\t\t\"by share weight, and executes nothing.\\n\"\n\n\tout += \"\\n\" + ui.Join(\" · \",\n\t\tui.Action(\"Join\", \"Join\", \"crewID\", id.String()),\n\t\tui.Action(\"Fund\", \"Fund\", \"crewID\", id.String()),\n\t\tui.Action(\"Propose\", \"Propose\", \"crewID\", id.String(), \"text\", \"\"),\n\t\tui.Action(\"Ragequit\", \"Ragequit\", \"crewID\", id.String()),\n\t) + \"\\n\"\n\treturn out\n}\n\nfunc renderProposal(raw string) string {\n\tpid, ok := store.ParseID(raw)\n\tif !ok {\n\t\treturn md.H1(\"Crews\") + \"Not a proposal id: \" + ui.Inline(raw)\n\t}\n\tp, found := crews.Proposal(pid)\n\tif !found {\n\t\treturn md.H1(\"Crews\") + \"No proposal #\" + pid.String()\n\t}\n\n\tout := md.H1(\"Proposal #\" + pid.String())\n\tout += md.Blockquote(ui.Inline(p.Text)) + \"\\n\"\n\n\tcrewName := \"crew #\" + p.CrewID.String()\n\tif c, ok := crews.Get(p.CrewID); ok {\n\t\tcrewName = c.Name\n\t}\n\tout += md.Italic(\"by \"+ui.Addr(p.Author)+\" · in \"+\n\t\tmd.Link(ui.ShortN(crewName, crew.ExcerptLen, 0), crewURL(p.CrewID))) + \"\\n\\n\"\n\n\tnow := runtime.ChainHeight()\n\tt := ui.NewTable(\"state\", \"yes\", \"no\", \"voters\")\n\tt.Row(\n\t\tstate(p, now),\n\t\tstrconv.FormatInt(p.Yes, 10),\n\t\tstrconv.FormatInt(p.No, 10),\n\t\tstrconv.Itoa(p.Voters()),\n\t)\n\tout += t.String()\n\n\tif p.Open(now) {\n\t\tout += \"\\n\" + ui.Join(\" · \",\n\t\t\tui.Action(\"Vote yes\", \"Vote\", \"proposalID\", pid.String(), \"yes\", \"true\"),\n\t\t\tui.Action(\"Vote no\", \"Vote\", \"proposalID\", pid.String(), \"yes\", \"false\"),\n\t\t) + \"\\n\"\n\t} else if !p.Closed {\n\t\tout += \"\\n\" + ui.Action(\"Close it\", \"Close\", \"proposalID\", pid.String()) + \"\\n\"\n\t}\n\treturn out\n}\n\n// crewTable lists crews, newest first.\nfunc crewTable(items []crew.Listing) string {\n\tt := ui.NewTable(\"crew\", \"members\", \"shares\", \"treasury\")\n\tfor _, it := range items {\n\t\tt.Row(\n\t\t\t// ShortN truncates without escaping and md.Link escapes what it\n\t\t\t// is given: ui.Inline here would escape twice and render the\n\t\t\t// backslashes. A pipe is what md.Link's escaper does NOT cover,\n\t\t\t// which is why crew.ValidName refuses one at write time.\n\t\t\tmd.Link(ui.ShortN(it.Crew.Name, crew.ExcerptLen, 0), crewURL(it.ID)),\n\t\t\tstrconv.Itoa(it.Crew.MemberCount()),\n\t\t\tstrconv.FormatInt(it.Crew.TotalShares, 10),\n\t\t\tnum.GNOTf(it.Crew.Treasury),\n\t\t)\n\t}\n\treturn t.OrEmpty(\"No crews yet.\")\n}\n\n// proposalTable lists a crew's proposals, newest first.\n//\n// The link title is the id and not the text, which is the opposite of\n// crewTable and deliberate: a proposal's text is free prose and may contain a\n// pipe, md.Link's escaper leaves pipes alone, and a pipe in a link title inside\n// a table cell opens a column. So the chrome carries the link and the prose\n// goes through ui.Cell, which is the escaper that knows it is in a table.\nfunc proposalTable(ids []store.ID) string {\n\tnow := runtime.ChainHeight()\n\tt := ui.NewTable(\"#\", \"proposal\", \"state\", \"yes\", \"no\")\n\tfor i := len(ids) - 1; i \u003e= 0; i-- {\n\t\tp, ok := crews.Proposal(ids[i])\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tt.Row(\n\t\t\tmd.Link(\"#\"+ids[i].String(), proposalURL(ids[i])),\n\t\t\t// Cut on a rune boundary first, escape once after: escaping\n\t\t\t// first and cutting after can strand a lone backslash.\n\t\t\tui.Cell(ui.ShortN(p.Text, crew.ExcerptLen, 0)),\n\t\t\tstate(p, now),\n\t\t\tstrconv.FormatInt(p.Yes, 10),\n\t\t\tstrconv.FormatInt(p.No, 10),\n\t\t)\n\t}\n\treturn t.OrEmpty(\"Nothing has been proposed yet.\")\n}\n\n// state is the one word a proposal is in at height now.\nfunc state(p *crew.Proposal, now int64) string {\n\tswitch {\n\tcase p.Open(now):\n\t\treturn \"open until \" + strconv.FormatInt(p.Deadline, 10)\n\tcase !p.Closed:\n\t\treturn \"awaiting a close\"\n\tcase p.Passed:\n\t\treturn \"passed\"\n\tdefault:\n\t\treturn \"failed\"\n\t}\n}\n\n// crewURL is the gnoweb path of one crew.\nfunc crewURL(id store.ID) string { return realmURL() + \":crew/\" + id.String() }\n\n// proposalURL is the gnoweb path of one proposal.\nfunc proposalURL(id store.ID) string { return realmURL() + \":proposal/\" + id.String() }\n\n// realmURL is this realm's gnoweb path. The chain domain is the first element\n// of a package path and a gnoweb path is the rest of it, so this is a prefix\n// strip and not a hostname the realm has to know.\nfunc realmURL() string {\n\tfor i := 0; i \u003c len(realmPath); i++ {\n\t\tif realmPath[i] == '/' {\n\t\t\treturn realmPath[i:]\n\t\t}\n\t}\n\treturn \"/\" + realmPath\n}\n"}]},"send":"","max_deposit":"17000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"curated","path":"gno.land/r/moul/x/social/curated/v0","files":[{"name":"README.md","body":"# r/moul/x/social/curated\n\nA curated list with skin in the game. Anyone lists an entry by locking a deposit, anyone\nchallenges an entry by matching that deposit with a bond, and after a voting window the\nloser's money goes to the winner. The deposit does not make an entry good. It makes a bad\none expensive to leave standing, which is the only reason a list anybody can write to is\nworth reading at all.\n\nThe engine is [`p/moul/x/social/curated/v0`](../../../../../p/moul/x/social/curated), a\npure package that returns errors and moves no coins. This realm is the chain wiring: the\nenvelope, the banker, the events and `Render`.\n\n## The API\n\n| call | pays | does |\n|---|---|---|\n| `Apply(key, url, description)` | exactly 1 GNOT | lists the entry immediately |\n| `Challenge(key)` | exactly that entry's deposit | opens a vote for 1000 blocks |\n| `Vote(key, keep)` | nothing | one address, one vote, while the window is open |\n| `Resolve(key)` | nothing | anyone, after the window: pays the winner |\n| `Unlist(key)` | nothing | the owner takes their own entry down, if unchallenged |\n| `Withdraw()` | nothing | collects everything credited to the caller |\n\nReads: `Get`, `Count`, `Listed`, `IsListed`, `ChallengeOf`, `CreditOf`.\n\nA key is a slug: lowercase ASCII letters, digits, `-`, `_` and `.`, starting alphanumeric,\nat most 64 bytes. A key whose entry was removed is free to apply for again: a challenge\nthat wins removes an entry, it does not burn the name.\n\nA majority of `keep` votes keeps the entry and credits its owner the challenger's bond.\nOtherwise the entry is removed and the challenger is credited the bond plus the deposit.\n**A tie keeps the entry**, including the tie of nobody voting at all: the incumbent paid\nfirst and is already at risk, so the burden is on the challenger to produce a reason. If\nties went the other way, a challenge that convinced nobody would still win and listing\nanything would be pointless.\n\n## The trap it avoids\n\n**Nothing is ever sent to you.** Every payout is a credit in an internal ledger, and the\npayee calls `Withdraw()` for their own. A realm that looped over winners and sent to each\none would fail entirely when one of them could not be paid, and would hand a griefer a\ndenial of service for the price of one entry. `Withdraw` zeroes the credit before the\ncoins move, so a reentrant call finds nothing left to take.\n\nThe consequence is an invariant worth knowing: every ugnot at this realm's address is\neither backing a live entry or an open challenge, or already assigned to somebody. The\ntests assert exactly that, against the chain balance rather than against the realm's own\nbooks.\n\n## Voting is sybil-prone, deliberately and visibly\n\n`Vote` is one address, one vote, unweighted, and an address is free. A resolution says\n\"nobody with a stake objected enough\", never \"this is true\". Deciding who counts as a\nperson is a different problem with its own realm behind it, `r/moul/x/social/vouch`, a\nsibling in this family; until a vote is gated on a vouched identity, the two addresses\nwith money on the outcome are the only ones whose vote means anything.\n\nWhich is the second thing: **voters are paid nothing in v0**. Voting costs gas and returns\nnothing, so there is no reason for a disinterested address to show up at all. A share of\nthe loser's stake for the winning side is the standard answer, and it is the first thing\nthis realm should grow. After that, an application period, so a bad entry is not visible\nbefore anybody can object to it.\n\n## Why the bonds are GNOT and not a token of this list's own\n\nA bond has to be denominated in something the challenger already holds. A list that minted\nits own token and demanded it as the bond would be asking a newcomer to acquire a token\nwhose only use is challenging entries on a list nobody reads yet, which is the\nchicken-and-egg problem in its purest form: the token is worth something once the list is\nworth gaming, and the list cannot become worth gaming until challenges work.\n\nSo v0 bonds are native GNOT, which every account on the chain already has.\n\nThe answer becomes yes under one condition: **the list is valuable enough that being on it\nis contested, and the challenge flow is busy enough that a bond denominated in a list\ntoken would have a real market price.** Concretely, a steady stream of challenges from\naddresses that are not the two parties, and a reason to hold the token between challenges.\nAt that point the token earns its own job, and it can pay the voters the paragraph above\nsays go unpaid, which is the sink a bond alone does not provide.\n\nThe slot it would drop into is `p/moul/x/social/coin/v0`, a GRC20 in this family that\nrefuses to exist until its mint rule, its sink and its buyer are all declared. This realm\ndeliberately does not import it: the three answers are not available yet, and a token\nissued before they are is a token with no reason to be held.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/social/curated/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/curated/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/social/curated/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/curated/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/social/curated/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/curated/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/social/curated/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/curated/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/social/curated/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/social/curated/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"curated.gno","body":"// Package curated is a list anyone can get onto by locking a deposit, and\n// anyone can try to get somebody else off by matching that deposit with a bond.\n// The loser of the challenge pays the winner.\n//\n// It is the registry member of a family of small social apps: a list is the\n// thing every other one of them eventually needs, and a list is only worth\n// reading if being on it cost something.\n//\n//\tApply(key, url, description)  -send 1000000ugnot   list it, immediately\n//\tChallenge(key)                -send \u003cthe deposit\u003e  object to it\n//\tVote(key, keep)                                    while the window is open\n//\tResolve(key)                                       anyone, after it closes\n//\tUnlist(key)                                        the owner, if unchallenged\n//\tWithdraw()                                         collect what you won\n//\n// # Money in, money out\n//\n// Coins arrive in the envelope of a call and sit at this realm's address. They\n// never leave by being pushed: a payout is a credit in a ledger and the payee\n// calls [Withdraw] for their own. A realm that looped over winners and sent to\n// each one would fail entirely when one of them could not be paid, and would\n// hand a griefer a cheap denial of service for the price of one entry.\n//\n// Every ugnot here is therefore either backing a live entry or an open\n// challenge, or already assigned to somebody. The realm's own tests assert\n// exactly that against the chain balance.\n//\n// # Voting is sybil-prone, and the bonds are GNOT\n//\n// [Vote] is one address, one vote, unweighted, and an address is free. Read a\n// resolution as \"nobody with a stake objected enough\", never as a verdict.\n// Gating a vote on something harder to manufacture is a different problem with\n// its own realm behind it, r/moul/x/social/vouch, a sibling in this family.\n//\n// Bonds are GNOT and not a token of this list's own: see the README on why\n// that is the only answer available at v0 and what would change it.\n//\n// # What v0 does not do, in the order it should be fixed\n//\n//  1. Voters are paid nothing. Voting costs gas and returns nothing, so the\n//     only two addresses with a reason to vote are the ones with money on the\n//     outcome. A share of the loser's stake for the winning side is the\n//     standard answer and the first thing to add.\n//  2. There is no application period: [Apply] lists immediately.\n//  3. A challenge cannot be withdrawn and a vote cannot be changed.\npackage curated\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"strconv\"\n\n\t\"gno.land/p/moul/x/envelope/v0\"\n\tcu \"gno.land/p/moul/x/social/curated/v0\"\n)\n\n// realmPath is this realm's own path, the one its gnomod.toml module line\n// declares. Render builds its links from it rather than from\n// unsafe.CurrentRealm(), which in a plain read reports the CALLER.\nconst realmPath = \"gno.land/r/moul/x/social/curated/v0\"\n\nconst (\n\t// Denom is what a deposit and a bond are paid in. Native coins, so the\n\t// amounts are real to a challenger before this list is worth anything.\n\tDenom = \"ugnot\"\n\n\t// Deposit is what listing costs, and therefore also what challenging one\n\t// of today's entries costs. One GNOT: enough to make a thousand junk\n\t// entries a real expense, cheap enough that one honest entry is not a\n\t// decision.\n\tDeposit = int64(1000000)\n\n\t// ChallengeBlocks is how long a challenge takes to resolve. Long enough\n\t// for a reader who is not watching the chain to notice and vote, short\n\t// enough that an entry is not held hostage.\n\tChallengeBlocks = int64(1000)\n)\n\n// list is every entry and the credit ledger behind them. A redeploy would wipe\n// it while leaving the coins at the address, which is what the note in\n// gnomod.toml is about.\nvar list = cu.New(Deposit, ChallengeBlocks)\n\n// Apply lists an entry under key, in exchange for exactly [Deposit] ugnot.\n//\n// The entry is on the list the moment this returns: there is no application\n// period in v0, and the check on a bad entry is that anybody can challenge it.\n// The deposit comes back through [Unlist] and [Withdraw] if nobody ever does.\n//\n// key is a slug: lowercase ASCII letters, digits, '-', '_' and '.', starting\n// alphanumeric. A key whose entry was removed is free to apply for again.\nfunc Apply(cur realm, key, url, description string) {\n\t// Both checks are inlined rather than hidden behind caller(), and in this\n\t// order. cur.IsCurrent() before cur.Previous() is the realm-token rule;\n\t// IsUserCall before the envelope read is the payment one, because the\n\t// envelope reports what the SIGNER attached to the transaction and not\n\t// what reached this realm. Without it a realm the user called keeps the\n\t// coins and calls in here as often as it likes, every call reading the\n\t// same send: that is r/moul/grant Fund, which recorded 5 donations of\n\t// 1 GNOT from one 1 GNOT send with nothing in the treasury.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"curated: paying in must be a direct user transaction\")\n\t}\n\twho := cur.Previous().Address()\n\tpaid := envelope.RequireExactly(Denom, Deposit)\n\tif err := list.Apply(key, url, description, who, paid, runtime.ChainHeight()); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Apply\", \"key\", key, \"owner\", who.String(),\n\t\t\"deposit\", strconv.FormatInt(paid, 10))\n}\n\n// Challenge objects to an entry, in exchange for a bond equal to that entry's\n// own deposit, and opens a vote that closes [ChallengeBlocks] blocks later.\n//\n// An owner cannot challenge their own entry: it would cost them nothing and\n// would make the entry immune to a real challenge for the whole window.\nfunc Challenge(cur realm, key string) {\n\t// The two guards every payable call needs, inlined; see Apply.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"curated: paying in must be a direct user transaction\")\n\t}\n\twho := cur.Previous().Address()\n\t// The bond is read before the envelope is, so somebody who attaches coins\n\t// to a challenge of something unchallengeable is told which of the two is\n\t// wrong.\n\tbond, ok := list.BondFor(key)\n\tif !ok {\n\t\tpanic(\"curated: \" + key + \" is not an entry that can be challenged\")\n\t}\n\tenvelope.RequireExactly(Denom, bond)\n\tif err := list.Challenge(key, who, bond, runtime.ChainHeight()); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tc, _ := list.ChallengeOf(key)\n\tchain.Emit(\"Challenge\", \"key\", key, \"by\", who.String(),\n\t\t\"bond\", strconv.FormatInt(bond, 10),\n\t\t\"deadline\", strconv.FormatInt(c.Deadline, 10))\n}\n\n// Vote takes a side on an open challenge: keep the entry, or remove it.\n//\n// One address, one vote, unweighted, and it cannot be changed. An address is\n// free, so this is cheap to manufacture; see the package doc.\nfunc Vote(cur realm, key string, keep bool) {\n\twho := caller(cur)\n\tif err := list.Vote(key, who, keep, runtime.ChainHeight()); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Vote\", \"key\", key, \"by\", who.String(), \"keep\", strconv.FormatBool(keep))\n}\n\n// Resolve closes a challenge whose window has passed. Anyone may call it, so\n// neither party can stall the other by sitting still.\n//\n// A majority of keep votes keeps the entry and credits its owner the bond.\n// Otherwise the entry is removed and the challenger is credited the bond plus\n// the deposit. A tie, including nobody voting at all, keeps the entry: the\n// incumbent is the one already at risk, so a challenge that convinced nobody\n// loses, which is what makes being wrong cost something.\nfunc Resolve(cur realm, key string) {\n\twho := caller(cur)\n\tout, err := list.Resolve(key, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Resolve\", \"key\", key,\n\t\t\"kept\", strconv.FormatBool(out.Kept),\n\t\t\"winner\", out.Winner.String(),\n\t\t\"amount\", strconv.FormatInt(out.Amount, 10),\n\t\t\"keep\", strconv.FormatInt(out.Keep, 10),\n\t\t\"remove\", strconv.FormatInt(out.Remove, 10),\n\t\t\"by\", who.String())\n}\n\n// Unlist takes the caller's own entry off the list and credits them the\n// deposit back, which [Withdraw] then pays out.\n//\n// It is refused while a challenge is open: an owner who could walk away\n// mid-challenge would be risking nothing, which is the one thing the deposit\n// exists to prevent.\nfunc Unlist(cur realm, key string) {\n\twho := caller(cur)\n\tif err := list.Unlist(key, who); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Unlist\", \"key\", key, \"owner\", who.String())\n}\n\n// Withdraw pays the caller everything credited to them and returns it.\n//\n// This is the only way coins leave the realm. The credit is zeroed before the\n// transfer, so a reentrant call finds nothing left to take.\nfunc Withdraw(cur realm) int64 {\n\twho := caller(cur)\n\tamount, err := list.Withdraw(who)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tbnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tbnk.SendCoins(cur.Address(), who, chain.NewCoins(chain.NewCoin(Denom, amount)))\n\n\tchain.Emit(\"Withdraw\", \"to\", who.String(), \"amount\", strconv.FormatInt(amount, 10))\n\treturn amount\n}\n\n// Get returns what is known about an entry: its URL, its description, its\n// owner, the deposit behind it, the height it was listed at, and its state,\n// which is one of \"listed\", \"challenged\" or \"removed\".\n//\n// A key that was never applied for reads as the zero value with an empty\n// state, which is how a caller tells it from a removed one.\nfunc Get(key string) (url, description string, owner address, deposit, at int64, state string) {\n\te, ok := list.Get(key)\n\tif !ok {\n\t\treturn \"\", \"\", \"\", 0, 0, \"\"\n\t}\n\treturn e.URL, e.Description, e.Owner, e.Deposit, e.At, e.State.String()\n}\n\n// Count is how many entries are on the list right now. A challenged entry\n// counts: a challenge is an objection, not a verdict.\nfunc Count() int { return list.Count() }\n\n// Listed is every key on the list, oldest first.\nfunc Listed() []string {\n\tentries := list.Listed()\n\tout := make([]string, 0, len(entries))\n\tfor _, e := range entries {\n\t\tout = append(out, e.Key)\n\t}\n\treturn out\n}\n\n// IsListed reports whether key is on the list right now.\nfunc IsListed(key string) bool { return list.IsListed(key) }\n\n// ChallengeOf returns the open challenge against key: who opened it, the bond\n// they put up, the height voting closes at, the two vote counts, and whether\n// there is one at all.\nfunc ChallengeOf(key string) (challenger address, bond, deadline, keep, remove int64, open bool) {\n\tc, ok := list.ChallengeOf(key)\n\tif !ok {\n\t\treturn \"\", 0, 0, 0, 0, false\n\t}\n\treturn c.Challenger, c.Bond, c.Deadline, c.Keep, c.Remove, true\n}\n\n// CreditOf is what who can collect with [Withdraw] right now.\nfunc CreditOf(who address) int64 { return list.CreditOf(who) }\n\n// caller is the address that called us, checked the one way that is safe.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"curated_test.gno","body":"package curated\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\n\tcu \"gno.land/p/moul/x/social/curated/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar realmAddr = chain.PackageAddress(realmPath)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\tdave  = testutils.TestAddress(\"dave\")\n)\n\n// reset clears realm state. Realm globals live for the whole test binary, so\n// every entry, challenge and credit a later test reads starts here. The BANK\n// does not carry over the same way, which is why every balance is asserted in\n// the test that issued it.\nfunc reset() {\n\tlist = cu.New(Deposit, ChallengeBlocks)\n}\n\n// pay credits the realm the way a real transaction would: the runtime deposits\n// the envelope at the realm's address, then OriginSend reports it to the\n// crossing function.\nfunc pay(amount int64) {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{Denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{Denom, amount}})\n}\n\n// apply lists an entry as who. It crosses immediately after SetRealm, which is\n// what makes the account switch take: a helper that sets the realm and does\n// not itself cross is silently ignored.\nfunc apply(cur realm, who address, key, url, description string) {\n\tpay(Deposit)\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tApply(cross(cur), key, url, description)\n}\n\n// challenge objects to an entry as who, bonding what that entry's deposit was.\nfunc challenge(cur realm, who address, key string) {\n\t_, _, _, bond, _, _ := Get(key)\n\tpay(bond)\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tChallenge(cross(cur), key)\n}\n\n// balance is what addr holds on chain right now.\nfunc balance(addr address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(addr).AmountOf(Denom)\n}\n\nfunc TestApplyTakesExactlyTheDepositAndListsAtOnce(cur realm, t *testing.T) {\n\treset()\n\n\t// Underpaying and overpaying are both refused: a realm that silently kept\n\t// the excess would have invented a fee nobody agreed to.\n\tpay(Deposit - 1)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"costs exactly\", func() {\n\t\tApply(cross(cur), \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\t})\n\tpay(Deposit + 1)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"costs exactly\", func() {\n\t\tApply(cross(cur), \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\t})\n\tuassert.Equal(t, 0, Count())\n\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io\", \"an AMM on gno.land\")\n\n\turl, description, owner, deposit, at, state := Get(\"gnoswap\")\n\tuassert.Equal(t, \"https://gnoswap.io\", url)\n\tuassert.Equal(t, \"an AMM on gno.land\", description)\n\tuassert.Equal(t, alice.String(), owner.String())\n\tuassert.Equal(t, Deposit, deposit)\n\tuassert.Equal(t, runtime.ChainHeight(), at)\n\tuassert.Equal(t, \"listed\", state)\n\n\tuassert.True(t, IsListed(\"gnoswap\"))\n\tuassert.Equal(t, 1, Count())\n\turequire.Equal(t, 1, len(Listed()))\n\tuassert.Equal(t, \"gnoswap\", Listed()[0])\n\n\t// A key that was never applied for reads as the empty state.\n\t_, _, _, _, _, state = Get(\"nothing\")\n\tuassert.Equal(t, \"\", state)\n\tuassert.False(t, IsListed(\"nothing\"))\n}\n\nfunc TestApplyRefusesAKeyAlreadyOnTheList(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\n\tpay(Deposit)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"already on the list\", func() {\n\t\tApply(cross(cur), \"gnoswap\", \"https://mine.io\", \"mine now\")\n\t})\n\n\tpay(Deposit)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"not a key\", func() {\n\t\tApply(cross(cur), \"GnoSwap\", \"https://mine.io\", \"mine now\")\n\t})\n\tuassert.Equal(t, 1, Count())\n}\n\nfunc TestChallengeMatchesTheDepositAndOpensAVote(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\n\t// Not a bond, not an entry: the entry is checked before the money is.\n\tpay(Deposit)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"is not an entry that can be challenged\", func() {\n\t\tChallenge(cross(cur), \"nothing\")\n\t})\n\n\t// An owner shielding their own entry would cost them nothing.\n\tpay(Deposit)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"cannot challenge their own entry\", func() {\n\t\tChallenge(cross(cur), \"gnoswap\")\n\t})\n\n\topened := runtime.ChainHeight()\n\tchallenge(cur, bob, \"gnoswap\")\n\n\tchallenger, bond, deadline, keep, remove, open := ChallengeOf(\"gnoswap\")\n\turequire.True(t, open, \"the challenge is readable\")\n\tuassert.Equal(t, bob.String(), challenger.String())\n\tuassert.Equal(t, Deposit, bond)\n\tuassert.Equal(t, opened+ChallengeBlocks, deadline)\n\tuassert.Equal(t, int64(0), keep)\n\tuassert.Equal(t, int64(0), remove)\n\tuassert.True(t, IsListed(\"gnoswap\"), \"a challenge is an objection, not a verdict\")\n\n\t// One address, one vote, and only while the window is open.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVote(cross(cur), \"gnoswap\", false)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsContains(t, cur, \"one address, one vote\", func() {\n\t\tVote(cross(cur), \"gnoswap\", true)\n\t})\n\n\ttesting.SkipHeights(ChallengeBlocks)\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tuassert.AbortsContains(t, cur, \"deadline has passed\", func() {\n\t\tVote(cross(cur), \"gnoswap\", true)\n\t})\n}\n\n// The full round, with the coins checked against the chain rather than against\n// the realm's own books.\nfunc TestResolveRemovesAnEntryAndPaysTheChallenger(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\tchallenge(cur, bob, \"gnoswap\")\n\tuassert.Equal(t, 2*Deposit, balance(realmAddr), \"both stakes are at the realm\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVote(cross(cur), \"gnoswap\", false)\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tVote(cross(cur), \"gnoswap\", false)\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsContains(t, cur, \"still open\", func() { Resolve(cross(cur), \"gnoswap\") })\n\n\ttesting.SkipHeights(ChallengeBlocks)\n\t// Anyone may settle it, including somebody with nothing on the outcome.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tResolve(cross(cur), \"gnoswap\")\n\n\tuassert.False(t, IsListed(\"gnoswap\"))\n\tuassert.Equal(t, 0, Count())\n\tuassert.Equal(t, 2*Deposit, CreditOf(bob), \"the bond back, plus alice's deposit\")\n\tuassert.Equal(t, int64(0), CreditOf(alice))\n\tuassert.Equal(t, int64(0), CreditOf(carol), \"voters are paid nothing in v0\")\n\tuassert.Equal(t, 2*Deposit, balance(realmAddr), \"credited is not sent\")\n\n\tbefore := balance(bob)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tgot := Withdraw(cross(cur))\n\tuassert.Equal(t, 2*Deposit, got)\n\tuassert.Equal(t, before+2*Deposit, balance(bob), \"the coins actually arrived\")\n\tuassert.Equal(t, int64(0), balance(realmAddr), \"and the realm kept nothing\")\n\n\t// A second call, which is what a reentrant one would be, finds nothing.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() { Withdraw(cross(cur)) })\n}\n\nfunc TestATieKeepsTheEntryAndPaysTheOwner(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\tchallenge(cur, bob, \"gnoswap\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVote(cross(cur), \"gnoswap\", true)\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tVote(cross(cur), \"gnoswap\", false)\n\n\ttesting.SkipHeights(ChallengeBlocks)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tResolve(cross(cur), \"gnoswap\")\n\n\tuassert.True(t, IsListed(\"gnoswap\"), \"the incumbent wins ties\")\n\tuassert.Equal(t, Deposit, CreditOf(alice), \"and takes the challenger's bond\")\n\tuassert.Equal(t, int64(0), CreditOf(bob))\n\n\t// Her own deposit is still locked behind the entry, so only the bond is\n\t// collectable until she unlists.\n\tbefore := balance(alice)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.Equal(t, Deposit, Withdraw(cross(cur)))\n\tuassert.Equal(t, before+Deposit, balance(alice))\n\tuassert.Equal(t, Deposit, balance(realmAddr), \"the deposit stays behind the entry\")\n}\n\n// Nobody voting is a tie too, which is the common case and the one that\n// decides whether a challenge is cheap. It is not: it costs the bond.\nfunc TestAChallengeNobodyVotedOnLoses(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\tchallenge(cur, bob, \"gnoswap\")\n\n\ttesting.SkipHeights(ChallengeBlocks)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tResolve(cross(cur), \"gnoswap\")\n\n\tuassert.True(t, IsListed(\"gnoswap\"))\n\tuassert.Equal(t, Deposit, CreditOf(alice))\n\tuassert.Equal(t, int64(0), CreditOf(bob), \"being wrong costs the bond\")\n}\n\nfunc TestUnlistIsTheOwnersAndNotWhileChallenged(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io\", \"an AMM\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"only the entry's owner\", func() {\n\t\tUnlist(cross(cur), \"gnoswap\")\n\t})\n\n\tchallenge(cur, bob, \"gnoswap\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"under challenge\", func() {\n\t\tUnlist(cross(cur), \"gnoswap\")\n\t})\n\tuassert.Equal(t, int64(0), CreditOf(alice), \"she cannot walk away mid-challenge\")\n\n\ttesting.SkipHeights(ChallengeBlocks)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tResolve(cross(cur), \"gnoswap\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tUnlist(cross(cur), \"gnoswap\")\n\n\tuassert.False(t, IsListed(\"gnoswap\"))\n\tuassert.Equal(t, 2*Deposit, CreditOf(alice), \"the bond she won, and her deposit back\")\n\n\t// The key is free again, and re-listing it costs a fresh deposit.\n\tapply(cur, bob, \"gnoswap\", \"https://mine.io\", \"mine now\")\n\t_, _, owner, _, _, state := Get(\"gnoswap\")\n\tuassert.Equal(t, bob.String(), owner.String())\n\tuassert.Equal(t, \"listed\", state)\n}\n\n// The realm holds exactly what it is accountable for, at every step: a stake\n// behind something live, or a credit somebody has not collected yet.\nfunc TestTheRealmHoldsExactlyWhatItOwes(cur realm, t *testing.T) {\n\treset()\n\tcheck := func(step string) {\n\t\tt.Helper()\n\t\tuassert.Equal(t, list.Locked()+list.Owed(), balance(realmAddr), step)\n\t}\n\tcheck(\"empty\")\n\n\tapply(cur, alice, \"one\", \"https://1.io\", \"first\")\n\tcheck(\"after a listing\")\n\n\tapply(cur, bob, \"two\", \"https://2.io\", \"second\")\n\tcheck(\"after a second listing\")\n\n\tchallenge(cur, bob, \"one\")\n\tcheck(\"after a challenge\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVote(cross(cur), \"one\", false)\n\tcheck(\"after a vote\")\n\n\ttesting.SkipHeights(ChallengeBlocks)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tResolve(cross(cur), \"one\")\n\tcheck(\"after a resolution\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tWithdraw(cross(cur))\n\tcheck(\"after the winner collected\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tUnlist(cross(cur), \"two\")\n\tcheck(\"after an unlisting\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tWithdraw(cross(cur))\n\tcheck(\"after the deposit came back\")\n\tuassert.Equal(t, int64(0), balance(realmAddr), \"and the realm is empty again\")\n}\n\n// A URL is caller-supplied too, and it is the one string that reaches the\n// renderer as a link target rather than as text.\nfunc TestAPipeInAUrlCannotOpenAColumn(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"weird\", \"https://x.io/a|b\", \"a url with a pipe in it\")\n\n\tindex := Render(\"\")\n\tuassert.False(t, strings.Contains(index, \"https://x.io/a|b\"),\n\t\t\"the raw pipe would open a column: \"+index)\n\tuassert.True(t, strings.Contains(index, \"https://x.io/a%7Cb\"),\n\t\t\"the link sanitizer percent-encodes it: \"+index)\n}\n\n// TestRender uses uassert rather than an Example because every view contains\n// consecutive blank lines, which gno collapses inside an // Output: block.\nfunc TestRender(cur realm, t *testing.T) {\n\treset()\n\tapply(cur, alice, \"gnoswap\", \"https://gnoswap.io/pools?a=1\", \"an AMM | with [a link](x)\")\n\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"# Curated\"), index)\n\tuassert.True(t, strings.Contains(index, \"| 1 | 0 |\"), \"one listed, none challenged: \"+index)\n\tuassert.True(t, strings.Contains(index, \"func=Apply\"), \"the index offers the transaction\")\n\tuassert.True(t, strings.Contains(index, \"Voters are paid nothing\"), \"the index says what v0 does not do\")\n\tuassert.True(t, strings.Contains(index, \"an AMM \\\\| with \\\\[a link\\\\]\\\\(x\\\\)\"),\n\t\t\"a pipe in a description cannot open a column, and its markdown is inert: \"+index)\n\n\tentry := Render(\"entry/gnoswap\")\n\tuassert.True(t, strings.Contains(entry, \"# gnoswap\"), entry)\n\tuassert.True(t, strings.Contains(entry, \"an AMM | with \\\\[a link\\\\]\\\\(x\\\\)\"),\n\t\t\"the description is escaped in prose too, where a pipe is not special: \"+entry)\n\tuassert.True(t, strings.Contains(entry, \"func=Challenge\"))\n\tuassert.True(t, strings.Contains(entry, \"func=Unlist\"))\n\n\t// Under challenge the page offers the two votes instead.\n\tchallenge(cur, bob, \"gnoswap\")\n\tentry = Render(\"entry/gnoswap\")\n\tuassert.True(t, strings.Contains(entry, \"## Under challenge\"), entry)\n\tuassert.True(t, strings.Contains(entry, \"keep=true\"), entry)\n\tuassert.True(t, strings.Contains(entry, \"keep=false\"), entry)\n\tuassert.False(t, strings.Contains(entry, \"func=Unlist\"), \"an owner cannot walk away here either\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"## Open challenges\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVote(cross(cur), \"gnoswap\", false)\n\ttesting.SetRealm(testing.NewUserRealm(dave))\n\tVote(cross(cur), \"gnoswap\", false)\n\n\t// Past the deadline it offers the settlement instead of the votes.\n\ttesting.SkipHeights(ChallengeBlocks)\n\tentry = Render(\"entry/gnoswap\")\n\tuassert.True(t, strings.Contains(entry, \"func=Resolve\"), entry)\n\tuassert.False(t, strings.Contains(entry, \"keep=true\"), \"voting is over: \"+entry)\n\n\t// Removed, the key is advertised as free again.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tResolve(cross(cur), \"gnoswap\")\n\n\tentry = Render(\"entry/gnoswap\")\n\tuassert.True(t, strings.Contains(entry, \"free to apply for again\"), entry)\n\tuassert.True(t, strings.Contains(Render(\"\"), \"Nothing is on the list yet.\"))\n\n\tuassert.Equal(t, \"# Curated\\nNo entry named nope\", Render(\"entry/nope\"))\n\tuassert.True(t, strings.HasPrefix(Render(\"elsewhere\"), \"# Not found\"))\n}\n\n// A realm that forwards a user's call must not be able to spend the user's\n// envelope as if it were its own. OriginSend reports what the SIGNER attached\n// to the transaction, so without the IsUserCall guard a realm that received\n// one GNOT could call in here repeatedly, each call reading the same send and\n// listing another entry for free. That is r/moul/grant Fund, and gnovet's\n// origin-send-unguarded rule caught this exact shape here in CI after the\n// local gate had passed.\nfunc TestOnlyAUserCanPayIn(cur realm, t *testing.T) {\n\treset()\n\n\tpay(Deposit)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/g1relay/forwarder\"))\n\tuassert.AbortsContains(t, cur, \"must be a direct user transaction\", func() {\n\t\tApply(cross(cur), \"relayed\", \"/r/x\", \"paid with somebody else's coins\")\n\t})\n\tuassert.Equal(t, 0, Count(), \"nothing was listed\")\n\n\tapply(cur, alice, \"real\", \"/r/real\", \"a real entry\")\n\n\tpay(Deposit)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/g1relay/forwarder\"))\n\tuassert.AbortsContains(t, cur, \"must be a direct user transaction\", func() {\n\t\tChallenge(cross(cur), \"real\")\n\t})\n\t_, _, _, _, _, open := ChallengeOf(\"real\")\n\tuassert.False(t, open, \"no challenge was opened\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/social/curated/v0\"\ngno = \"0.9\"\nprivate = true\n\n# private: nothing imports this realm. It is an application, not a library: the\n# engine every other realm would want is the p/ package, and the list itself is\n# read through Render or through the plain reads below, neither of which needs\n# an import.\n#\n# The price is the one private always charges, and it is sharper here than\n# usual because this realm holds coins: a redeploy keeps the balance at the\n# realm address and wipes every package-level variable, so the entries, the\n# challenges and the credit ledger would all go while the money they account\n# for stayed. A redeploy of a live list is therefore a migration and not a fix,\n# and anything beyond a patch ships as a v1 beside it.\n"},{"name":"render.gno","body":"package curated\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\tcu \"gno.land/p/moul/x/social/curated/v0\"\n)\n\n// Render routes two views: the list itself, and one entry.\n//\n// A key never contains a slash, so \"entry/\u003ckey\u003e\" is a prefix strip rather than\n// a path element that would have to be rejoined.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tswitch {\n\tcase strings.HasPrefix(req.Path, \"entry/\"):\n\t\treturn renderEntry(strings.TrimPrefix(req.Path, \"entry/\"))\n\tcase req.Path == \"\":\n\t\treturn renderIndex()\n\tdefault:\n\t\treturn md.H1(\"Not found\") + \"No such view: \" + ui.Inline(req.Path)\n\t}\n}\n\nfunc renderIndex() string {\n\tout := md.H1(\"Curated\")\n\tout += \"A list you pay to be on, and can be paid for getting somebody off. \" +\n\t\t\"The deposit does not make an entry good: it makes a bad one expensive \" +\n\t\t\"to leave standing, because anybody who disagrees can put the same \" +\n\t\t\"amount at risk and take it.\\n\\n\"\n\n\topen := list.Challenged()\n\n\tt := ui.NewTable(\"on the list\", \"open challenges\", \"deposit\", \"window\", \"locked\", \"credited\")\n\tt.Row(\n\t\tstrconv.Itoa(list.Count()),\n\t\tstrconv.Itoa(len(open)),\n\t\tnum.GNOTf(Deposit),\n\t\tstrconv.FormatInt(ChallengeBlocks, 10)+\" blocks\",\n\t\tnum.GNOTf(list.Locked()),\n\t\tnum.GNOTf(list.Owed()),\n\t)\n\tout += t.String()\n\n\tout += md.H2(\"The list\")\n\tout += listing(list.Listed())\n\tout += \"\\n\" + md.Link(\"➕ Apply for \"+num.GNOTf(Deposit), applyURL()) + \"\\n\"\n\n\tif len(open) \u003e 0 {\n\t\tout += md.H2(\"Open challenges\")\n\t\tout += challengeTable(open)\n\t}\n\n\tout += md.H2(\"How it works\")\n\tout += md.BulletList([]string{\n\t\t\"**Apply** locks \" + num.GNOTf(Deposit) + \" and lists the entry immediately. \" +\n\t\t\t\"There is no application period in v0.\",\n\t\t\"**Challenge** matches that entry's deposit with a bond and opens a vote \" +\n\t\t\t\"for \" + strconv.FormatInt(ChallengeBlocks, 10) + \" blocks. An owner cannot challenge their own entry.\",\n\t\t\"**Vote** is one address, one vote, unweighted. An address is free, so read \" +\n\t\t\t\"a resolution as nobody with a stake objecting, never as a verdict.\",\n\t\t\"**Resolve** can be called by anyone once the window closes. A majority to \" +\n\t\t\t\"keep credits the owner the bond; otherwise the challenger takes the bond \" +\n\t\t\t\"and the deposit. A tie keeps the entry, so a challenge that convinced \" +\n\t\t\t\"nobody loses its bond.\",\n\t\t\"**Voters are paid nothing** in v0, which is the first thing to fix: the only \" +\n\t\t\t\"two addresses with a reason to vote are the ones with money on the outcome.\",\n\t\t\"**Nothing is ever sent to you.** Every payout is a credit, and \" +\n\t\t\tmd.InlineCode(\"Withdraw()\") + \" collects it.\",\n\t})\n\n\treturn out\n}\n\nfunc renderEntry(key string) string {\n\te, ok := list.Get(key)\n\tif !ok {\n\t\treturn md.H1(\"Curated\") + \"No entry named \" + ui.Inline(key)\n\t}\n\n\tout := md.H1(ui.Inline(e.Key))\n\tout += md.Blockquote(ui.Inline(e.Description)) + \"\\n\"\n\t// ShortN truncates without escaping and md.Link escapes what it is given:\n\t// ui.Inline here would escape twice and render the backslashes.\n\tout += md.Link(ui.ShortN(e.URL, 60, 0), e.URL) + \"\\n\\n\"\n\n\tt := ui.NewTable(\"owner\", \"deposit\", \"listed at\", \"state\")\n\tt.Row(\n\t\tui.Addr(e.Owner),\n\t\tnum.GNOTf(e.Deposit),\n\t\t\"block \"+strconv.FormatInt(e.At, 10),\n\t\te.State.String(),\n\t)\n\tout += t.String()\n\n\tc, challenged := list.ChallengeOf(e.Key)\n\tswitch {\n\tcase challenged:\n\t\tout += md.H2(\"Under challenge\")\n\t\tout += challengeTable([]*cu.Entry{e})\n\t\tif c.Open(runtime.ChainHeight()) {\n\t\t\tout += \"\\n\" + ui.Action(\"👍 Keep\", \"Vote\", \"key\", e.Key, \"keep\", \"true\") +\n\t\t\t\t\" · \" + ui.Action(\"👎 Remove\", \"Vote\", \"key\", e.Key, \"keep\", \"false\") + \"\\n\"\n\t\t} else {\n\t\t\tout += \"\\n\" + ui.Action(\"⚖️ Resolve\", \"Resolve\", \"key\", e.Key) +\n\t\t\t\t\" · the window has closed and anyone can settle it\\n\"\n\t\t}\n\tcase e.Live():\n\t\tout += \"\\n\" + md.Link(\"🚩 Challenge for \"+num.GNOTf(e.Deposit), challengeURL(e.Key, e.Deposit)) +\n\t\t\t\" · \" + ui.Action(\"🗑 Unlist\", \"Unlist\", \"key\", e.Key) + \"\\n\"\n\tdefault:\n\t\tout += \"\\n\" + ui.Empty(\"Off the list. The key is free to apply for again.\")\n\t\tout += md.Link(\"➕ Apply for \"+num.GNOTf(Deposit), applyURL()) + \"\\n\"\n\t}\n\n\treturn out\n}\n\n// listing renders the entries as the list itself: the key links to its page,\n// the description links to the thing it describes.\nfunc listing(entries []*cu.Entry) string {\n\tif len(entries) == 0 {\n\t\treturn ui.Empty(\"Nothing is on the list yet.\")\n\t}\n\tt := ui.NewTable(\"key\", \"what\", \"link\", \"owner\", \"since\", \"state\")\n\tfor _, e := range entries {\n\t\tmark := \"\"\n\t\tif e.State == cu.StateChallenged {\n\t\t\tmark = \" 🚩\"\n\t\t}\n\t\tt.Row(\n\t\t\t// A key is charset-validated, so md.Link's escaping is the whole\n\t\t\t// story for it. A description is not: md.Link escapes markdown\n\t\t\t// but NOT the pipe, which in a cell would open a column, so the\n\t\t\t// description is never a link title here. Cut first with ShortN,\n\t\t\t// which does not escape, then escape once with ui.Cell.\n\t\t\tmd.Link(ui.ShortN(e.Key, 32, 0), entryURL(e.Key)),\n\t\t\tui.Cell(ui.ShortN(e.Description, 48, 0)),\n\t\t\tmd.Link(\"↗\", e.URL),\n\t\t\tui.Addr(e.Owner),\n\t\t\t\"block \"+strconv.FormatInt(e.At, 10),\n\t\t\te.State.String()+mark,\n\t\t)\n\t}\n\treturn t.String()\n}\n\n// challengeTable renders the open challenge against each of entries. An entry\n// with none is skipped rather than shown blank.\nfunc challengeTable(entries []*cu.Entry) string {\n\tt := ui.NewTable(\"entry\", \"challenger\", \"bond\", \"keep\", \"remove\", \"voting closes\")\n\tnow := runtime.ChainHeight()\n\tfor _, e := range entries {\n\t\tc, ok := list.ChallengeOf(e.Key)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tcloses := \"block \" + strconv.FormatInt(c.Deadline, 10)\n\t\tif !c.Open(now) {\n\t\t\tcloses = \"closed, awaiting `Resolve`\"\n\t\t}\n\t\tt.Row(\n\t\t\tmd.Link(ui.ShortN(e.Key, 32, 0), entryURL(e.Key)),\n\t\t\tui.Addr(c.Challenger),\n\t\t\tnum.GNOTf(c.Bond),\n\t\t\tstrconv.FormatInt(c.Keep, 10),\n\t\t\tstrconv.FormatInt(c.Remove, 10),\n\t\t\tcloses,\n\t\t)\n\t}\n\treturn t.OrEmpty(\"No challenge is open.\")\n}\n\n// entryURL is the gnoweb path of one entry's page.\n//\n// The chain domain is the first element of a package path and a gnoweb path is\n// the rest of it, so this is a prefix strip and not a hostname to hardcode.\nfunc entryURL(key string) string {\n\tpath := realmPath\n\tif i := strings.Index(path, \"/\"); i \u003e= 0 {\n\t\tpath = path[i:]\n\t}\n\treturn path + \":entry/\" + key\n}\n\n// applyURL is the Apply form with the deposit already attached, so a reader\n// never has to work out what -send should say.\nfunc applyURL() string {\n\treturn txlink.NewLink(\"Apply\").SetSend(send(Deposit)).URL()\n}\n\n// challengeURL is the same for Challenge, carrying that entry's own bond.\nfunc challengeURL(key string, bond int64) string {\n\treturn txlink.NewLink(\"Challenge\").AddArgs(\"key\", key).SetSend(send(bond)).URL()\n}\n\nfunc send(amount int64) string { return strconv.FormatInt(amount, 10) + Denom }\n"}]},"send":"","max_deposit":"17000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"patron","path":"gno.land/r/moul/x/social/patron/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/social/patron/v0`\n\n**Recurring support for a builder, on chain.** A creator opens a plan with a\nprice per period and a period measured in blocks; a supporter attaches ugnot to\n`Subscribe` and buys whole periods of it; anyone can ask at any height whether\na given address is still active.\n\n```\nOpen(title, description, pricePerPeriod, periodBlocks) -\u003e planID\nSubscribe(planID)            payable, returns the new paid-through height\nClose(planID) / Reopen(planID)   creator only\nWithdraw()                   earnings and change leave the same way\nIsActive(planID, who)        the one question a tip jar cannot answer\n```\n\n**There is no cron on chain, so a renewal is a pull and not a push.** Nothing\nhere can charge anybody: a renewal happens because the supporter sends another\npayment, never because a timer fired, and a native coin cannot be pulled at\nall. A reader arriving from web2 expects a standing mandate on a card; there is\nnothing of the kind anywhere on this chain, and that is the single most\nimportant sentence on this page.\n\n`r/moul/x/daily/tipjar` is the one-shot version and is already live. The\nrecurrence is the whole difference, and it makes this the one app in the\n`x/social` family that produces a recurring write rather than a one-off.\n\n**Renewing early never discards time already paid for**: an extension runs from\nwhichever is later, now or the current paid-through. Renewing after lapsing runs\nfrom now. A payment short of one period is refused rather than partially\ncredited, and the remainder under a whole period is **credited back to the\nsupporter**, because keeping it would be a silent fee and a subscription realm\nis exactly where a silent fee must not be.\n\n**Earnings are credited at payment time, not streamed.** The creator can\nwithdraw the full price the instant it is paid, and a supporter who stops being\nactive is not refunded. That is a deliberate v0 limitation: escrowed streaming,\nwhere the creator claims only what has elapsed and the supporter reclaims the\nrest, needs a claim schedule and a refund path, which is a larger realm rather\nthan a flag on this one.\n\nBoth halves of what the realm owes, a creator's earnings and a supporter's\nchange, land in one credit ledger and leave through `Withdraw`, which zeroes the\ncredit before any coin moves. `EarnedBy` and `CreditOf` are deliberately\ndifferent numbers: lifetime credited against withdrawable now.\n\n`Subscribe` is payable and therefore has to be called **directly by a user**. A\nrealm called by another realm cannot forward the envelope and `maketx run`\ncannot reach a payable function at all, so there is no path where another\ncontract subscribes on somebody's behalf.\n\n## The token question\n\n**v0 ships none, and the condition for yes is written down** in\n[the engine's README](https://github.com/moul/gno-contracts/tree/main/p/moul/x/social/patron):\na creator coin is easy to mint and has no sink, because what a supporter would\nredeem it for is a promise made off chain. What would change the answer is a\nredeem the chain can enforce. The slot it would drop into is\n[`p/moul/x/social/coin`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/social/coin),\na GRC20 that refuses to exist until its mint rule, its sink and its buyer are\ndeclared.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/social/patron/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/patron/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/social/patron/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/patron/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/social/patron/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/patron/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/social/patron/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/patron/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/social/patron/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/social/patron/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/social/patron/v0\"\ngno = \"0.9\"\nprivate = true\n"},{"name":"patron.gno","body":"// Package patron is recurring support for a builder, on chain.\n//\n// A creator opens a plan with a price per period and a period measured in\n// blocks. A supporter attaches ugnot to [Subscribe] and buys whole periods of\n// it. Anybody can ask at any height whether a given address is still active,\n// which is the one question a tip cannot answer.\n//\n// # There is no cron on chain, so a renewal is a pull and not a push\n//\n// Nothing in this realm can charge anybody. A renewal happens because the\n// supporter sends another payment, never because a timer fired: there is no\n// scheduler here, and there is no way to write one, since a native coin\n// cannot be pulled at all. A reader arriving from web2 expects a standing\n// mandate on a card and there is nothing of the kind, anywhere on this chain.\n//\n// # What this adds over the tip jar\n//\n// gno.land/r/moul/x/daily/tipjar is the one-shot version and is already live:\n// one payment, a leaderboard, and then nothing. The recurrence is the whole\n// difference. A plan has a price and a period, a payment buys whole periods\n// of it, renewing early never discards time already paid for, and the realm\n// answers \"is this address active right now\" at any height. It is the one app\n// in the x/social family that produces a recurring write rather than a\n// one-off.\n//\n// # Earnings are credited at payment time, not streamed\n//\n// The creator can withdraw the full price the instant it is paid. A supporter\n// who stops being active is NOT refunded, and no part of a paid period ever\n// comes back. That is a deliberate v0 limitation: escrowed streaming, where\n// the creator claims only what has elapsed and the supporter cancels and\n// reclaims the rest, needs a claim schedule and a refund path, and that is a\n// larger realm than this one rather than a flag on it.\n//\n// # Money leaves by pull\n//\n// Both halves of what this realm owes, a creator's earnings and a supporter's\n// change, land in one credit ledger and leave through [Withdraw]. The credit\n// is zeroed before any coin moves, and the realm never loops over payees: one\n// unpayable address would otherwise fail the whole batch and hand a griefer a\n// cheap denial of service.\n//\n// # v0 ships no token\n//\n// Deliberately, and the README says why: a creator coin minted per period\n// paid is easy, and the sink is not, because what it would be redeemed for is\n// a promise made off chain.\npackage patron\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"strconv\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/x/envelope/v0\"\n\tpt \"gno.land/p/moul/x/social/patron/v0\"\n)\n\n// realmPath is this realm's own path, the one its gnomod.toml module line\n// declares. It is written out rather than read from the frame, because a\n// plain read exported by a realm reports the CALLER and would build every\n// link against whoever asked.\nconst realmPath = \"gno.land/r/moul/x/social/patron/v0\"\n\n// denom is the only coin this realm handles.\nconst denom = \"ugnot\"\n\n// plans holds every plan and the credit ledger. A redeploy wipes it, which is\n// the trade `private = true` makes: see gnomod.toml.\nvar plans = pt.NewRegistry()\n\n// Open creates a plan and returns its id. Anyone may open one, and opening\n// one costs nothing beyond gas and the storage deposit.\n//\n// pricePerPeriod is in ugnot and must be at least one: a free plan is a tip\n// jar, not a subscription. periodBlocks is a period in BLOCKS, bounded both\n// ways by the engine, because height is the clock consensus agrees on and a\n// block timestamp is not something to build a billing cliff out of.\nfunc Open(cur realm, title, description string, pricePerPeriod, periodBlocks int64) int64 {\n\twho := caller(cur)\n\tid, err := plans.Open(who, title, description, pricePerPeriod, periodBlocks)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Open\",\n\t\t\"id\", id.String(),\n\t\t\"creator\", who.String(),\n\t\t\"price\", strconv.FormatInt(pricePerPeriod, 10),\n\t\t\"period\", strconv.FormatInt(periodBlocks, 10))\n\treturn int64(id)\n}\n\n// Subscribe buys whole periods on a plan with the ugnot attached to the call,\n// and returns the caller's new paid-through height.\n//\n// Attach the coins with -send: a payment short of one period is refused, and\n// the remainder under one period is credited back to the caller rather than\n// kept, so an overpayment is change and never a silent fee. Take it back with\n// [Withdraw].\n//\n// # It has to be called directly by a user, and that is not a style choice\n//\n// The envelope is what the SIGNER attached to the transaction. A realm the\n// user called has already received those coins itself, and could then call in\n// here as many times as it liked against one payment, so the caller is\n// checked before the envelope is read. The same property means a realm cannot\n// forward an envelope it was handed (`NewBanker` requires the previous frame\n// to be a user call), and that `maketx run` cannot reach this function at all,\n// because a run script is itself a code realm. Use `maketx call -send`.\nfunc Subscribe(cur realm, planID int64) int64 {\n\t// The frame is read here rather than through caller(), because this\n\t// function asks the previous frame two questions and the order of them is\n\t// the whole guard: is the token live, is the caller a user, and only then\n\t// what did they send.\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tprev := cur.Previous()\n\tif !prev.IsUserCall() {\n\t\tpanic(\"patron: Subscribe must be called directly by a user with maketx call -send, \" +\n\t\t\t\"not through another realm and not from maketx run\")\n\t}\n\twho := prev.Address()\n\n\tid := store.ID(planID)\n\tp := mustGet(id)\n\tif !p.Open {\n\t\tpanic(pt.ErrPlanClosed.Error())\n\t}\n\n\t// RequireAtLeast names both numbers when the envelope falls short, which\n\t// is the difference between a caller fixing their command and a caller\n\t// opening their wallet.\n\tsent := envelope.RequireAtLeast(denom, p.PricePerPeriod)\n\n\tpay, err := plans.Subscribe(id, who, sent, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Subscribe\",\n\t\t\"id\", id.String(),\n\t\t\"supporter\", who.String(),\n\t\t\"periods\", strconv.FormatInt(pay.Periods, 10),\n\t\t\"spent\", strconv.FormatInt(pay.Spent, 10),\n\t\t\"change\", strconv.FormatInt(pay.Change, 10),\n\t\t\"paidThrough\", strconv.FormatInt(pay.PaidThrough, 10))\n\treturn pay.PaidThrough\n}\n\n// Close stops a plan taking new subscriptions. Creator only.\n//\n// Everything already paid for runs to its own paid-through height. Closing a\n// plan is not a way to take a period back.\nfunc Close(cur realm, planID int64) {\n\twho := caller(cur)\n\tid := store.ID(planID)\n\tif err := plans.Close(id, who); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Close\", \"id\", id.String(), \"by\", who.String())\n}\n\n// Reopen lets a closed plan take subscriptions again. Creator only.\nfunc Reopen(cur realm, planID int64) {\n\twho := caller(cur)\n\tid := store.ID(planID)\n\tif err := plans.Reopen(id, who); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Reopen\", \"id\", id.String(), \"by\", who.String())\n}\n\n// Withdraw pays the caller everything this realm owes them and returns the\n// amount: a creator's earnings, a supporter's change, or both at once.\n//\n// The credit is zeroed by the engine before a coin moves, so a recipient that\n// calls straight back in finds nothing left to take.\nfunc Withdraw(cur realm) int64 {\n\twho := caller(cur)\n\tamount, err := plans.Withdraw(who)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(\n\t\tcur.Address(), who, chain.NewCoins(chain.NewCoin(denom, amount)))\n\tchain.Emit(\"Withdraw\", \"to\", who.String(), \"amount\", strconv.FormatInt(amount, 10))\n\treturn amount\n}\n\n// Get returns a plan's fields.\n//\n// It returns a tuple rather than the stored record: handing out a pointer to\n// realm state is a live mutation handle, and this realm is private, so an\n// importer retaining one of its objects would be a runtime panic rather than\n// a design debate.\nfunc Get(planID int64) (creator address, title, description string, pricePerPeriod, periodBlocks int64, open bool) {\n\tp := mustGet(store.ID(planID))\n\treturn p.Creator, p.Title, p.Description, p.PricePerPeriod, p.PeriodBlocks, p.Open\n}\n\n// Count is how many plans exist.\nfunc Count() int { return plans.Count() }\n\n// IsActive reports whether who is paid up on this plan at the current height.\n//\n// Active means now \u003c paidThrough, strictly: an address paid through height h\n// is active at h-1 and not at h.\nfunc IsActive(planID int64, who address) bool {\n\treturn mustGet(store.ID(planID)).IsActive(who, runtime.ChainHeight())\n}\n\n// PaidThrough is the height who stops being active at on this plan, or zero\n// if they never paid.\nfunc PaidThrough(planID int64, who address) int64 {\n\treturn mustGet(store.ID(planID)).PaidThrough(who)\n}\n\n// SupporterCount is how many distinct addresses have ever paid this plan,\n// active or not.\nfunc SupporterCount(planID int64) int {\n\treturn mustGet(store.ID(planID)).SupporterCount()\n}\n\n// Supporters is every address that has ever paid this plan, in first-payment\n// order. It is a copy, not the stored slice.\nfunc Supporters(planID int64) []address {\n\treturn mustGet(store.ID(planID)).Supporters()\n}\n\n// EarnedBy is the lifetime ugnot credited to creator across every plan,\n// whether or not it has been withdrawn.\nfunc EarnedBy(creator address) int64 { return plans.EarnedBy(creator) }\n\n// CreditOf is what addr can withdraw right now.\nfunc CreditOf(addr address) int64 { return plans.CreditOf(addr) }\n\n// TotalOwed is everything this realm owes, which is what it must keep in\n// reserve at its own address.\nfunc TotalOwed() int64 { return plans.TotalOwed() }\n\n// mustGet reads a plan or aborts naming it.\nfunc mustGet(id store.ID) *pt.Plan {\n\tp, ok := plans.Get(id)\n\tif !ok {\n\t\tpanic(\"patron: plan #\" + id.String() + \" not found\")\n\t}\n\treturn p\n}\n\n// caller is the address that called us, checked the one way that is safe.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"patron_test.gno","body":"package patron\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\n\tpt \"gno.land/p/moul/x/social/patron/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\tprice  = int64(1000000) // 1 GNOT per period\n\tperiod = int64(100)     // blocks\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\") // the creator, throughout\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\n\trealmAddr = chain.PackageAddress(realmPath)\n)\n\n// reset clears realm state. Realm globals live for the whole test binary, so\n// everything a later test or the Render tests read starts here.\nfunc reset() { plans = pt.NewRegistry() }\n\n// pay stages a payment the way the chain does: the coins land at the realm's\n// address before a line of its code runs, and OriginSend is what the crossing\n// function then reads.\nfunc pay(amount int64) {\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{denom, amount}})\n}\n\n// open creates a plan as alice. SetRealm is call-frame scoped, so the account\n// is switched here and then crossed from here, never from a helper that does\n// not itself cross.\nfunc open(cur realm, t *testing.T) int64 {\n\tt.Helper()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\treturn Open(cross(cur), \"monthly support\", \"a plan with a | pipe in it\", price, period)\n}\n\nfunc TestOpenStoresWhatItWasGiven(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tcreator, title, desc, p, blocks, isOpen := Get(id)\n\tuassert.Equal(t, alice.String(), creator.String())\n\tuassert.Equal(t, \"monthly support\", title)\n\tuassert.Equal(t, \"a plan with a | pipe in it\", desc)\n\tuassert.Equal(t, price, p)\n\tuassert.Equal(t, period, blocks)\n\tuassert.True(t, isOpen)\n\tuassert.Equal(t, 1, Count())\n\tuassert.Equal(t, 0, SupporterCount(id))\n}\n\nfunc TestOpenRefusesAFreePlanAndASillyPeriod(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"at least one ugnot per period\", func() {\n\t\tOpen(cross(cur), \"free\", \"\", 0, period)\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"period out of range\", func() {\n\t\tOpen(cross(cur), \"instant\", \"\", price, 0)\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"period out of range\", func() {\n\t\tOpen(cross(cur), \"forever\", \"\", price, pt.MaxPeriodBlocks+1)\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"title is empty\", func() {\n\t\tOpen(cross(cur), \"   \", \"\", price, period)\n\t})\n\tuassert.Equal(t, 0, Count())\n}\n\n// One period, paid exactly, credited to the creator at payment time and\n// withdrawable as real coins in this same test, because the bank does not\n// carry over between test functions.\nfunc TestOnePeriodIsBoughtAndTheCreatorIsPaid(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\tstart := runtime.ChainHeight()\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tthrough := Subscribe(cross(cur), id)\n\n\tuassert.Equal(t, start+period, through)\n\tuassert.Equal(t, start+period, PaidThrough(id, bob))\n\tuassert.True(t, IsActive(id, bob))\n\tuassert.Equal(t, 1, SupporterCount(id))\n\tuassert.Equal(t, price, EarnedBy(alice))\n\tuassert.Equal(t, price, CreditOf(alice))\n\tuassert.Equal(t, int64(0), CreditOf(bob), \"an exact payment leaves no change\")\n\tuassert.Equal(t, price, TotalOwed())\n\n\tro := banker.NewReadonlyBanker()\n\tbefore := ro.GetCoin(alice, denom)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tgot := Withdraw(cross(cur))\n\n\tuassert.Equal(t, price, got)\n\tuassert.Equal(t, price, ro.GetCoin(alice, denom)-before, \"the creator was really paid\")\n\tuassert.Equal(t, int64(0), CreditOf(alice))\n\tuassert.Equal(t, price, EarnedBy(alice), \"earnings outlive the withdrawal\")\n\tuassert.Equal(t, int64(0), TotalOwed())\n}\n\nfunc TestThreePeriodsAtOnce(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\tstart := runtime.ChainHeight()\n\n\tpay(3 * price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tthrough := Subscribe(cross(cur), id)\n\n\tuassert.Equal(t, start+3*period, through)\n\tuassert.Equal(t, 3*price, CreditOf(alice))\n\tuassert.Equal(t, int64(0), CreditOf(bob))\n}\n\n// Renewing before the lapse extends from paidThrough, so the time already\n// paid for is still there afterwards.\nfunc TestRenewingEarlyExtendsRatherThanRestarts(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfirst := Subscribe(cross(cur), id)\n\n\t// Ten blocks in, with ninety still paid for.\n\ttesting.SkipHeights(10)\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tsecond := Subscribe(cross(cur), id)\n\n\tuassert.Equal(t, first+period, second, \"the second period starts where the first ended\")\n\tuassert.True(t, second \u003e runtime.ChainHeight()+period,\n\t\t\"more than one period is left, which is the point\")\n\tuassert.Equal(t, 1, SupporterCount(id), \"renewing is not a second supporter\")\n}\n\n// Renewing after a lapse starts from now: the gap was never paid for.\nfunc TestRenewingAfterALapseStartsFromNow(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSubscribe(cross(cur), id)\n\n\ttesting.SkipHeights(500)\n\tuassert.False(t, IsActive(id, bob), \"the first period lapsed long ago\")\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tsecond := Subscribe(cross(cur), id)\n\n\tuassert.Equal(t, runtime.ChainHeight()+period, second)\n\tuassert.True(t, IsActive(id, bob))\n}\n\n// IsActive flips at the block the period ends on, and not a block either side.\nfunc TestIsActiveFlipsAtTheRightHeight(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\tstart := runtime.ChainHeight()\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSubscribe(cross(cur), id)\n\n\ttesting.SetHeight(start + period - 1)\n\tuassert.True(t, IsActive(id, bob), \"the last block of the period\")\n\n\ttesting.SetHeight(start + period)\n\tuassert.False(t, IsActive(id, bob), \"the first block after it\")\n\n\tuassert.False(t, IsActive(id, carol), \"an address that never paid is never active\")\n\tuassert.Equal(t, int64(0), PaidThrough(id, carol))\n}\n\nfunc TestAPaymentShortOfOnePeriodIsRefused(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tpay(price - 1)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"this call costs at least\", func() {\n\t\tSubscribe(cross(cur), id)\n\t})\n\n\tuassert.Equal(t, int64(0), PaidThrough(id, bob))\n\tuassert.Equal(t, int64(0), EarnedBy(alice))\n\tuassert.Equal(t, 0, SupporterCount(id))\n}\n\n// The remainder under one period is the supporter's, not the realm's, and it\n// comes back out as real coins.\nfunc TestChangeIsCreditedBackAndWithdrawable(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tpay(2*price + 250000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSubscribe(cross(cur), id)\n\n\tuassert.Equal(t, int64(250000), CreditOf(bob), \"the change is the supporter's\")\n\tuassert.Equal(t, 2*price, CreditOf(alice))\n\tuassert.Equal(t, 2*price+250000, TotalOwed(), \"every ugnot in is owed to somebody\")\n\n\tro := banker.NewReadonlyBanker()\n\tbefore := ro.GetCoin(bob, denom)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tgot := Withdraw(cross(cur))\n\n\tuassert.Equal(t, int64(250000), got)\n\tuassert.Equal(t, int64(250000), ro.GetCoin(bob, denom)-before)\n\tuassert.Equal(t, int64(0), CreditOf(bob))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() { Withdraw(cross(cur)) })\n}\n\nfunc TestWithdrawRefusesSomebodyOwedNothing(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() { Withdraw(cross(cur)) })\n}\n\n// A realm that the user called holds the coins itself and could subscribe\n// over and over against one payment. The guard runs before the envelope is\n// read, so it cannot.\nfunc TestOnlyAUserCanSubscribe(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/g1relay/forwarder\"))\n\tuassert.AbortsContains(t, cur, \"must be called directly by a user\", func() {\n\t\tSubscribe(cross(cur), id)\n\t})\n\tuassert.Equal(t, int64(0), EarnedBy(alice))\n}\n\nfunc TestCloseAndReopenAreTheCreatorsAlone(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSubscribe(cross(cur), id)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"only the plan's creator\", func() { Close(cross(cur), id) })\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClose(cross(cur), id)\n\t_, _, _, _, _, isOpen := Get(id)\n\tuassert.False(t, isOpen)\n\tuassert.True(t, IsActive(id, bob), \"closing does not take back a paid period\")\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tuassert.AbortsContains(t, cur, \"closed to new subscriptions\", func() {\n\t\tSubscribe(cross(cur), id)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"already closed\", func() { Close(cross(cur), id) })\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"only the plan's creator\", func() { Reopen(cross(cur), id) })\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReopen(cross(cur), id)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"already open\", func() { Reopen(cross(cur), id) })\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tSubscribe(cross(cur), id)\n\tuassert.Equal(t, 2, SupporterCount(id))\n}\n\nfunc TestAPlanThatIsNotThere(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"plan #4242 not found\", func() {\n\t\tSubscribe(cross(cur), 4242)\n\t})\n\tuassert.PanicsContains(t, cur, \"plan #4242 not found\", func() { Count(); IsActive(4242, bob) })\n}\n\nfunc TestSupportersAreDistinctAndInFirstPaymentOrder(cur realm, t *testing.T) {\n\treset()\n\tid := open(cur, t)\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tSubscribe(cross(cur), id)\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSubscribe(cross(cur), id)\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tSubscribe(cross(cur), id)\n\n\tgot := Supporters(id)\n\turequire.Equal(t, 2, len(got))\n\tuassert.Equal(t, carol.String(), got[0].String())\n\tuassert.Equal(t, bob.String(), got[1].String())\n}\n\n// TestRender uses uassert rather than an Example because every view contains\n// consecutive blank lines, which gno collapses inside an // Output: block.\nfunc TestRender(cur realm, t *testing.T) {\n\treset()\n\n\tempty := Render(\"\")\n\tuassert.True(t, strings.Contains(empty, \"No plans yet.\"), empty)\n\tuassert.True(t, strings.Contains(empty, \"no cron on chain\"), \"the index says it: \"+empty)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Open(cross(cur), \"a | pipe and [a link](x)\", \"about **everything**\", price, period)\n\n\tpay(price)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tSubscribe(cross(cur), id)\n\n\tindex := Render(\"\")\n\tuassert.False(t, strings.Contains(index, \"| a | pipe\"),\n\t\t\"a raw pipe would open a column: \"+index)\n\tuassert.True(t, strings.Contains(index, \"a \\\\| pipe and \\\\[a link\\\\]\\\\(x\\\\)\"),\n\t\t\"the title is escaped once in the listing, pipe included: \"+index)\n\tuassert.True(t, strings.Contains(index, \"[\"+strconv.FormatInt(id, 10)+\"](/r/moul/x/social/patron/v0:plan/\"),\n\t\t\"the link text is the plan number, which is ours and not the caller's: \"+index)\n\tuassert.True(t, strings.Contains(index, \"func=Open\"), \"the index offers the transaction\")\n\tuassert.True(t, strings.Contains(index, \"1 of 1\"), \"one active of one supporter: \"+index)\n\n\tsid := strconv.FormatInt(id, 10)\n\tpage := Render(\"plan/\" + sid)\n\tuassert.True(t, strings.Contains(page, \"# Plan #\"+sid))\n\t// A heading is prose, so ui.Inline escapes the link syntax and leaves the\n\t// pipe alone: a pipe only means something inside a table.\n\tuassert.True(t, strings.Contains(page, \"# Plan #\"+sid+\": a | pipe and \\\\[a link\\\\]\\\\(x\\\\)\"),\n\t\t\"the title is escaped in the heading too: \"+page)\n\tuassert.True(t, strings.Contains(page, \"about \\\\*\\\\*everything\\\\*\\\\*\"),\n\t\t\"the description is escaped: \"+page)\n\tuassert.True(t, strings.Contains(page, \"func=Subscribe\"))\n\tuassert.True(t, strings.Contains(page, \".send=\"+strconv.FormatInt(price, 10)+\"ugnot\"),\n\t\t\"the support link carries the price: \"+page)\n\tuassert.True(t, strings.Contains(page, \"func=Close\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClose(cross(cur), id)\n\tclosed := Render(\"plan/\" + sid)\n\tuassert.True(t, strings.Contains(closed, \"takes no new subscriptions\"), closed)\n\tuassert.False(t, strings.Contains(closed, \"func=Subscribe\"),\n\t\t\"a closed plan offers no payment: \"+closed)\n\n\tuassert.Equal(t, \"# Patron\\nNo plan #4242\", Render(\"plan/4242\"))\n\tuassert.Equal(t, \"# Patron\\nNot a plan id: nope\", Render(\"plan/nope\"))\n\tuassert.True(t, strings.HasPrefix(Render(\"elsewhere\"), \"# Not found\"))\n\n\t// A page past the end is an empty listing, not a panic.\n\tuassert.True(t, strings.Contains(Render(\"?page=99\"), \"No plans yet.\"))\n\tuassert.True(t, strings.Contains(Render(\"?page=nonsense\"), \"a \\\\| pipe\"),\n\t\t\"an unreadable page number falls back to the first\")\n}\n"},{"name":"render.gno","body":"package patron\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\tpt \"gno.land/p/moul/x/social/patron/v0\"\n)\n\n// pageSize is how many plans the index lists at once.\nconst pageSize = 20\n\n// titleWidth is how much of a plan's title a listing shows.\nconst titleWidth = 40\n\n// Render routes two views: the index and one plan.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tswitch {\n\tcase strings.HasPrefix(req.Path, \"plan/\"):\n\t\treturn renderPlan(strings.TrimPrefix(req.Path, \"plan/\"))\n\tcase req.Path == \"\":\n\t\treturn renderIndex(req)\n\tdefault:\n\t\treturn md.H1(\"Not found\") + \"No such view: \" + ui.Inline(req.Path)\n\t}\n}\n\nfunc renderIndex(req *realmpath.Request) string {\n\tnow := runtime.ChainHeight()\n\n\tout := md.H1(\"Patron\")\n\tout += \"Recurring support for a builder. A creator opens a plan with a price per \" +\n\t\t\"period and a period measured in blocks, and a supporter buys whole periods of \" +\n\t\t\"it with \" + md.InlineCode(\"ugnot\") + \".\\n\\n\"\n\tout += md.Blockquote(\"There is no cron on chain, so a renewal is a pull and not a \" +\n\t\t\"push: nothing here can charge anybody. A supporter renews by paying again, and \" +\n\t\t\"renewing early never loses time already paid for.\") + \"\\n\"\n\n\tstats := ui.NewTable(\"plans\", \"owed to creators and supporters\", \"block\")\n\tstats.Row(\n\t\tstrconv.Itoa(plans.Count()),\n\t\tnum.GNOTf(plans.TotalOwed()),\n\t\tstrconv.FormatInt(now, 10),\n\t)\n\tout += stats.String()\n\n\tout += md.H2(\"Plans\")\n\tout += planTable(plans.List(pageNum(req), pageSize), now)\n\n\tout += \"\\n\" + ui.Action(\"➕ Open a plan\", \"Open\",\n\t\t\"title\", \"\", \"description\", \"\", \"pricePerPeriod\", \"\", \"periodBlocks\", \"\") +\n\t\t\" · \" + ui.Action(\"💰 Withdraw what I am owed\", \"Withdraw\") + \"\\n\"\n\n\tout += md.H2(\"What it does not do\")\n\tout += md.BulletList([]string{\n\t\t\"**It does not charge anybody.** A renewal is a payment the supporter signs.\",\n\t\t\"**It does not stream.** A creator is credited the whole price at the moment \" +\n\t\t\t\"it is paid, so a supporter who stops being active is not refunded and no \" +\n\t\t\t\"part of a paid period comes back. Escrowed streaming needs a claim \" +\n\t\t\t\"schedule and a refund path, which is the v1.\",\n\t\t\"**It does not issue a token.** Minting a creator coin per period paid is \" +\n\t\t\t\"easy; the sink is not, because what it would be redeemed for is a promise \" +\n\t\t\t\"made off chain.\",\n\t})\n\n\treturn out\n}\n\nfunc renderPlan(raw string) string {\n\tid, ok := store.ParseID(raw)\n\tif !ok {\n\t\treturn md.H1(\"Patron\") + \"Not a plan id: \" + ui.Inline(raw)\n\t}\n\tp, found := plans.Get(id)\n\tif !found {\n\t\treturn md.H1(\"Patron\") + \"No plan #\" + id.String()\n\t}\n\tnow := runtime.ChainHeight()\n\n\tout := md.H1(\"Plan #\" + id.String() + \": \" + ui.Inline(p.Title))\n\tif p.Description != \"\" {\n\t\tout += md.Blockquote(ui.Inline(p.Description)) + \"\\n\"\n\t}\n\n\tstatus := \"open\"\n\tif !p.Open {\n\t\tstatus = \"closed to new subscriptions\"\n\t}\n\tfacts := ui.NewTable(\"creator\", \"price per period\", \"period\", \"status\")\n\tfacts.Row(\n\t\tui.Addr(p.Creator),\n\t\tnum.GNOTf(p.PricePerPeriod),\n\t\tstrconv.FormatInt(p.PeriodBlocks, 10)+\" blocks\",\n\t\tstatus,\n\t)\n\tout += facts.String()\n\n\tif p.Open {\n\t\t// The link carries the send amount, so the price is not something a\n\t\t// supporter has to copy out of the table and retype.\n\t\tout += md.Link(\n\t\t\t\"💜 Support for one period (\"+num.GNOTf(p.PricePerPeriod)+\")\",\n\t\t\ttxlink.Realm(realmPath).NewLink(\"Subscribe\").\n\t\t\t\tAddArgs(\"planID\", id.String()).\n\t\t\t\tSetSend(strconv.FormatInt(p.PricePerPeriod, 10)+denom).\n\t\t\t\tURL(),\n\t\t) + \"\\n\\n\"\n\t\tout += \"Paying \" + md.InlineCode(\"n\") + \" times the price buys \" +\n\t\t\tmd.InlineCode(\"n\") + \" periods at once. Anything left over under one \" +\n\t\t\t\"period is credited back to you, not kept: take it with \" +\n\t\t\tmd.InlineCode(\"Withdraw\") + \".\\n\"\n\t} else {\n\t\tout += ui.Empty(\"This plan takes no new subscriptions. Anything already paid \" +\n\t\t\t\"for runs to its own block.\")\n\t}\n\n\tout += md.H2(\"Supporters\")\n\tout += supporterTable(p, now)\n\n\tout += md.H2(\"Creator\")\n\tout += \"Earned across every plan: \" + md.Bold(num.GNOTf(plans.EarnedBy(p.Creator))) +\n\t\t\" · withdrawable now: \" + md.Bold(num.GNOTf(plans.CreditOf(p.Creator))) + \"\\n\\n\"\n\tout += ui.Action(\"🚪 Close\", \"Close\", \"planID\", id.String()) +\n\t\t\" · \" + ui.Action(\"🔓 Reopen\", \"Reopen\", \"planID\", id.String()) +\n\t\t\" · \" + ui.Action(\"💰 Withdraw\", \"Withdraw\") + \"\\n\\n\"\n\tout += md.Link(\"← every plan\", pt.RealmURL(realmPath)) + \"\\n\"\n\n\treturn out\n}\n\n// planTable lists plans.\n//\n// The link text is the plan NUMBER and not its title, which is the one thing\n// to copy from here. md.Link escapes its text with the inline escaper, and the\n// inline escaper does not touch a pipe, because a pipe means nothing in a\n// sentence: a user title carried inside a link inside a table cell therefore\n// still opens a column. So the title gets its own cell and goes through\n// ui.Cell, which is the escaper that knows it is in a table. It is truncated\n// first with ui.ShortN, which does not escape, so the cut can never strand a\n// backslash that the escaper had just inserted.\nfunc planTable(items []pt.Listing, now int64) string {\n\tt := ui.NewTable(\"#\", \"plan\", \"creator\", \"per period\", \"period\", \"supporters\", \"\")\n\tfor _, it := range items {\n\t\tmark := \"🟢\"\n\t\tif !it.Plan.Open {\n\t\t\tmark = \"🔒\"\n\t\t}\n\t\tt.Row(\n\t\t\tmd.Link(it.ID.String(), pt.PlanURL(realmPath, it.ID)),\n\t\t\tui.Cell(ui.ShortN(it.Plan.Title, titleWidth, 0)),\n\t\t\tui.Addr(it.Plan.Creator),\n\t\t\tnum.GNOTf(it.Plan.PricePerPeriod),\n\t\t\tstrconv.FormatInt(it.Plan.PeriodBlocks, 10)+\" blocks\",\n\t\t\tstrconv.Itoa(it.Plan.ActiveCount(now))+\" of \"+strconv.Itoa(it.Plan.SupporterCount()),\n\t\t\tmark,\n\t\t)\n\t}\n\treturn t.OrEmpty(\"No plans yet.\")\n}\n\nfunc supporterTable(p *pt.Plan, now int64) string {\n\tt := ui.NewTable(\"supporter\", \"paid through block\", \"active\")\n\tfor _, who := range p.Supporters() {\n\t\tactive := \"no\"\n\t\tif p.IsActive(who, now) {\n\t\t\tactive = \"yes\"\n\t\t}\n\t\tt.Row(ui.Addr(who), strconv.FormatInt(p.PaidThrough(who), 10), active)\n\t}\n\treturn t.OrEmpty(\"Nobody supports this plan yet.\")\n}\n\n// pageNum reads ?page= and falls back to the first page for anything it\n// cannot read, which is the only answer a Render can give: there is nobody to\n// report an error to.\nfunc pageNum(req *realmpath.Request) int {\n\tn, err := strconv.Atoi(req.Query.Get(\"page\"))\n\tif err != nil || n \u003c 1 {\n\t\treturn 1\n\t}\n\treturn n\n}\n"}]},"send":"","max_deposit":"14000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"threads","path":"gno.land/r/moul/x/social/threads/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/social/threads/v0`\n\n**A discussion block any realm can embed**, keyed on the page it appears on\nrather than on the realm that stores it. Two lines in the host realm, which\nstores nothing:\n\n```go\nimport \"gno.land/r/moul/x/social/threads/v0\"\n\nfunc Render(path string) string {\n\treturn body + threads.RenderBlock()\n}\n```\n\n`RenderBlock` takes no argument because it does not need one. A plain read\nexported by a realm and called by another opens no realm frame, so\n`unsafe.CurrentRealm()` inside it reports the **caller**: the host realm's own\npath is the page key, and nothing has to be configured, registered or passed.\n`RenderBlockFor(page)` is the explicit form, for a realm that renders several\npages or already holds its path as a constant. Adding a `cur realm` parameter to\neither would silently reverse that and key every embed to this realm.\n\nIt is the text half of\n[`r/moul/reactions`](https://github.com/moul/gno-contracts/tree/main/r/moul/reactions):\nthe same embed shape, the same page keys, and the same reason for existing.\n\n## The token, and the three things it has to answer\n\nTHREAD is a GRC20 issued through\n[`p/moul/x/social/coin`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/social/coin),\nwhich refuses to create a token until all three of these are written down:\n\n| | |\n|---|---|\n| **mint** | 1 THREAD to a thread's author, the first time each distinct address replies to it. People, not messages, and never yourself. |\n| **sink** | `Boost` burns 10 THREAD to pin a thread to the top of its page for 1,000 blocks. It is the only thing that removes supply, and the only thing the token does. |\n| **buyer** | anyone who wants placement and has not earned it. They have to acquire THREAD from somebody who did, with `Transfer`. |\n\n**Placement is the one thing a discussion has that people want and cannot all\nhave at once**, which is what makes it a sink worth paying for rather than a\nleaderboard. A pin extends from whichever is later, now or the current pin, so\nbuying one never shortens somebody else's, and `Boost` charges before it pins.\n\n**It is farmable, and saying so is cheaper than pretending otherwise**: two\naddresses replying to each other mint one THREAD each per thread. The fix is a\ngate on who counts as a replier, which belongs in\n[`r/moul/x/social/vouch`](https://github.com/moul/gno-contracts/tree/main/r/moul/x/social/vouch)\nand not here. Until then the cost of farming is one transaction per point and\nthe benefit is capped by what a pin is worth.\n\nThe token is registered with `r/nt/grc20reg`, so a realm that does not import\nthis one can still find and move it by key: `TokenKey()` returns it.\n\n## Why this realm is not private\n\nEvery other realm in the `x/social` family is `private = true` and can be\nredeployed in place. This one cannot be, twice over: a private realm cannot be\nimported at all, which would delete the embed, and handing an object to another\nrealm (registering the token) panics at runtime from a private realm. Every\nthread, balance and pin under this path belongs to the people who wrote them, so\na fix ships as a `v1` beside it rather than as a redeploy that wipes the lot.\n\n## Reading it\n\n`Render(\"\")` is the index: the counts, the recent threads across every page, the\ntoken's three declarations, and the embed snippet. `Render(\"page/\u003cpage key\u003e\")`\nis one page's threads, `Render(\"thread/\u003cid\u003e\")` is one thread with its replies and\nthe reply and boost buttons.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/social/threads/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/threads/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/social/threads/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/threads/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/social/threads/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/threads/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/social/threads/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/threads/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/social/threads/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/social/threads/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/social/threads/v0\"\ngno = \"0.9\"\n\n# public: the entire point of this realm is that other realms import it and\n# call RenderBlock() inside their own Render, exactly as r/moul/reactions does.\n# A private realm cannot be imported at all, so `private = true` here would\n# delete the feature rather than trade against it.\n#\n# It also issues a GRC20 and registers it with r/nt/grc20reg, which hands an\n# object to another realm: a private realm panics at runtime when it does that.\n#\n# What private would have bought, redeploy-in-place, is given up deliberately.\n# Every thread, every balance and every pin under this path belongs to the\n# people who wrote them, so a fix ships as a v1 beside it rather than as a\n# redeploy that silently wipes the lot.\n"},{"name":"render.gno","body":"package threads\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\tth \"gno.land/p/moul/x/social/threads/v0\"\n)\n\n// Render routes three views: the realm's own index, one page's threads, and\n// one thread.\n//\n// A page key contains slashes, so \"page/\u003ckey\u003e\" is split on the prefix rather\n// than by path element: realmpath gives the parts, and rejoining them would\n// only be a way to get it wrong.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tswitch {\n\tcase strings.HasPrefix(req.Path, \"page/\"):\n\t\treturn renderPage(strings.TrimPrefix(req.Path, \"page/\"))\n\tcase strings.HasPrefix(req.Path, \"thread/\"):\n\t\treturn renderThread(strings.TrimPrefix(req.Path, \"thread/\"))\n\tcase req.Path == \"\":\n\t\treturn renderIndex()\n\tdefault:\n\t\treturn md.H1(\"Not found\") + \"No such view: \" + ui.Inline(req.Path)\n\t}\n}\n\nfunc renderIndex() string {\n\tout := md.H1(\"Threads\")\n\tout += \"A discussion block any realm can embed, keyed on the page it appears on.\\n\\n\"\n\n\tt := ui.NewTable(\"threads\", \"pages\", \"THREAD supply\")\n\tt.Row(strconv.Itoa(board.Len()), strconv.Itoa(board.Pages()), strconv.FormatInt(points.Supply(), 10))\n\tout += t.String()\n\n\tout += md.H2(\"Recent, across every page\")\n\tout += listing(board.Recent(20), true)\n\n\tout += md.H2(\"The token\")\n\tout += points.Render()\n\n\tout += md.H2(\"Embedding it\")\n\tout += \"Two lines in the host realm, and it stores nothing:\\n\\n\"\n\tout += md.LanguageCodeBlock(\"go\", `import \"`+realmPath+`\"\n\nfunc Render(path string) string {\n\treturn body + threads.RenderBlock()\n}`)\n\tout += \"The page key is the host realm's own path, read off the call. \" +\n\t\tmd.InlineCode(\"RenderBlockFor(page)\") + \" names one explicitly.\\n\"\n\n\treturn out\n}\n\nfunc renderPage(page string) string {\n\tif !th.ValidPage(page) {\n\t\treturn md.H1(\"Threads\") + \"Not a page key: \" + ui.Inline(page)\n\t}\n\tout := md.H1(\"Threads on \" + ui.Inline(page))\n\tout += md.Link(\"the page itself\", th.RealmURL(page)) + \"\\n\\n\"\n\tout += listing(board.List(page, runtime.ChainHeight(), 0), false)\n\tout += \"\\n\" + ui.Action(\"💬 Post here\", \"Post\", \"page\", page, \"body\", \"\") + \"\\n\"\n\treturn out\n}\n\nfunc renderThread(raw string) string {\n\tid, ok := store.ParseID(raw)\n\tif !ok {\n\t\treturn md.H1(\"Threads\") + \"Not a thread id: \" + ui.Inline(raw)\n\t}\n\tt, found := board.Get(id)\n\tif !found {\n\t\treturn md.H1(\"Threads\") + \"No thread #\" + id.String()\n\t}\n\n\tout := md.H1(\"Thread #\" + id.String())\n\tout += md.Blockquote(ui.Inline(t.Body)) + \"\\n\"\n\tout += md.Italic(\"by \"+ui.Addr(t.Author)+\" · on \"+\n\t\tmd.Link(t.Page, th.PageURL(realmPath, t.Page))+\n\t\t\" · \"+strconv.Itoa(t.Repliers())+\" earned\") + \"\\n\\n\"\n\n\tif t.PinnedUntil \u003e runtime.ChainHeight() {\n\t\tout += \"📌 pinned until block \" + strconv.FormatInt(t.PinnedUntil, 10) + \"\\n\\n\"\n\t}\n\n\tout += md.H2(\"Replies\")\n\tif len(t.Replies) == 0 {\n\t\tout += ui.Empty(\"Nobody has replied yet.\")\n\t} else {\n\t\tr := ui.NewTable(\"by\", \"said\", \"block\")\n\t\tfor _, rep := range t.Replies {\n\t\t\tr.Row(ui.Addr(rep.Author), ui.Cell(rep.Body), strconv.FormatInt(rep.At, 10))\n\t\t}\n\t\tout += r.String()\n\t}\n\n\tout += \"\\n\" + ui.Action(\"💬 Reply\", \"Reply\", \"threadID\", id.String(), \"body\", \"\") +\n\t\t\" · \" + ui.Action(\"📌 Boost\", \"Boost\", \"threadID\", id.String()) + \"\\n\"\n\treturn out\n}\n\n// listing renders a set of threads. withPage adds the page column, which the\n// index needs and a page view would only repeat.\nfunc listing(items []th.Listing, withPage bool) string {\n\tif len(items) == 0 {\n\t\treturn ui.Empty(\"No threads yet.\")\n\t}\n\theaders := []string{\"\", \"#\", \"thread\", \"by\", \"replies\"}\n\tif withPage {\n\t\theaders = append(headers, \"page\")\n\t}\n\tt := ui.NewTable(headers...)\n\tnow := runtime.ChainHeight()\n\tfor _, it := range items {\n\t\tmark := \"\"\n\t\tif it.Thread.Pinned(now) {\n\t\t\tmark = \"📌\"\n\t\t}\n\t\tcells := []string{\n\t\t\tmark,\n\t\t\t// The link title is the id, never the body: md.Link escapes\n\t\t\t// markdown but not a pipe, and a pipe in a table cell opens a\n\t\t\t// column. ui.Cell is the only thing that rewrites it.\n\t\t\tmd.Link(\"#\"+it.ID.String(), th.ThreadURL(realmPath, it.ID)),\n\t\t\tui.Cell(ui.ShortN(it.Thread.Body, th.ExcerptLen, 0)),\n\t\t\tui.Addr(it.Thread.Author),\n\t\t\tstrconv.Itoa(len(it.Thread.Replies)),\n\t\t}\n\t\tif withPage {\n\t\t\tcells = append(cells, ui.Cell(it.Thread.Page))\n\t\t}\n\t\tt.Row(cells...)\n\t}\n\treturn t.String()\n}\n"},{"name":"threads.gno","body":"// Package threads is a discussion block any realm can embed, keyed on the page\n// it appears on rather than on the realm that stores it.\n//\n// It is the text half of gno.land/r/moul/reactions: the same embed shape, the\n// same page keys, two lines in the host realm.\n//\n//\timport \"gno.land/r/moul/x/social/threads/v0\"\n//\n//\tfunc Render(path string) string {\n//\t\treturn body + threads.RenderBlock()\n//\t}\n//\n// [RenderBlock] takes no argument because it does not need one: a plain read\n// exported by a realm and called by another opens no realm frame, so\n// unsafe.CurrentRealm() inside it reports the CALLER. The host realm's own\n// path is the page key, and nothing has to be configured or registered.\n// [RenderBlockFor] is the explicit form, for a realm that renders more than\n// one page or already holds its path as a constant.\n//\n// # The token, and the three things it has to answer\n//\n// THREAD exists because placement is the one thing a discussion has that\n// people want and cannot all have at once.\n//\n//\tmint   1 THREAD to a thread's author, the first time each distinct\n//\t       address replies to it. People, not messages, and never yourself.\n//\tsink   [Boost] burns PinCost THREAD to pin a thread to the top of its\n//\t       page for PinBlocks blocks. That is the only thing that removes\n//\t       supply, and the only thing the token does.\n//\tbuyer  anyone who wants placement and has not earned it. They have to\n//\t       acquire THREAD from someone who did, with [Transfer], which is\n//\t       what makes attention a market rather than a scoreboard.\n//\n// It is farmable, and saying so is cheaper than pretending otherwise: two\n// addresses replying to each other mint one THREAD each per thread. The fix is\n// a gate on who counts as a replier, which belongs in a vouching realm and not\n// here; until then the cost of farming is one transaction per point and the\n// benefit is capped by what a pin is worth.\npackage threads\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"strconv\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\tsc \"gno.land/p/moul/x/social/coin/v0\"\n\tth \"gno.land/p/moul/x/social/threads/v0\"\n\t\"gno.land/r/nt/grc20reg/v0\"\n)\n\n// realmPath is this realm's own path, the one its gnomod.toml module line\n// declares. It is written out rather than read from unsafe.CurrentRealm(),\n// which reports the CALLER in every plain read this realm exports and would\n// therefore build every link against whichever realm embedded the block.\nconst realmPath = \"gno.land/r/moul/x/social/threads/v0\"\n\nconst (\n\t// EarnPerReplier is minted to a thread's author the first time each\n\t// distinct address replies to it.\n\tEarnPerReplier = int64(1)\n\n\t// PinCost is burned by Boost, and PinBlocks is how long the pin lasts.\n\t// A pin extends from whichever is later, now or the current pin, so\n\t// buying one never shortens somebody else's.\n\tPinCost   = int64(10)\n\tPinBlocks = int64(1000)\n\n\t// BlockThreads is how many threads an embedded block shows before it\n\t// turns into a link to the full page.\n\tBlockThreads = 5\n)\n\nvar (\n\t// board holds every thread. A redeploy would wipe it, which is why this\n\t// realm is not private (see gnomod.toml).\n\tboard = th.NewBoard()\n\n\t// points is the THREAD ledger. The Coin is unexported on purpose: it\n\t// carries unrestricted mint and burn, and an exported pointer to it\n\t// would hand both to any importer.\n\tpoints *sc.Coin\n\n\t// tokenKey is the r/nt/grc20reg lookup key, which is how a realm that\n\t// does not import this one refers to THREAD.\n\ttokenKey string\n)\n\n// tokenPolicy is the three declarations THREAD is issued under. It is a var\n// and not three literals inside init so that the tests, which rebuild the\n// ledger between cases, issue the same token the chain holds.\nvar tokenPolicy = sc.Policy{\n\tMint:  \"1 to a thread's author per distinct address that replies to it\",\n\tSink:  \"burned by Boost to pin a thread to the top of its page\",\n\tBuyer: \"anyone who wants placement and has not earned it\",\n}\n\nfunc init(cur realm) {\n\tpoints = sc.New(\"Thread Points\", \"THREAD\", 0, 0, tokenPolicy, 0, cur)\n\ttokenKey = grc20reg.Register(cross(cur), points.Token(), \"thread\")\n}\n\n// Post opens a thread under page.\n//\n// page is a package path, the full one: \"gno.land/r/moul/home\". It does not\n// have to be a realm that embeds the block, and nothing checks that it exists.\n// A page is just a name, which is what lets a realm key discussion on\n// something finer than itself.\nfunc Post(cur realm, page, body string) int64 {\n\twho := caller(cur)\n\tid, err := board.Post(page, who, body, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Post\", \"id\", id.String(), \"page\", page, \"author\", who.String())\n\treturn int64(id)\n}\n\n// Reply appends to a thread.\n//\n// The first time each distinct address replies to a given thread, its author\n// earns EarnPerReplier. Replying again earns nothing, and replying to your own\n// thread never earns anything.\nfunc Reply(cur realm, threadID int64, body string) {\n\twho := caller(cur)\n\tid := store.ID(threadID)\n\tisNew, err := board.Reply(id, who, body, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Reply\", \"id\", id.String(), \"author\", who.String())\n\n\tif isNew {\n\t\tt, _ := board.Get(id)\n\t\tpoints.Earn(t.Author, EarnPerReplier)\n\t\tchain.Emit(\"Earn\", \"id\", id.String(), \"author\", t.Author.String())\n\t}\n}\n\n// Boost burns PinCost THREAD from the caller and pins the thread to the top of\n// its page for PinBlocks blocks.\n//\n// Anyone may boost anyone's thread. The pin is on the thread and not on the\n// buyer, so the thing being sold is placement and not authorship.\nfunc Boost(cur realm, threadID int64) {\n\twho := caller(cur)\n\tid := store.ID(threadID)\n\tt, ok := board.Get(id)\n\tif !ok {\n\t\tpanic(th.ErrNoThread.Error())\n\t}\n\n\tnow := runtime.ChainHeight()\n\tfrom := now\n\tif t.PinnedUntil \u003e from {\n\t\tfrom = t.PinnedUntil\n\t}\n\t// Charge first, pin second. The chain would revert both on an abort, so\n\t// the order is invisible on mainnet and load-bearing everywhere else: a\n\t// test, a filetest and any future caller that recovers see a refused\n\t// boost that pinned nothing.\n\tpoints.Spend(who, PinCost)\n\tif err := board.Pin(id, from+PinBlocks); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Boost\", \"id\", id.String(), \"by\", who.String(),\n\t\t\"until\", strconv.FormatInt(from+PinBlocks, 10))\n}\n\n// Transfer moves the caller's own THREAD. It is what makes the sink a market:\n// somebody who wants a pin and has written nothing has to buy from an author.\nfunc Transfer(cur realm, to address, amount int64) {\n\tif err := points.CallerTeller().Transfer(0, cur, to, amount); err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\n// Approve lets spender draw amount of the caller's THREAD.\nfunc Approve(cur realm, spender address, amount int64) {\n\tif err := points.CallerTeller().Approve(0, cur, spender, amount); err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\n// TransferFrom spends an allowance the caller was granted.\nfunc TransferFrom(cur realm, from, to address, amount int64) {\n\tif err := points.CallerTeller().TransferFrom(0, cur, from, to, amount); err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\n// RenderBlock returns the block for the realm CALLING it, which is the form a\n// host realm embeds.\n//\n// It has no cur realm parameter on purpose. A plain read is borrowed: gno\n// opens no realm frame for it, so unsafe.CurrentRealm() reports the caller's\n// path and the block keys itself with no argument. Adding a cur realm here\n// would silently reverse that and key every embed to this realm instead.\nfunc RenderBlock() string {\n\treturn blockFor(unsafe.CurrentRealm().PkgPath())\n}\n\n// RenderBlockFor is [RenderBlock] for a named page. Use it from a crossing\n// function, where there is no caller to read off the stack, or when one realm\n// renders several pages.\nfunc RenderBlockFor(page string) string { return blockFor(page) }\n\n// blockFor is the shared body, so no exported read of this realm calls another\n// and picks up the wrong path.\nfunc blockFor(page string) string {\n\tnow := runtime.ChainHeight()\n\treturn th.Block(realmPath, page, board.List(page, now, BlockThreads), board.PageLen(page), now)\n}\n\n// Count is how many threads a page holds.\nfunc Count(page string) int { return board.PageLen(page) }\n\n// Total is how many threads exist, across every page.\nfunc Total() int { return board.Len() }\n\n// Pages is how many pages have ever been posted on.\nfunc Pages() int { return board.Pages() }\n\n// Repliers is how many distinct addresses have replied to a thread, which is\n// also how much its author has earned from it.\nfunc Repliers(threadID int64) int {\n\tt, _ := board.Get(store.ID(threadID))\n\treturn t.Repliers()\n}\n\n// PinnedUntil is the height a thread stops being pinned at, or 0.\nfunc PinnedUntil(threadID int64) int64 {\n\tt, ok := board.Get(store.ID(threadID))\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn t.PinnedUntil\n}\n\n// BalanceOf is an address's THREAD balance.\nfunc BalanceOf(owner address) int64 { return points.BalanceOf(owner) }\n\n// Allowance is what owner let spender draw.\nfunc Allowance(owner, spender address) int64 {\n\treturn points.Token().Allowance(owner, spender)\n}\n\n// TotalSupply is the THREAD in existence: everything earned, less everything\n// burned by Boost.\nfunc TotalSupply() int64 { return points.Supply() }\n\n// TokenKey is the r/nt/grc20reg key for THREAD.\nfunc TokenKey() string { return tokenKey }\n\n// caller is the address that called us, checked the one way that is safe.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"threads_test.gno","body":"package threads\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\tsc \"gno.land/p/moul/x/social/coin/v0\"\n\tth \"gno.land/p/moul/x/social/threads/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst homePage = \"gno.land/r/moul/home\"\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// reset clears realm state. Realm globals live for the whole test binary, so\n// everything a later test reads, including the ledger, starts here.\n//\n// The ledger is rebuilt through a same-realm cross because grc20.NewToken\n// needs a code-realm frame, which a test's EOA-origin cur is not. It is NOT\n// re-registered with grc20reg: the registry is another realm and its entry\n// survives this one's state.\nfunc reset(cur realm) {\n\tboard = th.NewBoard()\n\tfunc(cur realm) { // the name is forced: a realm argument must be called cur\n\t\tpoints = sc.New(\"Thread Points\", \"THREAD\", 0, 0, tokenPolicy, 0, cur)\n\t}(cross(cur))\n}\n\n// earn gives who n THREAD the only way the realm allows: n distinct addresses\n// replying to a thread they wrote.\nfunc earn(cur realm, t *testing.T, who address, n int) int64 {\n\tt.Helper()\n\ttesting.SetRealm(testing.NewUserRealm(who))\n\tid := Post(cross(cur), homePage, \"a thread by \"+who.String())\n\tfor i := 0; i \u003c n; i++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"replier\" + strconv.Itoa(i))))\n\t\tReply(cross(cur), id, \"hello\")\n\t}\n\treturn id\n}\n\nfunc TestAnAuthorEarnsPeopleAndNotMessages(cur realm, t *testing.T) {\n\treset(cur)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Post(cross(cur), homePage, \"first thread\")\n\tuassert.Equal(t, int64(0), BalanceOf(alice), \"writing earns nothing on its own\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tReply(cross(cur), id, \"nice\")\n\tuassert.Equal(t, int64(1), BalanceOf(alice))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tReply(cross(cur), id, \"still me\")\n\tuassert.Equal(t, int64(1), BalanceOf(alice), \"one person is one point, however much they say\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tReply(cross(cur), id, \"thanks\")\n\tuassert.Equal(t, int64(1), BalanceOf(alice), \"replying to yourself is not an audience\")\n\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tReply(cross(cur), id, \"hi\")\n\tuassert.Equal(t, int64(2), BalanceOf(alice))\n\n\tuassert.Equal(t, 2, Repliers(id))\n\tuassert.Equal(t, int64(2), TotalSupply())\n\tuassert.Equal(t, int64(0), BalanceOf(bob), \"a replier earns nothing\")\n}\n\nfunc TestBoostIsTheOnlyThingThatBurns(cur realm, t *testing.T) {\n\treset(cur)\n\tid := earn(cur, t, alice, 10)\n\turequire.Equal(t, int64(10), BalanceOf(alice))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tBoost(cross(cur), id)\n\n\tuassert.Equal(t, int64(0), BalanceOf(alice))\n\tuassert.Equal(t, int64(0), TotalSupply(), \"the sink removes supply, it does not move it\")\n\tuassert.Equal(t, int64(123+PinBlocks), PinnedUntil(id), \"tests start at height 123\")\n}\n\nfunc TestBoostRefusesWhatTheCallerCannotAfford(cur realm, t *testing.T) {\n\treset(cur)\n\tid := earn(cur, t, alice, 1)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"balance 1 is short of 10\", func() {\n\t\tBoost(cross(cur), id)\n\t})\n\tuassert.Equal(t, int64(0), PinnedUntil(id), \"a refused boost pins nothing\")\n\tuassert.Equal(t, int64(1), BalanceOf(alice))\n}\n\n// A second boost extends from the current pin, not from now, so the thread\n// never loses time it was already paid for.\nfunc TestASecondBoostExtendsRatherThanRestarts(cur realm, t *testing.T) {\n\treset(cur)\n\tid := earn(cur, t, alice, 20)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tBoost(cross(cur), id)\n\tfirst := PinnedUntil(id)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tBoost(cross(cur), id)\n\tuassert.Equal(t, first+PinBlocks, PinnedUntil(id))\n\tuassert.Equal(t, int64(0), BalanceOf(alice))\n}\n\n// Anyone may boost anyone's thread, and the buyer has to get THREAD from\n// somebody who earned it. That is the whole market.\nfunc TestPlacementIsBoughtFromAnEarner(cur realm, t *testing.T) {\n\treset(cur)\n\tid := earn(cur, t, alice, 10)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tTransfer(cross(cur), bob, 10)\n\tuassert.Equal(t, int64(0), BalanceOf(alice))\n\tuassert.Equal(t, int64(10), BalanceOf(bob))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tBoost(cross(cur), id)\n\tuassert.True(t, PinnedUntil(id) \u003e 0, \"bob pinned alice's thread\")\n\tuassert.Equal(t, int64(0), TotalSupply())\n}\n\nfunc TestPostRefusals(cur realm, t *testing.T) {\n\treset(cur)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"not a page key\", func() {\n\t\tPost(cross(cur), \"nopath\", \"body\")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"body is empty\", func() {\n\t\tPost(cross(cur), homePage, \"   \")\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"no such thread\", func() {\n\t\tReply(cross(cur), 99, \"into the void\")\n\t})\n\tuassert.Equal(t, 0, Total())\n}\n\nfunc TestCountsAreScopedToTheirPage(cur realm, t *testing.T) {\n\treset(cur)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), homePage, \"on home\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), \"gno.land/r/moul/blog\", \"on the blog\")\n\n\tuassert.Equal(t, 1, Count(homePage))\n\tuassert.Equal(t, 0, Count(\"gno.land/r/nobody/here\"))\n\tuassert.Equal(t, 2, Total())\n\tuassert.Equal(t, 2, Pages())\n}\n\n// RenderBlockFor is the embed, and it escapes what it shows: a raw pipe in a\n// body would otherwise open a column in the host realm's page.\nfunc TestRenderBlockForEscapesTheBody(cur realm, t *testing.T) {\n\treset(cur)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPost(cross(cur), homePage, \"a | pipe\")\n\n\tgot := RenderBlockFor(homePage)\n\tuassert.True(t, strings.Contains(got, \"func=Post\"), \"the block offers the transaction: \"+got)\n\tuassert.True(t, strings.Contains(got, `| a \\| pipe |`),\n\t\t\"the body cell escapes the pipe rather than opening a column: \"+got)\n\tuassert.False(t, strings.Contains(got, \"| a | pipe\"), \"no raw pipe survives: \"+got)\n\tuassert.True(t, strings.Contains(RenderBlockFor(\"gno.land/r/nobody/here\"), \"No discussion yet.\"))\n}\n\n// TestRender uses uassert rather than an Example because every view contains\n// consecutive blank lines, which gno collapses inside an // Output: block.\nfunc TestRender(cur realm, t *testing.T) {\n\treset(cur)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Post(cross(cur), homePage, \"a thread about [links](x)\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tReply(cross(cur), id, \"a reply with a | pipe\")\n\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"| 1 | 1 | 1 |\"), \"threads, pages, supply: \"+index)\n\tuassert.True(t, strings.Contains(index, tokenPolicy.Sink), \"the index declares the sink\")\n\tuassert.True(t, strings.Contains(index, `import \"`+realmPath+`\"`), \"the index is the embed doc\")\n\n\tpage := Render(\"page/\" + homePage)\n\tuassert.True(t, strings.Contains(page, \"/r/moul/home\"), \"it links the page itself: \"+page)\n\tuassert.True(t, strings.Contains(page, \"func=Post\"))\n\n\tsid := strconv.FormatInt(id, 10)\n\tthread := Render(\"thread/\" + sid)\n\tuassert.True(t, strings.Contains(thread, \"# Thread #\"+sid))\n\tuassert.True(t, strings.Contains(thread, \"a thread about \\\\[links\\\\]\\\\(x\\\\)\"),\n\t\t\"the body is escaped where it is shown: \"+thread)\n\tuassert.True(t, strings.Contains(thread, \"a reply with a \\\\| pipe\"),\n\t\t\"a reply cell cannot open a column: \"+thread)\n\tuassert.True(t, strings.Contains(thread, \"func=Boost\"))\n\n\tuassert.Equal(t, \"# Threads\\nNo thread #4242\", Render(\"thread/4242\"))\n\tuassert.Equal(t, \"# Threads\\nNot a thread id: nope\", Render(\"thread/nope\"))\n\tuassert.Equal(t, \"# Threads\\nNot a page key: nope\", Render(\"page/nope\"))\n\tuassert.True(t, strings.HasPrefix(Render(\"elsewhere\"), \"# Not found\"))\n}\n\nfunc TestTokenIsDiscoverableWithoutImportingThisRealm(t *testing.T) {\n\tuassert.True(t, strings.HasSuffix(TokenKey(), \".THREAD\"), TokenKey())\n\tuassert.True(t, strings.Contains(TokenKey(), realmPath), TokenKey())\n}\n"}]},"send":"","max_deposit":"12000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"vouch","path":"gno.land/r/moul/x/social/vouch/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/social/vouch/v0`\n\n**A web of trust other realms gate on.** One address vouches for another, in\nwriting, optionally with GNOT locked behind it. Any realm can then ask whether\nan address is vouched for by at least N distinct people and refuse to serve it\nif it is not.\n\n```go\nimport \"gno.land/r/moul/x/social/vouch/v0\"\n\nfunc Claim(cur realm) {\n\tif !vouch.IsTrusted(cur.Previous().Address(), 2) {\n\t\tpanic(\"get two people to vouch for you first\")\n\t}\n\t...\n}\n```\n\nThat is the whole product. It exists because the apps beside it do not have a\nsybil gate: a realm that mints a point per distinct replier is farmed by two\naddresses replying to each other, and a realm that counts one vote per address\nis farmed by holding a hundred addresses. Neither can fix it alone, because\nneither knows anything about the people behind the addresses.\n\n## The API\n\n| write | |\n|---|---|\n| `Vouch(target, reason)` | payable. Records the caller's vouch. Coins sent are locked as a bond on it. Vouching again updates the reason and adds to the bond |\n| `Revoke(target)` | removes the caller's vouch and credits the bond back to them |\n| `Withdraw()` | pays the caller every bond their revocations freed |\n\n| read | |\n|---|---|\n| `IsTrusted(addr, min)` | **the gate.** At least `min` distinct vouchers, `min` below one read as one |\n| `ScoreOf(addr)` | distinct inbound vouchers |\n| `BondedFor(addr)` | total ugnot bonded on them |\n| `VouchedBy(addr)` / `VouchesOf(addr)` | the two directions, sorted |\n| `Mutual(a, b)` | whether they vouch for each other |\n| `ReasonFrom(from, to)` / `BondFrom(from, to)` | one edge |\n| `Count`, `People`, `Owed`, `TotalBonded`, `TotalOwed` | the totals |\n| `Badge(addr)` | the one-line trust mark, for a host realm's own page |\n\nThe engine is `p/moul/x/social/vouch/v0`,\nwhich holds the graph, the validation and the refund ledger and takes the\nheight, the caller and the bond as arguments. This realm is the chain wiring\nand the `Render`.\n\n## Three traps it avoids\n\n**A score counts people, not vouches.** A second vouch from the same address to\nthe same target is an edit: the reason is replaced, the bond is added to, and\nthe score does not move. Without that, the gate measures transactions, and\ntransactions are for sale.\n\n**It never loops and sends.** `Revoke` credits a ledger and `Withdraw` pays one\npayee, zeroing the credit before the coins leave. A realm that sent on revoke\nwould hand control to the recipient mid-transition, and a recipient that\nrefuses coins could make revoking impossible.\n\n**A realm cannot forward a bond.** The payment envelope belongs to the\ntransaction, not to the frame, so a realm that was itself paid and then calls\n`Vouch` would report coins sitting at its own address. This realm refuses that\ncall outright rather than quietly reading the bond as zero. A realm may vouch;\nit may not vouch while holding somebody else's payment.\n\n## No slashing in v0, and that is the hard part\n\nA bond is value at risk only in the sense that it is illiquid: it can be\nrecovered by revoking, and nothing can take it away. That is not an oversight,\nand the missing half is not the accounting.\n\nSlashing needs an arbiter, somebody who decides that a vouch was a lie. A DAO\nvote is a popularity contest against whoever is unpopular this month. A\nchallenge market pays whoever is loudest and turns the graph into a griefing\nsurface. An oracle is one key that can confiscate anybody's money. Shipping any\nof them by default would be shipping the wrong one, so v0 ships the part that\nis uncontroversial: who said what, who put money behind it, and the gate that\nreads it.\n\nThe bond still earns its place without slashing. An illiquid deposit is a cost\na hundred throwaway addresses cannot all pay at once, which is exactly the\nshape the gate is defending against.\n\n## And can it have a token?\n\n**No, and the reason is the point.** Every app in this family is asked the same\nquestion, and here the honest answer is no. A transferable vouch is a bought\nreputation: the moment a vouch can be sold, the score stops measuring what it\nclaims to measure, and what it measures instead is who had the most money this\nweek. That is the one failure mode a sybil gate cannot survive, because it is\nnot a degradation, it is the attack.\n\nThe bond is GNOT. It is value at risk without being a market in trust itself:\nyou can lock your own money behind a claim, and you cannot sell the claim.\n\nWhat would change the answer is a token whose **only** use is being locked and\nslashed, with no transfer path that buys standing, and that needs an arbiter\nfirst, because without something that can slash it the token is a scoreboard\nwith a price. If that day comes, the shape to issue it under is\n`p/moul/x/social/coin/v0`, a sibling package: a GRC20 that refuses to exist\nuntil its mint rule, its sink and its buyer are written down. It is not\nimported here, deliberately. Saying no with a reason is the deliverable.\n\n## Public, not private\n\nRealms in this family default to `private = true`, which buys redeploy in\nplace. This one is public and its `gnomod.toml` argues why: a private realm\ncannot be imported, and a gate that can only be read over the chain is not a\ngate, since a realm cannot pause mid-transaction to query itself. The second\nreason settles it: the graph and the refund ledger are package-level variables\nwhile the bonded ugnot sits at the realm's address, so a redeploy would wipe\nthe record of whose money that is and keep the money. A realm holding somebody\nelse's coins should not be able to forget who they belong to.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/social/vouch/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/vouch/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/social/vouch/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/vouch/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/social/vouch/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/vouch/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/social/vouch/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/social/vouch/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/social/vouch/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/social/vouch/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/social/vouch/v0\"\ngno = \"0.9\"\n\n# public: other realms are expected to IMPORT IsTrusted and call it inside\n# their own crossing functions. A private realm can still be READ from outside\n# (vm/qrender and vm/qeval are unaffected by private), but a gate that only\n# answers over the chain is not a gate: a realm cannot pause mid-transaction to\n# query itself, so gating a mint or a vote on this graph requires the import.\n# Making it private would leave the product intact for humans and remove it for\n# the callers it was written for.\n#\n# The second reason is the money, and it is the one that settles it. Every\n# vouch, every bond and the ledger that says who is owed a refund are\n# package-level variables, while the ugnot backing them sits at this realm's\n# address. A redeploy wipes the first and keeps the second, so the convenience\n# private buys would, the one time it were used, strand other people's bonds\n# with no record of whose they were. A realm holding somebody else's coins\n# should not be able to forget who they belong to.\n#\n# What private would have bought, redeploy-in-place, is given up deliberately.\n# The vouch graph belongs to the people who wrote it, not to whoever deployed\n# this path, so a fix ships as a v1 beside it rather than as a redeploy that\n# silently erases the lot.\n"},{"name":"render.gno","body":"package vouch\n\nimport (\n\t\"strconv\"\n\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\tvo \"gno.land/p/moul/x/social/vouch/v0\"\n)\n\n// Render routes two views: the realm's own index, and one address's page.\n//\n// An address carries no slash, so the per-address route is a path element and\n// not a prefix strip.\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tswitch req.PathPart(0) {\n\tcase \"\":\n\t\treturn renderIndex()\n\tcase \"addr\":\n\t\treturn renderAddr(req.PathPart(1))\n\tdefault:\n\t\treturn md.H1(\"Not found\") + \"No such view: \" + ui.Inline(req.Path)\n\t}\n}\n\nfunc renderIndex() string {\n\tout := md.H1(\"Vouch\")\n\tout += \"A web of trust other realms gate on. One address vouches for another, \" +\n\t\t\"in writing, optionally with GNOT locked behind it.\\n\\n\"\n\n\tt := ui.NewTable(\"vouches\", \"people vouched for\", \"bonded\", \"awaiting withdrawal\")\n\tt.Row(\n\t\tstrconv.Itoa(graph.Count()),\n\t\tstrconv.Itoa(graph.People()),\n\t\tnum.GNOTf(graph.TotalBonded()),\n\t\tnum.GNOTf(graph.TotalOwed()),\n\t)\n\tout += t.String()\n\n\tout += md.H2(\"Most vouched for\")\n\tout += board()\n\n\tout += md.H2(\"The gate\")\n\tout += \"One line in the realm that wants it, and it costs no transaction:\\n\\n\"\n\tout += md.LanguageCodeBlock(\"go\", `import \"`+realmPath+`\"\n\nif !vouch.IsTrusted(addr, 2) {\n\tpanic(\"get two people to vouch for you first\")\n}`)\n\tout += md.Italic(\"A score counts distinct vouchers, so restating a vouch does not \" +\n\t\t\"raise it and revoking lowers it. It does not count distinct people: a pair \" +\n\t\t\"vouching for each other both reach one, which is why a real gate asks for \" +\n\t\t\"more.\") + \"\\n\\n\"\n\n\tout += md.H2(\"Take part\")\n\tout += ui.Action(\"\\U0001F91D Vouch\", \"Vouch\", \"target\", \"\", \"reason\", \"\") +\n\t\t\" · \" + ui.Action(\"\\U0001F4B0 Withdraw a refunded bond\", \"Withdraw\") + \"\\n\\n\"\n\tout += md.Italic(\"Coins sent with Vouch are locked as a bond on that vouch and come \" +\n\t\t\"back when you revoke it. There is no slashing: deciding that a vouch was a lie \" +\n\t\t\"needs an arbiter, and choosing one is the whole design question.\") + \"\\n\"\n\n\treturn out\n}\n\nfunc board() string {\n\trows := graph.Leaderboard(BoardSize)\n\tif len(rows) == 0 {\n\t\treturn ui.Empty(\"Nobody has been vouched for yet.\")\n\t}\n\tt := ui.NewTable(\"\", \"address\", \"vouchers\", \"bonded\")\n\tfor i, r := range rows {\n\t\tt.Row(\n\t\t\tui.Podium(i),\n\t\t\tmd.Link(ui.AddrText(r.Addr), vo.AddrURL(realmPath, r.Addr)),\n\t\t\tstrconv.Itoa(r.Score),\n\t\t\tnum.GNOTf(r.Bonded),\n\t\t)\n\t}\n\treturn t.String()\n}\n\nfunc renderAddr(raw string) string {\n\taddr := address(raw)\n\tif !addr.IsValid() {\n\t\treturn md.H1(\"Vouch\") + \"Not an address: \" + ui.Inline(raw)\n\t}\n\n\tout := md.H1(\"Vouch for \" + ui.AddrText(addr))\n\tout += ui.AddrFull(addr) + \"\\n\\n\"\n\n\tscore := graph.ScoreOf(addr)\n\tt := ui.NewTable(\"vouchers\", \"bonded on them\", \"trusted at 2\", \"awaiting withdrawal\")\n\tt.Row(\n\t\tstrconv.Itoa(score),\n\t\tnum.GNOTf(graph.BondedFor(addr)),\n\t\tyesno(graph.IsTrusted(addr, 2)),\n\t\tnum.GNOTf(graph.Owed(addr)),\n\t)\n\tout += t.String()\n\n\tout += md.H2(\"Vouched for by\")\n\tout += inbound(addr)\n\n\tout += md.H2(\"Vouches for\")\n\tout += outbound(addr)\n\n\tout += \"\\n\" + ui.Action(\"\\U0001F91D Vouch for this address\", \"Vouch\",\n\t\t\"target\", addr.String(), \"reason\", \"\") +\n\t\t\" · \" + ui.Action(\"\\U0000274C Revoke mine\", \"Revoke\", \"target\", addr.String()) + \"\\n\"\n\treturn out\n}\n\nfunc inbound(addr address) string {\n\tfrom := graph.VouchedBy(addr)\n\tif len(from) == 0 {\n\t\treturn ui.Empty(\"Nobody vouches for this address.\")\n\t}\n\tt := ui.NewTable(\"voucher\", \"reason\", \"bond\", \"mutual\", \"since\")\n\tfor _, f := range from {\n\t\tv, ok := graph.Get(f, addr)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tt.Row(\n\t\t\tmd.Link(ui.AddrText(f), vo.AddrURL(realmPath, f)),\n\t\t\tui.Cell(v.Reason),\n\t\t\tnum.GNOTf(v.Bond),\n\t\t\tyesno(graph.Mutual(f, addr)),\n\t\t\tstrconv.FormatInt(v.At, 10),\n\t\t)\n\t}\n\treturn t.String()\n}\n\nfunc outbound(addr address) string {\n\tto := graph.VouchesOf(addr)\n\tif len(to) == 0 {\n\t\treturn ui.Empty(\"This address vouches for nobody.\")\n\t}\n\tt := ui.NewTable(\"for\", \"reason\", \"bond\", \"their vouchers\")\n\tfor _, target := range to {\n\t\tv, ok := graph.Get(addr, target)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tt.Row(\n\t\t\tmd.Link(ui.AddrText(target), vo.AddrURL(realmPath, target)),\n\t\t\tui.Cell(v.Reason),\n\t\t\tnum.GNOTf(v.Bond),\n\t\t\tstrconv.Itoa(graph.ScoreOf(target)),\n\t\t)\n\t}\n\treturn t.String()\n}\n\nfunc yesno(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}\n"},{"name":"vouch.gno","body":"// Package vouch is a web of trust other realms can gate on: one address\n// vouches for another, in writing, optionally with GNOT locked behind it.\n//\n// The one call that matters is a plain read:\n//\n//\timport \"gno.land/r/moul/x/social/vouch/v0\"\n//\n//\tfunc Claim(cur realm) {\n//\t\tif !vouch.IsTrusted(cur.Previous().Address(), 2) {\n//\t\t\tpanic(\"get two people to vouch for you first\")\n//\t\t}\n//\t\t…\n//\t}\n//\n// [IsTrusted] takes no cur realm on purpose. A read with no realm token is\n// borrowed: gno opens no realm frame for it, so it costs the caller nothing\n// beyond the read and cannot be tricked into acting as anybody. Nothing here\n// branches on who is asking, and no read in this realm ever will: the answer\n// to \"is this address trusted\" must not depend on who wants to know.\n//\n// # What it does, and what it refuses to do\n//\n// [Vouch] is payable. Any coins sent with it are locked as a bond on that\n// vouch, which is the voucher putting their own money where their claim is. A\n// bond is optional and zero is the ordinary case. [Revoke] takes the vouch\n// back and credits the bond to the voucher, who collects it with [Withdraw].\n//\n// There is no slashing in v0 and that is the interesting half. Slashing needs\n// an arbiter, somebody who decides a vouch was a lie, and every candidate is\n// a design question rather than a feature: a DAO vote is a popularity contest,\n// a challenge market pays whoever is loudest, an oracle is one key that can\n// confiscate anybody's money. The bond is still worth having without it,\n// because an illiquid deposit is a cost a hundred throwaway addresses cannot\n// all pay at once.\n//\n// # No token\n//\n// This realm issues none, deliberately. A transferable vouch is a bought\n// reputation, and the moment a vouch can be sold the score stops measuring\n// what it says it measures. The bond is GNOT: value at risk, without being a\n// market in trust itself. The README says what would change the answer.\npackage vouch\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime\"\n\t\"strconv\"\n\n\t\"gno.land/p/moul/x/envelope/v0\"\n\tvo \"gno.land/p/moul/x/social/vouch/v0\"\n)\n\n// realmPath is this realm's own path, the one its gnomod.toml module line\n// declares. It is written out rather than read from the frame, because every\n// read this realm exports is borrowed and would report whichever realm called\n// it, building every link against somebody else's page.\nconst realmPath = \"gno.land/r/moul/x/social/vouch/v0\"\n\n// denom is the only coin a bond can be posted in.\nconst denom = \"ugnot\"\n\n// BoardSize is how many addresses the index page ranks.\nconst BoardSize = 10\n\n// graph holds every vouch and the refund ledger. A redeploy would wipe it\n// while leaving the bonded coins at this address, which is why this realm is\n// not private (see gnomod.toml).\nvar graph = vo.NewGraph()\n\n// Vouch records that the caller stands behind target, for the stated reason.\n//\n// It is payable: coins sent with the call are locked as a bond on this vouch\n// and are returned by [Revoke], never by anything else. Sending nothing is\n// fine and is the ordinary case.\n//\n// Vouching again for the same address UPDATES the reason and ADDS to the\n// bond. It does not count twice: the score this realm exists to publish is a\n// count of people, so a second transaction from the same address buys\n// precisely nothing. Vouching for yourself is refused.\nfunc Vouch(cur realm, target address, reason string) {\n\twho, userCall := caller(cur)\n\tbond := bondOf(userCall)\n\n\tupdated, err := graph.Record(who, target, reason, bond, runtime.ChainHeight())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tevent := \"Vouch\"\n\tif updated {\n\t\tevent = \"Revouch\"\n\t}\n\tchain.Emit(event, \"from\", who.String(), \"for\", target.String(),\n\t\t\"bond\", strconv.FormatInt(bond, 10))\n}\n\n// Revoke withdraws the caller's vouch for target and credits any bond back to\n// them. The coins do not move here: call [Withdraw] to collect them.\n//\n// Splitting it in two is the pull-payment pattern. A realm that sent on revoke\n// would be handing control to the recipient in the middle of its own state\n// change, and a recipient that refuses the coins could make revoking\n// impossible.\nfunc Revoke(cur realm, target address) int64 {\n\twho, _ := caller(cur)\n\trefund, err := graph.Revoke(who, target)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tchain.Emit(\"Revoke\", \"from\", who.String(), \"for\", target.String(),\n\t\t\"refund\", strconv.FormatInt(refund, 10))\n\treturn refund\n}\n\n// Withdraw pays the caller every bond their revoked vouches freed, and\n// returns the amount sent.\n//\n// The credit is zeroed before the coins leave, so a recipient that calls\n// straight back in finds nothing to take.\nfunc Withdraw(cur realm) int64 {\n\twho, _ := caller(cur)\n\tamount, err := graph.Withdraw(who)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tbnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tbnk.SendCoins(cur.Address(), who, chain.NewCoins(chain.NewCoin(denom, amount)))\n\tchain.Emit(\"Withdraw\", \"to\", who.String(), \"amount\", strconv.FormatInt(amount, 10))\n\treturn amount\n}\n\n// IsTrusted reports whether addr is vouched for by at least min distinct\n// addresses. This is the gate, and it is one line at the call site.\n//\n// A min below one is read as one: a gate that lets everybody through is a bug\n// in the caller rather than an answer this realm will agree to.\n//\n// It cannot tell you that the vouchers are distinct people. Two addresses\n// vouching for each other both reach a score of one, which [Mutual] exposes\n// and which is the reason to ask for more than one.\nfunc IsTrusted(addr address, min int) bool { return graph.IsTrusted(addr, min) }\n\n// ScoreOf is how many distinct addresses vouch for addr.\nfunc ScoreOf(addr address) int { return graph.ScoreOf(addr) }\n\n// BondedFor is the total ugnot locked on addr by everyone vouching for them.\nfunc BondedFor(addr address) int64 { return graph.BondedFor(addr) }\n\n// VouchedBy is every address that vouches for addr, sorted.\nfunc VouchedBy(addr address) []address { return graph.VouchedBy(addr) }\n\n// VouchesOf is every address addr vouches for, sorted.\nfunc VouchesOf(addr address) []address { return graph.VouchesOf(addr) }\n\n// Mutual reports whether a and b vouch for each other, which is the cheapest\n// sybil shape and therefore worth discounting.\nfunc Mutual(a, b address) bool { return graph.Mutual(a, b) }\n\n// ReasonFrom is what from wrote about target, or the empty string. It is raw\n// caller text: escape it before rendering it anywhere.\nfunc ReasonFrom(from, target address) string { return graph.ReasonFrom(from, target) }\n\n// BondFrom is what from locked on target, or zero.\nfunc BondFrom(from, target address) int64 { return graph.BondFrom(from, target) }\n\n// Count is how many vouches exist.\nfunc Count() int { return graph.Count() }\n\n// People is how many addresses have at least one vouch for them.\nfunc People() int { return graph.People() }\n\n// Owed is what addr can collect with [Withdraw].\nfunc Owed(addr address) int64 { return graph.Owed(addr) }\n\n// TotalBonded is everything locked on vouches that still stand.\nfunc TotalBonded() int64 { return graph.TotalBonded() }\n\n// TotalOwed is every revoked bond nobody has collected yet. This realm holds\n// TotalBonded plus TotalOwed on behalf of other people.\nfunc TotalOwed() int64 { return graph.TotalOwed() }\n\n// Badge is the one-line trust mark for addr, for a host realm that wants to\n// show what its gate just read. Like [IsTrusted] it is a borrowed read and\n// takes no realm token.\nfunc Badge(addr address) string {\n\treturn vo.Badge(realmPath, addr, graph.ScoreOf(addr), graph.BondedFor(addr))\n}\n\n// bondOf reads the coins attached to this call, and only when the chain\n// credited them to THIS realm.\n//\n// The envelope is the transaction's, not the frame's: a realm that was itself\n// paid and then calls here would report coins sitting at its own address, and\n// crediting them would let it bond money this realm never received. A realm\n// may vouch, with no bond; a realm may not vouch while holding somebody's\n// payment, and saying so loudly beats silently reading the bond as zero.\n//\n// It takes the answer rather than the frame because a realm argument in this\n// package must be named cur, which would make this a crossing function.\nfunc bondOf(userCall bool) int64 {\n\tif userCall {\n\t\treturn envelope.Amount(denom)\n\t}\n\tif !envelope.IsEmpty() {\n\t\tpanic(\"a realm cannot forward a bond: those coins were credited to the realm the user paid, not to this one\")\n\t}\n\treturn 0\n}\n\n// caller is the address that called us, checked the one way that is safe,\n// plus whether it reached us as a direct user transaction.\n//\n// Both come from here so the realm reads cur.Previous() in exactly one place,\n// the one guarded by cur.IsCurrent().\nfunc caller(cur realm) (who address, userCall bool) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm: cur is not the live crossing frame\")\n\t}\n\tprev := cur.Previous()\n\treturn prev.Address(), prev.IsUserCall()\n}\n"},{"name":"vouch_test.gno","body":"package vouch\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\n\tvo \"gno.land/p/moul/x/social/vouch/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n\n\trealmAddr = chain.PackageAddress(realmPath)\n)\n\n// reset clears realm state. Realm globals live for the whole test binary, so\n// every test that reads a score, a bond or a refund starts here.\nfunc reset() { graph = vo.NewGraph() }\n\n// fund simulates the coins attached to the next call: the runtime credits the\n// realm's address first, and the crossing function then reads the envelope off\n// the transaction. fund(0) clears it, which is the ordinary unbonded case.\n//\n// testing.SetRealm is call-frame scoped, so the caller still switches account\n// inline in the test body right before crossing.\nfunc fund(amount int64) {\n\tif amount \u003c= 0 {\n\t\ttesting.SetOriginSend(chain.Coins{})\n\t\treturn\n\t}\n\ttesting.IssueCoins(realmAddr, chain.Coins{{denom, amount}})\n\ttesting.SetOriginSend(chain.Coins{{denom, amount}})\n}\n\nfunc balanceOf(addr address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(addr).AmountOf(denom)\n}\n\n// The score counts people, which is the property every caller of IsTrusted\n// depends on: a repeated vouch does not raise it, a revoke lowers it.\nfunc TestScoreCountsPeopleAndNotVouches(cur realm, t *testing.T) {\n\treset()\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"worked with them for two years\")\n\tuassert.Equal(t, 1, ScoreOf(alice))\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"still true\")\n\tuassert.Equal(t, 1, ScoreOf(alice), \"one person is one point, however often they say it\")\n\tuassert.Equal(t, \"still true\", ReasonFrom(bob, alice), \"the reason was updated\")\n\tuassert.Equal(t, 1, Count())\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVouch(cross(cur), alice, \"we shipped together\")\n\tuassert.Equal(t, 2, ScoreOf(alice))\n\tuassert.Equal(t, 1, People(), \"one address has been vouched for\")\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tRevoke(cross(cur), alice)\n\tuassert.Equal(t, 1, ScoreOf(alice), \"revoking lowers the score\")\n\tuassert.Equal(t, 1, Count())\n}\n\nfunc TestVouchRefusals(cur realm, t *testing.T) {\n\treset()\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"cannot vouch for itself\", func() {\n\t\tVouch(cross(cur), alice, \"I am great\")\n\t})\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"reason is empty\", func() {\n\t\tVouch(cross(cur), bob, \"   \")\n\t})\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"reason is empty\", func() {\n\t\tVouch(cross(cur), bob, \"one line\\nonly\")\n\t})\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"no such vouch\", func() {\n\t\tRevoke(cross(cur), bob)\n\t})\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() {\n\t\tWithdraw(cross(cur))\n\t})\n\n\tuassert.Equal(t, 0, Count())\n}\n\n// The bond follows the vouch in both directions, and the coins only move on\n// Withdraw. Balances are asserted here because the bank does not carry over\n// between test functions.\nfunc TestTheBondIsLockedUntilTheVouchIsRevoked(cur realm, t *testing.T) {\n\treset()\n\tbefore := balanceOf(bob)\n\n\tfund(1_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"1 GNOT says this is a real person\")\n\tuassert.Equal(t, int64(1_000_000), BondedFor(alice))\n\tuassert.Equal(t, int64(1_000_000), TotalBonded())\n\tuassert.Equal(t, int64(0), Owed(bob), \"nothing is owed while the vouch stands\")\n\n\t// Vouching again adds to the bond rather than replacing it.\n\tfund(500_000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"doubling down\")\n\tuassert.Equal(t, int64(1_500_000), BondedFor(alice))\n\tuassert.Equal(t, int64(1_500_000), BondFrom(bob, alice))\n\n\t// Revoking moves the bond to the ledger and nothing else.\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\trefund := Revoke(cross(cur), alice)\n\tuassert.Equal(t, int64(1_500_000), refund)\n\tuassert.Equal(t, int64(0), BondedFor(alice))\n\tuassert.Equal(t, int64(1_500_000), Owed(bob))\n\tuassert.Equal(t, int64(1_500_000), TotalOwed())\n\tuassert.Equal(t, before, balanceOf(bob), \"revoking sends nothing\")\n\n\t// Withdrawing is what moves the coins, once.\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tgot := Withdraw(cross(cur))\n\tuassert.Equal(t, int64(1_500_000), got)\n\tuassert.Equal(t, before+1_500_000, balanceOf(bob), \"the bond came back\")\n\tuassert.Equal(t, int64(0), Owed(bob))\n\tuassert.Equal(t, int64(0), TotalOwed())\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() {\n\t\tWithdraw(cross(cur))\n\t})\n\tuassert.Equal(t, before+1_500_000, balanceOf(bob), \"and only once\")\n}\n\n// A bond belongs to whoever posted it, not to whoever it was posted on.\nfunc TestOnlyTheVoucherGetsTheBondBack(cur realm, t *testing.T) {\n\treset()\n\n\tfund(700_000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"my money, my claim\")\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"no such vouch\", func() {\n\t\tRevoke(cross(cur), bob)\n\t})\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tuassert.AbortsContains(t, cur, \"nothing to withdraw\", func() {\n\t\tWithdraw(cross(cur))\n\t})\n\tuassert.Equal(t, int64(700_000), BondedFor(alice), \"the bond is untouched\")\n}\n\nfunc TestIsTrustedIsTheGate(cur realm, t *testing.T) {\n\treset()\n\n\tuassert.False(t, IsTrusted(alice, 1), \"nobody starts trusted\")\n\tuassert.False(t, IsTrusted(alice, 0), \"a zero min does not open the gate for nobody\")\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"one\")\n\tuassert.True(t, IsTrusted(alice, 1))\n\tuassert.False(t, IsTrusted(alice, 2))\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVouch(cross(cur), alice, \"two\")\n\tuassert.True(t, IsTrusted(alice, 2))\n\tuassert.False(t, IsTrusted(alice, 3))\n\n\t// The cheapest sybil shape, and the reason a real gate asks for two.\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tVouch(cross(cur), bob, \"back at you\")\n\tuassert.True(t, Mutual(alice, bob))\n\tuassert.True(t, IsTrusted(bob, 1), \"a mutual pair passes a gate set at one\")\n\tuassert.False(t, IsTrusted(bob, 2))\n}\n\nfunc TestTheTwoDirections(cur realm, t *testing.T) {\n\treset()\n\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tVouch(cross(cur), bob, \"a to b\")\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tVouch(cross(cur), carol, \"a to c\")\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), carol, \"b to c\")\n\n\tuassert.Equal(t, 2, len(VouchesOf(alice)))\n\tuassert.Equal(t, 0, len(VouchedBy(alice)))\n\tuassert.Equal(t, 2, len(VouchedBy(carol)))\n\tuassert.Equal(t, 0, len(VouchesOf(carol)))\n\tuassert.Equal(t, \"b to c\", ReasonFrom(bob, carol))\n\tuassert.Equal(t, \"\", ReasonFrom(carol, bob))\n\tuassert.Equal(t, int64(0), BondFrom(alice, bob), \"an unbonded vouch is worth nothing\")\n}\n\n// Badge is a borrowed read: a host realm calls it with no realm token and\n// gets a line pointing back at this realm's page.\nfunc TestBadge(cur realm, t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Badge(alice), \"not vouched for\"))\n\n\tfund(2_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"one\")\n\n\tgot := Badge(alice)\n\tuassert.True(t, strings.Contains(got, \"1 voucher]\"), got)\n\tuassert.True(t, strings.Contains(got, \"2 GNOT bonded\"), got)\n\tuassert.True(t, strings.Contains(got, \"/r/moul/x/social/vouch/v0:addr/\"+alice.String()), got)\n}\n\n// TestRender uses uassert rather than an Example because every view contains\n// consecutive blank lines, which gno collapses inside an // Output: block.\nfunc TestRender(cur realm, t *testing.T) {\n\treset()\n\n\tfund(3_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVouch(cross(cur), alice, \"a reason with [a link](x) and a | pipe\")\n\tfund(0)\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVouch(cross(cur), alice, \"second voucher\")\n\n\tindex := Render(\"\")\n\tuassert.True(t, strings.Contains(index, \"| 2 | 1 | 3 GNOT | 0 GNOT |\"),\n\t\t\"vouches, people, bonded, owed: \"+index)\n\tuassert.True(t, strings.Contains(index, `import \"`+realmPath+`\"`), \"the index is the gate doc\")\n\tuassert.True(t, strings.Contains(index, \"func=Vouch\"), \"the index offers the transaction\")\n\tuassert.True(t, strings.Contains(index, \"\\U0001F947\"), \"the board has a podium: \"+index)\n\n\tpage := Render(\"addr/\" + alice.String())\n\tuassert.True(t, strings.Contains(page, alice.String()), \"the page names the address\")\n\tuassert.True(t, strings.Contains(page, \"a reason with \\\\[a link\\\\]\\\\(x\\\\) and a \\\\| pipe\"),\n\t\t\"the reason is escaped where it is shown: \"+page)\n\tuassert.True(t, strings.Contains(page, \"func=Revoke\"))\n\n\t// The other direction of the same edge, from the voucher's page.\n\tvouchers := Render(\"addr/\" + bob.String())\n\tuassert.True(t, strings.Contains(vouchers, \"This address vouches for nobody.\") == false,\n\t\t\"bob vouches for alice: \"+vouchers)\n\tuassert.True(t, strings.Contains(vouchers, \"Nobody vouches for this address.\"))\n\n\tuassert.Equal(t, \"# Vouch\\nNot an address: nope\", Render(\"addr/nope\"))\n\tuassert.True(t, strings.HasPrefix(Render(\"elsewhere\"), \"# Not found\"))\n\n\t// An empty graph says so rather than rendering an empty table.\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"\"), \"Nobody has been vouched for yet.\"))\n}\n\nfunc TestRenderOfAnUnknownAddress(cur realm, t *testing.T) {\n\treset()\n\tpage := Render(\"addr/\" + carol.String())\n\tuassert.True(t, strings.Contains(page, \"Nobody vouches for this address.\"), page)\n\tuassert.True(t, strings.Contains(page, \"This address vouches for nobody.\"), page)\n\tuassert.True(t, strings.Contains(page, \"| 0 | 0 GNOT | no | 0 GNOT |\"), page)\n}\n"}]},"send":"","max_deposit":"13000000ugnot"}],"fee":{"gas_wanted":"513156600","gas_fee":"1539469ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"AjZyqpH4vJ3WLLVeLtRl+F2StxRT+LawNoGVosjVwS/F"},"signature":"KazLdcgmN5R5iT7jGkuDA1hOQdJkqEB4jfE6sIhN981TGmIrgyJ6mESGDklBOpw/13l+5BCFB5U0SPoyB0upjQ=="}],"memo":""},"metadata":{"timestamp":"1791257700"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"supplEAFIqI060H7uDcj4P1sQENfbvXdzGx9UWsaJQAZjDNApA4P8fYLRIxP0XDLsoCP1J7HGcNy7U0I0czlQA=="}],"memo":""},"metadata":{"timestamp":"1791257701"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"ZbdYrqpgIsK2VTbvPNdLL5lnzoes/2JyZ0Pzoa4kjQwfiXgh9oiM91TOYoS7g17mlxCIeOpYqDJiqA/m3ZiJPA=="}],"memo":""},"metadata":{"timestamp":"1791555776"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402560","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"vq9xiIuLoQLb+q1xuXtkND3n3DiSzStL5zeJxfBWtqVsKMKvplFBziztoAockhfcEMfh0lcOIg7ezInPtSkRLg=="}],"memo":""},"metadata":{"timestamp":"1791555838"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"toolbox","path":"gno.land/p/moul/toolbox/v0","files":[{"name":"README.md","body":"# `gno.land/p/moul/toolbox/v0`\n\n**The directory model behind [r/moul/toolbox](https://gno.land/r/moul/toolbox)**: `Tool`,\n`Catalog`, `BasePath`, `SlugOf`, `NewQuery`, `Index`, `Card`, `Nav`.\n\n```go\nimport \"gno.land/p/moul/toolbox/v0\"\n\nvar c toolbox.Catalog\nc.Set(toolbox.Tool{\n    Slug:  \"usernames\",\n    Path:  \"gno.land/r/moul/toolbox/usernames\",\n    Title: \"Usernames\",\n    Desc:  \"Resolve a username to an address, or an address to a username.\",\n    Tags:  []string{\"identity\", \"read\"},\n})\n\ntoolbox.Index(c.List())                       // → the markdown table of the directory\ntoolbox.SlugOf(\"gno.land/r/moul/toolbox\",\n               \"gno.land/r/moul/toolbox/usernames\") // → \"usernames\"\ntoolbox.NewQuery(\"lookup\").Field(\"q\", \"username or g1 address\").String()\n```\n\nA toolbox is a hub realm listing tools, each tool a realm of its own one level below it. The\nhub is `private = true`, which costs it the ability to be imported at all: the type checker\nrefuses any realm importing a private one. So the hub and its tools cannot share a single line\nof code by importing each other, and everything they must agree about lives here instead.\n\n**Nesting is checked on the base path, not the full one.**\n[`p/moul/nestedpkg`](https://gno.land/p/moul/nestedpkg/v0) decides \"is the caller below me\" by\nprefixing one package path with the other. That is exactly right once neither side carries a\nversion, which is the case for a private hub, and it breaks the moment either does:\n`gno.land/r/moul/toolbox/usernames/v0` does not begin with `gno.land/r/moul/toolbox/v0`.\n`BasePath` strips a trailing `/vN` so the comparison is about the family rather than the\nversion, and `IsUnder` and `SlugOf` are built on it: a hub and a tool may each be versioned or\nnot, independently, and all four combinations answer the same. A sibling whose name merely\nstarts with the hub's (`toolboxtwo`) is not under it, because the comparison is against the\nbase plus a slash.\n\nFive behaviours worth knowing before you use it:\n\n- **`Tool` is strings all the way down.** A tool that registers itself into a public hub hands\n  these values across a realm boundary, and a struct the caller allocated stays the caller's\n  object: persisting it panics with `cannot persist object from the private realm`. Scalars are\n  copied, so the hub owns what it stores whichever side built the entry.\n- **`Catalog` is a slug-keyed B+ tree (fanout 32), not a sorted slice.** The slice is cheaper to\n  *read* at this size: at n = 100 one cold operation costs 92,571 gas against a fanout-128\n  tree's 230,754 (`gnobench`, gno master `1fc4c140e`, 2026-09-29). It is still wrong. A slice is\n  one persisted object, so every write rewrites all of it, O(n) per transaction and O(n^2) over n\n  of them, which is free for a compiled-in catalog and is the whole bill for a hub that accepts\n  registration. Removing is worse: shortening a slice in place keeps the peak allocation charged\n  and refunds no deposit. Fanout 32 rather than 128 because a tool can be unregistered and wide\n  nodes lose most on removal. Slug order comes free from the tree rather than from a hand-rolled\n  binary search.\n- **A `Catalog` is a handle.** Copying one shares the directory, the way copying a map does, and\n  a write through either copy is seen through both. A copy of a zero value that was never\n  written is a separate empty catalog.\n- **`Catalog` never aliases a `Tool.Tags` slice**, in either direction: it copies on the way in\n  so the caller of `Set` keeps no handle on stored state, and on the way out so\n  `c.List()[0].Tags[0] = \"x\"` cannot reach the directory.\n- **`NewQuery` builds a read, never a write.** It emits gnoweb's `\u003cgno-form path=\"...\"\u003e`, whose\n  submission redirects to one of the realm's own `Render` paths with the fields as query\n  parameters. Nothing is signed and no transaction is built. A form that calls a function is a\n  different element (`\u003cgno-form exec=\"Fn\"\u003e`) and is deliberately not this one with a flag.\n\nEvery string is escaped exactly once, with the helper for the slot it lands in, and the\nescapers are not idempotent: `md.Link` and `md.InlineCode` sanitize their own arguments, so\n`Index` builds its title link by hand (`ui.Cell` for link text inside a cell, `md.EscapeURL`\nfor the href) rather than wrapping twice. Attribute values go through an\nHTML escaper: gnoweb parses forms with a real tokenizer, so an unescaped quote ends the\nattribute and whatever follows becomes further attributes of the same tag.\n"},{"name":"catalog.gno","body":"package toolbox\n\nimport \"gno.land/p/nt/bptree/v0\"\n\n// Catalog is the directory itself: tools keyed by slug, ordered by it.\n//\n// The zero value is an empty, usable catalog. A Catalog is a HANDLE: copying\n// one shares the directory, and a write through either copy is seen through\n// both, the way copying a map does. A copy of a zero value that was never\n// written is a separate empty catalog.\n//\n// # Why a tree and not a sorted slice\n//\n// A sorted slice is cheaper to READ at the size a directory actually reaches:\n// at n = 100 one cold operation costs 92,571 gas against a fanout-128 tree's\n// 230,754 (`gnobench`, gno master 1fc4c140e, 2026-09-29). It is still the\n// wrong structure, for two reasons that outlive the gas.\n//\n// A slice is ONE persisted object, so every write rewrites all of it: O(n) per\n// transaction and O(n^2) over n of them. That costs nothing for a hub whose\n// catalog is compiled in and never written after deploy, and it is the whole\n// bill for one that accepts registration, which is the other half of what this\n// package is for. Removing is worse than writing: shortening a slice in place\n// keeps the peak allocation charged and refunds no deposit at all.\n//\n// And the ordering comes free. A slug-keyed tree iterates in slug order, which\n// is the order every listing here wants, rather than a hand-rolled binary\n// search that has to be kept correct.\ntype Catalog struct {\n\ts *state\n}\n\n// state is everything a Catalog holds, behind one pointer so that a copy of\n// the handle cannot split the tree from the counter that describes it.\n//\n// Embedding [bptree.BPTree] by value was the first shape here and it is wrong\n// for exactly that reason: the tree's root is a pointer and its size is an int,\n// so `b := a; b.Set(x)` would thread the new node onto the tree both of them\n// see while incrementing only b's size. a.Len() would say 1 while a.Get(x)\n// found the entry. One pointer, or two readers of the same directory disagree\n// about how big it is.\ntype state struct {\n\ttools *bptree.BPTree\n}\n\n// Fanout is the B+ tree fanout this package uses.\n//\n// 32 rather than 128 because a tool can be unregistered, and wide nodes lose\n// most on removal: a removal shifts every later value in its leaf and rewrites\n// each one. Same choice, and the same reason, as\n// [gno.land/p/moul/kit/index](/p/moul/kit/index/v0).\nconst Fanout = 32\n\n// New returns an empty catalog. It is the zero value, spelled out for a caller\n// who prefers a constructor.\nfunc New() *Catalog { return \u0026Catalog{} }\n\n// init materialises the state. Called by every mutating method, so the zero\n// value works without a constructor. The tree is created with the state, so a\n// non-nil state always has one.\nfunc (c *Catalog) init() {\n\tif c.s == nil {\n\t\tc.s = \u0026state{tools: bptree.NewBPTreeN(Fanout)}\n\t}\n}\n\n// Set inserts t, replacing any tool already under its slug.\n//\n// Replacing rather than refusing is what makes a hub's init idempotent: a\n// compiled-in catalog is rebuilt from source on every redeploy, and a second\n// Set of the same slug is a corrected description rather than a collision.\nfunc (c *Catalog) Set(t Tool) error {\n\tif err := t.Validate(); err != nil {\n\t\treturn err\n\t}\n\tc.init()\n\tc.s.tools.Set(t.Slug, copyTool(t))\n\treturn nil\n}\n\n// Remove deletes the tool under slug. It returns [ErrUnknownSlug] when there\n// is none, so a realm removing an entry it believes in learns that it is gone.\nfunc (c *Catalog) Remove(slug string) error {\n\tif c.s == nil {\n\t\treturn ErrUnknownSlug\n\t}\n\tif _, removed := c.s.tools.Remove(slug); !removed {\n\t\treturn ErrUnknownSlug\n\t}\n\treturn nil\n}\n\n// Get returns the tool under slug.\nfunc (c *Catalog) Get(slug string) (Tool, bool) {\n\tif c.s == nil {\n\t\treturn Tool{}, false\n\t}\n\tv := c.s.tools.Get(slug)\n\tif v == nil {\n\t\treturn Tool{}, false\n\t}\n\treturn copyTool(v.(Tool)), true\n}\n\n// Has reports whether slug is in the catalog.\nfunc (c *Catalog) Has(slug string) bool {\n\treturn c.s != nil \u0026\u0026 c.s.tools.Has(slug)\n}\n\n// Len is how many tools the catalog holds.\nfunc (c *Catalog) Len() int {\n\tif c.s == nil {\n\t\treturn 0\n\t}\n\treturn c.s.tools.Size()\n}\n\n// List returns every tool, in slug order.\nfunc (c *Catalog) List() []Tool {\n\tif c.s == nil {\n\t\treturn nil\n\t}\n\tout := make([]Tool, 0, c.s.tools.Size())\n\tc.s.tools.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tout = append(out, copyTool(v.(Tool)))\n\t\treturn false\n\t})\n\treturn out\n}\n\n// ByTag returns every tool carrying tag, in slug order. An empty tag matches\n// nothing rather than everything: it is almost always an unset field.\nfunc (c *Catalog) ByTag(tag string) []Tool {\n\tif tag == \"\" || c.s == nil {\n\t\treturn nil\n\t}\n\tvar out []Tool\n\tc.s.tools.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tif t := v.(Tool); t.HasTag(tag) {\n\t\t\tout = append(out, copyTool(t))\n\t\t}\n\t\treturn false\n\t})\n\treturn out\n}\n\n// Tags returns every tag used by any tool, each once, in first-seen order\n// within slug order. Deterministic, which iterating a map would not be.\nfunc (c *Catalog) Tags() []string {\n\tif c.s == nil {\n\t\treturn nil\n\t}\n\tvar out []string\n\tc.s.tools.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\tfor _, tag := range v.(Tool).Tags {\n\t\t\tif !contains(out, tag) {\n\t\t\t\tout = append(out, tag)\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n\treturn out\n}\n\n// copyTool deep-copies the one field that is not a scalar.\n//\n// A Tool is a value, so handing one out already copies Slug, Path, Title and\n// Desc. Tags is a slice: the struct copy duplicates the header and shares the\n// backing array, so `c.List()[0].Tags[0] = \"x\"` would reach into the catalog\n// and change what every later read returns. Copied on the way in as well as on\n// the way out, or the caller of Set keeps a handle on stored state.\nfunc copyTool(t Tool) Tool {\n\tif t.Tags == nil {\n\t\treturn t\n\t}\n\ttags := make([]string, len(t.Tags))\n\tcopy(tags, t.Tags)\n\tt.Tags = tags\n\treturn t\n}\n\nfunc contains(haystack []string, needle string) bool {\n\tfor _, s := range haystack {\n\t\tif s == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"},{"name":"catalog_test.gno","body":"package toolbox\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc tool(slug string, tags ...string) Tool {\n\treturn Tool{\n\t\tSlug:  slug,\n\t\tPath:  \"gno.land/r/moul/toolbox/\" + slug + \"/v0\",\n\t\tTitle: slug,\n\t\tDesc:  \"the \" + slug + \" tool\",\n\t\tTags:  tags,\n\t}\n}\n\nfunc slugs(tools []Tool) []string {\n\tout := make([]string, len(tools))\n\tfor i, t := range tools {\n\t\tout[i] = t.Slug\n\t}\n\treturn out\n}\n\n// TestCatalogCopyIsAHandle is the shape bug the state pointer exists to stop.\n// With the tree embedded by value, the root is a pointer and the size an int,\n// so a write through a copy threaded the node onto the tree both of them saw\n// while incrementing only the copy's counter: a.Len() said 1 while a.Get found\n// the second entry.\nfunc TestCatalogCopyIsAHandle(t *testing.T) {\n\ta := New()\n\tuassert.NoError(t, a.Set(tool(\"amm\")))\n\n\tb := *a\n\tuassert.NoError(t, b.Set(tool(\"usernames\")))\n\n\tuassert.Equal(t, 2, a.Len())\n\tuassert.Equal(t, 2, b.Len())\n\tuassert.Equal(t, a.Len(), len(a.List()))\n\tuassert.True(t, a.Has(\"usernames\"))\n\n\tuassert.NoError(t, b.Remove(\"amm\"))\n\tuassert.Equal(t, 1, a.Len())\n\tuassert.False(t, a.Has(\"amm\"))\n}\n\n// TestCatalogCopyOfAZeroValueIsSeparate: nothing has been allocated yet, so\n// there is no directory to share. Stated because it is the one case where\n// copying does NOT alias, and a reader would otherwise have to guess.\nfunc TestCatalogCopyOfAZeroValueIsSeparate(t *testing.T) {\n\tvar a Catalog\n\tb := a\n\tuassert.NoError(t, b.Set(tool(\"usernames\")))\n\n\tuassert.Equal(t, 0, a.Len())\n\tuassert.Equal(t, 1, b.Len())\n}\n\nfunc TestCatalogZeroValue(t *testing.T) {\n\tvar c Catalog\n\tuassert.Equal(t, 0, c.Len())\n\tuassert.Equal(t, 0, len(c.List()))\n\tuassert.False(t, c.Has(\"usernames\"))\n\tuassert.ErrorIs(t, c.Remove(\"usernames\"), ErrUnknownSlug)\n}\n\n// TestCatalogSortsBySlug checks the only ordering guarantee the type makes,\n// against an insertion order that is reverse, interleaved and duplicated.\nfunc TestCatalogSortsBySlug(t *testing.T) {\n\tvar c Catalog\n\tfor _, s := range []string{\"zones\", \"amm\", \"usernames\", \"base64\", \"amm\"} {\n\t\tuassert.NoError(t, c.Set(tool(s)))\n\t}\n\tuassert.Equal(t, 4, c.Len())\n\twant := []string{\"amm\", \"base64\", \"usernames\", \"zones\"}\n\tgot := slugs(c.List())\n\tuassert.Equal(t, len(want), len(got))\n\tfor i := range want {\n\t\tuassert.Equal(t, want[i], got[i])\n\t}\n}\n\nfunc TestCatalogSetReplaces(t *testing.T) {\n\tvar c Catalog\n\tuassert.NoError(t, c.Set(tool(\"usernames\")))\n\tupdated := tool(\"usernames\")\n\tupdated.Desc = \"resolve a username or an address\"\n\tuassert.NoError(t, c.Set(updated))\n\n\tuassert.Equal(t, 1, c.Len())\n\tgot, ok := c.Get(\"usernames\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"resolve a username or an address\", got.Desc)\n}\n\nfunc TestCatalogSetRejectsInvalid(t *testing.T) {\n\tvar c Catalog\n\tuassert.ErrorIs(t, c.Set(Tool{Path: \"p\", Title: \"t\"}), ErrEmptySlug)\n\tuassert.ErrorIs(t, c.Set(Tool{Slug: \"A\", Path: \"p\", Title: \"t\"}), ErrBadSlug)\n\tuassert.ErrorIs(t, c.Set(Tool{Slug: \"a\", Title: \"t\"}), ErrEmptyPath)\n\tuassert.ErrorIs(t, c.Set(Tool{Slug: \"a\", Path: \"p\"}), ErrEmptyTitle)\n\tuassert.Equal(t, 0, c.Len())\n}\n\nfunc TestCatalogGetAndRemove(t *testing.T) {\n\tvar c Catalog\n\tfor _, s := range []string{\"amm\", \"base64\", \"usernames\"} {\n\t\tuassert.NoError(t, c.Set(tool(s)))\n\t}\n\n\tgot, ok := c.Get(\"base64\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"gno.land/r/moul/toolbox/base64/v0\", got.Path)\n\n\t_, ok = c.Get(\"nope\")\n\tuassert.False(t, ok)\n\n\tuassert.NoError(t, c.Remove(\"base64\"))\n\tuassert.False(t, c.Has(\"base64\"))\n\tuassert.Equal(t, 2, c.Len())\n\tuassert.ErrorIs(t, c.Remove(\"base64\"), ErrUnknownSlug)\n\n\t// The two survivors are still in order around the hole.\n\tgot2 := slugs(c.List())\n\tuassert.Equal(t, \"amm\", got2[0])\n\tuassert.Equal(t, \"usernames\", got2[1])\n}\n\n// TestCatalogListIsACopy: a caller rewriting what List handed back must not\n// reach the directory through it. The struct copy covers the string fields on\n// its own; Tags is a slice, so without copyTool the header is duplicated and\n// the backing array is shared, and the write below would land in the catalog.\nfunc TestCatalogListIsACopy(t *testing.T) {\n\tvar c Catalog\n\tuassert.NoError(t, c.Set(tool(\"usernames\", \"identity\")))\n\n\tgot := c.List()\n\tgot[0].Title = \"hijacked\"\n\tgot[0].Tags[0] = \"hijacked\"\n\n\tkept, ok := c.Get(\"usernames\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"usernames\", kept.Title)\n\tuassert.Equal(t, \"identity\", kept.Tags[0])\n}\n\n// TestCatalogDoesNotAliasTheCallersTags is the same hole from the other side:\n// Set must not keep a handle on the slice the caller still holds.\nfunc TestCatalogDoesNotAliasTheCallersTags(t *testing.T) {\n\tvar c Catalog\n\ttags := []string{\"identity\"}\n\tuassert.NoError(t, c.Set(Tool{\n\t\tSlug:  \"usernames\",\n\t\tPath:  \"gno.land/r/moul/toolbox/usernames\",\n\t\tTitle: \"Usernames\",\n\t\tTags:  tags,\n\t}))\n\n\ttags[0] = \"hijacked\"\n\n\tkept, ok := c.Get(\"usernames\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, \"identity\", kept.Tags[0])\n\tuassert.Equal(t, 1, len(c.ByTag(\"identity\")))\n\tuassert.Equal(t, 0, len(c.ByTag(\"hijacked\")))\n}\n\n// TestCatalogGetIsACopyToo: ByTag and Get hand out the same values List does.\nfunc TestCatalogGetIsACopyToo(t *testing.T) {\n\tvar c Catalog\n\tuassert.NoError(t, c.Set(tool(\"usernames\", \"identity\")))\n\n\tgot, ok := c.Get(\"usernames\")\n\tuassert.True(t, ok)\n\tgot.Tags[0] = \"hijacked\"\n\n\tbyTag := c.ByTag(\"identity\")\n\tuassert.Equal(t, 1, len(byTag))\n\tbyTag[0].Tags[0] = \"hijacked-again\"\n\n\tkept, _ := c.Get(\"usernames\")\n\tuassert.Equal(t, \"identity\", kept.Tags[0])\n}\n\nfunc TestCatalogByTagAndTags(t *testing.T) {\n\tvar c Catalog\n\tuassert.NoError(t, c.Set(tool(\"usernames\", \"identity\", \"read\")))\n\tuassert.NoError(t, c.Set(tool(\"amm\", \"defi\")))\n\tuassert.NoError(t, c.Set(tool(\"whois\", \"identity\")))\n\n\tidentity := slugs(c.ByTag(\"identity\"))\n\tuassert.Equal(t, 2, len(identity))\n\tuassert.Equal(t, \"usernames\", identity[0])\n\tuassert.Equal(t, \"whois\", identity[1])\n\n\tuassert.Equal(t, 0, len(c.ByTag(\"nope\")))\n\tuassert.Equal(t, 0, len(c.ByTag(\"\")))\n\n\ttags := c.Tags()\n\tuassert.Equal(t, 3, len(tags))\n\tuassert.Equal(t, \"defi\", tags[0])\n\tuassert.Equal(t, \"identity\", tags[1])\n\tuassert.Equal(t, \"read\", tags[2])\n}\n"},{"name":"form.gno","body":"package toolbox\n\nimport \"strings\"\n\n// Query builds the gnoweb form a read-only tool needs: a text box whose\n// submission navigates to one of the realm's own Render paths, with the typed\n// values as query parameters.\n//\n// This is the \"template of a query\" a toolbox page is for. Rendered by gnoweb,\n//\n//\tNewQuery(\"lookup\").Field(\"q\", \"username or g1 address\").String()\n//\n// posts to the realm and redirects to `/r/moul/toolbox/usernames:lookup?q=moul`\n// (`gno.land/pkg/gnoweb/handler_http.go`, `Post`: the `path` attribute travels\n// as the hidden `__gno_path` field and becomes the render args, every other\n// field becomes a query parameter). Nothing is signed and no transaction is\n// built: the result is a `Render` call, which is exactly what\n// `gnokey query vm/qrender` would have done from a terminal.\n//\n// A form whose fields should CALL a function instead is a different element,\n// `\u003cgno-form exec=\"Fn\"\u003e`, and it is not what this type builds. A query form is\n// free and a call is not, so the two are deliberately not one constructor with\n// a flag.\ntype Query struct {\n\tpath   string\n\tfields []queryField\n}\n\ntype queryField struct {\n\tname        string\n\tplaceholder string\n}\n\n// NewQuery starts a form submitting to the Render path args.\n//\n// Pass \"\" to submit to the realm's root page. Do not include a leading colon\n// or the realm path itself: gnoweb supplies both, and a value that looks like\n// a URL is percent-encoded into one path element rather than followed.\nfunc NewQuery(path string) *Query {\n\treturn \u0026Query{path: path}\n}\n\n// Field adds a text input. name is the query parameter the realm will read;\n// placeholder is the grey text in the empty box.\n//\n// A field with an empty name is ignored: gnoweb rejects the whole form for it,\n// and losing one input beats losing the page.\nfunc (q *Query) Field(name, placeholder string) *Query {\n\tif name == \"\" {\n\t\treturn q\n\t}\n\tq.fields = append(q.fields, queryField{name: name, placeholder: placeholder})\n\treturn q\n}\n\n// Len is how many fields the form carries.\nfunc (q *Query) Len() int { return len(q.fields) }\n\n// String renders the form as the markdown-embedded HTML gnoweb parses.\n//\n// A form with no field renders as the empty string rather than as a submit\n// button with nothing to submit.\nfunc (q *Query) String() string {\n\tif len(q.fields) == 0 {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(`\u003cgno-form`)\n\tif q.path != \"\" {\n\t\tb.WriteString(` path=\"` + attr(q.path) + `\"`)\n\t}\n\tb.WriteString(\"\u003e\\n\")\n\tfor _, f := range q.fields {\n\t\tb.WriteString(`\u003cgno-input name=\"` + attr(f.name) + `\" type=\"text\"`)\n\t\tif f.placeholder != \"\" {\n\t\t\tb.WriteString(` placeholder=\"` + attr(f.placeholder) + `\"`)\n\t\t}\n\t\tb.WriteString(\" /\u003e\\n\")\n\t}\n\tb.WriteString(\"\u003c/gno-form\u003e\\n\")\n\treturn b.String()\n}\n\n// attr escapes a value for an HTML attribute in double quotes.\n//\n// gnoweb parses these with a real HTML tokenizer, so an unescaped quote does\n// not merely look wrong: it ends the attribute and whatever follows becomes\n// further attributes of the same tag. Ampersand first, or the escapes of the\n// later replacements would themselves be escaped.\nfunc attr(s string) string {\n\ts = strings.ReplaceAll(s, \"\u0026\", \"\u0026amp;\")\n\ts = strings.ReplaceAll(s, `\"`, \"\u0026quot;\")\n\ts = strings.ReplaceAll(s, \"\u003c\", \"\u0026lt;\")\n\ts = strings.ReplaceAll(s, \"\u003e\", \"\u0026gt;\")\n\treturn s\n}\n"},{"name":"form_test.gno","body":"package toolbox\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestQueryString(t *testing.T) {\n\tgot := NewQuery(\"lookup\").Field(\"q\", \"username or g1 address\").String()\n\twant := \"\u003cgno-form path=\\\"lookup\\\"\u003e\\n\" +\n\t\t\"\u003cgno-input name=\\\"q\\\" type=\\\"text\\\" placeholder=\\\"username or g1 address\\\" /\u003e\\n\" +\n\t\t\"\u003c/gno-form\u003e\\n\"\n\tuassert.Equal(t, want, got)\n}\n\nfunc TestQueryNoPathNoPlaceholder(t *testing.T) {\n\tgot := NewQuery(\"\").Field(\"q\", \"\").String()\n\twant := \"\u003cgno-form\u003e\\n\u003cgno-input name=\\\"q\\\" type=\\\"text\\\" /\u003e\\n\u003c/gno-form\u003e\\n\"\n\tuassert.Equal(t, want, got)\n}\n\nfunc TestQueryTwoFields(t *testing.T) {\n\tq := NewQuery(\"compare\").Field(\"a\", \"first\").Field(\"b\", \"second\")\n\tuassert.Equal(t, 2, q.Len())\n\tgot := q.String()\n\tuassert.True(t, strings.Contains(got, `name=\"a\"`))\n\tuassert.True(t, strings.Contains(got, `name=\"b\"`))\n\tuassert.Equal(t, 1, strings.Count(got, \"\u003cgno-form\"))\n}\n\n// TestQueryEmptyRendersNothing: a form with no input is a submit button with\n// nothing to submit, so it is not rendered at all.\nfunc TestQueryEmptyRendersNothing(t *testing.T) {\n\tuassert.Equal(t, \"\", NewQuery(\"lookup\").String())\n\tuassert.Equal(t, \"\", NewQuery(\"lookup\").Field(\"\", \"ignored\").String())\n}\n\n// TestQueryEscapesAttributes: gnoweb parses these with a real HTML tokenizer,\n// so an unescaped quote ends the attribute and everything after it becomes\n// further attributes of the same tag.\nfunc TestQueryEscapesAttributes(t *testing.T) {\n\tgot := NewQuery(`a\"b`).Field(\"q\", `\u003cscript\u003e\u0026\"`).String()\n\tuassert.True(t, strings.Contains(got, `path=\"a\u0026quot;b\"`))\n\tuassert.True(t, strings.Contains(got, `placeholder=\"\u0026lt;script\u0026gt;\u0026amp;\u0026quot;\"`))\n\tuassert.False(t, strings.Contains(got, \"\u003cscript\u003e\"))\n}\n\nfunc TestAttr(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"plain\", \"username\", \"username\"},\n\t\t{\"quote\", `a\"b`, \"a\u0026quot;b\"},\n\t\t{\"ampersand\", \"a\u0026b\", \"a\u0026amp;b\"},\n\t\t{\"angle\", \"\u003cb\u003e\", \"\u0026lt;b\u0026gt;\"},\n\t\t{\"ampersand before quote\", `\u0026\"`, \"\u0026amp;\u0026quot;\"},\n\t\t{\"already escaped stays literal\", \"\u0026amp;\", \"\u0026amp;amp;\"},\n\t\t{\"empty\", \"\", \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, attr(tc.in))\n\t\t})\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/toolbox/v0\"\ngno = \"0.9\"\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"p/moul/toolbox\"\n  revision = \"015e568e04578f1d1fe1fc9a5c00505e9b9f08e6\"\n"},{"name":"render.gno","body":"package toolbox\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n)\n\n// Index renders a catalog as a markdown table: tool, what it does, tags.\n//\n// Every cell that came from a [Tool] is escaped exactly once, with the helper\n// for the slot it lands in. A tool description is written by whoever wrote the\n// entry, which in a hub that accepts runtime registration is not necessarily\n// whoever owns the hub, and a pipe or a backtick in one would otherwise\n// rewrite the table around it.\n//\n// The title link is built by hand rather than with [md.Link], which is the one\n// place the obvious call is wrong: md.Link runs its text through\n// sanitize.InlineText itself, so md.Link(ui.Cell(title), url) escapes twice and\n// a title with an asterisk in it renders as a backslash. The slot here is link\n// text INSIDE a table cell, and the helper for that is [ui.Cell] (InlineText\n// plus the pipe escape InlineText deliberately leaves alone), with the URL\n// escaped once by [md.EscapeURL].\nfunc Index(tools []Tool) string {\n\tt := ui.NewTable(\"Tool\", \"What it does\", \"Tags\")\n\tfor _, tool := range tools {\n\t\tt.Row(\n\t\t\t\"[\"+ui.Cell(tool.Title)+\"](\"+md.EscapeURL(tool.URL())+\")\",\n\t\t\tui.Cell(tool.Desc),\n\t\t\tui.Cell(strings.Join(tool.Tags, \", \")),\n\t\t)\n\t}\n\treturn t.OrEmpty(\"No tools yet.\")\n}\n\n// Card renders one tool on its own: the title as a link, the description, the\n// package path, and the two ways to reach it.\nfunc Card(tool Tool) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H2(ui.Inline(tool.Title)))\n\tif tool.Desc != \"\" {\n\t\tb.WriteString(\"\\n\" + ui.Inline(tool.Desc) + \"\\n\")\n\t}\n\tb.WriteString(\"\\n\" + md.BulletList([]string{\n\t\t\"Open: \" + md.Link(tool.URL(), tool.URL()),\n\t\t\"Path: \" + md.InlineCode(tool.Path),\n\t}))\n\tif len(tool.Tags) \u003e 0 {\n\t\tb.WriteString(\"\\nTags: \" + ui.Inline(strings.Join(tool.Tags, \", \")) + \"\\n\")\n\t}\n\treturn b.String()\n}\n\n// Nav renders the one line every tool page carries above its content: a link\n// back to the hub, then the tool's own title.\n//\n// hubURL is a gnoweb path (\"/r/moul/toolbox\"), not a package path. A tool\n// cannot import the hub to ask, so it states it, and this is the one place the\n// two have to agree.\nfunc Nav(hubURL, title string) string {\n\treturn md.Link(\"toolbox\", hubURL) + \" / \" + md.Bold(ui.Inline(title)) + \"\\n\"\n}\n"},{"name":"render_test.gno","body":"package toolbox\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestIndex(t *testing.T) {\n\tvar c Catalog\n\tuassert.NoError(t, c.Set(Tool{\n\t\tSlug:  \"usernames\",\n\t\tPath:  \"gno.land/r/moul/toolbox/usernames\",\n\t\tTitle: \"Usernames\",\n\t\tDesc:  \"resolve a username or an address\",\n\t\tTags:  []string{\"identity\", \"read\"},\n\t}))\n\n\tgot := Index(c.List())\n\tuassert.True(t, strings.Contains(got, \"[Usernames](/r/moul/toolbox/usernames)\"))\n\tuassert.True(t, strings.Contains(got, \"resolve a username or an address\"))\n\tuassert.True(t, strings.Contains(got, \"identity, read\"))\n}\n\nfunc TestIndexEmpty(t *testing.T) {\n\tuassert.True(t, strings.Contains(Index(nil), \"No tools yet.\"))\n}\n\n// TestIndexEscapesCells pins the escaping contract: a description is written\n// by whoever wrote the entry, and a pipe in one would otherwise add a column to\n// every row below it. The title is link text inside a cell, so it needs the\n// pipe escaped there too.\nfunc TestIndexEscapesCells(t *testing.T) {\n\tgot := Index([]Tool{{\n\t\tSlug:  \"evil\",\n\t\tPath:  \"gno.land/r/moul/toolbox/evil\",\n\t\tTitle: \"Ev|il\",\n\t\tDesc:  \"a | b\",\n\t\tTags:  []string{\"x|y\"},\n\t}})\n\tuassert.False(t, strings.Contains(got, \"a | b\"))\n\tuassert.True(t, strings.Contains(got, `[Ev\\|il](/r/moul/toolbox/evil)`))\n\tuassert.True(t, strings.Contains(got, `x\\|y`))\n}\n\n// TestIndexEscapesTitleExactlyOnce is the double-wrap regression, and the\n// values are copied from what the escapers actually produce rather than\n// guessed: md.Link runs its text through sanitize.InlineText itself, so\n// md.Link(ui.Cell(title), url) yields `[a\\\\\\*b]` where one pass yields\n// `[a\\*b]`, and the reader sees a stray backslash.\nfunc TestIndexEscapesTitleExactlyOnce(t *testing.T) {\n\tgot := Index([]Tool{{\n\t\tSlug:  \"star\",\n\t\tPath:  \"gno.land/r/moul/toolbox/star\",\n\t\tTitle: \"a*b\",\n\t\tDesc:  \"c*d\",\n\t}})\n\tuassert.True(t, strings.Contains(got, `[a\\*b](/r/moul/toolbox/star)`))\n\tuassert.False(t, strings.Contains(got, `a\\\\`))\n\tuassert.True(t, strings.Contains(got, `c\\*d`))\n}\n\nfunc TestCard(t *testing.T) {\n\tgot := Card(Tool{\n\t\tSlug:  \"usernames\",\n\t\tPath:  \"gno.land/r/moul/toolbox/usernames\",\n\t\tTitle: \"Usernames\",\n\t\tDesc:  \"resolve a username or an address\",\n\t\tTags:  []string{\"identity\"},\n\t})\n\tuassert.True(t, strings.Contains(got, \"## Usernames\"))\n\tuassert.True(t, strings.Contains(got, \"resolve a username or an address\"))\n\tuassert.True(t, strings.Contains(got, \"`gno.land/r/moul/toolbox/usernames`\"))\n\tuassert.True(t, strings.Contains(got, \"/r/moul/toolbox/usernames\"))\n\tuassert.True(t, strings.Contains(got, \"Tags: identity\"))\n}\n\nfunc TestCardMinimal(t *testing.T) {\n\tgot := Card(Tool{Slug: \"x\", Path: \"gno.land/r/moul/toolbox/x/v0\", Title: \"X\"})\n\tuassert.True(t, strings.Contains(got, \"## X\"))\n\tuassert.False(t, strings.Contains(got, \"Tags:\"))\n}\n\nfunc TestNav(t *testing.T) {\n\tuassert.Equal(t, \"[toolbox](/r/moul/toolbox) / **Usernames**\\n\",\n\t\tNav(\"/r/moul/toolbox\", \"Usernames\"))\n}\n"},{"name":"toolbox.gno","body":"// Package toolbox is the directory model behind\n// [r/moul/toolbox](/r/moul/toolbox): a list of small gno.land utilities,\n// each one a realm of its own, rendered as a single index.\n//\n// A tool is a [Tool]: a slug, the realm path that serves it, a title and one\n// line of description. A [Catalog] holds them sorted by slug and answers the\n// three questions a directory gets asked: what is here, what is this one, and\n// what is tagged X.\n//\n// # Why a package and not just a realm\n//\n// The hub realm is `private = true`, which buys redeploy-in-place at a stable\n// path and costs the ability to be imported at all: the type checker refuses\n// any realm importing a private one (`ImportPrivateError`). So the hub cannot\n// share a single line of code with its tools by importing them, and they\n// cannot import it either. Everything both sides must agree about (what a tool\n// entry looks like, how the index is rendered, how a query form is spelled)\n// has to live in a `p/`, which is this one.\n//\n// # Nesting is checked on the base path, not on the full one\n//\n// [p/moul/nestedpkg](/p/moul/nestedpkg/v0) decides \"is the caller below me\" by\n// prefixing one package path with the other. That is exactly right when\n// neither path carries a version, which is the case for a private hub: it is\n// redeployable, so its version could never increment and it does not carry\n// one. It breaks the moment either side does, because\n// `gno.land/r/moul/toolbox/usernames/v0` does not begin with\n// `gno.land/r/moul/toolbox/v0`.\n//\n// [BasePath] removes a trailing `/vN` so the comparison is about the family\n// rather than the version, and [IsUnder] and [SlugOf] are built on it. A hub\n// and a tool may each be versioned or not, independently, and all four\n// combinations answer the same.\n//\n// Live: [r/moul/toolbox](/r/moul/toolbox).\npackage toolbox\n\nimport (\n\t\"errors\"\n\t\"strings\"\n)\n\n// Errors a [Tool] or a [Catalog] returns. A /p/ package returns errors and\n// lets the realm decide whether they are fatal; all of these are a mistake in\n// the realm's own source rather than a value a user chose, so panicking on\n// them is the normal handling.\nvar (\n\t// ErrEmptySlug is returned for a tool with no slug. The slug is the key\n\t// and the URL segment, so there is nothing to list it under.\n\tErrEmptySlug = errors.New(\"toolbox: the slug is empty\")\n\n\t// ErrBadSlug is returned for a slug carrying anything but lowercase\n\t// letters, digits and dashes. A slug travels in a URL path and in a\n\t// markdown link, and those are the characters that need no escaping in\n\t// either.\n\tErrBadSlug = errors.New(\"toolbox: the slug has a character outside [a-z0-9-]\")\n\n\t// ErrEmptyPath is returned for a tool with no package path. A directory\n\t// entry nobody can open is worse than no entry.\n\tErrEmptyPath = errors.New(\"toolbox: the path is empty\")\n\n\t// ErrEmptyTitle is returned for a tool with no title.\n\tErrEmptyTitle = errors.New(\"toolbox: the title is empty\")\n\n\t// ErrUnknownSlug is returned by [Catalog.Remove] for a slug it does not\n\t// hold.\n\tErrUnknownSlug = errors.New(\"toolbox: no tool with that slug\")\n)\n\n// Tool is one entry of the directory.\n//\n// Every field is a string or a slice of strings on purpose. A tool realm that\n// registers itself into a public hub hands these values across a realm\n// boundary, and a struct allocated by the caller would be the caller's object:\n// persisting it panics with `cannot persist object from the private realm`\n// when the caller is private. Scalars are copied, so the hub owns everything\n// it stores whichever side built the entry.\ntype Tool struct {\n\t// Slug is the key, the URL segment and the sort order: \"usernames\".\n\tSlug string\n\n\t// Path is the package path serving the tool, with its version if it has\n\t// one: \"gno.land/r/moul/toolbox/usernames\".\n\tPath string\n\n\t// Title is the human name: \"Usernames\".\n\tTitle string\n\n\t// Desc is one line about what the tool does. It is rendered inside a\n\t// table cell, so [Index] escapes it rather than trusting it.\n\tDesc string\n\n\t// Tags group tools in the index. Order is preserved as written.\n\tTags []string\n}\n\n// Validate reports the first thing wrong with t, or nil.\nfunc (t Tool) Validate() error {\n\tswitch {\n\tcase t.Slug == \"\":\n\t\treturn ErrEmptySlug\n\tcase !ValidSlug(t.Slug):\n\t\treturn ErrBadSlug\n\tcase t.Path == \"\":\n\t\treturn ErrEmptyPath\n\tcase t.Title == \"\":\n\t\treturn ErrEmptyTitle\n\t}\n\treturn nil\n}\n\n// HasTag reports whether t carries tag, compared exactly.\nfunc (t Tool) HasTag(tag string) bool {\n\tfor _, got := range t.Tags {\n\t\tif got == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// URL is the gnoweb path of the tool, the package path with the chain domain\n// removed: \"/r/moul/toolbox/usernames\".\n//\n// It is derived rather than stored so an entry cannot carry a link that\n// disagrees with its own path.\nfunc (t Tool) URL() string {\n\tif i := strings.Index(t.Path, \"/\"); i \u003e= 0 \u0026\u0026 !strings.HasPrefix(t.Path, \"/\") {\n\t\treturn t.Path[i:]\n\t}\n\treturn t.Path\n}\n\n// ValidSlug reports whether s is a usable slug: non-empty, and lowercase\n// letters, digits and dashes only.\n//\n// It is deliberately narrower than what a package path allows. A slug ends up\n// in a URL and in markdown link syntax, and this is the set that survives both\n// untouched, so nothing downstream has to escape it.\nfunc ValidSlug(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z':\n\t\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '-':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// BasePath returns pkgPath with a trailing version element removed:\n// \"gno.land/p/moul/toolbox/v0\" becomes \"gno.land/p/moul/toolbox\".\n//\n// A path with no version element is returned unchanged, so calling it twice is\n// the same as calling it once.\nfunc BasePath(pkgPath string) string {\n\ti := strings.LastIndex(pkgPath, \"/\")\n\tif i \u003c 0 {\n\t\treturn pkgPath\n\t}\n\tif !isVersion(pkgPath[i+1:]) {\n\t\treturn pkgPath\n\t}\n\treturn pkgPath[:i]\n}\n\n// isVersion reports whether elem is a \"vN\" path element: a 'v' followed by at\n// least one digit and nothing else.\nfunc isVersion(elem string) bool {\n\tif len(elem) \u003c 2 || elem[0] != 'v' {\n\t\treturn false\n\t}\n\tfor i := 1; i \u003c len(elem); i++ {\n\t\tif elem[i] \u003c '0' || elem[i] \u003e '9' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// IsUnder reports whether pkgPath is a tool of the hub at hubPath, ignoring\n// both paths' versions.\n//\n// The hub itself is not under itself, and neither is a sibling whose name\n// merely starts with the hub's: \"toolboxtwo\" is not under \"toolbox\", because\n// the comparison is against the base plus a slash.\nfunc IsUnder(hubPath, pkgPath string) bool {\n\tbase := BasePath(hubPath)\n\tif base == \"\" {\n\t\treturn false\n\t}\n\treturn strings.HasPrefix(BasePath(pkgPath), base+\"/\")\n}\n\n// SlugOf returns the slug a tool at pkgPath would have under the hub at\n// hubPath, or \"\" when pkgPath is not under it.\n//\n// A tool nested deeper than one element has no slug: the directory is one\n// level by design, so \"toolbox/a/b\" is reported as not a tool rather than\n// silently listed as \"a\".\nfunc SlugOf(hubPath, pkgPath string) string {\n\tif !IsUnder(hubPath, pkgPath) {\n\t\treturn \"\"\n\t}\n\trest := strings.TrimPrefix(BasePath(pkgPath), BasePath(hubPath)+\"/\")\n\tif strings.Contains(rest, \"/\") {\n\t\treturn \"\"\n\t}\n\treturn rest\n}\n"},{"name":"toolbox_test.gno","body":"package toolbox\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestValidSlug(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tslug string\n\t\twant bool\n\t}{\n\t\t{\"plain\", \"usernames\", true},\n\t\t{\"dashed\", \"gov-dao\", true},\n\t\t{\"digits\", \"base64\", true},\n\t\t{\"all dashes\", \"--\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"uppercase\", \"Usernames\", false},\n\t\t{\"underscore\", \"gov_dao\", false},\n\t\t{\"slash\", \"a/b\", false},\n\t\t{\"space\", \"gov dao\", false},\n\t\t{\"dot\", \"v0.1\", false},\n\t\t{\"percent\", \"a%2Fb\", false},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, ValidSlug(tc.slug))\n\t\t})\n\t}\n}\n\nfunc TestBasePath(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant string\n\t}{\n\t\t{\"versioned realm\", \"gno.land/r/moul/toolbox/v0\", \"gno.land/r/moul/toolbox\"},\n\t\t{\"two digit version\", \"gno.land/r/moul/toolbox/v12\", \"gno.land/r/moul/toolbox\"},\n\t\t{\"nested tool\", \"gno.land/r/moul/toolbox/usernames/v0\", \"gno.land/r/moul/toolbox/usernames\"},\n\t\t{\"unversioned\", \"gno.land/r/moul/home\", \"gno.land/r/moul/home\"},\n\t\t{\"idempotent\", \"gno.land/r/moul/toolbox\", \"gno.land/r/moul/toolbox\"},\n\t\t{\"v with no digit\", \"gno.land/r/moul/v\", \"gno.land/r/moul/v\"},\n\t\t{\"v with a letter\", \"gno.land/r/moul/v0a\", \"gno.land/r/moul/v0a\"},\n\t\t{\"no slash\", \"toolbox\", \"toolbox\"},\n\t\t{\"empty\", \"\", \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, BasePath(tc.in))\n\t\t})\n\t}\n}\n\nfunc TestIsUnderAndSlugOf(t *testing.T) {\n\tconst hub = \"gno.land/r/moul/toolbox/v0\"\n\tcases := []struct {\n\t\tname      string\n\t\tpath      string\n\t\twantUnder bool\n\t\twantSlug  string\n\t}{\n\t\t{\"direct tool\", \"gno.land/r/moul/toolbox/usernames/v0\", true, \"usernames\"},\n\t\t{\"unversioned tool\", \"gno.land/r/moul/toolbox/usernames\", true, \"usernames\"},\n\t\t{\"tool at another version\", \"gno.land/r/moul/toolbox/usernames/v3\", true, \"usernames\"},\n\t\t{\"nested deeper\", \"gno.land/r/moul/toolbox/a/b/v0\", true, \"\"},\n\t\t{\"the hub itself\", hub, false, \"\"},\n\t\t{\"hub unversioned\", \"gno.land/r/moul/toolbox\", false, \"\"},\n\t\t{\"prefix sibling\", \"gno.land/r/moul/toolboxtwo/v0\", false, \"\"},\n\t\t{\"unrelated realm\", \"gno.land/r/moul/home\", false, \"\"},\n\t\t{\"empty\", \"\", false, \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.wantUnder, IsUnder(hub, tc.path))\n\t\t\tuassert.Equal(t, tc.wantSlug, SlugOf(hub, tc.path))\n\t\t})\n\t}\n}\n\n// TestIsUnderIgnoresEitherSideVersion is the claim the package doc makes: a\n// hub and a tool may each carry a version or not, independently, and all four\n// combinations answer the same. The live shape is the unversioned one, since a\n// private realm is redeployable and its version could never increment.\nfunc TestIsUnderIgnoresEitherSideVersion(t *testing.T) {\n\thubs := []string{\"gno.land/r/moul/toolbox\", \"gno.land/r/moul/toolbox/v0\"}\n\ttools := []string{\"gno.land/r/moul/toolbox/usernames\", \"gno.land/r/moul/toolbox/usernames/v2\"}\n\tfor _, hub := range hubs {\n\t\tfor _, tool := range tools {\n\t\t\tt.Run(hub+\" \u003c- \"+tool, func(t *testing.T) {\n\t\t\t\tuassert.True(t, IsUnder(hub, tool))\n\t\t\t\tuassert.Equal(t, \"usernames\", SlugOf(hub, tool))\n\t\t\t\tuassert.False(t, IsUnder(hub, hub))\n\t\t\t})\n\t\t}\n\t}\n}\n\n// TestIsUnderEmptyHub pins the one input that would otherwise make every path\n// a tool: an empty hub path has no family to be below.\nfunc TestIsUnderEmptyHub(t *testing.T) {\n\tuassert.False(t, IsUnder(\"\", \"gno.land/r/moul/toolbox/usernames/v0\"))\n\tuassert.Equal(t, \"\", SlugOf(\"\", \"gno.land/r/moul/toolbox/usernames/v0\"))\n}\n\nfunc TestToolValidate(t *testing.T) {\n\tok := Tool{Slug: \"usernames\", Path: \"gno.land/r/moul/toolbox/usernames/v0\", Title: \"Usernames\"}\n\tcases := []struct {\n\t\tname string\n\t\ttool Tool\n\t\twant error\n\t}{\n\t\t{\"complete\", ok, nil},\n\t\t{\"no slug\", Tool{Path: ok.Path, Title: ok.Title}, ErrEmptySlug},\n\t\t{\"bad slug\", Tool{Slug: \"User Names\", Path: ok.Path, Title: ok.Title}, ErrBadSlug},\n\t\t{\"no path\", Tool{Slug: ok.Slug, Title: ok.Title}, ErrEmptyPath},\n\t\t{\"no title\", Tool{Slug: ok.Slug, Path: ok.Path}, ErrEmptyTitle},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgot := tc.tool.Validate()\n\t\t\tif tc.want == nil {\n\t\t\t\tuassert.NoError(t, got)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tuassert.ErrorIs(t, got, tc.want)\n\t\t})\n\t}\n}\n\nfunc TestToolURL(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tpath string\n\t\twant string\n\t}{\n\t\t{\"chain path\", \"gno.land/r/moul/toolbox/usernames/v0\", \"/r/moul/toolbox/usernames/v0\"},\n\t\t{\"other domain\", \"example.com/r/x/v0\", \"/r/x/v0\"},\n\t\t{\"already a url\", \"/r/moul/toolbox/v0\", \"/r/moul/toolbox/v0\"},\n\t\t{\"no slash\", \"toolbox\", \"toolbox\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, Tool{Path: tc.path}.URL())\n\t\t})\n\t}\n}\n\nfunc TestToolHasTag(t *testing.T) {\n\ttool := Tool{Tags: []string{\"identity\", \"read\"}}\n\tuassert.True(t, tool.HasTag(\"identity\"))\n\tuassert.True(t, tool.HasTag(\"read\"))\n\tuassert.False(t, tool.HasTag(\"Identity\"))\n\tuassert.False(t, tool.HasTag(\"\"))\n\tuassert.False(t, Tool{}.HasTag(\"identity\"))\n}\n"}]},"send":"","max_deposit":"16000000ugnot"}],"fee":{"gas_wanted":"115586600","gas_fee":"346759ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"AjZyqpH4vJ3WLLVeLtRl+F2StxRT+LawNoGVosjVwS/F"},"signature":"EvQyHSeEJnpuy27u3GDtPvnsL2tjK4E7jiAbbPigs19xsZyiS6RXB71srL9o+k43crDVudfQ0Ak3W1CSpqSAuA=="}],"memo":""},"metadata":{"timestamp":"1791555900"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"toolbox","path":"gno.land/r/moul/toolbox","files":[{"name":"README.md","body":"# `gno.land/r/moul/toolbox`\n\n**A home for small utilities on gno.land.** One page listing every tool; each tool is its own\nrealm at `r/moul/toolbox/\u003cslug\u003e`.\n\nA tool composes contracts that are already on chain and renders the answer, so you open a page\ninstead of composing a query. The toolbox adds the view, not the data.\n\n```\n/r/moul/toolbox                  the directory\n/r/moul/toolbox?tag=identity     the directory, filtered to one tag\n/r/moul/toolbox:usernames        one tool\n```\n\n## The catalog is compiled in, and that is the interesting part\n\nThe obvious design is the opposite one: each tool calls `Register` on this realm from its own\ninit, and the directory assembles itself. That design is unavailable here, and the reason is\nnot a preference.\n\n`private = true` buys redeploy-in-place at the same path and costs the ability to be imported:\nthe type checker refuses any realm importing a private one (`ImportPrivateError`). A private\nhub therefore cannot be imported by its tools, and a hub that accepts registration has to be\npublic. **A public realm can never be redeployed at its own path**, so a public hub would be\nfrozen at v0 and the first bug in it would move the directory's URL.\n\nA stable URL is the whole point of a directory, so the trade goes the other way: everything\nhere is private and redeployable, and adding a tool is one entry in `tools` plus a redeploy.\nThe catalog is rebuilt from source every time, so the redeploy wipe costs nothing. There is no\nstate to lose.\n\n[`p/moul/toolbox`](https://gno.land/p/moul/toolbox/v0)'s `Catalog` stays mutable for whoever\nwants the other trade.\n\n## And that is also why the path carries no `/vN`\n\n`/vN` exists because a public path can never be redeployed, so a fix there means a new path.\nThis realm is private and redeployable, so its version could never increment and the suffix\nwould be a promise it cannot keep. The URL is the product here, bookmarked the way a blog post\nis, so it is the one that should not carry it. `unversionedContracts` in\n`tools/gnocontracts/model.go` is the allowlist, with the reason per entry.\n\n## Adding a tool\n\nOne entry in `tools`, then redeploy. `buildCatalog` panics at deploy, not at read, if the slug\nand the path disagree, so a copy-pasted entry that kept the wrong path fails the publish rather\nthan shipping a dead link.\n\n## The read API\n\nFlat strings, because a nested value inside a persisted object prints as an opaque `ref(...)`\nover `vm/qeval`:\n\n```sh\ngnokey query vm/qeval -remote https://rpc.gno.land \\\n  -data 'gno.land/r/moul/toolbox.Slugs()'\ngnokey query vm/qeval -remote https://rpc.gno.land \\\n  -data 'gno.land/r/moul/toolbox.PathOf(\"usernames\")'\n```\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/toolbox\"\ngno = \"0.9\"\n\n# Private, and therefore unversioned. The /vN suffix exists because a PUBLIC\n# path can never be redeployed, so a fix there means a new path; a private realm\n# is redeployable by its creator, so the version could never increment and the\n# suffix would be a promise this realm cannot keep. The directory URL is the\n# thing people bookmark, so it is the one that should not carry it.\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/toolbox\"\n  revision = \"015e568e04578f1d1fe1fc9a5c00505e9b9f08e6\"\n"},{"name":"render.gno","body":"package toolbox\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\ttb \"gno.land/p/moul/toolbox/v0\"\n)\n\n// Render routes gnoweb paths:\n//\n//\t/                 the directory\n//\t/?tag=identity    the directory, filtered to one tag\n//\t/\u003cslug\u003e           one tool\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tparts := req.PathParts()\n\n\tif len(parts) == 0 || parts[0] == \"\" {\n\t\treturn renderIndex(req.Query.Get(\"tag\"))\n\t}\n\tif len(parts) \u003e 1 {\n\t\treturn renderUnknown(parts[0] + \"/\" + parts[1])\n\t}\n\tt, ok := catalog.Get(parts[0])\n\tif !ok {\n\t\treturn renderUnknown(parts[0])\n\t}\n\treturn renderTool(t)\n}\n\nfunc renderIndex(tag string) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"Toolbox\"))\n\tb.WriteString(\"\\nSmall utilities on gno.land. Each one is its own realm, composing contracts that are already on chain and showing the answer as a page instead of as a query you have to compose.\\n\")\n\n\tlist := catalog.List()\n\tif tag != \"\" {\n\t\tlist = catalog.ByTag(tag)\n\t\tb.WriteString(\"\\nFiltered to \" + md.InlineCode(tag) + \". \" +\n\t\t\tmd.Link(\"Show all\", hubURL) + \"\\n\")\n\t}\n\tb.WriteString(\"\\n\" + tb.Index(list))\n\n\tif tag == \"\" {\n\t\tif links := tagLinks(catalog, hubURL); links != \"\" {\n\t\t\tb.WriteString(\"\\nTags: \" + links + \"\\n\")\n\t\t}\n\t}\n\n\tb.WriteString(\"\\n\" + md.H2(\"What a tool is\"))\n\tb.WriteString(\"\\n\" + md.BulletList([]string{\n\t\t\"A realm at \" + md.InlineCode(\"gno.land/r/moul/toolbox/\u003cslug\u003e\") + \", reachable on its own.\",\n\t\t\"Read-only unless it says otherwise: a page you open, not a transaction you sign.\",\n\t\t\"Composed from contracts already on chain, so the toolbox adds the view and not the data.\",\n\t}))\n\treturn b.String()\n}\n\n// tagLinks renders the tag filter row, or \"\" when nothing is tagged.\n//\n// QueryEscape, not plain concatenation: a tag is an arbitrary string on Tool,\n// and \"a\u0026b\" would otherwise become a second query parameter while \"a#b\" would\n// become a fragment, in both cases linking to a filter nobody asked for.\nfunc tagLinks(c *tb.Catalog, base string) string {\n\ttags := c.Tags()\n\tif len(tags) == 0 {\n\t\treturn \"\"\n\t}\n\tlinks := make([]string, 0, len(tags))\n\tfor _, name := range tags {\n\t\tlinks = append(links, md.Link(name, base+\"?tag=\"+url.QueryEscape(name)))\n\t}\n\treturn strings.Join(links, \" · \")\n}\n\nfunc renderTool(t tb.Tool) string {\n\tvar b strings.Builder\n\tb.WriteString(tb.Nav(hubURL, \"Toolbox\"))\n\tb.WriteString(\"\\n\" + tb.Card(t))\n\treturn b.String()\n}\n\nfunc renderUnknown(slug string) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"Not found\"))\n\tb.WriteString(\"\\nNo tool called \" + md.InlineCode(slug) + \".\\n\")\n\tb.WriteString(\"\\n\" + md.Link(\"Back to the toolbox\", hubURL) + \"\\n\")\n\treturn b.String()\n}\n"},{"name":"render_example_test.gno","body":"package toolbox\n\n// ExampleRender pins the directory page. The catalog is compiled in, so this\n// output changes only when a tool is added or re-described, which is exactly\n// when a reviewer should see the diff.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Toolbox\n\t//\n\t// Small utilities on gno.land. Each one is its own realm, composing contracts that are already on chain and showing the answer as a page instead of as a query you have to compose.\n\t//\n\t// | Tool | What it does | Tags |\n\t// | --- | --- | --- |\n\t// | [Usernames](/r/moul/toolbox/usernames) | Resolve a gno\\.land username to an address, or an address to a username\\. | identity, read |\n\t//\n\t// Tags: [identity](/r/moul/toolbox?tag=identity) · [read](/r/moul/toolbox?tag=read)\n\t//\n\t// ## What a tool is\n\t//\n\t// - A realm at `gno.land/r/moul/toolbox/\u003cslug\u003e`, reachable on its own.\n\t// - Read-only unless it says otherwise: a page you open, not a transaction you sign.\n\t// - Composed from contracts already on chain, so the toolbox adds the view and not the data.\n}\n"},{"name":"toolbox.gno","body":"// Package toolbox is the directory of moul's small gno.land utilities: one\n// page listing every tool, each tool a realm of its own at\n// `r/moul/toolbox/\u003cslug\u003e`.\n//\n// It holds no logic. A tool composes other contracts (resolve a username,\n// read a DAO, decode a denom) and renders the answer; this realm only says\n// which tools exist and where they are. The model, the rendering and the\n// query-form builder are\n// [p/moul/toolbox](/p/moul/toolbox/v0).\n//\n// # Why the catalog is compiled in and not registered\n//\n// The obvious design is the opposite one: each tool calls `Register` on this\n// realm from its own init, and the directory assembles itself. That design is\n// unavailable here, and the reason is worth stating because it is not a\n// preference.\n//\n// `private = true` buys redeploy-in-place at the same path and costs the\n// ability to be imported: the type checker refuses any realm importing a\n// private one (`ImportPrivateError`, `gnovm/pkg/gnolang/gotypecheck.go`). So a\n// private hub cannot be imported by its tools, and a hub that accepts\n// registration has to be public. A public realm can never be redeployed, which\n// would freeze this path at v0 and move the directory's URL on the first bug\n// in it.\n//\n// A stable URL is the whole point of a directory, so the trade goes the other\n// way: everything here is private and redeployable, and adding a tool is one\n// entry in [tools] plus a redeploy. The catalog is rebuilt from source every\n// time, so the redeploy wipe costs nothing: there is no state to lose.\n//\n// [p/moul/toolbox.Catalog] stays mutable for whoever wants the other trade.\npackage toolbox\n\nimport \"gno.land/p/moul/toolbox/v0\"\n\n// hubPath is this realm's own path. A realm can ask the chain for it, but a\n// constant is what [p/moul/toolbox.SlugOf] is checked against in tests, where\n// there is no chain frame to ask.\nconst hubPath = \"gno.land/r/moul/toolbox\"\n\n// hubURL is the gnoweb path of this realm, which every tool page links back\n// to. A tool cannot import this realm to read it, so each one repeats it; this\n// is the copy that is authoritative.\nconst hubURL = \"/r/moul/toolbox\"\n\n// tools is the directory. Adding one here and redeploying is how the toolbox\n// grows; see the package doc for why it is not a registration call.\n//\n// Every entry must be a realm under this one: [buildCatalog] refuses an entry\n// whose slug does not match its path, so a copy-paste that keeps the wrong\n// path fails the deploy rather than publishing a dead link.\nvar tools = []toolbox.Tool{\n\t{\n\t\tSlug:  \"usernames\",\n\t\tPath:  \"gno.land/r/moul/toolbox/usernames\",\n\t\tTitle: \"Usernames\",\n\t\tDesc:  \"Resolve a gno.land username to an address, or an address to a username.\",\n\t\tTags:  []string{\"identity\", \"read\"},\n\t},\n}\n\n// catalog is the directory, sorted and checked once at deploy.\nvar catalog = buildCatalog()\n\nfunc buildCatalog() *toolbox.Catalog {\n\tc := \u0026toolbox.Catalog{}\n\tfor _, t := range tools {\n\t\tif err := c.Set(t); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif got := toolbox.SlugOf(hubPath, t.Path); got != t.Slug {\n\t\t\tpanic(\"toolbox: \" + t.Slug + \" is declared at \" + t.Path +\n\t\t\t\t\", which is not gno.land/r/moul/toolbox/\" + t.Slug)\n\t\t}\n\t}\n\treturn c\n}\n\n// Count is how many tools the directory holds.\nfunc Count() int { return catalog.Len() }\n\n// Slugs lists every tool's slug, in directory order.\n//\n//\tgnokey query vm/qeval -data 'gno.land/r/moul/toolbox.Slugs()'\nfunc Slugs() []string {\n\tout := make([]string, 0, catalog.Len())\n\tfor _, t := range catalog.List() {\n\t\tout = append(out, t.Slug)\n\t}\n\treturn out\n}\n\n// PathOf returns the package path of one tool, or \"\" when there is no such\n// tool. Flat strings rather than the struct: a nested value inside a persisted\n// object prints as an opaque `ref(...)` over `vm/qeval`, so a read API that is\n// meant to be queried returns scalars.\n//\n//\tgnokey query vm/qeval -data 'gno.land/r/moul/toolbox.PathOf(\"usernames\")'\nfunc PathOf(slug string) string {\n\tt, ok := catalog.Get(slug)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn t.Path\n}\n\n// TitleOf returns the human name of one tool, or \"\".\nfunc TitleOf(slug string) string {\n\tt, ok := catalog.Get(slug)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn t.Title\n}\n\n// DescOf returns the one-line description of one tool, or \"\".\nfunc DescOf(slug string) string {\n\tt, ok := catalog.Get(slug)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn t.Desc\n}\n\n// Has reports whether a tool with that slug is listed.\nfunc Has(slug string) bool { return catalog.Has(slug) }\n\n// Tags lists every tag any tool carries, each once.\nfunc Tags() []string { return catalog.Tags() }\n"},{"name":"toolbox_test.gno","body":"package toolbox\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\ttb \"gno.land/p/moul/toolbox/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// TestEveryToolIsNested is the check that makes the compiled-in catalog safe:\n// a copy-pasted entry that kept the wrong path would publish a dead link, and\n// buildCatalog panics on it at deploy rather than at read.\nfunc TestEveryToolIsNested(t *testing.T) {\n\tuassert.True(t, len(tools) \u003e 0)\n\tfor _, tool := range tools {\n\t\tuassert.NoError(t, tool.Validate())\n\t\tuassert.Equal(t, tool.Slug, tb.SlugOf(hubPath, tool.Path))\n\t}\n}\n\nfunc TestReadAPI(t *testing.T) {\n\tuassert.Equal(t, len(tools), Count())\n\tuassert.True(t, Has(\"usernames\"))\n\tuassert.False(t, Has(\"nope\"))\n\tuassert.Equal(t, \"gno.land/r/moul/toolbox/usernames\", PathOf(\"usernames\"))\n\tuassert.Equal(t, \"Usernames\", TitleOf(\"usernames\"))\n\tuassert.True(t, strings.Contains(DescOf(\"usernames\"), \"address\"))\n\n\tuassert.Equal(t, \"\", PathOf(\"nope\"))\n\tuassert.Equal(t, \"\", TitleOf(\"nope\"))\n\tuassert.Equal(t, \"\", DescOf(\"nope\"))\n}\n\nfunc TestSlugsAreSorted(t *testing.T) {\n\tgot := Slugs()\n\tuassert.Equal(t, Count(), len(got))\n\tfor i := 1; i \u003c len(got); i++ {\n\t\tuassert.True(t, got[i-1] \u003c got[i])\n\t}\n}\n\nfunc TestTags(t *testing.T) {\n\tgot := Tags()\n\tuassert.True(t, len(got) \u003e 0)\n\tfound := false\n\tfor _, tag := range got {\n\t\tif tag == \"identity\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tuassert.True(t, found)\n}\n\nfunc TestRenderIndex(t *testing.T) {\n\tgot := Render(\"\")\n\tuassert.True(t, strings.Contains(got, \"# Toolbox\"))\n\tuassert.True(t, strings.Contains(got, \"[Usernames](/r/moul/toolbox/usernames)\"))\n\tuassert.True(t, strings.Contains(got, \"Tags:\"))\n}\n\nfunc TestRenderTagFilter(t *testing.T) {\n\tkept := Render(\"?tag=identity\")\n\tuassert.True(t, strings.Contains(kept, \"[Usernames](/r/moul/toolbox/usernames)\"))\n\tuassert.True(t, strings.Contains(kept, \"Show all\"))\n\n\tempty := Render(\"?tag=nope\")\n\tuassert.True(t, strings.Contains(empty, \"No tools yet.\"))\n\tuassert.False(t, strings.Contains(empty, \"[Usernames]\"))\n}\n\n// TestTagLinkIsURLEscaped: a tag is an arbitrary string on Tool, and\n// concatenating one into a query string unescaped turns \"a\u0026b\" into two\n// parameters and \"a#b\" into a fragment, so the link filters by something\n// nobody asked for. Values copied from what QueryEscape actually emits.\nfunc TestTagLinkIsURLEscaped(t *testing.T) {\n\tvar c tb.Catalog\n\tuassert.NoError(t, c.Set(tb.Tool{\n\t\tSlug:  \"weird\",\n\t\tPath:  \"gno.land/r/moul/toolbox/weird\",\n\t\tTitle: \"Weird\",\n\t\tTags:  []string{\"a\u0026b c\"},\n\t}))\n\n\tgot := tagLinks(\u0026c, hubURL)\n\tuassert.True(t, strings.Contains(got, \"?tag=a%26b+c\"))\n\tuassert.False(t, strings.Contains(got, \"?tag=a\u0026b c\"))\n}\n\nfunc TestTagLinksEmpty(t *testing.T) {\n\tvar c tb.Catalog\n\tuassert.Equal(t, \"\", tagLinks(\u0026c, hubURL))\n}\n\nfunc TestRenderTool(t *testing.T) {\n\tgot := Render(\"usernames\")\n\tuassert.True(t, strings.Contains(got, \"[toolbox](/r/moul/toolbox)\"))\n\tuassert.True(t, strings.Contains(got, \"## Usernames\"))\n\tuassert.True(t, strings.Contains(got, \"`gno.land/r/moul/toolbox/usernames`\"))\n}\n\nfunc TestRenderUnknown(t *testing.T) {\n\tfor _, path := range []string{\"nope\", \"a/b\", \"usernames/extra\"} {\n\t\tgot := Render(path)\n\t\tuassert.True(t, strings.Contains(got, \"# Not found\"))\n\t\tuassert.True(t, strings.Contains(got, \"Back to the toolbox\"))\n\t}\n}\n\n// TestRenderNeverEmitsTwoBlankLines: gno collapses them in an Output block, so\n// a Render that produces one can never be pinned by an example. Checked here\n// rather than discovered later.\nfunc TestRenderNeverEmitsTwoBlankLines(t *testing.T) {\n\tfor _, path := range []string{\"\", \"?tag=identity\", \"usernames\", \"nope\"} {\n\t\tuassert.False(t, strings.Contains(Render(path), \"\\n\\n\\n\"))\n\t}\n}\n"}]},"send":"","max_deposit":"7000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g108qxwrvwfrv8a39au4ckmspu6njghcsut4nu7s","package":{"name":"usernames","path":"gno.land/r/moul/toolbox/usernames","files":[{"name":"README.md","body":"# `gno.land/r/moul/toolbox/usernames`\n\n**Who holds a name, and what name an address holds.** Type either one into the box.\n\nIt is the page form of\n\n```sh\ngnokey query vm/qeval -remote https://rpc.gno.land \\\n  -data 'gno.land/r/sys/users.ResolveName(\"akkadia\")'\n```\n\nwith the three follow-up questions already asked: whether the name you typed is the user's\n**current** name or one they renamed away from, what canonical key it collapses to, and whether\na lookalike of it is already taken.\n\n```\n/r/moul/toolbox/usernames                 the form\n/r/moul/toolbox/usernames:lookup?q=moul   the result, where the form submits\n/r/moul/toolbox/usernames:moul            the same result, addressable directly\n/r/moul/toolbox/usernames:g1manfred...    the same, by address\n```\n\n## `ResolveAny` is the trap this tool exists not to repeat\n\n`r/sys/users.ResolveAny` returns `(*UserData, bool)` and the bool does not mean \"found\". For an\ninput that parses as an address it returns `(ResolveAddress(addr), true)` whatever the lookup\nproduced, so an unregistered address comes back as `(nil, true)`. Every caller that reads the\nbool and dereferences the pointer panics on the first address nobody claimed. This realm\nbranches on the input itself and checks the pointer, and pins the upstream behaviour in a test\nso a later fix is visible here.\n\n## The read API\n\n```sh\ngnokey query vm/qeval -remote https://rpc.gno.land \\\n  -data 'gno.land/r/moul/toolbox/usernames.Resolve(\"moul\")'\ngnokey query vm/qeval -remote https://rpc.gno.land \\\n  -data 'gno.land/r/moul/toolbox/usernames.AddressOf(\"moul\")'\n```\n\n`AddressOf` is the call another realm would want and the one it cannot have: this realm is\n`private = true`, so nothing can import it. Over `vm/qeval` it is the whole point.\n\nThree behaviours worth knowing:\n\n- **Not found means three different things**, and the page says which: a valid address with no\n  username, a name nobody ever held, and a name that **is** taken by an account that was deleted\n  or renamed away. The last one still refuses a registration, which is why it is not folded into\n  the second.\n- **An address is only ever looked up as an address.** A bech32 address is not a legal username,\n  so trying both would only widen what a typo can hit.\n- **The terminal hint disappears for input it cannot quote.** Nothing escapes inside a fenced\n  code block, so an input carrying a backtick gets no command block rather than a broken page.\n  Everything else the page reflects is escaped first.\n\nPart of [r/moul/toolbox](https://gno.land/r/moul/toolbox).\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/toolbox/usernames\"\ngno = \"0.9\"\n\n# Private, and therefore unversioned. See the hub at r/moul/toolbox.\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/toolbox/usernames\"\n  revision = \"015e568e04578f1d1fe1fc9a5c00505e9b9f08e6\"\n"},{"name":"render.gno","body":"package usernames\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\ttb \"gno.land/p/moul/toolbox/v0\"\n\t\"gno.land/r/sys/users\"\n)\n\n// hubURL is the toolbox this tool belongs to. A private realm cannot import\n// the hub, so the link is a constant on this side; `r/moul/toolbox` holds the\n// authoritative copy and its tests check that the tool path matches.\nconst hubURL = \"/r/moul/toolbox\"\n\n// maxInput bounds what is echoed back into the page. A render that reflects an\n// unbounded query parameter is a page anyone can make arbitrarily large.\nconst maxInput = 64\n\n// Render routes gnoweb paths:\n//\n//\t/                the form, and what the tool answers\n//\t/lookup?q=moul   the result, which is where the form submits\n//\t/moul            the same result, addressable directly\n//\t/g1manfred...    the same, by address\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\tparts := req.PathParts()\n\n\tinput := req.Query.Get(\"q\")\n\tif input == \"\" \u0026\u0026 len(parts) == 1 \u0026\u0026 parts[0] != \"\" \u0026\u0026 parts[0] != \"lookup\" {\n\t\tinput = parts[0]\n\t}\n\tif len(parts) \u003e 1 {\n\t\treturn header() + \"\\n\" + notFound(strings.Join(parts, \"/\"))\n\t}\n\tif input == \"\" {\n\t\treturn header() + \"\\n\" + renderHome()\n\t}\n\treturn header() + \"\\n\" + renderResult(input)\n}\n\nfunc header() string {\n\treturn tb.Nav(hubURL, \"Usernames\")\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"Usernames\"))\n\tb.WriteString(\"\\nWho holds a name, and what name an address holds. Type either one.\\n\")\n\tb.WriteString(\"\\n\" + form())\n\tb.WriteString(\"\\n\" + md.H2(\"What this answers\"))\n\tb.WriteString(\"\\n\" + md.BulletList([]string{\n\t\t\"The address behind a username, and the username behind an address.\",\n\t\t\"Whether the name you typed is their **current** name or one they renamed away from.\",\n\t\t\"The canonical key the name collapses to, and who already holds that key.\",\n\t}))\n\tb.WriteString(\"\\n\" + md.H2(\"The same thing from a terminal\"))\n\tb.WriteString(\"\\nThis page is \" + md.InlineCode(\"r/sys/users\") +\n\t\t\" read through \" + md.InlineCode(\"vm/qeval\") + \", with the follow-up questions already asked:\\n\")\n\tb.WriteString(\"\\n\" + md.LanguageCodeBlock(\"sh\", qevalCommand(\"moul\")))\n\tb.WriteString(\"\\nTry \" + md.Link(\"moul\", \"/r/moul/toolbox/usernames:moul\") +\n\t\t\", or paste an address into the box above.\\n\")\n\treturn b.String()\n}\n\nfunc renderResult(input string) string {\n\tvar b strings.Builder\n\tb.WriteString(md.H1(\"Usernames\"))\n\tb.WriteString(\"\\n\" + form())\n\n\tdata := lookup(input)\n\tif data == nil {\n\t\tb.WriteString(\"\\n\" + notFound(input))\n\t\treturn b.String()\n\t}\n\n\tt := ui.NewTable(\"Field\", \"Value\")\n\t// RenderLink builds `[@name](/u/name)` with no escaping of its own, which\n\t// is safe only because r/sys/users validates a name against\n\t// ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ before storing it: no pipe, no bracket,\n\t// nothing a table cell or a link would notice.\n\tt.Row(\"Username\", data.RenderLink(\"\"))\n\tt.Row(\"Address\", ui.AddrFull(data.Addr()))\n\tif current := CurrentName(input); current != \"\" {\n\t\t// One ui.Cell over the whole sentence, not a code span per name: a\n\t\t// code span escapes for running prose and leaves the `|` that would\n\t\t// split the row, and wrapping an already-escaped string again is the\n\t\t// double-wrap sanitize refuses to be idempotent about.\n\t\tt.Row(\"Note\", ui.Cell(\"You asked for \"+trim(input)+\n\t\t\t\", which is an earlier name. The current one is \"+current+\".\"))\n\t}\n\tt.Row(\"Canonical\", ui.Cell(users.Canonicalize(data.Name())))\n\tb.WriteString(\"\\n\" + t.String())\n\n\tif cmd := qevalCommand(input); cmd != \"\" {\n\t\tb.WriteString(\"\\n\" + md.LanguageCodeBlock(\"sh\", cmd))\n\t}\n\treturn b.String()\n}\n\nfunc notFound(input string) string {\n\tvar b strings.Builder\n\tb.WriteString(\"Nothing registered under \" + md.InlineCode(trim(input)) + \".\\n\")\n\tb.WriteString(\"\\n\" + md.BulletList(notFoundHints(input)))\n\treturn b.String()\n}\n\n// notFoundHints says what \"not found\" means for this particular input, which\n// is three different things.\nfunc notFoundHints(input string) []string {\n\ttrimmed := trim(input)\n\tif address(trimmed).IsValid() {\n\t\treturn []string{\n\t\t\t\"That is a valid address, so it exists on chain. It has no username.\",\n\t\t\t\"Register one at \" + md.Link(\"r/gnoland/users\", \"/r/gnoland/users\"),\n\t\t}\n\t}\n\thints := []string{\n\t\t\"Nobody holds it, or the account was deleted: a deleted name keeps its tombstone and resolves to nothing.\",\n\t}\n\tif owner := CanonicalOwner(trimmed); owner != \"\" {\n\t\thints = append(hints, \"A lookalike is taken: \"+md.InlineCode(owner)+\n\t\t\t\" already holds the canonical key \"+md.InlineCode(users.Canonicalize(trimmed))+\".\")\n\t} else if Taken(trimmed) {\n\t\thints = append(hints, \"The name IS taken, by an account that was deleted or renamed. Registering it would still fail.\")\n\t}\n\treturn hints\n}\n\nfunc form() string {\n\treturn tb.NewQuery(\"lookup\").Field(\"q\", \"username or g1 address\").String()\n}\n\n// qevalCommand is the CLI call this page is the equivalent of, with the input\n// substituted. It returns \"\" for an input that cannot be put inside a fenced\n// code block safely: nothing escapes inside a fence, so the only safe move is\n// not to print one.\nfunc qevalCommand(input string) string {\n\targ := trim(input)\n\tif !safeArg(arg) {\n\t\treturn \"\"\n\t}\n\treturn \"gnokey query vm/qeval -remote https://rpc.gno.land \\\\\\n\" +\n\t\t\"  -data 'gno.land/r/moul/toolbox/usernames.Resolve(\\\"\" + arg + \"\\\")'\"\n}\n\n// safeArg reports whether s can be interpolated into a shell single-quoted\n// string inside a markdown code fence. Usernames and addresses are both well\n// inside this set, so a refusal only ever hides the hint, never an answer.\nfunc safeArg(s string) bool {\n\tif s == \"\" || len(s) \u003e maxInput {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z':\n\t\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'Z':\n\t\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '_' || c == '-' || c == '.':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// trim bounds an echoed input. Everything downstream escapes it; this only\n// stops one query from rendering a page of arbitrary size.\n//\n// Cut on a rune boundary, not a byte one: s[:maxInput] on a multi-byte\n// character leaves half of it, and half a rune is not a character the escapers\n// downstream can do anything sensible with. Counting runes also makes the cap\n// mean the same thing for every alphabet.\nfunc trim(s string) string {\n\tn := 0\n\tfor i := range s {\n\t\tif n == maxInput {\n\t\t\treturn s[:i] + \"…\"\n\t\t}\n\t\tn++\n\t}\n\treturn s\n}\n"},{"name":"render_example_test.gno","body":"package usernames\n\n// ExampleRender pins the tool's landing page.\n//\n// The landing page only, deliberately: a result page reads r/sys/users, whose\n// state is whatever the tests in this package left behind, and an example runs\n// after all of them. The results are asserted in render_test.gno instead.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// [toolbox](/r/moul/toolbox) / **Usernames**\n\t//\n\t// # Usernames\n\t//\n\t// Who holds a name, and what name an address holds. Type either one.\n\t//\n\t// \u003cgno-form path=\"lookup\"\u003e\n\t// \u003cgno-input name=\"q\" type=\"text\" placeholder=\"username or g1 address\" /\u003e\n\t// \u003c/gno-form\u003e\n\t//\n\t// ## What this answers\n\t//\n\t// - The address behind a username, and the username behind an address.\n\t// - Whether the name you typed is their **current** name or one they renamed away from.\n\t// - The canonical key the name collapses to, and who already holds that key.\n\t//\n\t// ## The same thing from a terminal\n\t//\n\t// This page is `r/sys/users` read through `vm/qeval`, with the follow-up questions already asked:\n\t//\n\t// ```sh\n\t// gnokey query vm/qeval -remote https://rpc.gno.land \\\n\t//   -data 'gno.land/r/moul/toolbox/usernames.Resolve(\"moul\")'\n\t// ```\n\t//\n\t// Try [moul](/r/moul/toolbox/usernames:moul), or paste an address into the box above.\n}\n"},{"name":"render_test.gno","body":"package usernames\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRenderHome(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tgot := Render(\"\")\n\tuassert.True(t, strings.Contains(got, \"[toolbox](/r/moul/toolbox)\"))\n\tuassert.True(t, strings.Contains(got, \"# Usernames\"))\n\tuassert.True(t, strings.Contains(got, `\u003cgno-form path=\"lookup\"\u003e`))\n\tuassert.True(t, strings.Contains(got, `\u003cgno-input name=\"q\"`))\n\tuassert.True(t, strings.Contains(got, \"gnokey query vm/qeval\"))\n}\n\nfunc TestRenderResultByPathAndByQuery(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tbyPath := Render(\"moul\")\n\tbyQuery := Render(\"lookup?q=moul\")\n\tuassert.Equal(t, byPath, byQuery)\n\tuassert.True(t, strings.Contains(byPath, \"[@moul](/u/moul)\"))\n\tuassert.True(t, strings.Contains(byPath, moulAddr.String()))\n\tuassert.True(t, strings.Contains(byPath, \"Canonical\"))\n}\n\nfunc TestRenderResultByAddress(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tgot := Render(moulAddr.String())\n\tuassert.True(t, strings.Contains(got, \"[@moul](/u/moul)\"))\n}\n\nfunc TestRenderNotFound(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tgot := Render(\"nobodyholdsthis\")\n\tuassert.True(t, strings.Contains(got, \"Nothing registered under\"))\n\tuassert.True(t, strings.Contains(got, \"deleted\"))\n\n\taddr := Render(plainAddr.String())\n\tuassert.True(t, strings.Contains(addr, \"That is a valid address\"))\n\tuassert.True(t, strings.Contains(addr, \"/r/gnoland/users\"))\n}\n\nfunc TestRenderTooManyParts(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tgot := Render(\"a/b\")\n\tuassert.True(t, strings.Contains(got, \"Nothing registered under\"))\n}\n\n// TestRenderEscapesInput: the query parameter is attacker-chosen and a live\n// realm can never be fixed, so this is the test that must be seen to fail\n// before it is believed.\n//\n// The property is that the echo is INERT, not that particular bytes are\n// absent. A code span makes link syntax inert without removing it, so an\n// assertion that the substring is gone would pass for the wrong reason under\n// one escaper and fail for the wrong reason under the other.\nfunc TestRenderEscapesInput(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tconst link = \"[x](javascript:alert(1))\"\n\tgot := Render(\"lookup?q=\" + \"%5Bx%5D%28javascript%3Aalert%281%29%29\")\n\tuassert.True(t, strings.Contains(got, \"`\"+link+\"`\"))\n\tuassert.False(t, strings.Contains(got, \" \"+link+\" \"))\n\n\t// A backtick in the input cannot close the span early: the fence widens.\n\ttick := Render(\"lookup?q=a%60b\")\n\tuassert.True(t, strings.Contains(tick, \"``\"))\n\tuassert.False(t, strings.Contains(tick, \"under `a`b`.\"))\n\n\t// A heading marker cannot open a block of its own: the echo stays on the\n\t// line it was put on.\n\thead := Render(\"lookup?q=%0A%23%20pwned\")\n\tuassert.False(t, strings.Contains(head, \"\\n# pwned\"))\n}\n\n// TestRenderOmitsTheCommandForUnsafeInput: nothing escapes inside a fenced\n// code block, so an input that cannot go in one does not get one.\nfunc TestRenderOmitsTheCommandForUnsafeInput(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tuassert.True(t, strings.Contains(Render(\"moul\"), \"gnokey query vm/qeval\"))\n\tuassert.False(t, strings.Contains(Render(\"lookup?q=a%60b\"), \"gnokey query vm/qeval\"))\n}\n\nfunc TestRenderNeverEmitsTwoBlankLines(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tfor _, path := range []string{\"\", \"moul\", \"nobodyholdsthis\", moulAddr.String(), \"a/b\"} {\n\t\tuassert.False(t, strings.Contains(Render(path), \"\\n\\n\\n\"))\n\t}\n}\n"},{"name":"usernames.gno","body":"// Package usernames is the toolbox tool for gno.land identities: it turns a\n// username into an address, an address into a username, and tells you which\n// of the two you are actually holding.\n//\n// It is the page form of\n//\n//\tgnokey query vm/qeval --data 'gno.land/r/sys/users.ResolveName(\"akkadia\")' -remote https://rpc.gno.land\n//\n// with the three things that query does not tell you: whether the name you\n// asked about is the user's CURRENT name or an alias they renamed away from,\n// what canonical key it collapses to, and whether a lookalike of it is already\n// taken.\n//\n// # Why not r/sys/users.ResolveAny\n//\n// `ResolveAny` returns `(*UserData, bool)` and the bool does not mean \"found\".\n// For an input that parses as an address it returns `(ResolveAddress(addr),\n// true)` whatever the lookup produced, so an unregistered address comes back\n// as `(nil, true)`. Every caller that reads the bool and dereferences the\n// pointer panics on the first address nobody claimed. [lookup] branches on the\n// input itself and checks the pointer instead.\n//\n// Part of [r/moul/toolbox](/r/moul/toolbox).\npackage usernames\n\nimport \"gno.land/r/sys/users\"\n\n// lookup resolves any input to a user record, or nil.\n//\n// An input that parses as a gno.land address is only ever looked up as an\n// address, and anything else only as a name: a bech32 address is not a legal\n// username, so trying both would only widen what a typo can hit.\nfunc lookup(input string) *users.UserData {\n\tif input == \"\" {\n\t\treturn nil\n\t}\n\tif addr := address(input); addr.IsValid() {\n\t\treturn users.ResolveAddress(addr)\n\t}\n\tdata, _ := users.ResolveName(input)\n\treturn data\n}\n\n// Resolve returns the current username and the address behind any input, a\n// username or a `g1` address.\n//\n// found is false when nobody holds it, which is also the answer for a deleted\n// user: `r/sys/users` keeps the tombstone and resolves it to nothing.\n//\n//\tgnokey query vm/qeval -data 'gno.land/r/moul/toolbox/usernames.Resolve(\"moul\")'\nfunc Resolve(input string) (name string, addr string, found bool) {\n\tdata := lookup(input)\n\tif data == nil {\n\t\treturn \"\", \"\", false\n\t}\n\treturn data.Name(), data.Addr().String(), true\n}\n\n// AddressOf returns the address behind a username or an address, or \"\" when\n// nobody holds it.\n//\n// It is the call another realm would want, and the one it cannot have: this\n// realm is `private = true`, so nothing can import it. Over `vm/qeval` it is\n// the whole point.\n//\n//\tgnokey query vm/qeval -data 'gno.land/r/moul/toolbox/usernames.AddressOf(\"moul\")'\nfunc AddressOf(input string) string {\n\t_, addr, found := Resolve(input)\n\tif !found {\n\t\treturn \"\"\n\t}\n\treturn addr\n}\n\n// NameOf returns the current username behind a username or an address, or \"\"\n// when nobody holds it.\nfunc NameOf(input string) string {\n\tname, _, found := Resolve(input)\n\tif !found {\n\t\treturn \"\"\n\t}\n\treturn name\n}\n\n// Display returns what a page should print for an input: \"@name\" when there is\n// a username, and the input unchanged when there is not.\n//\n// So it is total over every input a page actually has, and a caller never has\n// to branch on \"not found\" the way [NameOf] makes it. The one input it has\n// nothing to say about is \"\", which it returns unchanged: an empty answer to an\n// empty question, rather than a placeholder a page would then have to special\n// case anyway.\nfunc Display(input string) string {\n\tif name := NameOf(input); name != \"\" {\n\t\treturn \"@\" + name\n\t}\n\treturn input\n}\n\n// CurrentName reports the user's current name when input is an alias they\n// renamed away from, and \"\" otherwise.\n//\n// `r/sys/users` keeps old names resolving on purpose, so an address looked up\n// by a name that is no longer current is not an error and nothing in the\n// resolve result says so. This is the one call that does.\nfunc CurrentName(input string) string {\n\tif input == \"\" {\n\t\treturn \"\"\n\t}\n\tif addr := address(input); addr.IsValid() {\n\t\treturn \"\"\n\t}\n\tdata, isCurrent := users.ResolveName(input)\n\tif data == nil || isCurrent {\n\t\treturn \"\"\n\t}\n\treturn data.Name()\n}\n\n// Canonical returns the canonical key a name collapses to. Two names with the\n// same canonical form cannot both be registered, which is how `r/sys/users`\n// refuses a lookalike of an existing account.\n//\n//\tgnokey query vm/qeval -data 'gno.land/r/moul/toolbox/usernames.Canonical(\"M0ul\")'\nfunc Canonical(name string) string { return users.Canonicalize(name) }\n\n// Taken reports whether the exact name is registered, including names that\n// were deleted or renamed away from: it answers \"would registering this\n// fail\", not \"is somebody using this\".\nfunc Taken(name string) bool {\n\tif name == \"\" {\n\t\treturn false\n\t}\n\treturn users.IsNameTaken(name)\n}\n\n// CanonicalOwner returns the name that already holds this name's canonical\n// key, or \"\" when the key is free. A non-empty answer that is not the name\n// itself is a lookalike collision.\nfunc CanonicalOwner(name string) string {\n\tif name == \"\" {\n\t\treturn \"\"\n\t}\n\texisting, taken := users.IsCanonicalTaken(name)\n\tif !taken {\n\t\treturn \"\"\n\t}\n\treturn existing\n}\n"},{"name":"usernames_test.gno","body":"package usernames\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"unicode/utf8\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/sys/users\"\n)\n\nconst (\n\tmoulAddr  = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\tplainAddr = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n)\n\n// controllerPath is the realm r/sys/users whitelists in its own init when the\n// chain id is \"dev\", which is what `gno test` runs as. Registering a fixture\n// means borrowing that identity: this package is not a controller and\n// AddControllerAtGenesis cannot be reached from here, since its `_ realm`\n// first parameter is the non-crossing threaded form and an external realm\n// refuses a cur-call to one.\nconst controllerPath = \"gno.land/r/sys/users/init\"\n\n// seed registers the fixtures every test in this file reads.\n//\n// The SetRealm is immediately followed by a crossing call, which is the only\n// shape that works: in a helper that does not itself cross, the switch is\n// silently dropped and the caller stays whoever it was.\nfunc seed(cur realm, t *testing.T) {\n\tt.Helper()\n\tif users.IsNameTaken(\"moul\") {\n\t\treturn\n\t}\n\ttesting.SetRealm(testing.NewCodeRealm(controllerPath))\n\turequire.NoError(t, users.RegisterUser(cross(cur), \"moul\", moulAddr))\n}\n\nfunc TestResolveByName(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tname, addr, found := Resolve(\"moul\")\n\tuassert.True(t, found)\n\tuassert.Equal(t, \"moul\", name)\n\tuassert.Equal(t, moulAddr.String(), addr)\n}\n\nfunc TestResolveByAddress(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tname, addr, found := Resolve(moulAddr.String())\n\tuassert.True(t, found)\n\tuassert.Equal(t, \"moul\", name)\n\tuassert.Equal(t, moulAddr.String(), addr)\n}\n\nfunc TestResolveMisses(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tcases := []struct {\n\t\tname  string\n\t\tinput string\n\t}{\n\t\t{\"empty\", \"\"},\n\t\t{\"unknown name\", \"nobodyholdsthis\"},\n\t\t{\"valid address with no name\", plainAddr.String()},\n\t\t{\"not an address and not a name\", \"g1notanaddress\"},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t_, _, found := Resolve(tc.input)\n\t\t\tuassert.False(t, found)\n\t\t})\n\t}\n}\n\n// TestResolveAnyTrap is the defect this tool exists not to repeat: for an\n// input that parses as an address, r/sys/users.ResolveAny reports true\n// whatever the lookup produced, so the pointer it returns can be nil. Pinned\n// against the vendored copy so a later upstream fix is visible here.\nfunc TestResolveAnyTrap(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tdata, ok := users.ResolveAny(plainAddr.String())\n\tuassert.True(t, ok)\n\tuassert.True(t, data == nil)\n\n\t_, _, found := Resolve(plainAddr.String())\n\tuassert.False(t, found)\n}\n\nfunc TestAccessors(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tuassert.Equal(t, moulAddr.String(), AddressOf(\"moul\"))\n\tuassert.Equal(t, \"moul\", NameOf(moulAddr.String()))\n\tuassert.Equal(t, \"@moul\", Display(\"moul\"))\n\tuassert.Equal(t, \"@moul\", Display(moulAddr.String()))\n\n\tuassert.Equal(t, \"\", AddressOf(\"nobodyholdsthis\"))\n\tuassert.Equal(t, \"\", NameOf(\"nobodyholdsthis\"))\n\tuassert.Equal(t, \"nobodyholdsthis\", Display(\"nobodyholdsthis\"))\n}\n\nfunc TestCanonicalAndTaken(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tuassert.Equal(t, users.Canonicalize(\"moul\"), Canonical(\"moul\"))\n\tuassert.True(t, Taken(\"moul\"))\n\tuassert.False(t, Taken(\"nobodyholdsthis\"))\n\tuassert.False(t, Taken(\"\"))\n\n\tuassert.Equal(t, \"moul\", CanonicalOwner(\"moul\"))\n\tuassert.Equal(t, \"\", CanonicalOwner(\"nobodyholdsthis\"))\n\tuassert.Equal(t, \"\", CanonicalOwner(\"\"))\n}\n\n// TestCurrentNameOnAlias: r/sys/users keeps an old name resolving after a\n// rename and nothing in the resolve result says it is old. CurrentName is the\n// only call that does.\nfunc TestCurrentNameOnAlias(cur realm, t *testing.T) {\n\tseed(cur, t)\n\n\tconst old = \"aliasfixture\"\n\tconst now = \"renamedfixture\"\n\n\tif !users.IsNameTaken(old) {\n\t\ttesting.SetRealm(testing.NewCodeRealm(controllerPath))\n\t\turequire.NoError(t, users.RegisterUser(cross(cur), old, plainAddr))\n\t}\n\n\tdata := users.ResolveAddress(plainAddr)\n\turequire.True(t, data != nil)\n\tif data.Name() == old {\n\t\ttesting.SetRealm(testing.NewCodeRealm(controllerPath))\n\t\turequire.NoError(t, data.UpdateName(0, cur, now))\n\t}\n\n\tuassert.Equal(t, now, CurrentName(old))\n\tuassert.Equal(t, \"\", CurrentName(now))\n\tuassert.Equal(t, \"\", CurrentName(plainAddr.String()))\n\tuassert.Equal(t, \"\", CurrentName(\"nobodyholdsthis\"))\n\tuassert.Equal(t, \"\", CurrentName(\"\"))\n\n\t// The old name still resolves, to the current one.\n\tname, _, found := Resolve(old)\n\tuassert.True(t, found)\n\tuassert.Equal(t, now, name)\n}\n\nfunc TestSafeArg(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   string\n\t\twant bool\n\t}{\n\t\t{\"username\", \"moul\", true},\n\t\t{\"address\", \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\", true},\n\t\t{\"dashes and dots\", \"a-b.c_d\", true},\n\t\t{\"empty\", \"\", false},\n\t\t{\"quote\", \"a'b\", false},\n\t\t{\"backtick\", \"a`b\", false},\n\t\t{\"fence\", \"```\", false},\n\t\t{\"dollar\", \"$(id)\", false},\n\t\t{\"too long\", strings.Repeat(\"a\", maxInput+1), false},\n\t\t{\"exactly max\", strings.Repeat(\"a\", maxInput), true},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, safeArg(tc.in))\n\t\t})\n\t}\n}\n\nfunc TestTrim(t *testing.T) {\n\tuassert.Equal(t, \"moul\", trim(\"moul\"))\n\tlong := strings.Repeat(\"a\", maxInput+10)\n\tuassert.Equal(t, strings.Repeat(\"a\", maxInput)+\"…\", trim(long))\n}\n\n// TestTrimCutsOnARuneBoundary: a byte cut at maxInput lands inside the\n// multi-byte character here and leaves half of it, which no escaper\n// downstream can do anything sensible with.\nfunc TestTrimCutsOnARuneBoundary(t *testing.T) {\n\tin := strings.Repeat(\"a\", maxInput-1) + \"é\" + \"tail\"\n\tgot := trim(in)\n\tuassert.Equal(t, strings.Repeat(\"a\", maxInput-1)+\"é\"+\"…\", got)\n\tuassert.True(t, utf8.ValidString(got))\n\n\t// And the cap counts characters, not bytes, so an all-multibyte input\n\t// keeps maxInput of them rather than half as many.\n\taccents := strings.Repeat(\"é\", maxInput+5)\n\tuassert.Equal(t, strings.Repeat(\"é\", maxInput)+\"…\", trim(accents))\n}\n\n// TestDisplayOnEmpty pins the one input Display has nothing to say about.\nfunc TestDisplayOnEmpty(t *testing.T) {\n\tuassert.Equal(t, \"\", Display(\"\"))\n}\n"}]},"send":"","max_deposit":"11000000ugnot"}],"fee":{"gas_wanted":"129232400","gas_fee":"387697ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"AjZyqpH4vJ3WLLVeLtRl+F2StxRT+LawNoGVosjVwS/F"},"signature":"bDFE7TgV8JF26sqvs5bdfrjf+IRAboFA8niD71T/sitgy9RdyUn8iN0BGKiOgcEIZdX7qWve8V6GNPFElbRszQ=="}],"memo":""},"metadata":{"timestamp":"1791555914"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"8ThJL2+gSjaXQ8LkWZHyCN7bGZAvjPfW9yoG5nZsvgRfMtj+2SPvtivlR6AkoWZI5XgETZQ4JFzwmsYFHE9LMw=="}],"memo":""},"metadata":{"timestamp":"1791555915"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"bfdemo","path":"gno.land/r/moul/x/vm/bfdemo/v0","files":[{"name":"README.md","body":"# r/moul/x/vm/bfdemo\n\nA realm that runs Brainfuck programs on chain, a slice at a time.\n\nIt is a demo of [`p/moul/x/vm/bf`](/p/moul/x/vm/bf/v0) (the machine) and\n[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, the\ninstance store), and carries no logic of its own.\n\nWhat it exists to show is the thing gno realm code cannot do for itself: a\nprogram that runs out of fuel does not fail, it pauses. The realm keeps the\nsnapshot, and the next caller pays for the next slice. Upload a program, call\n`Step` a few times, and watch one computation finish across several\ntransactions.\n\n## Calls\n\n| function | what |\n|---|---|\n| `Upload(src, input, budget)` | compile and store a program, returns its id. Compilation happens here, so a malformed program is rejected by the transaction that submitted it |\n| `Step(id, fuel)` | run one slice and keep the snapshot. Anyone may pay for a slice, not only the owner |\n| `Remove(id)` | delete an instance. Owner only |\n\n`Render(\"/\")` lists the instances and offers three sample programs.\n`Render(\"/\u003cid\u003e\")` shows one instance: its compiled program, status, fuel, and\noutput.\n\n## Limits\n\nEverything a caller can grow is bounded, because all of it is storage somebody\npays a deposit on: 64 instances, 64 KiB of source, 1 KiB of input, 4 KiB of\noutput, 5,000,000 fuel per slice, 30,000 tape cells. A guest that writes past\nthe output cap is trapped rather than truncated, so the rendered output is never\na lie.\n\n## Untrusted input\n\nA program's source is caller-supplied, and everything outside the eight\noperators is a comment that may hold anything at all. The page never renders it:\nit shows the program the machine actually compiled, which cannot contain a\nbacktick or a newline and so cannot break out of its code fence. Guest output is\narbitrary bytes and is escaped the same way, backtick included.\n\nNo instance is funded, so `Host.Send` always returns `ErrNotGranted`. That is\nthe capability rule doing its job, not a missing feature.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/vm/bfdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/bfdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/vm/bfdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/vm/bfdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"bfdemo.gno","body":"// Package bfdemo is the playground for the guest-VM work: a realm that runs\n// Brainfuck programs on chain, a slice at a time.\n//\n// It is a demo of two libraries and carries no logic of its own:\n// [p/moul/x/vm/bf](/p/moul/x/vm/bf/v0) is the machine, and\n// [p/moul/x/vm/vmkit](/p/moul/x/vm/vmkit/v0) is the host ABI, the fuel meter\n// and the instance store.\n//\n// What it exists to show is the thing gno realm code cannot do for itself: a\n// program that runs out of fuel does not fail, it pauses. The realm keeps the\n// snapshot, and the next caller pays for the next slice. Upload a program,\n// call Step a few times, and watch one computation finish across several\n// transactions.\npackage bfdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/vm/bf/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// Caps. Everything a caller can grow is bounded, because all of it is storage\n// somebody pays a deposit on.\nconst (\n\t// MaxInstances is how many programs the realm keeps at once. Past it,\n\t// an upload has to wait for someone to remove one.\n\tMaxInstances = 64\n\t// MaxOutput caps the bytes one program may write. Past it the guest is\n\t// trapped rather than truncated, so rendered output is never a lie.\n\tMaxOutput = 4096\n\t// MaxInput caps the call input a program can be given.\n\tMaxInput = 1024\n\t// DefaultFuel is the budget an upload gets when it asks for none, and\n\t// the slice size Step uses when asked for none.\n\tDefaultFuel = 100000\n\t// MaxSliceFuel bounds one transaction's work regardless of what the\n\t// caller asked for.\n\tMaxSliceFuel = 5000000\n)\n\nvar (\n\t// store holds the instances: program, snapshot, status, accounting.\n\tstore = vmkit.NewStore()\n\t// inputs holds each instance's call input, keyed by id. It is separate\n\t// from the instance so vmkit.Instance stays the VM-agnostic record it\n\t// is meant to be.\n\tinputs = avl.NewTree()\n\tidgen  seqid.ID\n\tcount  int\n)\n\n// host is the realm-backed [vmkit.Host]. One is built per call, wrapping the\n// instance being stepped, so a guest's output and authority are scoped to it\n// and nothing ambient leaks in.\ntype host struct {\n\tinst    *vmkit.Instance\n\tin      []byte\n\tkv      *avl.Tree\n\toverrun bool // the guest wrote past MaxOutput\n}\n\nfunc (h *host) Caller() address { return h.inst.Owner }\nfunc (h *host) Origin() address { return h.inst.Owner }\nfunc (h *host) Now() int64      { return time.Now().Unix() }\nfunc (h *host) Height() int64   { return runtime.ChainHeight() }\nfunc (h *host) Input() []byte   { return h.in }\n\n// Get and Set are scoped to the instance by construction: the tree belongs to\n// the instance being stepped, so one program cannot reach another's storage\n// even though both live in this one realm. bf never calls them; they are here\n// because the ABI is the point.\nfunc (h *host) Get(key []byte) []byte {\n\tv := h.kv.Get(string(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.([]byte)\n}\n\nfunc (h *host) Set(key, val []byte) { h.kv.Set(string(key), val) }\n\nfunc (h *host) Output(p []byte) {\n\tif len(h.inst.Output)+len(p) \u003e MaxOutput {\n\t\th.overrun = true\n\t\treturn\n\t}\n\th.inst.Output = append(h.inst.Output, p...)\n}\n\nfunc (h *host) Emit(typ string, kv ...string) { chain.Emit(typ, kv...) }\n\n// Send is never granted here. The demo funds no instance, so a guest that\n// tries to move coins is refused. That is the capability rule doing its job,\n// not a missing feature.\nfunc (h *host) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\n\nfunc (h *host) Log(msg string) {}\n\n// Upload compiles src and stores it as a new instance, returning its id.\n//\n// Compilation happens here rather than at the first Step, so an unbalanced\n// program is rejected by the transaction that submitted it instead of costing\n// somebody else the gas later.\nfunc Upload(cur realm, src, input string, budget int64) string {\n\tif count \u003e= MaxInstances {\n\t\tpanic(\"bfdemo: too many instances, remove one first\")\n\t}\n\tif len(input) \u003e MaxInput {\n\t\tpanic(\"bfdemo: input too long\")\n\t}\n\tif _, err := bf.CompileDefault(src); err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\tif budget \u003c= 0 {\n\t\tbudget = DefaultFuel\n\t}\n\n\tid := idgen.Next().String()\n\towner := unsafe.PreviousRealm().Address()\n\tstore.Set(vmkit.NewInstance(id, owner, bf.VMName, []byte(src), budget))\n\tif input != \"\" {\n\t\tinputs.Set(id, input)\n\t}\n\tcount++\n\n\tchain.Emit(\"bf_upload\", \"id\", id, \"bytes\", ufmt.Sprintf(\"%d\", len(src)))\n\treturn id\n}\n\n// Step runs one slice of the instance: up to `fuel` guest ops, then stop and\n// keep the snapshot. Anyone may pay for a slice, not only the owner: a paused\n// program that only its owner can advance is a worse demo and no safer, since\n// the program and its budget were both fixed at upload.\nfunc Step(cur realm, id string, fuel int64) string {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"bfdemo: no such instance\")\n\t}\n\tif inst.Status != vmkit.Running {\n\t\tpanic(\"bfdemo: instance is \" + inst.Status.String())\n\t}\n\tif fuel \u003c= 0 {\n\t\tfuel = DefaultFuel\n\t}\n\tif fuel \u003e MaxSliceFuel {\n\t\tfuel = MaxSliceFuel\n\t}\n\n\tprog, err := bf.CompileDefault(string(inst.Program))\n\tif err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\th := \u0026host{inst: inst, in: []byte(inputOf(id)), kv: avl.NewTree()}\n\tif err := inst.Run(bf.NewMachine(prog), h, fuel); err != nil {\n\t\tpanic(\"bfdemo: \" + err.Error())\n\t}\n\tif h.overrun {\n\t\tinst.Status = vmkit.Trapped\n\t\tinst.Trap = \"output limit reached\"\n\t}\n\n\tchain.Emit(\"bf_step\",\n\t\t\"id\", id,\n\t\t\"status\", inst.Status.String(),\n\t\t\"fuel\", ufmt.Sprintf(\"%d\", inst.FuelUsed),\n\t)\n\treturn inst.Status.String()\n}\n\n// Remove deletes an instance. Owner only.\nfunc Remove(cur realm, id string) {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"bfdemo: no such instance\")\n\t}\n\tif inst.Owner != unsafe.PreviousRealm().Address() {\n\t\tpanic(\"bfdemo: not your instance\")\n\t}\n\tstore.Remove(id)\n\tinputs.Remove(id)\n\tcount--\n}\n\nfunc inputOf(id string) string {\n\tv := inputs.Get(id)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n"},{"name":"bfdemo_test.gno","body":"package bfdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst hello = \"++++++++++[\u003e+++++++\u003e++++++++++\u003e+++\u003e+\u003c\u003c\u003c\u003c-]\u003e++.\u003e+.+++++++..+++.\u003e++.\u003c\u003c+++++++++++++++.\u003e.+++.------.--------.\"\n\n// resetState puts the realm globals back where init() left them. Realm state\n// persists for the whole test binary, so every test that asserts on ids or on\n// the rendered instance list has to start from here.\nfunc resetState() {\n\tstore = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen = seqid.ID(0)\n\tcount = 0\n}\n\nfunc TestUploadAndRunToCompletion(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := Upload(cross(cur), hello, \"\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"Hello World\", string(inst.Output))\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, alice, inst.Owner)\n}\n\n// TestOneProgramAcrossManyTransactions is what the realm exists to\n// demonstrate: the same computation, finished over several calls, each paying\n// for its own slice.\nfunc TestOneProgramAcrossManyTransactions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\tid := Upload(cross(cur), hello, \"\", 0)\n\tstatus := \"\"\n\tslices := 0\n\tfor slices \u003c 500 {\n\t\tstatus = Step(cross(cur), id, 7)\n\t\tslices++\n\t\tif status != \"running\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"halted\", status)\n\tuassert.Equal(t, \"Hello World\", string(inst.Output))\n\tuassert.True(t, inst.Slices \u003e 1, \"took more than one slice\")\n}\n\nfunc TestInputIsReadThroughTheHost(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// \",[.,]\" echoes its input back.\n\tid := Upload(cross(cur), \",[.,]\", \"gno.land\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\tuassert.Equal(t, \"gno.land\", string(store.Get(id).Output))\n}\n\nfunc TestBudgetStopsAProgram(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\tid := Upload(cross(cur), hello, \"\", 12)\n\tuassert.Equal(t, \"out of fuel\", Step(cross(cur), id, 0))\n\tuassert.Equal(t, int64(12), store.Get(id).FuelUsed)\n\n\t// And it stays stopped rather than quietly continuing.\n\tuassert.AbortsContains(t, cur, \"instance is out of fuel\", func() {\n\t\tStep(cross(cur), id, 0)\n\t})\n}\n\nfunc TestUploadRejectsAMalformedProgram(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// Rejected by the transaction that submitted it, not by whoever pays\n\t// for the first slice later.\n\tuassert.AbortsContains(t, cur, \"unmatched\", func() {\n\t\tUpload(cross(cur), \"+++[\", \"\", 0)\n\t})\n\tuassert.Equal(t, 0, count)\n}\n\nfunc TestRemoveIsOwnerOnly(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tid := Upload(cross(cur), hello, \"\", 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tuassert.AbortsContains(t, cur, \"not your instance\", func() {\n\t\tRemove(cross(cur), id)\n\t})\n\n\t// Anyone may pay for a slice, though: the program and its budget were\n\t// both fixed at upload.\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tRemove(cross(cur), id)\n\tuassert.Equal(t, 0, count)\n\tuassert.True(t, store.Get(id) == nil)\n}\n\nfunc TestOutputIsCappedAndTrapped(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// A cell set to 1 and printed forever: an infinite writer.\n\tid := Upload(cross(cur), \"+[.]\", \"\", 0)\n\tstatus := Step(cross(cur), id, 0)\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"trapped\", status)\n\tuassert.Equal(t, \"output limit reached\", inst.Trap)\n\tuassert.Equal(t, MaxOutput, len(inst.Output))\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tresetState()\n\tuassert.True(t, strings.Contains(Render(\"/nope\"), \"No such instance\"))\n}\n\n// TestRenderEscapesGuestOutput pins the rule that a realm cannot be fixed in\n// place once it is live: everything a caller controls is escaped before it\n// reaches the page.\nfunc TestRenderEscapesGuestOutput(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\n\t// Print a backtick (96), which would otherwise close the code fence.\n\tsrc := strings.Repeat(\"+\", 96) + \".\"\n\tid := Upload(cross(cur), src, \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tpage := Render(\"/\" + id)\n\tuassert.Equal(t, \"`\", string(store.Get(id).Output))\n\tuassert.True(t, strings.Contains(page, \"\\\\x60\"), \"the backtick is escaped\")\n\n\t// The comment text in a program never reaches the page at all: only\n\t// the eight operators do.\n\tuassert.Equal(t, \"+++[-]\u003c\u003e\", operatorsOnly(\"+++ this is a comment [-] \u003c/script\u003e\"))\n}\n\n// Output sits in a code span, where markdown escapes show verbatim: only the\n// pipe is escaped there, and nothing else.\nfunc TestCodeCell(t *testing.T) {\n\tuassert.Equal(t, \"`Hello, gno.land\\\\n`\", codeCell(\"Hello, gno.land\\\\n\"))\n\tuassert.Equal(t, \"`a\\\\|b`\", codeCell(\"a|b\"))\n}\n\n// emit returns a program that prints s, one byte at a time, so a test can put\n// any text in the output column without hand-writing Brainfuck.\nfunc emit(s string) string {\n\tvar sb strings.Builder\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tsb.WriteString(\"[-]\" + strings.Repeat(\"+\", int(s[i])) + \".\")\n\t}\n\treturn sb.String()\n}\n\n// instanceRow returns the first instance row of the home page.\nfunc instanceRow(t *testing.T) string {\n\tfor _, line := range strings.Split(Render(\"\"), \"\\n\") {\n\t\tif strings.HasPrefix(line, \"| [\") {\n\t\t\treturn line\n\t\t}\n\t}\n\tt.Fatalf(\"no instance row on the home page\")\n\treturn \"\"\n}\n\n// The output column is pinned on the rendered page, not only through the\n// helper, so the call site cannot drift back to ui.Cell inside backticks\n// (which would show `a\\.b`) with the suite green.\nfunc TestRenderOutputCell(cur realm, t *testing.T) {\n\tcases := []struct {\n\t\tname, out, cell string\n\t}{\n\t\t{\"an escapable character shows as written\", \"a.b\", \"| `a.b` |\"},\n\t\t{\"no output is an empty cell, not two backticks\", \"\", \"| 0 |  |\"},\n\t\t{\"a space at each end is padded in the markdown, past CommonMark's strip\", \" a \", \"| `  a  ` |\"},\n\t\t{\"a guest pipe stays inside its cell\", \"a|b\", \"| `a\\\\|b` |\"},\n\t}\n\tfor _, c := range cases {\n\t\tresetState()\n\t\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\t\tid := Upload(cross(cur), emit(c.out), \"\", 0)\n\t\tif c.out != \"\" {\n\t\t\tStep(cross(cur), id, 0)\n\t\t\tuassert.Equal(t, c.out, string(store.Get(id).Output))\n\t\t}\n\t\trow := instanceRow(t)\n\t\tuassert.True(t, strings.HasSuffix(row, c.cell), c.name+\": \"+row)\n\t}\n}\n\n// codeCell follows the three rules of a code span, not only the pipe: empty\n// content is not a span, a space at either end needs a pad, and the fence\n// outscans any backtick run in the content.\nfunc TestCodeCellRules(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"Hello World\", \"`Hello World`\"},\n\t\t{\"a|b\", \"`a\\\\|b`\"},\n\t\t{\" hi \", \"`  hi  `\"},\n\t\t{\" hi\", \"`  hi `\"},\n\t\t{\"hi \", \"` hi  `\"},\n\t\t{\"a`b\", \"``a`b``\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, codeCell(c.in), \"codeCell(\"+c.in+\")\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/vm/bfdemo/v0\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/vm/bfdemo\"\n  revision = \"d28fdd63c03756044952283a995142d29fd9b09a\"\n"},{"name":"render.gno","body":"package bfdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/x/vm/bf/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// samples are the programs the home page offers, so the realm is usable\n// without writing Brainfuck by hand.\nvar samples = []struct {\n\tname  string\n\tsrc   string\n\tinput string\n\tnote  string\n}{\n\t{\n\t\t\"Hello World\",\n\t\t\"++++++++++[\u003e+++++++\u003e++++++++++\u003e+++\u003e+\u003c\u003c\u003c\u003c-]\u003e++.\u003e+.+++++++..+++.\u003e++.\u003c\u003c+++++++++++++++.\u003e.+++.------.--------.\",\n\t\t\"\",\n\t\t\"385 guest ops, five tape cells. Finishes in one slice.\",\n\t},\n\t{\n\t\t\"Echo the input\",\n\t\t\",[.,]\",\n\t\t\"gno.land\",\n\t\t\"Reads through Host.Input, which is what the naive interpreter could not do at all: it panicked on `,`.\",\n\t},\n\t{\n\t\t\"Heavy loop\",\n\t\t\"++++++++++[-\u003e++++++++++[-\u003e++++++++++[-]\u003c]\u003c]\",\n\t\t\"\",\n\t\t\"About 111k guest ops. Give it 20000 fuel and it takes six slices, which is the point.\",\n\t},\n}\n\n// Render is the realm's gnoweb view.\n//\n//   - \"/\"      the samples, the instance list, and how the thing works.\n//   - \"/\u003cid\u003e\"  one instance: its program, status, fuel and output.\nfunc Render(path string) string {\n\tid := strings.TrimPrefix(path, \"/\")\n\tid = strings.TrimSpace(id)\n\tif id == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderInstance(id)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Brainfuck, on chain, a slice at a time\\n\\n\")\n\tsb.WriteString(\"Demo of [`p/moul/x/vm/bf`](/p/moul/x/vm/bf/v0) (the machine) and \")\n\tsb.WriteString(\"[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, \")\n\tsb.WriteString(\"the instance store). This realm holds no logic of its own.\\n\\n\")\n\tsb.WriteString(\"A program here does not run to completion. It runs until its fuel slice is spent, \")\n\tsb.WriteString(\"then pauses: the realm keeps the snapshot and the next caller pays for the next slice. \")\n\tsb.WriteString(\"Realm code cannot pause itself, and a guest can.\\n\\n\")\n\n\tsb.WriteString(\"## Samples\\n\\n\")\n\tfor _, s := range samples {\n\t\tsb.WriteString(\"**\" + ui.Inline(s.name) + \"**: \" + s.note + \"\\n\\n\")\n\t\tsb.WriteString(\"```\\n\" + s.src + \"\\n```\\n\\n\")\n\t\tsb.WriteString(ui.Action(\"Upload \"+s.name, \"Upload\",\n\t\t\t\"src\", s.src, \"input\", s.input, \"budget\", \"0\") + \"\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Instances\\n\\n\")\n\tt := ui.NewTable(\"id\", \"status\", \"fuel used\", \"slices\", \"output\")\n\tstore.ReverseIterate(func(i *vmkit.Instance) bool {\n\t\tt.Row(\n\t\t\t\"[\"+i.ID+\"](/r/moul/x/vm/bfdemo/v0:\"+i.ID+\")\",\n\t\t\ti.Status.String(),\n\t\t\tufmt.Sprintf(\"%d\", i.FuelUsed),\n\t\t\tufmt.Sprintf(\"%d\", i.Slices),\n\t\t\tcodeCell(printable(i.Output, 24)),\n\t\t)\n\t\treturn false\n\t})\n\tsb.WriteString(t.OrEmpty(\"No instances yet. Upload one of the samples above.\"))\n\tsb.WriteString(\"\\n\\n\")\n\n\tsb.WriteString(\"## Limits\\n\\n\")\n\tlt := ui.NewTable(\"limit\", \"value\")\n\tlt.Row(\"instances\", ufmt.Sprintf(\"%d\", MaxInstances))\n\tlt.Row(\"source bytes\", ufmt.Sprintf(\"%d\", bf.MaxSource))\n\tlt.Row(\"input bytes\", ufmt.Sprintf(\"%d\", MaxInput))\n\tlt.Row(\"output bytes\", ufmt.Sprintf(\"%d\", MaxOutput))\n\tlt.Row(\"fuel per slice\", ufmt.Sprintf(\"%d\", MaxSliceFuel))\n\tlt.Row(\"tape cells\", ufmt.Sprintf(\"%d\", bf.TapeSize))\n\tsb.WriteString(lt.String())\n\treturn sb.String()\n}\n\nfunc renderInstance(id string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Instance \" + ui.Inline(id) + \"\\n\\n\")\n\tsb.WriteString(\"[← all instances](/r/moul/x/vm/bfdemo/v0)\\n\\n\")\n\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tsb.WriteString(\"**No such instance.** It was never uploaded, or its owner removed it.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tt := ui.NewTable(\"field\", \"value\")\n\tt.Row(\"owner\", ui.Addr(inst.Owner))\n\tt.Row(\"vm\", ui.Cell(inst.VM))\n\tt.Row(\"status\", inst.Status.String())\n\tif inst.Trap != \"\" {\n\t\tt.Row(\"trap\", ui.Cell(inst.Trap))\n\t}\n\tt.Row(\"fuel used\", ufmt.Sprintf(\"%d\", inst.FuelUsed))\n\tt.Row(\"fuel budget\", fuelText(inst.FuelBudget))\n\tt.Row(\"slices\", ufmt.Sprintf(\"%d\", inst.Slices))\n\tt.Row(\"source bytes\", ufmt.Sprintf(\"%d\", len(inst.Program)))\n\tt.Row(\"snapshot bytes\", ufmt.Sprintf(\"%d\", len(inst.Snapshot)))\n\tsb.WriteString(t.String())\n\tsb.WriteString(\"\\n\")\n\n\t// The source is caller-supplied, and everything outside the eight\n\t// operators is a comment that may hold anything at all. Show the\n\t// program the machine actually compiled, which cannot contain a\n\t// backtick or a newline and so cannot break out of the fence.\n\tsb.WriteString(\"## Program\\n\\n```\\n\" + operatorsOnly(string(inst.Program)) + \"\\n```\\n\\n\")\n\n\tsb.WriteString(\"## Output\\n\\n\")\n\tif len(inst.Output) == 0 {\n\t\tsb.WriteString(ui.Empty(\"Nothing written yet.\"))\n\t} else {\n\t\tsb.WriteString(\"```\\n\" + printable(inst.Output, MaxOutput) + \"\\n```\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tif inst.Status == vmkit.Running {\n\t\tsb.WriteString(ui.Action(\"Run 10000 more fuel\", \"Step\", \"id\", id, \"fuel\", \"10000\"))\n\t\tsb.WriteString(\" · \")\n\t\tsb.WriteString(ui.Action(\"Run 100000 more fuel\", \"Step\", \"id\", id, \"fuel\", \"100000\"))\n\t\tsb.WriteString(\"\\n\")\n\t} else {\n\t\tsb.WriteString(\"This instance is **\" + inst.Status.String() + \"** and cannot be stepped again.\\n\")\n\t}\n\treturn sb.String()\n}\n\nfunc fuelText(n int64) string {\n\tif n == vmkit.Unmetered {\n\t\treturn \"unmetered\"\n\t}\n\treturn ufmt.Sprintf(\"%d\", n)\n}\n\n// operatorsOnly strips a program down to the eight characters the language\n// defines. Everything else is a comment by definition, and a comment is\n// attacker-controlled text that has no business reaching a renderer.\nfunc operatorsOnly(src string) string {\n\tvar sb strings.Builder\n\tfor i := 0; i \u003c len(src); i++ {\n\t\tswitch src[i] {\n\t\tcase '+', '-', '\u003c', '\u003e', '[', ']', '.', ',':\n\t\t\tsb.WriteByte(src[i])\n\t\t}\n\t}\n\tif sb.Len() == 0 {\n\t\treturn \"(no operators: this program does nothing)\"\n\t}\n\treturn sb.String()\n}\n\n// printable renders guest output for a code fence: printable ASCII as itself,\n// everything else as an escape. A guest writes arbitrary bytes, so this is\n// the only form of it that is safe to show.\nfunc printable(b []byte, max int) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tconst hexDigits = \"0123456789abcdef\"\n\tvar sb strings.Builder\n\tfor _, c := range b {\n\t\tswitch {\n\t\tcase c == '\\n':\n\t\t\tsb.WriteString(\"\\\\n\")\n\t\tcase c == '\\t':\n\t\t\tsb.WriteString(\"\\\\t\")\n\t\tcase c == '\\\\':\n\t\t\tsb.WriteString(\"\\\\\\\\\")\n\t\tcase c == '`':\n\t\t\tsb.WriteString(\"\\\\x60\")\n\t\tcase c \u003e= 0x20 \u0026\u0026 c \u003c 0x7f:\n\t\t\tsb.WriteByte(c)\n\t\tdefault:\n\t\t\tsb.WriteString(\"\\\\x\")\n\t\t\tsb.WriteByte(hexDigits[c\u003e\u003e4])\n\t\t\tsb.WriteByte(hexDigits[c\u00260x0f])\n\t\t}\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"…\")\n\t}\n\treturn sb.String()\n}\n\n// codeCell puts already-printable text in a code span inside a table cell.\n// Inside backticks markdown escapes are not applied, so ui.Cell's backslashes\n// would reach the reader verbatim (\"Hello, gno\\.land\"). md.InlineCode builds\n// the span: empty text is no span at all (two bare backticks render as two\n// backticks), a space at either end is padded so CommonMark's strip does not\n// eat it, and the fence outscans any backtick run. The GFM row splitter runs\n// before inline parsing, so the pipe is escaped on top.\nfunc codeCell(s string) string {\n\treturn strings.ReplaceAll(md.InlineCode(s), \"|\", \"\\\\|\")\n}\n"}]},"send":"","max_deposit":"10000000ugnot"},{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"riscvdemo","path":"gno.land/r/moul/x/vm/riscvdemo/v0","files":[{"name":"README.md","body":"# r/moul/x/vm/riscvdemo\n\nDemo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0), the RV32IM hart, and\n[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0), the host ABI. This realm holds no\nlogic of its own: it stores images, builds a `vmkit.Host`, and renders.\n\nWhat it exists to show is two things realm code cannot do for itself.\n\n**The guest was not written for gno.** The programs on the front page are flat\n`.text` images, the bytes a cross compiler emits for\n`riscv32im-unknown-none-elf`. `Upload` takes hex, so anything you can build with\n`clang`, `rustc`, TinyGo or Zig and strip to its text segment goes in unchanged.\n\nTwo samples are exactly that and neither is a mock up. **Compiled by clang** is\na freestanding C program; **A token, in Rust** is `#![no_std]` Rust that mints,\nsends and burns, linking Rust's real `core` and `compiler_builtins`, so a\n64-bit divide in it runs `__udivdi3` on a machine with no 64-bit divide\ninstruction. Both are shipped as the bytes the compiler emitted, and the page\nshows their source rather than a disassembly, because a disassembly would bury\nthe only interesting fact: nobody wrote the machine code. Sources and build\ncommands: `tools/riscv-guests`.\n\n**A program pauses instead of failing.** It runs until its fuel slice is spent,\nthen stops with a snapshot the realm keeps, and the next caller pays for the\nnext slice. The \"Heavy loop\" sample is 200,006 instructions and takes three\ntransactions at the default slice, which is the whole point.\n\n```\nUploadSample(\"heavy\", \"\", 0)   -\u003e id\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"running\"\nStep(id, 80000)                -\u003e \"halted\"\n```\n\n## Reading the instance page\n\nA guest that writes nothing has still computed something, so the instance page\nrestores the snapshot and shows the register file under its ABI names. That is\nthe only place the state is legible: the hart itself does not survive the\ntransaction, only its snapshot does.\n\n## What a slice costs\n\nAn RV32IM instruction costs about **8,500 gas**, measured rather than estimated,\nso a block buys roughly **350,000 guest instructions**. Loading the image costs\nabout **19,600 gas per instruction word** and is paid again on every resume,\nwhich is why `MaxImage` is 8 KiB and not a megabyte. The measurements and how\nthey were taken are in the [library README](/p/moul/x/vm/riscv/v0).\n\n## What this realm does not grant\n\n`Send` always returns `vmkit.ErrNotGranted`. No instance here is funded, so a\nguest that tries to move coins is refused, and that is the capability rule\nworking rather than a missing feature. Guest key-value storage is scoped to the\ninstance being stepped by construction: the tree belongs to the instance, so one\nprogram cannot reach another's even though both live in this realm.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/vm/riscvdemo/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/vm/riscvdemo/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/vm/riscvdemo/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/vm/riscvdemo/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/vm/riscvdemo/v0\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/vm/riscvdemo\"\n  revision = \"d28fdd63c03756044952283a995142d29fd9b09a\"\n"},{"name":"render.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/moul/vendor/nt/ufmt/v2\"\n)\n\n// regNames are the ABI names, because nobody reading a register dump thinks in\n// x-numbers and every compiler's output is annotated with these.\nvar regNames = [32]string{\n\t\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\t\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\t\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\t\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\",\n}\n\n// Render is the realm's gnoweb view.\n//\n//   - \"/\"      the samples, the instance list, and what the numbers mean.\n//   - \"/\u003cid\u003e\"  one instance: its status, fuel, output and register file.\nfunc Render(path string) string {\n\tid := strings.TrimSpace(strings.TrimPrefix(path, \"/\"))\n\tif id == \"\" {\n\t\treturn renderHome()\n\t}\n\treturn renderInstance(id)\n}\n\nfunc renderHome() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# RV32IM, on chain, a slice at a time\\n\\n\")\n\tsb.WriteString(\"Demo of [`p/moul/x/vm/riscv`](/p/moul/x/vm/riscv/v0) (the hart) and \")\n\tsb.WriteString(\"[`p/moul/x/vm/vmkit`](/p/moul/x/vm/vmkit/v0) (the host ABI, the fuel meter, \")\n\tsb.WriteString(\"the instance store). This realm holds no logic of its own.\\n\\n\")\n\tsb.WriteString(\"The programs below are flat `.text` images: the same bytes a cross compiler \")\n\tsb.WriteString(\"emits for `riscv32im-unknown-none-elf`. Nothing here was written in a \")\n\tsb.WriteString(\"chain language, and nothing translated it.\\n\\n\")\n\tsb.WriteString(\"A program does not run to completion. It runs until its fuel slice is spent, \")\n\tsb.WriteString(\"then pauses: the realm keeps the snapshot and the next caller pays for the \")\n\tsb.WriteString(\"next slice. Realm code cannot pause itself, and a guest can.\\n\\n\")\n\n\tsb.WriteString(\"## Samples\\n\\n\")\n\tfor i := range samples {\n\t\ts := \u0026samples[i]\n\t\tsb.WriteString(\"**\" + ui.Inline(s.name) + \"**: \" + s.note + \"\\n\\n\")\n\t\tsb.WriteString(\"```\" + s.lang() + \"\\n\" + s.asm + \"\\n```\\n\\n\")\n\t\tsb.WriteString(ui.Action(\"Upload \"+s.name, \"UploadSample\",\n\t\t\t\"name\", s.slug, \"input\", s.input,\n\t\t\t\"budget\", ufmt.Sprintf(\"%d\", s.budget)) + \"\\n\\n\")\n\t}\n\n\tsb.WriteString(\"## Instances\\n\\n\")\n\tt := ui.NewTable(\"id\", \"status\", \"instructions\", \"slices\", \"output\")\n\tstore.ReverseIterate(func(i *vmkit.Instance) bool {\n\t\tt.Row(\n\t\t\t\"[\"+i.ID+\"](/r/moul/x/vm/riscvdemo/v0:\"+i.ID+\")\",\n\t\t\ti.Status.String(),\n\t\t\tufmt.Sprintf(\"%d\", i.FuelUsed),\n\t\t\tufmt.Sprintf(\"%d\", i.Slices),\n\t\t\tcodeCell(printable(i.Output, 24)),\n\t\t)\n\t\treturn false\n\t})\n\tsb.WriteString(t.OrEmpty(\"No instances yet. Upload one of the samples above.\"))\n\tsb.WriteString(\"\\n\\n\")\n\n\tsb.WriteString(\"## What a slice costs\\n\\n\")\n\tsb.WriteString(\"An RV32IM instruction costs about **8,500 gas** here, measured rather than \")\n\tsb.WriteString(\"estimated, so a block buys roughly **350,000 guest instructions**. Loading \")\n\tsb.WriteString(\"the image costs about **19,600 gas per instruction word** and is paid again \")\n\tsb.WriteString(\"on every resume, which is why the image cap below is small. The numbers and \")\n\tsb.WriteString(\"how they were taken are in the [library README](/p/moul/x/vm/riscv/v0).\\n\\n\")\n\n\tsb.WriteString(\"## Limits\\n\\n\")\n\tlt := ui.NewTable(\"limit\", \"value\")\n\tlt.Row(\"instances\", ufmt.Sprintf(\"%d\", MaxInstances))\n\tlt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", MaxImage))\n\tlt.Row(\"input bytes\", ufmt.Sprintf(\"%d\", MaxInput))\n\tlt.Row(\"output bytes\", ufmt.Sprintf(\"%d\", MaxOutput))\n\tlt.Row(\"instructions per slice\", ufmt.Sprintf(\"%d\", MaxSliceFuel))\n\tlt.Row(\"address space\", ufmt.Sprintf(\"%d\", riscv.MemSize))\n\tsb.WriteString(lt.String())\n\treturn sb.String()\n}\n\nfunc renderInstance(id string) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"# Instance \" + ui.Inline(id) + \"\\n\\n\")\n\tsb.WriteString(\"[← all instances](/r/moul/x/vm/riscvdemo/v0)\\n\\n\")\n\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tsb.WriteString(\"**No such instance.** It was never uploaded, or its owner removed it.\\n\")\n\t\treturn sb.String()\n\t}\n\n\tt := ui.NewTable(\"field\", \"value\")\n\tt.Row(\"owner\", ui.Addr(inst.Owner))\n\tt.Row(\"vm\", ui.Cell(inst.VM))\n\tt.Row(\"status\", inst.Status.String())\n\tif inst.Trap != \"\" {\n\t\tt.Row(\"trap\", ui.Cell(inst.Trap))\n\t}\n\tt.Row(\"instructions run\", ufmt.Sprintf(\"%d\", inst.FuelUsed))\n\tt.Row(\"budget\", fuelText(inst.FuelBudget))\n\tt.Row(\"slices\", ufmt.Sprintf(\"%d\", inst.Slices))\n\tt.Row(\"image bytes\", ufmt.Sprintf(\"%d\", len(inst.Program)))\n\tt.Row(\"image words\", ufmt.Sprintf(\"%d\", len(inst.Program)/4))\n\tt.Row(\"snapshot bytes\", ufmt.Sprintf(\"%d\", len(inst.Snapshot)))\n\tsb.WriteString(t.String())\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Registers\\n\\n\")\n\tsb.WriteString(renderRegisters(inst))\n\n\tsb.WriteString(\"## Output\\n\\n\")\n\tif len(inst.Output) == 0 {\n\t\tsb.WriteString(ui.Empty(\"Nothing written yet.\"))\n\t} else {\n\t\tsb.WriteString(\"```\\n\" + printable(inst.Output, MaxOutput) + \"\\n```\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\n\tsb.WriteString(\"## Image\\n\\n```\\n\" + hexDump(inst.Program, 64) + \"\\n```\\n\\n\")\n\n\tif inst.Status == vmkit.Running {\n\t\tsb.WriteString(ui.Action(\"Run 25000 instructions\", \"Step\", \"id\", id, \"fuel\", \"25000\"))\n\t\tsb.WriteString(\" · \")\n\t\tsb.WriteString(ui.Action(\"Run 100000 instructions\", \"Step\", \"id\", id, \"fuel\", \"100000\"))\n\t\tsb.WriteString(\"\\n\")\n\t} else {\n\t\tsb.WriteString(\"This instance is **\" + inst.Status.String() + \"** and cannot be stepped again.\\n\")\n\t}\n\treturn sb.String()\n}\n\n// renderRegisters restores the snapshot to read the register file out of it.\n// The hart is not kept between transactions, only its snapshot is, so this is\n// the only place the state is legible, and it is the thing worth seeing: a\n// program that wrote nothing still computed something.\nfunc renderRegisters(inst *vmkit.Instance) string {\n\tif len(inst.Snapshot) == 0 {\n\t\treturn ui.Empty(\"Not started yet: no snapshot to read.\") + \"\\n\\n\"\n\t}\n\tvar m riscv.Machine\n\tif err := m.Restore(inst.Snapshot); err != nil {\n\t\treturn ui.Empty(\"The snapshot could not be read.\") + \"\\n\\n\"\n\t}\n\treg := m.Registers()\n\n\tvar sb strings.Builder\n\tt := ui.NewTable(\"register\", \"hex\", \"unsigned\", \"signed\")\n\tt.Row(\"pc\", ufmt.Sprintf(\"0x%08X\", m.PC()), \"\", \"\")\n\tshown := 0\n\tfor i := 1; i \u003c 32; i++ {\n\t\tif reg[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt.Row(\n\t\t\tregNames[i],\n\t\t\tufmt.Sprintf(\"0x%08X\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", reg[i]),\n\t\t\tufmt.Sprintf(\"%d\", int64(int32(reg[i]))),\n\t\t)\n\t\tshown++\n\t}\n\tsb.WriteString(t.String())\n\tif shown == 0 {\n\t\tsb.WriteString(\"\\nEvery register except `pc` is zero.\\n\")\n\t}\n\tsb.WriteString(\"\\n\")\n\treturn sb.String()\n}\n\nfunc fuelText(n int64) string {\n\tif n == vmkit.Unmetered {\n\t\treturn \"unmetered\"\n\t}\n\treturn ufmt.Sprintf(\"%d\", n)\n}\n\nconst hexDigits = \"0123456789abcdef\"\n\n// hexDump shows the image as words, which is how anyone reading RV32 reads it.\nfunc hexDump(b []byte, max int) string {\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor i := 0; i+3 \u003c len(b); i += 4 {\n\t\tif i \u003e 0 \u0026\u0026 i%16 == 0 {\n\t\t\tsb.WriteString(\"\\n\")\n\t\t} else if i \u003e 0 {\n\t\t\tsb.WriteString(\" \")\n\t\t}\n\t\tw := uint32(b[i]) | uint32(b[i+1])\u003c\u003c8 | uint32(b[i+2])\u003c\u003c16 | uint32(b[i+3])\u003c\u003c24\n\t\tsb.WriteString(ufmt.Sprintf(\"%08x\", w))\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"\\n...\")\n\t}\n\treturn sb.String()\n}\n\n// printable renders guest output for a code fence: printable ASCII as itself,\n// everything else as an escape. A guest writes arbitrary bytes, so this is the\n// only form of it that is safe to show.\nfunc printable(b []byte, max int) string {\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\ttruncated := false\n\tif len(b) \u003e max {\n\t\tb, truncated = b[:max], true\n\t}\n\tvar sb strings.Builder\n\tfor _, c := range b {\n\t\tswitch {\n\t\tcase c == '\\n':\n\t\t\tsb.WriteString(\"\\\\n\")\n\t\tcase c == '\\t':\n\t\t\tsb.WriteString(\"\\\\t\")\n\t\tcase c == '\\\\':\n\t\t\tsb.WriteString(\"\\\\\\\\\")\n\t\tcase c == '`':\n\t\t\tsb.WriteString(\"\\\\x60\")\n\t\tcase c \u003e= 0x20 \u0026\u0026 c \u003c 0x7f:\n\t\t\tsb.WriteByte(c)\n\t\tdefault:\n\t\t\tsb.WriteString(\"\\\\x\")\n\t\t\tsb.WriteByte(hexDigits[c\u003e\u003e4])\n\t\t\tsb.WriteByte(hexDigits[c\u00260x0f])\n\t\t}\n\t}\n\tif truncated {\n\t\tsb.WriteString(\"…\")\n\t}\n\treturn sb.String()\n}\n\n// codeCell puts already-printable text in a code span inside a table cell.\n// Inside backticks markdown escapes are not applied, so ui.Cell's backslashes\n// would reach the reader verbatim (\"Hello, gno\\.land\"). md.InlineCode builds\n// the span: empty text is no span at all (two bare backticks render as two\n// backticks), a space at either end is padded so CommonMark's strip does not\n// eat it, and the fence outscans any backtick run. The GFM row splitter runs\n// before inline parsing, so the pipe is escaped on top.\nfunc codeCell(s string) string {\n\treturn strings.ReplaceAll(md.InlineCode(s), \"|\", \"\\\\|\")\n}\n"},{"name":"riscvdemo.gno","body":"// Package riscvdemo runs real compiled machine code on chain, a slice at a\n// time.\n//\n// It is a demo of two libraries and carries no logic of its own:\n// [p/moul/x/vm/riscv](/p/moul/x/vm/riscv/v0) is the RV32IM hart, and\n// [p/moul/x/vm/vmkit](/p/moul/x/vm/vmkit/v0) is the host ABI, the fuel meter\n// and the instance store.\n//\n// What it exists to show is that the guest was not written for gno. The\n// programs on the front page are flat .text images: the same bytes\n// `rustc --target riscv32im-unknown-none-elf` emits, uploaded as hex. The\n// realm holds the snapshot between transactions, so one computation finishes\n// across several of them, and realm code cannot do that for itself.\npackage riscvdemo\n\nimport (\n\t\"chain\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\t\"time\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/moul/vendor/nt/ufmt/v2\"\n)\n\n// Caps. Everything a caller can grow is bounded, because all of it is storage\n// somebody pays a deposit on.\nconst (\n\t// MaxInstances is how many programs the realm keeps at once.\n\tMaxInstances = 64\n\t// MaxImage caps an uploaded text segment at 2,048 instructions.\n\t//\n\t// This one is not arbitrary. Predecoding costs about 19,600 gas per word\n\t// and is redone on every resume, so the image size is a tax on every\n\t// transaction that touches the instance, not just the upload. 8 KiB works\n\t// out to roughly 40M gas per slice before the guest executes anything,\n\t// which is about 1% of a block.\n\tMaxImage = 8192\n\t// MaxOutput caps the bytes one program may write. Past it the guest is\n\t// trapped rather than truncated, so rendered output is never a lie.\n\tMaxOutput = 4096\n\t// MaxInput caps the call input a program can be given.\n\tMaxInput = 1024\n\t// DefaultFuel is the budget an upload gets when it asks for none, and the\n\t// slice size Step uses when asked for none.\n\tDefaultFuel = 100000\n\t// MaxSliceFuel bounds one transaction's work regardless of what the\n\t// caller asked for, and it is derived from the measurement rather than\n\t// picked: an RV32IM instruction costs about 8,500 gas, so 100,000 of them\n\t// is about 850M, a little under a third of a 3G block. Twice this would\n\t// still be a legal transaction and a rude one, and it would leave no room\n\t// for the predecode and the realm's own storage writes on top.\n\tMaxSliceFuel = 100000\n)\n\nvar (\n\tstore  = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen  seqid.ID\n\tcount  int\n)\n\n// host is the realm-backed [vmkit.Host]. One is built per call, wrapping the\n// instance being stepped, so a guest's output and authority are scoped to it\n// and nothing ambient leaks in.\ntype host struct {\n\tinst    *vmkit.Instance\n\tin      []byte\n\tkv      *avl.Tree\n\toverrun bool // the guest wrote past MaxOutput\n}\n\nfunc (h *host) Caller() address { return h.inst.Owner }\nfunc (h *host) Origin() address { return h.inst.Owner }\nfunc (h *host) Now() int64      { return time.Now().Unix() }\nfunc (h *host) Height() int64   { return runtime.ChainHeight() }\nfunc (h *host) Input() []byte   { return h.in }\n\n// Get and Set are scoped to the instance by construction: the tree belongs to\n// the instance being stepped, so one program cannot reach another's storage\n// even though both live in this one realm.\nfunc (h *host) Get(key []byte) []byte {\n\tv := h.kv.Get(string(key))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.([]byte)\n}\n\nfunc (h *host) Set(key, val []byte) { h.kv.Set(string(key), val) }\n\nfunc (h *host) Output(p []byte) {\n\tif len(h.inst.Output)+len(p) \u003e MaxOutput {\n\t\th.overrun = true\n\t\treturn\n\t}\n\th.inst.Output = append(h.inst.Output, p...)\n}\n\nfunc (h *host) Emit(typ string, kv ...string) { chain.Emit(typ, kv...) }\n\n// Send is never granted here. The demo funds no instance, so a guest that\n// tries to move coins is refused. That is the capability rule doing its job,\n// not a missing feature.\nfunc (h *host) Send(to address, amount int64) error { return vmkit.ErrNotGranted }\n\nfunc (h *host) Log(msg string) {}\n\n// Upload stores a hex-encoded text image as a new instance and returns its id.\n//\n// The image is loaded here rather than at the first Step, so a misaligned or\n// oversized one is rejected by the transaction that submitted it instead of\n// costing somebody else the gas later.\nfunc Upload(cur realm, hexImage, input string, budget int64) string {\n\timg, ok := decodeHex(hexImage)\n\tif !ok {\n\t\tpanic(\"riscvdemo: image is not valid hex\")\n\t}\n\treturn upload(img, input, budget)\n}\n\n// UploadSample stores one of the programs the front page offers. Writing RV32IM\n// by hand is not the point of this realm, and without this nobody without a\n// cross compiler could press a button.\nfunc UploadSample(cur realm, name, input string, budget int64) string {\n\ts := sampleByName(name)\n\tif s == nil {\n\t\tpanic(\"riscvdemo: no such sample\")\n\t}\n\t// A sample carries its own budget because the default is a total, not a\n\t// slice: the heavy loop needs 200,006 instructions, and offering a button\n\t// that runs out of fuel halfway is a worse demo than no button.\n\tif budget \u003c= 0 {\n\t\tbudget = s.budget\n\t}\n\treturn upload(s.image(), input, budget)\n}\n\nfunc upload(img []byte, input string, budget int64) string {\n\tif count \u003e= MaxInstances {\n\t\tpanic(\"riscvdemo: too many instances, remove one first\")\n\t}\n\tif len(input) \u003e MaxInput {\n\t\tpanic(\"riscvdemo: input too long\")\n\t}\n\tif len(img) == 0 {\n\t\tpanic(\"riscvdemo: empty image\")\n\t}\n\tif len(img) \u003e MaxImage {\n\t\tpanic(\"riscvdemo: image too large\")\n\t}\n\t// Loading it now is the validation: NewMachine is what rejects an image\n\t// that is not a whole number of instructions.\n\tif _, err := riscv.NewMachine(img, riscv.DefaultEntry); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif budget \u003c= 0 {\n\t\tbudget = DefaultFuel\n\t}\n\n\tid := idgen.Next().String()\n\towner := unsafe.PreviousRealm().Address()\n\tstore.Set(vmkit.NewInstance(id, owner, riscv.VMName, img, budget))\n\tif input != \"\" {\n\t\tinputs.Set(id, input)\n\t}\n\tcount++\n\n\tchain.Emit(\"riscv_upload\", \"id\", id, \"bytes\", ufmt.Sprintf(\"%d\", len(img)))\n\treturn id\n}\n\n// Step runs one slice of the instance: up to `fuel` guest instructions, then\n// stop and keep the snapshot. Anyone may pay for a slice, not only the owner:\n// a paused program that only its owner can advance is a worse demo and no\n// safer, since the program and its budget were both fixed at upload.\nfunc Step(cur realm, id string, fuel int64) string {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Status != vmkit.Running {\n\t\tpanic(\"riscvdemo: instance is \" + inst.Status.String())\n\t}\n\tif fuel \u003c= 0 {\n\t\tfuel = DefaultFuel\n\t}\n\tif fuel \u003e MaxSliceFuel {\n\t\tfuel = MaxSliceFuel\n\t}\n\n\tm, err := riscv.NewMachine(inst.Program, riscv.DefaultEntry)\n\tif err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\th := \u0026host{inst: inst, in: []byte(inputOf(id)), kv: avl.NewTree()}\n\tif err := inst.Run(m, h, fuel); err != nil {\n\t\tpanic(\"riscvdemo: \" + err.Error())\n\t}\n\tif h.overrun {\n\t\tinst.Status = vmkit.Trapped\n\t\tinst.Trap = \"output limit reached\"\n\t}\n\n\tchain.Emit(\"riscv_step\",\n\t\t\"id\", id,\n\t\t\"status\", inst.Status.String(),\n\t\t\"fuel\", ufmt.Sprintf(\"%d\", inst.FuelUsed),\n\t)\n\treturn inst.Status.String()\n}\n\n// Remove deletes an instance. Owner only.\nfunc Remove(cur realm, id string) {\n\tinst := store.Get(id)\n\tif inst == nil {\n\t\tpanic(\"riscvdemo: no such instance\")\n\t}\n\tif inst.Owner != unsafe.PreviousRealm().Address() {\n\t\tpanic(\"riscvdemo: not your instance\")\n\t}\n\tstore.Remove(id)\n\tinputs.Remove(id)\n\tcount--\n}\n\nfunc inputOf(id string) string {\n\tv := inputs.Get(id)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(string)\n}\n\n// decodeHex accepts the output of any hexdump: an even number of hex digits,\n// with an optional 0x prefix, and whitespace anywhere. Whitespace is allowed\n// because that is what a pasted hexdump has in it; anything else is refused,\n// because a silently mangled image would trap somewhere unrelated later.\nfunc decodeHex(s string) ([]byte, bool) {\n\tif len(s) \u003e= 2 \u0026\u0026 s[0] == '0' \u0026\u0026 (s[1] == 'x' || s[1] == 'X') {\n\t\ts = s[2:]\n\t}\n\tdigits := make([]byte, 0, len(s))\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tc := s[i]\n\t\tif c == ' ' || c == '\\t' || c == '\\n' || c == '\\r' {\n\t\t\tcontinue\n\t\t}\n\t\tv, ok := hexVal(c)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tdigits = append(digits, v)\n\t}\n\tif len(digits) == 0 || len(digits)%2 != 0 {\n\t\treturn nil, false\n\t}\n\tout := make([]byte, len(digits)/2)\n\tfor i := 0; i \u003c len(out); i++ {\n\t\tout[i] = digits[i*2]\u003c\u003c4 | digits[i*2+1]\n\t}\n\treturn out, true\n}\n\nfunc hexVal(c byte) (byte, bool) {\n\tswitch {\n\tcase c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\treturn c - '0', true\n\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'f':\n\t\treturn c - 'a' + 10, true\n\tcase c \u003e= 'A' \u0026\u0026 c \u003c= 'F':\n\t\treturn c - 'A' + 10, true\n\t}\n\treturn 0, false\n}\n"},{"name":"riscvdemo_test.gno","body":"package riscvdemo\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/x/vm/riscv/v0\"\n\t\"gno.land/p/moul/x/vm/vmkit/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// resetState puts the realm globals back where init() left them. Realm state\n// persists for the whole test binary, so every test that asserts on ids or on\n// the rendered instance list has to start from here.\nfunc resetState() {\n\tstore = vmkit.NewStore()\n\tinputs = avl.NewTree()\n\tidgen = seqid.ID(0)\n\tcount = 0\n}\n\nfunc alice() address { return testutils.TestAddress(\"alice\") }\n\nfunc TestUploadAndRunToCompletion(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"hello\", \"\", 0)\n\tuassert.Equal(t, \"halted\", Step(cross(cur), id, 0))\n\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"Hello, gno.land\\n\", string(inst.Output))\n\tuassert.Equal(t, int64(1), inst.Slices)\n\tuassert.Equal(t, alice(), inst.Owner)\n\tuassert.Equal(t, \"riscv32im\", inst.VM)\n}\n\n// Every sample on the front page has to reach its documented answer, or the\n// page offers a button that traps when pressed. The words are assembled\n// outside this repo, so this is the test that catches a mistyped one.\nfunc TestEverySampleReachesItsAnswer(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tcases := []struct {\n\t\tslug   string\n\t\treg    int\n\t\twant   uint32\n\t\toutput string\n\t}{\n\t\t{\"hello\", 0, 0, \"Hello, gno.land\\n\"},\n\t\t{\"sum100\", 5, 5050, \"\"},\n\t\t{\"heavy\", 5, 1250025000, \"\"},\n\t\t{\"mext\", 5, 3000000021, \"\"},\n\t\t{\"clang\", 0, 0, \"fb7ffba0\"},\n\t\t{\"ledger\", 0, 0, \"alice 70\\nbob 80\\n\"},\n\t}\n\tfor _, c := range cases {\n\t\tid := UploadSample(cross(cur), c.slug, sampleByName(c.slug).input, 0)\n\t\tstatus := \"\"\n\t\tfor i := 0; i \u003c 20; i++ {\n\t\t\tstatus = Step(cross(cur), id, 0)\n\t\t\tif status != \"running\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tuassert.Equal(t, \"halted\", status, c.slug+\" must halt\")\n\t\tinst := store.Get(id)\n\t\tuassert.Equal(t, c.output, string(inst.Output), c.slug+\" output\")\n\t\tif c.reg != 0 {\n\t\t\tvar m riscv.Machine\n\t\t\tuassert.NoError(t, m.Restore(inst.Snapshot))\n\t\t\tuassert.Equal(t, uint64(c.want), uint64(m.Registers()[c.reg]), c.slug+\" result\")\n\t\t}\n\t}\n}\n\n// TestOneProgramAcrossManyTransactions is what the realm exists to\n// demonstrate: the same computation, finished over several calls, each paying\n// for its own slice.\nfunc TestOneProgramAcrossManyTransactions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"heavy\", \"\", 0)\n\tstatus := \"\"\n\tfor i := 0; i \u003c 50; i++ {\n\t\tstatus = Step(cross(cur), id, 80000)\n\t\tif status != \"running\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tinst := store.Get(id)\n\tuassert.Equal(t, \"halted\", status)\n\tuassert.True(t, inst.Slices \u003e 1, \"a 200k instruction program must not finish in one slice\")\n\tuassert.Equal(t, int64(200006), inst.FuelUsed)\n}\n\nfunc TestUploadTakesHex(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// addi a7, zero, 93 ; ecall\n\tid := Upload(cross(cur), \"0x9308d005 73000000\", \"\", 0)\n\t_ = id\n}\n\nfunc TestUploadRejectsBadImages(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// Called without cross(): a panic raised through a crossing call cannot be\n\t// recovered, so uassert would never see it.\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"zzzz\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: image is not valid hex\", func() {\n\t\tUpload(cur, \"abc\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"riscvdemo: no such sample\", func() {\n\t\tUploadSample(cur, \"nope\", \"\", 0)\n\t})\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"riscvdemo: riscv: image length is not a whole number of instructions\",\n\t\tfunc() { Upload(cur, \"0011\", \"\", 0) })\n}\n\nfunc TestDecodeHex(t *testing.T) {\n\tb, ok := decodeHex(\"0xDEADbeef\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\tuassert.Equal(t, uint64(0xDE), uint64(b[0]))\n\tuassert.Equal(t, uint64(0xEF), uint64(b[3]))\n\n\t_, ok = decodeHex(\"\")\n\tuassert.False(t, ok)\n\t_, ok = decodeHex(\"0x\")\n\tuassert.False(t, ok)\n\t// Whitespace is skipped, because a pasted hexdump has it.\n\tb, ok = decodeHex(\"00 11\\n22\\t33\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, 4, len(b))\n\t// An odd number of digits is still a refusal, whitespace or not.\n\t_, ok = decodeHex(\"00 1\")\n\tuassert.False(t, ok)\n}\n\nfunc TestRenderHomeOffersEverySample(cur realm, t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"RV32IM, on chain\"), \"the title\")\n\tfor _, s := range samples {\n\t\tuassert.True(t, strings.Contains(out, s.name), \"home must offer \"+s.slug)\n\t}\n\tuassert.True(t, strings.Contains(out, \"No instances yet\"), \"the empty state\")\n}\n\n// The register file is the interesting half of this VM: a program that writes\n// nothing still computed something, and the snapshot is the only place it is\n// legible between transactions.\nfunc TestRenderInstanceShowsTheRegisterFile(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"sum100\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"/\" + id)\n\tuassert.True(t, strings.Contains(out, \"## Registers\"), \"the section\")\n\tuassert.True(t, strings.Contains(out, \"5050\"), \"t0 must show the answer\")\n\tuassert.True(t, strings.Contains(out, \"halted\"), \"the status\")\n}\n\n// The instance page is all hex: the pc, every register, the image dump.\n// gno.land/p/nt/ufmt/v0 has no %X and no width flags, so this page shipped\n// printing \"0x(unhandled verb: %X)\" in every cell; the test pins the fix.\nfunc TestRenderInstanceHex(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\t// addi a7, zero, 93 ; ecall (exit)\n\tid := Upload(cross(cur), \"0x9308d005 73000000\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"/\" + id)\n\tuassert.False(t, strings.Contains(out, \"unhandled\"), out)\n\tuassert.True(t, strings.Contains(out, \"| a7 | 0x0000005D | 93 | 93 |\"), out)\n\tuassert.True(t, strings.Contains(out, \"05d00893 00000073\"), out)\n}\n\n// The instance list shows output in a code span, where markdown escapes do\n// not apply: ui.Cell's backslashes used to reach the reader as\n// `Hello, gno\\.land\\\\n`. Only the pipe needs escaping inside the span.\nfunc TestRenderOutputCell(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\n\tid := UploadSample(cross(cur), \"hello\", \"\", 0)\n\tStep(cross(cur), id, 0)\n\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"| `Hello, gno.land\\\\n` |\"), out)\n\tuassert.Equal(t, \"`a\\\\|b`\", codeCell(\"a|b\"))\n}\n\nfunc TestRenderUnknownInstance(t *testing.T) {\n\tuassert.True(t, strings.Contains(Render(\"/nope\"), \"No such instance\"))\n}\n\n// ExampleRender pins the realm's output for a path whose content cannot drift\n// with the instance list. The home page and the instance page both produce\n// consecutive blank lines, which an example block cannot represent, so they\n// are asserted in the tests above instead.\nfunc ExampleRender() {\n\tprint(Render(\"/missing\"))\n\t// Output:\n\t// # Instance missing\n\t//\n\t// [← all instances](/r/moul/x/vm/riscvdemo/v0)\n\t//\n\t// **No such instance.** It was never uploaded, or its owner removed it.\n}\n\n// An instance that has written nothing yet shows an empty output cell. Two\n// adjacent backticks are not an empty code span, they render as two\n// backticks.\nfunc TestRenderEmptyOutputCell(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice()))\n\tUploadSample(cross(cur), \"hello\", \"\", 0)\n\n\trow := \"\"\n\tfor _, line := range strings.Split(Render(\"\"), \"\\n\") {\n\t\tif strings.HasPrefix(line, \"| [\") {\n\t\t\trow = line\n\t\t}\n\t}\n\tuassert.True(t, row != \"\", \"an instance row is rendered\")\n\tuassert.True(t, strings.HasSuffix(row, \"| 0 |  |\"), row)\n}\n\n// codeCell follows the three rules of a code span, not only the pipe: empty\n// content is not a span, a space at either end needs a pad, and the fence\n// outscans any backtick run in the content.\nfunc TestCodeCellRules(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"Hello, gno.land\\\\n\", \"`Hello, gno.land\\\\n`\"},\n\t\t{\"a|b\", \"`a\\\\|b`\"},\n\t\t{\" hi \", \"`  hi  `\"},\n\t\t{\" hi\", \"`  hi `\"},\n\t\t{\"hi \", \"` hi  `\"},\n\t\t{\"a`b\", \"``a`b``\"},\n\t}\n\tfor _, c := range cases {\n\t\tuassert.Equal(t, c.want, codeCell(c.in), \"codeCell(\"+c.in+\")\")\n\t}\n}\n"},{"name":"samples.gno","body":"package riscvdemo\n\nimport \"gno.land/p/moul/x/vm/riscv/v0\"\n\n// The programs the front page offers, as the machine words a cross compiler\n// would have emitted. They are assembled outside this repo and pinned here,\n// and riscvdemo_test.gno runs every one of them to the expected answer, so a\n// wrong word is a failing test rather than a page that traps when clicked.\ntype sample struct {\n\tslug   string // what UploadSample takes: short, no punctuation, stable\n\tname   string\n\tbudget int64 // the instance's total instruction budget, not the slice\n\n\t// builtin names an image the library ships compiled, instead of the words\n\t// below. Empty means the words are the program.\n\tbuiltin string\n\twords []uint32\n\tinput string\n\tnote  string\n\tasm   string\n}\n\nvar samples = []sample{\n\t{\n\t\tslug: \"hello\",\n\t\tname: \"Hello, gno.land\",\n\t\twords: []uint32{\n\t\t\t0x00100513, 0x000015B7, 0x02058593, 0x01000613,\n\t\t\t0x04000893, 0x00000073, 0x05D00893, 0x00000073,\n\t\t\t0x6C6C6548, 0x67202C6F, 0x6C2E6F6E, 0x0A646E61,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"Eight instructions and a string constant. The write syscall reads \" +\n\t\t\t\"the bytes straight out of the text segment and hands them to Host.Output.\",\n\t\tasm: `addi a0, zero, 1          # fd\nlui  a1, 0x1000           # buf\naddi a1, a1, 0x20\naddi a2, zero, 16         # len\naddi a7, zero, 64         # write\necall\naddi a7, zero, 93         # exit\necall\n.ascii \"Hello, gno.land\\n\"`,\n\t},\n\t{\n\t\tslug: \"sum100\",\n\t\tname: \"Sum 1 to 100\",\n\t\twords: []uint32{\n\t\t\t0x06400413, 0x00000293, 0x00000313, 0x00130313,\n\t\t\t0x006282B3, 0xFE831CE3, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"A real loop, 303 instructions. Writes nothing: the answer is in t0, \" +\n\t\t\t\"and the instance page shows the register file.\",\n\t\tasm: `addi s0, zero, 100\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"heavy\",\n\t\tname: \"Heavy loop\",\n\t\twords: []uint32{\n\t\t\t0x0000C437, 0x35040413, 0x00000293, 0x00000313,\n\t\t\t0x00130313, 0x006282B3, 0x00000393, 0xFE831AE3,\n\t\t\t0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 250000,\n\t\tnote: \"200,006 instructions, four per iteration. At the largest slice this realm \" +\n\t\t\t\"allows it takes three transactions to finish, which is the thing it exists to show.\",\n\t\tasm: `lui  s0, 0xc000           # s0 = 50000\naddi s0, s0, 0x350\naddi t0, zero, 0\naddi t1, zero, 0\nloop:\naddi t1, t1, 1\nadd  t0, t0, t1\naddi t2, zero, 0\nbne  t1, s0, loop\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug: \"mext\",\n\t\tname: \"Multiply and divide\",\n\t\twords: []uint32{\n\t\t\t0x3B9AD2B7, 0xA0728293, 0x00300313, 0x026282B3,\n\t\t\t0x00700393, 0x0272D333, 0x05D00893, 0x00000073,\n\t\t},\n\t\tbudget: 1000,\n\t\tnote: \"The M extension. t0 = 1000000007 * 3 truncated to 32 bits, then t1 = t0 / 7. \" +\n\t\t\t\"Division by zero and the one signed overflow case return values here \" +\n\t\t\t\"rather than trapping, which is what the spec says and what a chain needs.\",\n\t\tasm: `lui  t0, 0x3b9ad000       # t0 = 1000000007\naddi t0, t0, -1529\naddi t1, zero, 3\nmul  t0, t0, t1\naddi t2, zero, 7\ndivu t1, t0, t2\naddi a7, zero, 93\necall`,\n\t},\n\t{\n\t\tslug:   \"clang\",\n\t\tname:   \"Compiled by clang\",\n\t\tinput:  \"gno.land\",\n\t\tbudget: 20000,\n\t\tnote: \"Not written for gno and not written by hand: a freestanding C program, \" +\n\t\t\t\"compiled by clang for riscv32im and shipped as the bytes LLVM emitted. It reads \" +\n\t\t\t\"the call input, hashes it with FNV-1a and writes eight hex digits back. \" +\n\t\t\t\"With the default input it prints fb7ffba0. Source and build command: \" +\n\t\t\t\"tools/riscv-guests/fnv.\",\n\t\tbuiltin: \"fnv\",\n\t\tasm: `long n = syscall3(SYS_READ, 0, (long)in, sizeof(in));\n\nunsigned int h = 2166136261u;\nfor (long i = 0; i \u003c n; i++) {\n\th ^= in[i];\n\th *= 16777619u;      /* the reason this is rv32im */\n}\n\nfor (int i = 0; i \u003c 8; i++) {\n\tunsigned int nib = (h \u003e\u003e (28 - i * 4)) \u0026 0xF;\n\tout[i] = nib \u003c 10 ? '0' + nib : 'a' + (nib - 10);\n}\n\nsyscall3(SYS_WRITE, 1, (long)out, 8);\nsyscall3(SYS_EXIT, 0, 0, 0);`,\n\t},\n\t{\n\t\tslug:   \"ledger\",\n\t\tname:   \"A token, in Rust\",\n\t\tinput:  \"mint alice 100\\nmint bob 50\\nsend alice bob 30\\n\",\n\t\tbudget: 20000,\n\t\tnote: \"no_std Rust, compiled by rustc for riscv32im: mint, send and burn, applied \" +\n\t\t\t\"from the call input. It links Rust's real core and compiler_builtins, so the \" +\n\t\t\t\"balances being 64-bit means a divide runs __udivdi3 here, because RV32 has no \" +\n\t\t\t\"64-bit divide instruction. With the default input it prints alice 70 and bob 80. \" +\n\t\t\t\"Source: tools/riscv-guests/ledger.\",\n\t\tbuiltin: \"ledger\",\n\t\tasm: `match cmd {\n\tb\"send\" =\u003e {\n\t\tlet (from, rest) = field(rest);\n\t\tlet (to, rest) = field(rest);\n\t\tlet (amount, _) = field(rest);\n\t\tlet n = parse_u32(amount).ok_or(\"bad amount\")?;\n\t\tlet fi = led.find(from).ok_or(\"unknown sender\")?;\n\t\tif led.balances[fi] \u003c n {\n\t\t\treturn Err(\"insufficient balance\");\n\t\t}\n\t\tlet ti = led.intern(to).ok_or(\"ledger full or bad name\")?;\n\t\tled.balances[fi] -= n;\n\t\tled.balances[ti] += n;\n\t\tOk(())\n\t}\n\t_ =\u003e Err(\"unknown command\"),\n}`,\n\t},\n}\n\n// image is what gets uploaded: either the words assembled here, or a program\n// the library ships because a compiler produced it.\nfunc (s *sample) image() []byte {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn riscv.GuestFNV()\n\tcase \"ledger\":\n\t\treturn riscv.GuestLedger()\n\t}\n\treturn riscv.Image(s.words)\n}\n\n// lang is the fence tag for what the sample shows. The compiled guest shows\n// its C, because showing a disassembly of what LLVM did with it would bury the\n// only interesting fact: nobody wrote the machine code.\nfunc (s *sample) lang() string {\n\tswitch s.builtin {\n\tcase \"fnv\":\n\t\treturn \"c\"\n\tcase \"ledger\":\n\t\treturn \"rust\"\n\t}\n\treturn \"asm\"\n}\n\nfunc sampleByName(slug string) *sample {\n\tfor i := range samples {\n\t\tif samples[i].slug == slug {\n\t\t\treturn \u0026samples[i]\n\t\t}\n\t}\n\treturn nil\n}\n"}]},"send":"","max_deposit":"15000000ugnot"}],"fee":{"gas_wanted":"180236600","gas_fee":"540709ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"yayH2Usv5teQ+SE010XAEQ0rSTfE5zoc5Z0pV0LK4gYjHLOKiAhIgh7xuinBDO3vWLopj1en13gODkDoV/E2Ow=="}],"memo":""},"metadata":{"timestamp":"1791961092"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"guestbook","path":"gno.land/r/moul/x/daily/guestbook/v1","files":[{"name":"README.md","body":"# Guestbook\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA public, on-chain guestbook realm for gno.land. Anyone can leave a signed\nmessage; every entry records the signer's address, the message, and the block\nheight at which it was signed. The realm's `Render` page shows all entries as a\nMarkdown table, newest-first, with a running total.\n\nBuilt for the **sapphire** testnet (gno 0.9).\n\n## Realm path\n\n```\ngno.land/r/REPLACE_ADDR/guestbook\n```\n\n(`REPLACE_ADDR` is substituted with the deployer's address at publish time.)\n\n## Public API\n\n- `Sign(cur realm, message string)` — crossing tx. Appends an entry attributed\n  to the immediate caller. Panics on an empty or over-long (\u003e280 bytes) message.\n- `Count() int` — total number of signatures (read-only).\n- `Render(path string) string` — Markdown table of all entries, newest-first.\n\n## Example calls\n\nSign the guestbook (from an EOA via `gnokey`):\n\n```sh\ngnokey maketx call \\\n  -pkgpath \"gno.land/r/REPLACE_ADDR/guestbook\" \\\n  -func Sign \\\n  -args \"gm gno.land!\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 \\\n  -broadcast -chainid sapphire-1 -remote \u003crpc\u003e mykey\n```\n\nFrom another realm, invoke it as a crossing call:\n\n```go\nguestbook.Sign(cross(cur), \"hello from my realm\")\n```\n\nView the rendered guestbook:\n\n```sh\ngnokey query vm/qrender --data \"gno.land/r/REPLACE_ADDR/guestbook:\"\n```\n\n## Example render output\n\n```markdown\n# Guestbook\n\n**Total signatures:** 2\n\n| # | Who | Message | Height |\n|---|-----|---------|--------|\n| 2 | g1v9jxgu…0gh | hello from my realm | 4210 |\n| 1 | g1jg8mtu…qf5 | gm gno.land! | 4180 |\n```\n\n## Notes\n\n- Caller identity uses the gno 0.9 interrealm convention: `Sign` is a crossing\n  function that checks `cur.IsCurrent()` before deriving the author from\n  `cur.Previous().Address()`.\n- Block height comes from `chain/runtime.ChainHeight()` — deterministic.\n- Entries are stored in a `gno.land/p/nt/avl/v0` tree keyed by a zero-padded\n  sequence number so iteration order is deterministic and matches insertion\n  order (reversed for newest-first rendering).\n```\n\n## What changed in v1\n\nTwo ports against [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/guestbook), which stays live and untouched.\n\n### Rendering\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/guestbook) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `shortAddr`, `escapeCell` helpers.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nVisible change: addresses now render in monospace.\n\n### Storage\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\n`v0` padded ids to width 16, the widest of the six hand-rolled variants in this\nrepo and still a ceiling. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`Entry` loses its `ID` field, which the store now owns, so `addEntry` returns\n`(store.ID, *Entry)`. The `count` global is gone too: `Len()` answers it.\n\nIds stay plain integers and the rendered output of the storage port is\nunchanged. Each port changes something `v0` promised, one the rendered output\nand one the storage layout, so under this repo's versioning rule each is a\ncompatibility change and neither could be an edit to `v0` in place.\n\nThey land in the **same** new version because `v1` was never published. A\nversion number is a tag on something that exists on a chain, and until it does\nthere is nothing for a second number to avoid disturbing, so the right move is\nto keep editing the version you have. `gnopm unbump` is what folded the second\nport back down into this one.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/guestbook/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/guestbook/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/guestbook/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/guestbook/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/guestbook/v1\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/daily/guestbook\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"guestbook.gno","body":"// Package guestbook is a public, on-chain guestbook realm for gno.land.\n//\n// Anyone can sign the guestbook with a short message via the Sign crossing\n// function. Every entry records the caller's address, the message, and the\n// block height at which it was signed. Render lists all entries newest-first\n// as a Markdown table.\n//\n// v1 renders through [p/moul/kit/ui](/p/moul/kit/ui/v0) instead of the\n// hand-rolled shortAddr and escapeCell helpers v0 carried. The escaping is the\n// substantive change: v0 replaced four characters, while ui.Cell also strips\n// bidi and zero-width characters, which a message can otherwise use to reorder\n// how the rest of the row reads.\npackage guestbook\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n)\n\n// Entry is a single signed guestbook line. It carries no ID field: the id\n// belongs to the store, which hands it back on lookup and iteration.\ntype Entry struct {\n\tAuthor  string // bech32 address of the signer\n\tMessage string // the message left by the signer\n\tHeight  int64  // block height at which the entry was signed\n}\n\nconst maxMessageLen = 280\n\n// entries assigns the sequence numbers. v1 kept its own count plus a seqKey()\n// that zero-padded to width 16, the widest of the six hand-rolled variants in\n// this repo and still a ceiling; the store key has none.\nvar entries = store.Named(\"guestbook: entry\")\n\n// Sign appends a new entry to the guestbook attributed to the immediate caller.\n//\n// It is a crossing function (gno 0.9 interrealm convention): callers invoke it\n// as Sign(cross(cur), \"hello\"). The cur.IsCurrent() guard is the authentication\n// primitive — without it a stale/forged realm value could spoof the author.\nfunc Sign(cur realm, message string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"guestbook: spoofed realm; Sign must be called via cross(cur)\")\n\t}\n\n\tauthor := cur.Previous().Address().String()\n\tid, e := addEntry(author, message, runtime.ChainHeight())\n\n\tchain.Emit(\"Signed\",\n\t\t\"id\", id.String(),\n\t\t\"author\", e.Author,\n\t\t\"height\", strconv.FormatInt(e.Height, 10),\n\t)\n}\n\n// addEntry validates the message and appends an entry. Non-crossing internal\n// helper so the append/validation logic is unit-testable without a realm frame.\n// Panics (aborting the tx, reverting state) on an invalid message.\nfunc addEntry(author, message string, height int64) (store.ID, *Entry) {\n\tmsg := strings.TrimSpace(message)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(msg)) == \"\" {\n\t\tpanic(\"guestbook: message must not be empty\")\n\t}\n\tif len(msg) \u003e maxMessageLen {\n\t\tpanic(\"guestbook: message too long (max \" + strconv.Itoa(maxMessageLen) + \" bytes)\")\n\t}\n\n\te := \u0026Entry{\n\t\tAuthor:  author,\n\t\tMessage: msg,\n\t\tHeight:  height,\n\t}\n\treturn entries.Add(e), e\n}\n\n// Count returns the total number of signatures. Read-only, non-crossing.\nfunc Count() int {\n\treturn entries.Len()\n}\n\n// Render lists every entry newest-first as a Markdown table plus a total count.\nfunc Render(path string) string {\n\tif entries.Len() == 0 {\n\t\treturn \"# Guestbook\\n\\n\" + ui.Empty(\"No one has signed yet. Be the first!\")\n\t}\n\n\tt := ui.NewTable(\"#\", \"Who\", \"Message\", \"Height\")\n\t// Ids ascend with signing, so reverse iteration is newest-first.\n\tentries.EachReverse(func(id store.ID, v any) {\n\t\te := v.(*Entry)\n\t\tt.Row(\n\t\t\tid.String(),\n\t\t\tui.AddrOf(e.Author),\n\t\t\tui.Cell(e.Message),\n\t\t\tstrconv.FormatInt(e.Height, 10),\n\t\t)\n\t})\n\n\treturn \"# Guestbook\\n\\n**Total signatures:** \" + strconv.Itoa(entries.Len()) + \"\\n\\n\" + t.String()\n}\n"},{"name":"guestbook_test.gno","body":"package guestbook\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n)\n\n// resetState clears package globals between tests (globals persist across\n// test functions in the same package binary).\nfunc resetState() {\n\tentries = store.Named(\"guestbook: entry\")\n}\n\nfunc TestAddEntryAppendsAndCounts(t *testing.T) {\n\tresetState()\n\n\taddEntry(\"g1alice\", \"hello world\", 100)\n\taddEntry(\"g1bob\", \"second entry\", 101)\n\n\tif got := Count(); got != 2 {\n\t\tt.Fatalf(\"Count() = %d, want 2\", got)\n\t}\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"**Total signatures:** 2\") {\n\t\tt.Errorf(\"Render missing total; got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"hello world\") {\n\t\tt.Errorf(\"Render missing first message; got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"second entry\") {\n\t\tt.Errorf(\"Render missing second message; got:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, \"100\") || !strings.Contains(out, \"101\") {\n\t\tt.Errorf(\"Render missing heights; got:\\n%s\", out)\n\t}\n}\n\nfunc TestRenderNewestFirst(t *testing.T) {\n\tresetState()\n\n\taddEntry(\"g1alice\", \"AAA oldest\", 1)\n\taddEntry(\"g1alice\", \"BBB newest\", 2)\n\n\tout := Render(\"\")\n\tiNew := strings.Index(out, \"BBB newest\")\n\tiOld := strings.Index(out, \"AAA oldest\")\n\tif iNew \u003c 0 || iOld \u003c 0 {\n\t\tt.Fatalf(\"both messages must appear; got:\\n%s\", out)\n\t}\n\tif iNew \u003e iOld {\n\t\tt.Errorf(\"newest entry should render before oldest; got:\\n%s\", out)\n\t}\n}\n\nfunc TestRenderEmpty(t *testing.T) {\n\tresetState()\n\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"No one has signed yet\") {\n\t\tt.Errorf(\"empty render should invite signing; got:\\n%s\", out)\n\t}\n}\n\nfunc TestEmptyMessagePanics(t *testing.T) {\n\tresetState()\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"signing an empty message should panic\")\n\t\t}\n\t}()\n\taddEntry(\"g1alice\", \"   \", 1)\n}\n\n// A message must not be able to break out of its table cell. The escaping now\n// lives in ui.Cell, so this asserts the realm's rendered output rather than a\n// local helper.\nfunc TestRenderEscapesMessage(t *testing.T) {\n\tresetState()\n\tdefer resetState()\n\taddEntry(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\", \"a|b\", 1)\n\tout := Render(\"\")\n\tif strings.Contains(out, \"| a|b |\") {\n\t\tt.Errorf(\"an unescaped pipe would open a column:\\n%s\", out)\n\t}\n\tif !strings.Contains(out, `a\\|b`) {\n\t\tt.Errorf(\"message should appear escaped:\\n%s\", out)\n\t}\n}\n\n// v1 asserted that its own seqKey() ordered numerically. That held only below\n// its width of 16: seqKey(10^16) is 17 characters and sorts before\n// seqKey(10^16-1). The store key is 8 bytes for every id, so there is no\n// ceiling to reach.\nfunc TestSeqKeyOrders(t *testing.T) {\n\tif a, b := store.ID(2).Key(), store.ID(10).Key(); !(a \u003c b) {\n\t\tt.Error(\"id 2 should sort before id 10\")\n\t}\n\tif a, b := store.ID(9999999999999999).Key(), store.ID(10000000000000000).Key(); !(a \u003c b) {\n\t\tt.Error(\"ordering should survive one past v1's width-16 ceiling\")\n\t}\n}\n"},{"name":"render_example_test.gno","body":"package guestbook\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # Guestbook\n\t//\n\t// *No one has signed yet. Be the first!*\n}\n"},{"name":"zz_zerowidth_test.gno","body":"package guestbook\n\nimport (\n\t\"testing\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc zwPanics(f func()) (p bool) {\n\tdefer func() {\n\t\tif recover() != nil {\n\t\t\tp = true\n\t\t}\n\t}()\n\tf()\n\treturn false\n}\n\nfunc TestZeroWidthMessageIsRefused(t *testing.T) {\n\tresetState()\n\tdefer resetState()\n\tfor _, s := range zwBlank {\n\t\tif !zwPanics(func() { addEntry(\"g1alice\", s, 1) }) {\n\t\t\tt.Errorf(\"addEntry(%q) accepted a message the render strips to blank\", s)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif zwPanics(func() { addEntry(\"g1alice\", s, 1) }) {\n\t\t\tt.Errorf(\"addEntry(%q) refused a message that renders as text\", s)\n\t\t}\n\t}\n\tif Count() != len(zwOK) {\n\t\tt.Errorf(\"Count = %d, want %d\", Count(), len(zwOK))\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"50162800","gas_fee":"150488ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"PUkkItnFjOpND8yU5T6JzswJ4xdLhx3nZ8QNMrzx3Mtal1jIx5heCkFFHNcSQpa13wn37vgy/ZDAzMpSzzrtKw=="}],"memo":""},"metadata":{"timestamp":"1791962638"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"TBvyO99rkuvtyRUOKQBssG9sSFKXvU4CZUM4ep/1kPY17YKsHfhgFqQOO+OqYeTDGPoHRfLOXzIJkHdSw0TqgA=="}],"memo":""},"metadata":{"timestamp":"1791963467"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"polls","path":"gno.land/r/moul/x/daily/polls/v1","files":[{"name":"README.md","body":"# Polls \u0026 Voting\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nAn on-chain poll and voting realm for gno.land (gno 0.9). Anyone can\ncreate a poll with a question and a comma-separated set of options; every caller\naddress may cast exactly one vote per poll. The realm's `Render` page lists each\npoll with its options, live tallies drawn as `▓░` bar charts, per-option\npercentages, and the total number of votes.\n\n## Realm path\n\n`gno.land/r/moul/x/daily/polls/v1`\n\n## Exported transactions\n\n- `CreatePoll(question string, options string) int` — create a poll. `options`\n  is a comma-separated list (blank entries are dropped; at least 2 required).\n  Returns the new poll's id.\n- `Vote(pollID int, optionIndex int)` — cast one vote for `optionIndex` on poll\n  `pollID`. One vote per caller address per poll; a second vote aborts.\n\nBoth are gno 0.9 crossing functions (first parameter `cur realm`); the caller\naddress is read via `runtime.PreviousRealm().Address()`.\n\n## Read path\n\n- `Render(\"\")` — index of all polls with bar-chart tallies.\n- `Render(\"\u003cid\u003e\")` — a single poll by id.\n\n## Example calls\n\n```sh\n# create a poll (returns its id, e.g. 0)\ngnokey maketx call -pkgpath \"gno.land/r/moul/x/daily/polls/v1\" \\\n  -func CreatePoll -args \"Best L1 for smart contracts?\" -args \"gno,eth,sol\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 mykey\n\n# vote for option index 0 on poll 0\ngnokey maketx call -pkgpath \"gno.land/r/moul/x/daily/polls/v1\" \\\n  -func Vote -args 0 -args 0 \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 mykey\n\n# view results in gnoweb\n#   https://gno.land/r/moul/x/daily/polls/v1\n#   https://gno.land/r/moul/x/daily/polls/v1:0\n```\n\n## Testing\n\n```sh\ngno test .\n```\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/polls/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/polls/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/polls/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/polls/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/polls/v1\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/daily/polls\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"polls.gno","body":"// Package polls is an on-chain poll / voting realm for gno.land.\n//\n// Anyone can create a poll with a question and a comma-separated list of\n// options. Each caller address may cast exactly one vote per poll. Render\n// draws every poll with its options, tallies as ▓░ bar charts, percentages\n// and the total vote count.\npackage polls\n\nimport (\n\t\"chain\"\n\t\"chain/markdown\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/polls/v1\"\n\n// Poll is a single question with its options and per-address vote tracking.\ntype Poll struct {\n\tID       int\n\tQuestion string\n\tOptions  []string\n\tTallies  []int\n\tCreator  string    // bech32 address of the poll creator\n\tvoted    *avl.Tree // address string -\u003e struct{}{}, one vote per address\n}\n\nvar (\n\tpolls  []*Poll // index i holds the poll with ID i\n\tnextID int\n)\n\n// CreatePoll registers a new poll. options is a comma-separated list; blank\n// entries are dropped. Returns the new poll's id. Crossing function: an EOA\n// invokes it via MsgCall; another realm via polls.CreatePoll(cross, q, opts).\nfunc CreatePoll(cur realm, question string, options string) int {\n\tcreator := caller(cur).String()\n\n\tq := strings.TrimSpace(question)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(q)) == \"\" {\n\t\tpanic(\"question must not be empty\")\n\t}\n\n\tif len(q) \u003e MaxQuestionLen {\n\t\tpanic(\"question too long\")\n\t}\n\topts := parseOptions(options)\n\tif len(opts) \u003c 2 {\n\t\tpanic(\"a poll needs at least 2 options\")\n\t}\n\tif len(opts) \u003e MaxOptions {\n\t\tpanic(\"a poll takes at most \" + strconv.Itoa(MaxOptions) + \" options\")\n\t}\n\tfor _, o := range opts {\n\t\tif len(o) \u003e MaxOptionLen {\n\t\t\tpanic(\"option too long\")\n\t\t}\n\t}\n\tif len(polls) \u003e= MaxPolls {\n\t\tpanic(\"polls is full at \" + strconv.Itoa(MaxPolls) + \" polls\")\n\t}\n\n\tid := nextID\n\tnextID++\n\tp := \u0026Poll{\n\t\tID:       id,\n\t\tQuestion: q,\n\t\tOptions:  opts,\n\t\tTallies:  make([]int, len(opts)),\n\t\tCreator:  creator,\n\t\tvoted:    avl.NewTree(),\n\t}\n\tpolls = append(polls, p)\n\n\tchain.Emit(\"PollCreated\",\n\t\t\"id\", strconv.Itoa(id),\n\t\t\"creator\", creator,\n\t\t\"options\", strconv.Itoa(len(opts)),\n\t)\n\treturn id\n}\n\n// Vote casts one vote for optionIndex on poll pollID. Each caller address may\n// vote at most once per poll. Crossing function.\nfunc Vote(cur realm, pollID int, optionIndex int) {\n\tvoter := caller(cur).String()\n\n\tp := getPoll(pollID)\n\tif optionIndex \u003c 0 || optionIndex \u003e= len(p.Options) {\n\t\tpanic(\"option index out of range\")\n\t}\n\tif p.voted.Has(voter) {\n\t\tpanic(\"address already voted on this poll\")\n\t}\n\n\tp.voted.Set(voter, struct{}{})\n\tp.Tallies[optionIndex]++\n\n\tchain.Emit(\"Voted\",\n\t\t\"id\", strconv.Itoa(pollID),\n\t\t\"voter\", voter,\n\t\t\"option\", strconv.Itoa(optionIndex),\n\t)\n}\n\n// parseOptions splits a comma-separated option string, trimming whitespace and\n// dropping empties. Pure logic — no realm state.\nfunc parseOptions(options string) []string {\n\tvar out []string\n\tfor _, raw := range strings.Split(options, \",\") {\n\t\to := strings.TrimSpace(raw)\n\t\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(o)) != \"\" {\n\t\t\tout = append(out, o)\n\t\t}\n\t}\n\treturn out\n}\n\n// getPoll returns the poll with the given id or panics if it does not exist.\nfunc getPoll(id int) *Poll {\n\tif id \u003c 0 || id \u003e= len(polls) {\n\t\tpanic(\"poll not found\")\n\t}\n\treturn polls[id]\n}\n\n// PollCount returns the number of polls created so far (read-only helper).\nfunc PollCount() int {\n\treturn len(polls)\n}\n\nconst barWidth = 20\n\n// The bounds on what a creator may store. Anyone may create a poll, and the\n// root page renders the newest ones.\nconst (\n\tMaxPolls       = 500\n\tMaxQuestionLen = 200\n\tMaxOptions     = 10\n\tMaxOptionLen   = 64\n\tIndexRecent    = 20 // polls the root page shows, newest first\n)\n\n// bar renders a proportional ▓░ bar of fixed width for count out of total.\nfunc bar(count, total int) string {\n\tfilled := 0\n\tif total \u003e 0 {\n\t\tfilled = count * barWidth / total\n\t}\n\tif filled \u003e barWidth {\n\t\tfilled = barWidth\n\t}\n\treturn strings.Repeat(\"▓\", filled) + strings.Repeat(\"░\", barWidth-filled)\n}\n\n// percent returns the integer percentage of count out of total.\nfunc percent(count, total int) int {\n\tif total == 0 {\n\t\treturn 0\n\t}\n\treturn count * 100 / total\n}\n\n// total sums a tally slice.\nfunc total(tallies []int) int {\n\tsum := 0\n\tfor _, t := range tallies {\n\t\tsum += t\n\t}\n\treturn sum\n}\n\n// renderPoll writes one poll's Markdown block into b.\nfunc renderPoll(b *strings.Builder, p *Poll) {\n\tsum := total(p.Tallies)\n\n\tb.WriteString(\"## Poll #\")\n\tb.WriteString(strconv.Itoa(p.ID))\n\tb.WriteString(\": \")\n\tb.WriteString(ui.Inline(p.Question))\n\tb.WriteString(\"\\n\\n\")\n\n\tfor i, opt := range p.Options {\n\t\tc := p.Tallies[i]\n\t\tb.WriteString(\"- **\")\n\t\tb.WriteString(ui.Inline(opt))\n\t\tb.WriteString(\"** `\")\n\t\tb.WriteString(bar(c, sum))\n\t\tb.WriteString(\"` \")\n\t\tb.WriteString(strconv.Itoa(percent(c, sum)))\n\t\tb.WriteString(\"% (\")\n\t\tb.WriteString(strconv.Itoa(c))\n\t\tif c == 1 {\n\t\t\tb.WriteString(\" vote)\")\n\t\t} else {\n\t\t\tb.WriteString(\" votes)\")\n\t\t}\n\t\tb.WriteString(\"\\n\")\n\t}\n\n\tb.WriteString(\"\\n_Total votes: \")\n\tb.WriteString(strconv.Itoa(sum))\n\tb.WriteString(\"_\\n\\n\")\n}\n\n// Render produces the Markdown page for gnoweb. It is NOT a crossing function.\n//\n//   - \"\"          -\u003e the IndexRecent newest polls\n//   - \"page/\u003cn\u003e\"  -\u003e the n-th page of IndexRecent, newest first (page/1 is \"\")\n//   - \"\u003cid\u003e\"      -\u003e a single poll by id\nfunc Render(path string) string {\n\tvar b strings.Builder\n\n\tpath = strings.TrimSpace(path)\n\tpage := 1\n\tif rest, ok := strings.CutPrefix(path, \"page/\"); ok {\n\t\tn, err := strconv.Atoi(rest)\n\t\t// Bounded before any multiply: the page comes from the URL.\n\t\tif err != nil || n \u003c 1 || n \u003e 1+(len(polls)-1)/IndexRecent {\n\t\t\treturn \"# Polls\\n\\nNo such page.\\n\\n[← all polls](\" + selfPath + \")\\n\"\n\t\t}\n\t\tpage, path = n, \"\"\n\t}\n\tif path != \"\" {\n\t\tid, err := strconv.Atoi(path)\n\t\tif err != nil || id \u003c 0 || id \u003e= len(polls) {\n\t\t\treturn \"# Polls\\n\\nPoll not found.\\n\"\n\t\t}\n\t\tb.WriteString(\"# Polls\\n\\n\")\n\t\trenderPoll(\u0026b, polls[id])\n\t\tb.WriteString(\"[← all polls](\" + selfPath + \")\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"# Polls \u0026 Voting\\n\\n\")\n\tif len(polls) == 0 {\n\t\tb.WriteString(\"_No polls yet. Create one with `CreatePoll(question, \\\"a,b,c\\\")`._\\n\")\n\t\treturn b.String()\n\t}\n\n\tpages := 1 + (len(polls)-1)/IndexRecent\n\tb.WriteString(\"Total polls: \")\n\tb.WriteString(strconv.Itoa(len(polls)))\n\tif pages \u003e 1 {\n\t\tb.WriteString(\", page \" + strconv.Itoa(page) + \" of \" + strconv.Itoa(pages))\n\t}\n\tb.WriteString(\"\\n\\n\")\n\t//gnovet:ignore page-offset-overflow page is bounded by pages above\n\ttop := len(polls) - 1 - (page-1)*IndexRecent\n\tfor i := top; i \u003e= 0 \u0026\u0026 i \u003e top-IndexRecent; i-- {\n\t\trenderPoll(\u0026b, polls[i])\n\t}\n\tif page \u003c pages {\n\t\tb.WriteString(\"[older polls →](\" + selfPath + \":page/\" + strconv.Itoa(page+1) + \")\\n\")\n\t}\n\treturn b.String()\n}\n\n// caller is the address that crossed into this realm, after checking that the\n// realm token is this frame's own.\nfunc caller(cur realm) address {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"polls: spoofed realm\")\n\t}\n\treturn cur.Previous().Address()\n}\n"},{"name":"polls_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarol = testutils.TestAddress(\"carol\")\n)\n\n// resetState clears package-level state between tests so cases are independent.\nfunc resetState() {\n\tpolls = nil\n\tnextID = 0\n}\n\nfunc TestParseOptions(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput string\n\t\twant  []string\n\t}{\n\t\t{\"simple\", \"a,b,c\", []string{\"a\", \"b\", \"c\"}},\n\t\t{\"trims spaces\", \" yes , no \", []string{\"yes\", \"no\"}},\n\t\t{\"drops empties\", \"a,,b, ,c\", []string{\"a\", \"b\", \"c\"}},\n\t\t{\"single\", \"only\", []string{\"only\"}},\n\t\t{\"all blank\", \" , ,\", nil},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := parseOptions(tt.input)\n\t\tif len(got) != len(tt.want) {\n\t\t\tt.Errorf(\"%s: len = %d, want %d (%v)\", tt.name, len(got), len(tt.want), got)\n\t\t\tcontinue\n\t\t}\n\t\tfor i := range got {\n\t\t\tif got[i] != tt.want[i] {\n\t\t\t\tt.Errorf(\"%s: [%d] = %q, want %q\", tt.name, i, got[i], tt.want[i])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestCreateAndVote(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"Best chain?\", \"gno,eth,btc\")\n\tif id != 0 {\n\t\tt.Fatalf(\"first poll id = %d, want 0\", id)\n\t}\n\tif PollCount() != 1 {\n\t\tt.Fatalf(\"PollCount = %d, want 1\", PollCount())\n\t}\n\n\t// alice votes gno.\n\tVote(cross(cur), id, 0)\n\n\t// bob votes eth.\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tVote(cross(cur), id, 1)\n\n\t// carol votes gno.\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\tVote(cross(cur), id, 0)\n\n\tp := getPoll(id)\n\tif p.Tallies[0] != 2 {\n\t\tt.Errorf(\"gno tally = %d, want 2\", p.Tallies[0])\n\t}\n\tif p.Tallies[1] != 1 {\n\t\tt.Errorf(\"eth tally = %d, want 1\", p.Tallies[1])\n\t}\n\tif total(p.Tallies) != 3 {\n\t\tt.Errorf(\"total = %d, want 3\", total(p.Tallies))\n\t}\n}\n\nfunc TestDoubleVotePanics(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"Coffee or tea?\", \"coffee,tea\")\n\tVote(cross(cur), id, 0)\n\n\t// A second vote by the same address aborts (cross-realm panic).\n\tuassert.AbortsWithMessage(t, cur, \"address already voted on this poll\", func() {\n\t\tVote(cross(cur), id, 1)\n\t})\n}\n\nfunc TestVoteBounds(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"A or B?\", \"a,b\")\n\n\tuassert.AbortsWithMessage(t, cur, \"option index out of range\", func() {\n\t\tVote(cross(cur), id, 5)\n\t})\n}\n\nfunc TestCreatePollNeedsTwoOptions(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsWithMessage(t, cur, \"a poll needs at least 2 options\", func() {\n\t\tCreatePoll(cross(cur), \"One?\", \"only\")\n\t})\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// Empty index.\n\tif got := Render(\"\"); !strings.Contains(got, \"No polls yet\") {\n\t\tt.Errorf(\"empty Render should mention no polls, got:\\n%s\", got)\n\t}\n\n\tid := CreatePoll(cross(cur), \"Pick one\", \"x,y\")\n\tVote(cross(cur), id, 0)\n\n\t// Index lists the poll and bar chart glyphs.\n\tidx := Render(\"\")\n\tif !strings.Contains(idx, \"Pick one\") {\n\t\tt.Errorf(\"index missing question:\\n%s\", idx)\n\t}\n\tif !strings.Contains(idx, \"▓\") || !strings.Contains(idx, \"░\") {\n\t\tt.Errorf(\"index missing bar glyphs:\\n%s\", idx)\n\t}\n\tif !strings.Contains(idx, \"Total votes: 1\") {\n\t\tt.Errorf(\"index missing total votes:\\n%s\", idx)\n\t}\n\tif !strings.Contains(idx, \"100%\") {\n\t\tt.Errorf(\"index missing 100%% for the sole vote:\\n%s\", idx)\n\t}\n\n\t// Single-poll path.\n\tsingle := Render(\"0\")\n\tif !strings.Contains(single, \"Poll #0\") {\n\t\tt.Errorf(\"single Render missing poll header:\\n%s\", single)\n\t}\n\n\t// Unknown path.\n\tif got := Render(\"99\"); !strings.Contains(got, \"not found\") {\n\t\tt.Errorf(\"unknown poll should say not found, got:\\n%s\", got)\n\t}\n}\n"},{"name":"zz_bounds_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// What a creator may store is bounded, and the root page renders a fixed\n// window of the newest polls whatever the count.\nfunc TestPollsAreBounded(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"bounded\")))\n\tuassert.AbortsContains(t, cur, \"question too long\", func() { CreatePoll(cross(cur), strings.Repeat(\"q\", MaxQuestionLen+1), \"a,b\") })\n\tuassert.AbortsContains(t, cur, \"at most\", func() { CreatePoll(cross(cur), \"many\", strings.Repeat(\"o,\", MaxOptions)+\"o\") })\n\tfor len(polls) \u003c IndexRecent+3 {\n\t\tCreatePoll(cross(cur), \"filler\", \"a,b\")\n\t}\n\tuassert.Equal(t, IndexRecent, strings.Count(Render(\"\"), \"## Poll #\"))\n}\n\n// The poll count is bounded globally.\nfunc TestPollCountIsBounded(cur realm, t *testing.T) {\n\tbefore := len(polls)\n\tfor len(polls) \u003c MaxPolls {\n\t\tpolls = append(polls, \u0026Poll{ID: len(polls), Question: \"q\", Options: []string{\"a\", \"b\"}, Tallies: []int{0, 0}})\n\t}\n\tdefer func() { polls = polls[:before] }()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"latecomer\")))\n\tuassert.AbortsContains(t, cur, \"polls is full\", func() { CreatePoll(cross(cur), \"one more\", \"a,b\") })\n}\n\n// Polls past the newest page stay reachable: the index links to the next\n// page, and a page past the end says so instead of wrapping.\nfunc TestOlderPollsArePaged(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"pager\")))\n\tfor len(polls) \u003c IndexRecent+1 {\n\t\tCreatePoll(cross(cur), \"filler\", \"a,b\")\n\t}\n\tidx := Render(\"\")\n\tuassert.True(t, strings.Contains(idx, \"(/r/moul/x/daily/polls/v1:page/2)\"), idx)\n\tp2 := Render(\"page/2\")\n\tuassert.True(t, strings.Contains(p2, \"## Poll #0:\"), p2)\n\tuassert.True(t, strings.Contains(Render(\"page/9223372036854775807\"), \"No such page\"))\n}\n"},{"name":"zz_escape_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A question and its options are the creator's text: escaped.\nfunc TestQuestionAndOptionsAreEscaped(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"escaper\")))\n\tid := CreatePoll(cross(cur), \"[claim](https://evil.example)\", \"[claim](https://evil.example)\"+\",no\")\n\tpage := Render(itoaTest(id))\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n\tuassert.False(t, strings.Contains(Render(\"\"), \"[claim](https://evil.example)\"), Render(\"\"))\n}\n"},{"name":"zz_links_test.gno","body":"package polls\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// A poll page links back to this realm. It once linked to\n// /r/REPLACE_ADDR/polls.\nfunc TestPollPageLinksBackToThisRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"linker\")))\n\tid := CreatePoll(cross(cur), \"Linked?\", \"yes,no\")\n\tpage := Render(itoaTest(id))\n\tuassert.True(t, strings.Contains(page, \"[← all polls](/r/moul/x/daily/polls/v1)\"), page)\n}\n\nfunc itoaTest(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\ts := \"\"\n\tfor n \u003e 0 {\n\t\ts = string(rune(byte(n%10)+byte(48))) + s\n\t\tn /= 10\n\t}\n\treturn s\n}\n"},{"name":"zz_zerowidth_test.gno","body":"package polls\n\nimport (\n\t\"testing\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc TestZeroWidthQuestionIsRefused(cur realm, t *testing.T) {\n\tresetState()\n\tdefer resetState()\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfor _, s := range zwBlank {\n\t\tif revive(func() { CreatePoll(cross(cur), s, \"x,y\") }) == nil {\n\t\t\tt.Errorf(\"CreatePoll accepted question %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif r := revive(func() { CreatePoll(cross(cur), s, \"x,y\") }); r != nil {\n\t\t\tt.Errorf(\"CreatePoll refused question %q: %v\", s, r)\n\t\t}\n\t}\n\tif PollCount() != len(zwOK) {\n\t\tt.Errorf(\"PollCount = %d, want %d\", PollCount(), len(zwOK))\n\t}\n}\n\nfunc TestZeroWidthOptionIsDropped(t *testing.T) {\n\tfor _, s := range zwBlank {\n\t\tif got := parseOptions(\"x,\" + s); len(got) != 1 {\n\t\t\tt.Errorf(\"parseOptions kept option %q, which the render strips to blank: %q\", s, got)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif got := parseOptions(\"x,\" + s); len(got) != 2 {\n\t\t\tt.Errorf(\"parseOptions dropped option %q, which renders as text: %q\", s, got)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"8000000ugnot"}],"fee":{"gas_wanted":"63435800","gas_fee":"190307ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"3VGTPszIosi92B/WVudXAp9b5PJbvfxFWnceZ7Z/cglHewgCrshd09hUY+ER/VUWDWjT9dz0EV4sgL7OpPilKw=="}],"memo":""},"metadata":{"timestamp":"1791963468"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"qvote","path":"gno.land/r/moul/x/daily/qvote/v1","files":[{"name":"README.md","body":"# Quadratic Voting\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nA Gno port of the classic Solidity 'Ballot' voting contract, but swapping one-address-one-vote for quadratic voting: every address gets a fixed 100-credit budget per poll, and stacking N votes on one option costs N^2 credits, so spreading conviction is cheap but dominating one option gets steep fast. Create a poll with CreatePoll, spend (or refund) credits with Vote(pollID, optionIdx, delta), and the creator ends it with ClosePoll. Render shows the poll board, per-poll results, and any voter's standing.\n\nBuilt for sapphire (gno 0.9). Live demo (agent address): https://sapphire.testnets.gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/qvote\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/qvote) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline` helper.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/qvote/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/qvote/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/qvote/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/qvote/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/qvote/v1\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/daily/qvote\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"qvote.gno","body":"// Package qvote is a quadratic-voting poll board, a Gno take on the classic\n// Solidity \"Ballot\" voting contract with one twist borrowed from mechanism\n// design instead of one-address-one-vote: every voter gets a fixed voice-\n// credit budget per poll, and piling votes onto a single option costs the\n// square of how many votes they stack there. Buying your 1st vote on an\n// option costs 1 credit, the 2nd costs 3 more (4 total), the 3rd costs 5\n// more (9 total) -- so spreading conviction across options is cheap, but\n// dominating one option gets expensive fast. Votes can also be pulled back\n// for a matching credit refund.\npackage qvote\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// InitialCredits is the fixed voice-credit budget every address gets to\n// spend on each poll (shared across all of that poll's options).\nconst InitialCredits int64 = 100\n\nconst (\n\tminOptions = 2\n\tmaxOptions = 8\n)\n\ntype poll struct {\n\tID            string\n\tCreator       address\n\tQuestion      string\n\tOptions       []string\n\tTally         []int64\n\tCreatedHeight int64\n\tClosed        bool\n}\n\n// voterState is one address's standing inside one poll: how many credits\n// they've spent so far and how many votes that bought them on each option.\ntype voterState struct {\n\tCreditsUsed int64\n\tVotes       []int64\n}\n\nvar (\n\tpolls  avl.Tree // poll ID -\u003e *poll\n\tvoters avl.Tree // \"\u003cpollID\u003e:\u003caddr\u003e\" -\u003e *voterState\n\tnextID int\n)\n\nfunc voterKey(pollID string, addr address) string {\n\treturn pollID + \":\" + addr.String()\n}\n\nfunc getPoll(pollID string) *poll {\n\tp, ok := polls.Get(pollID).(*poll)\n\tif !ok {\n\t\tpanic(\"no such poll: \" + pollID)\n\t}\n\treturn p\n}\n\nfunc getOrCreateVoter(pollID string, addr address, numOptions int) *voterState {\n\tkey := voterKey(pollID, addr)\n\tif v, ok := voters.Get(key).(*voterState); ok {\n\t\treturn v\n\t}\n\tvs := \u0026voterState{Votes: make([]int64, numOptions)}\n\tvoters.Set(key, vs)\n\treturn vs\n}\n\n// square is the quadratic-voting cost curve: N votes on one option cost\n// N*N credits in total.\nfunc square(n int64) int64 {\n\treturn n * n\n}\n\n// CreatePoll opens a new poll with the given question and comma-separated\n// options (at least 2, at most 8), returning its ID.\nfunc CreatePoll(cur realm, question string, optionsCSV string) string {\n\tcreator := cur.Previous().Address()\n\n\tquestion = strings.TrimSpace(question)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(question)) == \"\" {\n\t\tpanic(\"question must not be empty\")\n\t}\n\n\tvar options []string\n\tfor _, raw := range strings.Split(optionsCSV, \",\") {\n\t\topt := strings.TrimSpace(raw)\n\t\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(opt)) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\toptions = append(options, opt)\n\t}\n\tif len(options) \u003c minOptions {\n\t\tpanic(\"need at least \" + strconv.Itoa(minOptions) + \" non-empty options\")\n\t}\n\tif len(options) \u003e maxOptions {\n\t\tpanic(\"at most \" + strconv.Itoa(maxOptions) + \" options are allowed\")\n\t}\n\n\tnextID++\n\tid := strconv.Itoa(nextID)\n\tp := \u0026poll{\n\t\tID:            id,\n\t\tCreator:       creator,\n\t\tQuestion:      question,\n\t\tOptions:       options,\n\t\tTally:         make([]int64, len(options)),\n\t\tCreatedHeight: runtime.ChainHeight(),\n\t}\n\tpolls.Set(id, p)\n\n\tchain.Emit(\"PollCreated\", \"id\", id, \"creator\", creator.String(), \"question\", question)\n\n\treturn \"poll #\" + id + \" created with \" + strconv.Itoa(len(options)) + \" options\"\n}\n\n// Vote adjusts the caller's votes on one option of a poll by delta (positive\n// to buy more, negative to sell some back for a credit refund). The credit\n// cost of holding N votes on an option is N*N, taken from the caller's fixed\n// per-poll budget of InitialCredits.\nfunc Vote(cur realm, pollID string, optionIdx int, delta int64) string {\n\tcaller := cur.Previous().Address()\n\n\tp := getPoll(pollID)\n\tif p.Closed {\n\t\tpanic(\"poll #\" + pollID + \" is closed\")\n\t}\n\tif optionIdx \u003c 0 || optionIdx \u003e= len(p.Options) {\n\t\tpanic(\"invalid option index\")\n\t}\n\tif delta == 0 {\n\t\tpanic(\"delta must be non-zero\")\n\t}\n\n\tvs := getOrCreateVoter(pollID, caller, len(p.Options))\n\tcurrent := vs.Votes[optionIdx]\n\tupdated := current + delta\n\tif updated \u003c 0 {\n\t\tpanic(\"cannot remove more votes than you hold on this option\")\n\t}\n\n\tcost := square(updated) - square(current)\n\tnewCreditsUsed := vs.CreditsUsed + cost\n\tif newCreditsUsed \u003e InitialCredits {\n\t\tpanic(\"exceeds your voice-credit budget of \" + strconv.FormatInt(InitialCredits, 10) +\n\t\t\t\" for this poll (would need \" + strconv.FormatInt(newCreditsUsed, 10) + \")\")\n\t}\n\n\tvs.Votes[optionIdx] = updated\n\tvs.CreditsUsed = newCreditsUsed\n\tp.Tally[optionIdx] += delta\n\n\tchain.Emit(\"VoteCast\",\n\t\t\"pollID\", pollID,\n\t\t\"voter\", caller.String(),\n\t\t\"option\", p.Options[optionIdx],\n\t\t\"votes\", strconv.FormatInt(updated, 10),\n\t)\n\n\tverb := \"bought\"\n\tn := delta\n\tif delta \u003c 0 {\n\t\tverb = \"sold back\"\n\t\tn = -delta\n\t}\n\treturn \"you \" + verb + \" \" + strconv.FormatInt(n, 10) + \" vote(s) on \\\"\" + p.Options[optionIdx] +\n\t\t\"\\\" -- now holding \" + strconv.FormatInt(updated, 10) + \" (credits used: \" +\n\t\tstrconv.FormatInt(vs.CreditsUsed, 10) + \"/\" + strconv.FormatInt(InitialCredits, 10) + \")\"\n}\n\n// ClosePoll ends voting on a poll. Only its creator may close it.\nfunc ClosePoll(cur realm, pollID string) string {\n\tcaller := cur.Previous().Address()\n\n\tp := getPoll(pollID)\n\tif caller != p.Creator {\n\t\tpanic(\"only the poll creator can close it\")\n\t}\n\tif p.Closed {\n\t\tpanic(\"poll #\" + pollID + \" is already closed\")\n\t}\n\tp.Closed = true\n\n\tchain.Emit(\"PollClosed\", \"id\", pollID)\n\n\treturn \"poll #\" + pollID + \" closed\"\n}\n\nfunc leadingOption(p *poll) (string, int64) {\n\tbest := -1\n\tvar bestVotes int64 = -1\n\tfor i, v := range p.Tally {\n\t\tif v \u003e bestVotes {\n\t\t\tbestVotes = v\n\t\t\tbest = i\n\t\t}\n\t}\n\tif best \u003c 0 {\n\t\treturn \"\", 0\n\t}\n\treturn p.Options[best], bestVotes\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# Quadratic Voting\\n\\n\")\n\tb.WriteString(\"Create a poll, then spend voice credits on the options you care about -- \" +\n\t\t\"the Nth vote you stack on one option costs N^2 credits out of a fixed budget of \" +\n\t\tstrconv.FormatInt(InitialCredits, 10) + \" per poll, so spreading support across \" +\n\t\t\"options is cheap but dominating one gets steep fast.\\n\\n\")\n\n\tb.WriteString(\"## Polls\\n\\n\")\n\tcount := 0\n\tpolls.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tcount++\n\t\tp := value.(*poll)\n\t\tstatus := \"open\"\n\t\tif p.Closed {\n\t\t\tstatus = \"closed\"\n\t\t}\n\t\tlead, votes := leadingOption(p)\n\t\tline := \"- #\" + p.ID + \" (\" + status + \"): \" + ui.Inline(p.Question)\n\t\tif lead != \"\" {\n\t\t\tline += \" -- leading: \\\"\" + ui.Inline(lead) + \"\\\" (\" + strconv.FormatInt(votes, 10) + \")\"\n\t\t}\n\t\tb.WriteString(line + \"\\n\")\n\t\treturn false\n\t})\n\tif count == 0 {\n\t\tb.WriteString(\"_no polls yet -- call `CreatePoll(question, \\\"opt1,opt2,...\\\")` to start one._\\n\")\n\t}\n\n\tb.WriteString(\"\\n## How to use\\n\\n\")\n\tb.WriteString(\"1. `CreatePoll(\\\"Best pizza topping?\\\", \\\"pineapple,mushroom,pepperoni\\\")` -- returns a poll ID.\\n\")\n\tb.WriteString(\"2. `Vote(pollID, optionIdx, delta)` -- e.g. `Vote(\\\"1\\\", 0, 3)` buys 3 votes on option 0 \" +\n\t\t\"(costs 9 credits); a negative delta sells votes back for a refund.\\n\")\n\tb.WriteString(\"3. `ClosePoll(pollID)` -- the creator ends voting.\\n\\n\")\n\tb.WriteString(\"View a poll at this realm's path plus its ID (e.g. `.../qvote:1`), \" +\n\t\t\"or one voter's standing in it with `.../qvote:1/g1youraddress...`.\\n\")\n\n\treturn b.String()\n}\n\nfunc renderPoll(id string) string {\n\tp, ok := polls.Get(id).(*poll)\n\tif !ok {\n\t\treturn \"# Poll #\" + ui.Inline(id) + \"\\n\\nNo such poll.\\n\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Poll #\" + p.ID + \": \" + ui.Inline(p.Question) + \"\\n\\n\")\n\tstatus := \"open\"\n\tif p.Closed {\n\t\tstatus = \"closed\"\n\t}\n\tb.WriteString(\"- Status: \" + status + \"\\n\")\n\tb.WriteString(\"- Creator: `\" + p.Creator.String() + \"`\\n\\n\")\n\n\tb.WriteString(\"## Results\\n\\n\")\n\tvar total int64\n\tfor _, v := range p.Tally {\n\t\ttotal += v\n\t}\n\tfor i, opt := range p.Options {\n\t\tb.WriteString(strconv.Itoa(i) + \". \" + ui.Inline(opt) + \" -- \" +\n\t\t\tstrconv.FormatInt(p.Tally[i], 10) + \" vote(s)\\n\")\n\t}\n\tb.WriteString(\"\\nTotal votes cast: \" + strconv.FormatInt(total, 10) + \"\\n\")\n\n\treturn b.String()\n}\n\nfunc renderVoter(pollID, rawAddr string) string {\n\tsafeAddr := ui.Inline(strings.TrimSpace(rawAddr))\n\tp, ok := polls.Get(pollID).(*poll)\n\tif !ok {\n\t\treturn \"# Poll #\" + ui.Inline(pollID) + \"\\n\\nNo such poll.\\n\"\n\t}\n\n\tvar b strings.Builder\n\tb.WriteString(\"# \" + safeAddr + \" in poll #\" + p.ID + \"\\n\\n\")\n\n\tstate, ok := voters.Get(voterKey(pollID, address(strings.TrimSpace(rawAddr)))).(*voterState)\n\tif !ok {\n\t\tb.WriteString(\"No votes cast yet.\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"- Credits used: \" + strconv.FormatInt(state.CreditsUsed, 10) + \"/\" +\n\t\tstrconv.FormatInt(InitialCredits, 10) + \"\\n\\n\")\n\tfor i, opt := range p.Options {\n\t\tif state.Votes[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tb.WriteString(\"- \" + ui.Inline(opt) + \": \" + strconv.FormatInt(state.Votes[i], 10) + \" vote(s)\\n\")\n\t}\n\n\treturn b.String()\n}\n\n// Render shows the poll board at \"\", one poll's results at \"\u003cpollID\u003e\", or\n// one voter's standing in a poll at \"\u003cpollID\u003e/\u003caddr\u003e\".\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\tif idx := strings.IndexByte(path, '/'); idx \u003e= 0 {\n\t\treturn renderVoter(path[:idx], path[idx+1:])\n\t}\n\treturn renderPoll(path)\n}\n"},{"name":"qvote_test.gno","body":"package qvote\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\tpolls = avl.Tree{}\n\tvoters = avl.Tree{}\n\tnextID = 0\n}\n\nfunc TestSquare(t *testing.T) {\n\tcases := []struct {\n\t\tn, want int64\n\t}{\n\t\t{0, 0}, {1, 1}, {2, 4}, {3, 9}, {10, 100},\n\t}\n\tfor _, c := range cases {\n\t\tif got := square(c.n); got != c.want {\n\t\t\tt.Fatalf(\"square(%d) = %d, want %d\", c.n, got, c.want)\n\t\t}\n\t}\n}\n\n// Crossing: CreatePoll mutates realm state, so the test needs `cur realm`.\nfunc TestCreatePollValidatesOptions(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tid := CreatePoll(cross(cur), \"best color?\", \"red, green , blue\")\n\tif id != \"poll #1 created with 3 options\" {\n\t\tt.Fatalf(\"unexpected message: %q\", id)\n\t}\n\tp := getPoll(\"1\")\n\tif len(p.Options) != 3 || p.Options[0] != \"red\" || p.Options[2] != \"blue\" {\n\t\tt.Fatalf(\"options not parsed/trimmed correctly: %#v\", p.Options)\n\t}\n\n\tif rec := revive(func() { CreatePoll(cross(cur), \"one option?\", \"only-one\") }); rec == nil {\n\t\tt.Fatal(\"expected panic for too few options\")\n\t}\n\tif rec := revive(func() { CreatePoll(cross(cur), \"  \", \"a,b\") }); rec == nil {\n\t\tt.Fatal(\"expected panic for empty question\")\n\t}\n}\n\nfunc TestVoteQuadraticCostAndBudget(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreatePoll(cross(cur), \"pizza topping?\", \"pineapple,mushroom,pepperoni\")\n\n\t// 1st vote costs 1, 2nd costs 3 more (4 total), 3rd costs 5 more (9 total).\n\tVote(cross(cur), \"1\", 0, 1)\n\tvs := getOrCreateVoter(\"1\", alice, 3)\n\tif vs.CreditsUsed != 1 {\n\t\tt.Fatalf(\"credits used = %d, want 1\", vs.CreditsUsed)\n\t}\n\tVote(cross(cur), \"1\", 0, 2)\n\tif vs.CreditsUsed != 9 || vs.Votes[0] != 3 {\n\t\tt.Fatalf(\"after buying to 3 votes: credits=%d votes=%d, want 9/3\", vs.CreditsUsed, vs.Votes[0])\n\t}\n\n\t// Spending the rest of the 100-credit budget on another option should work\n\t// right up to the edge, then fail past it.\n\tVote(cross(cur), \"1\", 1, 9) // 81 credits, total 90\n\tif vs.CreditsUsed != 90 {\n\t\tt.Fatalf(\"credits used = %d, want 90\", vs.CreditsUsed)\n\t}\n\tif rec := revive(func() { Vote(cross(cur), \"1\", 2, 4) }); rec == nil { // would cost 16 more, total 106 \u003e 100\n\t\tt.Fatal(\"expected panic for exceeding voice-credit budget\")\n\t}\n\n\tp := getPoll(\"1\")\n\tif p.Tally[0] != 3 || p.Tally[1] != 9 {\n\t\tt.Fatalf(\"unexpected tally: %#v\", p.Tally)\n\t}\n}\n\nfunc TestVoteSellBackRefundsCredits(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreatePoll(cross(cur), \"best sea?\", \"north,baltic\")\n\n\tVote(cross(cur), \"1\", 0, 4) // 16 credits, 4 votes\n\tVote(cross(cur), \"1\", 0, -1) // back to 3 votes: cost delta = 9-16 = -7\n\n\tvs := getOrCreateVoter(\"1\", alice, 2)\n\tif vs.Votes[0] != 3 {\n\t\tt.Fatalf(\"votes = %d, want 3\", vs.Votes[0])\n\t}\n\tif vs.CreditsUsed != 9 {\n\t\tt.Fatalf(\"credits used = %d, want 9\", vs.CreditsUsed)\n\t}\n\tif getPoll(\"1\").Tally[0] != 3 {\n\t\tt.Fatalf(\"tally = %d, want 3\", getPoll(\"1\").Tally[0])\n\t}\n\n\tif rec := revive(func() { Vote(cross(cur), \"1\", 0, -10) }); rec == nil {\n\t\tt.Fatal(\"expected panic for selling more votes than held\")\n\t}\n}\n\nfunc TestClosePollOnlyCreator(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tCreatePoll(cross(cur), \"close me?\", \"yes,no\")\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tif rec := revive(func() { ClosePoll(cross(cur), \"1\") }); rec == nil {\n\t\tt.Fatal(\"expected panic when a non-creator closes the poll\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tClosePoll(cross(cur), \"1\")\n\tif !getPoll(\"1\").Closed {\n\t\tt.Fatal(\"poll should be closed\")\n\t}\n\n\tif rec := revive(func() { Vote(cross(cur), \"1\", 0, 1) }); rec == nil {\n\t\tt.Fatal(\"expected panic when voting on a closed poll\")\n\t}\n}\n\nfunc TestRenderNoPolls(t *testing.T) {\n\tresetState()\n\tout := Render(\"\")\n\tif !strings.Contains(out, \"no polls yet\") {\n\t\tt.Fatalf(\"expected empty-state message, got: %s\", out)\n\t}\n}\n\nfunc TestRenderPollNotFound(t *testing.T) {\n\tresetState()\n\tout := Render(\"42\")\n\tif !strings.Contains(out, \"No such poll\") {\n\t\tt.Fatalf(\"expected not-found message, got: %s\", out)\n\t}\n}\n\n"},{"name":"zz_zerowidth_test.gno","body":"package qvote\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc TestZeroWidthQuestionAndOptionAreRefused(cur realm, t *testing.T) {\n\tresetState()\n\tdefer resetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\tfor _, s := range zwBlank {\n\t\tif revive(func() { CreatePoll(cross(cur), s, \"x,y\") }) == nil {\n\t\t\tt.Errorf(\"CreatePoll accepted question %q, which the render strips to blank\", s)\n\t\t}\n\t\t// With the blank option dropped, one option is left and the poll is refused.\n\t\tif revive(func() { CreatePoll(cross(cur), \"q\", \"x,\"+s) }) == nil {\n\t\t\tt.Errorf(\"CreatePoll kept option %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif r := revive(func() { CreatePoll(cross(cur), s, \"x,\"+s) }); r != nil {\n\t\t\tt.Errorf(\"CreatePoll refused question and option %q: %v\", s, r)\n\t\t}\n\t}\n\tif nextID != len(zwOK) {\n\t\tt.Errorf(\"%d poll(s) created, want %d\", nextID, len(zwOK))\n\t}\n}\n"}]},"send":"","max_deposit":"8000000ugnot"}],"fee":{"gas_wanted":"60435400","gas_fee":"181306ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"irHZ5WaBsfNP+VKYG7WTUn5GM0tg0khOQnTQz6QLZ9MjMgk+HbZ9mbwooCoULGizPDZ3njjE91qx+lx7EuJ02g=="}],"memo":""},"metadata":{"timestamp":"1791963472"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"faucet","path":"gno.land/r/moul/faucet/v1","files":[{"name":"README.md","body":"# GNOT faucet\n\nA two-step, on-the-record way to get a small amount of GNOT to someone who has\nnone: anyone files a request on their behalf, an approver releases it, and both\nhalves stay on the page with a reason attached.\n\nIt exists because the accounts that most need a first coin are exactly the ones\nthat cannot ask for it. An empty account cannot pay the gas to call anything,\nso `Request` takes the recipient as an argument and the filer pays for the ask.\n\nThis is not the grant board. The grant board weighs work against milestones and\nproofs; this hands over pocket change so somebody can try the chain at all.\n\n## The float\n\nThe faucet spends only what has been sent to its own package address, never the\napprover's balance. Top it up with a plain bank send to that address, or with\n`Fund` if you want the donation on the record. `Withdraw` takes it back, to the\nowner and nowhere else.\n\n## `v0` is on chain, frozen, and not this code\n\n`gno.land/r/moul/faucet/v0` was published to mainnet at block 245194, two\nminutes before the commit that added `private = true`. `private` is read off the\nsubmitted package at deploy time, so the chain never saw the flag, and a public\npath cannot later be redeployed as a private one or at all. `v0` is therefore\nfrozen forever, carrying an unbounded `Render` whose page and query gas grow\nwith every request.\n\nThat is what this `v1` exists to replace. Its float lives at a different\naddress, its float was moved by hand, and `v0`'s page still answers with an\nempty board. **If you found `v0` first, this is the live one.**\n\nThe lesson is cheap to state and was not cheap to learn: **publish from the\ncommit you mean to publish**, because for a public realm the deploy is the last\nmoment anything about it can change.\n\n## It is a private realm\n\n`gnomod.toml` declares `private = true`, so the creator can redeploy this path\nwith corrected code rather than abandon it for a `v2`. On a realm holding other\npeople's rent money that is worth having, and `v0` is the demonstration of what\nits absence costs.\n\nWhat a redeploy costs is exact, and measured rather than assumed:\n\n| across a redeploy | |\n|---|---|\n| the code | replaced |\n| the float | **kept** — coins live at the address, which is bank state |\n| requests, approvers, counters | **wiped** — every initializer runs again |\n| storage deposit | accumulates; the old objects are not evicted, so nothing refunds them |\n\nSo a bug fix here is cheap in money and expensive in history. That is the right\nway round for a faucet and the wrong way round for anything whose ledger people\nrely on, which is why this is a per-realm decision and not a repo-wide default.\n\nPrivate is **one-way and set at the first deploy**: a public path can never\nbecome private, nor the reverse. And no other realm may import this one or hold\na reference to its objects. Nothing else here does, and reading it from outside\nis unaffected: `vm/qrender` and `vm/qeval` both work normally on a private\nrealm.\n\n## The two calls, and why they travel together\n\n| call | who | what it does |\n|---|---|---|\n| `Request(to, amount, reason)` | anyone | files an ask, returns its id, moves no money |\n| `Approve(id, to, amount)` | an approver | pays it out of the float |\n| `Deny(id, why)` | an approver | closes it unpaid, with the reason on the page |\n| `Fund()` | anyone, payable | credits the float and emits an event |\n| `Withdraw(amount)` | the owner | returns float to the owner |\n| `AddApprover` / `RemoveApprover` / `SetMaxPerRequest` | the owner | the knobs |\n\nA tm2 transaction carries a list of messages, runs them in order, and stops at\nthe first failure; a failed transaction writes none of their state, only the\nfee and the sequence survive. So `Request` and `Approve` sent as two messages of\none transaction either both happen or neither does, and the common case is a\nsingle signature.\n\n### The id the second message cannot know\n\n`Approve` names a request by id, and message 2 of a transaction cannot read what\nmessage 1 returned. The caller reads `NextID` before signing and writes that\nnumber into the approval, which is a race: another request landing in between\nshifts the id, and the approval would pay a stranger.\n\nThat is why `Approve` also takes the recipient and the amount it believes it is\napproving, and aborts when the stored request disagrees. The race then costs a\nfailed transaction instead of the wrong person's money.\n\n## Calls\n\n```sh\n# Ask, on someone else's behalf. Amount is in ugnot.\ngnokey maketx call -pkgpath \"gno.land/r/moul/faucet/v1\" -func Request \\\n  -args \"g1...\" -args 100000000 -args \"no gas, wants to try the chain\" \\\n  -gas-fee 30000ugnot -gas-wanted 3000000 -broadcast -chainid gnoland-1 moul\n\n# What id the next request will get, so an approval can be signed alongside it.\ngnokey query vm/qeval -data 'gno.land/r/moul/faucet/v1.NextID()'\n\n# What the float holds.\ngnokey query vm/qeval -data 'gno.land/r/moul/faucet/v1.Balance()'\n\n# The page.\ngnokey query vm/qrender -data 'gno.land/r/moul/faucet/v1:'\n```\n\n## Reading it\n\n`Render(\"\")` is the board: float, open requests, decided ones, approvers.\n`Render(\"req/\u003cid\u003e\")` is one request, with its reason and, if it was refused, why.\n\nEach table shows at most 20 rows, open oldest first and decided newest first,\nand says how many it is hiding. The cap is not cosmetic: the totals come from\nthe realm's counters, so the walk stops once a table is full. A board that\nrendered every request ever filed would grow its page and its gas cost forever,\nand this path is permanent. Anything hidden is still reachable by id.\n\nEvery caller-supplied string on those pages is escaped before it is rendered.\nA reason is arbitrary text from an arbitrary account and `Render` output is\nmarkdown that gnoweb parses, so an unescaped one can plant a link, an image\nbeacon or page chrome on a page the realm signs for. This path is permanent, so\nthat bug could only ever be fixed at a new path.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/faucet/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/faucet/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/faucet/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/faucet/v1/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"faucet.gno","body":"// Package faucet hands a small amount of GNOT to someone who has none, on the\n// record, in two calls that are meant to travel in one transaction.\n//\n// The chain's own faucet is gated and the people who most need a first coin\n// are exactly the people who cannot ask for one: an empty account cannot pay\n// the gas to call anything. So somebody else files the request on their\n// behalf, an approver releases it, and both halves are on chain with a reason\n// attached.\n//\n// # Why two calls and not one bank send\n//\n// [Request] is permissionless and [Approve] is not. Splitting them puts the\n// ask, its reason and who made it on chain even when the answer is no, and\n// makes every payout name the request it settles. A plain send would leave a\n// transfer with no why, and no way to refuse one in public.\n//\n// They are meant to be sent together. A tm2 transaction carries a LIST of\n// messages, runs them in order and stops at the first failure, and a failed\n// transaction writes none of their state: only the fee and the sequence\n// survive (tm2/pkg/sdk/baseapp.go, runMsgs and WriteCheckpoint). So a request\n// and its approval in one transaction either both happen or neither does.\n//\n// # The id the second message cannot know yet\n//\n// [Approve] names a request by id, and message 2 of a transaction cannot read\n// what message 1 returned. A caller therefore reads [NextID] first and writes\n// that number into the approval, which is a race: another Request landing in\n// between shifts the id under it, and the approval would pay a stranger.\n//\n// That is why [Approve] also takes the recipient and the amount it believes it\n// is approving, and refuses when the stored request disagrees. The race then\n// costs a failed transaction instead of the wrong person's rent.\n//\n// # What bounds the damage\n//\n// The faucet spends only what has been sent to its own address, never the\n// approver's balance, so the float is the ceiling and topping it up is a\n// deliberate act. [MaxPerRequest] caps any single payout under that, and\n// [Withdraw] takes the float back.\n//\n// # It is a private realm, which buys a code fix and costs the ledger\n//\n// gnomod.toml declares private = true, so the creator can redeploy this path\n// with corrected code instead of abandoning it for a v1. That matters for a\n// realm holding other people's rent money.\n//\n// The price is exact and was measured, not assumed: a redeploy re-runs every\n// package initializer, so the float SURVIVES (coins live at the address, which\n// is bank state) and everything on this page DOES NOT. Requests, approvers and\n// counters all return to their init values. Fixing a bug here is therefore\n// cheap in money and expensive in history, which is the right way round for a\n// faucet and the wrong way round for a ledger anyone relies on.\n//\n// Two more consequences worth knowing before copying this: private is one-way\n// and set at first deploy (a public path can never become private, nor the\n// reverse), and no other realm may import this one or hold a reference to its\n// objects.\npackage faucet\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nconst (\n\t// Denom is the only coin this faucet holds or pays.\n\tDenom = \"ugnot\"\n\t// Path is this realm's package path; its float is held at the address\n\t// derived from it.\n\tPath = \"gno.land/r/moul/faucet/v1\"\n\t// Link is Path as a gnoweb route.\n\tLink = \"/r/moul/faucet/v1\"\n)\n\n// Owner funds the faucet, approves by default, and is the only account that\n// can change who else approves or take the float back.\n//\n// Hardcoded rather than captured from the deployer: inside a plain\n// `func Test(t *testing.T)` the gno test runner reports OriginCaller() as the\n// EMPTY address, so an owner seeded from it is empty in every test and\n// something else on chain. That divergence is where an authorization bug\n// hides, so the address is written down.\nconst Owner = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\n// The three states a request can be in. A request is decided exactly once.\nconst (\n\tStatusPending = \"pending\"\n\tStatusSent    = \"sent\"\n\tStatusDenied  = \"denied\"\n)\n\nconst (\n\t// DefaultMaxPerRequest is the starting cap on a single payout, 200 GNOT.\n\t// It is a guard against a fat finger, not against a hostile approver:\n\t// an approver can raise nothing, but the Owner can.\n\tDefaultMaxPerRequest = 200_000_000\n\n\t// MaxReasonLen bounds the stored reason. It is rendered on a page, so it\n\t// is both a storage cost and a display one.\n\tMaxReasonLen = 280\n\n\t// idWidth pads the avl key. gno's ufmt supports no width flags, so the\n\t// padding is done by hand; unpadded numeric keys sort \"1\",\"10\",\"2\" and\n\t// the request list would lose its order past nine entries.\n\tidWidth = 12\n)\n\n// request is one ask. It is unexported because avl stores `any` and the\n// readable surface of this realm is its views and its page, not a struct\n// another realm would have to depend on.\ntype request struct {\n\tID      int64\n\tTo      address\n\tAmount  int64 // ugnot\n\tReason  string\n\tBy      address // who filed it, which is usually not who receives it\n\tAsked   int64   // chain height at filing\n\tStatus  string\n\tJudge   address // who decided, zero while pending\n\tDecided int64   // chain height of the decision\n\tNote    string  // the denial reason; empty otherwise\n}\n\nvar (\n\trequests  avl.Tree // padded id -\u003e *request\n\tpaid      avl.Tree // recipient address -\u003e int64 ugnot received in total\n\tapprovers avl.Tree // approver address -\u003e bool\n\n\tnextID        int64\n\tmaxPerRequest int64\n\n\ttotalSent   int64\n\tsentCount   int64\n\tdeniedCount int64\n\tpendingN    int64\n)\n\nfunc init() { reset() }\n\n// reset installs an empty faucet. Also called by the tests: realm globals\n// persist for a whole test binary and examples run after every Test, so a\n// pinned Render has to start from a known state.\nfunc reset() {\n\trequests = avl.Tree{}\n\tpaid = avl.Tree{}\n\tapprovers = avl.Tree{}\n\tapprovers.Set(Owner.String(), true)\n\tnextID = 1\n\tmaxPerRequest = DefaultMaxPerRequest\n\ttotalSent, sentCount, deniedCount, pendingN = 0, 0, 0, 0\n}\n\n// Address is where the float sits: this realm's own package address. Fund the\n// faucet by sending ugnot to it, with a plain bank send or with [Fund].\nfunc Address() address { return chain.PackageAddress(Path) }\n\n// Balance is what the faucet can actually pay out right now.\nfunc Balance() int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(Address()).AmountOf(Denom)\n}\n\n// NextID is the id the next [Request] will be given.\n//\n// Read it to build the [Approve] half of a two-message transaction, and pass\n// the recipient and amount to Approve so that a request landing in between\n// fails the transaction instead of being paid by it.\nfunc NextID() int64 { return nextID }\n\n// MaxPerRequest is the current cap on a single payout, in ugnot.\nfunc MaxPerRequest() int64 { return maxPerRequest }\n\n// TotalSent, SentCount, DeniedCount and Pending are the running tallies.\nfunc TotalSent() int64   { return totalSent }\nfunc SentCount() int64   { return sentCount }\nfunc DeniedCount() int64 { return deniedCount }\nfunc Pending() int64     { return pendingN }\n\n// Requests is how many requests have ever been filed.\nfunc Requests() int { return requests.Size() }\n\n// IsApprover reports whether addr may approve or deny.\nfunc IsApprover(addr string) bool { return approvers.Has(addr) }\n\n// ReceivedBy is everything this faucet has ever paid to addr.\nfunc ReceivedBy(addr string) int64 {\n\tif v := paid.Get(addr); v != nil {\n\t\treturn v.(int64)\n\t}\n\treturn 0\n}\n\n// Status is the state of request id: \"pending\", \"sent\", \"denied\", or \"\" when\n// no such request exists.\nfunc Status(id int64) string {\n\tr := find(id)\n\tif r == nil {\n\t\treturn \"\"\n\t}\n\treturn r.Status\n}\n\n// Fund credits the ugnot sent with the call to the float. Coins sent straight\n// to [Address] land there too; they just do not emit an event.\nfunc Fund(cur realm) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\t// OriginSend is what the SIGNER attached, not what reached this realm. A\n\t// realm the user called keeps those coins and could call Fund any number of\n\t// times, booking each as a donation, so only a user call may read it.\n\tprev := cur.Previous()\n\tif !prev.IsUserCall() {\n\t\tpanic(\"faucet: Fund must be called directly by an account, with -send\")\n\t}\n\tfrom := prev.Address()\n\tamount := unsafe.OriginSend().AmountOf(Denom)\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: send some \" + Denom + \" with the call\")\n\t}\n\tchain.Emit(\"Fund\", \"from\", from.String(), \"amount\", strconv.FormatInt(amount, 10))\n}\n\n// Request files an ask for amount ugnot to be paid to `to`, and returns its\n// id. Anyone may file, for anyone, which is the point: the account that needs\n// the coins is the one that cannot pay to ask for them.\n//\n// Filing costs the filer gas and nothing else, and moves no money.\nfunc Request(cur realm, to string, amount int64, reason string) int64 {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tby := cur.Previous().Address()\n\tdst := address(to)\n\tif !dst.IsValid() {\n\t\tpanic(\"faucet: \" + to + \" is not a valid address\")\n\t}\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: amount must be a positive number of \" + Denom)\n\t}\n\tif amount \u003e maxPerRequest {\n\t\tpanic(\"faucet: \" + strconv.FormatInt(amount, 10) + Denom +\n\t\t\t\" is over the per-request cap of \" + strconv.FormatInt(maxPerRequest, 10) + Denom)\n\t}\n\treason = strings.TrimSpace(reason)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(reason)) == \"\" {\n\t\tpanic(\"faucet: say what it is for\")\n\t}\n\tif len(reason) \u003e MaxReasonLen {\n\t\tpanic(\"faucet: reason is longer than \" + strconv.Itoa(MaxReasonLen) + \" bytes\")\n\t}\n\n\tid := nextID\n\tnextID++\n\trequests.Set(key(id), \u0026request{\n\t\tID:     id,\n\t\tTo:     dst,\n\t\tAmount: amount,\n\t\tReason: reason,\n\t\tBy:     by,\n\t\tAsked:  runtime.ChainHeight(),\n\t\tStatus: StatusPending,\n\t})\n\tpendingN++\n\n\tchain.Emit(\"Request\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"to\", dst.String(),\n\t\t\"amount\", strconv.FormatInt(amount, 10),\n\t\t\"by\", by.String(),\n\t)\n\treturn id\n}\n\n// Approve pays request id out of the float. Approvers only.\n//\n// wantTo and wantAmount are not redundant: they are what makes it safe to put\n// Approve in the same transaction as the Request it settles. The id has to be\n// guessed from [NextID] before either message is signed, and this call refuses\n// when the request sitting at that id is not the one the caller described.\nfunc Approve(cur realm, id int64, wantTo string, wantAmount int64) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tjudge := cur.Previous().Address()\n\tmustApprove(judge)\n\n\tr := find(id)\n\tif r == nil {\n\t\tpanic(\"faucet: no request \" + strconv.FormatInt(id, 10))\n\t}\n\tif r.Status != StatusPending {\n\t\tpanic(\"faucet: request \" + strconv.FormatInt(id, 10) + \" is already \" + r.Status)\n\t}\n\tif r.To.String() != wantTo || r.Amount != wantAmount {\n\t\tpanic(\"faucet: request \" + strconv.FormatInt(id, 10) + \" pays \" +\n\t\t\tstrconv.FormatInt(r.Amount, 10) + Denom + \" to \" + r.To.String() +\n\t\t\t\", not \" + strconv.FormatInt(wantAmount, 10) + Denom + \" to \" + wantTo +\n\t\t\t\"; the id moved under you, nothing was paid\")\n\t}\n\tif bal := Balance(); bal \u003c r.Amount {\n\t\tpanic(\"faucet: float is \" + strconv.FormatInt(bal, 10) + Denom +\n\t\t\t\", request needs \" + strconv.FormatInt(r.Amount, 10) + Denom)\n\t}\n\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(\n\t\tcur.Address(), r.To, chain.NewCoins(chain.NewCoin(Denom, r.Amount)))\n\n\tr.Status = StatusSent\n\tr.Judge = judge\n\tr.Decided = runtime.ChainHeight()\n\tpaid.Set(r.To.String(), ReceivedBy(r.To.String())+r.Amount)\n\ttotalSent += r.Amount\n\tsentCount++\n\tpendingN--\n\n\tchain.Emit(\"Approve\",\n\t\t\"id\", strconv.FormatInt(id, 10),\n\t\t\"to\", r.To.String(),\n\t\t\"amount\", strconv.FormatInt(r.Amount, 10),\n\t\t\"by\", judge.String(),\n\t)\n}\n\n// Deny closes a request unpaid, with a reason that goes on the page. The\n// reason is the whole value of denying in public rather than ignoring it.\nfunc Deny(cur realm, id int64, why string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tjudge := cur.Previous().Address()\n\tmustApprove(judge)\n\n\tr := find(id)\n\tif r == nil {\n\t\tpanic(\"faucet: no request \" + strconv.FormatInt(id, 10))\n\t}\n\tif r.Status != StatusPending {\n\t\tpanic(\"faucet: request \" + strconv.FormatInt(id, 10) + \" is already \" + r.Status)\n\t}\n\twhy = strings.TrimSpace(why)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(why)) == \"\" {\n\t\tpanic(\"faucet: say why\")\n\t}\n\tif len(why) \u003e MaxReasonLen {\n\t\tpanic(\"faucet: reason is longer than \" + strconv.Itoa(MaxReasonLen) + \" bytes\")\n\t}\n\n\tr.Status = StatusDenied\n\tr.Judge = judge\n\tr.Decided = runtime.ChainHeight()\n\tr.Note = why\n\tdeniedCount++\n\tpendingN--\n\n\tchain.Emit(\"Deny\", \"id\", strconv.FormatInt(id, 10), \"by\", judge.String())\n}\n\n// AddApprover lets addr approve and deny. Owner only.\nfunc AddApprover(cur realm, addr string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\ta := address(addr)\n\tif !a.IsValid() {\n\t\tpanic(\"faucet: \" + addr + \" is not a valid address\")\n\t}\n\tapprovers.Set(a.String(), true)\n\tchain.Emit(\"AddApprover\", \"addr\", a.String())\n}\n\n// RemoveApprover revokes addr. Owner only, and the Owner cannot be removed:\n// a faucet with no approver is a faucet with a locked float.\nfunc RemoveApprover(cur realm, addr string) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\tif addr == Owner.String() {\n\t\tpanic(\"faucet: the owner is always an approver\")\n\t}\n\t// avl's Remove returns (value, removed), unlike Get which returns one\n\t// value; the comma-ok is required here and forbidden there.\n\tif _, removed := approvers.Remove(addr); !removed {\n\t\tpanic(\"faucet: \" + addr + \" is not an approver\")\n\t}\n\tchain.Emit(\"RemoveApprover\", \"addr\", addr)\n}\n\n// SetMaxPerRequest changes the per-request cap, in ugnot. Owner only.\nfunc SetMaxPerRequest(cur realm, amount int64) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: cap must be positive\")\n\t}\n\tmaxPerRequest = amount\n\tchain.Emit(\"SetMaxPerRequest\", \"amount\", strconv.FormatInt(amount, 10))\n}\n\n// Withdraw returns amount ugnot of the float to the Owner. Owner only.\n//\n// This is what makes funding the faucet reversible, and it is deliberately\n// not payable to an arbitrary address: an approver who wanted to move money\n// somewhere has to file a request for it like everyone else.\nfunc Withdraw(cur realm, amount int64) {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"faucet: spoofed realm\")\n\t}\n\tmustOwn(cur.Previous().Address())\n\tif amount \u003c= 0 {\n\t\tpanic(\"faucet: amount must be positive\")\n\t}\n\tif bal := Balance(); amount \u003e bal {\n\t\tpanic(\"faucet: float is \" + strconv.FormatInt(bal, 10) + Denom)\n\t}\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(\n\t\tcur.Address(), Owner, chain.NewCoins(chain.NewCoin(Denom, amount)))\n\tchain.Emit(\"Withdraw\", \"amount\", strconv.FormatInt(amount, 10))\n}\n\nfunc mustOwn(caller address) {\n\tif caller != Owner {\n\t\tpanic(\"faucet: owner only\")\n\t}\n}\n\nfunc mustApprove(caller address) {\n\tif !approvers.Has(caller.String()) {\n\t\tpanic(\"faucet: \" + caller.String() + \" is not an approver\")\n\t}\n}\n\nfunc find(id int64) *request {\n\tv := requests.Get(key(id))\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*request)\n}\n\n// key pads an id to idWidth digits so the avl tree iterates in filing order.\nfunc key(id int64) string {\n\ts := strconv.FormatInt(id, 10)\n\tfor len(s) \u003c idWidth {\n\t\ts = \"0\" + s\n\t}\n\treturn s\n}\n"},{"name":"faucet_test.gno","body":"package faucet\n\nimport (\n\t\"strconv\"\n\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\tzoe  = address(\"g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz\") // a friend with nothing\n\tkim  = address(\"g1jvh5ukk07dvd57fxefcp5aa29xaydxmxs7myyp\") // a second approver\n\tcarl = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // nobody in particular\n)\n\nfunc balanceOf(a address) int64 {\n\treturn banker.NewReadonlyBanker().GetCoins(a).AmountOf(Denom)\n}\n\n// fund puts ugnot in the float the way a bank send to the realm address does,\n// with no call involved. Approve spends this, so a test that funds more than\n// it pays leaves a balance behind and ExampleRender sees it.\nfunc fund(n int64) {\n\ttesting.IssueCoins(Address(), chain.NewCoins(chain.NewCoin(Denom, n)))\n}\n\nfunc TestFreshFaucetIsEmptyAndOwned(t *testing.T) {\n\treset()\n\tuassert.True(t, Owner.IsValid(), \"the owner is a real address\")\n\tuassert.True(t, Address().IsValid(), \"the float address\")\n\tuassert.True(t, zoe.IsValid())\n\tuassert.True(t, kim.IsValid())\n\tuassert.True(t, carl.IsValid())\n\n\tuassert.Equal(t, 0, Requests(), \"nothing is seeded\")\n\tuassert.Equal(t, int64(1), NextID())\n\tuassert.Equal(t, int64(0), TotalSent())\n\tuassert.Equal(t, int64(DefaultMaxPerRequest), MaxPerRequest())\n\tuassert.True(t, IsApprover(Owner.String()), \"the owner approves by default\")\n\tuassert.False(t, IsApprover(carl.String()))\n\tuassert.Equal(t, \"\", Status(1), \"no such request\")\n}\n\n// The whole point, end to end: carl asks on zoe's behalf, the owner releases\n// it, and zoe (who could never have paid the gas to ask) has coins.\nfunc TestRequestForAFriendThenApprove(cur realm, t *testing.T) {\n\treset()\n\turequire.Equal(t, int64(0), Balance(), \"start from an empty float\")\n\tfund(300_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 100_000_000, \"no gas, needs to try the chain\")\n\tuassert.Equal(t, int64(1), id)\n\tuassert.Equal(t, StatusPending, Status(id))\n\tuassert.Equal(t, int64(1), Pending())\n\tuassert.Equal(t, int64(0), balanceOf(zoe), \"a request moves nothing\")\n\tuassert.Equal(t, int64(2), NextID(), \"and the next id is now readable\")\n\n\t// The filer is not an approver just because they filed.\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tuassert.AbortsContains(t, cur, \"is not an approver\", func() {\n\t\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\n\tuassert.Equal(t, int64(100_000_000), balanceOf(zoe), \"the coins landed\")\n\tuassert.Equal(t, int64(200_000_000), Balance(), \"out of the float, not the approver\")\n\tuassert.Equal(t, StatusSent, Status(id))\n\tuassert.Equal(t, int64(100_000_000), TotalSent())\n\tuassert.Equal(t, int64(1), SentCount())\n\tuassert.Equal(t, int64(0), Pending())\n\tuassert.Equal(t, int64(100_000_000), ReceivedBy(zoe.String()))\n\n\t// A decision happens once.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"already sent\", func() {\n\t\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\t})\n\n\t// Put the float back so ExampleRender starts from zero.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n\tuassert.Equal(t, int64(0), Balance())\n}\n\n// The guard that makes it safe to sign Request and Approve in the same\n// transaction before either has run. The approval names an id it had to guess\n// from NextID; if a different request took that id, the amounts and the\n// recipient no longer agree and nothing is paid.\nfunc TestApproveRefusesWhenTheIDMovedUnderYou(cur realm, t *testing.T) {\n\treset()\n\tfund(500_000_000)\n\n\t// What the caller read: the next id will be 1.\n\turequire.Equal(t, int64(1), NextID())\n\n\t// What actually landed at id 1: somebody else's ask, first.\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tRequest(cross(cur), kim.String(), 50_000_000, \"me first\")\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tRequest(cross(cur), zoe.String(), 100_000_000, \"for zoe\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"the id moved under you, nothing was paid\", func() {\n\t\tApprove(cross(cur), 1, zoe.String(), 100_000_000)\n\t})\n\tuassert.Equal(t, int64(0), balanceOf(zoe), \"nobody was paid\")\n\tuassert.Equal(t, StatusPending, Status(1), \"and nothing was decided\")\n\n\t// The same guard catches a wrong amount at the right id.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"the id moved under you, nothing was paid\", func() {\n\t\tApprove(cross(cur), 2, zoe.String(), 999_000_000)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tApprove(cross(cur), 2, zoe.String(), 100_000_000)\n\tuassert.Equal(t, int64(100_000_000), balanceOf(zoe))\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tDeny(cross(cur), 1, \"already funded elsewhere\")\n\tuassert.Equal(t, StatusDenied, Status(1))\n\tuassert.Equal(t, int64(1), DeniedCount())\n\tuassert.Equal(t, int64(0), Pending())\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\nfunc TestRequestRefusesBadInput(cur realm, t *testing.T) {\n\treset()\n\ttests := []struct {\n\t\tname   string\n\t\tto     string\n\t\tamount int64\n\t\treason string\n\t\twant   string\n\t}{\n\t\t{\"not an address\", \"nope\", 1_000_000, \"hi\", \"is not a valid address\"},\n\t\t{\"zero\", zoe.String(), 0, \"hi\", \"must be a positive number\"},\n\t\t{\"negative\", zoe.String(), -1, \"hi\", \"must be a positive number\"},\n\t\t{\"over the cap\", zoe.String(), DefaultMaxPerRequest + 1, \"hi\", \"is over the per-request cap\"},\n\t\t{\"no reason\", zoe.String(), 1_000_000, \"   \", \"say what it is for\"},\n\t}\n\tfor _, tt := range tests {\n\t\ttesting.SetRealm(testing.NewUserRealm(carl))\n\t\tuassert.AbortsContains(t, cur, tt.want, func() {\n\t\t\tRequest(cross(cur), tt.to, tt.amount, tt.reason)\n\t\t}, tt.name)\n\t}\n\tuassert.Equal(t, 0, Requests(), \"none of them were filed\")\n\tuassert.Equal(t, int64(1), NextID(), \"and the id did not move\")\n}\n\nfunc TestApproveRefusesWhatTheFloatCannotCover(cur realm, t *testing.T) {\n\treset()\n\tfund(10_000_000)\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 100_000_000, \"more than is there\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"float is 10000000ugnot\", func() {\n\t\tApprove(cross(cur), id, zoe.String(), 100_000_000)\n\t})\n\tuassert.Equal(t, StatusPending, Status(id), \"still open, the money simply is not there\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\nfunc TestOnlyTheOwnerChangesWhoApproves(cur realm, t *testing.T) {\n\treset()\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tAddApprover(cross(cur), carl.String())\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tAddApprover(cross(cur), kim.String())\n\tuassert.True(t, IsApprover(kim.String()))\n\n\t// A second approver can decide, but cannot widen the roster.\n\tfund(200_000_000)\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 50_000_000, \"kim vouches\")\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tApprove(cross(cur), id, zoe.String(), 50_000_000)\n\tuassert.Equal(t, StatusSent, Status(id))\n\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tAddApprover(cross(cur), carl.String())\n\t})\n\n\t// The owner is the one approver that cannot be removed: a faucet with no\n\t// approver is a faucet with a locked float.\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"the owner is always an approver\", func() {\n\t\tRemoveApprover(cross(cur), Owner.String())\n\t})\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tRemoveApprover(cross(cur), kim.String())\n\tuassert.False(t, IsApprover(kim.String()))\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\nfunc TestFundAndWithdrawAreOwnerReversible(cur realm, t *testing.T) {\n\treset()\n\tfund(400_000_000)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(Denom, 400_000_000)))\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tFund(cross(cur))\n\tuassert.Equal(t, int64(400_000_000), Balance())\n\n\ttesting.SetRealm(testing.NewUserRealm(kim))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tWithdraw(cross(cur), 1)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tuassert.AbortsContains(t, cur, \"float is 400000000ugnot\", func() {\n\t\tWithdraw(cross(cur), 400_000_001)\n\t})\n\n\tbefore := balanceOf(Owner)\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), 400_000_000)\n\tuassert.Equal(t, int64(0), Balance())\n\tuassert.Equal(t, before+400_000_000, balanceOf(Owner))\n}\n\nfunc TestSetMaxPerRequest(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tuassert.AbortsContains(t, cur, \"owner only\", func() {\n\t\tSetMaxPerRequest(cross(cur), 1)\n\t})\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tSetMaxPerRequest(cross(cur), 1_000_000_000)\n\tuassert.Equal(t, int64(1_000_000_000), MaxPerRequest())\n\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 900_000_000, \"over the old cap, under the new one\")\n\tuassert.Equal(t, StatusPending, Status(id))\n}\n\n// A reason is arbitrary text from an arbitrary account, and this realm's path\n// is permanent, so the escaping has to be right before it ships. Assert the\n// dangerous SEQUENCES are dead on the page, not that some particular escape\n// was chosen.\nfunc TestRenderEscapesTheReason(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 1_000_000,\n\t\t\"[click](https://evil.example) ![b](https://evil.example/p.png) \u003cgno-columns\u003e\")\n\n\tfor _, page := range []string{Render(\"\"), Render(\"req/\" + \"1\")} {\n\t\tuassert.False(t, contains(page, \"](https://evil.example\"), \"no live link\")\n\t\tuassert.False(t, contains(page, \"![b]\"), \"no image beacon\")\n\t\tuassert.False(t, contains(page, \"\u003cgno-columns\u003e\"), \"no gnoweb chrome\")\n\t\tuassert.True(t, contains(page, \"click\"), \"the readable text survives\")\n\t}\n\tuassert.Equal(t, StatusPending, Status(id))\n}\n\nfunc contains(haystack, needle string) bool {\n\tfor i := 0; i+len(needle) \u003c= len(haystack); i++ {\n\t\tif haystack[i:i+len(needle)] == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc TestGnotFormatting(t *testing.T) {\n\ttests := []struct {\n\t\tin   int64\n\t\twant string\n\t}{\n\t\t{0, \"0\"},\n\t\t{1, \"0.000001\"},\n\t\t{1_500_000, \"1.5\"},\n\t\t{100_000_000, \"100\"},\n\t\t{5_000_000_000, \"5000\"},\n\t\t{-2_500_000, \"-2.5\"},\n\t}\n\tfor _, tt := range tests {\n\t\tuassert.Equal(t, tt.want, gnot(tt.in))\n\t}\n}\n\nfunc TestReqPath(t *testing.T) {\n\ttests := []struct {\n\t\tin   string\n\t\tid   int64\n\t\twant bool\n\t}{\n\t\t{\"\", 0, false},\n\t\t{\"req/1\", 1, true},\n\t\t{\"req/42\", 42, true},\n\t\t{\"req/0\", 0, false},\n\t\t{\"req/x\", 0, false},\n\t\t{\"req/\", 0, false},\n\t\t{\"other\", 0, false},\n\t}\n\tfor _, tt := range tests {\n\t\tid, ok := reqPath(tt.in)\n\t\tuassert.Equal(t, tt.want, ok, tt.in)\n\t\tuassert.Equal(t, tt.id, id, tt.in)\n\t}\n}\n\n// A board that renders every request ever filed is a page that grows without\n// bound and a gas cost that grows with it, and this path is permanent. Assert\n// the cap holds and that what it hides is counted rather than lost.\nfunc TestRenderCapsEachTable(cur realm, t *testing.T) {\n\treset()\n\tfund(200_000_000)\n\n\tconst filed = Rows + 5\n\tfor i := 0; i \u003c filed; i++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(carl))\n\t\tRequest(cross(cur), zoe.String(), 1_000_000, \"batch\")\n\t}\n\turequire.Equal(t, int64(filed), Pending())\n\n\tpage := Render(\"\")\n\tuassert.Equal(t, Rows, countRows(page), \"the open table is capped\")\n\tuassert.True(t, contains(page, \"5 more not shown\"), \"and the rest are counted\")\n\n\t// Decide them all: the open table empties and the decided one caps in turn,\n\t// newest first, so the most recent decision is on the page and the oldest\n\t// is the one hidden.\n\tfor id := int64(1); id \u003c= filed; id++ {\n\t\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\t\tDeny(cross(cur), id, \"batch\")\n\t}\n\tpage = Render(\"\")\n\tuassert.Equal(t, int64(0), Pending())\n\tuassert.Equal(t, Rows, countRows(page), \"the decided table is capped too\")\n\tuassert.True(t, contains(page, \"5 more not shown\"))\n\tuassert.True(t, contains(page, \":req/\"+strconv.FormatInt(int64(filed), 10)+\")\"), \"newest is shown\")\n\tuassert.False(t, contains(page, \":req/1)\"), \"oldest is the one hidden\")\n\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tWithdraw(cross(cur), Balance())\n}\n\n// countRows counts request rows on a page: every one links to :req/.\nfunc countRows(page string) int {\n\tn, needle := 0, \"](/r/moul/faucet/v1:req/\"\n\tfor i := 0; i+len(needle) \u003c= len(page); i++ {\n\t\tif page[i:i+len(needle)] == needle {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// Path is a hand-written const and the module line is in gnomod.toml, so\n// nothing but this test stops them diverging. They must not: Address() derives\n// the float from Path, while the banker in Approve spends from cur.Address(),\n// which is derived by the VM. A divergence would make Balance() read a\n// different account from the one the payout leaves, and the realm would refuse\n// payouts it could afford while reporting a float it does not hold.\nfunc TestPathMatchesTheRealmItIsDeployedAs(cur realm, t *testing.T) {\n\tuassert.Equal(t, cur.Address().String(), Address().String(),\n\t\t\"Path disagrees with the module line in gnomod.toml\")\n}\n\n// A realm cannot emit a Fund event for coins it kept: OriginSend is what the\n// signer attached, not what reached the float.\nfunc TestFundRefusesARealmCaller(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(Denom, 1_000_000)))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/someone/relay\"))\n\tuassert.AbortsContains(t, cur, \"called directly by an account\", func() { Fund(cross(cur)) })\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/faucet/v1\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/faucet\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"render.gno","body":"package faucet\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// Rows is how many requests each table on the board shows. The rest are\n// counted, not rendered: the per-request page is always reachable by id.\nconst Rows = 20\n\n// Render shows the float, the open asks and everything already decided.\n//\n// Two paths: \"\" is the whole board, \"req/\u003cid\u003e\" is one request.\n//\n// Every string on this page that a caller typed goes through sanitize before\n// it is concatenated. A reason is arbitrary text from an arbitrary account and\n// Render output is markdown that gnoweb parses, so an unescaped one can plant\n// a link, an image beacon or gnoweb chrome on a page the realm is signing for.\n// This realm's path is permanent, so that bug could only ever be fixed at a\n// new path.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tif id, ok := reqPath(path); ok {\n\t\treturn renderOne(id)\n\t}\n\treturn renderBoard()\n}\n\nfunc renderBoard() string {\n\tvar b strings.Builder\n\n\tb.WriteString(\"# GNOT faucet\\n\\n\")\n\tb.WriteString(intro)\n\tb.WriteString(\"\\n\\n\")\n\n\tb.WriteString(\"| | |\\n| --- | ---: |\\n\")\n\tb.WriteString(\"| Float available | **\" + gnot(Balance()) + \" GNOT** |\\n\")\n\tb.WriteString(\"| Paid out | \" + gnot(totalSent) + \" GNOT over \" +\n\t\tstrconv.FormatInt(sentCount, 10) + \" request(s) |\\n\")\n\tb.WriteString(\"| Open requests | \" + strconv.FormatInt(pendingN, 10) + \" |\\n\")\n\tb.WriteString(\"| Refused | \" + strconv.FormatInt(deniedCount, 10) + \" |\\n\")\n\tb.WriteString(\"| Cap per request | \" + gnot(maxPerRequest) + \" GNOT |\\n\")\n\tb.WriteString(\"| Float address | `\" + Address().String() + \"` |\\n\\n\")\n\n\tb.WriteString(\"## Open\\n\\n\")\n\tb.WriteString(table(true, pendingN))\n\tb.WriteString(\"\\n## Decided\\n\\n\")\n\tb.WriteString(table(false, sentCount+deniedCount))\n\n\tb.WriteString(\"\\n## Approvers\\n\\n\")\n\tapprovers.Iterate(\"\", \"\", func(k string, _ any) bool {\n\t\tb.WriteString(\"- `\" + k + \"`\\n\")\n\t\treturn false\n\t})\n\n\tb.WriteString(\"\\n\" + howto + \"\\n\")\n\treturn b.String()\n}\n\n// table lists at most Rows requests: the open ones oldest first, because a\n// queue is worked from the front, and the decided ones newest first, because\n// nobody scrolls to the bottom of a ledger.\n//\n// It takes the total from the realm's counters rather than counting rows, so\n// it can STOP iterating once the page is full. A Render that walks every\n// request ever filed is a page that grows without bound and a gas cost that\n// grows with it, and this realm's path is permanent, so that would only ever\n// be fixable at a new path.\nfunc table(open bool, total int64) string {\n\tif total == 0 {\n\t\treturn \"_Nothing here yet._\\n\"\n\t}\n\tvar rows strings.Builder\n\tshown := int64(0)\n\tvisit := func(_ string, v any) bool {\n\t\tr := v.(*request)\n\t\tif (r.Status == StatusPending) != open {\n\t\t\treturn false\n\t\t}\n\t\trows.WriteString(\"| [\" + strconv.FormatInt(r.ID, 10) + \"](\" + Link + \":req/\" +\n\t\t\tstrconv.FormatInt(r.ID, 10) + \") | `\" + r.To.String() + \"` | \" +\n\t\t\tgnot(r.Amount) + \" | \" + sanitize.TableCell(excerpt(r.Reason, 60)) + \" | \" +\n\t\t\tr.Status + \" |\\n\")\n\t\tshown++\n\t\treturn shown \u003e= Rows // a true return stops the walk\n\t}\n\tif open {\n\t\trequests.Iterate(\"\", \"\", visit)\n\t} else {\n\t\trequests.ReverseIterate(\"\", \"\", visit)\n\t}\n\n\tout := \"| # | To | GNOT | Why | State |\\n| ---: | --- | ---: | --- | --- |\\n\" + rows.String()\n\tif rest := total - shown; rest \u003e 0 {\n\t\tout += \"\\n_\" + strconv.FormatInt(rest, 10) + \" more not shown._\\n\"\n\t}\n\treturn out\n}\n\nfunc renderOne(id int64) string {\n\tr := find(id)\n\tif r == nil {\n\t\treturn \"# Request \" + strconv.FormatInt(id, 10) + \"\\n\\n_No such request._\\n\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(\"# Request \" + strconv.FormatInt(r.ID, 10) + \"\\n\\n\")\n\tb.WriteString(\"| | |\\n| --- | --- |\\n\")\n\tb.WriteString(\"| To | `\" + r.To.String() + \"` |\\n\")\n\tb.WriteString(\"| Amount | \" + gnot(r.Amount) + \" GNOT |\\n\")\n\tb.WriteString(\"| Filed by | `\" + r.By.String() + \"` |\\n\")\n\tb.WriteString(\"| Filed at height | \" + strconv.FormatInt(r.Asked, 10) + \" |\\n\")\n\tb.WriteString(\"| State | \" + r.Status + \" |\\n\")\n\tif r.Status != StatusPending {\n\t\tb.WriteString(\"| Decided by | `\" + r.Judge.String() + \"` |\\n\")\n\t\tb.WriteString(\"| Decided at height | \" + strconv.FormatInt(r.Decided, 10) + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n**Why:** \" + sanitize.InlineText(r.Reason) + \"\\n\")\n\tif r.Note != \"\" {\n\t\tb.WriteString(\"\\n**Refused because:** \" + sanitize.InlineText(r.Note) + \"\\n\")\n\t}\n\tb.WriteString(\"\\n[Back to the faucet](\" + Link + \")\\n\")\n\treturn b.String()\n}\n\n// reqPath parses \"req/\u003cid\u003e\".\nfunc reqPath(path string) (int64, bool) {\n\trest, ok := strings.CutPrefix(path, \"req/\")\n\tif !ok {\n\t\treturn 0, false\n\t}\n\tid, err := strconv.ParseInt(rest, 10, 64)\n\tif err != nil || id \u003c= 0 {\n\t\treturn 0, false\n\t}\n\treturn id, true\n}\n\n// excerpt cuts to width RUNES, never bytes: slicing a multi-byte character in\n// half puts invalid UTF-8 on the page, and one emoji in a reason is enough.\n// It cuts before escaping, because escaping inserts backslashes and cutting an\n// already-escaped string can strand a lone one that escapes the chrome after\n// it.\nfunc excerpt(s string, width int) string {\n\tr := []rune(s)\n\tif len(r) \u003c= width+1 {\n\t\treturn s\n\t}\n\treturn string(r[:width]) + \"…\"\n}\n\n// gnot renders ugnot as GNOT with the trailing zeros of the fraction trimmed,\n// so 100000000 reads as 100 and 1500000 as 1.5.\nfunc gnot(ugnot int64) string {\n\tneg := \"\"\n\tif ugnot \u003c 0 {\n\t\tneg, ugnot = \"-\", -ugnot\n\t}\n\twhole := strconv.FormatInt(ugnot/1_000_000, 10)\n\tfrac := strconv.FormatInt(ugnot%1_000_000, 10)\n\tif frac == \"0\" {\n\t\treturn neg + whole\n\t}\n\tfor len(frac) \u003c 6 {\n\t\tfrac = \"0\" + frac\n\t}\n\treturn neg + whole + \".\" + strings.TrimRight(frac, \"0\")\n}\n\nconst (\n\tintro = \"Somebody you trust has no GNOT and cannot use the public faucet. File a\\n\" +\n\t\t\"request on their behalf, an approver releases it, and both halves stay on\\n\" +\n\t\t\"this page with a reason attached. The faucet only ever spends what has been\\n\" +\n\t\t\"sent to its own address.\"\n\n\thowto = \"## How\\n\\n\" +\n\t\t\"`Request(to, amount, reason)` is open to anyone and moves no money.\\n\" +\n\t\t\"`Approve(id, to, amount)` pays it, and only an approver can call it.\\n\\n\" +\n\t\t\"Send both in **one transaction**: a tm2 transaction stops at the first\\n\" +\n\t\t\"message that fails and writes none of their state, so the ask and its\\n\" +\n\t\t\"answer land together or not at all. Read `NextID` to address the approval,\\n\" +\n\t\t\"and pass the recipient and the amount into it as well: if another request\\n\" +\n\t\t\"takes that id first, the mismatch fails the transaction instead of paying\\n\" +\n\t\t\"the wrong account.\"\n)\n"},{"name":"render_example_test.gno","body":"package faucet\n\n// ExampleRender pins the faucet as it ships: no requests, an empty float, one\n// approver. That IS the deployed state, since nothing is seeded here.\n//\n// reset() first: realm globals persist for the whole test binary and examples\n// run after every Test. The float is NOT a realm global and reset() cannot\n// clear it, so every test above withdraws what it funded; a test that leaves\n// coins behind shows up as a diff here, which is the point.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # GNOT faucet\n\t//\n\t// Somebody you trust has no GNOT and cannot use the public faucet. File a\n\t// request on their behalf, an approver releases it, and both halves stay on\n\t// this page with a reason attached. The faucet only ever spends what has been\n\t// sent to its own address.\n\t//\n\t// | | |\n\t// | --- | ---: |\n\t// | Float available | **0 GNOT** |\n\t// | Paid out | 0 GNOT over 0 request(s) |\n\t// | Open requests | 0 |\n\t// | Refused | 0 |\n\t// | Cap per request | 200 GNOT |\n\t// | Float address | `g162rfssecz2jq770f7as3qunm4wvh4pmna0guxv` |\n\t//\n\t// ## Open\n\t//\n\t// _Nothing here yet._\n\t//\n\t// ## Decided\n\t//\n\t// _Nothing here yet._\n\t//\n\t// ## Approvers\n\t//\n\t// - `g1manfred47kzduec920z88wfr64ylksmdcedlf5`\n\t//\n\t// ## How\n\t//\n\t// `Request(to, amount, reason)` is open to anyone and moves no money.\n\t// `Approve(id, to, amount)` pays it, and only an approver can call it.\n\t//\n\t// Send both in **one transaction**: a tm2 transaction stops at the first\n\t// message that fails and writes none of their state, so the ask and its\n\t// answer land together or not at all. Read `NextID` to address the approval,\n\t// and pass the recipient and the amount into it as well: if another request\n\t// takes that id first, the mismatch fails the transaction instead of paying\n\t// the wrong account.\n}\n\n// ExampleRenderUnknownRequest pins the per-request path on the one state it\n// can reach deterministically from a reset faucet. A request page proper needs\n// a crossing call to exist, and an Example func cannot take `cur realm`, so\n// the filled-in version is asserted in TestRenderEscapesTheReason instead.\nfunc ExampleRenderUnknownRequest() {\n\treset()\n\tprint(Render(\"req/7\"))\n\t// Output:\n\t// # Request 7\n\t//\n\t// _No such request._\n}\n"},{"name":"zz_zerowidth_test.gno","body":"package faucet\n\nimport (\n\t\"testing\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc TestZeroWidthReasonIsRefused(cur realm, t *testing.T) {\n\treset()\n\tdefer reset()\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tfor _, s := range zwBlank {\n\t\tif revive(func() { Request(cross(cur), zoe.String(), 1_000_000, s) }) == nil {\n\t\t\tt.Errorf(\"Request accepted reason %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif r := revive(func() { Request(cross(cur), zoe.String(), 1_000_000, s) }); r != nil {\n\t\t\tt.Errorf(\"Request refused reason %q: %v\", s, r)\n\t\t}\n\t}\n\tif Requests() != len(zwOK) {\n\t\tt.Errorf(\"Requests = %d, want %d\", Requests(), len(zwOK))\n\t}\n}\n\nfunc TestZeroWidthDenyReasonIsRefused(cur realm, t *testing.T) {\n\treset()\n\tdefer reset()\n\ttesting.SetRealm(testing.NewUserRealm(carl))\n\tid := Request(cross(cur), zoe.String(), 1_000_000, \"to try the chain\")\n\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\tfor _, s := range zwBlank {\n\t\tif revive(func() { Deny(cross(cur), id, s) }) == nil {\n\t\t\tt.Errorf(\"Deny accepted reason %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tif Status(id) != StatusPending {\n\t\tt.Fatalf(\"Status = %q after blank denials, want %q\", Status(id), StatusPending)\n\t}\n\tfor _, s := range zwOK {\n\t\ttesting.SetRealm(testing.NewUserRealm(carl))\n\t\tid := Request(cross(cur), zoe.String(), 1_000_000, \"to try the chain\")\n\t\ttesting.SetRealm(testing.NewUserRealm(Owner))\n\t\tif r := revive(func() { Deny(cross(cur), id, s) }); r != nil {\n\t\t\tt.Errorf(\"Deny refused reason %q: %v\", s, r)\n\t\t}\n\t\tif Status(id) != StatusDenied {\n\t\t\tt.Errorf(\"Status = %q, want %q\", Status(id), StatusDenied)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"20000000ugnot"}],"fee":{"gas_wanted":"135991400","gas_fee":"407974ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"UVz0RcooZir0Ws0I0oBQ7H3eFJ/hEGiYsXotF6qsK6F3CqYAPor6wRfkgU3BanVBI0zkRCS1VcbSKOnfq12CWw=="}],"memo":""},"metadata":{"timestamp":"1791963473"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"blog","path":"gno.land/r/moul/blog","files":[{"name":"README.md","body":"# `gno.land/r/moul/blog`\n\nmoul's personal blog, on chain. One author, posts stored as data rather than\ncode, and a URL that is meant to survive being pasted into someone else's chat.\n\n```\ngno.land/r/moul/blog             the index, newest first\ngno.land/r/moul/blog:\u003cslug\u003e      one post\ngno.land/r/moul/blog:t/\u003ctag\u003e     every post carrying a tag\n```\n\n## Why private, and why no `/vN`\n\nThese are the same decision seen from two sides.\n\nA post URL leaves this repository the moment it is published: it goes into\nchats, into other people's articles, into a link someone bookmarked. None of\nthose can be rewritten. A `/v1` would break all of them at once, which is the\none failure a blog cannot absorb, so the module line carries no version.\n\nWhat normally pays for a version is the ability to change the code. Here that\ncomes from `private = true` instead: a private package may be re-added at the\nsame path by the address in `[addpkg].creator`\n(`gno.land/pkg/sdk/vm/keeper.go`, `checkRedeployPermission`), and nothing else\nmay import it. So the code can be replaced without the path moving.\n\nThe bill for that arrives as a wipe. A redeploy re-runs `init()` and resets\nevery package-level variable, so **every post is erased**. That is survivable\nonly because the markdown is kept off chain and `tools/gnoblog -all` pushes all\nof it back in one transaction. The chain holds the published copy; it is not\nthe only copy.\n\n`tools/gnocontracts` records the exemption from the repository's \"every path\nends in `/vN`\" rule, next to `r/moul/home`'s, with the reason.\n\n## The API\n\nWrites are restricted to `g1manfred47kzduec920z88wfr64ylksmdcedlf5`.\n\n| function | what it does |\n| --- | --- |\n| `Set(cur, slug, title, date, tags, body)` | create or replace a post, the ordinary publish |\n| `Append(cur, slug, body)` | append, for a body too large for one transaction |\n| `Delete(cur, slug)` | remove a post |\n| `SetIntro(cur, body)` | the markdown above the index; `\"\"` restores the default |\n| `Get(slug)` | one post's raw markdown |\n| `Count()` · `Revision()` | how many posts, and how many writes have been accepted |\n| `Manifest()` | `slug⇥rev⇥date⇥len⇥sha256` per post, the diff surface |\n\nA slug is 1 to 64 bytes of `[a-z0-9._-]`. No `':'` and no `'/'`, so a slug can\nnever break out of its own render path. `intro` is refused, because `intro.md`\nnames the index header on the local side and a post there would have nowhere to\nlive.\n\nA date is exactly `YYYY-MM-DD`, and that is load-bearing rather than cosmetic:\nposts are kept in a second avl tree keyed by `\"\u003cdate\u003e/\u003cslug\u003e\"` and walked in\nreverse, so lexical order has to be chronological order. gno has no\n`sort.Slice`; this is what replaces it.\n\n## `Manifest()` is the whole sync protocol\n\nOne `vm/qeval` returns a line per post carrying a sha256 over the title, date,\ntags and body **together**. So `gnoblog status` can say exactly which local\nfile needs a transaction without downloading a single body, and changing any\none of the four fields changes the hash.\n\nBoth halves build that hashed record the same way, and neither can check the\nother at run time: the realm's test asserts the record, and the tool's test\npins its digest as a literal. If one side ever drifts, the tool reports every\npost as up to date while the chain holds the old text.\n\n## Escaping\n\nThe body renders **verbatim**. It is markdown written by the one address that\ncan call `Set`, and escaping it would turn every heading and link in a post\ninto literal text.\n\nTitles, tags and index excerpts go through `p/moul/kit/ui` anyway. Not because\nthe author is untrusted, but because a title with a `]` in it would otherwise\nbreak the link it sits inside, and that is a rendering bug with no attacker in\nit at all.\n\n## Publishing a post\n\nThe markdown lives outside this repository; `tools/gnoblog` never defaults to a\npath to it.\n\n```sh\ngo -C tools tool gnoblog -content DIR status   # what differs from the chain\ngo -C tools tool gnoblog -content DIR tx       # the transaction that fixes it\n```\n\n`tx` builds one unsigned transaction document and hands it to `gnokey`, which\nsigns and broadcasts it. Several posts go in one document, so publishing three\nis one passphrase prompt and one atomic broadcast. After a redeploy, `tx -all`.\n\n`status` is the review step. `tx -print` writes the commands out and runs\nnothing, for the case where the signing happens somewhere else.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/blog?network=mainnet)](https://gnoscope.com/realm/r/moul/blog)\n\n**Dependency graph:**\n\n![gno.land/r/moul/blog dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/blog/deps.png)\n\n\u003e ⚠️ **Disclaimer:** provided as-is, without warranty; not security-audited. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"blog.gno","body":"// Package blog is moul's personal blog on gno.land: one realm, one author,\n// posts that live in chain storage rather than in the code.\n//\n// # The shape\n//\n// A post is markdown plus four fields (slug, title, date, tags). Writing one\n// is a single Set transaction, so publishing never redeploys the realm and\n// fixing a typo costs one small call instead of a new package path.\n//\n// The reader-facing paths are deliberately short, because they get pasted into\n// other people's chats:\n//\n//\tgno.land/r/moul/blog             the index, newest first\n//\tgno.land/r/moul/blog:\u003cslug\u003e      one post\n//\tgno.land/r/moul/blog:t/\u003ctag\u003e     every post carrying a tag\n//\n// # Ordering without sort\n//\n// gno has no sort.Slice, and avl.Tree iterates by key. So posts live in two\n// trees: `posts` keyed by slug, for the O(log n) lookup a permalink needs, and\n// `order` keyed by \"\u003cdate\u003e/\u003cslug\u003e\", walked in reverse for newest-first. The\n// date is YYYY-MM-DD precisely so that lexical order is chronological order,\n// which is what makes the second tree free.\n//\n// # Versioning\n//\n// gnomod.toml declares private = true, which lets the creator re-add the\n// package at this exact path. That redeploy re-runs init() and WIPES every\n// post here, so the markdown kept off chain is the source of truth and\n// tools/gnoblog pushes it back. Trading that risk for a stable URL is the\n// whole design: a /v1 would break every link already shared, a redeploy does\n// not, and Manifest() makes restoring the content one diff.\npackage blog\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// author is the only address allowed to write. Deliberately a constant rather\n// than transferable ownership: this is one person's blog, and the same address\n// is the only one the chain lets redeploy the realm anyway, so a second owner\n// could publish posts it could never restore after a wipe.\nconst author = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\n// realmPath is this realm's own path, used to build the links Render emits.\nconst realmPath = \"gno.land/r/moul/blog\"\n\n// maxSlugLen bounds a slug so a permalink stays typable and a key stays cheap.\nconst maxSlugLen = 64\n\n// excerptLen is how much of a post body the index shows.\nconst excerptLen = 200\n\n// introKey is the manifest key of the index header. It starts with '!', which\n// validSlug rejects, so it can never collide with a post.\nconst introKey = \"!intro\"\n\n// introSlug is refused as a post slug. Not because this realm needs it: the\n// intro lives in its own variable. It is refused so that the local half stays\n// representable, where a post is \u003cslug\u003e.md and the header is intro.md. A post\n// published at this slug by a hand-written transaction would have no file it\n// could live in, and tools/gnoblog would report it as an extra forever.\nconst introSlug = \"intro\"\n\ntype post struct {\n\tslug    string\n\ttitle   string\n\tdate    string // YYYY-MM-DD, the sort key\n\ttags    string // comma-separated, normalized by splitTags\n\tbody    string // raw markdown, authored by `author`, rendered unescaped\n\trev     int    // rev at the time of the last write to this post\n\tupdated int64  // block height of the last write\n}\n\nvar (\n\tposts = avl.NewTree() // slug             -\u003e *post\n\torder = avl.NewTree() // \"\u003cdate\u003e/\u003cslug\u003e\"  -\u003e *post\n\tintro string          // markdown shown above the index\n\trev   int             // total writes accepted, bumped by every mutation\n)\n\nfunc assertAuthor(cur realm) {\n\tif cur.Previous().Address() != author {\n\t\tpanic(\"restricted to the author\")\n\t}\n}\n\n// validSlug reports whether slug is a legal permalink: 1..maxSlugLen bytes of\n// [a-z0-9._-]. The character set excludes ':' and '/' so a slug can never\n// break out of its own render path, and excludes uppercase so a post has\n// exactly one URL.\nfunc validSlug(slug string) bool {\n\tif len(slug) == 0 || len(slug) \u003e maxSlugLen {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c len(slug); i++ {\n\t\tc := slug[i]\n\t\tswitch {\n\t\tcase c \u003e= 'a' \u0026\u0026 c \u003c= 'z', c \u003e= '0' \u0026\u0026 c \u003c= '9':\n\t\tcase c == '-', c == '_', c == '.':\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// validDate reports whether date is exactly YYYY-MM-DD. The format is not\n// cosmetic: `order` relies on lexical order being chronological order, so a\n// date of any other shape would silently sort into the wrong place.\nfunc validDate(date string) bool {\n\tif len(date) != 10 {\n\t\treturn false\n\t}\n\tfor i := 0; i \u003c 10; i++ {\n\t\tc := date[i]\n\t\tif i == 4 || i == 7 {\n\t\t\tif c != '-' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif c \u003c '0' || c \u003e '9' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// orderKey is the key a post takes in `order`. The slug is appended so two\n// posts published on the same day do not collide.\nfunc orderKey(date, slug string) string { return date + \"/\" + slug }\n\n// splitTags normalizes a comma-separated tag list: trimmed, lowercased,\n// deduplicated, empties dropped. It returns the canonical string that gets\n// stored, so the hash a client computes locally matches the one on chain.\nfunc splitTags(tags string) []string {\n\tvar out []string\n\tfor _, t := range strings.Split(tags, \",\") {\n\t\tt = strings.ToLower(strings.TrimSpace(t))\n\t\tif t == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdup := false\n\t\tfor _, seen := range out {\n\t\t\tif seen == t {\n\t\t\t\tdup = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !dup {\n\t\t\tout = append(out, t)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc joinTags(tags []string) string { return strings.Join(tags, \",\") }\n\n// record is the canonical serialization a post hashes to. Both this realm and\n// tools/gnoblog build it the same way, which is what lets one Manifest() read\n// decide whether a local file needs a transaction at all.\nfunc record(title, date, tags, body string) string {\n\treturn title + \"\\n\" + date + \"\\n\" + tags + \"\\n\" + body\n}\n\nfunc hashOf(s string) string {\n\tsum := sha256.Sum256([]byte(s))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// Set creates or replaces the post at slug. This is the ordinary publish: one\n// post, one transaction, idempotent.\n//\n// Changing the date moves the post in the index, so the old order entry is\n// removed before the new one is written.\nfunc Set(cur realm, slug, title, date, tags, body string) {\n\tassertAuthor(cur)\n\tif !validSlug(slug) {\n\t\tpanic(\"invalid slug: want 1-\" + strconv.Itoa(maxSlugLen) + \" bytes of [a-z0-9._-], got \" + strconv.Quote(slug))\n\t}\n\tif slug == introSlug {\n\t\tpanic(\"reserved slug: \" + introSlug + \" names the index header, set it with SetIntro\")\n\t}\n\tif !validDate(date) {\n\t\tpanic(\"invalid date: want YYYY-MM-DD, got \" + strconv.Quote(date))\n\t}\n\ttitle = strings.TrimSpace(title)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(title)) == \"\" {\n\t\tpanic(\"a post needs a title\")\n\t}\n\n\tif v := posts.Get(slug); v != nil {\n\t\torder.Remove(orderKey(v.(*post).date, slug))\n\t}\n\n\trev++\n\tp := \u0026post{\n\t\tslug:    slug,\n\t\ttitle:   title,\n\t\tdate:    date,\n\t\ttags:    joinTags(splitTags(tags)),\n\t\tbody:    body,\n\t\trev:     rev,\n\t\tupdated: runtime.ChainHeight(),\n\t}\n\tposts.Set(slug, p)\n\torder.Set(orderKey(date, slug), p)\n}\n\n// Append adds to the end of a post's body. It exists for a body too large to\n// fit in one transaction: Set the first chunk, Append the rest. An ordinary\n// edit uses Set, which is idempotent and therefore safe to retry.\nfunc Append(cur realm, slug, body string) {\n\tassertAuthor(cur)\n\tv := posts.Get(slug)\n\tif v == nil {\n\t\tpanic(\"no such post: \" + strconv.Quote(slug))\n\t}\n\tp := v.(*post)\n\trev++\n\tp.body += body\n\tp.rev = rev\n\tp.updated = runtime.ChainHeight()\n}\n\n// Delete removes a post and its index entry.\nfunc Delete(cur realm, slug string) {\n\tassertAuthor(cur)\n\tv, removed := posts.Remove(slug)\n\tif !removed {\n\t\tpanic(\"no such post: \" + strconv.Quote(slug))\n\t}\n\torder.Remove(orderKey(v.(*post).date, slug))\n\trev++\n}\n\n// SetIntro replaces the markdown shown above the index. Passing \"\" restores\n// the built-in header.\nfunc SetIntro(cur realm, body string) {\n\tassertAuthor(cur)\n\trev++\n\tintro = body\n}\n\n// Get returns a post's raw markdown body, or \"\" when there is no such post.\nfunc Get(slug string) string {\n\tv := posts.Get(slug)\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\treturn v.(*post).body\n}\n\n// Count returns the number of published posts.\nfunc Count() int { return posts.Size() }\n\n// Revision returns the total number of writes this realm has accepted. It\n// changes on every mutation, so a client can cheaply tell \"nothing moved\".\nfunc Revision() int { return rev }\n\n// Manifest returns one tab-separated line per post, plus one for the intro:\n//\n//\t\u003cslug\u003e\\t\u003crev\u003e\\t\u003cdate\u003e\\t\u003clen of body\u003e\\t\u003csha256 of the canonical record\u003e\n//\n// It is the diff surface tools/gnoblog reads with a single vm/qeval: the hash\n// covers the title, date, tags and body together, so one read says exactly\n// which local file needs a transaction without downloading a single body.\n//\n// The intro is reported under the key \"!intro\" with an empty date. '!' is not\n// a legal slug character, so that row can never be confused with a post.\nfunc Manifest() string {\n\tvar b strings.Builder\n\n\tb.WriteString(introKey)\n\tb.WriteString(\"\\t0\\t\\t\")\n\tb.WriteString(strconv.Itoa(len(intro)))\n\tb.WriteString(\"\\t\")\n\tb.WriteString(hashOf(intro))\n\tb.WriteString(\"\\n\")\n\n\tposts.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tp := value.(*post)\n\t\tb.WriteString(p.slug)\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.Itoa(p.rev))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(p.date)\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(strconv.Itoa(len(p.body)))\n\t\tb.WriteString(\"\\t\")\n\t\tb.WriteString(hashOf(record(p.title, p.date, p.tags, p.body)))\n\t\tb.WriteString(\"\\n\")\n\t\treturn false\n\t})\n\treturn b.String()\n}\n"},{"name":"blog_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// reset empties every package-level variable. ExampleRender runs after every\n// Test in this package and would otherwise render whatever they left behind,\n// so both the tests and the example start from here.\nfunc reset() {\n\tposts = avl.NewTree()\n\torder = avl.NewTree()\n\tintro = \"\"\n\trev = 0\n}\n\n// seed writes a post without going through Set, so a caller needs no\n// `cur realm` and the example stays a plain function.\nfunc seed(slug, title, date, tags, body string) {\n\trev++\n\tp := \u0026post{\n\t\tslug:  slug,\n\t\ttitle: title,\n\t\tdate:  date,\n\t\ttags:  joinTags(splitTags(tags)),\n\t\tbody:  body,\n\t\trev:   rev,\n\t}\n\tposts.Set(slug, p)\n\torder.Set(orderKey(date, slug), p)\n}\n\nfunc TestValidSlug(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tslug string\n\t\twant bool\n\t}{\n\t\t{\"mygnoscan\", true},\n\t\t{\"a\", true},\n\t\t{\"hello-world.2\", true},\n\t\t{\"under_score\", true},\n\t\t{\"\", false},\n\t\t{\"Caps\", false},\n\t\t{\"has space\", false},\n\t\t{\"colon:here\", false},\n\t\t{\"slash/here\", false},\n\t\t{\"!intro\", false},\n\t\t{strings.Repeat(\"a\", maxSlugLen), true},\n\t\t{strings.Repeat(\"a\", maxSlugLen+1), false},\n\t} {\n\t\tuassert.Equal(t, tc.want, validSlug(tc.slug), \"validSlug(\"+tc.slug+\")\")\n\t}\n}\n\nfunc TestValidDate(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdate string\n\t\twant bool\n\t}{\n\t\t{\"2026-09-23\", true},\n\t\t{\"0000-00-00\", true}, // shape only: ordering is all this field is for\n\t\t{\"2026-9-23\", false},\n\t\t{\"2026/09/23\", false},\n\t\t{\"2026-09-233\", false},\n\t\t{\"\", false},\n\t} {\n\t\tuassert.Equal(t, tc.want, validDate(tc.date), \"validDate(\"+tc.date+\")\")\n\t}\n}\n\nfunc TestSplitTagsNormalizes(t *testing.T) {\n\tfor _, tc := range []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"gno\", \"gno\"},\n\t\t{\" Gno , TOOLING \", \"gno,tooling\"},\n\t\t{\"gno,gno,gno\", \"gno\"},\n\t\t{\"gno,,tooling\", \"gno,tooling\"},\n\t} {\n\t\tuassert.Equal(t, tc.want, joinTags(splitTags(tc.in)), \"splitTags(\"+tc.in+\")\")\n\t}\n}\n\n// A post published earlier must render below one published later, which is\n// the only thing the second tree exists to guarantee.\nfunc TestIndexIsNewestFirst(t *testing.T) {\n\treset()\n\tseed(\"older\", \"Older\", \"2026-01-01\", \"\", \"First.\")\n\tseed(\"newer\", \"Newer\", \"2026-09-23\", \"\", \"Second.\")\n\n\tout := Render(\"\")\n\tiNew := strings.Index(out, \"Newer\")\n\tiOld := strings.Index(out, \"Older\")\n\tuassert.True(t, iNew \u003e= 0 \u0026\u0026 iOld \u003e= 0, \"both posts render\")\n\tuassert.True(t, iNew \u003c iOld, \"the newer post renders first\")\n}\n\n// Re-dating a post has to move it, not leave a ghost entry behind at the old\n// key. Set is the only path that can do this, so it is checked through Set.\nfunc TestRedatingMovesTheIndexEntry(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-01-01\", \"\", \"Body A.\")\n\tuassert.Equal(t, 1, order.Size(), \"one order entry\")\n\n\t// Emulate Set's re-key without needing a realm: remove then re-add.\n\tp := posts.Get(\"a\").(*post)\n\torder.Remove(orderKey(p.date, \"a\"))\n\tp.date = \"2026-12-31\"\n\torder.Set(orderKey(p.date, \"a\"), p)\n\n\tuassert.Equal(t, 1, order.Size(), \"still one order entry, not two\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"2026-12-31\"), \"the new date renders\")\n}\n\nfunc TestRenderPostAndNotFound(t *testing.T) {\n\treset()\n\tseed(\"mygnoscan\", \"Sharing mygnoscan\", \"2026-09-23\", \"mygnoscan,tooling\", \"## Why\\n\\nBecause it is useful.\")\n\n\tout := Render(\"mygnoscan\")\n\tuassert.True(t, strings.Contains(out, \"# Sharing mygnoscan\"), \"title renders as the H1\")\n\tuassert.True(t, strings.Contains(out, \"Because it is useful.\"), \"body renders verbatim\")\n\tuassert.True(t, strings.Contains(out, \"## Why\"), \"markdown in the body is not escaped\")\n\n\tmissing := Render(\"nope\")\n\tuassert.True(t, strings.Contains(missing, \"Not found\"), \"an unknown slug is a 404, not the index\")\n}\n\nfunc TestRenderTagFiltersAndReportsEmpty(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-01-01\", \"tooling\", \"Body A.\")\n\tseed(\"b\", \"B\", \"2026-01-02\", \"chain\", \"Body B.\")\n\n\tout := Render(\"t/tooling\")\n\tuassert.True(t, strings.Contains(out, \"A\"), \"the tagged post is listed\")\n\tuassert.False(t, strings.Contains(out, \"](/r/moul/blog:b)\"), \"the untagged post is not\")\n\n\tempty := Render(\"t/nothing\")\n\tuassert.True(t, strings.Contains(empty, \"No post carries this tag.\"), \"an unused tag says so\")\n}\n\n// The manifest is the whole diff protocol. A change to any of the four fields\n// the record covers has to change the hash, or gnoblog reports a stale post as\n// up to date and the fix never gets pushed.\nfunc TestManifestHashCoversEveryField(t *testing.T) {\n\tbase := record(\"T\", \"2026-01-01\", \"a\", \"body\")\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tgot  string\n\t}{\n\t\t{\"title\", record(\"T2\", \"2026-01-01\", \"a\", \"body\")},\n\t\t{\"date\", record(\"T\", \"2026-01-02\", \"a\", \"body\")},\n\t\t{\"tags\", record(\"T\", \"2026-01-01\", \"b\", \"body\")},\n\t\t{\"body\", record(\"T\", \"2026-01-01\", \"a\", \"body2\")},\n\t} {\n\t\tuassert.NotEqual(t, hashOf(base), hashOf(tc.got), \"changing the \"+tc.name+\" changes the hash\")\n\t}\n}\n\nfunc TestManifestShape(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-01-01\", \"tooling\", \"Body A.\")\n\n\tlines := strings.Split(strings.TrimRight(Manifest(), \"\\n\"), \"\\n\")\n\tuassert.Equal(t, 2, len(lines), \"one intro row plus one post row\")\n\tuassert.True(t, strings.HasPrefix(lines[0], introKey+\"\\t\"), \"the intro row comes first\")\n\n\tf := strings.Split(lines[1], \"\\t\")\n\tuassert.Equal(t, 5, len(f), \"five tab-separated fields\")\n\tuassert.Equal(t, \"a\", f[0], \"slug\")\n\tuassert.Equal(t, \"2026-01-01\", f[2], \"date\")\n\tuassert.Equal(t, \"7\", f[3], \"body length\")\n\tuassert.Equal(t, hashOf(record(\"A\", \"2026-01-01\", \"tooling\", \"Body A.\")), f[4], \"record hash\")\n}\n\nfunc TestFirstLineSkipsHeadings(t *testing.T) {\n\tuassert.Equal(t, \"The prose.\", firstLine(\"# Title\\n\\n## Sub\\n\\nThe prose.\\n\"))\n\tuassert.Equal(t, \"\", firstLine(\"# Only a heading\\n\"))\n}\n\nfunc TestIntroDefaultsAndOverrides(t *testing.T) {\n\treset()\n\tuassert.True(t, strings.Contains(Render(\"\"), \"moul's blog\"), \"the built-in header shows before SetIntro\")\n\n\tintro = \"# Something else\"\n\tuassert.True(t, strings.Contains(Render(\"\"), \"Something else\"), \"a set intro replaces it\")\n\tuassert.False(t, strings.Contains(Render(\"\"), \"moul's blog\"), \"and the default is gone\")\n}\n\n// A markdown link in the first line of a post reached the index as its own\n// source, backslash-escaped, on 2026-09-23. The excerpt is plain text, so the\n// link has to be flattened before ui.Excerpt escapes what is left.\nfunc TestFlattenLinks(t *testing.T) {\n\tfor _, tc := range []struct{ in, want string }{\n\t\t{\"plain text\", \"plain text\"},\n\t\t{\"I built [mygnoscan](https://x.example) in April\", \"I built mygnoscan in April\"},\n\t\t{\"[a](1) and [b](2)\", \"a and b\"},\n\t\t{\"\", \"\"},\n\t\t// Unbalanced: left alone rather than half-parsed.\n\t\t{\"an [unclosed link\", \"an [unclosed link\"},\n\t\t{\"brackets [only] here\", \"brackets [only] here\"},\n\t\t{\"[text](no-close\", \"[text](no-close\"},\n\t} {\n\t\tuassert.Equal(t, tc.want, flattenLinks(tc.in), \"flattenLinks(\"+tc.in+\")\")\n\t}\n}\n\n// The index excerpt must read as a sentence, not as markdown source.\nfunc TestExcerptIsProseNotSource(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-09-23\", \"\", \"I built [mygnoscan](https://mygnoscan.example) in April.\")\n\n\tout := Render(\"\")\n\tuassert.False(t, strings.Contains(out, \"\\\\[\"), \"no escaped bracket survives into the index\")\n\tuassert.True(t, strings.Contains(out, \"I built mygnoscan in April\"), \"the excerpt reads as prose\")\n}\n\n// The back link is the realm root, which carries no ':'. linkPrefix with an\n// empty path would produce \"/r/moul/blog:\", which shipped on 2026-09-23.\nfunc TestBackLinkHasNoTrailingColon(t *testing.T) {\n\treset()\n\tseed(\"a\", \"A\", \"2026-09-23\", \"tag\", \"Body.\")\n\n\tfor _, view := range []string{\"a\", \"t/tag\", \"nosuchpost\"} {\n\t\tout := Render(view)\n\t\tuassert.True(t, strings.Contains(out, \"](\"+indexLink+\")\"), view+\" links back to the index\")\n\t\tuassert.False(t, strings.Contains(out, \"](\"+indexLink+\":)\"), view+\" must not emit a trailing colon\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/blog\"\ngno = \"0.9\"\n\n# Redeployable by its creator. See README.md § \"Why private, and why no /vN\".\n#\n# A private package may be re-added at the same path by the address recorded in\n# [addpkg].creator (gno.land/pkg/sdk/vm/keeper.go, checkRedeployPermission), and\n# nothing else may import it. A redeploy RE-RUNS init() and resets realm state,\n# so the markdown kept off chain is the source of truth and tools/gnoblog pushes\n# every post back. That wipe is the reason the post URL can stay version-free:\n# a code change is a redeploy of this path, never a /v1 that moves every link\n# already shared.\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/blog\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"render.gno","body":"package blog\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// linkPrefix is what a permalink starts with. gnoweb addresses a realm's\n// render path with ':' after the package path, so this is realmPath with the\n// leading \"gno.land\" dropped and the separator appended.\nconst linkPrefix = \"/r/moul/blog:\"\n\n// indexLink is the index, which is the realm root and therefore has NO ':'.\n// Spelled separately rather than reusing linkPrefix, because linkPrefix with\n// an empty path produces a trailing colon and a link nobody wants to paste.\nconst indexLink = \"/r/moul/blog\"\n\n// defaultIntro is the header shown before SetIntro has ever been called, i.e.\n// right after the first deploy or after a redeploy wiped the state.\nconst defaultIntro = \"# moul's blog\\n\\nNotes on gno.land, from the person building on it.\\n\"\n\n// Render serves three views:\n//\n//\t\"\"         the index, newest first\n//\t\"\u003cslug\u003e\"   one post\n//\t\"t/\u003ctag\u003e\"  every post carrying a tag\n// Render wraps every view in the notice blocks from gno.land/r/moul/config: a\n// warning, a changelog line or a bit of news, set either on every realm of\n// moul's at once or on this one alone, plus a pause banner if this realm is\n// ever held back. Both are empty by default, so an unconfigured chain renders\n// exactly what it rendered before.\n//\n// The path is passed explicitly rather than using config's zero-argument\n// helpers. Both work, but this realm already states its own path for its\n// permalinks, and a constant cannot be wrong.\nfunc Render(path string) string {\n\treturn config.TopBlockFor(realmPath) + render(path) + config.BottomBlockFor(realmPath)\n}\n\nfunc render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tswitch {\n\tcase path == \"\":\n\t\treturn renderIndex()\n\tcase strings.HasPrefix(path, \"t/\"):\n\t\treturn renderTag(strings.TrimPrefix(path, \"t/\"))\n\tdefault:\n\t\treturn renderPost(path)\n\t}\n}\n\nfunc header() string {\n\tif intro == \"\" {\n\t\treturn defaultIntro\n\t}\n\treturn strings.TrimRight(intro, \"\\n\") + \"\\n\"\n}\n\nfunc renderIndex() string {\n\tvar b strings.Builder\n\tb.WriteString(header())\n\n\tif posts.Size() == 0 {\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(ui.Empty(\"Nothing published yet.\"))\n\t\treturn b.String()\n\t}\n\n\t// order is keyed by \"\u003cdate\u003e/\u003cslug\u003e\", so walking it backwards is\n\t// newest-first without a sort the language does not have.\n\torder.ReverseIterate(\"\", \"\", func(_ string, value any) bool {\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(entry(value.(*post)))\n\t\treturn false\n\t})\n\treturn b.String()\n}\n\nfunc renderTag(tag string) string {\n\ttag = strings.ToLower(strings.TrimSpace(tag))\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Tagged \")\n\tb.WriteString(ui.Inline(tag))\n\tb.WriteString(\"\\n\")\n\n\tfound := 0\n\torder.ReverseIterate(\"\", \"\", func(_ string, value any) bool {\n\t\tp := value.(*post)\n\t\tif !hasTag(p, tag) {\n\t\t\treturn false\n\t\t}\n\t\tfound++\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(entry(p))\n\t\treturn false\n\t})\n\tif found == 0 {\n\t\tb.WriteString(\"\\n\")\n\t\tb.WriteString(ui.Empty(\"No post carries this tag.\"))\n\t}\n\tb.WriteString(\"\\n[← all posts](\" + indexLink + \")\\n\")\n\treturn b.String()\n}\n\nfunc renderPost(slug string) string {\n\tv := posts.Get(slug)\n\tif v == nil {\n\t\treturn \"# Not found\\n\\nNo post at \" + strconv.Quote(ui.Inline(slug)) +\n\t\t\t\".\\n\\n[← all posts](\" + indexLink + \")\\n\"\n\t}\n\tp := v.(*post)\n\n\tvar b strings.Builder\n\tb.WriteString(\"# \")\n\tb.WriteString(ui.Inline(p.title))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(byline(p))\n\tb.WriteString(\"\\n\\n\")\n\t// The body is markdown written by `author`, who is also the only address\n\t// that can call Set. It is the post, so it renders verbatim: escaping it\n\t// would turn every heading and link in it into literal text.\n\tb.WriteString(strings.TrimRight(p.body, \"\\n\"))\n\tb.WriteString(\"\\n\\n---\\n\\n[← all posts](\" + indexLink + \")\\n\")\n\treturn b.String()\n}\n\n// entry is one row of a listing: linked title, byline, excerpt.\nfunc entry(p *post) string {\n\tvar b strings.Builder\n\tb.WriteString(\"## [\")\n\tb.WriteString(ui.Inline(p.title))\n\tb.WriteString(\"](\")\n\tb.WriteString(linkPrefix)\n\tb.WriteString(p.slug)\n\tb.WriteString(\")\\n\\n\")\n\tb.WriteString(byline(p))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(ui.Excerpt(flattenLinks(firstLine(p.body)), excerptLen))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\n// byline is the date plus the post's tags as links, on one line.\nfunc byline(p *post) string {\n\tvar b strings.Builder\n\tb.WriteString(p.date)\n\tfor _, t := range splitTags(p.tags) {\n\t\tb.WriteString(\" · [#\")\n\t\tb.WriteString(ui.Inline(t))\n\t\tb.WriteString(\"](\")\n\t\tb.WriteString(linkPrefix)\n\t\tb.WriteString(\"t/\")\n\t\tb.WriteString(t)\n\t\tb.WriteString(\")\")\n\t}\n\treturn b.String()\n}\n\nfunc hasTag(p *post, tag string) bool {\n\tfor _, t := range splitTags(p.tags) {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// flattenLinks rewrites \"[text](url)\" to \"text\".\n//\n// An excerpt is plain text: ui.Excerpt escapes what it is given, so a markdown\n// link survives into the index as its own source, backslashes and all, and the\n// reader sees `[mygnoscan](https://...)` where a sentence should be. Shipped\n// exactly that way on 2026-09-23 and it was the first thing on the page.\n//\n// Dropping the URL rather than keeping it bare is deliberate: the title beside\n// it is already a link to the post, and a second URL in a two-line preview is\n// noise. Unbalanced brackets are left alone and escaped as before, because a\n// half-parsed link is worse than an unparsed one.\nfunc flattenLinks(s string) string {\n\tvar b strings.Builder\n\tfor {\n\t\topen := strings.Index(s, \"[\")\n\t\tif open \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\tclose := strings.Index(s[open:], \"](\")\n\t\tif close \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\tclose += open\n\t\tend := strings.Index(s[close:], \")\")\n\t\tif end \u003c 0 {\n\t\t\tbreak\n\t\t}\n\t\tend += close\n\t\tb.WriteString(s[:open])\n\t\tb.WriteString(s[open+1 : close])\n\t\ts = s[end+1:]\n\t}\n\tb.WriteString(s)\n\treturn b.String()\n}\n\n// firstLine returns the first non-empty, non-heading line of a body, which is\n// what an excerpt should show: a post that opens with \"## Something\" would\n// otherwise preview its own heading.\nfunc firstLine(body string) string {\n\tfor _, line := range strings.Split(body, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\t\treturn line\n\t}\n\treturn \"\"\n}\n"},{"name":"render_example_test.gno","body":"package blog\n\nimport \"testing\"\n\n// ExampleRender pins the index. It seeds state directly (rather than through\n// Set) so the example takes no `cur realm`, and it resets first because an\n// example runs after every Test in the package and would otherwise render what\n// they left behind.\nfunc ExampleRender() {\n\treset()\n\tseed(\"mygnoscan\", \"Sharing mygnoscan\", \"2026-09-23\", \"mygnoscan,tooling\", \"An unfinished BI tool for gno.land.\")\n\tseed(\"hello\", \"Hello\", \"2026-09-01\", \"meta\", \"Starting a blog on chain.\")\n\tprint(Render(\"\"))\n\t// Output:\n\t// # moul's blog\n\t//\n\t// Notes on gno.land, from the person building on it.\n\t//\n\t// ## [Sharing mygnoscan](/r/moul/blog:mygnoscan)\n\t//\n\t// 2026-09-23 · [#mygnoscan](/r/moul/blog:t/mygnoscan) · [#tooling](/r/moul/blog:t/tooling)\n\t//\n\t// An unfinished BI tool for gno\\.land\\.\n\t//\n\t// ## [Hello](/r/moul/blog:hello)\n\t//\n\t// 2026-09-01 · [#meta](/r/moul/blog:t/meta)\n\t//\n\t// Starting a blog on chain\\.\n}\n\n// TestNoticeBlocksAreTransparentByDefault pins the property that made it safe\n// to wrap every view in them: with nothing set on r/moul/config, Render is\n// byte-for-byte the inner render. If that ever stops holding, every page of\n// this blog gains stray whitespace at the top and the bottom.\nfunc TestNoticeBlocksAreTransparentByDefault(t *testing.T) {\n\tfor _, path := range []string{\"\", \"t/gno\", \"no-such-post\"} {\n\t\tif Render(path) != render(path) {\n\t\t\tt.Fatalf(\"Render(%q) differs from the inner render with no notice configured\", path)\n\t\t}\n\t}\n}\n"},{"name":"write_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nvar stranger = testutils.TestAddress(\"stranger\")\n\n// Everything here goes through the real crossing functions rather than seed(),\n// because the author check, the re-key on a date change and the panic messages\n// only exist on that path and are exactly what a typo would break on a\n// permanent path.\n\nfunc TestSetPublishesAndRenders(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tSet(cross(cur), \"hello\", \"Hello\", \"2026-09-23\", \"Gno, tooling\", \"The body.\")\n\n\tuassert.Equal(t, 1, Count(), \"one post\")\n\tuassert.Equal(t, \"The body.\", Get(\"hello\"), \"the body round-trips\")\n\tuassert.True(t, strings.Contains(Render(\"hello\"), \"# Hello\"), \"it renders\")\n\t// Tags are normalized on write, not on read, so the hash the tool computed\n\t// locally is the hash the manifest reports.\n\tuassert.True(t, strings.Contains(Manifest(), \"\\t\"+hashOf(record(\"Hello\", \"2026-09-23\", \"gno,tooling\", \"The body.\"))),\n\t\t\"the manifest hashes the normalized record\")\n}\n\nfunc TestOnlyTheAuthorMayWrite(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(stranger))\n\t// AbortsWithMessage, not PanicsWithMessage: a panic that crosses a realm\n\t// boundary becomes an abort, which recover() cannot catch, so asserting it\n\t// as a panic does not fail the assertion, it kills the whole test binary.\n\tuassert.AbortsWithMessage(t, cur, \"restricted to the author\", func() {\n\t\tSet(cross(cur), \"nope\", \"Nope\", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"restricted to the author\", func() {\n\t\tSetIntro(cross(cur), \"mine now\")\n\t})\n\tuassert.Equal(t, 0, Count(), \"nothing was written\")\n}\n\n// The one case a second tree can get wrong: re-dating a post must MOVE its\n// index entry, not leave a ghost at the old key rendering the post twice.\nfunc TestSetRedatingMovesTheIndexEntry(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tSet(cross(cur), \"a\", \"A\", \"2026-01-01\", \"\", \"Body A.\")\n\tSet(cross(cur), \"a\", \"A\", \"2026-12-31\", \"\", \"Body A.\")\n\n\tuassert.Equal(t, 1, Count(), \"still one post\")\n\tout := Render(\"\")\n\tuassert.Equal(t, 1, strings.Count(out, \"](/r/moul/blog:a)\"), \"listed exactly once\")\n\tuassert.True(t, strings.Contains(out, \"2026-12-31\"), \"under the new date\")\n\tuassert.False(t, strings.Contains(out, \"2026-01-01\"), \"and not the old one\")\n}\n\nfunc TestSetRejectsWhatTheToolRejects(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tuassert.AbortsContains(t, cur, \"invalid slug\", func() {\n\t\tSet(cross(cur), \"Caps\", \"T\", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved slug\", func() {\n\t\tSet(cross(cur), introSlug, \"T\", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsContains(t, cur, \"invalid date\", func() {\n\t\tSet(cross(cur), \"ok\", \"T\", \"23-09-2026\", \"\", \"Body.\")\n\t})\n\tuassert.AbortsContains(t, cur, \"a post needs a title\", func() {\n\t\tSet(cross(cur), \"ok\", \"  \", \"2026-09-23\", \"\", \"Body.\")\n\t})\n\tuassert.Equal(t, 0, Count(), \"none of them was written\")\n}\n\nfunc TestAppendAndDelete(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tSet(cross(cur), \"long\", \"Long\", \"2026-09-23\", \"\", \"First half.\")\n\tAppend(cross(cur), \"long\", \" Second half.\")\n\tuassert.Equal(t, \"First half. Second half.\", Get(\"long\"), \"append concatenates, it does not replace\")\n\n\tuassert.AbortsWithMessage(t, cur, `no such post: \"ghost\"`, func() {\n\t\tAppend(cross(cur), \"ghost\", \"x\")\n\t})\n\n\tDelete(cross(cur), \"long\")\n\tuassert.Equal(t, 0, Count(), \"deleted\")\n\tuassert.True(t, strings.Contains(Render(\"\"), \"Nothing published yet.\"), \"and gone from the index\")\n\tuassert.AbortsWithMessage(t, cur, `no such post: \"long\"`, func() {\n\t\tDelete(cross(cur), \"long\")\n\t})\n}\n\nfunc TestRevisionMovesOnEveryWrite(cur realm, t *testing.T) {\n\treset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tuassert.Equal(t, 0, Revision(), \"a fresh realm is at zero\")\n\tSet(cross(cur), \"a\", \"A\", \"2026-09-23\", \"\", \"Body.\")\n\tAppend(cross(cur), \"a\", \"!\")\n\tSetIntro(cross(cur), \"# Header\")\n\tDelete(cross(cur), \"a\")\n\tuassert.Equal(t, 4, Revision(), \"one per mutation, so a client can tell nothing moved\")\n}\n"},{"name":"zz_zerowidth_test.gno","body":"package blog\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc TestZeroWidthTitleIsRefused(cur realm, t *testing.T) {\n\treset()\n\tdefer reset()\n\ttesting.SetRealm(testing.NewUserRealm(author))\n\tfor i, s := range zwBlank {\n\t\tslug := \"zw\" + strconv.Itoa(i)\n\t\tif revive(func() { Set(cross(cur), slug, s, \"2026-10-14\", \"\", \"body\") }) == nil {\n\t\t\tt.Errorf(\"Set accepted title %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tfor i, s := range zwOK {\n\t\tslug := \"ok\" + strconv.Itoa(i)\n\t\tif r := revive(func() { Set(cross(cur), slug, s, \"2026-10-14\", \"\", \"body\") }); r != nil {\n\t\t\tt.Errorf(\"Set refused title %q: %v\", s, r)\n\t\t}\n\t}\n\tif posts.Size() != len(zwOK) {\n\t\tt.Errorf(\"%d post(s), want %d\", posts.Size(), len(zwOK))\n\t}\n}\n"}]},"send":"","max_deposit":"15000000ugnot"}],"fee":{"gas_wanted":"108774600","gas_fee":"326323ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"zjYA+2dmeFRIOGC8VoE7KxE3MMZI2ZLSzYXDEbWhPwI9JBUbwKdDNKpfefDkbQEPxLQ6ep18rCf7Bbz2CK9W9Q=="}],"memo":""},"metadata":{"timestamp":"1791963474"}},{"tx":{"msg":[{"@type":"/bank.MsgSend","from_address":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","to_address":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","amount":"10000000ugnot"}],"fee":{"gas_wanted":"1402606","gas_fee":"2806ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"cPrHOSGxCK8VzB32gZU+TqEXHLw5fH6IH3QDFeUbwS5MhoRilM8LwgVl6gLFQVq6jfjhlxjixJNn64Esic0cEQ=="}],"memo":""},"metadata":{"timestamp":"1791963475"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"blog","path":"gno.land/r/moul/x/daily/blog/v1","files":[{"name":"README.md","body":"# Personal Blog\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA multi-author on-chain blog realm for gno.land. Anyone can publish a post; each\npost records its author (the calling address) and the block height at which it\nwas published. Posts are stored persistently and rendered newest-first, with a\ndedicated page for each post's full text.\n\n**Realm path:** `gno.land/r/moul/x/daily/blog/v1`\n\n## Example calls\n\nPublish a post (state-mutating, crossing function):\n\n```\ngnokey maketx call -pkgpath \"gno.land/r/moul/x/daily/blog/v1\" \\\n  -func Publish -args \"My first post\" -args \"Hello, gno.land!\" \\\n  -gas-fee 20000ugnot -gas-wanted 2000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 KEY\n```\n\nRead views (no transaction needed):\n\n- Root — list all posts, newest first: render `gno.land/r/moul/x/daily/blog/v1`\n- Single post by id: render `gno.land/r/moul/x/daily/blog/v1:/0`\n\n`PostCount()` returns the total number of published posts.\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\nIds stay plain integers, and `Post` loses its `ID` field, which the store now\nowns. Two things a reader will notice:\n\n- **Post ids now start at 1.** `v0` handed out 0 for the first post; the store\n  never assigns 0, so the zero id stays usable as \"absent\".\n- **`/0` is no longer a post path.** It is rejected as invalid rather than\n  looked up, along with anything else that is not a plain decimal.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/blog) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/blog/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/blog/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/blog/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/blog/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"blog.gno","body":"// Package blog is a multi-author on-chain blog realm for gno.land.\n//\n// Any caller can Publish a post; posts are stored persistently and rendered\n// newest-first. Each post records its author (the calling address) and the\n// block height at which it was published.\npackage blog\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n)\n\n// selfPath is this realm's own page. A root-relative link resolves against\n// the domain, not the realm, so every link back into it names it in full.\nconst selfPath = \"/r/moul/x/daily/blog/v1\"\n\n// Post is a single blog entry. It carries no id field: the id belongs to the\n// store, which hands it back on lookup and iteration.\ntype Post struct {\n\tTitle  string\n\tBody   string\n\tAuthor address\n\tHeight int64\n}\n\n// posts holds every published post. The store keys by seqid, so iteration is\n// in publication order for any number of posts; v0 kept its own nextID plus a\n// key() that zero-padded to width 12 and stopped ordering past it.\nvar posts = store.Named(\"post\")\n\n// Publish creates a new post authored by the caller and returns its id.\n// It is a state-mutating exported function, so it takes `cur realm`.\nfunc Publish(cur realm, title string, body string) int {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"blog: spoofed realm\")\n\t}\n\ttitle = strings.TrimSpace(title)\n\tbody = strings.TrimSpace(body)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(title)) == \"\" {\n\t\tpanic(\"blog: title must not be empty\")\n\t}\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(body)) == \"\" {\n\t\tpanic(\"blog: body must not be empty\")\n\t}\n\n\tauthor := cur.Previous().Address()\n\tid := posts.Add(\u0026Post{\n\t\tTitle:  title,\n\t\tBody:   body,\n\t\tAuthor: author,\n\t\tHeight: runtime.ChainHeight(),\n\t})\n\n\tchain.Emit(\n\t\t\"PostPublished\",\n\t\t\"id\", id.String(),\n\t\t\"author\", author.String(),\n\t)\n\treturn int(id)\n}\n\n// PostCount returns the number of published posts.\nfunc PostCount() int {\n\treturn posts.Len()\n}\n\n// Render lists all posts newest-first at the root, or a single post's full\n// text at path \"/\u003cid\u003e\". Render is NOT a crossing function.\nfunc Render(path string) string {\n\tpath = strings.TrimSpace(path)\n\tif path == \"\" || path == \"/\" {\n\t\treturn renderList()\n\t}\n\tidStr := strings.TrimPrefix(path, \"/\")\n\tid, ok := store.ParseID(idStr)\n\tif !ok {\n\t\treturn \"# Not found\\n\\nInvalid post path: \" + md.InlineCode(path) + \"\\n\\n[← back](\" + selfPath + \")\\n\"\n\t}\n\tv, ok := posts.Get(id)\n\tif !ok {\n\t\treturn \"# Not found\\n\\nNo post with id \" + idStr + \".\\n\\n[← back](\" + selfPath + \")\\n\"\n\t}\n\treturn renderPost(v.(*Post))\n}\n\nfunc renderList() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 📝 Blog\\n\\n\")\n\tif posts.Len() == 0 {\n\t\tb.WriteString(\"_No posts yet. Be the first to `Publish`._\\n\")\n\t\treturn b.String()\n\t}\n\tb.WriteString(strconv.Itoa(posts.Len()) + \" post(s), newest first.\\n\\n\")\n\n\t// Ids ascend with publication, so reverse iteration is newest-first.\n\tposts.EachReverse(func(id store.ID, v any) {\n\t\tp := v.(*Post)\n\t\tb.WriteString(\"## [\")\n\t\tb.WriteString(ui.Inline(p.Title))\n\t\tb.WriteString(\"](\" + selfPath + \":/\")\n\t\tb.WriteString(id.String())\n\t\tb.WriteString(\")\\n\\n\")\n\t\tb.WriteString(\"by `\")\n\t\tb.WriteString(p.Author.String())\n\t\tb.WriteString(\"` · height \")\n\t\tb.WriteString(strconv.FormatInt(p.Height, 10))\n\t\tb.WriteString(\"\\n\\n\")\n\t\tb.WriteString(ui.Excerpt(strings.TrimSpace(p.Body), 140))\n\t\tb.WriteString(\"\\n\\n---\\n\\n\")\n\t})\n\treturn b.String()\n}\n\nfunc renderPost(p *Post) string {\n\tvar b strings.Builder\n\tb.WriteString(\"# \")\n\tb.WriteString(ui.Inline(p.Title))\n\tb.WriteString(\"\\n\\n\")\n\tb.WriteString(\"by `\")\n\tb.WriteString(p.Author.String())\n\tb.WriteString(\"` · height \")\n\tb.WriteString(strconv.FormatInt(p.Height, 10))\n\tb.WriteString(\"\\n\\n\")\n\t// Anyone may publish, so the body is the caller's text, not this realm's\n\t// markdown: each line is escaped, and a blank line still breaks a paragraph.\n\tfor i, line := range strings.Split(p.Body, \"\\n\") {\n\t\tif i \u003e 0 {\n\t\t\tb.WriteString(\"  \\n\")\n\t\t}\n\t\tb.WriteString(ui.Inline(line))\n\t}\n\tb.WriteString(\"\\n\\n---\\n\\n[← back to all posts](\" + selfPath + \")\\n\")\n\treturn b.String()\n}\n"},{"name":"blog_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestPublishAndRender(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t// Ids start at 1 in v1: the store never assigns 0, so the zero id stays\n\t// usable as \"absent\". v0 handed out 0 for the first post.\n\tid0 := Publish(cross(cur), \"First Post\", \"Hello from alice.\")\n\tuassert.Equal(t, 1, id0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tid1 := Publish(cross(cur), \"Second Post\", \"A longer body\\nwith a newline from bob.\")\n\tuassert.Equal(t, 2, id1)\n\n\tuassert.Equal(t, 2, PostCount())\n\n\t// Root render lists both, newest (bob's) first.\n\tlist := Render(\"\")\n\tuassert.True(t, strings.Contains(list, \"First Post\"), \"list has first post\")\n\tuassert.True(t, strings.Contains(list, \"Second Post\"), \"list has second post\")\n\tuassert.True(t, strings.Index(list, \"Second Post\") \u003c strings.Index(list, \"First Post\"),\n\t\t\"newest post appears first\")\n\tuassert.True(t, strings.Contains(list, alice.String()), \"list shows alice author\")\n\n\t// Single-post render shows full body + back link.\n\tsingle := Render(\"/2\")\n\tuassert.True(t, strings.Contains(single, \"newline from bob\"), \"full body shown\")\n\tuassert.True(t, strings.Contains(single, \"← back\"), \"back link present\")\n\n\t// Unknown id.\n\tuassert.True(t, strings.Contains(Render(\"/99\"), \"Not found\"), \"missing post handled\")\n\n\t// Id 0 is never assigned, so the path is rejected rather than looked up.\n\tuassert.True(t, strings.Contains(Render(\"/0\"), \"Invalid post path\"), \"id 0 is not a post\")\n\tuassert.True(t, strings.Contains(Render(\"/abc\"), \"Invalid post path\"), \"a non-numeric path is rejected\")\n}\n\nfunc TestPublishEmptyTitleAborts(cur realm, t *testing.T) {\n\tcarol := testutils.TestAddress(\"carol\")\n\ttesting.SetRealm(testing.NewUserRealm(carol))\n\n\tuassert.AbortsWithMessage(t, cur, \"blog: title must not be empty\", func() {\n\t\tPublish(cross(cur), \"   \", \"some body\")\n\t})\n\tuassert.AbortsWithMessage(t, cur, \"blog: body must not be empty\", func() {\n\t\tPublish(cross(cur), \"a title\", \"\")\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/blog/v1\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/daily/blog\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"zz_escape_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Anyone may publish, so a title or a body is the caller's text and must not\n// become live markdown on the realm's own pages.\nfunc TestTitleAndBodyAreEscaped(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"escaper\")))\n\tid := Publish(cross(cur), \"[claim](https://evil.example)\", \"line one\\n[claim](https://evil.example)\")\n\tuassert.False(t, strings.Contains(Render(\"\"), \"[claim](https://evil.example)\"), Render(\"\"))\n\tpage := Render(\"/\" + itoaTest(id))\n\tuassert.False(t, strings.Contains(page, \"[claim](https://evil.example)\"), page)\n}\n\n// A path that names nothing is echoed back on the not-found page. It is the\n// visitor's text, so a backtick in it must not close a code span and let a\n// link through.\nfunc TestNotFoundPathIsEscaped(t *testing.T) {\n\tout := Render(\"/x` [claim](https://evil.example) `\")\n\t// Still there, but inside a span md.InlineCode widened past its backticks.\n\tuassert.True(t, strings.Contains(out, md.InlineCode(\"/x` [claim](https://evil.example) `\")), out)\n}\n"},{"name":"zz_links_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Every link the realm renders names its own absolute path. A dead link here\n// once read /r/REPLACE_ADDR/blog, and a test that only checked \"a back link\n// exists\" passed against it.\nfunc TestLinksNameThisRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"linker\")))\n\tid := Publish(cross(cur), \"Linked\", \"body\")\n\tidx := Render(\"\")\n\tuassert.True(t, strings.Contains(idx, \"](/r/moul/x/daily/blog/v1:/\"), idx)\n\tpage := Render(\"/\" + itoaTest(id))\n\tuassert.True(t, strings.Contains(page, \"(/r/moul/x/daily/blog/v1)\"), page)\n}\n\nfunc itoaTest(n int) string {\n\tif n == 0 {\n\t\treturn \"0\"\n\t}\n\ts := \"\"\n\tfor n \u003e 0 {\n\t\ts = string(rune(byte(n%10)+byte(48))) + s\n\t\tn /= 10\n\t}\n\treturn s\n}\n"},{"name":"zz_zerowidth_test.gno","body":"package blog\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc TestZeroWidthTitleAndBodyAreRefused(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\tbefore := PostCount()\n\tfor _, s := range zwBlank {\n\t\tif revive(func() { Publish(cross(cur), s, \"body\") }) == nil {\n\t\t\tt.Errorf(\"Publish accepted title %q, which the render strips to blank\", s)\n\t\t}\n\t\tif revive(func() { Publish(cross(cur), \"title\", s) }) == nil {\n\t\t\tt.Errorf(\"Publish accepted body %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif r := revive(func() { Publish(cross(cur), s, s) }); r != nil {\n\t\t\tt.Errorf(\"Publish refused title and body %q: %v\", s, r)\n\t\t}\n\t}\n\tif got := PostCount() - before; got != len(zwOK) {\n\t\tt.Errorf(\"%d post(s) published, want %d\", got, len(zwOK))\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"48467600","gas_fee":"145402ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"nN2ZdWVIQi+E3tfUikwa97vgDdbjJHX1W4LWzxfwUM8xnturKHau/gwLbO6NcGXSOsmqgxs8gBPP9pK3K5vmMQ=="}],"memo":""},"metadata":{"timestamp":"1791963530"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"devtools","path":"gno.land/r/moul/x/allinone/devtools/v0","files":[{"name":"README.md","body":"# `gno.land/r/moul/x/allinone/devtools`\n\nThe worked example of wiring moul's developer packages into one realm: what a\nnew realm should copy.\n\nEight packages, each earning its place in the output:\n\n| package | what it contributes |\n|---|---|\n| [`r/moul/config`](../../../config) | the notice block, the pause guard, which explorer to link |\n| [`p/moul/mygnoscan`](../../../../p/moul/mygnoscan) | the explorer routes |\n| [`p/moul/debug`](../../../../p/moul/debug) | the `?debug=1` panel |\n| [`p/moul/realmpath`](../../../../p/moul/realmpath) | reading the render path |\n| [`p/moul/kit/ui`](../../../../p/moul/kit/ui) | escaping caller input, and the tables |\n| [`p/moul/md`](../../../../p/moul/md) | the markdown |\n| [`p/moul/txlink`](../../../../p/moul/txlink) | the call links |\n| [`p/moul/fifo`](../../../../p/moul/fifo) | the bounded note list |\n\n## The three lines worth copying\n\n```go\nfunc Render(path string) string {\n\treturn config.TopBlockFor(realmPath) + body + config.BottomBlockFor(realmPath)\n}\n\nfunc Add(cur realm, body string) {\n\tconfig.AssertWritableFor(realmPath)  // honours the pause switch\n\tnotes.Append(ui.Inline(body))        // escapes what a caller typed\n}\n```\n\nThe first gives the realm a place for a warning and a pause banner without\nshipping any banner code, and returns `\"\"` while nothing is set, so a page that\nconcatenates it unconditionally is unchanged by default.\n\nThe second is two separate guards and both have to be there: the pause one so\nan incident can stop writes from outside this realm and without a redeploy, and\nthe escaping one because a string a caller typed is the oldest way to break a\npage.\n\n## Two views\n\n`Render(\"\")` is the root and is free of anything that moves, so an example test\ncan pin it. Everything live (the height, the chain id, the links built from\nthem) is under `:chain`, which is also what keeps the pinned output stable.\n\nState is disposable: the note list is bounded by `fifo` at 10 entries and this\nrealm is `private = true`, so a redeploy wipes it on purpose.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/allinone/devtools/v0?network=mainnet)](https://gnoscope.com/realm/r/moul/x/allinone/devtools/v0)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/allinone/devtools/v0 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/allinone/devtools/v0/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"devtools.gno","body":"// Package devtools is the worked example of wiring moul's developer packages\n// into one realm: what a new realm should copy.\n//\n// Everything here is a COMBINATION. Any one of these packages has its own demo\n// showing it alone; the thing that is hard to find is what they look like used\n// together, which is the only form a real realm ever meets them in. So this\n// realm imports ten of them and every one earns its place in the output:\n//\n//\tr/moul/config     the notice block, the pause switch, the explorer to link\n//\tp/moul/mygnoscan  the explorer routes themselves\n//\tp/moul/debug      a metadata panel behind ?debug=1\n//\tp/moul/realmpath  reading the query string Render was handed\n//\tp/moul/kit/ui     escaping what a caller typed, and the tables\n//\tp/moul/md         the markdown, without hand-rolled strings\n//\tp/moul/txlink     the \"call this function\" link\n//\tp/moul/fifo       the bounded note list, so the state cannot grow forever\n//\tp/moul/kit/tally  the note leaderboard, ties ordered rather than arbitrary\n//\tp/moul/kit/num    pricing that list in GNOT rather than raw ugnot\n//\n// # The three lines worth copying\n//\n// A realm that does nothing else should still do these:\n//\n//\tfunc Render(path string) string {\n//\t\treturn config.TopBlockFor(realmPath) + body + config.BottomBlockFor(realmPath)\n//\t}\n//\n//\tfunc Mutate(cur realm, s string) {\n//\t\tconfig.AssertWritableFor(realmPath)  // honours the pause switch\n//\t\tnotes.Append(ui.Inline(s))           // escapes what a caller typed\n//\t}\n//\n// The first gives every realm a place to put a warning and a pause banner\n// without shipping banner code. The second is two separate guards that both\n// have to be there: the pause one so an incident can stop writes from outside\n// the realm, and the escaping one because a string a caller typed is the\n// oldest way to break a page.\npackage devtools\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/moul/debug/v0\"\n\t\"gno.land/p/moul/fifo/v0\"\n\t\"gno.land/p/moul/kit/num/v0\"\n\t\"gno.land/p/moul/kit/tally/v0\"\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/moul/md/v0\"\n\t\"gno.land/p/moul/mygnoscan/v0\"\n\t\"gno.land/p/moul/realmpath/v0\"\n\t\"gno.land/p/moul/txlink/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// realmPath is this realm's own path.\n//\n// Passed explicitly to config rather than relying on its zero-argument helpers.\n// Both work (a plain read is borrowed, so config sees this realm as the\n// caller), but a constant cannot be wrong, and spelling it out is what a reader\n// copying this file needs to see.\nconst realmPath = \"gno.land/r/moul/x/allinone/devtools/v0\"\n\n// maxNotes bounds the guest list. fifo drops the oldest rather than growing,\n// because storage on chain is paid for and never refunded: an unbounded list in\n// a demo anyone can write to is a bill with no ceiling.\nconst maxNotes = 10\n\nvar notes = fifo.New(maxNotes)\n\n// authors counts notes per writer. A tally.Board rather than a map: gno map\n// iteration order is unspecified, so a leaderboard built by ranging one is not\n// reproducible between calls.\nvar authors = tally.NewBoard()\n\n// depositPerByte is what the chain charges to keep a byte, in ugnot. Used only\n// to price the note list on the page, never to settle anything.\nconst depositPerByte = 100\n\n// Add appends a note. It is the only mutating function here, and it carries\n// both guards a real one should.\nfunc Add(cur realm, body string) {\n\t// 1. The pause switch. Set `pause@r/moul/x/allinone/devtools` on\n\t//    r/moul/config and this aborts, with the reason, from outside this\n\t//    realm and without a redeploy.\n\tconfig.AssertWritableFor(realmPath)\n\n\tbody = strings.TrimSpace(body)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(body)) == \"\" {\n\t\tpanic(\"empty note\")\n\t}\n\tif len(body) \u003e 200 {\n\t\tpanic(\"note too long: max 200 bytes, got \" + strconv.Itoa(len(body)))\n\t}\n\n\t// 2. Escaping. body is a string a caller typed, and it is about to land in\n\t//    a markdown list. ui.Inline is the repo's standard for exactly this.\n\tnotes.Append(ui.Inline(body))\n\n\t// 3. The scoreboard. tally.Board keeps one score per author and orders\n\t//    ties by key, so two authors on the same count always render in the\n\t//    same order.\n\tauthors.Add(unsafe.PreviousRealm().Address().String(), 1)\n}\n\n// Reset empties the list, so the realm can be put back to a known state\n// without a redeploy. Not gated by the pause switch: clearing up is the thing\n// you still want to do while paused.\nfunc Reset(cur realm) {\n\tnotes = fifo.New(maxNotes)\n\tauthors = tally.NewBoard()\n}\n\n// Render shows every package at work. The root view is deliberately free of\n// anything that moves on its own, so an example test can pin it; the live\n// numbers live under \"chain\".\nfunc Render(path string) string {\n\treq := realmpath.Parse(path)\n\n\tvar b strings.Builder\n\tb.WriteString(config.TopBlockFor(realmPath))\n\tb.WriteString(md.H1(\"allinone: devtools\"))\n\tb.WriteString(\"\\nTen packages, used together rather than one at a time. \")\n\tb.WriteString(md.Link(\"source\", config.MygnoscanFor(realmPath)))\n\tb.WriteString(\"\\n\\n\")\n\n\tswitch req.PathPart(0) {\n\tcase \"chain\":\n\t\tb.WriteString(renderChain())\n\tdefault:\n\t\tb.WriteString(renderHome(path))\n\t}\n\n\t// debug prints its own panel only when ?debug=1 is set, and the empty\n\t// string otherwise, so this line is safe to leave in a deployed realm.\n\tb.WriteString(debug.Render(path))\n\tb.WriteString(config.BottomBlockFor(realmPath))\n\treturn b.String()\n}\n\nfunc renderHome(path string) string {\n\tvar b strings.Builder\n\n\tb.WriteString(md.H2(\"Notes\"))\n\tb.WriteString(\"\\n\")\n\t// renderNotes returns no trailing newline of its own: md.BulletList and\n\t// ui.Empty already end in one, and adding a second here produced two\n\t// consecutive blank lines, which gno collapses inside an // Output: block\n\t// and which therefore no example test can ever pin.\n\tb.WriteString(renderNotes())\n\tb.WriteString(\"\\n\")\n\n\t// txlink builds the \"call this function\" URL for the CURRENT realm, so it\n\t// keeps working after a version bump without anything here changing.\n\tb.WriteString(md.BulletList([]string{\n\t\tmd.Link(\"add a note\", txlink.NewLink(\"Add\").AddArgs(\"body\", \"hello\").URL()),\n\t\tmd.Link(\"clear them\", txlink.Call(\"Reset\")),\n\t\tmd.Link(\"live chain values\", \"/r/moul/x/allinone/devtools/v0:chain\"),\n\t\tmd.Link(\"toggle the debug panel\", debug.ToggleURL(path)),\n\t}))\n\tb.WriteString(\"\\n\")\n\n\tb.WriteString(renderBoard())\n\n\tb.WriteString(md.H2(\"What each package does here\"))\n\tb.WriteString(\"\\n\")\n\tt := ui.NewTable(\"package\", \"what it contributed\")\n\tt.Row(\"`r/moul/config`\", \"the notice block above, the pause guard on `Add`, and which explorer to link\")\n\tt.Row(\"`p/moul/mygnoscan`\", \"the explorer routes, so a link survives a route change\")\n\tt.Row(\"`p/moul/debug`\", \"the `?debug=1` panel, empty otherwise\")\n\tt.Row(\"`p/moul/realmpath`\", \"splitting the render path into a view and a query\")\n\tt.Row(\"`p/moul/kit/ui`\", \"escaping a caller's note, and this table\")\n\tt.Row(\"`p/moul/md`\", \"every heading, link and list on the page\")\n\tt.Row(\"`p/moul/txlink`\", \"the call links above, relative to this realm\")\n\tt.Row(\"`p/moul/fifo`\", \"the note list, bounded so storage cannot grow forever\")\n\tt.Row(\"`p/moul/kit/tally`\", \"the note leaderboard, with ties ordered by address\")\n\tt.Row(\"`p/moul/kit/num`\", \"pricing the note list in GNOT instead of raw ugnot\")\n\tb.WriteString(t.String())\n\n\treturn b.String()\n}\n\n// renderBoard shows who has written the most notes, and what the list costs to\n// keep. Both numbers come from a package rather than from arithmetic here.\nfunc renderBoard() string {\n\tvar b strings.Builder\n\tb.WriteString(md.H2(\"Who has written the most\"))\n\tb.WriteString(\"\\n\")\n\n\ttop := authors.Top(5)\n\tif len(top) == 0 {\n\t\tb.WriteString(ui.Empty(\"No notes yet, so nobody is on the board.\"))\n\t} else {\n\t\tt := ui.NewTable(\"#\", \"author\", \"notes\")\n\t\tfor i, e := range top {\n\t\t\tt.Row(ui.Podium(i+1), ui.AddrOf(e.Key), num.Pad(e.Score, 2))\n\t\t}\n\t\tb.WriteString(t.String())\n\t}\n\n\t// num.GNOTf, not a hand-rolled divide by a million. The storage deposit is\n\t// what the chain charges to keep these bytes, so it is the honest price of\n\t// the list above.\n\tb.WriteString(\"\\nStorage deposit for the list: **\")\n\tb.WriteString(num.GNOTf(int64(notesBytes()) * depositPerByte))\n\tb.WriteString(\"**\\n\\n\")\n\treturn b.String()\n}\n\n// notesBytes is the length of every note currently held.\nfunc notesBytes() int {\n\tn := 0\n\tfor _, v := range notes.Entries() {\n\t\tn += len(v.(string))\n\t}\n\treturn n\n}\n\n// renderChain is everything that moves: the height, and the links built from\n// it. Kept off the root view so the root can be pinned by an example.\nfunc renderChain() string {\n\ts := config.Scanner()\n\th := runtime.ChainHeight()\n\n\tvar b strings.Builder\n\tb.WriteString(md.H2(\"Live\"))\n\tb.WriteString(\"\\n\")\n\n\tt := ui.NewTable(\"what\", \"value\")\n\tt.Row(\"chain id\", ui.Cell(runtime.ChainID()))\n\tt.Row(\"height\", strconv.FormatInt(h, 10))\n\tt.Row(\"explorer\", ui.Cell(s.Base()))\n\tt.Row(\"network\", ui.Cell(s.Network()))\n\tb.WriteString(t.String())\n\tb.WriteString(\"\\n\")\n\n\t// mygnoscan.Link used directly, rather than through config, to show that\n\t// the builder is an ordinary value: config only decides where it points.\n\tb.WriteString(md.BulletList([]string{\n\t\tmygnoscan.Link(\"this block\", s.Block(h)),\n\t\tmygnoscan.Link(\"this realm's transactions\", s.Realm(realmPath, mygnoscan.TabCalls)),\n\t\tmygnoscan.Link(\"its dependency graph\", s.Realm(realmPath, mygnoscan.TabDeps)),\n\t\tmygnoscan.Link(\"the parked deploy queue\", s.Packages(mygnoscan.PackagesInert)),\n\t}))\n\tb.WriteString(\"\\n\")\n\tb.WriteString(md.Link(\"back\", \"/r/moul/x/allinone/devtools/v0\"))\n\tb.WriteString(\"\\n\")\n\treturn b.String()\n}\n\nfunc renderNotes() string {\n\tif notes.Size() == 0 {\n\t\treturn ui.Empty(\"no notes yet\")\n\t}\n\titems := []string{}\n\tfor _, e := range notes.Entries() {\n\t\titems = append(items, e.(string))\n\t}\n\treturn md.BulletList(items)\n}\n"},{"name":"devtools_test.gno","body":"package devtools\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/fifo/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/moul/config/v1\"\n)\n\n// reset puts the realm back to a just-deployed state. Realm globals live for\n// the whole test binary and gno runs every Example AFTER every Test, so without\n// this the pinned output would depend on which tests ran before it.\nfunc reset() { notes = fifo.New(maxNotes) }\n\nfunc TestAdd(cur realm, t *testing.T) {\n\treset()\n\n\tAdd(cross(cur), \"hello\")\n\tuassert.Equal(t, 1, notes.Size())\n\tuassert.Equal(t, \"hello\", notes.Get(0).(string))\n\n\tuassert.AbortsWithMessage(t, cur, \"empty note\", func() { Add(cross(cur), \"   \") })\n\tuassert.AbortsContains(t, cur, \"note too long\", func() {\n\t\tlong := \"\"\n\t\tfor i := 0; i \u003c 201; i++ {\n\t\t\tlong += \"x\"\n\t\t}\n\t\tAdd(cross(cur), long)\n\t})\n}\n\n// TestAddEscapes is the guard that matters most in a realm anyone can write to:\n// a note is a string a caller typed, and it lands in a markdown list. Without\n// ui.Inline the first line below would close the list item and render as a\n// heading, and the second would become a link.\nfunc TestAddEscapes(cur realm, t *testing.T) {\n\treset()\n\n\tAdd(cross(cur), \"# not a heading\")\n\tAdd(cross(cur), \"[not](https://evil.example.com)\")\n\n\tfor _, got := range []string{notes.Get(0).(string), notes.Get(1).(string)} {\n\t\tuassert.False(t, got == \"# not a heading\", \"markdown survived unescaped\")\n\t\tuassert.False(t, got == \"[not](https://evil.example.com)\", \"a link survived unescaped\")\n\t}\n\tuassert.True(t, len(notes.Get(0).(string)) \u003e len(\"# not a heading\"),\n\t\t\"escaping should have added characters\")\n}\n\n// TestNotesAreBounded pins the reason fifo is here rather than a slice: storage\n// is paid for and never refunded, so a list anyone can append to needs a\n// ceiling in the type, not in a comment.\nfunc TestNotesAreBounded(cur realm, t *testing.T) {\n\treset()\n\n\tfor i := 0; i \u003c maxNotes+5; i++ {\n\t\tAdd(cross(cur), \"note \"+string(rune('a'+i)))\n\t}\n\tuassert.Equal(t, maxNotes, notes.Size(), \"the list stops growing at maxNotes\")\n\tuassert.Equal(t, maxNotes, notes.MaxSize())\n}\n\n// TestAddHonoursThePause is the whole point of importing r/moul/config: this\n// realm can be stopped from outside, by a transaction against another realm,\n// with no redeploy here. It cannot set that from this package (config has its\n// own authority), so it asserts the wiring: Add goes through the pause check\n// and passes while nothing is set.\nfunc TestAddHonoursThePause(cur realm, t *testing.T) {\n\treset()\n\tuassert.False(t, config.IsPausedFor(realmPath), \"nothing configured means running\")\n\tAdd(cross(cur), \"allowed while running\")\n\tuassert.Equal(t, 1, notes.Size())\n}\n\nfunc TestReset(cur realm, t *testing.T) {\n\treset()\n\tAdd(cross(cur), \"one\")\n\tReset(cross(cur))\n\tuassert.Equal(t, 0, notes.Size())\n}\n\n// ExampleRender pins the root view. It is free of the height and the chain id\n// on purpose: those live under :chain, so this one is stable.\nfunc ExampleRender() {\n\treset()\n\tprint(Render(\"\"))\n\t// Output:\n\t// # allinone: devtools\n\t//\n\t// Ten packages, used together rather than one at a time. [source](https://mygnoscan.moul.p2p.team/realm/r/moul/x/allinone/devtools/v0)\n\t//\n\t// ## Notes\n\t//\n\t// *no notes yet*\n\t//\n\t// - [add a note](/r/moul/x/allinone/devtools/v0$help\u0026func=Add\u0026body=hello)\n\t// - [clear them](/r/moul/x/allinone/devtools/v0$help\u0026func=Reset)\n\t// - [live chain values](/r/moul/x/allinone/devtools/v0:chain)\n\t// - [toggle the debug panel](/r/moul/x/allinone/devtools/v0:?debug=1)\n\t//\n\t// ## Who has written the most\n\t//\n\t// *No notes yet, so nobody is on the board.*\n\t//\n\t// Storage deposit for the list: **0 GNOT**\n\t//\n\t// ## What each package does here\n\t//\n\t// | package | what it contributed |\n\t// | --- | --- |\n\t// | `r/moul/config` | the notice block above, the pause guard on `Add`, and which explorer to link |\n\t// | `p/moul/mygnoscan` | the explorer routes, so a link survives a route change |\n\t// | `p/moul/debug` | the `?debug=1` panel, empty otherwise |\n\t// | `p/moul/realmpath` | splitting the render path into a view and a query |\n\t// | `p/moul/kit/ui` | escaping a caller's note, and this table |\n\t// | `p/moul/md` | every heading, link and list on the page |\n\t// | `p/moul/txlink` | the call links above, relative to this realm |\n\t// | `p/moul/fifo` | the note list, bounded so storage cannot grow forever |\n\t// | `p/moul/kit/tally` | the note leaderboard, with ties ordered by address |\n\t// | `p/moul/kit/num` | pricing the note list in GNOT instead of raw ugnot |\n}\n\n// TestBoardRanksAuthorsAndPricesTheList exercises the two kit packages this\n// realm adopted, because ExampleRender only ever sees the empty page.\nfunc TestBoardRanksAuthorsAndPricesTheList(cur realm, t *testing.T) {\n\tReset(cross(cur))\n\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAdd(cross(cur), \"one\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tAdd(cross(cur), \"two\")\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tAdd(cross(cur), \"three\")\n\n\tuassert.Equal(t, int64(2), authors.Score(alice.String()))\n\tuassert.Equal(t, int64(1), authors.Score(bob.String()))\n\tuassert.Equal(t, 1, authors.Rank(alice.String()))\n\tuassert.Equal(t, 2, authors.Rank(bob.String()))\n\n\t// \"one\"+\"two\"+\"three\" is 11 bytes at 100 ugnot each, which num renders as\n\t// GNOT rather than as 1100.\n\tout := Render(\"\")\n\tuassert.True(t, strings.Contains(out, \"0.0011 GNOT\"))\n\tuassert.True(t, strings.Contains(out, \"## Who has written the most\"))\n\n\tReset(cross(cur))\n\tuassert.Equal(t, 0, authors.Len())\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/allinone/devtools/v0\"\ngno = \"0.9\"\n\n# Redeployable by its creator. A demo's state is disposable by design: its whole\n# job is to be redeployed whenever one of the packages it shows off changes, so\n# losing the notes people left is the intended trade rather than a regret.\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/allinone/devtools\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"zz_zerowidth_test.gno","body":"package devtools\n\nimport (\n\t\"testing\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc TestZeroWidthNoteIsRefused(cur realm, t *testing.T) {\n\t// Reset, not reset: the author board is what ExampleRender would see.\n\tReset(cross(cur))\n\tfor _, s := range zwBlank {\n\t\tif revive(func() { Add(cross(cur), s) }) == nil {\n\t\t\tt.Errorf(\"Add accepted note %q, which is stored escaped as blank\", s)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif r := revive(func() { Add(cross(cur), s) }); r != nil {\n\t\t\tt.Errorf(\"Add refused note %q: %v\", s, r)\n\t\t}\n\t}\n\tif notes.Size() != len(zwOK) {\n\t\tt.Errorf(\"%d note(s), want %d\", notes.Size(), len(zwOK))\n\t}\n\t// Not deferred: a crossing call cannot be.\n\tReset(cross(cur))\n}\n"}]},"send":"","max_deposit":"9000000ugnot"}],"fee":{"gas_wanted":"65924000","gas_fee":"197772ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"tdNwGzpZjKAbK3lm2wUfYoo+cVER5n6n/2UhpcOls8Bv8eeIWyljKm4Am0EMrz1qoTO9Tv85IeXFY+FlXygfMA=="}],"memo":""},"metadata":{"timestamp":"1791963534"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"eggling","path":"gno.land/r/moul/x/daily/eggling/v1","files":[{"name":"README.md","body":"# Eggling\n\n\u003e ⚠️ **Experimental — generated with no human supervision** by the daily MCP pipeline to exercise gno tooling. Not audited. See [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md).\n\n---\n\nPlant an on-chain egg, let it incubate for at least 20 blocks, then hatch it — how long you waited plus a bit of sealed-in luck decides whether you get a Common Slime or a Legendary Glimmer. Train hatched creatures for XP and levels, and rename them once they've hatched. It's a lighter, luck-and-patience spin on yesterday's tamagotchi: no hunger or death, just the thrill of the hatch and a slow climb of levels.\n\nBuilt for gno 0.9.\n\n## What changed in v1\n\nIdentical behaviour to [`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/eggling) apart from rendering, which now goes\nthrough [`p/moul/kit/ui`](/p/moul/kit/ui/v0) instead of the local `escapeInline`, `shortAddr` helpers.\n\n**One address format.** Eleven realms carried their own `shortAddr` with four different truncation rules, so the same account rendered differently depending on which realm you opened. `ui.Addr` is that decision made once: 8 leading characters, an ellipsis, 4 trailing, in backticks.\n\n**Real escaping.** The local helper replaced a handful of markdown metacharacters. `ui.Inline` and `ui.Cell` delegate to [`p/nt/markdown/sanitize`](/p/nt/markdown/sanitize/v0), which also strips bidi and zero-width characters and folds newlines, so user text cannot reorder or escape the line it sits on.\n\nThe rendering change means the output differs from v0, which under this repo's versioning rule is a compatibility change, hence a new version rather than an edit in place. `v0` stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/eggling/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/eggling/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/eggling/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/eggling/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"eggling.gno","body":"// Package eggling is an on-chain egg incubator and creature collector.\n// Plant an egg, let it incubate for a minimum number of blocks, then Hatch\n// it: the longer you waited (and a little luck, seeded from the egg's own\n// history) decides the rarity of the creature you get. Train hatched\n// creatures to level them up. Unlike a tamagotchi there's nothing to feed\n// or lose to neglect — eggling is about patience and the luck of the\n// hatch, not survival.\npackage eggling\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/ui/v0\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n// minIncubation is the minimum number of blocks an egg must sit before it\n// can hatch.\nconst minIncubation int64 = 20\n\n// waitCap is the incubation-time bonus cap (in blocks) used by rarityTier,\n// so waiting forever doesn't guarantee a legendary — it just improves odds.\nconst waitCap int64 = 200\n\nvar speciesNames = [...]string{\n\t\"Slime\", \"Sprout\", \"Ember\", \"Pebble\", \"Breeze\", \"Glimmer\", \"Shade\", \"Coral\",\n}\n\nvar rarityNames = [...]string{\"Common\", \"Uncommon\", \"Rare\", \"Legendary\"}\nvar rarityEmoji = [...]string{\"⚪\", \"🟢\", \"🔵\", \"🟡\"}\n\n// egg is the persisted record for one planted egg, hatched or not.\ntype egg struct {\n\tID         string\n\tOwner      address\n\tPlantedAt  int64\n\tHatched    bool\n\tSpecies    string\n\tRarityTier int\n\tName       string\n\tXP         int\n\tLevel      int\n}\n\nvar (\n\teggs         avl.Tree // id string -\u003e *egg\n\tnextID       int\n\ttotalPlanted int\n\ttotalHatched int\n\trarityCounts [4]int\n)\n\nfunc get(id string) (*egg, bool) {\n\tv := eggs.Get(id)\n\tif v == nil {\n\t\treturn nil, false\n\t}\n\treturn v.(*egg), true\n}\n\n// hashSeed hashes the given parts (joined with \":\") to a deterministic hex\n// digest. Used to derive an egg's species and rarity roll from facts\n// already fixed at plant time, so nobody — not even the owner — can game\n// the outcome after the fact.\nfunc hashSeed(parts ...string) string {\n\tsum := sha256.Sum256([]byte(strings.Join(parts, \":\")))\n\treturn hex.EncodeToString(sum[:])\n}\n\n// seedBytes pulls the first two bytes out of a hex digest for use as two\n// independent 0-255 rolls (species pick, rarity roll).\nfunc seedBytes(seedHex string) (byte, byte) {\n\traw, err := hex.DecodeString(seedHex)\n\tif err != nil || len(raw) \u003c 2 {\n\t\treturn 0, 0\n\t}\n\treturn raw[0], raw[1]\n}\n\n// rarityTier turns a 0-255 roll plus the blocks waited into a tier index\n// 0..3 (common..legendary). Waiting longer raises the effective score, so\n// patience improves your odds, but a bad roll can still land common even\n// after a long wait, and a lucky roll can hatch rare almost immediately.\nfunc rarityTier(roll uint8, waitBlocks int64) int {\n\tbonus := waitBlocks\n\tif bonus \u003e waitCap {\n\t\tbonus = waitCap\n\t}\n\tscore := int(roll) + int(bonus)/2\n\tswitch {\n\tcase score \u003e= 300:\n\t\treturn 3\n\tcase score \u003e= 220:\n\t\treturn 2\n\tcase score \u003e= 140:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n// plant is the non-crossing core of PlantEgg.\nfunc plant(owner address, height int64) *egg {\n\tnextID++\n\tid := strconv.Itoa(nextID)\n\te := \u0026egg{ID: id, Owner: owner, PlantedAt: height}\n\teggs.Set(id, e)\n\ttotalPlanted++\n\treturn e\n}\n\n// PlantEgg starts incubating a new egg for the caller. Returns its ID.\nfunc PlantEgg(cur realm) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te := plant(cur.Previous().Address(), runtime.ChainHeight())\n\treturn \"🥚 planted egg #\" + e.ID + \" — incubate at least \" +\n\t\tstrconv.Itoa(int(minIncubation)) + \" blocks, then Hatch(\\\"\" + e.ID + \"\\\")\"\n}\n\n// hatch is the non-crossing core of Hatch.\nfunc hatch(e *egg, height int64) string {\n\tif e.Hatched {\n\t\tpanic(\"egg #\" + e.ID + \" already hatched into a \" + e.Species)\n\t}\n\twait := height - e.PlantedAt\n\tif wait \u003c minIncubation {\n\t\tpanic(\"egg #\" + e.ID + \" needs \" + strconv.Itoa(int(minIncubation-wait)) + \" more blocks to incubate\")\n\t}\n\n\tseed := hashSeed(e.ID, e.Owner.String(), strconv.FormatInt(e.PlantedAt, 10))\n\trarityRoll, speciesRoll := seedBytes(seed)\n\ttier := rarityTier(rarityRoll, wait)\n\tspecies := speciesNames[int(speciesRoll)%len(speciesNames)]\n\n\te.Hatched = true\n\te.Species = species\n\te.RarityTier = tier\n\te.Name = species\n\te.Level = 1\n\trarityCounts[tier]++\n\ttotalHatched++\n\n\treturn rarityEmoji[tier] + \" egg #\" + e.ID + \" hatched into a \" + rarityNames[tier] + \" \" + species + \"!\"\n}\n\n// Hatch hatches an incubated egg the caller owns.\nfunc Hatch(cur realm, id string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te, ok := get(id)\n\tif !ok {\n\t\tpanic(\"no such egg #\" + id)\n\t}\n\tif e.Owner != cur.Previous().Address() {\n\t\tpanic(\"only the owner can hatch egg #\" + id)\n\t}\n\treturn hatch(e, runtime.ChainHeight())\n}\n\n// train is the non-crossing core of Train.\nfunc train(e *egg) string {\n\tif !e.Hatched {\n\t\tpanic(\"egg #\" + e.ID + \" hasn't hatched yet\")\n\t}\n\te.XP += 10\n\tnewLevel := e.XP/50 + 1\n\tleveled := newLevel \u003e e.Level\n\te.Level = newLevel\n\n\tmsg := e.Name + \" gained 10 XP (\" + strconv.Itoa(e.XP) + \" total)\"\n\tif leveled {\n\t\tmsg += \" and reached level \" + strconv.Itoa(e.Level) + \"!\"\n\t}\n\treturn msg\n}\n\n// Train gives a hatched creature the caller owns some experience, leveling\n// it up every 50 XP.\nfunc Train(cur realm, id string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te, ok := get(id)\n\tif !ok {\n\t\tpanic(\"no such egg #\" + id)\n\t}\n\tif e.Owner != cur.Previous().Address() {\n\t\tpanic(\"only the owner can train egg #\" + id)\n\t}\n\treturn train(e)\n}\n\n// rename is the non-crossing core of Rename.\nfunc rename(e *egg, name string) string {\n\tif !e.Hatched {\n\t\tpanic(\"egg #\" + e.ID + \" hasn't hatched yet — nothing to name\")\n\t}\n\tname = strings.TrimSpace(name)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(name)) == \"\" {\n\t\tpanic(\"name cannot be empty\")\n\t}\n\told := e.Name\n\te.Name = name\n\treturn old + \" renamed to \" + name\n}\n\n// Rename gives a hatched creature the caller owns a custom name.\nfunc Rename(cur realm, id string, name string) string {\n\tif !cur.IsCurrent() {\n\t\tpanic(\"spoofed realm\")\n\t}\n\te, ok := get(id)\n\tif !ok {\n\t\tpanic(\"no such egg #\" + id)\n\t}\n\tif e.Owner != cur.Previous().Address() {\n\t\tpanic(\"only the owner can rename egg #\" + id)\n\t}\n\treturn rename(e, name)\n}\n\n// byIDNumeric orders eggs by their numeric ID, ascending.\ntype byIDNumeric []*egg\n\nfunc (r byIDNumeric) Len() int      { return len(r) }\nfunc (r byIDNumeric) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byIDNumeric) Less(i, j int) bool {\n\ta, _ := strconv.Atoi(r[i].ID)\n\tb, _ := strconv.Atoi(r[j].ID)\n\treturn a \u003c b\n}\n\nfunc allEggs() []*egg {\n\tvar rows []*egg\n\teggs.Iterate(\"\", \"\", func(_ string, v any) bool {\n\t\trows = append(rows, v.(*egg))\n\t\treturn false\n\t})\n\tsort.Stable(byIDNumeric(rows))\n\treturn rows\n}\n\nfunc renderHome() string {\n\tvar b strings.Builder\n\tb.WriteString(\"# 🥚 Eggling\\n\\n\")\n\tb.WriteString(\"An on-chain egg incubator. `PlantEgg()` to start one, wait at least \" +\n\t\tstrconv.Itoa(int(minIncubation)) + \" blocks, then `Hatch(id)` — the longer you \" +\n\t\t\"waited (plus a little sealed-in luck) decides the rarity of the creature you get. \" +\n\t\t\"`Train(id)` levels a hatched creature up; `Rename(id, name)` gives it a name.\\n\\n\")\n\n\tb.WriteString(\"- Eggs planted: \" + strconv.Itoa(totalPlanted) + \"\\n\")\n\tb.WriteString(\"- Creatures hatched: \" + strconv.Itoa(totalHatched) + \"\\n\")\n\tif totalHatched \u003e 0 {\n\t\tfor tier := 3; tier \u003e= 0; tier-- {\n\t\t\tif rarityCounts[tier] \u003e 0 {\n\t\t\t\tb.WriteString(\"  - \" + rarityEmoji[tier] + \" \" + rarityNames[tier] + \": \" +\n\t\t\t\t\tstrconv.Itoa(rarityCounts[tier]) + \"\\n\")\n\t\t\t}\n\t\t}\n\t}\n\n\trows := allEggs()\n\tb.WriteString(\"\\n## Eggs\\n\\n\")\n\tif len(rows) == 0 {\n\t\tb.WriteString(\"_None planted yet. Be the first!_\\n\")\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"| ID | Owner | Status | Level |\\n\")\n\tb.WriteString(\"| :--- | :--- | :--- | ---: |\\n\")\n\tfor _, e := range rows {\n\t\tstatus := \"🥚 incubating\"\n\t\tlevel := \"-\"\n\t\tif e.Hatched {\n\t\t\tstatus = rarityEmoji[e.RarityTier] + \" \" + ui.Inline(e.Name) + \" (\" + rarityNames[e.RarityTier] + \" \" + e.Species + \")\"\n\t\t\tlevel = strconv.Itoa(e.Level)\n\t\t}\n\t\tb.WriteString(\"| #\" + e.ID + \" | \" + ui.Addr(e.Owner) + \" | \" + status + \" | \" + level + \" |\\n\")\n\t}\n\tb.WriteString(\"\\n_View a single egg at this realm's path plus its ID (e.g. `.../eggling:3`), \" +\n\t\t\"or one owner's eggs plus their address._\\n\")\n\treturn b.String()\n}\n\nfunc renderEgg(id string, height int64) string {\n\te, ok := get(id)\n\tif !ok {\n\t\treturn \"# Egg #\" + ui.Inline(id) + \"\\n\\nNo such egg.\\n\"\n\t}\n\n\tvar b strings.Builder\n\tif !e.Hatched {\n\t\twait := height - e.PlantedAt\n\t\tb.WriteString(\"# 🥚 Egg #\" + e.ID + \"\\n\\n\")\n\t\tb.WriteString(\"- Owner: `\" + e.Owner.String() + \"`\\n\")\n\t\tb.WriteString(\"- Planted at block: \" + strconv.FormatInt(e.PlantedAt, 10) + \"\\n\")\n\t\tif wait \u003c minIncubation {\n\t\t\tb.WriteString(\"- Ready to hatch in: \" + strconv.FormatInt(minIncubation-wait, 10) + \" more blocks\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"- Ready to hatch now — call `Hatch(\\\"\" + e.ID + \"\\\")`\\n\")\n\t\t}\n\t\treturn b.String()\n\t}\n\n\tb.WriteString(\"# \" + rarityEmoji[e.RarityTier] + \" \" + e.Name + \"\\n\\n\")\n\tb.WriteString(\"- Owner: `\" + e.Owner.String() + \"`\\n\")\n\tb.WriteString(\"- Species: \" + e.Species + \"\\n\")\n\tb.WriteString(\"- Rarity: \" + rarityNames[e.RarityTier] + \"\\n\")\n\tb.WriteString(\"- Level: \" + strconv.Itoa(e.Level) + \" (\" + strconv.Itoa(e.XP) + \" XP)\\n\")\n\treturn b.String()\n}\n\nfunc renderOwner(rawAddr string) string {\n\towner := address(strings.TrimSpace(rawAddr))\n\tsafe := ui.Inline(owner.String())\n\n\tvar b strings.Builder\n\tb.WriteString(\"# Eggs owned by \" + safe + \"\\n\\n\")\n\n\tfound := false\n\tfor _, e := range allEggs() {\n\t\tif e.Owner != owner {\n\t\t\tcontinue\n\t\t}\n\t\tfound = true\n\t\tif e.Hatched {\n\t\t\tb.WriteString(\"- #\" + e.ID + \": \" + rarityEmoji[e.RarityTier] + \" \" + ui.Inline(e.Name) +\n\t\t\t\t\" — \" + rarityNames[e.RarityTier] + \" \" + e.Species + \", level \" + strconv.Itoa(e.Level) + \"\\n\")\n\t\t} else {\n\t\t\tb.WriteString(\"- #\" + e.ID + \": 🥚 incubating\\n\")\n\t\t}\n\t}\n\tif !found {\n\t\tb.WriteString(\"_No eggs found for this address._\\n\")\n\t}\n\treturn b.String()\n}\n\n// Render shows the full egg list at \"\", a single egg's detail when path is\n// a numeric ID, or one owner's eggs when path is a bech32 address.\nfunc Render(path string) string {\n\tpath = strings.TrimPrefix(strings.TrimSpace(path), \"/\")\n\tif path == \"\" {\n\t\treturn renderHome()\n\t}\n\tif _, err := strconv.Atoi(path); err == nil {\n\t\treturn renderEgg(path, runtime.ChainHeight())\n\t}\n\treturn renderOwner(path)\n}\n"},{"name":"eggling_test.gno","body":"package eggling\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc resetState() {\n\teggs = avl.Tree{}\n\tnextID = 0\n\ttotalPlanted = 0\n\ttotalHatched = 0\n\trarityCounts = [4]int{}\n}\n\nfunc TestHashSeedDeterministicAndSensitive(t *testing.T) {\n\ta := hashSeed(\"1\", \"g1alice\", \"100\")\n\tb := hashSeed(\"1\", \"g1alice\", \"100\")\n\tif a != b {\n\t\tt.Fatal(\"hashSeed should be deterministic for the same inputs\")\n\t}\n\tif a == hashSeed(\"2\", \"g1alice\", \"100\") {\n\t\tt.Fatal(\"different egg IDs should hash differently\")\n\t}\n\tif len(a) != 64 {\n\t\tt.Fatalf(\"hashSeed length = %d, want 64 (hex sha256)\", len(a))\n\t}\n}\n\nfunc TestSeedBytesFromKnownDigest(t *testing.T) {\n\t// sha256(\"\") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n\tr1, r2 := seedBytes(hashSeed(\"\"))\n\tif r1 != 0xe3 || r2 != 0xb0 {\n\t\tt.Fatalf(\"seedBytes = (%x, %x), want (e3, b0)\", r1, r2)\n\t}\n}\n\nfunc TestRarityTierBoundaries(t *testing.T) {\n\tcases := []struct {\n\t\troll uint8\n\t\twait int64\n\t\twant int\n\t}{\n\t\t{0, 0, 0},     // score 0 -\u003e common\n\t\t{139, 0, 0},   // score 139 -\u003e common\n\t\t{140, 0, 1},   // score 140 -\u003e uncommon\n\t\t{219, 0, 1},   // score 219 -\u003e uncommon\n\t\t{220, 0, 2},   // score 220 -\u003e rare\n\t\t{255, 0, 2},   // score 255 -\u003e rare (no wait bonus)\n\t\t{255, 200, 3}, // score 355 -\u003e legendary (max wait bonus)\n\t\t{0, 200, 0},   // score 100 -\u003e still common, roll matters too\n\t}\n\tfor _, c := range cases {\n\t\tif got := rarityTier(c.roll, c.wait); got != c.want {\n\t\t\tt.Fatalf(\"rarityTier(%d, %d) = %d, want %d\", c.roll, c.wait, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestRarityTierCapsWaitBonus(t *testing.T) {\n\t// waitCap is 200; waiting 1000 blocks should score identically to\n\t// waiting exactly 200.\n\tif rarityTier(50, 1000) != rarityTier(50, 200) {\n\t\tt.Fatal(\"rarityTier should cap the wait bonus at waitCap\")\n\t}\n}\n\nfunc TestPlantAssignsSequentialIDs(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te1 := plant(alice, 100)\n\te2 := plant(alice, 101)\n\tif e1.ID != \"1\" || e2.ID != \"2\" {\n\t\tt.Fatalf(\"expected sequential IDs 1, 2; got %s, %s\", e1.ID, e2.ID)\n\t}\n\tif totalPlanted != 2 {\n\t\tt.Fatalf(\"totalPlanted = %d, want 2\", totalPlanted)\n\t}\n}\n\nfunc TestHatchTooEarlyPanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic hatching before minIncubation blocks pass\")\n\t\t}\n\t}()\n\thatch(e, 100+minIncubation-1)\n}\n\nfunc TestHatchTwicePanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic hatching an already-hatched egg\")\n\t\t}\n\t}()\n\thatch(e, 100+minIncubation)\n}\n\nfunc TestHatchSetsSpeciesAndCountsStats(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\tif !e.Hatched {\n\t\tt.Fatal(\"expected egg to be hatched\")\n\t}\n\tif e.Species == \"\" {\n\t\tt.Fatal(\"expected a species to be assigned\")\n\t}\n\tif e.Level != 1 {\n\t\tt.Fatalf(\"expected level 1 on hatch, got %d\", e.Level)\n\t}\n\tif totalHatched != 1 {\n\t\tt.Fatalf(\"totalHatched = %d, want 1\", totalHatched)\n\t}\n\tif rarityCounts[e.RarityTier] != 1 {\n\t\tt.Fatalf(\"expected rarityCounts[%d] = 1, got %d\", e.RarityTier, rarityCounts[e.RarityTier])\n\t}\n}\n\nfunc TestTrainBeforeHatchPanics(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic training an unhatched egg\")\n\t\t}\n\t}()\n\ttrain(e)\n}\n\nfunc TestTrainAccumulatesXPAndLevelsUp(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\tfor i := 0; i \u003c 5; i++ {\n\t\ttrain(e)\n\t}\n\tif e.XP != 50 {\n\t\tt.Fatalf(\"XP = %d, want 50\", e.XP)\n\t}\n\tif e.Level != 2 {\n\t\tt.Fatalf(\"Level = %d, want 2\", e.Level)\n\t}\n}\n\nfunc TestRenameRequiresHatchedAndNonEmpty(t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Fatal(\"expected panic renaming an unhatched egg\")\n\t\t\t}\n\t\t}()\n\t\trename(e, \"Sparky\")\n\t}()\n\n\thatch(e, 100+minIncubation)\n\trename(e, \"Sparky\")\n\tif e.Name != \"Sparky\" {\n\t\tt.Fatalf(\"Name = %q, want Sparky\", e.Name)\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Fatal(\"expected panic renaming with an empty name\")\n\t\t}\n\t}()\n\trename(e, \"   \")\n}\n\nfunc TestRenderShowsEmptyThenEggThenOwner(t *testing.T) {\n\tresetState()\n\tif !strings.Contains(Render(\"\"), \"None planted yet\") {\n\t\tt.Fatal(\"expected empty-state placeholder\")\n\t}\n\n\talice := testutils.TestAddress(\"alice\")\n\te := plant(alice, 100)\n\thatch(e, 100+minIncubation)\n\n\thome := Render(\"\")\n\tif !strings.Contains(home, \"#\"+e.ID) {\n\t\tt.Fatal(\"expected egg row in home listing\")\n\t}\n\n\tdetail := Render(e.ID)\n\tif !strings.Contains(detail, \"Rarity\") {\n\t\tt.Fatal(\"expected detail card to show rarity\")\n\t}\n\n\towned := Render(alice.String())\n\tif !strings.Contains(owned, e.Name) {\n\t\tt.Fatal(\"expected owner view to list the creature by name\")\n\t}\n}\n\n// TestFullLifecycleViaCrossingCalls smoke-tests the exported, realm-crossing\n// entry points end to end (as an on-chain caller would invoke them).\nfunc TestFullLifecycleViaCrossingCalls(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tmsg := PlantEgg(cross(cur))\n\tif !strings.Contains(msg, \"planted egg #1\") {\n\t\tt.Fatalf(\"expected plant confirmation, got %q\", msg)\n\t}\n\n\ttesting.SkipHeights(minIncubation)\n\n\thatchMsg := Hatch(cross(cur), \"1\")\n\tif !strings.Contains(hatchMsg, \"hatched into a\") {\n\t\tt.Fatalf(\"expected hatch confirmation, got %q\", hatchMsg)\n\t}\n\n\ttrainMsg := Train(cross(cur), \"1\")\n\tif !strings.Contains(trainMsg, \"gained 10 XP\") {\n\t\tt.Fatalf(\"expected train confirmation, got %q\", trainMsg)\n\t}\n\n\trenameMsg := Rename(cross(cur), \"1\", \"Buddy\")\n\tif !strings.Contains(renameMsg, \"renamed to Buddy\") {\n\t\tt.Fatalf(\"expected rename confirmation, got %q\", renameMsg)\n\t}\n\n\te, ok := get(\"1\")\n\tif !ok || e.Name != \"Buddy\" || e.XP != 10 {\n\t\tt.Fatalf(\"unexpected final state: %+v\", e)\n\t}\n}\n\n// TestOnlyOwnerCanHatch checks that another address can't hatch someone\n// else's egg.\nfunc TestOnlyOwnerCanHatch(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tPlantEgg(cross(cur))\n\ttesting.SkipHeights(minIncubation)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\trec := revive(func() { Hatch(cross(cur), \"1\") })\n\tif rec == nil {\n\t\tt.Fatal(\"expected panic hatching someone else's egg\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/eggling/v1\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/daily/eggling\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"zz_zerowidth_test.gno","body":"package eggling\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc zwPanics(f func()) (p bool) {\n\tdefer func() {\n\t\tif recover() != nil {\n\t\t\tp = true\n\t\t}\n\t}()\n\tf()\n\treturn false\n}\n\nfunc TestZeroWidthNameIsRefused(t *testing.T) {\n\tresetState()\n\tdefer resetState()\n\te := plant(testutils.TestAddress(\"alice\"), 100)\n\thatch(e, 100+minIncubation)\n\trename(e, \"Sparky\")\n\tfor _, s := range zwBlank {\n\t\tif !zwPanics(func() { rename(e, s) }) {\n\t\t\tt.Errorf(\"rename accepted name %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tif e.Name != \"Sparky\" {\n\t\tt.Fatalf(\"Name = %q after blank renames, want Sparky\", e.Name)\n\t}\n\tfor _, s := range zwOK {\n\t\tif zwPanics(func() { rename(e, s) }) {\n\t\t\tt.Errorf(\"rename refused name %q, which renders as text\", s)\n\t\t}\n\t}\n}\n"}]},"send":"","max_deposit":"9000000ugnot"}],"fee":{"gas_wanted":"69114200","gas_fee":"207342ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"Ltx7/wOTXECxSciO8NTlQ6b/FMwe+RKO8TTfTfzWuCE9NebNnkfKtTtbuIQfKYAJibbROhNGX/ON+QdW0l7IHw=="}],"memo":""},"metadata":{"timestamp":"1791963535"}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1ehcdua2lfmd9k5e0qmh3vq27ya68q8c59s6v5u","package":{"name":"timecapsule","path":"gno.land/r/moul/x/daily/timecapsule/v1","files":[{"name":"README.md","body":"# Time Capsule Guestbook\n\n\u003e ⚠️ **Experimental — generated with no human supervision.** This realm was\n\u003e produced automatically by an MCP-driven agent to exercise the gno MCP server\n\u003e and tooling, and to generate test content for gno compilers, linters and\n\u003e formatters. **Not audited. Not for production.** Full context \u0026 folder README:\n\u003e [r/moul/x/daily](https://github.com/moul/gno-contracts/blob/main/r/moul/x/daily/README.md)\n\n---\n\n\nA public guestbook with a twist: every message is sealed until a future block\nheight, chosen by its author when they leave it. Until then it's just a locked\nentry showing who sealed it and when it opens; once the chain reaches that\nheight, the message unlocks forever for anyone to read.\n\nRealm: `gno.land/r/g12cs4cehujpffpjpywmkqj43m6u5ya53nj69sjz/timecapsule`\n\n## Example calls\n\n- `Leave(\"see you in 100 blocks\", 100)` — seal a message that opens 100 blocks\n  from now. Returns the capsule id. Only direct EOA (`MsgCall`) calls can seal\n  one; empty messages, messages over 500 bytes, and delays outside\n  `(0, 1_000_000]` blocks are rejected.\n- `Render(\"\")` — home page: counts + every already-unlocked message.\n- `Render(\"sealed\")` — every still-sealed capsule with its unlock height and\n  blocks remaining (message hidden).\n- `Render(\"capsule/\u003cid\u003e\")` — a single capsule's detail page; shows the message\n  only once unlocked.\n\n## Toolchain status\n\nTested locally against a `gnolang/gno` master checkout (`~/p/gh/gnoland/gno`)\nusing its own `gno` binary as GNOROOT, resolving `/p/nt/*` deps through its\n`examples/` workspace. All 5 unit tests pass (`gno test -v .`), and `gno lint .`\nreports no issues. This is newer than sapphire (gno 0.9), but the code only uses\nAPIs documented as current in the project's gno skill (`chain`, `chain/runtime`,\n`gno.land/p/nt/avl/v0`, `gno.land/p/nt/markdown/sanitize/v0`), so it should be\non-chain-valid for sapphire as well.\n\n## What changed in v1\n\nState moved from a hand-rolled `avl.Tree` + `nextID` + zero-padding helper to\n[`p/moul/kit/store`](/p/moul/kit/store/v0), which keys entries by\n[`seqid`](/p/nt/seqid/v0) instead of a fixed-width decimal string.\n\nv0 padded ids to width 12. Past that width the padding stops and the tree\norders `\"1000000000000\"` before `\"999999999999\"`, so every list this realm\nrenders would be wrong from that entry on. `store` keys are 8 big-endian bytes\nwhose order is numeric for every `uint64`, so there is no width left to outgrow.\n\n`capsule` loses its `id` field, which the store now owns, and **capsule ids\nstart at 1** where `v0` handed out 0 for the first one. `capsule/0` is now\nrejected as an invalid id rather than looked up.\n\nThis is a storage change, which under this repo's versioning rule is a\ncompatibility change, hence a new version rather than an edit in place.\n[`v0`](https://github.com/moul/gno-contracts/tree/4f2df83869b80470eb81c48a82fdbe82256b8113/r/moul/x/daily/timecapsule) stays live and untouched.\n\n\u003c!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --\u003e\n\n---\n\nPart of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.\n\n**On mainnet:** [![deployment status](https://gnoscope.com/_badges/shield/status/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1) [![transactions](https://gnoscope.com/_badges/shield/txs/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1) [![unique callers](https://gnoscope.com/_badges/shield/users/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1) [![deployed revision](https://gnoscope.com/_badges/shield/version/r/moul/x/daily/timecapsule/v1?network=mainnet)](https://gnoscope.com/realm/r/moul/x/daily/timecapsule/v1)\n\n**Dependency graph:**\n\n![gno.land/r/moul/x/daily/timecapsule/v1 dependency graph](https://raw.githubusercontent.com/moul/gno-contracts/main/_assets/gno.land/r/moul/x/daily/timecapsule/v1/deps.png)\n\n\u003e 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md).\n\n\u003c!-- END GNOCONTRACTS FOOTER --\u003e\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/moul/x/daily/timecapsule/v1\"\ngno = \"0.9\"\nprivate = true\n\n[source]\n  repository = \"https://github.com/moul/gno-contracts\"\n  path = \"r/moul/x/daily/timecapsule\"\n  revision = \"83c8b0d6b1fc181ecdfc819f9c672476af26c7e7\"\n"},{"name":"render_example_test.gno","body":"package timecapsule\n\n// ExampleRender pins the realm's Render output as a testable example.\nfunc ExampleRender() {\n\tprint(Render(\"\"))\n\t// Output:\n\t// # ⏳ Time Capsule Guestbook\n\t//\n\t// Leave a message for the future. It stays sealed until its unlock block height, then anyone can read it — call `Leave(message, delayBlocks)`.\n\t//\n\t// 0 capsule(s) total · 0 unlocked · 0 still sealed.\n\t//\n\t// ## Unlocked messages\n\t//\n\t// _None yet. Be the first to leave one that will open later._\n}\n"},{"name":"timecapsule.gno","body":"// Package timecapsule is a public guestbook where every message is sealed\n// until a future block height, then permanently unlocked for anyone to read.\npackage timecapsule\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"chain\"\n\t\"chain/markdown\"\n\t\"chain/runtime\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\n// capsule carries no id field: the id belongs to the store, which hands it\n// back on lookup and iteration.\ntype capsule struct {\n\tauthor       address\n\tmessage      string\n\tcreatedAt    int64\n\tunlockHeight int64\n}\n\n// capsules assigns the capsule ids. v0 kept its own nextID plus an idKey()\n// that called strings.Repeat WITHOUT the length guard the other realms had, so\n// at the 10^12th capsule it did not mis-sort, it panicked: Repeat rejects a\n// negative count, and the realm would have stopped accepting Leave calls. The\n// store key is 8 fixed bytes with no width to outgrow.\nvar capsules = store.Named(\"capsule\")\n\nconst (\n\tmaxDelayBlocks int64 = 1_000_000\n\tmaxMessageLen  int   = 500\n)\n\n// Leave seals a new message that stays hidden until `delayBlocks` blocks\n// from now, then becomes publicly readable forever. Returns the capsule id.\nfunc Leave(cur realm, message string, delayBlocks int64) int64 {\n\tif !cur.Previous().IsUserCall() {\n\t\tpanic(\"only direct user calls can leave a capsule\")\n\t}\n\n\tmessage = strings.TrimSpace(message)\n\tif strings.TrimSpace(markdown.StripBidiAndZeroWidth(message)) == \"\" {\n\t\tpanic(\"message must not be empty\")\n\t}\n\tif len(message) \u003e maxMessageLen {\n\t\tpanic(\"message too long\")\n\t}\n\tif delayBlocks \u003c= 0 || delayBlocks \u003e maxDelayBlocks {\n\t\tpanic(\"delayBlocks out of range\")\n\t}\n\n\tnow := runtime.ChainHeight()\n\tc := \u0026capsule{\n\t\tauthor:       cur.Previous().Address(),\n\t\tmessage:      message,\n\t\tcreatedAt:    now,\n\t\tunlockHeight: now + delayBlocks,\n\t}\n\tid := capsules.Add(c)\n\n\tchain.Emit(\"CapsuleSealed\",\n\t\t\"id\", id.String(),\n\t\t\"unlockHeight\", strconv.FormatInt(c.unlockHeight, 10),\n\t)\n\treturn int64(id)\n}\n\nfunc Render(path string) string {\n\tswitch {\n\tcase path == \"\":\n\t\treturn renderHome()\n\tcase path == \"sealed\":\n\t\treturn renderSealed()\n\tcase strings.HasPrefix(path, \"capsule/\"):\n\t\treturn renderCapsule(strings.TrimPrefix(path, \"capsule/\"))\n\tdefault:\n\t\treturn \"\u003e [!WARNING]\\n\u003e Path not found\\n\"\n\t}\n}\n\nfunc renderHome() string {\n\tnow := runtime.ChainHeight()\n\n\trevealed := 0\n\tsealed := 0\n\tcapsules.Each(func(_ store.ID, value any) {\n\t\tif value.(*capsule).unlockHeight \u003c= now {\n\t\t\trevealed++\n\t\t} else {\n\t\t\tsealed++\n\t\t}\n\t})\n\n\tvar out strings.Builder\n\tout.WriteString(\"# ⏳ Time Capsule Guestbook\\n\\n\")\n\tout.WriteString(\"Leave a message for the future. It stays sealed until its unlock block height, then anyone can read it — call `Leave(message, delayBlocks)`.\\n\\n\")\n\tout.WriteString(strconv.Itoa(revealed+sealed) + \" capsule(s) total · \" +\n\t\tstrconv.Itoa(revealed) + \" unlocked · \" + strconv.Itoa(sealed) + \" still sealed\")\n\tif sealed \u003e 0 {\n\t\tout.WriteString(\" (see [sealed](sealed))\")\n\t}\n\tout.WriteString(\".\\n\\n## Unlocked messages\\n\\n\")\n\n\tif revealed == 0 {\n\t\tout.WriteString(\"_None yet. Be the first to leave one that will open later._\\n\")\n\t\treturn out.String()\n\t}\n\n\tcapsules.Each(func(id store.ID, value any) {\n\t\tc := value.(*capsule)\n\t\tif c.unlockHeight \u003c= now {\n\t\t\tout.WriteString(renderEntry(id, c))\n\t\t}\n\t})\n\treturn out.String()\n}\n\nfunc renderSealed() string {\n\tnow := runtime.ChainHeight()\n\n\tvar out strings.Builder\n\tout.WriteString(\"# Sealed Capsules\\n\\n\")\n\n\tfound := false\n\tcapsules.Each(func(id store.ID, value any) {\n\t\tc := value.(*capsule)\n\t\tif c.unlockHeight \u003e now {\n\t\t\tfound = true\n\t\t\tout.WriteString(\"- capsule [#\" + id.String() + \"](capsule/\" +\n\t\t\t\tid.String() + \") by `\" + c.author.String() +\n\t\t\t\t\"` — unlocks at block \" + strconv.FormatInt(c.unlockHeight, 10) +\n\t\t\t\t\" (\" + strconv.FormatInt(c.unlockHeight-now, 10) + \" blocks left)\\n\")\n\t\t}\n\t})\n\tif !found {\n\t\tout.WriteString(\"_No sealed capsules right now._\\n\")\n\t}\n\treturn out.String()\n}\n\nfunc renderCapsule(idStr string) string {\n\tid, ok := store.ParseID(idStr)\n\tif !ok {\n\t\treturn \"\u003e [!WARNING]\\n\u003e Invalid capsule id\\n\"\n\t}\n\tv, ok := capsules.Get(id)\n\tif !ok {\n\t\treturn \"\u003e [!WARNING]\\n\u003e Capsule not found\\n\"\n\t}\n\tc := v.(*capsule)\n\tnow := runtime.ChainHeight()\n\n\tvar out strings.Builder\n\tout.WriteString(\"# Capsule #\" + id.String() + \"\\n\\n\")\n\tout.WriteString(\"Sealed by `\" + c.author.String() + \"` at block \" + strconv.FormatInt(c.createdAt, 10) + \".\\n\\n\")\n\n\tif c.unlockHeight \u003e now {\n\t\tout.WriteString(\"\\U0001f512 Still sealed. Unlocks at block \" + strconv.FormatInt(c.unlockHeight, 10) +\n\t\t\t\" (\" + strconv.FormatInt(c.unlockHeight-now, 10) + \" blocks left).\\n\")\n\t\treturn out.String()\n\t}\n\n\tout.WriteString(\"\\U0001f513 Unlocked at block \" + strconv.FormatInt(c.unlockHeight, 10) + \":\\n\\n\u003e \" +\n\t\tsanitize.InlineText(c.message) + \"\\n\")\n\treturn out.String()\n}\n\nfunc renderEntry(id store.ID, c *capsule) string {\n\treturn \"- **#\" + id.String() + \"** by `\" + c.author.String() +\n\t\t\"` (sealed at block \" + strconv.FormatInt(c.createdAt, 10) +\n\t\t\", opened at block \" + strconv.FormatInt(c.unlockHeight, 10) + \"):\\n  \u003e \" +\n\t\tsanitize.InlineText(c.message) + \"\\n\\n\"\n}\n"},{"name":"timecapsule_test.gno","body":"package timecapsule\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/kit/store/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc resetState() {\n\tcapsules = store.Named(\"capsule\")\n}\n\nfunc TestLeaveAndReveal(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// v1 ids start at 1: the store never assigns 0, so the zero id stays\n\t// usable as \"absent\". v0 handed out 0 for the first capsule.\n\tid := Leave(cross(cur), \"hello, future\", 5)\n\tuassert.Equal(t, int64(1), id)\n\n\tif got := Render(\"\"); !strings.Contains(got, \"1 still sealed\") {\n\t\tt.Fatalf(\"expected capsule to still be sealed, got: %s\", got)\n\t}\n\tif got := Render(\"sealed\"); !strings.Contains(got, \"capsule/1\") {\n\t\tt.Fatalf(\"expected capsule 1 listed as sealed, got: %s\", got)\n\t}\n\n\ttesting.SkipHeights(5)\n\n\tif got := Render(\"\"); !strings.Contains(got, \"hello, future\") {\n\t\tt.Fatalf(\"expected capsule to be revealed, got: %s\", got)\n\t}\n\tif got := Render(\"capsule/1\"); !strings.Contains(got, \"hello, future\") {\n\t\tt.Fatalf(\"expected capsule detail to reveal message, got: %s\", got)\n\t}\n\n\t// Id 0 is never assigned, so the path is rejected rather than looked up.\n\tif got := Render(\"capsule/0\"); !strings.Contains(got, \"Invalid capsule id\") {\n\t\tt.Fatalf(\"expected capsule/0 to be rejected, got: %s\", got)\n\t}\n}\n\nfunc TestLeaveRejectsEmptyMessage(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsWithMessage(t, cur, \"message must not be empty\", func() {\n\t\tLeave(cross(cur), \"   \", 5)\n\t})\n}\n\nfunc TestLeaveRejectsBadDelay(cur realm, t *testing.T) {\n\tresetState()\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuassert.AbortsWithMessage(t, cur, \"delayBlocks out of range\", func() {\n\t\tLeave(cross(cur), \"hi\", 0)\n\t})\n}\n\n// Regression: an intermediate realm (not a direct EOA call) must never be\n// able to seal a capsule as if it were a user.\nfunc TestLeaveRejectsCodeRealm(cur realm, t *testing.T) {\n\tresetState()\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/some/attacker\"))\n\n\tuassert.AbortsWithMessage(t, cur, \"only direct user calls can leave a capsule\", func() {\n\t\tLeave(cross(cur), \"hi\", 5)\n\t})\n}\n\nfunc TestRenderNotFound(t *testing.T) {\n\tresetState()\n\tif got := Render(\"nope\"); !strings.Contains(got, \"not found\") {\n\t\tt.Fatalf(\"expected 404-ish message, got: %s\", got)\n\t}\n}\n"},{"name":"zz_zerowidth_test.gno","body":"package timecapsule\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\n// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth\n// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix\n// with real spaces. strings.TrimSpace keeps every one of them and the render\n// strips them all, so each must be refused.\nvar zwBlank = []string{\n\t\"\\u200b\\u200b\\u200b\", // ZWSP\n\t\"\\u200d\",             // ZWJ\n\t\"\\u200e\",             // LRM\n\t\"\\u202e\",             // RLO\n\t\"\\u2066\\u2069\",       // LRI PDI\n\t\"\\ufeff\",             // BOM\n\t\" \\u200b \\u200b \",    // mixed with real spaces\n}\n\n// zwOK must stay accepted: the stripper removes the marks and leaves text.\nvar zwOK = []string{\"a\", \"a\\u200bb\", \"  padded  \"}\n\nfunc TestZeroWidthMessageIsRefused(cur realm, t *testing.T) {\n\tresetState()\n\tdefer resetState()\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"alice\")))\n\tfor _, s := range zwBlank {\n\t\tif revive(func() { Leave(cross(cur), s, 5) }) == nil {\n\t\t\tt.Errorf(\"Leave accepted message %q, which the render strips to blank\", s)\n\t\t}\n\t}\n\tfor _, s := range zwOK {\n\t\tif r := revive(func() { Leave(cross(cur), s, 5) }); r != nil {\n\t\t\tt.Errorf(\"Leave refused message %q: %v\", s, r)\n\t\t}\n\t}\n\tif capsules.Len() != len(zwOK) {\n\t\tt.Errorf(\"%d capsule(s), want %d\", capsules.Len(), len(zwOK))\n\t}\n}\n"}]},"send":"","max_deposit":"6000000ugnot"}],"fee":{"gas_wanted":"48712000","gas_fee":"146136ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A1ue6PkRS8cAq+tZvrhMnIz38VybSzlBkRKywwTpHP+1"},"signature":"FF/ck//71ts930laDmOkw9yyzozrmmOIZi+v6LWl8/FHE2Hlp8dPZ3ISGx4EO94pnugDLYzGk+nk679usD4+ww=="}],"memo":""},"metadata":{"timestamp":"1791963536"}}],"auth":{"params":{"max_memo_bytes":"65536","tx_sig_limit":"7","tx_size_cost_per_byte":"10","sig_verify_cost_ed25519":"590","sig_verify_cost_secp256k1":"1000","gas_price_change_compressor":"10","target_gas_ratio":"70","initial_gasprice":{"gas":"1000","price":"1ugnot"},"unrestricted_addrs":null,"fee_collector":"g17xpfvakm2amg962yls6f84z3kell8c5lr9lr2e"}},"bank":{"params":{"restricted_denoms":[]}},"vm":{"params":{"sysnames_pkgpath":"gno.land/r/sys/names","syscla_pkgpath":"gno.land/r/sys/cla","chain_domain":"gno.land","default_deposit":"100000000ugnot","storage_price":"100ugnot","storage_fee_collector":"g1c9stkafpvcwez2efq3qtfuezw4zpaux3tvxggk","min_get_read_depth_100":"100","min_set_read_depth_100":"200","min_write_depth_100":"540","fixed_get_read_depth_100":"100","fixed_set_read_depth_100":"200","fixed_write_depth_100":"540","iter_next_cost_flat":"1000","preprocess_gas_per_byte":"1250","code_submission_policy":"permissionless","code_submitters":null,"pkg_approvers":null,"run_submitters":null,"inert_submission_charge":"","inert_charge_collector":"g1fgj3pu3rd7myc5hdk9q4wql8s96us5zqsyftw5"},"realm_params":null}}}}}